pi-tuck 1.1.1 → 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 CHANGED
@@ -3,6 +3,22 @@
3
3
  All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.1.2] - 2026-11-14
7
+
8
+ ### Changed
9
+
10
+ - **Internal: pi-tuck's run and calibration state each have one owner.** A run's failure is now its phase alone, changed only through a
11
+ fixed table of allowed moves, so a failed run can no longer be treated as admitted. The calibration values that three events used to
12
+ reset separately are one object reseeded in one place. Nothing the model sees changes. The lifecycle test now also resumes sessions
13
+ cold, switches models mid-session and back, and checks after every event that no impossible state appears.
14
+
15
+ ### Release gates
16
+
17
+ - **Shipped without a live gate: replay matches 1.1.1 byte for byte.** 29 recordings, 13,946 of 13,946 requests identical, the same
18
+ 1,971 cuts, 0 lost or dead tasks.
19
+ - **Strict stress:** 318 cells and the resumed-session suite, 0 findings. Lifecycle with 40 seeds. Tests and CI. The packed tarball loaded
20
+ in the real installed Pi.
21
+
6
22
  ## [1.1.1] - 2026-11-14
7
23
 
8
24
  ### Fixed
@@ -1 +1 @@
1
- export declare const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
1
+ export declare const BUILD_ID = "e36f2c823c0d56405dab4cda3f16894a034bdb082d322c30587474d15b332b70";
@@ -1 +1 @@
1
- export const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
1
+ export const BUILD_ID = "e36f2c823c0d56405dab4cda3f16894a034bdb082d322c30587474d15b332b70";
@@ -1,3 +1,4 @@
1
+ import { type Run } from "./run.js";
1
2
  import { type SemanticRecallController } from "./semantic-recall.js";
2
3
  import { type RecorderOptions } from "./diagnostics.js";
3
4
  import { type AgentMessage } from "./budget.js";
@@ -180,4 +181,10 @@ export declare function installCompaction(pi: ExtensionAPI, options?: Compaction
180
181
  };
181
182
  };
182
183
  state: (ctx: ExtensionContext) => CompactionState;
184
+ inspectState: (ctx: ExtensionContext) => {
185
+ run: Readonly<Run> | undefined;
186
+ phase: "starting" | "failed" | "decided" | "claimed" | "expired" | "admitted" | "commit-failed" | undefined;
187
+ calibrationIdentity: string;
188
+ pendingCut: boolean;
189
+ };
183
190
  }>;
@@ -119,6 +119,53 @@ export function seedWindow(branch, key) {
119
119
  }
120
120
  return initialWindow(key);
