pi-tuck 1.3.4 → 1.5.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 (48) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +67 -122
  3. package/dist/index.d.ts +1 -4
  4. package/dist/index.js +56 -10
  5. package/dist/src/budget.d.ts +6 -15
  6. package/dist/src/budget.js +6 -11
  7. package/dist/src/build-id.d.ts +1 -1
  8. package/dist/src/build-id.js +1 -1
  9. package/dist/src/compaction.d.ts +15 -20
  10. package/dist/src/compaction.js +236 -204
  11. package/dist/src/content-observations.d.ts +24 -0
  12. package/dist/src/content-observations.js +122 -0
  13. package/dist/src/diagnostics.d.ts +1 -3
  14. package/dist/src/footer.d.ts +37 -0
  15. package/dist/src/footer.js +91 -0
  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/recall.js +8 -25
  21. package/dist/src/request-capacity.d.ts +11 -26
  22. package/dist/src/request-capacity.js +20 -57
  23. package/dist/src/run.d.ts +16 -7
  24. package/dist/src/run.js +53 -25
  25. package/dist/src/status.d.ts +9 -0
  26. package/dist/src/status.js +14 -9
  27. package/dist/src/tuck/core/format.js +1 -1
  28. package/dist/src/tuck/core/readable-content.d.ts +14 -0
  29. package/dist/src/tuck/core/readable-content.js +43 -0
  30. package/dist/src/tuck.d.ts +2 -1
  31. package/dist/src/tuck.js +92 -30
  32. package/index.ts +46 -10
  33. package/package.json +3 -1
  34. package/src/budget.ts +7 -12
  35. package/src/build-id.ts +1 -1
  36. package/src/compaction.ts +228 -194
  37. package/src/content-observations.ts +115 -0
  38. package/src/diagnostics.ts +1 -1
  39. package/src/footer.ts +111 -0
  40. package/src/ledger.ts +17 -10
  41. package/src/llama-continuation.ts +176 -0
  42. package/src/recall.ts +8 -20
  43. package/src/request-capacity.ts +18 -57
  44. package/src/run.ts +48 -22
  45. package/src/status.ts +20 -9
  46. package/src/tuck/core/format.ts +1 -1
  47. package/src/tuck/core/readable-content.ts +44 -0
  48. 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 type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
3
  import type { AgentMessage, Messages } from './budget.js';
4
4
  import { parseRecords, splitSummary } from './tuck/core/transcript.js';
@@ -51,71 +51,32 @@ export async function piContextSafetyMargin(math?: PiRequestMath): Promise<numbe
51
51
  } catch { return 4_096; }
52
52
  }
53
53
 
54
- /** 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). */
55
- export const REPLY_FLOOR_MIN = 3_584;
56
-
57
- /** A spent thinking budget that produced neither a visible answer nor work. Empty/text/tool replies keep the existing length recovery. */
54
+ /** A length stop with visible reasoning but no visible answer or work. */
58
55
  export const thinkingOnlyLength = (message: AgentMessage): boolean => message.role === 'assistant' && message.stopReason === 'length' &&
59
56
  message.content.length > 0 && message.content.every(block => block.type === 'thinking');
60
57
 
61
- /** Thinking-only exhaustion uses the observed largest reply, not the full reserve. Every other failed length/overflow keeps its override. */
62
- export const needsFullReplyReserve = (message: AgentMessage): boolean => message.role === 'assistant' &&
63
- (message.stopReason === 'length' && !thinkingOnlyLength(message) || message.stopReason === 'error' && isContextOverflow(message));
58
+ type ReplyModel = { provider: string; api: string; id: string; maxTokens: number };
64
59
 
