@logictan/dsh-verbatim-compaction 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -62,13 +62,13 @@
62
62
 
63
63
  所以提取的材料是三段:用户请求(逐字)、助手正文(逐字)、工具轨迹(每条调用的 `description`,失败的调用另记一行首行错误)。模型输出固定的四节:`## Asked` / `## Did` / `## Concluded` / `## Overturned`。
64
64
 
65
- 空节直接删掉,不留占位。占位符既包括 `(none)`/`n/a`/`无`,也包括模型爱写的 `未提问。`;判据同时覆盖标题行(`## Asked`、裸写 `Asked`)和行内形式(`- Did: …`、`**Asked**:…`)——两种形式会混在同一个块里。中文标签(`问:`/`做:`/`结论:`/`推翻:`)同样识别:模型对中文会话会直接改用中文标签,只认英文时 `Asked` 不会被移到最后、空节也不会被清。判据同时接受 `## Asked` 和裸写 `Asked`——实测模型有时不带 `##`,只认 `^#{1,6}` 会让 `Concluded\n- (none)` 原样留在摘要里。实测一份真实提取块里 `## Asked` 和 `## Overturned` 都是 `(none)`,删掉后 312 → 271 字符;按 130 轮算,这些占位合计约 900 token 只是在记录「什么都没发生」。清理在代码里做(`pruneEmptySections`),不只依赖提示词——模型仍写了 `(none)` 也不会白花 token。判据是整节每一行去掉项目符号后都只是 `(none)` / `none` / `n/a` / `无` 之类的占位;`none of the tests passed`、`无法连接,改用代理` 这类真内容照原样保留。
65
+ 空节直接不出现:「没有内容」是一个空数组,不是需要事后识别的占位符。字段化之前是自由 markdown,模型写 `## Overturned\n- (none)` 就得在代码里再认一遍占位符,实测一份真实提取块里 `## Asked` 和 `## Overturned` 都是 `(none)`,删掉后 312 → 271 字符;按 130 轮算,这些占位合计约 900 token 只是在记录「什么都没发生」。现在这类占位在解析阶段就被滤掉,不再有一个专门的清理函数。`none of the tests passed`、`无法连接,改用代理` 这类真内容照原样保留。
66
66
 
67
67
  `## Asked` 记的是「**助手**向**用户**提了什么、给了哪些选项」。这一节最容易错成「把用户请求改写一遍」——真实一次压缩里,模型把用户那段中文请求翻成英文塞进了 `Asked`,而用户原话就在它上面逐字抄着,同一件事写了两遍。
68
68
 
69
69
  原因之一在材料标签:原来写 `USER REQUEST:`,模型有理由读成「这一轮问了什么」,现在改成 `USER INSTRUCTION (already in the digest verbatim; never copy it into Asked)`。另一部分靠指令本身——`## Asked` 的定义写明「助手问、用户答」,并注明照抄用户请求是这一节最常见的出错方式。
70
70
 
71
- 正文为空的轮次(那个真实案例有 96 条助手消息、150 次工具调用却只有 156 字符正文)本来就没有提问可记,`## Asked` 和 `## Did` 一样走 `pruneEmptySections` 整节省略,不需要单独规则。实测 123 条真人消息里 43 条(35%)不超过 12 个字符——`3`、`1`、`同意`、`做`、`继续`——而 46% 是在回答上一轮助手的提问。只逐字保留「3」而不保留它在回答什么问题,等于记下一个决定却没记下决定的是什么。
71
+ 正文为空的轮次(那个真实案例有 96 条助手消息、150 次工具调用却只有 156 字符正文)本来就没有提问可记,`## Asked` 和 `## Did` 一样整节省略,不需要单独规则。实测 123 条真人消息里 43 条(35%)不超过 12 个字符——`3`、`1`、`同意`、`做`、`继续`——而 46% 是在回答上一轮助手的提问。只逐字保留「3」而不保留它在回答什么问题,等于记下一个决定却没记下决定的是什么。
72
72
 
73
73
  模型用的是会话自己的路由(`session.requestHeader()?.config`),和宿主原生压缩同一个取法,不需要单独配置凭据。
74
74
 
@@ -76,12 +76,22 @@
76
76
 
77
77
  - **失败信号只认 `data.isError`**。曾用 `/error/i` 匹配序列化文本,347 条成功结果全部命中(工具输出里常有 "error" 字样),模型据此报告「整轮失败」。测试里有一条专门钉住这个坑。
78
78
  - **工具调用从 `assistant/message` 的 block 里取**。日志里没有独立的 `tool/call` 事件类型,按它过滤会一条都取不到。
