@molecule/api-ai-summarization-llm 1.0.2 → 1.1.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
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-08-04T01:47:38.403Z
6
+ Generated: 2026-09-25T13:12:59.988Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-ai-summarization-llm
@@ -40,6 +40,33 @@ const { summary, usage } = await requireProvider().summarize({
40
40
  })
41
41
  ```
42
42
 
43
+ ```typescript
44
+ // A one-sentence TL;DR with a HARD word cap, cached across builds — e.g. a
45
+ // build step that summarizes each long section of each page.
46
+ import { provider as anthropic } from '@molecule/api-ai-anthropic'
47
+ import { setProvider as setAI } from '@molecule/api-ai'
48
+ import { setProvider as setSummarizer } from '@molecule/api-ai-summarization'
49
+ import {
50
+ countWords,
51
+ createFileSummaryCache,
52
+ provider as summarization,
53
+ summarizeCached,
54
+ } from '@molecule/api-ai-summarization-llm'
55
+
56
+ setAI(anthropic)
57
+ setSummarizer(summarization)
58
+
59
+ const cache = createFileSummaryCache('.cache/summaries.json')
60
+ const rows: Record<string, string> = {}
61
+ for (const section of sections) {
62
+ if (countWords(section.prose) < 80) continue // too short to be worth a summary
63
+ const r = await summarizeCached({ text: section.prose, format: 'tldr', maxWords: 25 }, { cache })
64
+ rows[r.key] = r.summary // one complete sentence, ≤ 25 words
65
+ }
66
+ cache.save()
67
+ // publish `rows` (e.g. write it next to the page as summaries.json)
68
+ ```
69
+
43
70
  ## Type
44
71
 
45
72
  `provider`
@@ -52,6 +79,136 @@ npm install @molecule/api-ai-summarization-llm @molecule/api-ai @molecule/api-ai
52
79
 
53
80
  ## API
54
81
 
82
+ ### Interfaces
83
+
84
+ #### `CachedSummary`
85
+
86
+ One cached summary.
87
+
88
+ ```typescript
89
+ interface CachedSummary {
90
+ summary: string
91
+ withinCap?: boolean
92
+ }
93
+ ```
94
+
95
+ #### `SummaryCache`
96
+
97
+ The cache: a key → summary map persisted to a JSON file.
98
+
99
+ ```typescript
100
+ interface SummaryCache {
101
+ /** The file the cache reads and writes. */
102
+ readonly file: string
103
+ get(key: string): CachedSummary | undefined
104
+ set(key: string, value: CachedSummary): void
105
+ /** Every entry, e.g. to publish them as a static file. */
106
+ entries(): Record<string, CachedSummary>
107
+ /** Writes the file (creating its directory). */
108
+ save(): void
109
+ }
110
+ ```
111
+
112
+ ### Functions
113
+
114
+ #### `cleanSummary(raw)`
115
+
116
+ Strips what models wrap a summary in: reasoning blocks, a "TL;DR:" or
117
+ "Summary:" label, surrounding quotes or bold, and line breaks.
118
+
119
+ ```typescript
120
+ function cleanSummary(raw: string): string
121
+ ```
122
+
123
+ - `raw` — The model's answer.
124
+
125
+ **Returns:** The bare summary text.
126
+
127
+ #### `countWords(s)`
128
+
129
+ Words in a string, the way a reader counts them.
130
+
131
+ ```typescript
132
+ function countWords(s: string): number
133
+ ```
134
+
135
+ - `s` — Any text.
136
+
137
+ **Returns:** The number of whitespace-separated words.
138
+
139
+ #### `createFileSummaryCache(file)`
140
+
141
+ Opens (or starts) a summary cache stored at `file`.
142
+
143
+ ```typescript
144
+ function createFileSummaryCache(file: string): SummaryCache
145
+ ```
146
+
147
+ - `file` — Path of the JSON file, e.g. `.cache/summaries.json`.
148
+
149
+ **Returns:** The cache.
150
+
151
+ #### `firstSentences(s, n)`
152
+
153
+ The first `n` complete sentences of a text. A trailing fragment with no
154
+ terminal punctuation is dropped, never kept or given a full stop.
155
+
156
+ ```typescript
157
+ function firstSentences(s: string, n: number): string
158
+ ```
159
+
160
+ - `s` — Cleaned summary text.
161
+ - `n` — How many sentences to keep.
162
+
163
+ **Returns:** Those sentences, or `''` when the text holds no complete sentence.
164
+
165
+ #### `meetsCap(s, maxWords)`
166
+
167
+ Whether a summary meets the caps and reads as finished: at most `maxWords`
168
+ words, terminal punctuation, and a last word that is not a function word.
169
+
170
+ ```typescript
171
+ function meetsCap(s: string, maxWords?: number): boolean
172
+ ```
173
+
174
+ - `s` — Candidate summary.
175
+ - `maxWords` — The hard word cap, if any.
176
+
177
+ **Returns:** `true` when the summary can be published as is.
178
+
179
+ #### `summarizeCached(input, options)`
180
+
181
+ Summarize through the cache: a hit returns without a model call; a miss
182
+ summarizes and stores the result. A summary that did not meet its caps
183
+ (`withinCap: false`) is returned but not stored, so the next run tries again.
184
+
185
+ ```typescript
186
+ function summarizeCached(
187
+ input: SummarizeInput,
188
+ options: { cache: SummaryCache; summarizer?: AISummarizationProvider },
189
+ ): Promise<SummarizeResult & { cached: boolean; key: string }>
190
+ ```
191
+
192
+ - `input` — The summarize request.
193
+ - `options` — The cache, and optionally a provider (defaults to the bonded one).
194
+ - `options.cache` — The cache to read and fill.
195
+ - `options.summarizer` — A provider to use instead of the bonded one.
196
+
197
+ **Returns:** The result, with `cached: true` on a hit and `key` for publishing.
198
+
199
+ #### `summaryKey(input)`
200
+
201
+ The cache key for a request: a SHA-256 of the text (whitespace-normalized)
202
+ and every option that changes the answer.
203
+
204
+ ```typescript
205
+ function summaryKey(input: SummarizeInput): string
206
+ ```
207
+
208
+ - `input` — The summarize request.
209
+
210
+ **Returns:** A 64-char hex key.
211
+
55
212
  ### Constants
56
213
 
57
214
  #### `provider`
@@ -100,6 +257,32 @@ Peer dependencies:
100
257
  - `@molecule/api-ai-summarization`
101
258
  - `@molecule/api-i18n`
102
259
 
260
+ **A hard cap is enforced here, in code — do not rebuild it.** With `maxWords`
261
+ (and/or `sentences`, which defaults to 1 for `format: 'tldr'`) the provider
262
+ cleans the answer (drops "TL;DR:" labels, quotes, `<think>` blocks), keeps
263
+ whole sentences only, checks the cap and that the last word is not a
264
+ function word ("the", "and", "of"…), and asks the model again when it runs
265
+ long (`attempts`, default 3). It never slices a sentence and adds a full
266
+ stop. If every attempt runs long it returns the shortest complete sentence
267
+ with `withinCap: false`; `summarizeCached` does not store those, so the next
268
+ run retries. It throws only when the model returns no usable text at all, or
269
+ the AI provider fails — so "unavailable" is for a missing key or an
270
+ unreachable provider, never for a long answer.
271
+
272
+ Model quirks it already handles: it sends no `temperature` (several current
273
+ models reject it), and it asks for a large output budget, because a model
274
+ that reasons before answering can spend a small `maxTokens` entirely on
275
+ hidden reasoning and stream no text.
276
+
277
+ `summarizeCached` keys by a SHA-256 of the whitespace-normalized text plus
278
+ every option, so an unchanged text is never re-summarized; `summaryKey(input)`
279
+ gives the same key without calling the model. The cache is a plain JSON file
280
+ (`{ version: 1, entries: { key: { summary } } }`); call `save()` once at the
281
+ end. Server-only (Node `fs`/`crypto`): run it in a build script or a server
282
+ route, never in client code — at build time, bond the `ai` provider inside
283
+ the script that summarizes, since a bundler's separate passes do not share
284
+ bonds set up elsewhere.
285
+
103
286
  Composes the swappable `ai` bond: an `ai` provider MUST be bonded first
104
287
  (`bond('ai', <provider>)`) or `summarize()` throws (a missing AI provider
105
288
  throws at `summarize()` time, not at import). Pass `provider` on the input to
@@ -0,0 +1,59 @@
1
+ /**
2
+ * A summary cache kept in one JSON file, keyed by a hash of the text and the
3
+ * caps — so an unchanged text is never summarized twice, across builds.
4
+ *
5
+ * Works with any bonded `ai-summarization` provider.
6
+ *
7
+ * @module
8
+ */
9
+ import type { AISummarizationProvider, SummarizeInput, SummarizeResult } from '@molecule/api-ai-summarization';
10
+ /** One cached summary. */
11
+ export interface CachedSummary {
12
+ summary: string;
13
+ withinCap?: boolean;
14
+ }
15
+ /** The cache: a key → summary map persisted to a JSON file. */
16
+ export interface SummaryCache {
17
+ /** The file the cache reads and writes. */
18
+ readonly file: string;
19
+ get(key: string): CachedSummary | undefined;
20
+ set(key: string, value: CachedSummary): void;
21
+ /** Every entry, e.g. to publish them as a static file. */
22
+ entries(): Record<string, CachedSummary>;
23
+ /** Writes the file (creating its directory). */
24
+ save(): void;
25
+ }
26
+ /**
27
+ * The cache key for a request: a SHA-256 of the text (whitespace-normalized)
28
+ * and every option that changes the answer.
29
+ *
30
+ * @param input - The summarize request.
31
+ * @returns A 64-char hex key.
32
+ */
33
+ export declare function summaryKey(input: SummarizeInput): string;
34
+ /**
35
+ * Opens (or starts) a summary cache stored at `file`.
36
+ *
37
+ * @param file - Path of the JSON file, e.g. `.cache/summaries.json`.
38
+ * @returns The cache.
39
+ */
40
+ export declare function createFileSummaryCache(file: string): SummaryCache;
41
+ /**
42
+ * Summarize through the cache: a hit returns without a model call; a miss
43
+ * summarizes and stores the result. A summary that did not meet its caps
44
+ * (`withinCap: false`) is returned but not stored, so the next run tries again.
45
+ *
46
+ * @param input - The summarize request.
47
+ * @param options - The cache, and optionally a provider (defaults to the bonded one).
48
+ * @param options.cache - The cache to read and fill.
49
+ * @param options.summarizer - A provider to use instead of the bonded one.
50
+ * @returns The result, with `cached: true` on a hit and `key` for publishing.
51
+ */
52
+ export declare function summarizeCached(input: SummarizeInput, options: {
53
+ cache: SummaryCache;
54
+ summarizer?: AISummarizationProvider;
55
+ }): Promise<SummarizeResult & {
56
+ cached: boolean;
57
+ key: string;
58
+ }>;
59
+ //# sourceMappingURL=cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,OAAO,KAAK,EACV,uBAAuB,EACvB,cAAc,EACd,eAAe,EAChB,MAAM,gCAAgC,CAAA;AAGvC,0BAA0B;AAC1B,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,MAAM,CAAA;IACf,SAAS,CAAC,EAAE,OAAO,CAAA;CACpB;AAED,+DAA+D;AAC/D,MAAM,WAAW,YAAY;IAC3B,2CAA2C;IAC3C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa,GAAG,SAAS,CAAA;IAC3C,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,GAAG,IAAI,CAAA;IAC5C,0DAA0D;IAC1D,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA;IACxC,gDAAgD;IAChD,IAAI,IAAI,IAAI,CAAA;CACb;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,cAAc,GAAG,MAAM,CAWxD;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,CAyBjE;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,eAAe,CACnC,KAAK,EAAE,cAAc,EACrB,OAAO,EAAE;IAAE,KAAK,EAAE,YAAY,CAAC;IAAC,UAAU,CAAC,EAAE,uBAAuB,CAAA;CAAE,GACrE,OAAO,CAAC,eAAe,GAAG;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAC,CAS7D"}
package/dist/cache.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * A summary cache kept in one JSON file, keyed by a hash of the text and the
3
+ * caps — so an unchanged text is never summarized twice, across builds.
4
+ *
5
+ * Works with any bonded `ai-summarization` provider.
6
+ *
7
+ * @module
8
+ */
9
+ import { createHash } from 'node:crypto';
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { dirname } from 'node:path';
12
+ import { requireProvider } from '@molecule/api-ai-summarization';
13
+ /**
14
+ * The cache key for a request: a SHA-256 of the text (whitespace-normalized)
15
+ * and every option that changes the answer.
16
+ *
17
+ * @param input - The summarize request.
18
+ * @returns A 64-char hex key.
19
+ */
20
+ export function summaryKey(input) {
21
+ const basis = JSON.stringify([
22
+ input.text.replace(/\s+/g, ' ').trim(),
23
+ input.maxWords ?? null,
24
+ input.sentences ?? null,
25
+ input.maxLength ?? null,
26
+ input.format ?? null,
27
+ input.focus ?? null,
28
+ input.model ?? null,
29
+ ]);
30
+ return createHash('sha256').update(basis).digest('hex');
31
+ }
32
+ /**
33
+ * Opens (or starts) a summary cache stored at `file`.
34
+ *
35
+ * @param file - Path of the JSON file, e.g. `.cache/summaries.json`.
36
+ * @returns The cache.
37
+ */
38
+ export function createFileSummaryCache(file) {
39
+ let data = {};
40
+ if (existsSync(file)) {
41
+ try {
42
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
43
+ data = parsed.entries ?? {};
44
+ }
45
+ catch (_error) {
46
+ // A corrupt cache file is a cold cache: every text is summarized again and save() rewrites it.
47
+ data = {};
48
+ }
49
+ }
50
+ return {
51
+ file,
52
+ get: (key) => data[key],
53
+ set: (key, value) => {
54
+ data[key] = value;
55
+ },
56
+ entries: () => ({ ...data }),
57
+ save: () => {
58
+ mkdirSync(dirname(file), { recursive: true });
59
+ writeFileSync(file, JSON.stringify({ version: 1, entries: data }, null, 2) + '\n');
60
+ },
61
+ };
62
+ }
63
+ /**
64
+ * Summarize through the cache: a hit returns without a model call; a miss
65
+ * summarizes and stores the result. A summary that did not meet its caps
66
+ * (`withinCap: false`) is returned but not stored, so the next run tries again.
67
+ *
68
+ * @param input - The summarize request.
69
+ * @param options - The cache, and optionally a provider (defaults to the bonded one).
70
+ * @param options.cache - The cache to read and fill.
71
+ * @param options.summarizer - A provider to use instead of the bonded one.
72
+ * @returns The result, with `cached: true` on a hit and `key` for publishing.
73
+ */
74
+ export async function summarizeCached(input, options) {
75
+ const key = summaryKey(input);
76
+ const hit = options.cache.get(key);
77
+ if (hit)
78
+ return { ...hit, cached: true, key };
79
+ const result = await (options.summarizer ?? requireProvider()).summarize(input);
80
+ if (result.withinCap !== false && result.summary) {
81
+ options.cache.set(key, { summary: result.summary, withinCap: result.withinCap });
82
+ }
83
+ return { ...result, cached: false, key };
84
+ }
package/dist/index.d.ts CHANGED
@@ -26,7 +26,64 @@
26
26
  * })
27
27
  * ```
