@newses/plugin-digest-summary 0.1.0 → 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/dist/index.js CHANGED
@@ -14,7 +14,7 @@ const formatted = (tokens) => new Intl.NumberFormat('en').format(tokens);
14
14
  export default definePlugin({
15
15
  id: 'digest-summary',
16
16
  // Keep in step with package.json; a test checks they match.
17
- version: '0.1.0',
17
+ version: '0.1.1',
18
18
  apiVersion: '^0.1.1',
19
19
  scopes: ['user'],
20
20
  hosts: [API_HOST],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@newses/plugin-digest-summary",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "A Newses plugin that opens your email digest with an overview of the common themes of your unread articles, written by Claude",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "repository": {
@@ -1,50 +0,0 @@
1
- import type Anthropic from '@anthropic-ai/sdk';
2
- import type { EventEntry, EventEntryWithText, PluginLogger, PluginStore } from '@newses/plugin-api';
3
- import type { InstanceSettings } from './settings.js';
4
- /** How long a summary is kept: past the oldest article a weekly digest lists. */
5
- export declare const SUMMARY_TTL_SECONDS: number;
6
- /** Output tokens a summary is counted at when its batch is sent, thinking included. */
7
- export declare const SUMMARY_OUTPUT_ESTIMATE = 600;
8
- /**
9
- * Whether an entry may be sent to Anthropic: never from a feed with a login, whose articles are
10
- * the user's own, and never a page published from outside any feed.
11
- */
12
- export declare const sendable: (entry: EventEntry) => boolean;
13
- /** What is kept for an entry's hash in a language: a summary, null for none, pending, or nothing. */
14
- export declare function storedSummary(store: PluginStore, language: string, hash: string): Promise<{
15
- summary: string | null;
16
- } | 'pending' | undefined>;
17
- /** Keeps a summary, or that an entry has none. */
18
- export declare function keepSummary(store: PluginStore, language: string, hash: string, summary: string | null): Promise<void>;
19
- /** The tokens a summary request is counted at before it runs: about 3 characters a token. */
20
- export declare const estimateTokens: (prompt: string) => number;
21
- /**
22
- * Sends the entries not yet summarised in `language` as one Message Batch, as many as `allowance`
23
- * tokens cover, and counts their estimate. Returns how many were sent and the tokens counted.
24
- */
25
- export declare function submitBatch(options: {
26
- client: Anthropic;
27
- settings: InstanceSettings;
28
- store: PluginStore;
29
- entries: readonly EventEntryWithText[];
30
- language: string;
31
- allowance: number;
32
- signal: AbortSignal;
33
- }): Promise<{
34
- sent: number;
35
- tokens: number;
36
- }>;
37
- /**
38
- * Keeps the summaries of batches that have ended, until `deadline` (ms since the epoch): a
39
- * refused or unreadable answer as none, an errored or expired item as nothing, to be summarised
40
- * in a digest instead. Corrects the instance's count from the batch's estimate to what it used.
41
- * Returns how many batches it finished.
42
- */
43
- export declare function collectBatches(options: {
44
- client: Anthropic;
45
- store: PluginStore;
46
- logger: PluginLogger;
47
- deadline: number;
48
- signal: AbortSignal;
49
- now: () => Date;
50
- }): Promise<number>;
package/dist/summaries.js DELETED
@@ -1,147 +0,0 @@
1
- import { NotFoundError } from '@anthropic-ai/sdk';
2
- import { finalText } from './claude.js';
3
- import { readSummary, SUMMARY_FORMAT, SUMMARY_SYSTEM, summaryPrompt } from './prompts.js';
4
- import { count, tokensOf } from './usage.js';
5
- /*
6
- * Entries are shared: the same article reaches every user subscribed to its feed with the same
7
- * content hash. So each is summarised once per hash and language, kept in the instance's storage:
8
- *
9
- * summary:<language>:<hash> { summary: string | null } when done (null: refused, or no answer
10
- * worth keeping), or { batch: id } while a batch has it
11
- * batch:<id> the batch's hashes in request order, its language, and the tokens
12
- * counted for it when it was sent
13
- */
14
- /** How long a summary is kept: past the oldest article a weekly digest lists. */
15
- export const SUMMARY_TTL_SECONDS = 30 * 24 * 60 * 60;
16
- /** How long an entry waits for its batch, which ends within 24 hours. */
17
- const PENDING_TTL_SECONDS = 2 * 24 * 60 * 60;
18
- /** Output tokens a summary is counted at when its batch is sent, thinking included. */
19
- export const SUMMARY_OUTPUT_ESTIMATE = 600;
20
- /** A summary's `max_tokens`, thinking included. */
21
- const SUMMARY_MAX_TOKENS = 2000;
22
- const summaryKey = (language, hash) => `summary:${language}:${hash}`;
23
- const batchKey = (id) => `batch:${id}`;
24
- /**
25
- * Whether an entry may be sent to Anthropic: never from a feed with a login, whose articles are
26
- * the user's own, and never a page published from outside any feed.
27
- */
28
- export const sendable = (entry) => entry.feed !== null && !entry.feed.withLogin;
29
- /** What is kept for an entry's hash in a language: a summary, null for none, pending, or nothing. */
30
- export async function storedSummary(store, language, hash) {
31
- const value = (await store.get(summaryKey(language, hash)));
32
- if (!value)
33
- return undefined;
34
- return 'batch' in value ? 'pending' : { summary: value.summary };
35
- }
36
- /** Keeps a summary, or that an entry has none. */
37
- export async function keepSummary(store, language, hash, summary) {
38
- await store.set(summaryKey(language, hash), { summary }, {
39
- ttlSeconds: SUMMARY_TTL_SECONDS,
40
- });
41
- }
42
- /** The tokens a summary request is counted at before it runs: about 3 characters a token. */
43
- export const estimateTokens = (prompt) => Math.ceil((SUMMARY_SYSTEM.length + prompt.length) / 3) + SUMMARY_OUTPUT_ESTIMATE;
44
- /** A summary request, as a batch item. */
45
- function summaryParams(settings, prompt) {
46
- return {
47
- model: settings.model,
48
- max_tokens: SUMMARY_MAX_TOKENS,
49
- output_config: { effort: settings.effort, format: SUMMARY_FORMAT },
50
- // Unchanging and first, so the prompt cache can serve it.
51
- system: [{ type: 'text', text: SUMMARY_SYSTEM, cache_control: { type: 'ephemeral' } }],
52
- messages: [{ role: 'user', content: prompt }],
53
- };
54
- }
55
- /**
56
- * Sends the entries not yet summarised in `language` as one Message Batch, as many as `allowance`
57
- * tokens cover, and counts their estimate. Returns how many were sent and the tokens counted.
58
- */
59
- export async function submitBatch(options) {
60
- const { client, settings, store, language, signal } = options;
61
- const unique = new Map();
62
- for (const entry of options.entries)
63
- if (sendable(entry) && !unique.has(entry.contentHash))
64
- unique.set(entry.contentHash, entry);
65
- const kept = await Promise.all([...unique.keys()].map((hash) => storedSummary(store, language, hash)));
66
- const wanted = [...unique.values()].filter((_, index) => kept[index] === undefined);
67
- const items = [];
68
- let tokens = 0;
69
- for (const entry of wanted) {
70
- const prompt = summaryPrompt({ title: entry.title, feed: entry.feed?.title ?? '', text: entry.text }, language);
71
- const estimate = estimateTokens(prompt);
72
- if (tokens + estimate > options.allowance)
73
- break;
74
- tokens += estimate;
75
- items.push({ hash: entry.contentHash, prompt });
76
- }
77
- if (items.length === 0)
78
- return { sent: 0, tokens: 0 };
79
- const batch = await client.messages.batches.create({
80
- requests: items.map((item, index) => ({
81
- custom_id: `s${String(index)}`,
82
- params: summaryParams(settings, item.prompt),
83
- })),
84
- }, { signal });
85
- const record = {
86
- language,
87
- hashes: items.map((item) => item.hash),
88
- estimate: tokens,
89
- };
90
- await store.set(batchKey(batch.id), record, { ttlSeconds: 30 * 24 * 60 * 60 });
91
- await Promise.all(items.map((item) => store.set(summaryKey(language, item.hash), { batch: batch.id }, {
92
- ttlSeconds: PENDING_TTL_SECONDS,
93
- })));
94
- return { sent: items.length, tokens };
95
- }
96
- /**
97
- * Keeps the summaries of batches that have ended, until `deadline` (ms since the epoch): a
98
- * refused or unreadable answer as none, an errored or expired item as nothing, to be summarised
99
- * in a digest instead. Corrects the instance's count from the batch's estimate to what it used.
100
- * Returns how many batches it finished.
101
- */
102
- export async function collectBatches(options) {
103
- const { client, store, logger, signal } = options;
104
- let finished = 0;
105
- for (const { key, value } of await store.list('batch:', { limit: 20 })) {
106
- if (Date.now() >= options.deadline)
107
- break;
108
- const id = key.slice('batch:'.length);
109
- const record = value;
110
- try {
111
- const batch = await client.messages.batches.retrieve(id, null, { signal });
112
- if (batch.processing_status !== 'ended')
113
- continue;
114
- let used = 0;
115
- const seen = new Set();
116
- for await (const item of await client.messages.batches.results(id, undefined, { signal })) {
117
- const hash = record.hashes[Number(item.custom_id.slice(1))];
118
- if (hash === undefined)
119
- continue;
120
- seen.add(hash);
121
- if (item.result.type !== 'succeeded') {
122
- await store.delete(summaryKey(record.language, hash));
123
- continue;
124
- }
125
- const message = item.result.message;
126
- used += tokensOf(message.usage);
127
- const summary = message.stop_reason === 'end_turn' ? readSummary(finalText(message.content)) : null;
128
- await keepSummary(store, record.language, hash, summary);
129
- }
130
- for (const hash of record.hashes)
131
- if (!seen.has(hash))
132
- await store.delete(summaryKey(record.language, hash));
133
- await count(store, used - record.estimate, options.now());
134
- await store.delete(key);
135
- finished += 1;
136
- }
137
- catch (error) {
138
- if (error instanceof NotFoundError) {
139
- await store.delete(key);
140
- continue;
141
- }
142
- logger.warn('could not collect a summary batch', { batch: id, error: String(error) });
143
- break;
144
- }
145
- }
146
- return finished;
147
- }