@logictan/dsh-verbatim-compaction 0.11.0 → 0.12.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 +19 -7
- package/lib/index.js +195 -245
- package/lib/types/index.d.ts +30 -54
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -60,15 +60,15 @@
|
|
|
60
60
|
|
|
61
61
|
只抄正文救不了「正文为空」的轮次。实测一个 13878 事件的会话:1973 条 assistant 消息里只有 317 条带正文,其中一轮跑了 342 次工具调用却一个字没写,纯逐字摘要把它压成一行 `tools: bash×281`——活干了,记录没了。
|
|
62
62
|
|
|
63
|
-
所以提取的材料是三段:用户请求(逐字)、助手正文(逐字)、工具轨迹(每条调用的 `description
|
|
63
|
+
所以提取的材料是三段:用户请求(逐字)、助手正文(逐字)、工具轨迹(每条调用的 `description`,失败的调用另记一行首行错误)。模型输出四个字段:`asked` / `did` / `concluded` / `overturned`,标题与项目符号由渲染器拼装。
|
|
64
64
|
|
|
65
|
-
|
|
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`
|
|
71
|
+
正文为空的轮次(那个真实案例有 96 条助手消息、150 次工具调用却只有 156 字符正文)本来就没有提问可记,`## Asked` 和 `## Did` 一样整节省略,不需要单独规则。实测 123 条真人消息里 43 条(35%)不超过 12 个字符——`3`、`1`、`同意`、`做`、`继续`——而 46% 是在回答上一轮助手的提问。只逐字保留「3」而不保留它在回答什么问题,等于记下一个决定却没记下决定的是什么。
|
|
72
72
|
|
|
73
73
|
模型用的是会话自己的路由(`session.requestHeader()?.config`),和宿主原生压缩同一个取法,不需要单独配置凭据。
|
|
74
74
|
|
|
@@ -76,7 +76,15 @@
|
|
|
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`)。加入 `asked` 后每槽位预算从 220 提到 900:真实 8 槽批次上思考单独就占 1057–4086 token,`220 × 8 + 1000` 曾把一次调用从 JSON 中间截断,解析出 0 个槽位、整批丢失;`900 × n + 1000` 每次都能解析出全部槽位。`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
|
|
|
@@ -84,11 +92,15 @@
|
|
|
84
92
|
|
|
85
93
|
提取调用返回 **JSON 字段**(`{"slots":[{"key","did","concluded","overturned"}]}`),标题、项目符号、空行全部由代码拼装。此前是自由 markdown,模型会把标题和正文挤在同一行——真实产出里出现过 `… 重出 4 屏 Concluded Stitch 会回填真实车牌`,事后无法用正则判断句子在哪结束、下一个标题从哪开始。字段化之后这个歧义不存在。
|
|
86
94
|
|
|
87
|
-
`## Asked`
|
|
95
|
+
`## Asked` 由**模型**输出,和 `did`/`concluded`/`overturned` 并列成 JSON 字段:`asked: [{question, options}]`。曾经改成由代码从 `ask_user_question` 的调用与结果里确定性生成,那个方案在「提问走的是工具」时才成立,而实测里提问大量出现在正文末尾,工具调用根本没有。
|
|
96
|
+
|
|
97
|
+
**为什么不能只靠日志读。** 两件事需要判断,而不是取字段:其一,提问不在可靠的位置——231 个「引出了短回复」的真实轮次里,34% 的提问后面还有正文(p90 = 7 段,最多 24 段),形如 `## 需要你决定` 后面又跟一节 `## 还没验证的`;其二,选项通常也不在提问旁边——28 个纯数字回复的轮次里,28 个都提供过编号列表,但只有 26/231 轮那份列表落在提问本段或前一段,多数隔着自己的小标题在上面。要认出「这个提问指的是哪份列表」需要判断,日志里只有文字。
|
|
98
|
+
|
|
99
|
+
**`answer` 字段被明确去掉。** 用户的回复就是下一节的 `## user` 行,逐字渲染;再写进 `asked.answer` 等于同一句话印两遍。指令里对应加了一条「不要报告用户的回复」,渲染上 `## Asked` 是块的最后一节,所以回复永远紧接在它下面。
|
|
88
100
|
|
|
89
|
-
`## Asked`
|
|
101
|
+
`## Asked` 的位置由渲染器保证在最后,不靠模型。选项在问题下面缩进编号列出,`- 问题` 一行、` 1. …` 各行,用户的 `1` 因此有东西可指。
|
|
90
102
|
|
|
91
|
-
|
|
103
|
+
**选项自带的编号会被剥掉。** 模型会把源列表的 `1.` 一起抄进 `options`,渲染器再加一次编号就变成 `1. 1. …`;实测 5 次里 3 次如此,所以在解析阶段用正则剥掉,而不是只靠指令。
|
|
92
104
|
|
|
93
105
|
`ask_user_question` 不计入工具调用上限(120 条)。它是「问了什么」的唯一记录,而答案按调用 id 匹配、不受上限约束;提问被截断时答案会变成孤立一行——实测一轮 292 次调用,提问排在后面被切掉,用户的选择就此丢失。
|
|
94
106
|
|
package/lib/index.js
CHANGED
|
@@ -231,99 +231,27 @@ 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
|
-
'You are summarizing a batch of turns from a coding session for a compaction checkpoint.',
|
|
307
|
-
'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
|
-
'',
|
|
309
236
|
'Reply with ONE JSON object and nothing else. No prose, no code fence, no markdown.',
|
|
310
|
-
'Shape: {"slots":[{"key":"<the slot key>","did":["…"],"concluded":["…"],"overturned":["…"]}]}',
|
|
311
|
-
'',
|
|
312
|
-
'
|
|
313
|
-
'- `
|
|
314
|
-
'-
|
|
315
|
-
'-
|
|
316
|
-
'- Write only the content of a line. Never write a heading, a bullet, or a field name inside a string.',
|
|
317
|
-
'- Do not describe the tool calls themselves ("ran bash", "explored the repo"). State what came out of them.',
|
|
318
|
-
'- Do not repeat a conclusion an earlier turn already stated.',
|
|
237
|
+
'Shape: {"slots":[{"key":"<the slot key>","did":["…"],"concluded":["…"],"overturned":["…"],"asked":[{"question":"…","options":["…"]}]}]}',
|
|
238
|
+
'Rules:',
|
|
239
|
+
'- `key` must be copied exactly from the `=== SLOT <key> ===` line. One entry per slot, in the order given. Never skip a slot.',
|
|
240
|
+
'- `did`: what was done, at most two short strings. `concluded`: findings a later turn needs, at most two. `overturned`: earlier conclusions this turn disproved.',
|
|
241
|
+
'- Each field is an array of short strings. Use [] for a field with nothing to say.',
|
|
242
|
+
'- Never write a heading, a bullet, or a field name inside a string.',
|
|
319
243
|
'- Never invent. If the material does not support a claim, leave the field empty.',
|
|
244
|
+
// A question is not reliably the last paragraph: measured over 231 real turns
|
|
245
|
+
// that drew a short reply, 34% had prose after it (p90 = 7 paragraphs, max 24).
|
|
246
|
+
'- `asked`: one entry per question this turn put to the user and was still waiting on when it ended. A question is anywhere in the prose, not only the last paragraph.',
|
|
247
|
+
// And the options are usually further up: in 26 of 231 turns was the list in the
|
|
248
|
+
// question's own paragraph or the one before it.
|
|
249
|
+
'- `options`: what the user could pick from, in order, one short line each, with their own numbering stripped. The list is often a paragraph or two above the question. Use [] when the question offered none.',
|
|
250
|
+
// The reply is the next turn's `## user` line, already verbatim in the digest.
|
|
251
|
+
// Asking for it here printed the same sentence twice.
|
|
252
|
+
"- Use [] for `asked` when the turn asked nothing. Do not report the user's reply.",
|
|
320
253
|
'',
|
|
321
|
-
'
|
|
322
|
-
'',
|
|
323
|
-
// Measured on a real 32-slot session: whole batches came back in English while
|
|
324
|
-
// the material was Chinese, so the digest mixed two languages for one
|
|
325
|
-
// conversation.
|
|
326
|
-
'Write the strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
|
|
254
|
+
'Write strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
|
|
327
255
|
].join('\n');
|
|
328
256
|
/**
|
|
329
257
|
* Parse the model's JSON reply into per-slot extractions.
|
|
@@ -366,6 +294,31 @@ export function parseExtraction(answer) {
|
|
|
366
294
|
.filter((item) => !/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有)$/i.test(item))
|
|
367
295
|
.filter((item) => !/^(?:未提问|无提问|没有提问|no questions? (?:were |was )?asked|none asked)[。.!!]*$/i.test(item))
|
|
368
296
|
: []);
|
|
297
|
+
// Asked is a list of objects, not of strings: a question without its options
|
|
298
|
+
// turns the user's `1` into a number that selects nothing.
|
|
299
|
+
const pairs = (value) => (Array.isArray(value)
|
|
300
|
+
? value
|
|
301
|
+
.flatMap((item) => {
|
|
302
|
+
if (typeof item !== 'object' || item === null)
|
|
303
|
+
return [];
|
|
304
|
+
const record = item;
|
|
305
|
+
const question = typeof record['question'] === 'string'
|
|
306
|
+
? record['question'].replace(/\s+/g, ' ').trim()
|
|
307
|
+
: '';
|
|
308
|
+
if (question.length === 0)
|
|
309
|
+
return [];
|
|
310
|
+
const options = Array.isArray(record['options'])
|
|
311
|
+
? record['options']
|
|
312
|
+
.filter((option) => typeof option === 'string')
|
|
313
|
+
// The renderer supplies the numbering, so a model that echoes the source
|
|
314
|
+
// list's own `1.` would print `1. 1. …`. Stripped here rather than asked
|
|
315
|
+
// for in the prompt alone: three of five real runs kept it.
|
|
316
|
+
.map((option) => option.replace(/\s+/g, ' ').replace(/^\s*\d{1,2}\s*[.、)]\s*/, '').trim())
|
|
317
|
+
.filter((option) => option.length > 0)
|
|
318
|
+
: [];
|
|
319
|
+
return [{ question, options }];
|
|
320
|
+
})
|
|
321
|
+
: []);
|
|
369
322
|
for (const slot of slots) {
|
|
370
323
|
if (typeof slot !== 'object' || slot === null)
|
|
371
324
|
continue;
|
|
@@ -377,6 +330,7 @@ export function parseExtraction(answer) {
|
|
|
377
330
|
did: strings(record['did']),
|
|
378
331
|
concluded: strings(record['concluded']),
|
|
379
332
|
overturned: strings(record['overturned']),
|
|
333
|
+
asked: pairs(record['asked']),
|
|
380
334
|
});
|
|
381
335
|
}
|
|
382
336
|
return out;
|
|
@@ -400,12 +354,46 @@ export function renderExtractionBlock(extraction) {
|
|
|
400
354
|
section('Did', extraction.did);
|
|
401
355
|
section('Concluded', extraction.concluded);
|
|
402
356
|
section('Overturned', extraction.overturned);
|
|
357
|
+
// Asked goes last and its options are listed under it, so the user's reply — the
|
|
358
|
+
// next `## user` line — lands directly under the list it chose from.
|
|
359
|
+
if (extraction.asked.length > 0) {
|
|
360
|
+
lines.push('## Asked');
|
|
361
|
+
for (const pair of extraction.asked) {
|
|
362
|
+
lines.push(`- ${pair.question}`);
|
|
363
|
+
// Indented under the question so a reader cannot mistake an option for a
|
|
364
|
+
// separate question, and numbered so the reply's digit has something to
|
|
365
|
+
// point at.
|
|
366
|
+
for (const [index, option] of pair.options.entries()) {
|
|
367
|
+
lines.push(` ${index + 1}. ${option}`);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
403
371
|
return lines.join('\n');
|
|
404
372
|
}
|
|
405
373
|
/** Turns handed to one extraction call. */
|
|
406
374
|
const TURNS_PER_CALL = 8;
|
|
407
|
-
/**
|
|
408
|
-
|
|
375
|
+
/**
|
|
376
|
+
* Output tokens allowed per turn in an extraction call.
|
|
377
|
+
*
|
|
378
|
+
* Raised from 220 when `asked` was added. The model thinks before it answers and
|
|
379
|
+
* thinking is charged to the same `maxTokens`, so the answer's own budget has to
|
|
380
|
+
* cover both. Measured on real 8-slot batches: thinking alone ran 1057–4086
|
|
381
|
+
* tokens, and a cap of `220 x 8 + 1000` cut one run off mid-JSON, which parsed to
|
|
382
|
+
* zero slots and lost the whole batch. `900` per slot plus the reserve below
|
|
383
|
+
* parsed 8 of 8 on every attempt.
|
|
384
|
+
*/
|
|
385
|
+
const EXTRACT_TOKENS_PER_TURN = 900;
|
|
386
|
+
/**
|
|
387
|
+
* Fixed thinking reserve added to every extraction call's `maxTokens`.
|
|
388
|
+
*
|
|
389
|
+
* `maxTokens` covers thinking and the answer together, and thinking is a
|
|
390
|
+
* per-call cost that does not shrink with the batch. Measured on the live route
|
|
391
|
+
* with real-length material: one slot at `220 x 1` with no reserve returned zero
|
|
392
|
+
* parseable slots in 4 of 4 runs, while `220 x 1 + 1000` parsed in 4 of 4. See
|
|
393
|
+
* `extractOnce` for the effort half of the same problem, and for why the reserve
|
|
394
|
+
* is the fix rather than an `off` effort.
|
|
395
|
+
*/
|
|
396
|
+
const EXTRACT_THINKING_RESERVE_TOKENS = 1000;
|
|
409
397
|
/** Most tool calls one turn may contribute to the hint block. */
|
|
410
398
|
const MAX_HINTS_PER_TURN = 120;
|
|
411
399
|
/** Characters kept from one call's description or command head. */
|
|
@@ -544,81 +532,6 @@ function pathArgumentOf(argumentsJson) {
|
|
|
544
532
|
return undefined;
|
|
545
533
|
}
|
|
546
534
|
}
|
|
547
|
-
/**
|
|
548
|
-
* The question an `ask_user_question` call put, with its options, or undefined.
|
|
549
|
-
*
|
|
550
|
-
* @param argumentsJson - the call's raw arguments.
|
|
551
|
-
* @returns one line per question, options appended in brackets.
|
|
552
|
-
*/
|
|
553
|
-
function questionTextOf(argumentsJson) {
|
|
554
|
-
let parsed;
|
|
555
|
-
try {
|
|
556
|
-
parsed = JSON.parse(argumentsJson);
|
|
557
|
-
}
|
|
558
|
-
catch {
|
|
559
|
-
return undefined;
|
|
560
|
-
}
|
|
561
|
-
if (typeof parsed !== 'object' || parsed === null)
|
|
562
|
-
return undefined;
|
|
563
|
-
const questions = parsed['questions'];
|
|
564
|
-
if (!Array.isArray(questions))
|
|
565
|
-
return undefined;
|
|
566
|
-
const lines = questions
|
|
567
|
-
.map((question) => {
|
|
568
|
-
if (typeof question !== 'object' || question === null)
|
|
569
|
-
return '';
|
|
570
|
-
const record = question;
|
|
571
|
-
const text = typeof record['question'] === 'string'
|
|
572
|
-
? record['question']
|
|
573
|
-
: typeof record['header'] === 'string' ? record['header'] : '';
|
|
574
|
-
if (text.trim().length === 0)
|
|
575
|
-
return '';
|
|
576
|
-
const options = Array.isArray(record['options'])
|
|
577
|
-
? record['options']
|
|
578
|
-
.map((option) => (typeof option === 'object' && option !== null
|
|
579
|
-
? String(option['label'] ?? '')
|
|
580
|
-
: ''))
|
|
581
|
-
.filter((label) => label.length > 0)
|
|
582
|
-
: [];
|
|
583
|
-
return options.length === 0 ? text.trim() : `${text.trim()} [${options.join(' / ')}]`;
|
|
584
|
-
})
|
|
585
|
-
.filter((line) => line.length > 0);
|
|
586
|
-
return lines.length > 0 ? lines.join('\n') : undefined;
|
|
587
|
-
}
|
|
588
|
-
/**
|
|
589
|
-
* The answer carried by an `ask_user_question` result, or undefined.
|
|
590
|
-
*
|
|
591
|
-
* @param text - the result body.
|
|
592
|
-
* @returns the chosen labels, or the typed reply when nothing was chosen.
|
|
593
|
-
*/
|
|
594
|
-
function answerTextOf(text) {
|
|
595
|
-
let parsed;
|
|
596
|
-
try {
|
|
597
|
-
parsed = JSON.parse(text);
|
|
598
|
-
}
|
|
599
|
-
catch {
|
|
600
|
-
return undefined;
|
|
601
|
-
}
|
|
602
|
-
if (typeof parsed !== 'object' || parsed === null)
|
|
603
|
-
return undefined;
|
|
604
|
-
const answers = parsed['answers'];
|
|
605
|
-
if (!Array.isArray(answers))
|
|
606
|
-
return undefined;
|
|
607
|
-
const chosen = answers
|
|
608
|
-
.flatMap((answer) => {
|
|
609
|
-
if (typeof answer !== 'object' || answer === null)
|
|
610
|
-
return [];
|
|
611
|
-
const record = answer;
|
|
612
|
-
const selected = record['selected'];
|
|
613
|
-
const picked = Array.isArray(selected) ? selected.map((value) => String(value)) : [];
|
|
614
|
-
// A typed answer arrives with `selected: []` and the text in `custom`.
|
|
615
|
-
const typed = typeof record['custom'] === 'string' && record['custom'].trim().length > 0
|
|
616
|
-
? [record['custom'].trim()] : [];
|
|
617
|
-
return [...picked, ...typed];
|
|
618
|
-
})
|
|
619
|
-
.filter((value) => value.length > 0);
|
|
620
|
-
return chosen.length > 0 ? chosen.join(' / ') : undefined;
|
|
621
|
-
}
|
|
622
535
|
/** The turn number an event belongs to, when the log records one. */
|
|
623
536
|
function turnOf(event) {
|
|
624
537
|
const turn = event.data.turn;
|
|
@@ -626,7 +539,7 @@ function turnOf(event) {
|
|
|
626
539
|
}
|
|
627
540
|
/** A fresh, empty turn accumulator. */
|
|
628
541
|
function emptyTurn(turn) {
|
|
629
|
-
return { turn, user: [], assistant: [], tools: new Map(), resultBytes: 0, errors: [], writes: []
|
|
542
|
+
return { turn, user: [], assistant: [], tools: new Map(), resultBytes: 0, errors: [], writes: [] };
|
|
630
543
|
}
|
|
631
544
|
/**
|
|
632
545
|
* Group append-origin surface events into per-turn digest material.
|
|
@@ -660,8 +573,6 @@ export function buildSections(events) {
|
|
|
660
573
|
// objective on every round, so recording each copy would repeat it dozens of
|
|
661
574
|
// times across a long autonomous run.
|
|
662
575
|
const recordedObjectives = new Set();
|
|
663
|
-
// Question text by tool-call id, so the matching result can be read as its answer.
|
|
664
|
-
const pendingQuestions = new Map();
|
|
665
576
|
for (const event of events) {
|
|
666
577
|
if (event.type === 'turn/start') {
|
|
667
578
|
const turn = turnOf(event);
|
|
@@ -692,16 +603,6 @@ export function buildSections(events) {
|
|
|
692
603
|
const text = textOf(event);
|
|
693
604
|
currentTurn.resultBytes += text.length;
|
|
694
605
|
const message = messageOf(event);
|
|
695
|
-
// A question's own result is its answer. Recorded here rather than left to the
|
|
696
|
-
// model, which dropped or reworded it depending on its heading style.
|
|
697
|
-
const callId = message?.toolCallId;
|
|
698
|
-
if (callId !== undefined) {
|
|
699
|
-
const question = pendingQuestions.get(callId);
|
|
700
|
-
if (question !== undefined) {
|
|
701
|
-
pendingQuestions.delete(callId);
|
|
702
|
-
currentTurn.asked.push({ question, answer: answerTextOf(text) ?? '(no answer recorded)' });
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
606
|
if (message?.isError === true) {
|
|
706
607
|
const firstLine = text.split('\n')[0] ?? '';
|
|
707
608
|
currentTurn.errors.push(firstLine.slice(0, 100));
|
|
@@ -742,11 +643,6 @@ export function buildSections(events) {
|
|
|
742
643
|
if (text.length > 0)
|
|
743
644
|
currentTurn.assistant.push(text);
|
|
744
645
|
for (const call of toolCallsOf(event)) {
|
|
745
|
-
if (call.name === 'ask_user_question') {
|
|
746
|
-
const question = questionTextOf(call.arguments);
|
|
747
|
-
if (question !== undefined)
|
|
748
|
-
pendingQuestions.set(call.id, question);
|
|
749
|
-
}
|
|
750
646
|
currentTurn.tools.set(call.name, (currentTurn.tools.get(call.name) ?? 0) + 1);
|
|
751
647
|
if (!WRITE_TOOLS.has(call.name))
|
|
752
648
|
continue;
|
|
@@ -833,47 +729,6 @@ function materialKey(events) {
|
|
|
833
729
|
* The tool pointer line stays either way: it is one line, and it is the only
|
|
834
730
|
* record of what was actually run when the prose and extraction both say little.
|
|
835
731
|
*/
|
|
836
|
-
/**
|
|
837
|
-
* Move the `## Asked` section to the end of one extraction block.
|
|
838
|
-
*
|
|
839
|
-
* The digest reads as a conversation, and the user's next message is often just
|
|
840
|
-
* "8399" or "继续". That reply only makes sense beside the question it answers, so
|
|
841
|
-
* Asked belongs at the bottom of the block. The model puts it first about as often
|
|
842
|
-
* as last, so the order is fixed here rather than requested in the prompt.
|
|
843
|
-
*
|
|
844
|
-
* @param block - one extraction block, possibly malformed.
|
|
845
|
-
* @returns the same block with Asked last; unchanged when Asked is absent or already last.
|
|
846
|
-
*/
|
|
847
|
-
export function moveAskedLast(block, asked = []) {
|
|
848
|
-
const lines = block.split('\n');
|
|
849
|
-
// Recognise every form the model has used for this section, in both languages, so
|
|
850
|
-
// it can be dropped. The content is regenerated from the log instead: four format
|
|
851
|
-
// changes across runs each broke either the position or the wording, and the log
|
|
852
|
-
// already holds both halves verbatim.
|
|
853
|
-
const isAsked = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(?:Asked|问)(?:\*\*)?\s*[::]?\s*$/i.test(line);
|
|
854
|
-
const isAskedInline = (line) => /^\s*(?:[-*]\s+)?(?:\*\*)?(?:Asked|问)(?:\*\*)?\s*[::]/i.test(line);
|
|
855
|
-
const isOther = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(?:Did|Concluded|Overturned|做|结论|推翻)(?:\*\*)?\s*[::]?/i.test(line);
|
|
856
|
-
const start = lines.findIndex((line) => isAsked(line) || isAskedInline(line));
|
|
857
|
-
const kept = [...lines];
|
|
858
|
-
if (start >= 0) {
|
|
859
|
-
const inline = isAskedInline(kept[start] ?? '') && !isAsked(kept[start] ?? '');
|
|
860
|
-
let end = start + 1;
|
|
861
|
-
if (!inline) {
|
|
862
|
-
while (end < kept.length && !isOther(kept[end] ?? ''))
|
|
863
|
-
end += 1;
|
|
864
|
-
}
|
|
865
|
-
kept.splice(start, end - start);
|
|
866
|
-
}
|
|
867
|
-
while (kept.length > 0 && (kept.at(-1) ?? '').trim().length === 0)
|
|
868
|
-
kept.pop();
|
|
869
|
-
if (asked.length === 0)
|
|
870
|
-
return kept.join('\n');
|
|
871
|
-
const block_lines = asked.map(({ question, answer }) => {
|
|
872
|
-
const q = question.split('\n').join(' ');
|
|
873
|
-
return `- ${q} → ${answer}`;
|
|
874
|
-
});
|
|
875
|
-
return [...kept, '', '## Asked', ...block_lines].join('\n');
|
|
876
|
-
}
|
|
877
732
|
function renderSection(section, capChars) {
|
|
878
733
|
const lines = [];
|
|
879
734
|
for (const turn of section.turns) {
|
|
@@ -886,18 +741,17 @@ function renderSection(section, capChars) {
|
|
|
886
741
|
if (capChars !== undefined && block.length > capChars) {
|
|
887
742
|
block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
|
|
888
743
|
}
|
|
889
|
-
//
|
|
890
|
-
//
|
|
891
|
-
//
|
|
892
|
-
// — see moveAskedLast being applied after the trailer is joined.
|
|
744
|
+
// The trailer goes *above* the block, not below it. `## Asked` is the block's
|
|
745
|
+
// last section and the user's reply is the very next line, so an errors line
|
|
746
|
+
// in between would separate the reply from the question it answers.
|
|
893
747
|
const trailer = [];
|
|
894
748
|
if (turn.errors.length > 0) {
|
|
895
749
|
trailer.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
|
|
896
750
|
}
|
|
897
751
|
if (turn.writes.length > 0)
|
|
898
752
|
trailer.push(` wrote: ${turn.writes.join(', ')}`);
|
|
899
|
-
const body = trailer.length > 0 ? `${
|
|
900
|
-
lines.push(`### assistant\n${
|
|
753
|
+
const body = trailer.length > 0 ? `${trailer.join('\n')}\n${block}` : block;
|
|
754
|
+
lines.push(`### assistant\n${body}`);
|
|
901
755
|
}
|
|
902
756
|
else {
|
|
903
757
|
let body = turn.assistant.join('\n');
|
|
@@ -1133,27 +987,114 @@ export function buildExtractionMaterial(turn, prose) {
|
|
|
1133
987
|
* compaction does (`ctx.llm.stream` with the session's provider/model), so no
|
|
1134
988
|
* separate credential or configuration is involved.
|
|
1135
989
|
*
|
|
1136
|
-
* Every failure path
|
|
1137
|
-
* a compaction that cannot reach the model must still compact, or the
|
|
1138
|
-
* dies of context overflow instead of losing detail.
|
|
990
|
+
* Every failure path yields no blocks and the caller falls back to the plain
|
|
991
|
+
* digest: a compaction that cannot reach the model must still compact, or the
|
|
992
|
+
* session dies of context overflow instead of losing detail. The degradation is
|
|
993
|
+
* per turn, but it is never silent — a batch that comes back unusable is
|
|
994
|
+
* reported, because the whole point of that fallback is invisible otherwise.
|
|
1139
995
|
*
|
|
1140
|
-
* @param ctx - plugin context carrying the `llm` service.
|
|
996
|
+
* @param ctx - plugin context carrying the `llm` service and a logger.
|
|
1141
997
|
* @param agent - owner of the session being compacted; supplies the routed model.
|
|
1142
|
-
* @param
|
|
1143
|
-
* @param prose - that turn's assistant prose, already extracted.
|
|
998
|
+
* @param batch - slots to extract, in one call unless the answer is truncated.
|
|
1144
999
|
* @param signal - cancellation forwarded to the adapter.
|
|
1145
|
-
* @returns the extracted
|
|
1000
|
+
* @returns the extracted blocks by slot key; empty when extraction is unavailable.
|
|
1146
1001
|
*/
|
|
1147
1002
|
async function extractBatch(ctx, agent, batch, signal) {
|
|
1003
|
+
const out = new Map();
|
|
1004
|
+
if (batch.length === 0)
|
|
1005
|
+
return out;
|
|
1006
|
+
const attempt = await extractOnce(ctx, agent, batch, signal);
|
|
1007
|
+
if (!attempt.truncated) {
|
|
1008
|
+
if (attempt.blocks.size === 0) {
|
|
1009
|
+
ctx.logger?.warn(`verbatim-compaction: extraction returned no usable JSON for ${batch.length} slot(s) `
|
|
1010
|
+
+ `(${batch.map((slot) => slot.key).join(', ')}); those turns keep their verbatim prose`);
|
|
1011
|
+
}
|
|
1012
|
+
return attempt.blocks;
|
|
1013
|
+
}
|
|
1014
|
+
// A truncated answer parses to nothing, so one over-budget turn would cost
|
|
1015
|
+
// every turn in its batch. Measured on 191 real compactions, failures arrived
|
|
1016
|
+
// in runs of exactly `TURNS_PER_CALL`, which is this batching, not the model
|
|
1017
|
+
// failing per turn. Halving bounds the loss to the half that still does not
|
|
1018
|
+
// fit, and a single slot cannot be split further.
|
|
1019
|
+
if (batch.length === 1) {
|
|
1020
|
+
ctx.logger?.warn(`verbatim-compaction: extraction truncated at the token cap for slot ${batch[0]?.key ?? '?'}; `
|
|
1021
|
+
+ 'that turn keeps its verbatim prose');
|
|
1022
|
+
return attempt.blocks;
|
|
1023
|
+
}
|
|
1024
|
+
for (const [key, block] of attempt.blocks)
|
|
1025
|
+
out.set(key, block);
|
|
1026
|
+
const middle = Math.ceil(batch.length / 2);
|
|
1027
|
+
for (const half of [batch.slice(0, middle), batch.slice(middle)]) {
|
|
1028
|
+
for (const [key, block] of await extractBatch(ctx, agent, half, signal))
|
|
1029
|
+
out.set(key, block);
|
|
1030
|
+
}
|
|
1031
|
+
return out;
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* The cheapest effort a route advertises, or undefined when it advertises none.
|
|
1035
|
+
*
|
|
1036
|
+
* The route's own default is not used: it is typically the highest level, and
|
|
1037
|
+
* thinking is paid out of the answer's token budget. The list is ordered from
|
|
1038
|
+
* least to greatest effort by the host's own contract, so the first entry is the
|
|
1039
|
+
* cheapest. `off` is skipped even when present — pi-ai maps it to a wire value
|
|
1040
|
+
* the route may reject, and a level that cannot be sent is worse than a cheap
|
|
1041
|
+
* one that can.
|
|
1042
|
+
*
|
|
1043
|
+
* @param efforts - the route's advertised efforts, in escalation order.
|
|
1044
|
+
* @returns the cheapest usable effort id, or undefined to leave the choice alone.
|
|
1045
|
+
*/
|
|
1046
|
+
function cheapestEffort(efforts) {
|
|
1047
|
+
return efforts?.find((entry) => entry.id !== 'off')?.id;
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* One extraction request, no retry.
|
|
1051
|
+
*
|
|
1052
|
+
* The cap must carry a fixed thinking reserve on top of the per-slot output
|
|
1053
|
+
* budget. `maxTokens` covers thinking and the answer together, and thinking is
|
|
1054
|
+
* a per-call cost that does not shrink when the batch does. Measured against the
|
|
1055
|
+
* live route (deepseek-flash, `reasoning_effort` unset, real-length material):
|
|
1056
|
+
* a single slot at the old `220 x 1` cap returned zero parseable slots in 4 of 4
|
|
1057
|
+
* runs, the thinking block having consumed the entire cap; the same single slot
|
|
1058
|
+
* at `220 x 1 + 1000` parsed in 4 of 4. The reserve is what makes the cap work
|
|
1059
|
+
* for a batch of any size, including the batches the caller splits down to.
|
|
1060
|
+
*
|
|
1061
|
+
* The effort is pinned to the route's cheapest advertised level rather than left
|
|
1062
|
+
* to the route default. Thinking is paid out of the same `maxTokens` as the
|
|
1063
|
+
* answer, so a default that thinks hard shrinks the answer budget even with the
|
|
1064
|
+
* reserve in place. Measured on the live route at a 2-slot cap with the reserve:
|
|
1065
|
+
* `low` spent 375 thinking tokens and parsed 3 of 3; `high` spent 931 and parsed
|
|
1066
|
+
* 2 of 3.
|
|
1067
|
+
*
|
|
1068
|
+
* Two things that look like fixes and are not:
|
|
1069
|
+
*
|
|
1070
|
+
* - `off` cannot be reached through pi-ai. Its `deepseek` thinking format maps
|
|
1071
|
+
* the `off` level to `reasoning_effort: "minimal"`, which the route rejects
|
|
1072
|
+
* outright (`valid levels: low, medium, high`), and its `thinking` field is
|
|
1073
|
+
* pinned to `{type: "enabled"}` for every level. Captured from pi-ai 1.3.0
|
|
1074
|
+
* against a local echo server, not inferred.
|
|
1075
|
+
* - Only the provider's own `thinking: {type: "disabled"}` actually stops
|
|
1076
|
+
* thinking (0 thinking tokens, measured), but `GenerateOptions` has no field
|
|
1077
|
+
* that carries it, so no plugin on this seam can send it.
|
|
1078
|
+
*
|
|
1079
|
+
* An effort is requested only when the route advertises it, because the host
|
|
1080
|
+
* rejects one it does not.
|
|
1081
|
+
*
|
|
1082
|
+
* @param ctx - plugin context carrying the `llm` service and a logger.
|
|
1083
|
+
* @param agent - owner of the session being compacted.
|
|
1084
|
+
* @param batch - slots to ask about in this one call.
|
|
1085
|
+
* @param signal - cancellation forwarded to the adapter.
|
|
1086
|
+
* @returns the parsed blocks and whether the model stopped at the token cap.
|
|
1087
|
+
*/
|
|
1088
|
+
async function extractOnce(ctx, agent, batch, signal) {
|
|
1148
1089
|
const out = new Map();
|
|
1149
1090
|
const llm = ctx.llm;
|
|
1150
1091
|
if (llm === undefined)
|
|
1151
|
-
return out;
|
|
1092
|
+
return { blocks: out, truncated: false };
|
|
1152
1093
|
const route = agent.session.requestHeader()?.config;
|
|
1153
1094
|
const provider = route?.provider ?? agent.options.provider;
|
|
1154
1095
|
const model = route?.model ?? agent.options.model;
|
|
1155
1096
|
if (provider === undefined || model === undefined)
|
|
1156
|
-
return out;
|
|
1097
|
+
return { blocks: out, truncated: false };
|
|
1157
1098
|
// The label the model echoes back is the slot key, not the turn number: two
|
|
1158
1099
|
// requests can share a number, and a duplicate label would collapse two blocks
|
|
1159
1100
|
// into one entry.
|
|
@@ -1170,8 +1111,13 @@ async function extractBatch(ctx, agent, batch, signal) {
|
|
|
1170
1111
|
parts.push(`=== SLOT ${slot.key} (turn ${slot.turn ?? '?'}) ===\n${material}`);
|
|
1171
1112
|
}
|
|
1172
1113
|
if (parts.length === 0)
|
|
1173
|
-
return out;
|
|
1114
|
+
return { blocks: out, truncated: false };
|
|
1115
|
+
const info = await Promise.resolve()
|
|
1116
|
+
.then(() => llm.resolveModelInfo?.(provider, model, signal))
|
|
1117
|
+
.catch(() => undefined);
|
|
1118
|
+
const cheapest = cheapestEffort(info?.reasoning?.efforts);
|
|
1174
1119
|
const chunks = [];
|
|
1120
|
+
let truncated = false;
|
|
1175
1121
|
try {
|
|
1176
1122
|
const stream = llm.stream({
|
|
1177
1123
|
provider,
|
|
@@ -1179,24 +1125,28 @@ async function extractBatch(ctx, agent, batch, signal) {
|
|
|
1179
1125
|
messages: [
|
|
1180
1126
|
{ role: 'user', content: [{ type: 'text', text: `${parts.join('\n\n')}\n\n${EXTRACT_INSTRUCTION}` }] },
|
|
1181
1127
|
],
|
|
1182
|
-
maxTokens: EXTRACT_TOKENS_PER_TURN * parts.length,
|
|
1128
|
+
maxTokens: EXTRACT_TOKENS_PER_TURN * parts.length + EXTRACT_THINKING_RESERVE_TOKENS,
|
|
1183
1129
|
sessionId: agent.session.id,
|
|
1184
1130
|
purpose: 'compaction',
|
|
1131
|
+
...(cheapest === undefined ? {} : { reasoningEffort: cheapest }),
|
|
1185
1132
|
...(signal === undefined ? {} : { signal }),
|
|
1186
1133
|
});
|
|
1187
1134
|
for await (const chunk of stream) {
|
|
1188
1135
|
const delta = chunk;
|
|
1189
1136
|
if (delta.type === 'text-delta' && typeof delta.text === 'string')
|
|
1190
1137
|
chunks.push(delta.text);
|
|
1138
|
+
else if (delta.type === 'finish' && delta.reason?.kind === 'max-tokens')
|
|
1139
|
+
truncated = true;
|
|
1191
1140
|
}
|
|
1192
1141
|
}
|
|
1193
|
-
catch {
|
|
1194
|
-
|
|
1142
|
+
catch (error) {
|
|
1143
|
+
ctx.logger?.warn(`verbatim-compaction: extraction call failed for ${parts.length} slot(s): ${String(error)}`);
|
|
1144
|
+
return { blocks: out, truncated: false };
|
|
1195
1145
|
}
|
|
1196
1146
|
const answer = chunks.join('').trim();
|
|
1197
1147
|
if (answer.length === 0)
|
|
1198
|
-
return out;
|
|
1199
|
-
return parseExtraction(answer);
|
|
1148
|
+
return { blocks: out, truncated };
|
|
1149
|
+
return { blocks: parseExtraction(answer), truncated };
|
|
1200
1150
|
}
|
|
1201
1151
|
/**
|
|
1202
1152
|
* Deterministic compaction backend: verbatim prose, pointerized tools, no model
|
package/lib/types/index.d.ts
CHANGED
|
@@ -80,28 +80,41 @@ 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
|
-
/**
|
|
84
|
-
* Drop headings whose body says nothing.
|
|
85
|
-
*
|
|
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.
|
|
90
|
-
*
|
|
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.
|
|
94
|
-
*
|
|
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.
|
|
98
|
-
*/
|
|
99
|
-
export declare function pruneEmptySections(block: string): string;
|
|
100
83
|
/** One slot's extraction, as the model returns it. */
|
|
101
84
|
export interface Extraction {
|
|
102
85
|
did: string[];
|
|
103
86
|
concluded: string[];
|
|
104
87
|
overturned: string[];
|
|
88
|
+
/**
|
|
89
|
+
* What this turn asked the user and what came back, when it asked anything.
|
|
90
|
+
*
|
|
91
|
+
* Written by the model rather than read off the log. The two cases the log
|
|
92
|
+
* cannot cover are the reason:
|
|
93
|
+
*
|
|
94
|
+
* - A question is often not in the last line. Over 231 real turns that drew a
|
|
95
|
+
* short reply, 34% had prose after the question (p90 = 7 paragraphs, max
|
|
96
|
+
* 24) — a `## 需要你决定` block followed by `## 还没验证的`. The log records
|
|
97
|
+
* text, not which paragraph was the question.
|
|
98
|
+
* - A bare `1` is meaningless without the list it selects from, and that list
|
|
99
|
+
* is usually a paragraph or more above the question, under its own heading.
|
|
100
|
+
* Reading it out needs judgement about which list the question refers to.
|
|
101
|
+
*
|
|
102
|
+
* The model already reads the same prose to fill `did`/`concluded`, so this
|
|
103
|
+
* costs one more field rather than another pass.
|
|
104
|
+
*/
|
|
105
|
+
asked: AskedPair[];
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* One question the assistant put to the user, with the options it offered.
|
|
109
|
+
*
|
|
110
|
+
* No `answer` field: the reply is the next section's `## user` line, already in the
|
|
111
|
+
* digest verbatim. Carrying it here as well printed the same sentence twice.
|
|
112
|
+
*/
|
|
113
|
+
export interface AskedPair {
|
|
114
|
+
/** The question, one line. */
|
|
115
|
+
question: string;
|
|
116
|
+
/** The options as offered, each one line; empty when the question offered none. */
|
|
117
|
+
options: string[];
|
|
105
118
|
}
|
|
106
119
|
/**
|
|
107
120
|
* Parse the model's JSON reply into per-slot extractions.
|
|
@@ -148,17 +161,6 @@ interface Turn {
|
|
|
148
161
|
resultBytes: number;
|
|
149
162
|
errors: string[];
|
|
150
163
|
writes: string[];
|
|
151
|
-
/**
|
|
152
|
-
* Question/answer pairs the assistant put to the user in this turn.
|
|
153
|
-
*
|
|
154
|
-
* Rendered by code rather than by the model: the model changed its Asked format
|
|
155
|
-
* four times across runs, and each change silently broke the position or the
|
|
156
|
-
* content. Both halves are in the log, so there is nothing to summarise.
|
|
157
|
-
*/
|
|
158
|
-
asked: {
|
|
159
|
-
question: string;
|
|
160
|
-
answer: string;
|
|
161
|
-
}[];
|
|
162
164
|
/**
|
|
163
165
|
* The extracted summary for this turn, when extraction succeeded.
|
|
164
166
|
*
|
|
@@ -185,32 +187,6 @@ interface Section {
|
|
|
185
187
|
* @returns one section per non-injected user message.
|
|
186
188
|
*/
|
|
187
189
|
export declare function buildSections(events: readonly SessionEvent[]): Section[];
|
|
188
|
-
/**
|
|
189
|
-
* Render one section to digest text, truncating assistant prose to `capChars`.
|
|
190
|
-
*
|
|
191
|
-
* When the turn carries an extraction, that extraction *replaces* the assistant
|
|
192
|
-
* prose. Keeping both was the duplication this design removes: 58.2% of
|
|
193
|
-
* assistant characters are substantive conclusions that the extraction restates,
|
|
194
|
-
* and the doubled copy pushed real history out through the budget.
|
|
195
|
-
*
|
|
196
|
-
* The tool pointer line stays either way: it is one line, and it is the only
|
|
197
|
-
* record of what was actually run when the prose and extraction both say little.
|
|
198
|
-
*/
|
|
199
|
-
/**
|
|
200
|
-
* Move the `## Asked` section to the end of one extraction block.
|
|
201
|
-
*
|
|
202
|
-
* The digest reads as a conversation, and the user's next message is often just
|
|
203
|
-
* "8399" or "继续". That reply only makes sense beside the question it answers, so
|
|
204
|
-
* Asked belongs at the bottom of the block. The model puts it first about as often
|
|
205
|
-
* as last, so the order is fixed here rather than requested in the prompt.
|
|
206
|
-
*
|
|
207
|
-
* @param block - one extraction block, possibly malformed.
|
|
208
|
-
* @returns the same block with Asked last; unchanged when Asked is absent or already last.
|
|
209
|
-
*/
|
|
210
|
-
export declare function moveAskedLast(block: string, asked?: readonly {
|
|
211
|
-
question: string;
|
|
212
|
-
answer: string;
|
|
213
|
-
}[]): string;
|
|
214
190
|
/**
|
|
215
191
|
* Render the digest under a hard character budget.
|
|
216
192
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@logictan/dsh-verbatim-compaction",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.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",
|