pi-tuck 1.7.0 → 1.8.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 +14 -0
- package/README.md +3 -1
- package/dist/src/budget.d.ts +2 -0
- package/dist/src/budget.js +2 -1
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.js +22 -5
- 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/thrash.d.ts +12 -0
- package/dist/src/thrash.js +52 -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 +2 -0
- package/dist/src/tuck.js +38 -15
- 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 +3 -2
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +20 -5
- package/src/kept-reads.ts +2 -2
- package/src/thrash.ts +44 -0
- package/src/tuck/core/format.ts +11 -0
- package/src/tuck.ts +34 -13
- package/src/working-set.ts +66 -0
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,20 @@
|
|
|
3
3
|
All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
|
4
4
|
[Semantic Versioning](https://semver.org/).
|
|
5
5
|
|
|
6
|
+
## [1.8.0]
|
|
7
|
+
|
|
8
|
+
### Changed
|
|
9
|
+
|
|
10
|
+
- Working files: at a trim, the files the agent has read more than once are carried whole, verbatim, after the summary's closing words,
|
|
11
|
+
most reads first, then the most recent. A file is carried only when its last read covered the whole file and the file on disk still holds
|
|
12
|
+
exactly that text, so a change by any means (an edit, a shell command, a generator) keeps it out. They are paid for from the summary
|
|
13
|
+
(at most two thirds of it beyond the protected prompts), never from the kept recent messages. The "re-read a file before editing it"
|
|
14
|
+
rule no longer applies to carried files; it stays for every other file.
|
|
15
|
+
- Thrash-adaptive trigger: when a session's trims keep dropping files the agent then reads again unchanged within three replies (half a
|
|
16
|
+
re-read or more per trim), the trim point moves to native Pi's line, the larger of the band and `keepRecentTokens`, capped so the next
|
|
17
|
+
reply keeps its room (at least 3,584 tokens, or 1.7.0's raised room after a length stop). Trims still cut to the band. Sessions without
|
|
18
|
+
such re-reads, an explicit `cutAt`, or a host reserve keep 1.7.0's trim point. Admission is unchanged.
|
|
19
|
+
|
|
6
20
|
## [1.7.0]
|
|
7
21
|
|
|
8
22
|
### Changed
|
package/README.md
CHANGED
|
@@ -12,12 +12,14 @@ pi install npm:pi-tuck
|
|
|
12
12
|
|
|
13
13
|
Start a new Pi process after installing or updating. pi-tuck handles automatic compaction and `/compact` by default. Run `/tuck` to see the loaded version, cut history, and active cut policy.
|
|
14
14
|
|
|
15
|
-
This README describes pi-tuck 1.
|
|
15
|
+
This README describes pi-tuck 1.8.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.8.0` or `pi install git:github.com/galyavin/pi-tuck@v1.8.0`. To uninstall, run `pi remove` with the source you installed.
|
|
16
16
|
|
|
17
17
|
## Compaction and recall
|
|
18
18
|
|
|
19
19
|
A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
|
|
20
20
|
|
|
21
|
+
Files the agent has read more than once are carried whole after the summary, most-read first, as far as a share of the summary allows. A file is carried only when its last read covered the whole file and the file on disk still holds exactly that text; the agent can edit from a carried copy without re-reading it. When a session's cuts keep dropping files the agent then reads again unchanged, pi-tuck moves its trim point later, to native Pi's (the larger of the room and `keepRecentTokens`), while keeping room for the next reply. Cuts still trim to the usual size.
|
|
22
|
+
|
|
21
23
|
When pi-tuck is active, `tuck_recall` becomes available after a cut on the current branch. Use a keyword query to locate a passage.
|
|
22
24
|
|
|
23
25
|
```json
|
package/dist/src/budget.d.ts
CHANGED
|
@@ -125,11 +125,13 @@ export type Gate = {
|
|
|
125
125
|
kind: "plan";
|
|
126
126
|
opportunistic: boolean;
|
|
127
127
|
};
|
|
128
|
+
/** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. */
|
|
128
129
|
export declare function gateCut(input: {
|
|
129
130
|
total: number;
|
|
130
131
|
mandatory: number;
|
|
131
132
|
room: number;
|
|
132
133
|
band: number;
|
|
134
|
+
trigger?: number;
|
|
133
135
|
fits: CutInput["fits"];
|
|
134
136
|
}): Gate;
|
|
135
137
|
/** Whether and how to cut at one boundary: the only decision procedure both triggers use. */
|
package/dist/src/budget.js
CHANGED
|
@@ -105,9 +105,10 @@ export function chooseCut(input) {
|
|
|
105
105
|
return { kind: "fault", capacity: !fits(chosen.after + mandatory, room), message: unreduced };
|
|
106
106
|
return { kind: "cut", target, plan: chosen };
|
|
107
107
|
}
|
|
108
|
+
/** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. */
|
|
108
109
|
export function gateCut(input) {
|
|
109
110
|
const { total, mandatory, room, band, fits } = input;
|
|
110
|
-
if (fits(total, band))
|
|
111
|
+
if (fits(total, Math.max(band, input.trigger ?? band)))
|
|
111
112
|
return { kind: "none" };
|
|
112
113
|
const inBand = fits(total, room);
|
|
113
114
|
if (!fits(mandatory, room))
|
package/dist/src/build-id.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const BUILD_ID = "
|
|
1
|
+
export declare const BUILD_ID = "380741e47dc6a4378eeb32390a184eb747a610ac7b9614d97e86c1dbd3539cc8";
|
package/dist/src/build-id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "380741e47dc6a4378eeb32390a184eb747a610ac7b9614d97e86c1dbd3539cc8";
|
package/dist/src/compaction.js
CHANGED
|
@@ -12,13 +12,14 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
12
12
|
import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
|
|
13
13
|
import { projectedMessages } from "./omissions.js";
|
|
14
14
|
import { applyClips, clipBudgets, clipFor } from "./clip.js";
|
|
15
|
-
import { DEFAULT_CUT_AT, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
|
|
15
|
+
import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
|
|
16
16
|
import { getCurrentSystemMessage, isContextOverflow, normalizeContext } from "@earendil-works/pi-ai";
|
|
17
17
|
import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
18
18
|
import { Type } from "typebox";
|
|
19
19
|
import { Check } from "typebox/value";
|
|
20
20
|
import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
|
|
21
21
|
import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
|
|
22
|
+
import { thrashing } from "./thrash.js";
|
|
22
23
|
import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
|
|
23
24
|
import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
|
|
24
25
|
import { notify } from "./notify.js";
|
|
@@ -403,12 +404,28 @@ export async function installCompaction(pi, options = {}) {
|
|
|
403
404
|
const preservePrefix = (ctx) => ctx.model !== undefined &&
|
|
404
405
|
options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
|
|
405
406
|
const decisionBand = (ctx, room) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
|
|
407
|
+
// Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
|
|
408
|
+
// to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
|
|
409
|
+
// Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
|
|
410
|
+
// room: window - Pi's margin - the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
|
|
411
|
+
// sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
|
|
412
|
+
const triggerLine = (ctx, room) => {
|
|
413
|
+
if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
|
|
414
|
+
return undefined;
|
|
415
|
+
const branch = ctx.sessionManager.getBranch();
|
|
416
|
+
if (!thrashing(branch))
|
|
417
|
+
return undefined;
|
|
418
|
+
const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
|
|
419
|
+
const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
|
|
420
|
+
const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
|
|
421
|
+
return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
422
|
+
};
|
|
406
423
|
/** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
|
|
407
424
|
const cutPoint = (ctx) => {
|
|
408
425
|
if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
|
|
409
426
|
return undefined;
|
|
410
427
|
try {
|
|
411
|
-
const band = decisionBand(ctx,
|
|
428
|
+
const { room } = limits(ctx), band = Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0);
|
|
412
429
|
return band > 0 ? band : undefined;
|
|
413
430
|
}
|
|
414
431
|
catch {
|
|
@@ -648,7 +665,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
648
665
|
// cancel (Pi reports it as aborted), never a failure.
|
|
649
666
|
let thresholdOpportunistic = false;
|
|
650
667
|
if (event.reason === "threshold") {
|
|
651
|
-
const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
668
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
652
669
|
if (gate.kind !== "plan")
|
|
653
670
|
return { cancel: true };
|
|
654
671
|
thresholdOpportunistic = gate.opportunistic;
|
|
@@ -821,7 +838,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
821
838
|
throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
|
|
822
839
|
// A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
|
|
823
840
|
// help: leave it to the complete-context guard, which fails closed.
|
|
824
|
-
const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
841
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
825
842
|
if (gate.kind === "none")
|
|
826
843
|
return;
|
|
827
844
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
@@ -976,7 +993,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
976
993
|
floorKept = undefined;
|
|
977
994
|
const before = measure(saved);
|
|
978
995
|
const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan", opportunistic: false } :
|
|
979
|
-
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
996
|
+
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
980
997
|
if (gate.kind !== "plan")
|
|
981
998
|
return gate;
|
|
982
999
|
return chooseCut({
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type RecallPolicy } from './recall.js';
|
|
2
2
|
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
3
|
-
export declare const DIAGNOSTIC_BUILD = "
|
|
3
|
+
export declare const DIAGNOSTIC_BUILD = "380741e47dc6a4378eeb32390a184eb747a610ac7b9614d97e86c1dbd3539cc8";
|
|
4
4
|
export interface Receipt {
|
|
5
5
|
id: string;
|
|
6
6
|
build: string;
|
package/dist/src/kept-reads.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import type { TranscriptRecord } from "./tuck/core/transcript.js";
|
|
3
3
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
4
|
-
export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
|
|
4
|
+
export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, exclude?: ReadonlySet<string>): TranscriptRecord[];
|
package/dist/src/kept-reads.js
CHANGED
|
@@ -3,7 +3,7 @@ import { pathKey } from "./path-key.js";
|
|
|
3
3
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
4
4
|
import { extractPath } from "./tuck/core/tool-args.js";
|
|
5
5
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
6
|
-
export function keptReadCandidates(entries, indices, resolvable) {
|
|
6
|
+
export function keptReadCandidates(entries, indices, resolvable, exclude = new Set()) {
|
|
7
7
|
const cwd = entries.find((entry) => entry.type === "session")?.cwd;
|
|
8
8
|
const reads = new Map(), mutations = new Map();
|
|
9
9
|
let allMutated = -1;
|
|
@@ -54,7 +54,7 @@ export function keptReadCandidates(entries, indices, resolvable) {
|
|
|
54
54
|
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
|
|
55
55
|
continue;
|
|
56
56
|
const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
|
|
57
|
-
if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order)
|
|
57
|
+
if (!read || seen.has(read.key) || exclude.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order)
|
|
58
58
|
continue;
|
|
59
59
|
const text = textOf(entry.message.content);
|
|
60
60
|
if (!text.length || sourceIndex === undefined || !resolvable(entry))
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/** A re-read counts when it is issued within this many replies after a cut. */
|
|
3
|
+
export declare const THRASH_WINDOW_REPLIES = 3;
|
|
4
|
+
/** Re-reads per cut at which a session is thrashing. */
|
|
5
|
+
export declare const THRASH_BAR = 0.5;
|
|
6
|
+
/**
|
|
7
|
+
* 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
|
|
8
|
+
* 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
|
|
9
|
+
* 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
|
|
10
|
+
* such re-read, it never does. Deterministic: it reads only the recorded branch.
|
|
11
|
+
*/
|
|
12
|
+
export declare function thrashing(branch: readonly SessionEntry[]): boolean;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { isDiscardedResponse } from "./protocol.js";
|
|
2
|
+
import { pathKey } from "./path-key.js";
|
|
3
|
+
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
4
|
+
import { extractPath } from "./tuck/core/tool-args.js";
|
|
5
|
+
/** A re-read counts when it is issued within this many replies after a cut. */
|
|
6
|
+
export const THRASH_WINDOW_REPLIES = 3;
|
|
7
|
+
/** Re-reads per cut at which a session is thrashing. */
|
|
8
|
+
export const THRASH_BAR = 0.5;
|
|
9
|
+
/**
|
|
10
|
+
* 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
|
|
11
|
+
* 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
|
|
12
|
+
* 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
|
|
13
|
+
* such re-read, it never does. Deterministic: it reads only the recorded branch.
|
|
14
|
+
*/
|
|
15
|
+
export function thrashing(branch) {
|
|
16
|
+
let cuts = 0, replies = 0, rereads = 0;
|
|
17
|
+
const pending = new Map(), last = new Map();
|
|
18
|
+
for (const entry of branch) {
|
|
19
|
+
if (entry.type === "compaction") {
|
|
20
|
+
cuts++;
|
|
21
|
+
replies = 0;
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (entry.type !== "message")
|
|
25
|
+
continue;
|
|
26
|
+
const message = entry.message;
|
|
27
|
+
if (message.role === "assistant") {
|
|
28
|
+
if (isDiscardedResponse(message))
|
|
29
|
+
continue;
|
|
30
|
+
replies++;
|
|
31
|
+
for (const block of message.content) {
|
|
32
|
+
if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object")
|
|
33
|
+
continue;
|
|
34
|
+
const args = block.arguments, path = extractPath(args);
|
|
35
|
+
if (!path)
|
|
36
|
+
continue;
|
|
37
|
+
pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: cuts, soon: cuts > 0 && replies <= THRASH_WINDOW_REPLIES });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
else if (message.role === "toolResult") {
|
|
41
|
+
const read = pending.get(message.toolCallId);
|
|
42
|
+
if (!read || message.isError || !isTextOnly(message.content))
|
|
43
|
+
continue;
|
|
44
|
+
pending.delete(message.toolCallId);
|
|
45
|
+
const text = textOf(message.content), earlier = last.get(read.key);
|
|
46
|
+
if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text)
|
|
47
|
+
rereads++;
|
|
48
|
+
last.set(read.key, { cut: read.cut, text });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return cuts > 0 && rereads / cuts >= THRASH_BAR;
|
|
52
|
+
}
|
|
@@ -2,3 +2,17 @@
|
|
|
2
2
|
export declare const CLOSING_INSTRUCTION: string;
|
|
3
3
|
/** Parsing never depends on this wording (transcript.ts splitSummary). */
|
|
4
4
|
export declare const DIALOGUE_SUFFIX: string;
|
|
5
|
+
/** The closing words when working files follow: the re-read rule stays for every other file. */
|
|
6
|
+
export declare const WORKING_FILES_INSTRUCTION: string;
|
|
7
|
+
/** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
|
|
8
|
+
* exactly in an edit). The closing section is kept byte for byte by every parser (transcript.ts splitSummary), so raw text is safe there. */
|
|
9
|
+
export declare 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.";
|
|
10
|
+
export declare const workingFileBlock: (file: {
|
|
11
|
+
path: string;
|
|
12
|
+
text: string;
|
|
13
|
+
}) => string;
|
|
14
|
+
/** The closing section: the dialogue suffix alone, or, with working files, its working-files form followed by each file. */
|
|
15
|
+
export declare const closingSuffix: (files: readonly {
|
|
16
|
+
path: string;
|
|
17
|
+
text: string;
|
|
18
|
+
}[]) => string;
|
|
@@ -4,3 +4,13 @@ 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, "Re-read a file before editing it or importing from it, unless it is one of the working files below.");
|
|
10
|
+
/** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
|
|
11
|
+
* exactly in an edit). The closing section is kept byte for byte by every parser (transcript.ts splitSummary), so raw text is safe there. */
|
|
12
|
+
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.";
|
|
13
|
+
export const workingFileBlock = (file) => `\n<file path=${JSON.stringify(file.path)}>\n${file.text}\n</file>`;
|
|
14
|
+
/** The closing section: the dialogue suffix alone, or, with working files, its working-files form followed by each file. */
|
|
15
|
+
export const closingSuffix = (files) => files.length
|
|
16
|
+
? CLOSING_SEPARATOR + WORKING_FILES_INSTRUCTION + WORKING_FILES_HEADER + files.map(workingFileBlock).join("") : DIALOGUE_SUFFIX;
|
package/dist/src/tuck.d.ts
CHANGED
|
@@ -32,6 +32,8 @@ export interface RecallContinuation {
|
|
|
32
32
|
}
|
|
33
33
|
/** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
|
|
34
34
|
export declare 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 declare const WORKING_SET_SHARE: number;
|
|
35
37
|
/** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
|
|
36
38
|
export interface Tuck {
|
|
37
39
|
buildOwnCut(entries: SessionEntry[], keep: number): Cut;
|
package/dist/src/tuck.js
CHANGED
|
@@ -2,12 +2,13 @@ import { resolveSourceTime } from "./tuck/core/source-time.js";
|
|
|
2
2
|
import { orderByOriginalSource } from "./tuck/core/source-order.js";
|
|
3
3
|
import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
|
|
4
4
|
import { parseRecords, serializeTranscript, serializeRecord, splitSummary, TRANSCRIPT_HEADER } from "./tuck/core/transcript.js";
|
|
5
|
-
import { DIALOGUE_SUFFIX } from "./tuck/core/format.js";
|
|
5
|
+
import { closingSuffix, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format.js";
|
|
6
6
|
import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.js";
|
|
7
7
|
import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
|
|
8
8
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
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 } from "./working-set.js";
|
|
11
12
|
import { keptSearchCandidates } from "./kept-searches.js";
|
|
12
13
|
import { fileObservations, thinkingRecords } from "./content-observations.js";
|
|
13
14
|
import { pathKey } from "./path-key.js";
|
|
@@ -15,6 +16,8 @@ import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
|
15
16
|
import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
|
|
16
17
|
/** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
|
|
17
18
|
export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
|
|
19
|
+
/** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
|
|
20
|
+
export const WORKING_SET_SHARE = 2 / 3;
|
|
18
21
|
import { buildOwnCut, applyTailBudget, MAX_TAIL_TOKENS, OVERSIZED_TAIL_FACTOR } from "./tuck/cut.js";
|
|
19
22
|
import { calibrateCharsPerToken, estimateSourceMessageChars } from "./tuck/core/token-estimate.js";
|
|
20
23
|
import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
|
|
@@ -225,8 +228,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
225
228
|
const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
|
|
226
229
|
const summaryTokens = (characters) => Math.ceil((characters + wrapperCharacters) / 4);
|
|
227
230
|
const lineCost = (records) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
|
|
228
|
-
|
|
229
|
-
|
|
231
|
+
// Working files carried raw in the closing section. Chosen once the boundary is known; until then the suffix is the plain one.
|
|
232
|
+
let carried = [], suffix = DIALOGUE_SUFFIX;
|
|
233
|
+
const frameLength = (cost, count) => TRANSCRIPT_HEADER.length + suffix.length + cost + (count ? 0 : 1);
|
|
234
|
+
const render = (records) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + suffix;
|
|
230
235
|
const units = { user: [], assistant: [], toolResult: [] };
|
|
231
236
|
for (const row of rows) {
|
|
232
237
|
if (row.index === undefined)
|
|
@@ -382,6 +387,23 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
382
387
|
const lists = listsAt(boundary);
|
|
383
388
|
const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
|
|
384
389
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
390
|
+
// The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
|
|
391
|
+
// WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
|
|
392
|
+
const resolvable = (entry) => readable(entry) !== undefined;
|
|
393
|
+
const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
|
|
394
|
+
if (workingSet.files.length) {
|
|
395
|
+
const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
|
|
396
|
+
let cost = WORKING_FILES_INSTRUCTION.length - CLOSING_INSTRUCTION.length + WORKING_FILES_HEADER.length;
|
|
397
|
+
for (const file of workingSet.files) {
|
|
398
|
+
const extra = workingFileBlock(file).length;
|
|
399
|
+
if (cost + extra > allowance)
|
|
400
|
+
continue;
|
|
401
|
+
carried.push(file);
|
|
402
|
+
cost += extra;
|
|
403
|
+
}
|
|
404
|
+
suffix = closingSuffix(carried);
|
|
405
|
+
}
|
|
406
|
+
const carriedKeys = new Set(carried.map(file => file.key));
|
|
385
407
|
let ledger = lists.records;
|
|
386
408
|
let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
|
|
387
409
|
// List caps are existing ranking policy; only the carried target is a
|
|
@@ -402,7 +424,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
402
424
|
return row?.message.role === "user" && isTextOnly(row.message.content);
|
|
403
425
|
}));
|
|
404
426
|
const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
|
|
405
|
-
const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
|
|
427
|
+
const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
|
|
406
428
|
const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
|
|
407
429
|
sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position])),
|
|
408
430
|
ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
|
|
@@ -473,10 +495,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
473
495
|
let keptResultCost = 0;
|
|
474
496
|
const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
|
|
475
497
|
const counts = new Map();
|
|
476
|
-
const prefix = [header, ...entries.slice(0, boundary)]
|
|
498
|
+
const prefix = [header, ...entries.slice(0, boundary)];
|
|
477
499
|
// Reads and searches share the lead rank, newest result first, and one
|
|
478
500
|
// allowance. Keep L2's independent four-item caps and whole-item skips.
|
|
479
|
-
const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
501
|
+
const candidates = [...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
480
502
|
.sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
|
|
481
503
|
for (const record of candidates) {
|
|
482
504
|
if ((counts.get(record.title) ?? 0) === 4)
|
|
@@ -492,10 +514,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
492
514
|
offer = assemble(compiled.text, boundary);
|
|
493
515
|
const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
|
|
494
516
|
const shownFiles = lists.files.slice(0, Math.min(listedKeep, MAX_LEDGER_LINES));
|
|
495
|
-
const keptReadPaths = new Set(keptResults.filter(record => record.title === "Kept-read").map(record => {
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
517
|
+
const keptReadPaths = new Set([...carriedKeys, ...keptResults.filter(record => record.title === "Kept-read").map(record => {
|
|
518
|
+
const heading = record.text.slice(0, record.text.indexOf("\n"));
|
|
519
|
+
return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
|
|
520
|
+
})]);
|
|
499
521
|
const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
|
|
500
522
|
const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
|
|
501
523
|
for (const item of shownFiles)
|
|
@@ -583,12 +605,12 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
583
605
|
return [{ role, missing, ends, counts, cost: lineCost([record]) }];
|
|
584
606
|
});
|
|
585
607
|
const baseCost = lineCost(offer.records) + lineCost(ledger) + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
|
|
586
|
-
const keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
|
|
608
|
+
const keptResultIndices = new Set([...keptResults.map(record => record.sourceIndex), ...carried.map(file => file.sourceIndex)]);
|
|
587
609
|
const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
|
|
588
610
|
const extensionPrice = (at) => {
|
|
589
|
-
// Kept results already spend this extension's
|
|
590
|
-
// the compacted prefix, so the native tail never repeats them.
|
|
591
|
-
if (
|
|
611
|
+
// Kept results and working files already spend this extension's
|
|
612
|
+
// price. They stay in the compacted prefix, so the native tail never repeats them.
|
|
613
|
+
if (keptResultIndices.size && at <= lastKeptResultPosition)
|
|
592
614
|
return Infinity;
|
|
593
615
|
let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
|
|
594
616
|
let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
|
|
@@ -623,7 +645,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
623
645
|
return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
|
|
624
646
|
const mode = compiled.step === "whole" ? "dialogue" : "shrunk";
|
|
625
647
|
return { compaction: { summary: offer.summary, firstKeptEntryId: entries[boundary]?.id ?? "", tokensBefore: input.tokensBefore,
|
|
626
|
-
details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode
|
|
648
|
+
details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode,
|
|
649
|
+
...(workingSet.files.length || workingSet.rejected ? { workingSet: { carried: carried.map(file => file.path), offered: workingSet.files.length, rejected: workingSet.rejected } } : {}) } }, after, mode };
|
|
627
650
|
}
|
|
628
651
|
/** Numeric references use the original session index, then intersect with readable current-branch entries. */
|
|
629
652
|
export function tuckRecall(tuck, entries, branch, input, policy = {}) {
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/** Reads a file's current text, or undefined when it cannot be read. Never throws. */
|
|
3
|
+
export type FileReader = (absolutePath: string) => string | undefined;
|
|
4
|
+
/** Test and offline-replay seam: where carried files are checked. Undefined restores the disk. */
|
|
5
|
+
export declare const setWorkingFileReader: (next?: FileReader) => void;
|
|
6
|
+
/** Where Pi's read tool reads a recorded path: an "@" prefix dropped, "~" expanded, relative to the session's folder. */
|
|
7
|
+
export declare const readPath: (path: string, cwd: string) => string;
|
|
8
|
+
export interface WorkingFile {
|
|
9
|
+
path: string;
|
|
10
|
+
key: string;
|
|
11
|
+
reads: number;
|
|
12
|
+
sourceIndex: number;
|
|
13
|
+
position: number;
|
|
14
|
+
text: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* 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
|
|
18
|
+
* 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
|
|
19
|
+
* file verbatim, so equality proves both that the read was complete and that nothing (an edit, a write, a shell command, a generator) has
|
|
20
|
+
* changed the file since. `rejected` counts the files whose last read was whole but whose disk text differs or cannot be read.
|
|
21
|
+
* Only last reads inside the compacted prefix (before `boundary`) are offered: a later read is still in the native tail.
|
|
22
|
+
*/
|
|
23
|
+
export declare function workingSetCandidates(entries: readonly SessionEntry[], boundary: number, indices: ReadonlyMap<string, number>, cwd: string, resolvable: (entry: SessionEntry) => boolean): {
|
|
24
|
+
files: WorkingFile[];
|
|
25
|
+
rejected: number;
|
|
26
|
+
};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { isAbsolute, resolve } from "node:path";
|
|
4
|
+
import { pathKey } from "./path-key.js";
|
|
5
|
+
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
6
|
+
import { extractPath } from "./tuck/core/tool-args.js";
|
|
7
|
+
/** Pi's read tool returns at most 50KB of a file's text, so a larger file can never equal a recorded whole read. */
|
|
8
|
+
const MAX_FILE_BYTES = 64 * 1024;
|
|
9
|
+
const diskReader = path => {
|
|
10
|
+
try {
|
|
11
|
+
return statSync(path).size > MAX_FILE_BYTES ? undefined : readFileSync(path, "utf8");
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
let reader = diskReader;
|
|
18
|
+
/** Test and offline-replay seam: where carried files are checked. Undefined restores the disk. */
|
|
19
|
+
export const setWorkingFileReader = (next) => { reader = next ?? diskReader; };
|
|
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, cwd) => {
|
|
22
|
+
let name = path.startsWith("@") ? path.slice(1) : path;
|
|
23
|
+
if (name === "~")
|
|
24
|
+
name = homedir();
|
|
25
|
+
else if (name.startsWith("~/"))
|
|
26
|
+
name = homedir() + name.slice(1);
|
|
27
|
+
return isAbsolute(name) ? name : resolve(cwd, name);
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* 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
|
|
31
|
+
* 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
|
|
32
|
+
* file verbatim, so equality proves both that the read was complete and that nothing (an edit, a write, a shell command, a generator) has
|
|
33
|
+
* changed the file since. `rejected` counts the files whose last read was whole but whose disk text differs or cannot be read.
|
|
34
|
+
* Only last reads inside the compacted prefix (before `boundary`) are offered: a later read is still in the native tail.
|
|
35
|
+
*/
|
|
36
|
+
export function workingSetCandidates(entries, boundary, indices, cwd, resolvable) {
|
|
37
|
+
const calls = new Map(), last = new Map(), reads = new Map();
|
|
38
|
+
const results = new Map();
|
|
39
|
+
entries.forEach((entry, position) => {
|
|
40
|
+
if (entry.type !== "message")
|
|
41
|
+
return;
|
|
42
|
+
if (entry.message.role === "toolResult") {
|
|
43
|
+
results.set(entry.message.toolCallId, { entry, position });
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (entry.message.role !== "assistant")
|
|
47
|
+
return;
|
|
48
|
+
for (const block of entry.message.content) {
|
|
49
|
+
if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object")
|
|
50
|
+
continue;
|
|
51
|
+
const args = block.arguments, path = extractPath(args);
|
|
52
|
+
if (!path || /[\r\n]/u.test(path))
|
|
53
|
+
continue;
|
|
54
|
+
const key = pathKey(path, cwd);
|
|
55
|
+
calls.set(block.id, { path, key, whole: !("offset" in args) && !("limit" in args) });
|
|
56
|
+
last.set(key, block.id);
|
|
57
|
+
reads.set(key, (reads.get(key) ?? 0) + 1);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
const files = [];
|
|
61
|
+
let rejected = 0;
|
|
62
|
+
for (const [key, id] of last) {
|
|
63
|
+
const count = reads.get(key), call = calls.get(id), result = results.get(id);
|
|
64
|
+
if (count < 2 || !call.whole || !result || result.position >= boundary)
|
|
65
|
+
continue;
|
|
66
|
+
const { entry, position } = result;
|
|
67
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
|
|
68
|
+
continue;
|
|
69
|
+
const text = textOf(entry.message.content), sourceIndex = indices.get(entry.id);
|
|
70
|
+
if (!text.length || sourceIndex === undefined || !resolvable(entry))
|
|
71
|
+
continue;
|
|
72
|
+
if (reader(readPath(call.path, cwd)) !== text) {
|
|
73
|
+
rejected++;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
files.push({ path: call.path, key, reads: count, sourceIndex, position, text });
|
|
77
|
+
}
|
|
78
|
+
files.sort((a, b) => b.reads - a.reads || b.position - a.position);
|
|
79
|
+
return { files, rejected };
|
|
80
|
+
}
|
package/package.json
CHANGED
package/src/budget.ts
CHANGED
|
@@ -151,9 +151,10 @@ export function chooseCut<D extends object = {}>(input: CutInput<D> & { opportun
|
|
|
151
151
|
}
|
|
152
152
|
/** Rules 1 to 3: before any plan exists, does this request need a cut, and is a cut allowed to fail? */
|
|
153
153
|
export type Gate = { kind: "none" } | { kind: "defer" } | { kind: "plan"; opportunistic: boolean };
|
|
154
|
-
|
|
154
|
+
/** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. */
|
|
155
|
+
export function gateCut(input: { total: number; mandatory: number; room: number; band: number; trigger?: number; fits: CutInput["fits"] }): Gate {
|
|
155
156
|
const { total, mandatory, room, band, fits } = input;
|
|
156
|
-
if (fits(total, band)) return { kind: "none" };
|
|
157
|
+
if (fits(total, Math.max(band, input.trigger ?? band))) return { kind: "none" };
|
|
157
158
|
const inBand = fits(total, room);
|
|
158
159
|
if (!fits(mandatory, room)) return { kind: "defer" };
|
|
159
160
|
return { kind: "plan", opportunistic: inBand };
|
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "380741e47dc6a4378eeb32390a184eb747a610ac7b9614d97e86c1dbd3539cc8";
|
package/src/compaction.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
12
12
|
import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
|
|
13
13
|
import { projectedMessages } from "./omissions.js";
|
|
14
14
|
import { applyClips, clipBudgets, clipFor, type Clip } from "./clip.js";
|
|
15
|
-
import { DEFAULT_CUT_AT, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt,
|
|
15
|
+
import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt,
|
|
16
16
|
type AgentMessage, type Decision, type Messages, type Plan, type Target } from "./budget.js";
|
|
17
17
|
import { getCurrentSystemMessage, isContextOverflow, normalizeContext, type ImageContent, type ToolResultMessage } from "@earendil-works/pi-ai";
|
|
18
18
|
import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
|
|
@@ -22,6 +22,7 @@ import type { RecallPolicy } from "./recall.js";
|
|
|
22
22
|
import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
|
|
23
23
|
|
|
24
24
|
import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
|
|
25
|
+
import { thrashing } from "./thrash.js";
|
|
25
26
|
import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
|
|
26
27
|
import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
|
|
27
28
|
import { notify } from "./notify.js";
|
|
@@ -376,10 +377,24 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
376
377
|
const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
|
|
377
378
|
options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
|
|
378
379
|
const decisionBand = (ctx: ExtensionContext, room: number) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
|
|
380
|
+
// Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
|
|
381
|
+
// to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
|
|
382
|
+
// Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
|
|
383
|
+
// room: window - Pi's margin - the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
|
|
384
|
+
// sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
|
|
385
|
+
const triggerLine = (ctx: ExtensionContext, room: number): number | undefined => {
|
|
386
|
+
if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
|
|
387
|
+
const branch = ctx.sessionManager.getBranch();
|
|
388
|
+
if (!thrashing(branch)) return undefined;
|
|
389
|
+
const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
|
|
390
|
+
const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
|
|
391
|
+
const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
|
|
392
|
+
return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
393
|
+
};
|
|
379
394
|
/** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
|
|
380
395
|
const cutPoint = (ctx: ExtensionContext): number | undefined => {
|
|
381
396
|
if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
|
|
382
|
-
try { const band = decisionBand(ctx,
|
|
397
|
+
try { const { room } = limits(ctx), band = Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0); return band > 0 ? band : undefined; } catch { return undefined; }
|
|
383
398
|
};
|
|
384
399
|
const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
|
|
385
400
|
// The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
|
|
@@ -580,7 +595,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
580
595
|
// cancel (Pi reports it as aborted), never a failure.
|
|
581
596
|
let thresholdOpportunistic = false;
|
|
582
597
|
if (event.reason === "threshold") {
|
|
583
|
-
const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
598
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
584
599
|
if (gate.kind !== "plan") return { cancel: true };
|
|
585
600
|
thresholdOpportunistic = gate.opportunistic;
|
|
586
601
|
}
|
|
@@ -731,7 +746,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
731
746
|
throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
|
|
732
747
|
// A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
|
|
733
748
|
// help: leave it to the complete-context guard, which fails closed.
|
|
734
|
-
const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
749
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
735
750
|
if (gate.kind === "none") return;
|
|
736
751
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
737
752
|
const decide = (targetRoom: number, targetBand: number, opportunistic: boolean) => chooseCut({
|
|
@@ -868,7 +883,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
868
883
|
floorKept = undefined;
|
|
869
884
|
const before = measure(saved);
|
|
870
885
|
const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan" as const, opportunistic: false } :
|
|
871
|
-
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
886
|
+
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
872
887
|
if (gate.kind !== "plan") return gate;
|
|
873
888
|
return chooseCut({
|
|
874
889
|
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: options.cutAt === undefined,
|
package/src/kept-reads.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { TranscriptRecord } from "./tuck/core/transcript";
|
|
|
7
7
|
|
|
8
8
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
9
9
|
export function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
|
|
10
|
-
resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
|
|
10
|
+
resolvable: (entry: SessionEntry) => boolean, exclude: ReadonlySet<string> = new Set()): TranscriptRecord[] {
|
|
11
11
|
const cwd = entries.find((entry): entry is SessionHeader => entry.type === "session")?.cwd;
|
|
12
12
|
const reads = new Map<string, { path: string; key: string; order: number }>(), mutations = new Map<string, number>();
|
|
13
13
|
let allMutated = -1;
|
|
@@ -42,7 +42,7 @@ export function keptReadCandidates(entries: readonly (SessionEntry | SessionHead
|
|
|
42
42
|
const entry = entries[at]!;
|
|
43
43
|
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
|
|
44
44
|
const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
|
|
45
|
-
if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order) continue;
|
|
45
|
+
if (!read || seen.has(read.key) || exclude.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order) continue;
|
|
46
46
|
const text = textOf(entry.message.content);
|
|
47
47
|
if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
|
|
48
48
|
seen.add(read.key);
|
package/src/thrash.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
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 function thrashing(branch: readonly SessionEntry[]): boolean {
|
|
19
|
+
let cuts = 0, replies = 0, rereads = 0;
|
|
20
|
+
const pending = new Map<string, { key: string; cut: number; soon: boolean }>(), last = new Map<string, { cut: number; text: string }>();
|
|
21
|
+
for (const entry of branch) {
|
|
22
|
+
if (entry.type === "compaction") { cuts++; replies = 0; continue; }
|
|
23
|
+
if (entry.type !== "message") continue;
|
|
24
|
+
const message = entry.message;
|
|
25
|
+
if (message.role === "assistant") {
|
|
26
|
+
if (isDiscardedResponse(message)) continue;
|
|
27
|
+
replies++;
|
|
28
|
+
for (const block of message.content) {
|
|
29
|
+
if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;
|
|
30
|
+
const args = block.arguments as Record<string, unknown>, path = extractPath(args);
|
|
31
|
+
if (!path) continue;
|
|
32
|
+
pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: cuts, soon: cuts > 0 && replies <= THRASH_WINDOW_REPLIES });
|
|
33
|
+
}
|
|
34
|
+
} else if (message.role === "toolResult") {
|
|
35
|
+
const read = pending.get(message.toolCallId);
|
|
36
|
+
if (!read || message.isError || !isTextOnly(message.content)) continue;
|
|
37
|
+
pending.delete(message.toolCallId);
|
|
38
|
+
const text = textOf(message.content), earlier = last.get(read.key);
|
|
39
|
+
if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text) rereads++;
|
|
40
|
+
last.set(read.key, { cut: read.cut, text });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return cuts > 0 && rereads / cuts >= THRASH_BAR;
|
|
44
|
+
}
|
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;
|
|
@@ -233,8 +236,10 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
233
236
|
const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
|
|
234
237
|
const summaryTokens = (characters: number) => Math.ceil((characters + wrapperCharacters) / 4);
|
|
235
238
|
const lineCost = (records: readonly TranscriptRecord[]) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
|
|
236
|
-
|
|
237
|
-
|
|
239
|
+
// Working files carried raw in the closing section. Chosen once the boundary is known; until then the suffix is the plain one.
|
|
240
|
+
let carried: WorkingFile[] = [], suffix = DIALOGUE_SUFFIX;
|
|
241
|
+
const frameLength = (cost: number, count: number) => TRANSCRIPT_HEADER.length + suffix.length + cost + (count ? 0 : 1);
|
|
242
|
+
const render = (records: TranscriptRecord[]) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + suffix;
|
|
238
243
|
type Unit = { position: number; index: number; count: number };
|
|
239
244
|
const units: Record<"user" | "assistant" | "toolResult", Unit[]> = { user: [], assistant: [], toolResult: [] };
|
|
240
245
|
for (const row of rows) {
|
|
@@ -362,6 +367,21 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
362
367
|
const lists = listsAt(boundary);
|
|
363
368
|
const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
|
|
364
369
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
370
|
+
// The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
|
|
371
|
+
// WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
|
|
372
|
+
const resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
|
|
373
|
+
const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
|
|
374
|
+
if (workingSet.files.length) {
|
|
375
|
+
const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
|
|
376
|
+
let cost = WORKING_FILES_INSTRUCTION.length - CLOSING_INSTRUCTION.length + WORKING_FILES_HEADER.length;
|
|
377
|
+
for (const file of workingSet.files) {
|
|
378
|
+
const extra = workingFileBlock(file).length;
|
|
379
|
+
if (cost + extra > allowance) continue;
|
|
380
|
+
carried.push(file); cost += extra;
|
|
381
|
+
}
|
|
382
|
+
suffix = closingSuffix(carried);
|
|
383
|
+
}
|
|
384
|
+
const carriedKeys = new Set(carried.map(file => file.key));
|
|
365
385
|
let ledger: TranscriptRecord[] = lists.records;
|
|
366
386
|
let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
|
|
367
387
|
// List caps are existing ranking policy; only the carried target is a
|
|
@@ -381,7 +401,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
381
401
|
return row?.message.role === "user" && isTextOnly(row.message.content);
|
|
382
402
|
}));
|
|
383
403
|
const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
|
|
384
|
-
const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
|
|
404
|
+
const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
|
|
385
405
|
const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
|
|
386
406
|
sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position]!)),
|
|
387
407
|
ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
|
|
@@ -443,10 +463,10 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
443
463
|
let keptResultCost = 0;
|
|
444
464
|
const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
|
|
445
465
|
const counts = new Map<string, number>();
|
|
446
|
-
const prefix = [header, ...entries.slice(0, boundary)]
|
|
466
|
+
const prefix = [header, ...entries.slice(0, boundary)];
|
|
447
467
|
// Reads and searches share the lead rank, newest result first, and one
|
|
448
468
|
// allowance. Keep L2's independent four-item caps and whole-item skips.
|
|
449
|
-
const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
469
|
+
const candidates = [...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
450
470
|
.sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
|
|
451
471
|
for (const record of candidates) {
|
|
452
472
|
if ((counts.get(record.title!) ?? 0) === 4) continue;
|
|
@@ -458,10 +478,10 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
458
478
|
if (keptResults.length) offer = assemble(compiled.text, boundary);
|
|
459
479
|
const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
|
|
460
480
|
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 => {
|
|
481
|
+
const keptReadPaths = new Set([...carriedKeys, ...keptResults.filter(record => record.title === "Kept-read").map(record => {
|
|
462
482
|
const heading = record.text!.slice(0, record.text!.indexOf("\n"));
|
|
463
483
|
return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
|
|
464
|
-
}));
|
|
484
|
+
})]);
|
|
465
485
|
const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
|
|
466
486
|
const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
|
|
467
487
|
for (const item of shownFiles) item.definitions = observations.get(item.path);
|
|
@@ -533,12 +553,12 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
533
553
|
return [{ role, missing, ends, counts, cost: lineCost([record]) }];
|
|
534
554
|
});
|
|
535
555
|
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));
|
|
556
|
+
const keptResultIndices = new Set([...keptResults.map(record => record.sourceIndex), ...carried.map(file => file.sourceIndex)]);
|
|
537
557
|
const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
|
|
538
558
|
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 (
|
|
559
|
+
// Kept results and working files already spend this extension's
|
|
560
|
+
// price. They stay in the compacted prefix, so the native tail never repeats them.
|
|
561
|
+
if (keptResultIndices.size && at <= lastKeptResultPosition) return Infinity;
|
|
542
562
|
let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
|
|
543
563
|
let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
|
|
544
564
|
for (const range of ranges) {
|
|
@@ -565,7 +585,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
565
585
|
return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
|
|
566
586
|
const mode: DraftMode = compiled.step === "whole" ? "dialogue" : "shrunk";
|
|
567
587
|
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
|
|
588
|
+
details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode,
|
|
589
|
+
...(workingSet.files.length || workingSet.rejected ? { workingSet: { carried: carried.map(file => file.path), offered: workingSet.files.length, rejected: workingSet.rejected } } : {}) } }, after, mode };
|
|
569
590
|
}
|
|
570
591
|
|
|
571
592
|
/** 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
|
+
}
|