pi-tuck 1.10.2 → 1.10.5

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +2 -2
  3. package/dist/src/budget.d.ts +0 -2
  4. package/dist/src/budget.js +1 -3
  5. package/dist/src/build-id.d.ts +1 -1
  6. package/dist/src/build-id.js +1 -1
  7. package/dist/src/compaction.d.ts +1 -4
  8. package/dist/src/compaction.js +46 -18
  9. package/dist/src/content-observations.d.ts +0 -6
  10. package/dist/src/content-observations.js +5 -5
  11. package/dist/src/diagnostic-replay.js +6 -6
  12. package/dist/src/diagnostics.d.ts +0 -1
  13. package/dist/src/diagnostics.js +2 -3
  14. package/dist/src/history-image.d.ts +0 -2
  15. package/dist/src/history-image.js +1 -1
  16. package/dist/src/kept-reads.d.ts +3 -0
  17. package/dist/src/kept-reads.js +51 -0
  18. package/dist/src/omissions.d.ts +3 -6
  19. package/dist/src/omissions.js +3 -10
  20. package/dist/src/recall.js +2 -2
  21. package/dist/src/thrash.d.ts +0 -6
  22. package/dist/src/thrash.js +1 -1
  23. package/dist/src/tuck/core/format.d.ts +2 -0
  24. package/dist/src/tuck/core/format.js +3 -0
  25. package/dist/src/tuck/core/token-estimate.d.ts +2 -8
  26. package/dist/src/tuck/core/token-estimate.js +3 -9
  27. package/dist/src/tuck/core/tool-args.d.ts +0 -1
  28. package/dist/src/tuck/core/tool-args.js +1 -1
  29. package/dist/src/tuck/core/transcript.d.ts +3 -2
  30. package/dist/src/tuck/cut.d.ts +0 -1
  31. package/dist/src/tuck/cut.js +0 -3
  32. package/dist/src/tuck.d.ts +2 -2
  33. package/dist/src/tuck.js +16 -13
  34. package/package.json +1 -1
  35. package/src/budget.ts +1 -4
  36. package/src/build-id.ts +1 -1
  37. package/src/compaction.ts +42 -17
  38. package/src/content-observations.ts +5 -5
  39. package/src/diagnostic-replay.ts +7 -6
  40. package/src/diagnostics.ts +2 -3
  41. package/src/history-image.ts +1 -1
  42. package/src/kept-reads.ts +40 -0
  43. package/src/omissions.ts +3 -10
  44. package/src/recall.ts +3 -3
  45. package/src/thrash.ts +1 -7
  46. package/src/tuck/core/format.ts +3 -0
  47. package/src/tuck/core/token-estimate.ts +4 -20
  48. package/src/tuck/core/tool-args.ts +1 -1
  49. package/src/tuck/core/transcript.ts +2 -2
  50. package/src/tuck/cut.ts +0 -4
  51. package/src/tuck.ts +16 -13
  52. package/dist/src/tuck/core/render-entries.d.ts +0 -6
  53. package/dist/src/tuck/core/render-entries.js +0 -1
  54. package/src/tuck/core/render-entries.ts +0 -6
@@ -4,19 +4,13 @@ export const MAX_CHARS_PER_TOKEN = 6;
4
4
  const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
5
5
  export const calibrateCharsPerToken = (sourceChars, sourceTokens) => {
6
6
  if (!sourceTokens || sourceTokens <= 0 || sourceChars <= 0) {
7
- return { mode: "heuristic", charsPerToken: DEFAULT_CHARS_PER_TOKEN };
7
+ return { charsPerToken: DEFAULT_CHARS_PER_TOKEN };
8
8
  }
9
9
  const rawCharsPerToken = sourceChars / sourceTokens;
10
10
  if (!Number.isFinite(rawCharsPerToken) || rawCharsPerToken <= 0) {
11
- return { mode: "heuristic", charsPerToken: DEFAULT_CHARS_PER_TOKEN };
11
+ return { charsPerToken: DEFAULT_CHARS_PER_TOKEN };
12
12
  }
13
- return {
14
- mode: "calibrated",
15
- charsPerToken: clamp(rawCharsPerToken, MIN_CHARS_PER_TOKEN, MAX_CHARS_PER_TOKEN),
16
- sourceChars,
17
- sourceTokens,
18
- rawCharsPerToken,
19
- };
13
+ return { charsPerToken: clamp(rawCharsPerToken, MIN_CHARS_PER_TOKEN, MAX_CHARS_PER_TOKEN) };
20
14
  };
21
15
  export const estimateTokensFromChars = (chars, charsPerToken = DEFAULT_CHARS_PER_TOKEN) => Math.ceil(chars / charsPerToken);
22
16
  /**
@@ -1,2 +1 @@
1
- export declare const PATH_KEYS: readonly ["path", "file_path", "filePath", "file"];
2
1
  export declare const extractPath: (args: Record<string, unknown>) => string | null;
@@ -1,4 +1,4 @@
1
- export const PATH_KEYS = ["path", "file_path", "filePath", "file"];
1
+ const PATH_KEYS = ["path", "file_path", "filePath", "file"];
2
2
  export const extractPath = (args) => {
3
3
  for (const key of PATH_KEYS) {
4
4
  if (typeof args[key] === "string")
@@ -1,3 +1,4 @@
1
+ import { type SourceTime } from "./source-time.js";
1
2
  import type { HistoricalReceipt } from "../types.js";
2
3
  export declare const MAX_RECEIPT_CHARACTERS = 8000;
3
4
  export declare const MAX_PRODUCER_ARGUMENT_CHARACTERS = 1000;
@@ -5,10 +6,10 @@ export declare const RECEIPT_RANGE_NOTICE = "Incomplete original readable text a
5
6
  /** Only complete JSON arguments; serialization must not coerce or omit values. */
