pi-tuck 1.12.0 → 1.13.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,27 @@
3
3
  All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.13.0]
7
+
8
+ ### Changed
9
+
10
+ - Kept tail after a cut: when the tool round just older than the kept turns would leave the kept tail short (a large read, command
11
+ output or file write that does not fit the tail), the summary now carries that round in a closing "Kept-round" section: its calls
12
+ and their text results, within two thirds of a quarter of the summary room. Parts that do not fit are clipped to their head and
13
+ tail with a `tuck_recall` locator for the rest, call arguments included. On recorded sessions, cuts whose kept context falls below
14
+ 80% of the tail size went from 59 to 11 of 9,272. The 11 that remain: 5 at a 48k window, where the summary share cannot hold a
15
+ full tail; 4 where the crossing round is mostly the model's thinking, which is not carried; 1 where the entry before the kept turns
16
+ records no tokens; 1 where the newest entry is a length-stopped reply that the cut drops.
17
+
18
+ ## [1.12.1]
19
+
20
+ ### Fixed
21
+
22
+ - The first user turn (the task statement) rides whole in every summary, the smallest one after a length retry included, so an
23
+ instruction past its opening line is no longer cut off after a few chained cuts. A first turn over 8,000 characters keeps its first
24
+ and last 4,000, with a `tuck_recall` locator for the rest. Below a 64k-token room the cap is one character per 8 tokens of room, so
25
+ a small window keeps room to cut.
26
+
6
27
  ## [1.12.0]
7
28
 
8
29
  ### Changed
package/README.md CHANGED
@@ -12,11 +12,11 @@ pi install npm:pi-tuck
12
12
 
13
13
  Start a new Pi process after installing or updating. pi-tuck handles automatic compaction and `/compact` by default. Run `/tuck` to see the loaded version, cut history, and active cut policy.
14
14
 
15
- This README describes pi-tuck 1.12.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.12.0` or `pi install git:github.com/galyavin/pi-tuck@v1.12.0`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.13.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.13.0` or `pi install git:github.com/galyavin/pi-tuck@v1.13.0`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
19
- A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It carries the output of a command a prompt told the agent to run (such as "Run: telex read NAME"), the newest four and at most 8,000 characters in all, since an agent driven by messages gets its tasks that way. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
19
+ A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It carries the output of a command a prompt told the agent to run (such as "Run: telex read NAME"), the newest four and at most 8,000 characters in all, since an agent driven by messages gets its tasks that way. When the tool round just before the kept turns is too large to keep with them, the summary carries it, clipped where needed, with a `tuck_recall` locator for each clipped part. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
20
20
 
21
21
  Files the agent has read more than once are carried whole after the summary, most-read first, as far as a share of the summary allows. A file is carried only when its last read covered the whole file and the file on disk still holds exactly that text; the agent can edit from a carried copy without re-reading it. When a session's cuts keep dropping files the agent then reads again unchanged, pi-tuck moves its trim point later, to native Pi's (the larger of the room and `keepRecentTokens`), while keeping room for the next reply. Cuts still trim to the usual size.
22
22
 
@@ -1 +1 @@
1
- export declare const BUILD_ID = "210d6264761e797d386437e785ce52781a630ff250d80b12160f987b5ba346ca";
1
+ export declare const BUILD_ID = "9a1d1acbec0fa4d9ce13c203156e107f843afb87bb3123d9b20b3a44236f366e";
@@ -1 +1 @@
1
- export const BUILD_ID = "210d6264761e797d386437e785ce52781a630ff250d80b12160f987b5ba346ca";
1
+ export const BUILD_ID = "9a1d1acbec0fa4d9ce13c203156e107f843afb87bb3123d9b20b3a44236f366e";
@@ -4,6 +4,13 @@ export interface Clip {
4
4
  toolCallId: string;
5
5
  content: ToolResultMessage["content"];
6
6
  }
7
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
8
+ /** `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
9
+ export declare const clipText: (text: string, keep: number, locator: {
10
+ entryId: string;
11
+ } | {
12
+ index: number;
13
+ }, base?: number) => string;
7
14
  /** The budgets to offer a fresh round the room cannot hold whole, in the units the round and the mandatory input are counted in, tried in order.
8
15
  * The room is the provider's, so it is divided by the factor the provider's counts have been running at - the same conversion the planner's own
9
16
  * reserve makes (budget.ts) - before the input no cut can remove is taken out; counting the provider's room against an estimate asks the round for
package/dist/src/clip.js CHANGED
@@ -3,12 +3,15 @@ import { MAX_RECALL_CHARACTERS } from "./recall.js";
3
3
  /** The text `tuck_recall {entryId, offset}` reads from a text-only result; any other result is not clipped. */
