pi-tuck 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/compaction.ts CHANGED
@@ -56,6 +56,9 @@ class Refusal extends Error {}
56
56
  class CommitFault extends Error {}
57
57
  /** A refusal for want of room, which the user can remedy: it carries advice. */
58
58
  class CapacityError extends Refusal {}
59
+ function notify(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error") {
60
+ try { if (ctx.hasUI === false) process.stderr.write(message + "\n"); else ctx.ui.notify(message, level); } catch { /* ended */ }
61
+ }
59
62
  /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
60
63
  * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
61
64
  export const refusalNotice = (message: string, factor: number): string =>
@@ -79,7 +82,8 @@ export const MEASURED_CALIBRATION: Readonly<Record<string, number>> = {};
79
82
  function initialWindow(key: string): number[] {
80
83
  try { const [provider, , id] = JSON.parse(key) as [string, string, string]; return [Math.min(MEASURED_CALIBRATION[`${provider}/${id}`] ?? 1, CALIBRATION_CEILING)]; } catch { return [1]; }
81
84
  }
82
- /** The calibration window a session starts with under accounting identity `key`: the newest compaction on the branch that carries this package's
85
+ export const CALIBRATION_RECEIPT = 'pi-tuck-calibration';
86
+ /** The calibration window a session starts with under accounting identity `key`: the newest calibration entry or compaction on the branch that carries this package's
83
87
  * receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
84
88
  * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
85
89
  * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
@@ -88,10 +92,14 @@ function initialWindow(key: string): number[] {
88
92
  export function seedWindow(branch: readonly SessionEntry[], key: string): number[] {
89
93
  for (let i = branch.length; i--;) {
90
94
  const entry = branch[i]!;
91
- const receipt = entry.type === "compaction" ? (entry.details as { diagnosticReceipt?: { settings?: Partial<Receipt["settings"]> } | null } | undefined)?.diagnosticReceipt : undefined;
95
+ const receipt = entry.type === "custom" && entry.customType === CALIBRATION_RECEIPT ? { settings: entry.data as Partial<Receipt["settings"]> | undefined }
96
+ : entry.type === "compaction" ? (entry.details as { diagnosticReceipt?: { settings?: Partial<Receipt["settings"]> } | null } | undefined)?.diagnosticReceipt : undefined;
92
97
  if (receipt === undefined) continue;
93
98
  const { calibrationIdentity, calibrationFactor, calibrationWindow } = receipt?.settings ?? {}, stored: unknown = calibrationWindow;
94
- if (calibrationIdentity !== key) return initialWindow(key);
99
+ if (calibrationIdentity !== key) {
100
+ if (entry.type === "custom") continue; // Another model's new observation does not hide this model's last saved seed.
101
+ return initialWindow(key);
102
+ }
95
103
  if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
96
104
  return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
97
105
  if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor)) return [Math.min(Math.max(calibrationFactor, 1), CALIBRATION_CEILING)];
@@ -99,6 +107,55 @@ export function seedWindow(branch: readonly SessionEntry[], key: string): number
99
107
  }
100
108
  return initialWindow(key);
101
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
+ }
150
+ export type CompactionState = { kind: "active" } | { kind: "standingDown"; reason: string };
151
+ /** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
152
+ export function compactionState(model: { api: string; contextWindow?: number } | undefined, enabled: boolean): CompactionState {
153
+ const reason = !enabled ? "compaction is disabled" : model?.api === "pi-virtual" ? "pi-virtual model" : !model ? undefined
154
+ : model.contextWindow === undefined ? "context window is missing"
155
+ : !Number.isFinite(model.contextWindow) ? "context window is not finite"
156
+ : model.contextWindow <= 0 ? "context window is zero or negative" : undefined;
157
+ return reason ? { kind: "standingDown", reason } : { kind: "active" };
158
+ }
102
159
  export interface CompactionOptions {
103
160
  semanticRecall?: SemanticRecallController;
104
161
  /** Whether `tuck_search` exists: false where semantic recall cannot run (off Apple silicon), so the model is offered word recall only. */