6
7
  export declare const smallOriginalArguments: (value: unknown, maxCharacters?: number) => value is Record<string, unknown>;
7
8
  interface RecordFields {
8
- sourceTime?: import("./source-time.js").SourceTime;
9
+ sourceTime?: SourceTime;
9
10
  sourceTimes?: ({
10
11
  sourceIndex: number;
11
- } & import("./source-time.js").SourceTime)[];
12
+ } & SourceTime)[];
12
13
  sourceEntryId?: string;
13
14
  role?: "user" | "assistant" | "custom" | "bashExecution" | "toolResult";
14
15
  sourceIndex?: number;
@@ -19,7 +19,6 @@ export type OwnCutResult = {
19
19
  selectedIds: string[];
20
20
  firstKeptEntryId: string;
21
21
  compactAll: boolean;
22
- keptUserTurns: number;
23
22
  keepFallbackToCompactAll: boolean;
24
23
  budgetCut?: BudgetCutKind;
25
24
  } | {
@@ -67,7 +67,6 @@ export function buildOwnCut(branchEntries, keepUserTurns = 1) {
67
67
  selectedIds: liveMessages.map((e) => e.entry.id),
68
68
  firstKeptEntryId: "",
69
69
  compactAll: true,
70
- keptUserTurns: 0,
71
70
  keepFallbackToCompactAll,
72
71
  });
73
72
  if (normalizedKeepUserTurns <= 0)
@@ -88,7 +87,6 @@ export function buildOwnCut(branchEntries, keepUserTurns = 1) {
88
87
  selectedIds: liveMessages.slice(0, cutIdx).map((e) => e.entry.id),
89
88
  firstKeptEntryId: liveMessages[cutIdx].entry.id,
90
89
  compactAll: false,
91
- keptUserTurns: userIndices.length - targetUserIdx,
92
90
  keepFallbackToCompactAll: false,
93
91
  };
94
92
  }
@@ -138,7 +136,6 @@ export const applyTailBudget = (branchEntries, cut, opts = {}) => {
138
136
  selectedIds: live.slice(0, idx).map((m) => m.entry.id),
139
137
  firstKeptEntryId: live[idx].entry.id,
140
138
  compactAll: false,
141
- keptUserTurns: live.slice(idx).filter((m) => m.message.role === "user").length,
142
139
  keepFallbackToCompactAll: false,
143
140
  budgetCut,
144
141
  });
@@ -72,8 +72,8 @@ export declare const tuck: Tuck;
72
72
  /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
73
73
  * `_operatorManual` retains the exported positional slot for existing callers. */
74
74
  export declare function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy?: RecallPolicy, retainCurrentInput?: boolean, _operatorManual?: boolean, newPrompt?: boolean, protectedPromptEntryId?: string, keepRecentTokens?: number): Draft;
75
- /** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
76
- /** `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
75
+ /** Shared compiler observes canonical branch and current token estimate; no native preparation utility.
76
+ * `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
77
77
  * a run a custom message starts); the session has moved on from an ended run.
78
78
  * `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
79
79
  export declare function tuckObservedDraft(tuck: Tuck, input: {
package/dist/src/tuck.js CHANGED
@@ -2,12 +2,12 @@ import { resolveSourceTime } from "./tuck/core/source-time.js";
2
2
  import { orderByOriginalSource } from "./tuck/core/source-order.js";
3
3
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
4
4
  import { parseRecords, serializeTranscript, serializeRecord, splitSummary, TRANSCRIPT_HEADER } from "./tuck/core/transcript.js";
5
- import { closingSuffix, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format.js";
5
+ import { closingSuffix, DEEPEST_SUFFIX, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format.js";
6
6
  import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.js";
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content.js";
9
9
  import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
10
- import { keptReadCandidates } from "./kept-reads.js";
10
+ import { keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
11
11
  import { workingSetCandidates } from "./working-set.js";
12
12
  import { keptSearchCandidates } from "./kept-searches.js";
13
13
  import { fileObservations, thinkingRecords } from "./content-observations.js";
@@ -33,8 +33,8 @@ export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {},
33
33
  return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId,
34
34
  keepRecentTokens: event.preparation.settings?.keepRecentTokens ?? keepRecentTokens }, ctx, reserveTokens, measure, policy, retainCurrentInput);
35
35
  }
36
- /** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
37
- /** `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
36
+ /** Shared compiler observes canonical branch and current token estimate; no native preparation utility.
37
+ * `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
38
38
  * a run a custom message starts); the session has moved on from an ended run.
39
39
  * `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
40
40
  export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true) {
@@ -74,13 +74,12 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
74
74
  // made smaller. Inside the band a cut is opportunistic, and re-rendering there shrinks the summary and costs history for nothing (replays
75
75
  // s04-B task 13, s08-B task 23: a 13,008-token first request became 3,336), so an opportunistic cut refuses as it did before.
76
76
  else if (input.reRenderSummary && cut.reason === "no_live_messages" && entries.some(entry => entry.type === "compaction"))
77
- cut = { ok: true, messages: [], selectedIds: [], firstKeptEntryId: "", compactAll: true, keptUserTurns: 0, keepFallbackToCompactAll: false };
77
+ cut = { ok: true, messages: [], selectedIds: [], firstKeptEntryId: "", compactAll: true, keepFallbackToCompactAll: false };
78
78
  if (!cut.ok)
79
79
  return { unavailable: `pi-tuck cannot select a cut: ${cut.reason}` };
80
80
  const cutBefore = (cut, boundary, prefix) => ({
81
81
  ...cut, messages: prefix.messages, selectedIds: prefix.selectedIds,
82
82
  firstKeptEntryId: entries[boundary]?.id ?? "", compactAll: boundary === entries.length, keepFallbackToCompactAll: false,
83
- keptUserTurns: entries.slice(boundary).filter(entry => entry.type === "message" && entry.message.role === "user").length,
84
83
  });
85
84
  // The latest call's trailing receipts have not reached a subsequent response.
86
85
  // A preferred tail size must not erase this first exposure when the whole
@@ -327,9 +326,13 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
327
326
  // The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
328
327
  // existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
329
328
  if (input.deepest) {
330
- assertNativeToolRounds(floorProjection);
331
- const after = measure(floorProjection);
332
- return { compaction: { summary: floorSummary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
329
+ // The floor carries the outputs prompts asked for (capped at 8,000 characters) and closes without claiming lists it does not have.
330
+ const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, entry => readable(entry) !== undefined);
331
+ const summary = (serializeTranscript([...calibrationHigh.rows, ...outputs]) || TRANSCRIPT_HEADER + "\n") + DEEPEST_SUFFIX;
332
+ const projection = preview(summary, floorBoundary);
333
+ assertNativeToolRounds(projection);
334
+ const after = measure(projection);
335
+ return { compaction: { summary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
333
336
  details: { ...detailsAt(floorBoundary), tokensAfter: after, carriedTarget: after, view: "shrunk-dialogue", mode: "shrunk", deepest: true } }, after, mode: "shrunk" };
334
337
  }
335
338
  const offset = measure(floorProjection) - nativeAt(floorBoundary) - summaryTokens(floorSummary.length);
@@ -580,10 +583,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
580
583
  const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
581
584
  const counts = new Map();
582
585
  const prefix = [header, ...entries.slice(0, boundary)];
583
- // Reads and searches share the lead rank, newest result first, and one
584
- // allowance. Keep L2's independent four-item caps and whole-item skips.
585
- const candidates = [...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
586
- .sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
586
+ // Outputs a user prompt asked for lead (a message-driven agent's tasks); reads and searches follow, newest result first. One
587
+ // allowance; L2's independent four-item caps and whole-item skips.
588
+ const candidates = [...promptOutputCandidates(prefix, indices, resolvable), ...[...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
589
+ .sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"))];
587
590
  for (const record of candidates) {
588
591
  if ((counts.get(record.title) ?? 0) === 4)
589
592
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.10.2",
3
+ "version": "1.10.5",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/budget.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { getCurrentSystemMessage, type ImageContent } from "@earendil-works/pi-ai";
2
2
  import { convertToLlm, estimateTokens, type BeforeAgentStartEvent, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { measurableMessages, projectedMessages } from "./omissions.js";
3
+ import { projectedMessages } from "./omissions.js";
4
4
  import type { RecallPolicy } from "./recall.js";
5
5
  import { isDiscardedResponse } from "./protocol.js";
6
6
  import { MAX_TAIL_TOKENS } from "./tuck/cut.js";
@@ -92,9 +92,6 @@ export const requestTokens = (messages: Messages, systemPrompt: string): number
92
92
  /** The saved conversation as the model receives it from this compactor, counted after Pi's conversion. This is the planner's measure too. */
