pi-tuck 1.10.3 → 1.11.0

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 (57) hide show
  1. package/CHANGELOG.md +26 -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 +10 -4
  8. package/dist/src/compaction.js +91 -19
  9. package/dist/src/config-check.d.ts +6 -0
  10. package/dist/src/config-check.js +13 -2
  11. package/dist/src/content-observations.d.ts +0 -6
  12. package/dist/src/content-observations.js +5 -5
  13. package/dist/src/diagnostic-replay.js +6 -6
  14. package/dist/src/diagnostics.d.ts +0 -1
  15. package/dist/src/diagnostics.js +2 -3
  16. package/dist/src/history-image.d.ts +0 -2
  17. package/dist/src/history-image.js +1 -1
  18. package/dist/src/kept-reads.d.ts +0 -2
  19. package/dist/src/kept-reads.js +1 -1
  20. package/dist/src/omissions.d.ts +3 -6
  21. package/dist/src/omissions.js +3 -10
  22. package/dist/src/recall.js +2 -2
  23. package/dist/src/thrash.d.ts +0 -6
  24. package/dist/src/thrash.js +1 -1
  25. package/dist/src/tuck/core/format.d.ts +2 -0
  26. package/dist/src/tuck/core/format.js +3 -0
  27. package/dist/src/tuck/core/token-estimate.d.ts +2 -8
  28. package/dist/src/tuck/core/token-estimate.js +3 -9
  29. package/dist/src/tuck/core/tool-args.d.ts +0 -1
  30. package/dist/src/tuck/core/tool-args.js +1 -1
  31. package/dist/src/tuck/core/transcript.d.ts +3 -2
  32. package/dist/src/tuck/cut.d.ts +0 -1
  33. package/dist/src/tuck/cut.js +0 -3
  34. package/dist/src/tuck.d.ts +2 -2
  35. package/dist/src/tuck.js +11 -8
  36. package/package.json +1 -1
  37. package/src/budget.ts +1 -4
  38. package/src/build-id.ts +1 -1
  39. package/src/compaction.ts +80 -18
  40. package/src/config-check.ts +12 -2
  41. package/src/content-observations.ts +5 -5
  42. package/src/diagnostic-replay.ts +7 -6
  43. package/src/diagnostics.ts +2 -3
  44. package/src/history-image.ts +1 -1
  45. package/src/kept-reads.ts +1 -1
  46. package/src/omissions.ts +3 -10
  47. package/src/recall.ts +3 -3
  48. package/src/thrash.ts +1 -7
  49. package/src/tuck/core/format.ts +3 -0
  50. package/src/tuck/core/token-estimate.ts +4 -20
  51. package/src/tuck/core/tool-args.ts +1 -1
  52. package/src/tuck/core/transcript.ts +2 -2
  53. package/src/tuck/cut.ts +0 -4
  54. package/src/tuck.ts +11 -8
  55. package/dist/src/tuck/core/render-entries.d.ts +0 -6
  56. package/dist/src/tuck/core/render-entries.js +0 -1
  57. package/src/tuck/core/render-entries.ts +0 -6
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,
@@ -2,39 +2,23 @@ export const DEFAULT_CHARS_PER_TOKEN = 4;
2
2
  export const MIN_CHARS_PER_TOKEN = 2;
3
3
  export const MAX_CHARS_PER_TOKEN = 6;
4
4
 
5
- export type TokenEstimateMode = "heuristic" | "calibrated";
6
-
7
- export interface TokenEstimateCalibration {
8
- mode: TokenEstimateMode;
9
- charsPerToken: number;
10
- sourceChars?: number;
11
- sourceTokens?: number;
12
- rawCharsPerToken?: number;
13
- }
14
-
15
5
  const clamp = (value: number, min: number, max: number): number =>
16
6
  Math.min(max, Math.max(min, value));
17
7
 