79
- - **提取失败就退回逐字正文**。模型不可达、超时、输出为空时,该轮保留原来的助手正文;压缩本身不能因此失败,否则会话死于上下文溢出,比丢细节更糟。降级是逐轮的:一批里某一轮没答,只有那一轮退回正文。
79
+ - **提取失败就退回逐字正文**。模型不可达、超时、输出为空时,该轮保留原来的助手正文;压缩本身不能因此失败,否则会话死于上下文溢出,比丢细节更糟。降级是逐轮的:一批里某一轮没答,只有那一轮退回正文。**但降级不再无声**:整批拿不到可用 JSON、或单槽位在令牌上限被截断,都会打一条 `verbatim-compaction:` 开头的 warn,写明受影响的 slot key。没有这条日志时,插件退化成纯逐字摘要这件事在运行期完全不可观测——这正是「JSON 经常不生效却查不到」的成因。
80
+
81
+ 提取调用的 `maxTokens` **在每槽位预算之外另加一笔固定的思考余量**(`EXTRACT_TOKENS_PER_TURN × 槽位数 + EXTRACT_THINKING_RESERVE_TOKENS`)。`maxTokens` 把思考与正文算在一起,而思考是**每次调用的固定开销,不随批次变小而变小**——这正是「按槽位线性给上限」必然失败的原因。对真实路由(deepseek-flash,真实量级材料)实测:单槽位按旧公式 `220 × 1` 给上限,**4 次全部解析出 0 个槽位**(思考块吃光了整个配额);改成 `220 × 1 + 1000` 后 **4 次全部成功**,1/2/4/8 槽位各 4 次同样全通过。
82
+
83
+ 同时把 effort **钉在路由声明的最便宜档**,而不是沿用路由默认档。思考与正文共用同一笔 `maxTokens`,默认档通常是最贵那档,会挤占正文预算。实测 2 槽位、带余量:`low` 花 375 个思考 token、3/3 解析成功;`high` 花 931、只有 2/3。
84
+
85
+ **`off` 走不通,这一点是实测而非推断。** 用本地回显服务抓 pi-ai 1.3.0 对 `thinkingFormat: deepseek` 真正发出的 body:`off` 档被映射成 `reasoning_effort: "minimal"` 且 `thinking: {"type":"enabled"}` 固定不变,而该端点直接拒绝 `minimal`(`valid levels: low, medium, high`)。真正能关掉思考的是 provider 自己的 `thinking: {"type":"disabled"}`(实测 0 个思考 token),但 `GenerateOptions` 没有承载它的字段,这条接缝上的任何插件都发不出去。所以 effort 只在路由**声明了**非 `off` 档时才发——宿主会拒绝未声明的档位。
86
+
87
+ 被令牌上限截断的那一批会**对半拆开重发**:截断的答案解析为空,一个超预算的轮次会连带丢掉同批其余七轮;对半拆把损失限制在仍然装不下的那一半,单槽位无法再拆时放弃并留 warn。注意这两条是一组:没有思考余量时,对半拆只会让每半的每槽位预算更紧、必然全败,所以余量是拆分重试成立的前提。判据钉在 `extractive.spec.mjs` 的「carries a thinking reserve」「pins the cheapest advertised effort」「never sent an effort it did not advertise」「split and retried, not dropped whole」「leaves a warning, not silence」。
80
88
 
81
89
  提取结果按内容哈希缓存,同一次会话内复用。`digestSource` 每次压缩都从原始日志重建,而原始事件永远留在日志里,所以同一轮会被反复读到。实测那个压缩了 33 次的会话:共提取 142 轮,其中 **129 轮(91%)在更早的压缩里已经提取过**;全机 370 个会话、456 次压缩里,**81% 的压缩工作量是这种重复**(有压缩的 88 个会话中 70 个压缩过 2 次以上)。
82
90
 
83
91
  缓存的键是提取材料的哈希(用户请求 + 助手正文 + 工具轨迹),不是 slot 位置:位置会随历史增长而错位,内容变了哈希就变,不会读到过期块。缓存是进程内的,重启即失效——代价只是重新提取一次,与加缓存前行为一致。
84
92
 