93
93
  export const projectedConversationTokens = (messages: Messages, ctx: ExtensionContext, policy?: RecallPolicy): number =>
94
94
  conversationTokens(projectedMessages(messages, ctx, policy));
95
- /** As `projectedConversationTokens`, but a summary that is not in this compactor's format is counted as it is instead of failing: what the planner measures with, so that a cut can replace one. */
96
- export const measurableConversationTokens = (messages: Messages, ctx: ExtensionContext, policy?: RecallPolicy): number =>
97
- conversationTokens(measurableMessages(messages, ctx, policy));
98
95
  /** Raw reserve for the cut planner: the window less the raw tokens that fit the target room, plus the input no cut can remove. */
99
96
  export const planningReserve = (window: number, targetRoom: number, factor: number, mandatory: number): number =>
100
97
  window - Math.floor(targetRoom / factor) + mandatory;
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "40fe96e6b860dcdd5a9a060eac86b30698e64e377f1d2c4d9e243308cb2a6bf9";
1
+ export const BUILD_ID = "092a7cfa8000bf0285eb4fd76580b229336faaf9af7b50d3c30b11d0f1a8d787";
package/src/compaction.ts CHANGED
@@ -2,7 +2,7 @@ import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run, type CutEntry } from "./run.js";
3
3
  import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
- import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry, type Receipt, type RecorderOptions } from "./diagnostics.js";
5
+ import { IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry, type Receipt, type RecorderOptions } from "./diagnostics.js";
6
6
  import { createHash } from "node:crypto";
7
7
  import { readFileSync } from "node:fs";
8
8
  import { homedir } from "node:os";
@@ -12,14 +12,13 @@ import { isDeepStrictEqual } from "node:util";
12
12
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
13
13
  import { projectedMessages } from "./omissions.js";
14
14
  import { applyClips, clipBudgets, clipFor, type Clip } from "./clip.js";
15
- import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt,
15
+ import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt,
16
16
  type AgentMessage, type Decision, type Messages, type Plan, type Target } from "./budget.js";
17
17
  import { getCurrentSystemMessage, isContextOverflow, normalizeContext, type ImageContent, type ToolResultMessage } from "@earendil-works/pi-ai";
18
18
  import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
19
19
  import { Type } from "typebox";
20
20
  import { Check } from "typebox/value";
21
- import type { RecallPolicy } from "./recall.js";
22
- import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
21
+ import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS, type RecallPolicy } from "./recall.js";
23
22
 
24
23
  import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
25
24
  import { thrashing } from "./thrash.js";
@@ -65,7 +64,6 @@ export const refusalNotice = (message: string, factor: number): string =>
65
64
  export const overflowNotice = (contextWindow: number, bound: number, learned: boolean): string =>
66
65
  `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
67
66
  (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
68
- /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
69
67
  /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
70
68
  export const capStopNotice = (model: string, maxTokens: number, file: string) =>
71
69
  `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