28
28
  *
29
+ * @example
30
+ * ```typescript
31
+ * // A one-sentence TL;DR with a HARD word cap, cached across builds — e.g. a
32
+ * // build step that summarizes each long section of each page.
33
+ * import { provider as anthropic } from '@molecule/api-ai-anthropic'
34
+ * import { setProvider as setAI } from '@molecule/api-ai'
35
+ * import { setProvider as setSummarizer } from '@molecule/api-ai-summarization'
36
+ * import {
37
+ * countWords,
38
+ * createFileSummaryCache,
39
+ * provider as summarization,
40
+ * summarizeCached,
41
+ * } from '@molecule/api-ai-summarization-llm'
42
+ *
43
+ * setAI(anthropic)
44
+ * setSummarizer(summarization)
45
+ *
46
+ * const cache = createFileSummaryCache('.cache/summaries.json')
47
+ * const rows: Record<string, string> = {}
48
+ * for (const section of sections) {
49
+ * if (countWords(section.prose) < 80) continue // too short to be worth a summary
50
+ * const r = await summarizeCached(
51
+ * { text: section.prose, format: 'tldr', maxWords: 25 },
52
+ * { cache },
53
+ * )
54
+ * rows[r.key] = r.summary // one complete sentence, ≤ 25 words
55
+ * }
56
+ * cache.save()
57
+ * // publish `rows` (e.g. write it next to the page as summaries.json)
58
+ * ```
59
+ *
29
60
  * @remarks