65
- /** Saved immediately at the reply's turn boundary, even when recovery cannot make a compaction. */
66
- /** `catalogueContextWindow` is the model's configured window when the server clipped below it. A learned window holds only while the
67
- * configured window is unchanged: a server or catalogue that grew must not stay capped by an old clip (Nautilus, 2026-11-20). */
68
- export interface WindowReceipt { calibrationIdentity: string; learnedContextWindow: number; catalogueContextWindow: number; serverClippedReplyId: string }
69
- export const WINDOW_RECEIPT = 'pi-tuck-window';
70
- function windowSettings(entry: SessionEntry): Partial<WindowReceipt> | undefined {
71
- if (entry.type === 'custom' && entry.customType === WINDOW_RECEIPT) return entry.data as Partial<WindowReceipt> | undefined;
72
- if (entry.type === 'compaction') return (entry.details as { diagnosticReceipt?: { settings?: Partial<WindowReceipt> } } | undefined)?.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: readonly SessionEntry[], identity: string, catalogue: number | undefined): number | undefined {
78
- for (let i = branch.length; i--;) {
79
- const settings = windowSettings(branch[i]!);
80
- if (settings?.calibrationIdentity !== identity) continue;
81
- const window = settings.learnedContextWindow;
82
- if (!(Number.isSafeInteger(window) && window! > 0)) return undefined;
83
- return catalogue !== undefined && settings.catalogueContextWindow === catalogue ? window : undefined;
84
- }
85
- return undefined;
86
- }
60
+ /** Reply room a cut above the room aims for before any long reply is seen. Cuts only: admission keeps the observed floor. */
61
+ export const CUT_REPLY_FLOOR = 3_584;
87
62
 
88
- /** One branch reader for the reserve override and reply floor, including history before cuts. A server-clipping receipt follows its reply. */
89
- export function replyFit(branch: readonly SessionEntry[]): { failed: boolean; largestOutput: number; thinkingStop: boolean } {
90
- let failed = false, largestOutput = 0, thinkingStop = false;
91
- const clipped = new Set<string>();
92
- for (let i = branch.length; i--;) {
93
- const entry = branch[i]!;
94
- const receipt = entry.type === 'custom' && entry.customType === WINDOW_RECEIPT ? windowSettings(entry) : undefined;
95
- if (receipt && Number.isSafeInteger(receipt.learnedContextWindow) && receipt.learnedContextWindow! > 0 &&
96
- typeof receipt.serverClippedReplyId === 'string') clipped.add(receipt.serverClippedReplyId);
63
+ /** Ordinary reply demand is bounded by the reserve and model output limit.
64
+ * Recovery compares its candidate against the interrupted attempt separately. */
65
+ export function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, model: ReplyModel, minimum = 1): number {
66
+ const reserved = Math.max(1, reserve);
67
+ const limit = model.maxTokens > 0 ? Math.min(reserved, model.maxTokens) : reserved;
68
+ let largest = minimum;
69
+ for (const entry of branch) {
97
70
  if (entry.type !== 'message' || entry.message.role !== 'assistant') continue;
98
71
  const message = entry.message;
99
- failed ||= !clipped.has(entry.id) && needsFullReplyReserve(message);
100
- thinkingStop ||= thinkingOnlyLength(message);
72
+ if (message.model !== model.id || message.provider !== model.provider || message.api !== model.api ||
73
+ message.stopReason === 'error' || message.stopReason === 'aborted') continue;
101
74
  const output = message.usage?.output;
102
- if (typeof output === 'number' && Number.isFinite(output) && output > largestOutput) largestOutput = output;
75
+ if (typeof output !== 'number' || !Number.isFinite(output) || output <= 0) continue;
76
+ largest = Math.max(largest, output);
77
+ if (largest >= limit) break;
103
78
  }
104
- return { failed, largestOutput, thinkingStop };
105
- }
106
-
107
- export function branchReplyFloor(branch: readonly SessionEntry[], reserve: number): number {
108
- const { failed, largestOutput, thinkingStop } = replyFit(branch);
109
- if (failed) return reserve;
110
- // Include exhausted thinking output across cuts/restarts; requestReplyFloor applies the model cap.
111
- const largest = Math.ceil(Math.max(REPLY_FLOOR_MIN, largestOutput));
112
- return thinkingStop ? largest : Math.min(reserve, largest);
113
- }
114
-
115
- /** Admission never promises more output than a model with a positive reply cap can produce. */
116
- export function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, maxTokens?: number): number {
117
- const floor = branchReplyFloor(branch, reserve);
118
- return maxTokens !== undefined && maxTokens > 0 ? Math.min(floor, maxTokens) : floor;
79
+ return Math.min(limit, Math.ceil(largest));
119
80
  }