@@ -168,7 +225,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
168
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; }
169
226
  });
170
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(() => {
171
- 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 });
172
229
  proposalId = receiptId(attached);
173
230
  if (recorder.enabled) { try {
174
231
  const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
@@ -186,7 +243,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
186
243
  } });
187
244
  pi.on("session_compact", (_event, ctx) => observe(ctx));
188
245
  // A saved cut moves entries out of view: index them now, in the background, even for a session that has not searched or whose worker the idle limit stopped.
189
- pi.on("session_compact", (_event, ctx) => { semantic.indexAtCut(semanticProvider(ctx)); });
246
+ pi.on("session_compact", (_event, ctx) => { if (!standDown(ctx)) semantic.indexAtCut(semanticProvider(ctx)); });
190
247
  pi.on("session_shutdown", async () => { semanticRequest++; recorder.stop("session-shutdown"); await semantic.close(); await Promise.allSettled([...semanticPending]); });
191
248
  pi.on("session_start", () => { semanticRequest++; semanticTransition = semantic.close();void semanticTransition.catch(error => { options.fail?.(error); }); });
192
249
  pi.on("turn_end", (_event,ctx) => { semantic.schedule(semanticProvider(ctx)); });
@@ -223,68 +280,77 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
223
280
  }});
224
281
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
225
282
  const state = semantic.status();
226
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
283
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
227
284
  } });
228
285
  // Pi's native start/settled events bracket the run and its post-turn cuts.
229
286
  let run: Run | undefined;
230
- // A native append may have mutated memory before its disk write failed. This session fault outlives the run.
231
- let commitFault: Error | undefined;
232
- 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;
233
289
  const protectedPrompt = (ctx: ExtensionContext) => run?.prompt?.id(ctx.sessionManager.getBranch());
234
290
  const clips = () => run?.clips ?? emptyClips;
235
291
  const emptyClips = new Map<string, Clip>();
236
- 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
+ };
299
+ const stateFor = (ctx: ExtensionContext) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
300
+ // A prerequisite can change with the model/settings; discard the old plan before returning control to native.
301
+ const standDown = (ctx: ExtensionContext) => {
302
+ if (stateFor(ctx).kind === "active") return false;
303
+ resetRun();
304
+ calibration.windowObservation = undefined;
305
+ lengthStop = false;
306
+ return true;
307
+ };
237
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");
238
- let estimatedTokens = 0;
239
- // One serial request, one accounting identity; observations never certify new content. A new identity (the first request after a session
240
- // 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`).
241
- let identity = "", factor = 1, ratios: number[] = [];
242
- let learnedContextWindow: number | undefined;
309
+ const calibration = new Calibration();
243
310
  const serverClipped = new WeakSet<object>();
244
- let windowObservation: { message: AgentMessage; identity: string; window: number } | undefined;
245
- let lastCeiling: number | null = null;
246
- let pending: { identity: string; tokens: number; messages: Parameters<typeof convertToLlm>[0]; snapshot: ReturnType<typeof convertToLlm>; requestedMaxTokens?: () => number | undefined } | undefined;
247
311
  const identityFor = (ctx: ExtensionContext) => {
248
- const key = ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : "";
249
- if (key !== identity) { identity = key; ratios = seedWindow(ctx.sessionManager.getBranch(), key); factor = Math.max(1, ...ratios); learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), key); pending = undefined; }
250
- return key;
312
+ calibration.select(ctx);
313
+ if (calibration.needsSeed(ctx)) calibration.reseed(ctx, "identity");
314
+ return calibration.identity;
251
315
  };
316
+ pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
252
317
  const contextWindow = (ctx: ExtensionContext) => {
253
318
  identityFor(ctx);
254
- return Math.min(ctx.model?.contextWindow ?? 0, learnedContextWindow ?? Infinity);
319
+ return Math.min(ctx.model?.contextWindow ?? 0, calibration.learnedContextWindow ?? Infinity);
255
320
  };
256
321
  // This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
257
322
  // An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