@@ -74,7 +72,7 @@ export const capStopNotice = (model: string, maxTokens: number, file: string) =>
74
72
  /** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
75
73
  export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
76
74
  /** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
77
- export const ACT_NOW_LIMIT = 2;
75
+ const ACT_NOW_LIMIT = 2;
78
76
  /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
79
77
  * or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
80
78
  export function actNowsInARow(branch: readonly SessionEntry[]): number {
@@ -204,10 +202,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
204
202
  const piClamp = piMath?.clampMaxTokensToContext;
205
203
  const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
206
204
  if (!validCutAt(cutAt)) throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
207
- const hostAccess = () => {
208
- if (!active()) throw new Error("Compaction host is inactive");
209
- options.assertAccess?.();
210
- };
211
205
  const view = (ctx: ExtensionContext, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
212
206
  const liveCut = new PendingCut();
213
207
  const recorder = new IncidentRecorder(options.diagnostics);
@@ -223,7 +217,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
223
217
  proposalId = receiptId(attached);
224
218
  if (recorder.enabled) { try {
225
219
  const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
226
- recorder.capture("replay-input", "reconstruction-from-existing-native-history", { build: DIAGNOSTIC_BUILD, receiptId: proposalId, entries: filtered.entries, branchEntryIds: ctx.sessionManager.getBranch().map(e => e.id), header: ctx.sessionManager.getHeader(), contextWindow: ctx.model?.contextWindow, reserve, tokensBefore, retainCurrentInput, operatorManual, previousSummary }, filtered.partial || Boolean(options.recallPolicy?.readAttemptMarker));
220
+ recorder.capture("replay-input", "reconstruction-from-existing-native-history", { build: BUILD_ID, receiptId: proposalId, entries: filtered.entries, branchEntryIds: ctx.sessionManager.getBranch().map(e => e.id), header: ctx.sessionManager.getHeader(), contextWindow: ctx.model?.contextWindow, reserve, tokensBefore, retainCurrentInput, operatorManual, previousSummary }, filtered.partial || Boolean(options.recallPolicy?.readAttemptMarker));
227
221
  recorder.capture("proposal", "selected-draft-not-saved", attached);
228
222
  } catch { recorder.stop("capture-failed-gap"); } }
229
223
  return attached;
@@ -442,7 +436,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
442
436
  // The planner counts with the same function, except that it does not fail on a summary in another format: a cut can replace one
443
437
  // (an operator's /compact repairs a session whose saved summary is foreign). Identical to the strict one for this compactor's summaries.
444
438
  const plannerMeasureFor = (ctx: ExtensionContext) => Object.assign(
445
- (messages: Messages) => measurableConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy),
439
+ (messages: Messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy),
446
440
  { messageTokens: (message: Messages[number]) => conversationTokens(applyClips([message], clips())) });
447
441
  const hostMessages = (ctx: ExtensionContext) => options.hostMessages?.(ctx) ?? [];
448
442
  const toolShapes = (names: Iterable<string>) => {
@@ -553,7 +547,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
553
547
 
554
548
  const access = () => {
555
549
  if (failure()) throw failure();
556
- hostAccess();
550
+ if (!active()) throw new Error("Compaction host is inactive");
551
+ options.assertAccess?.();
557
552
  };
558
553
  pi.on("input", async (event, ctx) => {
559
554
  if (!ctx.isIdle() || run?.phase === "starting") return; // steering joins the existing run
@@ -1060,6 +1055,36 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1060
1055
  markBoundary(entries);
1061
1056
  return { entries, continue: false };
1062
1057
  };
1058
+ // A retry's cut is an ordinary planned cut (summary with the action and file lists and kept results), shrunk until Pi's own clamp gives
1059
+ // the raised reply room, at most three times. Only when no such plan exists does the retry fall back to the deepest floor.
1060
+ const retryDecision = (ctx: ExtensionContext, asIs: Messages, host: Messages, pending: Messages): Extract<Decision<CutPlan>, { kind: "cut" }> | undefined => {
1061
+ const saved = ctx.sessionManager.buildSessionProjection().messages, before = conversationTokens(projectContext(saved, ctx));
1062
+ const mandatory = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), asIs, ctx.getSystemPrompt()) + conversationTokens(host) + conversationTokens(pending);
1063
+ const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
1064
+ const { response, room } = limits(ctx), want = response - piMargin, band = decisionBand(ctx, room);
1065
+ let target = room;
1066
+ for (let attempt = 0; attempt < 4 && fits(mandatory, target, ctx); attempt++) {
1067
+ const targetBand = target === room ? band : target;
1068
+ const decision = chooseCut<CutPlan>({ before, mandatory, room: target, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), opportunistic: false,
1069
+ unreduced: "Length-retry compaction did not reduce context within the estimated request budget",
1070
+ plan: (kind): Plan<CutPlan> => {
1071
+ const reserve = planReserve(kind, target, targetBand, mandatory, ctx);
1072
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
1073
+ protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
1074
+ if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
1075
+ const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
1076
+ assertNativeToolRounds(kept);
1077
+ return { draft: true, after: measureFor(ctx)(kept), compaction: draft.compaction, reserve, messages: kept };
1078
+ },
1079
+ });
1080
+ if (decision.kind !== "cut") return undefined;
1081
+ const check = requestClamp(projectedRequest(decision.plan.messages, ctx, host, pending, ctx.getSystemPrompt(), pi.getActiveTools(), true), ctx);
1082
+ if (check.cap === undefined) return undefined;
1083
+ if (check.leavesFloor && check.cap >= want) return decision;
1084
+ target = Math.floor(target * (check.estimate - (want - check.cap)) / check.estimate);
1085
+ }
1086
+ return undefined;
1087
+ };
1063
1088
  const retryLength = (event: TurnEndEvent, ctx: ExtensionContext) => {
1064
1089
  // Exhausting the full per-request allowance is not evidence that input is too large.
1065
1090
  // Preserve the unfinished response; provider-native continuation owns this case.
@@ -1080,7 +1105,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1080
1105
  const asIs = projectedRequest(preview.buildSessionProjection().messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), false);
1081
1106
  const asIsCheck = requestClamp(asIs, view);
1082
1107
  const previousClips = new Map(clips());
1083
- const decision = deepestDecision(view, false, true);
1108
+ const decision = retryDecision(view, asIs, hostInput, event.context.pendingMessages) ?? deepestDecision(view, false, true);
1084
1109
  const cut = decision.kind === "cut" ? {
1085
1110
  ...decision,
1086
1111
  messages: projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true),
@@ -1171,7 +1196,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1171
1196
  };
1172
1197
  // A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
1173
1198
  // atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
1174
- const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): { messages: Messages; native?: boolean } => {
1199
+ const guardCut = (messages: Messages, tokens: number, ctx: ExtensionContext): { messages: Messages; native?: boolean } => {
1175
1200
  const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
1176
1201
  const before = conversationTokens(source), mandatory = tokens - before;
1177
1202
  const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room);
@@ -1257,7 +1282,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1257
1282
  try { if (!boundarySaved(ctx)) throw new Error("Boundary receipt absent from the session file"); }
1258
1283
  catch { return void fail(new CommitFault("Native tool-loop boundary cut was not saved in the session file"), ctx); }
1259
1284
  }
1260
- if (run) { run.pendingBoundaryReceipts = []; }
1285
+ run.pendingBoundaryReceipts = [];
1261
1286
  }
1262
1287
  // Pi commits these entries before the run settles.
1263
1288
  try {
@@ -1292,7 +1317,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1292
1317
  const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
1293
1318
  piClamp && !requestClamp(messages, ctx).leavesFloor;
1294
1319
  if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1295
- const cut = guardCut(messages, tokens, system, ctx);
1320
+ const cut = guardCut(messages, tokens, ctx);
1296
1321
  messages = cut.messages;
1297
1322
  native = Boolean(cut.native);
1298
1323
  system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
@@ -6,13 +6,13 @@ import { readableContentParts } from "./tuck/core/readable-content";
6
6
  import type { TranscriptRecord } from "./tuck/core/transcript";
7
7
  import { MAX_RECALL_CHARACTERS } from "./recall";
8
8
 
9
- export const MAX_OUTPUT_TAIL_LINES = 3;
10
- export const MAX_OUTPUT_TAIL_CHARACTERS = 200;
11
- export const MAX_DEFINITION_LINES = 40;
12
- export const MAX_DEFINITION_CHARACTERS = 800;
9
+ const MAX_OUTPUT_TAIL_LINES = 3;
10
+ const MAX_OUTPUT_TAIL_CHARACTERS = 200;
11
+ const MAX_DEFINITION_LINES = 40;
12
+ const MAX_DEFINITION_CHARACTERS = 800;
13
13
 
14
14
  /** Mechanical line matches only; no language detection or inferred symbols. */
