pi-tuck 1.1.0 → 1.1.2
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 +42 -0
- package/README.md +10 -3
- package/dist/index.js +2 -0
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +21 -1
- package/dist/src/compaction.js +203 -106
- package/dist/src/diagnostics.d.ts +1 -1
- package/dist/src/run.d.ts +14 -7
- package/dist/src/run.js +57 -2
- package/dist/src/semantic-recall.d.ts +2 -0
- package/dist/src/semantic-recall.js +53 -6
- package/dist/src/status.d.ts +1 -0
- package/dist/src/status.js +2 -0
- package/index.ts +1 -0
- package/package.json +1 -1
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +163 -86
- package/src/run.ts +48 -13
- package/src/semantic-recall.ts +28 -3
- package/src/status.ts +2 -0
package/dist/src/compaction.js
CHANGED
|
@@ -55,6 +55,15 @@ class CommitFault extends Error {
|
|
|
55
55
|
/** A refusal for want of room, which the user can remedy: it carries advice. */
|
|
56
56
|
class CapacityError extends Refusal {
|
|
57
57
|
}
|
|
58
|
+
function notify(ctx, message, level) {
|
|
59
|
+
try {
|
|
60
|
+
if (ctx.hasUI === false)
|
|
61
|
+
process.stderr.write(message + "\n");
|
|
62
|
+
else
|
|
63
|
+
ctx.ui.notify(message, level);
|
|
64
|
+
}
|
|
65
|
+
catch { /* ended */ }
|
|
66
|
+
}
|
|
58
67
|
/** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
|
|
59
68
|
* likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
|
|
60
69
|
export const refusalNotice = (message, factor) => message + "; shorten the input, use a model with a larger window, or lower Pi's compaction.reserveTokens, then retry." +
|
|
@@ -82,7 +91,8 @@ function initialWindow(key) {
|
|
|
82
91
|
return [1];
|
|
83
92
|
}
|
|
84
93
|
}
|
|
85
|
-
|
|
94
|
+
export const CALIBRATION_RECEIPT = 'pi-tuck-calibration';
|
|
95
|
+
/** The calibration window a session starts with under accounting identity `key`: the newest calibration entry or compaction on the branch that carries this package's
|
|
86
96
|
* receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
|
|
87
97
|
* Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
|
|
88
98
|
* [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
|
|
@@ -91,12 +101,16 @@ function initialWindow(key) {
|
|
|
91
101
|
export function seedWindow(branch, key) {
|
|
92
102
|
for (let i = branch.length; i--;) {
|
|
93
103
|
const entry = branch[i];
|
|
94
|
-
const receipt = entry.type === "
|
|
104
|
+
const receipt = entry.type === "custom" && entry.customType === CALIBRATION_RECEIPT ? { settings: entry.data }
|
|
105
|
+
: entry.type === "compaction" ? entry.details?.diagnosticReceipt : undefined;
|
|
95
106
|
if (receipt === undefined)
|
|
96
107
|
continue;
|
|
97
108
|
const { calibrationIdentity, calibrationFactor, calibrationWindow } = receipt?.settings ?? {}, stored = calibrationWindow;
|
|
98
|
-
if (calibrationIdentity !== key)
|
|
109
|
+
if (calibrationIdentity !== key) {
|
|
110
|
+
if (entry.type === "custom")
|
|
111
|
+
continue; // Another model's new observation does not hide this model's last saved seed.
|
|
99
112
|
return initialWindow(key);
|
|
113
|
+
}
|
|
100
114
|
if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
|
|
101
115
|
return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
|
|
102
116
|
if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor))
|
|
@@ -105,6 +119,61 @@ export function seedWindow(branch, key) {
|
|
|
105
119
|
}
|
|
106
120
|
return initialWindow(key);
|
|
107
121
|
}
|
|
122
|
+
/** One accounting owner. Session start still defers receipt loading until the first budget read;
|
|
123
|
+
* tree moves load immediately, and identity changes keep any uncommitted window observation. */
|
|
124
|
+
class Calibration {
|
|
125
|
+
identity = '';
|
|
126
|
+
factor = 1;
|
|
127
|
+
ratios = [];
|
|
128
|
+
learnedContextWindow;
|
|
129
|
+
windowObservation;
|
|
130
|
+
pending;
|
|
131
|
+
lastCeiling = null;
|
|
132
|
+
estimatedTokens = 0;
|
|
133
|
+
seededIdentity = '';
|
|
134
|
+
static key(ctx) { return ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : ''; }
|
|
135
|
+
/** Model selection itself never reloads receipts: switching away and back without a request keeps the learned window. */
|
|
136
|
+
select(ctx) { this.identity = Calibration.key(ctx); }
|
|
137
|
+
needsSeed(ctx) { return this.seededIdentity !== Calibration.key(ctx); }
|
|
138
|
+
reseed(ctx, reason) {
|
|
139
|
+
this.identity = Calibration.key(ctx);
|
|
140
|
+
this.pending = undefined;
|
|
141
|
+
if (reason !== 'identity')
|
|
142
|
+
this.windowObservation = undefined;
|
|
143
|
+
if (reason === 'session') {
|
|
144
|
+
this.factor = 1;
|
|
145
|
+
this.learnedContextWindow = undefined;
|
|
146
|
+
this.estimatedTokens = 0;
|
|
147
|
+
// Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
|
|
148
|
+
this.seededIdentity = '';
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
this.seededIdentity = this.identity;
|
|
152
|
+
if (reason === 'tree' && !this.identity)
|
|
153
|
+
return;
|
|
154
|
+
const branch = ctx.sessionManager.getBranch();
|
|
155
|
+
this.ratios = seedWindow(branch, this.identity);
|
|
156
|
+
this.factor = Math.max(1, ...this.ratios);
|
|
157
|
+
this.learnedContextWindow = seedContextWindow(branch, this.identity);
|
|
158
|
+
}
|
|
159
|
+
learn(value, ctx, append) {
|
|
160
|
+
this.ratios.push(value);
|
|
161
|
+
if (this.ratios.length > CALIBRATION_WINDOW)
|
|
162
|
+
this.ratios.shift();
|
|
163
|
+
this.factor = Math.max(1, ...this.ratios);
|
|
164
|
+
// D7: compare what a cold instance would seed, including the existing clamps.
|
|
165
|
+
if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), this.identity), this.ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
|
|
166
|
+
append(CALIBRATION_RECEIPT, { calibrationIdentity: this.identity, calibrationWindow: [...this.ratios] });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
|
|
170
|
+
export function compactionState(model, enabled) {
|
|
171
|
+
const reason = !enabled ? "compaction is disabled" : model?.api === "pi-virtual" ? "pi-virtual model" : !model ? undefined
|
|
172
|
+
: model.contextWindow === undefined ? "context window is missing"
|
|
173
|
+
: !Number.isFinite(model.contextWindow) ? "context window is not finite"
|
|
174
|
+
: model.contextWindow <= 0 ? "context window is zero or negative" : undefined;
|
|
175
|
+
return reason ? { kind: "standingDown", reason } : { kind: "active" };
|
|
176
|
+
}
|
|
108
177
|
export async function installCompaction(pi, options = {}) {
|
|
109
178
|
const piMath = await loadPiRequestMath();
|
|
110
179
|
const piMargin = options.requestReserve ? 0 : await piContextSafetyMargin(piMath);
|
|
@@ -145,7 +214,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
145
214
|
}
|
|
146
215
|
});
|
|
147
216
|
const captureDraft = (draft, ctx, reserve, reason, tokensBefore, retainCurrentInput, operatorManual, previousSummary, budget) => recorder.measureInline(() => {
|
|
148
|
-
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: factor, calibrationWindow: [...ratios], calibrationIdentity: identity, learnedContextWindow, activeInputCeilingTokens: lastCeiling });
|
|
217
|
+
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, learnedContextWindow: calibration.learnedContextWindow, activeInputCeilingTokens: calibration.lastCeiling });
|
|
149
218
|
proposalId = receiptId(attached);
|
|
150
219
|
if (recorder.enabled) {
|
|
151
220
|
try {
|
|
@@ -174,7 +243,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
174
243
|
} });
|
|
175
244
|
pi.on("session_compact", (_event, ctx) => observe(ctx));
|
|
176
245
|
// A saved cut moves entries out of view: index them now, in the background, even for a session that has not searched or whose worker the idle limit stopped.
|
|
177
|
-
pi.on("session_compact", (_event, ctx) => {
|
|
246
|
+
pi.on("session_compact", (_event, ctx) => { if (!standDown(ctx))
|
|
247
|
+
semantic.indexAtCut(semanticProvider(ctx)); });
|
|
178
248
|
pi.on("session_shutdown", async () => { semanticRequest++; recorder.stop("session-shutdown"); await semantic.close(); await Promise.allSettled([...semanticPending]); });
|
|
179
249
|
pi.on("session_start", () => { semanticRequest++; semanticTransition = semantic.close(); void semanticTransition.catch(error => { options.fail?.(error); }); });
|
|
180
250
|
pi.on("turn_end", (_event, ctx) => { semantic.schedule(semanticProvider(ctx)); });
|
|
@@ -226,71 +296,82 @@ export async function installCompaction(pi, options = {}) {
|
|
|
226
296
|
} });
|
|
227
297
|
pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
|
|
228
298
|
const state = semantic.status();
|
|
229
|
-
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
|
|
299
|
+
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
|
|
230
300
|
} });
|
|
231
301
|
// Pi's native start/settled events bracket the run and its post-turn cuts.
|
|
232
302
|
let run;
|
|
233
|
-
// A
|
|
234
|
-
|
|
235
|
-
const failure = () => commitFault ?? run?.failure;
|
|
303
|
+
// A commit-failed phase survives attempts/tree moves until session_start: native memory may be ahead of disk.
|
|
304
|
+
const failure = () => run?.phase === "failed" || run?.phase === "commit-failed" ? run.error : undefined;
|
|
236
305
|
const protectedPrompt = (ctx) => run?.prompt?.id(ctx.sessionManager.getBranch());
|
|
237
306
|
const clips = () => run?.clips ?? emptyClips;
|
|
238
307
|
const emptyClips = new Map();
|
|
239
|
-
const resetRun = () => {
|
|
308
|
+
const resetRun = (session = false) => {
|
|
309
|
+
if (!session && run?.phase === "commit-failed")
|
|
310
|
+
run.clear();
|
|
311
|
+
else
|
|
312
|
+
run = undefined;
|
|
313
|
+
calibration.pending = undefined;
|
|
314
|
+
};
|
|
315
|
+
const beginRun = (phase) => {
|
|
316
|
+
if (run?.phase === "commit-failed")
|
|
317
|
+
run.clear();
|
|
318
|
+
else
|
|
319
|
+
run = createRun(phase);
|
|
320
|
+
};
|
|
321
|
+
const stateFor = (ctx) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
|
|
322
|
+
// A prerequisite can change with the model/settings; discard the old plan before returning control to native.
|
|
323
|
+
const standDown = (ctx) => {
|
|
324
|
+
if (stateFor(ctx).kind === "active")
|
|
325
|
+
return false;
|
|
326
|
+
resetRun();
|
|
327
|
+
calibration.windowObservation = undefined;
|
|
328
|
+
lengthStop = false;
|
|
329
|
+
return true;
|
|
330
|
+
};
|
|
240
331
|
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");
|
|
241
|
-
|
|
242
|
-
// One serial request, one accounting identity; observations never certify new content. A new identity (the first request after a session
|
|
243
|
-
// start, or a model switch) starts with the window its branch's newest receipt recorded for that identity, else that receipt's factor, else the model's measured undercount or 1 (`seedWindow`).
|
|
244
|
-
let identity = "", factor = 1, ratios = [];
|
|
245
|
-
let learnedContextWindow;
|
|
332
|
+
const calibration = new Calibration();
|
|
246
333
|
const serverClipped = new WeakSet();
|
|
247
|
-
let windowObservation;
|
|
248
|
-
let lastCeiling = null;
|
|
249
|
-
let pending;
|
|
250
334
|
const identityFor = (ctx) => {
|
|
251
|
-
|
|
252
|
-
if (
|
|
253
|
-
identity
|
|
254
|
-
|
|
255
|
-
factor = Math.max(1, ...ratios);
|
|
256
|
-
learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), key);
|
|
257
|
-
pending = undefined;
|
|
258
|
-
}
|
|
259
|
-
return key;
|
|
335
|
+
calibration.select(ctx);
|
|
336
|
+
if (calibration.needsSeed(ctx))
|
|
337
|
+
calibration.reseed(ctx, "identity");
|
|
338
|
+
return calibration.identity;
|
|
260
339
|
};
|
|
340
|
+
pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
|
|
261
341
|
const contextWindow = (ctx) => {
|
|
262
342
|
identityFor(ctx);
|
|
263
|
-
return Math.min(ctx.model?.contextWindow ?? 0, learnedContextWindow ?? Infinity);
|
|
343
|
+
return Math.min(ctx.model?.contextWindow ?? 0, calibration.learnedContextWindow ?? Infinity);
|
|
264
344
|
};
|
|
265
345
|
// This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
|
|
266
346
|
// An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
|
|
267
347
|
pi.on("before_provider_request", event => {
|
|
268
|
-
if (!pending || !event.payload || typeof event.payload !== "object")
|
|
348
|
+
if (!calibration.pending || !event.payload || typeof event.payload !== "object")
|
|
269
349
|
return;
|
|
270
350
|
const payload = event.payload;
|
|
271
351
|
// Read at reply time so later in-place payload edits are included too.
|
|
272
|
-
pending.requestedMaxTokens = () => {
|
|
352
|
+
calibration.pending.requestedMaxTokens = () => {
|
|
273
353
|
const cap = payload.max_tokens ?? payload.max_completion_tokens ?? payload.max_output_tokens;
|
|
274
354
|
return typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0 ? cap : undefined;
|
|
275
355
|
};
|
|
276
356
|
});
|
|
277
357
|
// 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.
|
|
278
|
-
const learn = (value) =>
|
|
279
|
-
|
|
280
|
-
const corrected = (tokens, ctx) => { identityFor(ctx); return Math.ceil(tokens * factor); };
|
|
358
|
+
const learn = (value, ctx) => calibration.learn(value, ctx, (kind, data) => pi.appendEntry(kind, data));
|
|
359
|
+
const corrected = (tokens, ctx) => { identityFor(ctx); return Math.ceil(tokens * calibration.factor); };
|
|
281
360
|
const observeBudget = (rawTokens, ctx) => {
|
|
282
361
|
if (options.observeBudget)
|
|
283
|
-
options.observeBudget({ rawTokens, tokens: corrected(rawTokens, ctx), factor, ...limits(ctx), context: ctx });
|
|
362
|
+
options.observeBudget({ rawTokens, tokens: corrected(rawTokens, ctx), factor: calibration.factor, ...limits(ctx), context: ctx });
|
|
284
363
|
};
|
|
285
364
|
// The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
|
|
286
365
|
const planReserve = (target, room, band, mandatory, ctx) => {
|
|
287
366
|
identityFor(ctx);
|
|
288
367
|
// The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
|
|
289
|
-
return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, factor, mandatory);
|
|
368
|
+
return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, calibration.factor, mandatory);
|
|
290
369
|
};
|
|
291
370
|
pi.on("message_end", (event, ctx) => {
|
|
292
371
|
if (event.message.role !== "assistant")
|
|
293
372
|
return;
|
|
373
|
+
if (standDown(ctx))
|
|
374
|
+
return;
|
|
294
375
|
const responseMessage = event.message;
|
|
295
376
|
if (recorder.enabled && !recorder.waitingForCut)
|
|
296
377
|
recorder.measureInline(() => {
|
|
@@ -300,8 +381,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
300
381
|
recorder.capture("response-actions", "hidden-material-excluded", { stopReason: responseMessage.stopReason }, true);
|
|
301
382
|
recorder.responded(responseMessage.stopReason);
|
|
302
383
|
});
|
|
303
|
-
const paired = pending;
|
|
304
|
-
pending = undefined;
|
|
384
|
+
const paired = calibration.pending;
|
|
385
|
+
calibration.pending = undefined;
|
|
305
386
|
const key = identityFor(ctx), message = event.message;
|
|
306
387
|
const overflow = message.stopReason === "error" && isContextOverflow(message);
|
|
307
388
|
if (!paired || !key || paired.identity !== key || !active() || failure() || ctx.signal?.aborted || (message.errorMessage && !overflow) ||
|
|
@@ -316,9 +397,9 @@ export async function installCompaction(pi, options = {}) {
|
|
|
316
397
|
if (overflow) {
|
|
317
398
|
const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
|
|
318
399
|
const learned = bound <= CALIBRATION_CEILING;
|
|
319
|
-
|
|
400
|
+
notify(ctx, overflowNotice(window, bound, learned), "warning");
|
|
320
401
|
if (learned)
|
|
321
|
-
learn(bound);
|
|
402
|
+
learn(bound, ctx);
|
|
322
403
|
return;
|
|
323
404
|
}
|
|
324
405
|
const usage = message.usage;
|
|
@@ -332,50 +413,48 @@ export async function installCompaction(pi, options = {}) {
|
|
|
332
413
|
if (message.stopReason === "length" && requested !== undefined &&
|
|
333
414
|
Number.isSafeInteger(output) && output >= 0 && output < requested &&
|
|
334
415
|
Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
|
|
335
|
-
learnedContextWindow = Math.min(learnedContextWindow ?? Infinity, bound);
|
|
416
|
+
calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
|
|
336
417
|
serverClipped.add(message);
|
|
337
|
-
windowObservation = { message, identity: key, window: learnedContextWindow };
|
|
418
|
+
calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow };
|
|
338
419
|
}
|
|
339
420
|
// A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
|
|
340
421
|
// 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
|
|
341
422
|
// 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.
|
|
342
423
|
if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio))
|
|
343
|
-
learn(ratio);
|
|
424
|
+
learn(ratio, ctx);
|
|
344
425
|
});
|
|
345
|
-
pi.on("turn_end", event => {
|
|
346
|
-
if (
|
|
426
|
+
pi.on("turn_end", (event, ctx) => {
|
|
427
|
+
if (standDown(ctx))
|
|
428
|
+
return;
|
|
429
|
+
if (calibration.windowObservation?.message !== event.message)
|
|
347
430
|
return;
|
|
348
|
-
const observation = windowObservation;
|
|
349
|
-
windowObservation = undefined;
|
|
431
|
+
const observation = calibration.windowObservation;
|
|
432
|
+
calibration.windowObservation = undefined;
|
|
350
433
|
pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
|
|
351
434
|
serverClippedReplyId: event.messageEntryId });
|
|
352
435
|
});
|
|
353
436
|
// 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
|
|
354
437
|
// extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
|
|
355
438
|
let lengthStop = false;
|
|
356
|
-
pi.on("agent_start", () => {
|
|
439
|
+
pi.on("agent_start", (_event, ctx) => { if (standDown(ctx))
|
|
440
|
+
return; run ??= createRun("starting"); if (!failure())
|
|
441
|
+
run.transition("admitted", ctx); run.thinkingRetryPending = false; lengthStop = false; calibration.pending = undefined; });
|
|
357
442
|
pi.on("message_end", event => { if (event.message.role === "assistant")
|
|
358
443
|
lengthStop = event.message.stopReason === "length"; });
|
|
359
444
|
pi.on("agent_settled", (_event, ctx) => {
|
|
360
445
|
try {
|
|
361
|
-
if (!lengthStop || !active())
|
|
446
|
+
if (standDown(ctx) || !lengthStop || !active())
|
|
362
447
|
return;
|
|
363
448
|
lengthStop = false;
|
|
364
449
|
const message = "pi-tuck: the last reply stopped at the model's output limit and may be cut off. Ask the agent to continue.";
|
|
365
|
-
|
|
366
|
-
if (ctx.hasUI === false)
|
|
367
|
-
process.stderr.write(message + "\n");
|
|
368
|
-
else
|
|
369
|
-
ctx.ui.notify(message, "warning");
|
|
370
|
-
}
|
|
371
|
-
catch { /* ended */ }
|
|
450
|
+
notify(ctx, message, "warning");
|
|
372
451
|
}
|
|
373
452
|
finally {
|
|
374
453
|
resetRun();
|
|
375
454
|
}
|
|
376
455
|
});
|
|
377
456
|
const active = () => options.active?.() ?? true;
|
|
378
|
-
const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings());
|
|
457
|
+
const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings?.());
|
|
379
458
|
// The one reserve decision; every consumer takes its room from limits. Standalone starts at Pi's native cut point. Once a reply did
|
|
380
459
|
// not fit (a length stop with text/tools, or a refusal pi-ai classes as a context overflow), hold the catalogue maximum too. A thinking-only
|
|
381
460
|
// length stop uses branchReplyFloor's observed output instead; reserving the catalogue maximum would strand setups above the room.
|
|
@@ -392,7 +471,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
392
471
|
const inputRoom = (response, ctx) => {
|
|
393
472
|
const configured = options.activeInputTokens;
|
|
394
473
|
const ceiling = typeof configured === "function" ? configured(ctx) : configured;
|
|
395
|
-
lastCeiling = ceiling ?? null;
|
|
474
|
+
calibration.lastCeiling = ceiling ?? null;
|
|
396
475
|
if (ceiling !== undefined && (!Number.isSafeInteger(ceiling) || ceiling <= 0))
|
|
397
476
|
throw new Error("Invalid active-input token ceiling");
|
|
398
477
|
return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
|
|
@@ -401,14 +480,14 @@ export async function installCompaction(pi, options = {}) {
|
|
|
401
480
|
const limits = (ctx) => {
|
|
402
481
|
const { response } = requestReserve(ctx), room = inputRoom(response, ctx);
|
|
403
482
|
const floor = options.requestReserve ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model?.maxTokens);
|
|
404
|
-
const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), lastCeiling ?? Infinity);
|
|
483
|
+
const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
|
|
405
484
|
return { response, room, hardLine, replyFloor: floor };
|
|
406
485
|
};
|
|
407
486
|
const decisionBand = (ctx, room, system, current = view(ctx)) => {
|
|
408
487
|
const last = current.session.getBranch().findLast(entry => entry.type === "compaction");
|
|
409
488
|
const after = last?.type === "compaction" ? last.details?.tokensAfter : undefined;
|
|
410
489
|
return bandOf(room, cutAt, options.cutAt === undefined && typeof after === "number" && Number.isFinite(after) && after >= 0
|
|
411
|
-
? { system, tokensAfter: after, factor } : undefined);
|
|
490
|
+
? { system, tokensAfter: after, factor: calibration.factor } : undefined);
|
|
412
491
|
};
|
|
413
492
|
const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
|
|
414
493
|
// The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
|
|
@@ -486,22 +565,21 @@ export async function installCompaction(pi, options = {}) {
|
|
|
486
565
|
({ room, hardLine } = limits(ctx));
|
|
487
566
|
}
|
|
488
567
|
catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
|
|
489
|
-
pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens, room, hardLine, buildId: BUILD_ID });
|
|
568
|
+
pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID });
|
|
490
569
|
};
|
|
491
570
|
const fail = (error, ctx) => {
|
|
492
571
|
recorder.stop("native-attempt-failed");
|
|
493
572
|
// 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
|
|
494
573
|
// means for the session, anything else as it is (an attempt that ended with no word looked like a hang).
|
|
495
|
-
const previous = failure(),
|
|
574
|
+
const previous = failure(), shouldNotify = !previous;
|
|
496
575
|
const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
|
|
497
576
|
const receipted = run?.refusalReceipted;
|
|
498
|
-
|
|
499
|
-
// Keep
|
|
500
|
-
run
|
|
501
|
-
run.
|
|
577
|
+
calibration.pending = undefined;
|
|
578
|
+
// Keep the same terminal run until Pi settles; later start hooks cannot admit it.
|
|
579
|
+
run ??= createRun("starting");
|
|
580
|
+
run.clear();
|
|
581
|
+
run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", ctx, fault);
|
|
502
582
|
run.refusalReceipted = true;
|
|
503
|
-
if (fault instanceof CommitFault)
|
|
504
|
-
commitFault = fault;
|
|
505
583
|
try {
|
|
506
584
|
if (!receipted)
|
|
507
585
|
receipt("refusal", fault.message, ctx);
|
|
@@ -509,8 +587,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
509
587
|
}
|
|
510
588
|
finally {
|
|
511
589
|
try {
|
|
512
|
-
if (
|
|
513
|
-
|
|
590
|
+
if (shouldNotify)
|
|
591
|
+
notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
|
|
514
592
|
? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
|
|
515
593
|
: `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error");
|
|
516
594
|
}
|
|
@@ -527,7 +605,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
527
605
|
pi.on("input", async (event, ctx) => {
|
|
528
606
|
if (!ctx.isIdle() || run?.phase === "starting")
|
|
529
607
|
return; // steering joins the existing run
|
|
530
|
-
|
|
608
|
+
beginRun("decided");
|
|
531
609
|
const decision = run;
|
|
532
610
|
try {
|
|
533
611
|
syncHistoryTools(ctx);
|
|
@@ -539,8 +617,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
539
617
|
}
|
|
540
618
|
// Pi normally reaches its pre-run threshold check within microtasks. Auth I/O or a later extension's input I/O can make a
|
|
541
619
|
// real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
|
|
542
|
-
setImmediate(() => { if (run === decision &&
|
|
543
|
-
decision.expired
|
|
620
|
+
setImmediate(() => { if (run === decision && decision.phase === "decided")
|
|
621
|
+
decision.transition("expired", ctx); });
|
|
544
622
|
});
|
|
545
623
|
pi.registerTool({
|
|
546
624
|
name: "tuck_recall", label: "pi-tuck history", parameters: RecallInput,
|
|
@@ -610,6 +688,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
610
688
|
} });
|
|
611
689
|
pi.on("session_before_compact", (event, ctx) => {
|
|
612
690
|
try {
|
|
691
|
+
if (standDown(ctx))
|
|
692
|
+
return;
|
|
613
693
|
if (!active())
|
|
614
694
|
return { cancel: true };
|
|
615
695
|
if (event.signal.aborted || ctx.signal?.aborted) {
|
|
@@ -618,8 +698,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
618
698
|
}
|
|
619
699
|
// Pi checks its own threshold after a prompt's input and before the run starts: the prompt's cut, planned with the prompt counted,
|
|
620
700
|
// is the answer, and it is saved before the first request.
|
|
621
|
-
if (run?.phase === "decided"
|
|
622
|
-
run.claimed
|
|
701
|
+
if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
|
|
702
|
+
run.transition("claimed", ctx);
|
|
623
703
|
if (view(ctx).pending) {
|
|
624
704
|
access();
|
|
625
705
|
const current = view(ctx), { type: _, ...compaction } = run.cut.take();
|
|
@@ -633,7 +713,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
633
713
|
// pi-tuck's summary is built from the session itself, so text after /compact cannot steer it. The operator asked for a cut: make the one
|
|
634
714
|
// plain /compact makes and say the text was not used, rather than cancel (which Pi shows as an error, with no cut).
|
|
635
715
|
if (event.customInstructions?.trim())
|
|
636
|
-
|
|
716
|
+
notify(ctx, "pi-tuck: /compact ignores the text after it, since pi-tuck builds its summary from the session itself. Cutting as plain /compact does.", "info");
|
|
637
717
|
const { response, room } = limits(ctx);
|
|
638
718
|
const retain = operatorManual || run?.phase === "admitted";
|
|
639
719
|
// A cut Pi asks for (an operator's /compact, Pi's threshold or overflow recovery) charges what the request must carry whatever is
|
|
@@ -670,7 +750,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
670
750
|
: { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
671
751
|
},
|
|
672
752
|
});
|
|
673
|
-
estimatedTokens = corrected(before + mandatory, ctx);
|
|
753
|
+
calibration.estimatedTokens = corrected(before + mandatory, ctx);
|
|
674
754
|
let decision = decide();
|
|
675
755
|
const { hardLine } = limits(ctx);
|
|
676
756
|
if (!operatorManual && hardLine > room && decision.kind === "fault") {
|
|
@@ -684,7 +764,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
684
764
|
if (decision.kind === "none" || decision.kind === "defer")
|
|
685
765
|
return { cancel: true };
|
|
686
766
|
recorder.stop("no-cut");
|
|
687
|
-
|
|
767
|
+
notify(ctx, decision.message, "warning");
|
|
688
768
|
if (operatorManual)
|
|
689
769
|
receipt("refusal", decision.message, ctx);
|
|
690
770
|
if (!operatorManual)
|
|
@@ -700,23 +780,23 @@ export async function installCompaction(pi, options = {}) {
|
|
|
700
780
|
}
|
|
701
781
|
}
|
|
702
782
|
});
|
|
703
|
-
pi.on("session_before_tree", (event) => event.preparation.userWantsSummary ? { cancel: true } : undefined);
|
|
704
|
-
pi.on("session_start", () => { resetRun(); recorder.stop("session-transition"); proposalId = undefined;
|
|
705
|
-
const historyToolsEnabled = (ctx) => view(ctx).hasTuckCut;
|
|
783
|
+
pi.on("session_before_tree", (event, ctx) => !standDown(ctx) && event.preparation.userWantsSummary ? { cancel: true } : undefined);
|
|
784
|
+
pi.on("session_start", (_event, ctx) => { resetRun(true); recorder.stop("session-transition"); proposalId = undefined; calibration.reseed(ctx, "session"); });
|
|
785
|
+
const historyToolsEnabled = (ctx) => stateFor(ctx).kind === "active" && view(ctx).hasTuckCut;
|
|
706
786
|
const syncHistoryTools = (ctx) => { if (active())
|
|
707
787
|
applyHistoryTools(pi, historyToolsEnabled(ctx)); };
|
|
708
788
|
pi.on("session_start", (_event, ctx) => syncHistoryTools(ctx));
|
|
709
789
|
// A plan decided on `input` is for the branch it was decided on: moving in the tree leaves it planned for another branch, whose kept entry
|
|
710
790
|
// may not be on this one.
|
|
711
|
-
pi.on("session_tree", (_event, ctx) => { resetRun();
|
|
791
|
+
pi.on("session_tree", (_event, ctx) => { resetRun(); calibration.reseed(ctx, "tree"); syncHistoryTools(ctx); });
|
|
712
792
|
pi.on("session_compact", (_event, ctx) => { if (run?.phase !== "admitted")
|
|
713
793
|
syncHistoryTools(ctx); });
|
|
714
794
|
pi.on("turn_start", (_event, ctx) => syncHistoryTools(ctx));
|
|
715
795
|
pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
|
|
716
796
|
const plannedView = (ctx, cut) => {
|
|
717
|
-
const
|
|
718
|
-
|
|
719
|
-
return
|
|
797
|
+
const preview = new PendingCut();
|
|
798
|
+
preview.plan(cut, ctx.sessionManager.getBranch().length);
|
|
799
|
+
return preview.view(ctx);
|
|
720
800
|
};
|
|
721
801
|
// The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
|
|
722
802
|
// get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
|
|
@@ -759,6 +839,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
759
839
|
// keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
|
|
760
840
|
// Pi's defaults on a 32k window). Each request of the run carries the cut, and the run's first boundary saves it.
|
|
761
841
|
const preflight = (ctx, incomingPart, incomingMessages, observedPrompt, tools, hostSnapshot) => {
|
|
842
|
+
if (standDown(ctx))
|
|
843
|
+
return;
|
|
762
844
|
run.cut.clear();
|
|
763
845
|
const branchLength = ctx.sessionManager.getBranch().length;
|
|
764
846
|
if (!active())
|
|
@@ -776,7 +858,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
776
858
|
const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
|
|
777
859
|
const incoming = incomingPart + system, mandatory = incoming + host;
|
|
778
860
|
observeBudget(before + mandatory, ctx);
|
|
779
|
-
estimatedTokens = corrected(before + mandatory, ctx);
|
|
861
|
+
calibration.estimatedTokens = corrected(before + mandatory, ctx);
|
|
780
862
|
if (!fits(incoming, limits(ctx).hardLine, ctx))
|
|
781
863
|
throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
|
|
782
864
|
// A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
|
|
@@ -820,14 +902,16 @@ export async function installCompaction(pi, options = {}) {
|
|
|
820
902
|
run.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
|
|
821
903
|
};
|
|
822
904
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
905
|
+
if (standDown(ctx))
|
|
906
|
+
return;
|
|
823
907
|
// A decided plan is for the prompt `input` saw. A run that a custom message starts is not that run (another extension handled the
|
|
824
908
|
// input, so no run started for it): plan afresh.
|
|
825
|
-
const prompted = run
|
|
826
|
-
if (!prompted &&
|
|
827
|
-
|
|
909
|
+
const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
|
|
910
|
+
if (!prompted && !failure())
|
|
911
|
+
beginRun("starting");
|
|
828
912
|
run ??= createRun("starting");
|
|
829
|
-
run.
|
|
830
|
-
|
|
913
|
+
if (!failure() && run.phase !== "starting")
|
|
914
|
+
run.transition("starting", ctx);
|
|
831
915
|
const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
|
|
832
916
|
run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
|
|
833
917
|
try {
|
|
@@ -854,6 +938,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
854
938
|
// handlers have run. Pi's prepareRequest has not yet snapshotted executable tools. A first cut discovered in context_with_system
|
|
855
939
|
// would be too late for that snapshot, even if its declarations were repaired there, so make the late prompt decision here.
|
|
856
940
|
pi.on("message_end", (event, ctx) => {
|
|
941
|
+
if (standDown(ctx))
|
|
942
|
+
return;
|
|
857
943
|
if (event.message.role !== "user" || !active() || run?.phase !== "admitted" || view(ctx).pending)
|
|
858
944
|
return;
|
|
859
945
|
try {
|
|
@@ -967,7 +1053,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
967
1053
|
const entryIdOf = (toolCallId) => branch.findLast(entry => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolCallId === toolCallId)?.id;
|
|
968
1054
|
const fresh = new Set(event.toolResults.map(result => result.toolCallId));
|
|
969
1055
|
const kept = previews.length ? Math.max(...previews.map(preview => measure(preview.filter(message => !(message.role === "toolResult" && fresh.has(message.toolCallId)))))) : floorKept;
|
|
970
|
-
for (const budget of clipBudgets(clipRoom, factor, mandatory, kept)) {
|
|
1056
|
+
for (const budget of clipBudgets(clipRoom, calibration.factor, mandatory, kept)) {
|
|
971
1057
|
const round = clipFor(event.toolResults, entryIdOf, budget);
|
|
972
1058
|
if (!round.length)
|
|
973
1059
|
continue;
|
|
@@ -986,7 +1072,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
986
1072
|
tryClips(room, band);
|
|
987
1073
|
const before = measure(saved);
|
|
988
1074
|
observeBudget(before + mandatory, ctx);
|
|
989
|
-
estimatedTokens = corrected(before + mandatory, ctx);
|
|
1075
|
+
calibration.estimatedTokens = corrected(before + mandatory, ctx);
|
|
990
1076
|
const { hardLine } = limits(ctx);
|
|
991
1077
|
if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
|
|
992
1078
|
if (fits(before + mandatory, hardLine, ctx))
|
|
@@ -1017,7 +1103,6 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1017
1103
|
if (!run)
|
|
1018
1104
|
return;
|
|
1019
1105
|
run.pendingBoundaryReceipts = entries.flatMap(entry => entry.type === "compaction" ? receiptId(entry) ?? [] : []);
|
|
1020
|
-
run.pendingBoundaryCommit = run.pendingBoundaryReceipts.length > 0;
|
|
1021
1106
|
};
|
|
1022
1107
|
const boundarySaved = (ctx) => {
|
|
1023
1108
|
const wanted = run?.pendingBoundaryReceipts ?? [];
|
|
@@ -1051,8 +1136,10 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1051
1136
|
// Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
|
|
1052
1137
|
const entries = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
|
|
1053
1138
|
{ type: "context_edit", targetId: event.messageEntryId, replacement: null }];
|
|
1054
|
-
if (run.thinkingRetryPending)
|
|
1139
|
+
if (run.thinkingRetryPending) {
|
|
1140
|
+
markBoundary(entries);
|
|
1055
1141
|
return { entries, continue: false };
|
|
1142
|
+
}
|
|
1056
1143
|
const preview = liveCut.view(ctx, entries).session;
|
|
1057
1144
|
const view = Object.create(ctx, { sessionManager: { value: preview } });
|
|
1058
1145
|
const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
|
|
@@ -1069,9 +1156,11 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1069
1156
|
clips().set(id, clip);
|
|
1070
1157
|
const { room, hardLine } = limits(view);
|
|
1071
1158
|
run.thinkingRetryPending = true;
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1159
|
+
const drafts = [...entries, { type: "custom", customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
|
|
1160
|
+
stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: false,
|
|
1161
|
+
piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
|
|
1162
|
+
markBoundary(drafts);
|
|
1163
|
+
return { entries: drafts, continue: true };
|
|
1075
1164
|
}
|
|
1076
1165
|
if (decision.kind !== "cut")
|
|
1077
1166
|
throw new CapacityError(clampMessage);
|
|
@@ -1099,6 +1188,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1099
1188
|
};
|
|
1100
1189
|
pi.on("turn_end", (event, ctx) => {
|
|
1101
1190
|
try {
|
|
1191
|
+
if (standDown(ctx))
|
|
1192
|
+
return;
|
|
1102
1193
|
if (!active() || run?.phase !== "admitted")
|
|
1103
1194
|
return;
|
|
1104
1195
|
if ((thinkingOnlyLength(event.message) || serverClipped.has(event.message)) && !failure() && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
|
|
@@ -1195,6 +1286,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1195
1286
|
};
|
|
1196
1287
|
pi.on("context", (event, ctx) => {
|
|
1197
1288
|
try {
|
|
1289
|
+
if (standDown(ctx))
|
|
1290
|
+
return;
|
|
1198
1291
|
if (!active())
|
|
1199
1292
|
return;
|
|
1200
1293
|
run?.prompt?.id(ctx.sessionManager.getBranch());
|
|
@@ -1214,6 +1307,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1214
1307
|
}
|
|
1215
1308
|
});
|
|
1216
1309
|
pi.on("session_compact_failed", (event, ctx) => {
|
|
1310
|
+
if (standDown(ctx))
|
|
1311
|
+
return;
|
|
1217
1312
|
// This compactor's own refusal of a Pi threshold ask (the gate, or an opportunistic cut that cannot reach the band) reaches here as a
|
|
1218
1313
|
// threshold compaction cancelled and not from an extension: no event for the recorder.
|
|
1219
1314
|
if (event.reason === "threshold" && event.aborted && !event.fromExtension)
|
|
@@ -1233,7 +1328,9 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1233
1328
|
fail(new (event.fromExtension ? CommitFault : Error)(event.errorMessage ?? "Compaction failed"), ctx);
|
|
1234
1329
|
});
|
|
1235
1330
|
pi.on("agent_before_settle", (event, ctx) => {
|
|
1236
|
-
if (
|
|
1331
|
+
if (standDown(ctx))
|
|
1332
|
+
return;
|
|
1333
|
+
if (run?.pendingBoundaryReceipts.length) {
|
|
1237
1334
|
if (event.outcome === "error") {
|
|
1238
1335
|
try {
|
|
1239
1336
|
if (!boundarySaved(ctx))
|
|
@@ -1244,7 +1341,6 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1244
1341
|
}
|
|
1245
1342
|
}
|
|
1246
1343
|
if (run) {
|
|
1247
|
-
run.pendingBoundaryCommit = false;
|
|
1248
1344
|
run.pendingBoundaryReceipts = [];
|
|
1249
1345
|
}
|
|
1250
1346
|
}
|
|
@@ -1262,12 +1358,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1262
1358
|
}
|
|
1263
1359
|
});
|
|
1264
1360
|
pi.on("context_with_system", (event, ctx) => {
|
|
1361
|
+
if (standDown(ctx))
|
|
1362
|
+
return;
|
|
1265
1363
|
// Reaching the next request boundary proves native commit returned, not durable storage.
|
|
1266
1364
|
if (run) {
|
|
1267
|
-
run.pendingBoundaryCommit = false;
|
|
1268
1365
|
run.pendingBoundaryReceipts = [];
|
|
1269
1366
|
}
|
|
1270
|
-
pending = undefined;
|
|
1367
|
+
calibration.pending = undefined;
|
|
1271
1368
|
try {
|
|
1272
1369
|
if (!active())
|
|
1273
1370
|
return;
|
|
@@ -1290,16 +1387,16 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1290
1387
|
assertNativeToolRounds(messages);
|
|
1291
1388
|
}
|
|
1292
1389
|
observeBudget(tokens, ctx);
|
|
1293
|
-
estimatedTokens = corrected(tokens, ctx);
|
|
1390
|
+
calibration.estimatedTokens = corrected(tokens, ctx);
|
|
1294
1391
|
if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
|
|
1295
1392
|
throw new Refusal("Prompt check failed: the request is missing the whole text of the prompt that started this run. Shorten the prompt or choose a model with a larger context window, then retry");
|
|
1296
1393
|
if (!fits(tokens, hardLine, ctx))
|
|
1297
1394
|
throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
|
|
1298
1395
|
// Pi's request estimator and its compaction estimator need not agree. The hard line is
|
|
1299
1396
|
// necessary; above the room, also require the real request clamp to preserve the floor.
|
|
1300
|
-
if (!options.requestReserve && estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
|
|
1397
|
+
if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
|
|
1301
1398
|
throw new CapacityError(clampMessage);
|
|
1302
|
-
if (estimatedTokens > room)
|
|
1399
|
+
if (calibration.estimatedTokens > room)
|
|
1303
1400
|
receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
|
|
1304
1401
|
if (recorder.enabled && !recorder.waitingForCut)
|
|
1305
1402
|
recorder.measureInline(() => {
|
|
@@ -1311,7 +1408,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1311
1408
|
recorder.capture("prepared-request", "public-context-with-system-hook-before-later-transforms-not-wire", { messages: permitted, estimatedInputTokens: tokens }, permitted.length !== event.messages.length);
|
|
1312
1409
|
});
|
|
1313
1410
|
if (tokens > 0 && Number.isSafeInteger(tokens))
|
|
1314
|
-
pending = {
|
|
1411
|
+
calibration.pending = {
|
|
1315
1412
|
identity: identityFor(ctx), tokens, messages, snapshot: structuredClone(convertToLlm(messages)),
|
|
1316
1413
|
};
|
|
1317
1414
|
if (messages !== event.messages)
|
|
@@ -1321,7 +1418,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1321
1418
|
fail(error, ctx);
|
|
1322
1419
|
}
|
|
1323
1420
|
});
|
|
1324
|
-
return { close: async () => { semanticRequest++; recorder.stop("caller-close"); await semantic.close(); await Promise.allSettled([...semanticPending]); }, semanticRecall: semantic, setSemanticEnabled, semanticStatus };
|
|
1421
|
+
return { close: async () => { semanticRequest++; recorder.stop("caller-close"); await semantic.close(); await Promise.allSettled([...semanticPending]); }, semanticRecall: semantic, setSemanticEnabled, semanticStatus, state: stateFor, inspectState: (ctx) => ({ run: run, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending }) };
|
|
1325
1422
|
}
|
|
1326
1423
|
function checkedInput(raw) { if (!Check(RecallInput, raw))
|
|
1327
1424
|
throw new Error("Invalid recall input"); return structuredClone(raw); }
|