18
8
  export const calibrateCharsPerToken = (
19
9
  sourceChars: number,
20
10
  sourceTokens: number | undefined,
21
- ): TokenEstimateCalibration => {
11
+ ): { charsPerToken: number } => {
22
12
  if (!sourceTokens || sourceTokens <= 0 || sourceChars <= 0) {
23
- return { mode: "heuristic", charsPerToken: DEFAULT_CHARS_PER_TOKEN };
13
+ return { charsPerToken: DEFAULT_CHARS_PER_TOKEN };
24
14
  }
25
15
 
26
16
  const rawCharsPerToken = sourceChars / sourceTokens;
27
17
  if (!Number.isFinite(rawCharsPerToken) || rawCharsPerToken <= 0) {
28
- return { mode: "heuristic", charsPerToken: DEFAULT_CHARS_PER_TOKEN };
18
+ return { charsPerToken: DEFAULT_CHARS_PER_TOKEN };
29
19
  }
30
20
 
31
- return {
32
- mode: "calibrated",
33
- charsPerToken: clamp(rawCharsPerToken, MIN_CHARS_PER_TOKEN, MAX_CHARS_PER_TOKEN),
34
- sourceChars,
35
- sourceTokens,
36
- rawCharsPerToken,
37
- };
21
+ return { charsPerToken: clamp(rawCharsPerToken, MIN_CHARS_PER_TOKEN, MAX_CHARS_PER_TOKEN) };
38
22
  };
39
23
 
40
24
  export const estimateTokensFromChars = (
@@ -1,4 +1,4 @@
1
- export const PATH_KEYS = ["path", "file_path", "filePath", "file"] as const;
1
+ const PATH_KEYS = ["path", "file_path", "filePath", "file"] as const;
2
2
 
3
3
  export const extractPath = (args: Record<string, unknown>): string | null => {
4
4
  for (const key of PATH_KEYS) {
@@ -15,8 +15,8 @@ export const smallOriginalArguments = (value: unknown, maxCharacters = MAX_PRODU
15
15
  };
16
16
 
17
17
  interface RecordFields {
18
- sourceTime?: import("./source-time").SourceTime;
19
- sourceTimes?: ({ sourceIndex: number } & import("./source-time").SourceTime)[];
18
+ sourceTime?: SourceTime;
19
+ sourceTimes?: ({ sourceIndex: number } & SourceTime)[];
20
20
  sourceEntryId?: string;
21
21
  role?: "user" | "assistant" | "custom" | "bashExecution" | "toolResult";
22
22
  sourceIndex?: number;
package/src/tuck/cut.ts CHANGED
@@ -48,7 +48,6 @@ export type OwnCutResult =
48
48
  selectedIds: string[];
49
49
  firstKeptEntryId: string;
50
50
  compactAll: boolean;
51
- keptUserTurns: number;
52
51
  keepFallbackToCompactAll: boolean;
53
52
  budgetCut?: BudgetCutKind;
54
53
  }
@@ -87,7 +86,6 @@ export function buildOwnCut(branchEntries: any[], keepUserTurns = 1): OwnCutResu
87
86
  selectedIds: liveMessages.map((e) => e.entry.id),
88
87
  firstKeptEntryId: "",
89
88
  compactAll: true,
90
- keptUserTurns: 0,
91
89
  keepFallbackToCompactAll,
92
90
  });
93
91
 
@@ -111,7 +109,6 @@ export function buildOwnCut(branchEntries: any[], keepUserTurns = 1): OwnCutResu
111
109
  selectedIds: liveMessages.slice(0, cutIdx).map((e) => e.entry.id),
112
110
  firstKeptEntryId: liveMessages[cutIdx].entry.id,
113
111
  compactAll: false,
114
- keptUserTurns: userIndices.length - targetUserIdx,
115
112
  keepFallbackToCompactAll: false,
116
113
  };
117
114
  }
@@ -168,7 +165,6 @@ export const applyTailBudget = (
168
165
  selectedIds: live.slice(0, idx).map((m) => m.entry.id),
169
166
  firstKeptEntryId: live[idx].entry.id,
170
167
  compactAll: false,
171
- keptUserTurns: live.slice(idx).filter((m) => m.message.role === "user").length,
172
168
  keepFallbackToCompactAll: false,
173
169
  budgetCut,
174
170
  });
package/src/tuck.ts CHANGED
@@ -2,7 +2,7 @@ import { resolveSourceTime, type SourceTime } from "./tuck/core/source-time";
2
2
  import { orderByOriginalSource } from "./tuck/core/source-order";
