pi-tuck 1.1.1 → 1.1.3

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.
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
3
+ export declare const DIAGNOSTIC_BUILD = "d3c9d03a4fd2a19793701c4c043b680a24b0a5f219c4c3ab6f7c3a232feb333e";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
package/dist/src/run.d.ts CHANGED
@@ -36,18 +36,25 @@ export declare class StartingPrompt {
36
36
  id(branch: readonly SessionEntry[]): string | undefined;
37
37
  text(branch: readonly SessionEntry[]): string;
38
38
  }
39
- export interface Run {
40
- phase: 'decided' | 'starting' | 'admitted' | 'failed';
41
- claimed: boolean;
42
- expired: boolean;
39
+ export type RunPhase = 'decided' | 'claimed' | 'expired' | 'starting' | 'admitted' | 'failed' | 'commit-failed';
40
+ /** Claim/expiry describe the input plan; a failed attempt cannot re-enter a live phase. */
41
+ export declare const RUN_TRANSITIONS: Readonly<Record<RunPhase, readonly RunPhase[]>>;
42
+ export declare class Run {
43
+ private state;
44
+ private expiredPlan;
45
+ constructor(phase: Exclude<RunPhase, 'failed' | 'commit-failed'>);
46
+ get phase(): "starting" | "failed" | "decided" | "claimed" | "expired" | "admitted" | "commit-failed";
47
+ get expired(): boolean;
48
+ /** Failure data, only present in a failed phase. The phase alone decides admission. */
49
+ get error(): Error | undefined;
50
+ transition(phase: RunPhase, ctx?: Pick<ExtensionContext, 'hasUI'>, error?: Error): boolean;
43
51
  prompt?: StartingPrompt;
44
52
  cut: PendingCut;
45
53
  clips: Map<string, Clip>;
46
- pendingBoundaryCommit: boolean;
47
54
  pendingBoundaryReceipts: string[];
48
55
  thinkingRetryPending: boolean;
49
- failure?: Error;
50
56
  refusalReceipted: boolean;
57
+ clear(): void;
51
58
  }
52
- export declare const createRun: (phase: Run["phase"]) => Run;
59
+ export declare const createRun: (phase: ConstructorParameters<typeof Run>[0]) => Run;
53
60
  export {};
package/dist/src/run.js CHANGED
@@ -85,5 +85,60 @@ export class StartingPrompt {
85
85
  throw new Error('The starting prompt entry is no longer on this branch');
86
86
  }
87
87
  }
88
- export const createRun = (phase) => ({ phase, claimed: false, expired: false,
89
- cut: new PendingCut(), clips: new Map(), pendingBoundaryCommit: false, pendingBoundaryReceipts: [], thinkingRetryPending: false, refusalReceipted: false });
88
+ /** Claim/expiry describe the input plan; a failed attempt cannot re-enter a live phase. */
89
+ export const RUN_TRANSITIONS = {
90
+ decided: ['claimed', 'expired', 'starting', 'failed', 'commit-failed'],
91
+ claimed: ['claimed', 'starting', 'failed', 'commit-failed'],
92
+ expired: ['starting', 'failed', 'commit-failed'],
93
+ starting: ['admitted', 'failed', 'commit-failed'],
94
+ admitted: ['admitted', 'failed', 'commit-failed'],
95
+ failed: ['failed', 'commit-failed'],
96
+ 'commit-failed': ['commit-failed'],
97
+ };
98
+ let reportedInvalidTransition = false;
99
+ export class Run {
100
+ state;
101
+ // Input-plan provenance survives starting/admission: later native threshold
102
+ // checks still choose the live view when the original input plan expired.
103
+ expiredPlan = false;
104
+ constructor(phase) { this.state = { phase }; }
105
+ get phase() { return this.state.phase; }
106
+ get expired() { return this.expiredPlan; }
107
+ /** Failure data, only present in a failed phase. The phase alone decides admission. */
108
+ get error() { return 'error' in this.state ? this.state.error : undefined; }
109
+ transition(phase, ctx, error) {
110
+ if (!RUN_TRANSITIONS[this.phase].includes(phase) || ((phase === 'failed' || phase === 'commit-failed') && !error)) {
111
+ const message = `pi-tuck: invalid run transition ${this.phase} -> ${phase}`;
112
+ if (process.env.NODE_ENV === 'test')
113
+ throw new Error(message);
114
+ if (ctx?.hasUI === false && !reportedInvalidTransition) {
115
+ reportedInvalidTransition = true;
116
+ try {
117
+ process.stderr.write(message + '\n');
118
+ }
119
+ catch { /* ended */ }
120
+ }
121
+ return false;
122
+ }
123
+ this.state = phase === 'failed' || phase === 'commit-failed' ? { phase, error: error } : { phase };
124
+ if (phase === 'expired')
125
+ this.expiredPlan = true;
126
+ return true;
127
+ }
128
+ prompt;
129
+ cut = new PendingCut();
130
+ clips = new Map();
131
+ pendingBoundaryReceipts = [];
132
+ thinkingRetryPending = false;
133
+ refusalReceipted = false;
134
+ clear() {
135
+ this.prompt = undefined;
136
+ this.cut.clear();
137
+ this.clips.clear();
138
+ this.pendingBoundaryReceipts = [];
139
+ this.thinkingRetryPending = false;
140
+ this.refusalReceipted = false;
141
+ this.expiredPlan = false;
142
+ }
143
+ }
144
+ export const createRun = (phase) => new Run(phase);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history. Search by meaning on Apple silicon.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
1
+ export const BUILD_ID = "d3c9d03a4fd2a19793701c4c043b680a24b0a5f219c4c3ab6f7c3a232feb333e";
package/src/compaction.ts CHANGED
@@ -107,6 +107,46 @@ export function seedWindow(branch: readonly SessionEntry[], key: string): number
107
107
  }