15
- export const DEFINITION_PATTERNS: readonly RegExp[] = [
15
+ const DEFINITION_PATTERNS: readonly RegExp[] = [
16
16
  /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:func|def|function)\b/u,
17
17
  /^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:type|struct|interface|class)\b/u,
18
18
  /^\s*export\s+(?:const|let)\b/u,
@@ -1,21 +1,22 @@
1
1
  import { SessionManager, type ExtensionContext, type SessionEntry, type SessionHeader } from '@earendil-works/pi-coding-agent';
2
2
  import { tuck, tuckObservedDraft } from './tuck.js';
3
- import { measurableConversationTokens } from './budget.js';
4
- import { DIAGNOSTIC_BUILD, type IncidentRecord } from './diagnostics.js';
3
+ import { projectedConversationTokens } from './budget.js';
4
+ import { BUILD_ID } from './build-id.js';
5
+ import { type IncidentRecord } from './diagnostics.js';
5
6
  export function inspectIncident(records: IncidentRecord[]) {
6
7
  const inputs = records.filter(r => r.kind === 'replay-input');
7
8
  const results = inputs.map(record => {
8
9
  const i = record.data as { build?: string; receiptId?: string; entries?: SessionEntry[]; branchEntryIds?: string[]; header?: SessionHeader; contextWindow?: number; reserve?: number; tokensBefore?: number; retainCurrentInput?: boolean; operatorManual?: boolean; previousSummary?: string };
9
- if (record.partial || i.build !== DIAGNOSTIC_BUILD || !i.entries || !i.header || !Array.isArray(i.branchEntryIds) || i.branchEntryIds.some(id => typeof id !== 'string') || !Number.isSafeInteger(i.contextWindow) || !Number.isSafeInteger(i.reserve) || !Number.isSafeInteger(i.tokensBefore)) return { mode: 'partial-inspection', notice: 'Missing/redacted inputs or nonmatching build; no deterministic replay claim.' };
10
+ if (record.partial || i.build !== BUILD_ID || !i.entries || !i.header || !Array.isArray(i.branchEntryIds) || i.branchEntryIds.some(id => typeof id !== 'string') || !Number.isSafeInteger(i.contextWindow) || !Number.isSafeInteger(i.reserve) || !Number.isSafeInteger(i.tokensBefore)) return { mode: 'partial-inspection', notice: 'Missing/redacted inputs or nonmatching build; no deterministic replay claim.' };
10
11
  const manager = SessionManager.inMemory('/offline-compaction-replay', undefined, [i.header, ...i.entries]);
11
- if (i.branchEntryIds?.length) manager.branch(i.branchEntryIds.at(-1)!);
12
+ if (i.branchEntryIds.length) manager.branch(i.branchEntryIds.at(-1)!);
12
13
  const ctx = { sessionManager: manager, cwd: '/offline-compaction-replay', model: { contextWindow: i.contextWindow } } as unknown as ExtensionContext;
13
- const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary }, ctx, i.reserve!, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
14
+ const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary }, ctx, i.reserve!, messages => projectedConversationTokens(messages, ctx), {}, i.retainCurrentInput);
14
15
  const proposal = records.find(r => r.kind === 'proposal' && (r.data as { details?: { diagnosticReceipt?: { id?: string } } })?.details?.diagnosticReceipt?.id === i.receiptId)?.data as { summary?: string; firstKeptEntryId?: string } | undefined;