93
+ 提取调用返回 **JSON 字段**(`{"slots":[{"key","did","concluded","overturned"}]}`),标题、项目符号、空行全部由代码拼装。此前是自由 markdown,模型会把标题和正文挤在同一行——真实产出里出现过 `… 重出 4 屏 Concluded Stitch 会回填真实车牌`,事后无法用正则判断句子在哪结束、下一个标题从哪开始。字段化之后这个歧义不存在。
94
+
85
95
  `## Asked` 由**代码**从日志直接生成,不使用模型的输出:问题原文、选项、用户的选择(含打字回答)逐字取自 `ask_user_question` 的调用与结果。模型对这一段先后换过四种写法(`## Asked`、`**Asked**:`、`- Asked:`、中文 `问:`),每次换法都会破坏位置或内容,而这两半本来就在日志里,没有可概括的余地。模型写的那段一律丢弃。
86
96
 
87
97
  `## Asked` 记的是「助手问了什么 + 用户选了什么」。原来指令写「record the question, never the answer」——本意是防模型把用户请求抄进这一节,却被照字面执行:实测材料里两条 `ANSWER` 都在(其中一条把整个设计方向改成「游戏化、赛博朋克、提取 3D 模型」),模型只写了问题。
package/lib/index.js CHANGED
@@ -231,109 +231,122 @@ export function isErrorResult(event) {
231
231
  const message = messageOf(event);
232
232
  return message?.isError === true;
233
233
  }
234
- /**
235
- * Drop headings whose body says nothing.
236
- *
237
- * The instruction asks the model to omit empty sections, but a model that writes
238
- * `## Overturned\n- (none)` anyway must not cost tokens on every turn: 130 turns
239
- * of that placeholder is ~900 tokens recording that nothing was overturned. So
240
- * the shape is enforced here as well, not only requested in the prompt.
241
- *
242
- * A heading is dropped when every non-blank line under it, once its bullet is
243
- * stripped, is a placeholder — `(none)`, `none`, `n/a`, `-`, `无`. A heading with
244
- * any real content is kept verbatim.
245
- *
246
- * @param body - one slot's extracted text.
247
- * @returns the same text with empty sections removed, or an empty string when
248
- * nothing substantive remains.
249
- */
250
- export function pruneEmptySections(block) {
251
- const lines = block.split('\n');
252
- const kept = [];
253
- // A section is one heading plus the lines under it. The heading may be a line of
254
- // its own (`## Asked`, bare `Asked`) or carry its body inline (`- Did: …`,
255
- // `**Asked**:…`). Both forms occur in real output, sometimes in the same block.
256
- const headingOf = (line) => {
257
- if (/^#{1,6}\s/.test(line))
258
- return { own: '' };
259
- if (/^\s*(?:[-*]\s+)?(?:\*\*)?(Asked|Did|Concluded|Overturned|问|做|结论|推翻)(?:\*\*)?\s*[::]?\s*$/i.test(line)) {
260
- return { own: '' };
261
- }
262
- const inline = /^\s*(?:[-*]\s+)?(?:\*\*)?(Asked|Did|Concluded|Overturned|问|做|结论|推翻)(?:\*\*)?\s*[::]\s*(.*)$/i.exec(line);
263
- if (inline !== null)
264
- return { own: inline[2] ?? '' };
265
- return undefined;
266
- };
267
- // Placeholders for "nothing here" that models actually write. `未提问` came from a
268
- // real run and cost a line on every turn that asked no question.
269
- const placeholder = (text) => {
270
- const trimmed = text.trim();
271
- if (trimmed.length === 0)
272
- return true;
273
- if (/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有)$/i.test(trimmed))
274
- return true;
275
- return /^(?:未提问|无提问|没有提问|未提出|no questions? (?:were |was )?asked|none asked|no question)[。.!!]*$/i.test(trimmed);
276
- };
277
- let heading;
278
- let under = [];
279
- const flush = () => {
280
- if (heading !== undefined) {
281
- const own = headingOf(heading)?.own ?? '';
282
- const substantive = (own.length > 0 && !placeholder(own))
283
- || under.some((line) => !placeholder(line.replace(/^\s*(?:[-*]|\d+\.)\s*/, '')));
284
- if (substantive)
285
- kept.push(heading, ...under);
286
- }
287
- else {
288
- kept.push(...under);
289
- }
290
- heading = undefined;
291
- under = [];
292
- };
293
- for (const line of lines) {
294
- if (headingOf(line) !== undefined) {
295
- flush();
296
- heading = line;
297
- continue;
298
- }
299
- under.push(line);
300
- }
301
- flush();
302
- return kept.join('\n').replace(/\n{3,}/g, '\n\n').trim();
303
- }
304
234
  /** Directive appended as the final user message of the extraction call. */