108
108
  return initialWindow(key);
109
109
  }
110
+ /** One accounting owner. Session start still defers receipt loading until the first budget read;
111
+ * tree moves load immediately, and identity changes keep any uncommitted window observation. */
112
+ class Calibration {
113
+ identity = '';
114
+ factor = 1;
115
+ ratios: number[] = [];
116
+ learnedContextWindow: number | undefined;
117
+ windowObservation: { message: AgentMessage; identity: string; window: number } | undefined;
118
+ pending: { identity: string; tokens: number; messages: Parameters<typeof convertToLlm>[0]; snapshot: ReturnType<typeof convertToLlm>; requestedMaxTokens?: () => number | undefined } | undefined;
119
+ lastCeiling: number | null = null;
120
+ estimatedTokens = 0;
121
+ private seededIdentity = '';
122
+ static key(ctx: ExtensionContext) { return ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : ''; }
123
+ /** Model selection itself never reloads receipts: switching away and back without a request keeps the learned window. */
124
+ select(ctx: ExtensionContext) { this.identity = Calibration.key(ctx); }
125
+ needsSeed(ctx: ExtensionContext) { return this.seededIdentity !== Calibration.key(ctx); }
126
+ reseed(ctx: ExtensionContext, reason: 'identity' | 'session' | 'tree') {
127
+ this.identity = Calibration.key(ctx);
128
+ this.pending = undefined;
129
+ if (reason !== 'identity') this.windowObservation = undefined;
130
+ if (reason === 'session') {
131
+ this.factor = 1; this.learnedContextWindow = undefined; this.estimatedTokens = 0;
132
+ // Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
133
+ this.seededIdentity = '';
134
+ return;
135
+ }
136
+ this.seededIdentity = this.identity;
137
+ if (reason === 'tree' && !this.identity) return;
138
+ const branch = ctx.sessionManager.getBranch();
139
+ this.ratios = seedWindow(branch, this.identity);
140
+ this.factor = Math.max(1, ...this.ratios);
141
+ this.learnedContextWindow = seedContextWindow(branch, this.identity);
142
+ }
143
+ learn(value: number, ctx: ExtensionContext, append: (kind: string, data: unknown) => void) {
144
+ this.ratios.push(value); if (this.ratios.length > CALIBRATION_WINDOW) this.ratios.shift(); this.factor = Math.max(1, ...this.ratios);
145
+ // D7: compare what a cold instance would seed, including the existing clamps.
146
+ if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), this.identity), this.ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
147
+ append(CALIBRATION_RECEIPT, { calibrationIdentity: this.identity, calibrationWindow: [...this.ratios] });
148
+ }
149
+ }
110
150
  export type CompactionState = { kind: "active" } | { kind: "standingDown"; reason: string };
