@logictan/dsh-verbatim-compaction 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -82,6 +82,14 @@
82
82
 
83
83
  缓存的键是提取材料的哈希(用户请求 + 助手正文 + 工具轨迹),不是 slot 位置:位置会随历史增长而错位,内容变了哈希就变,不会读到过期块。缓存是进程内的,重启即失效——代价只是重新提取一次,与加缓存前行为一致。
84
84
 
85
+ `## Asked` 由代码移到最后(`moveAskedLast`),因为用户的回复常常只有「8399」「继续」,只有紧接在提问后面才读得懂。模型用过三种写法——`## Asked`、`**Asked**:`、`- Asked:`——三种都认。
86
+
87
+ `ask_user_question` 的问题与用户选择都会进材料。它没有 `description` 参数,载荷在 `questions[]`,原来只留下 `TOOL ask_user_question` 五个字——问题是什么、用户选了什么全丢。答案在工具结果里(`answers[].selected`,或用户自己打字时的 `answers[].custom`),实测 31 次提问里 10 次是打字回答。
88
+
89
+ 一个 section 就是一次请求、一个 turn。日志会在同一次请求里推进 turn 号(实测一个请求的 7 条助手消息记作 turn 2、另 9 条记作 turn 3),按号码切分会把一个请求拆成「空请求 turn + 无用户消息的回复 turn」,摘要里就出现两个 `### assistant`。用户消息本身不带 turn 字段,这条也曾让两者永远对不上。
90
+
91
+ 一个 section 只提取一次,提取块写给该 section 的第一个 turn——如果每个 turn 都拿到同一份事件,模型会对同一段材料答两遍(实测出现过两个完全相同的 `## Concluded` 块和 `(duplicate of SLOT 4:0)` 占位)。
92
+
85
93
  提取按批调用:每 8 轮一次,一轮输出一个 `=== TURN n ===` 块。早期实现是每轮一次调用,122 轮就是 131 次往返,单轮 400 token 的输出上限乘以 131 就可能超过整个摘要上限。批处理把往返压到约 17 次,并共享 prompt 前缀以复用 provider 的 KV cache。
86
94
 
87
95
  用户原话在布局上**先占额度**,提取块不得挤占。实测那个 122 轮会话:区间内真人原话共 469 字符(117 token),而每轮一块 420 字符的提取共 55020 字符——提取是正文的 117 倍,任何让二者竞争的布局都会把正文挤掉,而正文是「请用pixi管理开发环境」这类永不过期的约束,提取描述的却是已经做完的工作。
package/lib/index.js CHANGED
@@ -159,10 +159,62 @@ function toolCallsOf(event) {
159
159
  const calls = [];
160
160
  for (const block of message.content) {
161
161
  if (block.type === 'tool-call')
162
- calls.push({ name: block.name, arguments: block.arguments });
162
+ calls.push({ id: block.id, name: block.name, arguments: block.arguments });
163
163
  }
164
164
  return calls;
165
165
  }
