pi-tuck 1.7.0 → 1.9.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/CHANGELOG.md +32 -0
- package/README.md +5 -1
- package/dist/src/budget.d.ts +4 -0
- package/dist/src/budget.js +3 -1
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.js +53 -10
- package/dist/src/diagnostics.d.ts +1 -1
- package/dist/src/kept-reads.d.ts +1 -1
- package/dist/src/kept-reads.js +2 -2
- package/dist/src/lean.d.ts +23 -0
- package/dist/src/lean.js +55 -0
- package/dist/src/status.d.ts +2 -0
- package/dist/src/status.js +3 -1
- package/dist/src/thrash.d.ts +25 -0
- package/dist/src/thrash.js +59 -0
- package/dist/src/tuck/core/format.d.ts +14 -0
- package/dist/src/tuck/core/format.js +10 -0
- package/dist/src/tuck.d.ts +4 -0
- package/dist/src/tuck.js +124 -17
- package/dist/src/working-set.d.ts +26 -0
- package/dist/src/working-set.js +80 -0
- package/package.json +1 -1
- package/src/budget.ts +4 -2
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +47 -10
- package/src/kept-reads.ts +2 -2
- package/src/lean.ts +47 -0
- package/src/status.ts +5 -1
- package/src/thrash.ts +57 -0
- package/src/tuck/core/format.ts +11 -0
- package/src/tuck.ts +109 -15
- package/src/working-set.ts +66 -0
package/src/thrash.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { isDiscardedResponse } from "./protocol";
|
|
3
|
+
import { pathKey } from "./path-key";
|
|
4
|
+
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
5
|
+
import { extractPath } from "./tuck/core/tool-args";
|
|
6
|
+
|
|
7
|
+
/** A re-read counts when it is issued within this many replies after a cut. */
|
|
8
|
+
export const THRASH_WINDOW_REPLIES = 3;
|
|
9
|
+
/** Re-reads per cut at which a session is thrashing. */
|
|
10
|
+
export const THRASH_BAR = 0.5;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
|
|
14
|
+
* limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
|
|
15
|
+
* within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
|
|
16
|
+
* such re-read, it never does. Deterministic: it reads only the recorded branch.
|
|
17
|
+
*/
|
|
18
|
+
export interface Rereads { cuts: number; rereads: number; tokens: number }
|
|
19
|
+
/** The branch's cuts and the re-reads that followed them (as `thrashing` defines a re-read), with their text in tokens at 4 characters each. */
|
|
20
|
+
export function rereadsAfterCuts(branch: readonly SessionEntry[]): Rereads {
|
|
21
|
+
let cuts = 0, replies = 0, rereads = 0, chars = 0;
|
|
22
|
+
const pending = new Map<string, { key: string; cut: number; soon: boolean }>(), last = new Map<string, { cut: number; text: string }>();
|
|
23
|
+
for (const entry of branch) {
|
|
24
|
+
if (entry.type === "compaction") { cuts++; replies = 0; continue; }
|
|
25
|
+
if (entry.type !== "message") continue;
|
|
26
|
+
const message = entry.message;
|
|
27
|
+
if (message.role === "assistant") {
|
|
28
|
+
if (isDiscardedResponse(message)) continue;
|
|
29
|
+
replies++;
|
|
30
|
+
for (const block of message.content) {
|
|
31
|
+
if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;
|
|
32
|
+
const args = block.arguments as Record<string, unknown>, path = extractPath(args);
|
|
33
|
+
if (!path) continue;
|
|
34
|
+
pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: cuts, soon: cuts > 0 && replies <= THRASH_WINDOW_REPLIES });
|
|
35
|
+
}
|
|
36
|
+
} else if (message.role === "toolResult") {
|
|
37
|
+
const read = pending.get(message.toolCallId);
|
|
38
|
+
if (!read || message.isError || !isTextOnly(message.content)) continue;
|
|
39
|
+
pending.delete(message.toolCallId);
|
|
40
|
+
const text = textOf(message.content), earlier = last.get(read.key);
|
|
41
|
+
if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text) { rereads++; chars += text.length; }
|
|
42
|
+
last.set(read.key, { cut: read.cut, text });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return { cuts, rereads, tokens: Math.ceil(chars / 4) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
|
|
50
|
+
* limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
|
|
51
|
+
* within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
|
|
52
|
+
* such re-read, it never does. Deterministic: it reads only the recorded branch.
|
|
53
|
+
*/
|
|
54
|
+
export function thrashing(branch: readonly SessionEntry[]): boolean {
|
|
55
|
+
const { cuts, rereads } = rereadsAfterCuts(branch);
|
|
56
|
+
return cuts > 0 && rereads / cuts >= THRASH_BAR;
|
|
57
|
+
}
|
package/src/tuck/core/format.ts
CHANGED
|
@@ -4,3 +4,14 @@ export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files
|
|
|
4
4
|
"Files created by commands are not listed: Before re-running a command listed above, read its output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
|
|
5
5
|
/** Parsing never depends on this wording (transcript.ts splitSummary). */
|
|
6
6
|
export const DIALOGUE_SUFFIX = CLOSING_SEPARATOR + CLOSING_INSTRUCTION;
|
|
7
|
+
const REREAD = "Re-read a file before editing it or importing from it.";
|
|
8
|
+
/** The closing words when working files follow: the re-read rule stays for every other file. */
|
|
9
|
+
export const WORKING_FILES_INSTRUCTION = CLOSING_INSTRUCTION.replace(REREAD,
|
|
10
|
+
"Re-read a file before editing it or importing from it, unless it is one of the working files below.");
|
|
11
|
+
/** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
|
|
12
|
+
* exactly in an edit). The closing section is kept byte for byte by every parser (transcript.ts splitSummary), so raw text is safe there. */
|
|
13
|
+
export const WORKING_FILES_HEADER = "\n\nWorking files: each is the whole file, identical to the file on disk when this summary was made. Edit from these copies.";
|
|
14
|
+
export const workingFileBlock = (file: { path: string; text: string }): string => `\n<file path=${JSON.stringify(file.path)}>\n${file.text}\n</file>`;
|
|
15
|
+
/** The closing section: the dialogue suffix alone, or, with working files, its working-files form followed by each file. */
|
|
16
|
+
export const closingSuffix = (files: readonly { path: string; text: string }[]): string => files.length
|
|
17
|
+
? CLOSING_SEPARATOR + WORKING_FILES_INSTRUCTION + WORKING_FILES_HEADER + files.map(workingFileBlock).join("") : DIALOGUE_SUFFIX;
|
package/src/tuck.ts
CHANGED
|
@@ -2,12 +2,13 @@ import { resolveSourceTime, type SourceTime } from "./tuck/core/source-time";
|
|
|
2
2
|
import { orderByOriginalSource } from "./tuck/core/source-order";
|
|
3
3
|
import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
|
|
4
4
|
import { parseRecords, serializeTranscript, serializeRecord, splitSummary, TRANSCRIPT_HEADER, type TranscriptRecord } from "./tuck/core/transcript";
|
|
5
|
-
import { DIALOGUE_SUFFIX } from "./tuck/core/format";
|
|
5
|
+
import { closingSuffix, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format";
|
|
6
6
|
import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget";
|
|
7
7
|
import { omissionRecord, userPrefixRecords } from "./tuck/core/brief";
|
|
8
8
|
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
9
9
|
import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
|
|
10
10
|
import { keptReadCandidates } from "./kept-reads.js";
|
|
11
|
+
import { workingSetCandidates, type WorkingFile } from "./working-set.js";
|
|
11
12
|
import { keptSearchCandidates } from "./kept-searches.js";
|
|
12
13
|
import { fileObservations, thinkingRecords } from "./content-observations";
|
|
13
14
|
import { pathKey } from "./path-key";
|
|
@@ -31,6 +32,8 @@ type Draft = { compaction: Pick<Extract<SessionEntry, { type: "compaction" }>, "
|
|
|
31
32
|
export interface RecallContinuation { query: string; throughEntryId: string; offset: number }
|
|
32
33
|
/** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
|
|
33
34
|
export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
|
|
35
|
+
/** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
|
|
36
|
+
export const WORKING_SET_SHARE = 2 / 3;
|
|
34
37
|
/** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
|
|
35
38
|
export interface Tuck {
|
|
36
39
|
buildOwnCut(entries: SessionEntry[], keep: number): Cut;
|
|
@@ -49,6 +52,8 @@ import { buildGlobalIndexById } from "./tuck/core/global-indices";
|
|
|
49
52
|
import { compileDialogue } from "./tuck/core/summarize";
|
|
50
53
|
import { prepareKeywordQuery } from "./tuck/core/keyword-query";
|
|
51
54
|
import { rankRecallRows } from "./tuck/core/search-entries";
|
|
55
|
+
/** The share of the brief below which the carried part of a prefix-stable summary keeps only its user and custom records. */
|
|
56
|
+
export const STABLE_CONSOLIDATE_AT = 0.5;
|
|
52
57
|
export const tuck: Tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
|
|
53
58
|
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
54
59
|
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
@@ -233,8 +238,10 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
233
238
|
const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
|
|
234
239
|
const summaryTokens = (characters: number) => Math.ceil((characters + wrapperCharacters) / 4);
|
|
235
240
|
const lineCost = (records: readonly TranscriptRecord[]) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
|
|
236
|
-
|
|
237
|
-
|
|
241
|
+
// Working files carried raw in the closing section. Chosen once the boundary is known; until then the suffix is the plain one.
|
|
242
|
+
let carried: WorkingFile[] = [], suffix = DIALOGUE_SUFFIX;
|
|
243
|
+
const frameLength = (cost: number, count: number) => TRANSCRIPT_HEADER.length + suffix.length + cost + (count ? 0 : 1);
|
|
244
|
+
const render = (records: TranscriptRecord[]) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + suffix;
|
|
238
245
|
type Unit = { position: number; index: number; count: number };
|
|
239
246
|
const units: Record<"user" | "assistant" | "toolResult", Unit[]> = { user: [], assistant: [], toolResult: [] };
|
|
240
247
|
for (const row of rows) {
|
|
@@ -362,6 +369,21 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
362
369
|
const lists = listsAt(boundary);
|
|
363
370
|
const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
|
|
364
371
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
372
|
+
// The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
|
|
373
|
+
// WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
|
|
374
|
+
const resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
|
|
375
|
+
const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
|
|
376
|
+
if (workingSet.files.length) {
|
|
377
|
+
const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
|
|
378
|
+
let cost = WORKING_FILES_INSTRUCTION.length - CLOSING_INSTRUCTION.length + WORKING_FILES_HEADER.length;
|
|
379
|
+
for (const file of workingSet.files) {
|
|
380
|
+
const extra = workingFileBlock(file).length;
|
|
381
|
+
if (cost + extra > allowance) continue;
|
|
382
|
+
carried.push(file); cost += extra;
|
|
383
|
+
}
|
|
384
|
+
suffix = closingSuffix(carried);
|
|
385
|
+
}
|
|
386
|
+
const carriedKeys = new Set(carried.map(file => file.key));
|
|
365
387
|
let ledger: TranscriptRecord[] = lists.records;
|
|
366
388
|
let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
|
|
367
389
|
// List caps are existing ranking policy; only the carried target is a
|
|
@@ -381,7 +403,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
381
403
|
return row?.message.role === "user" && isTextOnly(row.message.content);
|
|
382
404
|
}));
|
|
383
405
|
const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
|
|
384
|
-
const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
|
|
406
|
+
const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
|
|
385
407
|
const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
|
|
386
408
|
sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position]!)),
|
|
387
409
|
ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
|
|
@@ -420,7 +442,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
420
442
|
const missing = units.user.filter(unit => unit.position < at && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end && !wholeUser.has(unit.index));
|
|
421
443
|
if (!missing.length) records.splice(pos, 1);
|
|
422
444
|
else records[pos] = omissionRecord("user", missing.length, [missing[0]!.index, missing.at(-1)!.index], false);
|
|
423
|
-
} else if (at !== compiledBoundary) {
|
|
445
|
+
} else if (at !== compiledBoundary || stable) {
|
|
424
446
|
const role = record.role;
|
|
425
447
|
if (role === "assistant" || role === "toolResult") {
|
|
426
448
|
const missing = units[role].filter(unit => unit.position < at && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end &&
|
|
@@ -436,17 +458,88 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
436
458
|
const summary = render([...records, ...ledger, ...keptResults, ...thoughtOpenings]);
|
|
437
459
|
return { summary, records: [...records, ...thoughtOpenings] };
|
|
438
460
|
};
|
|
439
|
-
|
|
461
|
+
// Prefix-stable summary: the previous pi-tuck summary's dialogue records are carried verbatim as the oldest part, and only the sources
|
|
462
|
+
// since that cut are compiled after them; counters, lists and kept results follow the dialogue. Consecutive summaries then share a
|
|
463
|
+
// prefix a provider's prompt cache can read. When the carried part leaves the new sources less than half the brief, it keeps only its
|
|
464
|
+
// user and custom records (a fixed point, so the part already kept that way stays the prefix), and past half the brief its oldest
|
|
465
|
+
// sources go, down to a quarter. With no previous pi-tuck summary, a floor summary, or nothing that fits, the whole history is compiled.
|
|
466
|
+
const stableCompile = (): { compiled: ReturnType<typeof tuck.compileDialogue>; carried: boolean } => {
|
|
467
|
+
const whole = () => ({ compiled: tuck.compileDialogue(compileInput), carried: false });
|
|
468
|
+
const previousAt = entries.findLastIndex(entry => entry.type === "compaction");
|
|
469
|
+
const previous = entries[previousAt];
|
|
470
|
+
const details = previous?.type === "compaction" ? previous.details as { compactor?: string; deepest?: boolean } | undefined : undefined;
|
|
471
|
+
if (previous?.type !== "compaction" || details?.compactor !== "pi-tuck" || details.deepest) return whole();
|
|
472
|
+
const split = splitSummary(previous.summary);
|
|
473
|
+
if (!split || split.version !== 2) return whole();
|
|
474
|
+
const from = Math.min(previous.firstKeptEntryId ? positions.get(previous.firstKeptEntryId) ?? previousAt : previousAt, compiledBoundary);
|
|
475
|
+
const indexAt = new Map(rows.map(row => [row.index, row.position]));
|
|
476
|
+
const positionOf = (record: TranscriptRecord) => record.sourceEntryId !== undefined ? positions.get(record.sourceEntryId)
|
|
477
|
+
: record.sourceIndex !== undefined ? indexAt.get(record.sourceIndex) : undefined;
|
|
478
|
+
const dialogue = (record: TranscriptRecord) => record.sourceIndex !== undefined || record.sourceEntryId !== undefined
|
|
479
|
+
? (record.kind === "excerpt" || record.kind === "omission") && (record.role === "user" || record.role === "assistant" || record.role === "custom") : false;
|
|
480
|
+
let old: TranscriptRecord[];
|
|
481
|
+
try { old = parseRecords(split.body, 2).filter(record => dialogue(record) && (positionOf(record) ?? Infinity) < from); }
|
|
482
|
+
catch { return whole(); }
|
|
483
|
+
// One counter per role over the whole compacted history: what the records leave out (assemble counts it again once the protected
|
|
484
|
+
// prompts are merged). Without `records`, every unit counts: a counter that costs at least as much as any real one.
|
|
485
|
+
const counters = (records?: readonly TranscriptRecord[]) => (["user", "assistant", "toolResult"] as const).flatMap(role => {
|
|
486
|
+
const shown = new Map<number, number>();
|
|
487
|
+
for (const record of records ?? []) if (record.kind === "excerpt" && record.role === role && !record.span && record.sourceIndex !== undefined &&
|
|
488
|
+
(role !== "user" || record.text === userTexts.get(record.sourceIndex))) shown.set(record.sourceIndex, (shown.get(record.sourceIndex) ?? 0) + 1);
|
|
489
|
+
const missing = units[role].flatMap(unit => {
|
|
490
|
+
const count = unit.position < compiledBoundary ? unit.count - Math.min(unit.count, shown.get(unit.index) ?? 0) : 0;
|
|
491
|
+
return count ? [{ index: unit.index, count }] : [];
|
|
492
|
+
});
|
|
493
|
+
return missing.length ? [omissionRecord(role, missing.reduce((n, unit) => n + unit.count, 0), [missing[0]!.index, missing.at(-1)!.index], false)] : [];
|
|
494
|
+
});
|
|
495
|
+
// A carried prompt that the protected rows quote too is paid for once, in their fixed cost (assemble keeps one of the two).
|
|
496
|
+
const protectedCost = new Map(protectedView.kept.map(record => [sourceKey(record), lineCost([record])]));
|
|
497
|
+
const oldCost = () => old.reduce((n, record) => n + Math.max(0, lineCost([record]) - (record.role === "user" || record.role === "custom" ? protectedCost.get(sourceKey(record)) ?? 0 : 0)), 0);
|
|
498
|
+
const fresh = sourceRows.filter(row => row.position >= from);
|
|
499
|
+
const compileFresh = (reserve: number) => fresh.length ? tuck.compileDialogue({ messages: fresh.map(row => row.message), sourceIndices: fresh.map(row => row.index),
|
|
500
|
+
sourceEntryIds: fresh.map(row => row.id), sourceTimes: fresh.map(row => resolveSourceTime(entries[row.position]!)),
|
|
501
|
+
ranking: { maxBriefChars: maxBriefChars - oldCost() - reserve, mandatorySourceIndices: mandatory } }) : { text: "", step: "whole" as const, size: 0 };
|
|
502
|
+
// First as if every new source fits whole: then only the counters the carried part and the tool history need are reserved.
|
|
503
|
+
const freshRecords = (compiled: ReturnType<typeof compileFresh>) => {
|
|
504
|
+
const body = compiled.text ? splitSummary(compiled.text) : undefined;
|
|
505
|
+
return body ? parseRecords(body.body, body.version).filter(record => record.kind !== "omission" || record.sourceIndex !== undefined) : undefined;
|
|
506
|
+
};
|
|
507
|
+
const wholeFresh: TranscriptRecord[] = fresh.flatMap((row): TranscriptRecord[] => row.message.role === "user" ? [{ kind: "excerpt" as const, role: "user" as const, sourceIndex: row.index, text: userTexts.get(row.index!) ?? "" }]
|
|
508
|
+
: row.message.role === "assistant" ? row.message.content.flatMap(part => part.type === "text" && part.text.trim() ? [{ kind: "excerpt" as const, role: "assistant" as const, sourceIndex: row.index, text: "" }] : []) : []);
|
|
509
|
+
let compiled = compileFresh(lineCost(counters([...old, ...wholeFresh]))), consolidated = false;
|
|
510
|
+
if (compiled.step !== "whole") {
|
|
511
|
+
if (maxBriefChars - oldCost() - lineCost(counters()) < STABLE_CONSOLIDATE_AT * maxBriefChars) {
|
|
512
|
+
consolidated = true;
|
|
513
|
+
old = old.filter(record => record.role === "user" || record.role === "custom");
|
|
514
|
+
if (oldCost() > STABLE_CONSOLIDATE_AT * maxBriefChars) {
|
|
515
|
+
let cost = oldCost(), first = 0;
|
|
516
|
+
while (first < old.length && cost > maxBriefChars / 4) {
|
|
517
|
+
const at = positionOf(old[first]!);
|
|
518
|
+
while (first < old.length && positionOf(old[first]!) === at) cost -= lineCost([old[first++]!]);
|
|
519
|
+
}
|
|
520
|
+
old = old.slice(first);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
compiled = compileFresh(lineCost(counters()));
|
|
524
|
+
}
|
|
525
|
+
const added = fresh.length ? freshRecords(compiled) : [];
|
|
526
|
+
if (!added) return whole();
|
|
527
|
+
const text = serializeTranscript([...old, ...added, ...counters([...old, ...added])]) + DIALOGUE_SUFFIX;
|
|
528
|
+
if (text.length - lineCost(old) + oldCost() > maxBriefChars) return whole();
|
|
529
|
+
const step = !consolidated && compiled.step === "whole" && (details as { mode?: string }).mode === "dialogue" ? "whole" : "ranked";
|
|
530
|
+
return { compiled: { text, step, size: text.length }, carried: true };
|
|
531
|
+
};
|
|
532
|
+
const { compiled, carried: stable } = stableCompile();
|
|
440
533
|
let offer = assemble(compiled.text);
|
|
441
534
|
// After the complete dialogue fill, observations spend the remaining
|
|
442
535
|
// room before the native tail's older end. The pinned tail is untouched.
|
|
443
536
|
let keptResultCost = 0;
|
|
444
537
|
const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
|
|
445
538
|
const counts = new Map<string, number>();
|
|
446
|
-
const prefix = [header, ...entries.slice(0, boundary)]
|
|
539
|
+
const prefix = [header, ...entries.slice(0, boundary)];
|
|
447
540
|
// Reads and searches share the lead rank, newest result first, and one
|
|
448
541
|
// allowance. Keep L2's independent four-item caps and whole-item skips.
|
|
449
|
-
const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
542
|
+
const candidates = [...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
450
543
|
.sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
|
|
451
544
|
for (const record of candidates) {
|
|
452
545
|
if ((counts.get(record.title!) ?? 0) === 4) continue;
|
|
@@ -458,10 +551,10 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
458
551
|
if (keptResults.length) offer = assemble(compiled.text, boundary);
|
|
459
552
|
const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
|
|
460
553
|
const shownFiles = lists.files.slice(0, Math.min(listedKeep, MAX_LEDGER_LINES));
|
|
461
|
-
const keptReadPaths = new Set(keptResults.filter(record => record.title === "Kept-read").map(record => {
|
|
554
|
+
const keptReadPaths = new Set([...carriedKeys, ...keptResults.filter(record => record.title === "Kept-read").map(record => {
|
|
462
555
|
const heading = record.text!.slice(0, record.text!.indexOf("\n"));
|
|
463
556
|
return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
|
|
464
|
-
}));
|
|
557
|
+
})]);
|
|
465
558
|
const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
|
|
466
559
|
const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
|
|
467
560
|
for (const item of shownFiles) item.definitions = observations.get(item.path);
|
|
@@ -533,12 +626,12 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
533
626
|
return [{ role, missing, ends, counts, cost: lineCost([record]) }];
|
|
534
627
|
});
|
|
535
628
|
const baseCost = lineCost(offer.records) + lineCost(ledger) + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
|
|
536
|
-
const keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
|
|
629
|
+
const keptResultIndices = new Set([...keptResults.map(record => record.sourceIndex), ...carried.map(file => file.sourceIndex)]);
|
|
537
630
|
const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
|
|
538
631
|
const extensionPrice = (at: number) => {
|
|
539
|
-
// Kept results already spend this extension's
|
|
540
|
-
// the compacted prefix, so the native tail never repeats them.
|
|
541
|
-
if (
|
|
632
|
+
// Kept results and working files already spend this extension's
|
|
633
|
+
// price. They stay in the compacted prefix, so the native tail never repeats them.
|
|
634
|
+
if (keptResultIndices.size && at <= lastKeptResultPosition) return Infinity;
|
|
542
635
|
let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
|
|
543
636
|
let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
|
|
544
637
|
for (const range of ranges) {
|
|
@@ -565,7 +658,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
565
658
|
return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
|
|
566
659
|
const mode: DraftMode = compiled.step === "whole" ? "dialogue" : "shrunk";
|
|
567
660
|
return { compaction: { summary: offer.summary, firstKeptEntryId: entries[boundary]?.id ?? "", tokensBefore: input.tokensBefore,
|
|
568
|
-
details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode
|
|
661
|
+
details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode,
|
|
662
|
+
...(workingSet.files.length || workingSet.rejected ? { workingSet: { carried: carried.map(file => file.path), offered: workingSet.files.length, rejected: workingSet.rejected } } : {}) } }, after, mode };
|
|
569
663
|
}
|
|
570
664
|
|
|
571
665
|
/** Numeric references use the original session index, then intersect with readable current-branch entries. */
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { isAbsolute, resolve } from "node:path";
|
|
4
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { pathKey } from "./path-key";
|
|
6
|
+
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
7
|
+
import { extractPath } from "./tuck/core/tool-args";
|
|
8
|
+
|
|
9
|
+
/** Pi's read tool returns at most 50KB of a file's text, so a larger file can never equal a recorded whole read. */
|
|
10
|
+
const MAX_FILE_BYTES = 64 * 1024;
|
|
11
|
+
/** Reads a file's current text, or undefined when it cannot be read. Never throws. */
|
|
12
|
+
export type FileReader = (absolutePath: string) => string | undefined;
|
|
13
|
+
const diskReader: FileReader = path => {
|
|
14
|
+
try { return statSync(path).size > MAX_FILE_BYTES ? undefined : readFileSync(path, "utf8"); } catch { return undefined; }
|
|
15
|
+
};
|
|
16
|
+
let reader = diskReader;
|
|
17
|
+
/** Test and offline-replay seam: where carried files are checked. Undefined restores the disk. */
|
|
18
|
+
export const setWorkingFileReader = (next?: FileReader): void => { reader = next ?? diskReader; };
|
|
19
|
+
|
|
20
|
+
/** Where Pi's read tool reads a recorded path: an "@" prefix dropped, "~" expanded, relative to the session's folder. */
|
|
21
|
+
export const readPath = (path: string, cwd: string): string => {
|
|
22
|
+
let name = path.startsWith("@") ? path.slice(1) : path;
|
|
23
|
+
if (name === "~") name = homedir(); else if (name.startsWith("~/")) name = homedir() + name.slice(1);
|
|
24
|
+
return isAbsolute(name) ? name : resolve(cwd, name);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export interface WorkingFile { path: string; key: string; reads: number; sourceIndex: number; position: number; text: string }
|
|
28
|
+
/**
|
|
29
|
+
* The files the agent has read more than once, most reads first, then most recent last read. A file is carried only when its last read
|
|
30
|
+
* covered the whole file (no offset or limit) and the file on disk holds exactly that read's text now. Pi's read tool returns a whole small
|
|
31
|
+
* file verbatim, so equality proves both that the read was complete and that nothing (an edit, a write, a shell command, a generator) has
|
|
32
|
+
* changed the file since. `rejected` counts the files whose last read was whole but whose disk text differs or cannot be read.
|
|
33
|
+
* Only last reads inside the compacted prefix (before `boundary`) are offered: a later read is still in the native tail.
|
|
34
|
+
*/
|
|
35
|
+
export function workingSetCandidates(entries: readonly SessionEntry[], boundary: number, indices: ReadonlyMap<string, number>, cwd: string,
|
|
36
|
+
resolvable: (entry: SessionEntry) => boolean): { files: WorkingFile[]; rejected: number } {
|
|
37
|
+
const calls = new Map<string, { path: string; key: string; whole: boolean }>(), last = new Map<string, string>(), reads = new Map<string, number>();
|
|
38
|
+
const results = new Map<string, { entry: SessionEntry; position: number }>();
|
|
39
|
+
entries.forEach((entry, position) => {
|
|
40
|
+
if (entry.type !== "message") return;
|
|
41
|
+
if (entry.message.role === "toolResult") { results.set(entry.message.toolCallId, { entry, position }); return; }
|
|
42
|
+
if (entry.message.role !== "assistant") return;
|
|
43
|
+
for (const block of entry.message.content) {
|
|
44
|
+
if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;
|
|
45
|
+
const args = block.arguments as Record<string, unknown>, path = extractPath(args);
|
|
46
|
+
if (!path || /[\r\n]/u.test(path)) continue;
|
|
47
|
+
const key = pathKey(path, cwd);
|
|
48
|
+
calls.set(block.id, { path, key, whole: !("offset" in args) && !("limit" in args) });
|
|
49
|
+
last.set(key, block.id); reads.set(key, (reads.get(key) ?? 0) + 1);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
const files: WorkingFile[] = [];
|
|
53
|
+
let rejected = 0;
|
|
54
|
+
for (const [key, id] of last) {
|
|
55
|
+
const count = reads.get(key)!, call = calls.get(id)!, result = results.get(id);
|
|
56
|
+
if (count < 2 || !call.whole || !result || result.position >= boundary) continue;
|
|
57
|
+
const { entry, position } = result;
|
|
58
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
|
|
59
|
+
const text = textOf(entry.message.content), sourceIndex = indices.get(entry.id);
|
|
60
|
+
if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
|
|
61
|
+
if (reader(readPath(call.path, cwd)) !== text) { rejected++; continue; }
|
|
62
|
+
files.push({ path: call.path, key, reads: count, sourceIndex, position, text });
|
|
63
|
+
}
|
|
64
|
+
files.sort((a, b) => b.reads - a.reads || b.position - a.position);
|
|
65
|
+
return { files, rejected };
|
|
66
|
+
}
|