4
4
  const textOf = (message) => message.content.every(block => block.type === "text")
5
5
  ? message.content.map(block => block.type === "text" ? block.text : "").join("\n") : undefined;
6
- const clipped = (text, keep, entryId) => {
6
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
7
+ /** `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
8
+ export const clipText = (text, keep, locator, base = 0) => {
7
9
  const head = Math.ceil(keep / 2), tail = keep - head;
8
- return [{ type: "text", text: text.slice(0, head) +
9
- `\n[pi-tuck: characters ${head}-${text.length - tail} of ${text.length} are not shown, to fit the context window; read them with ` +
10
- `tuck_recall {"entryId":"${entryId}","offset":${head}}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail) }];
10
+ return text.slice(0, head) +
11
+ `\n[pi-tuck: characters ${head}-${text.length - tail} of ${text.length} are not shown, to fit the context window; read them with ` +
12
+ `tuck_recall ${JSON.stringify({ ...locator, offset: base + head })}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail);
11
13
  };
14
+ const clipped = (text, keep, entryId) => [{ type: "text", text: clipText(text, keep, { entryId }) }];
12
15
  /** The budgets to offer a fresh round the room cannot hold whole, in the units the round and the mandatory input are counted in, tried in order.
13
16
  * The room is the provider's, so it is divided by the factor the provider's counts have been running at - the same conversion the planner's own
14
17
  * reserve makes (budget.ts) - before the input no cut can remove is taken out; counting the provider's room against an estimate asks the round for
@@ -5,3 +5,8 @@ export declare function keptReadCandidates(entries: readonly (SessionEntry | Ses
5
5
  /** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
6
6
  * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
7
7
  export declare function promptOutputCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
8
+ /** The tool round just older than a tail boundary (the assistant's calls and their text results), as one closing-section record whose calls and
9
+ * results fit `budget` tokens together: the smallest go whole, the rest share what is left and are clipped as a fresh result is (clip.ts), so that
10
+ * tuck_recall reads the rest from the untouched entries by their summary index (the arguments of a call at their place in the assistant entry's readable text).
11
+ * Nothing when no round ends at the boundary, a result is not text, a result cannot be recalled, or the budget cannot hold even the locators. */
12
+ export declare function crossingRoundRecord(entries: readonly SessionEntry[], boundary: number, indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, budget: number): TranscriptRecord | undefined;
@@ -1,7 +1,10 @@
1
1
  import { classifyBash } from "./bash-command.js";
2
+ import { conversationTokens } from "./budget.js";
3
+ import { clipText } from "./clip.js";
2
4
  import { pathKey } from "./path-key.js";
3
5
  import { isDiscardedResponse } from "./protocol.js";
4
6
  import { isTextOnly, textOf } from "./tuck/core/content.js";
7
+ import { readableContentParts } from "./tuck/core/readable-content.js";
5
8
  import { extractPath } from "./tuck/core/tool-args.js";
6
9
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
7
10
  export function keptReadCandidates(entries, indices, resolvable, exclude = new Set()) {
@@ -119,3 +122,70 @@ export function promptOutputCandidates(entries, indices, resolvable) {
119
122
  }
120
123
  return records;
121
124
  }
125
+ /** The tool round just older than a tail boundary (the assistant's calls and their text results), as one closing-section record whose calls and
126
+ * results fit `budget` tokens together: the smallest go whole, the rest share what is left and are clipped as a fresh result is (clip.ts), so that
127
+ * tuck_recall reads the rest from the untouched entries by their summary index (the arguments of a call at their place in the assistant entry's readable text).
128
+ * Nothing when no round ends at the boundary, a result is not text, a result cannot be recalled, or the budget cannot hold even the locators. */
129
+ export function crossingRoundRecord(entries, boundary, indices, resolvable, budget) {
130
+ const results = [];
131
+ let at = boundary - 1;
132
+ for (; at >= 0; at--) {
133
+ const entry = entries[at];
134
+ if (entry.type !== "message" || entry.message.role !== "toolResult")
135
+ break;
136
+ results.unshift({ entry, message: entry.message });
137
+ }
138
+ const call = entries[at];
139
+ if (!results.length || call?.type !== "message" || call.message.role !== "assistant")
140
+ return undefined;
141
+ // Each call's arguments and their place in the readable text: {"toolCall":{"name":…,"id":…,"arguments":ARGS}}
142
+ const parts = new Map(readableContentParts(call.message.content, true).flatMap(part => {
143
+ if (part.kind !== "toolCall")
144
+ return [];
145
+ const args = JSON.stringify(part.arguments) ?? "";
146
+ return [[JSON.parse(part.text).toolCall.id,
147
+ { name: part.toolName, args, offset: part.offset + part.text.length - args.length - 2 }]];
148
+ }));
149
+ const sourceIndex = indices.get(results[0].entry.id);
150
+ if (sourceIndex === undefined || results.some(({ entry, message }) => !parts.has(message.toolCallId) || !isTextOnly(message.content) ||
151
+ indices.get(entry.id) === undefined || !resolvable(entry)))
152
+ return undefined;
153
+ const callIndex = indices.get(call.id), callLocatable = callIndex !== undefined && resolvable(call);
154
+ const size = (text) => conversationTokens([{ role: "user", content: text, timestamp: 0 }]);
155
+ // One item per call's arguments and per result; arguments that cannot be recalled keep a fixed 400-character head.
156
+ const items = results.flatMap(({ entry, message }) => {
157
+ const part = parts.get(message.toolCallId);
158
+ const args = callLocatable ? { text: part.args, locator: { index: callIndex }, base: part.offset }
159
+ : { text: part.args.length > 400 ? `${part.args.slice(0, 400)}…` : part.args, locator: undefined, base: 0 };
160
+ return [args, { text: textOf(message.content), locator: { index: indices.get(entry.id) }, base: 0 }];
161
+ }).map((item, index) => ({ ...item, index, size: size(item.text) }));
162
+ const shown = [];
163
+ let left = budget - Math.ceil(results.reduce((n, { message }) => n + parts.get(message.toolCallId).name.length + 4, 0) / 4);
164
+ const order = [...items].sort((a, b) => a.size - b.size);
165
+ for (const [rank, item] of order.entries()) {
166
+ const share = Math.floor(left / (order.length - rank));
167
+ if (item.size <= share || !item.locator) {
168
+ shown[item.index] = item.text;
169
+ left -= item.size;
170
+ continue;
171
+ }
172
+ const locator = item.locator, clip = (keep) => clipText(item.text, keep, locator, item.base);
173
+ if (size(clip(0)) > share)
174
+ return undefined;
175
+ let low = 0, high = item.text.length;
176
+ while (low < high) {
177
+ const mid = Math.ceil((low + high) / 2);
178
+ if (size(clip(mid)) <= share)
179
+ low = mid;
180
+ else
181
+ high = mid - 1;
182
+ }
183
+ shown[item.index] = clip(low);
184
+ left -= size(shown[item.index]);
185
+ }
186
+ if (left < 0)
187
+ return undefined;
188
+ const body = results.map(({ message }, i) => `${parts.get(message.toolCallId).name} ${shown[2 * i]}:\n${shown[2 * i + 1]}`).join("\n\n");
189
+ return { kind: "section", title: "Kept-round", sourceIndex,
190
+ text: `the tool round just before the kept tail (as recorded at #${sourceIndex}; clipped where a recall locator says so):\n${body}` };
191
+ }
@@ -34,6 +34,8 @@ export interface RecallContinuation {
34
34
  export declare const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
35
35
  /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
36
36
  export declare const WORKING_SET_SHARE: number;
37
+ /** The first user turn (the task statement) rides whole in every summary up to this many characters, and no more characters than an eighth of the room's tokens (rooms below 64k); a longer one keeps its head and tail (1.12.1). */
38
+ export declare const FIRST_TURN_CHARACTERS = 8000;
37
39
  /** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
38
40
  export interface Tuck {
39
41
  buildOwnCut(entries: SessionEntry[], keep: number): Cut;
package/dist/src/tuck.js CHANGED
@@ -7,9 +7,10 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.j
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content.js";
9
9
  import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
10
- import { keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
10
+ import { crossingRoundRecord, keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
11
11
  import { workingSetCandidates } from "./working-set.js";
12
12
  import { keptSearchCandidates } from "./kept-searches.js";
13
+ import { clipText } from "./clip.js";
13
14
  import { fileObservations, thinkingRecords } from "./content-observations.js";
14
15
  import { pathKey } from "./path-key.js";
15
16
  import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
@@ -18,6 +19,8 @@ import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
18
19
  export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
19
20
  /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
20
21
  export const WORKING_SET_SHARE = 2 / 3;
22
+ /** The first user turn (the task statement) rides whole in every summary up to this many characters, and no more characters than an eighth of the room's tokens (rooms below 64k); a longer one keeps its head and tail (1.12.1). */
23
+ export const FIRST_TURN_CHARACTERS = 8_000;
21
24
  import { buildOwnCut, applyTailBudget, MAX_TAIL_TOKENS, OVERSIZED_TAIL_FACTOR } from "./tuck/cut.js";
22
25
  import { calibrateCharsPerToken, estimateSourceMessageChars } from "./tuck/core/token-estimate.js";
23
26
  import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
@@ -162,6 +165,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
162
165
  throw new Error("Missing native session header");
163
166
  const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
164
167
  const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
168
+ // At most about a thirty-second of the room in tokens, so a small window keeps its cut room (1.12.1).
169
+ const firstTurnCap = Math.min(FIRST_TURN_CHARACTERS, Math.floor(room / 8));
165
170
  const positions = new Map(entries.map((entry, at) => [entry.id, at]));
166
171
  const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
167
172
  if (!originals.ok)
@@ -212,7 +217,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
212
217
  for (let at = branch.length - 1; at >= 0; at--)
213
218
  native[at] += native[at + 1];
214
219
  const nativeAt = (boundary) => boundary === entries.length ? 0 : native[rawPositions.get(entries[boundary].id)];
215
- const tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
220
+ const originalBoundary = preferredBoundary, tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
216
221
  // Move only the older end, to the newest whole protocol-safe entries
217
222
  // within the shared tail size. Required current/fresh native sources
218
223
  // stay whole even when their floor exceeds that preferred amount.
@@ -259,6 +264,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
259
264
  list.forEach((unit, at) => count[at + 1] = count[at] + unit.count);
260
265
  return [role, { end, count }];
261
266
  }));