166
+ /**
167
+ * The answer the user gave to one `ask_user_question` call, or undefined.
168
+ *
169
+ * The answer is the tool's own result — `{"answers":[{"id":"…","selected":[…]}]}`
170
+ * — not an error, so without this the result was skipped and the only record of
171
+ * what the user chose never reached the extractor. The user's next message is
172
+ * often just "1" or "继续", which is unreadable without the question beside it.
173
+ *
174
+ * @param event - any event; non-results and unrelated results yield undefined.
175
+ * @param askedIds - tool-call ids of this turn's questions.
176
+ * @returns the chosen labels, or undefined when this result answers no question.
177
+ */
178
+ function answerOf(event, askedIds) {
179
+ if (askedIds.size === 0)
180
+ return undefined;
181
+ const message = messageOf(event);
182
+ if (message === null)
183
+ return undefined;
184
+ const callId = message.toolCallId;
185
+ if (callId === undefined || !askedIds.has(callId))
186
+ return undefined;
187
+ const text = textOf(event);
188
+ let parsed;
189
+ try {
190
+ parsed = JSON.parse(text);
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ if (typeof parsed !== 'object' || parsed === null)
196
+ return undefined;
197
+ const answers = parsed['answers'];
198
+ if (!Array.isArray(answers))
199
+ return undefined;
200
+ const chosen = answers
201
+ .flatMap((answer) => {
202
+ if (typeof answer !== 'object' || answer === null)
203
+ return [];
204
+ const record = answer;
205
+ const selected = record['selected'];
206
+ const picked = Array.isArray(selected) ? selected.map((value) => String(value)) : [];
207
+ // A typed answer arrives with `selected: []` and the text in `custom`. Ten
208
+ // of 31 real questions were answered this way, and those carried the user's
209
+ // actual observations rather than a menu label.
210
+ const typed = typeof record['custom'] === 'string' ? [record['custom']] : [];
211
+ return [...picked, ...typed];
212
+ })
213
+ .filter((value) => value.length > 0);
214
+ if (chosen.length === 0)
215
+ return undefined;
216
+ return chosen.join(' / ').replace(/\s+/g, ' ').slice(0, HINT_CHARS * 2);
217
+ }
166
218
  /**
167
219
  * Whether one tool result is a failure.
168
220
  *
@@ -255,6 +307,11 @@ const EXTRACT_INSTRUCTION = [
255
307
  '- earlier conclusions this turn disproved or replaced',
256
308
  '',
257
309
  '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)".',
310
+ '',
311
+ // Measured on a real 32-slot session: whole batches came back in English while
312
+ // the material was Chinese, so the digest mixed two languages for one
313
+ // conversation.
314
+ 'Write in the same language as the material. A session whose requests are Chinese gets Chinese blocks; do not switch to English.',
258
315
  ].join('\n');
259
316
  /** Turns handed to one extraction call. */
260
317
  const TURNS_PER_CALL = 8;
@@ -284,6 +341,35 @@ function hintOf(argumentsJson) {
284
341
  catch {
285
342
  return '';
286
343
  }
344
+ // `ask_user_question` carries `questions[]`, not a `description`. Without this
345
+ // branch the hint was the bare tool name, so the extractor never saw what was
346
+ // asked and `## Asked` came out empty or wrong on every turn that used it.
347
+ const questions = parsed['questions'];
348
+ if (Array.isArray(questions)) {
349
+ const asked = questions
350
+ .map((question) => {
351
+ if (typeof question !== 'object' || question === null)
352
+ return '';
353
+ const record = question;
354
+ const text = typeof record['question'] === 'string'
355
+ ? record['question']
356
+ : typeof record['header'] === 'string' ? record['header'] : '';
357
+ const options = Array.isArray(record['options'])
358
+ ? record['options']
359
+ .map((option) => (typeof option === 'object' && option !== null
360
+ ? String(option['label'] ?? '')
361
+ : ''))
362
+ .filter((label) => label.length > 0)
363
+ : [];
364
+ if (text.length === 0)
365
+ return '';
366
+ return options.length === 0 ? text : `${text} [options: ${options.join(' / ')}]`;
367
+ })
368
+ .filter((text) => text.length > 0)
369
+ .join(' | ');
370
+ if (asked.length > 0)
371
+ return asked.replace(/\s+/g, ' ').slice(0, HINT_CHARS * 2);
372
+ }
287
373
  for (const key of ['description', 'command', 'query', 'file_path', 'path', 'pattern']) {
288
374
  const candidate = parsed[key];
289
375
  if (typeof candidate === 'string' && candidate.trim().length > 0) {
@@ -310,6 +396,9 @@ function hintOf(argumentsJson) {
310
396
  export function collectHints(events) {
311
397
  const lines = [];
312
398
  let calls = 0;
399
+ // Tool-call ids of this turn's questions, so the matching result can be read as
400
+ // an answer rather than being skipped as a non-error result.
401
+ const askedIds = new Set();
313
402
  for (const event of events) {
314
403
  // Tool calls are blocks inside `assistant/message`, not standalone events:
315
404
  // `digestSource` emits no `tool/call` type at all, so selecting on that type
@@ -321,11 +410,21 @@ export function collectHints(events) {
321
410
  calls += 1;
322
411
  const hint = hintOf(call.arguments);
323
412
  lines.push(hint.length > 0 ? `TOOL ${call.name}: ${hint}` : `TOOL ${call.name}`);
413
+ if (call.name === 'ask_user_question')
414
+ askedIds.add(call.id);
324
415
  }
325
416
  continue;
326
417
  }
327
418
  if (event.type !== 'tool/result')
328
419
  continue;
420
+ // The answer to a question is the tool's own result, not an error. It is the
421
+ // only record of what the user chose, and the next user message is often just
422
+ // "1" — so it has to travel with the question.
423
+ const answered = answerOf(event, askedIds);
424
+ if (answered !== undefined) {
425
+ lines.push(`ANSWER: ${answered}`);
426
+ continue;
427
+ }
329
428
  if (!isErrorResult(event))
330
429
  continue;
331
430
  const firstLine = textOf(event).split('\n')[0] ?? '';
@@ -442,9 +541,19 @@ export function buildSections(events) {
442
541
  currentTurn.user.push(text);
443
542
  continue;
444
543
  }
445
- if (currentTurn === undefined || (eventTurn !== undefined && currentTurn.turn !== eventTurn)) {
446
- currentTurn = openTurn(eventTurn);
447
- }
544
+ // A user message carries no `turn` field while the reply carries one, so a
545
+ // plain turn-number comparison opened a second turn for the same request: every
546
+ // real section ended up with an empty request turn plus a reply turn holding no
547
+ // user text, and the digest printed `## user` and `### assistant` twice.
548
+ //
549
+ // The turn number only separates work when the current turn already holds some,
550
+ // i.e. when the log really moved on to a later turn.
551
+ // A section is one request, so it is one turn. The log keeps advancing the turn
552
+ // number inside a single request (7 assistant messages as turn 2, then 9 more as
553
+ // turn 3), and splitting on the number gave every section a second turn whose
554
+ // block was the tail of the same request's prose.
555
+ if (currentTurn === undefined)
556
+ currentTurn = openTurn(eventTurn ?? lastTurn);
448
557
  const text = textOf(event);
449
558
  if (text.length > 0)
450
559
  currentTurn.assistant.push(text);
@@ -535,6 +644,44 @@ function materialKey(events) {
535
644
  * The tool pointer line stays either way: it is one line, and it is the only
536
645
  * record of what was actually run when the prose and extraction both say little.
537
646
  */
647
+ /**
648
+ * Move the `## Asked` section to the end of one extraction block.
649
+ *
650
+ * The digest reads as a conversation, and the user's next message is often just
651
+ * "8399" or "继续". That reply only makes sense beside the question it answers, so
652
+ * Asked belongs at the bottom of the block. The model puts it first about as often
653
+ * as last, so the order is fixed here rather than requested in the prompt.
654
+ *
655
+ * @param block - one extraction block, possibly malformed.
656
+ * @returns the same block with Asked last; unchanged when Asked is absent or already last.
657
+ */
658
+ export function moveAskedLast(block) {
659
+ const lines = block.split('\n');
660
+ // Three heading forms observed from the same model: `## Asked`, `**Asked**:` and
661
+ // `- Asked:`. Recognising only the first left Asked at the top whenever the model
662
+ // changed style.
663
+ const isAsked = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?Asked(?:\*\*)?\s*[::]?\s*$/i.test(line);
664
+ const isAskedInline = (line) => /^\s*(?:[-*]\s+)?(?:\*\*)?Asked(?:\*\*)?\s*[::]/i.test(line);
665
+ const isOther = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(Did|Concluded|Overturned)(?:\*\*)?\s*[::]?/i.test(line);
666
+ const start = lines.findIndex((line) => isAsked(line) || isAskedInline(line));
667
+ if (start < 0)
668
+ return block;
669
+ // A heading form owns the lines until the next heading; an inline `- Asked: x`
670
+ // form owns only its own line.
671
+ const inline = isAskedInline(lines[start] ?? '') && !isAsked(lines[start] ?? '');
672
+ let end = start + 1;
673
+ if (!inline) {
674
+ while (end < lines.length && !isOther(lines[end] ?? ''))
675
+ end += 1;
676
+ }
677
+ const asked = lines.slice(start, end);
678
+ while (asked.length > 0 && (asked.at(-1) ?? '').trim().length === 0)
679
+ asked.pop();
680
+ const rest = [...lines.slice(0, start), ...lines.slice(end)];
681
+ while (rest.length > 0 && (rest.at(-1) ?? '').trim().length === 0)
682
+ rest.pop();
683
+ return [...rest, '', ...asked].join('\n');
684
+ }
538
685
  function renderSection(section, capChars) {
539
686
  const lines = [];
540
687
  for (const turn of section.turns) {
@@ -545,7 +692,18 @@ function renderSection(section, capChars) {
545
692
  if (capChars !== undefined && block.length > capChars) {
546
693
  block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
547
694
  }
548
- lines.push(`### assistant\n${block}`);
695
+ // Errors and writes sit after the block: Asked has to be the last thing in the
696
+ // turn, and the errors line directly under `## user` read as if the user had
697
+ // said it. Asked is inside the block, so the trailer goes before Asked instead
698
+ // — see moveAskedLast being applied after the trailer is joined.
699
+ const trailer = [];
700
+ if (turn.errors.length > 0) {
701
+ trailer.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
702
+ }
703
+ if (turn.writes.length > 0)
704
+ trailer.push(` wrote: ${turn.writes.join(', ')}`);
705
+ const body = trailer.length > 0 ? `${block}\n${trailer.join('\n')}` : block;
706
+ lines.push(`### assistant\n${moveAskedLast(body)}`);
549
707
  }
550
708
  else {
551
709
  let body = turn.assistant.join('\n');
@@ -554,12 +712,12 @@ function renderSection(section, capChars) {
554
712
  }
555
713
  if (body.length > 0)
556
714
  lines.push(`### assistant\n${body}`);
715
+ if (turn.errors.length > 0) {
716
+ lines.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
717
+ }
718
+ if (turn.writes.length > 0)
719
+ lines.push(` wrote: ${turn.writes.join(', ')}`);
557
720
  }
558
- if (turn.errors.length > 0) {
559
- lines.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
560
- }
561
- if (turn.writes.length > 0)
562
- lines.push(` wrote: ${turn.writes.join(', ')}`);
563
721
  }
564
722
  return lines.join('\n');
565
723
  }
@@ -974,14 +1132,20 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
974
1132
  if (sectionIndex >= 0)
975
1133
  grouped[sectionIndex]?.push(event);
976
1134
  }
1135
+ // One slot per section, addressed to the section's first turn.
1136
+ //
1137
+ // The material is about what the section did as a whole, so handing it to
1138
+ // every turn in the section made the model answer twice with the same block:
1139
+ // a real section holding two turns produced two identical `## Concluded`
1140
+ // bodies plus `(duplicate of SLOT 4:0)` placeholders in the digest. The extra
1141
+ // turns keep their prose and their own headings; only the first carries the
1142
+ // section's extraction.
977
1143
  const slots = [];
978
1144
  for (const [sectionIndex, section] of sections.entries()) {
979
- // A section may hold more than one turn; all of them see the section's
980
- // events, because the material is about what the section did as a whole.
981
- const events = grouped[sectionIndex] ?? [];
982
- for (const [turnIndex, turn] of section.turns.entries()) {
983
- slots.push({ key: turnKey(sectionIndex, turnIndex), turn: turn.turn, events });
984
- }
1145
+ const first = section.turns[0];
1146
+ if (first === undefined)
1147
+ continue;
1148
+ slots.push({ key: turnKey(sectionIndex, 0), turn: first.turn, events: grouped[sectionIndex] ?? [] });
985
1149
  }
986
1150
  const extracted = new Map();
987
1151
  const missing = [];
@@ -148,6 +148,29 @@ interface Section {
148
148
  * @returns one section per non-injected user message.
149
149
  */
150
150
  export declare function buildSections(events: readonly SessionEvent[]): Section[];
151
+ /**
152
+ * Render one section to digest text, truncating assistant prose to `capChars`.
153
+ *
154
+ * When the turn carries an extraction, that extraction *replaces* the assistant
155
+ * prose. Keeping both was the duplication this design removes: 58.2% of
156
+ * assistant characters are substantive conclusions that the extraction restates,
157
+ * and the doubled copy pushed real history out through the budget.
158
+ *
159
+ * The tool pointer line stays either way: it is one line, and it is the only
160
+ * record of what was actually run when the prose and extraction both say little.
161
+ */
162
+ /**
163
+ * Move the `## Asked` section to the end of one extraction block.
164
+ *
165
+ * The digest reads as a conversation, and the user's next message is often just
166
+ * "8399" or "继续". That reply only makes sense beside the question it answers, so
167
+ * Asked belongs at the bottom of the block. The model puts it first about as often
168
+ * as last, so the order is fixed here rather than requested in the prompt.
169
+ *
170
+ * @param block - one extraction block, possibly malformed.
171
+ * @returns the same block with Asked last; unchanged when Asked is absent or already last.
172
+ */
173
+ export declare function moveAskedLast(block: string): string;
151
174
  /**
152
175
  * Render the digest under a hard character budget.
153
176
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
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",