258
323
  pi.on("before_provider_request", event => {
259
- if (!pending || !event.payload || typeof event.payload !== "object") return;
324
+ if (!calibration.pending || !event.payload || typeof event.payload !== "object") return;
260
325
  const payload = event.payload as Record<string, unknown>;
261
326
  // Read at reply time so later in-place payload edits are included too.
262
- pending.requestedMaxTokens = () => {
327
+ calibration.pending.requestedMaxTokens = () => {
263
328
  const cap = payload.max_tokens ?? payload.max_completion_tokens ?? payload.max_output_tokens;
264
329
  return typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0 ? cap : undefined;
265
330
  };
266
331
  });
267
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.
268
- const learn = (value: number) => { ratios.push(value); if (ratios.length > CALIBRATION_WINDOW) ratios.shift(); factor = Math.max(1, ...ratios); };
269
- 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); };
270
335
  const observeBudget = (rawTokens: number, ctx: ExtensionContext) => {
271
- 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 });
272
337
  };
273
338
  // The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
274
339
  const planReserve = (target: Target, room: number, band: number, mandatory: number, ctx: ExtensionContext) => {
275
340
  identityFor(ctx);
276
341
  // The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
277
- 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);
278
343
  };
279
344
  pi.on("message_end", (event, ctx) => {
280
345
  if (event.message.role !== "assistant") return;
346
+ if (standDown(ctx)) return;
281
347
  const responseMessage = event.message;
282
348
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
283
349
  if (!responseMessage.content.some(b => b.type === "thinking")) recorder.capture("response-actions", "native-public-message-end", responseMessage);
284
350
  else recorder.capture("response-actions", "hidden-material-excluded", { stopReason: responseMessage.stopReason }, true);
285
351
  recorder.responded(responseMessage.stopReason);
286
352
  });
287
- const paired = pending; pending = undefined;
353
+ const paired = calibration.pending; calibration.pending = undefined;
288
354
  const key = identityFor(ctx), message = event.message;
289
355
  const overflow = message.stopReason === "error" && isContextOverflow(message);
290
356
  if (!paired || !key || paired.identity !== key || !active() || failure() || ctx.signal?.aborted || (message.errorMessage && !overflow) ||
@@ -298,8 +364,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
298
364
  if (overflow) {
299
365
  const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
300
366
  const learned = bound <= CALIBRATION_CEILING;
301
- ctx.ui.notify(overflowNotice(window, bound, learned), "warning");
302
- if (learned) learn(bound);
367
+ notify(ctx, overflowNotice(window, bound, learned), "warning");
368
+ if (learned) learn(bound, ctx);
303
369
  return;
304
370
  }
305
371
  const usage = message.usage;
@@ -311,36 +377,37 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
311
377
  if (message.stopReason === "length" && requested !== undefined &&
312
378
  Number.isSafeInteger(output) && output >= 0 && output < requested &&
313
379
  Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
314
- learnedContextWindow = Math.min(learnedContextWindow ?? Infinity, bound);
380
+ calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
315
381
  serverClipped.add(message);
316
- windowObservation = { message, identity: key, window: learnedContextWindow };
382
+ calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow };
317
383
  }
318
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.
319
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
320
386
  // 6,000-token prompt refuse. The overflow branch above learns from a refusal, where the count is a lower bound, and the ceiling is unchanged.
321
- if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio)) learn(ratio);
387
+ if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio)) learn(ratio, ctx);
322
388
  });
323
- pi.on("turn_end", event => {
324
- if (windowObservation?.message !== event.message) return;
325
- const observation = windowObservation; windowObservation = undefined;
389
+ pi.on("turn_end", (event, ctx) => {
390
+ if (standDown(ctx)) return;
391
+ if (calibration.windowObservation?.message !== event.message) return;
392
+ const observation = calibration.windowObservation; calibration.windowObservation = undefined;
326
393
  pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
327
394
  serverClippedReplyId: event.messageEntryId } satisfies WindowReceipt);
328
395
  });
329
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
330
397
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
331
398
  let lengthStop = false;