267
+ const shorter = (a, b) => a.length < b.length ? a : b;
262
268
  const quoteCache = new Map();
263
269
  const quote = (entry, take) => {
264
270
  const key = `${entry.id}:${take}`;
@@ -269,11 +275,14 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
269
275
  const text = entry.type === "custom_message" ? textOf(entry.content) : entry.type === "message" && entry.message.role === "user" ? textOf(entry.message.content) : "";
270
276
  const sourceTimes = index === undefined ? undefined : [{ sourceIndex: index, ...resolveSourceTime(entry) }];
271
277
  // Custom entries have a native identity but no global message index.
272
- const records = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity
273
- ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }), text, sourceTimes,
278
+ // The first user turn as an anchor: whole up to its cap, else its head and tail (1.12.1). A protected input stays whole.
279
+ const firstTurn = entry.id === firstUser?.id && take === firstTurnCap;
280
+ const records = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity || firstTurn
281
+ ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }),
282
+ text: firstTurn && text.length > take ? shorter(clipText(text, take, { index: index }), text) : text, sourceTimes,
274
283
  ...(entry.type === "custom_message" ? { sourceEntryId: entry.id } : {}) }]
275
284
  : userPrefixRecords({ kind: "user", text, originalText: text, startsSource: true, sourceIndex: index }, undefined, take).map(record => ({ ...record, sourceTimes }));