121
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
+ }
122
169
  /** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
123
170
  export function compactionState(model, enabled) {
124
171
  const reason = !enabled ? "compaction is disabled" : model?.api === "pi-virtual" ? "pi-virtual model" : !model ? undefined
@@ -167,7 +214,7 @@ export async function installCompaction(pi, options = {}) {
167
214
  }
168
215
  });
169
216
  const captureDraft = (draft, ctx, reserve, reason, tokensBefore, retainCurrentInput, operatorManual, previousSummary, budget) => recorder.measureInline(() => {
170
- 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 });
171
218
  proposalId = receiptId(attached);
172
219
  if (recorder.enabled) {
173
220
  try {
@@ -253,80 +300,72 @@ export async function installCompaction(pi, options = {}) {
253
300
  } });
254
301
  // Pi's native start/settled events bracket the run and its post-turn cuts.
255
302
  let run;
256
- // A native append may have mutated memory before its disk write failed. This session fault outlives the run.
257
- let commitFault;
258
- 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;
259
305
  const protectedPrompt = (ctx) => run?.prompt?.id(ctx.sessionManager.getBranch());
260
306
  const clips = () => run?.clips ?? emptyClips;
261
307
  const emptyClips = new Map();
262
- const resetRun = () => { run = undefined; pending = undefined; };
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
+ };
263
321
  const stateFor = (ctx) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
264
322
  // A prerequisite can change with the model/settings; discard the old plan before returning control to native.
265
323
  const standDown = (ctx) => {
266
324
  if (stateFor(ctx).kind === "active")
267
325
  return false;
268
326
  resetRun();
269
- windowObservation = undefined;
327
+ calibration.windowObservation = undefined;
270
328
  lengthStop = false;
271
329
  return true;
272
330
  };
273
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");
274
- let estimatedTokens = 0;
275
- // One serial request, one accounting identity; observations never certify new content. A new identity (the first request after a session
276
- // 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`).
277
- let identity = "", factor = 1, ratios = [];
278
- let learnedContextWindow;
332
+ const calibration = new Calibration();
279
333
  const serverClipped = new WeakSet();
280
- let windowObservation;
281
- let lastCeiling = null;
282
- let pending;
283
334
  const identityFor = (ctx) => {
284
- const key = ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : "";
285
- if (key !== identity) {
286
- identity = key;
287
- ratios = seedWindow(ctx.sessionManager.getBranch(), key);
288
- factor = Math.max(1, ...ratios);
289
- learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), key);
290
- pending = undefined;
291
- }
292
- return key;
335
+ calibration.select(ctx);
336
+ if (calibration.needsSeed(ctx))
337
+ calibration.reseed(ctx, "identity");
338
+ return calibration.identity;
293
339
  };
340
+ pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
294
341
  const contextWindow = (ctx) => {
295
342
  identityFor(ctx);
296
- return Math.min(ctx.model?.contextWindow ?? 0, learnedContextWindow ?? Infinity);
343
+ return Math.min(ctx.model?.contextWindow ?? 0, calibration.learnedContextWindow ?? Infinity);
297
344
  };
298
345
  // This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
299
346
  // An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
300
347
  pi.on("before_provider_request", event => {
301
- if (!pending || !event.payload || typeof event.payload !== "object")
348
+ if (!calibration.pending || !event.payload || typeof event.payload !== "object")
302
349
  return;
303
350
  const payload = event.payload;
304
351
  // Read at reply time so later in-place payload edits are included too.
305
- pending.requestedMaxTokens = () => {
352
+ calibration.pending.requestedMaxTokens = () => {
306
353
  const cap = payload.max_tokens ?? payload.max_completion_tokens ?? payload.max_output_tokens;
307
354
  return typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0 ? cap : undefined;
308
355
  };
309
356
  });
310
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.
311
- const learn = (value, ctx) => {
312
- ratios.push(value);
313
- if (ratios.length > CALIBRATION_WINDOW)
314
- ratios.shift();
315
- factor = Math.max(1, ...ratios);
316
- // Compare what a cold instance would seed (including the existing clamps). Stable windows write nothing.
317
- if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), identity), ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
318
- pi.appendEntry(CALIBRATION_RECEIPT, { calibrationIdentity: identity, calibrationWindow: [...ratios] });
319
- };
320
- 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); };
321
360
  const observeBudget = (rawTokens, ctx) => {
322
361
  if (options.observeBudget)
323
- 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 });
324
363
  };
325
364
  // The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
326
365
  const planReserve = (target, room, band, mandatory, ctx) => {
327
366
  identityFor(ctx);
328
367
  // The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
329
- 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);
330
369
  };
331
370
  pi.on("message_end", (event, ctx) => {
332
371
  if (event.message.role !== "assistant")
@@ -342,8 +381,8 @@ export async function installCompaction(pi, options = {}) {
342
381
  recorder.capture("response-actions", "hidden-material-excluded", { stopReason: responseMessage.stopReason }, true);
343
382
  recorder.responded(responseMessage.stopReason);
344
383
  });
345
- const paired = pending;
346
- pending = undefined;
384
+ const paired = calibration.pending;
385
+ calibration.pending = undefined;
347
386
  const key = identityFor(ctx), message = event.message;
348
387
  const overflow = message.stopReason === "error" && isContextOverflow(message);
349
388
  if (!paired || !key || paired.identity !== key || !active() || failure() || ctx.signal?.aborted || (message.errorMessage && !overflow) ||
@@ -374,9 +413,9 @@ export async function installCompaction(pi, options = {}) {
374
413
  if (message.stopReason === "length" && requested !== undefined &&
375
414
  Number.isSafeInteger(output) && output >= 0 && output < requested &&
376
415
  Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
377
- learnedContextWindow = Math.min(learnedContextWindow ?? Infinity, bound);
416
+ calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
378
417
  serverClipped.add(message);
379
- windowObservation = { message, identity: key, window: learnedContextWindow };
418
+ calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow };
380
419
  }
381
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.
382
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
@@ -387,10 +426,10 @@ export async function installCompaction(pi, options = {}) {
387
426
  pi.on("turn_end", (event, ctx) => {
388
427
  if (standDown(ctx))
389
428
  return;
390
- if (windowObservation?.message !== event.message)
429
+ if (calibration.windowObservation?.message !== event.message)
391
430
  return;
392
- const observation = windowObservation;
393
- windowObservation = undefined;
431
+ const observation = calibration.windowObservation;
432
+ calibration.windowObservation = undefined;
394
433
  pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
395
434
  serverClippedReplyId: event.messageEntryId });
396
435
  });
@@ -398,7 +437,8 @@ export async function installCompaction(pi, options = {}) {
398
437
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
399
438
  let lengthStop = false;
400
439
  pi.on("agent_start", (_event, ctx) => { if (standDown(ctx))
401
- return; run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
440
+ return; run ??= createRun("starting"); if (!failure())
441
+ run.transition("admitted", ctx); run.thinkingRetryPending = false; lengthStop = false; calibration.pending = undefined; });
402
442
  pi.on("message_end", event => { if (event.message.role === "assistant")
403
443
  lengthStop = event.message.stopReason === "length"; });
404
444
  pi.on("agent_settled", (_event, ctx) => {
@@ -431,7 +471,7 @@ export async function installCompaction(pi, options = {}) {
431
471
  const inputRoom = (response, ctx) => {
432
472
  const configured = options.activeInputTokens;
433
473
  const ceiling = typeof configured === "function" ? configured(ctx) : configured;
434
- lastCeiling = ceiling ?? null;
474
+ calibration.lastCeiling = ceiling ?? null;
435
475
  if (ceiling !== undefined && (!Number.isSafeInteger(ceiling) || ceiling <= 0))
436
476
  throw new Error("Invalid active-input token ceiling");
437
477
  return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
@@ -440,14 +480,14 @@ export async function installCompaction(pi, options = {}) {
440
480
  const limits = (ctx) => {
441
481
  const { response } = requestReserve(ctx), room = inputRoom(response, ctx);
442
482
  const floor = options.requestReserve ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model?.maxTokens);
443
- 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);
444
484
  return { response, room, hardLine, replyFloor: floor };
445
485
  };
446
486
  const decisionBand = (ctx, room, system, current = view(ctx)) => {
447
487
  const last = current.session.getBranch().findLast(entry => entry.type === "compaction");
448
488
  const after = last?.type === "compaction" ? last.details?.tokensAfter : undefined;
449
489
  return bandOf(room, cutAt, options.cutAt === undefined && typeof after === "number" && Number.isFinite(after) && after >= 0
450
- ? { system, tokensAfter: after, factor } : undefined);
490
+ ? { system, tokensAfter: after, factor: calibration.factor } : undefined);
451
491
  };
452
492
  const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
453
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).
@@ -525,7 +565,7 @@ export async function installCompaction(pi, options = {}) {
525
565
  ({ room, hardLine } = limits(ctx));
526
566
  }
527
567
  catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
528
- 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 });
529
569
  };
530
570
  const fail = (error, ctx) => {
531
571
  recorder.stop("native-attempt-failed");
@@ -534,13 +574,12 @@ export async function installCompaction(pi, options = {}) {
534
574
  const previous = failure(), shouldNotify = !previous;
535
575
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
536
576
  const receipted = run?.refusalReceipted;
537
- resetRun();
538
- // Keep only a terminal attempt record until Pi settles: its fresh abort controller must still see the refusal.
539
- run = createRun("failed");
540
- run.failure = fault;
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);
541
582
  run.refusalReceipted = true;
542
- if (fault instanceof CommitFault)
543
- commitFault = fault;
544
583
  try {
545
584
  if (!receipted)
546
585
  receipt("refusal", fault.message, ctx);
@@ -549,7 +588,7 @@ export async function installCompaction(pi, options = {}) {
549
588
  finally {
550
589
  try {
551
590
  if (shouldNotify)
552
- notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
591
+ notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
553
592
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
554
593
  : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error");
555
594
  }
@@ -566,7 +605,7 @@ export async function installCompaction(pi, options = {}) {
566
605
  pi.on("input", async (event, ctx) => {
567
606
  if (!ctx.isIdle() || run?.phase === "starting")
568
607
  return; // steering joins the existing run
569
- run = createRun("decided");
608
+ beginRun("decided");
570
609
  const decision = run;
571
610
  try {
572
611
  syncHistoryTools(ctx);
@@ -578,8 +617,8 @@ export async function installCompaction(pi, options = {}) {
578
617
  }
579
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
580
619
  // real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
581
- setImmediate(() => { if (run === decision && !decision.claimed)
582
- decision.expired = true; });
620
+ setImmediate(() => { if (run === decision && decision.phase === "decided")
621
+ decision.transition("expired", ctx); });
583
622
  });
584
623
  pi.registerTool({
585
624
  name: "tuck_recall", label: "pi-tuck history", parameters: RecallInput,
@@ -659,8 +698,8 @@ export async function installCompaction(pi, options = {}) {
659
698
  }
660
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,
661
700
  // is the answer, and it is saved before the first request.
662
- if (run?.phase === "decided" && !run.expired && event.reason === "threshold") {
663
- run.claimed = true;
701
+ if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
702
+ run.transition("claimed", ctx);
664
703
  if (view(ctx).pending) {
665
704
  access();
666
705
  const current = view(ctx), { type: _, ...compaction } = run.cut.take();
@@ -711,7 +750,7 @@ export async function installCompaction(pi, options = {}) {
711
750
  : { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
712
751
  },
713
752
  });
714
- estimatedTokens = corrected(before + mandatory, ctx);
753
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
715
754
  let decision = decide();
716
755
  const { hardLine } = limits(ctx);
717
756
  if (!operatorManual && hardLine > room && decision.kind === "fault") {
@@ -742,22 +781,22 @@ export async function installCompaction(pi, options = {}) {
742
781
  }
743
782
  });
744
783
  pi.on("session_before_tree", (event, ctx) => !standDown(ctx) && event.preparation.userWantsSummary ? { cancel: true } : undefined);
745
- pi.on("session_start", () => { resetRun(); recorder.stop("session-transition"); proposalId = undefined; commitFault = undefined; estimatedTokens = 0; identity = ""; factor = 1; learnedContextWindow = undefined; windowObservation = undefined; });
784
+ pi.on("session_start", (_event, ctx) => { resetRun(true); recorder.stop("session-transition"); proposalId = undefined; calibration.reseed(ctx, "session"); });
746
785
  const historyToolsEnabled = (ctx) => stateFor(ctx).kind === "active" && view(ctx).hasTuckCut;
747
786
  const syncHistoryTools = (ctx) => { if (active())
748
787
  applyHistoryTools(pi, historyToolsEnabled(ctx)); };
749
788
  pi.on("session_start", (_event, ctx) => syncHistoryTools(ctx));
750
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
751
790
  // may not be on this one.
752
- pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; identity = ""; identityFor(ctx); syncHistoryTools(ctx); });
791
+ pi.on("session_tree", (_event, ctx) => { resetRun(); calibration.reseed(ctx, "tree"); syncHistoryTools(ctx); });
753
792
  pi.on("session_compact", (_event, ctx) => { if (run?.phase !== "admitted")
754
793
  syncHistoryTools(ctx); });
755
794
  pi.on("turn_start", (_event, ctx) => syncHistoryTools(ctx));
756
795
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
757
796
  const plannedView = (ctx, cut) => {
758
- const pending = new PendingCut();
759
- pending.plan(cut, ctx.sessionManager.getBranch().length);
760
- return pending.view(ctx);
797
+ const preview = new PendingCut();
798
+ preview.plan(cut, ctx.sessionManager.getBranch().length);
799
+ return preview.view(ctx);
761
800
  };
762
801
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
763
802
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
@@ -819,7 +858,7 @@ export async function installCompaction(pi, options = {}) {
819
858
  const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
820
859
  const incoming = incomingPart + system, mandatory = incoming + host;
821
860
  observeBudget(before + mandatory, ctx);
822
- estimatedTokens = corrected(before + mandatory, ctx);
861
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
823
862
  if (!fits(incoming, limits(ctx).hardLine, ctx))
824
863
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
825
864
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
@@ -867,12 +906,12 @@ export async function installCompaction(pi, options = {}) {
867
906
  return;
868
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
869
908
  // input, so no run started for it): plan afresh.
870
- const prompted = run?.phase === "decided" && event.messageType !== "custom";
871
- if (!prompted && run?.phase !== "failed")
872
- run = createRun("starting");
909
+ const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
910
+ if (!prompted && !failure())
911
+ beginRun("starting");
873
912
  run ??= createRun("starting");
874
- run.claimed = true;
875
- run.phase = "starting";
913
+ if (!failure() && run.phase !== "starting")
914
+ run.transition("starting", ctx);
876
915
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
877
916
  run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
878
917
  try {
@@ -1014,7 +1053,7 @@ export async function installCompaction(pi, options = {}) {
1014
1053
  const entryIdOf = (toolCallId) => branch.findLast(entry => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolCallId === toolCallId)?.id;
1015
1054
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
1016
1055
  const kept = previews.length ? Math.max(...previews.map(preview => measure(preview.filter(message => !(message.role === "toolResult" && fresh.has(message.toolCallId)))))) : floorKept;
1017
- for (const budget of clipBudgets(clipRoom, factor, mandatory, kept)) {
1056
+ for (const budget of clipBudgets(clipRoom, calibration.factor, mandatory, kept)) {
1018
1057
  const round = clipFor(event.toolResults, entryIdOf, budget);
1019
1058
  if (!round.length)
1020
1059
  continue;
@@ -1033,7 +1072,7 @@ export async function installCompaction(pi, options = {}) {
1033
1072
  tryClips(room, band);
1034
1073
  const before = measure(saved);
1035
1074
  observeBudget(before + mandatory, ctx);
1036
- estimatedTokens = corrected(before + mandatory, ctx);
1075
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
1037
1076
  const { hardLine } = limits(ctx);
1038
1077
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
1039
1078
  if (fits(before + mandatory, hardLine, ctx))
@@ -1064,7 +1103,6 @@ export async function installCompaction(pi, options = {}) {
1064
1103
  if (!run)
1065
1104
  return;
1066
1105
  run.pendingBoundaryReceipts = entries.flatMap(entry => entry.type === "compaction" ? receiptId(entry) ?? [] : []);
1067
- run.pendingBoundaryCommit = run.pendingBoundaryReceipts.length > 0;
1068
1106
  };
1069
1107
  const boundarySaved = (ctx) => {
1070
1108
  const wanted = run?.pendingBoundaryReceipts ?? [];
@@ -1292,7 +1330,7 @@ export async function installCompaction(pi, options = {}) {
1292
1330
  pi.on("agent_before_settle", (event, ctx) => {
1293
1331
  if (standDown(ctx))
1294
1332
  return;
1295
- if (run?.pendingBoundaryCommit) {
1333
+ if (run?.pendingBoundaryReceipts.length) {
1296
1334
  if (event.outcome === "error") {
1297
1335
  try {
1298
1336
  if (!boundarySaved(ctx))
@@ -1303,7 +1341,6 @@ export async function installCompaction(pi, options = {}) {
1303
1341
  }
1304
1342
  }
1305
1343
  if (run) {
1306
- run.pendingBoundaryCommit = false;
1307
1344
  run.pendingBoundaryReceipts = [];
1308
1345
  }
1309
1346
  }
@@ -1325,10 +1362,9 @@ export async function installCompaction(pi, options = {}) {
1325
1362
  return;
1326
1363
  // Reaching the next request boundary proves native commit returned, not durable storage.
1327
1364
  if (run) {
1328
- run.pendingBoundaryCommit = false;
1329
1365
  run.pendingBoundaryReceipts = [];
1330
1366
  }
1331
- pending = undefined;
1367
+ calibration.pending = undefined;
1332
1368
  try {
1333
1369
  if (!active())
1334
1370
  return;
@@ -1351,16 +1387,16 @@ export async function installCompaction(pi, options = {}) {
1351
1387
  assertNativeToolRounds(messages);
1352
1388
  }
1353
1389
  observeBudget(tokens, ctx);
1354
- estimatedTokens = corrected(tokens, ctx);
1390
+ calibration.estimatedTokens = corrected(tokens, ctx);
1355
1391
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1356
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");
1357
1393
  if (!fits(tokens, hardLine, ctx))
1358
1394
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1359
1395
  // Pi's request estimator and its compaction estimator need not agree. The hard line is
1360
1396
  // necessary; above the room, also require the real request clamp to preserve the floor.
1361
- if (!options.requestReserve && estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1397
+ if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1362
1398
  throw new CapacityError(clampMessage);
1363
- if (estimatedTokens > room)
1399
+ if (calibration.estimatedTokens > room)
1364
1400
  receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1365
1401
  if (recorder.enabled && !recorder.waitingForCut)
1366
1402
  recorder.measureInline(() => {
@@ -1372,7 +1408,7 @@ export async function installCompaction(pi, options = {}) {
1372
1408
  recorder.capture("prepared-request", "public-context-with-system-hook-before-later-transforms-not-wire", { messages: permitted, estimatedInputTokens: tokens }, permitted.length !== event.messages.length);
1373
1409
  });
1374
1410
  if (tokens > 0 && Number.isSafeInteger(tokens))
1375
- pending = {
1411
+ calibration.pending = {
1376
1412
  identity: identityFor(ctx), tokens, messages, snapshot: structuredClone(convertToLlm(messages)),
1377
1413
  };
1378
1414
  if (messages !== event.messages)
@@ -1382,7 +1418,7 @@ export async function installCompaction(pi, options = {}) {
1382
1418
  fail(error, ctx);
1383
1419
  }
1384
1420
  });
1385
- return { close: async () => { semanticRequest++; recorder.stop("caller-close"); await semantic.close(); await Promise.allSettled([...semanticPending]); }, semanticRecall: semantic, setSemanticEnabled, semanticStatus, state: stateFor };
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 }) };
1386
1422
  }
1387
1423
  function checkedInput(raw) { if (!Check(RecallInput, raw))
1388
1424
  throw new Error("Invalid recall input"); return structuredClone(raw); }
@@ -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 = "e36f2c823c0d56405dab4cda3f16894a034bdb082d322c30587474d15b332b70";
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.2",
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 = "e36f2c823c0d56405dab4cda3f16894a034bdb082d322c30587474d15b332b70";
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.
@@ -710,7 +745,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
710
745
  const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
711
746
  const incoming = incomingPart + system, mandatory = incoming + host;
712
747
  observeBudget(before + mandatory, ctx);
713
- estimatedTokens = corrected(before + mandatory, ctx);
748
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
714
749
  if (!fits(incoming, limits(ctx).hardLine, ctx))
715
750
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
716
751
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
@@ -757,11 +792,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
757
792
  if (standDown(ctx)) return;
758
793
  // 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
794
  // 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");
795
+ const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
796
+ if (!prompted && !failure()) beginRun("starting");
762
797
  run ??= createRun("starting");
763
- run.claimed = true;
764
- run.phase = "starting";
798
+ if (!failure() && run.phase !== "starting") run.transition("starting", ctx);
765
799
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
766
800
  run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
767
801
  try {
@@ -889,7 +923,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
889
923
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
890
924
  const kept = previews.length ? Math.max(...previews.map(preview => measure(preview.filter(message =>
891
925
  !(message.role === "toolResult" && fresh.has((message as ToolResultMessage).toolCallId)))))) : floorKept;
892
- for (const budget of clipBudgets(clipRoom, factor, mandatory, kept)) {
926
+ for (const budget of clipBudgets(clipRoom, calibration.factor, mandatory, kept)) {
893
927
  const round = clipFor(event.toolResults, entryIdOf, budget);
894
928
  if (!round.length) continue;
895
929
  for (const clip of round) run!.clips.set(clip.toolCallId, clip);
@@ -901,7 +935,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
901
935
  tryClips(room, band);
902
936
  const before = measure(saved);
903
937
  observeBudget(before + mandatory, ctx);
904
- estimatedTokens = corrected(before + mandatory, ctx);
938
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
905
939
  const { hardLine } = limits(ctx);
906
940
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
907
941
  if (fits(before + mandatory, hardLine, ctx)) decision = { kind: "none" };
@@ -932,7 +966,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
932
966
  const markBoundary = (entries: readonly SessionBoundaryDraft[]) => {
933
967
  if (!run) return;
934
968
  run.pendingBoundaryReceipts = entries.flatMap(entry => entry.type === "compaction" ? receiptId(entry) ?? [] : []);
935
- run.pendingBoundaryCommit = run.pendingBoundaryReceipts.length > 0;
936
969
  };
937
970
  const boundarySaved = (ctx: ExtensionContext) => {
938
971
  const wanted = run?.pendingBoundaryReceipts ?? [];
@@ -1127,12 +1160,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1127
1160
  });
1128
1161
  pi.on("agent_before_settle", (event, ctx) => {
1129
1162
  if (standDown(ctx)) return;
1130
- if (run?.pendingBoundaryCommit) {
1163
+ if (run?.pendingBoundaryReceipts.length) {
1131
1164
  if (event.outcome === "error") {
1132
1165
  try { if (!boundarySaved(ctx)) throw new Error("Boundary receipt absent from the session file"); }
1133
1166
  catch { return void fail(new CommitFault("Native tool-loop boundary cut was not saved in the session file"), ctx); }
1134
1167
  }
1135
- if (run) { run.pendingBoundaryCommit = false; run.pendingBoundaryReceipts = []; }
1168
+ if (run) { run.pendingBoundaryReceipts = []; }
1136
1169
  }
1137
1170
  // Pi commits these entries before the run settles.
1138
1171
  try {
@@ -1145,8 +1178,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1145
1178
  pi.on("context_with_system", (event, ctx) => {
1146
1179
  if (standDown(ctx)) return;
1147
1180
  // Reaching the next request boundary proves native commit returned, not durable storage.
1148
- if (run) { run.pendingBoundaryCommit = false; run.pendingBoundaryReceipts = []; }
1149
- pending = undefined;
1181
+ if (run) { run.pendingBoundaryReceipts = []; }
1182
+ calibration.pending = undefined;
1150
1183
  try {
1151
1184
  if (!active()) return;
1152
1185
  access();
@@ -1167,16 +1200,16 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1167
1200
  assertNativeToolRounds(messages);
1168
1201
  }
1169
1202
  observeBudget(tokens, ctx);
1170
- estimatedTokens = corrected(tokens, ctx);
1203
+ calibration.estimatedTokens = corrected(tokens, ctx);
1171
1204
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1172
1205
  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
1206
  if (!fits(tokens, hardLine, ctx))
1174
1207
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1175
1208
  // Pi's request estimator and its compaction estimator need not agree. The hard line is
1176
1209
  // 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)
1210
+ if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1178
1211
  throw new CapacityError(clampMessage);
1179
- if (estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1212
+ if (calibration.estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1180
1213
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
1181
1214
  recorder.request();
1182
1215
  // No system prompt or hidden assistant blocks; no provider payload/headers.
@@ -1185,14 +1218,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1185
1218
  !(m.role === "custom" && options.recallPolicy?.privateCustomTypes?.includes(m.customType)));
1186
1219
  recorder.capture("prepared-request", "public-context-with-system-hook-before-later-transforms-not-wire", { messages: permitted, estimatedInputTokens: tokens }, permitted.length !== event.messages.length);
1187
1220
  });
1188
- if (tokens > 0 && Number.isSafeInteger(tokens)) pending = {
1221
+ if (tokens > 0 && Number.isSafeInteger(tokens)) calibration.pending = {
1189
1222
  identity: identityFor(ctx), tokens, messages, snapshot: structuredClone(convertToLlm(messages)),
1190
1223
  };
1191
1224
  if (messages !== event.messages) return { messages };
1192
1225
 
1193
1226
  } catch (error) { fail(error, ctx); }
1194
1227
  });
1195
- return {close:async()=>{semanticRequest++;recorder.stop("caller-close");await semantic.close();await Promise.allSettled([...semanticPending]);}, semanticRecall:semantic, setSemanticEnabled, semanticStatus, state: stateFor};
1228
+ 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
1229
  }
1197
1230
 
1198
1231
  function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }
package/src/run.ts CHANGED
@@ -75,18 +75,53 @@ export class StartingPrompt {
75
75
  }
76
76
  }
77
77
 
78
- export interface Run {
79
- phase: 'decided' | 'starting' | 'admitted' | 'failed';
80
- claimed: boolean;
81
- expired: boolean;
78
+ export type RunPhase = 'decided' | 'claimed' | 'expired' | 'starting' | 'admitted' | 'failed' | 'commit-failed';
79
+ /** Claim/expiry describe the input plan; a failed attempt cannot re-enter a live phase. */
80
+ export const RUN_TRANSITIONS: Readonly<Record<RunPhase, readonly RunPhase[]>> = {
81
+ decided: ['claimed', 'expired', 'starting', 'failed', 'commit-failed'],
82
+ claimed: ['claimed', 'starting', 'failed', 'commit-failed'],
83
+ expired: ['starting', 'failed', 'commit-failed'],
84
+ starting: ['admitted', 'failed', 'commit-failed'],
85
+ admitted: ['admitted', 'failed', 'commit-failed'],
86
+ failed: ['failed', 'commit-failed'],
87
+ 'commit-failed': ['commit-failed'],
88
+ };
89
+ let reportedInvalidTransition = false;
90
+ type RunState = { phase: Exclude<RunPhase, 'failed' | 'commit-failed'> } | { phase: 'failed' | 'commit-failed'; error: Error };
91
+
92
+ export class Run {
93
+ private state: RunState;
94
+ // Input-plan provenance survives starting/admission: later native threshold
95
+ // checks still choose the live view when the original input plan expired.
96
+ private expiredPlan = false;
97
+ constructor(phase: Exclude<RunPhase, 'failed' | 'commit-failed'>) { this.state = { phase }; }
98
+ get phase() { return this.state.phase; }
99
+ get expired() { return this.expiredPlan; }
100
+ /** Failure data, only present in a failed phase. The phase alone decides admission. */
101
+ get error() { return 'error' in this.state ? this.state.error : undefined; }
102
+ transition(phase: RunPhase, ctx?: Pick<ExtensionContext, 'hasUI'>, error?: Error): boolean {
103
+ if (!RUN_TRANSITIONS[this.phase].includes(phase) || ((phase === 'failed' || phase === 'commit-failed') && !error)) {
104
+ const message = `pi-tuck: invalid run transition ${this.phase} -> ${phase}`;
105
+ if (process.env.NODE_ENV === 'test') throw new Error(message);
106
+ if (ctx?.hasUI === false && !reportedInvalidTransition) {
107
+ reportedInvalidTransition = true;
108
+ try { process.stderr.write(message + '\n'); } catch { /* ended */ }
109
+ }
110
+ return false;
111
+ }
112
+ this.state = phase === 'failed' || phase === 'commit-failed' ? { phase, error: error! } : { phase };
113
+ if (phase === 'expired') this.expiredPlan = true;
114
+ return true;
115
+ }
82
116
  prompt?: StartingPrompt;
83
- cut: PendingCut;
84
- clips: Map<string, Clip>;
85
- pendingBoundaryCommit: boolean;
86
- pendingBoundaryReceipts: string[];
87
- thinkingRetryPending: boolean;
88
- failure?: Error;
89
- refusalReceipted: boolean;
117
+ cut = new PendingCut();
118
+ clips = new Map<string, Clip>();
119
+ pendingBoundaryReceipts: string[] = [];
120
+ thinkingRetryPending = false;
121
+ refusalReceipted = false;
122
+ clear() {
123
+ this.prompt = undefined; this.cut.clear(); this.clips.clear(); this.pendingBoundaryReceipts = [];
124
+ this.thinkingRetryPending = false; this.refusalReceipted = false; this.expiredPlan = false;
125
+ }
90
126
  }
91
- export const createRun = (phase: Run['phase']): Run => ({ phase, claimed: false, expired: false,
92
- cut: new PendingCut(), clips: new Map(), pendingBoundaryCommit: false, pendingBoundaryReceipts: [], thinkingRetryPending: false, refusalReceipted: false });
127
+ export const createRun = (phase: ConstructorParameters<typeof Run>[0]): Run => new Run(phase);