305
235
  const EXTRACT_INSTRUCTION = [
306
236
  'You are summarizing a batch of turns from a coding session for a compaction checkpoint.',
307
237
  'Each item is introduced by a line `=== SLOT <key> (turn <n>) ===` and contains the user request, the assistant prose (may be empty), and a trace of the tool calls it made (descriptions only) plus any results the log marked as errors.',
308
238
  '',
309
- 'For EVERY item, emit exactly one block, introduced by `=== SLOT <key> ===` using that same key. Under each heading write at most two terse lines. OMIT a heading entirely when it has no real information — do not write "(none)" and do not invent. An item where nothing substantive happened may be omitted altogether.',
310
- '',
311
- '## Asked',
312
- '- what the ASSISTANT asked the USER in this turn, and what the user chose',
313
- '- the trace shows an `ANSWER:` line for a question the user answered, including answers they typed instead of picking an option. Record it: a later turn cannot rebuild which option was chosen, and a typed answer often redirects the whole task',
314
- '- the user may also answer in their next message, which appears in the digest as plain text. Prefer the `ANSWER:` line when both exist',
315
- '- NEVER restate or translate the user request here. It is already in the digest verbatim, directly above this block; copying it is the single most common way this section goes wrong. Recording the answer is not copying the request — the answer is the user replying to your question.',
316
- '',
317
- '## Did',
318
- '- what was actually done, concretely',
239
+ 'Reply with ONE JSON object and nothing else. No prose, no code fence, no markdown.',
240
+ 'Shape: {"slots":[{"key":"<the slot key>","did":["…"],"concluded":["…"],"overturned":["…"]}]}',
319
241
  '',
320
- '## Concluded',
321
- '- findings, decisions, or measurements that a later turn would need',
242
+ 'Rules for the fields:',
243
+ '- `key` must be copied exactly from the `=== SLOT <key> ===` line. One entry per slot.',
244
+ '- `did`: what was actually done, concretely. `concluded`: findings, decisions or measurements a later turn would need. `overturned`: earlier conclusions this turn disproved.',
245
+ '- Each field is an array of short strings, at most two per field. Use `[]` for a field with nothing to say. Omit the whole entry when nothing substantive happened.',
246
+ '- Write only the content of a line. Never write a heading, a bullet, or a field name inside a string.',
247
+ '- Do not describe the tool calls themselves ("ran bash", "explored the repo"). State what came out of them.',
248
+ '- Do not repeat a conclusion an earlier turn already stated.',
249
+ '- Never invent. If the material does not support a claim, leave the field empty.',
322
250
  '',
323
- '## Overturned',
324
- '- earlier conclusions this turn disproved or replaced',
325
- '',
326
- 'Do not describe the tool calls themselves ("ran bash", "explored the repo"). State what came out of them. Do not repeat a conclusion the previous turn already stated. If the trace is too thin to support a claim, write "(none)".',
251
+ 'Do not report questions and answers: those are read from the session log directly and need no summary.',
327
252
  '',
328
253
  // Measured on a real 32-slot session: whole batches came back in English while
329
254
  // the material was Chinese, so the digest mixed two languages for one
330
255
  // conversation.
331
- 'Write in the same language as the material. A session whose requests are Chinese gets Chinese blocks; do not switch to English.',
256
+ 'Write the strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
332
257
  ].join('\n');
