pi-tuck 1.8.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 +18 -0
- package/README.md +3 -1
- package/dist/src/budget.d.ts +3 -1
- package/dist/src/budget.js +3 -2
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.js +35 -9
- package/dist/src/diagnostics.d.ts +1 -1
- 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 +13 -0
- package/dist/src/thrash.js +16 -9
- package/dist/src/tuck.d.ts +2 -0
- package/dist/src/tuck.js +86 -2
- package/package.json +1 -1
- package/src/budget.ts +4 -3
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +31 -9
- package/src/lean.ts +47 -0
- package/src/status.ts +5 -1
- package/src/thrash.ts +16 -3
- package/src/tuck.ts +75 -2
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,24 @@
|
|
|
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.9.0]
|
|
7
|
+
|
|
8
|
+
### Changed
|
|
9
|
+
|
|
10
|
+
- At large windows pi-tuck now trims more often, to keep each request small: in a simulation of 25 sessions at a 272k window it made
|
|
11
|
+
about five times the trims of 1.8.0 (20.7 per session against 3.8) and cut simulated request cost by about 41% against native Pi. Each
|
|
12
|
+
trim drops older context, so a long session sees more summaries than before. At small windows (32k) behavior is essentially unchanged.
|
|
13
|
+
- Lean trigger: once a session has trimmed and made at least five requests since, the trim point can move earlier, to K + sqrt(2(K + R)·δ / 0.1),
|
|
14
|
+
where K is what the latest trim left, δ the mean growth per request and R the mean tokens of unchanged re-reads soon after each trim. It
|
|
15
|
+
balances the cost of a trim against the cost of carrying a larger context each request. It never moves the trim point later than
|
|
16
|
+
1.8.0's, it is off with an explicit `cutAt`, a host reserve or a protected prefix, and admission is unchanged.
|
|
17
|
+
- Prefix-stable summary: a trim's summary begins with the previous summary's dialogue records, byte for byte, and adds the messages
|
|
18
|
+
trimmed since after them; the omission counts, lists and kept results follow the dialogue. Consecutive summaries then share their
|
|
19
|
+
longest possible prefix, which a provider's prompt cache can serve. When the new messages do not fit whole and the carried part leaves
|
|
20
|
+
them less than half of the summary's room, the carried part keeps only its prompts (and drops its oldest ones past half the room), so a
|
|
21
|
+
summary still makes room for recent work. Sessions without an earlier pi-tuck summary are summarized as before.
|
|
22
|
+
- `/tuck` names the line that sets the trim point when it is not the default: the lean line or the thrash line (native Pi's).
|
|
23
|
+
|
|
6
24
|
## [1.8.0]
|
|
7
25
|
|
|
8
26
|
### Changed
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ 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.9.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.9.0` or `pi install git:github.com/galyavin/pi-tuck@v1.9.0`. To uninstall, run `pi remove` with the source you installed.
|
|
16
16
|
|
|
17
17
|
## Compaction and recall
|
|
18
18
|
|
|
@@ -20,6 +20,8 @@ A cut replaces older turns in the model's context with a summary while keeping t
|
|
|
20
20
|
|
|
21
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
22
|
|
|
23
|
+
Once a session has trimmed and grown for a few requests, pi-tuck can move its trim point earlier, to the line that balances the cost of a trim (the summary and the re-reads that follow) against the cost of carrying a larger context on every request. At large windows this means more, smaller trims and smaller requests; it never trims later than the default line. Each summary begins with the previous summary's dialogue, unchanged, and adds what was trimmed since, so consecutive summaries share a prefix a provider's prompt cache can serve. `/tuck` names the line in use: the default, the lean line, or native Pi's line.
|
|
24
|
+
|
|
23
25
|
When pi-tuck is active, `tuck_recall` becomes available after a cut on the current branch. Use a keyword query to locate a passage.
|
|
24
26
|
|
|
25
27
|
```json
|
package/dist/src/budget.d.ts
CHANGED
|
@@ -125,13 +125,15 @@ 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
|
+
/** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. `lean`, when below that line, moves
|
|
129
|
+
* it down: a cut becomes due there too, as an opportunistic cut inside the band. */
|
|
129
130
|
export declare function gateCut(input: {
|
|
130
131
|
total: number;
|
|
131
132
|
mandatory: number;
|
|
132
133
|
room: number;
|
|
133
134
|
band: number;
|
|
134
135
|
trigger?: number;
|
|
136
|
+
lean?: number;
|
|
135
137
|
fits: CutInput["fits"];
|
|
136
138
|
}): Gate;
|
|
137
139
|
/** Whether and how to cut at one boundary: the only decision procedure both triggers use. */
|
package/dist/src/budget.js
CHANGED
|
@@ -105,10 +105,11 @@ 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
|
+
/** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. `lean`, when below that line, moves
|
|
109
|
+
* it down: a cut becomes due there too, as an opportunistic cut inside the band. */
|
|
109
110
|
export function gateCut(input) {
|
|
110
111
|
const { total, mandatory, room, band, fits } = input;
|
|
111
|
-
if (fits(total, Math.max(band, input.trigger ?? band)))
|
|
112
|
+
if (fits(total, Math.min(Math.max(band, input.trigger ?? band), input.lean ?? Infinity)))
|
|
112
113
|
return { kind: "none" };
|
|
113
114
|
const inBand = fits(total, room);
|
|
114
115
|
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 = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
|
package/dist/src/build-id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
|
package/dist/src/compaction.js
CHANGED
|
@@ -20,6 +20,7 @@ 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
22
|
import { thrashing } from "./thrash.js";
|
|
23
|
+
import { leanLine } from "./lean.js";
|
|
23
24
|
import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
|
|
24
25
|
import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
|
|
25
26
|
import { notify } from "./notify.js";
|
|
@@ -214,7 +215,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
214
215
|
pi.on("session_compact", (_event, ctx) => observe(ctx));
|
|
215
216
|
pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
|
|
216
217
|
pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
|
|
217
|
-
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx) }), "info");
|
|
218
|
+
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx), trigger: activeTrigger(ctx) }), "info");
|
|
218
219
|
} });
|
|
219
220
|
// Pi's native start/settled events bracket the run and its post-turn cuts.
|
|
220
221
|
let run;
|
|
@@ -420,18 +421,41 @@ export async function installCompaction(pi, options = {}) {
|
|
|
420
421
|
const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
|
|
421
422
|
return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
422
423
|
};
|
|
424
|
+
// Lean line (lean.ts): once the branch has a cut and a measured growth rate, a cut also becomes due at K + sqrt(2(K + R)·δ / h), the
|
|
425
|
+
// economic order quantity of the context, when that is below the line above. Never later than it, and admission is unchanged: a cut it
|
|
426
|
+
// asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off.
|
|
427
|
+
const leanLimit = (ctx) => {
|
|
428
|
+
if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
|
|
429
|
+
return undefined;
|
|
430
|
+
return leanLine(ctx.sessionManager.getBranch());
|
|
431
|
+
};
|
|
432
|
+
// A cut the lean line makes due inside the band is sized by that line, not by the tenth-of-the-room rule for opportunistic cuts.
|
|
433
|
+
const usefulOnlyAt = (total, band, lean, ctx) => options.cutAt === undefined && !(lean !== undefined && fits(total, band, ctx));
|
|
423
434
|
/** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
|
|
424
435
|
const cutPoint = (ctx) => {
|
|
425
436
|
if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
|
|
426
437
|
return undefined;
|
|
427
438
|
try {
|
|
428
|
-
const { room } = limits(ctx), band = Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0);
|
|
439
|
+
const { room } = limits(ctx), band = Math.min(Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0), leanLimit(ctx) ?? Infinity);
|
|
429
440
|
return band > 0 ? band : undefined;
|
|
430
441
|
}
|
|
431
442
|
catch {
|
|
432
443
|
return undefined;
|
|
433
444
|
}
|
|
434
445
|
};
|
|
446
|
+
/** Which line sets the cut point now, for `/tuck`: the lean line, the thrash line, or neither (the band). Reads only. */
|
|
447
|
+
const activeTrigger = (ctx) => {
|
|
448
|
+
if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
|
|
449
|
+
return undefined;
|
|
450
|
+
try {
|
|
451
|
+
const { room } = limits(ctx), band = decisionBand(ctx, room), thrash = triggerLine(ctx, room), lean = leanLimit(ctx);
|
|
452
|
+
const line = Math.max(band, thrash ?? 0);
|
|
453
|
+
return lean !== undefined && lean < line ? "lean" : thrash !== undefined && thrash > band ? "thrash" : undefined;
|
|
454
|
+
}
|
|
455
|
+
catch {
|
|
456
|
+
return undefined;
|
|
457
|
+
}
|
|
458
|
+
};
|
|
435
459
|
const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
|
|
436
460
|
// The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
|
|
437
461
|
const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
|
|
@@ -664,15 +688,16 @@ export async function installCompaction(pi, options = {}) {
|
|
|
664
688
|
// trigger would: nothing below the band, an opportunistic cut inside it, a due cut at or above the room. A refusal is a plain
|
|
665
689
|
// cancel (Pi reports it as aborted), never a failure.
|
|
666
690
|
let thresholdOpportunistic = false;
|
|
691
|
+
const lean = leanLimit(ctx);
|
|
667
692
|
if (event.reason === "threshold") {
|
|
668
|
-
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
693
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
669
694
|
if (gate.kind !== "plan")
|
|
670
695
|
return { cancel: true };
|
|
671
696
|
thresholdOpportunistic = gate.opportunistic;
|
|
672
697
|
}
|
|
673
698
|
// Pi checks old history before appending a new idle prompt. During an active run/manual cut the latest admitted input stays protected.
|
|
674
699
|
const decide = (targetRoom = room, targetBand = band) => chooseCut({
|
|
675
|
-
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
700
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
|
|
676
701
|
opportunistic: thresholdOpportunistic,
|
|
677
702
|
unreduced: "Compaction did not reduce context within the estimated request budget",
|
|
678
703
|
plan: (target) => {
|
|
@@ -838,12 +863,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
838
863
|
throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
|
|
839
864
|
// A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
|
|
840
865
|
// help: leave it to the complete-context guard, which fails closed.
|
|
841
|
-
const
|
|
866
|
+
const lean = leanLimit(ctx);
|
|
867
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
842
868
|
if (gate.kind === "none")
|
|
843
869
|
return;
|
|
844
870
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
845
871
|
const decide = (targetRoom, targetBand, opportunistic) => chooseCut({
|
|
846
|
-
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
872
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx), opportunistic,
|
|
847
873
|
unreduced: "Incoming prompt compaction did not reduce context within the estimated request budget",
|
|
848
874
|
plan: (target) => {
|
|
849
875
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
@@ -991,13 +1017,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
991
1017
|
const decide = (targetRoom = room, targetBand = band, required = false) => {
|
|
992
1018
|
previews = [];
|
|
993
1019
|
floorKept = undefined;
|
|
994
|
-
const before = measure(saved);
|
|
1020
|
+
const before = measure(saved), lean = targetBand === band ? leanLimit(ctx) : undefined;
|
|
995
1021
|
const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan", opportunistic: false } :
|
|
996
|
-
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
1022
|
+
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
997
1023
|
if (gate.kind !== "plan")
|
|
998
1024
|
return gate;
|
|
999
1025
|
return chooseCut({
|
|
1000
|
-
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
1026
|
+
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
|
|
1001
1027
|
unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
|
|
1002
1028
|
plan: (target) => {
|
|
1003
1029
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
@@ -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 = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
|
|
4
4
|
export interface Receipt {
|
|
5
5
|
id: string;
|
|
6
6
|
build: string;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/** Holding cost of a context token per request, as a share of its fresh price: a cached re-send costs about a tenth. */
|
|
3
|
+
export declare const LEAN_HOLDING = 0.1;
|
|
4
|
+
/** Growth samples (consecutive replies with no cut between) needed before the growth rate counts. */
|
|
5
|
+
export declare const LEAN_MIN_SAMPLES = 4;
|
|
6
|
+
export interface LeanInputs {
|
|
7
|
+
kept: number;
|
|
8
|
+
growth: number;
|
|
9
|
+
rereads: number;
|
|
10
|
+
samples: number;
|
|
11
|
+
cuts: number;
|
|
12
|
+
}
|
|
13
|
+
/** The quantities the lean line is built from, read from the branch's recorded usage only. `kept` (K): the prompt of the first reply after
|
|
14
|
+
* the latest cut, what that cut left (system, summary, kept turns, carried files). `growth` (δ): the mean rise of the prompt between
|
|
15
|
+
* consecutive replies with no cut between. `rereads` (R): the mean tokens per cut of unchanged files re-read soon after it (thrash.ts). */
|
|
16
|
+
export declare function leanInputs(branch: readonly SessionEntry[]): LeanInputs;
|
|
17
|
+
/**
|
|
18
|
+
* The lean cut line: the economic order quantity of a context. Each cut costs a fresh re-send of what it keeps (K) and the re-reads it causes
|
|
19
|
+
* (R); each token held costs LEAN_HOLDING per request; the context grows by δ per request. The cheapest cycle cuts every
|
|
20
|
+
* n* = sqrt(2(K + R) / (h·δ)) requests, so the line is K + δ·n* = K + sqrt(2(K + R)·δ / h). Rising re-reads raise R and so the line.
|
|
21
|
+
* Undefined until the branch has a cut with a measured reply after it and LEAN_MIN_SAMPLES growth samples with a positive mean.
|
|
22
|
+
*/
|
|
23
|
+
export declare function leanLine(branch: readonly SessionEntry[]): number | undefined;
|
package/dist/src/lean.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { isDiscardedResponse } from "./protocol.js";
|
|
2
|
+
import { rereadsAfterCuts } from "./thrash.js";
|
|
3
|
+
/** Holding cost of a context token per request, as a share of its fresh price: a cached re-send costs about a tenth. */
|
|
4
|
+
export const LEAN_HOLDING = 0.1;
|
|
5
|
+
/** Growth samples (consecutive replies with no cut between) needed before the growth rate counts. */
|
|
6
|
+
export const LEAN_MIN_SAMPLES = 4;
|
|
7
|
+
const promptTokens = (entry) => {
|
|
8
|
+
if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message))
|
|
9
|
+
return undefined;
|
|
10
|
+
const message = entry.message;
|
|
11
|
+
if (message.stopReason === "error" || message.stopReason === "aborted")
|
|
12
|
+
return undefined;
|
|
13
|
+
const u = message.usage;
|
|
14
|
+
const total = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0);
|
|
15
|
+
return Number.isFinite(total) && total > 0 ? total : undefined;
|
|
16
|
+
};
|
|
17
|
+
/** The quantities the lean line is built from, read from the branch's recorded usage only. `kept` (K): the prompt of the first reply after
|
|
18
|
+
* the latest cut, what that cut left (system, summary, kept turns, carried files). `growth` (δ): the mean rise of the prompt between
|
|
19
|
+
* consecutive replies with no cut between. `rereads` (R): the mean tokens per cut of unchanged files re-read soon after it (thrash.ts). */
|
|
20
|
+
export function leanInputs(branch) {
|
|
21
|
+
let kept = 0, previous, afterCut = false, sum = 0, samples = 0;
|
|
22
|
+
for (const entry of branch) {
|
|
23
|
+
if (entry.type === "compaction") {
|
|
24
|
+
previous = undefined;
|
|
25
|
+
afterCut = true;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const prompt = promptTokens(entry);
|
|
29
|
+
if (prompt === undefined)
|
|
30
|
+
continue;
|
|
31
|
+
if (afterCut) {
|
|
32
|
+
kept = prompt;
|
|
33
|
+
afterCut = false;
|
|
34
|
+
}
|
|
35
|
+
if (previous !== undefined) {
|
|
36
|
+
sum += prompt - previous;
|
|
37
|
+
samples++;
|
|
38
|
+
}
|
|
39
|
+
previous = prompt;
|
|
40
|
+
}
|
|
41
|
+
const { cuts, tokens } = rereadsAfterCuts(branch);
|
|
42
|
+
return { kept, growth: samples ? sum / samples : 0, rereads: cuts ? tokens / cuts : 0, samples, cuts };
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The lean cut line: the economic order quantity of a context. Each cut costs a fresh re-send of what it keeps (K) and the re-reads it causes
|
|
46
|
+
* (R); each token held costs LEAN_HOLDING per request; the context grows by δ per request. The cheapest cycle cuts every
|
|
47
|
+
* n* = sqrt(2(K + R) / (h·δ)) requests, so the line is K + δ·n* = K + sqrt(2(K + R)·δ / h). Rising re-reads raise R and so the line.
|
|
48
|
+
* Undefined until the branch has a cut with a measured reply after it and LEAN_MIN_SAMPLES growth samples with a positive mean.
|
|
49
|
+
*/
|
|
50
|
+
export function leanLine(branch) {
|
|
51
|
+
const { kept, growth, rereads, samples, cuts } = leanInputs(branch);
|
|
52
|
+
if (!cuts || kept <= 0 || samples < LEAN_MIN_SAMPLES || !(growth > 0))
|
|
53
|
+
return undefined;
|
|
54
|
+
return Math.ceil(kept + Math.sqrt(2 * (kept + rereads) * growth / LEAN_HOLDING));
|
|
55
|
+
}
|
package/dist/src/status.d.ts
CHANGED
|
@@ -23,4 +23,6 @@ export declare function statusText(input: {
|
|
|
23
23
|
cacheSensitive?: boolean;
|
|
24
24
|
/** The trim point in tokens for the current model, the footer's full bar; absent when it cannot be computed. */
|
|
25
25
|
cutPoint?: number;
|
|
26
|
+
/** The line that sets the trim point now, when it is not the default band: the lean line or the thrash line. */
|
|
27
|
+
trigger?: "lean" | "thrash";
|
|
26
28
|
}): string;
|
package/dist/src/status.js
CHANGED
|
@@ -38,7 +38,9 @@ export function statusText(input) {
|
|
|
38
38
|
...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
|
|
39
39
|
...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
|
|
40
40
|
input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
|
|
41
|
-
? `Trim point:
|
|
41
|
+
? input.trigger === "lean" ? `Trim point: this session's lean line, set by its growth per request and the size of its last trim${now}.`
|
|
42
|
+
: input.trigger === "thrash" ? `Trim point: native Pi's line, because this session's trims keep dropping files it then re-reads${now}.`
|
|
43
|
+
: `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
|
|
42
44
|
"Search: by keyword.",
|
|
43
45
|
...checkLines,
|
|
44
46
|
].join("\n");
|
package/dist/src/thrash.d.ts
CHANGED
|
@@ -3,6 +3,19 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
|
3
3
|
export declare const THRASH_WINDOW_REPLIES = 3;
|
|
4
4
|
/** Re-reads per cut at which a session is thrashing. */
|
|
5
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 interface Rereads {
|
|
13
|
+
cuts: number;
|
|
14
|
+
rereads: number;
|
|
15
|
+
tokens: number;
|
|
16
|
+
}
|
|
17
|
+
/** 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. */
|
|
18
|
+
export declare function rereadsAfterCuts(branch: readonly SessionEntry[]): Rereads;
|
|
6
19
|
/**
|
|
7
20
|
* 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
21
|
* 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
|
package/dist/src/thrash.js
CHANGED
|
@@ -6,14 +6,9 @@ import { extractPath } from "./tuck/core/tool-args.js";
|
|
|
6
6
|
export const THRASH_WINDOW_REPLIES = 3;
|
|
7
7
|
/** Re-reads per cut at which a session is thrashing. */
|
|
8
8
|
export const THRASH_BAR = 0.5;
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
|
|
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;
|
|
9
|
+
/** 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. */
|
|
10
|
+
export function rereadsAfterCuts(branch) {
|
|
11
|
+
let cuts = 0, replies = 0, rereads = 0, chars = 0;
|
|
17
12
|
const pending = new Map(), last = new Map();
|
|
18
13
|
for (const entry of branch) {
|
|
19
14
|
if (entry.type === "compaction") {
|
|
@@ -43,10 +38,22 @@ export function thrashing(branch) {
|
|
|
43
38
|
continue;
|
|
44
39
|
pending.delete(message.toolCallId);
|
|
45
40
|
const text = textOf(message.content), earlier = last.get(read.key);
|
|
46
|
-
if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text)
|
|
41
|
+
if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text) {
|
|
47
42
|
rereads++;
|
|
43
|
+
chars += text.length;
|
|
44
|
+
}
|
|
48
45
|
last.set(read.key, { cut: read.cut, text });
|
|
49
46
|
}
|
|
50
47
|
}
|
|
48
|
+
return { cuts, rereads, tokens: Math.ceil(chars / 4) };
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* 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
|
|
52
|
+
* 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
|
|
53
|
+
* 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
|
|
54
|
+
* such re-read, it never does. Deterministic: it reads only the recorded branch.
|
|
55
|
+
*/
|
|
56
|
+
export function thrashing(branch) {
|
|
57
|
+
const { cuts, rereads } = rereadsAfterCuts(branch);
|
|
51
58
|
return cuts > 0 && rereads / cuts >= THRASH_BAR;
|
|
52
59
|
}
|
package/dist/src/tuck.d.ts
CHANGED
|
@@ -66,6 +66,8 @@ export interface Tuck {
|
|
|
66
66
|
}[], query: string): number[];
|
|
67
67
|
}
|
|
68
68
|
import { compileDialogue } from "./tuck/core/summarize.js";
|
|
69
|
+
/** The share of the brief below which the carried part of a prefix-stable summary keeps only its user and custom records. */
|
|
70
|
+
export declare const STABLE_CONSOLIDATE_AT = 0.5;
|
|
69
71
|
export declare const tuck: Tuck;
|
|
70
72
|
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
71
73
|
* `_operatorManual` retains the exported positional slot for existing callers. */
|
package/dist/src/tuck.js
CHANGED
|
@@ -24,6 +24,8 @@ import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
|
|
|
24
24
|
import { compileDialogue } from "./tuck/core/summarize.js";
|
|
25
25
|
import { prepareKeywordQuery } from "./tuck/core/keyword-query.js";
|
|
26
26
|
import { rankRecallRows } from "./tuck/core/search-entries.js";
|
|
27
|
+
/** The share of the brief below which the carried part of a prefix-stable summary keeps only its user and custom records. */
|
|
28
|
+
export const STABLE_CONSOLIDATE_AT = 0.5;
|
|
27
29
|
export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
|
|
28
30
|
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
29
31
|
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
@@ -470,7 +472,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
470
472
|
else
|
|
471
473
|
records[pos] = omissionRecord("user", missing.length, [missing[0].index, missing.at(-1).index], false);
|
|
472
474
|
}
|
|
473
|
-
else if (at !== compiledBoundary) {
|
|
475
|
+
else if (at !== compiledBoundary || stable) {
|
|
474
476
|
const role = record.role;
|
|
475
477
|
if (role === "assistant" || role === "toolResult") {
|
|
476
478
|
const missing = units[role].filter(unit => unit.position < at && unit.index >= record.sourceRange.start && unit.index <= record.sourceRange.end &&
|
|
@@ -488,7 +490,89 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
488
490
|
const summary = render([...records, ...ledger, ...keptResults, ...thoughtOpenings]);
|
|
489
491
|
return { summary, records: [...records, ...thoughtOpenings] };
|
|
490
492
|
};
|
|
491
|
-
|
|
493
|
+
// Prefix-stable summary: the previous pi-tuck summary's dialogue records are carried verbatim as the oldest part, and only the sources
|
|
494
|
+
// since that cut are compiled after them; counters, lists and kept results follow the dialogue. Consecutive summaries then share a
|
|
495
|
+
// 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
|
|
496
|
+
// user and custom records (a fixed point, so the part already kept that way stays the prefix), and past half the brief its oldest
|
|
497
|
+
// sources go, down to a quarter. With no previous pi-tuck summary, a floor summary, or nothing that fits, the whole history is compiled.
|
|
498
|
+
const stableCompile = () => {
|
|
499
|
+
const whole = () => ({ compiled: tuck.compileDialogue(compileInput), carried: false });
|
|
500
|
+
const previousAt = entries.findLastIndex(entry => entry.type === "compaction");
|
|
501
|
+
const previous = entries[previousAt];
|
|
502
|
+
const details = previous?.type === "compaction" ? previous.details : undefined;
|
|
503
|
+
if (previous?.type !== "compaction" || details?.compactor !== "pi-tuck" || details.deepest)
|
|
504
|
+
return whole();
|
|
505
|
+
const split = splitSummary(previous.summary);
|
|
506
|
+
if (!split || split.version !== 2)
|
|
507
|
+
return whole();
|
|
508
|
+
const from = Math.min(previous.firstKeptEntryId ? positions.get(previous.firstKeptEntryId) ?? previousAt : previousAt, compiledBoundary);
|
|
509
|
+
const indexAt = new Map(rows.map(row => [row.index, row.position]));
|
|
510
|
+
const positionOf = (record) => record.sourceEntryId !== undefined ? positions.get(record.sourceEntryId)
|
|
511
|
+
: record.sourceIndex !== undefined ? indexAt.get(record.sourceIndex) : undefined;
|
|
512
|
+
const dialogue = (record) => record.sourceIndex !== undefined || record.sourceEntryId !== undefined
|
|
513
|
+
? (record.kind === "excerpt" || record.kind === "omission") && (record.role === "user" || record.role === "assistant" || record.role === "custom") : false;
|
|
514
|
+
let old;
|
|
515
|
+
try {
|
|
516
|
+
old = parseRecords(split.body, 2).filter(record => dialogue(record) && (positionOf(record) ?? Infinity) < from);
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
return whole();
|
|
520
|
+
}
|
|
521
|
+
// One counter per role over the whole compacted history: what the records leave out (assemble counts it again once the protected
|
|
522
|
+
// prompts are merged). Without `records`, every unit counts: a counter that costs at least as much as any real one.
|
|
523
|
+
const counters = (records) => ["user", "assistant", "toolResult"].flatMap(role => {
|
|
524
|
+
const shown = new Map();
|
|
525
|
+
for (const record of records ?? [])
|
|
526
|
+
if (record.kind === "excerpt" && record.role === role && !record.span && record.sourceIndex !== undefined &&
|
|
527
|
+
(role !== "user" || record.text === userTexts.get(record.sourceIndex)))
|
|
528
|
+
shown.set(record.sourceIndex, (shown.get(record.sourceIndex) ?? 0) + 1);
|
|
529
|
+
const missing = units[role].flatMap(unit => {
|
|
530
|
+
const count = unit.position < compiledBoundary ? unit.count - Math.min(unit.count, shown.get(unit.index) ?? 0) : 0;
|
|
531
|
+
return count ? [{ index: unit.index, count }] : [];
|
|
532
|
+
});
|
|
533
|
+
return missing.length ? [omissionRecord(role, missing.reduce((n, unit) => n + unit.count, 0), [missing[0].index, missing.at(-1).index], false)] : [];
|
|
534
|
+
});
|
|
535
|
+
// A carried prompt that the protected rows quote too is paid for once, in their fixed cost (assemble keeps one of the two).
|
|
536
|
+
const protectedCost = new Map(protectedView.kept.map(record => [sourceKey(record), lineCost([record])]));
|
|
537
|
+
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);
|
|
538
|
+
const fresh = sourceRows.filter(row => row.position >= from);
|
|
539
|
+
const compileFresh = (reserve) => fresh.length ? tuck.compileDialogue({ messages: fresh.map(row => row.message), sourceIndices: fresh.map(row => row.index),
|
|
540
|
+
sourceEntryIds: fresh.map(row => row.id), sourceTimes: fresh.map(row => resolveSourceTime(entries[row.position])),
|
|
541
|
+
ranking: { maxBriefChars: maxBriefChars - oldCost() - reserve, mandatorySourceIndices: mandatory } }) : { text: "", step: "whole", size: 0 };
|
|
542
|
+
// First as if every new source fits whole: then only the counters the carried part and the tool history need are reserved.
|
|
543
|
+
const freshRecords = (compiled) => {
|
|
544
|
+
const body = compiled.text ? splitSummary(compiled.text) : undefined;
|
|
545
|
+
return body ? parseRecords(body.body, body.version).filter(record => record.kind !== "omission" || record.sourceIndex !== undefined) : undefined;
|
|
546
|
+
};
|
|
547
|
+
const wholeFresh = fresh.flatMap((row) => row.message.role === "user" ? [{ kind: "excerpt", role: "user", sourceIndex: row.index, text: userTexts.get(row.index) ?? "" }]
|
|
548
|
+
: row.message.role === "assistant" ? row.message.content.flatMap(part => part.type === "text" && part.text.trim() ? [{ kind: "excerpt", role: "assistant", sourceIndex: row.index, text: "" }] : []) : []);
|
|
549
|
+
let compiled = compileFresh(lineCost(counters([...old, ...wholeFresh]))), consolidated = false;
|
|
550
|
+
if (compiled.step !== "whole") {
|
|
551
|
+
if (maxBriefChars - oldCost() - lineCost(counters()) < STABLE_CONSOLIDATE_AT * maxBriefChars) {
|
|
552
|
+
consolidated = true;
|
|
553
|
+
old = old.filter(record => record.role === "user" || record.role === "custom");
|
|
554
|
+
if (oldCost() > STABLE_CONSOLIDATE_AT * maxBriefChars) {
|
|
555
|
+
let cost = oldCost(), first = 0;
|
|
556
|
+
while (first < old.length && cost > maxBriefChars / 4) {
|
|
557
|
+
const at = positionOf(old[first]);
|
|
558
|
+
while (first < old.length && positionOf(old[first]) === at)
|
|
559
|
+
cost -= lineCost([old[first++]]);
|
|
560
|
+
}
|
|
561
|
+
old = old.slice(first);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
compiled = compileFresh(lineCost(counters()));
|
|
565
|
+
}
|
|
566
|
+
const added = fresh.length ? freshRecords(compiled) : [];
|
|
567
|
+
if (!added)
|
|
568
|
+
return whole();
|
|
569
|
+
const text = serializeTranscript([...old, ...added, ...counters([...old, ...added])]) + DIALOGUE_SUFFIX;
|
|
570
|
+
if (text.length - lineCost(old) + oldCost() > maxBriefChars)
|
|
571
|
+
return whole();
|
|
572
|
+
const step = !consolidated && compiled.step === "whole" && details.mode === "dialogue" ? "whole" : "ranked";
|
|
573
|
+
return { compiled: { text, step, size: text.length }, carried: true };
|
|
574
|
+
};
|
|
575
|
+
const { compiled, carried: stable } = stableCompile();
|
|
492
576
|
let offer = assemble(compiled.text);
|
|
493
577
|
// After the complete dialogue fill, observations spend the remaining
|
|
494
578
|
// room before the native tail's older end. The pinned tail is untouched.
|
package/package.json
CHANGED
package/src/budget.ts
CHANGED
|
@@ -151,10 +151,11 @@ 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
|
-
/** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band.
|
|
155
|
-
|
|
154
|
+
/** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. `lean`, when below that line, moves
|
|
155
|
+
* it down: a cut becomes due there too, as an opportunistic cut inside the band. */
|
|
156
|
+
export function gateCut(input: { total: number; mandatory: number; room: number; band: number; trigger?: number; lean?: number; fits: CutInput["fits"] }): Gate {
|
|
156
157
|
const { total, mandatory, room, band, fits } = input;
|
|
157
|
-
if (fits(total, Math.max(band, input.trigger ?? band))) return { kind: "none" };
|
|
158
|
+
if (fits(total, Math.min(Math.max(band, input.trigger ?? band), input.lean ?? Infinity))) return { kind: "none" };
|
|
158
159
|
const inBand = fits(total, room);
|
|
159
160
|
if (!fits(mandatory, room)) return { kind: "defer" };
|
|
160
161
|
return { kind: "plan", opportunistic: inBand };
|
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
|
package/src/compaction.ts
CHANGED
|
@@ -23,6 +23,7 @@ import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY
|
|
|
23
23
|
|
|
24
24
|
import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
|
|
25
25
|
import { thrashing } from "./thrash.js";
|
|
26
|
+
import { leanLine } from "./lean.js";
|
|
26
27
|
import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
|
|
27
28
|
import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
|
|
28
29
|
import { notify } from "./notify.js";
|
|
@@ -220,7 +221,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
220
221
|
pi.on("session_compact", (_event, ctx) => observe(ctx));
|
|
221
222
|
pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
|
|
222
223
|
pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
|
|
223
|
-
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx) }), "info");
|
|
224
|
+
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx), trigger: activeTrigger(ctx) }), "info");
|
|
224
225
|
} });
|
|
225
226
|
// Pi's native start/settled events bracket the run and its post-turn cuts.
|
|
226
227
|
let run: Run | undefined;
|
|
@@ -391,10 +392,29 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
391
392
|
const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
|
|
392
393
|
return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
393
394
|
};
|
|
395
|
+
// Lean line (lean.ts): once the branch has a cut and a measured growth rate, a cut also becomes due at K + sqrt(2(K + R)·δ / h), the
|
|
396
|
+
// economic order quantity of the context, when that is below the line above. Never later than it, and admission is unchanged: a cut it
|
|
397
|
+
// asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off.
|
|
398
|
+
const leanLimit = (ctx: ExtensionContext): number | undefined => {
|
|
399
|
+
if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
|
|
400
|
+
return leanLine(ctx.sessionManager.getBranch());
|
|
401
|
+
};
|
|
402
|
+
// A cut the lean line makes due inside the band is sized by that line, not by the tenth-of-the-room rule for opportunistic cuts.
|
|
403
|
+
const usefulOnlyAt = (total: number, band: number, lean: number | undefined, ctx: ExtensionContext) =>
|
|
404
|
+
options.cutAt === undefined && !(lean !== undefined && fits(total, band, ctx));
|
|
394
405
|
/** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
|
|
395
406
|
const cutPoint = (ctx: ExtensionContext): number | undefined => {
|
|
396
407
|
if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
|
|
397
|
-
try { const { room } = limits(ctx), band = Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0); return band > 0 ? band : undefined; } catch { return undefined; }
|
|
408
|
+
try { const { room } = limits(ctx), band = Math.min(Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0), leanLimit(ctx) ?? Infinity); return band > 0 ? band : undefined; } catch { return undefined; }
|
|
409
|
+
};
|
|
410
|
+
/** Which line sets the cut point now, for `/tuck`: the lean line, the thrash line, or neither (the band). Reads only. */
|
|
411
|
+
const activeTrigger = (ctx: ExtensionContext): "lean" | "thrash" | undefined => {
|
|
412
|
+
if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
|
|
413
|
+
try {
|
|
414
|
+
const { room } = limits(ctx), band = decisionBand(ctx, room), thrash = triggerLine(ctx, room), lean = leanLimit(ctx);
|
|
415
|
+
const line = Math.max(band, thrash ?? 0);
|
|
416
|
+
return lean !== undefined && lean < line ? "lean" : thrash !== undefined && thrash > band ? "thrash" : undefined;
|
|
417
|
+
} catch { return undefined; }
|
|
398
418
|
};
|
|
399
419
|
const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
|
|
400
420
|
// The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
|
|
@@ -594,14 +614,15 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
594
614
|
// trigger would: nothing below the band, an opportunistic cut inside it, a due cut at or above the room. A refusal is a plain
|
|
595
615
|
// cancel (Pi reports it as aborted), never a failure.
|
|
596
616
|
let thresholdOpportunistic = false;
|
|
617
|
+
const lean = leanLimit(ctx);
|
|
597
618
|
if (event.reason === "threshold") {
|
|
598
|
-
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
619
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
599
620
|
if (gate.kind !== "plan") return { cancel: true };
|
|
600
621
|
thresholdOpportunistic = gate.opportunistic;
|
|
601
622
|
}
|
|
602
623
|
// Pi checks old history before appending a new idle prompt. During an active run/manual cut the latest admitted input stays protected.
|
|
603
624
|
const decide = (targetRoom = room, targetBand = band) => chooseCut({
|
|
604
|
-
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
625
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
|
|
605
626
|
opportunistic: thresholdOpportunistic,
|
|
606
627
|
unreduced: "Compaction did not reduce context within the estimated request budget",
|
|
607
628
|
plan: (target): Plan<CutPlan> => {
|
|
@@ -746,11 +767,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
746
767
|
throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
|
|
747
768
|
// A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
|
|
748
769
|
// help: leave it to the complete-context guard, which fails closed.
|
|
749
|
-
const
|
|
770
|
+
const lean = leanLimit(ctx);
|
|
771
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
750
772
|
if (gate.kind === "none") return;
|
|
751
773
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
752
774
|
const decide = (targetRoom: number, targetBand: number, opportunistic: boolean) => chooseCut({
|
|
753
|
-
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
775
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx), opportunistic,
|
|
754
776
|
unreduced: "Incoming prompt compaction did not reduce context within the estimated request budget",
|
|
755
777
|
plan: (target): Plan<CutPlan> => {
|
|
756
778
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
@@ -881,12 +903,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
881
903
|
const decide = (targetRoom = room, targetBand = band, required = false) => {
|
|
882
904
|
previews = [];
|
|
883
905
|
floorKept = undefined;
|
|
884
|
-
const before = measure(saved);
|
|
906
|
+
const before = measure(saved), lean = targetBand === band ? leanLimit(ctx) : undefined;
|
|
885
907
|
const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan" as const, opportunistic: false } :
|
|
886
|
-
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
908
|
+
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
887
909
|
if (gate.kind !== "plan") return gate;
|
|
888
910
|
return chooseCut({
|
|
889
|
-
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
911
|
+
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
|
|
890
912
|
unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
|
|
891
913
|
plan: (target): Plan<CutPlan> => {
|
|
892
914
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
package/src/lean.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { isDiscardedResponse } from "./protocol";
|
|
3
|
+
import { rereadsAfterCuts } from "./thrash";
|
|
4
|
+
|
|
5
|
+
/** Holding cost of a context token per request, as a share of its fresh price: a cached re-send costs about a tenth. */
|
|
6
|
+
export const LEAN_HOLDING = 0.1;
|
|
7
|
+
/** Growth samples (consecutive replies with no cut between) needed before the growth rate counts. */
|
|
8
|
+
export const LEAN_MIN_SAMPLES = 4;
|
|
9
|
+
|
|
10
|
+
const promptTokens = (entry: SessionEntry): number | undefined => {
|
|
11
|
+
if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message)) return undefined;
|
|
12
|
+
const message = entry.message;
|
|
13
|
+
if (message.stopReason === "error" || message.stopReason === "aborted") return undefined;
|
|
14
|
+
const u = message.usage;
|
|
15
|
+
const total = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0);
|
|
16
|
+
return Number.isFinite(total) && total > 0 ? total : undefined;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export interface LeanInputs { kept: number; growth: number; rereads: number; samples: number; cuts: number }
|
|
20
|
+
/** The quantities the lean line is built from, read from the branch's recorded usage only. `kept` (K): the prompt of the first reply after
|
|
21
|
+
* the latest cut, what that cut left (system, summary, kept turns, carried files). `growth` (δ): the mean rise of the prompt between
|
|
22
|
+
* consecutive replies with no cut between. `rereads` (R): the mean tokens per cut of unchanged files re-read soon after it (thrash.ts). */
|
|
23
|
+
export function leanInputs(branch: readonly SessionEntry[]): LeanInputs {
|
|
24
|
+
let kept = 0, previous: number | undefined, afterCut = false, sum = 0, samples = 0;
|
|
25
|
+
for (const entry of branch) {
|
|
26
|
+
if (entry.type === "compaction") { previous = undefined; afterCut = true; continue; }
|
|
27
|
+
const prompt = promptTokens(entry);
|
|
28
|
+
if (prompt === undefined) continue;
|
|
29
|
+
if (afterCut) { kept = prompt; afterCut = false; }
|
|
30
|
+
if (previous !== undefined) { sum += prompt - previous; samples++; }
|
|
31
|
+
previous = prompt;
|
|
32
|
+
}
|
|
33
|
+
const { cuts, tokens } = rereadsAfterCuts(branch);
|
|
34
|
+
return { kept, growth: samples ? sum / samples : 0, rereads: cuts ? tokens / cuts : 0, samples, cuts };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The lean cut line: the economic order quantity of a context. Each cut costs a fresh re-send of what it keeps (K) and the re-reads it causes
|
|
39
|
+
* (R); each token held costs LEAN_HOLDING per request; the context grows by δ per request. The cheapest cycle cuts every
|
|
40
|
+
* n* = sqrt(2(K + R) / (h·δ)) requests, so the line is K + δ·n* = K + sqrt(2(K + R)·δ / h). Rising re-reads raise R and so the line.
|
|
41
|
+
* Undefined until the branch has a cut with a measured reply after it and LEAN_MIN_SAMPLES growth samples with a positive mean.
|
|
42
|
+
*/
|
|
43
|
+
export function leanLine(branch: readonly SessionEntry[]): number | undefined {
|
|
44
|
+
const { kept, growth, rereads, samples, cuts } = leanInputs(branch);
|
|
45
|
+
if (!cuts || kept <= 0 || samples < LEAN_MIN_SAMPLES || !(growth > 0)) return undefined;
|
|
46
|
+
return Math.ceil(kept + Math.sqrt(2 * (kept + rereads) * growth / LEAN_HOLDING));
|
|
47
|
+
}
|
package/src/status.ts
CHANGED
|
@@ -27,6 +27,8 @@ export function statusText(input: {
|
|
|
27
27
|
cacheSensitive?: boolean;
|
|
28
28
|
/** The trim point in tokens for the current model, the footer's full bar; absent when it cannot be computed. */
|
|
29
29
|
cutPoint?: number;
|
|
30
|
+
/** The line that sets the trim point now, when it is not the default band: the lean line or the thrash line. */
|
|
31
|
+
trigger?: "lean" | "thrash";
|
|
30
32
|
}): string {
|
|
31
33
|
if (!input.active) return `pi-tuck ${input.version} is inactive in this host.`;
|
|
32
34
|
if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version} is standing down (${input.compaction.reason}). Pi controls compaction.`;
|
|
@@ -48,7 +50,9 @@ export function statusText(input: {
|
|
|
48
50
|
...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
|
|
49
51
|
...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
|
|
50
52
|
input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
|
|
51
|
-
? `Trim point:
|
|
53
|
+
? input.trigger === "lean" ? `Trim point: this session's lean line, set by its growth per request and the size of its last trim${now}.`
|
|
54
|
+
: input.trigger === "thrash" ? `Trim point: native Pi's line, because this session's trims keep dropping files it then re-reads${now}.`
|
|
55
|
+
: `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
|
|
52
56
|
"Search: by keyword.",
|
|
53
57
|
...checkLines,
|
|
54
58
|
].join("\n");
|
package/src/thrash.ts
CHANGED
|
@@ -15,8 +15,10 @@ export const THRASH_BAR = 0.5;
|
|
|
15
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
16
|
* such re-read, it never does. Deterministic: it reads only the recorded branch.
|
|
17
17
|
*/
|
|
18
|
-
export
|
|
19
|
-
|
|
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;
|
|
20
22
|
const pending = new Map<string, { key: string; cut: number; soon: boolean }>(), last = new Map<string, { cut: number; text: string }>();
|
|
21
23
|
for (const entry of branch) {
|
|
22
24
|
if (entry.type === "compaction") { cuts++; replies = 0; continue; }
|
|
@@ -36,9 +38,20 @@ export function thrashing(branch: readonly SessionEntry[]): boolean {
|
|
|
36
38
|
if (!read || message.isError || !isTextOnly(message.content)) continue;
|
|
37
39
|
pending.delete(message.toolCallId);
|
|
38
40
|
const text = textOf(message.content), earlier = last.get(read.key);
|
|
39
|
-
if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text) rereads++;
|
|
41
|
+
if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text) { rereads++; chars += text.length; }
|
|
40
42
|
last.set(read.key, { cut: read.cut, text });
|
|
41
43
|
}
|
|
42
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);
|
|
43
56
|
return cuts > 0 && rereads / cuts >= THRASH_BAR;
|
|
44
57
|
}
|
package/src/tuck.ts
CHANGED
|
@@ -52,6 +52,8 @@ import { buildGlobalIndexById } from "./tuck/core/global-indices";
|
|
|
52
52
|
import { compileDialogue } from "./tuck/core/summarize";
|
|
53
53
|
import { prepareKeywordQuery } from "./tuck/core/keyword-query";
|
|
54
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;
|
|
55
57
|
export const tuck: Tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
|
|
56
58
|
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
57
59
|
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
@@ -440,7 +442,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
440
442
|
const missing = units.user.filter(unit => unit.position < at && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end && !wholeUser.has(unit.index));
|
|
441
443
|
if (!missing.length) records.splice(pos, 1);
|
|
442
444
|
else records[pos] = omissionRecord("user", missing.length, [missing[0]!.index, missing.at(-1)!.index], false);
|
|
443
|
-
} else if (at !== compiledBoundary) {
|
|
445
|
+
} else if (at !== compiledBoundary || stable) {
|
|
444
446
|
const role = record.role;
|
|
445
447
|
if (role === "assistant" || role === "toolResult") {
|
|
446
448
|
const missing = units[role].filter(unit => unit.position < at && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end &&
|
|
@@ -456,7 +458,78 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
456
458
|
const summary = render([...records, ...ledger, ...keptResults, ...thoughtOpenings]);
|
|
457
459
|
return { summary, records: [...records, ...thoughtOpenings] };
|
|
458
460
|
};
|
|
459
|
-
|
|
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();
|
|
460
533
|
let offer = assemble(compiled.text);
|
|
461
534
|
// After the complete dialogue fill, observations spend the remaining
|
|
462
535
|
// room before the native tail's older end. The pinned tail is untouched.
|