276
- cached = { records, cost: lineCost(records), whole: take >= text.length };
285
+ cached = { records, cost: lineCost(records), whole: take >= text.length || firstTurn && records[0]?.text === text };
277
286
  quoteCache.set(key, cached);
278
287
  return cached;
279
288
  };
@@ -296,7 +305,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
296
305
  add(current, Infinity);
297
306
  for (const entry of anchors)
298
307
  if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id) < boundary)
299
- add(entry, length);
308
+ add(entry, entry.id === firstUser?.id ? firstTurnCap : length);
300
309
  const omissions = [];
301
310
  for (const role of ["user", "assistant", "toolResult"]) {
302
311
  const list = units[role], prefix = prefixes[role];
@@ -429,7 +438,20 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
429
438
  return row?.message.role === "user" && isTextOnly(row.message.content);
430
439
  }));
431
440
  const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
432
- const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
441
+ // The tool round the tail boundary passed (the one crossing the tail size) rides in the closing section, so the tail is not left far
442
+ // below its size. It is paid from the summary, up to what the native tail leaves of that size, and is reserved before the dialogue fills.
443
+ let crossingRound;
444
+ const briefRoom = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
445
+ if (boundary === preferredBoundary && (preferredBoundary > originalBoundary || budgetCut) && boundary < entries.length) {
446
+ const crossing = entries.slice(0, boundary).findLastIndex(entry => !(entry.type === "message" && entry.message.role === "toolResult"));
447
+ const tail = crossing < 0 ? 0 : carriedTailTokens(Math.max(nativeAt(originalBoundary), nativeAt(crossing))) - nativeAt(boundary);
448
+ // Like the working set, at most WORKING_SET_SHARE of what the summary may spend beyond its protected rows: the dialogue keeps the rest.
449
+ const size = Math.min(tail, Math.floor(WORKING_SET_SHARE * briefRoom / 4));
450
+ if (size > 0)
451
+ crossingRound = crossingRoundRecord(entries, boundary, indices, resolvable, size);
452
+ }
453
+ const crossingCost = crossingRound ? lineCost([crossingRound]) : 0;
454
+ const maxBriefChars = briefRoom;
433
455
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
434
456
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position])),
435
457
  ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