258
+ /**
259
+ * Parse the model's JSON reply into per-slot extractions.
260
+ *
261
+ * The reply used to be free-form markdown, which let a heading share a line with
262
+ * its body — a real block read `… 重出 4 屏 Concluded Stitch 会回填真实车牌`, and no
263
+ * post-hoc regex can decide where that sentence ends and the next heading begins.
264
+ * Fields remove the ambiguity: the renderer owns every heading and bullet.
265
+ *
266
+ * @param answer - the model's raw reply.
267
+ * @returns extractions by slot key; empty when the reply is not usable JSON.
268
+ */
269
+ export function parseExtraction(answer) {
270
+ const out = new Map();
271
+ // Models wrap JSON in a fence often enough that stripping it is not defensive
272
+ // programming but the common case.
273
+ const body = answer.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
274
+ const start = body.indexOf('{');
275
+ const end = body.lastIndexOf('}');
276
+ if (start < 0 || end <= start)
277
+ return out;
278
+ let parsed;
279
+ try {
280
+ parsed = JSON.parse(body.slice(start, end + 1));
281
+ }
282
+ catch {
283
+ return out;
284
+ }
285
+ if (typeof parsed !== 'object' || parsed === null)
286
+ return out;
287
+ const slots = parsed['slots'];
288
+ if (!Array.isArray(slots))
289
+ return out;
290
+ const strings = (value) => (Array.isArray(value)
291
+ ? value.filter((item) => typeof item === 'string')
292
+ .map((item) => item.replace(/\s+/g, ' ').trim())
293
+ .filter((item) => item.length > 0)
294
+ // A field is a list, so "nothing here" is an empty list. Models still write a
295
+ // placeholder often enough that dropping it is worth one test.
296
+ .filter((item) => !/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有)$/i.test(item))
297
+ .filter((item) => !/^(?:未提问|无提问|没有提问|no questions? (?:were |was )?asked|none asked)[。.!!]*$/i.test(item))
298
+ : []);
299
+ for (const slot of slots) {
300
+ if (typeof slot !== 'object' || slot === null)
301
+ continue;
302
+ const record = slot;
303
+ const key = record['key'];
304
+ if (typeof key !== 'string' || key.length === 0)
305
+ continue;
306
+ out.set(key, {
307
+ did: strings(record['did']),
308
+ concluded: strings(record['concluded']),
309
+ overturned: strings(record['overturned']),
310
+ });
311
+ }
312
+ return out;
313
+ }
314
+ /**
315
+ * Render one extraction as the digest block, headings included.
316
+ *
317
+ * @param extraction - the fields for one slot.
318
+ * @returns markdown with a heading per non-empty field; empty string when every
319
+ * field is empty.
320
+ */
321
+ export function renderExtractionBlock(extraction) {
322
+ if (extraction === undefined)
323
+ return '';
324
+ const lines = [];
325
+ const section = (heading, items) => {
326
+ if (items === undefined || items.length === 0)
327
+ return;
328
+ lines.push(`## ${heading}`, ...items.map((item) => `- ${item}`));
329
+ };
330
+ section('Did', extraction.did);
331
+ section('Concluded', extraction.concluded);
332
+ section('Overturned', extraction.overturned);
333
+ return lines.join('\n');
334
+ }
333
335
  /** Turns handed to one extraction call. */
334
336
  const TURNS_PER_CALL = 8;
335
337
  /** Output tokens allowed per turn in an extraction call. */
336
338
  const EXTRACT_TOKENS_PER_TURN = 220;
339
+ /**
340
+ * Fixed thinking reserve added to every extraction call's `maxTokens`.
341
+ *
342
+ * `maxTokens` covers thinking and the answer together, and thinking is a
343
+ * per-call cost that does not shrink with the batch. Measured on the live route
344
+ * with real-length material: one slot at `220 x 1` with no reserve returned zero
345
+ * parseable slots in 4 of 4 runs, while `220 x 1 + 1000` parsed in 4 of 4. See
346
+ * `extractOnce` for the effort half of the same problem, and for why the reserve
347
+ * is the fix rather than an `off` effort.
348
+ */
349
+ const EXTRACT_THINKING_RESERVE_TOKENS = 1000;
337
350
  /** Most tool calls one turn may contribute to the hint block. */
338
351
  const MAX_HINTS_PER_TURN = 120;
339
352
  /** Characters kept from one call's description or command head. */