332
- pi.on("agent_start", () => { 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; });
333
400
  pi.on("message_end", event => { if (event.message.role === "assistant") lengthStop = event.message.stopReason === "length"; });
334
401
  pi.on("agent_settled", (_event, ctx) => {
335
402
  try {
336
- if (!lengthStop || !active()) return;
403
+ if (standDown(ctx) || !lengthStop || !active()) return;
337
404
  lengthStop = false;
338
405
  const message = "pi-tuck: the last reply stopped at the model's output limit and may be cut off. Ask the agent to continue.";
339
- try { if (ctx.hasUI === false) process.stderr.write(message + "\n"); else ctx.ui.notify(message, "warning"); } catch { /* ended */ }
406
+ notify(ctx, message, "warning");
340
407
  } finally { resetRun(); }
341
408
  });
342
409
  const active = () => options.active?.() ?? true;
343
- const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings());
410
+ const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings?.());
344
411
  // The one reserve decision; every consumer takes its room from limits. Standalone starts at Pi's native cut point. Once a reply did
345
412
  // not fit (a length stop with text/tools, or a refusal pi-ai classes as a context overflow), hold the catalogue maximum too. A thinking-only
346
413
  // length stop uses branchReplyFloor's observed output instead; reserving the catalogue maximum would strand setups above the room.
@@ -357,7 +424,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
357
424
  const inputRoom = (response: number, ctx: ExtensionContext) => {
358
425
  const configured = options.activeInputTokens;
359
426
  const ceiling = typeof configured === "function" ? configured(ctx) : configured;
360
- lastCeiling = ceiling ?? null;
427
+ calibration.lastCeiling = ceiling ?? null;
361
428
  if (ceiling !== undefined && (!Number.isSafeInteger(ceiling) || ceiling <= 0))
362
429
  throw new Error("Invalid active-input token ceiling");
363
430
  return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
@@ -366,14 +433,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
366
433
  const limits = (ctx: ExtensionContext) => {
367
434
  const { response } = requestReserve(ctx), room = inputRoom(response, ctx);
368
435
  const floor = options.requestReserve ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model?.maxTokens);
369
- 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);
370
437
  return { response, room, hardLine, replyFloor: floor };
371
438
  };
372
439
  const decisionBand = (ctx: ExtensionContext, room: number, system: number, current = view(ctx)) => {
373
440
  const last = current.session.getBranch().findLast(entry => entry.type === "compaction");
374
441
  const after = last?.type === "compaction" ? (last.details as { tokensAfter?: unknown } | undefined)?.tokensAfter : undefined;
375
442
  return bandOf(room, cutAt, options.cutAt === undefined && typeof after === "number" && Number.isFinite(after) && after >= 0
376
- ? { system, tokensAfter: after, factor } : undefined);
443
+ ? { system, tokensAfter: after, factor: calibration.factor } : undefined);
377
444
  };
378
445
  const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
379
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).
@@ -444,24 +511,25 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
444
511
  const receipt = (kind: "refusal" | "above-room", reason: string, ctx: ExtensionContext) => {
445
512
  let room: number | null = null, hardLine: number | null = null;
446
513
  try { ({ room, hardLine } = limits(ctx)); } catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
447
- 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 });
448
515
  };