61
+ * **A hard cap is enforced here, in code — do not rebuild it.** With `maxWords`
62
+ * (and/or `sentences`, which defaults to 1 for `format: 'tldr'`) the provider
63
+ * cleans the answer (drops "TL;DR:" labels, quotes, `<think>` blocks), keeps
64
+ * whole sentences only, checks the cap and that the last word is not a
65
+ * function word ("the", "and", "of"…), and asks the model again when it runs
66
+ * long (`attempts`, default 3). It never slices a sentence and adds a full
67
+ * stop. If every attempt runs long it returns the shortest complete sentence
68
+ * with `withinCap: false`; `summarizeCached` does not store those, so the next
69
+ * run retries. It throws only when the model returns no usable text at all, or
70
+ * the AI provider fails — so "unavailable" is for a missing key or an
71
+ * unreachable provider, never for a long answer.
72
+ *
73
+ * Model quirks it already handles: it sends no `temperature` (several current
74
+ * models reject it), and it asks for a large output budget, because a model
75
+ * that reasons before answering can spend a small `maxTokens` entirely on
76
+ * hidden reasoning and stream no text.
77
+ *
78
+ * `summarizeCached` keys by a SHA-256 of the whitespace-normalized text plus
79
+ * every option, so an unchanged text is never re-summarized; `summaryKey(input)`
80
+ * gives the same key without calling the model. The cache is a plain JSON file
81
+ * (`{ version: 1, entries: { key: { summary } } }`); call `save()` once at the
82
+ * end. Server-only (Node `fs`/`crypto`): run it in a build script or a server
83
+ * route, never in client code — at build time, bond the `ai` provider inside
84
+ * the script that summarizes, since a bundler's separate passes do not share
85
+ * bonds set up elsewhere.
86
+ *
30
87
  * Composes the swappable `ai` bond: an `ai` provider MUST be bonded first
31
88
  * (`bond('ai', <provider>)`) or `summarize()` throws (a missing AI provider
32
89
  * throws at `summarize()` time, not at import). Pass `provider` on the input to
@@ -37,5 +94,6 @@
37
94
  * @module
38
95
  */
39
96
  export * from './browser-guard.js';
97
+ export * from './cache.js';
40
98
  export * from './provider.js';
41
99
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8FG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA"}
package/dist/index.js CHANGED
@@ -26,7 +26,64 @@
26
26
  * })
27
27
  * ```
28
28
  *
29
+ * @example
30
+ * ```typescript
31
+ * // A one-sentence TL;DR with a HARD word cap, cached across builds — e.g. a
32
+ * // build step that summarizes each long section of each page.
33
+ * import { provider as anthropic } from '@molecule/api-ai-anthropic'
34
+ * import { setProvider as setAI } from '@molecule/api-ai'
35
+ * import { setProvider as setSummarizer } from '@molecule/api-ai-summarization'
36
+ * import {
37
+ * countWords,
38
+ * createFileSummaryCache,
39
+ * provider as summarization,
40
+ * summarizeCached,
41
+ * } from '@molecule/api-ai-summarization-llm'
42
+ *
43
+ * setAI(anthropic)
44
+ * setSummarizer(summarization)
45
+ *
46
+ * const cache = createFileSummaryCache('.cache/summaries.json')
47
+ * const rows: Record<string, string> = {}
48
+ * for (const section of sections) {
49
+ * if (countWords(section.prose) < 80) continue // too short to be worth a summary
50
+ * const r = await summarizeCached(
51
+ * { text: section.prose, format: 'tldr', maxWords: 25 },
52
+ * { cache },
53
+ * )
54
+ * rows[r.key] = r.summary // one complete sentence, ≤ 25 words
55
+ * }
56
+ * cache.save()
57
+ * // publish `rows` (e.g. write it next to the page as summaries.json)
58
+ * ```
59
+ *
29
60
  * @remarks
61
+ * **A hard cap is enforced here, in code — do not rebuild it.** With `maxWords`
62
+ * (and/or `sentences`, which defaults to 1 for `format: 'tldr'`) the provider
63
+ * cleans the answer (drops "TL;DR:" labels, quotes, `<think>` blocks), keeps
64
+ * whole sentences only, checks the cap and that the last word is not a
65
+ * function word ("the", "and", "of"…), and asks the model again when it runs
66
+ * long (`attempts`, default 3). It never slices a sentence and adds a full
67
+ * stop. If every attempt runs long it returns the shortest complete sentence
68
+ * with `withinCap: false`; `summarizeCached` does not store those, so the next
69
+ * run retries. It throws only when the model returns no usable text at all, or
70
+ * the AI provider fails — so "unavailable" is for a missing key or an
71
+ * unreachable provider, never for a long answer.
72
+ *
73
+ * Model quirks it already handles: it sends no `temperature` (several current
74
+ * models reject it), and it asks for a large output budget, because a model
75
+ * that reasons before answering can spend a small `maxTokens` entirely on
76
+ * hidden reasoning and stream no text.
77
+ *
78
+ * `summarizeCached` keys by a SHA-256 of the whitespace-normalized text plus
79
+ * every option, so an unchanged text is never re-summarized; `summaryKey(input)`
80
+ * gives the same key without calling the model. The cache is a plain JSON file
81
+ * (`{ version: 1, entries: { key: { summary } } }`); call `save()` once at the
82
+ * end. Server-only (Node `fs`/`crypto`): run it in a build script or a server
83
+ * route, never in client code — at build time, bond the `ai` provider inside
84
+ * the script that summarizes, since a bundler's separate passes do not share
85
+ * bonds set up elsewhere.
86
+ *
30
87
  * Composes the swappable `ai` bond: an `ai` provider MUST be bonded first
31
88
  * (`bond('ai', <provider>)`) or `summarize()` throws (a missing AI provider
32
89
  * throws at `summarize()` time, not at import). Pass `provider` on the input to
@@ -37,4 +94,5 @@
37
94
  * @module
38
95
  */
39
96
  export * from './browser-guard.js';
97
+ export * from './cache.js';
40
98
  export * from './provider.js';
@@ -19,4 +19,37 @@ import type { AISummarizationProvider } from '@molecule/api-ai-summarization';
19
19
  * `AISummarizationProvider` to replace it without touching call sites.
20
20
  */
21
21
  export declare const provider: AISummarizationProvider;
22
+ /**
23
+ * Words in a string, the way a reader counts them.
24
+ *
25
+ * @param s - Any text.
26
+ * @returns The number of whitespace-separated words.
27
+ */
28
+ export declare function countWords(s: string): number;
29
+ /**
30
+ * Strips what models wrap a summary in: reasoning blocks, a "TL;DR:" or
31
+ * "Summary:" label, surrounding quotes or bold, and line breaks.
32
+ *
33
+ * @param raw - The model's answer.
34
+ * @returns The bare summary text.
35
+ */
36
+ export declare function cleanSummary(raw: string): string;
37
+ /**
38
+ * The first `n` complete sentences of a text. A trailing fragment with no
39
+ * terminal punctuation is dropped, never kept or given a full stop.
40
+ *
41
+ * @param s - Cleaned summary text.
42
+ * @param n - How many sentences to keep.
43
+ * @returns Those sentences, or `''` when the text holds no complete sentence.
44
+ */
45
+ export declare function firstSentences(s: string, n: number): string;
46
+ /**
47
+ * Whether a summary meets the caps and reads as finished: at most `maxWords`
48
+ * words, terminal punctuation, and a last word that is not a function word.
49
+ *
50
+ * @param s - Candidate summary.
51
+ * @param maxWords - The hard word cap, if any.
52
+ * @returns `true` when the summary can be published as is.
53
+ */
54
+ export declare function meetsCap(s: string, maxWords?: number): boolean;
22
55
  //# sourceMappingURL=provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AASH,OAAO,KAAK,EACV,uBAAuB,EAGxB,MAAM,gCAAgC,CAAA;AAgEvC;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ,EAAE,uBA2BtB,CAAA"}
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AASH,OAAO,KAAK,EACV,uBAAuB,EAGxB,MAAM,gCAAgC,CAAA;AAgEvC;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ,EAAE,uBA8BtB,CAAA;AASD;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAG5C;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAMhD;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAS3D;AAED;;;;;;;GAOG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAS9D"}
package/dist/provider.js CHANGED
@@ -78,14 +78,163 @@ export const provider = {
78
78
  defaultValue: 'AI provider "{{provider}}" is not bonded. Bond it before summarizing.',
79
79
  }));
80
80
  }
81
- const params = {
82
- messages: [{ role: 'user', content: input.text }],
83
- system: buildSystemPrompt(input),
81
+ const sentences = input.sentences ?? (input.format === 'tldr' ? 1 : undefined);
82
+ if (!input.maxWords && !sentences) {
83
+ const params = {
84
+ messages: [{ role: 'user', content: input.text }],
85
+ system: buildSystemPrompt(input),
86
+ model: input.model,
87
+ stream: false,
88
+ signal: input.signal,
89
+ };
90
+ const { text, usage } = await complete(ai, params);
91
+ return { summary: text.trim(), usage };
92
+ }
93
+ return summarizeCapped(ai, input, sentences ?? 1);
94
+ },
95
+ };
96
+ /** Words that never end a finished sentence — a summary ending on one was cut. */
97
+ const FUNCTION_WORDS = new Set('a an the and or but nor of to in on at by for with from into onto as than that which who whose whom is are was were be been its their his her our your my each every this these those so if then'.split(' '));
98
+ /**
99
+ * Words in a string, the way a reader counts them.
100
+ *
101
+ * @param s - Any text.
102
+ * @returns The number of whitespace-separated words.
103
+ */
104
+ export function countWords(s) {
105
+ const t = s.trim();
106
+ return t ? t.split(/\s+/).length : 0;
107
+ }
108
+ /**
109
+ * Strips what models wrap a summary in: reasoning blocks, a "TL;DR:" or
110
+ * "Summary:" label, surrounding quotes or bold, and line breaks.
111
+ *
112
+ * @param raw - The model's answer.
113
+ * @returns The bare summary text.
114
+ */
115
+ export function cleanSummary(raw) {
116
+ let s = raw.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, '');
117
+ s = s.replace(/\s+/g, ' ').trim();
118
+ s = s.replace(/^(?:\*\*)?(?:tl;?\s?dr|summary)(?:\*\*)?\s*[:\-–—]\s*/i, '');
119
+ s = s.replace(/^(\*\*|__|["“'‘])+/, '').replace(/(\*\*|__|["”'’])+$/, '');
120
+ return s.trim();
121
+ }
122
+ /**
123
+ * The first `n` complete sentences of a text. A trailing fragment with no
124
+ * terminal punctuation is dropped, never kept or given a full stop.
125
+ *
126
+ * @param s - Cleaned summary text.
127
+ * @param n - How many sentences to keep.
128
+ * @returns Those sentences, or `''` when the text holds no complete sentence.
129
+ */
130
+ export function firstSentences(s, n) {
131
+ const parts = s.split(/(?<=[.!?]["')\]”’]*)\s+(?=["'(“‘]?[A-Z0-9])/);
132
+ // Only the leading run of complete sentences counts: a fragment ends it.
133
+ const out = [];
134
+ for (const p of parts) {
135
+ if (!/[.!?]["')\]”’]*$/.test(p) || out.length === n)
136
+ break;
137
+ out.push(p);
138
+ }
139
+ return out.join(' ');
140
+ }
141
+ /**
142
+ * Whether a summary meets the caps and reads as finished: at most `maxWords`
143
+ * words, terminal punctuation, and a last word that is not a function word.
144
+ *
145
+ * @param s - Candidate summary.
146
+ * @param maxWords - The hard word cap, if any.
147
+ * @returns `true` when the summary can be published as is.
148
+ */
149
+ export function meetsCap(s, maxWords) {
150
+ if (!s || !/[.!?]["')\]”’]*$/.test(s))
151
+ return false;
152
+ if (maxWords && countWords(s) > maxWords)
153
+ return false;
154
+ const last = s
155
+ .replace(/[.!?"')\]”’]+$/, '')
156
+ .split(/\s+/)
157
+ .pop()
158
+ ?.toLowerCase();
159
+ return !!last && !FUNCTION_WORDS.has(last);
160
+ }
161
+ /**
162
+ * Summarize under hard caps: ask, keep whole sentences, re-ask when it runs
163
+ * long, and never slice a sentence to fit.
164
+ *
165
+ * @param ai - The resolved AI provider.
166
+ * @param input - The request.
167
+ * @param sentences - Sentence cap.
168
+ * @returns The summary, whether it met the caps, the calls made and summed usage.
169
+ */
170
+ async function summarizeCapped(ai, input, sentences) {
171
+ const cap = input.maxWords;
172
+ const attempts = Math.max(1, input.attempts ?? 3);
173
+ const shape = sentences === 1 ? 'one sentence' : `at most ${sentences} sentences`;
174
+ const system = [
175
+ `Summarize the user's text in ${shape}${cap ? ` of at most ${cap} words in total` : ''}, stating what the text does or says.`,
176
+ input.focus ? `Focus on: ${input.focus}` : '',
177
+ 'Reply with the summary only: no preamble, no label, no quotes, no markdown.',
178
+ ]
179
+ .filter(Boolean)
180
+ .join('\n');
181
+ const messages = [{ role: 'user', content: input.text }];
182
+ const candidates = [];
183
+ let usage;
184
+ for (let i = 0; i < attempts; i++) {
185
+ // No temperature (several current models reject it) and a generous output
186
+ // budget: a model that reasons before answering can spend a small budget
187
+ // entirely on hidden reasoning and return no text at all.
188
+ const r = await complete(ai, {
189
+ messages,
190
+ system,
84
191
  model: input.model,
192
+ maxTokens: Math.max(2048, (cap ?? 60) * 16),
85
193
  stream: false,
86
194
  signal: input.signal,
87
- };
88
- const { text, usage } = await complete(ai, params);
89
- return { summary: text.trim(), usage };
90
- },
91
- };
195
+ });
196
+ usage = addUsage(usage, r.usage);
197
+ const cleaned = cleanSummary(r.text);
198
+ const kept = firstSentences(cleaned, sentences);
199
+ if (kept)
200
+ candidates.push(kept);
201
+ if (meetsCap(kept, cap))
202
+ return { summary: kept, withinCap: true, attempts: i + 1, usage };
203
+ messages.push({ role: 'assistant', content: cleaned || '(no answer)' });
204
+ messages.push({
205
+ role: 'user',
206
+ content: kept
207
+ ? `That is ${countWords(kept)} words. Rewrite it as ${shape}${cap ? ` of at most ${cap} words` : ''}, ending with a full stop. Reply with the summary only.`
208
+ : `Reply with the summary only, as ${shape}${cap ? ` of at most ${cap} words` : ''}.`,
209
+ });
210
+ }
211
+ // Every attempt ran long: the first single sentence that fits, else the shortest answer.
212
+ for (const c of candidates) {
213
+ const one = firstSentences(c, 1);
214
+ if (meetsCap(one, cap))
215
+ return { summary: one, withinCap: true, attempts, usage };
216
+ }
217
+ const shortest = [...candidates].sort((a, b) => countWords(a) - countWords(b))[0];
218
+ if (!shortest) {
219
+ throw new Error(t('ai-summarization.error.noText', { attempts }, { defaultValue: 'The AI provider returned no usable summary after {{attempts}} attempts.' }));
220
+ }
221
+ return { summary: shortest, withinCap: false, attempts, usage };
222
+ }
223
+ /**
224
+ * Sums two usage records.
225
+ *
226
+ * @param a - Running total.
227
+ * @param b - This call's usage.
228
+ * @returns The sum (or whichever is defined).
229
+ */
230
+ function addUsage(a, b) {
231
+ if (!a)
232
+ return b;
233
+ if (!b)
234
+ return a;
235
+ return {
236
+ ...a,
237
+ inputTokens: a.inputTokens + b.inputTokens,
238
+ outputTokens: a.outputTokens + b.outputTokens,
239
+ };
240
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-ai-summarization-llm",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "Default LLM-composed AI summarization provider for molecule.dev — summarizes over any bonded @molecule/api-ai chat provider",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -33,8 +33,8 @@
33
33
  "@molecule/api-i18n": "^1.0.1"
34
34
  },
35
35
  "devDependencies": {
36
- "@molecule/api-ai": "1.2.1",
37
- "@molecule/api-ai-summarization": "1.0.2",
36
+ "@molecule/api-ai": "1.3.0",
37
+ "@molecule/api-ai-summarization": "1.1.0",
38
38
  "@molecule/api-bond": "1.0.2",
39
39
  "@molecule/api-i18n": "1.0.3",
40
40
  "@types/node": "26.1.2",