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,6 +1,7 @@
1
1
  import { resolveSourceTime } from "./tuck/core/source-time.js";
2
2
  import { isSourceExport, isLookupTool, isRecallTool } from "./tuck/core/recall-operation.js";
3
3
  import { escapeRegex } from "./tuck/core/keyword-query.js";
4
+ import { readableContentParts } from "./tuck/core/readable-content.js";
4
5
  export const MAX_RECALL_CHARACTERS = 16000;
5
6
  export const MAX_RECALL_QUERY_CHARACTERS = 256;
6
7
  export const MAX_RECALL_ENTRY_ID_CHARACTERS = 100;
@@ -56,22 +57,8 @@ export function createRecall(policy = {}) {
56
57
  (entry.message.role === "assistant" && entry.message.content.some((b) => b.type === "toolCall")) ||
57
58
  entry.message.role === "bashExecution");
58
59
  }
59
- function textContent(content, includeToolCalls = false) {
60
- if (typeof content === "string")
61
- return content;
62
- if (!Array.isArray(content))
63
- return "";
64
- const blocks = content;
65
- return blocks.flatMap((block) => {
66
- if (block === null || typeof block !== "object" || !("type" in block))
67
- return [];
68
- if (block.type === "text" && "text" in block && typeof block.text === "string")
69
- return [block.text];
70
- if (includeToolCalls && block.type === "toolCall" && "name" in block && typeof block.name === "string"
71
- && "id" in block && typeof block.id === "string" && "arguments" in block)
72
- return [JSON.stringify({ toolCall: { name: block.name, id: block.id, arguments: block.arguments } })];
73
- return [];
74
- }).join("\n");
60
+ function textContent(content, assistant = false) {
61
+ return readableContentParts(content, assistant).map(part => part.text).join("\n");
75
62
  }
76
63
  function readable(entry, attempts, links) {
77
64
  if (!isHistorySource(entry))
@@ -142,7 +129,8 @@ export function createRecall(policy = {}) {
142
129
  calls.set(block.id, group);
143
130
  local.push(call);
144
131
  }
145
- // Exactly the parts admitted by textContent, including empty text/newlines.
132
+ // Exactly the public prefix admitted by textContent, including empty
133
+ // text/newlines. Plain thinking is appended after this prefix.
146
134
  if (!(block.type === "text" && typeof block.text === "string" || block.type === "toolCall" &&
147
135
  typeof block.name === "string" && typeof block.id === "string" && "arguments" in block))
148
136
  continue;
@@ -186,20 +174,15 @@ export function createRecall(policy = {}) {
186
174
  if (message.role !== "assistant")
187
175
  return [{ start: 0, end: text.length }];
188
176
  const ranges = [];
189
- let position = 0;
190
- for (const block of message.content) {
191
- if (block.type !== "text" && block.type !== "toolCall")
192
- continue;
193
- const part = textContent([block], true);
194
- const end = position + part.length;
195
- if (block.type !== "toolCall" || !isLookupTool(block.name) || isRecallTool(block.name) && isSourceExport(block.arguments)) {
177
+ for (const part of readableContentParts(message.content, true)) {
178
+ const position = part.offset, end = position + part.text.length;
179
+ if (part.kind !== "toolCall" || !isLookupTool(part.toolName) || isRecallTool(part.toolName) && isSourceExport(part.arguments)) {
196
180
  const previous = ranges.at(-1);
197
181
  if (previous && previous.end + 1 === position)
198
182
  previous.end = end;
199
183
  else
200
184
  ranges.push({ start: position, end });
201
185
  }
202
- position = end + 1;
203
186
  }
204
187
  return ranges.filter(({ start, end }) => end > start);
205
188
  }
@@ -16,34 +16,19 @@ export declare function loadPiRequestMath(): Promise<PiRequestMath | undefined>;
16
16
  * Without Pi's request arithmetic, fall back to Pi 1.2–1.5's documented 4,096-token allowance.
17
17
  */
18
18
  export declare function piContextSafetyMargin(math?: PiRequestMath): Promise<number>;
19
- /** 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). */
20
- export declare const REPLY_FLOOR_MIN = 3584;
21
- /** A spent thinking budget that produced neither a visible answer nor work. Empty/text/tool replies keep the existing length recovery. */
19
+ /** A length stop with visible reasoning but no visible answer or work. */
22
20
  export declare const thinkingOnlyLength: (message: AgentMessage) => boolean;
23
- /** Thinking-only exhaustion uses the observed largest reply, not the full reserve. Every other failed length/overflow keeps its override. */
24
- export declare const needsFullReplyReserve: (message: AgentMessage) => boolean;
25
- /** Saved immediately at the reply's turn boundary, even when recovery cannot make a compaction. */
26
- /** `catalogueContextWindow` is the model's configured window when the server clipped below it. A learned window holds only while the
27
- * configured window is unchanged: a server or catalogue that grew must not stay capped by an old clip (Nautilus, 2026-11-20). */
28
- export interface WindowReceipt {
29
- calibrationIdentity: string;
30
- learnedContextWindow: number;
31
- catalogueContextWindow: number;
32
- serverClippedReplyId: string;
33
- }
34
- export declare const WINDOW_RECEIPT = "pi-tuck-window";
35
- /** The newest learned window for `identity`, if it was learned under the model's current configured window. One recorded before 1.3.3
36
- * carries no configured window and is not trusted: if the server still clips, the next clipped reply learns it again. */
37
- export declare function seedContextWindow(branch: readonly SessionEntry[], identity: string, catalogue: number | undefined): number | undefined;
38
- /** One branch reader for the reserve override and reply floor, including history before cuts. A server-clipping receipt follows its reply. */
39
- export declare function replyFit(branch: readonly SessionEntry[]): {
40
- failed: boolean;
41
- largestOutput: number;
42
- thinkingStop: boolean;
21
+ type ReplyModel = {
22
+ provider: string;
23
+ api: string;
24
+ id: string;
25
+ maxTokens: number;
43
26
  };
44
- export declare function branchReplyFloor(branch: readonly SessionEntry[], reserve: number): number;
45
- /** Admission never promises more output than a model with a positive reply cap can produce. */
46
- export declare function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, maxTokens?: number): number;
27
+ /** Reply room a cut above the room aims for before any long reply is seen. Cuts only: admission keeps the observed floor. */
28
+ export declare const CUT_REPLY_FLOOR = 3584;
29
+ /** Ordinary reply demand is bounded by the reserve and model output limit.
30
+ * Recovery compares its candidate against the interrupted attempt separately. */
31
+ export declare function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, model: ReplyModel, minimum?: number): number;
47
32
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
48
33
  export declare function carriesPrompt(messages: Messages, prompt: string, role?: 'user' | 'custom'): boolean;
49
34
  export {};
@@ -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,5 +1,11 @@
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;
4
+ /** pi-tuck's own cuts on a branch: what `/tuck` and the footer count. */
5
+ export declare const tuckCuts: <E extends {
6
+ type: string;
7
+ details?: unknown;
8
+ }>(branch: readonly E[]) => E[];
3
9
  /** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
4
10
  export declare function statusText(input: {
5
11
  version: string;
@@ -14,4 +20,7 @@ export declare function statusText(input: {
14
20
  }[];
15
21
  pending?: boolean;
16
22
  cutAt: number | undefined;
23
+ cacheSensitive?: boolean;
24
+ /** The trim point in tokens for the current model, the footer's full bar; absent when it cannot be computed. */
25
+ cutPoint?: number;
17
26
  }): 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 {
@@ -11,27 +12,31 @@ export const LOADED_VERSION = (() => {
11
12
  return "unknown";
12
13
  }
13
14
  })();
15
+ /** pi-tuck's own cuts on a branch: what `/tuck` and the footer count. */
16
+ export const tuckCuts = (branch) => branch.filter(e => e.type === "compaction" && e.details?.compactor === "pi-tuck");
14
17
  /** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
15
18
  export function statusText(input) {
16
19
  if (!input.active)
17
- return `pi-tuck ${input.version} is loaded but inactive in this host; Pi's own compaction runs.`;
20
+ return `pi-tuck ${input.version} is inactive in this host.`;
18
21
  if (input.compaction?.kind === 'standingDown')
19
- return `pi-tuck ${input.version}: standing down: ${input.compaction.reason}; Pi's own compaction runs.`;
20
- const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => e.details?.compactor === "pi-tuck");
22
+ return `pi-tuck ${input.version} is standing down (${input.compaction.reason}). Pi controls compaction.`;
23
+ const cuts = input.branch.filter(e => e.type === "compaction"), ours = tuckCuts(input.branch);
21
24
  const last = ours.at(-1), before = last?.tokensBefore, after = last?.details?.tokensAfter;
22
25
  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
- : `Cuts: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
26
+ 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."
27
+ : `Trims: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
25
28
  const native = cuts.length - ours.length;
29
+ const now = input.cutPoint === undefined ? "" : ` (about ${count(input.cutPoint)} tokens with this model)`;
26
30
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
27
31
  entry.data?.kind === "retry").length;
28
32
  return [
29
33
  `pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
30
34
  cutLine,
31
- ...(retries ? [`Retries: ${retries} after thinking-only length stops in this session.`] : []),
32
- ...(input.pending ? ["A cut is pending: requests already carry it; the first boundary saves it."] : []),
33
- ...(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
+ ...(retries ? [`Capacity retries on this branch: ${retries}.`] : []),
36
+ ...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
37
+ ...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
38
+ input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
39
+ ? `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.`,
35
40
  "Search: by keyword.",
36
41
  ].join("\n");
37
42
  }
@@ -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 & {