120
81
 
121
82
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
package/src/run.ts CHANGED
@@ -4,22 +4,38 @@ import { textOf } from './tuck/core/content.js';
4
4
  import type { Clip } from './clip.js';
5
5
 
6
6
  export type CutEntry = { type: 'compaction'; summary: string; firstKeptEntryId: string; tokensBefore: number; details?: unknown };
7
- type Context = Pick<ExtensionContext, 'cwd' | 'sessionManager'>;
7
+ type Context = Pick<ExtensionContext, 'cwd' | 'sessionManager'> & Partial<Pick<ExtensionContext, 'model'>>;
8
+ const budgetIdentity = (model: Context['model']) => model &&
9
+ JSON.stringify([model.provider, model.api, model.id, model.contextWindow, model.maxTokens]);
8
10
  export interface CutView { session: ExtensionContext['sessionManager']; keptFromId: string | undefined; hasTuckCut: boolean; pending: boolean }
9
11
 
10
12
  /** The only owner of a cut that requests carry before Pi saves it. */
11
13
  export class PendingCut {
12
- private cut?: CutEntry;
13
- private branchLength = 0;
14
+ private proposal?: { cut: CutEntry; manager: Context['sessionManager']; cwd: string; branchLength: number; anchor: string | undefined; budget?: string };
14
15
  private preview?: { manager: Context['sessionManager']; cwd: string; leaf: string | null; view: CutView };
15
- plan(cut: CutEntry, branchLength: number) { this.cut = cut; this.branchLength = branchLength; this.preview = undefined; }
16
- clear() { this.cut = undefined; this.branchLength = 0; this.preview = undefined; }
17
- take() { const cut = this.cut; this.clear(); return cut; }
16
+ plan(cut: CutEntry, ctx: Context) {
17
+ const branch = ctx.sessionManager.getBranch();
18
+ this.proposal = { cut, manager: ctx.sessionManager, cwd: ctx.cwd, branchLength: branch.length,
19
+ anchor: branch.at(-1)?.id, budget: budgetIdentity(ctx.model) };
20
+ this.preview = undefined;
21
+ }
22
+ clear() { this.proposal = undefined; this.preview = undefined; }
23
+ take(ctx: Context) {
24
+ if (!this.view(ctx).pending) return;
25
+ const cut = this.proposal?.cut;
26
+ this.clear();
27
+ return cut;
28
+ }
18
29
  view(ctx: Context, entries: readonly SessionBoundaryDraft[] = []): CutView {
19
- const live = ctx.sessionManager, leaf = live.getLeafId?.(), held = this.preview;
20
- // Native entries are append-only; a leaf move invalidates both the saved and pending views.
30
+ const live = ctx.sessionManager, leaf = live.getLeafId?.();
31
+ const proposal = this.proposal;
32
+ if (proposal && (proposal.manager !== live || proposal.cwd !== ctx.cwd || proposal.budget !== budgetIdentity(ctx.model))) this.clear();
33
+ const held = this.preview;
34
+ // Native entries are append-only. A changed leaf requires checking that the plan's anchor still precedes it.
21
35
  if (!entries.length && leaf !== undefined && held && held.manager === live && held.cwd === ctx.cwd && held.leaf === leaf) return held.view;
22
- const branch = live.getBranch(), cut = this.cut;
36
+ const branch = live.getBranch();
37
+ if (this.proposal?.anchor !== undefined && branch[this.proposal.branchLength - 1]?.id !== this.proposal.anchor) this.clear();
38
+ const cut = this.proposal?.cut;
23
39
  const remember = (view: CutView) => {
24
40
  if (!entries.length && leaf !== undefined) this.preview = { manager: live, cwd: ctx.cwd, leaf, view };
25
41
  return view;
@@ -30,7 +46,7 @@ export class PendingCut {
30
46
  hasTuckCut: hasTuckCut(branch), pending: false });
31
47
  }
32
48
  // A compact-all plan predates the prompt. Keep from the first appended entry, skipping our capacity receipts.
33
- const keptFromId = cut && (cut.firstKeptEntryId || branch.slice(this.branchLength)
49
+ const keptFromId = cut && (cut.firstKeptEntryId || branch.slice(this.proposal!.branchLength)
34
50
  .find(entry => entry.type !== 'custom' || entry.customType !== 'pi-tuck-capacity')?.id || '');
35
51
  const header = live.getHeader();
36
52
  if (!header) throw new Error("Missing native session header for the prompt's cut");
@@ -85,7 +101,6 @@ export const RUN_TRANSITIONS: Readonly<Record<RunPhase, readonly RunPhase[]>> =
85
101
  failed: ['failed', 'commit-failed'],
86
102
  'commit-failed': ['commit-failed'],
87
103
  };
88
- let reportedInvalidTransition = false;
89
104
  type RunState = { phase: Exclude<RunPhase, 'failed' | 'commit-failed'> } | { phase: 'failed' | 'commit-failed'; error: Error };
90
105
 
91
106
  export class Run {
@@ -98,30 +113,41 @@ export class Run {
98
113
  get expired() { return this.expiredPlan; }
99
114
  /** Failure data, only present in a failed phase. The phase alone decides admission. */
100
115
  get error() { return 'error' in this.state ? this.state.error : undefined; }
101
- transition(phase: RunPhase, ctx?: Pick<ExtensionContext, 'hasUI'>, error?: Error): boolean {
116
+ transition(phase: RunPhase, error?: Error): void {
102
117
  if (!RUN_TRANSITIONS[this.phase].includes(phase) || ((phase === 'failed' || phase === 'commit-failed') && !error)) {
103
- const message = `pi-tuck: invalid run transition ${this.phase} -> ${phase}`;
104
- if (process.env.NODE_ENV === 'test') throw new Error(message);
105
- if (ctx?.hasUI === false && !reportedInvalidTransition) {
106
- reportedInvalidTransition = true;
107
- try { process.stderr.write(message + '\n'); } catch { /* ended */ }
108
- }
109
- return false;
118
+ const fault = new Error(`pi-tuck: invalid run transition ${this.phase} -> ${phase}`);
119
+ // A rejected transition must stop the caller and latch admission shut.
120
+ // Preserve an existing terminal cause, especially a persistence fault.
121
+ if (this.state.phase !== 'failed' && this.state.phase !== 'commit-failed')
122
+ this.state = { phase: 'failed', error: fault };
123
+ throw fault;
110
124
  }
111
125
  this.state = phase === 'failed' || phase === 'commit-failed' ? { phase, error: error! } : { phase };
112
126
  if (phase === 'expired') this.expiredPlan = true;
113
- return true;
114
127
  }
115
128
  prompt?: StartingPrompt;
116
129
  cut = new PendingCut();
117
130
  clips = new Map<string, Clip>();
118
131
  pendingBoundaryReceipts: string[] = [];
119
- thinkingRetryPending = false;
132
+ rejectedBudget?: { input: number; output: number };
133
+ private lengthRecovery: 'available' | 'pending' | 'used' = 'available';
134
+ get lengthRetryPending() { return this.lengthRecovery === 'pending'; }
135
+ get canRetryLength() { return this.phase === 'admitted' && this.lengthRecovery === 'available'; }
136
+ requestLengthRetry() {
137
+ if (!this.canRetryLength) throw new Error('pi-tuck: capacity recovery is unavailable for this run');
138
+ this.lengthRecovery = 'pending';
139
+ }
140
+ finishLengthRetry() {
141
+ if (this.lengthRecovery === 'pending') this.lengthRecovery = 'used';
142
+ }
143
+ /** Pi grants another recovery after a good reply or a new user message. */
144
+ rearmLengthRetry() { this.lengthRecovery = 'available';
145
+ }
120
146
  /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
121
147
  nativeFloorPending = false;
122
148
  refusalReceipted = false;
123
149
  clear() {
124
150
  this.prompt = undefined; this.cut.clear(); this.clips.clear(); this.pendingBoundaryReceipts = [];
125
- this.thinkingRetryPending = false; this.nativeFloorPending = false; this.refusalReceipted = false; this.expiredPlan = false;
151
+ this.rejectedBudget = undefined; this.nativeFloorPending = false; this.refusalReceipted = false; this.expiredPlan = false;
126
152
  }
127
153
  }
package/src/status.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
3
 
4
+ export const CONTINUATION_CACHE_MISS = "Native continuation stopped because the server could not reuse the unfinished response without rebuilding context.";
5
+
4
6
  /** The version of the package this code was loaded from: the open session keeps it until Pi restarts, whatever is installed since. */
5
7
  export const LOADED_VERSION: string = (() => {
6
8
  try {
@@ -10,6 +12,10 @@ export const LOADED_VERSION: string = (() => {
10
12
  } catch { return "unknown"; }
11
13
  })();
12
14
 
15
+ /** pi-tuck's own cuts on a branch: what `/tuck` and the footer count. */
16
+ export const tuckCuts = <E extends { type: string; details?: unknown }>(branch: readonly E[]): E[] =>
17
+ branch.filter(e => e.type === "compaction" && (e.details as { compactor?: unknown } | null | undefined)?.compactor === "pi-tuck");
18
+
13
19
  /** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
14
20
  export function statusText(input: {
15
21
  version: string;
@@ -18,24 +24,29 @@ export function statusText(input: {
18
24
  branch: readonly { type: string; tokensBefore?: unknown; details?: unknown; customType?: unknown; data?: unknown }[];
19
25
  pending?: boolean;
20
26
  cutAt: number | undefined;
27
+ cacheSensitive?: boolean;
28
+ /** The trim point in tokens for the current model, the footer's full bar; absent when it cannot be computed. */
29
+ cutPoint?: number;
21
30
  }): string {
22
- if (!input.active) return `pi-tuck ${input.version} is loaded but inactive in this host; Pi's own compaction runs.`;
23
- if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version}: standing down: ${input.compaction.reason}; Pi's own compaction runs.`;
24
- const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => (e.details as { compactor?: unknown } | null | undefined)?.compactor === "pi-tuck");
31
+ if (!input.active) return `pi-tuck ${input.version} is inactive in this host.`;
32
+ if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version} is standing down (${input.compaction.reason}). Pi controls compaction.`;
33
+ const cuts = input.branch.filter(e => e.type === "compaction"), ours = tuckCuts(input.branch);
25
34
  const last = ours.at(-1), before = last?.tokensBefore, after = (last?.details as { tokensAfter?: unknown } | undefined)?.tokensAfter;
26
35
  const count = (n: number) => n.toLocaleString("en-US");
27
- 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."
28
- : `Cuts: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
36
+ const cutLine = ours.length === 0 ? input.pending ? "Trims: none saved yet in this session." : "Trims: none yet in this session. Recall becomes available after the first pi-tuck trim on this branch."
37
+ : `Trims: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
29
38
  const native = cuts.length - ours.length;
39
+ const now = input.cutPoint === undefined ? "" : ` (about ${count(input.cutPoint)} tokens with this model)`;
30
40
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
31
41
  (entry.data as { kind?: unknown } | null | undefined)?.kind === "retry").length;
32
42
  return [
33
43
  `pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
34
44
  cutLine,
35
- ...(retries ? [`Retries: ${retries} after thinking-only length stops in this session.`] : []),
36
- ...(input.pending ? ["A cut is pending: requests already carry it; the first boundary saves it."] : []),
37
- ...(native > 0 ? [`Pi's own compaction cut ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
38
- 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.`,
45
+ ...(retries ? [`Capacity retries on this branch: ${retries}.`] : []),
46
+ ...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
47
+ ...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
48
+ input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
49
+ ? `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
39
50
  "Search: by keyword.",
40
51
  ].join("\n");
41
52
  }
@@ -1,6 +1,6 @@
1
1
  import { CLOSING_SEPARATOR } from "./transcript";
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,44 @@
1
+ export interface ReadableContentPart {
2
+ kind: "text" | "toolCall" | "thinking";
3
+ text: string;
4
+ offset: number;
5
+ toolName?: string;
6
+ arguments?: unknown;
7
+ }
8
+
9
+ /** Pi stores opaque/encrypted reasoning in thinkingSignature. The one exception: pi-ai's openai-completions adapter stores only the name of the
10
+ * response field the plain reasoning came from (OPENAI_COMPLETIONS_REASONING_FIELDS), which signs or encrypts nothing. Also refuse explicit
11
+ * redaction/encryption markers in imported session blocks. */
12
+ const PLAIN_REASONING_FIELDS: ReadonlySet<unknown> = new Set(["reasoning", "reasoning_content", "reasoning_text"]);
13
+ export function isPlainThinking(block: unknown): block is { type: "thinking"; thinking: string } {
14
+ if (!block || typeof block !== "object") return false;
15
+ const value = block as Record<string, unknown>;
16
+ return value.type === "thinking" && typeof value.thinking === "string" && (value.thinkingSignature === undefined || PLAIN_REASONING_FIELDS.has(value.thinkingSignature)) &&
17
+ (value.redacted === undefined || value.redacted === false) &&
18
+ (value.encrypted === undefined || value.encrypted === false) &&
19
+ value.encryptedContent === undefined && value.encrypted_content === undefined;
20
+ }
21
+
22
+ /** Keep the existing text/tool-call prefix byte for byte, including empty text
23
+ * parts. Append plain thinking in block order so older recall offsets remain valid. */
24
+ export function readableContentParts(content: unknown, assistant = false): ReadableContentPart[] {
25
+ if (typeof content === "string") return [{ kind: "text", text: content, offset: 0 }];
26
+ if (!Array.isArray(content)) return [];
27
+ const parts: Omit<ReadableContentPart, "offset">[] = [];
28
+ for (const block of content) {
29
+ if (!block || typeof block !== "object") continue;
30
+ if (block.type === "text" && typeof block.text === "string") parts.push({ kind: "text", text: block.text });
31
+ else if (assistant && block.type === "toolCall" && typeof block.name === "string" && typeof block.id === "string" && "arguments" in block)
32
+ parts.push({ kind: "toolCall", toolName: block.name, arguments: block.arguments,
33
+ text: JSON.stringify({ toolCall: { name: block.name, id: block.id, arguments: block.arguments } }) });
34
+ }
35
+ if (assistant) for (const block of content)
36
+ if (isPlainThinking(block) && block.thinking.length) parts.push({ kind: "thinking", text: block.thinking });
37
+ let offset = 0;
38
+ return parts.map((part, at) => {
39
+ if (at) offset++;
40
+ const located = { ...part, offset };
41
+ offset += part.text.length;
42
+ return located;
43
+ });
44
+ }
package/src/tuck.ts CHANGED
@@ -9,6 +9,8 @@ import { isTextOnly, textOf } from "./tuck/core/content";
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";
13
+ import { pathKey } from "./path-key";
12
14
  import { convertToLlm, SessionManager, type ExtensionContext,
13
15
  type SessionBeforeCompactEvent, type SessionEntry } from "@earendil-works/pi-coding-agent";
14
16
  import { ATTEMPT_NOTICE, createRecall, type RecallPolicy,
@@ -50,14 +52,15 @@ import { rankRecallRows } from "./tuck/core/search-entries";
50
52
  export const tuck: Tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
51
53
  /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
52
54
  * `_operatorManual` retains the exported positional slot for existing callers. */
53
- export function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId?: string) {
54
- return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId }, ctx, reserveTokens, measure, policy, retainCurrentInput);
55
+ export function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId?: string, keepRecentTokens?: number) {
56
+ return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId,
57
+ keepRecentTokens: event.preparation.settings?.keepRecentTokens ?? keepRecentTokens }, ctx, reserveTokens, measure, policy, retainCurrentInput);
55
58
  }
56
59
  /** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
57
60
  /** `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
58
61
  * a run a custom message starts); the session has moved on from an ended run.
59
62
  * `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
60
- export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string; newPrompt?: boolean; reRenderSummary?: boolean; protectedPromptEntryId?: string; deepest?: boolean }, ctx: ExtensionContext,
63
+ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string; newPrompt?: boolean; reRenderSummary?: boolean; protectedPromptEntryId?: string; deepest?: boolean; keepRecentTokens?: number }, ctx: ExtensionContext,
61
64
  reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true): Draft {
62
65
  const { isHistorySource, readable } = createRecall(policy);
63
66
  const projected = ctx.sessionManager.buildSessionProjection();
@@ -325,7 +328,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
325
328
  const fixedRowsCost = preferredHigh.cost + lineCost(preferredLists.records);
326
329
  const baseCharacters = frameLength(fixedRowsCost, preferredHigh.rows.length + preferredLists.records.length);
327
330
  const base = price(baseCharacters, preferredBoundary);
328
- const target = carriedTarget(model.contextWindow, reserveTokens, base, before);
331
+ // Cap historical fill at native keep-recent for post-cut headroom parity, preserving the floor and preferred tail.
332
+ const target = Math.min(carriedTarget(model.contextWindow, reserveTokens, base, before), Math.max(base, offset + (input.keepRecentTokens ?? Infinity)));
329
333
  // The old tail rule supplies an ordering boundary only. Its recent
330
334
  // suffix follows the openings, and is charged to the same total grant.
331
335
  const boundaries = [floorBoundary];
@@ -358,30 +362,18 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
358
362
  const lists = listsAt(boundary);
359
363
  const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
360
364
  const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
361
- let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
362
- const keptResults: TranscriptRecord[] = [], counts = new Map<string, number>();
363
- const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
364
- const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
365
- .sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
366
- for (const record of candidates) {
367
- if ((counts.get(record.title!) ?? 0) === 4) continue;
368
- const cost = lineCost([record]);
369
- if (cost > allowance) continue;
370
- keptResults.push(record); allowance -= cost;
371
- counts.set(record.title!, (counts.get(record.title!) ?? 0) + 1);
372
- }
373
- let ledger: TranscriptRecord[] = [...lists.records, ...keptResults];
365
+ let ledger: TranscriptRecord[] = lists.records;
366
+ let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
374
367
  // List caps are existing ranking policy; only the carried target is a
375
368
  // spending limit. Candidate list sizes have fixed, cached line prices.
376
- while (keptResults.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
377
- keptResults.pop();
378
- ledger = [...lists.records, ...keptResults];
379
- }
380
369
  if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
381
370
  ledger = [];
371
+ listedKeep = 0;
382
372
  for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
383
373
  const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
384
- if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) ledger = candidate;
374
+ if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) {
375
+ ledger = candidate; listedKeep = keep;
376
+ }
385
377
  }
386
378
  }
387
379
  const mandatory = new Set([...protectedView.whole].filter(index => {
@@ -399,6 +391,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
399
391
  const compiledBoundary = boundary;
400
392
  // A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
401
393
  const sourceKey = (record: TranscriptRecord) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
394
+ const keptResults: TranscriptRecord[] = [], thinking: TranscriptRecord[] = [];
402
395
  const assemble = (compiled: string, at = compiledBoundary) => {
403
396
  const split = compiled ? splitSummary(compiled) : undefined;
404
397
  if (compiled && !split) throw new Error("pi-tuck returned an invalid summary");
@@ -439,11 +432,68 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
439
432
  }
440
433
  }
441
434
  orderByOriginalSource(records, sourceIndices, originals.selectedIds);
442
- const summary = render([...records, ...ledger]);
443
- return { summary, records };
435
+ const thoughtOpenings = thinking.filter(record => !moved.has(record.sourceIndex));
436
+ const summary = render([...records, ...ledger, ...keptResults, ...thoughtOpenings]);
437
+ return { summary, records: [...records, ...thoughtOpenings] };
444
438
  };
445
439
  const compiled = tuck.compileDialogue(compileInput);
446
440
  let offer = assemble(compiled.text);
441
+ // After the complete dialogue fill, observations spend the remaining
442
+ // room before the native tail's older end. The pinned tail is untouched.
443
+ let keptResultCost = 0;
444
+ const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
445
+ const counts = new Map<string, number>();
446
+ const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
447
+ // Reads and searches share the lead rank, newest result first, and one
448
+ // allowance. Keep L2's independent four-item caps and whole-item skips.
449
+ const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
450
+ .sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
451
+ for (const record of candidates) {
452
+ if ((counts.get(record.title!) ?? 0) === 4) continue;
453
+ const extra = lineCost([record]);
454
+ if (keptResultCost + extra > keptResultCap || price(offer.summary.length + keptResultCost + extra, boundary) > target) continue;
455
+ keptResults.push(record); keptResultCost += extra;
456
+ counts.set(record.title!, (counts.get(record.title!) ?? 0) + 1);
457
+ }
458
+ if (keptResults.length) offer = assemble(compiled.text, boundary);
459
+ const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
460
+ const shownFiles = lists.files.slice(0, Math.min(listedKeep, MAX_LEDGER_LINES));
461
+ const keptReadPaths = new Set(keptResults.filter(record => record.title === "Kept-read").map(record => {
462
+ const heading = record.text!.slice(0, record.text!.indexOf("\n"));
463
+ return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
464
+ }));
465
+ const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
466
+ const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
467
+ for (const item of shownFiles) item.definitions = observations.get(item.path);
468
+ const outputs = new Set<(typeof lists.actions)[number]>(), definitions = new Set<(typeof lists.files)[number]>();
469
+ let observationCost = 0;
470
+ const fitsObservation = (extra: number) => price(offer.summary.length + observationCost + extra, boundary) <= target;
471
+ // Each kind gives way as whole items, oldest first; an oversized newest
472
+ // item cannot promote an older one. Pointer lines need no extra omission.
473
+ for (const item of shownActions) {
474
+ if (!item.outputTail) continue;
475
+ const extra = lineCost(actionRecords([item], 1, new Set([item]))) - lineCost(actionRecords([item], 1));
476
+ if (!fitsObservation(extra)) break;
477
+ outputs.add(item); observationCost += extra;
478
+ }
479
+ for (const item of shownFiles) {
480
+ if (!item.definitions) continue;
481
+ const extra = lineCost(ledgerRecords([item], 1, new Set([item]))) - lineCost(ledgerRecords([item], 1));
482
+ if (!fitsObservation(extra)) break;
483
+ definitions.add(item); observationCost += extra;
484
+ }
485
+ if (outputs.size || definitions.size) {
486
+ ledger = [...actionRecords(lists.actions, listedKeep, outputs), ...ledgerRecords(lists.files, listedKeep, definitions)];
487
+ offer = assemble(compiled.text, boundary);
488
+ }
489
+ // Plain thinking follows kept reads/searches, output tails and definition maps.
490
+ let thinkingCost = 0;
491
+ for (const record of thinkingRecords(entries.slice(0, boundary), indices, openingLength)) {
492
+ const extra = lineCost([record]);
493
+ if (price(offer.summary.length + thinkingCost + extra, boundary) > target) break;
494
+ thinking.push(record); thinkingCost += extra;
495
+ }
496
+ if (thinking.length) offer = assemble(compiled.text, boundary);
447
497
  // Only capacity left after all higher ranks can extend the native tail
448
498
  // beyond its preferred rank boundary. No old allocator is consulted.
449
499
  const liveStartId = calibration.ok ? calibration.selectedIds[0] : undefined;
@@ -482,12 +532,13 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
482
532
  missing.forEach((unit, at) => counts[at + 1] = counts[at]! + unit.count);
483
533
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
484
534
  });
485
- const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
486
- const keptResultCost = lineCost(keptResults), keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
535
+ const baseCost = lineCost(offer.records) + lineCost(ledger) + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
536
+ const keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
487
537
  const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
488
538
  const extensionPrice = (at: number) => {
489
- // Fixed kept results outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
490
- if (keptResults.length && (at <= lastKeptResultPosition || keptResultCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000))) return Infinity;
539
+ // Kept results already spend this extension's price. They stay in
540
+ // the compacted prefix, so the native tail never repeats them.
541
+ if (keptResults.length && at <= lastKeptResultPosition) return Infinity;
491
542
  let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
492
543
  let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
493
544
  for (const range of ranges) {