acp-kernel 0.0.63-pr.250.97 → 0.0.63-pr.252.98

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/DESIGN.md CHANGED
@@ -169,6 +169,8 @@ type NudgeDecision = {
169
169
  shouldInject: boolean;
170
170
  reason: string;
171
171
  compressibleRanges: { startRef: string; endRef: string; tokens: number }[];
172
+ activeBlocks?: CompressionBlock[]; // rendered as a compact block ledger (id → ref span) in the nudge text (#251)
173
+ messageRefs?: MessageRefMap; // resolves each block's effectiveMessageIds back to m-refs
172
174
  contextUsage: number; // 0..1
173
175
  tier: 1 | 2 | 3 | null; // multi-tier trigger, if any
174
176
  breakdown: Record<string, number>;
@@ -1,3 +1,77 @@
1
+ // src/refs.ts
2
+ var REF_WIDTH = 5;
3
+ var MIN_INDEX = 1;
4
+ var MAX_INDEX = 99999;
5
+ var REF_PATTERN = /^m0*(\d{1,5})$/;
6
+ var BLOCKED_REF = "BLOCKED";
7
+ function emptyRefMap() {
8
+ return { byRaw: {}, byRef: {} };
9
+ }
10
+ function indexToRef(index) {
11
+ if (!Number.isInteger(index) || index < MIN_INDEX || index > MAX_INDEX) {
12
+ throw new RangeError(
13
+ `ref index out of bounds: ${index} (allowed ${MIN_INDEX}-${MAX_INDEX})`
14
+ );
15
+ }
16
+ return `m${String(index).padStart(REF_WIDTH, "0")}`;
17
+ }
18
+ function refToIndex(ref) {
19
+ const match = REF_PATTERN.exec(ref.trim().toLowerCase());
20
+ if (!match) return null;
21
+ const index = Number(match[1]);
22
+ if (index < MIN_INDEX || index > MAX_INDEX) return null;
23
+ return index;
24
+ }
25
+ function refForRaw(map, rawId) {
26
+ return map.byRaw[rawId] ?? null;
27
+ }
28
+ function rawForRef(map, ref) {
29
+ return map.byRef[ref] ?? null;
30
+ }
31
+ function assignRefs(messages, options) {
32
+ const map = {
33
+ byRaw: { ...options.existing.byRaw },
34
+ byRef: { ...options.existing.byRef }
35
+ };
36
+ let cursor = Number.isInteger(options.nextIndex) && options.nextIndex >= MIN_INDEX ? options.nextIndex : MIN_INDEX;
37
+ let newlyAssigned = 0;
38
+ for (const message of messages) {
39
+ if (!message.id || options.shouldSkip?.(message)) continue;
40
+ if (map.byRaw[message.id]) continue;
41
+ if (options.isProtected?.(message)) {
42
+ map.byRaw[message.id] = BLOCKED_REF;
43
+ continue;
44
+ }
45
+ const ref = allocateFreeRef(map, cursor);
46
+ cursor = ref.index + 1;
47
+ map.byRaw[message.id] = ref.text;
48
+ map.byRef[ref.text] = message.id;
49
+ newlyAssigned++;
50
+ }
51
+ return { map, nextIndex: cursor, newlyAssigned };
52
+ }
53
+ function allocateFreeRef(map, start) {
54
+ let candidate = Math.max(start, MIN_INDEX);
55
+ while (candidate <= MAX_INDEX) {
56
+ const text = indexToRef(candidate);
57
+ if (!map.byRef[text]) {
58
+ return { text, index: candidate };
59
+ }
60
+ candidate++;
61
+ }
62
+ throw new Error(
63
+ `ref capacity exhausted: cannot allocate beyond ${indexToRef(MAX_INDEX)}`
64
+ );
65
+ }
66
+ function highestUsedIndex(map) {
67
+ let highest = 0;
68
+ for (const ref of Object.values(map.byRaw)) {
69
+ const index = ref === BLOCKED_REF ? null : refToIndex(ref);
70
+ if (index !== null && index > highest) highest = index;
71
+ }
72
+ return highest;
73
+ }
74
+
1
75
  // src/tokenize.ts
2
76
  import { createRequire } from "module";
3
77
  var require2 = createRequire(import.meta.url);
@@ -169,17 +243,15 @@ function resolvePrompts(overrides, options = {}) {
169
243
  }
170
244
 
171
245
  // src/nudge-text.ts
172
- function efficiencyNote(prompts, includeGuidance) {
173
- const note = "This is an efficiency nudge to compress early and keep context lean \u2014 not an overflow warning. A separate, stronger alert will appear if the context is actually full.";
174
- return includeGuidance ? `${note}
246
+ function efficiencyNote(prompts) {
247
+ return `This is an efficiency nudge to compress early and keep context lean \u2014 not an overflow warning. A separate, stronger alert will appear if the context is actually full.
175
248
 
176
- ${prompts.compressPhilosophy}` : note;
249
+ ${prompts.compressPhilosophy}`;
177
250
  }
178
- function emergencyHeader(prompts, includeGuidance) {
179
- const header = "\u26A0\uFE0F Context limit reached \u2014 compress now. Prioritize consumed tool outputs.";
180
- return includeGuidance ? `${header}
251
+ function emergencyHeader(prompts) {
252
+ return `\u26A0\uFE0F Context limit reached \u2014 compress now. Prioritize consumed tool outputs.
181
253
 
182
- ${prompts.compressPhilosophy}` : header;
254
+ ${prompts.compressPhilosophy}`;
183
255
  }
184
256
  function formatK(n) {
185
257
  if (n >= 1e3) return `${(n / 1e3).toFixed(1)}K`;
@@ -288,10 +360,64 @@ function formatRanges(compressible, protectedRanges) {
288
360
  return `Compressible ranges (${merged.length}, oldest first):
289
361
  ${lines.join("\n")}`;
290
362
  }
291
- function renderNudgeText(decision, prompts = defaultPrompts, options = {}) {
292
- const includeGuidance = options.includeGuidance ?? true;
363
+ var MAX_BLOCK_LEDGER_ENTRIES = 8;
364
+ function blockIndex(id) {
365
+ const n = Number(id.slice(1));
366
+ return Number.isFinite(n) ? n : 0;
367
+ }
368
+ function blockSpan(block, refs) {
369
+ let loIdx = null;
370
+ let hiIdx = null;
371
+ let loRef = "";
372
+ let hiRef = "";
373
+ for (const rawId of block.effectiveMessageIds) {
374
+ const ref = refs?.byRaw[rawId];
375
+ if (!ref || ref === BLOCKED_REF) continue;
376
+ const idx = refToIndex(ref);
377
+ if (idx === null) continue;
378
+ if (loIdx === null || idx < loIdx) {
379
+ loIdx = idx;
380
+ loRef = ref;
381
+ }
382
+ if (hiIdx === null || idx > hiIdx) {
383
+ hiIdx = idx;
384
+ hiRef = ref;
385
+ }
386
+ }
387
+ if (loIdx !== null && hiIdx !== null) return { start: loRef, end: hiRef };
388
+ if (block.startRef && block.endRef) {
389
+ const s = refToIndex(block.startRef);
390
+ const e = refToIndex(block.endRef);
391
+ if (s !== null && e !== null) {
392
+ return s <= e ? { start: block.startRef, end: block.endRef } : { start: block.endRef, end: block.startRef };
393
+ }
394
+ }
395
+ return null;
396
+ }
397
+ function formatBlockLedger(blocks, refs, maxEntries = MAX_BLOCK_LEDGER_ENTRIES) {
398
+ const entries = [];
399
+ const sorted = [...blocks].sort((a, b) => blockIndex(a.blockId) - blockIndex(b.blockId));
400
+ for (const block of sorted) {
401
+ const span = blockSpan(block, refs);
402
+ if (!span) continue;
403
+ const range = span.start === span.end ? span.start : `${span.start}\u2013${span.end}`;
404
+ entries.push(
405
+ block.tier >= 2 ? `${block.blockId}=tier${block.tier}(${range})` : `${block.blockId}=${range}`
406
+ );
407
+ }
408
+ if (entries.length === 0) return "";
409
+ let shown = entries;
410
+ let olderNote = "";
411
+ if (entries.length > maxEntries) {
412
+ shown = entries.slice(entries.length - maxEntries);
413
+ olderNote = ` (+${entries.length - maxEntries} older)`;
414
+ }
415
+ return `Blocks${olderNote}: ${shown.join(" \xB7 ")}`;
416
+ }
417
+ function renderNudgeText(decision, prompts = defaultPrompts) {
293
418
  const breakdownStr = formatBreakdown(decision.contextBreakdown);
294
419
  const rangesStr = formatRanges(decision.compressibleRanges, decision.protectedRanges ?? []);
420
+ const ledgerStr = formatBlockLedger(decision.activeBlocks ?? [], decision.messageRefs);
295
421
  const isEmergency = !!decision.breakdown?.emergencyOverride || !!decision.breakdown?.overLimit;
296
422
  if (decision.tier !== null && decision.tier >= 2) {
297
423
  const isT2 = decision.tier === 2;
@@ -301,37 +427,58 @@ function renderNudgeText(decision, prompts = defaultPrompts, options = {}) {
301
427
  const endId = targets[targets.length - 1]?.blockId ?? "b5";
302
428
  const voice = isEmergency ? "emergency" : "gentle";
303
429
  const triggerLine = isEmergency ? `[EMERGENCY \u2014 TIER ${decision.tier} ${isT2 ? "DISTILLATION" : "CONDENSATION"}] Context limit reached \u2014 distill NOW into a denser summary to reclaim tokens.` : `[TIER ${decision.tier} ${isT2 ? "DISTILLATION" : "CONDENSATION"} TRIGGER]`;
304
- const parts2 = [
305
- efficiencyNote(prompts, includeGuidance),
430
+ return {
431
+ voice,
432
+ text: [
433
+ efficiencyNote(prompts),
434
+ "",
435
+ breakdownStr,
436
+ "",
437
+ triggerLine,
438
+ isT2 ? `Your tier-1 compression summaries have accumulated. Distill them into a single denser tier-2 summary. Use block IDs as boundaries (startId and endId as bN). Any raw (uncompressed) messages sitting between the boundary blocks are absorbed into the tier-2 block as well \u2014 apply HOW TO COMPRESS to those raw messages and the TIER 2 distillation rules to the existing summaries, so the whole span is covered and nothing is lost.` : `Your tier-2 compression summaries have accumulated. Condense them further into a tier-3 ultra-condensed summary. Use block IDs as boundaries (startId and endId as bN). Any raw (uncompressed) messages sitting between the boundary blocks are absorbed into the tier-3 block as well \u2014 apply HOW TO COMPRESS to those raw messages and the TIER 3 condensation rules to the existing summaries, so the whole span is covered and nothing is lost.`,
439
+ blockList,
440
+ ...ledgerStr ? [ledgerStr] : [],
441
+ `Example: compress({ content: [{ startId: "${startId}", endId: "${endId}", summary: "..." }] })`,
442
+ "",
443
+ prompts.howToCompressRules,
444
+ "",
445
+ isT2 ? prompts.tier2DistillRules : prompts.tier3CondenseRules
446
+ ].join("\n")
447
+ };
448
+ }
449
+ if (isEmergency) {
450
+ return {
451
+ voice: "emergency",
452
+ text: [
453
+ emergencyHeader(prompts),
454
+ "",
455
+ breakdownStr,
456
+ "",
457
+ prompts.howToCompressRules,
458
+ "",
459
+ `{ "topic": "...", "content": [{ "startId": "<ID>", "endId": "<ID>", "summary": "..." }] }`,
460
+ "Only use IDs from visible messages above. Compress older work first.",
461
+ "",
462
+ rangesStr,
463
+ ...ledgerStr ? [ledgerStr] : []
464
+ ].join("\n")
465
+ };
466
+ }
467
+ return {
468
+ voice: "gentle",
469
+ text: [
470
+ efficiencyNote(prompts),
306
471
  "",
307
472
  breakdownStr,
308
473
  "",
309
- triggerLine,
310
- isT2 ? `Your tier-1 compression summaries have accumulated. Distill them into a single denser tier-2 summary. Use block IDs as boundaries (startId and endId as bN). Any raw (uncompressed) messages sitting between the boundary blocks are absorbed into the tier-2 block as well \u2014 apply HOW TO COMPRESS to those raw messages and the TIER 2 distillation rules to the existing summaries, so the whole span is covered and nothing is lost.` : `Your tier-2 compression summaries have accumulated. Condense them further into a tier-3 ultra-condensed summary. Use block IDs as boundaries (startId and endId as bN). Any raw (uncompressed) messages sitting between the boundary blocks are absorbed into the tier-3 block as well \u2014 apply HOW TO COMPRESS to those raw messages and the TIER 3 condensation rules to the existing summaries, so the whole span is covered and nothing is lost.`,
311
- blockList,
312
- `Example: compress({ content: [{ startId: "${startId}", endId: "${endId}", summary: "..." }] })`
313
- ];
314
- if (includeGuidance) {
315
- parts2.push("", prompts.howToCompressRules, "", isT2 ? prompts.tier2DistillRules : prompts.tier3CondenseRules);
316
- }
317
- return { voice, text: parts2.join("\n") };
318
- }
319
- if (isEmergency) {
320
- const parts2 = [emergencyHeader(prompts, includeGuidance), "", breakdownStr];
321
- if (includeGuidance) parts2.push("", prompts.howToCompressRules);
322
- parts2.push(
474
+ prompts.howToCompressRules,
323
475
  "",
324
- `{ "topic": "...", "content": [{ "startId": "<ID>", "endId": "<ID>", "summary": "..." }] }`,
325
- "Only use IDs from visible messages above. Compress older work first.",
476
+ rangesStr,
477
+ ...ledgerStr ? [ledgerStr] : [],
326
478
  "",
327
- rangesStr
328
- );
329
- return { voice: "emergency", text: parts2.join("\n") };
330
- }
331
- const parts = [efficiencyNote(prompts, includeGuidance), "", breakdownStr];
332
- if (includeGuidance) parts.push("", prompts.howToCompressRules);
333
- parts.push("", rangesStr, "", `\u{1F4A1} Compress all ranges in one call (pass multiple content entries: \`content: [{...}, {...}]\`).`);
334
- return { voice: "gentle", text: parts.join("\n") };
479
+ `\u{1F4A1} Compress all ranges in one call (pass multiple content entries: \`content: [{...}, {...}]\`).`
480
+ ].join("\n")
481
+ };
335
482
  }
336
483
 
337
484
  // src/viable.ts
@@ -341,6 +488,14 @@ function viableRanges(ranges) {
341
488
  }
342
489
 
343
490
  export {
491
+ BLOCKED_REF,
492
+ emptyRefMap,
493
+ indexToRef,
494
+ refToIndex,
495
+ refForRaw,
496
+ rawForRef,
497
+ assignRefs,
498
+ highestUsedIndex,
344
499
  defaultCountTokens,
345
500
  thinkingTokenValue,
346
501
  countMessageTokens,
@@ -357,4 +512,4 @@ export {
357
512
  VIABLE_RANGE_MIN_TOKENS,
358
513
  viableRanges
359
514
  };
360
- //# sourceMappingURL=chunk-T6YQEHNL.js.map
515
+ //# sourceMappingURL=chunk-PYVC2AWM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/refs.ts","../src/tokenize.ts","../src/compression-rules.ts","../src/prompts.ts","../src/nudge-text.ts","../src/viable.ts"],"sourcesContent":["import type { CoreMessage, MessageRefMap } from \"./types.js\";\n\nconst REF_WIDTH = 5;\nconst MIN_INDEX = 1;\nconst MAX_INDEX = 99999;\nconst REF_PATTERN = /^m0*(\\d{1,5})$/;\n\nexport const BLOCKED_REF = \"BLOCKED\";\n\nexport function emptyRefMap(): MessageRefMap {\n return { byRaw: {}, byRef: {} };\n}\n\nexport function indexToRef(index: number): string {\n if (!Number.isInteger(index) || index < MIN_INDEX || index > MAX_INDEX) {\n throw new RangeError(\n `ref index out of bounds: ${index} (allowed ${MIN_INDEX}-${MAX_INDEX})`,\n );\n }\n return `m${String(index).padStart(REF_WIDTH, \"0\")}`;\n}\n\nexport function refToIndex(ref: string): number | null {\n const match = REF_PATTERN.exec(ref.trim().toLowerCase());\n if (!match) return null;\n const index = Number(match[1]);\n if (index < MIN_INDEX || index > MAX_INDEX) return null;\n return index;\n}\n\nexport function refForRaw(map: MessageRefMap, rawId: string): string | null {\n return map.byRaw[rawId] ?? null;\n}\n\nexport function rawForRef(map: MessageRefMap, ref: string): string | null {\n return map.byRef[ref] ?? null;\n}\n\nexport interface AssignRefsResult {\n map: MessageRefMap;\n nextIndex: number;\n newlyAssigned: number;\n}\n\nexport interface AssignRefsOptions {\n existing: MessageRefMap;\n nextIndex: number;\n isProtected?: (message: CoreMessage) => boolean;\n shouldSkip?: (message: CoreMessage) => boolean;\n}\n\nexport function assignRefs(\n messages: CoreMessage[],\n options: AssignRefsOptions,\n): AssignRefsResult {\n const map: MessageRefMap = {\n byRaw: { ...options.existing.byRaw },\n byRef: { ...options.existing.byRef },\n };\n let cursor =\n Number.isInteger(options.nextIndex) && options.nextIndex >= MIN_INDEX\n ? options.nextIndex\n : MIN_INDEX;\n let newlyAssigned = 0;\n\n for (const message of messages) {\n if (!message.id || options.shouldSkip?.(message)) continue;\n\n if (map.byRaw[message.id]) continue;\n\n if (options.isProtected?.(message)) {\n map.byRaw[message.id] = BLOCKED_REF;\n continue;\n }\n\n const ref = allocateFreeRef(map, cursor);\n cursor = ref.index + 1;\n map.byRaw[message.id] = ref.text;\n map.byRef[ref.text] = message.id;\n newlyAssigned++;\n }\n\n return { map, nextIndex: cursor, newlyAssigned };\n}\n\nfunction allocateFreeRef(\n map: MessageRefMap,\n start: number,\n): { text: string; index: number } {\n let candidate = Math.max(start, MIN_INDEX);\n while (candidate <= MAX_INDEX) {\n const text = indexToRef(candidate);\n if (!map.byRef[text]) {\n return { text, index: candidate };\n }\n candidate++;\n }\n throw new Error(\n `ref capacity exhausted: cannot allocate beyond ${indexToRef(MAX_INDEX)}`,\n );\n}\n\nexport function rebuildRefIndex(map: MessageRefMap): MessageRefMap {\n const byRef: Record<string, string> = {};\n for (const [rawId, ref] of Object.entries(map.byRaw)) {\n if (ref !== BLOCKED_REF) byRef[ref] = rawId;\n }\n return { byRaw: { ...map.byRaw }, byRef };\n}\n\nexport function highestUsedIndex(map: MessageRefMap): number {\n let highest = 0;\n for (const ref of Object.values(map.byRaw)) {\n const index = ref === BLOCKED_REF ? null : refToIndex(ref);\n if (index !== null && index > highest) highest = index;\n }\n return highest;\n}\n","import { createRequire } from \"node:module\";\n\nconst require = createRequire(import.meta.url);\n\nexport function defaultCountTokens(text: string): number {\n if (!text) return 0;\n // CJK chars tokenize ~1:1 (chars/4 badly underestimates them). Count them\n // directly, then estimate the non-CJK remainder with chars/4 so digits,\n // punctuation, and symbols in code/JSON are not dropped to zero.\n const cjk = text.match(/[\\u4e00-\\u9fff\\u3040-\\u30ff\\uac00-\\ud7af]/g);\n const cjkCount = cjk?.length ?? 0;\n return cjkCount + Math.ceil((text.length - cjkCount) / 4);\n}\n\nexport function estimateMessageTokens(text: string | undefined): number {\n return defaultCountTokens(text ?? \"\");\n}\n\n/** Guarded contribution of a host-projected thinking payload to the metered\n * message size. Non-finite or non-positive values are treated as absent (0),\n * so a bad host value can never poison the accounting. */\nexport function thinkingTokenValue(thinking: number | undefined): number {\n return typeof thinking === \"number\" &&\n Number.isFinite(thinking) &&\n thinking > 0\n ? thinking\n : 0;\n}\n\n/** Total metered size of a core message: visible text plus any host-projected\n * thinking payload (CoreMessage.thinkingTokens). Every per-message counting\n * site (range recommendations, block compressedTokens, status reports, context\n * breakdown) goes through this so all surfaces share one caliber. */\nexport function countMessageTokens(\n message: { text?: string; thinkingTokens?: number },\n countTokens: TokenCountFn = defaultCountTokens,\n): number {\n return (\n countTokens(message.text ?? \"\") + thinkingTokenValue(message.thinkingTokens)\n );\n}\n\nexport function estimateTokensFast(text: string): number {\n if (!text) return 0;\n return Math.ceil(text.length / 4);\n}\n\nexport type TokenCountFn = (text: string) => number;\n\nconst BPE_SIZE_GUARD = 100_000;\n\nexport function createBpeTokenizer(): TokenCountFn {\n try {\n const mod = require(\"@anthropic-ai/tokenizer\");\n const bpeCount = mod.countTokens ?? mod.default?.countTokens;\n if (typeof bpeCount !== \"function\") return defaultCountTokens;\n return (text: string) => {\n if (text.length > BPE_SIZE_GUARD) return defaultCountTokens(text);\n try {\n return bpeCount(text);\n } catch {\n return defaultCountTokens(text);\n }\n };\n } catch {\n return defaultCountTokens;\n }\n}\n","/**\n * Compression rule texts — VERBATIM copy from context-compress-algorithms (MIT, ours).\n * These were tuned over months of production use.\n *\n * 2026-09-06 amendment (owner-approved; billion-context-pi#309 incident): write-side\n * quote-fidelity rules merged INTO the tuned text. Verbatim user quotes now require\n * a message ref; recorded task state is labeled as history; unicode written directly.\n * Motivation: session 01a071dc blocks b60/b61 stored a fabricated\n * `user verbatim '合并了 下一个'` as a live \"CURRENT TASK\", causing loop relapses.\n */\n\nexport const COMPRESS_PHILOSOPHY = `Compression Philosophy:\n- All compression serves the primary task, but be frugal.\n- Context capacity is precious. Save context by compressing consumed outputs, not by avoiding tools.\n- Compress by need, not by percentage.\n- Work from summaries, not raw tool outputs. All listed ranges (user prompts, tool outputs, code, logs, exploration, intermediate steps) should be compressed to summary format — the ONLY exceptions are protected content, content the current step is actively using, or critical content you cannot reconstruct.`;\n\nexport const HOW_TO_COMPRESS_RULES = `HOW TO COMPRESS\n\nWhen you call \\`compress\\`, the summary you write becomes the only record of the replaced conversation. Make it self-contained and complete: every user request, experiment purpose, and work task in the range must be accurately captured. A later reader (or you, after decompressing) should be able to continue the task WITHOUT needing the original. The summary records the PAST as of this block's creation: label recorded task state as history (\"TASK AS OF THIS BLOCK: ...\") — never as a live instruction, so a later reader treats it as settled context, not something to re-execute. Write plain text with real unicode characters; never copy \\\\uXXXX escape sequences or JSON-escaped fragments out of tool output.\n\nKEEP VERBATIM — never paraphrase or abbreviate these:\n- Full file paths with line numbers, directory prefix on every mention (\\`lib/hooks.ts:347\\`, \\`src/index.ts:12-18\\`, \\`gatenet_v3/model.py:45\\`). Never abbreviate to a bare filename (\\`hooks.ts\\`, \\`model.py\\`) — they are ambiguous and cannot be grepped or decompressed-to later.\n- Function, class, and type signatures (exact names, params, return types) AND critical code lines that encode logic — the line that IS the finding, not just the function name (e.g. \\`kv_keys += define_gate * a_key[i](emb)\\` is more useful than \"see model_kvnet.py\").\n- Error messages and stack traces (exact text — you need the literal string to grep for it later).\n- Key details from reports and analyses — not just the conclusion. Keep the comparison numbers and the mechanism, not \"X is worse\" alone (write \"1.76× PPL gap because KV store is static\", not \"KVNet underperforms\").\n- Decisions and their rationale (\"chose X over Y because Z\" — the \"because\" is load-bearing; without it the decision looks arbitrary).\n- Constraints discovered (\"must support Node 22\", \"no new dependencies\", \"AGENTS.md forbids \\`as any\\`\").\n- Exact values: versions, config keys, thresholds, magic numbers.\n- User intent — quote short user messages verbatim ONLY WITH their message ref, e.g. \\`User said (m00132): \"ship it tonight\"\\`. Without a verifiable ref, paraphrase (\\`user previously asked (paraphrased): ...\\`) — this is the one exception to the verbatim rule above; never present a reconstructed or half-remembered phrase as a verbatim quote. When the message is too long to quote, preserve intent with extra care: do not change scope, constraints, priorities, acceptance criteria, or requested outcomes. Quotes are historical records, never current directives. Losing these changes the task itself.\n- The user's overall goal and any changes to it — the big-picture objective plus how it evolved during the compressed range. Each summary must reflect the goal as it stood at the end of the range, including pivots (e.g., \"initially: fix bug X → pivoted to: refactor module Y after discovering root cause\"). Losing the goal or its evolution makes all subsequent work appear unmotivated.\n- Purpose behind each significant action — preserve not just what was done but why: the hypothesis behind each experiment, the question behind each exploration, the task goal behind each work action. Without purpose, the summary reads as disconnected technical steps with no through-line.\n- Open questions and unresolved TODOs — losing these changes what work appears to remain.\n- Message refs of key anchors (\\`m00420\\`, \\`m00510–m00520\\`) — they let you or a later reader jump back via decompress to the exact original.\n\nDROP — extract the signal, discard the vessel:\n- Verbose logs (build/test/\\`npm\\` output) once you have captured the error line or the result.\n- Duplicate file reads once the needed content is recorded.\n- Consumed exploration — search hits, agent return values, successful tool outputs — once you have extracted the facts you need (same rule as dead-ends, but nothing went wrong; the content is simply spent).\n- Dead-end exploration — but PRESERVE the lesson in one line: \"tried X, failed because Y\".\n- Back-and-forth discussion and self-corrections once the final position is captured (keep the outcome, drop the journey to it).\n- Repeated status checks (\\`git status\\`, \\`ls\\`) once state is known.\n\nFor each significant item you DROP (scripts, reports, large analyses, long tool outputs), add a one-line CONTENT description of what it covers — not where it lives. Bad: \"probe script at /path/probe_kvnet.py\". Good: \"probe_kvnet.py: tests n-gram baseline, generation quality, long-range dependency, position sensitivity, op pipeline, QUERY attention.\" This lets a later decompress target the right block by relevance, not by guessing locations.\n\nPRIORITY — when the summary must be compact, preserve in this order:\n1. User's overall goal, goal evolution, intent, and hard constraints (losing these changes the task).\n2. Decisions and rationale.\n3. Exact technical artifacts: paths, signatures, errors, values.\n4. Conclusions and key findings.\n5. Lessons learned: what failed and why.\n\nWrite dense, scannable bullets — not narrative prose. If the range spans distinct concerns (request → findings → decision), group bullets under short thematic headers so a reader can scan to the part they need. Every line must earn its place. Do not mimic the style of existing summaries in context; follow these rules.`;\n\nexport const TIER2_DISTILL_RULES = `TIER 2 COMPRESSION — DISTILLATION\n\nYou are compressing historical summaries (not raw conversation). These summaries have already captured the details. Your job is to DISTILL them: extract only what matters for future work, discard the process.\n\nKEEP — these are the only things that survive distillation:\n- Decisions and their rationale (\"chose X over Y because Z\" — the \"because\" is load-bearing).\n- Final outcomes: version numbers shipped, PR numbers merged/closed, bugs fixed or deferred.\n- Key lessons: what failed and why (\"tried X, failed because Y\"). These prevent repeating mistakes.\n- Critical constraints discovered (\"must support Node 22\", \"AGENTS.md forbids as any\").\n- Design decisions with architectural impact (\"chose compress-as-anchor over synthetic messages because prefix cache\").\n- User quotes and task state only as attributed history: keep the source ref with any user quote; never carry a tier-1 \"CURRENT TASK\" claim forward as a live directive — relabel it \"TASK AS OF THIS BLOCK\".\n- Whether content is OBSOLETE or SUPERSEDED — mark with one line: \"[SUPERSEDED by PR #NNN]\" or \"[OBSOLETE: deleted in vX.Y.Z]\". Do NOT keep the obsolete content's details — just the marker and reason.\n- Function/class/type names and module paths that are the SUBJECT of the work — e.g., \"fixed filterCompressedRanges in prune.ts\", \"added SessionStateRegistry in state.ts\". Not exact line numbers or full signatures — just enough to LOCATE the code without searching.\n- Exploration findings: if a block was exploratory with no decision, keep the CONCLUSION in one line (\"explored X, not viable because Y\"). Do not keep the exploration process.\n\nDROP — these were useful during the work but are no longer needed:\n- Exact line numbers, diffs, verbose function signatures, full code listings.\n- Build/deploy process details, test execution steps.\n- Review process details (who reviewed, what rounds, test counts).\n- Verbose logs, command output, intermediate debugging steps.\n\nFORMAT:\n- Start each distilled block with a source header line:\n \\`Source: bN+bM+... (XK→YK tok, Zx). [original topic]\\`\n Example: \\`Source: b5+b7 (56K+44K→268 tok, 375x). [Tool-result recap + publish]\\`\n- 3-5 bullet points per source block, each a self-contained fact.\n- Dense, scannable — no narrative prose.\n- Start with the outcome, not the process: \"v1.13.0 shipped (7 PRs bundled)\" not \"implemented 7 PRs then reviewed then merged\".\n- Cross-block synthesis: if multiple source blocks cover the same topic (same PR, same feature, same bug), MERGE them into a single group of bullets. Do not repeat the same fact from different blocks — keep it once under the most relevant source header.\n\nSIZE TARGET: 50-150 tokens per source block (excluding the header). If you can't fit it in 150 tokens, you're keeping too much process. If a block has nothing worth keeping (pure noise), output just the header followed by \"[no actionable content].\"`;\n\nexport const TIER3_CONDENSE_RULES = `TIER 3 COMPRESSION — ULTRA-CONDENSATION\n\nYou are compressing distilled summaries (Tier 2) into ultra-condensed facts (Tier 3). The distilled summaries already contain only decisions and outcomes. Your job is to reduce them to bare factual references.\n\nPRIORITY — when a source block has more facts than the size target allows, keep in this order:\n1. Shipped outcomes (versions released, PRs merged) — these are permanent record.\n2. Open work (PRs/issues still pending) — these may need follow-up.\n3. Key decisions with architectural impact (\"chose X over Y because Z\").\n4. Critical constraints (\"must support Node 22\").\nDrop everything else. Tier 3 is a lookup index, not a knowledge base.\n\nFORMAT:\n- Start with a source header line:\n \\`Source: bN+bM+... (XK→YK tok, Zx). [original topic]\\`\n- Output 1-3 facts per source block. Each fact is a single line: subject + outcome.\n- No explanations, no rationale, no process — just the fact.\n- Format: \"[PR/Issue/Version] — [outcome in ≤8 words]\"\n- Merge related facts from different source blocks if they concern the same topic.\n\nEXAMPLES:\n- \"v1.13.0 shipped — quality gate + GC fix (7 PRs)\"\n- \"PR #196 merged — preserve-first-user (supersedes #169)\"\n- \"Bug 1214 fixed — compress consumed all user messages\"\n- \"Chose compress-as-anchor — prefix cache benefit over synthetic injection\"\n- \"Constraint: AGENTS.md forbids as any — never suppress types\"\n\nDROP:\n- Multi-sentence context. If a fact needs >1 sentence, it's too detailed for Tier 3.\n- Lessons learned (\"tried X, failed because Y\") — drop UNLESS the failure is likely to recur and the block is <30 days old.\n- Design rationale details — keep the decision, drop the \"because\" unless it's a critical constraint.\n- Anything marked [OBSOLETE] or [SUPERSEDED] — drop entirely, note \"[N blocks obsolete]\" in the summary.\n\nSIZE TARGET: 30-60 tokens per source block (including header). For a batch of N source blocks, total output ≈ N × 40 tokens. If a source block has only one trivial fact, output just the header + one line.`;\n","import {\n COMPRESS_PHILOSOPHY,\n HOW_TO_COMPRESS_RULES,\n TIER2_DISTILL_RULES,\n TIER3_CONDENSE_RULES,\n} from \"./compression-rules.js\";\n\n/**\n * Overridable prompt text consumed by the kernel's nudge renderer and, via the\n * adapter, the system prompt. Every field here is LOAD-BEARING: these rules\n * were tuned over months of production use and are quality-critical. Overriding\n * them can degrade summary quality (loss of paths / signatures / decisions →\n * broken retrieval), so {@link resolvePrompts} requires `{ acknowledgeRisk: true }`.\n *\n * Surface-level text (summary section headers, status-report chrome, tool\n * descriptions) is intentionally NOT part of this interface — it is owned by\n * the adapter or a later \"prompt-set format\" layer and is safe to customize\n * freely. See DESIGN.md for the load-bearing vs surface classification.\n */\nexport interface Prompts {\n /** Core compression philosophy. Embedded in the system prompt + every nudge. */\n compressPhilosophy: string;\n /** Rules the model follows when writing a tier-1 summary. */\n howToCompressRules: string;\n /** Rules for tier-2 distillation of existing summaries. */\n tier2DistillRules: string;\n /** Rules for tier-3 ultra-condensation of distilled summaries. */\n tier3CondenseRules: string;\n}\n\n/**\n * The kernel's canonical prompt values (verbatim from compression-rules.ts).\n * Frozen so a buggy caller cannot mutate the shared singleton and corrupt\n * every other consumer of {@link defaultPrompts}.\n */\nexport const defaultPrompts: Prompts = Object.freeze({\n compressPhilosophy: COMPRESS_PHILOSOPHY,\n howToCompressRules: HOW_TO_COMPRESS_RULES,\n tier2DistillRules: TIER2_DISTILL_RULES,\n tier3CondenseRules: TIER3_CONDENSE_RULES,\n}) as Prompts;\n\nexport interface ResolvePromptsOptions {\n /**\n * Must be `true` to override any prompt field. Every {@link Prompts} field is\n * load-bearing; overriding without acknowledging the quality risk is a\n * programming error and throws.\n */\n acknowledgeRisk?: boolean;\n}\n\n/**\n * Merge prompt overrides onto the kernel defaults. All fields are load-bearing,\n * so ANY override requires `{ acknowledgeRisk: true }`.\n *\n * Only `string`-valued overrides take effect: an explicit `undefined`/`null` or\n * a wrong type is silently dropped (never clobbers a good default), so a\n * malformed partial never degrades the canonical rules. Resolve once at host\n * startup, then pass the resulting {@link Prompts} to {@link renderNudgeText}\n * and to the adapter's system-prompt composition so both layers stay consistent.\n */\nexport function resolvePrompts(\n overrides?: Partial<Prompts>,\n options: ResolvePromptsOptions = {},\n): Prompts {\n const clean: Partial<Prompts> = {};\n if (overrides) {\n for (const [key, value] of Object.entries(overrides)) {\n if (typeof value === \"string\") {\n (clean as Record<string, unknown>)[key] = value;\n }\n }\n }\n const keys = Object.keys(clean) as (keyof Prompts)[];\n if (keys.length > 0 && !options.acknowledgeRisk) {\n throw new Error(\n `resolvePrompts: overriding compression rules requires { acknowledgeRisk: true }. ` +\n `Overridden keys: ${keys.join(\", \")}. These rules are quality-critical (tuned over months of production use); ` +\n `changing them can degrade summary quality and break retrieval (summaries may lose paths, signatures, decisions).`,\n );\n }\n return { ...defaultPrompts, ...clean };\n}\n","import type { NudgeDecision, CompressibleRange, ProtectedRange, ContextBreakdown, CompressionBlock, MessageRefMap } from \"./types.js\";\nimport { defaultPrompts } from \"./prompts.js\";\nimport type { Prompts } from \"./prompts.js\";\nimport { refToIndex, BLOCKED_REF } from \"./refs.js\";\n\nexport type NudgeVoice = \"gentle\" | \"emergency\";\n\nexport interface RenderedNudge {\n voice: NudgeVoice;\n text: string;\n}\n\nfunction efficiencyNote(prompts: Prompts): string {\n return `This is an efficiency nudge to compress early and keep context lean — not an overflow warning. A separate, stronger alert will appear if the context is actually full.\\n\\n${prompts.compressPhilosophy}`;\n}\n\nfunction emergencyHeader(prompts: Prompts): string {\n return `⚠️ Context limit reached — compress now. Prioritize consumed tool outputs.\\n\\n${prompts.compressPhilosophy}`;\n}\n\nfunction formatK(n: number): string {\n if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;\n return `${n}`;\n}\n\nfunction formatBreakdown(bd?: ContextBreakdown): string {\n if (!bd) return \"\";\n const parts: string[] = [];\n if (bd.system > 0) parts.push(`${formatK(bd.system)} system`);\n if (bd.tool > 0) parts.push(`${formatK(bd.tool)} tool`);\n if (bd.summaries > 0) parts.push(`${formatK(bd.summaries)} summaries`);\n if (bd.code > 0) parts.push(`${formatK(bd.code)} code`);\n if (bd.text > 0) parts.push(`${formatK(bd.text)} text`);\n const growth = bd.growth > 0 ? `\\n+${formatK(bd.growth)} since last nudge` : \"\";\n return `Context breakdown: ${parts.join(\" | \")}${growth}`;\n}\n\n\n\nfunction formatTierTargetBlocks(blocks: CompressionBlock[]): string {\n if (blocks.length === 0) {\n return \"Target blocks: (none — no tier blocks found)\";\n }\n const lines = blocks.map((b) => {\n const summaryTokens = Math.ceil((b.summary ?? \"\").length / 4);\n const topic = b.topic ? ` \"${b.topic}\"` : \"\";\n return ` ${b.blockId} ${b.effectiveMessageIds.length} msgs ${formatK(b.compressedTokens)}→${formatK(summaryTokens)}${topic}`;\n });\n return `Target ${blocks[0]!.tier === 1 ? \"tier-1\" : \"tier-2\"} blocks to distill (${blocks.length}):\\n${lines.join(\"\\n\")}`;\n}\n\nexport function formatRanges(compressible: CompressibleRange[], protectedRanges: ProtectedRange[]): string {\n if (compressible.length === 0 && protectedRanges.length === 0) {\n return \"[No specific ranges detected — compress any consumed content.]\";\n }\n\n // Merge compressible + protected into a single oldest-first list, mirroring\n // opencode-acp's formatCompressibleRanges. Splitting them into two sections\n // lost the time order and hid overlaps; a range can be partly compressible\n // and partly protected, which only the merged view shows correctly.\n interface Merged {\n startRef: string; endRef: string; startNum: number; endNum: number;\n count: number; tokens: number;\n compressibleTokens: number; compressibleCount: number;\n protectedTokens: number; protectedCount: number; protectedTools: string[];\n toolPct: number; textPct: number; dangerous: boolean;\n }\n const refNum = (ref: string): number => {\n const m = ref.match(/\\d+/);\n return m ? parseInt(m[0], 10) : 0;\n };\n const entries: Merged[] = [];\n for (const r of compressible) {\n entries.push({\n startRef: r.startRef, endRef: r.endRef, startNum: refNum(r.startRef), endNum: refNum(r.endRef),\n count: r.count, tokens: r.tokens, toolPct: r.toolPct, textPct: r.textPct,\n compressibleTokens: r.tokens, compressibleCount: r.count,\n protectedTokens: 0, protectedCount: 0, protectedTools: [], dangerous: r.dangerous ?? false,\n });\n }\n for (const r of protectedRanges) {\n entries.push({\n startRef: r.startRef, endRef: r.endRef, startNum: refNum(r.startRef), endNum: refNum(r.endRef),\n count: r.count, tokens: r.tokens, toolPct: 0, textPct: 0,\n compressibleTokens: 0, compressibleCount: 0,\n protectedTokens: r.tokens, protectedCount: r.count, protectedTools: [...r.tools], dangerous: false,\n });\n }\n entries.sort((a, b) => a.startNum - b.startNum);\n // Merge adjacent/overlapping ranges (gap ≤ 1 ref).\n const merged: Merged[] = [];\n for (const e of entries) {\n const last = merged[merged.length - 1];\n if (last && e.startNum <= last.endNum + 1) {\n last.endRef = e.endRef;\n last.endNum = Math.max(last.endNum, e.endNum);\n last.count += e.count;\n last.tokens += e.tokens;\n last.compressibleTokens += e.compressibleTokens;\n last.compressibleCount += e.compressibleCount;\n last.protectedTokens += e.protectedTokens;\n last.protectedCount += e.protectedCount;\n if (e.dangerous) last.dangerous = true;\n for (const t of e.protectedTools) {\n if (!last.protectedTools.includes(t)) last.protectedTools.push(t);\n }\n } else {\n merged.push({ ...e });\n }\n }\n const lines = merged.map((e) => {\n const suffix = e.dangerous && e.compressibleTokens > 0 ? \" ⚠️ NOT recommended unless you are certain.\" : \"\";\n if (e.protectedTokens > 0 && e.compressibleTokens === 0) {\n return ` ${e.startRef}–${e.endRef} ${e.count} msgs ${formatK(e.tokens)} [PROTECTED: ${e.protectedTools.join(\", \")} — not compressible]${suffix}`;\n }\n if (e.protectedTokens > 0 && e.compressibleTokens > 0) {\n return ` ${e.startRef}–${e.endRef} ${e.count} msgs ${formatK(e.tokens)} [${formatK(e.compressibleTokens)} compressible | ${formatK(e.protectedTokens)} protected: ${e.protectedTools.join(\", \")}]${suffix}`;\n }\n return ` ${e.startRef}–${e.endRef} ${e.count} msgs ${formatK(e.tokens)} [tool ${e.toolPct}% | text ${e.textPct}%]${suffix}`;\n });\n return `Compressible ranges (${merged.length}, oldest first):\\n${lines.join(\"\\n\")}`;\n}\n\nexport const MAX_BLOCK_LEDGER_ENTRIES = 8;\n\nfunction blockIndex(id: string): number {\n const n = Number(id.slice(1));\n return Number.isFinite(n) ? n : 0;\n}\n\nfunction blockSpan(\n block: CompressionBlock,\n refs: MessageRefMap | undefined,\n): { start: string; end: string } | null {\n let loIdx: number | null = null;\n let hiIdx: number | null = null;\n let loRef = \"\";\n let hiRef = \"\";\n for (const rawId of block.effectiveMessageIds) {\n const ref = refs?.byRaw[rawId];\n if (!ref || ref === BLOCKED_REF) continue;\n const idx = refToIndex(ref);\n if (idx === null) continue;\n if (loIdx === null || idx < loIdx) {\n loIdx = idx;\n loRef = ref;\n }\n if (hiIdx === null || idx > hiIdx) {\n hiIdx = idx;\n hiRef = ref;\n }\n }\n if (loIdx !== null && hiIdx !== null) return { start: loRef, end: hiRef };\n // effectiveMessageIds may be unresolvable after fork/rebuild remapping.\n // Fall back to the stored spec span only when it parses as m-refs —\n // block-boundary calls store block IDs (\"b1\") there, which would mislead.\n if (block.startRef && block.endRef) {\n const s = refToIndex(block.startRef);\n const e = refToIndex(block.endRef);\n if (s !== null && e !== null) {\n return s <= e\n ? { start: block.startRef, end: block.endRef }\n : { start: block.endRef, end: block.startRef };\n }\n }\n return null;\n}\n\nexport function formatBlockLedger(\n blocks: CompressionBlock[],\n refs?: MessageRefMap,\n maxEntries: number = MAX_BLOCK_LEDGER_ENTRIES,\n): string {\n const entries: string[] = [];\n const sorted = [...blocks].sort((a, b) => blockIndex(a.blockId) - blockIndex(b.blockId));\n for (const block of sorted) {\n const span = blockSpan(block, refs);\n if (!span) continue;\n const range = span.start === span.end ? span.start : `${span.start}–${span.end}`;\n entries.push(\n block.tier >= 2\n ? `${block.blockId}=tier${block.tier}(${range})`\n : `${block.blockId}=${range}`,\n );\n }\n if (entries.length === 0) return \"\";\n let shown = entries;\n let olderNote = \"\";\n if (entries.length > maxEntries) {\n shown = entries.slice(entries.length - maxEntries);\n olderNote = ` (+${entries.length - maxEntries} older)`;\n }\n return `Blocks${olderNote}: ${shown.join(\" · \")}`;\n}\n\nexport function renderNudgeText(decision: NudgeDecision, prompts: Prompts = defaultPrompts): RenderedNudge {\n const breakdownStr = formatBreakdown(decision.contextBreakdown);\n const rangesStr = formatRanges(decision.compressibleRanges, decision.protectedRanges ?? []);\n const ledgerStr = formatBlockLedger(decision.activeBlocks ?? [], decision.messageRefs);\n const isEmergency = !!decision.breakdown?.emergencyOverride || !!decision.breakdown?.overLimit;\n\n if (decision.tier !== null && decision.tier >= 2) {\n const isT2 = decision.tier === 2;\n const targets = decision.tierTargetBlocks ?? [];\n const blockList = formatTierTargetBlocks(targets);\n const startId = targets[0]?.blockId ?? \"b1\";\n const endId = targets[targets.length - 1]?.blockId ?? \"b5\";\n const voice: NudgeVoice = isEmergency ? \"emergency\" : \"gentle\";\n const triggerLine = isEmergency\n ? `[EMERGENCY — TIER ${decision.tier} ${isT2 ? \"DISTILLATION\" : \"CONDENSATION\"}] Context limit reached — distill NOW into a denser summary to reclaim tokens.`\n : `[TIER ${decision.tier} ${isT2 ? \"DISTILLATION\" : \"CONDENSATION\"} TRIGGER]`;\n return {\n voice,\n text: [\n efficiencyNote(prompts),\n \"\",\n breakdownStr,\n \"\",\n triggerLine,\n isT2\n ? `Your tier-1 compression summaries have accumulated. Distill them into a single denser tier-2 summary. Use block IDs as boundaries (startId and endId as bN). Any raw (uncompressed) messages sitting between the boundary blocks are absorbed into the tier-2 block as well — apply HOW TO COMPRESS to those raw messages and the TIER 2 distillation rules to the existing summaries, so the whole span is covered and nothing is lost.`\n : `Your tier-2 compression summaries have accumulated. Condense them further into a tier-3 ultra-condensed summary. Use block IDs as boundaries (startId and endId as bN). Any raw (uncompressed) messages sitting between the boundary blocks are absorbed into the tier-3 block as well — apply HOW TO COMPRESS to those raw messages and the TIER 3 condensation rules to the existing summaries, so the whole span is covered and nothing is lost.`,\n blockList,\n ...(ledgerStr ? [ledgerStr] : []),\n `Example: compress({ content: [{ startId: \"${startId}\", endId: \"${endId}\", summary: \"...\" }] })`,\n \"\",\n prompts.howToCompressRules,\n \"\",\n isT2 ? prompts.tier2DistillRules : prompts.tier3CondenseRules,\n ].join(\"\\n\"),\n };\n }\n\n if (isEmergency) {\n return {\n voice: \"emergency\",\n text: [\n emergencyHeader(prompts),\n \"\",\n breakdownStr,\n \"\",\n prompts.howToCompressRules,\n \"\",\n `{ \"topic\": \"...\", \"content\": [{ \"startId\": \"<ID>\", \"endId\": \"<ID>\", \"summary\": \"...\" }] }`,\n \"Only use IDs from visible messages above. Compress older work first.\",\n \"\",\n rangesStr,\n ...(ledgerStr ? [ledgerStr] : []),\n ].join(\"\\n\"),\n };\n }\n\n return {\n voice: \"gentle\",\n text: [\n efficiencyNote(prompts),\n \"\",\n breakdownStr,\n \"\",\n prompts.howToCompressRules,\n \"\",\n rangesStr,\n ...(ledgerStr ? [ledgerStr] : []),\n \"\",\n `💡 Compress all ranges in one call (pass multiple content entries: \\`content: [{...}, {...}]\\`).`,\n ].join(\"\\n\"),\n };\n}\n","/** Minimum size for a compressible range to be worth recommending. Ranges\n * below this are fragmented leftovers (a 16-token ack, a one-line tool\n * result): the model cannot write a meaningful >=50-char summary for them,\n * and a batched compress call that includes one gets atomically rejected\n * (the kernel validates the whole batch). Observed in the wild: a 14-range\n * recommendation list containing a 16-token range → every batch attempt\n * failed with \"Summary too short\". Apply on every surface that recommends\n * ranges: the injected nudge, acp_status, and the /acp panel. */\nexport const VIABLE_RANGE_MIN_TOKENS = 200;\n\nexport function viableRanges<T extends { tokens: number }>(ranges: T[]): T[] {\n return ranges.filter((r) => r.tokens >= VIABLE_RANGE_MIN_TOKENS);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,QACA,OAAO,QAAQ,oBAAoB,QAAQ;AAAA,MAC7C,EAAE,KAAK,IAAI;AAAA,IACb;AAAA,EACF;AAEA,MAAI,aAAa;AACf,WAAO;AAAA,MACL,OAAO;AAAA,MACP,MAAM;AAAA,QACJ,gBAAgB,OAAO;AAAA,QACvB;AAAA,QACA;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,GAAI,YAAY,CAAC,SAAS,IAAI,CAAC;AAAA,MACjC,EAAE,KAAK,IAAI;AAAA,IACb;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,MACJ,eAAe,OAAO;AAAA,MACtB;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA,GAAI,YAAY,CAAC,SAAS,IAAI,CAAC;AAAA,MAC/B;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAAA,EACb;AACF;;;ACnQO,IAAM,0BAA0B;AAEhC,SAAS,aAA2C,QAAkB;AAC3E,SAAO,OAAO,OAAO,CAAC,MAAM,EAAE,UAAU,uBAAuB;AACjE;","names":["require","require"]}
@@ -1 +1 @@
1
- {"version":3,"file":"compress.d.ts","sourceRoot":"","sources":["../src/compress.ts"],"names":[],"mappings":"AAIA,OAAO,EAAkC,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAehF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAUvD,OAAO,EAGL,KAAK,YAAY,EAElB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EACV,sBAAsB,EACtB,gBAAgB,EAChB,gBAAgB,EAEhB,MAAM,EAEN,WAAW,EAGX,iBAAiB,EAEjB,YAAY,EACb,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,KAAK;IACpB,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAA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CAAC;QACjB,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,EAAE,MAAM,CAAC;QAChB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,eAAe,CAAC,EAAE,MAAM,CAAC;KAC1B,EAAE,CAAC;IACJ,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,KAAK,EAAE,gBAAgB,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,mBAAmB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACnC;AA2DD,wBAAgB,UAAU,CAAC,KAAK,GAAE,KAAU,GAAG,eAAe,CAyU7D;AA0gCD,OAAO,EAAE,kBAAkB,EAAE,CAAC"}
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export { resolveBoundaries, parseBoundary, BoundaryNotFoundError, visibleBlockAn
11
11
  export { defaultCountTokens, estimateTokensFast, createBpeTokenizer, countMessageTokens, } from "./tokenize.js";
12
12
  export type { TokenCountFn } from "./tokenize.js";
13
13
  export { renderNudgeText, formatRanges } from "./nudge-text.js";
14
- export type { NudgeVoice, RenderedNudge, RenderNudgeOptions } from "./nudge-text.js";
14
+ export type { NudgeVoice, RenderedNudge } from "./nudge-text.js";
15
15
  export { COMPRESS_PHILOSOPHY, HOW_TO_COMPRESS_RULES, TIER2_DISTILL_RULES, TIER3_CONDENSE_RULES, } from "./compression-rules.js";
16
16
  export { defaultPrompts, resolvePrompts } from "./prompts.js";
17
17
  export type { Prompts, ResolvePromptsOptions } from "./prompts.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,YAAY,EACV,KAAK,EACL,eAAe,EACf,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,kBAAkB,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,kBAAkB,CAAC;AACvD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,YAAY,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,SAAS,EACT,WAAW,GACZ,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,cAAc,GACf,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,YAAY,EACZ,aAAa,EACb,eAAe,EACf,oBAAoB,EACpB,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,WAAW,EACX,WAAW,EACX,WAAW,EACX,YAAY,GACb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,uBAAuB,EACvB,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,EACL,WAAW,EACX,MAAM,EACN,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,MAAM,EACX,KAAK,WAAW,GACjB,MAAM,eAAe,CAAC;AACvB,cAAc,mBAAmB,CAAC;AAElC,OAAO,EAAE,uBAAuB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,YAAY,EACV,KAAK,EACL,eAAe,EACf,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,SAAS,EACT,YAAY,EACZ,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,aAAa,EA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,iBAAiB,EACjB,SAAS,EACT,WAAW,GACZ,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,cAAc,GACf,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,YAAY,EACZ,aAAa,EACb,eAAe,EACf,oBAAoB,EACpB,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,WAAW,EACX,WAAW,EACX,WAAW,EACX,YAAY,GACb,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,uBAAuB,EACvB,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,EACL,WAAW,EACX,MAAM,EACN,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,MAAM,EACX,KAAK,WAAW,GACjB,MAAM,eAAe,CAAC;AACvB,cAAc,mBAAmB,CAAC;AAElC,OAAO,EAAE,uBAAuB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js CHANGED
@@ -1,20 +1,28 @@
1
1
  import {
2
+ BLOCKED_REF,
2
3
  COMPRESS_PHILOSOPHY,
3
4
  HOW_TO_COMPRESS_RULES,
4
5
  TIER2_DISTILL_RULES,
5
6
  TIER3_CONDENSE_RULES,
6
7
  VIABLE_RANGE_MIN_TOKENS,
8
+ assignRefs,
7
9
  countMessageTokens,
8
10
  createBpeTokenizer,
9
11
  defaultCountTokens,
10
12
  defaultPrompts,
13
+ emptyRefMap,
11
14
  estimateTokensFast,
12
15
  formatRanges,
16
+ highestUsedIndex,
17
+ indexToRef,
18
+ rawForRef,
19
+ refForRaw,
20
+ refToIndex,
13
21
  renderNudgeText,
14
22
  resolvePrompts,
15
23
  thinkingTokenValue,
16
24
  viableRanges
17
- } from "./chunk-T6YQEHNL.js";
25
+ } from "./chunk-PYVC2AWM.js";
18
26
  import {
19
27
  activeBlocks,
20
28
  advanceSurvival,
@@ -26,80 +34,6 @@ import {
26
34
  highestActiveTier
27
35
  } from "./chunk-UX4LINT7.js";
28
36
 
29
- // src/refs.ts
30
- var REF_WIDTH = 5;
31
- var MIN_INDEX = 1;
32
- var MAX_INDEX = 99999;
33
- var REF_PATTERN = /^m0*(\d{1,5})$/;
34
- var BLOCKED_REF = "BLOCKED";
35
- function emptyRefMap() {
36
- return { byRaw: {}, byRef: {} };
37
- }
38
- function indexToRef(index) {
39
- if (!Number.isInteger(index) || index < MIN_INDEX || index > MAX_INDEX) {
40
- throw new RangeError(
41
- `ref index out of bounds: ${index} (allowed ${MIN_INDEX}-${MAX_INDEX})`
42
- );
43
- }
44
- return `m${String(index).padStart(REF_WIDTH, "0")}`;
45
- }
46
- function refToIndex(ref) {
47
- const match = REF_PATTERN.exec(ref.trim().toLowerCase());
48
- if (!match) return null;
49
- const index = Number(match[1]);
50
- if (index < MIN_INDEX || index > MAX_INDEX) return null;
51
- return index;
52
- }
53
- function refForRaw(map, rawId) {
54
- return map.byRaw[rawId] ?? null;
55
- }
56
- function rawForRef(map, ref) {
57
- return map.byRef[ref] ?? null;
58
- }
59
- function assignRefs(messages, options) {
60
- const map = {
61
- byRaw: { ...options.existing.byRaw },
62
- byRef: { ...options.existing.byRef }
63
- };
64
- let cursor = Number.isInteger(options.nextIndex) && options.nextIndex >= MIN_INDEX ? options.nextIndex : MIN_INDEX;
65
- let newlyAssigned = 0;
66
- for (const message of messages) {
67
- if (!message.id || options.shouldSkip?.(message)) continue;
68
- if (map.byRaw[message.id]) continue;
69
- if (options.isProtected?.(message)) {
70
- map.byRaw[message.id] = BLOCKED_REF;
71
- continue;
72
- }
73
- const ref = allocateFreeRef(map, cursor);
74
- cursor = ref.index + 1;
75
- map.byRaw[message.id] = ref.text;
76
- map.byRef[ref.text] = message.id;
77
- newlyAssigned++;
78
- }
79
- return { map, nextIndex: cursor, newlyAssigned };
80
- }
81
- function allocateFreeRef(map, start) {
82
- let candidate = Math.max(start, MIN_INDEX);
83
- while (candidate <= MAX_INDEX) {
84
- const text = indexToRef(candidate);
85
- if (!map.byRef[text]) {
86
- return { text, index: candidate };
87
- }
88
- candidate++;
89
- }
90
- throw new Error(
91
- `ref capacity exhausted: cannot allocate beyond ${indexToRef(MAX_INDEX)}`
92
- );
93
- }
94
- function highestUsedIndex(map) {
95
- let highest = 0;
96
- for (const ref of Object.values(map.byRaw)) {
97
- const index = ref === BLOCKED_REF ? null : refToIndex(ref);
98
- if (index !== null && index > highest) highest = index;
99
- }
100
- return highest;
101
- }
102
-
103
37
  // src/prune.ts
104
38
  var SUMMARY_HEADER = "[Compressed conversation section]";
105
39
  var SUMMARY_ID_PREFIX = "acp_summary_";
@@ -2846,6 +2780,8 @@ function decideNudge(input) {
2846
2780
  compressibleRanges: rec?.recommendedRanges ?? [],
2847
2781
  protectedRanges: rec?.contextRanges.protected ?? [],
2848
2782
  tierTargetBlocks: injectedTier ? tiers[injectedTier].targetBlocks : [],
2783
+ activeBlocks: activeBlocks(state),
2784
+ messageRefs: state.messageRefs,
2849
2785
  contextUsage: usage,
2850
2786
  tier: injectedTier,
2851
2787
  breakdown: {