449
516
  const fail = (error: unknown, ctx: ExtensionContext) => {
450
517
  recorder.stop("native-attempt-failed");
451
518
  // Every refusal says why, once per attempt: a capacity error with what the user can change, a cut Pi failed to commit with what that
452
519
  // means for the session, anything else as it is (an attempt that ended with no word looked like a hang).
453
- const previous = failure(), notify = !previous;
520
+ const previous = failure(), shouldNotify = !previous;
454
521
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
455
522
  const receipted = run?.refusalReceipted;
456
- resetRun();
457
- // Keep only a terminal attempt record until Pi settles: its fresh abort controller must still see the refusal.
458
- run = createRun("failed"); run.failure = fault; run.refusalReceipted = true;
459
- 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;
460
528
  try {
461
529
  if (!receipted) receipt("refusal", fault.message, ctx);
462
530
  options.fail?.(error);
463
531
  } finally {
464
- try { if (notify) ctx.ui.notify(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
465
533
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
466
534
  : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error"); }
467
535
  finally { ctx.abort(); }
@@ -474,14 +542,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
474
542
  };
475
543
  pi.on("input", async (event, ctx) => {
476
544
  if (!ctx.isIdle() || run?.phase === "starting") return; // steering joins the existing run
477
- run = createRun("decided");
478
- const decision = run;
545
+ beginRun("decided");
546
+ const decision = run!;
479
547
  try { syncHistoryTools(ctx); await preflight(ctx, incomingTokens(event.text, event.images),
480
548
  [{ role: "user", content: [{ type: "text", text: event.text }, ...(event.images ?? [])], timestamp: 0 }], ctx.getSystemPrompt(), pi.getActiveTools()); syncHistoryTools(ctx); }
481
549
  catch (error) { fail(error, ctx); }
482
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
483
551
  // real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
484
- setImmediate(() => { if (run === decision && !decision.claimed) decision.expired = true; });
552
+ setImmediate(() => { if (run === decision && decision.phase === "decided") decision.transition("expired", ctx); });
485
553
  });
486
554
 
487
555
  pi.registerTool({
@@ -533,12 +601,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
533
601
 
534
602
  pi.on("session_before_compact", (event, ctx) => {
535
603
  try {
604
+ if (standDown(ctx)) return;
536
605
  if (!active()) return { cancel: true };
537
606
  if (event.signal.aborted || ctx.signal?.aborted) { recorder.stop("cut-cancelled"); return { cancel: true }; }
538
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,
539
608
  // is the answer, and it is saved before the first request.
540
- if (run?.phase === "decided" && !run.expired && event.reason === "threshold") {
541
- run.claimed = true;
609
+ if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
610
+ run.transition("claimed", ctx);
542
611
  if (view(ctx).pending) {
543
612
  access();
544
613
  const current = view(ctx), { type: _, ...compaction } = run.cut.take()!;
@@ -550,7 +619,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
550
619
  access();
551
620
  // pi-tuck's summary is built from the session itself, so text after /compact cannot steer it. The operator asked for a cut: make the one
552
621
  // plain /compact makes and say the text was not used, rather than cancel (which Pi shows as an error, with no cut).
553
- if (event.customInstructions?.trim()) ctx.ui.notify("pi-tuck: /compact ignores the text after it, since pi-tuck builds its summary from the session itself. Cutting as plain /compact does.", "info");
622
+ if (event.customInstructions?.trim()) notify(ctx, "pi-tuck: /compact ignores the text after it, since pi-tuck builds its summary from the session itself. Cutting as plain /compact does.", "info");
554
623
  const { response, room } = limits(ctx);
555
624
  const retain = operatorManual || run?.phase === "admitted";
556
625
  // A cut Pi asks for (an operator's /compact, Pi's threshold or overflow recovery) charges what the request must carry whatever is
@@ -586,7 +655,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
586
655
  : { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
587
656
  },
588
657
  });
589
- estimatedTokens = corrected(before + mandatory, ctx);
658
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
590
659
  let decision: Decision<CutPlan> = decide();
591
660
  const { hardLine } = limits(ctx);
592
661
  if (!operatorManual && hardLine > room && decision.kind === "fault") {
@@ -602,7 +671,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
602
671
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
603
672
  if (decision.kind === "none" || decision.kind === "defer") return { cancel: true };
604
673
  recorder.stop("no-cut");
605
- ctx.ui.notify(decision.message, "warning");
674
+ notify(ctx, decision.message, "warning");
606
675
  if (operatorManual) receipt("refusal", decision.message, ctx);
607
676
  if (!operatorManual) fail(new (decision.capacity ? CapacityError : Refusal)(decision.message), ctx);
608
677
  return { cancel: true };
@@ -610,21 +679,21 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
610
679
  try { fail(error, ctx); } finally { return { cancel: true }; }
611
680
  }
612
681
  });
613
- pi.on("session_before_tree", (event) => event.preparation.userWantsSummary ? { cancel: true } : undefined);
614
- pi.on("session_start", () => { resetRun(); recorder.stop("session-transition"); proposalId = undefined; commitFault = undefined; estimatedTokens = 0; identity = ""; factor = 1; learnedContextWindow = undefined; windowObservation = undefined; });
615
- const historyToolsEnabled = (ctx: ExtensionContext) => view(ctx).hasTuckCut;
682
+ pi.on("session_before_tree", (event, ctx) => !standDown(ctx) && event.preparation.userWantsSummary ? { cancel: true } : undefined);
683
+ pi.on("session_start", (_event, ctx) => { resetRun(true); recorder.stop("session-transition"); proposalId = undefined; calibration.reseed(ctx, "session"); });
684
+ const historyToolsEnabled = (ctx: ExtensionContext) => stateFor(ctx).kind === "active" && view(ctx).hasTuckCut;
616
685
  const syncHistoryTools = (ctx: ExtensionContext) => { if (active()) applyHistoryTools(pi, historyToolsEnabled(ctx)); };
617
686
  pi.on("session_start", (_event, ctx) => syncHistoryTools(ctx));
618
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
619
688
  // may not be on this one.
620
- pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), identityFor(ctx)); syncHistoryTools(ctx); });
689
+ pi.on("session_tree", (_event, ctx) => { resetRun(); calibration.reseed(ctx, "tree"); syncHistoryTools(ctx); });
621
690
  pi.on("session_compact", (_event, ctx) => { if (run?.phase !== "admitted") syncHistoryTools(ctx); });
622
691
  pi.on("turn_start", (_event, ctx) => syncHistoryTools(ctx));
623
692
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
624
693
  const plannedView = (ctx: ExtensionContext, cut: CutEntry) => {
625
- const pending = new PendingCut();
626
- pending.plan(cut, ctx.sessionManager.getBranch().length);
627
- return pending.view(ctx);
694
+ const preview = new PendingCut();
695
+ preview.plan(cut, ctx.sessionManager.getBranch().length);
696
+ return preview.view(ctx);
628
697
  };
629
698
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
630
699
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
@@ -661,6 +730,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
661
730
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
662
731
  // Pi's defaults on a 32k window). Each request of the run carries the cut, and the run's first boundary saves it.
663
732
  const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages) => {
733
+ if (standDown(ctx)) return;
664
734
  run!.cut.clear();
665
735
  const branchLength = ctx.sessionManager.getBranch().length;
666
736
  if (!active()) return;
@@ -675,7 +745,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
675
745
  const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
676
746
  const incoming = incomingPart + system, mandatory = incoming + host;
677
747
  observeBudget(before + mandatory, ctx);
678
- estimatedTokens = corrected(before + mandatory, ctx);
748
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
679
749
  if (!fits(incoming, limits(ctx).hardLine, ctx))
680
750
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
681
751
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
@@ -719,13 +789,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
719
789
  run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
720
790
  };
721
791
  pi.on("before_agent_start", async (event, ctx) => {
792
+ if (standDown(ctx)) return;
722
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
723
794
  // input, so no run started for it): plan afresh.
724
- const prompted = run?.phase === "decided" && event.messageType !== "custom";
725
- 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");
726
797
  run ??= createRun("starting");
727
- run.claimed = true;
728
- run.phase = "starting";
798
+ if (!failure() && run.phase !== "starting") run.transition("starting", ctx);
729
799
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
730
800
  run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
731
801
  try {
@@ -747,6 +817,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
747
817
  // handlers have run. Pi's prepareRequest has not yet snapshotted executable tools. A first cut discovered in context_with_system
748
818
  // would be too late for that snapshot, even if its declarations were repaired there, so make the late prompt decision here.
749
819
  pi.on("message_end", (event, ctx) => {
820
+ if (standDown(ctx)) return;
750
821
  if (event.message.role !== "user" || !active() || run?.phase !== "admitted" || view(ctx).pending) return;
751
822
  try {
752
823
  access();
@@ -852,7 +923,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
852
923
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
853
924
  const kept = previews.length ? Math.max(...previews.map(preview => measure(preview.filter(message =>
854
925
  !(message.role === "toolResult" && fresh.has((message as ToolResultMessage).toolCallId)))))) : floorKept;
855
- for (const budget of clipBudgets(clipRoom, factor, mandatory, kept)) {
926
+ for (const budget of clipBudgets(clipRoom, calibration.factor, mandatory, kept)) {
856
927
  const round = clipFor(event.toolResults, entryIdOf, budget);
857
928
  if (!round.length) continue;
858
929
  for (const clip of round) run!.clips.set(clip.toolCallId, clip);
@@ -864,7 +935,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
864
935
  tryClips(room, band);
865
936
  const before = measure(saved);
866
937
  observeBudget(before + mandatory, ctx);
867
- estimatedTokens = corrected(before + mandatory, ctx);
938
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
868
939
  const { hardLine } = limits(ctx);
869
940
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
870
941
  if (fits(before + mandatory, hardLine, ctx)) decision = { kind: "none" };
@@ -895,7 +966,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
895
966
  const markBoundary = (entries: readonly SessionBoundaryDraft[]) => {
896
967
  if (!run) return;
897
968
  run.pendingBoundaryReceipts = entries.flatMap(entry => entry.type === "compaction" ? receiptId(entry) ?? [] : []);
898
- run.pendingBoundaryCommit = run.pendingBoundaryReceipts.length > 0;
899
969
  };
900
970
  const boundarySaved = (ctx: ExtensionContext) => {
901
971
  const wanted = run?.pendingBoundaryReceipts ?? [];
@@ -928,7 +998,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
928
998
  // Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
929
999
  const entries: SessionBoundaryDraft[] = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
930
1000
  { type: "context_edit", targetId: event.messageEntryId, replacement: null }];
931
- if (run!.thinkingRetryPending) return { entries, continue: false };
1001
+ if (run!.thinkingRetryPending) { markBoundary(entries); return { entries, continue: false }; }
932
1002
  const preview = liveCut.view(ctx, entries).session;
933
1003
  const view: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
934
1004
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
@@ -943,9 +1013,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
943
1013
  clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
944
1014
  const { room, hardLine } = limits(view);
945
1015
  run!.thinkingRetryPending = true;
946
- return { entries: [...entries, { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
1016
+ const drafts = [...entries, { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
947
1017
  stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: false,
948
- piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }], continue: true };
1018
+ piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
1019
+ markBoundary(drafts);
1020
+ return { entries: drafts, continue: true };
949
1021
  }
950
1022
  if (decision.kind !== "cut") throw new CapacityError(clampMessage);
951
1023
  const messages = projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true);
@@ -971,6 +1043,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
971
1043
  };
972
1044
  pi.on("turn_end", (event, ctx) => {
973
1045
  try {
1046
+ if (standDown(ctx)) return;
974
1047
  if (!active() || run?.phase !== "admitted") return;
975
1048
  if ((thinkingOnlyLength(event.message) || serverClipped.has(event.message)) && !failure() && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
976
1049
  return retryLength(event, ctx);
@@ -1061,6 +1134,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1061
1134
  };
1062
1135
  pi.on("context", (event, ctx) => {
1063
1136
  try {
1137
+ if (standDown(ctx)) return;
1064
1138
  if (!active()) return;
1065
1139
  run?.prompt?.id(ctx.sessionManager.getBranch());
1066
1140
  // Before a cut, Pi owns the whole request, including its object identities and system-message serialization.
@@ -1070,6 +1144,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1070
1144
  } catch (error) { try { fail(error, ctx); } finally { return historyToolsEnabled(ctx) ? { messages: [] } : undefined; } }
1071
1145
  });
1072
1146
  pi.on("session_compact_failed", (event, ctx) => {
1147
+ if (standDown(ctx)) return;
1073
1148
  // This compactor's own refusal of a Pi threshold ask (the gate, or an opportunistic cut that cannot reach the band) reaches here as a
1074
1149
  // threshold compaction cancelled and not from an extension: no event for the recorder.
1075
1150
  if (event.reason === "threshold" && event.aborted && !event.fromExtension) return;
@@ -1084,12 +1159,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1084
1159
  if (active() && !event.aborted) fail(new (event.fromExtension ? CommitFault : Error)(event.errorMessage ?? "Compaction failed"), ctx);
1085
1160
  });
1086
1161
  pi.on("agent_before_settle", (event, ctx) => {
1087
- if (run?.pendingBoundaryCommit) {
1162
+ if (standDown(ctx)) return;
1163
+ if (run?.pendingBoundaryReceipts.length) {
1088
1164
  if (event.outcome === "error") {
1089
1165
  try { if (!boundarySaved(ctx)) throw new Error("Boundary receipt absent from the session file"); }
1090
1166
  catch { return void fail(new CommitFault("Native tool-loop boundary cut was not saved in the session file"), ctx); }
1091
1167
  }
1092
- if (run) { run.pendingBoundaryCommit = false; run.pendingBoundaryReceipts = []; }
1168
+ if (run) { run.pendingBoundaryReceipts = []; }
1093
1169
  }
1094
1170
  // Pi commits these entries before the run settles.
1095
1171
  try {
@@ -1100,9 +1176,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1100
1176
  } catch (error) { fail(error, ctx); }
1101
1177
  });
1102
1178
  pi.on("context_with_system", (event, ctx) => {
1179
+ if (standDown(ctx)) return;
1103
1180
  // Reaching the next request boundary proves native commit returned, not durable storage.
1104
- if (run) { run.pendingBoundaryCommit = false; run.pendingBoundaryReceipts = []; }
1105
- pending = undefined;
1181
+ if (run) { run.pendingBoundaryReceipts = []; }
1182
+ calibration.pending = undefined;
1106
1183
  try {
1107
1184
  if (!active()) return;
1108
1185
  access();
@@ -1123,16 +1200,16 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1123
1200
  assertNativeToolRounds(messages);
1124
1201
  }
1125
1202
  observeBudget(tokens, ctx);
1126
- estimatedTokens = corrected(tokens, ctx);
1203
+ calibration.estimatedTokens = corrected(tokens, ctx);
1127
1204
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1128
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");
1129
1206
  if (!fits(tokens, hardLine, ctx))
1130
1207
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1131
1208
  // Pi's request estimator and its compaction estimator need not agree. The hard line is
1132
1209
  // necessary; above the room, also require the real request clamp to preserve the floor.
1133
- if (!options.requestReserve && estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1210
+ if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1134
1211
  throw new CapacityError(clampMessage);
1135
- 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);
1136
1213
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
1137
1214
  recorder.request();
1138
1215
  // No system prompt or hidden assistant blocks; no provider payload/headers.
@@ -1141,14 +1218,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1141
1218
  !(m.role === "custom" && options.recallPolicy?.privateCustomTypes?.includes(m.customType)));
1142
1219
  recorder.capture("prepared-request", "public-context-with-system-hook-before-later-transforms-not-wire", { messages: permitted, estimatedInputTokens: tokens }, permitted.length !== event.messages.length);
1143
1220
  });
1144
- if (tokens > 0 && Number.isSafeInteger(tokens)) pending = {
1221
+ if (tokens > 0 && Number.isSafeInteger(tokens)) calibration.pending = {
1145
1222
  identity: identityFor(ctx), tokens, messages, snapshot: structuredClone(convertToLlm(messages)),
1146
1223
  };
1147
1224
  if (messages !== event.messages) return { messages };
1148
1225
 
1149
1226
  } catch (error) { fail(error, ctx); }
1150
1227
  });
1151
- return {close:async()=>{semanticRequest++;recorder.stop("caller-close");await semantic.close();await Promise.allSettled([...semanticPending]);}, semanticRecall:semantic, setSemanticEnabled, semanticStatus};
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 })};
1152
1229
  }
1153
1230
 
1154
1231
  function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }