@drsamonline/compression 0.0.0-stage → 0.12.3

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.
Files changed (3) hide show
  1. package/package.json +23 -4
  2. package/src/index.js +652 -0
  3. package/README.md +0 -3
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@drsamonline/compression",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.12.3",
4
+ "description": "Prompt compression engines, presets and the quota-aware budget manager.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./src/index.js",
8
+ "exports": {
9
+ ".": "./src/index.js",
10
+ "./src/*": "./src/*"
11
+ },
12
+ "files": [
13
+ "src"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git://github.com/drsamonline/sui.git",
18
+ "directory": "packages/compression"
19
+ },
20
+ "homepage": "https://github.com/drsamonline/sui#readme",
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org/"
24
+ }
25
+ }
package/src/index.js ADDED
@@ -0,0 +1,652 @@
1
+ /**
2
+ * @drsamonline/compression — prompt compression (B4.1, B4.3).
3
+ *
4
+ * The point is not "smaller prompts". It is that a free tier has a quota, and a
5
+ * quota is spent in tokens. When a provider is plentiful, compress lightly; when
6
+ * it is nearly spent, compress hard, so the last of the quota buys more turns.
7
+ *
8
+ * Two rules hold across every engine:
9
+ *
10
+ * 1. **Protected spans are never touched.** Fenced code, inline code, URLs,
11
+ * email addresses, file paths and JSON-looking blocks are lifted out before
12
+ * any engine runs and put back byte-for-byte afterwards. A compressor that
13
+ * breaks a code block has cost more than it saved.
14
+ * 2. **A floor, not a target.** Every preset has a ratio it aims for and a
15
+ * floor it will not cross. If the text is mostly protected spans, the
16
+ * honest answer is "nothing to compress", not a mangled prompt.
17
+ *
18
+ * Honest labels: `session_dedup`, `rtk`, `headroom` and `caveman` are
19
+ * deterministic text transforms. `llmlingua_2` and `ccr` are *approximations* of
20
+ * the methods with those names — the real ones need a trained model or an
21
+ * external cache. What ships here is the shape, without pretending otherwise.
22
+ */
23
+
24
+ import { createHmac, randomUUID } from 'node:crypto';
25
+
26
+ export const ENGINES = ['canonicalise', 'session_dedup', 'rtk', 'headroom', 'caveman', 'llmlingua_2', 'ccr'];
27
+
28
+ export const PRESETS = {
29
+ lite: { target: 0.15, floor: 0.02, engines: ['canonicalise', 'session_dedup', 'rtk'] },
30
+ standard: { target: 0.3, floor: 0.05, engines: ['canonicalise', 'session_dedup', 'rtk', 'llmlingua_2'] },
31
+ aggressive: { target: 0.5, floor: 0.1, engines: ['canonicalise', 'session_dedup', 'rtk', 'llmlingua_2', 'caveman'] },
32
+ ultra: {
33
+ target: 0.75,
34
+ floor: 0.2,
35
+ engines: ['canonicalise', 'session_dedup', 'rtk', 'llmlingua_2', 'caveman', 'headroom', 'ccr'],
36
+ },
37
+ };
38
+
39
+ export const OUTPUT_STYLES = ['off', 'auto', 'terse', 'explanatory', 'bullet', 'code_only'];
40
+
41
+ /**
42
+ * The output axis: a short instruction, not a rewrite of the user's prompt.
43
+ *
44
+ * These are deliberately terse — a directive that costs 200 tokens to save 300
45
+ * is not a saving. Each is under 90 characters.
46
+ */
47
+ export const STYLE_DIRECTIVES = {
48
+ terse: 'Answer in as few words as possible. No preamble.',
49
+ explanatory: 'Give the answer, then one short paragraph explaining why.',
50
+ bullet: 'Answer as a short bullet list. No preamble.',
51
+ code_only: 'Return only code. No prose, no explanation, no fences.',
52
+ };
53
+
54
+ /**
55
+ * B4.4 — the adaptive dial.
56
+ *
57
+ * Scarce quota wants fewer output tokens, so the style tightens as the quota
58
+ * empties. `explanatory` is only chosen when there is room to pay for it.
59
+ *
60
+ * @param {{fraction?: number, taskHint?: string}} [input]
61
+ * @returns {{style: keyof typeof STYLE_DIRECTIVES, reason: string}}
62
+ */
63
+ export function chooseStyle(input = {}) {
64
+ const fraction = input.fraction ?? 1;
65
+ const hint = String(input.taskHint ?? '').toLowerCase();
66
+
67
+ if (/\b(code|function|refactor|test|regex|sql)\b/.test(hint)) {
68
+ return { style: 'code_only', reason: 'the task looks like code, so prose is noise' };
69
+ }
70
+ if (fraction > 0.6) return { style: 'explanatory', reason: `${Math.round(fraction * 100)}% of quota left — room to explain` };
71
+ if (fraction > 0.3) return { style: 'terse', reason: `${Math.round(fraction * 100)}% of quota left — keep it short` };
72
+ return { style: 'bullet', reason: `${Math.round(fraction * 100)}% of quota left — bullets cost less than paragraphs` };
73
+ }
74
+
75
+ /**
76
+ * Put the directive in front of the system message, without losing what was
77
+ * already there.
78
+ * @param {Array<{role: string, content: string}>} messages
79
+ * @param {string} style
80
+ */
81
+ export function applyStyle(messages, style) {
82
+ const directive = STYLE_DIRECTIVES[style];
83
+ if (!directive) return messages;
84
+
85
+ const out = [...messages];
86
+ const systemIndex = out.findIndex((m) => m.role === 'system');
87
+ if (systemIndex === -1) {
88
+ out.unshift({ role: 'system', content: directive });
89
+ } else {
90
+ out[systemIndex] = { ...out[systemIndex], content: `${directive}\n\n${out[systemIndex].content}` };
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /** Never compress past this, whatever the preset asks for. */
96
+ const HARD_MAX_RATIO = 0.8;
97
+ /** If protected spans cover more than this share of the text, do nothing. */
98
+ const PROTECTED_SKIP_SHARE = 0.8;
99
+
100
+ const STOPWORDS = new Set(
101
+ 'a an the and or but if then than that this these those is are was were be been being of to in on at by for with from as it its it\'s we you they he she i not no do does did have has had will would can could should may might must just very really quite rather also however therefore thus so such about into over under again further once here there when where why how all any both each few more most other some only own same too s t don now'.split(
102
+ ' ',
103
+ ),
104
+ );
105
+
106
+ /* ------------------------------------------------------------------ protection */
107
+
108
+ /**
109
+ * Lift out everything that must survive untouched.
110
+ * @param {string} text
111
+ * @returns {{masked: string, spans: string[], protectedChars: number}}
112
+ */
113
+ export function protect(text) {
114
+ const spans = [];
115
+ const hold = (s) => {
116
+ spans.push(s);
117
+ return `\u0000${spans.length - 1}\u0000`;
118
+ };
119
+
120
+ let masked = String(text ?? '');
121
+
122
+ // order matters: fenced code first, so its contents are not re-matched
123
+ masked = masked.replace(/```[\s\S]*?```/g, hold);
124
+ masked = masked.replace(/`[^`\n]{1,400}`/g, hold);
125
+ masked = masked.replace(/https?:\/\/[^\s<>"')]+/g, hold);
126
+ masked = masked.replace(/\b[\w.+-]+@[\w-]+\.[\w.-]+\b/g, hold);
127
+ masked = masked.replace(/(?:\/[\w.@-]+){2,}\/?/g, hold); // file paths
128
+ masked = masked.replace(/\b[0-9a-f]{7,40}\b/g, hold); // commit-ish ids
129
+ masked = replaceJsonBlocks(masked, hold);
130
+
131
+ const protectedChars = spans.reduce((a, s) => a + s.length, 0);
132
+ return { masked, spans, protectedChars };
133
+ }
134
+
135
+ /** @param {string} text @param {string[]} spans */
136
+ export function restore(text, spans) {
137
+ return String(text).replace(/\u0000(\d+)\u0000/g, (_, i) => spans[Number(i)] ?? '');
138
+ }
139
+
140
+ /** Balanced-brace JSON blocks, capped so a stray "{" cannot swallow a prompt. */
141
+ function replaceJsonBlocks(text, hold) {
142
+ let out = '';
143
+ let i = 0;
144
+ while (i < text.length) {
145
+ const ch = text[i];
146
+ if ((ch === '{' || ch === '[') && looksLikeJson(text, i)) {
147
+ const end = matchBracket(text, i);
148
+ if (end > i && end - i < 4000) {
149
+ out += hold(text.slice(i, end + 1));
150
+ i = end + 1;
151
+ continue;
152
+ }
153
+ }
154
+ out += ch;
155
+ i += 1;
156
+ }
157
+ return out;
158
+ }
159
+
160
+ function looksLikeJson(text, start) {
161
+ const window = text.slice(start, start + 200);
162
+ return /"[^"]{1,40}"\s*:/.test(window) || /^\s*[[{]\s*$/.test(window.slice(0, 3));
163
+ }
164
+
165
+ function matchBracket(text, start) {
166
+ const open = text[start];
167
+ const close = open === '{' ? '}' : ']';
168
+ let depth = 0;
169
+ for (let i = start; i < text.length && i < start + 4000; i++) {
170
+ if (text[i] === open) depth += 1;
171
+ else if (text[i] === close) {
172
+ depth -= 1;
173
+ if (depth === 0) return i;
174
+ }
175
+ }
176
+ return -1;
177
+ }
178
+
179
+ /* -------------------------------------------------------------------- engines */
180
+
181
+ /**
182
+ * B4.2 — canonicalise before compressing, the way `lexora` does.
183
+ *
184
+ * Lossless normalisation: unicode form, line endings, zero-width characters,
185
+ * smart quotes and dashes, ragged indentation, trailing spaces, repeated blank
186
+ * lines. None of it changes what the text says, and every byte removed is a byte
187
+ * the later engines do not have to reason about.
188
+ */
189
+ export function canonicalise(text) {
190
+ const before = text.length;
191
+ let out = String(text)
192
+ .normalize('NFKC')
193
+ .replace(/\r\n?/g, '\n')
194
+ .replace(/[\u200b-\u200f\u202a-\u202e\ufeff]/g, '') // zero-width and bidi controls
195
+ .replace(/[\u2018\u2019\u201b]/g, "'")
196
+ .replace(/[\u201c\u201d\u201f]/g, '"')
197
+ .replace(/[\u2013\u2014]/g, '-')
198
+ .replace(/\u2026/g, '...')
199
+ .replace(/[\u00a0\u2007\u202f]/g, ' ') // non-breaking spaces
200
+ .replace(/[ \t]+$/gm, '')
201
+ .replace(/\n{3,}/g, '\n\n');
202
+
203
+ // dedent: drop the indentation every non-empty line shares
204
+ const lines = out.split('\n').filter((l) => l.trim());
205
+ const indent = lines.length ? Math.min(...lines.map((l) => l.match(/^[ \t]*/)?.[0].length ?? 0)) : 0;
206
+ if (indent > 0) out = out.split('\n').map((l) => l.slice(Math.min(indent, l.length))).join('\n');
207
+
208
+ const dropped = Math.max(0, before - out.length);
209
+ return {
210
+ text: out,
211
+ droppedChars: dropped,
212
+ note: dropped ? `normalised ${dropped} chars (unicode, quotes, indentation, blank lines)` : 'already canonical',
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Drop paragraphs that repeat something already said. A conversation resent in
218
+ * full on every turn is mostly repetition.
219
+ * @param {string} text
220
+ * @param {{store?: RecallStore}} [ctx]
221
+ */
222
+ export function sessionDedup(text, ctx = {}) {
223
+ const blocks = text.split(/\n{2,}/);
224
+ const seen = new Set();
225
+ const kept = [];
226
+ let droppedChars = 0;
227
+
228
+ for (const block of blocks) {
229
+ const normalised = block.replace(/\s+/g, ' ').trim().toLowerCase();
230
+ if (normalised.length < 40) {
231
+ kept.push(block);
232
+ continue;
233
+ }
234
+ if (seen.has(normalised) && !block.includes('\u0000')) {
235
+ // A duplicated block is only droppable if it holds no protected span:
236
+ // repeating code is still code, and the guarantee is that code survives.
237
+ droppedChars += block.length;
238
+ continue;
239
+ }
240
+ seen.add(normalised);
241
+ kept.push(block);
242
+ }
243
+
244
+ const out = kept.join('\n\n');
245
+ return {
246
+ text: droppedChars ? `${out}\n\n[${droppedChars} chars of repeated context removed]` : out,
247
+ droppedChars,
248
+ note: droppedChars ? `dropped ${droppedChars} chars of duplicate context` : 'no duplicates',
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Collapse repeated tokens and punctuation runs. "very very very" costs tokens;
254
+ * "very ×3" does not.
255
+ */
256
+ export function rtk(text) {
257
+ const before = text.length;
258
+ let out = text
259
+ .replace(/\b(\w{2,})(\s+\1\b){2,}/gi, (m, word) => {
260
+ const occurrences = (m.match(new RegExp(`\\b${word}\\b`, 'gi')) ?? []).length;
261
+ return `${word} ×${occurrences}`;
262
+ })
263
+ .replace(/([!?.,])\1{2,}/g, '$1')
264
+ .replace(/[ \t]{3,}/g, ' ')
265
+ .replace(/\n{4,}/g, '\n\n\n');
266
+
267
+ return {
268
+ text: out,
269
+ droppedChars: Math.max(0, before - out.length),
270
+ note: before === out.length ? 'no runs to collapse' : `collapsed ${before - out.length} chars of repetition`,
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Split text into atoms where every protected placeholder is one indivisible
276
+ * atom. Truncation must never cut a placeholder in half, or the span it stands
277
+ * for is lost when the text is restored.
278
+ * @param {string} text
279
+ */
280
+ export function atomise(text) {
281
+ const atoms = [];
282
+ const re = /\u0000\d+\u0000/g;
283
+ let last = 0;
284
+ let m;
285
+ while ((m = re.exec(text))) {
286
+ if (m.index > last) atoms.push(...text.slice(last, m.index).split(''));
287
+ atoms.push(m[0]);
288
+ last = m.index + m[0].length;
289
+ }
290
+ if (last < text.length) atoms.push(...text.slice(last).split(''));
291
+ return atoms;
292
+ }
293
+
294
+ /**
295
+ * Keep the head and the tail, drop the middle. For a long file dump the middle
296
+ * is usually the least useful part of the context.
297
+ */
298
+ export function headroom(text, opts = {}) {
299
+ const keepHead = opts.keepHead ?? 0.6;
300
+ const keepTail = opts.keepTail ?? 0.25;
301
+ const maxChars = opts.maxChars ?? Math.max(600, Math.round(text.length * 0.5));
302
+
303
+ if (text.length <= maxChars) return { text, droppedChars: 0, note: 'within budget' };
304
+
305
+ // Atoms, so a placeholder is kept or dropped whole — never split.
306
+ const atoms = atomise(text).map((a) => ({ a, prot: /^\u0000\d+\u0000$/.test(a) }));
307
+ const protectedChars = atoms.reduce((n, x) => n + (x.prot ? x.a.length : 0), 0);
308
+
309
+ // The guarantee wins over the budget: every protected span is kept, even if
310
+ // that leaves less room than the preset asked for.
311
+ const headBudget = Math.max(0, Math.round(maxChars * keepHead));
312
+ const tailBudget = Math.max(0, Math.round(maxChars * keepTail));
313
+
314
+ const keep = new Array(atoms.length).fill(false);
315
+
316
+ // Walk the whole array for both passes. A `break` when the prose budget runs
317
+ // out would skip every protected span past that point — which is exactly how
318
+ // a JSON block in the middle of a prompt gets silently dropped.
319
+ let headUsed = 0;
320
+ let headFull = false;
321
+ for (let i = 0; i < atoms.length; i++) {
322
+ if (atoms[i].prot) {
323
+ keep[i] = true;
324
+ continue;
325
+ }
326
+ if (headFull) continue;
327
+ if (headUsed + atoms[i].a.length > headBudget) {
328
+ headFull = true;
329
+ continue;
330
+ }
331
+ keep[i] = true;
332
+ headUsed += atoms[i].a.length;
333
+ }
334
+
335
+ let tailUsed = 0;
336
+ let tailFull = false;
337
+ for (let i = atoms.length - 1; i >= 0; i--) {
338
+ if (atoms[i].prot) {
339
+ keep[i] = true;
340
+ continue;
341
+ }
342
+ if (tailFull) continue;
343
+ if (tailUsed + atoms[i].a.length > tailBudget) {
344
+ tailFull = true;
345
+ continue;
346
+ }
347
+ keep[i] = true;
348
+ tailUsed += atoms[i].a.length;
349
+ }
350
+
351
+ let out = '';
352
+ let dropped = 0;
353
+ let inGap = false;
354
+ for (let i = 0; i < atoms.length; i++) {
355
+ if (keep[i]) {
356
+ if (inGap) {
357
+ out += `\n\n[… ${dropped} chars omitted from the middle …]\n\n`;
358
+ dropped = 0;
359
+ inGap = false;
360
+ }
361
+ out += atoms[i].a;
362
+ } else {
363
+ dropped += atoms[i].a.length;
364
+ inGap = true;
365
+ }
366
+ }
367
+ if (inGap) out += `\n\n[… ${dropped} chars omitted from the middle …]\n\n`;
368
+
369
+ if (out.length >= text.length) return { text, droppedChars: 0, note: 'nothing safe to drop' };
370
+ return {
371
+ text: out,
372
+ droppedChars: text.length - out.length,
373
+ note: `dropped ${text.length - out.length} chars from the middle, kept ${protectedChars} chars of protected spans`,
374
+ };
375
+ }
376
+
377
+ /**
378
+ * Strip function words from prose lines only. Code, URLs and JSON are protected
379
+ * before this runs, so "caveman" cannot turn a query into a syntax error.
380
+ */
381
+ export function caveman(text) {
382
+ const before = text.length;
383
+ const out = text
384
+ .split('\n')
385
+ .map((line) => {
386
+ if (!/[a-z]/i.test(line)) return line;
387
+ const words = line.split(/(\s+)/);
388
+ const kept = [];
389
+ let atSentenceStart = true;
390
+
391
+ for (const w of words) {
392
+ if (/^\s+$/.test(w)) {
393
+ kept.push(w);
394
+ continue;
395
+ }
396
+ const bare = w.toLowerCase().replace(/[^a-z']/g, '');
397
+ const structural = /[{}[\]()=<>+*/|&%$#@_\\]/.test(w);
398
+ const keep = structural || atSentenceStart || !STOPWORDS.has(bare);
399
+ if (keep) kept.push(w);
400
+ // a sentence boundary is what makes the next word structural
401
+ if (/[.!?:;]$/.test(w) || /^[-*•]$/.test(w)) atSentenceStart = true;
402
+ else if (keep) atSentenceStart = false;
403
+ }
404
+ return kept.join('').replace(/\s{2,}/g, ' ').trim();
405
+ })
406
+ .join('\n');
407
+
408
+ return {
409
+ text: out,
410
+ droppedChars: Math.max(0, before - out.length),
411
+ note: before === out.length ? 'nothing to strip' : `removed ${before - out.length} chars of function words`,
412
+ };
413
+ }
414
+
415
+ /**
416
+ * An approximation of LLMLingua's idea: keep the sentences that carry the rare
417
+ * terms, drop the ones that only repeat common ones. No model, no download —
418
+ * a sentence score from term frequency inside this prompt.
419
+ */
420
+ export function llmLingua2(text, opts = {}) {
421
+ const keep = opts.keep ?? 0.7;
422
+ const sentences = text.split(/(?<=[.!?])\s+/).filter((s) => s.trim().length > 0);
423
+ if (sentences.length < 3) return { text, droppedChars: 0, note: 'too few sentences to prune' };
424
+
425
+ const df = new Map();
426
+ for (const s of sentences) {
427
+ for (const term of new Set(terms(s))) df.set(term, (df.get(term) ?? 0) + 1);
428
+ }
429
+ const scored = sentences.map((s, i) => {
430
+ const t = terms(s);
431
+ const score = t.reduce((a, term) => a + 1 / (df.get(term) ?? 1), 0) / Math.sqrt(Math.max(1, t.length));
432
+ // A sentence holding a protected span scores as if it were priceless.
433
+ const protectedBoost = s.includes('\u0000') ? 1000 : 0;
434
+ return { s, i, score: score + protectedBoost + (i === sentences.length - 1 ? 0.5 : 0) };
435
+ });
436
+
437
+ const keepCount = Math.max(1, Math.round(sentences.length * keep));
438
+ const keptIndexes = new Set(
439
+ [...scored].sort((a, b) => b.score - a.score).slice(0, keepCount).map((x) => x.i),
440
+ );
441
+ // The last sentence is usually the actual ask. It is kept unconditionally.
442
+ keptIndexes.add(sentences.length - 1);
443
+
444
+ const out = sentences
445
+ .map((s, i) => (keptIndexes.has(i) ? s : null))
446
+ .filter(Boolean)
447
+ .join(' ');
448
+ return {
449
+ text: out,
450
+ droppedChars: Math.max(0, text.length - out.length),
451
+ note: `kept ${keepCount}/${sentences.length} sentences by term rarity`,
452
+ };
453
+ }
454
+
455
+ function terms(s) {
456
+ return String(s)
457
+ .toLowerCase()
458
+ .split(/[^a-z0-9']+/)
459
+ .filter((w) => w.length > 2 && !STOPWORDS.has(w));
460
+ }
461
+
462
+ /* ----------------------------------------------------------------------- ccr */
463
+
464
+ /**
465
+ * A recall store: what compression throws away is kept here, under a signed
466
+ * token, so the full text can be recovered deliberately.
467
+ *
468
+ * This is the honest half of "compress, cache, retrieve": the prompt carries a
469
+ * marker, and `retrieve(token)` returns what was dropped. The signature means a
470
+ * token cannot be guessed from another prompt.
471
+ */
472
+ export class RecallStore {
473
+ /**
474
+ * @param {{secret?: string, maxEntries?: number, now?: () => number}} [opts]
475
+ */
476
+ constructor(opts = {}) {
477
+ this.secret = opts.secret ?? process.env.SUI_RECALL_SECRET ?? 'sui-recall-local';
478
+ this.maxEntries = opts.maxEntries ?? 200;
479
+ this.now = opts.now ?? Date.now;
480
+ /** @type {Map<string, {text: string, at: number}>} */
481
+ this.entries = new Map();
482
+ }
483
+
484
+ /** @param {string} text */
485
+ put(text) {
486
+ const id = randomUUID().slice(0, 8);
487
+ const sig = createHmac('sha256', this.secret).update(id).digest('hex').slice(0, 8);
488
+ const token = `${id}.${sig}`;
489
+ this.entries.set(token, { text, at: this.now() });
490
+ if (this.entries.size > this.maxEntries) {
491
+ const oldest = this.entries.keys().next();
492
+ if (!oldest.done) this.entries.delete(oldest.value);
493
+ }
494
+ return token;
495
+ }
496
+
497
+ /** @param {string} token */
498
+ get(token) {
499
+ const [id, sig] = String(token).split('.');
500
+ if (!id || !sig) return null;
501
+ const expected = createHmac('sha256', this.secret).update(id).digest('hex').slice(0, 8);
502
+ if (expected !== sig) return null;
503
+ return this.entries.get(token)?.text ?? null;
504
+ }
505
+
506
+ /** @param {string} token */
507
+ verify(token) {
508
+ const [id, sig] = String(token).split('.');
509
+ if (!id || !sig) return false;
510
+ return createHmac('sha256', this.secret).update(id).digest('hex').slice(0, 8) === sig;
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Replace the middle of the prompt with a signed recall marker.
516
+ * @param {string} text
517
+ * @param {{store: RecallStore, keepShare?: number}} opts
518
+ */
519
+ export function ccr(text, opts) {
520
+ const store = opts?.store;
521
+ const keepShare = opts?.keepShare ?? 0.5;
522
+ if (!store) return { text, droppedChars: 0, note: 'no recall store — ccr skipped' };
523
+ if (text.length < 400) return { text, droppedChars: 0, note: 'too short to recall' };
524
+
525
+ const head = Math.round(text.length * keepShare);
526
+ const dropped = text.slice(head);
527
+ const token = store.put(dropped);
528
+ const out = `${text.slice(0, head)}\n\n[sui:recall ${token} — ${dropped.length} chars omitted, retrievable]`;
529
+
530
+ return { text: out, droppedChars: text.length - out.length, note: `moved ${dropped.length} chars behind a signed marker`, token };
531
+ }
532
+
533
+ /* -------------------------------------------------------------------- presets */
534
+
535
+ /**
536
+ * Run a preset over a prompt.
537
+ *
538
+ * @param {string} text
539
+ * @param {{preset?: keyof typeof PRESETS, store?: RecallStore, engines?: string[]}} [opts]
540
+ * @returns {{text: string, preset: string, originalChars: number, compressedChars: number, ratio: number, savedChars: number, skipped: string|null, steps: Array<{engine: string, note: string, droppedChars: number}>, tokens: string[]}}
541
+ */
542
+ export function compress(text, opts = {}) {
543
+ const presetName = opts.preset ?? 'standard';
544
+ const preset = PRESETS[presetName];
545
+ if (!preset) throw new Error(`Unknown compression preset "${presetName}". Use: ${Object.keys(PRESETS).join(', ')}.`);
546
+
547
+ const original = String(text ?? '');
548
+ const originalChars = original.length;
549
+ const empty = {
550
+ text: original,
551
+ preset: presetName,
552
+ originalChars,
553
+ compressedChars: originalChars,
554
+ ratio: 0,
555
+ savedChars: 0,
556
+ skipped: null,
557
+ steps: [],
558
+ tokens: [],
559
+ };
560
+
561
+ if (originalChars < 200) return { ...empty, skipped: 'too short to be worth compressing' };
562
+
563
+ const { masked, spans, protectedChars } = protect(original);
564
+ if (protectedChars / originalChars > PROTECTED_SKIP_SHARE) {
565
+ return { ...empty, skipped: `${Math.round((protectedChars / originalChars) * 100)}% of this prompt is code, URLs or JSON — left alone` };
566
+ }
567
+
568
+ const target = Math.max(preset.floor, Math.min(HARD_MAX_RATIO, preset.target));
569
+ const engines = opts.engines ?? preset.engines;
570
+ let current = masked;
571
+ const steps = [];
572
+ const tokens = [];
573
+
574
+ for (const engine of engines) {
575
+ if (current.length <= masked.length * (1 - target)) break;
576
+ let result;
577
+ switch (engine) {
578
+ case 'canonicalise':
579
+ result = canonicalise(current);
580
+ break;
581
+ case 'session_dedup':
582
+ result = sessionDedup(current, opts);
583
+ break;
584
+ case 'rtk':
585
+ result = rtk(current);
586
+ break;
587
+ case 'caveman':
588
+ result = caveman(current);
589
+ break;
590
+ case 'llmlingua_2':
591
+ result = llmLingua2(current, { keep: 0.7 });
592
+ break;
593
+ case 'headroom':
594
+ result = headroom(current, { maxChars: Math.round(current.length * 0.6) });
595
+ break;
596
+ case 'ccr':
597
+ result = ccr(current, { store: opts.store, keepShare: 0.5 });
598
+ break;
599
+ default:
600
+ result = { text: current, droppedChars: 0, note: `unknown engine "${engine}" — skipped` };
601
+ }
602
+ if (result.token) tokens.push(result.token);
603
+ if (result.text.length < current.length) {
604
+ steps.push({ engine, note: result.note, droppedChars: current.length - result.text.length });
605
+ current = result.text;
606
+ } else {
607
+ steps.push({ engine, note: result.note, droppedChars: 0 });
608
+ }
609
+ }
610
+
611
+ const restored = restore(current, spans);
612
+ const compressedChars = restored.length;
613
+ const savedChars = Math.max(0, originalChars - compressedChars);
614
+
615
+ return {
616
+ text: restored,
617
+ preset: presetName,
618
+ originalChars,
619
+ compressedChars,
620
+ ratio: originalChars ? Math.round((savedChars / originalChars) * 1000) / 1000 : 0,
621
+ savedChars,
622
+ skipped: null,
623
+ steps,
624
+ tokens,
625
+ };
626
+ }
627
+
628
+ /* ------------------------------------------------------------ budget manager */
629
+
630
+ /**
631
+ * B4.3 — pick a preset from what is left of the quota.
632
+ *
633
+ * The rule is simple on purpose: plentiful → compress lightly (quality first),
634
+ * scarce → compress hard (a smaller prompt that still gets an answer beats a
635
+ * perfect prompt the provider refuses).
636
+ *
637
+ * @param {{remaining?: number, limit?: number, fraction?: number}} quota
638
+ * @returns {{preset: keyof typeof PRESETS, reason: string, fraction: number}}
639
+ */
640
+ export function choosePreset(quota = {}) {
641
+ const fraction =
642
+ quota.fraction != null
643
+ ? Number(quota.fraction)
644
+ : quota.remaining != null && quota.limit
645
+ ? Number(quota.remaining) / Number(quota.limit)
646
+ : 1;
647
+
648
+ if (fraction > 0.6) return { preset: 'lite', fraction, reason: `${Math.round(fraction * 100)}% of quota left — compress lightly` };
649
+ if (fraction > 0.3) return { preset: 'standard', fraction, reason: `${Math.round(fraction * 100)}% of quota left — standard compression` };
650
+ if (fraction > 0.1) return { preset: 'aggressive', fraction, reason: `${Math.round(fraction * 100)}% of quota left — compress hard` };
651
+ return { preset: 'ultra', fraction, reason: `${Math.round(fraction * 100)}% of quota left — squeeze the last turns out of it` };
652
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.