pi-tuck 1.3.3 → 1.4.1
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 +43 -0
- package/LICENSE +0 -59
- package/NOTICE +63 -0
- package/README.md +59 -189
- package/dist/index.d.ts +1 -4
- package/dist/index.js +49 -10
- package/dist/src/budget.d.ts +6 -15
- package/dist/src/budget.js +6 -11
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +12 -20
- package/dist/src/compaction.js +220 -202
- package/dist/src/content-observations.d.ts +24 -0
- package/dist/src/content-observations.js +122 -0
- package/dist/src/diagnostics.d.ts +1 -3
- package/dist/src/ledger.d.ts +6 -3
- package/dist/src/ledger.js +14 -7
- package/dist/src/llama-continuation.d.ts +8 -0
- package/dist/src/llama-continuation.js +179 -0
- package/dist/src/omissions.d.ts +1 -5
- package/dist/src/omissions.js +8 -10
- package/dist/src/recall.js +8 -25
- package/dist/src/request-capacity.d.ts +11 -26
- package/dist/src/request-capacity.js +20 -57
- package/dist/src/run.d.ts +16 -7
- package/dist/src/run.js +53 -25
- package/dist/src/status.d.ts +2 -0
- package/dist/src/status.js +6 -5
- package/dist/src/tuck/core/format.js +1 -1
- package/dist/src/tuck/core/readable-content.d.ts +14 -0
- package/dist/src/tuck/core/readable-content.js +43 -0
- package/dist/src/tuck.d.ts +2 -1
- package/dist/src/tuck.js +92 -30
- package/index.ts +42 -10
- package/package.json +3 -2
- package/src/budget.ts +7 -12
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +220 -193
- package/src/content-observations.ts +115 -0
- package/src/diagnostics.ts +1 -1
- package/src/ledger.ts +17 -10
- package/src/llama-continuation.ts +176 -0
- package/src/omissions.ts +8 -10
- package/src/recall.ts +8 -20
- package/src/request-capacity.ts +18 -57
- package/src/run.ts +48 -22
- package/src/status.ts +8 -5
- package/src/tuck/core/format.ts +1 -1
- package/src/tuck/core/readable-content.ts +44 -0
- package/src/tuck.ts +79 -28
package/src/compaction.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { textOf } from "./tuck/core/content.js";
|
|
2
2
|
import { PendingCut, StartingPrompt, Run, type CutEntry } from "./run.js";
|
|
3
|
-
import {
|
|
3
|
+
import { CUT_REPLY_FLOOR, requestReplyFloor, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
|
|
4
4
|
import { BUILD_ID } from "./build-id.js";
|
|
5
5
|
import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry, type Receipt, type RecorderOptions } from "./diagnostics.js";
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
@@ -20,7 +20,7 @@ import type { RecallPolicy } from "./recall.js";
|
|
|
20
20
|
import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
|
|
21
21
|
|
|
22
22
|
import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
|
|
23
|
-
import { LOADED_VERSION, statusText } from "./status.js";
|
|
23
|
+
import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
|
|
24
24
|
import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
|
|
25
25
|
import { notify } from "./notify.js";
|
|
26
26
|
import { applyHistoryTools, historyToolDeclarations, historyToolNames, stageHistoryTools } from "./history-tools.js";
|
|
@@ -49,41 +49,27 @@ const reply = (value: unknown) => ({ content: [{ type: "text" as const, text: JS
|
|
|
49
49
|
/** The compactor's verdict that this attempt cannot be made: the cut it needs cannot be made, or the request cannot fit. Like every failure but
|
|
50
50
|
* a `CommitFault`, it ends with its attempt (`resetRun`), and the next attempt plans afresh from the session as it is. */
|
|
51
51
|
class Refusal extends Error {}
|
|
52
|
-
/**
|
|
53
|
-
* session may hold a cut its file lacks; what is written after would build on it. The one failure that stays until the session restarts. */
|
|
52
|
+
/** Pi could not confirm a pi-tuck cut on disk. Keep this fault until restart because a failed boundary may leave memory and disk out of sync. */
|
|
54
53
|
class CommitFault extends Error {}
|
|
55
54
|
/** A refusal for want of room, which the user can remedy: it carries advice. */
|
|
56
55
|
class CapacityError extends Refusal {}
|
|
57
|
-
/**
|
|
58
|
-
* likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
|
|
56
|
+
/** Explain a high planning factor, which can come from reported usage or an overflow estimate. */
|
|
59
57
|
export const refusalNotice = (message: string, factor: number): string =>
|
|
60
58
|
message + "; shorten the input, use a model with a larger window, or lower Pi's compaction.reserveTokens, then retry." +
|
|
61
|
-
(factor >= 1.5 ? `
|
|
62
|
-
/**
|
|
63
|
-
* what pi-tuck did with it. A bound pi-tuck cannot carry (above the ceiling) says so rather than implying the next request is planned at it. */
|
|
59
|
+
(factor >= 1.5 ? ` pi-tuck is planning with ${factor.toFixed(1)}x its base input estimate. Through a router such as OpenRouter, a different upstream may count less.` : "");
|
|
60
|
+
/** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
|
|
64
61
|
export const overflowNotice = (contextWindow: number, bound: number, learned: boolean): string =>
|
|
65
|
-
`pi-tuck: the provider refused this request
|
|
66
|
-
(learned ? "
|
|
62
|
+
`pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
|
|
63
|
+
(learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
|
|
67
64
|
/** 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. */
|
|
68
65
|
export const CALIBRATION_CEILING = 1.5;
|
|
69
66
|
/** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
|
|
70
67
|
export const CALIBRATION_WINDOW = 32;
|
|
71
|
-
/** Measured provider-input undercount by model, as "provider/id". An identity with no usable receipt of its own starts its window with this entry, which
|
|
72
|
-
* ages out after CALIBRATION_WINDOW later entries; every other model starts at 1. Empty: an undercount of 1.18 once measured for openai/gpt-6.1-sol
|
|
73
|
-
* was replayed reasoning, which the estimate now counts; with it counted, the first 32 requests of a real session measured at most 0.97. */
|
|
74
|
-
export const MEASURED_CALIBRATION: Readonly<Record<string, number>> = {};
|
|
75
|
-
/** The window of an identity with no usable receipt of its own: the model's measured undercount (at most CALIBRATION_CEILING), else 1. `key` is
|
|
76
|
-
* `identityFor`'s [provider, api, id]. */
|
|
77
|
-
function initialWindow(key: string): number[] {
|
|
78
|
-
try { const [provider, , id] = JSON.parse(key) as [string, string, string]; return [Math.min(MEASURED_CALIBRATION[`${provider}/${id}`] ?? 1, CALIBRATION_CEILING)]; } catch { return [1]; }
|
|
79
|
-
}
|
|
80
68
|
export const CALIBRATION_RECEIPT = 'pi-tuck-calibration';
|
|
81
|
-
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* `initialWindow`. A usable receipt of the identity's own wins over the measured seed, as a learned window replaces it: a Resume from a receipt
|
|
86
|
-
* written before the seed existed, or after it aged out, starts at that receipt's window (as low as 1). Reads only; a malformed receipt never throws. */
|
|
69
|
+
/** Read the newest applicable calibration receipt on the branch for `key` ([provider, api, id]). A custom
|
|
70
|
+
* observation for another identity is skipped. A compaction receipt for another or missing identity resets
|
|
71
|
+
* the seed to [1]. A matching receipt supplies its recent ratios clamped to [0, CALIBRATION_CEILING],
|
|
72
|
+
* or its legacy factor clamped to [1, CALIBRATION_CEILING]. Without a usable seed, start at [1]. */
|
|
87
73
|
export function seedWindow(branch: readonly SessionEntry[], key: string): number[] {
|
|
88
74
|
for (let i = branch.length; i--;) {
|
|
89
75
|
const entry = branch[i]!;
|
|
@@ -93,39 +79,33 @@ export function seedWindow(branch: readonly SessionEntry[], key: string): number
|
|
|
93
79
|
const { calibrationIdentity, calibrationFactor, calibrationWindow } = receipt?.settings ?? {}, stored: unknown = calibrationWindow;
|
|
94
80
|
if (calibrationIdentity !== key) {
|
|
95
81
|
if (entry.type === "custom") continue; // Another model's new observation does not hide this model's last saved seed.
|
|
96
|
-
return
|
|
82
|
+
return [1];
|
|
97
83
|
}
|
|
98
84
|
if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
|
|
99
85
|
return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
|
|
100
86
|
if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor)) return [Math.min(Math.max(calibrationFactor, 1), CALIBRATION_CEILING)];
|
|
101
|
-
return
|
|
87
|
+
return [1];
|
|
102
88
|
}
|
|
103
|
-
return
|
|
89
|
+
return [1];
|
|
104
90
|
}
|
|
105
91
|
/** One accounting owner. Session start still defers receipt loading until the first budget read;
|
|
106
|
-
* tree moves load immediately
|
|
92
|
+
* tree moves load immediately. */
|
|
107
93
|
class Calibration {
|
|
108
94
|
identity = '';
|
|
109
95
|
factor = 1;
|
|
110
96
|
ratios: number[] = [];
|
|
111
|
-
|
|
112
|
-
/** The configured window the learned window was learned under; the learned window applies only while the model still has it. */
|
|
113
|
-
learnedCatalogue: number | undefined;
|
|
114
|
-
windowObservation: { message: AgentMessage; identity: string; window: number; catalogue: number } | undefined;
|
|
115
|
-
pending: { identity: string; tokens: number; messages: Parameters<typeof convertToLlm>[0]; snapshot: ReturnType<typeof convertToLlm>; requestedMaxTokens?: () => number | undefined } | undefined;
|
|
97
|
+
pending: { identity: string; tokens: number; messages: Parameters<typeof convertToLlm>[0]; snapshot: ReturnType<typeof convertToLlm> } | undefined;
|
|
116
98
|
lastCeiling: number | null = null;
|
|
117
99
|
estimatedTokens = 0;
|
|
118
100
|
private seededIdentity = '';
|
|
119
101
|
static key(ctx: ExtensionContext) { return ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : ''; }
|
|
120
|
-
/** Model selection itself never reloads receipts: switching away and back without a request keeps the learned window. */
|
|
121
102
|
select(ctx: ExtensionContext) { this.identity = Calibration.key(ctx); }
|
|
122
|
-
needsSeed(
|
|
103
|
+
needsSeed() { return this.seededIdentity !== this.identity; }
|
|
123
104
|
reseed(ctx: ExtensionContext, reason: 'identity' | 'session' | 'tree') {
|
|
124
105
|
this.identity = Calibration.key(ctx);
|
|
125
106
|
this.pending = undefined;
|
|
126
|
-
if (reason !== 'identity') this.windowObservation = undefined;
|
|
127
107
|
if (reason === 'session') {
|
|
128
|
-
this.factor = 1; this.
|
|
108
|
+
this.factor = 1; this.estimatedTokens = 0;
|
|
129
109
|
// Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
|
|
130
110
|
this.seededIdentity = '';
|
|
131
111
|
return;
|
|
@@ -135,8 +115,6 @@ class Calibration {
|
|
|
135
115
|
const branch = ctx.sessionManager.getBranch();
|
|
136
116
|
this.ratios = seedWindow(branch, this.identity);
|
|
137
117
|
this.factor = Math.max(1, ...this.ratios);
|
|
138
|
-
this.learnedCatalogue = ctx.model?.contextWindow;
|
|
139
|
-
this.learnedContextWindow = seedContextWindow(branch, this.identity, this.learnedCatalogue);
|
|
140
118
|
}
|
|
141
119
|
learn(value: number, ctx: ExtensionContext, append: (kind: string, data: unknown) => void) {
|
|
142
120
|
this.ratios.push(value); if (this.ratios.length > CALIBRATION_WINDOW) this.ratios.shift(); this.factor = Math.max(1, ...this.ratios);
|
|
@@ -165,12 +143,12 @@ export interface CompactionOptions {
|
|
|
165
143
|
* which is the room less 2% of it, or this fraction of the room when that is lower; a lower value cuts earlier and leaves less. The room
|
|
166
144
|
* owns cut targets; standalone final capacity admission uses the branch reply floor. If omitted, the band adapts to the last cut. */
|
|
167
145
|
cutAt?: number;
|
|
168
|
-
/**
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
*
|
|
146
|
+
/** Models where a usable cached prefix is more valuable than an early cut. */
|
|
147
|
+
cacheSensitiveModels?: readonly string[];
|
|
148
|
+
/** provider/model with provider-native continuation; it keeps one length recovery per run, and only where a cut adds reply room. */
|
|
149
|
+
continuationModel?: string;
|
|
150
|
+
/** Host response reserve. `responseExact: true` uses it as declared. Otherwise the SDK
|
|
151
|
+
* keeps the catalogue maximum as a floor for existing callers. Standalone uses Pi’s soft reserve. */
|
|
174
152
|
requestReserve?: (ctx: ExtensionContext) => { response: number; responseExact?: true };
|
|
175
153
|
/** The exact messages the host's `context` hook adds to every final request beyond the saved conversation (for example a role
|
|
176
154
|
* view), in the form the hook injects them. Cut triggers, the cut planner and the post-cut checks count them with the same
|
|
@@ -206,7 +184,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
206
184
|
if (found) { recorder.capture("observed-entry", "current-native-branch-memory-not-durable", { entryId: found.id, diagnosticReceiptId: proposalId, details: found.type === "compaction" ? found.details : undefined }); recorder.cut(); proposalId = undefined; }
|
|
207
185
|
});
|
|
208
186
|
const captureDraft = (draft: NonNullable<ReturnType<typeof tuckDraft>["compaction"]>, ctx: ExtensionContext, reserve: number, reason: string, tokensBefore: number, retainCurrentInput: boolean, operatorManual: boolean, previousSummary?: string, budget?: { response: number; host: number; mandatory: number; target: Target; margin: number }) => recorder.measureInline(() => {
|
|
209
|
-
const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: calibration.factor, calibrationWindow: [...calibration.ratios], calibrationIdentity: calibration.identity,
|
|
187
|
+
const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: calibration.factor, calibrationWindow: [...calibration.ratios], calibrationIdentity: calibration.identity, activeInputCeilingTokens: calibration.lastCeiling });
|
|
210
188
|
proposalId = receiptId(attached);
|
|
211
189
|
if (recorder.enabled) { try {
|
|
212
190
|
const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
|
|
@@ -225,7 +203,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
225
203
|
pi.on("session_compact", (_event, ctx) => observe(ctx));
|
|
226
204
|
pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
|
|
227
205
|
pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
|
|
228
|
-
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, pending: view(ctx).pending }), "info");
|
|
206
|
+
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 }), "info");
|
|
229
207
|
} });
|
|
230
208
|
// Pi's native start/settled events bracket the run and its post-turn cuts.
|
|
231
209
|
let run: Run | undefined;
|
|
@@ -234,6 +212,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
234
212
|
const protectedPrompt = (ctx: ExtensionContext) => run?.prompt?.id(ctx.sessionManager.getBranch());
|
|
235
213
|
const clips = () => run?.clips ?? emptyClips;
|
|
236
214
|
const emptyClips = new Map<string, Clip>();
|
|
215
|
+
const restoreClips = (snapshot: ReadonlyMap<string, Clip>) => {
|
|
216
|
+
const current = clips();
|
|
217
|
+
current.clear();
|
|
218
|
+
for (const [id, clip] of snapshot) current.set(id, clip);
|
|
219
|
+
};
|
|
237
220
|
const resetRun = (session = false) => {
|
|
238
221
|
if (!session && run?.phase === "commit-failed") run.clear(); else run = undefined;
|
|
239
222
|
calibration.pending = undefined;
|
|
@@ -246,36 +229,21 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
246
229
|
const standDown = (ctx: ExtensionContext) => {
|
|
247
230
|
if (stateFor(ctx).kind === "active") return false;
|
|
248
231
|
resetRun();
|
|
249
|
-
|
|
250
|
-
lengthStop = false;
|
|
232
|
+
lengthStop = undefined;
|
|
251
233
|
return true;
|
|
252
234
|
};
|
|
253
235
|
const promptRefusal = () => new Refusal("Prompt check failed: the whole starting prompt cannot fit after cutting to the band and room, shrinking the summary and clipping fresh results. Shorten the prompt or choose a model with a larger context window, then retry");
|
|
254
236
|
const calibration = new Calibration();
|
|
255
|
-
const serverClipped = new WeakSet<object>();
|
|
256
237
|
const identityFor = (ctx: ExtensionContext) => {
|
|
257
238
|
calibration.select(ctx);
|
|
258
|
-
if (calibration.needsSeed(
|
|
239
|
+
if (calibration.needsSeed()) calibration.reseed(ctx, "identity");
|
|
259
240
|
return calibration.identity;
|
|
260
241
|
};
|
|
261
|
-
pi.on("model_select", (_event, ctx) => {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
const model = ctx.model?.contextWindow ?? 0;
|
|
265
|
-
const learned = calibration.learnedCatalogue === ctx.model?.contextWindow ? calibration.learnedContextWindow : undefined;
|
|
266
|
-
return Math.min(model, learned ?? Infinity);
|
|
267
|
-
};
|
|
268
|
-
// This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
|
|
269
|
-
// An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
|
|
270
|
-
pi.on("before_provider_request", event => {
|
|
271
|
-
if (!calibration.pending || !event.payload || typeof event.payload !== "object") return;
|
|
272
|
-
const payload = event.payload as Record<string, unknown>;
|
|
273
|
-
// Read at reply time so later in-place payload edits are included too.
|
|
274
|
-
calibration.pending.requestedMaxTokens = () => {
|
|
275
|
-
const cap = payload.max_tokens ?? payload.max_completion_tokens ?? payload.max_output_tokens;
|
|
276
|
-
return typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0 ? cap : undefined;
|
|
277
|
-
};
|
|
242
|
+
pi.on("model_select", (_event, ctx) => {
|
|
243
|
+
calibration.select(ctx);
|
|
244
|
+
if (run) run.rejectedBudget = undefined;
|
|
278
245
|
});
|
|
246
|
+
const contextWindow = (ctx: ExtensionContext) => ctx.model?.contextWindow ?? 0;
|
|
279
247
|
// The factor is max(1, the last CALIBRATION_WINDOW paired ratios, overflow bounds and seed): it rises at once and a stale high ratio ages out.
|
|
280
248
|
const learn = (value: number, ctx: ExtensionContext) => calibration.learn(value, ctx, (kind, data) => pi.appendEntry(kind, data));
|
|
281
249
|
const corrected = (tokens: number, ctx: ExtensionContext) => { identityFor(ctx); return Math.ceil(tokens * calibration.factor); };
|
|
@@ -285,7 +253,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
285
253
|
// The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
|
|
286
254
|
const planReserve = (target: Target, room: number, band: number, mandatory: number, ctx: ExtensionContext) => {
|
|
287
255
|
identityFor(ctx);
|
|
288
|
-
// The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
|
|
289
256
|
return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, calibration.factor, mandatory);
|
|
290
257
|
};
|
|
291
258
|
pi.on("message_end", (event, ctx) => {
|
|
@@ -304,11 +271,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
304
271
|
message.provider !== ctx.model?.provider || message.model !== ctx.model.id || message.api !== ctx.model.api ||
|
|
305
272
|
(!overflow && !["stop", "toolUse", "length"].includes(message.stopReason)) ||
|
|
306
273
|
!isDeepStrictEqual(convertToLlm(paired.messages), paired.snapshot)) return;
|
|
307
|
-
// The
|
|
308
|
-
//
|
|
309
|
-
// Either way the operator hears it from pi-tuck. The estimate is what admitted the request, and a turn that ended in the provider's error
|
|
310
|
-
// with no word from pi-tuck read as a hang: every other refusal says why, and this is the path that skipped it.
|
|
274
|
+
// The error alone does not report the server's window or whether it counted input plus output. Use the configured
|
|
275
|
+
// input limit as a planning assumption and keep that assumption explicit in the notice.
|
|
311
276
|
if (overflow) {
|
|
277
|
+
if (run?.phase === "admitted" && !options.requestReserve && piClamp) {
|
|
278
|
+
const { estimate, cap } = requestClamp(paired.messages, ctx);
|
|
279
|
+
if (cap !== undefined) run.rejectedBudget = { input: estimate, output: cap };
|
|
280
|
+
}
|
|
312
281
|
const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
|
|
313
282
|
const learned = bound <= CALIBRATION_CEILING;
|
|
314
283
|
notify(ctx, overflowNotice(window, bound, learned), "warning");
|
|
@@ -320,56 +289,48 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
320
289
|
const counts = [usage.input, usage.cacheRead, usage.cacheWrite];
|
|
321
290
|
if (!counts.every(n => Number.isSafeInteger(n) && n >= 0)) return;
|
|
322
291
|
const input = counts.reduce((a, b) => a + b, 0), ratio = input / paired.tokens;
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
Number.isSafeInteger(output) && output >= 0 && output < requested &&
|
|
326
|
-
Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
|
|
327
|
-
// A learned window from another configured window no longer bounds this one.
|
|
328
|
-
if (calibration.learnedCatalogue !== ctx.model.contextWindow) calibration.learnedContextWindow = undefined;
|
|
329
|
-
calibration.learnedCatalogue = ctx.model.contextWindow;
|
|
330
|
-
calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
|
|
331
|
-
serverClipped.add(message);
|
|
332
|
-
calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow, catalogue: ctx.model.contextWindow };
|
|
333
|
-
}
|
|
334
|
-
// A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
|
|
335
|
-
// Learning from one sets the factor for the requests after it: a 60,000-token cache read reported in a 32,768-token window made a
|
|
336
|
-
// 6,000-token prompt refuse. The overflow branch above learns from a refusal, where the count is a lower bound, and the ceiling is unchanged.
|
|
292
|
+
// Reject usage above the configured window for calibration. Learning from a reported 60,000-token
|
|
293
|
+
// cache read with a 32,768-token window once made a subsequent 6,000-token prompt refuse.
|
|
337
294
|
if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio)) learn(ratio, ctx);
|
|
338
295
|
});
|
|
339
|
-
pi.on("turn_end", (event, ctx) => {
|
|
340
|
-
if (standDown(ctx)) return;
|
|
341
|
-
if (calibration.windowObservation?.message !== event.message) return;
|
|
342
|
-
const observation = calibration.windowObservation; calibration.windowObservation = undefined;
|
|
343
|
-
pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window, catalogueContextWindow: observation.catalogue,
|
|
344
|
-
serverClippedReplyId: event.messageEntryId } satisfies WindowReceipt);
|
|
345
|
-
});
|
|
346
296
|
// The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
|
|
347
297
|
// extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
|
|
348
|
-
let lengthStop
|
|
349
|
-
pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= new Run("starting"); if (!failure()) run.transition("admitted"
|
|
350
|
-
|
|
298
|
+
let lengthStop: { kind: "thinking" | "output"; cacheMiss: boolean } | undefined;
|
|
299
|
+
pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= new Run("starting"); if (!failure()) run.transition("admitted"); lengthStop = undefined; calibration.pending = undefined; });
|
|
300
|
+
// Pi's overflow-recovery rule: a new user message or a good reply grants another recovery.
|
|
301
|
+
const rearmLengthRetry = (ctx: ExtensionContext) => {
|
|
302
|
+
if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel) run?.rearmLengthRetry();
|
|
303
|
+
};
|
|
304
|
+
pi.on("message_start", (event, ctx) => { if (event.message.role === "user") rearmLengthRetry(ctx); });
|
|
305
|
+
pi.on("message_end", (event, ctx) => {
|
|
306
|
+
if (event.message.role !== "assistant") return;
|
|
307
|
+
if (event.message.stopReason !== "error" && event.message.stopReason !== "length") rearmLengthRetry(ctx);
|
|
308
|
+
lengthStop = event.message.stopReason === "length" ? {
|
|
309
|
+
kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
|
|
310
|
+
cacheMiss: event.message.errorMessage === CONTINUATION_CACHE_MISS,
|
|
311
|
+
} : undefined;
|
|
312
|
+
});
|
|
351
313
|
pi.on("agent_settled", (_event, ctx) => {
|
|
352
314
|
try {
|
|
353
315
|
if (standDown(ctx) || !lengthStop || !active()) return;
|
|
354
|
-
|
|
355
|
-
const message =
|
|
356
|
-
|
|
316
|
+
const { kind, cacheMiss } = lengthStop;
|
|
317
|
+
const message = kind === "thinking"
|
|
318
|
+
? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
|
|
319
|
+
: "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
|
|
320
|
+
lengthStop = undefined;
|
|
321
|
+
notify(ctx, kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message, "warning");
|
|
357
322
|
} finally { resetRun(); }
|
|
358
323
|
});
|
|
359
324
|
const active = () => options.active?.() ?? true;
|
|
360
325
|
const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings?.());
|
|
361
|
-
//
|
|
362
|
-
|
|
363
|
-
// length stop uses branchReplyFloor's observed output instead; reserving the catalogue maximum would strand setups above the room.
|
|
364
|
-
// Other errors, such as a 503, keep native's room. Read the whole branch, including history before compactions, each time: no flag to persist or reset on resume,
|
|
365
|
-
// fork, /tree or a new session.
|
|
366
|
-
const requestReserve = (ctx: ExtensionContext) => {
|
|
326
|
+
// Pi’s configured reserve is the standalone cut target, separate from the output cap.
|
|
327
|
+
const responseReserve = (ctx: ExtensionContext) => {
|
|
367
328
|
const host = options.requestReserve?.(ctx);
|
|
368
329
|
const budget = host ?? { response: settingsFor().getCompactionSettings(ctx.model).reserveTokens };
|
|
369
330
|
if (!Number.isSafeInteger(budget.response) || budget.response < 0)
|
|
370
331
|
throw new Error("Invalid host request reserve");
|
|
371
|
-
const floor = host
|
|
372
|
-
return
|
|
332
|
+
const floor = host && host.responseExact !== true;
|
|
333
|
+
return floor ? Math.max(budget.response, ctx.model?.maxTokens ?? 0) : budget.response;
|
|
373
334
|
};
|
|
374
335
|
const inputRoom = (response: number, ctx: ExtensionContext) => {
|
|
375
336
|
const configured = options.activeInputTokens;
|
|
@@ -380,18 +341,16 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
380
341
|
return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
|
|
381
342
|
};
|
|
382
343
|
// Room still owns every existing cut/clip attempt. Only final capacity admission uses the hard line.
|
|
344
|
+
let floorMinimum = 1;
|
|
383
345
|
const limits = (ctx: ExtensionContext) => {
|
|
384
|
-
const
|
|
385
|
-
const floor = options.requestReserve ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model
|
|
346
|
+
const response = responseReserve(ctx), room = inputRoom(response, ctx);
|
|
347
|
+
const floor = options.requestReserve || !ctx.model ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model, floorMinimum);
|
|
386
348
|
const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
|
|
387
349
|
return { response, room, hardLine, replyFloor: floor };
|
|
388
350
|
};
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
return bandOf(room, cutAt, options.cutAt === undefined && typeof after === "number" && Number.isFinite(after) && after >= 0
|
|
393
|
-
? { system, tokensAfter: after, factor: calibration.factor } : undefined);
|
|
394
|
-
};
|
|
351
|
+
const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
|
|
352
|
+
options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
|
|
353
|
+
const decisionBand = (ctx: ExtensionContext, room: number) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
|
|
395
354
|
const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
|
|
396
355
|
// The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
|
|
397
356
|
const measureFor = (ctx: ExtensionContext) => (messages: Messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
|
|
@@ -418,10 +377,29 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
418
377
|
// whereas our hard line is in corrected units; fitting that line alone need not leave the branch's reply floor.
|
|
419
378
|
const requestClamp = (messages: Messages, ctx: ExtensionContext) => {
|
|
420
379
|
const context = normalizeContext({ messages: convertToLlm(messages) });
|
|
421
|
-
const cap = piClamp?.(
|
|
380
|
+
const cap = piClamp?.(ctx.model!, context, ctx.model!.maxTokens);
|
|
422
381
|
const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
|
|
423
|
-
|
|
424
|
-
|
|
382
|
+
const fitsWindow = cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx);
|
|
383
|
+
// The native clamp bottoms out at one even when the estimate leaves no room.
|
|
384
|
+
return { cap, leavesFloor: cap === undefined || fitsWindow && cap >= limits(ctx).replyFloor, estimate, fitsWindow };
|
|
385
|
+
};
|
|
386
|
+
// Plan a cut above the room for the cut floor first. The floor only shapes cuts: where no plan reaches it, the admission floor plans as if it
|
|
387
|
+
// did not exist, so it never refuses a request.
|
|
388
|
+
const planAboveRoom = (plan: (hardLine: number) => Decision<CutPlan>, ctx: ExtensionContext): Decision<CutPlan> => {
|
|
389
|
+
const { replyFloor, room } = limits(ctx);
|
|
390
|
+
if (!options.requestReserve) {
|
|
391
|
+
const previousClips = new Map(clips());
|
|
392
|
+
floorMinimum = CUT_REPLY_FLOOR;
|
|
393
|
+
try {
|
|
394
|
+
const shaped = limits(ctx);
|
|
395
|
+
if (shaped.replyFloor > replyFloor && shaped.hardLine > room) {
|
|
396
|
+
const decision = plan(shaped.hardLine);
|
|
397
|
+
if (decision.kind === "cut" || decision.kind === "none") return decision;
|
|
398
|
+
}
|
|
399
|
+
} finally { floorMinimum = 1; }
|
|
400
|
+
restoreClips(previousClips);
|
|
401
|
+
}
|
|
402
|
+
return plan(limits(ctx).hardLine);
|
|
425
403
|
};
|
|
426
404
|
const projectedRequest = (messages: Messages, ctx: ExtensionContext, host: Messages, incoming: Messages, prompt: string, tools: readonly string[], cut: boolean) => {
|
|
427
405
|
const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
|
|
@@ -438,7 +416,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
438
416
|
const candidate = deepest();
|
|
439
417
|
if (candidate.kind === "cut" && fits(total(candidate), limits(ctx).hardLine, ctx) && requestClamp(project(candidate), ctx).leavesFloor)
|
|
440
418
|
return candidate;
|
|
441
|
-
|
|
419
|
+
restoreClips(previousClips);
|
|
442
420
|
return { kind: "fault", capacity: true, message: clampMessage };
|
|
443
421
|
};
|
|
444
422
|
for (let retry = 0; ; retry++) {
|
|
@@ -469,19 +447,19 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
469
447
|
recorder.stop("native-attempt-failed");
|
|
470
448
|
// Every refusal says why, once per attempt: a capacity error with what the user can change, a cut Pi failed to commit with what that
|
|
471
449
|
// means for the session, anything else as it is (an attempt that ended with no word looked like a hang).
|
|
472
|
-
const previous = failure()
|
|
450
|
+
const previous = failure();
|
|
473
451
|
const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
|
|
474
452
|
const receipted = run?.refusalReceipted;
|
|
475
453
|
calibration.pending = undefined;
|
|
476
454
|
// Keep the same terminal run until Pi settles; later start hooks cannot admit it.
|
|
477
455
|
run ??= new Run("starting"); run.clear();
|
|
478
|
-
run.transition(fault instanceof CommitFault ? "commit-failed" : "failed",
|
|
456
|
+
run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", fault);
|
|
479
457
|
run.refusalReceipted = true;
|
|
480
458
|
try {
|
|
481
459
|
if (!receipted) receipt("refusal", fault.message, ctx);
|
|
482
460
|
options.fail?.(error);
|
|
483
461
|
} finally {
|
|
484
|
-
try { if (
|
|
462
|
+
try { if (!receipted) notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
|
|
485
463
|
? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
|
|
486
464
|
: `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error"); }
|
|
487
465
|
finally { ctx.abort(); }
|
|
@@ -501,12 +479,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
501
479
|
catch (error) { fail(error, ctx); }
|
|
502
480
|
// Pi normally reaches its pre-run threshold check within microtasks. Auth I/O or a later extension's input I/O can make a
|
|
503
481
|
// real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
|
|
504
|
-
setImmediate(() => { if (run === decision && decision.phase === "decided") decision.transition("expired"
|
|
482
|
+
setImmediate(() => { if (run === decision && decision.phase === "decided") decision.transition("expired"); });
|
|
505
483
|
});
|
|
506
484
|
|
|
507
485
|
pi.registerTool({
|
|
508
486
|
name: "tuck_recall", label: "pi-tuck history", parameters: RecallInput,
|
|
509
|
-
description: "Keyword lookup locates particular text in your current branch. {query} returns ranked passages with read coordinates; punctuation separates words. Pass the returned next as {continuation} unchanged. Knowing an identifier does not itself justify narrowing discovery. {entryId} or {index} (a summary sourceIndex or #N) reads one source, optionally with query, offset and limit in UTF-16 characters (limit defaults to 8000). {} browses history; {around} expands neighbors; {entryId,image} reads an image; outputPath writes an original to a file with the native write tool.
|
|
487
|
+
description: "Keyword lookup locates particular text in your current branch. {query} returns ranked passages with read coordinates; punctuation separates words. Pass the returned next as {continuation} unchanged. Knowing an identifier does not itself justify narrowing discovery. {entryId} or {index} (a summary sourceIndex or #N) reads one source, optionally with query, offset and limit in UTF-16 characters (limit defaults to 8000). {} browses history; {around} expands neighbors; {entryId,image} reads an image; outputPath writes an original to a file with the native write tool. Plain thinking is readable; signed, redacted or encrypted reasoning and system records are excluded.",
|
|
510
488
|
async execute(_id, raw, signal, _update, ctx) {
|
|
511
489
|
access();
|
|
512
490
|
const input = checkedInput(raw);
|
|
@@ -538,13 +516,16 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
538
516
|
// Pi checks its own threshold after a prompt's input and before the run starts: the prompt's cut, planned with the prompt counted,
|
|
539
517
|
// is the answer, and it is saved before the first request.
|
|
540
518
|
if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
|
|
541
|
-
run.transition("claimed"
|
|
519
|
+
run.transition("claimed");
|
|
542
520
|
if (view(ctx).pending) {
|
|
543
521
|
access();
|
|
544
|
-
const current = view(ctx), { type: _, ...compaction } = run.cut.take()!;
|
|
522
|
+
const current = view(ctx), { type: _, ...compaction } = run.cut.take(ctx)!;
|
|
545
523
|
return { compaction: { ...compaction, firstKeptEntryId: current.keptFromId! } };
|
|
546
524
|
}
|
|
547
525
|
}
|
|
526
|
+
// Capacity is decided when there is another request to send. A threshold
|
|
527
|
+
// notification after exhausted reasoning must not put that response away.
|
|
528
|
+
if (event.reason === "threshold" && lengthStop?.kind === "thinking") return { cancel: true };
|
|
548
529
|
const operatorManual = event.reason === "manual";
|
|
549
530
|
if (operatorManual && run?.phase !== "admitted") resetRun();
|
|
550
531
|
access();
|
|
@@ -557,8 +538,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
557
538
|
// cut: the system part and the host input. A prompt's cut is pi-tuck's own and never comes here.
|
|
558
539
|
const saved = ctx.sessionManager.buildSessionProjection().messages;
|
|
559
540
|
const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
|
|
560
|
-
const
|
|
561
|
-
const
|
|
541
|
+
const systemPrompt = ctx.getSystemPrompt(), tools = pi.getActiveTools();
|
|
542
|
+
const system = requestSystemPart(systemPrompt, tools, saved, systemPrompt);
|
|
543
|
+
const project = (messages: Messages, cut: boolean) => projectedRequest(messages, ctx, hostInput, [], systemPrompt, tools, cut);
|
|
544
|
+
const mandatory = system + host, band = decisionBand(ctx, room);
|
|
562
545
|
const before = plannerMeasureFor(ctx)(saved);
|
|
563
546
|
observeBudget(before + mandatory, ctx);
|
|
564
547
|
// Pi's own usage threshold (reason "threshold") counts the last reply's output tokens, reasoning included, plus the messages after
|
|
@@ -580,7 +563,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
580
563
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
581
564
|
// Every cut asked while no run is admitted (an operator's cut) is planned for a run that has not begun: the session has moved on
|
|
582
565
|
// from any run that ended. A retry is inside its run.
|
|
583
|
-
const draft = tuckDraft(tuck, event, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, retain, operatorManual, operatorManual || run?.phase !== "admitted", run?.phase === "admitted" ? protectedPrompt(ctx) : undefined);
|
|
566
|
+
const draft = tuckDraft(tuck, event, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, retain, operatorManual, operatorManual || run?.phase !== "admitted", run?.phase === "admitted" ? protectedPrompt(ctx) : undefined, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
|
|
584
567
|
return draft.compaction ? { draft: true, after: draft.after, compaction: draft.compaction, reserve,
|
|
585
568
|
messages: plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages }
|
|
586
569
|
: { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
@@ -590,12 +573,35 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
590
573
|
let decision: Decision<CutPlan> = decide();
|
|
591
574
|
const { hardLine } = limits(ctx);
|
|
592
575
|
if (!operatorManual && hardLine > room && decision.kind === "fault") {
|
|
593
|
-
decision = fits(before + mandatory, hardLine, ctx) ? { kind: "none" } : decide(hardLine, hardLine)
|
|
594
|
-
decision = clampAboveRoom(decision, ctx, room, hardLine,
|
|
576
|
+
decision = planAboveRoom(hardLine => clampAboveRoom(fits(before + mandatory, hardLine, ctx) ? { kind: "none" } : decide(hardLine, hardLine), ctx, room, hardLine,
|
|
595
577
|
candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
|
|
596
|
-
candidate =>
|
|
578
|
+
candidate => project(candidate.kind === "cut" ? candidate.plan.messages : saved, candidate.kind === "cut"),
|
|
597
579
|
target => target <= room ? decide() : decide(target, target),
|
|
598
|
-
() => deepestDecision(ctx, operatorManual || run?.phase !== "admitted", retain));
|
|
580
|
+
() => deepestDecision(ctx, operatorManual || run?.phase !== "admitted", retain)), ctx);
|
|
581
|
+
}
|
|
582
|
+
const rejected = event.reason === "overflow" && event.willRetry ? run?.rejectedBudget : undefined;
|
|
583
|
+
if (rejected && decision.kind === "cut") {
|
|
584
|
+
const prompt = run?.prompt;
|
|
585
|
+
const canRetry = (candidate: CutPlan) => {
|
|
586
|
+
const messages = project(candidate.messages, true);
|
|
587
|
+
const { estimate, cap, leavesFloor } = requestClamp(messages, ctx);
|
|
588
|
+
const improves = leavesFloor && cap !== undefined && estimate < rejected.input &&
|
|
589
|
+
estimate + cap < rejected.input + rejected.output &&
|
|
590
|
+
fits(requestSystemPart(systemPrompt, tools, messages, systemPrompt) + conversationTokens(messages), hardLine, ctx) &&
|
|
591
|
+
(!prompt || carriesPrompt(messages, prompt.text(ctx.sessionManager.getBranch()), prompt.role));
|
|
592
|
+
recorder.capture("overflow-recovery", "estimated-before-provider-transforms", { rejected, input: estimate, output: cap, improves });
|
|
593
|
+
return improves;
|
|
594
|
+
};
|
|
595
|
+
if (!canRetry(decision.plan)) {
|
|
596
|
+
const previousClips = new Map(clips());
|
|
597
|
+
const deepest = deepestDecision(ctx, false, retain);
|
|
598
|
+
if (deepest.kind !== "cut" || !canRetry(deepest.plan)) {
|
|
599
|
+
restoreClips(previousClips);
|
|
600
|
+
recorder.stop("no-capacity-gain");
|
|
601
|
+
return { cancel: true };
|
|
602
|
+
}
|
|
603
|
+
decision = deepest;
|
|
604
|
+
}
|
|
599
605
|
}
|
|
600
606
|
if (decision.kind === "cut") { return { compaction: captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, event.reason, event.preparation.tokensBefore,
|
|
601
607
|
retain, operatorManual, event.preparation.previousSummary, { response, host, mandatory, target: decision.target, margin: room - band }) }; }
|
|
@@ -623,7 +629,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
623
629
|
pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
|
|
624
630
|
const plannedView = (ctx: ExtensionContext, cut: CutEntry) => {
|
|
625
631
|
const preview = new PendingCut();
|
|
626
|
-
preview.plan(cut, ctx
|
|
632
|
+
preview.plan(cut, ctx);
|
|
627
633
|
return preview.view(ctx);
|
|
628
634
|
};
|
|
629
635
|
// The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
|
|
@@ -647,7 +653,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
647
653
|
}
|
|
648
654
|
}
|
|
649
655
|
const before = measureFor(ctx)(saved);
|
|
650
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before,
|
|
656
|
+
const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before,
|
|
651
657
|
previousSummary: saved.find(message => message.role === "compactionSummary")?.summary, newPrompt, reRenderSummary: true,
|
|
652
658
|
protectedPromptEntryId: newPrompt ? undefined : protectedPrompt(ctx), deepest: true }, ctx, 0, plannerMeasureFor(ctx), options.recallPolicy, retain);
|
|
653
659
|
if (!draft.compaction) return { kind: "fault", capacity: Boolean(draft.capacityRejected), message: draft.unavailable };
|
|
@@ -662,7 +668,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
662
668
|
// and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
|
|
663
669
|
const nativeFloorDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean,
|
|
664
670
|
project: (candidate: Decision<CutPlan>) => Messages): Extract<Decision<CutPlan>, { kind: "cut" }> | undefined => {
|
|
665
|
-
if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.
|
|
671
|
+
if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.lengthRetryPending) return;
|
|
666
672
|
const candidate = deepestDecision(ctx, newPrompt, retain, false);
|
|
667
673
|
if (candidate.kind !== "cut") return;
|
|
668
674
|
const messages = project(candidate);
|
|
@@ -678,7 +684,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
678
684
|
if (standDown(ctx)) return;
|
|
679
685
|
run!.cut.clear();
|
|
680
686
|
run!.nativeFloorPending = false;
|
|
681
|
-
const branchLength = ctx.sessionManager.getBranch().length;
|
|
682
687
|
if (!active()) return;
|
|
683
688
|
access();
|
|
684
689
|
if (!settingsFor().getCompactionSettings(ctx.model).enabled) return;
|
|
@@ -687,7 +692,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
687
692
|
// Public early view only: later handlers, image normalization and tool-loop growth remain the complete-context guard's responsibility.
|
|
688
693
|
const saved = ctx.sessionManager.buildSessionProjection().messages;
|
|
689
694
|
const system = requestSystemPart(observedPrompt, tools, saved, ctx.getSystemPrompt());
|
|
690
|
-
const band = decisionBand(ctx, room
|
|
695
|
+
const band = decisionBand(ctx, room);
|
|
691
696
|
const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
|
|
692
697
|
const incoming = incomingPart + system, mandatory = incoming + host;
|
|
693
698
|
observeBudget(before + mandatory, ctx);
|
|
@@ -707,11 +712,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
707
712
|
// Only a due cut re-renders a summary that sits alone in the session: inside the band a cut is opportunistic, and a smaller summary
|
|
708
713
|
// there buys nothing the request needed and costs history the next recall would have found.
|
|
709
714
|
// A steer joins the admitted run: keep its starting prompt and the unexposed tool round, just as at a tool boundary.
|
|
710
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
715
|
+
const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
711
716
|
newPrompt: !protectedId, protectedPromptEntryId: protectedId, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, Boolean(protectedId));
|
|
712
717
|
if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
713
718
|
const candidate = new PendingCut();
|
|
714
|
-
candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before },
|
|
719
|
+
candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, ctx);
|
|
715
720
|
const messages = candidate.view(ctx).session.buildSessionProjection().messages;
|
|
716
721
|
assertNativeToolRounds(messages);
|
|
717
722
|
return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
|
|
@@ -720,13 +725,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
720
725
|
let decision: Decision<CutPlan> = gate.kind === "plan" ? decide(room, band, gate.opportunistic) : { kind: "defer" };
|
|
721
726
|
const { hardLine } = limits(ctx);
|
|
722
727
|
if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
|
|
723
|
-
decision = fits(before + mandatory, hardLine, ctx) ? { kind: "none" } :
|
|
724
|
-
fits(mandatory, hardLine, ctx) ? decide(hardLine, hardLine, false) : { kind: "defer" }
|
|
725
|
-
decision = clampAboveRoom(decision, ctx, room, hardLine,
|
|
728
|
+
decision = planAboveRoom(hardLine => clampAboveRoom(fits(before + mandatory, hardLine, ctx) ? { kind: "none" } :
|
|
729
|
+
fits(mandatory, hardLine, ctx) ? decide(hardLine, hardLine, false) : { kind: "defer" }, ctx, room, hardLine,
|
|
726
730
|
candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
|
|
727
731
|
candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, candidate.kind === "cut"),
|
|
728
732
|
target => decide(target, target <= room ? band : target, false),
|
|
729
|
-
() => deepestDecision(ctx, !protectedId, Boolean(protectedId)));
|
|
733
|
+
() => deepestDecision(ctx, !protectedId, Boolean(protectedId))), ctx);
|
|
730
734
|
}
|
|
731
735
|
if (decision.kind === "defer") return;
|
|
732
736
|
// An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
|
|
@@ -739,7 +743,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
739
743
|
if (decision.kind === "fault") throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
|
|
740
744
|
const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary,
|
|
741
745
|
{ response, host, mandatory, target: decision.target, margin: room - band });
|
|
742
|
-
run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details },
|
|
746
|
+
run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, ctx);
|
|
743
747
|
};
|
|
744
748
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
745
749
|
if (standDown(ctx)) return;
|
|
@@ -748,7 +752,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
748
752
|
const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
|
|
749
753
|
if (!prompted && !failure()) beginRun("starting");
|
|
750
754
|
run ??= new Run("starting");
|
|
751
|
-
if (!failure() && run.phase !== "starting") run.transition("starting"
|
|
755
|
+
if (!failure() && run.phase !== "starting") run.transition("starting");
|
|
752
756
|
const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
|
|
753
757
|
run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
|
|
754
758
|
try {
|
|
@@ -803,7 +807,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
803
807
|
// saved conversation. Pi's peek returns the steering queue, else the follow-up queue; a follow-up is not in the very next
|
|
804
808
|
// request while tools still run, so it can be counted early: conservative, and nothing else would cut at that later boundary.
|
|
805
809
|
const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
|
|
806
|
-
const band = decisionBand(ctx, room
|
|
810
|
+
const band = decisionBand(ctx, room);
|
|
807
811
|
const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
|
|
808
812
|
const queued = event.context.pendingMessages.length ? conversationTokens(event.context.pendingMessages as Messages) : 0;
|
|
809
813
|
const mandatory = system + host + queued;
|
|
@@ -841,7 +845,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
841
845
|
unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
|
|
842
846
|
plan: (target): Plan<CutPlan> => {
|
|
843
847
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
844
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
|
|
848
|
+
const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
|
|
845
849
|
if (!draft.compaction) {
|
|
846
850
|
// The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
|
|
847
851
|
if (draft.floorMessages && event.toolResults) {
|
|
@@ -888,17 +892,19 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
888
892
|
calibration.estimatedTokens = corrected(before + mandatory, ctx);
|
|
889
893
|
const { hardLine } = limits(ctx);
|
|
890
894
|
if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
895
|
+
decision = planAboveRoom(hardLine => {
|
|
896
|
+
if (fits(before + mandatory, hardLine, ctx)) decision = { kind: "none" };
|
|
897
|
+
else { decision = decide(hardLine, hardLine); tryClips(hardLine, hardLine); }
|
|
898
|
+
return clampAboveRoom(decision, ctx, room, hardLine,
|
|
899
|
+
candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
|
|
900
|
+
candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, event.context.pendingMessages as Messages, ctx.getSystemPrompt(), pi.getActiveTools(), candidate.kind === "cut"),
|
|
901
|
+
target => {
|
|
902
|
+
const targetBand = target <= room ? band : target;
|
|
903
|
+
decision = decide(target, targetBand, target > room);
|
|
904
|
+
tryClips(target, targetBand, target > room);
|
|
905
|
+
return decision;
|
|
906
|
+
}, () => deepestDecision(ctx, false, true));
|
|
907
|
+
}, ctx);
|
|
902
908
|
}
|
|
903
909
|
if (decision.kind === "fault" && reason === "tool-loop") {
|
|
904
910
|
if (decision.capacity) decision = nativeFloorDecision(ctx, false, true,
|
|
@@ -934,7 +940,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
934
940
|
const atBoundary = (event: Boundary, ctx: ExtensionContext, reason: "tool-loop" | "run-end", decide: boolean) => {
|
|
935
941
|
const current = view(ctx);
|
|
936
942
|
if (!current.pending) return decide ? boundaryCut(event, ctx, reason) : undefined;
|
|
937
|
-
const entry = run!.cut.take()!;
|
|
943
|
+
const entry = run!.cut.take(ctx)!;
|
|
938
944
|
const preview = current.session, context: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
|
|
939
945
|
const more = decide && !event.entries.length
|
|
940
946
|
? boundaryCut({ ...event, context: { ...event.context, contextMessages: preview.buildSessionProjection().messages } }, context, reason) : undefined;
|
|
@@ -943,47 +949,66 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
943
949
|
return { entries: [...event.entries as CutEntry[], saved, ...(more?.entries ?? [])] };
|
|
944
950
|
};
|
|
945
951
|
const retryLength = (event: TurnEndEvent, ctx: ExtensionContext) => {
|
|
952
|
+
// Exhausting the full per-request allowance is not evidence that input is too large.
|
|
953
|
+
// Preserve the unfinished response; provider-native continuation owns this case.
|
|
954
|
+
// Native Pi does not compact-and-retry output that reached the catalogue cap.
|
|
955
|
+
if (event.message.role !== "assistant" || !ctx.model) return;
|
|
956
|
+
const stoppedOutput = event.message.usage?.output;
|
|
957
|
+
if (stoppedOutput >= ctx.model.maxTokens) {
|
|
958
|
+
return { entries: event.entries, continue: false };
|
|
959
|
+
}
|
|
946
960
|
// Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
|
|
947
961
|
// Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
|
|
948
962
|
const entries: SessionBoundaryDraft[] = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
|
|
949
963
|
{ type: "context_edit", targetId: event.messageEntryId, replacement: null }];
|
|
950
|
-
if (run!.
|
|
964
|
+
if (!run!.canRetryLength) { markBoundary(entries); return { entries, continue: false }; }
|
|
951
965
|
const preview = liveCut.view(ctx, entries).session;
|
|
952
966
|
const view: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
|
|
953
967
|
const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
|
|
954
|
-
// The deepest cut only when it buys reply room: where Pi's cap on the request as it stands (the stopped reply left out) is already
|
|
955
|
-
// as large as the deepest cut's, the turn is retried uncut, and no history is given up for nothing.
|
|
956
968
|
const asIs = projectedRequest(preview.buildSessionProjection().messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), false);
|
|
957
969
|
const asIsCheck = requestClamp(asIs, view);
|
|
958
970
|
const previousClips = new Map(clips());
|
|
959
971
|
const decision = deepestDecision(view, false, true);
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
972
|
+
const cut = decision.kind === "cut" ? {
|
|
973
|
+
...decision,
|
|
974
|
+
messages: projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true),
|
|
975
|
+
} : undefined;
|
|
976
|
+
const check = cut && requestClamp(cut.messages, view);
|
|
977
|
+
const continuation = `${ctx.model.provider}/${ctx.model.id}` === options.continuationModel;
|
|
978
|
+
// A cut that adds no reply room gives up history for nothing: retry the request uncut.
|
|
979
|
+
if (!continuation && asIsCheck.cap !== undefined && asIsCheck.leavesFloor && (check?.cap === undefined || check.cap <= asIsCheck.cap)) {
|
|
980
|
+
restoreClips(previousClips);
|
|
963
981
|
const { room, hardLine } = limits(view);
|
|
964
|
-
run!.
|
|
982
|
+
run!.requestLengthRetry();
|
|
965
983
|
const drafts = [...entries, { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
|
|
966
|
-
stoppedOutputTokens:
|
|
984
|
+
stoppedOutputTokens: stoppedOutput ?? 0, cut: false,
|
|
967
985
|
piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
|
|
968
986
|
markBoundary(drafts);
|
|
969
987
|
return { entries: drafts, continue: true };
|
|
970
988
|
}
|
|
971
|
-
|
|
972
|
-
|
|
989
|
+
// With a continuation model an unchanged allowance would repeat the same failed generation. If the
|
|
990
|
+
// planner found no history to cut, there is no capacity diagnosis to make.
|
|
991
|
+
if (!cut || check?.cap === undefined || asIsCheck.cap === undefined || check.cap <= (continuation ? Math.max(asIsCheck.cap, stoppedOutput ?? 0) : asIsCheck.cap)) {
|
|
992
|
+
restoreClips(previousClips);
|
|
993
|
+
if (!asIsCheck.leavesFloor) {
|
|
994
|
+
if (check && !check.leavesFloor) throw new CapacityError(clampMessage);
|
|
995
|
+
if (decision.kind === "fault" && decision.capacity) throw new CapacityError(decision.message);
|
|
996
|
+
}
|
|
997
|
+
markBoundary(entries);
|
|
998
|
+
return { entries, continue: false };
|
|
999
|
+
}
|
|
1000
|
+
const { messages } = cut;
|
|
973
1001
|
if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role)) throw promptRefusal();
|
|
974
1002
|
const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
|
975
|
-
const tokens = system + conversationTokens(messages)
|
|
1003
|
+
const tokens = system + conversationTokens(messages);
|
|
976
1004
|
const { response, room, hardLine } = limits(view);
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
const compaction = captureDraft(decision.plan.compaction, view, decision.plan.reserve, "length-retry", tokens, true, false, undefined,
|
|
982
|
-
{ response, host, mandatory: system + host + conversationTokens(event.context.pendingMessages), target: decision.target, margin: room - decisionBand(view, room, system) });
|
|
983
|
-
run!.thinkingRetryPending = true;
|
|
1005
|
+
if (!fits(tokens, hardLine, view) || !check.leavesFloor) throw new CapacityError(clampMessage);
|
|
1006
|
+
const compaction = captureDraft(cut.plan.compaction, view, cut.plan.reserve, "length-retry", tokens, true, false, undefined,
|
|
1007
|
+
{ response, host, mandatory: system + host + conversationTokens(event.context.pendingMessages), target: cut.target, margin: room - decisionBand(view, room) });
|
|
1008
|
+
run!.requestLengthRetry();
|
|
984
1009
|
const drafts = [...entries, { type: "compaction" as const, summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId || null, details: compaction.details },
|
|
985
1010
|
{ type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
|
|
986
|
-
stoppedOutputTokens:
|
|
1011
|
+
stoppedOutputTokens: stoppedOutput ?? 0, cut: true,
|
|
987
1012
|
estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
|
|
988
1013
|
markBoundary(drafts);
|
|
989
1014
|
return { entries: drafts, continue: true };
|
|
@@ -992,9 +1017,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
992
1017
|
try {
|
|
993
1018
|
if (standDown(ctx)) return;
|
|
994
1019
|
if (!active() || run?.phase !== "admitted") return;
|
|
995
|
-
if (
|
|
1020
|
+
if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
|
|
996
1021
|
return retryLength(event, ctx);
|
|
997
|
-
run.
|
|
1022
|
+
run.finishLengthRetry();
|
|
998
1023
|
const decide = event.outcome === "completed" && !ctx.signal?.aborted && event.context.canContinue && event.toolResults.length > 0 &&
|
|
999
1024
|
settingsFor().getCompactionSettings(ctx.model).enabled;
|
|
1000
1025
|
if (!view(ctx).pending && !decide) return;
|
|
@@ -1034,7 +1059,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1034
1059
|
const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): { messages: Messages; native?: boolean } => {
|
|
1035
1060
|
const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
|
|
1036
1061
|
const before = conversationTokens(source), mandatory = tokens - before;
|
|
1037
|
-
const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room
|
|
1062
|
+
const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room);
|
|
1038
1063
|
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
1039
1064
|
const previousClips = new Map(clips());
|
|
1040
1065
|
const measure = measureFor(ctx);
|
|
@@ -1043,7 +1068,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1043
1068
|
unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
|
|
1044
1069
|
plan: (target): Plan<CutPlan> => {
|
|
1045
1070
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
1046
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
1071
|
+
const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
1047
1072
|
protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
|
|
1048
1073
|
if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
1049
1074
|
const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
@@ -1057,9 +1082,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1057
1082
|
const total = (candidate: Decision<CutPlan>) => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory;
|
|
1058
1083
|
let decision = decide(room, band);
|
|
1059
1084
|
if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
|
|
1060
|
-
decision = decide(hardLine, hardLine)
|
|
1061
|
-
|
|
1062
|
-
target => decide(target, target <= room ? band : target), () => deepestDecision(ctx, false, true));
|
|
1085
|
+
decision = planAboveRoom(hardLine => clampAboveRoom(decide(hardLine, hardLine), ctx, room, hardLine, total, project,
|
|
1086
|
+
target => decide(target, target <= room ? band : target), () => deepestDecision(ctx, false, true)), ctx);
|
|
1063
1087
|
}
|
|
1064
1088
|
const accepts = (candidate: Decision<CutPlan>) => {
|
|
1065
1089
|
if (candidate.kind !== "cut" || candidate.plan.after >= before) return false;
|
|
@@ -1070,7 +1094,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1070
1094
|
if (!accepts(decision)) decision = deepestDecision(ctx, false, true);
|
|
1071
1095
|
let native = false;
|
|
1072
1096
|
if (decision.kind !== "cut" || !accepts(decision)) {
|
|
1073
|
-
|
|
1097
|
+
restoreClips(previousClips);
|
|
1074
1098
|
const floor = nativeFloorDecision(ctx, false, true, project);
|
|
1075
1099
|
if (!floor) return { messages };
|
|
1076
1100
|
decision = floor;
|
|
@@ -1079,7 +1103,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1079
1103
|
if (decision.kind !== "cut") return { messages };
|
|
1080
1104
|
const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary,
|
|
1081
1105
|
{ response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
|
|
1082
|
-
run!.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx
|
|
1106
|
+
run!.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx);
|
|
1083
1107
|
run!.nativeFloorPending = native;
|
|
1084
1108
|
syncHistoryTools(ctx);
|
|
1085
1109
|
return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
|
|
@@ -1123,7 +1147,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1123
1147
|
// Pi commits these entries before the run settles.
|
|
1124
1148
|
try {
|
|
1125
1149
|
if (!active() || run?.phase !== "admitted" || failure() || !settingsFor().getCompactionSettings(ctx.model).enabled) return;
|
|
1126
|
-
const decide = event.outcome === "completed" && !ctx.signal?.aborted;
|
|
1150
|
+
const decide = event.outcome === "completed" && !ctx.signal?.aborted && lengthStop?.kind !== "thinking";
|
|
1127
1151
|
if (view(ctx).pending ? event.outcome === "error" : !decide) return;
|
|
1128
1152
|
return atBoundary(event, ctx, "run-end", decide);
|
|
1129
1153
|
} catch (error) { fail(error, ctx); }
|
|
@@ -1131,7 +1155,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1131
1155
|
pi.on("context_with_system", (event, ctx) => {
|
|
1132
1156
|
if (standDown(ctx)) return;
|
|
1133
1157
|
// Reaching the next request boundary proves native commit returned, not durable storage.
|
|
1134
|
-
if (run) {
|
|
1158
|
+
if (run) {
|
|
1159
|
+
run.pendingBoundaryReceipts = [];
|
|
1160
|
+
run.rejectedBudget = undefined;
|
|
1161
|
+
}
|
|
1135
1162
|
calibration.pending = undefined;
|
|
1136
1163
|
try {
|
|
1137
1164
|
if (!active()) return;
|