acp-kernel 0.0.82-pr.250.209 → 0.0.82-pr.255.210
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-L6QNVRC3.js → chunk-VPRKYTHW.js} +59 -71
- package/dist/chunk-VPRKYTHW.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/nudge-text.d.ts +1 -14
- package/dist/nudge-text.d.ts.map +1 -1
- package/dist/panel/index.d.ts +2 -0
- package/dist/panel/index.d.ts.map +1 -1
- package/dist/panel/index.js +106 -23
- package/dist/panel/index.js.map +1 -1
- package/dist/panel/labels.d.ts +68 -0
- package/dist/panel/labels.d.ts.map +1 -0
- package/dist/panel/panel.d.ts +5 -0
- package/dist/panel/panel.d.ts.map +1 -1
- package/dist/prompts.d.ts +0 -5
- package/dist/prompts.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-L6QNVRC3.js.map +0 -1
|
@@ -169,19 +169,17 @@ function resolvePrompts(overrides, options = {}) {
|
|
|
169
169
|
}
|
|
170
170
|
|
|
171
171
|
// src/nudge-text.ts
|
|
172
|
-
function efficiencyNote(prompts, sections
|
|
172
|
+
function efficiencyNote(prompts, sections) {
|
|
173
173
|
if (sections.efficiencyNote !== void 0) return sections.efficiencyNote;
|
|
174
|
-
|
|
175
|
-
return includeGuidance ? `${note}
|
|
174
|
+
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.
|
|
176
175
|
|
|
177
|
-
${prompts.compressPhilosophy}
|
|
176
|
+
${prompts.compressPhilosophy}`;
|
|
178
177
|
}
|
|
179
|
-
function emergencyHeader(prompts, sections
|
|
178
|
+
function emergencyHeader(prompts, sections) {
|
|
180
179
|
if (sections.emergencyHeader !== void 0) return sections.emergencyHeader;
|
|
181
|
-
|
|
182
|
-
return includeGuidance ? `${header}
|
|
180
|
+
return `\u26A0\uFE0F Context limit reached \u2014 compress now. Prioritize consumed tool outputs.
|
|
183
181
|
|
|
184
|
-
${prompts.compressPhilosophy}
|
|
182
|
+
${prompts.compressPhilosophy}`;
|
|
185
183
|
}
|
|
186
184
|
function formatK(n) {
|
|
187
185
|
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}K`;
|
|
@@ -318,21 +316,10 @@ function tierGuidance(tier, sections) {
|
|
|
318
316
|
return tier === 2 ? DEFAULT_T2_GUIDANCE : DEFAULT_T3_GUIDANCE;
|
|
319
317
|
}
|
|
320
318
|
function compact(parts) {
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
for (const p of parts) {
|
|
324
|
-
if (p === "") {
|
|
325
|
-
pendingBlank = true;
|
|
326
|
-
continue;
|
|
327
|
-
}
|
|
328
|
-
if (pendingBlank && out.length > 0) out.push("");
|
|
329
|
-
pendingBlank = false;
|
|
330
|
-
out.push(p);
|
|
331
|
-
}
|
|
332
|
-
return out;
|
|
319
|
+
while (parts.length > 0 && parts[0] === "") parts.shift();
|
|
320
|
+
return parts;
|
|
333
321
|
}
|
|
334
|
-
function renderNudgeText(decision, prompts = defaultPrompts,
|
|
335
|
-
const includeGuidance = options.includeGuidance ?? true;
|
|
322
|
+
function renderNudgeText(decision, prompts = defaultPrompts, sections = {}) {
|
|
336
323
|
const breakdownStr = formatBreakdown(decision.contextBreakdown);
|
|
337
324
|
const rangesStr = formatRanges(decision.compressibleRanges, decision.protectedRanges ?? []);
|
|
338
325
|
const blockMapStr = formatBlockMap(decision.activeBlockSpans ?? []);
|
|
@@ -345,60 +332,61 @@ function renderNudgeText(decision, prompts = defaultPrompts, options = {}) {
|
|
|
345
332
|
const endId = targets[targets.length - 1]?.blockId ?? "b5";
|
|
346
333
|
const voice = isEmergency ? "emergency" : "gentle";
|
|
347
334
|
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]`;
|
|
348
|
-
const guidance = tierGuidance(isT2 ? 2 : 3,
|
|
349
|
-
const head = efficiencyNote(prompts,
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
335
|
+
const guidance = tierGuidance(isT2 ? 2 : 3, sections);
|
|
336
|
+
const head = efficiencyNote(prompts, sections);
|
|
337
|
+
return {
|
|
338
|
+
voice,
|
|
339
|
+
text: compact([
|
|
340
|
+
...head === null ? [] : [head],
|
|
341
|
+
"",
|
|
342
|
+
breakdownStr,
|
|
343
|
+
"",
|
|
344
|
+
triggerLine,
|
|
345
|
+
...guidance === null ? [] : [guidance],
|
|
346
|
+
blockList,
|
|
347
|
+
`Example: compress({ content: [{ startId: "${startId}", endId: "${endId}", summary: "..." }] })`,
|
|
348
|
+
"",
|
|
349
|
+
prompts.howToCompressRules,
|
|
350
|
+
"",
|
|
351
|
+
isT2 ? prompts.tier2DistillRules : prompts.tier3CondenseRules
|
|
352
|
+
]).join("\n")
|
|
353
|
+
};
|
|
364
354
|
}
|
|
365
355
|
if (isEmergency) {
|
|
366
|
-
const head = emergencyHeader(prompts,
|
|
367
|
-
|
|
368
|
-
|
|
356
|
+
const head = emergencyHeader(prompts, sections);
|
|
357
|
+
return {
|
|
358
|
+
voice: "emergency",
|
|
359
|
+
text: compact([
|
|
360
|
+
...head === null ? [] : [head],
|
|
361
|
+
"",
|
|
362
|
+
breakdownStr,
|
|
363
|
+
"",
|
|
364
|
+
prompts.howToCompressRules,
|
|
365
|
+
"",
|
|
366
|
+
`{ "topic": "...", "content": [{ "startId": "<ID>", "endId": "<ID>", "summary": "..." }] }`,
|
|
367
|
+
"Only use IDs from visible messages above. Compress older work first.",
|
|
368
|
+
"",
|
|
369
|
+
rangesStr,
|
|
370
|
+
...blockMapStr ? ["", blockMapStr] : []
|
|
371
|
+
]).join("\n")
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
const gentleHead = efficiencyNote(prompts, sections);
|
|
375
|
+
return {
|
|
376
|
+
voice: "gentle",
|
|
377
|
+
text: compact([
|
|
378
|
+
...gentleHead === null ? [] : [gentleHead],
|
|
369
379
|
"",
|
|
370
|
-
breakdownStr
|
|
371
|
-
];
|
|
372
|
-
if (includeGuidance) {
|
|
373
|
-
parts2.push("", prompts.howToCompressRules);
|
|
374
|
-
}
|
|
375
|
-
parts2.push(
|
|
380
|
+
breakdownStr,
|
|
376
381
|
"",
|
|
377
|
-
|
|
378
|
-
"Only use IDs from visible messages above. Compress older work first.",
|
|
382
|
+
prompts.howToCompressRules,
|
|
379
383
|
"",
|
|
380
384
|
rangesStr,
|
|
381
|
-
...blockMapStr ? ["", blockMapStr] : []
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
const parts = [
|
|
387
|
-
...gentleHead === null ? [] : [gentleHead],
|
|
388
|
-
"",
|
|
389
|
-
breakdownStr
|
|
390
|
-
];
|
|
391
|
-
if (includeGuidance) {
|
|
392
|
-
parts.push("", prompts.howToCompressRules);
|
|
393
|
-
}
|
|
394
|
-
parts.push(
|
|
395
|
-
"",
|
|
396
|
-
rangesStr,
|
|
397
|
-
...blockMapStr ? ["", blockMapStr] : [],
|
|
398
|
-
"",
|
|
399
|
-
`\u{1F4A1} Compress all ranges in one call (pass multiple content entries: \`content: [{...}, {...}]\`).`
|
|
400
|
-
);
|
|
401
|
-
return { voice: "gentle", text: compact(parts).join("\n") };
|
|
385
|
+
...blockMapStr ? ["", blockMapStr] : [],
|
|
386
|
+
"",
|
|
387
|
+
`\u{1F4A1} Compress all ranges in one call (pass multiple content entries: \`content: [{...}, {...}]\`).`
|
|
388
|
+
]).join("\n")
|
|
389
|
+
};
|
|
402
390
|
}
|
|
403
391
|
|
|
404
392
|
// src/viable.ts
|
|
@@ -446,4 +434,4 @@ export {
|
|
|
446
434
|
VIABLE_RANGE_MIN_TOKENS,
|
|
447
435
|
viableRanges
|
|
448
436
|
};
|
|
449
|
-
//# sourceMappingURL=chunk-
|
|
437
|
+
//# sourceMappingURL=chunk-VPRKYTHW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tokenize.ts","../src/compression-rules.ts","../src/prompts.ts","../src/nudge-text.ts","../src/viable.ts","../src/truncate.ts"],"sourcesContent":["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, BlockSpan } from \"./types.js\";\nimport { defaultPrompts } from \"./prompts.js\";\nimport type { Prompts } from \"./prompts.js\";\n\nexport type NudgeVoice = \"gentle\" | \"emergency\";\n\nexport interface NudgePromptSections {\n efficiencyNote?: string | null;\n emergencyHeader?: string | null;\n t2Guidance?: string | null;\n t3Guidance?: string | null;\n}\n\nexport interface RenderedNudge {\n voice: NudgeVoice;\n text: string;\n}\n\nfunction efficiencyNote(prompts: Prompts, sections: NudgePromptSections): string | null {\n if (sections.efficiencyNote !== undefined) return sections.efficiencyNote;\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, sections: NudgePromptSections): string | null {\n if (sections.emergencyHeader !== undefined) return sections.emergencyHeader;\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\nconst BLOCK_MAP_MAX_SHOWN = 8;\n\nfunction formatBlockMap(spans: BlockSpan[]): string {\n if (spans.length === 0) return \"\";\n const hidden = Math.max(0, spans.length - BLOCK_MAP_MAX_SHOWN);\n const shown = hidden > 0 ? spans.slice(-BLOCK_MAP_MAX_SHOWN) : spans;\n const items = shown.map(\n (s) => `${s.blockId}=${s.startRef}–${s.endRef}${s.tier > 1 ? ` t${s.tier}` : \"\"}`,\n );\n const prefix = hidden > 0 ? `…+${hidden} older · ` : \"\";\n return `Active blocks (${spans.length}): ${prefix}${items.join(\" · \")}`;\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 startPos: number; endPos: number;\n count: number; tokens: number; userMsgs: 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 startPos: r.startIndex ?? refNum(r.startRef), endPos: r.endIndex ?? refNum(r.endRef),\n count: r.count, tokens: r.tokens, userMsgs: r.userMsgs ?? 0, 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 startPos: r.startIndex ?? refNum(r.startRef), endPos: r.endIndex ?? refNum(r.endRef),\n count: r.count, tokens: r.tokens, userMsgs: 0, toolPct: 0, textPct: 0,\n compressibleTokens: 0, compressibleCount: 0,\n protectedTokens: r.tokens, protectedCount: r.count, protectedTools: [...r.tools], dangerous: false,\n });\n }\n // Order/merge by POSITION, never ref number: refs can be non-monotonic vs array\n // order (subagent interleaving / mid-array summary nodes), and ref-number merging\n // then yields endpoints resolveBoundaries collapses to a tiny slice (#887).\n entries.sort((a, b) => a.startPos - b.startPos || a.startNum - b.startNum);\n // Merge positionally adjacent/overlapping ranges (gap ≤ 1 slot).\n const merged: Merged[] = [];\n for (const e of entries) {\n const last = merged[merged.length - 1];\n if (last && e.startPos <= last.endPos + 1) {\n last.endRef = e.endRef;\n last.endNum = Math.max(last.endNum, e.endNum);\n last.endPos = Math.max(last.endPos, e.endPos);\n last.count += e.count;\n last.tokens += e.tokens;\n last.userMsgs += e.userMsgs;\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 userNote = (n: number): string =>\n n > 0 ? ` · ${n} user msg${n > 1 ? \"s\" : \"\"}` : \"\";\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(\", \")}]${userNote(e.userMsgs)}${suffix}`;\n }\n return ` ${e.startRef}–${e.endRef} ${e.count} msgs ${formatK(e.tokens)} [tool ${e.toolPct}% | text ${e.textPct}%]${userNote(e.userMsgs)}${suffix}`;\n });\n return `Compressible ranges (${merged.length}, oldest first):\\n${lines.join(\"\\n\")}`;\n}\n\nconst DEFAULT_T2_GUIDANCE = `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\nconst DEFAULT_T3_GUIDANCE = `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\nfunction tierGuidance(tier: 2 | 3, sections: NudgePromptSections): string | null {\n const value = tier === 2 ? sections.t2Guidance : sections.t3Guidance;\n if (value !== undefined) return value;\n return tier === 2 ? DEFAULT_T2_GUIDANCE : DEFAULT_T3_GUIDANCE;\n}\n\nfunction compact(parts: string[]): string[] {\n while (parts.length > 0 && parts[0] === \"\") parts.shift();\n return parts;\n}\n\nexport function renderNudgeText(decision: NudgeDecision, prompts: Prompts = defaultPrompts, sections: NudgePromptSections = {}): RenderedNudge {\n const breakdownStr = formatBreakdown(decision.contextBreakdown);\n const rangesStr = formatRanges(decision.compressibleRanges, decision.protectedRanges ?? []);\n const blockMapStr = formatBlockMap(decision.activeBlockSpans ?? []);\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 const guidance = tierGuidance(isT2 ? 2 : 3, sections);\n const head = efficiencyNote(prompts, sections);\n return {\n voice,\n text: compact([\n ...(head === null ? [] : [head]),\n \"\",\n breakdownStr,\n \"\",\n triggerLine,\n ...(guidance === null ? [] : [guidance]),\n blockList,\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 const head = emergencyHeader(prompts, sections);\n return {\n voice: \"emergency\",\n text: compact([\n ...(head === null ? [] : [head]),\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 ...(blockMapStr ? [\"\", blockMapStr] : []),\n ]).join(\"\\n\"),\n };\n }\n\n const gentleHead = efficiencyNote(prompts, sections);\n return {\n voice: \"gentle\",\n text: compact([\n ...(gentleHead === null ? [] : [gentleHead]),\n \"\",\n breakdownStr,\n \"\",\n prompts.howToCompressRules,\n \"\",\n rangesStr,\n ...(blockMapStr ? [\"\", blockMapStr] : []),\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);\n}\n","// UTF-16-safe truncation. A plain slice can land between the two code units\n// of an astral character (emoji, CJK ext-B+), stranding a lone surrogate:\n// JSON.stringify escapes it (\\ud83e), and gateways that re-encode request\n// bodies to strict UTF-8 then throw UnicodeEncodeError on every retry\n// (ranxianglei/billion-context#816) — a deterministic poison that never heals.\n\nfunction isHighSurrogate(c: number): boolean {\n return c >= 0xd800 && c <= 0xdbff;\n}\n\nfunction isLowSurrogate(c: number): boolean {\n return c >= 0xdc00 && c <= 0xdfff;\n}\n\n/** At most maxUnits code units; never ends on a stranded high surrogate. */\nexport function clampPrefix(text: string, maxUnits: number): string {\n const cut = Math.min(maxUnits, text.length);\n if (cut > 0 && isHighSurrogate(text.charCodeAt(cut - 1))) return text.slice(0, cut - 1);\n return text.slice(0, cut);\n}\n\n/** A [start, end) window with both edges snapped off surrogate pairs. */\nexport function clampWindow(text: string, start: number, end: number): string {\n let s = Math.max(0, Math.min(start, text.length));\n let e = Math.min(text.length, Math.max(s, end));\n if (s > 0 && isLowSurrogate(text.charCodeAt(s))) s += 1;\n if (e > s && isHighSurrogate(text.charCodeAt(e - 1))) e -= 1;\n return text.slice(s, Math.max(s, e));\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;AAE9B,IAAMA,WAAU,cAAc,YAAY,GAAG;AAEtC,SAAS,mBAAmB,MAAsB;AACvD,MAAI,CAAC,KAAM,QAAO;AAIlB,QAAM,MAAM,KAAK,MAAM,4CAA4C;AACnE,QAAM,WAAW,KAAK,UAAU;AAChC,SAAO,WAAW,KAAK,MAAM,KAAK,SAAS,YAAY,CAAC;AAC1D;AASO,SAAS,mBAAmB,UAAsC;AACvE,SAAO,OAAO,aAAa,YACzB,OAAO,SAAS,QAAQ,KACxB,WAAW,IACT,WACA;AACN;AAMO,SAAS,mBACd,SACA,cAA4B,oBACpB;AACR,SACE,YAAY,QAAQ,QAAQ,EAAE,IAAI,mBAAmB,QAAQ,cAAc;AAE/E;AAEO,SAAS,mBAAmB,MAAsB;AACvD,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AAClC;AAIA,IAAM,iBAAiB;AAEhB,SAAS,qBAAmC;AACjD,MAAI;AACF,UAAM,MAAMC,SAAQ,yBAAyB;AAC7C,UAAM,WAAW,IAAI,eAAe,IAAI,SAAS;AACjD,QAAI,OAAO,aAAa,WAAY,QAAO;AAC3C,WAAO,CAAC,SAAiB;AACvB,UAAI,KAAK,SAAS,eAAgB,QAAO,mBAAmB,IAAI;AAChE,UAAI;AACF,eAAO,SAAS,IAAI;AAAA,MACtB,QAAQ;AACN,eAAO,mBAAmB,IAAI;AAAA,MAChC;AAAA,IACF;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;AC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cAAc,CAAC,IAAI,WAAW,IAAI,CAAC;AAAA,MACvC;AAAA,MACA;AAAA,IACF,CAAC,EAAE,KAAK,IAAI;AAAA,EACd;AACF;;;AC1OO,IAAM,0BAA0B;AAEhC,SAAS,aAA2C,QAAkB;AAC3E,SAAO,OAAO,OAAO,CAAC,MAAM,EAAE,UAAU,uBAAuB;AACjE;;;ACNA,SAAS,gBAAgB,GAAoB;AACzC,SAAO,KAAK,SAAU,KAAK;AAC/B;AAEA,SAAS,eAAe,GAAoB;AACxC,SAAO,KAAK,SAAU,KAAK;AAC/B;AAGO,SAAS,YAAY,MAAc,UAA0B;AAChE,QAAM,MAAM,KAAK,IAAI,UAAU,KAAK,MAAM;AAC1C,MAAI,MAAM,KAAK,gBAAgB,KAAK,WAAW,MAAM,CAAC,CAAC,EAAG,QAAO,KAAK,MAAM,GAAG,MAAM,CAAC;AACtF,SAAO,KAAK,MAAM,GAAG,GAAG;AAC5B;AAGO,SAAS,YAAY,MAAc,OAAe,KAAqB;AAC1E,MAAI,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI,OAAO,KAAK,MAAM,CAAC;AAChD,MAAI,IAAI,KAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,GAAG,GAAG,CAAC;AAC9C,MAAI,IAAI,KAAK,eAAe,KAAK,WAAW,CAAC,CAAC,EAAG,MAAK;AACtD,MAAI,IAAI,KAAK,gBAAgB,KAAK,WAAW,IAAI,CAAC,CAAC,EAAG,MAAK;AAC3D,SAAO,KAAK,MAAM,GAAG,KAAK,IAAI,GAAG,CAAC,CAAC;AACvC;","names":["require","require"]}
|
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, NudgePromptSections,
|
|
14
|
+
export type { NudgeVoice, RenderedNudge, NudgePromptSections, } from "./nudge-text.js";
|
|
15
15
|
export { resolveBlockSpan, activeBlockSpans, formatCreatedBlocks, } from "./block-map.js";
|
|
16
16
|
export { COMPRESS_PHILOSOPHY, HOW_TO_COMPRESS_RULES, TIER2_DISTILL_RULES, TIER3_CONDENSE_RULES, } from "./compression-rules.js";
|
|
17
17
|
export { defaultPrompts, resolvePrompts } from "./prompts.js";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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,EAClB,eAAe,EACf,aAAa,EACb,SAAS,EACT,YAAY,EACZ,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC5D,cAAc,qBAAqB,CAAC;AACpC,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,GACZ,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,EACL,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,qBAAqB,EACrB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,eAAe,CAAC;AACvB,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAChE,YAAY,EACV,UAAU,EACV,aAAa,EACb,mBAAmB,
|
|
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,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC5D,cAAc,qBAAqB,CAAC;AACpC,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,GACZ,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,EACL,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,qBAAqB,EACrB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,eAAe,CAAC;AACvB,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,e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CHANGED
package/dist/nudge-text.d.ts
CHANGED
|
@@ -11,19 +11,6 @@ export interface RenderedNudge {
|
|
|
11
11
|
voice: NudgeVoice;
|
|
12
12
|
text: string;
|
|
13
13
|
}
|
|
14
|
-
export interface RenderNudgeOptions extends NudgePromptSections {
|
|
15
|
-
/**
|
|
16
|
-
* Embed the load-bearing guidance texts (compressPhilosophy, howToCompressRules,
|
|
17
|
-
* and the active tier's distill/condense rules) in the nudge body. Defaults to
|
|
18
|
-
* true, so existing callers render byte-identical output. Set to false when the
|
|
19
|
-
* host already delivers these same texts once via its system prompt or tool
|
|
20
|
-
* descriptions — re-billing them on every injection is pure repetition. Only
|
|
21
|
-
* the four guidance texts are dropped; per-injection dynamic content
|
|
22
|
-
* (breakdown, trigger line, ranges, tier target blocks) survives. An explicit
|
|
23
|
-
* section override above always wins verbatim, independently of this flag.
|
|
24
|
-
*/
|
|
25
|
-
includeGuidance?: boolean;
|
|
26
|
-
}
|
|
27
14
|
export declare function formatRanges(compressible: CompressibleRange[], protectedRanges: ProtectedRange[]): string;
|
|
28
|
-
export declare function renderNudgeText(decision: NudgeDecision, prompts?: Prompts,
|
|
15
|
+
export declare function renderNudgeText(decision: NudgeDecision, prompts?: Prompts, sections?: NudgePromptSections): RenderedNudge;
|
|
29
16
|
//# sourceMappingURL=nudge-text.d.ts.map
|
package/dist/nudge-text.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nudge-text.d.ts","sourceRoot":"","sources":["../src/nudge-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,cAAc,EAAiD,MAAM,YAAY,CAAC;AAElI,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEhD,MAAM,WAAW,mBAAmB;IAClC,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,UAAU,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;
|
|
1
|
+
{"version":3,"file":"nudge-text.d.ts","sourceRoot":"","sources":["../src/nudge-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,cAAc,EAAiD,MAAM,YAAY,CAAC;AAElI,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEhD,MAAM,WAAW,mBAAmB;IAClC,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,UAAU,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AAwDD,wBAAgB,YAAY,CAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,MAAM,CAgFzG;AAiBD,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,GAAE,OAAwB,EAAE,QAAQ,GAAE,mBAAwB,GAAG,aAAa,CAyE7I"}
|
package/dist/panel/index.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ export { topicFallback } from "./topic.js";
|
|
|
2
2
|
export { formatCompactTokens } from "./format.js";
|
|
3
3
|
export { buildStatusPanel } from "./panel.js";
|
|
4
4
|
export type { StatusPanelInput } from "./panel.js";
|
|
5
|
+
export { DEFAULT_PANEL_LABELS, displayWidth, fill, padLabel, renderTitleBox, resolvePanelLabels } from "./labels.js";
|
|
6
|
+
export type { PanelLabels } from "./labels.js";
|
|
5
7
|
export { cacheHitStats, formatHitRate } from "./cache.js";
|
|
6
8
|
export type { CacheUsageSample, CacheHitSummary } from "./cache.js";
|
|
7
9
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/panel/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC1D,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/panel/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACrH,YAAY,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC1D,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/panel/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
defaultCountTokens,
|
|
4
4
|
formatRanges,
|
|
5
5
|
viableRanges
|
|
6
|
-
} from "../chunk-
|
|
6
|
+
} from "../chunk-VPRKYTHW.js";
|
|
7
7
|
|
|
8
8
|
// src/panel/topic.ts
|
|
9
9
|
function topicFallback(summary) {
|
|
@@ -54,6 +54,76 @@ function formatHitRate(rate) {
|
|
|
54
54
|
return `${(Math.max(0, Math.min(1, rate)) * 100).toFixed(1)}%`;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
// src/panel/labels.ts
|
|
58
|
+
var DEFAULT_PANEL_LABELS = {
|
|
59
|
+
title: "ACP Context Analysis",
|
|
60
|
+
context: "Context (session accounting, host footer scale): {pct}% ({used} / {limit}) \u2014 includes compressed originals; shrinks slower than the sent view",
|
|
61
|
+
growth: "Growth: +{growth} since last nudge",
|
|
62
|
+
sent: "Sent to LLM (after compression, est.): {sent}",
|
|
63
|
+
sentOfLimit: " ({pct}% of limit)",
|
|
64
|
+
sessionOnly: "Session-only (compressed originals, est.): {only} \u2014 pruned from every request; the footer/nudge still count them",
|
|
65
|
+
breakdown: "Token Breakdown (sent view):",
|
|
66
|
+
catTool: "Tool",
|
|
67
|
+
catSysPrompt: "SysPrompt",
|
|
68
|
+
catText: "Text",
|
|
69
|
+
catCode: "Code",
|
|
70
|
+
catSummaries: "Summaries",
|
|
71
|
+
promptCache: "Prompt cache (provider-reported): {last} last \xB7 {session} session avg \u2014 {read} of {billed} billed prompt tokens served from cache ({requests} req)",
|
|
72
|
+
nudgeActive: "Nudge: ACTIVE{tierInfo} \u2014 {reason}",
|
|
73
|
+
nudgeTierInfo: " [T{tier} distillation]",
|
|
74
|
+
nudgeIdle: "Nudge: idle \u2014 {reason}",
|
|
75
|
+
blocksHeader: "Blocks: {active} active / {total} total ({tokens} tokens compressed, cumulative)",
|
|
76
|
+
blocksNone: "Blocks: none (nothing compressed yet)",
|
|
77
|
+
tagVisibility: "Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal."
|
|
78
|
+
};
|
|
79
|
+
function resolvePanelLabels(labels) {
|
|
80
|
+
const out = { ...DEFAULT_PANEL_LABELS };
|
|
81
|
+
if (!labels) return out;
|
|
82
|
+
for (const key of Object.keys(labels)) {
|
|
83
|
+
const value = labels[key];
|
|
84
|
+
if (typeof value === "string" && Object.hasOwn(DEFAULT_PANEL_LABELS, key)) out[key] = value;
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
function fill(template, params) {
|
|
89
|
+
return template.replace(/\{([A-Za-z][A-Za-z0-9_]*)\}/g, (m, k) => k in params ? String(params[k]) : m);
|
|
90
|
+
}
|
|
91
|
+
var LEGACY_TITLE_BOX = [
|
|
92
|
+
"\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E",
|
|
93
|
+
"\u2502 ACP Context Analysis \u2502",
|
|
94
|
+
"\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"
|
|
95
|
+
];
|
|
96
|
+
var MIN_INNER_WIDTH = 45;
|
|
97
|
+
function charDisplayWidth(ch) {
|
|
98
|
+
const cp = ch.codePointAt(0);
|
|
99
|
+
const wide = cp >= 4352 && cp <= 4447 || // Hangul Jamo
|
|
100
|
+
cp >= 11904 && cp <= 42191 || // CJK radicals .. Yi syllables
|
|
101
|
+
cp >= 44032 && cp <= 55203 || // Hangul syllables
|
|
102
|
+
cp >= 63744 && cp <= 64255 || // CJK compatibility ideographs
|
|
103
|
+
cp >= 65072 && cp <= 65103 || // CJK compatibility forms
|
|
104
|
+
cp >= 65280 && cp <= 65376 || // fullwidth forms
|
|
105
|
+
cp >= 65504 && cp <= 65510 || // halfwidth/fullwidth forms
|
|
106
|
+
cp >= 131072;
|
|
107
|
+
return wide ? 2 : 1;
|
|
108
|
+
}
|
|
109
|
+
function displayWidth(s) {
|
|
110
|
+
let w = 0;
|
|
111
|
+
for (const ch of s) w += charDisplayWidth(ch);
|
|
112
|
+
return w;
|
|
113
|
+
}
|
|
114
|
+
function padLabel(s, width) {
|
|
115
|
+
const dw = displayWidth(s);
|
|
116
|
+
return dw >= width ? s : s + " ".repeat(width - dw);
|
|
117
|
+
}
|
|
118
|
+
function renderTitleBox(title) {
|
|
119
|
+
if (title === DEFAULT_PANEL_LABELS.title) return LEGACY_TITLE_BOX;
|
|
120
|
+
const dw = displayWidth(title);
|
|
121
|
+
const inner = Math.max(MIN_INNER_WIDTH, dw + 2);
|
|
122
|
+
const padL = Math.floor((inner - dw) / 2);
|
|
123
|
+
const padR = inner - dw - padL;
|
|
124
|
+
return ["\u256D" + "\u2500".repeat(inner) + "\u256E", `\u2502${" ".repeat(padL)}${title}${" ".repeat(padR)}\u2502`, "\u2570" + "\u2500".repeat(inner) + "\u256F"];
|
|
125
|
+
}
|
|
126
|
+
|
|
57
127
|
// src/panel/panel.ts
|
|
58
128
|
function bar(value, total, width = 20) {
|
|
59
129
|
if (total === 0) return "";
|
|
@@ -62,6 +132,7 @@ function bar(value, total, width = 20) {
|
|
|
62
132
|
}
|
|
63
133
|
function buildStatusPanel(input) {
|
|
64
134
|
const { tokenCount, state, nudge, modelContextLimit } = input;
|
|
135
|
+
const L = resolvePanelLabels(input.labels);
|
|
65
136
|
const fmt = input.fmtTokens ?? formatCompactTokens;
|
|
66
137
|
const bd = nudge?.contextBreakdown;
|
|
67
138
|
const limit = modelContextLimit;
|
|
@@ -75,36 +146,36 @@ function buildStatusPanel(input) {
|
|
|
75
146
|
const activeBlocksList = state.blocks.filter((b) => b.active);
|
|
76
147
|
const totalBlocksList = state.blocks;
|
|
77
148
|
const lines = [];
|
|
78
|
-
lines.push(
|
|
79
|
-
lines.push("\u2502 ACP Context Analysis \u2502");
|
|
80
|
-
lines.push("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");
|
|
149
|
+
lines.push(...renderTitleBox(L.title));
|
|
81
150
|
if (input.version) lines.push(input.version);
|
|
82
151
|
lines.push("");
|
|
83
|
-
lines.push(
|
|
152
|
+
lines.push(fill(L.context, { pct: displayPct, used: fmt(displayTotal), limit: fmt(limit) }));
|
|
84
153
|
if (nudge && bd) {
|
|
85
154
|
const growth = bd.growth;
|
|
86
155
|
if (growth > 0 && displayTotal > 0) {
|
|
87
|
-
lines.push(
|
|
156
|
+
lines.push(fill(L.growth, { growth: fmt(growth) }));
|
|
88
157
|
}
|
|
89
158
|
lines.push("");
|
|
90
|
-
|
|
159
|
+
let sentLine = fill(L.sent, { sent: fmt(sentTotal) });
|
|
160
|
+
if (limit > 0) sentLine += fill(L.sentOfLimit, { pct: sentPct });
|
|
161
|
+
lines.push(sentLine);
|
|
91
162
|
if (input.unprunedTokens !== void 0 && sessionOnly > 0) {
|
|
92
|
-
lines.push(
|
|
163
|
+
lines.push(fill(L.sessionOnly, { only: fmt(sessionOnly) }));
|
|
93
164
|
}
|
|
94
165
|
lines.push("");
|
|
95
|
-
lines.push(
|
|
166
|
+
lines.push(L.breakdown);
|
|
96
167
|
const categories = [
|
|
97
|
-
{ label:
|
|
98
|
-
{ label:
|
|
99
|
-
{ label:
|
|
100
|
-
{ label:
|
|
101
|
-
{ label:
|
|
168
|
+
{ label: L.catTool, value: bd.tool },
|
|
169
|
+
{ label: L.catSysPrompt, value: systemPromptTokens },
|
|
170
|
+
{ label: L.catText, value: bd.text },
|
|
171
|
+
{ label: L.catCode, value: bd.code },
|
|
172
|
+
{ label: L.catSummaries, value: bd.summaries }
|
|
102
173
|
];
|
|
103
174
|
for (const cat of categories) {
|
|
104
175
|
if (cat.value <= 0) continue;
|
|
105
176
|
const pct = sentTotal > 0 ? Math.round(cat.value / sentTotal * 100) : 0;
|
|
106
177
|
const b = bar(cat.value, sentTotal);
|
|
107
|
-
lines.push(` ${cat.label
|
|
178
|
+
lines.push(` ${padLabel(cat.label, 10)} ${b} ${String(pct).padStart(3)}% ${fmt(cat.value)}`);
|
|
108
179
|
}
|
|
109
180
|
}
|
|
110
181
|
if (input.cacheUsages) {
|
|
@@ -112,17 +183,23 @@ function buildStatusPanel(input) {
|
|
|
112
183
|
if (cache.requests > 0 && cache.session !== void 0 && cache.last !== void 0) {
|
|
113
184
|
lines.push("");
|
|
114
185
|
lines.push(
|
|
115
|
-
|
|
186
|
+
fill(L.promptCache, {
|
|
187
|
+
last: formatHitRate(cache.last),
|
|
188
|
+
session: formatHitRate(cache.session),
|
|
189
|
+
read: fmt(cache.cacheRead),
|
|
190
|
+
billed: fmt(cache.billedPrompt),
|
|
191
|
+
requests: cache.requests
|
|
192
|
+
})
|
|
116
193
|
);
|
|
117
194
|
}
|
|
118
195
|
}
|
|
119
196
|
lines.push("");
|
|
120
197
|
if (nudge) {
|
|
121
198
|
if (nudge.shouldInject) {
|
|
122
|
-
const tierInfo = nudge.tier ?
|
|
123
|
-
lines.push(
|
|
199
|
+
const tierInfo = nudge.tier ? fill(L.nudgeTierInfo, { tier: nudge.tier }) : "";
|
|
200
|
+
lines.push(fill(L.nudgeActive, { tierInfo, reason: nudge.reason }));
|
|
124
201
|
} else {
|
|
125
|
-
lines.push(
|
|
202
|
+
lines.push(fill(L.nudgeIdle, { reason: nudge.reason }));
|
|
126
203
|
}
|
|
127
204
|
}
|
|
128
205
|
const ranges = viableRanges(nudge?.compressibleRanges ?? []);
|
|
@@ -133,7 +210,7 @@ function buildStatusPanel(input) {
|
|
|
133
210
|
}
|
|
134
211
|
if (activeBlocksList.length > 0) {
|
|
135
212
|
lines.push("");
|
|
136
|
-
lines.push(
|
|
213
|
+
lines.push(fill(L.blocksHeader, { active: activeBlocksList.length, total: totalBlocksList.length, tokens: fmt(state.stats.tokensCompressed) }));
|
|
137
214
|
for (const b of activeBlocksList) {
|
|
138
215
|
const topic = b.topic ? `: ${b.topic}` : `: ${topicFallback(b.summary || "")}`;
|
|
139
216
|
const summaryTok = defaultCountTokens(b.summary || "");
|
|
@@ -142,20 +219,26 @@ function buildStatusPanel(input) {
|
|
|
142
219
|
}
|
|
143
220
|
} else if (totalBlocksList.length > 0) {
|
|
144
221
|
lines.push("");
|
|
145
|
-
lines.push(
|
|
222
|
+
lines.push(fill(L.blocksHeader, { active: 0, total: totalBlocksList.length, tokens: fmt(state.stats.tokensCompressed) }));
|
|
146
223
|
} else {
|
|
147
224
|
lines.push("");
|
|
148
|
-
lines.push(
|
|
225
|
+
lines.push(L.blocksNone);
|
|
149
226
|
}
|
|
150
227
|
lines.push("");
|
|
151
|
-
lines.push(
|
|
228
|
+
lines.push(L.tagVisibility);
|
|
152
229
|
return lines.join("\n");
|
|
153
230
|
}
|
|
154
231
|
export {
|
|
232
|
+
DEFAULT_PANEL_LABELS,
|
|
155
233
|
buildStatusPanel,
|
|
156
234
|
cacheHitStats,
|
|
235
|
+
displayWidth,
|
|
236
|
+
fill,
|
|
157
237
|
formatCompactTokens,
|
|
158
238
|
formatHitRate,
|
|
239
|
+
padLabel,
|
|
240
|
+
renderTitleBox,
|
|
241
|
+
resolvePanelLabels,
|
|
159
242
|
topicFallback
|
|
160
243
|
};
|
|
161
244
|
//# sourceMappingURL=index.js.map
|
package/dist/panel/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/panel/topic.ts","../../src/panel/format.ts","../../src/panel/cache.ts","../../src/panel/panel.ts"],"sourcesContent":["/** Short topic for a block when the model did not provide one: first sentence\n * segment, leading quotes stripped, truncated to 30 chars with an ellipsis.\n * Used wherever block lists are rendered (panels, search results). */\nimport { clampPrefix } from \"../truncate.js\";\n\nexport function topicFallback(summary: string): string {\n const first = summary.split(/[.\\n]/)[0] ?? \"\";\n const t = first.trim().replace(/^[\"'`]+/, \"\").trim();\n return t.length <= 30 ? t : `${clampPrefix(t, 30).trimEnd()}…`;\n}\n","/** Compact token formatting for user-facing panels: lowercase k/M with the\n * same thresholds as the hosts' footers (<1000 → raw, <10000 → one decimal\n * k, <1e6 → rounded k, <1e7 → one decimal M). */\nexport function formatCompactTokens(count: number): string {\n if (count < 1000) return count.toString();\n if (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n if (count < 1000000) return `${Math.round(count / 1000)}k`;\n if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n return `${Math.round(count / 1000000)}M`;\n}\n","/** Cache hit-rate math for the /acp status panel.\n *\n * Hosts feed per-request prompt-cache usage samples (from assistant\n * messages' provider-reported `usage`); the kernel derives the display\n * numbers. A request COUNTS only when the provider reported cache\n * activity for it (`cacheRead + cacheWrite > 0`): providers without\n * prompt-cache reporting (0/0 with plain `input`) must not drag the\n * average to a fabricated 0%. */\n\nexport interface CacheUsageSample {\n /** Non-cached conversation input tokens billed for the request. */\n input: number;\n /** Conversation tokens served from the prompt cache. */\n cacheRead: number;\n /** Conversation tokens written to the prompt cache (cache creation). */\n cacheWrite: number;\n}\n\nexport interface CacheHitSummary {\n /** Session hit rate (0..1), weighted by billed prompt tokens.\n * Undefined when no request reported cache activity. */\n session: number | undefined;\n /** Hit rate (0..1) of the most recent request that reported cache\n * activity. Undefined when no request reported any. */\n last: number | undefined;\n /** Counted requests (provider reported cache activity). */\n requests: number;\n /** Cumulative tokens served from cache. */\n cacheRead: number;\n /** Cumulative billed prompt tokens (input + cacheRead + cacheWrite). */\n billedPrompt: number;\n}\n\nfunction num(v: unknown): number {\n return typeof v === \"number\" && Number.isFinite(v) && v > 0 ? v : 0;\n}\n\n/** Aggregate per-request cache usage into panel display numbers. */\nexport function cacheHitStats(usages: readonly CacheUsageSample[]): CacheHitSummary {\n let cacheRead = 0;\n let billedPrompt = 0;\n let requests = 0;\n let last: number | undefined;\n for (const u of usages) {\n const read = num(u?.cacheRead);\n const write = num(u?.cacheWrite);\n const input = num(u?.input);\n // No cache signal on this request → excluded entirely (see header).\n if (read + write <= 0) continue;\n const total = read + write + input;\n if (total <= 0) continue;\n cacheRead += read;\n billedPrompt += total;\n requests += 1;\n last = read / total;\n }\n return {\n session: requests > 0 ? cacheRead / billedPrompt : undefined,\n last,\n requests,\n cacheRead,\n billedPrompt,\n };\n}\n\n/** Format a 0..1 rate as a percentage with one decimal (\"92.3%\"). */\nexport function formatHitRate(rate: number): string {\n return `${(Math.max(0, Math.min(1, rate)) * 100).toFixed(1)}%`;\n}\n","import { defaultCountTokens } from \"../tokenize.js\";\nimport { formatRanges } from \"../nudge-text.js\";\nimport type { CompressionState, NudgeDecision } from \"../types.js\";\nimport { formatCompactTokens } from \"./format.js\";\nimport { topicFallback } from \"./topic.js\";\nimport { viableRanges } from \"../viable.js\";\nimport { cacheHitStats, formatHitRate, type CacheUsageSample } from \"./cache.js\";\n\nexport interface StatusPanelInput {\n /** Adapter identifier for the header, e.g. \"billion-context-omp@0.1.6\".\n * Omit to hide the version line. */\n version?: string;\n /** Host session accounting — the SAME number the host footer displays.\n * It includes compressed originals (summaries stay in the window), so it\n * shrinks slower than the sent view when compression prunes the\n * per-request projection. */\n tokenCount: number;\n /** Measured token count of the host system prompt (host-specific to\n * obtain; the kernel breakdown does not see it). */\n systemPromptTokens: number;\n /** Kernel state (blocks drive the Blocks section). */\n state: CompressionState;\n /** The nudge decision from core.processTurn for this turn, if any. The\n * panel applies the viability filter to compressibleRanges itself. */\n nudge: NudgeDecision | undefined;\n /** Configured model context window, in tokens. */\n modelContextLimit: number;\n /** Estimate of the FULL (unpruned) core-message projection, computed\n * with the SAME countTokens the core uses (kernel default = CJK-aware\n * defaultCountTokens) — the same estimation scale as the kernel\n * breakdown. When provided, the panel derives `Session-only` on that\n * scale (unpruned − sent). Without it the line is omitted: subtracting\n * the host's provider-scale number from an estimate-scale number\n * invents a third, meaningless scale (issue #18 \"看板统计的和拆分的有差异\"). */\n unprunedTokens?: number;\n /** Per-request prompt-cache usage (from assistant messages' provider-\n * reported `usage`). Requests without cache reporting are excluded by\n * cacheHitStats; when no counted request remains, the section is\n * omitted entirely. Omit the field to hide the section. */\n cacheUsages?: ReadonlyArray<CacheUsageSample>;\n /** Token formatter override (defaults to formatCompactTokens). */\n fmtTokens?: (n: number) => string;\n}\n\nfunction bar(value: number, total: number, width: number = 20): string {\n if (total === 0) return \"\";\n const filled = Math.max(0, Math.min(width, Math.round((value / total) * width)));\n return \"█\".repeat(filled) + \"░\".repeat(width - filled);\n}\n\n/** Render the /acp status panel. Three token numbers, each labeled with\n * its own scale, never mixed in arithmetic:\n * - Session accounting (host footer scale): the host's reported context\n * size INCLUDING compressed originals (summaries stay in the window), so\n * it shrinks slower than the sent view when compression prunes the\n * per-request projection.\n * - Sent view (estimated, kernel countTokens scale): what actually\n * reaches the LLM after compression (kernel's classification over the\n * pruned projection + measured system prompt). This is the number\n * compression controls.\n * - Session-only (estimated, kernel countTokens scale): unpruned\n * projection − sent view; the compressed originals pruned from every\n * request.\n * Subtracting the host number from an estimate produced numbers that\n * reconciled with neither scale (\"Framework 390K\", \"session-only 29k vs\n * 112k compressed\") — that is what issue #18 reported. */\nexport function buildStatusPanel(input: StatusPanelInput): string {\n const { tokenCount, state, nudge, modelContextLimit } = input;\n const fmt = input.fmtTokens ?? formatCompactTokens;\n const bd = nudge?.contextBreakdown;\n const limit = modelContextLimit;\n const classified = bd ? bd.system + bd.tool + bd.summaries + bd.code + bd.text : 0;\n const systemPromptTokens = input.systemPromptTokens;\n const sentTotal = classified + systemPromptTokens;\n // Same-scale derivation only: both sides use the core's countTokens\n // estimate (kernel default = CJK-aware defaultCountTokens). The host\n // footer's tokenCount (provider-anchored, session-tree) is displayed as\n // its own line and never fed into an arithmetic difference with these.\n const sessionOnly = input.unprunedTokens !== undefined ? Math.max(0, input.unprunedTokens - sentTotal) : 0;\n const displayTotal = tokenCount;\n const displayPct = limit > 0 ? Math.round((displayTotal / limit) * 100) : 0;\n const sentPct = limit > 0 ? Math.round((sentTotal / limit) * 100) : 0;\n const activeBlocksList = state.blocks.filter((b) => b.active);\n const totalBlocksList = state.blocks;\n\n const lines: string[] = [];\n\n lines.push(\"╭─────────────────────────────────────────────╮\");\n lines.push(\"│ ACP Context Analysis │\");\n lines.push(\"╰─────────────────────────────────────────────╯\");\n if (input.version) lines.push(input.version);\n lines.push(\"\");\n lines.push(`Context (session accounting, host footer scale): ${displayPct}% (${fmt(displayTotal)} / ${fmt(limit)}) — includes compressed originals; shrinks slower than the sent view`);\n\n if (nudge && bd) {\n const growth = bd.growth;\n if (growth > 0 && displayTotal > 0) {\n lines.push(`Growth: +${fmt(growth)} since last nudge`);\n }\n lines.push(\"\");\n lines.push(`Sent to LLM (after compression, est.): ${fmt(sentTotal)}${limit > 0 ? ` (${sentPct}% of limit)` : \"\"}`);\n if (input.unprunedTokens !== undefined && sessionOnly > 0) {\n lines.push(`Session-only (compressed originals, est.): ${fmt(sessionOnly)} — pruned from every request; the footer/nudge still count them`);\n }\n lines.push(\"\");\n lines.push(\"Token Breakdown (sent view):\");\n\n const categories: Array<{ label: string; value: number }> = [\n { label: \"Tool\", value: bd.tool },\n { label: \"SysPrompt\", value: systemPromptTokens },\n { label: \"Text\", value: bd.text },\n { label: \"Code\", value: bd.code },\n { label: \"Summaries\", value: bd.summaries },\n ];\n\n for (const cat of categories) {\n if (cat.value <= 0) continue;\n const pct = sentTotal > 0 ? Math.round((cat.value / sentTotal) * 100) : 0;\n const b = bar(cat.value, sentTotal);\n lines.push(` ${cat.label.padEnd(10)} ${b} ${String(pct).padStart(3)}% ${fmt(cat.value)}`);\n }\n }\n\n if (input.cacheUsages) {\n const cache = cacheHitStats(input.cacheUsages);\n if (cache.requests > 0 && cache.session !== undefined && cache.last !== undefined) {\n lines.push(\"\");\n lines.push(\n `Prompt cache (provider-reported): ${formatHitRate(cache.last)} last · ${formatHitRate(cache.session)} session avg — ${fmt(cache.cacheRead)} of ${fmt(cache.billedPrompt)} billed prompt tokens served from cache (${cache.requests} req)`,\n );\n }\n }\n\n lines.push(\"\");\n\n if (nudge) {\n if (nudge.shouldInject) {\n const tierInfo = nudge.tier ? ` [T${nudge.tier} distillation]` : \"\";\n lines.push(`Nudge: ACTIVE${tierInfo} — ${nudge.reason}`);\n } else {\n lines.push(`Nudge: idle — ${nudge.reason}`);\n }\n }\n\n const ranges = viableRanges(nudge?.compressibleRanges ?? []);\n const protectedRanges = nudge?.protectedRanges ?? [];\n if (ranges.length > 0 || protectedRanges.length > 0) {\n lines.push(\"\");\n lines.push(formatRanges(ranges, protectedRanges));\n }\n\n if (activeBlocksList.length > 0) {\n lines.push(\"\");\n lines.push(`Blocks: ${activeBlocksList.length} active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`);\n for (const b of activeBlocksList) {\n const topic = b.topic ? `: ${b.topic}` : `: ${topicFallback(b.summary || \"\")}`;\n const summaryTok = defaultCountTokens(b.summary || \"\");\n const origTok = b.compressedTokens > 0 ? b.compressedTokens : summaryTok;\n lines.push(` [${b.blockId}] T${b.tier} ${fmt(origTok)}→${fmt(summaryTok)}${topic}`);\n }\n } else if (totalBlocksList.length > 0) {\n lines.push(\"\");\n lines.push(`Blocks: 0 active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`);\n } else {\n lines.push(\"\");\n lines.push(\"Blocks: none (nothing compressed yet)\");\n }\n\n lines.push(\"\");\n lines.push(\"Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.\");\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;AAKO,SAAS,cAAc,SAAyB;AACrD,QAAM,QAAQ,QAAQ,MAAM,OAAO,EAAE,CAAC,KAAK;AAC3C,QAAM,IAAI,MAAM,KAAK,EAAE,QAAQ,WAAW,EAAE,EAAE,KAAK;AACnD,SAAO,EAAE,UAAU,KAAK,IAAI,GAAG,YAAY,GAAG,EAAE,EAAE,QAAQ,CAAC;AAC7D;;;ACNO,SAAS,oBAAoB,OAAuB;AACzD,MAAI,QAAQ,IAAM,QAAO,MAAM,SAAS;AACxC,MAAI,QAAQ,IAAO,QAAO,IAAI,QAAQ,KAAM,QAAQ,CAAC,CAAC;AACtD,MAAI,QAAQ,IAAS,QAAO,GAAG,KAAK,MAAM,QAAQ,GAAI,CAAC;AACvD,MAAI,QAAQ,IAAU,QAAO,IAAI,QAAQ,KAAS,QAAQ,CAAC,CAAC;AAC5D,SAAO,GAAG,KAAK,MAAM,QAAQ,GAAO,CAAC;AACvC;;;ACwBA,SAAS,IAAI,GAAoB;AAC/B,SAAO,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,IAAI,IAAI,IAAI;AACpE;AAGO,SAAS,cAAc,QAAsD;AAClF,MAAI,YAAY;AAChB,MAAI,eAAe;AACnB,MAAI,WAAW;AACf,MAAI;AACJ,aAAW,KAAK,QAAQ;AACtB,UAAM,OAAO,IAAI,GAAG,SAAS;AAC7B,UAAM,QAAQ,IAAI,GAAG,UAAU;AAC/B,UAAM,QAAQ,IAAI,GAAG,KAAK;AAE1B,QAAI,OAAO,SAAS,EAAG;AACvB,UAAM,QAAQ,OAAO,QAAQ;AAC7B,QAAI,SAAS,EAAG;AAChB,iBAAa;AACb,oBAAgB;AAChB,gBAAY;AACZ,WAAO,OAAO;AAAA,EAChB;AACA,SAAO;AAAA,IACL,SAAS,WAAW,IAAI,YAAY,eAAe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AK,EAAE;AAAA,IACrF;AAAA,EACF,WAAW,gBAAgB,SAAS,GAAG;AACrC,UAAM,KAAK,EAAE;AACb,UAAM,KAAK,sBAAsB,gBAAgB,MAAM,WAAW,IAAI,MAAM,MAAM,gBAAgB,CAAC,iCAAiC;AAAA,EACtI,OAAO;AACL,UAAM,KAAK,EAAE;AACb,UAAM,KAAK,uCAAuC;AAAA,EACpD;AAEA,QAAM,KAAK,EAAE;AACb,QAAM,KAAK,yGAAyG;AAEpH,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/panel/topic.ts","../../src/panel/format.ts","../../src/panel/cache.ts","../../src/panel/labels.ts","../../src/panel/panel.ts"],"sourcesContent":["/** Short topic for a block when the model did not provide one: first sentence\n * segment, leading quotes stripped, truncated to 30 chars with an ellipsis.\n * Used wherever block lists are rendered (panels, search results). */\nimport { clampPrefix } from \"../truncate.js\";\n\nexport function topicFallback(summary: string): string {\n const first = summary.split(/[.\\n]/)[0] ?? \"\";\n const t = first.trim().replace(/^[\"'`]+/, \"\").trim();\n return t.length <= 30 ? t : `${clampPrefix(t, 30).trimEnd()}…`;\n}\n","/** Compact token formatting for user-facing panels: lowercase k/M with the\n * same thresholds as the hosts' footers (<1000 → raw, <10000 → one decimal\n * k, <1e6 → rounded k, <1e7 → one decimal M). */\nexport function formatCompactTokens(count: number): string {\n if (count < 1000) return count.toString();\n if (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n if (count < 1000000) return `${Math.round(count / 1000)}k`;\n if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n return `${Math.round(count / 1000000)}M`;\n}\n","/** Cache hit-rate math for the /acp status panel.\n *\n * Hosts feed per-request prompt-cache usage samples (from assistant\n * messages' provider-reported `usage`); the kernel derives the display\n * numbers. A request COUNTS only when the provider reported cache\n * activity for it (`cacheRead + cacheWrite > 0`): providers without\n * prompt-cache reporting (0/0 with plain `input`) must not drag the\n * average to a fabricated 0%. */\n\nexport interface CacheUsageSample {\n /** Non-cached conversation input tokens billed for the request. */\n input: number;\n /** Conversation tokens served from the prompt cache. */\n cacheRead: number;\n /** Conversation tokens written to the prompt cache (cache creation). */\n cacheWrite: number;\n}\n\nexport interface CacheHitSummary {\n /** Session hit rate (0..1), weighted by billed prompt tokens.\n * Undefined when no request reported cache activity. */\n session: number | undefined;\n /** Hit rate (0..1) of the most recent request that reported cache\n * activity. Undefined when no request reported any. */\n last: number | undefined;\n /** Counted requests (provider reported cache activity). */\n requests: number;\n /** Cumulative tokens served from cache. */\n cacheRead: number;\n /** Cumulative billed prompt tokens (input + cacheRead + cacheWrite). */\n billedPrompt: number;\n}\n\nfunction num(v: unknown): number {\n return typeof v === \"number\" && Number.isFinite(v) && v > 0 ? v : 0;\n}\n\n/** Aggregate per-request cache usage into panel display numbers. */\nexport function cacheHitStats(usages: readonly CacheUsageSample[]): CacheHitSummary {\n let cacheRead = 0;\n let billedPrompt = 0;\n let requests = 0;\n let last: number | undefined;\n for (const u of usages) {\n const read = num(u?.cacheRead);\n const write = num(u?.cacheWrite);\n const input = num(u?.input);\n // No cache signal on this request → excluded entirely (see header).\n if (read + write <= 0) continue;\n const total = read + write + input;\n if (total <= 0) continue;\n cacheRead += read;\n billedPrompt += total;\n requests += 1;\n last = read / total;\n }\n return {\n session: requests > 0 ? cacheRead / billedPrompt : undefined,\n last,\n requests,\n cacheRead,\n billedPrompt,\n };\n}\n\n/** Format a 0..1 rate as a percentage with one decimal (\"92.3%\"). */\nexport function formatHitRate(rate: number): string {\n return `${(Math.max(0, Math.min(1, rate)) * 100).toFixed(1)}%`;\n}\n","/** Display labels for buildStatusPanel. The English defaults below are the\n * key source of truth; hosts pass Partial<PanelLabels> to localize the panel\n * (billion-context-pi issue #153). This is a DISPLAY-ONLY surface: these\n * strings render in the terminal and never reach the model, so translating\n * them cannot affect compression/nudge behavior.\n *\n * Templates use `{name}` placeholders filled by fill(). Keys omitted by a\n * host pack fall back to the English default per key (partial packs degrade\n * gracefully instead of failing wholesale). */\nexport interface PanelLabels {\n /** Title rendered inside the decorative box. */\n title: string;\n /** Params: pct (number), used / limit (formatted token counts). */\n context: string;\n /** Params: growth (formatted). Line rendered only when growth > 0. */\n growth: string;\n /** Params: sent (formatted). */\n sent: string;\n /** Params: pct (number). Appended to the sent line only when a context\n * limit is configured; omit the placeholder in a pack to drop it. */\n sentOfLimit: string;\n /** Params: only (formatted). Line rendered only when unprunedTokens is\n * provided and the derived value is positive. */\n sessionOnly: string;\n breakdown: string;\n catTool: string;\n catSysPrompt: string;\n catText: string;\n catCode: string;\n catSummaries: string;\n /** Params: last / session (hit-rate strings), read / billed (formatted),\n * requests (number). */\n promptCache: string;\n /** Params: tierInfo (string, empty when no tier), reason (verbatim model-\n * facing text — keep it in your template verbatim). */\n nudgeActive: string;\n /** Params: tier (number). */\n nudgeTierInfo: string;\n /** Params: reason (verbatim model-facing text). */\n nudgeIdle: string;\n /** Params: active / total (numbers), tokens (formatted). Used for both the\n * active and zero-active block counts. */\n blocksHeader: string;\n /** Rendered when no blocks exist at all. */\n blocksNone: string;\n tagVisibility: string;\n}\n\nexport const DEFAULT_PANEL_LABELS: PanelLabels = {\n title: \"ACP Context Analysis\",\n context: \"Context (session accounting, host footer scale): {pct}% ({used} / {limit}) — includes compressed originals; shrinks slower than the sent view\",\n growth: \"Growth: +{growth} since last nudge\",\n sent: \"Sent to LLM (after compression, est.): {sent}\",\n sentOfLimit: \" ({pct}% of limit)\",\n sessionOnly: \"Session-only (compressed originals, est.): {only} — pruned from every request; the footer/nudge still count them\",\n breakdown: \"Token Breakdown (sent view):\",\n catTool: \"Tool\",\n catSysPrompt: \"SysPrompt\",\n catText: \"Text\",\n catCode: \"Code\",\n catSummaries: \"Summaries\",\n promptCache: \"Prompt cache (provider-reported): {last} last · {session} session avg — {read} of {billed} billed prompt tokens served from cache ({requests} req)\",\n nudgeActive: \"Nudge: ACTIVE{tierInfo} — {reason}\",\n nudgeTierInfo: \" [T{tier} distillation]\",\n nudgeIdle: \"Nudge: idle — {reason}\",\n blocksHeader: \"Blocks: {active} active / {total} total ({tokens} tokens compressed, cumulative)\",\n blocksNone: \"Blocks: none (nothing compressed yet)\",\n tagVisibility: \"Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.\",\n};\n\n/** Merge a partial label pack over the English defaults, ignoring entries\n * whose value is not a string (explicit `undefined` from a config merge,\n * `null`, …). A plain `{ ...defaults, ...pack }` spread lets one undefined\n * key blank out its default and crash the display-width renderers. */\nexport function resolvePanelLabels(labels?: Partial<PanelLabels>): PanelLabels {\n const out: PanelLabels = { ...DEFAULT_PANEL_LABELS };\n if (!labels) return out;\n for (const key of Object.keys(labels) as Array<keyof PanelLabels>) {\n const value = labels[key];\n if (typeof value === \"string\" && Object.hasOwn(DEFAULT_PANEL_LABELS, key)) out[key] = value;\n }\n return out;\n}\n\n/** Substitute `{name}` placeholders from params. Unknown placeholders are\n * left intact so a typo in a host pack is visible on screen instead of\n * silently dropping information. */\nexport function fill(template: string, params: Record<string, string | number>): string {\n return template.replace(/\\{([A-Za-z][A-Za-z0-9_]*)\\}/g, (m, k: string) => (k in params ? String(params[k]) : m));\n}\n\n// Legacy fixed-width title box (inner width 45). Frozen so the default\n// output stays byte-identical for hosts that don't pass labels.\nconst LEGACY_TITLE_BOX = [\n \"╭─────────────────────────────────────────────╮\",\n \"│ ACP Context Analysis │\",\n \"╰─────────────────────────────────────────────╯\",\n];\nconst MIN_INNER_WIDTH = 45;\n\nfunction charDisplayWidth(ch: string): number {\n const cp = ch.codePointAt(0)!;\n const wide =\n (cp >= 0x1100 && cp <= 0x115f) || // Hangul Jamo\n (cp >= 0x2e80 && cp <= 0xa4cf) || // CJK radicals .. Yi syllables\n (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul syllables\n (cp >= 0xf900 && cp <= 0xfaff) || // CJK compatibility ideographs\n (cp >= 0xfe30 && cp <= 0xfe4f) || // CJK compatibility forms\n (cp >= 0xff00 && cp <= 0xff60) || // fullwidth forms\n (cp >= 0xffe0 && cp <= 0xffe6) || // halfwidth/fullwidth forms\n cp >= 0x20000; // CJK extensions and beyond\n return wide ? 2 : 1;\n}\n\nexport function displayWidth(s: string): number {\n let w = 0;\n for (const ch of s) w += charDisplayWidth(ch);\n return w;\n}\n\n/** Pad s with trailing spaces to a DISPLAY width (wide chars count as two\n * columns), keeping bar-chart columns aligned for CJK category labels.\n * Identical to String.prototype.padEnd for ASCII input. */\nexport function padLabel(s: string, width: number): string {\n const dw = displayWidth(s);\n return dw >= width ? s : s + \" \".repeat(width - dw);\n}\n\n/** Decorative title box, width-aware so CJK titles stay aligned (wide chars\n * occupy two terminal columns). The exact default title renders the legacy\n * fixed box; any other title gets a computed box that widens past\n * MIN_INNER_WIDTH when the title is long. */\nexport function renderTitleBox(title: string): string[] {\n if (title === DEFAULT_PANEL_LABELS.title) return LEGACY_TITLE_BOX;\n const dw = displayWidth(title);\n const inner = Math.max(MIN_INNER_WIDTH, dw + 2);\n const padL = Math.floor((inner - dw) / 2);\n const padR = inner - dw - padL;\n return [\"╭\" + \"─\".repeat(inner) + \"╮\", `│${\" \".repeat(padL)}${title}${\" \".repeat(padR)}│`, \"╰\" + \"─\".repeat(inner) + \"╯\"];\n}\n","import { defaultCountTokens } from \"../tokenize.js\";\nimport { formatRanges } from \"../nudge-text.js\";\nimport type { CompressionState, NudgeDecision } from \"../types.js\";\nimport { formatCompactTokens } from \"./format.js\";\nimport { topicFallback } from \"./topic.js\";\nimport { viableRanges } from \"../viable.js\";\nimport { cacheHitStats, formatHitRate, type CacheUsageSample } from \"./cache.js\";\nimport { fill, padLabel, renderTitleBox, resolvePanelLabels, type PanelLabels } from \"./labels.js\";\n\nexport interface StatusPanelInput {\n /** Adapter identifier for the header, e.g. \"billion-context-omp@0.1.6\".\n * Omit to hide the version line. */\n version?: string;\n /** Host session accounting — the SAME number the host footer displays.\n * It includes compressed originals (summaries stay in the window), so it\n * shrinks slower than the sent view when compression prunes the\n * per-request projection. */\n tokenCount: number;\n /** Measured token count of the host system prompt (host-specific to\n * obtain; the kernel breakdown does not see it). */\n systemPromptTokens: number;\n /** Kernel state (blocks drive the Blocks section). */\n state: CompressionState;\n /** The nudge decision from core.processTurn for this turn, if any. The\n * panel applies the viability filter to compressibleRanges itself. */\n nudge: NudgeDecision | undefined;\n /** Configured model context window, in tokens. */\n modelContextLimit: number;\n /** Estimate of the FULL (unpruned) core-message projection, computed\n * with the SAME countTokens the core uses (kernel default = CJK-aware\n * defaultCountTokens) — the same estimation scale as the kernel\n * breakdown. When provided, the panel derives `Session-only` on that\n * scale (unpruned − sent). Without it the line is omitted: subtracting\n * the host's provider-scale number from an estimate-scale number\n * invents a third, meaningless scale (issue #18 \"看板统计的和拆分的有差异\"). */\n unprunedTokens?: number;\n /** Localized display labels; every key optional, per-key fallback to the\n * English defaults (DEFAULT_PANEL_LABELS). Display-only — model-facing\n * text is unaffected. */\n labels?: Partial<PanelLabels>;\n /** Per-request prompt-cache usage (from assistant messages' provider-\n * reported `usage`). Requests without cache reporting are excluded by\n * cacheHitStats; when no counted request remains, the section is\n * omitted entirely. Omit the field to hide the section. */\n cacheUsages?: ReadonlyArray<CacheUsageSample>;\n /** Token formatter override (defaults to formatCompactTokens). */\n fmtTokens?: (n: number) => string;\n}\n\nfunction bar(value: number, total: number, width: number = 20): string {\n if (total === 0) return \"\";\n const filled = Math.max(0, Math.min(width, Math.round((value / total) * width)));\n return \"█\".repeat(filled) + \"░\".repeat(width - filled);\n}\n\n/** Render the /acp status panel. Three token numbers, each labeled with\n * its own scale, never mixed in arithmetic:\n * - Session accounting (host footer scale): the host's reported context\n * size INCLUDING compressed originals (summaries stay in the window), so\n * it shrinks slower than the sent view when compression prunes the\n * per-request projection.\n * - Sent view (estimated, kernel countTokens scale): what actually\n * reaches the LLM after compression (kernel's classification over the\n * pruned projection + measured system prompt). This is the number\n * compression controls.\n * - Session-only (estimated, kernel countTokens scale): unpruned\n * projection − sent view; the compressed originals pruned from every\n * request.\n * Subtracting the host number from an estimate produced numbers that\n * reconciled with neither scale (\"Framework 390K\", \"session-only 29k vs\n * 112k compressed\") — that is what issue #18 reported. */\nexport function buildStatusPanel(input: StatusPanelInput): string {\n const { tokenCount, state, nudge, modelContextLimit } = input;\n const L = resolvePanelLabels(input.labels);\n const fmt = input.fmtTokens ?? formatCompactTokens;\n const bd = nudge?.contextBreakdown;\n const limit = modelContextLimit;\n const classified = bd ? bd.system + bd.tool + bd.summaries + bd.code + bd.text : 0;\n const systemPromptTokens = input.systemPromptTokens;\n const sentTotal = classified + systemPromptTokens;\n // Same-scale derivation only: both sides use the core's countTokens\n // estimate (kernel default = CJK-aware defaultCountTokens). The host\n // footer's tokenCount (provider-anchored, session-tree) is displayed as\n // its own line and never fed into an arithmetic difference with these.\n const sessionOnly = input.unprunedTokens !== undefined ? Math.max(0, input.unprunedTokens - sentTotal) : 0;\n const displayTotal = tokenCount;\n const displayPct = limit > 0 ? Math.round((displayTotal / limit) * 100) : 0;\n const sentPct = limit > 0 ? Math.round((sentTotal / limit) * 100) : 0;\n const activeBlocksList = state.blocks.filter((b) => b.active);\n const totalBlocksList = state.blocks;\n\n const lines: string[] = [];\n\n lines.push(...renderTitleBox(L.title));\n if (input.version) lines.push(input.version);\n lines.push(\"\");\n lines.push(fill(L.context, { pct: displayPct, used: fmt(displayTotal), limit: fmt(limit) }));\n\n if (nudge && bd) {\n const growth = bd.growth;\n if (growth > 0 && displayTotal > 0) {\n lines.push(fill(L.growth, { growth: fmt(growth) }));\n }\n lines.push(\"\");\n let sentLine = fill(L.sent, { sent: fmt(sentTotal) });\n if (limit > 0) sentLine += fill(L.sentOfLimit, { pct: sentPct });\n lines.push(sentLine);\n if (input.unprunedTokens !== undefined && sessionOnly > 0) {\n lines.push(fill(L.sessionOnly, { only: fmt(sessionOnly) }));\n }\n lines.push(\"\");\n lines.push(L.breakdown);\n\n const categories: Array<{ label: string; value: number }> = [\n { label: L.catTool, value: bd.tool },\n { label: L.catSysPrompt, value: systemPromptTokens },\n { label: L.catText, value: bd.text },\n { label: L.catCode, value: bd.code },\n { label: L.catSummaries, value: bd.summaries },\n ];\n\n for (const cat of categories) {\n if (cat.value <= 0) continue;\n const pct = sentTotal > 0 ? Math.round((cat.value / sentTotal) * 100) : 0;\n const b = bar(cat.value, sentTotal);\n lines.push(` ${padLabel(cat.label, 10)} ${b} ${String(pct).padStart(3)}% ${fmt(cat.value)}`);\n }\n }\n\n if (input.cacheUsages) {\n const cache = cacheHitStats(input.cacheUsages);\n if (cache.requests > 0 && cache.session !== undefined && cache.last !== undefined) {\n lines.push(\"\");\n lines.push(\n fill(L.promptCache, {\n last: formatHitRate(cache.last),\n session: formatHitRate(cache.session),\n read: fmt(cache.cacheRead),\n billed: fmt(cache.billedPrompt),\n requests: cache.requests,\n }),\n );\n }\n }\n\n lines.push(\"\");\n\n if (nudge) {\n if (nudge.shouldInject) {\n const tierInfo = nudge.tier ? fill(L.nudgeTierInfo, { tier: nudge.tier }) : \"\";\n lines.push(fill(L.nudgeActive, { tierInfo, reason: nudge.reason }));\n } else {\n lines.push(fill(L.nudgeIdle, { reason: nudge.reason }));\n }\n }\n\n const ranges = viableRanges(nudge?.compressibleRanges ?? []);\n const protectedRanges = nudge?.protectedRanges ?? [];\n if (ranges.length > 0 || protectedRanges.length > 0) {\n lines.push(\"\");\n lines.push(formatRanges(ranges, protectedRanges));\n }\n\n if (activeBlocksList.length > 0) {\n lines.push(\"\");\n lines.push(fill(L.blocksHeader, { active: activeBlocksList.length, total: totalBlocksList.length, tokens: fmt(state.stats.tokensCompressed) }));\n for (const b of activeBlocksList) {\n const topic = b.topic ? `: ${b.topic}` : `: ${topicFallback(b.summary || \"\")}`;\n const summaryTok = defaultCountTokens(b.summary || \"\");\n const origTok = b.compressedTokens > 0 ? b.compressedTokens : summaryTok;\n lines.push(` [${b.blockId}] T${b.tier} ${fmt(origTok)}→${fmt(summaryTok)}${topic}`);\n }\n } else if (totalBlocksList.length > 0) {\n lines.push(\"\");\n lines.push(fill(L.blocksHeader, { active: 0, total: totalBlocksList.length, tokens: fmt(state.stats.tokensCompressed) }));\n } else {\n lines.push(\"\");\n lines.push(L.blocksNone);\n }\n\n lines.push(\"\");\n lines.push(L.tagVisibility);\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;AAKO,SAAS,cAAc,SAAyB;AACrD,QAAM,QAAQ,QAAQ,MAAM,OAAO,EAAE,CAAC,KAAK;AAC3C,QAAM,IAAI,MAAM,KAAK,EAAE,QAAQ,WAAW,EAAE,EAAE,KAAK;AACnD,SAAO,EAAE,UAAU,KAAK,IAAI,GAAG,YAAY,GAAG,EAAE,EAAE,QAAQ,CAAC;AAC7D;;;ACNO,SAAS,oBAAoB,OAAuB;AACzD,MAAI,QAAQ,IAAM,QAAO,MAAM,SAAS;AACxC,MAAI,QAAQ,IAAO,QAAO,IAAI,QAAQ,KAAM,QAAQ,CAAC,CAAC;AACtD,MAAI,QAAQ,IAAS,QAAO,GAAG,KAAK,MAAM,QAAQ,GAAI,CAAC;AACvD,MAAI,QAAQ,IAAU,QAAO,IAAI,QAAQ,KAAS,QAAQ,CAAC,CAAC;AAC5D,SAAO,GAAG,KAAK,MAAM,QAAQ,GAAO,CAAC;AACvC;;;ACwBA,SAAS,IAAI,GAAoB;AAC/B,SAAO,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,IAAI,IAAI,IAAI;AACpE;AAGO,SAAS,cAAc,QAAsD;AAClF,MAAI,YAAY;AAChB,MAAI,eAAe;AACnB,MAAI,WAAW;AACf,MAAI;AACJ,aAAW,KAAK,QAAQ;AACtB,UAAM,OAAO,IAAI,GAAG,SAAS;AAC7B,UAAM,QAAQ,IAAI,GAAG,UAAU;AAC/B,UAAM,QAAQ,IAAI,GAAG,KAAK;AAE1B,QAAI,OAAO,SAAS,EAAG;AACvB,UAAM,QAAQ,OAAO,QAAQ;AAC7B,QAAI,SAAS,EAAG;AAChB,iBAAa;AACb,oBAAgB;AAChB,gBAAY;AACZ,WAAO,OAA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AA,EAC1H,OAAO;AACL,UAAM,KAAK,EAAE;AACb,UAAM,KAAK,EAAE,UAAU;AAAA,EACzB;AAEA,QAAM,KAAK,EAAE;AACb,QAAM,KAAK,EAAE,aAAa;AAE1B,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** Display labels for buildStatusPanel. The English defaults below are the
|
|
2
|
+
* key source of truth; hosts pass Partial<PanelLabels> to localize the panel
|
|
3
|
+
* (billion-context-pi issue #153). This is a DISPLAY-ONLY surface: these
|
|
4
|
+
* strings render in the terminal and never reach the model, so translating
|
|
5
|
+
* them cannot affect compression/nudge behavior.
|
|
6
|
+
*
|
|
7
|
+
* Templates use `{name}` placeholders filled by fill(). Keys omitted by a
|
|
8
|
+
* host pack fall back to the English default per key (partial packs degrade
|
|
9
|
+
* gracefully instead of failing wholesale). */
|
|
10
|
+
export interface PanelLabels {
|
|
11
|
+
/** Title rendered inside the decorative box. */
|
|
12
|
+
title: string;
|
|
13
|
+
/** Params: pct (number), used / limit (formatted token counts). */
|
|
14
|
+
context: string;
|
|
15
|
+
/** Params: growth (formatted). Line rendered only when growth > 0. */
|
|
16
|
+
growth: string;
|
|
17
|
+
/** Params: sent (formatted). */
|
|
18
|
+
sent: string;
|
|
19
|
+
/** Params: pct (number). Appended to the sent line only when a context
|
|
20
|
+
* limit is configured; omit the placeholder in a pack to drop it. */
|
|
21
|
+
sentOfLimit: string;
|
|
22
|
+
/** Params: only (formatted). Line rendered only when unprunedTokens is
|
|
23
|
+
* provided and the derived value is positive. */
|
|
24
|
+
sessionOnly: string;
|
|
25
|
+
breakdown: string;
|
|
26
|
+
catTool: string;
|
|
27
|
+
catSysPrompt: string;
|
|
28
|
+
catText: string;
|
|
29
|
+
catCode: string;
|
|
30
|
+
catSummaries: string;
|
|
31
|
+
/** Params: last / session (hit-rate strings), read / billed (formatted),
|
|
32
|
+
* requests (number). */
|
|
33
|
+
promptCache: string;
|
|
34
|
+
/** Params: tierInfo (string, empty when no tier), reason (verbatim model-
|
|
35
|
+
* facing text — keep it in your template verbatim). */
|
|
36
|
+
nudgeActive: string;
|
|
37
|
+
/** Params: tier (number). */
|
|
38
|
+
nudgeTierInfo: string;
|
|
39
|
+
/** Params: reason (verbatim model-facing text). */
|
|
40
|
+
nudgeIdle: string;
|
|
41
|
+
/** Params: active / total (numbers), tokens (formatted). Used for both the
|
|
42
|
+
* active and zero-active block counts. */
|
|
43
|
+
blocksHeader: string;
|
|
44
|
+
/** Rendered when no blocks exist at all. */
|
|
45
|
+
blocksNone: string;
|
|
46
|
+
tagVisibility: string;
|
|
47
|
+
}
|
|
48
|
+
export declare const DEFAULT_PANEL_LABELS: PanelLabels;
|
|
49
|
+
/** Merge a partial label pack over the English defaults, ignoring entries
|
|
50
|
+
* whose value is not a string (explicit `undefined` from a config merge,
|
|
51
|
+
* `null`, …). A plain `{ ...defaults, ...pack }` spread lets one undefined
|
|
52
|
+
* key blank out its default and crash the display-width renderers. */
|
|
53
|
+
export declare function resolvePanelLabels(labels?: Partial<PanelLabels>): PanelLabels;
|
|
54
|
+
/** Substitute `{name}` placeholders from params. Unknown placeholders are
|
|
55
|
+
* left intact so a typo in a host pack is visible on screen instead of
|
|
56
|
+
* silently dropping information. */
|
|
57
|
+
export declare function fill(template: string, params: Record<string, string | number>): string;
|
|
58
|
+
export declare function displayWidth(s: string): number;
|
|
59
|
+
/** Pad s with trailing spaces to a DISPLAY width (wide chars count as two
|
|
60
|
+
* columns), keeping bar-chart columns aligned for CJK category labels.
|
|
61
|
+
* Identical to String.prototype.padEnd for ASCII input. */
|
|
62
|
+
export declare function padLabel(s: string, width: number): string;
|
|
63
|
+
/** Decorative title box, width-aware so CJK titles stay aligned (wide chars
|
|
64
|
+
* occupy two terminal columns). The exact default title renders the legacy
|
|
65
|
+
* fixed box; any other title gets a computed box that widens past
|
|
66
|
+
* MIN_INNER_WIDTH when the title is long. */
|
|
67
|
+
export declare function renderTitleBox(title: string): string[];
|
|
68
|
+
//# sourceMappingURL=labels.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"labels.d.ts","sourceRoot":"","sources":["../../src/panel/labels.ts"],"names":[],"mappings":"AAAA;;;;;;;;gDAQgD;AAChD,MAAM,WAAW,WAAW;IAC1B,gDAAgD;IAChD,KAAK,EAAE,MAAM,CAAC;IACd,mEAAmE;IACnE,OAAO,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,gCAAgC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb;0EACsE;IACtE,WAAW,EAAE,MAAM,CAAC;IACpB;sDACkD;IAClD,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB;6BACyB;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB;4DACwD;IACxD,WAAW,EAAE,MAAM,CAAC;IACpB,6BAA6B;IAC7B,aAAa,EAAE,MAAM,CAAC;IACtB,mDAAmD;IACnD,SAAS,EAAE,MAAM,CAAC;IAClB;+CAC2C;IAC3C,YAAY,EAAE,MAAM,CAAC;IACrB,4CAA4C;IAC5C,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,eAAO,MAAM,oBAAoB,EAAE,WAoBlC,CAAC;AAEF;;;uEAGuE;AACvE,wBAAgB,kBAAkB,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,WAAW,CAQ7E;AAED;;qCAEqC;AACrC,wBAAgB,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,GAAG,MAAM,CAEtF;AAyBD,wBAAgB,YAAY,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAI9C;AAED;;4DAE4D;AAC5D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAGzD;AAED;;;8CAG8C;AAC9C,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAOtD"}
|
package/dist/panel/panel.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { CompressionState, NudgeDecision } from "../types.js";
|
|
2
2
|
import { type CacheUsageSample } from "./cache.js";
|
|
3
|
+
import { type PanelLabels } from "./labels.js";
|
|
3
4
|
export interface StatusPanelInput {
|
|
4
5
|
/** Adapter identifier for the header, e.g. "billion-context-omp@0.1.6".
|
|
5
6
|
* Omit to hide the version line. */
|
|
@@ -27,6 +28,10 @@ export interface StatusPanelInput {
|
|
|
27
28
|
* the host's provider-scale number from an estimate-scale number
|
|
28
29
|
* invents a third, meaningless scale (issue #18 "看板统计的和拆分的有差异"). */
|
|
29
30
|
unprunedTokens?: number;
|
|
31
|
+
/** Localized display labels; every key optional, per-key fallback to the
|
|
32
|
+
* English defaults (DEFAULT_PANEL_LABELS). Display-only — model-facing
|
|
33
|
+
* text is unaffected. */
|
|
34
|
+
labels?: Partial<PanelLabels>;
|
|
30
35
|
/** Per-request prompt-cache usage (from assistant messages' provider-
|
|
31
36
|
* reported `usage`). Requests without cache reporting are excluded by
|
|
32
37
|
* cacheHitStats; when no counted request remains, the section is
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"panel.d.ts","sourceRoot":"","sources":["../../src/panel/panel.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAInE,OAAO,EAAgC,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"panel.d.ts","sourceRoot":"","sources":["../../src/panel/panel.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAInE,OAAO,EAAgC,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACjF,OAAO,EAAsD,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAEnG,MAAM,WAAW,gBAAgB;IAC/B;yCACqC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;kCAG8B;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB;yDACqD;IACrD,kBAAkB,EAAE,MAAM,CAAC;IAC3B,sDAAsD;IACtD,KAAK,EAAE,gBAAgB,CAAC;IACxB;2EACuE;IACvE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,kDAAkD;IAClD,iBAAiB,EAAE,MAAM,CAAC;IAC1B;;;;;;yEAMqE;IACrE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;8BAE0B;IAC1B,MAAM,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IAC9B;;;gEAG4D;IAC5D,WAAW,CAAC,EAAE,aAAa,CAAC,gBAAgB,CAAC,CAAC;IAC9C,kEAAkE;IAClE,SAAS,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;CACnC;AAQD;;;;;;;;;;;;;;;2DAe2D;AAC3D,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAiHhE"}
|
package/dist/prompts.d.ts
CHANGED
|
@@ -43,11 +43,6 @@ export interface ResolvePromptsOptions {
|
|
|
43
43
|
* malformed partial never degrades the canonical rules. Resolve once at host
|
|
44
44
|
* startup, then pass the resulting {@link Prompts} to {@link renderNudgeText}
|
|
45
45
|
* and to the adapter's system-prompt composition so both layers stay consistent.
|
|
46
|
-
*
|
|
47
|
-
* To keep guidance in the system prompt but drop it from every nudge (hosts that
|
|
48
|
-
* deliver these texts once at startup), do NOT override fields here — that would
|
|
49
|
-
* change both surfaces at once. Pass `{ includeGuidance: false }` to
|
|
50
|
-
* {@link renderNudgeText} instead; the system-prompt path is unaffected by it.
|
|
51
46
|
*/
|
|
52
47
|
export declare function resolvePrompts(overrides?: Partial<Prompts>, options?: ResolvePromptsOptions): Prompts;
|
|
53
48
|
//# sourceMappingURL=prompts.d.ts.map
|
package/dist/prompts.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAOA;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,OAAO;IACtB,gFAAgF;IAChF,kBAAkB,EAAE,MAAM,CAAC;IAC3B,6DAA6D;IAC7D,kBAAkB,EAAE,MAAM,CAAC;IAC3B,2DAA2D;IAC3D,iBAAiB,EAAE,MAAM,CAAC;IAC1B,kEAAkE;IAClE,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,eAAO,MAAM,cAAc,EAAE,OAKhB,CAAC;AAEd,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED
|
|
1
|
+
{"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAOA;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,OAAO;IACtB,gFAAgF;IAChF,kBAAkB,EAAE,MAAM,CAAC;IAC3B,6DAA6D;IAC7D,kBAAkB,EAAE,MAAM,CAAC;IAC3B,2DAA2D;IAC3D,iBAAiB,EAAE,MAAM,CAAC;IAC1B,kEAAkE;IAClE,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,eAAO,MAAM,cAAc,EAAE,OAKhB,CAAC;AAEd,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAC5B,SAAS,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,EAC5B,OAAO,GAAE,qBAA0B,GAClC,OAAO,CAkBT"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tokenize.ts","../src/compression-rules.ts","../src/prompts.ts","../src/nudge-text.ts","../src/viable.ts","../src/truncate.ts"],"sourcesContent":["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 *\n * To keep guidance in the system prompt but drop it from every nudge (hosts that\n * deliver these texts once at startup), do NOT override fields here — that would\n * change both surfaces at once. Pass `{ includeGuidance: false }` to\n * {@link renderNudgeText} instead; the system-prompt path is unaffected by it.\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, BlockSpan } from \"./types.js\";\nimport { defaultPrompts } from \"./prompts.js\";\nimport type { Prompts } from \"./prompts.js\";\n\nexport type NudgeVoice = \"gentle\" | \"emergency\";\n\nexport interface NudgePromptSections {\n efficiencyNote?: string | null;\n emergencyHeader?: string | null;\n t2Guidance?: string | null;\n t3Guidance?: string | null;\n}\n\nexport interface RenderedNudge {\n voice: NudgeVoice;\n text: string;\n}\n\nexport interface RenderNudgeOptions extends NudgePromptSections {\n /**\n * Embed the load-bearing guidance texts (compressPhilosophy, howToCompressRules,\n * and the active tier's distill/condense rules) in the nudge body. Defaults to\n * true, so existing callers render byte-identical output. Set to false when the\n * host already delivers these same texts once via its system prompt or tool\n * descriptions — re-billing them on every injection is pure repetition. Only\n * the four guidance texts are dropped; per-injection dynamic content\n * (breakdown, trigger line, ranges, tier target blocks) survives. An explicit\n * section override above always wins verbatim, independently of this flag.\n */\n includeGuidance?: boolean;\n}\n\nfunction efficiencyNote(prompts: Prompts, sections: NudgePromptSections, includeGuidance: boolean): string | null {\n if (sections.efficiencyNote !== undefined) return sections.efficiencyNote;\n const note = \"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 return includeGuidance ? `${note}\\n\\n${prompts.compressPhilosophy}` : note;\n}\n\nfunction emergencyHeader(prompts: Prompts, sections: NudgePromptSections, includeGuidance: boolean): string | null {\n if (sections.emergencyHeader !== undefined) return sections.emergencyHeader;\n const header = \"⚠️ Context limit reached — compress now. Prioritize consumed tool outputs.\";\n return includeGuidance ? `${header}\\n\\n${prompts.compressPhilosophy}` : header;\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\nconst BLOCK_MAP_MAX_SHOWN = 8;\n\nfunction formatBlockMap(spans: BlockSpan[]): string {\n if (spans.length === 0) return \"\";\n const hidden = Math.max(0, spans.length - BLOCK_MAP_MAX_SHOWN);\n const shown = hidden > 0 ? spans.slice(-BLOCK_MAP_MAX_SHOWN) : spans;\n const items = shown.map(\n (s) => `${s.blockId}=${s.startRef}–${s.endRef}${s.tier > 1 ? ` t${s.tier}` : \"\"}`,\n );\n const prefix = hidden > 0 ? `…+${hidden} older · ` : \"\";\n return `Active blocks (${spans.length}): ${prefix}${items.join(\" · \")}`;\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 startPos: number; endPos: number;\n count: number; tokens: number; userMsgs: 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 startPos: r.startIndex ?? refNum(r.startRef), endPos: r.endIndex ?? refNum(r.endRef),\n count: r.count, tokens: r.tokens, userMsgs: r.userMsgs ?? 0, 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 startPos: r.startIndex ?? refNum(r.startRef), endPos: r.endIndex ?? refNum(r.endRef),\n count: r.count, tokens: r.tokens, userMsgs: 0, toolPct: 0, textPct: 0,\n compressibleTokens: 0, compressibleCount: 0,\n protectedTokens: r.tokens, protectedCount: r.count, protectedTools: [...r.tools], dangerous: false,\n });\n }\n // Order/merge by POSITION, never ref number: refs can be non-monotonic vs array\n // order (subagent interleaving / mid-array summary nodes), and ref-number merging\n // then yields endpoints resolveBoundaries collapses to a tiny slice (#887).\n entries.sort((a, b) => a.startPos - b.startPos || a.startNum - b.startNum);\n // Merge positionally adjacent/overlapping ranges (gap ≤ 1 slot).\n const merged: Merged[] = [];\n for (const e of entries) {\n const last = merged[merged.length - 1];\n if (last && e.startPos <= last.endPos + 1) {\n last.endRef = e.endRef;\n last.endNum = Math.max(last.endNum, e.endNum);\n last.endPos = Math.max(last.endPos, e.endPos);\n last.count += e.count;\n last.tokens += e.tokens;\n last.userMsgs += e.userMsgs;\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 userNote = (n: number): string =>\n n > 0 ? ` · ${n} user msg${n > 1 ? \"s\" : \"\"}` : \"\";\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(\", \")}]${userNote(e.userMsgs)}${suffix}`;\n }\n return ` ${e.startRef}–${e.endRef} ${e.count} msgs ${formatK(e.tokens)} [tool ${e.toolPct}% | text ${e.textPct}%]${userNote(e.userMsgs)}${suffix}`;\n });\n return `Compressible ranges (${merged.length}, oldest first):\\n${lines.join(\"\\n\")}`;\n}\n\nconst DEFAULT_T2_GUIDANCE = `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\nconst DEFAULT_T3_GUIDANCE = `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\nfunction tierGuidance(tier: 2 | 3, sections: NudgePromptSections): string | null {\n const value = tier === 2 ? sections.t2Guidance : sections.t3Guidance;\n if (value !== undefined) return value;\n return tier === 2 ? DEFAULT_T2_GUIDANCE : DEFAULT_T3_GUIDANCE;\n}\n\nfunction compact(parts: string[]): string[] {\n const out: string[] = [];\n let pendingBlank = false;\n for (const p of parts) {\n if (p === \"\") {\n pendingBlank = true;\n continue;\n }\n if (pendingBlank && out.length > 0) out.push(\"\");\n pendingBlank = false;\n out.push(p);\n }\n return out;\n}\n\nexport function renderNudgeText(\n decision: NudgeDecision,\n prompts: Prompts = defaultPrompts,\n options: RenderNudgeOptions = {},\n): RenderedNudge {\n const includeGuidance = options.includeGuidance ?? true;\n const breakdownStr = formatBreakdown(decision.contextBreakdown);\n const rangesStr = formatRanges(decision.compressibleRanges, decision.protectedRanges ?? []);\n const blockMapStr = formatBlockMap(decision.activeBlockSpans ?? []);\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 const guidance = tierGuidance(isT2 ? 2 : 3, options);\n const head = efficiencyNote(prompts, options, includeGuidance);\n const parts: string[] = [\n ...(head === null ? [] : [head]),\n \"\",\n breakdownStr,\n \"\",\n triggerLine,\n ...(guidance === null ? [] : [guidance]),\n blockList,\n `Example: compress({ content: [{ startId: \"${startId}\", endId: \"${endId}\", summary: \"...\" }] })`,\n ];\n if (includeGuidance) {\n parts.push(\"\", prompts.howToCompressRules, \"\", isT2 ? prompts.tier2DistillRules : prompts.tier3CondenseRules);\n }\n return { voice, text: compact(parts).join(\"\\n\") };\n }\n\n if (isEmergency) {\n const head = emergencyHeader(prompts, options, includeGuidance);\n const parts: string[] = [\n ...(head === null ? [] : [head]),\n \"\",\n breakdownStr,\n ];\n if (includeGuidance) {\n parts.push(\"\", prompts.howToCompressRules);\n }\n parts.push(\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 ...(blockMapStr ? [\"\", blockMapStr] : []),\n );\n return { voice: \"emergency\", text: compact(parts).join(\"\\n\") };\n }\n\n const gentleHead = efficiencyNote(prompts, options, includeGuidance);\n const parts: string[] = [\n ...(gentleHead === null ? [] : [gentleHead]),\n \"\",\n breakdownStr,\n ];\n if (includeGuidance) {\n parts.push(\"\", prompts.howToCompressRules);\n }\n parts.push(\n \"\",\n rangesStr,\n ...(blockMapStr ? [\"\", blockMapStr] : []),\n \"\",\n `💡 Compress all ranges in one call (pass multiple content entries: \\`content: [{...}, {...}]\\`).`,\n );\n return { voice: \"gentle\", text: compact(parts).join(\"\\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);\n}\n","// UTF-16-safe truncation. A plain slice can land between the two code units\n// of an astral character (emoji, CJK ext-B+), stranding a lone surrogate:\n// JSON.stringify escapes it (\\ud83e), and gateways that re-encode request\n// bodies to strict UTF-8 then throw UnicodeEncodeError on every retry\n// (ranxianglei/billion-context#816) — a deterministic poison that never heals.\n\nfunction isHighSurrogate(c: number): boolean {\n return c >= 0xd800 && c <= 0xdbff;\n}\n\nfunction isLowSurrogate(c: number): boolean {\n return c >= 0xdc00 && c <= 0xdfff;\n}\n\n/** At most maxUnits code units; never ends on a stranded high surrogate. */\nexport function clampPrefix(text: string, maxUnits: number): string {\n const cut = Math.min(maxUnits, text.length);\n if (cut > 0 && isHighSurrogate(text.charCodeAt(cut - 1))) return text.slice(0, cut - 1);\n return text.slice(0, cut);\n}\n\n/** A [start, end) window with both edges snapped off surrogate pairs. */\nexport function clampWindow(text: string, start: number, end: number): string {\n let s = Math.max(0, Math.min(start, text.length));\n let e = Math.min(text.length, Math.max(s, end));\n if (s > 0 && isLowSurrogate(text.charCodeAt(s))) s += 1;\n if (e > s && isHighSurrogate(text.charCodeAt(e - 1))) e -= 1;\n return text.slice(s, Math.max(s, e));\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;AAE9B,IAAMA,WAAU,cAAc,YAAY,GAAG;AAEtC,SAAS,mBAAmB,MAAsB;AACvD,MAAI,CAAC,KAAM,QAAO;AAIlB,QAAM,MAAM,KAAK,MAAM,4CAA4C;AACnE,QAAM,WAAW,KAAK,UAAU;AAChC,SAAO,WAAW,KAAK,MAAM,KAAK,SAAS,YAAY,CAAC;AAC1D;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