@logictan/dsh-verbatim-compaction 0.12.1 → 0.13.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 +17 -9
- package/lib/index.js +258 -159
- package/lib/types/index.d.ts +62 -18
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -21,18 +21,24 @@
|
|
|
21
21
|
(用户原话,逐字,永不改写)
|
|
22
22
|
|
|
23
23
|
### assistant
|
|
24
|
-
## Asked
|
|
25
|
-
- 是否要用 FULL 而不是 INCREMENTAL
|
|
26
24
|
## Did
|
|
27
25
|
- 实测 `auto_vacuum=FULL` 删除后自动缩容:19.61 MB → 0.01 MB
|
|
28
26
|
## Concluded
|
|
29
27
|
- 选 FULL:回收发生在宿主自己的 DELETE 里,不受 busy_timeout=0 影响
|
|
30
28
|
## Overturned
|
|
31
29
|
- 先前认为必须显式执行 VACUUM 才能回收空间
|
|
32
|
-
errors: 1: Error: 命令超过 600 秒未结束,已断开连接
|
|
33
30
|
wrote: /Volumes/LogicExt/Git/BookReader/src/video.js
|
|
31
|
+
## Answers
|
|
32
|
+
- 验证码已发出,请输入手机上收到的验证码
|
|
33
|
+
→ 现在试(推荐)
|
|
34
|
+
## Asked
|
|
35
|
+
- 是否要用 FULL 而不是 INCREMENTAL
|
|
36
|
+
1. 用 FULL
|
|
37
|
+
2. 用 INCREMENTAL
|
|
34
38
|
```
|
|
35
39
|
|
|
40
|
+
`## Answers` 是走 `ask_user_question` 的问答,由代码从日志渲染;`## Asked` 是模型从正文里认出来的提问。两者并列,各管一半——`## Asked` 永远在最后,因为它的用户回复就是下一行。
|
|
41
|
+
|
|
36
42
|
标题不带轮次号:日志里的 `turn` 号既不唯一也不是一轮一个(一个真实会话把两条请求都编号成 1),印出来就是会撒谎的标题。
|
|
37
43
|
|
|
38
44
|
- **用户原话逐字**,不重写、不改写、不摘要。
|
|
@@ -60,7 +66,7 @@
|
|
|
60
66
|
|
|
61
67
|
只抄正文救不了「正文为空」的轮次。实测一个 13878 事件的会话:1973 条 assistant 消息里只有 317 条带正文,其中一轮跑了 342 次工具调用却一个字没写,纯逐字摘要把它压成一行 `tools: bash×281`——活干了,记录没了。
|
|
62
68
|
|
|
63
|
-
所以提取的材料是三段:用户请求(逐字)、助手正文(逐字)、工具轨迹(每条调用的 `description
|
|
69
|
+
所以提取的材料是三段:用户请求(逐字)、助手正文(逐字)、工具轨迹(每条调用的 `description`)。工具结果一条都不读:唯一曾被读出的东西是失败结果的首行,而那一行永远是传输或退出状态(`命令超过 600 秒未结束`),不是让失败有意义的那部分。模型输出四个字段:`asked` / `did` / `concluded` / `overturned`,标题与项目符号由渲染器拼装。
|
|
64
70
|
|
|
65
71
|
空节直接不出现:「没有内容」是一个空数组,不是需要事后识别的占位符。字段化之前是自由 markdown,模型写 `## Overturned\n- (none)` 就得在代码里再认一遍占位符,实测一份真实提取块里 `## Asked` 和 `## Overturned` 都是 `(none)`,删掉后 312 → 271 字符;按 130 轮算,这些占位合计约 900 token 只是在记录「什么都没发生」。现在这类占位在解析阶段就被滤掉,不再有一个专门的清理函数。`none of the tests passed`、`无法连接,改用代理` 这类真内容照原样保留。
|
|
66
72
|
|
|
@@ -74,7 +80,7 @@
|
|
|
74
80
|
|
|
75
81
|
三件事刻意做成这样:
|
|
76
82
|
|
|
77
|
-
-
|
|
83
|
+
- **工具轨迹不读工具结果**。曾经读失败结果的首行(先用 `/error/i` 匹配,347 条成功结果全部命中;改用 `data.isError` 后信号是对的,但那行文字从没被模型用上)。摘要里既没有 `ERR` 行,也没有 ` errors: N: …` 尾行。唯一的例外是 `ask_user_question` 的答案,它本身就是工具结果,由 `## Answers` 单独承载(见下)。
|
|
78
84
|
- **工具调用从 `assistant/message` 的 block 里取**。日志里没有独立的 `tool/call` 事件类型,按它过滤会一条都取不到。
|
|
79
85
|
- **提取失败就退回逐字正文**。模型不可达、超时、输出为空时,该轮保留原来的助手正文;压缩本身不能因此失败,否则会话死于上下文溢出,比丢细节更糟。降级是逐轮的:一批里某一轮没答,只有那一轮退回正文。**但降级不再无声**:整批拿不到可用 JSON、或单槽位在令牌上限被截断,都会打一条 `verbatim-compaction:` 开头的 warn,写明受影响的 slot key。没有这条日志时,插件退化成纯逐字摘要这件事在运行期完全不可观测——这正是「JSON 经常不生效却查不到」的成因。
|
|
80
86
|
|
|
@@ -96,15 +102,17 @@
|
|
|
96
102
|
|
|
97
103
|
**为什么不能只靠日志读。** 两件事需要判断,而不是取字段:其一,提问不在可靠的位置——231 个「引出了短回复」的真实轮次里,34% 的提问后面还有正文(p90 = 7 段,最多 24 段),形如 `## 需要你决定` 后面又跟一节 `## 还没验证的`;其二,选项通常也不在提问旁边——28 个纯数字回复的轮次里,28 个都提供过编号列表,但只有 26/231 轮那份列表落在提问本段或前一段,多数隔着自己的小标题在上面。要认出「这个提问指的是哪份列表」需要判断,日志里只有文字。
|
|
98
104
|
|
|
99
|
-
**`answer` 字段被明确去掉。**
|
|
105
|
+
**`answer` 字段被明确去掉。** 正文里提的问,回复就是下一节的 `## user` 行,逐字渲染;再写进 `asked.answer` 等于同一句话印两遍。指令里对应加了一条「不要报告用户的回复」,渲染上 `## Asked` 是块的最后一节,所以回复永远紧接在它下面。
|
|
106
|
+
|
|
107
|
+
**但「回复就在下一节 `## user`」只对正文提问成立。** 走 `ask_user_question` 的提问,用户是在工具自己的选择界面里作答的,答案变成**工具结果**,日志里根本没有 user 消息——实测一个真实会话:三个问题全部在界面里答完,相邻事件是 `tool/result`(`{"answers":[{"id","selected","custom"}]}`),没有 `user/message`,而连续两次检查点的摘要里问题和选择全都不在。所以工具问答由代码从日志确定性渲染成 `## Answers` 一节,与模型的 `asked` 并列、互不重叠:`ask_user_question` 不再进工具轨迹,模型也就无从复述它。
|
|
108
|
+
|
|
109
|
+
宿主还有第二种送达方式:用户在工具已经返回 pending 提示之后才答,宿主会补写一条 `user/message`,`source.kind` 是 `user-question-reply`,正文是同一份答案批次 JSON(连 `questions` 一起带上)。这条消息不是新请求,所以不另起 section,答案照样进 `## Answers`——它原本会被「只认 `user`/`goal`」的注入过滤整条丢掉。
|
|
100
110
|
|
|
101
111
|
`## Asked` 的位置由渲染器保证在最后,不靠模型。选项在问题下面缩进编号列出,`- 问题` 一行、` 1. …` 各行,用户的 `1` 因此有东西可指。
|
|
102
112
|
|
|
103
113
|
**选项自带的编号会被剥掉。** 模型会把源列表的 `1.` 一起抄进 `options`,渲染器再加一次编号就变成 `1. 1. …`;实测 5 次里 3 次如此,所以在解析阶段用正则剥掉,而不是只靠指令。
|
|
104
114
|
|
|
105
|
-
`ask_user_question`
|
|
106
|
-
|
|
107
|
-
`ask_user_question` 的问题与用户选择都会进材料。它没有 `description` 参数,载荷在 `questions[]`,原来只留下 `TOOL ask_user_question` 五个字——问题是什么、用户选了什么全丢。答案在工具结果里(`answers[].selected`,或用户自己打字时的 `answers[].custom`),实测 31 次提问里 10 次是打字回答。
|
|
115
|
+
`ask_user_question` 既不进工具轨迹、也不受 120 条调用上限约束,因为它的问答已经整组由代码渲染进 `## Answers`。答案取 `answers[].selected`;用户没选而是自己打字的,答案在 `answers[].custom`(实测 31 次提问里 10 次是打字回答),两条都渲染。
|
|
108
116
|
|
|
109
117
|
一个 section 就是一次请求、一个 turn。日志会在同一次请求里推进 turn 号(实测一个请求的 7 条助手消息记作 turn 2、另 9 条记作 turn 3),按号码切分会把一个请求拆成「空请求 turn + 无用户消息的回复 turn」,摘要里就出现两个 `### assistant`。用户消息本身不带 turn 字段,这条也曾让两者永远对不上。
|
|
110
118
|
|
package/lib/index.js
CHANGED
|
@@ -31,8 +31,40 @@
|
|
|
31
31
|
* @module @logictan/dsh-verbatim-compaction
|
|
32
32
|
*/
|
|
33
33
|
import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
|
|
34
|
+
import { ReasoningEffortId } from '@deepseek-ai/dsh-llm';
|
|
35
|
+
import Schema from '@deepseek-ai/schemastery';
|
|
34
36
|
/** Cordis companion plugin name. Must equal this plugin's `cordis.patch.yml` row id. */
|
|
35
37
|
export const name = 'verbatim-compaction';
|
|
38
|
+
/** Three editable scalars; empty strings mean "follow the chat model". */
|
|
39
|
+
export const OVERRIDE_FIELDS = {
|
|
40
|
+
provider: Schema.string().default('').volatile(),
|
|
41
|
+
model: Schema.string().default('').volatile(),
|
|
42
|
+
reasoningEffort: Schema.string().default('').volatile(),
|
|
43
|
+
};
|
|
44
|
+
/** A provider/model override takes effect only as a complete pair. */
|
|
45
|
+
export function pairedRouteOf(config) {
|
|
46
|
+
const provider = config?.provider?.get().trim();
|
|
47
|
+
const model = config?.model?.get().trim();
|
|
48
|
+
return provider !== undefined && provider !== '' && model !== undefined && model !== ''
|
|
49
|
+
? { provider, model }
|
|
50
|
+
: undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Apply the optional override; without a configured effort the cheapest usable
|
|
54
|
+
* effort still wins, because a route's own default is typically the priciest.
|
|
55
|
+
*/
|
|
56
|
+
export function applyPurposeOverride(options, config, cheapest) {
|
|
57
|
+
const route = pairedRouteOf(config);
|
|
58
|
+
const configured = config?.reasoningEffort?.get().trim();
|
|
59
|
+
const effort = configured !== undefined && configured !== '' ? configured : cheapest;
|
|
60
|
+
if (route === undefined && effort === undefined)
|
|
61
|
+
return options;
|
|
62
|
+
return {
|
|
63
|
+
...options,
|
|
64
|
+
...(route === undefined ? {} : { provider: route.provider, model: route.model }),
|
|
65
|
+
...(effort === undefined ? {} : { reasoningEffort: ReasoningEffortId(effort) }),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
36
68
|
/**
|
|
37
69
|
* Absolute ceiling for one digest, in the meter's fixed 4-chars-per-token
|
|
38
70
|
* heuristic.
|
|
@@ -161,73 +193,108 @@ function toolCallsOf(event) {
|
|
|
161
193
|
}
|
|
162
194
|
return calls;
|
|
163
195
|
}
|
|
196
|
+
/** The `questions[]` payload of an `ask_user_question` call, as `{id → text}`. */
|
|
197
|
+
function questionTextsOf(argumentsJson) {
|
|
198
|
+
const out = new Map();
|
|
199
|
+
let parsed;
|
|
200
|
+
try {
|
|
201
|
+
parsed = JSON.parse(argumentsJson);
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
207
|
+
return out;
|
|
208
|
+
const questions = parsed['questions'];
|
|
209
|
+
if (!Array.isArray(questions))
|
|
210
|
+
return out;
|
|
211
|
+
for (const question of questions) {
|
|
212
|
+
if (typeof question !== 'object' || question === null)
|
|
213
|
+
continue;
|
|
214
|
+
const record = question;
|
|
215
|
+
const id = record['id'];
|
|
216
|
+
const text = typeof record['question'] === 'string' ? record['question'] : undefined;
|
|
217
|
+
if (typeof id === 'string' && text !== undefined)
|
|
218
|
+
out.set(id, text);
|
|
219
|
+
}
|
|
220
|
+
return out;
|
|
221
|
+
}
|
|
164
222
|
/**
|
|
165
|
-
*
|
|
223
|
+
* Read one answer batch into per-question answers.
|
|
166
224
|
*
|
|
167
|
-
* The
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
225
|
+
* The batch is `{answers:[{id, selected:[…], custom?}]}`, and it arrives two
|
|
226
|
+
* ways: as the result of an answered `ask_user_question` call, and inside the
|
|
227
|
+
* `user/message` the host writes when the user answers after the call already
|
|
228
|
+
* returned its pending notice. Both carry the same shape, so both are read here.
|
|
171
229
|
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
230
|
+
* A typed answer arrives with `selected: []` and the text in `custom`. Ten of 31
|
|
231
|
+
* real questions in one session were answered that way, and those carried the
|
|
232
|
+
* user's actual observations rather than a menu label.
|
|
233
|
+
*
|
|
234
|
+
* @param text - the JSON body.
|
|
235
|
+
* @param texts - question id to question text, from the call's arguments.
|
|
236
|
+
* @returns one entry per answered question; empty when the body is not a batch.
|
|
175
237
|
*/
|
|
176
|
-
function
|
|
177
|
-
if (askedIds.size === 0)
|
|
178
|
-
return undefined;
|
|
179
|
-
const message = messageOf(event);
|
|
180
|
-
if (message === null)
|
|
181
|
-
return undefined;
|
|
182
|
-
const callId = message.toolCallId;
|
|
183
|
-
if (callId === undefined || !askedIds.has(callId))
|
|
184
|
-
return undefined;
|
|
185
|
-
const text = textOf(event);
|
|
238
|
+
function answersOf(text, texts) {
|
|
186
239
|
let parsed;
|
|
187
240
|
try {
|
|
188
241
|
parsed = JSON.parse(text);
|
|
189
242
|
}
|
|
190
243
|
catch {
|
|
191
|
-
return
|
|
244
|
+
return [];
|
|
192
245
|
}
|
|
193
246
|
if (typeof parsed !== 'object' || parsed === null)
|
|
194
|
-
return
|
|
195
|
-
|
|
247
|
+
return [];
|
|
248
|
+
// A late reply carries its own `questions` array beside the answers, so it does
|
|
249
|
+
// not depend on the call still being in the same turn's events.
|
|
250
|
+
const body = parsed;
|
|
251
|
+
const own = Array.isArray(body['questions']) ? body['questions'] : [];
|
|
252
|
+
const merged = new Map(texts);
|
|
253
|
+
for (const question of own) {
|
|
254
|
+
if (typeof question !== 'object' || question === null)
|
|
255
|
+
continue;
|
|
256
|
+
const record = question;
|
|
257
|
+
const id = record['id'];
|
|
258
|
+
const text = record['question'];
|
|
259
|
+
if (typeof id === 'string' && typeof text === 'string')
|
|
260
|
+
merged.set(id, text);
|
|
261
|
+
}
|
|
262
|
+
const answers = body['answers'];
|
|
196
263
|
if (!Array.isArray(answers))
|
|
197
|
-
return
|
|
198
|
-
const
|
|
199
|
-
|
|
264
|
+
return [];
|
|
265
|
+
const out = [];
|
|
266
|
+
for (const answer of answers) {
|
|
200
267
|
if (typeof answer !== 'object' || answer === null)
|
|
201
|
-
|
|
268
|
+
continue;
|
|
202
269
|
const record = answer;
|
|
203
|
-
const
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
270
|
+
const id = typeof record['id'] === 'string' ? record['id'] : '';
|
|
271
|
+
const question = merged.get(id);
|
|
272
|
+
if (question === undefined)
|
|
273
|
+
continue;
|
|
274
|
+
const selected = Array.isArray(record['selected'])
|
|
275
|
+
? record['selected'].map((value) => String(value)).filter((value) => value.length > 0)
|
|
276
|
+
: [];
|
|
277
|
+
const typed = typeof record['custom'] === 'string' ? record['custom'].trim() : '';
|
|
278
|
+
if (selected.length === 0 && typed.length === 0)
|
|
279
|
+
continue;
|
|
280
|
+
out.push({ question, selected, typed });
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
215
283
|
}
|
|
216
284
|
/**
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
* Reads `data.message.isError` and nothing else. Matching the serialized text
|
|
220
|
-
* for /error/i was tried and is wrong: tool output routinely contains that word
|
|
221
|
-
* (grep misses, compiler logs, dumps of source files), so it labelled every
|
|
222
|
-
* result in a 347-result turn as failed and the summarizer reported the whole
|
|
223
|
-
* turn as a failure.
|
|
285
|
+
* Render one answered question as a digest line pair.
|
|
224
286
|
*
|
|
225
|
-
* @param
|
|
226
|
-
* @returns
|
|
287
|
+
* @param answered - one question and the answer it got.
|
|
288
|
+
* @returns the question line and, indented under it, the answer line.
|
|
227
289
|
*/
|
|
228
|
-
|
|
229
|
-
const
|
|
230
|
-
|
|
290
|
+
function renderAnswered(answered) {
|
|
291
|
+
const picked = [...answered.selected];
|
|
292
|
+
if (answered.typed.length > 0)
|
|
293
|
+
picked.push(answered.typed);
|
|
294
|
+
return [
|
|
295
|
+
`- ${answered.question.replace(/\s+/g, ' ').trim()}`,
|
|
296
|
+
` → ${picked.join(' / ').replace(/\s+/g, ' ').trim()}`,
|
|
297
|
+
];
|
|
231
298
|
}
|
|
232
299
|
/** Directive appended as the final user message of the extraction call. */
|
|
233
300
|
const EXTRACT_INSTRUCTION = [
|
|
@@ -458,8 +525,6 @@ const EXTRACT_THINKING_RESERVE_TOKENS = 1000;
|
|
|
458
525
|
const MAX_HINTS_PER_TURN = 120;
|
|
459
526
|
/** Characters kept from one call's description or command head. */
|
|
460
527
|
const HINT_CHARS = 100;
|
|
461
|
-
/** Characters kept from one failing result's first line. */
|
|
462
|
-
const ERROR_CHARS = 140;
|
|
463
528
|
/**
|
|
464
529
|
* The best short description of what one call was for.
|
|
465
530
|
*
|
|
@@ -478,35 +543,6 @@ function hintOf(argumentsJson) {
|
|
|
478
543
|
catch {
|
|
479
544
|
return '';
|
|
480
545
|
}
|
|
481
|
-
// `ask_user_question` carries `questions[]`, not a `description`. Without this
|
|
482
|
-
// branch the hint was the bare tool name, so the extractor never saw what was
|
|
483
|
-
// asked and `## Asked` came out empty or wrong on every turn that used it.
|
|
484
|
-
const questions = parsed['questions'];
|
|
485
|
-
if (Array.isArray(questions)) {
|
|
486
|
-
const asked = questions
|
|
487
|
-
.map((question) => {
|
|
488
|
-
if (typeof question !== 'object' || question === null)
|
|
489
|
-
return '';
|
|
490
|
-
const record = question;
|
|
491
|
-
const text = typeof record['question'] === 'string'
|
|
492
|
-
? record['question']
|
|
493
|
-
: typeof record['header'] === 'string' ? record['header'] : '';
|
|
494
|
-
const options = Array.isArray(record['options'])
|
|
495
|
-
? record['options']
|
|
496
|
-
.map((option) => (typeof option === 'object' && option !== null
|
|
497
|
-
? String(option['label'] ?? '')
|
|
498
|
-
: ''))
|
|
499
|
-
.filter((label) => label.length > 0)
|
|
500
|
-
: [];
|
|
501
|
-
if (text.length === 0)
|
|
502
|
-
return '';
|
|
503
|
-
return options.length === 0 ? text : `${text} [options: ${options.join(' / ')}]`;
|
|
504
|
-
})
|
|
505
|
-
.filter((text) => text.length > 0)
|
|
506
|
-
.join(' | ');
|
|
507
|
-
if (asked.length > 0)
|
|
508
|
-
return asked.replace(/\s+/g, ' ').slice(0, HINT_CHARS * 2);
|
|
509
|
-
}
|
|
510
546
|
for (const key of ['description', 'command', 'query', 'file_path', 'path', 'pattern']) {
|
|
511
547
|
const candidate = parsed[key];
|
|
512
548
|
if (typeof candidate === 'string' && candidate.trim().length > 0) {
|
|
@@ -521,8 +557,10 @@ function hintOf(argumentsJson) {
|
|
|
521
557
|
* This is what lets a turn whose assistant prose is empty still leave a record:
|
|
522
558
|
* in the measured session one turn ran 342 tool calls and emitted zero prose, so
|
|
523
559
|
* the verbatim digest reduced it to a single `tools:` count line. The trace names
|
|
524
|
-
* what was attempted
|
|
525
|
-
*
|
|
560
|
+
* what was attempted, which is enough for a model to state the outcome.
|
|
561
|
+
*
|
|
562
|
+
* Tool results are not read. Their only contribution used to be a first-line
|
|
563
|
+
* error string, and that string was never the part of a failure that mattered.
|
|
526
564
|
*
|
|
527
565
|
* Bounded on purpose — 500 calls would otherwise produce a prompt larger than the
|
|
528
566
|
* material it summarizes.
|
|
@@ -533,49 +571,25 @@ function hintOf(argumentsJson) {
|
|
|
533
571
|
export function collectHints(events) {
|
|
534
572
|
const lines = [];
|
|
535
573
|
let calls = 0;
|
|
536
|
-
// Tool-call ids of this turn's questions, so the matching result can be read as
|
|
537
|
-
// an answer rather than being skipped as a non-error result.
|
|
538
|
-
const askedIds = new Set();
|
|
539
574
|
for (const event of events) {
|
|
540
575
|
// Tool calls are blocks inside `assistant/message`, not standalone events:
|
|
541
576
|
// `digestSource` emits no `tool/call` type at all, so selecting on that type
|
|
542
577
|
// matched nothing and a 342-call turn produced a single hint line.
|
|
543
|
-
if (event.type
|
|
544
|
-
for (const call of toolCallsOf(event)) {
|
|
545
|
-
// A question is never dropped by the cap. It is the only record of what was
|
|
546
|
-
// asked, and its answer is matched by call id rather than by the cap, so
|
|
547
|
-
// dropping the question left an orphan ANSWER line with nothing beside it —
|
|
548
|
-
// a real turn made 292 calls, the question came late, and the user's choice
|
|
549
|
-
// never reached the digest.
|
|
550
|
-
const isQuestion = call.name === 'ask_user_question';
|
|
551
|
-
if (!isQuestion) {
|
|
552
|
-
if (calls >= MAX_HINTS_PER_TURN)
|
|
553
|
-
break;
|
|
554
|
-
calls += 1;
|
|
555
|
-
}
|
|
556
|
-
const hint = hintOf(call.arguments);
|
|
557
|
-
lines.push(hint.length > 0 ? `TOOL ${call.name}: ${hint}` : `TOOL ${call.name}`);
|
|
558
|
-
if (isQuestion)
|
|
559
|
-
askedIds.add(call.id);
|
|
560
|
-
}
|
|
561
|
-
continue;
|
|
562
|
-
}
|
|
563
|
-
if (event.type !== 'tool/result')
|
|
564
|
-
continue;
|
|
565
|
-
// The answer to a question is the tool's own result, not an error. It is the
|
|
566
|
-
// only record of what the user chose, and the next user message is often just
|
|
567
|
-
// "1" — so it has to travel with the question.
|
|
568
|
-
const answered = answerOf(event, askedIds);
|
|
569
|
-
if (answered !== undefined) {
|
|
570
|
-
lines.push(`ANSWER: ${answered}`);
|
|
578
|
+
if (event.type !== 'assistant/message')
|
|
571
579
|
continue;
|
|
580
|
+
for (const call of toolCallsOf(event)) {
|
|
581
|
+
// A question is not a hint. It and its answer are rendered from the log by
|
|
582
|
+
// `renderAnswers`, so listing it here as well only invited the model to
|
|
583
|
+
// restate it in `asked` — the same exchange printed twice, once of them
|
|
584
|
+
// paraphrased.
|
|
585
|
+
if (call.name === 'ask_user_question')
|
|
586
|
+
continue;
|
|
587
|
+
if (calls >= MAX_HINTS_PER_TURN)
|
|
588
|
+
break;
|
|
589
|
+
calls += 1;
|
|
590
|
+
const hint = hintOf(call.arguments);
|
|
591
|
+
lines.push(hint.length > 0 ? `TOOL ${call.name}: ${hint}` : `TOOL ${call.name}`);
|
|
572
592
|
}
|
|
573
|
-
if (!isErrorResult(event))
|
|
574
|
-
continue;
|
|
575
|
-
const firstLine = textOf(event).split('\n')[0] ?? '';
|
|
576
|
-
if (firstLine.trim().length === 0)
|
|
577
|
-
continue;
|
|
578
|
-
lines.push(`ERR ${firstLine.trim().slice(0, ERROR_CHARS)}`);
|
|
579
593
|
}
|
|
580
594
|
return lines.join('\n');
|
|
581
595
|
}
|
|
@@ -599,7 +613,7 @@ function turnOf(event) {
|
|
|
599
613
|
}
|
|
600
614
|
/** A fresh, empty turn accumulator. */
|
|
601
615
|
function emptyTurn(turn, fromRequest = false) {
|
|
602
|
-
return { turn, fromRequest, user: [], assistant: [], tools: new Map(),
|
|
616
|
+
return { turn, fromRequest, user: [], assistant: [], tools: new Map(), writes: [], answered: [] };
|
|
603
617
|
}
|
|
604
618
|
/**
|
|
605
619
|
* Group append-origin surface events into per-turn digest material.
|
|
@@ -633,6 +647,16 @@ export function buildSections(events) {
|
|
|
633
647
|
// objective on every round, so recording each copy would repeat it dozens of
|
|
634
648
|
// times across a long autonomous run.
|
|
635
649
|
const recordedObjectives = new Set();
|
|
650
|
+
// Question id to question text, for every `ask_user_question` call seen so far.
|
|
651
|
+
// The answer batch names questions by id only, and an id like `quota` says
|
|
652
|
+
// nothing on its own.
|
|
653
|
+
const questionTexts = new Map();
|
|
654
|
+
// Call ids of this turn's `ask_user_question` calls. A result is an answer only
|
|
655
|
+
// when its own call asked something: without this every result in the log was
|
|
656
|
+
// JSON-parsed (536 KB across 157 results in one measured session, the largest
|
|
657
|
+
// 49.9 KB) and any output that happened to look like an answer batch — a file
|
|
658
|
+
// dump, a test fixture — would be recorded as something the user chose.
|
|
659
|
+
const questionCallIds = new Set();
|
|
636
660
|
for (const event of events) {
|
|
637
661
|
if (event.type === 'turn/start') {
|
|
638
662
|
const turn = turnOf(event);
|
|
@@ -658,15 +682,22 @@ export function buildSections(events) {
|
|
|
658
682
|
continue;
|
|
659
683
|
}
|
|
660
684
|
if (event.type === 'tool/result') {
|
|
661
|
-
|
|
685
|
+
// An answered question arrives as this call's own result. The call's
|
|
686
|
+
// arguments named the questions; the result carries the choices.
|
|
687
|
+
const callId = messageOf(event)?.toolCallId;
|
|
688
|
+
if (callId === undefined || !questionCallIds.has(callId) || currentTurn === undefined)
|
|
662
689
|
continue;
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
690
|
+
currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
// The host answers a question two ways. Inside the waiting window the answer
|
|
694
|
+
// is the tool result above; after the call already returned its pending
|
|
695
|
+
// notice, it is a `user/message` whose source kind is `user-question-reply`
|
|
696
|
+
// and whose body is the same answer batch. That message is not a new request,
|
|
697
|
+
// so it is read here rather than opening a section.
|
|
698
|
+
if (sourceKind(event) === 'user-question-reply') {
|
|
699
|
+
if (currentTurn !== undefined)
|
|
700
|
+
currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
|
|
670
701
|
continue;
|
|
671
702
|
}
|
|
672
703
|
if (event.type !== 'user/message' && event.type !== 'assistant/message')
|
|
@@ -704,6 +735,12 @@ export function buildSections(events) {
|
|
|
704
735
|
currentTurn.assistant.push(text);
|
|
705
736
|
for (const call of toolCallsOf(event)) {
|
|
706
737
|
currentTurn.tools.set(call.name, (currentTurn.tools.get(call.name) ?? 0) + 1);
|
|
738
|
+
if (call.name === 'ask_user_question') {
|
|
739
|
+
for (const [id, question] of questionTextsOf(call.arguments))
|
|
740
|
+
questionTexts.set(id, question);
|
|
741
|
+
questionCallIds.add(call.id);
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
707
744
|
if (!WRITE_TOOLS.has(call.name))
|
|
708
745
|
continue;
|
|
709
746
|
const path = pathArgumentOf(call.arguments);
|
|
@@ -838,30 +875,75 @@ function renderSection(section, level, condensed, sectionIndex) {
|
|
|
838
875
|
if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted, level).length > 0) {
|
|
839
876
|
const block = renderExtractionBlock(turn.extracted, level);
|
|
840
877
|
// The trailer goes *above* the block, not below it. `## Asked` is the block's
|
|
841
|
-
// last section and the user's reply is the very next line, so
|
|
878
|
+
// last section and the user's reply is the very next line, so a trailer line
|
|
842
879
|
// in between would separate the reply from the question it answers.
|
|
843
880
|
const trailer = [];
|
|
844
|
-
if (turn.errors.length > 0) {
|
|
845
|
-
trailer.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
|
|
846
|
-
}
|
|
847
881
|
if (turn.writes.length > 0)
|
|
848
882
|
trailer.push(` wrote: ${turn.writes.join(', ')}`);
|
|
849
|
-
const
|
|
883
|
+
const withAnswers = insertAnswers(block, renderAnswers(turn));
|
|
884
|
+
const body = trailer.length > 0 ? `${trailer.join('\n')}\n${withAnswers}` : withAnswers;
|
|
850
885
|
lines.push(`### assistant\n${body}`);
|
|
851
886
|
}
|
|
852
887
|
else {
|
|
853
888
|
const body = turn.assistant.join('\n');
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
889
|
+
const answers = renderAnswers(turn);
|
|
890
|
+
// The heading goes on whenever there is anything to put under it. Emitting
|
|
891
|
+
// the answers bare put `## Answers` directly below `## user`, at the user's
|
|
892
|
+
// own heading level, where it reads as something the user said.
|
|
893
|
+
if (body.length > 0 || answers.length > 0)
|
|
894
|
+
lines.push(`### assistant\n${[body, answers].filter((part) => part.length > 0).join('\n')}`);
|
|
859
895
|
if (turn.writes.length > 0)
|
|
860
896
|
lines.push(` wrote: ${turn.writes.join(', ')}`);
|
|
861
897
|
}
|
|
862
898
|
}
|
|
863
899
|
return lines.join('\n');
|
|
864
900
|
}
|
|
901
|
+
/**
|
|
902
|
+
* Render a turn's tool questions and their answers, or an empty string.
|
|
903
|
+
*
|
|
904
|
+
* This section exists because `## Asked` cannot cover these. `asked` is written by
|
|
905
|
+
* the model from prose, and its contract says the reply is the next `## user` line
|
|
906
|
+
* — true for a question asked in prose, false for one asked through
|
|
907
|
+
* `ask_user_question`: the user answers inside the picker, the answer becomes the
|
|
908
|
+
* tool result, and no user message is ever written. Two consecutive checkpoints of
|
|
909
|
+
* a real session carried neither the question nor the answer.
|
|
910
|
+
*
|
|
911
|
+
* Rendered from the log, so it cannot be paraphrased away, and placed after the
|
|
912
|
+
* assistant block because it belongs to that turn's work.
|
|
913
|
+
*
|
|
914
|
+
* @param turn - one turn's digest material.
|
|
915
|
+
* @returns the `## Answers` section, or an empty string when nothing was asked.
|
|
916
|
+
*/
|
|
917
|
+
function renderAnswers(turn) {
|
|
918
|
+
if (turn.answered.length === 0)
|
|
919
|
+
return '';
|
|
920
|
+
return `## Answers\n${turn.answered.flatMap(renderAnswered).join('\n')}`;
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* Place the `## Answers` section just above `## Asked`, or at the end when the
|
|
924
|
+
* block has none.
|
|
925
|
+
*
|
|
926
|
+
* Not at the end unconditionally: `## Asked` is the block's last section because
|
|
927
|
+
* the user's reply — a bare `1` — is the very next line and needs the options
|
|
928
|
+
* directly above it. A second question-and-answer block wedged in between would
|
|
929
|
+
* separate them.
|
|
930
|
+
*
|
|
931
|
+
* @param block - the rendered extraction block.
|
|
932
|
+
* @param answers - the rendered `## Answers` section, or an empty string.
|
|
933
|
+
* @returns the block with the answers placed.
|
|
934
|
+
*/
|
|
935
|
+
function insertAnswers(block, answers) {
|
|
936
|
+
if (answers.length === 0)
|
|
937
|
+
return block;
|
|
938
|
+
// The heading as a whole line, not the bare text: a `did`/`concluded` item is a
|
|
939
|
+
// free string, and one that happens to contain `## Asked` would otherwise be
|
|
940
|
+
// split in the middle of a bullet.
|
|
941
|
+
const at = block.startsWith('## Asked\n') ? 0 : block.indexOf('\n## Asked\n') + 1;
|
|
942
|
+
if (at <= 0 && !block.startsWith('## Asked\n'))
|
|
943
|
+
return `${block}\n${answers}`;
|
|
944
|
+
const head = block.slice(0, at);
|
|
945
|
+
return head.length === 0 ? `${answers}\n${block}` : `${head}${answers}\n${block.slice(at)}`;
|
|
946
|
+
}
|
|
865
947
|
/**
|
|
866
948
|
* Render the digest under a hard character budget.
|
|
867
949
|
*
|
|
@@ -1004,8 +1086,11 @@ export function renderDigest(events, budgetTokens, extracted, condensed) {
|
|
|
1004
1086
|
// key's absence and its undefined value as different types.
|
|
1005
1087
|
delete target.extracted;
|
|
1006
1088
|
target.assistant = [];
|
|
1007
|
-
target.errors = [];
|
|
1008
1089
|
target.writes = [];
|
|
1090
|
+
// The answers belong to the body: they were produced by this turn's own
|
|
1091
|
+
// tool call, so a dropped body that kept them would still print a full
|
|
1092
|
+
// `## Answers` at every tier, and the truncation would never fit.
|
|
1093
|
+
target.answered = [];
|
|
1009
1094
|
}
|
|
1010
1095
|
return trimmed;
|
|
1011
1096
|
};
|
|
@@ -1068,7 +1153,7 @@ export function renderDigest(events, budgetTokens, extracted, condensed) {
|
|
|
1068
1153
|
const keeperTurn = turnAt(positions[lastRequest]);
|
|
1069
1154
|
if (keeperTurn === undefined)
|
|
1070
1155
|
return '';
|
|
1071
|
-
const bare = { ...keeperTurn, assistant: [],
|
|
1156
|
+
const bare = { ...keeperTurn, assistant: [], writes: [], answered: [] };
|
|
1072
1157
|
delete bare.extracted;
|
|
1073
1158
|
return render([{ turns: [bare] }], 0);
|
|
1074
1159
|
}
|
|
@@ -1189,7 +1274,7 @@ export function buildExtractionMaterial(turn, prose) {
|
|
|
1189
1274
|
* @param signal - cancellation forwarded to the adapter.
|
|
1190
1275
|
* @returns the folded paragraph, or undefined when the call produced nothing.
|
|
1191
1276
|
*/
|
|
1192
|
-
async function condenseOnce(ctx, agent, material, signal) {
|
|
1277
|
+
async function condenseOnce(ctx, agent, material, signal, override) {
|
|
1193
1278
|
const llm = ctx.llm;
|
|
1194
1279
|
if (llm === undefined) {
|
|
1195
1280
|
ctx.logger?.warn('verbatim-compaction: no llm service, condensation skipped');
|
|
@@ -1208,16 +1293,15 @@ async function condenseOnce(ctx, agent, material, signal) {
|
|
|
1208
1293
|
const cheapest = cheapestEffort(info?.reasoning?.efforts);
|
|
1209
1294
|
const chunks = [];
|
|
1210
1295
|
try {
|
|
1211
|
-
const stream = llm.stream({
|
|
1296
|
+
const stream = llm.stream(applyPurposeOverride({
|
|
1212
1297
|
provider,
|
|
1213
1298
|
model,
|
|
1214
1299
|
messages: [{ role: 'user', content: [{ type: 'text', text: `${material}\n\n${CONDENSE_INSTRUCTION}` }] }],
|
|
1215
1300
|
maxTokens: CONDENSE_TOKENS,
|
|
1216
1301
|
sessionId: agent.session.id,
|
|
1217
1302
|
purpose: 'compaction',
|
|
1218
|
-
...(cheapest === undefined ? {} : { reasoningEffort: cheapest }),
|
|
1219
1303
|
...(signal === undefined ? {} : { signal }),
|
|
1220
|
-
});
|
|
1304
|
+
}, override, cheapest));
|
|
1221
1305
|
for await (const chunk of stream) {
|
|
1222
1306
|
const delta = chunk;
|
|
1223
1307
|
if (delta.type === 'text-delta' && typeof delta.text === 'string')
|
|
@@ -1237,11 +1321,11 @@ async function condenseOnce(ctx, agent, material, signal) {
|
|
|
1237
1321
|
}
|
|
1238
1322
|
return text;
|
|
1239
1323
|
}
|
|
1240
|
-
async function extractBatch(ctx, agent, batch, signal) {
|
|
1324
|
+
async function extractBatch(ctx, agent, batch, signal, override) {
|
|
1241
1325
|
const out = new Map();
|
|
1242
1326
|
if (batch.length === 0)
|
|
1243
1327
|
return out;
|
|
1244
|
-
const attempt = await extractOnce(ctx, agent, batch, signal);
|
|
1328
|
+
const attempt = await extractOnce(ctx, agent, batch, signal, override);
|
|
1245
1329
|
if (!attempt.truncated) {
|
|
1246
1330
|
if (attempt.blocks.size === 0) {
|
|
1247
1331
|
ctx.logger?.warn(`verbatim-compaction: extraction returned no usable JSON for ${batch.length} slot(s) `
|
|
@@ -1263,7 +1347,7 @@ async function extractBatch(ctx, agent, batch, signal) {
|
|
|
1263
1347
|
out.set(key, block);
|
|
1264
1348
|
const middle = Math.ceil(batch.length / 2);
|
|
1265
1349
|
for (const half of [batch.slice(0, middle), batch.slice(middle)]) {
|
|
1266
|
-
for (const [key, block] of await extractBatch(ctx, agent, half, signal))
|
|
1350
|
+
for (const [key, block] of await extractBatch(ctx, agent, half, signal, override))
|
|
1267
1351
|
out.set(key, block);
|
|
1268
1352
|
}
|
|
1269
1353
|
return out;
|
|
@@ -1323,7 +1407,7 @@ function cheapestEffort(efforts) {
|
|
|
1323
1407
|
* @param signal - cancellation forwarded to the adapter.
|
|
1324
1408
|
* @returns the parsed blocks and whether the model stopped at the token cap.
|
|
1325
1409
|
*/
|
|
1326
|
-
async function extractOnce(ctx, agent, batch, signal) {
|
|
1410
|
+
async function extractOnce(ctx, agent, batch, signal, override) {
|
|
1327
1411
|
const out = new Map();
|
|
1328
1412
|
const llm = ctx.llm;
|
|
1329
1413
|
if (llm === undefined)
|
|
@@ -1357,7 +1441,7 @@ async function extractOnce(ctx, agent, batch, signal) {
|
|
|
1357
1441
|
const chunks = [];
|
|
1358
1442
|
let truncated = false;
|
|
1359
1443
|
try {
|
|
1360
|
-
const stream = llm.stream({
|
|
1444
|
+
const stream = llm.stream(applyPurposeOverride({
|
|
1361
1445
|
provider,
|
|
1362
1446
|
model,
|
|
1363
1447
|
messages: [
|
|
@@ -1366,9 +1450,8 @@ async function extractOnce(ctx, agent, batch, signal) {
|
|
|
1366
1450
|
maxTokens: EXTRACT_TOKENS_PER_TURN * parts.length + EXTRACT_THINKING_RESERVE_TOKENS,
|
|
1367
1451
|
sessionId: agent.session.id,
|
|
1368
1452
|
purpose: 'compaction',
|
|
1369
|
-
...(cheapest === undefined ? {} : { reasoningEffort: cheapest }),
|
|
1370
1453
|
...(signal === undefined ? {} : { signal }),
|
|
1371
|
-
});
|
|
1454
|
+
}, override, cheapest));
|
|
1372
1455
|
for await (const chunk of stream) {
|
|
1373
1456
|
const delta = chunk;
|
|
1374
1457
|
if (delta.type === 'text-delta' && typeof delta.text === 'string')
|
|
@@ -1396,6 +1479,22 @@ async function extractOnce(ctx, agent, batch, signal) {
|
|
|
1396
1479
|
* subclass cannot diverge from the host's transaction semantics.
|
|
1397
1480
|
*/
|
|
1398
1481
|
export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
1482
|
+
/**
|
|
1483
|
+
* The Loader reads Config from the default-exported class, and the base
|
|
1484
|
+
* constructor rejects unknown keys, so the base schema is merged instead of
|
|
1485
|
+
* replaced. Only the three new fields are volatile: existing keys stay
|
|
1486
|
+
* ordinary patch-level configuration.
|
|
1487
|
+
*/
|
|
1488
|
+
static Config = Schema.object({
|
|
1489
|
+
...BasicCompactionEngine.Config.dict,
|
|
1490
|
+
...OVERRIDE_FIELDS,
|
|
1491
|
+
});
|
|
1492
|
+
purposeConfig;
|
|
1493
|
+
constructor(ctx, config) {
|
|
1494
|
+
const { provider, model, reasoningEffort, ...base } = config ?? {};
|
|
1495
|
+
super(ctx, base);
|
|
1496
|
+
this.purposeConfig = { provider, model, reasoningEffort };
|
|
1497
|
+
}
|
|
1399
1498
|
/**
|
|
1400
1499
|
* Extraction results, keyed by a hash of the material they were derived from.
|
|
1401
1500
|
*
|
|
@@ -1451,12 +1550,12 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1451
1550
|
// size independent of history length; the guard bound only exists for the
|
|
1452
1551
|
// degenerate case of a span smaller than the ceiling.
|
|
1453
1552
|
const budget = Math.max(0, Math.min(DIGEST_TOKEN_CEILING, shadowedPrice - FRAME_TOKENS - SHRINK_MARGIN_TOKENS));
|
|
1454
|
-
const extracted = await this.extractAll(source, agent, signal);
|
|
1553
|
+
const extracted = await this.extractAll(source, agent, signal, this.purposeConfig);
|
|
1455
1554
|
// Fold the oldest turns up only when the plain digest overflows. The fold is an
|
|
1456
1555
|
// LLM call, so a digest that already fits must not pay for one.
|
|
1457
1556
|
let condensed;
|
|
1458
1557
|
if (renderDigest(source, budget, extracted).length > budget * 4) {
|
|
1459
|
-
condensed = await this.condenseOldest(source, extracted, agent, budget, signal);
|
|
1558
|
+
condensed = await this.condenseOldest(source, extracted, agent, budget, signal, this.purposeConfig);
|
|
1460
1559
|
}
|
|
1461
1560
|
// The fold path returns its digest whole, so it can still overflow when every
|
|
1462
1561
|
// group has been folded and the user lines alone are too long. The budget is a
|
|
@@ -1500,7 +1599,7 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1500
1599
|
* @param signal - cancellation forwarded to every call.
|
|
1501
1600
|
* @returns condensed blocks keyed by the `turnKey` of the first covered section.
|
|
1502
1601
|
*/
|
|
1503
|
-
async condenseOldest(source, extracted, agent, budget, signal) {
|
|
1602
|
+
async condenseOldest(source, extracted, agent, budget, signal, override) {
|
|
1504
1603
|
const sections = withExtractions(buildSections(source), extracted);
|
|
1505
1604
|
const budgetChars = budget * 4;
|
|
1506
1605
|
const out = new Map();
|
|
@@ -1517,7 +1616,7 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1517
1616
|
const group = sections.slice(start, start + CONDENSE_GROUP);
|
|
1518
1617
|
if (group.length === 0)
|
|
1519
1618
|
continue;
|
|
1520
|
-
const text = await this.condenseGroup(group, agent, signal);
|
|
1619
|
+
const text = await this.condenseGroup(group, agent, signal, override);
|
|
1521
1620
|
// A failed group is skipped rather than retried: the next group still buys
|
|
1522
1621
|
// room, and retrying the same material against a failing model only spends
|
|
1523
1622
|
// calls. The remaining turns keep their own blocks either way.
|
|
@@ -1537,7 +1636,7 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1537
1636
|
* @param signal - cancellation forwarded to the call.
|
|
1538
1637
|
* @returns the folded paragraph, or undefined when the call produced nothing.
|
|
1539
1638
|
*/
|
|
1540
|
-
async condenseGroup(group, agent, signal) {
|
|
1639
|
+
async condenseGroup(group, agent, signal, override) {
|
|
1541
1640
|
// Both sources, because a turn has one or the other: extraction succeeds and
|
|
1542
1641
|
// the block replaces the prose, or it fails and the verbatim prose is what the
|
|
1543
1642
|
// digest shows. Reading only `extracted` meant a run of turns whose extraction
|
|
@@ -1568,7 +1667,7 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1568
1667
|
const cached = this.condensedCache.get(key);
|
|
1569
1668
|
if (cached !== undefined)
|
|
1570
1669
|
return cached;
|
|
1571
|
-
const text = await condenseOnce(this.ctx, agent, material, signal);
|
|
1670
|
+
const text = await condenseOnce(this.ctx, agent, material, signal, override);
|
|
1572
1671
|
if (text === undefined)
|
|
1573
1672
|
return undefined;
|
|
1574
1673
|
this.condensedCache.set(key, text);
|
|
@@ -1595,7 +1694,7 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1595
1694
|
* @param signal - cancellation forwarded to every call.
|
|
1596
1695
|
* @returns turn number to extracted block, omitting turns that yielded none.
|
|
1597
1696
|
*/
|
|
1598
|
-
async extractAll(source, agent, signal) {
|
|
1697
|
+
async extractAll(source, agent, signal, override) {
|
|
1599
1698
|
// Walk the same sections the renderer will use, so a key addresses the exact
|
|
1600
1699
|
// slot the block will be written into. Grouping by turn number instead lost
|
|
1601
1700
|
// blocks whenever the log reused a number.
|
|
@@ -1659,7 +1758,7 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1659
1758
|
if (signal?.aborted === true)
|
|
1660
1759
|
break;
|
|
1661
1760
|
const batch = missing.slice(index, index + TURNS_PER_CALL);
|
|
1662
|
-
const blocks = await extractBatch(this.ctx, agent, batch, signal);
|
|
1761
|
+
const blocks = await extractBatch(this.ctx, agent, batch, signal, override);
|
|
1663
1762
|
for (const slot of batch) {
|
|
1664
1763
|
const block = blocks.get(slot.key);
|
|
1665
1764
|
if (block === undefined)
|
package/lib/types/index.d.ts
CHANGED
|
@@ -32,10 +32,37 @@
|
|
|
32
32
|
*/
|
|
33
33
|
import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
|
|
34
34
|
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
35
|
-
import type
|
|
35
|
+
import { type ContentBlock, type Message } from '@deepseek-ai/dsh-llm';
|
|
36
|
+
import Schema from '@deepseek-ai/schemastery';
|
|
36
37
|
import type { Session, SessionEvent, SessionSeq } from '@deepseek-ai/dsh-session';
|
|
37
38
|
/** Cordis companion plugin name. Must equal this plugin's `cordis.patch.yml` row id. */
|
|
38
39
|
export declare const name = "verbatim-compaction";
|
|
40
|
+
/** Live reference Cordis hands over for a volatile Config field. */
|
|
41
|
+
interface ConfigRef<T> {
|
|
42
|
+
get(): T;
|
|
43
|
+
}
|
|
44
|
+
/** Optional model/effort override for compaction's two LLM calls. */
|
|
45
|
+
export interface PurposeConfig {
|
|
46
|
+
provider?: ConfigRef<string>;
|
|
47
|
+
model?: ConfigRef<string>;
|
|
48
|
+
reasoningEffort?: ConfigRef<string>;
|
|
49
|
+
}
|
|
50
|
+
/** Three editable scalars; empty strings mean "follow the chat model". */
|
|
51
|
+
export declare const OVERRIDE_FIELDS: {
|
|
52
|
+
provider: Schema<string, string, "volatile-defined">;
|
|
53
|
+
model: Schema<string, string, "volatile-defined">;
|
|
54
|
+
reasoningEffort: Schema<string, string, "volatile-defined">;
|
|
55
|
+
};
|
|
56
|
+
/** A provider/model override takes effect only as a complete pair. */
|
|
57
|
+
export declare function pairedRouteOf(config: PurposeConfig | undefined): {
|
|
58
|
+
provider: string;
|
|
59
|
+
model: string;
|
|
60
|
+
} | undefined;
|
|
61
|
+
/**
|
|
62
|
+
* Apply the optional override; without a configured effort the cheapest usable
|
|
63
|
+
* effort still wins, because a route's own default is typically the priciest.
|
|
64
|
+
*/
|
|
65
|
+
export declare function applyPurposeOverride<T extends object>(options: T, config: PurposeConfig | undefined, cheapest: string | undefined): T;
|
|
39
66
|
/**
|
|
40
67
|
* Absolute ceiling for one digest, in the meter's fixed 4-chars-per-token
|
|
41
68
|
* heuristic.
|
|
@@ -67,19 +94,14 @@ export interface SummaryResult {
|
|
|
67
94
|
provider: string;
|
|
68
95
|
model: string;
|
|
69
96
|
}
|
|
70
|
-
/**
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
*
|
|
79
|
-
* @param event - a `tool/result` event.
|
|
80
|
-
* @returns true only when the log itself marks the result as an error.
|
|
81
|
-
*/
|
|
82
|
-
export declare function isErrorResult(event: SessionEvent): boolean;
|
|
97
|
+
/** One question the user answered through the question tool, with its answer. */
|
|
98
|
+
interface AnsweredQuestion {
|
|
99
|
+
question: string;
|
|
100
|
+
/** The labels the user picked, in the order they were offered. */
|
|
101
|
+
selected: string[];
|
|
102
|
+
/** What the user typed instead of picking, when they did. */
|
|
103
|
+
typed: string;
|
|
104
|
+
}
|
|
83
105
|
/** One slot's extraction, as the model returns it. */
|
|
84
106
|
export interface Extraction {
|
|
85
107
|
did: string[];
|
|
@@ -178,8 +200,10 @@ export interface Condensed {
|
|
|
178
200
|
* This is what lets a turn whose assistant prose is empty still leave a record:
|
|
179
201
|
* in the measured session one turn ran 342 tool calls and emitted zero prose, so
|
|
180
202
|
* the verbatim digest reduced it to a single `tools:` count line. The trace names
|
|
181
|
-
* what was attempted
|
|
182
|
-
*
|
|
203
|
+
* what was attempted, which is enough for a model to state the outcome.
|
|
204
|
+
*
|
|
205
|
+
* Tool results are not read. Their only contribution used to be a first-line
|
|
206
|
+
* error string, and that string was never the part of a failure that mattered.
|
|
183
207
|
*
|
|
184
208
|
* Bounded on purpose — 500 calls would otherwise produce a prompt larger than the
|
|
185
209
|
* material it summarizes.
|
|
@@ -203,9 +227,20 @@ interface Turn {
|
|
|
203
227
|
user: string[];
|
|
204
228
|
assistant: string[];
|
|
205
229
|
tools: Map<string, number>;
|
|
206
|
-
resultBytes: number;
|
|
207
|
-
errors: string[];
|
|
208
230
|
writes: string[];
|
|
231
|
+
/**
|
|
232
|
+
* Questions this turn put to the user through `ask_user_question`, with the
|
|
233
|
+
* answers they got.
|
|
234
|
+
*
|
|
235
|
+
* Read from the log rather than asked of the model, and rendered as its own
|
|
236
|
+
* `## Answers` section. The model's `asked` field covers questions written in
|
|
237
|
+
* prose; a question asked through the tool is answered in the tool's own picker,
|
|
238
|
+
* and that answer is the tool result. Measured on one real session: three such
|
|
239
|
+
* questions were answered inside the picker and no `user/message` was written at
|
|
240
|
+
* all, so both the question and the choice were absent from two consecutive
|
|
241
|
+
* checkpoints.
|
|
242
|
+
*/
|
|
243
|
+
answered: AnsweredQuestion[];
|
|
209
244
|
/**
|
|
210
245
|
* The extracted summary for this turn, when extraction succeeded.
|
|
211
246
|
*
|
|
@@ -323,6 +358,15 @@ export declare function buildExtractionMaterial(turn: readonly SessionEvent[], p
|
|
|
323
358
|
* subclass cannot diverge from the host's transaction semantics.
|
|
324
359
|
*/
|
|
325
360
|
export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
361
|
+
/**
|
|
362
|
+
* The Loader reads Config from the default-exported class, and the base
|
|
363
|
+
* constructor rejects unknown keys, so the base schema is merged instead of
|
|
364
|
+
* replaced. Only the three new fields are volatile: existing keys stay
|
|
365
|
+
* ordinary patch-level configuration.
|
|
366
|
+
*/
|
|
367
|
+
static Config: typeof BasicCompactionEngine.Config;
|
|
368
|
+
private readonly purposeConfig;
|
|
369
|
+
constructor(ctx: ConstructorParameters<typeof BasicCompactionEngine>[0], config: any);
|
|
326
370
|
/**
|
|
327
371
|
* Extraction results, keyed by a hash of the material they were derived from.
|
|
328
372
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@logictan/dsh-verbatim-compaction",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.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",
|
|
@@ -45,6 +45,9 @@
|
|
|
45
45
|
"url": "git+https://github.com/dale0525/dsh-plugins.git",
|
|
46
46
|
"directory": "packages/dsh-verbatim-compaction"
|
|
47
47
|
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@deepseek-ai/schemastery": "^3.18.5"
|
|
50
|
+
},
|
|
48
51
|
"peerDependencies": {
|
|
49
52
|
"@deepseek-ai/cordis": "^4.0.2",
|
|
50
53
|
"@deepseek-ai/dsh-agent": ">=0.1.6-alpha.1 <0.2.0 || ^0.2.1-rc.2",
|
|
@@ -52,7 +55,8 @@
|
|
|
52
55
|
"@deepseek-ai/dsh-compaction-basic": ">=0.1.6-alpha.1 <0.2.0 || ^0.2.1-rc.2",
|
|
53
56
|
"@deepseek-ai/dsh-llm": ">=0.1.6-alpha.1 <0.2.0 || ^0.2.1-rc.2",
|
|
54
57
|
"@deepseek-ai/dsh-session": ">=0.1.6-alpha.1 <0.2.0 || ^0.2.1-rc.2",
|
|
55
|
-
"@deepseek-ai/dsh-token-meter": ">=0.1.6-alpha.1 <0.2.0 || ^0.2.1-rc.2"
|
|
58
|
+
"@deepseek-ai/dsh-token-meter": ">=0.1.6-alpha.1 <0.2.0 || ^0.2.1-rc.2",
|
|
59
|
+
"@deepseek-ai/schemastery": "^3.18.0 || ^3.18.5-alpha.1"
|
|
56
60
|
},
|
|
57
61
|
"devDependencies": {
|
|
58
62
|
"@deepseek-ai/cordis": "^4.0.5",
|
|
@@ -62,6 +66,7 @@
|
|
|
62
66
|
"@deepseek-ai/dsh-llm": "0.2.1-rc.2",
|
|
63
67
|
"@deepseek-ai/dsh-session": "0.2.1-rc.2",
|
|
64
68
|
"@deepseek-ai/dsh-token-meter": "0.2.1-rc.2",
|
|
69
|
+
"@deepseek-ai/schemastery": "^3.18.5",
|
|
65
70
|
"typescript": "^5.9.0",
|
|
66
71
|
"@types/node": "^22.20.0"
|
|
67
72
|
}
|