15
16
  const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
16
17
  return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference, meaning preservation, persistence or transmission claim.' };
17
18
  });
18
- return { build: DIAGNOSTIC_BUILD, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
19
+ return { build: BUILD_ID, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
19
20
  }
20
21
  export function readableIncident(records: IncidentRecord[]): string {
21
22
  return '# Compaction incident\n\n' + JSON.stringify(inspectIncident(records), null, 2) + '\n\n' + records.map(r => `## ${r.kind} (${r.scope})${r.partial ? ' — PARTIAL' : ''}\n\n${JSON.stringify(r.data, null, 2)}`).join('\n\n');
@@ -7,11 +7,10 @@ import { homedir } from 'node:os';
7
7
  import { createRecall, type RecallPolicy } from './recall.js';
8
8
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
9
9
  import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
10
- export const DIAGNOSTIC_BUILD = BUILD_ID;
11
10
  export interface Receipt { id: string; build: string; reason: string; selectedView: string; boundary: string; settings: { draftReservedTokens: number; contextWindow: number; responseReserveTokens?: number; hostInputTokens?: number; mandatoryInputTokens?: number; target?: 'band' | 'room'; triggerMarginTokens?: number; cutAt?: number; calibrationFactor?: number; calibrationWindow?: number[]; calibrationIdentity?: string; activeInputCeilingTokens?: number | null }; before: { value: number; unit: 'estimated-input-tokens'; scope: 'native-preparation' | 'public-conversation' }; after: { value: number | null; unit: 'estimated-input-tokens'; scope: 'draft-preview' }; }
12
11
  export function attachReceipt<T extends { details?: unknown; firstKeptEntryId: string; tokensBefore: number }>(draft: T, reason: string, reserveTokens: number, contextWindow: number, resolved: Partial<Receipt['settings']> = {}): T & { details: Record<string, unknown> & { diagnosticReceipt: Receipt } } {
13
12
  const details = draft.details && typeof draft.details === 'object' ? draft.details as Record<string, unknown> : {};
14
- const receipt: Receipt = { id: randomUUID(), build: DIAGNOSTIC_BUILD, reason, selectedView: typeof details.view === 'string' ? details.view : 'deterministic-selected-draft', boundary: draft.firstKeptEntryId, settings: { draftReservedTokens: reserveTokens, contextWindow, ...resolved }, before: { value: draft.tokensBefore, unit: 'estimated-input-tokens', scope: reason === 'tool-loop' || reason === 'run-end' || reason === 'prompt' ? 'public-conversation' : 'native-preparation' }, after: { value: typeof details.tokensAfter === 'number' ? details.tokensAfter : null, unit: 'estimated-input-tokens', scope: 'draft-preview' } };
13
+ const receipt: Receipt = { id: randomUUID(), build: BUILD_ID, reason, selectedView: typeof details.view === 'string' ? details.view : 'deterministic-selected-draft', boundary: draft.firstKeptEntryId, settings: { draftReservedTokens: reserveTokens, contextWindow, ...resolved }, before: { value: draft.tokensBefore, unit: 'estimated-input-tokens', scope: reason === 'tool-loop' || reason === 'run-end' || reason === 'prompt' ? 'public-conversation' : 'native-preparation' }, after: { value: typeof details.tokensAfter === 'number' ? details.tokensAfter : null, unit: 'estimated-input-tokens', scope: 'draft-preview' } };
15
14
  return { ...draft, details: { ...details, diagnosticReceipt: receipt } };
16
15
  }
17
16
  export function receiptId(entry: { details?: unknown }): string | undefined {
@@ -82,7 +81,7 @@ export class IncidentRecorder {
82
81
  if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) { notify('Recorder directory must be outside project'); return; }
83
82
  this.projectDirectory = resolve(project); this.notify = notify; this.state = 'recording'; this.nextCut = nextCut; this.sawCut = false; this.requests = 0; this.response = false; this.total = 0; this.captureCalls = 0; this.inlineMs = 0; this.hookMs = 0; this.id = randomUUID(); this.path = join(this.directory, 'tuck-incident-' + this.id + '.jsonl');
84
83
  this.timer = setTimeout(() => this.stop(this.sawCut ? 'duration-exhausted' : 'no-cut-expired'), this.options.durationMs); this.timer.unref();
85
- this.capture('start', 'operator-session-control', { id: this.id, build: DIAGNOSTIC_BUILD, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. Secrets without recognizable patterns may remain.' });
84
+ this.capture('start', 'operator-session-control', { id: this.id, build: BUILD_ID, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. Secrets without recognizable patterns may remain.' });
86
85
  }
87
86
  measureInline<T>(operation: () => T): T { if (!this.enabled) return operation(); const started = performance.now(); try { return operation(); } finally { this.hookMs += performance.now() - started; } }
88
87
  capture(kind: string, scope: string, value: unknown, inheritedPartial = false) {
@@ -30,7 +30,7 @@ function images(entry: SessionEntry): ImageContent[] {
30
30
  return entry.message.content.filter((block): block is ImageContent => block.type === "image");
31
31
  }
32
32
  /** Factual locators only; no interpretation of pixels or claim of current truth. */
33
- export function imageSource(entry: SessionEntry): ImageSource | undefined {
33
+ function imageSource(entry: SessionEntry): ImageSource | undefined {
34
34
  const imageCount = images(entry).length;
35
35
  if (!imageCount || entry.type !== "message" || (entry.message.role !== "user" && entry.message.role !== "toolResult")) return;
36
36
  if (!entry.id || entry.id.length > MAX_RECALL_ENTRY_ID_CHARACTERS) throw new Error("Recall image source has an invalid or oversized ID");
package/src/kept-reads.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
2
2
  import { classifyBash } from "./bash-command";
3
3
  import { pathKey } from "./path-key";
4
+ import { isDiscardedResponse } from "./protocol";
4
5
  import { isTextOnly, textOf } from "./tuck/core/content";
5
6
  import { extractPath } from "./tuck/core/tool-args";
6
7
  import type { TranscriptRecord } from "./tuck/core/transcript";
@@ -51,3 +52,42 @@ export function keptReadCandidates(entries: readonly (SessionEntry | SessionHead
51
52
  }
52
53
  return records;
53
54
  }
55
+
56
+ /** At most this many outputs, newest first, holding at most this much output text in all; the rest is cut with a pointer. */
57
+ const MAX_PROMPT_OUTPUTS = 4, MAX_PROMPT_OUTPUT_CHARACTERS = 8000;
58
+ const words = (text: string) => text.replace(/\s+/gu, " ").trim();
59
+ /** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
60
+ * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
61
+ export function promptOutputCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
62
+ resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
63
+ const results = new Map<string, SessionEntry>(), named = new Map<string, string>();
64
+ let prompt: string | undefined;
65
+ for (const entry of entries) {
66
+ if (entry.type !== "message") continue;
67
+ const message = entry.message;
68
+ if (message.role === "user") { prompt = words(textOf(message.content)); continue; }
69
+ if (message.role === "toolResult") { results.set(message.toolCallId, entry); continue; }
70
+ if (message.role !== "assistant" || prompt === undefined || isDiscardedResponse(message)) continue;
71
+ for (const block of message.content) {
72
+ if (block.type !== "toolCall" || block.name !== "bash" || typeof (block.arguments as { command?: unknown })?.command !== "string") continue;
73
+ const command = (block.arguments as { command: string }).command, lead = words(command.split(/[|;&<>]|\d>/u)[0]!);
74
+ if (lead.includes(" ") && prompt.includes(lead)) named.set(block.id, command);
75
+ }
76
+ prompt = undefined;
77
+ }
78
+ const records: TranscriptRecord[] = [];
79
+ let room = MAX_PROMPT_OUTPUT_CHARACTERS;
80
+ for (const [id, command] of [...named].reverse()) {
81
+ const entry = results.get(id), sourceIndex = entry && indices.get(entry.id);
82
+ if (entry?.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content) ||
83
+ sourceIndex === undefined || !resolvable(entry)) continue;
84
+ const text = textOf(entry.message.content);
85
+ if (!text.length) continue;
86
+ const kept = text.length <= room ? text : `${text.slice(0, room)}\n… (truncated; whole output: tuck_recall {"index":${sourceIndex}})`;
87
+ records.push({ kind: "section", title: "Kept-prompt-output", sourceIndex,
88
+ text: `bash ${words(command)} (run as a user prompt asked; output as recorded at #${sourceIndex}):\n${kept}` });
89
+ room -= Math.min(room, text.length);
90
+ if (!room || records.length === MAX_PROMPT_OUTPUTS) break;
91
+ }
92
+ return records;
93
+ }
package/src/omissions.ts CHANGED
@@ -5,7 +5,7 @@ import { textOf } from "./tuck/core/content";
5
5
  import { isDiscardedResponse } from "./protocol";
6
6
  import { createRecall, type RecallPolicy } from './recall';
7
7
  /** Native branch edits supply exclusion; original global indices supply provenance. */
8
- export function omittedSourceIndices(entries: readonly SessionEntry[], branch: readonly SessionEntry[]): ReadonlySet<number> {
8
+ function omittedSourceIndices(entries: readonly SessionEntry[], branch: readonly SessionEntry[]): ReadonlySet<number> {
9
9
  const edits = new Set<string>();
10
10
  for (const entry of branch) if (entry.type === 'context_edit') {
11
11
  if (entry.replacement !== null) throw new Error('pi-tuck does not support replacement context edits');
@@ -71,7 +71,7 @@ export function filterOmittedSummary(summary: string, omitted: ReadonlySet<numbe
71
71
  }
72
72
 
73
73
  /** Custom quotes carry native entry identity; no text matching or legacy fallback. */
74
- export function filterCustomQuotes(summary: string, entries: readonly SessionEntry[], branch: readonly SessionEntry[], policy: RecallPolicy = {}): string {
74
+ function filterCustomQuotes(summary: string, entries: readonly SessionEntry[], branch: readonly SessionEntry[], policy: RecallPolicy = {}): string {
75
75
  const split = splitSummary(summary);
76
76
  if (!split) throw new Error('Cannot resolve custom sources in an unsupported compaction summary');
77
77
  const { body, closing, version } = split;
@@ -98,7 +98,7 @@ type ProjectedMessages = ReturnType<ExtensionContext['sessionManager']['buildSes
98
98
  /** The saved conversation as this compactor delivers it: native omissions and ineligible custom quotes removed from its own summaries. A
99
99
  * summary of another format (Pi's own /compact before pi-tuck was loaded, an empty draft) cannot be filtered and goes out as it is, as
100
100
  * native Pi sends it; the next pi-tuck cut replaces it. Failing closed on it left such a session unable to send any prompt (issue #1). */
101
- function projectMessages(messages: ProjectedMessages, ctx: ExtensionContext, policy: RecallPolicy | undefined): ProjectedMessages {
101
+ export function projectedMessages(messages: ProjectedMessages, ctx: ExtensionContext, policy?: RecallPolicy): ProjectedMessages {
102
102
  const entries = ctx.sessionManager.getEntries(), branch = ctx.sessionManager.getBranch();
103
103
  const omitted = omittedSourceIndices(entries, branch);
104
104
  const lastCut = branch.findLastIndex(entry => entry.type === 'compaction');
@@ -114,10 +114,3 @@ function projectMessages(messages: ProjectedMessages, ctx: ExtensionContext, pol
114
114
  ? { ...message, summary: filterCustomQuotes(filterOmittedSummary(message.summary, omitted, entries,
115
115
  cut?.type === 'compaction' && cut.summary === message.summary ? afterCut : new Set()), entries, branch, policy) } : message);
116
116
  }
117
- export function projectedMessages(messages: ProjectedMessages, ctx: ExtensionContext, policy?: RecallPolicy): ProjectedMessages {
118
- return projectMessages(messages, ctx, policy);
119
- }
120
- /** The planner's name for the same projection (kept for its callers). */
121
- export function measurableMessages(messages: ProjectedMessages, ctx: ExtensionContext, policy?: RecallPolicy): ProjectedMessages {
122
- return projectMessages(messages, ctx, policy);
123
- }
package/src/recall.ts CHANGED
@@ -94,7 +94,7 @@ function recallAttempts(branch: readonly SessionEntry[]): ReadonlyMap<string, Re
94
94
  if (entry.type === "custom" && policy.readAttemptMarker && entry.customType === policy.attemptMarkerType) {
95
95
  current = null;
96
96
  try {
97
- const marker = policy.readAttemptMarker!(entry);
97
+ const marker = policy.readAttemptMarker(entry);
98
98
  if (!marker) continue;
99
99
  identities.add(marker.nodeId);
100
100
  if (marker.attemptId && counts.get(entry.id) === 1)
@@ -124,7 +124,7 @@ function readable(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAt
124
124
  else if (entry.type === "custom_message")
125
125
  value = { role: "custom", text: textContent(entry.content) };
126
126
  else if (entry.type === "message") {
127
- const message = entry.message;
127
+ const message = entry.message, link = links?.get(entry.id);
128
128
  if (message.role === "user" || message.role === "assistant" || message.role === "custom")
129
129
  value = { role: message.role, text: textContent(message.content, message.role === "assistant"),
130
130
  ...(message.role === "assistant" && message.stopReason !== undefined ? { stopReason: message.stopReason } : {}) };
@@ -135,7 +135,7 @@ function readable(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAt
135
135
  toolName: message.toolName.slice(0, MAX_TOOL_METADATA),
136
136
  toolCallId: message.toolCallId.slice(0, MAX_TOOL_METADATA),
137
137
  isError: message.isError,
138
- ...(links?.has(entry.id) ? { producerRead: { entryId: links.get(entry.id)!.entryId, offset: links.get(entry.id)!.offset, limit: links.get(entry.id)!.limit }, producerTime: links.get(entry.id)!.sourceTime } : {}),
138
+ ...(link ? { producerRead: { entryId: link.entryId, offset: link.offset, limit: link.limit }, producerTime: link.sourceTime } : {}),
139
139
  ...(message.toolName.length > MAX_TOOL_METADATA || message.toolCallId.length > MAX_TOOL_METADATA
140
140
  ? { metadataTruncated: true as const } : {}),
141
141
  };
package/src/thrash.ts CHANGED
@@ -10,12 +10,6 @@ export const THRASH_WINDOW_REPLIES = 3;
10
10
  /** Re-reads per cut at which a session is thrashing. */
11
11
  export const THRASH_BAR = 0.5;
12
12
 
13
- /**
14
- * Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
15
- * limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
16
- * within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
17
- * such re-read, it never does. Deterministic: it reads only the recorded branch.
18
- */
19
13
  export interface Rereads { cuts: number; rereads: number; tokens: number }
20
14
  /** The branch's cuts and the re-reads that followed them (as `thrashing` defines a re-read), with their text in tokens at 4 characters each. */
21
15
  export function rereadsAfterCuts(branch: readonly SessionEntry[]): Rereads {
@@ -35,7 +29,7 @@ export function rereadsAfterCuts(branch: readonly SessionEntry[]): Rereads {
35
29
  if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;
36
30
  const args = block.arguments as Record<string, unknown>, path = extractPath(args);
37
31
  if (!path) continue;
38
- pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: cuts, soon: cuts > 0 && replies <= THRASH_WINDOW_REPLIES });
32
+ pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: current, soon: current > 0 && replies <= THRASH_WINDOW_REPLIES });
39
33
  }
40
34
  } else if (message.role === "toolResult") {
41
35
  const read = pending.get(message.toolCallId);
@@ -4,6 +4,9 @@ export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files
4
4
  "Files created by commands are not listed: Before re-running a command listed above, read its output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
5
5
  /** Parsing never depends on this wording (transcript.ts splitSummary). */
6
6
  export const DIALOGUE_SUFFIX = CLOSING_SEPARATOR + CLOSING_INSTRUCTION;
7
+ /** The deepest floor's last words: it lists no actions or files, so it does not claim to. */
8
+ export const DEEPEST_SUFFIX = CLOSING_SEPARATOR + "Only the dialogue and the outputs shown above carry over; no list of actions or files was kept. " +
9
+ "Before re-running a command, read its earlier output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
7
10
  const REREAD = "Re-read a file before editing it or importing from it.";
8
11
  /** The closing words when working files follow: the re-read rule stays for every other file. */
9
12
  export const WORKING_FILES_INSTRUCTION = CLOSING_INSTRUCTION.replace(REREAD,