@@ -591,7 +613,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
591
613
  if ((counts.get(record.title) ?? 0) === 4)
592
614
  continue;
593
615
  const extra = lineCost([record]);
594
- if (keptResultCost + extra > keptResultCap || price(offer.summary.length + keptResultCost + extra, boundary) > target)
616
+ if (keptResultCost + extra > keptResultCap || price(offer.summary.length + crossingCost + keptResultCost + extra, boundary) > target)
595
617
  continue;
596
618
  keptResults.push(record);
597
619
  keptResultCost += extra;
@@ -611,7 +633,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
611
633
  item.definitions = observations.get(item.path);
612
634
  const outputs = new Set(), definitions = new Set();
613
635
  let observationCost = 0;
614
- const fitsObservation = (extra) => price(offer.summary.length + observationCost + extra, boundary) <= target;
636
+ const fitsObservation = (extra) => price(offer.summary.length + crossingCost + observationCost + extra, boundary) <= target;
615
637
  // Each kind gives way as whole items, oldest first; an oversized newest
616
638
  // item cannot promote an older one. Pointer lines need no extra omission.
617
639
  for (const item of shownActions) {
@@ -640,7 +662,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
640
662
  let thinkingCost = 0;
641
663
  for (const record of thinkingRecords(entries.slice(0, boundary), indices, openingLength)) {
642
664
  const extra = lineCost([record]);
643
- if (price(offer.summary.length + thinkingCost + extra, boundary) > target)
665
+ if (price(offer.summary.length + crossingCost + thinkingCost + extra, boundary) > target)
644
666
  break;
645
667
  thinking.push(record);
646
668
  thinkingCost += extra;
@@ -725,6 +747,11 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
725
747
  if (boundary !== compiledBoundary)
726
748
  offer = assemble(compiled.text, boundary);
727
749
  }
750
+ // Still the preferred boundary (leftover room did not take the round into the native tail): the round rides in the summary instead.
751
+ if (crossingRound && boundary === preferredBoundary && price(offer.summary.length + crossingCost, boundary) <= target) {
752
+ keptResults.unshift(crossingRound);
753
+ offer = assemble(compiled.text, boundary);
754
+ }
728
755
  const projection = preview(offer.summary, boundary);
729
756
  assertNativeToolRounds(projection);
730
757
  const after = measure(projection);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "210d6264761e797d386437e785ce52781a630ff250d80b12160f987b5ba346ca";
1
+ export const BUILD_ID = "9a1d1acbec0fa4d9ce13c203156e107f843afb87bb3123d9b20b3a44236f366e";
package/src/clip.ts CHANGED
@@ -9,13 +9,17 @@ export interface Clip { toolCallId: string; content: ToolResultMessage["content"
9
9
  const textOf = (message: ToolResultMessage) => message.content.every(block => block.type === "text")
10
10
  ? message.content.map(block => block.type === "text" ? block.text : "").join("\n") : undefined;
11
11
 
12
- const clipped = (text: string, keep: number, entryId: string): ToolResultMessage["content"] => {
12
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
13
+ /** `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
14
+ export const clipText = (text: string, keep: number, locator: { entryId: string } | { index: number }, base = 0): string => {
13
15
  const head = Math.ceil(keep / 2), tail = keep - head;
14
- return [{ type: "text", text: text.slice(0, head) +
16
+ return text.slice(0, head) +
15
17
  `\n[pi-tuck: characters ${head}-${text.length - tail} of ${text.length} are not shown, to fit the context window; read them with ` +
16
- `tuck_recall {"entryId":"${entryId}","offset":${head}}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail) }];
18
+ `tuck_recall ${JSON.stringify({ ...locator, offset: base + head })}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail);
17
19
  };
18
20
 
21
+ const clipped = (text: string, keep: number, entryId: string): ToolResultMessage["content"] => [{ type: "text", text: clipText(text, keep, { entryId }) }];
22
+
19
23
  /** The budgets to offer a fresh round the room cannot hold whole, in the units the round and the mandatory input are counted in, tried in order.
20
24
  * The room is the provider's, so it is divided by the factor the provider's counts have been running at - the same conversion the planner's own
21
25
  * reserve makes (budget.ts) - before the input no cut can remove is taken out; counting the provider's room against an estimate asks the round for
package/src/kept-reads.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
2
+ import type { ToolResultMessage } from "@earendil-works/pi-ai";
2
3
  import { classifyBash } from "./bash-command";
4
+ import { conversationTokens, type Messages } from "./budget";
5
+ import { clipText } from "./clip";
3
6
  import { pathKey } from "./path-key";
4
7
  import { isDiscardedResponse } from "./protocol";
5
8
  import { isTextOnly, textOf } from "./tuck/core/content";
9
+ import { readableContentParts } from "./tuck/core/readable-content";
6
10
  import { extractPath } from "./tuck/core/tool-args";
7
11
  import type { TranscriptRecord } from "./tuck/core/transcript";
8
12
 
@@ -94,3 +98,55 @@ export function promptOutputCandidates(entries: readonly (SessionEntry | Session
94
98
  }
95
99
  return records;
96
100
  }
101
+
102
+ /** The tool round just older than a tail boundary (the assistant's calls and their text results), as one closing-section record whose calls and
103
+ * results fit `budget` tokens together: the smallest go whole, the rest share what is left and are clipped as a fresh result is (clip.ts), so that
104
+ * tuck_recall reads the rest from the untouched entries by their summary index (the arguments of a call at their place in the assistant entry's readable text).
105
+ * Nothing when no round ends at the boundary, a result is not text, a result cannot be recalled, or the budget cannot hold even the locators. */
106
+ export function crossingRoundRecord(entries: readonly SessionEntry[], boundary: number, indices: ReadonlyMap<string, number>,
107
+ resolvable: (entry: SessionEntry) => boolean, budget: number): TranscriptRecord | undefined {
108
+ const results: { entry: SessionEntry; message: ToolResultMessage }[] = [];
109
+ let at = boundary - 1;
110
+ for (; at >= 0; at--) {
111
+ const entry = entries[at]!;
112
+ if (entry.type !== "message" || entry.message.role !== "toolResult") break;
113
+ results.unshift({ entry, message: entry.message as ToolResultMessage });
114
+ }
115
+ const call = entries[at];
116
+ if (!results.length || call?.type !== "message" || call.message.role !== "assistant") return undefined;
117
+ // Each call's arguments and their place in the readable text: {"toolCall":{"name":…,"id":…,"arguments":ARGS}}
118
+ const parts = new Map(readableContentParts(call.message.content, true).flatMap(part => {
119
+ if (part.kind !== "toolCall") return [];
120
+ const args = JSON.stringify(part.arguments) ?? "";
121
+ return [[(JSON.parse(part.text) as { toolCall: { id: string } }).toolCall.id,
122
+ { name: part.toolName!, args, offset: part.offset + part.text.length - args.length - 2 }] as const];
123
+ }));
124
+ const sourceIndex = indices.get(results[0]!.entry.id);
125
+ if (sourceIndex === undefined || results.some(({ entry, message }) => !parts.has(message.toolCallId) || !isTextOnly(message.content) ||
126
+ indices.get(entry.id) === undefined || !resolvable(entry))) return undefined;
127
+ const callIndex = indices.get(call.id), callLocatable = callIndex !== undefined && resolvable(call);
128
+ const size = (text: string) => conversationTokens([{ role: "user", content: text, timestamp: 0 }] as Messages);
129
+ // One item per call's arguments and per result; arguments that cannot be recalled keep a fixed 400-character head.
130
+ const items = results.flatMap(({ entry, message }) => {
131
+ const part = parts.get(message.toolCallId)!;
132
+ const args = callLocatable ? { text: part.args, locator: { index: callIndex } as { index: number } | undefined, base: part.offset }
133
+ : { text: part.args.length > 400 ? `${part.args.slice(0, 400)}…` : part.args, locator: undefined, base: 0 };
134
+ return [args, { text: textOf(message.content), locator: { index: indices.get(entry.id)! }, base: 0 }];
135
+ }).map((item, index) => ({ ...item, index, size: size(item.text) }));
136
+ const shown: string[] = [];
137
+ let left = budget - Math.ceil(results.reduce((n, { message }) => n + parts.get(message.toolCallId)!.name.length + 4, 0) / 4);
138
+ const order = [...items].sort((a, b) => a.size - b.size);
139
+ for (const [rank, item] of order.entries()) {
140
+ const share = Math.floor(left / (order.length - rank));
141
+ if (item.size <= share || !item.locator) { shown[item.index] = item.text; left -= item.size; continue; }
142
+ const locator = item.locator, clip = (keep: number) => clipText(item.text, keep, locator, item.base);
143
+ if (size(clip(0)) > share) return undefined;
144
+ let low = 0, high = item.text.length;
145
+ while (low < high) { const mid = Math.ceil((low + high) / 2); if (size(clip(mid)) <= share) low = mid; else high = mid - 1; }
146
+ shown[item.index] = clip(low); left -= size(shown[item.index]!);
147
+ }
148
+ if (left < 0) return undefined;
149
+ const body = results.map(({ message }, i) => `${parts.get(message.toolCallId)!.name} ${shown[2 * i]}:\n${shown[2 * i + 1]}`).join("\n\n");
150
+ return { kind: "section", title: "Kept-round", sourceIndex,
151
+ text: `the tool round just before the kept tail (as recorded at #${sourceIndex}; clipped where a recall locator says so):\n${body}` };
152
+ }
package/src/tuck.ts CHANGED
@@ -7,9 +7,10 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget";
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief";
8
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
- import { keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
10
+ import { crossingRoundRecord, keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
11
11
  import { workingSetCandidates, type WorkingFile } from "./working-set.js";
12
12
  import { keptSearchCandidates } from "./kept-searches.js";
13
+ import { clipText } from "./clip.js";
13
14
  import { fileObservations, thinkingRecords } from "./content-observations";
14
15
  import { pathKey } from "./path-key";
15
16
  import { convertToLlm, SessionManager, type ExtensionContext,
@@ -34,6 +35,8 @@ export interface RecallContinuation { query: string; throughEntryId: string; off
34
35
  export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
35
36
  /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
36
37
  export const WORKING_SET_SHARE = 2 / 3;
38
+ /** The first user turn (the task statement) rides whole in every summary up to this many characters, and no more characters than an eighth of the room's tokens (rooms below 64k); a longer one keeps its head and tail (1.12.1). */
39
+ export const FIRST_TURN_CHARACTERS = 8_000;
37
40
  /** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
38
41
  export interface Tuck {
39
42
  buildOwnCut(entries: SessionEntry[], keep: number): Cut;
@@ -181,6 +184,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
181
184
  if (!header) throw new Error("Missing native session header");
182
185
  const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
183
186
  const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
187
+ // At most about a thirty-second of the room in tokens, so a small window keeps its cut room (1.12.1).
188
+ const firstTurnCap = Math.min(FIRST_TURN_CHARACTERS, Math.floor(room / 8));
184
189
  const positions = new Map(entries.map((entry, at) => [entry.id, at]));
185
190
  const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
186
191
  if (!originals.ok) return { unavailable: "No eligible original prefix to compile" };
@@ -221,7 +226,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
221
226
  }
222
227
  for (let at = branch.length - 1; at >= 0; at--) native[at] += native[at + 1]!;
223
228
  const nativeAt = (boundary: number) => boundary === entries.length ? 0 : native[rawPositions.get(entries[boundary]!.id)!]!;
224
- const tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
229
+ const originalBoundary = preferredBoundary, tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
225
230
  // Move only the older end, to the newest whole protocol-safe entries
226
231
  // within the shared tail size. Required current/fresh native sources
227
232
  // stay whole even when their floor exceeds that preferred amount.
@@ -263,6 +268,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
263
268
  list.forEach((unit, at) => count[at + 1] = count[at]! + unit.count);
264
269
  return [role, { end, count }];
265
270
  })) as Record<keyof typeof units, { end: Int32Array; count: Int32Array }>;
271
+ const shorter = (a: string, b: string) => a.length < b.length ? a : b;
266
272
  const quoteCache = new Map<string, { records: TranscriptRecord[]; cost: number; whole: boolean }>();
267
273
  const quote = (entry: SessionEntry, take: number) => {
268
274
  const key = `${entry.id}:${take}`;
@@ -272,11 +278,14 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
272
278
  const text = entry.type === "custom_message" ? textOf(entry.content) : entry.type === "message" && entry.message.role === "user" ? textOf(entry.message.content) : "";
273
279
  const sourceTimes = index === undefined ? undefined : [{ sourceIndex: index, ...resolveSourceTime(entry) }];
274
280
  // Custom entries have a native identity but no global message index.
275
- const records: TranscriptRecord[] = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity
276
- ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }), text, sourceTimes,
281
+ // The first user turn as an anchor: whole up to its cap, else its head and tail (1.12.1). A protected input stays whole.
282
+ const firstTurn = entry.id === firstUser?.id && take === firstTurnCap;
283
+ const records: TranscriptRecord[] = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity || firstTurn
284
+ ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }),
285
+ text: firstTurn && text.length > take ? shorter(clipText(text, take, { index: index! }), text) : text, sourceTimes,
277
286
  ...(entry.type === "custom_message" ? { sourceEntryId: entry.id } : {}) }]
278
287
  : userPrefixRecords({ kind: "user", text, originalText: text, startsSource: true, sourceIndex: index }, undefined, take).map(record => ({ ...record, sourceTimes }));
279
- cached = { records, cost: lineCost(records), whole: take >= text.length };
288
+ cached = { records, cost: lineCost(records), whole: take >= text.length || firstTurn && records[0]?.text === text };
280
289
  quoteCache.set(key, cached);
281
290
  return cached;
282
291
  };
@@ -290,7 +299,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
290
299
  };
291
300
  if (latestPosition >= 0 && latestPosition < boundary && latestTextOnly) add(latest!, Infinity);
292
301
  if (currentPosition >= 0 && currentPosition < boundary && current?.id !== latest?.id) add(current!, Infinity);
293
- for (const entry of anchors) if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id)! < boundary) add(entry, length);
302
+ for (const entry of anchors) if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id)! < boundary) add(entry, entry.id === firstUser?.id ? firstTurnCap : length);
294
303
  const omissions: TranscriptRecord[] = [];
295
304
  for (const role of ["user", "assistant", "toolResult"] as const) {
296
305
  const list = units[role], prefix = prefixes[role];
@@ -406,7 +415,19 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
406
415
  return row?.message.role === "user" && isTextOnly(row.message.content);
407
416
  }));
408
417
  const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
409
- const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
418
+ // The tool round the tail boundary passed (the one crossing the tail size) rides in the closing section, so the tail is not left far
419
+ // below its size. It is paid from the summary, up to what the native tail leaves of that size, and is reserved before the dialogue fills.
420
+ let crossingRound: TranscriptRecord | undefined;
421
+ const briefRoom = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
422
+ if (boundary === preferredBoundary && (preferredBoundary > originalBoundary || budgetCut) && boundary < entries.length) {
423
+ const crossing = entries.slice(0, boundary).findLastIndex(entry => !(entry.type === "message" && entry.message.role === "toolResult"));
424
+ const tail = crossing < 0 ? 0 : carriedTailTokens(Math.max(nativeAt(originalBoundary), nativeAt(crossing))) - nativeAt(boundary);
425
+ // Like the working set, at most WORKING_SET_SHARE of what the summary may spend beyond its protected rows: the dialogue keeps the rest.
426
+ const size = Math.min(tail, Math.floor(WORKING_SET_SHARE * briefRoom / 4));
427
+ if (size > 0) crossingRound = crossingRoundRecord(entries, boundary, indices, resolvable, size);
428
+ }
429
+ const crossingCost = crossingRound ? lineCost([crossingRound]) : 0;
430
+ const maxBriefChars = briefRoom;
410
431
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
411
432
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position]!)),
412
433
  ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
@@ -547,7 +568,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
547
568
  for (const record of candidates) {
548
569
  if ((counts.get(record.title!) ?? 0) === 4) continue;
549
570
  const extra = lineCost([record]);
550
- if (keptResultCost + extra > keptResultCap || price(offer.summary.length + keptResultCost + extra, boundary) > target) continue;
571
+ if (keptResultCost + extra > keptResultCap || price(offer.summary.length + crossingCost + keptResultCost + extra, boundary) > target) continue;
551
572
  keptResults.push(record); keptResultCost += extra;
552
573
  counts.set(record.title!, (counts.get(record.title!) ?? 0) + 1);
553
574
  }
@@ -563,7 +584,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
563
584
  for (const item of shownFiles) item.definitions = observations.get(item.path);
564
585
  const outputs = new Set<(typeof lists.actions)[number]>(), definitions = new Set<(typeof lists.files)[number]>();
565
586
  let observationCost = 0;
566
- const fitsObservation = (extra: number) => price(offer.summary.length + observationCost + extra, boundary) <= target;
587
+ const fitsObservation = (extra: number) => price(offer.summary.length + crossingCost + observationCost + extra, boundary) <= target;
567
588
  // Each kind gives way as whole items, oldest first; an oversized newest
568
589
  // item cannot promote an older one. Pointer lines need no extra omission.
569
590
  for (const item of shownActions) {
@@ -586,7 +607,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
586
607
  let thinkingCost = 0;
587
608
  for (const record of thinkingRecords(entries.slice(0, boundary), indices, openingLength)) {
588
609
  const extra = lineCost([record]);
589
- if (price(offer.summary.length + thinkingCost + extra, boundary) > target) break;
610
+ if (price(offer.summary.length + crossingCost + thinkingCost + extra, boundary) > target) break;
590
611
  thinking.push(record); thinkingCost += extra;
591
612
  }
592
613
  if (thinking.length) offer = assemble(compiled.text, boundary);
@@ -654,6 +675,11 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
654
675
  }
655
676
  if (boundary !== compiledBoundary) offer = assemble(compiled.text, boundary);
656
677
  }
678
+ // Still the preferred boundary (leftover room did not take the round into the native tail): the round rides in the summary instead.
679
+ if (crossingRound && boundary === preferredBoundary && price(offer.summary.length + crossingCost, boundary) <= target) {
680
+ keptResults.unshift(crossingRound);
681
+ offer = assemble(compiled.text, boundary);
682
+ }
657
683
  const projection = preview(offer.summary, boundary);
658
684
  assertNativeToolRounds(projection);
659
685
  const after = measure(projection);