3
3
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
4
4
  import { parseRecords, serializeTranscript, serializeRecord, splitSummary, TRANSCRIPT_HEADER, type TranscriptRecord } from "./tuck/core/transcript";
5
- import { closingSuffix, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format";
5
+ import { closingSuffix, DEEPEST_SUFFIX, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format";
6
6
  import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget";
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content";
@@ -61,8 +61,8 @@ export function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: Ext
61
61
  return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId,
62
62
  keepRecentTokens: event.preparation.settings?.keepRecentTokens ?? keepRecentTokens }, ctx, reserveTokens, measure, policy, retainCurrentInput);
63
63
  }
64
- /** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
65
- /** `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
64
+ /** Shared compiler observes canonical branch and current token estimate; no native preparation utility.
65
+ * `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
66
66
  * a run a custom message starts); the session has moved on from an ended run.
67
67
  * `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
68
68
  export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string; newPrompt?: boolean; reRenderSummary?: boolean; protectedPromptEntryId?: string; deepest?: boolean; keepRecentTokens?: number }, ctx: ExtensionContext,
@@ -100,12 +100,11 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
100
100
  // made smaller. Inside the band a cut is opportunistic, and re-rendering there shrinks the summary and costs history for nothing (replays
101
101
  // 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.
102
102
  else if (input.reRenderSummary && cut.reason === "no_live_messages" && entries.some(entry => entry.type === "compaction"))
103
- cut = { ok: true, messages: [], selectedIds: [], firstKeptEntryId: "", compactAll: true, keptUserTurns: 0, keepFallbackToCompactAll: false };
103
+ cut = { ok: true, messages: [], selectedIds: [], firstKeptEntryId: "", compactAll: true, keepFallbackToCompactAll: false };
104
104
  if (!cut.ok) return { unavailable: `pi-tuck cannot select a cut: ${cut.reason}` };
105
105
  const cutBefore = (cut: Extract<Cut, { ok: true }>, boundary: number, prefix: Extract<Cut, { ok: true }>): Extract<Cut, { ok: true }> => ({
106
106
  ...cut, messages: prefix.messages, selectedIds: prefix.selectedIds,
107
107
  firstKeptEntryId: entries[boundary]?.id ?? "", compactAll: boundary === entries.length, keepFallbackToCompactAll: false,
108
- keptUserTurns: entries.slice(boundary).filter(entry => entry.type === "message" && entry.message.role === "user").length,
109
108
  });
110
109
  // The latest call's trailing receipts have not reached a subsequent response.
111
110
  // A preferred tail size must not erase this first exposure when the whole
@@ -314,9 +313,13 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
314
313
  // The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
315
314
  // existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
316
315
  if (input.deepest) {
317
- assertNativeToolRounds(floorProjection);
318
- const after = measure(floorProjection);
319
- return { compaction: { summary: floorSummary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
316
+ // The floor carries the outputs prompts asked for (capped at 8,000 characters) and closes without claiming lists it does not have.
317
+ const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, entry => readable(entry) !== undefined);
318
+ const summary = (serializeTranscript([...calibrationHigh.rows, ...outputs]) || TRANSCRIPT_HEADER + "\n") + DEEPEST_SUFFIX;
319
+ const projection = preview(summary, floorBoundary);
320
+ assertNativeToolRounds(projection);
321
+ const after = measure(projection);
322
+ return { compaction: { summary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
320
323
  details: { ...detailsAt(floorBoundary), tokensAfter: after, carriedTarget: after, view: "shrunk-dialogue", mode: "shrunk", deepest: true } }, after, mode: "shrunk" };
321
324
  }
322
325
  const offset = measure(floorProjection) - nativeAt(floorBoundary) - summaryTokens(floorSummary.length);
@@ -1,6 +0,0 @@
1
- export interface RenderedEntry {
2
- index: number;
3
- role: string;
4
- summary: string;
5
- files?: string[];
6
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,6 +0,0 @@
1
- export interface RenderedEntry {
2
- index: number;
3
- role: string;
4
- summary: string;
5
- files?: string[];
6
- }