pi-tuck 1.3.3 → 1.4.1

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 (50) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +0 -59
  3. package/NOTICE +63 -0
  4. package/README.md +59 -189
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +49 -10
  7. package/dist/src/budget.d.ts +6 -15
  8. package/dist/src/budget.js +6 -11
  9. package/dist/src/build-id.d.ts +1 -1
  10. package/dist/src/build-id.js +1 -1
  11. package/dist/src/compaction.d.ts +12 -20
  12. package/dist/src/compaction.js +220 -202
  13. package/dist/src/content-observations.d.ts +24 -0
  14. package/dist/src/content-observations.js +122 -0
  15. package/dist/src/diagnostics.d.ts +1 -3
  16. package/dist/src/ledger.d.ts +6 -3
  17. package/dist/src/ledger.js +14 -7
  18. package/dist/src/llama-continuation.d.ts +8 -0
  19. package/dist/src/llama-continuation.js +179 -0
  20. package/dist/src/omissions.d.ts +1 -5
  21. package/dist/src/omissions.js +8 -10
  22. package/dist/src/recall.js +8 -25
  23. package/dist/src/request-capacity.d.ts +11 -26
  24. package/dist/src/request-capacity.js +20 -57
  25. package/dist/src/run.d.ts +16 -7
  26. package/dist/src/run.js +53 -25
  27. package/dist/src/status.d.ts +2 -0
  28. package/dist/src/status.js +6 -5
  29. package/dist/src/tuck/core/format.js +1 -1
  30. package/dist/src/tuck/core/readable-content.d.ts +14 -0
  31. package/dist/src/tuck/core/readable-content.js +43 -0
  32. package/dist/src/tuck.d.ts +2 -1
  33. package/dist/src/tuck.js +92 -30
  34. package/index.ts +42 -10
  35. package/package.json +3 -2
  36. package/src/budget.ts +7 -12
  37. package/src/build-id.ts +1 -1
  38. package/src/compaction.ts +220 -193
  39. package/src/content-observations.ts +115 -0
  40. package/src/diagnostics.ts +1 -1
  41. package/src/ledger.ts +17 -10
  42. package/src/llama-continuation.ts +176 -0
  43. package/src/omissions.ts +8 -10
  44. package/src/recall.ts +8 -20
  45. package/src/request-capacity.ts +18 -57
  46. package/src/run.ts +48 -22
  47. package/src/status.ts +8 -5
  48. package/src/tuck/core/format.ts +1 -1
  49. package/src/tuck/core/readable-content.ts +44 -0
  50. package/src/tuck.ts +79 -28
@@ -1,4 +1,4 @@
1
- import { isContextOverflow, normalizeContext } from '@earendil-works/pi-ai';
1
+ import { normalizeContext } from '@earendil-works/pi-ai';
2
2
  import { parseRecords, splitSummary } from './tuck/core/transcript.js';
3
3
  /** Pi's own request arithmetic: its reply clamp and the estimator behind it, as the running Pi has them.
4
4
  * An installed extension cannot import these subpaths by name: Pi's extension loader aliases only pi-ai's root, compat, models, oauth and
@@ -56,69 +56,32 @@ export async function piContextSafetyMargin(math) {
56
56
  return 4_096;
57
57
  }
58
58
  }
59
- /** The smallest reply room a request above the room must leave after Pi's own clamp: above the user's p99 reply (3,270 tokens). */
60
- export const REPLY_FLOOR_MIN = 3_584;
61
- /** A spent thinking budget that produced neither a visible answer nor work. Empty/text/tool replies keep the existing length recovery. */
59
+ /** A length stop with visible reasoning but no visible answer or work. */
62
60
  export const thinkingOnlyLength = (message) => message.role === 'assistant' && message.stopReason === 'length' &&
63
61
  message.content.length > 0 && message.content.every(block => block.type === 'thinking');
