pi-tuck 1.8.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +5 -3
- 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.d.ts +4 -0
- package/dist/src/compaction.js +86 -12
- 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/run.d.ts +2 -0
- package/dist/src/run.js +2 -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 +70 -12
- package/src/lean.ts +47 -0
- package/src/run.ts +2 -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,38 @@
|
|
|
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.10.0]
|
|
7
|
+
|
|
8
|
+
### Added
|
|
9
|
+
|
|
10
|
+
- Act-now turn: when a reply stops at its output limit while still thinking (no text, no tool call) and pi-tuck does not retry it, pi-tuck
|
|
11
|
+
queues one more user turn asking the model to act now, with the next tool call or the answer. The stopped reply stays saved but leaves
|
|
12
|
+
that request's context, and the request gets the raised reply room. At most two such turns go out in a row, and only when the request
|
|
13
|
+
fits; if the second also stops, the exhaustion notice shows as before. A reply that is not such a stop re-arms it. The act-now turn
|
|
14
|
+
does not re-arm the length retry.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- README: `cacheSensitiveModels` also turns off the lean line (as in 1.9.0); a local server with a strong prompt cache belongs in it.
|
|
19
|
+
|
|
20
|
+
## [1.9.0]
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- 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
|
|
25
|
+
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
|
|
26
|
+
trim drops older context, so a long session sees more summaries than before. At small windows (32k) behavior is essentially unchanged.
|
|
27
|
+
- 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),
|
|
28
|
+
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
|
|
29
|
+
balances the cost of a trim against the cost of carrying a larger context each request. It never moves the trim point later than
|
|
30
|
+
1.8.0's, it is off with an explicit `cutAt`, a host reserve or a protected prefix, and admission is unchanged.
|
|
31
|
+
- Prefix-stable summary: a trim's summary begins with the previous summary's dialogue records, byte for byte, and adds the messages
|
|
32
|
+
trimmed since after them; the omission counts, lists and kept results follow the dialogue. Consecutive summaries then share their
|
|
33
|
+
longest possible prefix, which a provider's prompt cache can serve. When the new messages do not fit whole and the carried part leaves
|
|
34
|
+
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
|
|
35
|
+
summary still makes room for recent work. Sessions without an earlier pi-tuck summary are summarized as before.
|
|
36
|
+
- `/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).
|
|
37
|
+
|
|
6
38
|
## [1.8.0]
|
|
7
39
|
|
|
8
40
|
### 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.10.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.10.0` or `pi install git:github.com/galyavin/pi-tuck@v1.10.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
|
|
@@ -56,7 +58,7 @@ Once per Pi start, in the background, pi-tuck reads the server's own model list
|
|
|
56
58
|
Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by default, or `PI_CODING_AGENT_DIR`). Restart Pi to apply changes. The input room starts at the model's context window minus Pi's `compaction.reserveTokens`. Invalid JSON uses defaults. An invalid field uses its own default, with a notice when compaction is active.
|
|
57
59
|
|
|
58
60
|
- **`cutAt`** is a fraction above 0 and at most 1. By default pi-tuck cuts at the room, less a 2% margin. An explicit value fixes a fraction of the room, subject to the same margin even at `1`.
|
|
59
|
-
- **`cacheSensitiveModels`** lists exact `provider/model` identifiers. For these models, the cut point is the full room, taking precedence over `cutAt`. This delays early cuts that would discard a reusable prompt prefix.
|
|
61
|
+
- **`cacheSensitiveModels`** lists exact `provider/model` identifiers. For these models, the cut point is the full room, taking precedence over `cutAt`. This delays early cuts that would discard a reusable prompt prefix. It also turns off the lean line for these models; list a local server with a strong prompt cache here, where cached input is nearly free and wall time is the cost.
|
|
60
62
|
- **`footer`** set to `false` keeps Pi's own footer.
|
|
61
63
|
- **`llamaContinuation`** opts one reasoning model into a single extra request after a thinking-only response exhausts the full configured output allowance. In Pi's `models.json`, configure that model on a llama.cpp provider using the `openai-completions` API. Verify that the runtime and template support `continue_final_message: "reasoning_content"` and report reused prompt tokens through `prompt_progress`. Pi-tuck requires the first cache report to match the prefix within 15 seconds. The positive integer `extraTokens` caps the additional allowance within the remaining context. The positive integer `deadlineMs` covers both requests.
|
|
62
64
|
|
|
@@ -73,7 +75,7 @@ Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by
|
|
|
73
75
|
|
|
74
76
|
## Output exhaustion and small windows
|
|
75
77
|
|
|
76
|
-
- Pi-tuck preserves thinking-only stops in session history. At the model's full output allowance, it reports exhaustion if the reply remains unfinished. Below that allowance, it retries once, re-armed as Pi's overflow recovery is. After any length stop on the branch, pi-tuck trims so the next reply gets twice that stop's output (at most `maxTokens` and half the window). A stop at the full `maxTokens` while still thinking names the setting and `models.json`; a lower thinking level usually helps more than a bigger cap.
|
|
78
|
+
- Pi-tuck preserves thinking-only stops in session history. At the model's full output allowance, it reports exhaustion if the reply remains unfinished. Below that allowance, it retries once, re-armed as Pi's overflow recovery is. After any length stop on the branch, pi-tuck trims so the next reply gets twice that stop's output (at most `maxTokens` and half the window). When such a stop is not retried, pi-tuck queues one more user turn asking the model to act: "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning." The stopped reply stays saved but leaves that request's context. At most two such turns go out in a row, and only when the request fits; if the second also stops, the notice below stands. A stop at the full `maxTokens` while still thinking names the setting and `models.json`; a lower thinking level usually helps more than a bigger cap.
|
|
77
79
|
- Pi-tuck uses the context window declared in Pi's model configuration. A length stop alone does not establish a smaller window. If the server has a smaller effective limit, set that limit in Pi's model configuration.
|
|
78
80
|
- Pi's compaction reserve sets the cut target. For larger requests, pi-tuck estimates reply needs from observed output on the current branch for the active model, bounded by the reserve and model output limit. A cut above the room aims to leave 3,584 reply tokens within those bounds; where no cut can, the request goes out as before. If cuts cannot leave enough room for the protected prompt and a reply, try a shorter prompt, fewer tools, or a larger window. Pi-tuck's checks use estimates. Pi handles recognized provider overflows, and silent truncation can go undetected.
|
|
79
81
|
|
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 = "d6d248d0fe5344d96ce72d313dc9e120007dcff704b4e0a233bb506d927a3309";
|
package/dist/src/build-id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "d6d248d0fe5344d96ce72d313dc9e120007dcff704b4e0a233bb506d927a3309";
|
package/dist/src/compaction.d.ts
CHANGED
|
@@ -10,6 +10,10 @@ export declare const overflowNotice: (contextWindow: number, bound: number, lear
|
|
|
10
10
|
/** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
|
|
11
11
|
/** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
|
|
12
12
|
export declare const capStopNotice: (model: string, maxTokens: number, file: string) => string;
|
|
13
|
+
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
14
|
+
export declare const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
|
|
15
|
+
/** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply is not a stall. */
|
|
16
|
+
export declare const ACT_NOW_LIMIT = 2;
|
|
13
17
|
export declare const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
|
|
14
18
|
/** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
|
|
15
19
|
export declare const CALIBRATION_CEILING = 1.5;
|
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";
|
|
@@ -66,6 +67,10 @@ export const overflowNotice = (contextWindow, bound, learned) => `pi-tuck: the p
|
|
|
66
67
|
export const capStopNotice = (model, maxTokens, file) => `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
|
|
67
68
|
`The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
|
|
68
69
|
"The unfinished response is saved in the session.";
|
|
70
|
+
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
71
|
+
export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
|
|
72
|
+
/** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply is not a stall. */
|
|
73
|
+
export const ACT_NOW_LIMIT = 2;
|
|
69
74
|
/** Pi's models.json, shown with ~ for the home folder. */
|
|
70
75
|
function modelsPath() {
|
|
71
76
|
try {
|
|
@@ -214,7 +219,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
214
219
|
pi.on("session_compact", (_event, ctx) => observe(ctx));
|
|
215
220
|
pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
|
|
216
221
|
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");
|
|
222
|
+
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
223
|
} });
|
|
219
224
|
// Pi's native start/settled events bracket the run and its post-turn cuts.
|
|
220
225
|
let run;
|
|
@@ -338,11 +343,16 @@ export async function installCompaction(pi, options = {}) {
|
|
|
338
343
|
if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel)
|
|
339
344
|
run?.rearmLengthRetry();
|
|
340
345
|
};
|
|
341
|
-
pi
|
|
346
|
+
// The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
|
|
347
|
+
pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW)
|
|
342
348
|
rearmLengthRetry(ctx); });
|
|
349
|
+
// Act-now turns sent since the last reply that was not a stall.
|
|
350
|
+
let actNows = 0;
|
|
343
351
|
pi.on("message_end", (event, ctx) => {
|
|
344
352
|
if (event.message.role !== "assistant")
|
|
345
353
|
return;
|
|
354
|
+
if (event.message.stopReason !== "error" && event.message.stopReason !== "aborted" && !(event.message.content && thinkingOnlyLength(event.message)))
|
|
355
|
+
actNows = 0;
|
|
346
356
|
if (event.message.stopReason !== "error" && event.message.stopReason !== "length")
|
|
347
357
|
rearmLengthRetry(ctx);
|
|
348
358
|
lengthStop = event.message.stopReason === "length" ? {
|
|
@@ -420,18 +430,41 @@ export async function installCompaction(pi, options = {}) {
|
|
|
420
430
|
const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
|
|
421
431
|
return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
422
432
|
};
|
|
433
|
+
// 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
|
|
434
|
+
// economic order quantity of the context, when that is below the line above. Never later than it, and admission is unchanged: a cut it
|
|
435
|
+
// asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off.
|
|
436
|
+
const leanLimit = (ctx) => {
|
|
437
|
+
if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
|
|
438
|
+
return undefined;
|
|
439
|
+
return leanLine(ctx.sessionManager.getBranch());
|
|
440
|
+
};
|
|
441
|
+
// 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.
|
|
442
|
+
const usefulOnlyAt = (total, band, lean, ctx) => options.cutAt === undefined && !(lean !== undefined && fits(total, band, ctx));
|
|
423
443
|
/** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
|
|
424
444
|
const cutPoint = (ctx) => {
|
|
425
445
|
if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
|
|
426
446
|
return undefined;
|
|
427
447
|
try {
|
|
428
|
-
const { room } = limits(ctx), band = Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0);
|
|
448
|
+
const { room } = limits(ctx), band = Math.min(Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0), leanLimit(ctx) ?? Infinity);
|
|
429
449
|
return band > 0 ? band : undefined;
|
|
430
450
|
}
|
|
431
451
|
catch {
|
|
432
452
|
return undefined;
|
|
433
453
|
}
|
|
434
454
|
};
|
|
455
|
+
/** Which line sets the cut point now, for `/tuck`: the lean line, the thrash line, or neither (the band). Reads only. */
|
|
456
|
+
const activeTrigger = (ctx) => {
|
|
457
|
+
if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
|
|
458
|
+
return undefined;
|
|
459
|
+
try {
|
|
460
|
+
const { room } = limits(ctx), band = decisionBand(ctx, room), thrash = triggerLine(ctx, room), lean = leanLimit(ctx);
|
|
461
|
+
const line = Math.max(band, thrash ?? 0);
|
|
462
|
+
return lean !== undefined && lean < line ? "lean" : thrash !== undefined && thrash > band ? "thrash" : undefined;
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
return undefined;
|
|
466
|
+
}
|
|
467
|
+
};
|
|
435
468
|
const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
|
|
436
469
|
// 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
470
|
const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
|
|
@@ -664,15 +697,16 @@ export async function installCompaction(pi, options = {}) {
|
|
|
664
697
|
// 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
698
|
// cancel (Pi reports it as aborted), never a failure.
|
|
666
699
|
let thresholdOpportunistic = false;
|
|
700
|
+
const lean = leanLimit(ctx);
|
|
667
701
|
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) });
|
|
702
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
669
703
|
if (gate.kind !== "plan")
|
|
670
704
|
return { cancel: true };
|
|
671
705
|
thresholdOpportunistic = gate.opportunistic;
|
|
672
706
|
}
|
|
673
707
|
// Pi checks old history before appending a new idle prompt. During an active run/manual cut the latest admitted input stays protected.
|
|
674
708
|
const decide = (targetRoom = room, targetBand = band) => chooseCut({
|
|
675
|
-
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
709
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
|
|
676
710
|
opportunistic: thresholdOpportunistic,
|
|
677
711
|
unreduced: "Compaction did not reduce context within the estimated request budget",
|
|
678
712
|
plan: (target) => {
|
|
@@ -838,12 +872,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
838
872
|
throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
|
|
839
873
|
// A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
|
|
840
874
|
// help: leave it to the complete-context guard, which fails closed.
|
|
841
|
-
const
|
|
875
|
+
const lean = leanLimit(ctx);
|
|
876
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
842
877
|
if (gate.kind === "none")
|
|
843
878
|
return;
|
|
844
879
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
845
880
|
const decide = (targetRoom, targetBand, opportunistic) => chooseCut({
|
|
846
|
-
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
881
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx), opportunistic,
|
|
847
882
|
unreduced: "Incoming prompt compaction did not reduce context within the estimated request budget",
|
|
848
883
|
plan: (target) => {
|
|
849
884
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
@@ -991,13 +1026,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
991
1026
|
const decide = (targetRoom = room, targetBand = band, required = false) => {
|
|
992
1027
|
previews = [];
|
|
993
1028
|
floorKept = undefined;
|
|
994
|
-
const before = measure(saved);
|
|
1029
|
+
const before = measure(saved), lean = targetBand === band ? leanLimit(ctx) : undefined;
|
|
995
1030
|
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) });
|
|
1031
|
+
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
1032
|
if (gate.kind !== "plan")
|
|
998
1033
|
return gate;
|
|
999
1034
|
return chooseCut({
|
|
1000
|
-
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
1035
|
+
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
|
|
1001
1036
|
unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
|
|
1002
1037
|
plan: (target) => {
|
|
1003
1038
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
@@ -1111,6 +1146,42 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1111
1146
|
const saved = { ...cut, firstKeptEntryId: current.keptFromId };
|
|
1112
1147
|
return { entries: [...event.entries, saved, ...(more?.entries ?? [])] };
|
|
1113
1148
|
};
|
|
1149
|
+
// After a stall that is not retried: leave the stalled reply out of the context (it stays saved, with its output usage, so the next
|
|
1150
|
+
// request keeps the raised reply room) and queue one act-now turn, if that request fits as it stands. Otherwise the notice stands.
|
|
1151
|
+
const actNow = (event, ctx, result) => {
|
|
1152
|
+
if (actNows >= ACT_NOW_LIMIT || !ctx.model)
|
|
1153
|
+
return undefined;
|
|
1154
|
+
const edit = { type: "context_edit", targetId: event.messageEntryId, replacement: null };
|
|
1155
|
+
// The cap path returns before taking a pending cut: preview it in place, and take it only if the turn is queued.
|
|
1156
|
+
const untaken = !result || result.entries === event.entries;
|
|
1157
|
+
const base = result?.entries ?? event.entries;
|
|
1158
|
+
let entries = base.some(entry => entry.type === "context_edit" && entry.targetId === event.messageEntryId) ? [...base] : [...base, edit];
|
|
1159
|
+
const restore = untaken ? run?.cut.hold() : undefined;
|
|
1160
|
+
try {
|
|
1161
|
+
const preview = (untaken ? run?.cut ?? liveCut : liveCut).view(ctx, entries).session;
|
|
1162
|
+
const view = Object.create(ctx, { sessionManager: { value: preview } });
|
|
1163
|
+
const turn = { role: "user", content: [{ type: "text", text: ACT_NOW }], timestamp: 0 };
|
|
1164
|
+
const messages = projectedRequest(preview.buildSessionProjection().messages, view, hostMessages(ctx), [...event.context.pendingMessages, turn], ctx.getSystemPrompt(), pi.getActiveTools(), false);
|
|
1165
|
+
const tokens = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt()) + conversationTokens(messages);
|
|
1166
|
+
const { room, hardLine } = limits(view);
|
|
1167
|
+
if (!fits(tokens, hardLine, view) || !options.requestReserve && corrected(tokens, view) > room && piClamp && !requestClamp(messages, view).leavesFloor)
|
|
1168
|
+
return undefined;
|
|
1169
|
+
}
|
|
1170
|
+
finally {
|
|
1171
|
+
restore?.();
|
|
1172
|
+
}
|
|
1173
|
+
try {
|
|
1174
|
+
pi.sendUserMessage(ACT_NOW, { deliverAs: "followUp" });
|
|
1175
|
+
}
|
|
1176
|
+
catch {
|
|
1177
|
+
return undefined;
|
|
1178
|
+
}
|
|
1179
|
+
if (untaken)
|
|
1180
|
+
entries = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries), edit];
|
|
1181
|
+
actNows++;
|
|
1182
|
+
markBoundary(entries);
|
|
1183
|
+
return { entries, continue: false };
|
|
1184
|
+
};
|
|
1114
1185
|
const retryLength = (event, ctx) => {
|
|
1115
1186
|
// Exhausting the full per-request allowance is not evidence that input is too large.
|
|
1116
1187
|
// Preserve the unfinished response; provider-native continuation owns this case.
|
|
@@ -1189,8 +1260,11 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1189
1260
|
return;
|
|
1190
1261
|
if (!active() || run?.phase !== "admitted")
|
|
1191
1262
|
return;
|
|
1192
|
-
if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
|
|
1193
|
-
|
|
1263
|
+
if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled) {
|
|
1264
|
+
// A stall that is not retried gets one follow-up turn asking the model to act; its reply replaces the cap-stop notice.
|
|
1265
|
+
const result = retryLength(event, ctx);
|
|
1266
|
+
return result?.continue ? result : actNow(event, ctx, result) ?? result;
|
|
1267
|
+
}
|
|
1194
1268
|
run.finishLengthRetry();
|
|
1195
1269
|
const decide = event.outcome === "completed" && !ctx.signal?.aborted && event.context.canContinue && event.toolResults.length > 0 &&
|
|
1196
1270
|
settingsFor().getCompactionSettings(ctx.model).enabled;
|
|
@@ -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 = "d6d248d0fe5344d96ce72d313dc9e120007dcff704b4e0a233bb506d927a3309";
|
|
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/run.d.ts
CHANGED
|
@@ -20,6 +20,8 @@ export declare class PendingCut {
|
|
|
20
20
|
private preview?;
|
|
21
21
|
plan(cut: CutEntry, ctx: Context): void;
|
|
22
22
|
clear(): void;
|
|
23
|
+
/** Puts the plan back after a check that read a preview session (a read from another session clears it). */
|
|
24
|
+
hold(): () => void;
|
|
23
25
|
take(ctx: Context): CutEntry | undefined;
|
|
24
26
|
view(ctx: Context, entries?: readonly SessionBoundaryDraft[]): CutView;
|
|
25
27
|
}
|
package/dist/src/run.js
CHANGED
|
@@ -14,6 +14,8 @@ export class PendingCut {
|
|
|
14
14
|
this.preview = undefined;
|
|
15
15
|
}
|
|
16
16
|
clear() { this.proposal = undefined; this.preview = undefined; }
|
|
17
|
+
/** Puts the plan back after a check that read a preview session (a read from another session clears it). */
|
|
18
|
+
hold() { const proposal = this.proposal; return () => { this.proposal = proposal; this.preview = undefined; }; }
|
|
17
19
|
take(ctx) {
|
|
18
20
|
if (!this.view(ctx).pending)
|
|
19
21
|
return;
|
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 = "d6d248d0fe5344d96ce72d313dc9e120007dcff704b4e0a233bb506d927a3309";
|
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";
|
|
@@ -70,6 +71,10 @@ export const capStopNotice = (model: string, maxTokens: number, file: string) =>
|
|
|
70
71
|
`pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
|
|
71
72
|
`The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
|
|
72
73
|
"The unfinished response is saved in the session.";
|
|
74
|
+
/** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
|
|
75
|
+
export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
|
|
76
|
+
/** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply is not a stall. */
|
|
77
|
+
export const ACT_NOW_LIMIT = 2;
|
|
73
78
|
/** Pi's models.json, shown with ~ for the home folder. */
|
|
74
79
|
function modelsPath(): string {
|
|
75
80
|
try {
|
|
@@ -220,7 +225,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
220
225
|
pi.on("session_compact", (_event, ctx) => observe(ctx));
|
|
221
226
|
pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
|
|
222
227
|
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");
|
|
228
|
+
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
229
|
} });
|
|
225
230
|
// Pi's native start/settled events bracket the run and its post-turn cuts.
|
|
226
231
|
let run: Run | undefined;
|
|
@@ -318,9 +323,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
318
323
|
const rearmLengthRetry = (ctx: ExtensionContext) => {
|
|
319
324
|
if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel) run?.rearmLengthRetry();
|
|
320
325
|
};
|
|
321
|
-
pi
|
|
326
|
+
// The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
|
|
327
|
+
pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW) rearmLengthRetry(ctx); });
|
|
328
|
+
// Act-now turns sent since the last reply that was not a stall.
|
|
329
|
+
let actNows = 0;
|
|
322
330
|
pi.on("message_end", (event, ctx) => {
|
|
323
331
|
if (event.message.role !== "assistant") return;
|
|
332
|
+
if (event.message.stopReason !== "error" && event.message.stopReason !== "aborted" && !(event.message.content && thinkingOnlyLength(event.message))) actNows = 0;
|
|
324
333
|
if (event.message.stopReason !== "error" && event.message.stopReason !== "length") rearmLengthRetry(ctx);
|
|
325
334
|
lengthStop = event.message.stopReason === "length" ? {
|
|
326
335
|
kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
|
|
@@ -391,10 +400,29 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
391
400
|
const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
|
|
392
401
|
return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
393
402
|
};
|
|
403
|
+
// 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
|
|
404
|
+
// economic order quantity of the context, when that is below the line above. Never later than it, and admission is unchanged: a cut it
|
|
405
|
+
// asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off.
|
|
406
|
+
const leanLimit = (ctx: ExtensionContext): number | undefined => {
|
|
407
|
+
if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
|
|
408
|
+
return leanLine(ctx.sessionManager.getBranch());
|
|
409
|
+
};
|
|
410
|
+
// 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.
|
|
411
|
+
const usefulOnlyAt = (total: number, band: number, lean: number | undefined, ctx: ExtensionContext) =>
|
|
412
|
+
options.cutAt === undefined && !(lean !== undefined && fits(total, band, ctx));
|
|
394
413
|
/** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
|
|
395
414
|
const cutPoint = (ctx: ExtensionContext): number | undefined => {
|
|
396
415
|
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; }
|
|
416
|
+
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; }
|
|
417
|
+
};
|
|
418
|
+
/** Which line sets the cut point now, for `/tuck`: the lean line, the thrash line, or neither (the band). Reads only. */
|
|
419
|
+
const activeTrigger = (ctx: ExtensionContext): "lean" | "thrash" | undefined => {
|
|
420
|
+
if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
|
|
421
|
+
try {
|
|
422
|
+
const { room } = limits(ctx), band = decisionBand(ctx, room), thrash = triggerLine(ctx, room), lean = leanLimit(ctx);
|
|
423
|
+
const line = Math.max(band, thrash ?? 0);
|
|
424
|
+
return lean !== undefined && lean < line ? "lean" : thrash !== undefined && thrash > band ? "thrash" : undefined;
|
|
425
|
+
} catch { return undefined; }
|
|
398
426
|
};
|
|
399
427
|
const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
|
|
400
428
|
// 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 +622,15 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
594
622
|
// 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
623
|
// cancel (Pi reports it as aborted), never a failure.
|
|
596
624
|
let thresholdOpportunistic = false;
|
|
625
|
+
const lean = leanLimit(ctx);
|
|
597
626
|
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) });
|
|
627
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
599
628
|
if (gate.kind !== "plan") return { cancel: true };
|
|
600
629
|
thresholdOpportunistic = gate.opportunistic;
|
|
601
630
|
}
|
|
602
631
|
// Pi checks old history before appending a new idle prompt. During an active run/manual cut the latest admitted input stays protected.
|
|
603
632
|
const decide = (targetRoom = room, targetBand = band) => chooseCut({
|
|
604
|
-
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
633
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
|
|
605
634
|
opportunistic: thresholdOpportunistic,
|
|
606
635
|
unreduced: "Compaction did not reduce context within the estimated request budget",
|
|
607
636
|
plan: (target): Plan<CutPlan> => {
|
|
@@ -746,11 +775,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
746
775
|
throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
|
|
747
776
|
// A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
|
|
748
777
|
// help: leave it to the complete-context guard, which fails closed.
|
|
749
|
-
const
|
|
778
|
+
const lean = leanLimit(ctx);
|
|
779
|
+
const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
750
780
|
if (gate.kind === "none") return;
|
|
751
781
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
752
782
|
const decide = (targetRoom: number, targetBand: number, opportunistic: boolean) => chooseCut({
|
|
753
|
-
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
783
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx), opportunistic,
|
|
754
784
|
unreduced: "Incoming prompt compaction did not reduce context within the estimated request budget",
|
|
755
785
|
plan: (target): Plan<CutPlan> => {
|
|
756
786
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
@@ -881,12 +911,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
881
911
|
const decide = (targetRoom = room, targetBand = band, required = false) => {
|
|
882
912
|
previews = [];
|
|
883
913
|
floorKept = undefined;
|
|
884
|
-
const before = measure(saved);
|
|
914
|
+
const before = measure(saved), lean = targetBand === band ? leanLimit(ctx) : undefined;
|
|
885
915
|
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) });
|
|
916
|
+
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
917
|
if (gate.kind !== "plan") return gate;
|
|
888
918
|
return chooseCut({
|
|
889
|
-
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly:
|
|
919
|
+
opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
|
|
890
920
|
unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
|
|
891
921
|
plan: (target): Plan<CutPlan> => {
|
|
892
922
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
@@ -993,6 +1023,31 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
993
1023
|
const saved = { ...cut, firstKeptEntryId: current.keptFromId! };
|
|
994
1024
|
return { entries: [...event.entries as CutEntry[], saved, ...(more?.entries ?? [])] };
|
|
995
1025
|
};
|
|
1026
|
+
// After a stall that is not retried: leave the stalled reply out of the context (it stays saved, with its output usage, so the next
|
|
1027
|
+
// request keeps the raised reply room) and queue one act-now turn, if that request fits as it stands. Otherwise the notice stands.
|
|
1028
|
+
const actNow = (event: TurnEndEvent, ctx: ExtensionContext, result: { entries: readonly SessionBoundaryDraft[] } | undefined) => {
|
|
1029
|
+
if (actNows >= ACT_NOW_LIMIT || !ctx.model) return undefined;
|
|
1030
|
+
const edit: SessionBoundaryDraft = { type: "context_edit", targetId: event.messageEntryId, replacement: null };
|
|
1031
|
+
// The cap path returns before taking a pending cut: preview it in place, and take it only if the turn is queued.
|
|
1032
|
+
const untaken = !result || result.entries === event.entries;
|
|
1033
|
+
const base = result?.entries ?? event.entries;
|
|
1034
|
+
let entries: SessionBoundaryDraft[] = base.some(entry => entry.type === "context_edit" && entry.targetId === event.messageEntryId) ? [...base] : [...base, edit];
|
|
1035
|
+
const restore = untaken ? run?.cut.hold() : undefined;
|
|
1036
|
+
try {
|
|
1037
|
+
const preview = (untaken ? run?.cut ?? liveCut : liveCut).view(ctx, entries).session;
|
|
1038
|
+
const view: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
|
|
1039
|
+
const turn = { role: "user" as const, content: [{ type: "text" as const, text: ACT_NOW }], timestamp: 0 };
|
|
1040
|
+
const messages = projectedRequest(preview.buildSessionProjection().messages, view, hostMessages(ctx), [...event.context.pendingMessages, turn], ctx.getSystemPrompt(), pi.getActiveTools(), false);
|
|
1041
|
+
const tokens = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt()) + conversationTokens(messages);
|
|
1042
|
+
const { room, hardLine } = limits(view);
|
|
1043
|
+
if (!fits(tokens, hardLine, view) || !options.requestReserve && corrected(tokens, view) > room && piClamp && !requestClamp(messages, view).leavesFloor) return undefined;
|
|
1044
|
+
} finally { restore?.(); }
|
|
1045
|
+
try { pi.sendUserMessage(ACT_NOW, { deliverAs: "followUp" }); } catch { return undefined; }
|
|
1046
|
+
if (untaken) entries = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries), edit];
|
|
1047
|
+
actNows++;
|
|
1048
|
+
markBoundary(entries);
|
|
1049
|
+
return { entries, continue: false };
|
|
1050
|
+
};
|
|
996
1051
|
const retryLength = (event: TurnEndEvent, ctx: ExtensionContext) => {
|
|
997
1052
|
// Exhausting the full per-request allowance is not evidence that input is too large.
|
|
998
1053
|
// Preserve the unfinished response; provider-native continuation owns this case.
|
|
@@ -1062,8 +1117,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1062
1117
|
try {
|
|
1063
1118
|
if (standDown(ctx)) return;
|
|
1064
1119
|
if (!active() || run?.phase !== "admitted") return;
|
|
1065
|
-
if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
|
|
1066
|
-
|
|
1120
|
+
if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled) {
|
|
1121
|
+
// A stall that is not retried gets one follow-up turn asking the model to act; its reply replaces the cap-stop notice.
|
|
1122
|
+
const result = retryLength(event, ctx);
|
|
1123
|
+
return result?.continue ? result : actNow(event, ctx, result) ?? result;
|
|
1124
|
+
}
|
|
1067
1125
|
run.finishLengthRetry();
|
|
1068
1126
|
const decide = event.outcome === "completed" && !ctx.signal?.aborted && event.context.canContinue && event.toolResults.length > 0 &&
|
|
1069
1127
|
settingsFor().getCompactionSettings(ctx.model).enabled;
|
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/run.ts
CHANGED
|
@@ -20,6 +20,8 @@ export class PendingCut {
|
|
|
20
20
|
this.preview = undefined;
|
|
21
21
|
}
|
|
22
22
|
clear() { this.proposal = undefined; this.preview = undefined; }
|
|
23
|
+
/** Puts the plan back after a check that read a preview session (a read from another session clears it). */
|
|
24
|
+
hold() { const proposal = this.proposal; return () => { this.proposal = proposal; this.preview = undefined; }; }
|
|
23
25
|
take(ctx: Context) {
|
|
24
26
|
if (!this.view(ctx).pending) return;
|
|
25
27
|
const cut = this.proposal?.cut;
|
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.
|