@@ -807,8 +820,10 @@ function renderSection(section, capChars) {
807
820
  for (const turn of section.turns) {
808
821
  if (turn.user.length > 0)
809
822
  lines.push(`\n## user\n${turn.user.join('\n')}`);
810
- if (turn.extracted !== undefined) {
811
- let block = turn.extracted;
823
+ // An extraction whose every field is empty renders nothing: a heading followed by
824
+ // no body reads as a turn that did something but says nothing.
825
+ if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted).length > 0) {
826
+ let block = renderExtractionBlock(turn.extracted);
812
827
  if (capChars !== undefined && block.length > capChars) {
813
828
  block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
814
829
  }
@@ -855,7 +870,9 @@ function assistantChars(sections) {
855
870
  let total = 0;
856
871
  for (const section of sections) {
857
872
  for (const turn of section.turns) {
858
- total += turn.extracted !== undefined ? turn.extracted.length : turn.assistant.join('\n').length;
873
+ total += turn.extracted !== undefined
874
+ ? renderExtractionBlock(turn.extracted).length
875
+ : turn.assistant.join('\n').length;
859
876
  }
860
877
  }
861
878
  return total;
@@ -1057,27 +1074,114 @@ export function buildExtractionMaterial(turn, prose) {
1057
1074
  * compaction does (`ctx.llm.stream` with the session's provider/model), so no
1058
1075
  * separate credential or configuration is involved.
1059
1076
  *
1060
- * Every failure path returns null and the caller falls back to the plain digest:
1061
- * a compaction that cannot reach the model must still compact, or the session
1062
- * dies of context overflow instead of losing detail.
1077
+ * Every failure path yields no blocks and the caller falls back to the plain
1078
+ * digest: a compaction that cannot reach the model must still compact, or the
1079
+ * session dies of context overflow instead of losing detail. The degradation is
1080
+ * per turn, but it is never silent — a batch that comes back unusable is
1081
+ * reported, because the whole point of that fallback is invisible otherwise.
1063
1082
  *
1064
- * @param ctx - plugin context carrying the `llm` service.
1083
+ * @param ctx - plugin context carrying the `llm` service and a logger.
1065
1084
  * @param agent - owner of the session being compacted; supplies the routed model.
1066
- * @param turn - one turn's events.
1067
- * @param prose - that turn's assistant prose, already extracted.
1085
+ * @param batch - slots to extract, in one call unless the answer is truncated.
1068
1086
  * @param signal - cancellation forwarded to the adapter.
1069
- * @returns the extracted block, or null when extraction is unavailable.
1087
+ * @returns the extracted blocks by slot key; empty when extraction is unavailable.
1070
1088
  */
1071
1089
  async function extractBatch(ctx, agent, batch, signal) {
1090
+ const out = new Map();
1091
+ if (batch.length === 0)
1092
+ return out;
1093
+ const attempt = await extractOnce(ctx, agent, batch, signal);
1094
+ if (!attempt.truncated) {
1095
+ if (attempt.blocks.size === 0) {
1096
+ ctx.logger?.warn(`verbatim-compaction: extraction returned no usable JSON for ${batch.length} slot(s) `
1097
+ + `(${batch.map((slot) => slot.key).join(', ')}); those turns keep their verbatim prose`);
1098
+ }
1099
+ return attempt.blocks;
1100
+ }
1101
+ // A truncated answer parses to nothing, so one over-budget turn would cost
1102
+ // every turn in its batch. Measured on 191 real compactions, failures arrived
1103
+ // in runs of exactly `TURNS_PER_CALL`, which is this batching, not the model
1104
+ // failing per turn. Halving bounds the loss to the half that still does not
1105
+ // fit, and a single slot cannot be split further.
1106
+ if (batch.length === 1) {
1107
+ ctx.logger?.warn(`verbatim-compaction: extraction truncated at the token cap for slot ${batch[0]?.key ?? '?'}; `
1108
+ + 'that turn keeps its verbatim prose');
1109
+ return attempt.blocks;
1110
+ }
1111
+ for (const [key, block] of attempt.blocks)
1112
+ out.set(key, block);
1113
+ const middle = Math.ceil(batch.length / 2);
1114
+ for (const half of [batch.slice(0, middle), batch.slice(middle)]) {
1115
+ for (const [key, block] of await extractBatch(ctx, agent, half, signal))
1116
+ out.set(key, block);
1117
+ }
1118
+ return out;
1119
+ }
1120
+ /**
1121
+ * The cheapest effort a route advertises, or undefined when it advertises none.
1122
+ *
1123
+ * The route's own default is not used: it is typically the highest level, and
1124
+ * thinking is paid out of the answer's token budget. The list is ordered from
1125
+ * least to greatest effort by the host's own contract, so the first entry is the
1126
+ * cheapest. `off` is skipped even when present — pi-ai maps it to a wire value
1127
+ * the route may reject, and a level that cannot be sent is worse than a cheap
1128
+ * one that can.
1129
+ *
1130
+ * @param efforts - the route's advertised efforts, in escalation order.
1131
+ * @returns the cheapest usable effort id, or undefined to leave the choice alone.
1132
+ */
1133
+ function cheapestEffort(efforts) {
1134
+ return efforts?.find((entry) => entry.id !== 'off')?.id;
1135
+ }
1136
+ /**
1137
+ * One extraction request, no retry.
1138
+ *
1139
+ * The cap must carry a fixed thinking reserve on top of the per-slot output
1140
+ * budget. `maxTokens` covers thinking and the answer together, and thinking is
1141
+ * a per-call cost that does not shrink when the batch does. Measured against the
1142
+ * live route (deepseek-flash, `reasoning_effort` unset, real-length material):
1143
+ * a single slot at the old `220 x 1` cap returned zero parseable slots in 4 of 4
1144
+ * runs, the thinking block having consumed the entire cap; the same single slot
1145
+ * at `220 x 1 + 1000` parsed in 4 of 4. The reserve is what makes the cap work
1146
+ * for a batch of any size, including the batches the caller splits down to.
1147
+ *
1148
+ * The effort is pinned to the route's cheapest advertised level rather than left
1149
+ * to the route default. Thinking is paid out of the same `maxTokens` as the
1150
+ * answer, so a default that thinks hard shrinks the answer budget even with the
1151
+ * reserve in place. Measured on the live route at a 2-slot cap with the reserve:
1152
+ * `low` spent 375 thinking tokens and parsed 3 of 3; `high` spent 931 and parsed
1153
+ * 2 of 3.
1154
+ *
1155
+ * Two things that look like fixes and are not:
1156
+ *
1157
+ * - `off` cannot be reached through pi-ai. Its `deepseek` thinking format maps
1158
+ * the `off` level to `reasoning_effort: "minimal"`, which the route rejects
1159
+ * outright (`valid levels: low, medium, high`), and its `thinking` field is
1160
+ * pinned to `{type: "enabled"}` for every level. Captured from pi-ai 1.3.0
1161
+ * against a local echo server, not inferred.
1162
+ * - Only the provider's own `thinking: {type: "disabled"}` actually stops
1163
+ * thinking (0 thinking tokens, measured), but `GenerateOptions` has no field
1164
+ * that carries it, so no plugin on this seam can send it.
1165
+ *
1166
+ * An effort is requested only when the route advertises it, because the host
1167
+ * rejects one it does not.
1168
+ *
1169
+ * @param ctx - plugin context carrying the `llm` service and a logger.
1170
+ * @param agent - owner of the session being compacted.
1171
+ * @param batch - slots to ask about in this one call.
1172
+ * @param signal - cancellation forwarded to the adapter.
1173
+ * @returns the parsed blocks and whether the model stopped at the token cap.
1174
+ */
1175
+ async function extractOnce(ctx, agent, batch, signal) {
1072
1176
  const out = new Map();
1073
1177
  const llm = ctx.llm;
1074
1178
  if (llm === undefined)
1075
- return out;
1179
+ return { blocks: out, truncated: false };
1076
1180
  const route = agent.session.requestHeader()?.config;
1077
1181
  const provider = route?.provider ?? agent.options.provider;
1078
1182
  const model = route?.model ?? agent.options.model;
1079
1183
  if (provider === undefined || model === undefined)
1080
- return out;
1184
+ return { blocks: out, truncated: false };
1081
1185
  // The label the model echoes back is the slot key, not the turn number: two
1082
1186
  // requests can share a number, and a duplicate label would collapse two blocks
1083
1187
  // into one entry.
@@ -1094,8 +1198,13 @@ async function extractBatch(ctx, agent, batch, signal) {
1094
1198
  parts.push(`=== SLOT ${slot.key} (turn ${slot.turn ?? '?'}) ===\n${material}`);
1095
1199
  }
1096
1200
  if (parts.length === 0)
1097
- return out;
1201
+ return { blocks: out, truncated: false };
1202
+ const info = await Promise.resolve()
1203
+ .then(() => llm.resolveModelInfo?.(provider, model, signal))
1204
+ .catch(() => undefined);
1205
+ const cheapest = cheapestEffort(info?.reasoning?.efforts);
1098
1206
  const chunks = [];
1207
+ let truncated = false;
1099
1208
  try {
1100
1209
  const stream = llm.stream({
1101
1210
  provider,
@@ -1103,31 +1212,28 @@ async function extractBatch(ctx, agent, batch, signal) {
1103
1212
  messages: [
1104
1213
  { role: 'user', content: [{ type: 'text', text: `${parts.join('\n\n')}\n\n${EXTRACT_INSTRUCTION}` }] },
1105
1214
  ],
1106
- maxTokens: EXTRACT_TOKENS_PER_TURN * parts.length,
1215
+ maxTokens: EXTRACT_TOKENS_PER_TURN * parts.length + EXTRACT_THINKING_RESERVE_TOKENS,
1107
1216
  sessionId: agent.session.id,
1108
1217
  purpose: 'compaction',
1218
+ ...(cheapest === undefined ? {} : { reasoningEffort: cheapest }),
1109
1219
  ...(signal === undefined ? {} : { signal }),
1110
1220
  });
1111
1221
  for await (const chunk of stream) {
1112
1222
  const delta = chunk;
1113
1223
  if (delta.type === 'text-delta' && typeof delta.text === 'string')
1114
1224
  chunks.push(delta.text);
1225
+ else if (delta.type === 'finish' && delta.reason?.kind === 'max-tokens')
1226
+ truncated = true;
1115
1227
  }
1116
1228
  }
1117
- catch {
1118
- return out;
1229
+ catch (error) {
1230
+ ctx.logger?.warn(`verbatim-compaction: extraction call failed for ${parts.length} slot(s): ${String(error)}`);
1231
+ return { blocks: out, truncated: false };
1119
1232
  }
1120
1233
  const answer = chunks.join('').trim();
1121
1234
  if (answer.length === 0)
1122
- return out;
1123
- const blocks = answer.split(/^=== SLOT ([^\s(]+)[^=]*===$/m);
1124
- for (let index = 1; index < blocks.length; index += 2) {
1125
- const key = blocks[index];
1126
- const body = pruneEmptySections((blocks[index + 1] ?? '').trim());
1127
- if (key !== undefined && body.length > 0)
1128
- out.set(key, body);
1129
- }
1130
- return out;
1235
+ return { blocks: out, truncated };
1236
+ return { blocks: parseExtraction(answer), truncated };
1131
1237
  }
1132
1238
  /**
1133
1239
  * Deterministic compaction backend: verbatim prose, pointerized tools, no model
@@ -80,23 +80,32 @@ export interface SummaryResult {
80
80
  * @returns true only when the log itself marks the result as an error.
81
81
  */
82
82
  export declare function isErrorResult(event: SessionEvent): boolean;
83
+ /** One slot's extraction, as the model returns it. */
84
+ export interface Extraction {
85
+ did: string[];
86
+ concluded: string[];
87
+ overturned: string[];
88
+ }
83
89
  /**
84
- * Drop headings whose body says nothing.
90
+ * Parse the model's JSON reply into per-slot extractions.
85
91
  *
86
- * The instruction asks the model to omit empty sections, but a model that writes
87
- * `## Overturned\n- (none)` anyway must not cost tokens on every turn: 130 turns
88
- * of that placeholder is ~900 tokens recording that nothing was overturned. So
89
- * the shape is enforced here as well, not only requested in the prompt.
92
+ * The reply used to be free-form markdown, which let a heading share a line with
93
+ * its body — a real block read `… 重出 4 屏 Concluded Stitch 会回填真实车牌`, and no
94
+ * post-hoc regex can decide where that sentence ends and the next heading begins.
95
+ * Fields remove the ambiguity: the renderer owns every heading and bullet.
90
96
  *
91
- * A heading is dropped when every non-blank line under it, once its bullet is
92
- * stripped, is a placeholder — `(none)`, `none`, `n/a`, `-`, `无`. A heading with
93
- * any real content is kept verbatim.
97
+ * @param answer - the model's raw reply.
98
+ * @returns extractions by slot key; empty when the reply is not usable JSON.
99
+ */
100
+ export declare function parseExtraction(answer: string): Map<string, Extraction>;
101
+ /**
102
+ * Render one extraction as the digest block, headings included.
94
103
  *
95
- * @param body - one slot's extracted text.
96
- * @returns the same text with empty sections removed, or an empty string when
97
- * nothing substantive remains.
104
+ * @param extraction - the fields for one slot.
105
+ * @returns markdown with a heading per non-empty field; empty string when every
106
+ * field is empty.
98
107
  */
99
- export declare function pruneEmptySections(block: string): string;
108
+ export declare function renderExtractionBlock(extraction: Extraction | undefined): string;
100
109
  /**
101
110
  * Build the compact per-turn trace fed to the summarizer.
102
111
  *
@@ -140,7 +149,7 @@ interface Turn {
140
149
  * the assistant prose's place in the digest: keeping both duplicated the same
141
150
  * content and pushed the prose out through the budget.
142
151
  */
143
- extracted?: string;
152
+ extracted?: Extraction;
144
153
  }
145
154
  /** One digest section: everything from one non-injected user message to the next. */
146
155
  interface Section {
@@ -210,7 +219,7 @@ export declare function moveAskedLast(block: string, asked?: readonly {
210
219
  * ceiling; the tiers exist for the turns where extraction was unavailable and
211
220
  * the prose is all that remains.
212
221
  */
213
- export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, string>): string;
222
+ export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, Extraction>): string;
214
223
  /**
215
224
  * The surface seqs this compaction shadows, recovered from the summarization
216
225
  * input's message count.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "description": "Deterministic compaction backend that keeps conversation prose verbatim in the checkpoint instead of re-summarizing it: user and assistant text survive word for word, tool results collapse to one-line pointers, reasoning is never read, and no model call is made.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",