64
- /** Thinking-only exhaustion uses the observed largest reply, not the full reserve. Every other failed length/overflow keeps its override. */
65
- export const needsFullReplyReserve = (message) => message.role === 'assistant' &&
66
- (message.stopReason === 'length' && !thinkingOnlyLength(message) || message.stopReason === 'error' && isContextOverflow(message));
67
- export const WINDOW_RECEIPT = 'pi-tuck-window';
68
- function windowSettings(entry) {
69
- if (entry.type === 'custom' && entry.customType === WINDOW_RECEIPT)
70
- return entry.data;
71
- if (entry.type === 'compaction')
72
- return entry.details?.diagnosticReceipt?.settings;
73
- return undefined;
74
- }
75
- /** The newest learned window for `identity`, if it was learned under the model's current configured window. One recorded before 1.3.3
76
- * carries no configured window and is not trusted: if the server still clips, the next clipped reply learns it again. */
77
- export function seedContextWindow(branch, identity, catalogue) {
78
- for (let i = branch.length; i--;) {
79
- const settings = windowSettings(branch[i]);
80
- if (settings?.calibrationIdentity !== identity)
81
- continue;
82
- const window = settings.learnedContextWindow;
83
- if (!(Number.isSafeInteger(window) && window > 0))
84
- return undefined;
85
- return catalogue !== undefined && settings.catalogueContextWindow === catalogue ? window : undefined;
86
- }
87
- return undefined;
88
- }
89
- /** One branch reader for the reserve override and reply floor, including history before cuts. A server-clipping receipt follows its reply. */
90
- export function replyFit(branch) {
91
- let failed = false, largestOutput = 0, thinkingStop = false;
92
- const clipped = new Set();
93
- for (let i = branch.length; i--;) {
94
- const entry = branch[i];
95
- const receipt = entry.type === 'custom' && entry.customType === WINDOW_RECEIPT ? windowSettings(entry) : undefined;
96
- if (receipt && Number.isSafeInteger(receipt.learnedContextWindow) && receipt.learnedContextWindow > 0 &&
97
- typeof receipt.serverClippedReplyId === 'string')
98
- clipped.add(receipt.serverClippedReplyId);
62
+ /** Reply room a cut above the room aims for before any long reply is seen. Cuts only: admission keeps the observed floor. */
63
+ export const CUT_REPLY_FLOOR = 3_584;
64
+ /** Ordinary reply demand is bounded by the reserve and model output limit.
65
+ * Recovery compares its candidate against the interrupted attempt separately. */
66
+ export function requestReplyFloor(branch, reserve, model, minimum = 1) {
67
+ const reserved = Math.max(1, reserve);
68
+ const limit = model.maxTokens > 0 ? Math.min(reserved, model.maxTokens) : reserved;
69
+ let largest = minimum;
70
+ for (const entry of branch) {
99
71
  if (entry.type !== 'message' || entry.message.role !== 'assistant')
100
72
  continue;
101
73
  const message = entry.message;
102
- failed ||= !clipped.has(entry.id) && needsFullReplyReserve(message);
103
- thinkingStop ||= thinkingOnlyLength(message);
74
+ if (message.model !== model.id || message.provider !== model.provider || message.api !== model.api ||
75
+ message.stopReason === 'error' || message.stopReason === 'aborted')
76
+ continue;
104
77
  const output = message.usage?.output;
105
- if (typeof output === 'number' && Number.isFinite(output) && output > largestOutput)
106
- largestOutput = output;
78
+ if (typeof output !== 'number' || !Number.isFinite(output) || output <= 0)
79
+ continue;
80
+ largest = Math.max(largest, output);
81
+ if (largest >= limit)
82
+ break;
107
83
  }
108
- return { failed, largestOutput, thinkingStop };
109
- }
110
- export function branchReplyFloor(branch, reserve) {
111
- const { failed, largestOutput, thinkingStop } = replyFit(branch);
112
- if (failed)
113
- return reserve;
114
- // Include exhausted thinking output across cuts/restarts; requestReplyFloor applies the model cap.
115
- const largest = Math.ceil(Math.max(REPLY_FLOOR_MIN, largestOutput));
116
- return thinkingStop ? largest : Math.min(reserve, largest);
117
- }
118
- /** Admission never promises more output than a model with a positive reply cap can produce. */
119
- export function requestReplyFloor(branch, reserve, maxTokens) {
120
- const floor = branchReplyFloor(branch, reserve);
121
- return maxTokens !== undefined && maxTokens > 0 ? Math.min(floor, maxTokens) : floor;
84
+ return Math.min(limit, Math.ceil(largest));
122
85
  }
123
86
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
124
87
  export function carriesPrompt(messages, prompt, role = 'user') {
package/dist/src/run.d.ts CHANGED
@@ -7,7 +7,7 @@ export type CutEntry = {
7
7
  tokensBefore: number;
8
8
  details?: unknown;
9
9
  };
10
- type Context = Pick<ExtensionContext, 'cwd' | 'sessionManager'>;
10
+ type Context = Pick<ExtensionContext, 'cwd' | 'sessionManager'> & Partial<Pick<ExtensionContext, 'model'>>;
11
11
  export interface CutView {
12
12
  session: ExtensionContext['sessionManager'];
13
13
  keptFromId: string | undefined;
@@ -16,12 +16,11 @@ export interface CutView {
16
16
  }
17
17
  /** The only owner of a cut that requests carry before Pi saves it. */
18
18
  export declare class PendingCut {
19
- private cut?;
20
- private branchLength;
19
+ private proposal?;
21
20
  private preview?;
22
- plan(cut: CutEntry, branchLength: number): void;
21
+ plan(cut: CutEntry, ctx: Context): void;
23
22
  clear(): void;
24
- take(): CutEntry | undefined;
23
+ take(ctx: Context): CutEntry | undefined;
25
24
  view(ctx: Context, entries?: readonly SessionBoundaryDraft[]): CutView;
26
25
  }
27
26
  /** Text bridges before Pi appends the starting message. Once visible, every reader uses its entry id.
@@ -46,12 +45,22 @@ export declare class Run {
46
45
  get expired(): boolean;
47
46
  /** Failure data, only present in a failed phase. The phase alone decides admission. */
48
47
  get error(): Error | undefined;
49
- transition(phase: RunPhase, ctx?: Pick<ExtensionContext, 'hasUI'>, error?: Error): boolean;
48
+ transition(phase: RunPhase, error?: Error): void;
50
49
  prompt?: StartingPrompt;
51
50
  cut: PendingCut;
52
51
  clips: Map<string, Clip>;
53
52
  pendingBoundaryReceipts: string[];
54
- thinkingRetryPending: boolean;
53
+ rejectedBudget?: {
54
+ input: number;
55
+ output: number;
56
+ };
57
+ private lengthRecovery;
58
+ get lengthRetryPending(): boolean;
59
+ get canRetryLength(): boolean;
60
+ requestLengthRetry(): void;
61
+ finishLengthRetry(): void;
62
+ /** Pi grants another recovery after a good reply or a new user message. */
63
+ rearmLengthRetry(): void;
55
64
  /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
56
65
  nativeFloorPending: boolean;
57
66
  refusalReceipted: boolean;
package/dist/src/run.js CHANGED
@@ -1,20 +1,39 @@
1
1
  import { SessionManager } from '@earendil-works/pi-coding-agent';
2
2
  import { hasTuckCut } from './history-tools.js';
3
3
  import { textOf } from './tuck/core/content.js';
4
+ const budgetIdentity = (model) => model &&
5
+ JSON.stringify([model.provider, model.api, model.id, model.contextWindow, model.maxTokens]);
4
6
  /** The only owner of a cut that requests carry before Pi saves it. */
5
7
  export class PendingCut {
6
- cut;
7
- branchLength = 0;
8
+ proposal;
8
9
  preview;
9
- plan(cut, branchLength) { this.cut = cut; this.branchLength = branchLength; this.preview = undefined; }
10
- clear() { this.cut = undefined; this.branchLength = 0; this.preview = undefined; }
11
- take() { const cut = this.cut; this.clear(); return cut; }
10
+ plan(cut, ctx) {
11
+ const branch = ctx.sessionManager.getBranch();
12
+ this.proposal = { cut, manager: ctx.sessionManager, cwd: ctx.cwd, branchLength: branch.length,
13
+ anchor: branch.at(-1)?.id, budget: budgetIdentity(ctx.model) };
14
+ this.preview = undefined;
15
+ }
16
+ clear() { this.proposal = undefined; this.preview = undefined; }
17
+ take(ctx) {
18
+ if (!this.view(ctx).pending)
19
+ return;
20
+ const cut = this.proposal?.cut;
21
+ this.clear();
22
+ return cut;
23
+ }
12
24
  view(ctx, entries = []) {
13
- const live = ctx.sessionManager, leaf = live.getLeafId?.(), held = this.preview;
14
- // Native entries are append-only; a leaf move invalidates both the saved and pending views.
25
+ const live = ctx.sessionManager, leaf = live.getLeafId?.();
26
+ const proposal = this.proposal;
27
+ if (proposal && (proposal.manager !== live || proposal.cwd !== ctx.cwd || proposal.budget !== budgetIdentity(ctx.model)))
28
+ this.clear();
29
+ const held = this.preview;
30
+ // Native entries are append-only. A changed leaf requires checking that the plan's anchor still precedes it.
15
31
  if (!entries.length && leaf !== undefined && held && held.manager === live && held.cwd === ctx.cwd && held.leaf === leaf)
16
32
  return held.view;
17
- const branch = live.getBranch(), cut = this.cut;
33
+ const branch = live.getBranch();
34
+ if (this.proposal?.anchor !== undefined && branch[this.proposal.branchLength - 1]?.id !== this.proposal.anchor)
35
+ this.clear();
36
+ const cut = this.proposal?.cut;
18
37
  const remember = (view) => {
19
38
  if (!entries.length && leaf !== undefined)
20
39
  this.preview = { manager: live, cwd: ctx.cwd, leaf, view };
@@ -26,7 +45,7 @@ export class PendingCut {
26
45
  hasTuckCut: hasTuckCut(branch), pending: false });
27
46
  }
28
47
  // A compact-all plan predates the prompt. Keep from the first appended entry, skipping our capacity receipts.
29
- const keptFromId = cut && (cut.firstKeptEntryId || branch.slice(this.branchLength)
48
+ const keptFromId = cut && (cut.firstKeptEntryId || branch.slice(this.proposal.branchLength)
30
49
  .find(entry => entry.type !== 'custom' || entry.customType !== 'pi-tuck-capacity')?.id || '');
31
50
  const header = live.getHeader();
32
51
  if (!header)
@@ -94,7 +113,6 @@ export const RUN_TRANSITIONS = {
94
113
  failed: ['failed', 'commit-failed'],
95
114
  'commit-failed': ['commit-failed'],
96
115
  };
97
- let reportedInvalidTransition = false;
98
116
  export class Run {
99
117
  state;
100
118
  // Input-plan provenance survives starting/admission: later native threshold
@@ -105,30 +123,40 @@ export class Run {
105
123
  get expired() { return this.expiredPlan; }
106
124
  /** Failure data, only present in a failed phase. The phase alone decides admission. */
107
125
  get error() { return 'error' in this.state ? this.state.error : undefined; }
108
- transition(phase, ctx, error) {
126
+ transition(phase, error) {
109
127
  if (!RUN_TRANSITIONS[this.phase].includes(phase) || ((phase === 'failed' || phase === 'commit-failed') && !error)) {
110
- const message = `pi-tuck: invalid run transition ${this.phase} -> ${phase}`;
111
- if (process.env.NODE_ENV === 'test')
112
- throw new Error(message);
113
- if (ctx?.hasUI === false && !reportedInvalidTransition) {
114
- reportedInvalidTransition = true;
115
- try {
116
- process.stderr.write(message + '\n');
117
- }
118
- catch { /* ended */ }
119
- }
120
- return false;
128
+ const fault = new Error(`pi-tuck: invalid run transition ${this.phase} -> ${phase}`);
129
+ // A rejected transition must stop the caller and latch admission shut.
130
+ // Preserve an existing terminal cause, especially a persistence fault.
131
+ if (this.state.phase !== 'failed' && this.state.phase !== 'commit-failed')
132
+ this.state = { phase: 'failed', error: fault };
133
+ throw fault;
121
134
  }
122
135
  this.state = phase === 'failed' || phase === 'commit-failed' ? { phase, error: error } : { phase };
123
136
  if (phase === 'expired')
124
137
  this.expiredPlan = true;
125
- return true;
126
138
  }
127
139
  prompt;
128
140
  cut = new PendingCut();
129
141
  clips = new Map();
130
142
  pendingBoundaryReceipts = [];
131
- thinkingRetryPending = false;
143
+ rejectedBudget;
144
+ lengthRecovery = 'available';
145
+ get lengthRetryPending() { return this.lengthRecovery === 'pending'; }
146
+ get canRetryLength() { return this.phase === 'admitted' && this.lengthRecovery === 'available'; }
147
+ requestLengthRetry() {
148
+ if (!this.canRetryLength)
149
+ throw new Error('pi-tuck: capacity recovery is unavailable for this run');
150
+ this.lengthRecovery = 'pending';
151
+ }
152
+ finishLengthRetry() {
153
+ if (this.lengthRecovery === 'pending')
154
+ this.lengthRecovery = 'used';
155
+ }
156
+ /** Pi grants another recovery after a good reply or a new user message. */
157
+ rearmLengthRetry() {
158
+ this.lengthRecovery = 'available';
159
+ }
132
160
  /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
133
161
  nativeFloorPending = false;
134
162
  refusalReceipted = false;
@@ -137,7 +165,7 @@ export class Run {
137
165
  this.cut.clear();
138
166
  this.clips.clear();
139
167
  this.pendingBoundaryReceipts = [];
140
- this.thinkingRetryPending = false;
168
+ this.rejectedBudget = undefined;
141
169
  this.nativeFloorPending = false;
142
170
  this.refusalReceipted = false;
143
171
  this.expiredPlan = false;
@@ -1,3 +1,4 @@
1
+ export declare const CONTINUATION_CACHE_MISS = "Native continuation stopped because the server could not reuse the unfinished response without rebuilding context.";
1
2
  /** The version of the package this code was loaded from: the open session keeps it until Pi restarts, whatever is installed since. */
2
3
  export declare const LOADED_VERSION: string;
3
4
  /** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
@@ -14,4 +15,5 @@ export declare function statusText(input: {
14
15
  }[];
15
16
  pending?: boolean;
16
17
  cutAt: number | undefined;
18
+ cacheSensitive?: boolean;
17
19
  }): string;
@@ -1,5 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
+ export const CONTINUATION_CACHE_MISS = "Native continuation stopped because the server could not reuse the unfinished response without rebuilding context.";
3
4
  /** The version of the package this code was loaded from: the open session keeps it until Pi restarts, whatever is installed since. */
4
5
  export const LOADED_VERSION = (() => {
5
6
  try {
@@ -14,13 +15,13 @@ export const LOADED_VERSION = (() => {
14
15
  /** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
15
16
  export function statusText(input) {
16
17
  if (!input.active)
17
- return `pi-tuck ${input.version} is loaded but inactive in this host; Pi's own compaction runs.`;
18
+ return `pi-tuck ${input.version} is inactive in this host.`;
18
19
  if (input.compaction?.kind === 'standingDown')
19
- return `pi-tuck ${input.version}: standing down: ${input.compaction.reason}; Pi's own compaction runs.`;
20
+ return `pi-tuck ${input.version} is standing down (${input.compaction.reason}). Pi controls compaction.`;
20
21
  const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => e.details?.compactor === "pi-tuck");
21
22
  const last = ours.at(-1), before = last?.tokensBefore, after = last?.details?.tokensAfter;
22
23
  const count = (n) => n.toLocaleString("en-US");
23
- const cutLine = ours.length === 0 ? input.pending ? "Cuts: none saved yet in this session." : "Cuts: none yet in this session. The recall tools appear after the first cut."
24
+ const cutLine = ours.length === 0 ? input.pending ? "Cuts: none saved yet in this session." : "Cuts: none yet in this session. Recall becomes available after the first pi-tuck cut on this branch."
24
25
  : `Cuts: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
25
26
  const native = cuts.length - ours.length;
26
27
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
@@ -28,10 +29,10 @@ export function statusText(input) {
28
29
  return [
29
30
  `pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
30
31
  cutLine,
31
- ...(retries ? [`Retries: ${retries} after thinking-only length stops in this session.`] : []),
32
+ ...(retries ? [`Capacity retries on this branch: ${retries}.`] : []),
32
33
  ...(input.pending ? ["A cut is pending: requests already carry it; the first boundary saves it."] : []),
33
34
  ...(native > 0 ? [`Pi's own compaction cut ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
34
- input.cutAt === undefined ? "Cut point: adapts by itself." : `Cut point: fixed at cutAt ${input.cutAt} of the input room. Remove cutAt from pi-tuck.json to let it adapt.`,
35
+ input.cacheSensitive ? "Cut point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined ? "Cut point: adapts by itself." : `Cut point: cutAt ${input.cutAt} of the room, subject to the standard margin. Remove cutAt from pi-tuck.json to let it adapt.`,
35
36
  "Search: by keyword.",
36
37
  ].join("\n");
37
38
  }
@@ -1,6 +1,6 @@
1
1
  import { CLOSING_SEPARATOR } from "./transcript.js";
2
2
  /** A summary's last words: it holds only the dialogue (whole or shrunk) and the file ledger. */
3
3
  export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files listed above carry over. " +
4
- "Files created by commands are not listed: before redoing a step, read its output with tuck_recall or list your output folders. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
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;
@@ -0,0 +1,14 @@
1
+ export interface ReadableContentPart {
2
+ kind: "text" | "toolCall" | "thinking";
3
+ text: string;
4
+ offset: number;
5
+ toolName?: string;
6
+ arguments?: unknown;
7
+ }
8
+ export declare function isPlainThinking(block: unknown): block is {
9
+ type: "thinking";
10
+ thinking: string;
11
+ };
12
+ /** Keep the existing text/tool-call prefix byte for byte, including empty text
13
+ * parts. Append plain thinking in block order so older recall offsets remain valid. */
14
+ export declare function readableContentParts(content: unknown, assistant?: boolean): ReadableContentPart[];
@@ -0,0 +1,43 @@
1
+ /** Pi stores opaque/encrypted reasoning in thinkingSignature. The one exception: pi-ai's openai-completions adapter stores only the name of the
2
+ * response field the plain reasoning came from (OPENAI_COMPLETIONS_REASONING_FIELDS), which signs or encrypts nothing. Also refuse explicit
3
+ * redaction/encryption markers in imported session blocks. */
4
+ const PLAIN_REASONING_FIELDS = new Set(["reasoning", "reasoning_content", "reasoning_text"]);
5
+ export function isPlainThinking(block) {
6
+ if (!block || typeof block !== "object")
7
+ return false;
8
+ const value = block;
9
+ return value.type === "thinking" && typeof value.thinking === "string" && (value.thinkingSignature === undefined || PLAIN_REASONING_FIELDS.has(value.thinkingSignature)) &&
10
+ (value.redacted === undefined || value.redacted === false) &&
11
+ (value.encrypted === undefined || value.encrypted === false) &&
12
+ value.encryptedContent === undefined && value.encrypted_content === undefined;
13
+ }
14
+ /** Keep the existing text/tool-call prefix byte for byte, including empty text
15
+ * parts. Append plain thinking in block order so older recall offsets remain valid. */
16
+ export function readableContentParts(content, assistant = false) {
17
+ if (typeof content === "string")
18
+ return [{ kind: "text", text: content, offset: 0 }];
19
+ if (!Array.isArray(content))
20
+ return [];
21
+ const parts = [];
22
+ for (const block of content) {
23
+ if (!block || typeof block !== "object")
24
+ continue;
25
+ if (block.type === "text" && typeof block.text === "string")
26
+ parts.push({ kind: "text", text: block.text });
27
+ else if (assistant && block.type === "toolCall" && typeof block.name === "string" && typeof block.id === "string" && "arguments" in block)
28
+ parts.push({ kind: "toolCall", toolName: block.name, arguments: block.arguments,
29
+ text: JSON.stringify({ toolCall: { name: block.name, id: block.id, arguments: block.arguments } }) });
30
+ }
31
+ if (assistant)
32
+ for (const block of content)
33
+ if (isPlainThinking(block) && block.thinking.length)
34
+ parts.push({ kind: "thinking", text: block.thinking });
35
+ let offset = 0;
36
+ return parts.map((part, at) => {
37
+ if (at)
38
+ offset++;
39
+ const located = { ...part, offset };
40
+ offset += part.text.length;
41
+ return located;
42
+ });
43
+ }
@@ -67,7 +67,7 @@ import { compileDialogue } from "./tuck/core/summarize.js";
67
67
  export declare const tuck: Tuck;
68
68
  /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
69
69
  * `_operatorManual` retains the exported positional slot for existing callers. */
70
- export declare function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy?: RecallPolicy, retainCurrentInput?: boolean, _operatorManual?: boolean, newPrompt?: boolean, protectedPromptEntryId?: string): Draft;
70
+ 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;
71
71
  /** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
72
72
  /** `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
73
73
  * a run a custom message starts); the session has moved on from an ended run.
@@ -80,6 +80,7 @@ export declare function tuckObservedDraft(tuck: Tuck, input: {
80
80
  reRenderSummary?: boolean;
81
81
  protectedPromptEntryId?: string;
82
82
  deepest?: boolean;
83
+ keepRecentTokens?: number;
83
84
  }, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy?: RecallPolicy, retainCurrentInput?: boolean): Draft;
84
85
  /** Numeric references use the original session index, then intersect with readable current-branch entries. */
85
86
  export declare function tuckRecall(tuck: Tuck, entries: readonly SessionEntry[], branch: readonly SessionEntry[], input: RecallOptions & {
package/dist/src/tuck.js CHANGED
@@ -9,6 +9,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
10
  import { keptReadCandidates } from "./kept-reads.js";
11
11
  import { keptSearchCandidates } from "./kept-searches.js";
12
+ import { fileObservations, thinkingRecords } from "./content-observations.js";
13
+ import { pathKey } from "./path-key.js";
12
14
  import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
13
15
  import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
14
16
  /** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
@@ -22,8 +24,9 @@ import { rankRecallRows } from "./tuck/core/search-entries.js";
22
24
  export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
23
25
  /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
24
26
  * `_operatorManual` retains the exported positional slot for existing callers. */
25
- export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId) {
26
- return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId }, ctx, reserveTokens, measure, policy, retainCurrentInput);
27
+ export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId, keepRecentTokens) {
28
+ return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId,
29
+ keepRecentTokens: event.preparation.settings?.keepRecentTokens ?? keepRecentTokens }, ctx, reserveTokens, measure, policy, retainCurrentInput);
27
30
  }
28
31
  /** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
29
32
  /** `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
@@ -339,7 +342,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
339
342
  const fixedRowsCost = preferredHigh.cost + lineCost(preferredLists.records);
340
343
  const baseCharacters = frameLength(fixedRowsCost, preferredHigh.rows.length + preferredLists.records.length);
341
344
  const base = price(baseCharacters, preferredBoundary);
342
- const target = carriedTarget(model.contextWindow, reserveTokens, base, before);
345
+ // Cap historical fill at native keep-recent for post-cut headroom parity, preserving the floor and preferred tail.
346
+ const target = Math.min(carriedTarget(model.contextWindow, reserveTokens, base, before), Math.max(base, offset + (input.keepRecentTokens ?? Infinity)));
343
347
  // The old tail rule supplies an ordering boundary only. Its recent
344
348
  // suffix follows the openings, and is charged to the same total grant.
345
349
  const boundaries = [floorBoundary];
@@ -378,34 +382,19 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
378
382
  const lists = listsAt(boundary);
379
383
  const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
380
384
  const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
381
- let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
382
- const keptResults = [], counts = new Map();
383
- const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry) => readable(entry) !== undefined;
384
- const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
385
- .sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
386
- for (const record of candidates) {
387
- if ((counts.get(record.title) ?? 0) === 4)
388
- continue;
389
- const cost = lineCost([record]);
390
- if (cost > allowance)
391
- continue;
392
- keptResults.push(record);
393
- allowance -= cost;
394
- counts.set(record.title, (counts.get(record.title) ?? 0) + 1);
395
- }
396
- let ledger = [...lists.records, ...keptResults];
385
+ let ledger = lists.records;
386
+ let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
397
387
  // List caps are existing ranking policy; only the carried target is a
398
388
  // spending limit. Candidate list sizes have fixed, cached line prices.
399
- while (keptResults.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
400
- keptResults.pop();
401
- ledger = [...lists.records, ...keptResults];
402
- }
403
389
  if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
404
390
  ledger = [];
391
+ listedKeep = 0;
405
392
  for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
406
393
  const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
407
- if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target)
394
+ if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) {
408
395
  ledger = candidate;
396
+ listedKeep = keep;
397
+ }
409
398
  }
410
399
  }
411
400
  const mandatory = new Set([...protectedView.whole].filter(index => {
@@ -424,6 +413,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
424
413
  const compiledBoundary = boundary;
425
414
  // A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
426
415
  const sourceKey = (record) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
416
+ const keptResults = [], thinking = [];
427
417
  const assemble = (compiled, at = compiledBoundary) => {
428
418
  const split = compiled ? splitSummary(compiled) : undefined;
429
419
  if (compiled && !split)
@@ -472,11 +462,82 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
472
462
  }
473
463
  }
474
464
  orderByOriginalSource(records, sourceIndices, originals.selectedIds);
475
- const summary = render([...records, ...ledger]);
476
- return { summary, records };
465
+ const thoughtOpenings = thinking.filter(record => !moved.has(record.sourceIndex));
466
+ const summary = render([...records, ...ledger, ...keptResults, ...thoughtOpenings]);
467
+ return { summary, records: [...records, ...thoughtOpenings] };
477
468
  };
478
469
  const compiled = tuck.compileDialogue(compileInput);
479
470
  let offer = assemble(compiled.text);
471
+ // After the complete dialogue fill, observations spend the remaining
472
+ // room before the native tail's older end. The pinned tail is untouched.
473
+ let keptResultCost = 0;
474
+ const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
475
+ const counts = new Map();
476
+ const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry) => readable(entry) !== undefined;
477
+ // Reads and searches share the lead rank, newest result first, and one
478
+ // allowance. Keep L2's independent four-item caps and whole-item skips.
479
+ const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
480
+ .sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
481
+ for (const record of candidates) {
482
+ if ((counts.get(record.title) ?? 0) === 4)
483
+ continue;
484
+ const extra = lineCost([record]);
485
+ if (keptResultCost + extra > keptResultCap || price(offer.summary.length + keptResultCost + extra, boundary) > target)
486
+ continue;
487
+ keptResults.push(record);
488
+ keptResultCost += extra;
489
+ counts.set(record.title, (counts.get(record.title) ?? 0) + 1);
490
+ }
491
+ if (keptResults.length)
492
+ offer = assemble(compiled.text, boundary);
493
+ const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
494
+ const shownFiles = lists.files.slice(0, Math.min(listedKeep, MAX_LEDGER_LINES));
495
+ const keptReadPaths = new Set(keptResults.filter(record => record.title === "Kept-read").map(record => {
496
+ const heading = record.text.slice(0, record.text.indexOf("\n"));
497
+ return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
498
+ }));
499
+ const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
500
+ const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
501
+ for (const item of shownFiles)
502
+ item.definitions = observations.get(item.path);
503
+ const outputs = new Set(), definitions = new Set();
504
+ let observationCost = 0;
505
+ const fitsObservation = (extra) => price(offer.summary.length + observationCost + extra, boundary) <= target;
506
+ // Each kind gives way as whole items, oldest first; an oversized newest
507
+ // item cannot promote an older one. Pointer lines need no extra omission.
508
+ for (const item of shownActions) {
509
+ if (!item.outputTail)
510
+ continue;
511
+ const extra = lineCost(actionRecords([item], 1, new Set([item]))) - lineCost(actionRecords([item], 1));
512
+ if (!fitsObservation(extra))
513
+ break;
514
+ outputs.add(item);
515
+ observationCost += extra;
516
+ }
517
+ for (const item of shownFiles) {
518
+ if (!item.definitions)
519
+ continue;
520
+ const extra = lineCost(ledgerRecords([item], 1, new Set([item]))) - lineCost(ledgerRecords([item], 1));
521
+ if (!fitsObservation(extra))
522
+ break;
523
+ definitions.add(item);
524
+ observationCost += extra;
525
+ }
526
+ if (outputs.size || definitions.size) {
527
+ ledger = [...actionRecords(lists.actions, listedKeep, outputs), ...ledgerRecords(lists.files, listedKeep, definitions)];
528
+ offer = assemble(compiled.text, boundary);
529
+ }
530
+ // Plain thinking follows kept reads/searches, output tails and definition maps.
531
+ let thinkingCost = 0;
532
+ for (const record of thinkingRecords(entries.slice(0, boundary), indices, openingLength)) {
533
+ const extra = lineCost([record]);
534
+ if (price(offer.summary.length + thinkingCost + extra, boundary) > target)
535
+ break;
536
+ thinking.push(record);
537
+ thinkingCost += extra;
538
+ }
539
+ if (thinking.length)
540
+ offer = assemble(compiled.text, boundary);
480
541
  // Only capacity left after all higher ranks can extend the native tail
481
542
  // beyond its preferred rank boundary. No old allocator is consulted.
482
543
  const liveStartId = calibration.ok ? calibration.selectedIds[0] : undefined;
@@ -521,12 +582,13 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
521
582
  missing.forEach((unit, at) => counts[at + 1] = counts[at] + unit.count);
522
583
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
523
584
  });
524
- const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
525
- const keptResultCost = lineCost(keptResults), keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
585
+ const baseCost = lineCost(offer.records) + lineCost(ledger) + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
586
+ const keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
526
587
  const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
527
588
  const extensionPrice = (at) => {
528
- // Fixed kept results outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
529
- if (keptResults.length && (at <= lastKeptResultPosition || keptResultCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000)))
589
+ // Kept results already spend this extension's price. They stay in
590
+ // the compacted prefix, so the native tail never repeats them.
591
+ if (keptResults.length && at <= lastKeptResultPosition)
530
592
  return Infinity;
531
593
  let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
532
594
  let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);