@logictan/dsh-verbatim-compaction 0.12.0 → 0.13.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 +56 -12
- package/lib/index.js +645 -232
- package/lib/types/index.d.ts +133 -30
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* This backend keeps the base class's replay, range selection, durable
|
|
16
16
|
* transaction and shrink guard untouched and overrides only `summarize()`, the
|
|
17
17
|
* one hook the base class documents for exactly this purpose. The replacement
|
|
18
|
-
* summary is built
|
|
18
|
+
* summary is built from the log, with one model call per batch of turns:
|
|
19
19
|
*
|
|
20
20
|
* - user and assistant prose verbatim, per turn;
|
|
21
21
|
* - tool results reduced to one line (tool names, call counts, bytes);
|
|
@@ -55,8 +55,6 @@ export const DIGEST_TOKEN_CEILING = 20000;
|
|
|
55
55
|
const FRAME_TOKENS = 86;
|
|
56
56
|
/** Safety margin below the shrink guard, in tokens. */
|
|
57
57
|
const SHRINK_MARGIN_TOKENS = 512;
|
|
58
|
-
/** Per-turn floor when assistant prose has to be truncated, in characters. */
|
|
59
|
-
const MIN_TURN_CHARS = 800;
|
|
60
58
|
/**
|
|
61
59
|
* Share of the budget user prose may occupy before oldest-first truncation.
|
|
62
60
|
*
|
|
@@ -163,73 +161,108 @@ function toolCallsOf(event) {
|
|
|
163
161
|
}
|
|
164
162
|
return calls;
|
|
165
163
|
}
|
|
164
|
+
/** The `questions[]` payload of an `ask_user_question` call, as `{id → text}`. */
|
|
165
|
+
function questionTextsOf(argumentsJson) {
|
|
166
|
+
const out = new Map();
|
|
167
|
+
let parsed;
|
|
168
|
+
try {
|
|
169
|
+
parsed = JSON.parse(argumentsJson);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
175
|
+
return out;
|
|
176
|
+
const questions = parsed['questions'];
|
|
177
|
+
if (!Array.isArray(questions))
|
|
178
|
+
return out;
|
|
179
|
+
for (const question of questions) {
|
|
180
|
+
if (typeof question !== 'object' || question === null)
|
|
181
|
+
continue;
|
|
182
|
+
const record = question;
|
|
183
|
+
const id = record['id'];
|
|
184
|
+
const text = typeof record['question'] === 'string' ? record['question'] : undefined;
|
|
185
|
+
if (typeof id === 'string' && text !== undefined)
|
|
186
|
+
out.set(id, text);
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
166
190
|
/**
|
|
167
|
-
*
|
|
191
|
+
* Read one answer batch into per-question answers.
|
|
192
|
+
*
|
|
193
|
+
* The batch is `{answers:[{id, selected:[…], custom?}]}`, and it arrives two
|
|
194
|
+
* ways: as the result of an answered `ask_user_question` call, and inside the
|
|
195
|
+
* `user/message` the host writes when the user answers after the call already
|
|
196
|
+
* returned its pending notice. Both carry the same shape, so both are read here.
|
|
168
197
|
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
* often just "1" or "继续", which is unreadable without the question beside it.
|
|
198
|
+
* A typed answer arrives with `selected: []` and the text in `custom`. Ten of 31
|
|
199
|
+
* real questions in one session were answered that way, and those carried the
|
|
200
|
+
* user's actual observations rather than a menu label.
|
|
173
201
|
*
|
|
174
|
-
* @param
|
|
175
|
-
* @param
|
|
176
|
-
* @returns
|
|
202
|
+
* @param text - the JSON body.
|
|
203
|
+
* @param texts - question id to question text, from the call's arguments.
|
|
204
|
+
* @returns one entry per answered question; empty when the body is not a batch.
|
|
177
205
|
*/
|
|
178
|
-
function
|
|
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);
|
|
206
|
+
function answersOf(text, texts) {
|
|
188
207
|
let parsed;
|
|
189
208
|
try {
|
|
190
209
|
parsed = JSON.parse(text);
|
|
191
210
|
}
|
|
192
211
|
catch {
|
|
193
|
-
return
|
|
212
|
+
return [];
|
|
194
213
|
}
|
|
195
214
|
if (typeof parsed !== 'object' || parsed === null)
|
|
196
|
-
return
|
|
197
|
-
|
|
215
|
+
return [];
|
|
216
|
+
// A late reply carries its own `questions` array beside the answers, so it does
|
|
217
|
+
// not depend on the call still being in the same turn's events.
|
|
218
|
+
const body = parsed;
|
|
219
|
+
const own = Array.isArray(body['questions']) ? body['questions'] : [];
|
|
220
|
+
const merged = new Map(texts);
|
|
221
|
+
for (const question of own) {
|
|
222
|
+
if (typeof question !== 'object' || question === null)
|
|
223
|
+
continue;
|
|
224
|
+
const record = question;
|
|
225
|
+
const id = record['id'];
|
|
226
|
+
const text = record['question'];
|
|
227
|
+
if (typeof id === 'string' && typeof text === 'string')
|
|
228
|
+
merged.set(id, text);
|
|
229
|
+
}
|
|
230
|
+
const answers = body['answers'];
|
|
198
231
|
if (!Array.isArray(answers))
|
|
199
|
-
return
|
|
200
|
-
const
|
|
201
|
-
|
|
232
|
+
return [];
|
|
233
|
+
const out = [];
|
|
234
|
+
for (const answer of answers) {
|
|
202
235
|
if (typeof answer !== 'object' || answer === null)
|
|
203
|
-
|
|
236
|
+
continue;
|
|
204
237
|
const record = answer;
|
|
205
|
-
const
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
.
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
238
|
+
const id = typeof record['id'] === 'string' ? record['id'] : '';
|
|
239
|
+
const question = merged.get(id);
|
|
240
|
+
if (question === undefined)
|
|
241
|
+
continue;
|
|
242
|
+
const selected = Array.isArray(record['selected'])
|
|
243
|
+
? record['selected'].map((value) => String(value)).filter((value) => value.length > 0)
|
|
244
|
+
: [];
|
|
245
|
+
const typed = typeof record['custom'] === 'string' ? record['custom'].trim() : '';
|
|
246
|
+
if (selected.length === 0 && typed.length === 0)
|
|
247
|
+
continue;
|
|
248
|
+
out.push({ question, selected, typed });
|
|
249
|
+
}
|
|
250
|
+
return out;
|
|
217
251
|
}
|
|
218
252
|
/**
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
* Reads `data.message.isError` and nothing else. Matching the serialized text
|
|
222
|
-
* for /error/i was tried and is wrong: tool output routinely contains that word
|
|
223
|
-
* (grep misses, compiler logs, dumps of source files), so it labelled every
|
|
224
|
-
* result in a 347-result turn as failed and the summarizer reported the whole
|
|
225
|
-
* turn as a failure.
|
|
253
|
+
* Render one answered question as a digest line pair.
|
|
226
254
|
*
|
|
227
|
-
* @param
|
|
228
|
-
* @returns
|
|
255
|
+
* @param answered - one question and the answer it got.
|
|
256
|
+
* @returns the question line and, indented under it, the answer line.
|
|
229
257
|
*/
|
|
230
|
-
|
|
231
|
-
const
|
|
232
|
-
|
|
258
|
+
function renderAnswered(answered) {
|
|
259
|
+
const picked = [...answered.selected];
|
|
260
|
+
if (answered.typed.length > 0)
|
|
261
|
+
picked.push(answered.typed);
|
|
262
|
+
return [
|
|
263
|
+
`- ${answered.question.replace(/\s+/g, ' ').trim()}`,
|
|
264
|
+
` → ${picked.join(' / ').replace(/\s+/g, ' ').trim()}`,
|
|
265
|
+
];
|
|
233
266
|
}
|
|
234
267
|
/** Directive appended as the final user message of the extraction call. */
|
|
235
268
|
const EXTRACT_INSTRUCTION = [
|
|
@@ -342,7 +375,7 @@ export function parseExtraction(answer) {
|
|
|
342
375
|
* @returns markdown with a heading per non-empty field; empty string when every
|
|
343
376
|
* field is empty.
|
|
344
377
|
*/
|
|
345
|
-
export function renderExtractionBlock(extraction) {
|
|
378
|
+
export function renderExtractionBlock(extraction, level = 3) {
|
|
346
379
|
if (extraction === undefined)
|
|
347
380
|
return '';
|
|
348
381
|
const lines = [];
|
|
@@ -351,9 +384,17 @@ export function renderExtractionBlock(extraction) {
|
|
|
351
384
|
return;
|
|
352
385
|
lines.push(`## ${heading}`, ...items.map((item) => `- ${item}`));
|
|
353
386
|
};
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
section
|
|
387
|
+
// `level` is how many of the graded sections survive: 3 keeps all, 2 drops
|
|
388
|
+
// Overturned, 1 keeps only Did, 0 keeps only Asked. Asked is never dropped by
|
|
389
|
+
// the level because it is the one section nothing later can rebuild — the
|
|
390
|
+
// reply arrives in the next turn, but the question and its options exist only
|
|
391
|
+
// here. See `renderDigest` for why the ladder exists at all.
|
|
392
|
+
if (level >= 1)
|
|
393
|
+
section('Did', extraction.did);
|
|
394
|
+
if (level >= 2)
|
|
395
|
+
section('Concluded', extraction.concluded);
|
|
396
|
+
if (level >= 3)
|
|
397
|
+
section('Overturned', extraction.overturned);
|
|
357
398
|
// Asked goes last and its options are listed under it, so the user's reply — the
|
|
358
399
|
// next `## user` line — lands directly under the list it chose from.
|
|
359
400
|
if (extraction.asked.length > 0) {
|
|
@@ -370,8 +411,62 @@ export function renderExtractionBlock(extraction) {
|
|
|
370
411
|
}
|
|
371
412
|
return lines.join('\n');
|
|
372
413
|
}
|
|
414
|
+
/**
|
|
415
|
+
* The group starts a fold walk visits, oldest first, one entry per group.
|
|
416
|
+
*
|
|
417
|
+
* Extracted so the walk's bounds are testable without a session, a logger and a
|
|
418
|
+
* model: the walk itself was where two defects lived — a bound that skipped the
|
|
419
|
+
* last group, and a start advanced from the success count, which retried a failed
|
|
420
|
+
* group on every pass.
|
|
421
|
+
*
|
|
422
|
+
* @param sectionCount - how many sections the digest has.
|
|
423
|
+
* @returns the start index of each group, in order.
|
|
424
|
+
*/
|
|
425
|
+
export function foldGroupStarts(sectionCount) {
|
|
426
|
+
const starts = [];
|
|
427
|
+
for (let start = 0; start < sectionCount; start += CONDENSE_GROUP)
|
|
428
|
+
starts.push(start);
|
|
429
|
+
return starts;
|
|
430
|
+
}
|
|
373
431
|
/** Turns handed to one extraction call. */
|
|
374
432
|
const TURNS_PER_CALL = 8;
|
|
433
|
+
/**
|
|
434
|
+
* Sections folded into one condensed block when the digest overflows.
|
|
435
|
+
*
|
|
436
|
+
* Each fold is a model call, so the group size trades calls against compression.
|
|
437
|
+
* Simulated on a 700- and a 1200-turn digest at the measured 8.2% fold ratio:
|
|
438
|
+
*
|
|
439
|
+
* group 20 → 19 and 52 calls
|
|
440
|
+
* group 50 → 8 and 21 calls
|
|
441
|
+
* group 100 → 4 and 11 calls
|
|
442
|
+
*
|
|
443
|
+
* Larger groups fold more text per call, which is also where the ratio holds
|
|
444
|
+
* best: a 20-section group is small enough that the model's own paragraph is a
|
|
445
|
+
* larger share of it. 100 keeps a long session to a handful of calls.
|
|
446
|
+
*/
|
|
447
|
+
const CONDENSE_GROUP = 100;
|
|
448
|
+
/**
|
|
449
|
+
* Output tokens allowed for one condensation call.
|
|
450
|
+
*
|
|
451
|
+
* A condensed block stands in for `CONDENSE_GROUP` sections, so it has to be far
|
|
452
|
+
* smaller than what it replaces to buy any room at all. Measured on 12000
|
|
453
|
+
* characters of real digest: the answer ran 565 tokens and produced 987
|
|
454
|
+
* characters, 8.2% of the input.
|
|
455
|
+
*
|
|
456
|
+
* The cap is far above that answer because thinking is charged to the same
|
|
457
|
+
* budget and is not small: the same call spent 1873 tokens thinking. At a 1200
|
|
458
|
+
* cap it returned an empty string in one run out of one — the thinking block
|
|
459
|
+
* took the whole allowance, the same failure the extraction call had.
|
|
460
|
+
*/
|
|
461
|
+
const CONDENSE_TOKENS = 6000;
|
|
462
|
+
const CONDENSE_INSTRUCTION = [
|
|
463
|
+
'The text above is the digest of a run of already-finished turns from a coding session.',
|
|
464
|
+
'Fold it into one short paragraph that a later turn can read to know what that stretch established.',
|
|
465
|
+
'Keep: decisions still in force, constraints that still apply, conclusions a later turn would otherwise redo, and anything later turns disproved.',
|
|
466
|
+
'Drop: per-turn narration, restatements, and detail already superseded by later turns in the same run.',
|
|
467
|
+
'Reply with the paragraph and nothing else. No heading, no bullets, no code fence, no preamble.',
|
|
468
|
+
'Write in the same language as the material.',
|
|
469
|
+
].join('\n');
|
|
375
470
|
/**
|
|
376
471
|
* Output tokens allowed per turn in an extraction call.
|
|
377
472
|
*
|
|
@@ -398,8 +493,6 @@ const EXTRACT_THINKING_RESERVE_TOKENS = 1000;
|
|
|
398
493
|
const MAX_HINTS_PER_TURN = 120;
|
|
399
494
|
/** Characters kept from one call's description or command head. */
|
|
400
495
|
const HINT_CHARS = 100;
|
|
401
|
-
/** Characters kept from one failing result's first line. */
|
|
402
|
-
const ERROR_CHARS = 140;
|
|
403
496
|
/**
|
|
404
497
|
* The best short description of what one call was for.
|
|
405
498
|
*
|
|
@@ -418,35 +511,6 @@ function hintOf(argumentsJson) {
|
|
|
418
511
|
catch {
|
|
419
512
|
return '';
|
|
420
513
|
}
|
|
421
|
-
// `ask_user_question` carries `questions[]`, not a `description`. Without this
|
|
422
|
-
// branch the hint was the bare tool name, so the extractor never saw what was
|
|
423
|
-
// asked and `## Asked` came out empty or wrong on every turn that used it.
|
|
424
|
-
const questions = parsed['questions'];
|
|
425
|
-
if (Array.isArray(questions)) {
|
|
426
|
-
const asked = questions
|
|
427
|
-
.map((question) => {
|
|
428
|
-
if (typeof question !== 'object' || question === null)
|
|
429
|
-
return '';
|
|
430
|
-
const record = question;
|
|
431
|
-
const text = typeof record['question'] === 'string'
|
|
432
|
-
? record['question']
|
|
433
|
-
: typeof record['header'] === 'string' ? record['header'] : '';
|
|
434
|
-
const options = Array.isArray(record['options'])
|
|
435
|
-
? record['options']
|
|
436
|
-
.map((option) => (typeof option === 'object' && option !== null
|
|
437
|
-
? String(option['label'] ?? '')
|
|
438
|
-
: ''))
|
|
439
|
-
.filter((label) => label.length > 0)
|
|
440
|
-
: [];
|
|
441
|
-
if (text.length === 0)
|
|
442
|
-
return '';
|
|
443
|
-
return options.length === 0 ? text : `${text} [options: ${options.join(' / ')}]`;
|
|
444
|
-
})
|
|
445
|
-
.filter((text) => text.length > 0)
|
|
446
|
-
.join(' | ');
|
|
447
|
-
if (asked.length > 0)
|
|
448
|
-
return asked.replace(/\s+/g, ' ').slice(0, HINT_CHARS * 2);
|
|
449
|
-
}
|
|
450
514
|
for (const key of ['description', 'command', 'query', 'file_path', 'path', 'pattern']) {
|
|
451
515
|
const candidate = parsed[key];
|
|
452
516
|
if (typeof candidate === 'string' && candidate.trim().length > 0) {
|
|
@@ -461,8 +525,10 @@ function hintOf(argumentsJson) {
|
|
|
461
525
|
* This is what lets a turn whose assistant prose is empty still leave a record:
|
|
462
526
|
* in the measured session one turn ran 342 tool calls and emitted zero prose, so
|
|
463
527
|
* the verbatim digest reduced it to a single `tools:` count line. The trace names
|
|
464
|
-
* what was attempted
|
|
465
|
-
*
|
|
528
|
+
* what was attempted, which is enough for a model to state the outcome.
|
|
529
|
+
*
|
|
530
|
+
* Tool results are not read. Their only contribution used to be a first-line
|
|
531
|
+
* error string, and that string was never the part of a failure that mattered.
|
|
466
532
|
*
|
|
467
533
|
* Bounded on purpose — 500 calls would otherwise produce a prompt larger than the
|
|
468
534
|
* material it summarizes.
|
|
@@ -473,49 +539,25 @@ function hintOf(argumentsJson) {
|
|
|
473
539
|
export function collectHints(events) {
|
|
474
540
|
const lines = [];
|
|
475
541
|
let calls = 0;
|
|
476
|
-
// Tool-call ids of this turn's questions, so the matching result can be read as
|
|
477
|
-
// an answer rather than being skipped as a non-error result.
|
|
478
|
-
const askedIds = new Set();
|
|
479
542
|
for (const event of events) {
|
|
480
543
|
// Tool calls are blocks inside `assistant/message`, not standalone events:
|
|
481
544
|
// `digestSource` emits no `tool/call` type at all, so selecting on that type
|
|
482
545
|
// matched nothing and a 342-call turn produced a single hint line.
|
|
483
|
-
if (event.type
|
|
484
|
-
for (const call of toolCallsOf(event)) {
|
|
485
|
-
// A question is never dropped by the cap. It is the only record of what was
|
|
486
|
-
// asked, and its answer is matched by call id rather than by the cap, so
|
|
487
|
-
// dropping the question left an orphan ANSWER line with nothing beside it —
|
|
488
|
-
// a real turn made 292 calls, the question came late, and the user's choice
|
|
489
|
-
// never reached the digest.
|
|
490
|
-
const isQuestion = call.name === 'ask_user_question';
|
|
491
|
-
if (!isQuestion) {
|
|
492
|
-
if (calls >= MAX_HINTS_PER_TURN)
|
|
493
|
-
break;
|
|
494
|
-
calls += 1;
|
|
495
|
-
}
|
|
496
|
-
const hint = hintOf(call.arguments);
|
|
497
|
-
lines.push(hint.length > 0 ? `TOOL ${call.name}: ${hint}` : `TOOL ${call.name}`);
|
|
498
|
-
if (isQuestion)
|
|
499
|
-
askedIds.add(call.id);
|
|
500
|
-
}
|
|
501
|
-
continue;
|
|
502
|
-
}
|
|
503
|
-
if (event.type !== 'tool/result')
|
|
504
|
-
continue;
|
|
505
|
-
// The answer to a question is the tool's own result, not an error. It is the
|
|
506
|
-
// only record of what the user chose, and the next user message is often just
|
|
507
|
-
// "1" — so it has to travel with the question.
|
|
508
|
-
const answered = answerOf(event, askedIds);
|
|
509
|
-
if (answered !== undefined) {
|
|
510
|
-
lines.push(`ANSWER: ${answered}`);
|
|
546
|
+
if (event.type !== 'assistant/message')
|
|
511
547
|
continue;
|
|
548
|
+
for (const call of toolCallsOf(event)) {
|
|
549
|
+
// A question is not a hint. It and its answer are rendered from the log by
|
|
550
|
+
// `renderAnswers`, so listing it here as well only invited the model to
|
|
551
|
+
// restate it in `asked` — the same exchange printed twice, once of them
|
|
552
|
+
// paraphrased.
|
|
553
|
+
if (call.name === 'ask_user_question')
|
|
554
|
+
continue;
|
|
555
|
+
if (calls >= MAX_HINTS_PER_TURN)
|
|
556
|
+
break;
|
|
557
|
+
calls += 1;
|
|
558
|
+
const hint = hintOf(call.arguments);
|
|
559
|
+
lines.push(hint.length > 0 ? `TOOL ${call.name}: ${hint}` : `TOOL ${call.name}`);
|
|
512
560
|
}
|
|
513
|
-
if (!isErrorResult(event))
|
|
514
|
-
continue;
|
|
515
|
-
const firstLine = textOf(event).split('\n')[0] ?? '';
|
|
516
|
-
if (firstLine.trim().length === 0)
|
|
517
|
-
continue;
|
|
518
|
-
lines.push(`ERR ${firstLine.trim().slice(0, ERROR_CHARS)}`);
|
|
519
561
|
}
|
|
520
562
|
return lines.join('\n');
|
|
521
563
|
}
|
|
@@ -538,8 +580,8 @@ function turnOf(event) {
|
|
|
538
580
|
return typeof turn === 'number' && Number.isInteger(turn) ? turn : undefined;
|
|
539
581
|
}
|
|
540
582
|
/** A fresh, empty turn accumulator. */
|
|
541
|
-
function emptyTurn(turn) {
|
|
542
|
-
return { turn, user: [], assistant: [], tools: new Map(),
|
|
583
|
+
function emptyTurn(turn, fromRequest = false) {
|
|
584
|
+
return { turn, fromRequest, user: [], assistant: [], tools: new Map(), writes: [], answered: [] };
|
|
543
585
|
}
|
|
544
586
|
/**
|
|
545
587
|
* Group append-origin surface events into per-turn digest material.
|
|
@@ -558,12 +600,12 @@ export function buildSections(events) {
|
|
|
558
600
|
let current;
|
|
559
601
|
let currentTurn;
|
|
560
602
|
let lastTurn;
|
|
561
|
-
const openTurn = (turn) => {
|
|
603
|
+
const openTurn = (turn, fromRequest = false) => {
|
|
562
604
|
if (current === undefined) {
|
|
563
605
|
current = { turns: [] };
|
|
564
606
|
sections.push(current);
|
|
565
607
|
}
|
|
566
|
-
const next = emptyTurn(turn);
|
|
608
|
+
const next = emptyTurn(turn, fromRequest);
|
|
567
609
|
current.turns.push(next);
|
|
568
610
|
if (turn !== undefined)
|
|
569
611
|
lastTurn = turn;
|
|
@@ -573,6 +615,16 @@ export function buildSections(events) {
|
|
|
573
615
|
// objective on every round, so recording each copy would repeat it dozens of
|
|
574
616
|
// times across a long autonomous run.
|
|
575
617
|
const recordedObjectives = new Set();
|
|
618
|
+
// Question id to question text, for every `ask_user_question` call seen so far.
|
|
619
|
+
// The answer batch names questions by id only, and an id like `quota` says
|
|
620
|
+
// nothing on its own.
|
|
621
|
+
const questionTexts = new Map();
|
|
622
|
+
// Call ids of this turn's `ask_user_question` calls. A result is an answer only
|
|
623
|
+
// when its own call asked something: without this every result in the log was
|
|
624
|
+
// JSON-parsed (536 KB across 157 results in one measured session, the largest
|
|
625
|
+
// 49.9 KB) and any output that happened to look like an answer batch — a file
|
|
626
|
+
// dump, a test fixture — would be recorded as something the user chose.
|
|
627
|
+
const questionCallIds = new Set();
|
|
576
628
|
for (const event of events) {
|
|
577
629
|
if (event.type === 'turn/start') {
|
|
578
630
|
const turn = turnOf(event);
|
|
@@ -593,20 +645,27 @@ export function buildSections(events) {
|
|
|
593
645
|
// takes the user slot: it is the request this turn serves.
|
|
594
646
|
current = { turns: [] };
|
|
595
647
|
sections.push(current);
|
|
596
|
-
currentTurn = openTurn(turnOf(event) ?? lastTurn);
|
|
648
|
+
currentTurn = openTurn(turnOf(event) ?? lastTurn, false);
|
|
597
649
|
currentTurn.user.push(objective);
|
|
598
650
|
continue;
|
|
599
651
|
}
|
|
600
652
|
if (event.type === 'tool/result') {
|
|
601
|
-
|
|
653
|
+
// An answered question arrives as this call's own result. The call's
|
|
654
|
+
// arguments named the questions; the result carries the choices.
|
|
655
|
+
const callId = messageOf(event)?.toolCallId;
|
|
656
|
+
if (callId === undefined || !questionCallIds.has(callId) || currentTurn === undefined)
|
|
602
657
|
continue;
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
658
|
+
currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
// The host answers a question two ways. Inside the waiting window the answer
|
|
662
|
+
// is the tool result above; after the call already returned its pending
|
|
663
|
+
// notice, it is a `user/message` whose source kind is `user-question-reply`
|
|
664
|
+
// and whose body is the same answer batch. That message is not a new request,
|
|
665
|
+
// so it is read here rather than opening a section.
|
|
666
|
+
if (sourceKind(event) === 'user-question-reply') {
|
|
667
|
+
if (currentTurn !== undefined)
|
|
668
|
+
currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
|
|
610
669
|
continue;
|
|
611
670
|
}
|
|
612
671
|
if (event.type !== 'user/message' && event.type !== 'assistant/message')
|
|
@@ -620,7 +679,7 @@ export function buildSections(events) {
|
|
|
620
679
|
// what makes the digest readable after a hundred turns.
|
|
621
680
|
current = { turns: [] };
|
|
622
681
|
sections.push(current);
|
|
623
|
-
currentTurn = openTurn(eventTurn);
|
|
682
|
+
currentTurn = openTurn(eventTurn, true);
|
|
624
683
|
const text = textOf(event);
|
|
625
684
|
if (text.length > 0)
|
|
626
685
|
currentTurn.user.push(text);
|
|
@@ -644,6 +703,12 @@ export function buildSections(events) {
|
|
|
644
703
|
currentTurn.assistant.push(text);
|
|
645
704
|
for (const call of toolCallsOf(event)) {
|
|
646
705
|
currentTurn.tools.set(call.name, (currentTurn.tools.get(call.name) ?? 0) + 1);
|
|
706
|
+
if (call.name === 'ask_user_question') {
|
|
707
|
+
for (const [id, question] of questionTextsOf(call.arguments))
|
|
708
|
+
questionTexts.set(id, question);
|
|
709
|
+
questionCallIds.add(call.id);
|
|
710
|
+
continue;
|
|
711
|
+
}
|
|
647
712
|
if (!WRITE_TOOLS.has(call.name))
|
|
648
713
|
continue;
|
|
649
714
|
const path = pathArgumentOf(call.arguments);
|
|
@@ -685,19 +750,35 @@ function withExtractions(sections, extracted) {
|
|
|
685
750
|
function turnKey(sectionIndex, turnIndex) {
|
|
686
751
|
return `${sectionIndex}:${turnIndex}`;
|
|
687
752
|
}
|
|
753
|
+
/**
|
|
754
|
+
* A stable hex digest of one string, used as a cache key.
|
|
755
|
+
*
|
|
756
|
+
* FNV-1a, 32-bit, two seeds. Not cryptographic: the risk here is an accidental
|
|
757
|
+
* collision between two inputs, and 64 bits over a few hundred entries makes that
|
|
758
|
+
* vanishingly unlikely.
|
|
759
|
+
*
|
|
760
|
+
* @param input - the text to hash.
|
|
761
|
+
* @returns a stable hex key.
|
|
762
|
+
*/
|
|
763
|
+
function hashText(input) {
|
|
764
|
+
let a = 0x811c9dc5;
|
|
765
|
+
let b = 0x01000193;
|
|
766
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
767
|
+
const code = input.charCodeAt(index);
|
|
768
|
+
a = Math.imul(a ^ code, 0x01000193) >>> 0;
|
|
769
|
+
b = Math.imul(b ^ (code + index), 0x85ebca6b) >>> 0;
|
|
770
|
+
}
|
|
771
|
+
return `${a.toString(16)}${b.toString(16)}`;
|
|
772
|
+
}
|
|
688
773
|
/**
|
|
689
774
|
* Cache key for one slot's extraction material: a hash of everything the model
|
|
690
775
|
* would be shown.
|
|
691
776
|
*
|
|
692
777
|
* The material, not the slot's position or turn number: positions shift as
|
|
693
778
|
* history grows and numbers repeat, but identical material must produce an
|
|
694
|
-
* identical extraction. Hashing the exact string `buildExtractionMaterial`
|
|
695
|
-
*
|
|
696
|
-
*
|
|
697
|
-
*
|
|
698
|
-
* FNV-1a, 32-bit, two seeds. Not cryptographic: the risk here is an accidental
|
|
699
|
-
* collision between two turns, and 64 bits over a few hundred entries makes that
|
|
700
|
-
* vanishingly unlikely.
|
|
779
|
+
* identical extraction. Hashing the exact string `buildExtractionMaterial` returns
|
|
780
|
+
* means a change anywhere in the user request, the prose, or the tool trace
|
|
781
|
+
* invalidates the entry — nothing can silently go stale.
|
|
701
782
|
*
|
|
702
783
|
* @param events - one slot's events, in log order.
|
|
703
784
|
* @returns a stable hex key.
|
|
@@ -708,15 +789,7 @@ function materialKey(events) {
|
|
|
708
789
|
.map((event) => textOf(event))
|
|
709
790
|
.filter((text) => text.length > 0)
|
|
710
791
|
.join('\n');
|
|
711
|
-
|
|
712
|
-
let a = 0x811c9dc5;
|
|
713
|
-
let b = 0x01000193;
|
|
714
|
-
for (let index = 0; index < material.length; index += 1) {
|
|
715
|
-
const code = material.charCodeAt(index);
|
|
716
|
-
a = Math.imul(a ^ code, 0x01000193) >>> 0;
|
|
717
|
-
b = Math.imul(b ^ (code + index), 0x85ebca6b) >>> 0;
|
|
718
|
-
}
|
|
719
|
-
return `${a.toString(16)}${b.toString(16)}`;
|
|
792
|
+
return hashText(buildExtractionMaterial(events, prose));
|
|
720
793
|
}
|
|
721
794
|
/**
|
|
722
795
|
* Render one section to digest text, truncating assistant prose to `capChars`.
|
|
@@ -729,40 +802,64 @@ function materialKey(events) {
|
|
|
729
802
|
* The tool pointer line stays either way: it is one line, and it is the only
|
|
730
803
|
* record of what was actually run when the prose and extraction both say little.
|
|
731
804
|
*/
|
|
732
|
-
function renderSection(section,
|
|
805
|
+
function renderSection(section, level, condensed, sectionIndex) {
|
|
733
806
|
const lines = [];
|
|
734
|
-
|
|
807
|
+
// The block that covers this section, if any. Looked up by scanning the keys
|
|
808
|
+
// rather than by probing one key per turn: a fold spans whole sections, so the
|
|
809
|
+
// covering key belongs to an earlier section, not to this turn's own key.
|
|
810
|
+
const index = sectionIndex ?? 0;
|
|
811
|
+
let covering;
|
|
812
|
+
if (condensed !== undefined) {
|
|
813
|
+
for (const [key, block] of condensed) {
|
|
814
|
+
const start = Number(key.split(':')[0]);
|
|
815
|
+
if (index >= start && index < start + block.covers) {
|
|
816
|
+
covering = { key, block };
|
|
817
|
+
break;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
if (covering !== undefined) {
|
|
822
|
+
// The user line stays: a request is a standing constraint. Only the first
|
|
823
|
+
// covered section prints the folded text — the rest contribute their user
|
|
824
|
+
// lines alone, which is the room the condensation buys.
|
|
825
|
+
const start = Number(covering.key.split(':')[0]);
|
|
826
|
+
for (const turn of section.turns) {
|
|
827
|
+
if (turn.user.length > 0)
|
|
828
|
+
lines.push(`\n## user\n${turn.user.join('\n')}`);
|
|
829
|
+
}
|
|
830
|
+
if (index === start) {
|
|
831
|
+
const range = covering.block.covers <= 1
|
|
832
|
+
? `section ${start + 1}`
|
|
833
|
+
: `sections ${start + 1}-${start + covering.block.covers}`;
|
|
834
|
+
lines.push(`\n### assistant\n## Condensed (condensed from ${range})\n- ${covering.block.text}`);
|
|
835
|
+
}
|
|
836
|
+
return lines.join('\n');
|
|
837
|
+
}
|
|
838
|
+
for (const [turnIndex, turn] of section.turns.entries()) {
|
|
735
839
|
if (turn.user.length > 0)
|
|
736
840
|
lines.push(`\n## user\n${turn.user.join('\n')}`);
|
|
737
841
|
// An extraction whose every field is empty renders nothing: a heading followed by
|
|
738
842
|
// no body reads as a turn that did something but says nothing.
|
|
739
|
-
if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted).length > 0) {
|
|
740
|
-
|
|
741
|
-
if (capChars !== undefined && block.length > capChars) {
|
|
742
|
-
block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
|
|
743
|
-
}
|
|
843
|
+
if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted, level).length > 0) {
|
|
844
|
+
const block = renderExtractionBlock(turn.extracted, level);
|
|
744
845
|
// 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
|
|
846
|
+
// last section and the user's reply is the very next line, so a trailer line
|
|
746
847
|
// in between would separate the reply from the question it answers.
|
|
747
848
|
const trailer = [];
|
|
748
|
-
if (turn.errors.length > 0) {
|
|
749
|
-
trailer.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
|
|
750
|
-
}
|
|
751
849
|
if (turn.writes.length > 0)
|
|
752
850
|
trailer.push(` wrote: ${turn.writes.join(', ')}`);
|
|
753
|
-
const
|
|
851
|
+
const withAnswers = insertAnswers(block, renderAnswers(turn));
|
|
852
|
+
const body = trailer.length > 0 ? `${trailer.join('\n')}\n${withAnswers}` : withAnswers;
|
|
754
853
|
lines.push(`### assistant\n${body}`);
|
|
755
854
|
}
|
|
756
855
|
else {
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
lines.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
|
|
765
|
-
}
|
|
856
|
+
const body = turn.assistant.join('\n');
|
|
857
|
+
const answers = renderAnswers(turn);
|
|
858
|
+
// The heading goes on whenever there is anything to put under it. Emitting
|
|
859
|
+
// the answers bare put `## Answers` directly below `## user`, at the user's
|
|
860
|
+
// own heading level, where it reads as something the user said.
|
|
861
|
+
if (body.length > 0 || answers.length > 0)
|
|
862
|
+
lines.push(`### assistant\n${[body, answers].filter((part) => part.length > 0).join('\n')}`);
|
|
766
863
|
if (turn.writes.length > 0)
|
|
767
864
|
lines.push(` wrote: ${turn.writes.join(', ')}`);
|
|
768
865
|
}
|
|
@@ -770,55 +867,90 @@ function renderSection(section, capChars) {
|
|
|
770
867
|
return lines.join('\n');
|
|
771
868
|
}
|
|
772
869
|
/**
|
|
773
|
-
*
|
|
774
|
-
*
|
|
775
|
-
*
|
|
776
|
-
*
|
|
777
|
-
*
|
|
778
|
-
*
|
|
779
|
-
*
|
|
780
|
-
*
|
|
870
|
+
* Render a turn's tool questions and their answers, or an empty string.
|
|
871
|
+
*
|
|
872
|
+
* This section exists because `## Asked` cannot cover these. `asked` is written by
|
|
873
|
+
* the model from prose, and its contract says the reply is the next `## user` line
|
|
874
|
+
* — true for a question asked in prose, false for one asked through
|
|
875
|
+
* `ask_user_question`: the user answers inside the picker, the answer becomes the
|
|
876
|
+
* tool result, and no user message is ever written. Two consecutive checkpoints of
|
|
877
|
+
* a real session carried neither the question nor the answer.
|
|
878
|
+
*
|
|
879
|
+
* Rendered from the log, so it cannot be paraphrased away, and placed after the
|
|
880
|
+
* assistant block because it belongs to that turn's work.
|
|
881
|
+
*
|
|
882
|
+
* @param turn - one turn's digest material.
|
|
883
|
+
* @returns the `## Answers` section, or an empty string when nothing was asked.
|
|
781
884
|
*/
|
|
782
|
-
function
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
885
|
+
function renderAnswers(turn) {
|
|
886
|
+
if (turn.answered.length === 0)
|
|
887
|
+
return '';
|
|
888
|
+
return `## Answers\n${turn.answered.flatMap(renderAnswered).join('\n')}`;
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Place the `## Answers` section just above `## Asked`, or at the end when the
|
|
892
|
+
* block has none.
|
|
893
|
+
*
|
|
894
|
+
* Not at the end unconditionally: `## Asked` is the block's last section because
|
|
895
|
+
* the user's reply — a bare `1` — is the very next line and needs the options
|
|
896
|
+
* directly above it. A second question-and-answer block wedged in between would
|
|
897
|
+
* separate them.
|
|
898
|
+
*
|
|
899
|
+
* @param block - the rendered extraction block.
|
|
900
|
+
* @param answers - the rendered `## Answers` section, or an empty string.
|
|
901
|
+
* @returns the block with the answers placed.
|
|
902
|
+
*/
|
|
903
|
+
function insertAnswers(block, answers) {
|
|
904
|
+
if (answers.length === 0)
|
|
905
|
+
return block;
|
|
906
|
+
// The heading as a whole line, not the bare text: a `did`/`concluded` item is a
|
|
907
|
+
// free string, and one that happens to contain `## Asked` would otherwise be
|
|
908
|
+
// split in the middle of a bullet.
|
|
909
|
+
const at = block.startsWith('## Asked\n') ? 0 : block.indexOf('\n## Asked\n') + 1;
|
|
910
|
+
if (at <= 0 && !block.startsWith('## Asked\n'))
|
|
911
|
+
return `${block}\n${answers}`;
|
|
912
|
+
const head = block.slice(0, at);
|
|
913
|
+
return head.length === 0 ? `${answers}\n${block}` : `${head}${answers}\n${block.slice(at)}`;
|
|
792
914
|
}
|
|
793
915
|
/**
|
|
794
916
|
* Render the digest under a hard character budget.
|
|
795
917
|
*
|
|
796
|
-
*
|
|
918
|
+
* Three tiers, in order:
|
|
797
919
|
*
|
|
798
920
|
* - **T1** user prose is verbatim unless it alone exceeds `USER_BUDGET_SHARE` of
|
|
799
921
|
* the budget, then the oldest turns are cut first. The share is 0.9 rather than
|
|
800
922
|
* 0.5 because real user prose is a few percent of the digest: at 0.5 the
|
|
801
923
|
* extracted blocks crowded out the oldest human messages, which are exactly the
|
|
802
924
|
* standing constraints (「请用pixi管理开发环境」) that must survive.
|
|
803
|
-
* - **T1'**
|
|
804
|
-
*
|
|
925
|
+
* - **T1'** the graded ladder: each block drops Overturned, then Concluded, then
|
|
926
|
+
* Did, while Asked survives every level.
|
|
927
|
+
* - **T2** whole turn bodies go, oldest first, when even the surviving sections
|
|
928
|
+
* overflow. The user lines stay; only what the assistant produced is dropped.
|
|
805
929
|
*
|
|
806
930
|
* T1' runs *after* T1 because a user's own words are the least reconstructible
|
|
807
|
-
* thing in the log: an assistant's reply can be inferred from its tool calls
|
|
808
|
-
*
|
|
809
|
-
* exists so a tight budget thins every turn instead of erasing the last few.
|
|
931
|
+
* thing in the log: an assistant's reply can be inferred from its tool calls and
|
|
932
|
+
* the surrounding turns, a user's request cannot.
|
|
810
933
|
*
|
|
811
|
-
*
|
|
934
|
+
* All three tiers run on a long session, and that is by design: the ceiling is
|
|
812
935
|
* absolute (`DIGEST_TOKEN_CEILING`), so a 122-turn history with 316k characters
|
|
813
936
|
* of assistant prose cannot fit verbatim. In the extractive design most turns
|
|
814
937
|
* carry an extraction instead of prose, which keeps the digest far below the
|
|
815
938
|
* ceiling; the tiers exist for the turns where extraction was unavailable and
|
|
816
939
|
* the prose is all that remains.
|
|
940
|
+
*
|
|
941
|
+
* When `condensed` is supplied the tiers are skipped and the digest is returned
|
|
942
|
+
* whole. That path is entered only by `condenseOldest`, which owns the overflow:
|
|
943
|
+
* degrading here would report "fits" at a level that has already dropped the
|
|
944
|
+
* sections the fold was meant to preserve, and the fold loop would stop early
|
|
945
|
+
* having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
|
|
946
|
+
* bodies, leaving only `## Asked`, before condensation ever got a chance.
|
|
817
947
|
*/
|
|
818
|
-
export function renderDigest(events, budgetTokens, extracted) {
|
|
948
|
+
export function renderDigest(events, budgetTokens, extracted, condensed) {
|
|
819
949
|
const sections = extracted === undefined ? buildSections(events) : withExtractions(buildSections(events), extracted);
|
|
820
950
|
const budgetChars = Math.max(0, budgetTokens * 4);
|
|
821
|
-
const render = (
|
|
951
|
+
const render = (trimmed, level = 3) => (trimmed ?? sections)
|
|
952
|
+
.map((section, index) => renderSection(section, level, condensed, index))
|
|
953
|
+
.join('\n');
|
|
822
954
|
// User prose is reserved before anything else is placed.
|
|
823
955
|
//
|
|
824
956
|
// Measured on a 122-turn session: every human message in the span totalled 469
|
|
@@ -828,7 +960,7 @@ export function renderDigest(events, budgetTokens, extracted) {
|
|
|
828
960
|
// standing constraints (「请用pixi管理开发环境」) that never expire, while the
|
|
829
961
|
// extraction describes work that is already finished.
|
|
830
962
|
const userReserve = Math.min(Math.floor(budgetChars * USER_BUDGET_SHARE), sections.reduce((total, section) => total + section.turns.reduce((sum, turn) => sum + turn.user.join('\n').length, 0), 0));
|
|
831
|
-
const verbatim = render(
|
|
963
|
+
const verbatim = render();
|
|
832
964
|
if (verbatim.length <= budgetChars)
|
|
833
965
|
return verbatim;
|
|
834
966
|
// T1: user prose over its share, oldest first. Only the user side changes, so
|
|
@@ -856,43 +988,142 @@ export function renderDigest(events, budgetTokens, extracted) {
|
|
|
856
988
|
}
|
|
857
989
|
}
|
|
858
990
|
}
|
|
859
|
-
const afterT1 = render(
|
|
991
|
+
const afterT1 = render(t1);
|
|
860
992
|
if (afterT1.length <= budgetChars)
|
|
861
993
|
return afterT1;
|
|
862
994
|
// The user side fits inside its reserve; what overflows is the turn bodies
|
|
863
995
|
// (extraction or prose plus pointers). Thin those, and only drop whole turns
|
|
864
996
|
// once every body is already at zero — dropping a turn also drops the user
|
|
865
997
|
// prose in it, which is what the reserve exists to prevent.
|
|
866
|
-
// T1':
|
|
867
|
-
//
|
|
868
|
-
//
|
|
869
|
-
//
|
|
998
|
+
// T1': the graded ladder. Each level drops one section from every block —
|
|
999
|
+
// Overturned first, then Concluded, then Did — and Asked survives all of them.
|
|
1000
|
+
//
|
|
1001
|
+
// This replaces a character cap applied to each block. That cap sliced every
|
|
1002
|
+
// extraction at the same offset, and because Asked is the block's last section
|
|
1003
|
+
// it was the first thing eaten: at 490 turns each question rendered as ` 1.`
|
|
1004
|
+
// with its options gone, and by 520 both Asked and Overturned were absent from
|
|
1005
|
+
// every block. A half-line reads as data, so slicing loses more than dropping:
|
|
1006
|
+
// the reader cannot tell a truncated fact from a short one.
|
|
1007
|
+
//
|
|
1008
|
+
// Asked outranks everything because it is the only section nothing later can
|
|
1009
|
+
// rebuild. Did and Concluded describe work whose results are still in the
|
|
1010
|
+
// working tree; the question and the options the user chose between exist only
|
|
1011
|
+
// in this line.
|
|
1012
|
+
//
|
|
1013
|
+
// No character cap at any level: a block either renders whole or loses a whole
|
|
1014
|
+
// section. Slicing was the original mechanism and it cut Asked's options off
|
|
1015
|
+
// mid-list, which reads as data rather than as truncation.
|
|
1016
|
+
//
|
|
1017
|
+
// The ladder only runs when no condensation was supplied. A condensed digest
|
|
1018
|
+
// that still overflows is the caller's problem to fix by folding more turns:
|
|
1019
|
+
// degrading it here would report "fits" at a level that has already dropped the
|
|
1020
|
+
// sections the fold was meant to preserve, and the fold loop would stop early
|
|
1021
|
+
// having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
|
|
1022
|
+
// bodies, leaving only `## Asked`, before condensation ever got a chance.
|
|
1023
|
+
if (condensed !== undefined && condensed.size > 0) {
|
|
1024
|
+
// Returned whole even when it still overflows. The caller folds more turns and
|
|
1025
|
+
// asks again; slicing here would cut the last block mid-line, which is the
|
|
1026
|
+
// failure this whole path exists to remove.
|
|
1027
|
+
return render(t1, 3);
|
|
1028
|
+
}
|
|
1029
|
+
for (let level = 3; level >= 0; level -= 1) {
|
|
1030
|
+
const whole = render(t1, level);
|
|
1031
|
+
if (whole.length <= budgetChars)
|
|
1032
|
+
return whole;
|
|
1033
|
+
}
|
|
1034
|
+
// Every level overflowed with prose already at zero, so the user lines plus the
|
|
1035
|
+
// surviving Asked sections alone exceed the budget. Drop the oldest turn
|
|
1036
|
+
// *bodies* rather than the oldest sections: a dropped section takes the user's
|
|
1037
|
+
// request with it, and those requests are standing constraints ("请用pixi管理
|
|
1038
|
+
// 开发环境") that never expire, while a body describes work already superseded.
|
|
1039
|
+
// The newest turns are the ones the next request depends on, so the cut runs
|
|
1040
|
+
// from the oldest end.
|
|
1041
|
+
const positions = [];
|
|
1042
|
+
for (const [section, { turns }] of t1.entries()) {
|
|
1043
|
+
for (let turn = 0; turn < turns.length; turn += 1)
|
|
1044
|
+
positions.push({ section, turn });
|
|
1045
|
+
}
|
|
1046
|
+
const withoutBodies = (count) => {
|
|
1047
|
+
const trimmed = t1.map((section) => ({ turns: section.turns.map((turn) => ({ ...turn })) }));
|
|
1048
|
+
for (const { section, turn } of positions.slice(0, count)) {
|
|
1049
|
+
const target = trimmed[section]?.turns[turn];
|
|
1050
|
+
if (target === undefined)
|
|
1051
|
+
continue;
|
|
1052
|
+
// The user line stays; only what the assistant produced goes. `delete`
|
|
1053
|
+
// rather than assigning undefined: `exactOptionalPropertyTypes` treats the
|
|
1054
|
+
// key's absence and its undefined value as different types.
|
|
1055
|
+
delete target.extracted;
|
|
1056
|
+
target.assistant = [];
|
|
1057
|
+
target.writes = [];
|
|
1058
|
+
// The answers belong to the body: they were produced by this turn's own
|
|
1059
|
+
// tool call, so a dropped body that kept them would still print a full
|
|
1060
|
+
// `## Answers` at every tier, and the truncation would never fit.
|
|
1061
|
+
target.answered = [];
|
|
1062
|
+
}
|
|
1063
|
+
return trimmed;
|
|
1064
|
+
};
|
|
1065
|
+
// Lower bound on the drop count: the smallest number that fits. `Math.floor`
|
|
1066
|
+
// rather than `ceil` is load-bearing — with `ceil`, `mid` equals `high` once the
|
|
1067
|
+
// range narrows to two entries, so a fitting `mid` left `high` unchanged and the
|
|
1068
|
+
// loop never terminated. A 2200-turn digest hung here; 2100 happened to converge.
|
|
870
1069
|
let low = 0;
|
|
871
|
-
let high =
|
|
1070
|
+
let high = positions.length;
|
|
872
1071
|
while (low < high) {
|
|
873
|
-
const mid = Math.
|
|
874
|
-
|
|
875
|
-
|
|
1072
|
+
const mid = Math.floor((low + high) / 2);
|
|
1073
|
+
const marker = mid === 0 ? '' : `…(${mid} oldest turn bodies dropped: over budget)\n`;
|
|
1074
|
+
if (marker.length + render(withoutBodies(mid), 0).length <= budgetChars)
|
|
1075
|
+
high = mid;
|
|
876
1076
|
else
|
|
877
|
-
|
|
1077
|
+
low = mid + 1;
|
|
878
1078
|
}
|
|
879
|
-
const
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
//
|
|
884
|
-
//
|
|
1079
|
+
const marker = low === 0 ? '' : `…(${low} oldest turn bodies dropped: over budget)\n`;
|
|
1080
|
+
const stripped = render(withoutBodies(low), 0);
|
|
1081
|
+
if (marker.length + stripped.length <= budgetChars)
|
|
1082
|
+
return `${marker}${stripped}`;
|
|
1083
|
+
// Even with every body gone the user lines alone overflow — a budget smaller
|
|
1084
|
+
// than the requests it must hold. Only here do whole sections go, oldest first:
|
|
1085
|
+
// slicing the tail instead would cut the newest turns, which are exactly the
|
|
1086
|
+
// ones the next request depends on.
|
|
1087
|
+
// Still over budget with every body gone. Drop whole turns from the oldest end
|
|
1088
|
+
// — a dropped turn takes its user line with it, which is the price of a budget
|
|
1089
|
+
// too small to hold the requests themselves. The newest turn is never dropped,
|
|
1090
|
+
// and the walk keeps every turn after the cut point rather than only the last
|
|
1091
|
+
// one: a `goal` round records its objective as a user message and can sit after
|
|
1092
|
+
// the newest request, so keeping just `slice(-1)` kept the goal and lost the
|
|
1093
|
+
// request.
|
|
1094
|
+
// The cut never passes the last turn carrying a user request. Without this the
|
|
1095
|
+
// walk reached the very end — the fixture's `goal` round is the last position,
|
|
1096
|
+
// so dropping up to it kept the goal and lost `USER-13`, the newest request.
|
|
1097
|
+
const turnAt = (position) => position === undefined ? undefined : t1[position.section]?.turns[position.turn];
|
|
1098
|
+
let lastRequest = positions.length - 1;
|
|
1099
|
+
while (lastRequest > 0 && turnAt(positions[lastRequest])?.fromRequest !== true)
|
|
1100
|
+
lastRequest -= 1;
|
|
885
1101
|
let first = 0;
|
|
886
|
-
|
|
887
|
-
while (first < t1.length - 1) {
|
|
888
|
-
dropped += 1;
|
|
1102
|
+
while (first < lastRequest) {
|
|
889
1103
|
first += 1;
|
|
890
|
-
const
|
|
891
|
-
|
|
1104
|
+
const cut = positions[first];
|
|
1105
|
+
if (cut === undefined)
|
|
1106
|
+
break;
|
|
1107
|
+
const kept = t1
|
|
1108
|
+
.map((section, sectionIndex) => ({
|
|
1109
|
+
turns: section.turns.filter((_, turnIndex) => sectionIndex > cut.section || (sectionIndex === cut.section && turnIndex >= cut.turn)),
|
|
1110
|
+
}))
|
|
1111
|
+
.filter((section) => section.turns.length > 0);
|
|
1112
|
+
const rest = render(kept, 0);
|
|
1113
|
+
const text = `…(${first} earlier turn(s) dropped: over budget)\n${rest}`;
|
|
892
1114
|
if (text.length <= budgetChars)
|
|
893
1115
|
return text;
|
|
894
1116
|
}
|
|
895
|
-
|
|
1117
|
+
// Nothing fit, so keep the one turn the next request depends on: the newest one
|
|
1118
|
+
// carrying a user request, not the last position in the log.
|
|
1119
|
+
// Only the user line: the budget cannot even hold one full turn, and the request
|
|
1120
|
+
// is the part the next turn is answering.
|
|
1121
|
+
const keeperTurn = turnAt(positions[lastRequest]);
|
|
1122
|
+
if (keeperTurn === undefined)
|
|
1123
|
+
return '';
|
|
1124
|
+
const bare = { ...keeperTurn, assistant: [], writes: [], answered: [] };
|
|
1125
|
+
delete bare.extracted;
|
|
1126
|
+
return render([{ turns: [bare] }], 0);
|
|
896
1127
|
}
|
|
897
1128
|
/**
|
|
898
1129
|
* The surface seqs this compaction shadows, recovered from the summarization
|
|
@@ -999,6 +1230,66 @@ export function buildExtractionMaterial(turn, prose) {
|
|
|
999
1230
|
* @param signal - cancellation forwarded to the adapter.
|
|
1000
1231
|
* @returns the extracted blocks by slot key; empty when extraction is unavailable.
|
|
1001
1232
|
*/
|
|
1233
|
+
/**
|
|
1234
|
+
* One condensation request: fold a run of already-finished turns into a paragraph.
|
|
1235
|
+
*
|
|
1236
|
+
* Module-level and shaped like `extractOnce` rather than a method, so both calls
|
|
1237
|
+
* derive their route and reasoning effort the same way.
|
|
1238
|
+
*
|
|
1239
|
+
* @param ctx - plugin context carrying the `llm` service and a logger.
|
|
1240
|
+
* @param agent - owner of the session being compacted.
|
|
1241
|
+
* @param material - the rendered blocks being folded.
|
|
1242
|
+
* @param signal - cancellation forwarded to the adapter.
|
|
1243
|
+
* @returns the folded paragraph, or undefined when the call produced nothing.
|
|
1244
|
+
*/
|
|
1245
|
+
async function condenseOnce(ctx, agent, material, signal) {
|
|
1246
|
+
const llm = ctx.llm;
|
|
1247
|
+
if (llm === undefined) {
|
|
1248
|
+
ctx.logger?.warn('verbatim-compaction: no llm service, condensation skipped');
|
|
1249
|
+
return undefined;
|
|
1250
|
+
}
|
|
1251
|
+
const route = agent.session.requestHeader()?.config;
|
|
1252
|
+
const provider = route?.provider ?? agent.options.provider;
|
|
1253
|
+
const model = route?.model ?? agent.options.model;
|
|
1254
|
+
if (provider === undefined || model === undefined) {
|
|
1255
|
+
ctx.logger?.warn('verbatim-compaction: no route for condensation, skipped');
|
|
1256
|
+
return undefined;
|
|
1257
|
+
}
|
|
1258
|
+
const info = await Promise.resolve()
|
|
1259
|
+
.then(() => llm.resolveModelInfo?.(provider, model, signal))
|
|
1260
|
+
.catch(() => undefined);
|
|
1261
|
+
const cheapest = cheapestEffort(info?.reasoning?.efforts);
|
|
1262
|
+
const chunks = [];
|
|
1263
|
+
try {
|
|
1264
|
+
const stream = llm.stream({
|
|
1265
|
+
provider,
|
|
1266
|
+
model,
|
|
1267
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: `${material}\n\n${CONDENSE_INSTRUCTION}` }] }],
|
|
1268
|
+
maxTokens: CONDENSE_TOKENS,
|
|
1269
|
+
sessionId: agent.session.id,
|
|
1270
|
+
purpose: 'compaction',
|
|
1271
|
+
...(cheapest === undefined ? {} : { reasoningEffort: cheapest }),
|
|
1272
|
+
...(signal === undefined ? {} : { signal }),
|
|
1273
|
+
});
|
|
1274
|
+
for await (const chunk of stream) {
|
|
1275
|
+
const delta = chunk;
|
|
1276
|
+
if (delta.type === 'text-delta' && typeof delta.text === 'string')
|
|
1277
|
+
chunks.push(delta.text);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
catch (error) {
|
|
1281
|
+
ctx.logger?.warn(`verbatim-compaction: condensation call failed: ${String(error)}`);
|
|
1282
|
+
return undefined;
|
|
1283
|
+
}
|
|
1284
|
+
const text = chunks.join('').trim();
|
|
1285
|
+
if (text.length === 0) {
|
|
1286
|
+
// Silence here is what makes "the digest stopped folding" invisible at runtime:
|
|
1287
|
+
// the summary still renders, just without the room the fold would have bought.
|
|
1288
|
+
ctx.logger?.warn(`verbatim-compaction: condensation returned no text for ${material.length} chars of material`);
|
|
1289
|
+
return undefined;
|
|
1290
|
+
}
|
|
1291
|
+
return text;
|
|
1292
|
+
}
|
|
1002
1293
|
async function extractBatch(ctx, agent, batch, signal) {
|
|
1003
1294
|
const out = new Map();
|
|
1004
1295
|
if (batch.length === 0)
|
|
@@ -1149,7 +1440,7 @@ async function extractOnce(ctx, agent, batch, signal) {
|
|
|
1149
1440
|
return { blocks: parseExtraction(answer), truncated };
|
|
1150
1441
|
}
|
|
1151
1442
|
/**
|
|
1152
|
-
*
|
|
1443
|
+
* Extractive compaction backend: verbatim user prose, one model call per batch,
|
|
1153
1444
|
* call.
|
|
1154
1445
|
*
|
|
1155
1446
|
* Everything except `summarize()` is inherited. The base class prices pressure,
|
|
@@ -1175,6 +1466,14 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1175
1466
|
* the same behaviour as before this cache existed.
|
|
1176
1467
|
*/
|
|
1177
1468
|
extractionCache = new Map();
|
|
1469
|
+
/**
|
|
1470
|
+
* Folded text, keyed by provider, model and a hash of the material folded.
|
|
1471
|
+
*
|
|
1472
|
+
* Same reasoning as `extractionCache`: the fold is a model call over material
|
|
1473
|
+
* rebuilt from the raw log on every compaction, so the same run of old turns is
|
|
1474
|
+
* re-folded on every later compaction unless it is remembered.
|
|
1475
|
+
*/
|
|
1476
|
+
condensedCache = new Map();
|
|
1178
1477
|
/**
|
|
1179
1478
|
* Build the replacement checkpoint content from the session log.
|
|
1180
1479
|
*
|
|
@@ -1187,10 +1486,10 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1187
1486
|
*
|
|
1188
1487
|
* @param input - replayed conversation prefix the base class is shadowing.
|
|
1189
1488
|
* @param agent - owner of the session being compacted.
|
|
1190
|
-
* @param
|
|
1489
|
+
* @param signal - cancellation forwarded to the extraction and fold calls.
|
|
1191
1490
|
* @returns text summary blocks, unmarked by any LLM call.
|
|
1192
1491
|
*/
|
|
1193
|
-
async summarize(input, agent,
|
|
1492
|
+
async summarize(input, agent, signal) {
|
|
1194
1493
|
const session = agent.session;
|
|
1195
1494
|
const shadowed = shadowedSeqs(session, input);
|
|
1196
1495
|
const shadowedSet = new Set(shadowed);
|
|
@@ -1205,8 +1504,24 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1205
1504
|
// size independent of history length; the guard bound only exists for the
|
|
1206
1505
|
// degenerate case of a span smaller than the ceiling.
|
|
1207
1506
|
const budget = Math.max(0, Math.min(DIGEST_TOKEN_CEILING, shadowedPrice - FRAME_TOKENS - SHRINK_MARGIN_TOKENS));
|
|
1208
|
-
const extracted = await this.extractAll(source, agent,
|
|
1209
|
-
|
|
1507
|
+
const extracted = await this.extractAll(source, agent, signal);
|
|
1508
|
+
// Fold the oldest turns up only when the plain digest overflows. The fold is an
|
|
1509
|
+
// LLM call, so a digest that already fits must not pay for one.
|
|
1510
|
+
let condensed;
|
|
1511
|
+
if (renderDigest(source, budget, extracted).length > budget * 4) {
|
|
1512
|
+
condensed = await this.condenseOldest(source, extracted, agent, budget, signal);
|
|
1513
|
+
}
|
|
1514
|
+
// The fold path returns its digest whole, so it can still overflow when every
|
|
1515
|
+
// group has been folded and the user lines alone are too long. The budget is a
|
|
1516
|
+
// contract the host's shrink guard depends on, so that case falls back to the
|
|
1517
|
+
// ladder: a degraded digest beats an over-budget one. The fold is the better
|
|
1518
|
+
// outcome, not the only permitted one.
|
|
1519
|
+
let text = renderDigest(source, budget, extracted, condensed);
|
|
1520
|
+
if (text.length > budget * 4) {
|
|
1521
|
+
this.ctx.logger?.warn(`verbatim-compaction: digest still over budget after folding ${condensed?.size ?? 0} group(s) `
|
|
1522
|
+
+ `(${text.length} > ${budget * 4} chars), falling back to the graded ladder`);
|
|
1523
|
+
text = renderDigest(source, budget, extracted);
|
|
1524
|
+
}
|
|
1210
1525
|
const route = session.requestHeader()?.config;
|
|
1211
1526
|
return {
|
|
1212
1527
|
summary: [{ type: 'text', text }],
|
|
@@ -1214,6 +1529,104 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1214
1529
|
model: route?.model ?? agent.options.model ?? 'digest',
|
|
1215
1530
|
};
|
|
1216
1531
|
}
|
|
1532
|
+
/**
|
|
1533
|
+
* Fold the oldest turns into condensed blocks until the digest fits.
|
|
1534
|
+
*
|
|
1535
|
+
* Only reached when the plain digest overflows `budget`. The oldest turns are
|
|
1536
|
+
* the right ones to fold: they describe work already superseded, while the
|
|
1537
|
+
* newest are what the next request depends on.
|
|
1538
|
+
*
|
|
1539
|
+
* Linear in groups, not bisected: a fold is not monotone in how much is folded —
|
|
1540
|
+
* a paragraph's length depends on what the model chose to keep — so there is no
|
|
1541
|
+
* boundary to bisect. The walk stops at the first size that fits, which is the
|
|
1542
|
+
* fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
|
|
1543
|
+
* consecutive sections, so the number of calls is proportional to the digest,
|
|
1544
|
+
* not to the number of turns.
|
|
1545
|
+
*
|
|
1546
|
+
* Cached by content, like the extraction: the same prefix of turns folds to the
|
|
1547
|
+
* same text, and a later compaction re-reads the same history.
|
|
1548
|
+
*
|
|
1549
|
+
* @param source - digest source events, in log order.
|
|
1550
|
+
* @param extracted - per-turn extractions already computed.
|
|
1551
|
+
* @param agent - owner of the session being compacted.
|
|
1552
|
+
* @param budget - token budget the digest must fit.
|
|
1553
|
+
* @param signal - cancellation forwarded to every call.
|
|
1554
|
+
* @returns condensed blocks keyed by the `turnKey` of the first covered section.
|
|
1555
|
+
*/
|
|
1556
|
+
async condenseOldest(source, extracted, agent, budget, signal) {
|
|
1557
|
+
const sections = withExtractions(buildSections(source), extracted);
|
|
1558
|
+
const budgetChars = budget * 4;
|
|
1559
|
+
const out = new Map();
|
|
1560
|
+
// One group per iteration, oldest first, checking after each whether the digest
|
|
1561
|
+
// fits. Single loop, `start` monotone: the earlier two-level form advanced its
|
|
1562
|
+
// inner start from `out.size`, so a group whose call failed was retried on every
|
|
1563
|
+
// outer pass (45 calls instead of 4 with the model down), and the outer bound
|
|
1564
|
+
// `covered < sections.length` stopped one group short of the end — at 700
|
|
1565
|
+
// sections the last 100 were never folded, and at 100 or fewer the loop body
|
|
1566
|
+
// never ran at all.
|
|
1567
|
+
for (const start of foldGroupStarts(sections.length)) {
|
|
1568
|
+
if (signal?.aborted === true)
|
|
1569
|
+
break;
|
|
1570
|
+
const group = sections.slice(start, start + CONDENSE_GROUP);
|
|
1571
|
+
if (group.length === 0)
|
|
1572
|
+
continue;
|
|
1573
|
+
const text = await this.condenseGroup(group, agent, signal);
|
|
1574
|
+
// A failed group is skipped rather than retried: the next group still buys
|
|
1575
|
+
// room, and retrying the same material against a failing model only spends
|
|
1576
|
+
// calls. The remaining turns keep their own blocks either way.
|
|
1577
|
+
if (text === undefined)
|
|
1578
|
+
continue;
|
|
1579
|
+
out.set(turnKey(start, 0), { text, covers: group.length });
|
|
1580
|
+
if (renderDigest(source, budget, extracted, out).length <= budgetChars)
|
|
1581
|
+
return out;
|
|
1582
|
+
}
|
|
1583
|
+
return out;
|
|
1584
|
+
}
|
|
1585
|
+
/**
|
|
1586
|
+
* Hand one group of turns to the model and return its folded text.
|
|
1587
|
+
*
|
|
1588
|
+
* @param group - consecutive sections to fold into one paragraph.
|
|
1589
|
+
* @param agent - owner of the session being compacted.
|
|
1590
|
+
* @param signal - cancellation forwarded to the call.
|
|
1591
|
+
* @returns the folded paragraph, or undefined when the call produced nothing.
|
|
1592
|
+
*/
|
|
1593
|
+
async condenseGroup(group, agent, signal) {
|
|
1594
|
+
// Both sources, because a turn has one or the other: extraction succeeds and
|
|
1595
|
+
// the block replaces the prose, or it fails and the verbatim prose is what the
|
|
1596
|
+
// digest shows. Reading only `extracted` meant a run of turns whose extraction
|
|
1597
|
+
// failed contributed nothing — and because the fold then still replaced them,
|
|
1598
|
+
// their content vanished from the digest entirely rather than merely being
|
|
1599
|
+
// summarised badly.
|
|
1600
|
+
const material = group
|
|
1601
|
+
.map((section) => section.turns
|
|
1602
|
+
.map((turn) => {
|
|
1603
|
+
const block = renderExtractionBlock(turn.extracted);
|
|
1604
|
+
return block.length > 0 ? block : turn.assistant.join('\n');
|
|
1605
|
+
})
|
|
1606
|
+
.filter((block) => block.length > 0)
|
|
1607
|
+
.join('\n'))
|
|
1608
|
+
.filter((block) => block.length > 0)
|
|
1609
|
+
.join('\n\n');
|
|
1610
|
+
if (material.length === 0)
|
|
1611
|
+
return undefined;
|
|
1612
|
+
const llm = this.ctx.llm;
|
|
1613
|
+
if (llm === undefined)
|
|
1614
|
+
return undefined;
|
|
1615
|
+
const route = agent.session.requestHeader()?.config;
|
|
1616
|
+
const provider = route?.provider ?? agent.options.provider;
|
|
1617
|
+
const model = route?.model ?? agent.options.model;
|
|
1618
|
+
if (provider === undefined || model === undefined)
|
|
1619
|
+
return undefined;
|
|
1620
|
+
const key = `${provider}:${model}:${hashText(material)}`;
|
|
1621
|
+
const cached = this.condensedCache.get(key);
|
|
1622
|
+
if (cached !== undefined)
|
|
1623
|
+
return cached;
|
|
1624
|
+
const text = await condenseOnce(this.ctx, agent, material, signal);
|
|
1625
|
+
if (text === undefined)
|
|
1626
|
+
return undefined;
|
|
1627
|
+
this.condensedCache.set(key, text);
|
|
1628
|
+
return text;
|
|
1629
|
+
}
|
|
1217
1630
|
/**
|
|
1218
1631
|
* Run the extraction for every turn in the digest source.
|
|
1219
1632
|
*
|