@newses/plugin-digest-summary 0.0.0-stage → 0.1.1

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,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # Newses digest summary plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
4
+
5
+ ## What is sent, and to whom
6
+
7
+ - Requests go to Anthropic (`api.anthropic.com`) with the server's API key, under the terms of that key's Anthropic account.
8
+ - What is sent, for each digest:
9
+ - the digest's language;
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.
12
+
13
+ That covers the up to 100 articles the digest lists and up to 2,000 more that it counts.
14
+
15
+ - Never sent: articles from feeds with a login, pages a user published from outside any feed, links, authors, and anything about the user.
16
+ - Only for users who turn the plugin on for themselves.
17
+
18
+ ## Install
19
+
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.
21
+
22
+ - **Docker:** add it to `PLUGINS` in `.env` and start with the plugins override ([Self-hosting](https://newses.app/guide/self-hosting#plugins)).
23
+ - **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)).
24
+
25
+ Then, in Settings > Plugins:
26
+
27
+ 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.
29
+
30
+ ## Settings
31
+
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 |
41
+
42
+ ## How it works
43
+
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 |
48
+
49
+ - **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.
51
+ - **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).
52
+ - **Declined requests:** when the model declines a request, the server's default fallback model answers instead (server-side fallback).
53
+
54
+ ## Costs
55
+
56
+ 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
+
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.
59
+ - **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
+ - **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.
62
+
63
+ To choose the effort, measure it on digests like yours, billed to your key:
64
+
65
+ ```sh
66
+ npm install && npm run build
67
+ ANTHROPIC_API_KEY=sk-ant-... node scripts/measure-effort.mjs [DIGEST.json ...] --efforts low,medium,high [--copies 100]
68
+ ```
69
+
70
+ - **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
+ - **Larger digests:** `--copies N` adds N copies of its articles as unlisted ones, to measure a digest read in parts.
72
+
73
+ ## Failures
74
+
75
+ A request that fails, is declined, or runs out of time leaves the digest without an overview, and never fails the digest. The server's log says why.
76
+
77
+ ## Development
78
+
79
+ Node 24 and npm: `npm install`, then `npm run check` (lint, typecheck, format check, tests) and `npm run build`.
80
+
81
+ - **Tests** run the hooks as the server does with `@newses/plugin-api/testing`, against a stand-in for the API that answers with responses shaped as the API's (`src/test/`).
82
+ - **Releases** are version tags (`v1.2.3`), published to npm with provenance by the Publish workflow. The plugin's `version` in `src/index.ts` and `package.json` must match.
83
+
84
+ ## Licence
85
+
86
+ AGPL-3.0-or-later, as Newses is.
@@ -0,0 +1,19 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ import type { InstanceSettings } from './settings.js';
3
+ /** The API's host, which an admin approves for the plugin. */
4
+ export declare const API_HOST = "api.anthropic.com";
5
+ /** Server-side fallback when the model declines, on direct requests only. */
6
+ export declare const FALLBACK_BETA = "server-side-fallback-2026-07-01";
7
+ /**
8
+ * A client sending requests through the hook's `fetch`, with the key from the settings. The host,
9
+ * key, and logging are set here, so nothing in the server's environment (`ANTHROPIC_*`) changes
10
+ * where requests go or what credentials they carry.
11
+ */
12
+ export declare function clientFor(settings: Pick<InstanceSettings, 'apiKey'>, fetch: typeof globalThis.fetch): Anthropic;
13
+ /** The text a response ends with: its text blocks after any switch to a fallback model. */
14
+ export declare function finalText(content: readonly {
15
+ type: string;
16
+ text?: string;
17
+ }[]): string;
18
+ /** An API failure as people read it, without anything from the request. */
19
+ export declare function failureText(error: unknown): string;
package/dist/claude.js ADDED
@@ -0,0 +1,49 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ /** The API's host, which an admin approves for the plugin. */
3
+ export const API_HOST = 'api.anthropic.com';
4
+ /** Server-side fallback when the model declines, on direct requests only. */
5
+ export const FALLBACK_BETA = 'server-side-fallback-2026-07-01';
6
+ /**
7
+ * A client sending requests through the hook's `fetch`, with the key from the settings. The host,
8
+ * key, and logging are set here, so nothing in the server's environment (`ANTHROPIC_*`) changes
9
+ * where requests go or what credentials they carry.
10
+ */
11
+ export function clientFor(settings, fetch) {
12
+ return new Anthropic({
13
+ apiKey: settings.apiKey,
14
+ authToken: null,
15
+ baseURL: `https://${API_HOST}`,
16
+ fetch,
17
+ maxRetries: 1,
18
+ timeout: 40_000,
19
+ logLevel: 'off',
20
+ });
21
+ }
22
+ /** The text a response ends with: its text blocks after any switch to a fallback model. */
23
+ export function finalText(content) {
24
+ const switched = content.findLastIndex((block) => block.type === 'fallback');
25
+ return content
26
+ .slice(switched + 1)
27
+ .map((block) => (block.type === 'text' ? (block.text ?? '') : ''))
28
+ .join('');
29
+ }
30
+ /** An API failure as people read it, without anything from the request. */
31
+ export function failureText(error) {
32
+ if (error instanceof Anthropic.AuthenticationError)
33
+ return 'The API key was refused (HTTP 401): check it in the server’s settings';
34
+ if (error instanceof Anthropic.PermissionDeniedError)
35
+ return 'The API key may not use this model (HTTP 403)';
36
+ if (error instanceof Anthropic.NotFoundError)
37
+ return 'The model was not found (HTTP 404)';
38
+ if (error instanceof Anthropic.RateLimitError)
39
+ return 'Rate limited by the API (HTTP 429)';
40
+ if (error instanceof Anthropic.APIConnectionTimeoutError)
41
+ return 'The API did not answer in time';
42
+ if (error instanceof Anthropic.APIConnectionError)
43
+ return error.cause instanceof Error
44
+ ? `The API could not be reached: ${error.cause.message}`
45
+ : 'The API could not be reached';
46
+ if (error instanceof Anthropic.APIError && error.status !== undefined)
47
+ return `The API answered HTTP ${String(error.status)}`;
48
+ return error instanceof Error ? error.message : String(error);
49
+ }
@@ -0,0 +1,80 @@
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';
4
+ import { type RequestTokens } from './prices.js';
5
+ import type { InstanceSettings, UserSettings } from './settings.js';
6
+ /** Input tokens one request reads at most; a larger digest is read in parts. */
7
+ export declare const PART_TOKENS = 50000;
8
+ /** Parts read at once, at most; a digest larger than this many parts has larger parts. */
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[];
12
+ /** What a digest's overview ended as, for the log. */
13
+ export type DigestOutcome = 'written'
14
+ /** Written from the parts that answered, saying how many did not. */
15
+ | 'partial' | 'refused' | 'invalid' | 'over budget' | 'failed' | 'timed out' | 'none';
16
+ /** Whether an entry may go to the API: never one of a feed with a login, or a published page. */
17
+ export declare const sendable: (entry: DigestEntry) => boolean;
18
+ /** The digest's entries the user's feed choice takes, of those that may be sent. */
19
+ 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[];
22
+ /** Tokens a text is about, rounded up: some 3 characters each. */
23
+ export declare const estimateTokens: (text: string) => number;
24
+ /**
25
+ * Feeds packed into parts of about `limit` tokens, each feed's articles together where they fit;
26
+ * a feed larger than a part is split across parts.
27
+ */
28
+ export declare function partsOf(feeds: readonly FeedArticles[], limit: number): FeedArticles[][];
29
+ /**
30
+ * 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.
32
+ */
33
+ export declare function planOf(input: DigestComposeInput, userSettings: UserSettings): {
34
+ entries: DigestEntry[];
35
+ feeds: FeedArticles[];
36
+ total: number;
37
+ parts: FeedArticles[][] | null;
38
+ planned: RequestTokens[];
39
+ } | null;
40
+ /**
41
+ * What the overview of a digest is expected to cost, making no request, as plain text: how it
42
+ * would be read, its tokens, and US dollars at list prices, or why it would add nothing.
43
+ */
44
+ export declare function estimate(options: {
45
+ settings: InstanceSettings;
46
+ userSettings: UserSettings;
47
+ input: DigestComposeInput;
48
+ storage: PluginStore;
49
+ userStorage: PluginStore | null;
50
+ now: () => Date;
51
+ }): Promise<string>;
52
+ /**
53
+ * 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.
56
+ */
57
+ export declare function compose(options: {
58
+ client: Anthropic;
59
+ settings: InstanceSettings;
60
+ userSettings: UserSettings;
61
+ input: DigestComposeInput;
62
+ storage: PluginStore;
63
+ userStorage: PluginStore | null;
64
+ logger: PluginLogger;
65
+ signal: AbortSignal;
66
+ /** When the overview must be written by, in ms since the epoch. */
67
+ deadline: number;
68
+ now: () => Date;
69
+ }): Promise<{
70
+ overview: string | null;
71
+ outcome: DigestOutcome;
72
+ }>;
73
+ /** What an overview written from only some parts says of the rest. */
74
+ export declare function missingNote(counts: {
75
+ read: number;
76
+ given: number;
77
+ parts: number;
78
+ timedOut: number;
79
+ failed: number;
80
+ }): string;
package/dist/digest.js ADDED
@@ -0,0 +1,263 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ 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';
5
+ 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. */
10
+ export const MAX_PARTS = 6;
11
+ /** Of the time left, the share the parts may take, leaving the rest to the merge. */
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;
17
+ /** 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
+ cacheWrite: 0,
24
+ cacheRead: 0,
25
+ output: OUTPUT_ESTIMATE,
26
+ });
27
+ if (!partTokens)
28
+ return [request(whole)];
29
+ return [
30
+ ...partTokens.map((tokens) => request(estimateTokens(PART_SYSTEM) + tokens)),
31
+ request(estimateTokens(MERGE_SYSTEM) + THEMES_ESTIMATE * partTokens.length),
32
+ ];
33
+ }
34
+ /** Whether an entry may go to the API: never one of a feed with a login, or a published page. */
35
+ export const sendable = (entry) => entry.feed !== null && !entry.feed.withLogin;
36
+ /** The digest's entries the user's feed choice takes, of those that may be sent. */
37
+ export function chosen(entries, settings) {
38
+ const picked = new Set(settings.feeds);
39
+ return entries.filter((entry) => {
40
+ if (!sendable(entry))
41
+ return false;
42
+ const id = entry.feed?.id ?? 0;
43
+ if (settings.feedChoice === 'only')
44
+ return picked.has(id);
45
+ if (settings.feedChoice === 'except')
46
+ return !picked.has(id);
47
+ return true;
48
+ });
49
+ }
50
+ /** Entries grouped by feed, feeds in the order their newest entry comes. */
51
+ export function byFeed(entries) {
52
+ const feeds = new Map();
53
+ for (const entry of entries) {
54
+ if (!entry.feed)
55
+ continue;
56
+ let feed = feeds.get(entry.feed.id);
57
+ if (!feed) {
58
+ feed = { feed: entry.feed.title, articles: [] };
59
+ feeds.set(entry.feed.id, feed);
60
+ }
61
+ feed.articles.push({ title: entry.title, excerpt: entry.excerpt });
62
+ }
63
+ return [...feeds.values()];
64
+ }
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>`);
68
+ /**
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.
71
+ */
72
+ export function partsOf(feeds, limit) {
73
+ const parts = [];
74
+ let part = [];
75
+ let size = 0;
76
+ const close = () => {
77
+ if (part.length > 0)
78
+ parts.push(part);
79
+ part = [];
80
+ size = 0;
81
+ };
82
+ 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();
86
+ let piece = { feed: feed.feed, articles: [] };
87
+ for (const article of feed.articles) {
88
+ const cost = articleTokens(article);
89
+ if (size > 0 && size + cost > limit) {
90
+ if (piece.articles.length > 0)
91
+ part.push(piece);
92
+ close();
93
+ piece = { feed: feed.feed, articles: [] };
94
+ }
95
+ piece.articles.push(article);
96
+ size += cost;
97
+ }
98
+ if (piece.articles.length > 0)
99
+ part.push(piece);
100
+ }
101
+ close();
102
+ return parts;
103
+ }
104
+ /**
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.
107
+ */
108
+ export function planOf(input, userSettings) {
109
+ const entries = chosen([...input.entries, ...input.unlisted], userSettings);
110
+ if (entries.length === 0)
111
+ return null;
112
+ const feeds = byFeed(entries);
113
+ const total = entries.length + Math.max(0, input.more - input.unlisted.length);
114
+ 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 };
120
+ }
121
+ /**
122
+ * 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.
124
+ */
125
+ export async function estimate(options) {
126
+ const { settings } = options;
127
+ const plan = planOf(options.input, options.userSettings);
128
+ if (!plan)
129
+ return "None of the test digest's articles are from feeds it reads, so it would add nothing.";
130
+ const tokens = tokensIn(plan.planned);
131
+ const left = await remaining({ instance: settings.monthlyTokens, user: settings.userMonthlyTokens }, { instance: options.storage, user: options.userStorage }, options.now());
132
+ const formatted = (n) => new Intl.NumberFormat('en').format(n);
133
+ const count = plan.entries.length;
134
+ const articles = `${formatted(count)} ${count === 1 ? 'article' : 'articles'}`;
135
+ const requests = `${String(plan.planned.length)} ${plan.planned.length === 1 ? 'request' : 'requests'}`;
136
+ if (left < tokens)
137
+ 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.`;
139
+ }
140
+ /**
141
+ * 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.
144
+ */
145
+ export async function compose(options) {
146
+ const { client, settings, input, storage, userStorage, logger, signal } = options;
147
+ const plan = planOf(input, options.userSettings);
148
+ if (!plan)
149
+ return { overview: null, outcome: 'none' };
150
+ const { entries, feeds, total, parts, planned } = plan;
151
+ const budgets = { instance: settings.monthlyTokens, user: settings.userMonthlyTokens };
152
+ if ((await remaining(budgets, { instance: storage, user: userStorage }, options.now())) <
153
+ tokensIn(planned))
154
+ return { overview: null, outcome: 'over budget' };
155
+ // Counts are read and written back, so parts answering together count one after another.
156
+ let counting = Promise.resolve();
157
+ const counted = (tokens) => {
158
+ counting = counting.then(async () => {
159
+ await count(storage, tokens, options.now());
160
+ if (userStorage)
161
+ await count(userStorage, tokens, options.now());
162
+ });
163
+ return counting;
164
+ };
165
+ const ask = async (system, prompt, format, by) => {
166
+ let response;
167
+ // Whole milliseconds: AbortSignal.timeout refuses fractions.
168
+ const left = Math.max(1, Math.floor(by - Date.now()));
169
+ 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' };
193
+ }
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) };
200
+ };
201
+ const language = input.language;
202
+ const frequency = input.frequency;
203
+ if (!parts) {
204
+ const asked = await ask(OVERVIEW_SYSTEM, overviewPrompt({ language, frequency, total, feeds }), OVERVIEW_FORMAT, options.deadline);
205
+ 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' };
209
+ }
210
+ 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);
213
+ if (!asked.ok)
214
+ return asked.outcome;
215
+ return readPart(asked.text) ?? 'invalid';
216
+ }));
217
+ // 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({
222
+ language,
223
+ frequency,
224
+ given: entries.length,
225
+ read: read.length < parts.length ? articleCount(read.flat()) : entries.length,
226
+ total,
227
+ parts: found.filter((part) => typeof part !== 'string'),
228
+ }), OVERVIEW_FORMAT, options.deadline);
229
+ if (!asked.ok)
230
+ return { overview: null, outcome: asked.outcome };
231
+ const overview = readOverview(asked.text);
232
+ if (!overview)
233
+ return { overview: null, outcome: 'invalid' };
234
+ if (read.length === parts.length)
235
+ return { overview, outcome: 'written' };
236
+ const missed = found.filter((part) => typeof part === 'string');
237
+ const note = missingNote({
238
+ read: articleCount(read.flat()),
239
+ given: entries.length,
240
+ parts: parts.length,
241
+ timedOut: missed.filter((outcome) => outcome === 'timed out').length,
242
+ failed: missed.filter((outcome) => outcome !== 'timed out').length,
243
+ });
244
+ return { overview: withNote(overview, note), outcome: 'partial' };
245
+ }
246
+ /** What an overview written from only some parts says of the rest. */
247
+ export function missingNote(counts) {
248
+ const n = (count) => new Intl.NumberFormat('en').format(count);
249
+ const { timedOut, failed } = counts;
250
+ const why = [
251
+ timedOut > 0 && `${n(timedOut)} ran out of time`,
252
+ failed > 0 && `${n(failed)} failed`,
253
+ ].filter(Boolean);
254
+ return `This overview covers ${n(counts.read)} of ${n(counts.given)} articles: of the ${n(counts.parts)} parts they were read in, ${why.join(' and ')}.`;
255
+ }
256
+ /** The overview with a last paragraph, within the digest's limit. */
257
+ const withNote = (overview, note) => `${overview.slice(0, DIGEST_LIMITS.overview - note.length - 2).trimEnd()}\n\n${note}`;
258
+ /** Articles in the feeds. */
259
+ const articleCount = (feeds) => feeds.reduce((sum, feed) => sum + feed.articles.length, 0);
260
+ /** Tokens the articles take in a request, about. */
261
+ const articlesTokens = (feeds) => feeds.reduce((sum, feed) => sum +
262
+ estimateTokens(`<feed><name>${feed.feed}</name></feed>`) +
263
+ feed.articles.reduce((n, article) => n + articleTokens(article), 0), 0);
@@ -0,0 +1,28 @@
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.
5
+ */
6
+ declare const _default: import("@newses/plugin-api").PluginDefinition<import("zod").ZodObject<{
7
+ apiKey: import("zod").ZodString;
8
+ model: import("zod").ZodDefault<import("zod").ZodEnum<{
9
+ "claude-opus-5-5": "claude-opus-5-5";
10
+ "claude-sonnet-5-5": "claude-sonnet-5-5";
11
+ "claude-haiku-5-5": "claude-haiku-5-5";
12
+ }>>;
13
+ effort: import("zod").ZodDefault<import("zod").ZodEnum<{
14
+ low: "low";
15
+ medium: "medium";
16
+ high: "high";
17
+ }>>;
18
+ monthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
19
+ userMonthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
20
+ }, import("zod/v4/core").$strip>, import("zod").ZodObject<{
21
+ feedChoice: import("zod").ZodDefault<import("zod").ZodEnum<{
22
+ all: "all";
23
+ only: "only";
24
+ except: "except";
25
+ }>>;
26
+ feeds: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodInt>>;
27
+ }, import("zod/v4/core").$strip>>;
28
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,110 @@
1
+ import { definePlugin, DIGEST_LIMITS } from '@newses/plugin-api';
2
+ import { API_HOST, clientFor, failureText } from './claude.js';
3
+ import { compose, estimate } from './digest.js';
4
+ import { instanceSettings, userSettings } from './settings.js';
5
+ import { usedThisMonth } from './usage.js';
6
+ /** Of the digest's time, what is left unused, for counting what came back. */
7
+ const MARGIN_MS = 3_000;
8
+ const formatted = (tokens) => new Intl.NumberFormat('en').format(tokens);
9
+ /**
10
+ * Opens each user's email digest with an overview of what their unread articles are about,
11
+ * written by Claude through the Anthropic API from the titles and excerpts of every unread
12
+ * article the digest counts, of the feeds the user chooses.
13
+ */
14
+ export default definePlugin({
15
+ id: 'digest-summary',
16
+ // Keep in step with package.json; a test checks they match.
17
+ version: '0.1.1',
18
+ apiVersion: '^0.1.1',
19
+ scopes: ['user'],
20
+ hosts: [API_HOST],
21
+ settings: { instance: instanceSettings, user: userSettings },
22
+ messages: {
23
+ en: {
24
+ name: 'Digest summary',
25
+ description: 'Opens your email digest with an overview of what your unread articles are about: their common themes, then other notable stories, written by Claude. The title, feed name, and first lines of the unread articles of the feeds you choose go to Anthropic (api.anthropic.com) with the server’s API key, under Anthropic’s commercial terms. Articles from feeds with a login, and pages you published, are never sent.',
26
+ 'settings.apiKey': 'Anthropic API key',
27
+ 'settings.apiKey.hint': 'From the Claude Console (platform.claude.com), under API keys. Every request is billed to it. Stored as a secret.',
28
+ 'settings.model': 'Model',
29
+ 'settings.model.hint': 'Opus writes best, Haiku costs least.',
30
+ 'settings.model.option.claude-opus-5-5': 'Claude Opus 5.5',
31
+ 'settings.model.option.claude-sonnet-5-5': 'Claude Sonnet 5.5',
32
+ 'settings.model.option.claude-haiku-5-5': 'Claude Haiku 5.5',
33
+ 'settings.effort': 'Effort',
34
+ 'settings.effort.hint': 'How much the model thinks before it writes; more costs more tokens and takes longer, and a digest waits at most a minute.',
35
+ 'settings.effort.option.low': 'Low',
36
+ 'settings.effort.option.medium': 'Medium',
37
+ 'settings.effort.option.high': 'High',
38
+ 'settings.monthlyTokens': 'Tokens a month, for the server',
39
+ 'settings.monthlyTokens.hint': 'Once used, no more overviews are written until the month ends (UTC). Send test shows how many are used.',
40
+ 'settings.userMonthlyTokens': 'Tokens a month, for each user',
41
+ 'settings.userMonthlyTokens.hint': 'A digest of 1,000 unread articles reads about 100,000 tokens.',
42
+ 'settings.feedChoice': 'Feeds to read',
43
+ 'settings.feedChoice.option.all': 'All my feeds',
44
+ 'settings.feedChoice.option.only': 'Only the feeds below',
45
+ 'settings.feedChoice.option.except': 'All but the feeds below',
46
+ 'settings.feeds': 'Feeds',
47
+ 'settings.feeds.hint': 'Used when only some feeds are read, or all but some.',
48
+ 'action.estimate': 'Estimate cost',
49
+ 'action.estimate.hint': 'What the overview of a test digest of your unread articles from the last day would cost now, without sending it.',
50
+ },
51
+ },
52
+ hooks: {
53
+ 'digest.compose': {
54
+ async run(input, context) {
55
+ const started = Date.now();
56
+ const { overview, outcome } = await compose({
57
+ client: clientFor(context.settings, context.fetch),
58
+ settings: context.settings,
59
+ userSettings: context.userSettings ?? userSettings.parse({}),
60
+ input,
61
+ storage: context.storage,
62
+ userStorage: context.userStorage,
63
+ logger: context.logger,
64
+ signal: context.signal,
65
+ deadline: started + DIGEST_LIMITS.timeoutSeconds * 1000 - MARGIN_MS,
66
+ now: () => new Date(),
67
+ });
68
+ context.logger.info('digest composed', { outcome });
69
+ return { overview };
70
+ },
71
+ },
72
+ test: {
73
+ async run(context) {
74
+ const client = clientFor(context.settings, context.fetch);
75
+ try {
76
+ await client.models.retrieve(context.settings.model, null, { signal: context.signal });
77
+ }
78
+ catch (error) {
79
+ return { ok: false, message: failureText(error) };
80
+ }
81
+ const now = new Date();
82
+ const server = await usedThisMonth(context.storage, now);
83
+ const mine = context.userStorage ? await usedThisMonth(context.userStorage, now) : 0;
84
+ return {
85
+ ok: true,
86
+ message: `The API key works with ${context.settings.model}. Tokens this month: yours ${formatted(mine)} of ${formatted(context.settings.userMonthlyTokens)}, the server's ${formatted(server)} of ${formatted(context.settings.monthlyTokens)}.`,
87
+ };
88
+ },
89
+ },
90
+ },
91
+ actions: {
92
+ // What digest.compose would cost for a test digest now, making no request.
93
+ estimate: {
94
+ digest: true,
95
+ run: async (context, digest) => ({
96
+ ok: true,
97
+ message: digest
98
+ ? await estimate({
99
+ settings: context.settings,
100
+ userSettings: context.userSettings ?? userSettings.parse({}),
101
+ input: digest,
102
+ storage: context.storage,
103
+ userStorage: context.userStorage,
104
+ now: () => new Date(),
105
+ })
106
+ : 'No test digest to estimate.',
107
+ }),
108
+ },
109
+ },
110
+ });
@@ -0,0 +1,14 @@
1
+ import type { InstanceSettings } from './settings.js';
2
+ /** One request's tokens, by how they are billed; estimated before a digest. */
3
+ export interface RequestTokens {
4
+ input: number;
5
+ cacheWrite: number;
6
+ cacheRead: number;
7
+ output: number;
8
+ }
9
+ /** What requests cost with a model, in US dollars. */
10
+ export declare function costOf(model: InstanceSettings['model'], requests: readonly RequestTokens[]): number;
11
+ /** Every token of some requests. */
12
+ export declare const tokensIn: (requests: readonly RequestTokens[]) => number;
13
+ /** US dollars for a message: `about $0.95`, or `less than $0.01`. */
14
+ export declare const dollars: (amount: number) => string;