111
151
  /** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
112
152
  export function compactionState(model: { api: string; contextWindow?: number } | undefined, enabled: boolean): CompactionState {
@@ -185,7 +225,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
185
225
  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; }
186
226
  });
187
227
  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(() => {
188
- 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 });
228
+ 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 });
189
229
  proposalId = receiptId(attached);
190
230
  if (recorder.enabled) { try {
191
231
  const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
@@ -244,68 +284,62 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
244
284
  } });
245
285
  // Pi's native start/settled events bracket the run and its post-turn cuts.
246
286
  let run: Run | undefined;
247
- // A native append may have mutated memory before its disk write failed. This session fault outlives the run.
248
- let commitFault: Error | undefined;
249
- const failure = () => commitFault ?? run?.failure;
287
+ // A commit-failed phase survives attempts/tree moves until session_start: native memory may be ahead of disk.
288
+ const failure = () => run?.phase === "failed" || run?.phase === "commit-failed" ? run.error : undefined;
250
289
  const protectedPrompt = (ctx: ExtensionContext) => run?.prompt?.id(ctx.sessionManager.getBranch());
251
290
  const clips = () => run?.clips ?? emptyClips;
252
291
  const emptyClips = new Map<string, Clip>();
253
- const resetRun = () => { run = undefined; pending = undefined; };
292
+ const resetRun = (session = false) => {
293
+ if (!session && run?.phase === "commit-failed") run.clear(); else run = undefined;
294
+ calibration.pending = undefined;
295
+ };
296
+ const beginRun = (phase: "decided" | "starting" | "admitted") => {
297
+ if (run?.phase === "commit-failed") run.clear(); else run = createRun(phase);
298
+ };
254
299
  const stateFor = (ctx: ExtensionContext) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
255
300
  // A prerequisite can change with the model/settings; discard the old plan before returning control to native.
256
301
  const standDown = (ctx: ExtensionContext) => {
257
302
  if (stateFor(ctx).kind === "active") return false;
258
303
  resetRun();
259
- windowObservation = undefined;
304
+ calibration.windowObservation = undefined;
260
305
  lengthStop = false;
261
306
  return true;
262
307
  };
263
308
  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");
264
- let estimatedTokens = 0;
265
- // One serial request, one accounting identity; observations never certify new content. A new identity (the first request after a session
266
- // 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`).
267
- let identity = "", factor = 1, ratios: number[] = [];
268
- let learnedContextWindow: number | undefined;
309
+ const calibration = new Calibration();
269
310
  const serverClipped = new WeakSet<object>();
270
- let windowObservation: { message: AgentMessage; identity: string; window: number } | undefined;
271
- let lastCeiling: number | null = null;
272
- let pending: { identity: string; tokens: number; messages: Parameters<typeof convertToLlm>[0]; snapshot: ReturnType<typeof convertToLlm>; requestedMaxTokens?: () => number | undefined } | undefined;
273
311
  const identityFor = (ctx: ExtensionContext) => {
274
- const key = ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : "";
275
- if (key !== identity) { identity = key; ratios = seedWindow(ctx.sessionManager.getBranch(), key); factor = Math.max(1, ...ratios); learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), key); pending = undefined; }
276
- return key;
312
+ calibration.select(ctx);
313
+ if (calibration.needsSeed(ctx)) calibration.reseed(ctx, "identity");
314
+ return calibration.identity;
277
315
  };
316
+ pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
278
317
  const contextWindow = (ctx: ExtensionContext) => {
279
318
  identityFor(ctx);
280
- return Math.min(ctx.model?.contextWindow ?? 0, learnedContextWindow ?? Infinity);
319
+ return Math.min(ctx.model?.contextWindow ?? 0, calibration.learnedContextWindow ?? Infinity);
281
320
  };
282
321
  // This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
283
322
  // An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
284
323
  pi.on("before_provider_request", event => {
285
- if (!pending || !event.payload || typeof event.payload !== "object") return;
324
+ if (!calibration.pending || !event.payload || typeof event.payload !== "object") return;
286
325
  const payload = event.payload as Record<string, unknown>;
287
326
  // Read at reply time so later in-place payload edits are included too.
288
- pending.requestedMaxTokens = () => {
327
+ calibration.pending.requestedMaxTokens = () => {
289
328
  const cap = payload.max_tokens ?? payload.max_completion_tokens ?? payload.max_output_tokens;
290
329
  return typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0 ? cap : undefined;
291
330
  };
292
331
  });
293
332
  // 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.
294
- const learn = (value: number, ctx: ExtensionContext) => {
295
- ratios.push(value); if (ratios.length > CALIBRATION_WINDOW) ratios.shift(); factor = Math.max(1, ...ratios);
296
- // Compare what a cold instance would seed (including the existing clamps). Stable windows write nothing.
297
- if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), identity), ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
298
- pi.appendEntry(CALIBRATION_RECEIPT, { calibrationIdentity: identity, calibrationWindow: [...ratios] });
299
- };
300
- const corrected = (tokens: number, ctx: ExtensionContext) => { identityFor(ctx); return Math.ceil(tokens * factor); };
333
+ const learn = (value: number, ctx: ExtensionContext) => calibration.learn(value, ctx, (kind, data) => pi.appendEntry(kind, data));
334
+ const corrected = (tokens: number, ctx: ExtensionContext) => { identityFor(ctx); return Math.ceil(tokens * calibration.factor); };
301
335
  const observeBudget = (rawTokens: number, ctx: ExtensionContext) => {
302
- if (options.observeBudget) options.observeBudget({ rawTokens, tokens: corrected(rawTokens, ctx), factor, ...limits(ctx), context: ctx });
336
+ if (options.observeBudget) options.observeBudget({ rawTokens, tokens: corrected(rawTokens, ctx), factor: calibration.factor, ...limits(ctx), context: ctx });
303
337
  };
304
338
  // The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
305
339
  const planReserve = (target: Target, room: number, band: number, mandatory: number, ctx: ExtensionContext) => {
306
340
  identityFor(ctx);
307
341
  // The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
308
- return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, factor, mandatory);
342
+ return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, calibration.factor, mandatory);
309
343
  };
310
344
  pi.on("message_end", (event, ctx) => {
311
345
  if (event.message.role !== "assistant") return;
@@ -316,7 +350,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
316
350
  else recorder.capture("response-actions", "hidden-material-excluded", { stopReason: responseMessage.stopReason }, true);
317
351
  recorder.responded(responseMessage.stopReason);
318
352
  });
319
- const paired = pending; pending = undefined;
353
+ const paired = calibration.pending; calibration.pending = undefined;
320
354
  const key = identityFor(ctx), message = event.message;
321
355
  const overflow = message.stopReason === "error" && isContextOverflow(message);
322
356
  if (!paired || !key || paired.identity !== key || !active() || failure() || ctx.signal?.aborted || (message.errorMessage && !overflow) ||
@@ -343,9 +377,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
343
377
  if (message.stopReason === "length" && requested !== undefined &&
344
378
  Number.isSafeInteger(output) && output >= 0 && output < requested &&
345
379
  Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
346
- learnedContextWindow = Math.min(learnedContextWindow ?? Infinity, bound);
380
+ calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
347
381
  serverClipped.add(message);
348
- windowObservation = { message, identity: key, window: learnedContextWindow };
382
+ calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow };
349
383
  }
350
384
  // A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
351
385
  // 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
@@ -354,15 +388,15 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
354
388
  });
355
389
  pi.on("turn_end", (event, ctx) => {
356
390
  if (standDown(ctx)) return;
357
- if (windowObservation?.message !== event.message) return;
358
- const observation = windowObservation; windowObservation = undefined;
391
+ if (calibration.windowObservation?.message !== event.message) return;
392
+ const observation = calibration.windowObservation; calibration.windowObservation = undefined;
359
393
  pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
360
394
  serverClippedReplyId: event.messageEntryId } satisfies WindowReceipt);
361
395
  });
362
396
  // 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
363
397
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
364
398
  let lengthStop = false;
365
- pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
399
+ pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= createRun("starting"); if (!failure()) run.transition("admitted", ctx); run.thinkingRetryPending = false; lengthStop = false; calibration.pending = undefined; });
366
400
  pi.on("message_end", event => { if (event.message.role === "assistant") lengthStop = event.message.stopReason === "length"; });
367
401
  pi.on("agent_settled", (_event, ctx) => {
368
402
  try {
@@ -390,7 +424,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
390
424
  const inputRoom = (response: number, ctx: ExtensionContext) => {
391
425
  const configured = options.activeInputTokens;
392
426
  const ceiling = typeof configured === "function" ? configured(ctx) : configured;
393
- lastCeiling = ceiling ?? null;
427
+ calibration.lastCeiling = ceiling ?? null;
394
428
  if (ceiling !== undefined && (!Number.isSafeInteger(ceiling) || ceiling <= 0))
395
429
  throw new Error("Invalid active-input token ceiling");
396
430
  return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
@@ -399,14 +433,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
399
433
  const limits = (ctx: ExtensionContext) => {
400
434
  const { response } = requestReserve(ctx), room = inputRoom(response, ctx);
401
435
  const floor = options.requestReserve ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model?.maxTokens);
402
- const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), lastCeiling ?? Infinity);
436
+ const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
403
437
  return { response, room, hardLine, replyFloor: floor };
404
438
  };
405
439
  const decisionBand = (ctx: ExtensionContext, room: number, system: number, current = view(ctx)) => {
406
440
  const last = current.session.getBranch().findLast(entry => entry.type === "compaction");
407
441
  const after = last?.type === "compaction" ? (last.details as { tokensAfter?: unknown } | undefined)?.tokensAfter : undefined;
408
442
  return bandOf(room, cutAt, options.cutAt === undefined && typeof after === "number" && Number.isFinite(after) && after >= 0
409
- ? { system, tokensAfter: after, factor } : undefined);
443
+ ? { system, tokensAfter: after, factor: calibration.factor } : undefined);
410
444
  };
411
445
  const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
412
446
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
@@ -477,7 +511,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
477
511
  const receipt = (kind: "refusal" | "above-room", reason: string, ctx: ExtensionContext) => {
478
512
  let room: number | null = null, hardLine: number | null = null;
479
513
  try { ({ room, hardLine } = limits(ctx)); } catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
480
- pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens, room, hardLine, buildId: BUILD_ID });
514
+ pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID });
481
515
  };
482
516
  const fail = (error: unknown, ctx: ExtensionContext) => {
483
517
  recorder.stop("native-attempt-failed");
@@ -486,15 +520,16 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
486
520
  const previous = failure(), shouldNotify = !previous;
487
521
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
488
522
  const receipted = run?.refusalReceipted;
489
- resetRun();
490
- // Keep only a terminal attempt record until Pi settles: its fresh abort controller must still see the refusal.
491
- run = createRun("failed"); run.failure = fault; run.refusalReceipted = true;
492
- if (fault instanceof CommitFault) commitFault = fault;
523
+ calibration.pending = undefined;
524
+ // Keep the same terminal run until Pi settles; later start hooks cannot admit it.
525
+ run ??= createRun("starting"); run.clear();
526
+ run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", ctx, fault);
527
+ run.refusalReceipted = true;
493
528
  try {
494
529
  if (!receipted) receipt("refusal", fault.message, ctx);
495
530
  options.fail?.(error);
496
531
  } finally {
497
- try { if (shouldNotify) notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
532
+ try { if (shouldNotify) notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
498
533
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
499
534
  : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error"); }
500
535
  finally { ctx.abort(); }
@@ -507,14 +542,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
507
542
  };
508
543
  pi.on("input", async (event, ctx) => {
509
544
  if (!ctx.isIdle() || run?.phase === "starting") return; // steering joins the existing run
510
- run = createRun("decided");
511
- const decision = run;
545
+ beginRun("decided");
546
+ const decision = run!;
512
547
  try { syncHistoryTools(ctx); await preflight(ctx, incomingTokens(event.text, event.images),
513
548
  [{ role: "user", content: [{ type: "text", text: event.text }, ...(event.images ?? [])], timestamp: 0 }], ctx.getSystemPrompt(), pi.getActiveTools()); syncHistoryTools(ctx); }
514
549
  catch (error) { fail(error, ctx); }
515
550
  // Pi normally reaches its pre-run threshold check within microtasks. Auth I/O or a later extension's input I/O can make a
516
551
  // real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
517
- setImmediate(() => { if (run === decision && !decision.claimed) decision.expired = true; });
552
+ setImmediate(() => { if (run === decision && decision.phase === "decided") decision.transition("expired", ctx); });
518
553
  });
519
554
 
520
555
  pi.registerTool({
@@ -571,8 +606,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
571
606
  if (event.signal.aborted || ctx.signal?.aborted) { recorder.stop("cut-cancelled"); return { cancel: true }; }
572
607
  // Pi checks its own threshold after a prompt's input and before the run starts: the prompt's cut, planned with the prompt counted,
573
608
  // is the answer, and it is saved before the first request.
574
- if (run?.phase === "decided" && !run.expired && event.reason === "threshold") {
575
- run.claimed = true;
609
+ if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
610
+ run.transition("claimed", ctx);
576
611
  if (view(ctx).pending) {
577
612
  access();
578
613
  const current = view(ctx), { type: _, ...compaction } = run.cut.take()!;
@@ -620,7 +655,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
620
655
  : { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
621
656
  },
622
657
  });
623
- estimatedTokens = corrected(before + mandatory, ctx);
658
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
624
659
  let decision: Decision<CutPlan> = decide();
625
660
  const { hardLine } = limits(ctx);
626
661
  if (!operatorManual && hardLine > room && decision.kind === "fault") {
@@ -645,20 +680,20 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
645
680
  }
646
681
  });
647
682
  pi.on("session_before_tree", (event, ctx) => !standDown(ctx) && event.preparation.userWantsSummary ? { cancel: true } : undefined);
648
- pi.on("session_start", () => { resetRun(); recorder.stop("session-transition"); proposalId = undefined; commitFault = undefined; estimatedTokens = 0; identity = ""; factor = 1; learnedContextWindow = undefined; windowObservation = undefined; });
683
+ pi.on("session_start", (_event, ctx) => { resetRun(true); recorder.stop("session-transition"); proposalId = undefined; calibration.reseed(ctx, "session"); });
649
684
  const historyToolsEnabled = (ctx: ExtensionContext) => stateFor(ctx).kind === "active" && view(ctx).hasTuckCut;
650
685
  const syncHistoryTools = (ctx: ExtensionContext) => { if (active()) applyHistoryTools(pi, historyToolsEnabled(ctx)); };
651
686
  pi.on("session_start", (_event, ctx) => syncHistoryTools(ctx));
652
687
  // 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
653
688
  // may not be on this one.
654
- pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; identity = ""; identityFor(ctx); syncHistoryTools(ctx); });
689
+ pi.on("session_tree", (_event, ctx) => { resetRun(); calibration.reseed(ctx, "tree"); syncHistoryTools(ctx); });
655
690
  pi.on("session_compact", (_event, ctx) => { if (run?.phase !== "admitted") syncHistoryTools(ctx); });
656
691
  pi.on("turn_start", (_event, ctx) => syncHistoryTools(ctx));
657
692
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
658
693
  const plannedView = (ctx: ExtensionContext, cut: CutEntry) => {
659
- const pending = new PendingCut();
660
- pending.plan(cut, ctx.sessionManager.getBranch().length);
661
- return pending.view(ctx);
694
+ const preview = new PendingCut();
695
+ preview.plan(cut, ctx.sessionManager.getBranch().length);
696
+ return preview.view(ctx);
662
697
  };
663
698
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
664
699
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
@@ -693,8 +728,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
693
728
  // The cut before a run, decided on `input` while the session is idle; before_agent_start decides only for a run no input started (one a
694
729
  // custom message starts). The cut is pi-tuck's own, planned as at a tool boundary. It is not Pi's: Pi's cut finder keeps the last
695
730
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
696
- // Pi's defaults on a 32k window). Each request of the run carries the cut, and the run's first boundary saves it.
697
- const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages) => {
731
+ // Pi's defaults on a 32k window). Each request carries the cut until the next boundary saves it. A late steer uses the same path with
732
+ // its existing run owner's entry protected; an incoming prompt that starts a run has no saved owner yet.
733
+ const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages, protectedId?: string) => {
698
734
  if (standDown(ctx)) return;
699
735
  run!.cut.clear();
700
736
  const branchLength = ctx.sessionManager.getBranch().length;
@@ -710,7 +746,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
710
746
  const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
711
747
  const incoming = incomingPart + system, mandatory = incoming + host;
712
748
  observeBudget(before + mandatory, ctx);
713
- estimatedTokens = corrected(before + mandatory, ctx);
749
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
714
750
  if (!fits(incoming, limits(ctx).hardLine, ctx))
715
751
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
716
752
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
@@ -725,7 +761,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
725
761
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
726
762
  // 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
727
763
  // there buys nothing the request needed and costs history the next recall would have found.
728
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary, newPrompt: true, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, false);
764
+ // A steer joins the admitted run: keep its starting prompt and the unexposed tool round, just as at a tool boundary.
765
+ const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
766
+ newPrompt: !protectedId, protectedPromptEntryId: protectedId, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, Boolean(protectedId));
729
767
  if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
730
768
  const candidate = new PendingCut();
731
769
  candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, branchLength);
@@ -743,13 +781,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
743
781
  candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
744
782
  candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, candidate.kind === "cut"),
745
783
  target => decide(target, target <= room ? band : target, false),
746
- () => deepestDecision(ctx, true, false));
784
+ () => deepestDecision(ctx, !protectedId, Boolean(protectedId)));
747
785
  }
748
786
  if (decision.kind === "defer") return;
749
787
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
750
788
  if (decision.kind === "none") return;
751
789
  if (decision.kind === "fault") throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
752
- const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, false, false, previousSummary,
790
+ const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary,
753
791
  { response, host, mandatory, target: decision.target, margin: room - band });
754
792
  run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
755
793
  };
@@ -757,11 +795,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
757
795
  if (standDown(ctx)) return;
758
796
  // A decided plan is for the prompt `input` saw. A run that a custom message starts is not that run (another extension handled the
759
797
  // input, so no run started for it): plan afresh.
760
- const prompted = run?.phase === "decided" && event.messageType !== "custom";
761
- if (!prompted && run?.phase !== "failed") run = createRun("starting");
798
+ const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
799
+ if (!prompted && !failure()) beginRun("starting");
762
800
  run ??= createRun("starting");
763
- run.claimed = true;
764
- run.phase = "starting";
801
+ if (!failure() && run.phase !== "starting") run.transition("starting", ctx);
765
802
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
766
803
  run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
767
804
  try {
@@ -795,7 +832,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
795
832
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
796
833
  const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
797
834
  if (fits(conversationTokens(saved) + system + incoming + host, limits(ctx).room, ctx)) return;
798
- preflight(ctx, incoming, [message], ctx.getSystemPrompt(), pi.getActiveTools(), hostInput);
835
+ preflight(ctx, incoming, [message], ctx.getSystemPrompt(), pi.getActiveTools(), hostInput, protectedPrompt(ctx));
799
836
  syncHistoryTools(ctx);
800
837
  } catch (error) { fail(error, ctx); }
801
838
  });
@@ -889,7 +926,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
889
926
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
890
927
  const kept = previews.length ? Math.max(...previews.map(preview => measure(preview.filter(message =>
891
928
  !(message.role === "toolResult" && fresh.has((message as ToolResultMessage).toolCallId)))))) : floorKept;
892
- for (const budget of clipBudgets(clipRoom, factor, mandatory, kept)) {
929
+ for (const budget of clipBudgets(clipRoom, calibration.factor, mandatory, kept)) {
893
930
  const round = clipFor(event.toolResults, entryIdOf, budget);
894
931
  if (!round.length) continue;
895
932
  for (const clip of round) run!.clips.set(clip.toolCallId, clip);
@@ -901,7 +938,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
901
938
  tryClips(room, band);
902
939
  const before = measure(saved);
903
940
  observeBudget(before + mandatory, ctx);
904
- estimatedTokens = corrected(before + mandatory, ctx);
941
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
905
942
  const { hardLine } = limits(ctx);
906
943
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
907
944
  if (fits(before + mandatory, hardLine, ctx)) decision = { kind: "none" };
@@ -932,7 +969,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
932
969
  const markBoundary = (entries: readonly SessionBoundaryDraft[]) => {
933
970
  if (!run) return;
934
971
  run.pendingBoundaryReceipts = entries.flatMap(entry => entry.type === "compaction" ? receiptId(entry) ?? [] : []);
935
- run.pendingBoundaryCommit = run.pendingBoundaryReceipts.length > 0;
936
972
  };
937
973
  const boundarySaved = (ctx: ExtensionContext) => {
938
974
  const wanted = run?.pendingBoundaryReceipts ?? [];
@@ -1127,12 +1163,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1127
1163
  });
1128
1164
  pi.on("agent_before_settle", (event, ctx) => {
1129
1165
  if (standDown(ctx)) return;
1130
- if (run?.pendingBoundaryCommit) {
1166
+ if (run?.pendingBoundaryReceipts.length) {
1131
1167
  if (event.outcome === "error") {
1132
1168
  try { if (!boundarySaved(ctx)) throw new Error("Boundary receipt absent from the session file"); }
1133
1169
  catch { return void fail(new CommitFault("Native tool-loop boundary cut was not saved in the session file"), ctx); }
1134
1170
  }
1135
- if (run) { run.pendingBoundaryCommit = false; run.pendingBoundaryReceipts = []; }
1171
+ if (run) { run.pendingBoundaryReceipts = []; }
1136
1172
  }
1137
1173
  // Pi commits these entries before the run settles.
1138
1174
  try {
@@ -1145,8 +1181,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1145
1181
  pi.on("context_with_system", (event, ctx) => {
1146
1182
  if (standDown(ctx)) return;
1147
1183
  // Reaching the next request boundary proves native commit returned, not durable storage.
1148
- if (run) { run.pendingBoundaryCommit = false; run.pendingBoundaryReceipts = []; }
1149
- pending = undefined;
1184
+ if (run) { run.pendingBoundaryReceipts = []; }
1185
+ calibration.pending = undefined;
1150
1186
  try {
1151
1187
  if (!active()) return;
1152
1188
  access();
@@ -1167,16 +1203,16 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1167
1203
  assertNativeToolRounds(messages);
1168
1204
  }
1169
1205
  observeBudget(tokens, ctx);
1170
- estimatedTokens = corrected(tokens, ctx);
1206
+ calibration.estimatedTokens = corrected(tokens, ctx);
1171
1207
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1172
1208
  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");
1173
1209
  if (!fits(tokens, hardLine, ctx))
1174
1210
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1175
1211
  // Pi's request estimator and its compaction estimator need not agree. The hard line is
1176
1212
  // necessary; above the room, also require the real request clamp to preserve the floor.
1177
- if (!options.requestReserve && estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1213
+ if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1178
1214
  throw new CapacityError(clampMessage);
1179
- if (estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1215
+ if (calibration.estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1180
1216
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
1181
1217
  recorder.request();
1182
1218
  // No system prompt or hidden assistant blocks; no provider payload/headers.
@@ -1185,14 +1221,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1185
1221
  !(m.role === "custom" && options.recallPolicy?.privateCustomTypes?.includes(m.customType)));
1186
1222
  recorder.capture("prepared-request", "public-context-with-system-hook-before-later-transforms-not-wire", { messages: permitted, estimatedInputTokens: tokens }, permitted.length !== event.messages.length);
1187
1223
  });
1188
- if (tokens > 0 && Number.isSafeInteger(tokens)) pending = {
1224
+ if (tokens > 0 && Number.isSafeInteger(tokens)) calibration.pending = {
1189
1225
  identity: identityFor(ctx), tokens, messages, snapshot: structuredClone(convertToLlm(messages)),
1190
1226
  };
1191
1227
  if (messages !== event.messages) return { messages };
1192
1228
 
1193
1229
  } catch (error) { fail(error, ctx); }
1194
1230
  });
1195
- return {close:async()=>{semanticRequest++;recorder.stop("caller-close");await semantic.close();await Promise.allSettled([...semanticPending]);}, semanticRecall:semantic, setSemanticEnabled, semanticStatus, state: stateFor};
1231
+ return {close:async()=>{semanticRequest++;recorder.stop("caller-close");await semantic.close();await Promise.allSettled([...semanticPending]);}, semanticRecall:semantic, setSemanticEnabled, semanticStatus, state: stateFor, inspectState: (ctx: ExtensionContext) => ({ run: run as Readonly<Run> | undefined, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending })};
1196
1232
  }
1197
1233
 
1198
1234
  function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }