pi-tuck 1.6.0 → 1.8.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,30 @@
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.8.0]
7
+
8
+ ### Changed
9
+
10
+ - Working files: at a trim, the files the agent has read more than once are carried whole, verbatim, after the summary's closing words,
11
+ most reads first, then the most recent. A file is carried only when its last read covered the whole file and the file on disk still holds
12
+ exactly that text, so a change by any means (an edit, a shell command, a generator) keeps it out. They are paid for from the summary
13
+ (at most two thirds of it beyond the protected prompts), never from the kept recent messages. The "re-read a file before editing it"
14
+ rule no longer applies to carried files; it stays for every other file.
15
+ - Thrash-adaptive trigger: when a session's trims keep dropping files the agent then reads again unchanged within three replies (half a
16
+ re-read or more per trim), the trim point moves to native Pi's line, the larger of the band and `keepRecentTokens`, capped so the next
17
+ reply keeps its room (at least 3,584 tokens, or 1.7.0's raised room after a length stop). Trims still cut to the band. Sessions without
18
+ such re-reads, an explicit `cutAt`, or a host reserve keep 1.7.0's trim point. Admission is unchanged.
19
+
20
+ ## [1.7.0]
21
+
22
+ ### Changed
23
+
24
+ - Reply room after a length stop: once a reply on the current branch stops at its length limit, pi-tuck trims so the next request leaves
25
+ twice that reply's output for the reply (at most the model's `maxTokens`, and at most half the window), by Pi's own clamp math. With no
26
+ length stop the trim point is unchanged. Admission is unchanged: the raise never refuses a request Pi would send.
27
+ - A reply that used the model's whole `maxTokens` while still thinking gets its own notice: it names the model, the cap and `models.json`,
28
+ and says a lower thinking level or a task that writes to files as it goes usually helps more than a bigger cap.
29
+
6
30
  ## [1.6.0]
7
31
 
8
32
  ### Added
package/README.md CHANGED
@@ -12,12 +12,14 @@ 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.6.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.6.0` or `pi install git:github.com/galyavin/pi-tuck@v1.6.0`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.8.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.8.0` or `pi install git:github.com/galyavin/pi-tuck@v1.8.0`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
19
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 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
+ 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
+
21
23
  When pi-tuck is active, `tuck_recall` becomes available after a cut on the current branch. Use a keyword query to locate a passage.
22
24
 
23
25
  ```json
@@ -71,7 +73,7 @@ Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by
71
73
 
72
74
  ## Output exhaustion and small windows
73
75
 
74
- - Pi-tuck preserves thinking-only stops in session history. At the model's full output allowance, it reports exhaustion if the reply remains unfinished. Below that allowance, it retries once, re-armed as Pi's overflow recovery is.
76
+ - Pi-tuck preserves thinking-only stops in session history. At the model's full output allowance, it reports exhaustion if the reply remains unfinished. Below that allowance, it retries once, re-armed as Pi's overflow recovery is. After any length stop on the branch, pi-tuck trims so the next reply gets twice that stop's output (at most `maxTokens` and half the window). A stop at the full `maxTokens` while still thinking names the setting and `models.json`; a lower thinking level usually helps more than a bigger cap.
75
77
  - Pi-tuck uses the context window declared in Pi's model configuration. A length stop alone does not establish a smaller window. If the server has a smaller effective limit, set that limit in Pi's model configuration.
76
78
  - Pi's compaction reserve sets the cut target. For larger requests, pi-tuck estimates reply needs from observed output on the current branch for the active model, bounded by the reserve and model output limit. A cut above the room aims to leave 3,584 reply tokens within those bounds; where no cut can, the request goes out as before. If cuts cannot leave enough room for the protected prompt and a reply, try a shorter prompt, fewer tools, or a larger window. Pi-tuck's checks use estimates. Pi handles recognized provider overflows, and silent truncation can go undetected.
77
79
 
@@ -125,11 +125,13 @@ export type Gate = {
125
125
  kind: "plan";
126
126
  opportunistic: boolean;
127
127
  };
128
+ /** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. */
128
129
  export declare function gateCut(input: {
129
130
  total: number;
130
131
  mandatory: number;
131
132
  room: number;
132
133
  band: number;
134
+ trigger?: number;
133
135
  fits: CutInput["fits"];
134
136
  }): Gate;
135
137
  /** Whether and how to cut at one boundary: the only decision procedure both triggers use. */
@@ -105,9 +105,10 @@ export function chooseCut(input) {
105
105
  return { kind: "fault", capacity: !fits(chosen.after + mandatory, room), message: unreduced };
106
106
  return { kind: "cut", target, plan: chosen };
107
107
  }
108
+ /** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. */
108
109
  export function gateCut(input) {
109
110
  const { total, mandatory, room, band, fits } = input;
110
- if (fits(total, band))
111
+ if (fits(total, Math.max(band, input.trigger ?? band)))
111
112
  return { kind: "none" };
112
113
  const inBand = fits(total, room);
113
114
  if (!fits(mandatory, room))
@@ -1 +1 @@
1
- export declare const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
1
+ export declare const BUILD_ID = "380741e47dc6a4378eeb32390a184eb747a610ac7b9614d97e86c1dbd3539cc8";
@@ -1 +1 @@
1
- export const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
1
+ export const BUILD_ID = "380741e47dc6a4378eeb32390a184eb747a610ac7b9614d97e86c1dbd3539cc8";
@@ -8,6 +8,8 @@ export declare const refusalNotice: (message: string, factor: number) => string;
8
8
  /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
9
9
  export declare const overflowNotice: (contextWindow: number, bound: number, learned: boolean) => string;
10
10
  /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
11
+ /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
12
+ export declare const capStopNotice: (model: string, maxTokens: number, file: string) => string;
11
13
  export declare const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
12
14
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
13
15
  export declare const CALIBRATION_CEILING = 1.5;
@@ -1,22 +1,25 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run } from "./run.js";
3
- import { CUT_REPLY_FLOOR, requestReplyFloor, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
3
+ import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
5
  import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
6
6
  import { createHash } from "node:crypto";
7
7
  import { readFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
8
10
  import { exportSource } from "./source-export.js";
9
11
  import { isDeepStrictEqual } from "node:util";
10
12
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
11
13
  import { projectedMessages } from "./omissions.js";
12
14
  import { applyClips, clipBudgets, clipFor } from "./clip.js";
13
- import { DEFAULT_CUT_AT, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
15
+ import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
14
16
  import { getCurrentSystemMessage, isContextOverflow, normalizeContext } from "@earendil-works/pi-ai";
15
- import { calculateContextTokens, convertToLlm, estimateTokens, shouldCompact, SettingsManager } from "@earendil-works/pi-coding-agent";
17
+ import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager } from "@earendil-works/pi-coding-agent";
16
18
  import { Type } from "typebox";
17
19
  import { Check } from "typebox/value";
18
20
  import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
19
21
  import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
22
+ import { thrashing } from "./thrash.js";
20
23
  import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
21
24
  import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
22
25
  import { notify } from "./notify.js";
@@ -59,6 +62,20 @@ export const refusalNotice = (message, factor) => message + "; shorten the input
59
62
  export const overflowNotice = (contextWindow, bound, learned) => `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
60
63
  (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
61
64
  /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
65
+ /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
66
+ export const capStopNotice = (model, maxTokens, file) => `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
67
+ `The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
68
+ "The unfinished response is saved in the session.";
69
+ /** Pi's models.json, shown with ~ for the home folder. */
70
+ function modelsPath() {
71
+ try {
72
+ const path = join(getAgentDir(), "models.json"), home = homedir();
73
+ return path.startsWith(home + "/") ? "~" + path.slice(home.length) : path;
74
+ }
75
+ catch {
76
+ return "~/.pi/agent/models.json";
77
+ }
78
+ }
62
79
  export const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
63
80
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
64
81
  export const CALIBRATION_CEILING = 1.5;
@@ -331,18 +348,22 @@ export async function installCompaction(pi, options = {}) {
331
348
  lengthStop = event.message.stopReason === "length" ? {
332
349
  kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
333
350
  cacheMiss: event.message.errorMessage === CONTINUATION_CACHE_MISS,
351
+ cap: ctx.model && ctx.model.maxTokens > 0 && event.message.usage?.output === ctx.model.maxTokens
352
+ ? { model: `${ctx.model.provider}/${ctx.model.id}`, maxTokens: ctx.model.maxTokens } : undefined,
334
353
  } : undefined;
335
354
  });
336
355
  pi.on("agent_settled", (_event, ctx) => {
337
356
  try {
338
357
  if (standDown(ctx) || !lengthStop || !active())
339
358
  return;
340
- const { kind, cacheMiss } = lengthStop;
341
- const message = kind === "thinking"
342
- ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
343
- : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
359
+ const { kind, cacheMiss, cap } = lengthStop;
360
+ // A thinking-only stop exactly at the configured cap: the cap itself, not the context, ended the reply.
361
+ const message = kind === "thinking" && cap ? capStopNotice(cap.model, cap.maxTokens, modelsPath())
362
+ : kind === "thinking"
363
+ ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
364
+ : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
344
365
  lengthStop = undefined;
345
- notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + INCIDENT_HINT, "warning");
366
+ notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + (cap && kind === "thinking" ? "" : INCIDENT_HINT), "warning");
346
367
  }
347
368
  finally {
348
369
  resetRun();
@@ -370,20 +391,41 @@ export async function installCompaction(pi, options = {}) {
370
391
  // Room still owns every existing cut/clip attempt. Only final capacity admission uses the hard line.
371
392
  let floorMinimum = 1;
372
393
  const limits = (ctx) => {
373
- const response = responseReserve(ctx), room = inputRoom(response, ctx);
374
- const floor = options.requestReserve || !ctx.model ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model, floorMinimum);
375
- const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
394
+ const reserve = responseReserve(ctx);
395
+ const floor = options.requestReserve || !ctx.model ? reserve : requestReplyFloor(ctx.sessionManager.getBranch(), reserve, ctx.model, floorMinimum);
396
+ // After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: Pi gives a request
397
+ // min(maxTokens, window - input - margin), so the room is window - margin - raised. Admission (floor, hard line) stays as without a
398
+ // stop: the raise asks cuts for more reply room, it never refuses a request Pi would send. No stop: exactly the reserve, as before.
399
+ const raised = options.requestReserve || !ctx.model ? undefined : stoppedReplyRoom(ctx.sessionManager.getBranch(), ctx.model, contextWindow(ctx), piMargin);
400
+ const response = raised === undefined ? reserve : Math.max(reserve, raised + piMargin), room = inputRoom(response, ctx);
401
+ const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
376
402
  return { response, room, hardLine, replyFloor: floor };
377
403
  };
378
404
  const preservePrefix = (ctx) => ctx.model !== undefined &&
379
405
  options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
380
406
  const decisionBand = (ctx, room) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
407
+ // Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
408
+ // to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
409
+ // Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
410
+ // room: window - Pi's margin - the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
411
+ // sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
412
+ const triggerLine = (ctx, room) => {
413
+ if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
414
+ return undefined;
415
+ const branch = ctx.sessionManager.getBranch();
416
+ if (!thrashing(branch))
417
+ return undefined;
418
+ const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
419
+ const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
420
+ const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
421
+ return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
422
+ };
381
423
  /** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
382
424
  const cutPoint = (ctx) => {
383
425
  if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
384
426
  return undefined;
385
427
  try {
386
- const band = decisionBand(ctx, limits(ctx).room);
428
+ const { room } = limits(ctx), band = Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0);
387
429
  return band > 0 ? band : undefined;
388
430
  }
389
431
  catch {
@@ -623,7 +665,7 @@ export async function installCompaction(pi, options = {}) {
623
665
  // cancel (Pi reports it as aborted), never a failure.
624
666
  let thresholdOpportunistic = false;
625
667
  if (event.reason === "threshold") {
626
- const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
668
+ const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
627
669
  if (gate.kind !== "plan")
628
670
  return { cancel: true };
629
671
  thresholdOpportunistic = gate.opportunistic;
@@ -796,7 +838,7 @@ export async function installCompaction(pi, options = {}) {
796
838
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
797
839
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
798
840
  // help: leave it to the complete-context guard, which fails closed.
799
- const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
841
+ const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
800
842
  if (gate.kind === "none")
801
843
  return;
802
844
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
@@ -951,7 +993,7 @@ export async function installCompaction(pi, options = {}) {
951
993
  floorKept = undefined;
952
994
  const before = measure(saved);
953
995
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan", opportunistic: false } :
954
- gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
996
+ gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, fits: (tokens, limit) => fits(tokens, limit, ctx) });
955
997
  if (gate.kind !== "plan")
956
998
  return gate;
957
999
  return chooseCut({
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
3
+ export declare const DIAGNOSTIC_BUILD = "380741e47dc6a4378eeb32390a184eb747a610ac7b9614d97e86c1dbd3539cc8";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -1,4 +1,4 @@
1
1
  import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
2
2
  import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
3
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
4
- export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
4
+ export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, exclude?: ReadonlySet<string>): TranscriptRecord[];
@@ -3,7 +3,7 @@ import { pathKey } from "./path-key.js";
3
3
  import { isTextOnly, textOf } from "./tuck/core/content.js";
4
4
  import { extractPath } from "./tuck/core/tool-args.js";
5
5
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
6
- export function keptReadCandidates(entries, indices, resolvable) {
6
+ export function keptReadCandidates(entries, indices, resolvable, exclude = new Set()) {
7
7
  const cwd = entries.find((entry) => entry.type === "session")?.cwd;
8
8
  const reads = new Map(), mutations = new Map();
9
9
  let allMutated = -1;
@@ -54,7 +54,7 @@ export function keptReadCandidates(entries, indices, resolvable) {
54
54
  if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
55
55
  continue;
56
56
  const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
57
- if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order)
57
+ if (!read || seen.has(read.key) || exclude.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order)
58
58
  continue;
59
59
  const text = textOf(entry.message.content);
60
60
  if (!text.length || sourceIndex === undefined || !resolvable(entry))
@@ -29,6 +29,10 @@ export declare const CUT_REPLY_FLOOR = 3584;
29
29
  /** Ordinary reply demand is bounded by the reserve and model output limit.
30
30
  * Recovery compares its candidate against the interrupted attempt separately. */
31
31
  export declare function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, model: ReplyModel, minimum?: number): number;
32
+ /** Reply room after a length stop on this branch (1.7.0): twice the largest stopped output of this model, bounded by its maxTokens instead of
33
+ * the reserve, and by half of what Pi can give a request (so a small window keeps room for the conversation). Undefined with no length stop:
34
+ * then nothing changes. Read from the branch only; nothing carries across sessions. */
35
+ export declare function stoppedReplyRoom(branch: readonly SessionEntry[], model: ReplyModel, window: number, margin: number): number | undefined;
32
36
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
33
37
  export declare function carriesPrompt(messages: Messages, prompt: string, role?: 'user' | 'custom'): boolean;
34
38
  export {};
@@ -83,6 +83,26 @@ export function requestReplyFloor(branch, reserve, model, minimum = 1) {
83
83
  }
84
84
  return Math.min(limit, Math.ceil(largest));
85
85
  }
86
+ /** Reply room after a length stop on this branch (1.7.0): twice the largest stopped output of this model, bounded by its maxTokens instead of
87
+ * the reserve, and by half of what Pi can give a request (so a small window keeps room for the conversation). Undefined with no length stop:
88
+ * then nothing changes. Read from the branch only; nothing carries across sessions. */
89
+ export function stoppedReplyRoom(branch, model, window, margin) {
90
+ let largest = 0;
91
+ for (const entry of branch) {
92
+ if (entry.type !== 'message' || entry.message.role !== 'assistant')
93
+ continue;
94
+ const message = entry.message;
95
+ if (message.stopReason !== 'length' || message.model !== model.id || message.provider !== model.provider || message.api !== model.api)
96
+ continue;
97
+ const output = message.usage?.output;
98
+ if (typeof output === 'number' && Number.isFinite(output) && output > largest)
99
+ largest = output;
100
+ }
101
+ if (largest <= 0)
102
+ return undefined;
103
+ const raised = Math.ceil(2 * largest), cap = model.maxTokens > 0 ? model.maxTokens : raised;
104
+ return Math.max(1, Math.min(raised, cap, Math.floor((window - margin) / 2)));
105
+ }
86
106
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
87
107
  export function carriesPrompt(messages, prompt, role = 'user') {
88
108
  if (!prompt.length)
@@ -0,0 +1,12 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ /** A re-read counts when it is issued within this many replies after a cut. */
3
+ export declare const THRASH_WINDOW_REPLIES = 3;
4
+ /** Re-reads per cut at which a session is thrashing. */
5
+ export declare const THRASH_BAR = 0.5;
6
+ /**
7
+ * Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
8
+ * limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
9
+ * within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
10
+ * such re-read, it never does. Deterministic: it reads only the recorded branch.
11
+ */
12
+ export declare function thrashing(branch: readonly SessionEntry[]): boolean;
@@ -0,0 +1,52 @@
1
+ import { isDiscardedResponse } from "./protocol.js";
2
+ import { pathKey } from "./path-key.js";
3
+ import { isTextOnly, textOf } from "./tuck/core/content.js";
4
+ import { extractPath } from "./tuck/core/tool-args.js";
5
+ /** A re-read counts when it is issued within this many replies after a cut. */
6
+ export const THRASH_WINDOW_REPLIES = 3;
7
+ /** Re-reads per cut at which a session is thrashing. */
8
+ export const THRASH_BAR = 0.5;
9
+ /**
10
+ * Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
11
+ * limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
12
+ * within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
13
+ * such re-read, it never does. Deterministic: it reads only the recorded branch.
14
+ */
15
+ export function thrashing(branch) {
16
+ let cuts = 0, replies = 0, rereads = 0;
17
+ const pending = new Map(), last = new Map();
18
+ for (const entry of branch) {
19
+ if (entry.type === "compaction") {
20
+ cuts++;
21
+ replies = 0;
22
+ continue;
23
+ }
24
+ if (entry.type !== "message")
25
+ continue;
26
+ const message = entry.message;
27
+ if (message.role === "assistant") {
28
+ if (isDiscardedResponse(message))
29
+ continue;
30
+ replies++;
31
+ for (const block of message.content) {
32
+ if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object")
33
+ continue;
34
+ const args = block.arguments, path = extractPath(args);
35
+ if (!path)
36
+ continue;
37
+ pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: cuts, soon: cuts > 0 && replies <= THRASH_WINDOW_REPLIES });
38
+ }
39
+ }
40
+ else if (message.role === "toolResult") {
41
+ const read = pending.get(message.toolCallId);
42
+ if (!read || message.isError || !isTextOnly(message.content))
43
+ continue;
44
+ pending.delete(message.toolCallId);
45
+ const text = textOf(message.content), earlier = last.get(read.key);
46
+ if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text)
47
+ rereads++;
48
+ last.set(read.key, { cut: read.cut, text });
49
+ }
50
+ }
51
+ return cuts > 0 && rereads / cuts >= THRASH_BAR;
52
+ }
@@ -2,3 +2,17 @@
2
2
  export declare const CLOSING_INSTRUCTION: string;
3
3
  /** Parsing never depends on this wording (transcript.ts splitSummary). */
4
4
  export declare const DIALOGUE_SUFFIX: string;
5
+ /** The closing words when working files follow: the re-read rule stays for every other file. */
6
+ export declare const WORKING_FILES_INSTRUCTION: string;
7
+ /** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
8
+ * exactly in an edit). The closing section is kept byte for byte by every parser (transcript.ts splitSummary), so raw text is safe there. */
9
+ export declare const WORKING_FILES_HEADER = "\n\nWorking files: each is the whole file, identical to the file on disk when this summary was made. Edit from these copies.";
10
+ export declare const workingFileBlock: (file: {
11
+ path: string;
12
+ text: string;
13
+ }) => string;
14
+ /** The closing section: the dialogue suffix alone, or, with working files, its working-files form followed by each file. */
15
+ export declare const closingSuffix: (files: readonly {
16
+ path: string;
17
+ text: string;
18
+ }[]) => string;
@@ -4,3 +4,13 @@ export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files
4
4
  "Files created by commands are not listed: Before re-running a command listed above, read its output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
5
5
  /** Parsing never depends on this wording (transcript.ts splitSummary). */
6
6
  export const DIALOGUE_SUFFIX = CLOSING_SEPARATOR + CLOSING_INSTRUCTION;
7
+ const REREAD = "Re-read a file before editing it or importing from it.";
8
+ /** The closing words when working files follow: the re-read rule stays for every other file. */
9
+ export const WORKING_FILES_INSTRUCTION = CLOSING_INSTRUCTION.replace(REREAD, "Re-read a file before editing it or importing from it, unless it is one of the working files below.");
10
+ /** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
11
+ * exactly in an edit). The closing section is kept byte for byte by every parser (transcript.ts splitSummary), so raw text is safe there. */
12
+ export const WORKING_FILES_HEADER = "\n\nWorking files: each is the whole file, identical to the file on disk when this summary was made. Edit from these copies.";
13
+ export const workingFileBlock = (file) => `\n<file path=${JSON.stringify(file.path)}>\n${file.text}\n</file>`;
14
+ /** The closing section: the dialogue suffix alone, or, with working files, its working-files form followed by each file. */
15
+ export const closingSuffix = (files) => files.length
16
+ ? CLOSING_SEPARATOR + WORKING_FILES_INSTRUCTION + WORKING_FILES_HEADER + files.map(workingFileBlock).join("") : DIALOGUE_SUFFIX;
@@ -32,6 +32,8 @@ export interface RecallContinuation {
32
32
  }
33
33
  /** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
34
34
  export declare const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
35
+ /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
36
+ export declare const WORKING_SET_SHARE: number;
35
37
  /** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
36
38
  export interface Tuck {
37
39
  buildOwnCut(entries: SessionEntry[], keep: number): Cut;
package/dist/src/tuck.js CHANGED
@@ -2,12 +2,13 @@ import { resolveSourceTime } from "./tuck/core/source-time.js";
2
2
  import { orderByOriginalSource } from "./tuck/core/source-order.js";
3
3
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
4
4
  import { parseRecords, serializeTranscript, serializeRecord, splitSummary, TRANSCRIPT_HEADER } from "./tuck/core/transcript.js";
5
- import { DIALOGUE_SUFFIX } from "./tuck/core/format.js";
5
+ import { closingSuffix, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format.js";
6
6
  import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.js";
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
10
  import { keptReadCandidates } from "./kept-reads.js";
11
+ import { workingSetCandidates } from "./working-set.js";
11
12
  import { keptSearchCandidates } from "./kept-searches.js";
12
13
  import { fileObservations, thinkingRecords } from "./content-observations.js";
13
14
  import { pathKey } from "./path-key.js";
@@ -15,6 +16,8 @@ import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
15
16
  import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
16
17
  /** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
17
18
  export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
19
+ /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
20
+ export const WORKING_SET_SHARE = 2 / 3;
18
21
  import { buildOwnCut, applyTailBudget, MAX_TAIL_TOKENS, OVERSIZED_TAIL_FACTOR } from "./tuck/cut.js";
19
22
  import { calibrateCharsPerToken, estimateSourceMessageChars } from "./tuck/core/token-estimate.js";
20
23
  import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
@@ -225,8 +228,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
225
228
  const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
226
229
  const summaryTokens = (characters) => Math.ceil((characters + wrapperCharacters) / 4);
227
230
  const lineCost = (records) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
228
- const frameLength = (cost, count) => TRANSCRIPT_HEADER.length + DIALOGUE_SUFFIX.length + cost + (count ? 0 : 1);
229
- const render = (records) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + DIALOGUE_SUFFIX;
231
+ // Working files carried raw in the closing section. Chosen once the boundary is known; until then the suffix is the plain one.
232
+ let carried = [], suffix = DIALOGUE_SUFFIX;
233
+ const frameLength = (cost, count) => TRANSCRIPT_HEADER.length + suffix.length + cost + (count ? 0 : 1);
234
+ const render = (records) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + suffix;
230
235
  const units = { user: [], assistant: [], toolResult: [] };
231
236
  for (const row of rows) {
232
237
  if (row.index === undefined)
@@ -382,6 +387,23 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
382
387
  const lists = listsAt(boundary);
383
388
  const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
384
389
  const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
390
+ // The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
391
+ // WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
392
+ const resolvable = (entry) => readable(entry) !== undefined;
393
+ const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
394
+ if (workingSet.files.length) {
395
+ const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
396
+ let cost = WORKING_FILES_INSTRUCTION.length - CLOSING_INSTRUCTION.length + WORKING_FILES_HEADER.length;
397
+ for (const file of workingSet.files) {
398
+ const extra = workingFileBlock(file).length;
399
+ if (cost + extra > allowance)
400
+ continue;
401
+ carried.push(file);
402
+ cost += extra;
403
+ }
404
+ suffix = closingSuffix(carried);
405
+ }
406
+ const carriedKeys = new Set(carried.map(file => file.key));
385
407
  let ledger = lists.records;
386
408
  let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
387
409
  // List caps are existing ranking policy; only the carried target is a
@@ -402,7 +424,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
402
424
  return row?.message.role === "user" && isTextOnly(row.message.content);
403
425
  }));
404
426
  const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
405
- const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
427
+ const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
406
428
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
407
429
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position])),
408
430
  ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
@@ -473,10 +495,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
473
495
  let keptResultCost = 0;
474
496
  const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
475
497
  const counts = new Map();
476
- const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry) => readable(entry) !== undefined;
498
+ const prefix = [header, ...entries.slice(0, boundary)];
477
499
  // Reads and searches share the lead rank, newest result first, and one
478
500
  // allowance. Keep L2's independent four-item caps and whole-item skips.
479
- const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
501
+ const candidates = [...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
480
502
  .sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
481
503
  for (const record of candidates) {
482
504
  if ((counts.get(record.title) ?? 0) === 4)
@@ -492,10 +514,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
492
514
  offer = assemble(compiled.text, boundary);
493
515
  const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
494
516
  const shownFiles = lists.files.slice(0, Math.min(listedKeep, MAX_LEDGER_LINES));
495
- const keptReadPaths = new Set(keptResults.filter(record => record.title === "Kept-read").map(record => {
496
- const heading = record.text.slice(0, record.text.indexOf("\n"));
497
- return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
498
- }));
517
+ const keptReadPaths = new Set([...carriedKeys, ...keptResults.filter(record => record.title === "Kept-read").map(record => {
518
+ const heading = record.text.slice(0, record.text.indexOf("\n"));
519
+ return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
520
+ })]);
499
521
  const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
500
522
  const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
501
523
  for (const item of shownFiles)
@@ -583,12 +605,12 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
583
605
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
584
606
  });
585
607
  const baseCost = lineCost(offer.records) + lineCost(ledger) + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
586
- const keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
608
+ const keptResultIndices = new Set([...keptResults.map(record => record.sourceIndex), ...carried.map(file => file.sourceIndex)]);
587
609
  const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
588
610
  const extensionPrice = (at) => {
589
- // Kept results already spend this extension's price. They stay in
590
- // the compacted prefix, so the native tail never repeats them.
591
- if (keptResults.length && at <= lastKeptResultPosition)
611
+ // Kept results and working files already spend this extension's
612
+ // price. They stay in the compacted prefix, so the native tail never repeats them.
613
+ if (keptResultIndices.size && at <= lastKeptResultPosition)
592
614
  return Infinity;
593
615
  let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
594
616
  let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
@@ -623,7 +645,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
623
645
  return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
624
646
  const mode = compiled.step === "whole" ? "dialogue" : "shrunk";
625
647
  return { compaction: { summary: offer.summary, firstKeptEntryId: entries[boundary]?.id ?? "", tokensBefore: input.tokensBefore,
626
- details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode } }, after, mode };
648
+ details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode,
649
+ ...(workingSet.files.length || workingSet.rejected ? { workingSet: { carried: carried.map(file => file.path), offered: workingSet.files.length, rejected: workingSet.rejected } } : {}) } }, after, mode };
627
650
  }
628
651
  /** Numeric references use the original session index, then intersect with readable current-branch entries. */
629
652
  export function tuckRecall(tuck, entries, branch, input, policy = {}) {
@@ -0,0 +1,26 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ /** Reads a file's current text, or undefined when it cannot be read. Never throws. */
3
+ export type FileReader = (absolutePath: string) => string | undefined;
4
+ /** Test and offline-replay seam: where carried files are checked. Undefined restores the disk. */
5
+ export declare const setWorkingFileReader: (next?: FileReader) => void;
6
+ /** Where Pi's read tool reads a recorded path: an "@" prefix dropped, "~" expanded, relative to the session's folder. */
7
+ export declare const readPath: (path: string, cwd: string) => string;
8
+ export interface WorkingFile {
9
+ path: string;
10
+ key: string;
11
+ reads: number;
12
+ sourceIndex: number;
13
+ position: number;
14
+ text: string;
15
+ }
16
+ /**
17
+ * The files the agent has read more than once, most reads first, then most recent last read. A file is carried only when its last read
18
+ * covered the whole file (no offset or limit) and the file on disk holds exactly that read's text now. Pi's read tool returns a whole small
19
+ * file verbatim, so equality proves both that the read was complete and that nothing (an edit, a write, a shell command, a generator) has
20
+ * changed the file since. `rejected` counts the files whose last read was whole but whose disk text differs or cannot be read.
21
+ * Only last reads inside the compacted prefix (before `boundary`) are offered: a later read is still in the native tail.
22
+ */
23
+ export declare function workingSetCandidates(entries: readonly SessionEntry[], boundary: number, indices: ReadonlyMap<string, number>, cwd: string, resolvable: (entry: SessionEntry) => boolean): {
24
+ files: WorkingFile[];
25
+ rejected: number;
26
+ };
@@ -0,0 +1,80 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, resolve } from "node:path";
4
+ import { pathKey } from "./path-key.js";
5
+ import { isTextOnly, textOf } from "./tuck/core/content.js";
6
+ import { extractPath } from "./tuck/core/tool-args.js";
7
+ /** Pi's read tool returns at most 50KB of a file's text, so a larger file can never equal a recorded whole read. */
8
+ const MAX_FILE_BYTES = 64 * 1024;
9
+ const diskReader = path => {
10
+ try {
11
+ return statSync(path).size > MAX_FILE_BYTES ? undefined : readFileSync(path, "utf8");
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ };
17
+ let reader = diskReader;
18
+ /** Test and offline-replay seam: where carried files are checked. Undefined restores the disk. */
19
+ export const setWorkingFileReader = (next) => { reader = next ?? diskReader; };
20
+ /** Where Pi's read tool reads a recorded path: an "@" prefix dropped, "~" expanded, relative to the session's folder. */
21
+ export const readPath = (path, cwd) => {
22
+ let name = path.startsWith("@") ? path.slice(1) : path;
23
+ if (name === "~")
24
+ name = homedir();
25
+ else if (name.startsWith("~/"))
26
+ name = homedir() + name.slice(1);
27
+ return isAbsolute(name) ? name : resolve(cwd, name);
28
+ };
29
+ /**
30
+ * The files the agent has read more than once, most reads first, then most recent last read. A file is carried only when its last read
31
+ * covered the whole file (no offset or limit) and the file on disk holds exactly that read's text now. Pi's read tool returns a whole small
32
+ * file verbatim, so equality proves both that the read was complete and that nothing (an edit, a write, a shell command, a generator) has
33
+ * changed the file since. `rejected` counts the files whose last read was whole but whose disk text differs or cannot be read.
34
+ * Only last reads inside the compacted prefix (before `boundary`) are offered: a later read is still in the native tail.
35
+ */
36
+ export function workingSetCandidates(entries, boundary, indices, cwd, resolvable) {
37
+ const calls = new Map(), last = new Map(), reads = new Map();
38
+ const results = new Map();
39
+ entries.forEach((entry, position) => {
40
+ if (entry.type !== "message")
41
+ return;
42
+ if (entry.message.role === "toolResult") {
43
+ results.set(entry.message.toolCallId, { entry, position });
44
+ return;
45
+ }
46
+ if (entry.message.role !== "assistant")
47
+ return;
48
+ for (const block of entry.message.content) {
49
+ if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object")
50
+ continue;
51
+ const args = block.arguments, path = extractPath(args);
52
+ if (!path || /[\r\n]/u.test(path))
53
+ continue;
54
+ const key = pathKey(path, cwd);
55
+ calls.set(block.id, { path, key, whole: !("offset" in args) && !("limit" in args) });
56
+ last.set(key, block.id);
57
+ reads.set(key, (reads.get(key) ?? 0) + 1);
58
+ }
59
+ });
60
+ const files = [];
61
+ let rejected = 0;
62
+ for (const [key, id] of last) {
63
+ const count = reads.get(key), call = calls.get(id), result = results.get(id);
64
+ if (count < 2 || !call.whole || !result || result.position >= boundary)
65
+ continue;
66
+ const { entry, position } = result;
67
+ if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
68
+ continue;
69
+ const text = textOf(entry.message.content), sourceIndex = indices.get(entry.id);
70
+ if (!text.length || sourceIndex === undefined || !resolvable(entry))
71
+ continue;
72
+ if (reader(readPath(call.path, cwd)) !== text) {
73
+ rejected++;
74
+ continue;
75
+ }
76
+ files.push({ path: call.path, key, reads: count, sourceIndex, position, text });
77
+ }
78
+ files.sort((a, b) => b.reads - a.reads || b.position - a.position);
79
+ return { files, rejected };
80
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.6.0",
3
+ "version": "1.8.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/budget.ts CHANGED
@@ -151,9 +151,10 @@ export function chooseCut<D extends object = {}>(input: CutInput<D> & { opportun
151
151
  }
152
152
  /** Rules 1 to 3: before any plan exists, does this request need a cut, and is a cut allowed to fail? */
153
153
  export type Gate = { kind: "none" } | { kind: "defer" } | { kind: "plan"; opportunistic: boolean };
154
- export function gateCut(input: { total: number; mandatory: number; room: number; band: number; fits: CutInput["fits"] }): Gate {
154
+ /** `trigger`, when above the band, moves only where a cut becomes due; the cut still plans to the band. */
155
+ export function gateCut(input: { total: number; mandatory: number; room: number; band: number; trigger?: number; fits: CutInput["fits"] }): Gate {
155
156
  const { total, mandatory, room, band, fits } = input;
156
- if (fits(total, band)) return { kind: "none" };
157
+ if (fits(total, Math.max(band, input.trigger ?? band))) return { kind: "none" };
157
158
  const inBand = fits(total, room);
158
159
  if (!fits(mandatory, room)) return { kind: "defer" };
159
160
  return { kind: "plan", opportunistic: inBand };
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
1
+ export const BUILD_ID = "380741e47dc6a4378eeb32390a184eb747a610ac7b9614d97e86c1dbd3539cc8";
package/src/compaction.ts CHANGED
@@ -1,25 +1,28 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run, type CutEntry } from "./run.js";
3
- import { CUT_REPLY_FLOOR, requestReplyFloor, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
3
+ import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
5
  import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry, type Receipt, type RecorderOptions } from "./diagnostics.js";
6
6
  import { createHash } from "node:crypto";
7
7
  import { readFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
8
10
  import { exportSource } from "./source-export.js";
9
11
  import { isDeepStrictEqual } from "node:util";
10
12
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
11
13
  import { projectedMessages } from "./omissions.js";
12
14
  import { applyClips, clipBudgets, clipFor, type Clip } from "./clip.js";
13
- import { DEFAULT_CUT_AT, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt,
15
+ import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt,
14
16
  type AgentMessage, type Decision, type Messages, type Plan, type Target } from "./budget.js";
15
17
  import { getCurrentSystemMessage, isContextOverflow, normalizeContext, type ImageContent, type ToolResultMessage } from "@earendil-works/pi-ai";
16
- import { calculateContextTokens, convertToLlm, estimateTokens, shouldCompact, SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
18
+ import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
17
19
  import { Type } from "typebox";
18
20
  import { Check } from "typebox/value";
19
21
  import type { RecallPolicy } from "./recall.js";
20
22
  import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
21
23
 
22
24
  import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
25
+ import { thrashing } from "./thrash.js";
23
26
  import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
24
27
  import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
25
28
  import { notify } from "./notify.js";
@@ -62,6 +65,18 @@ export const overflowNotice = (contextWindow: number, bound: number, learned: bo
62
65
  `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
63
66
  (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
64
67
  /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
68
+ /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
69
+ export const capStopNotice = (model: string, maxTokens: number, file: string) =>
70
+ `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
71
+ `The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
72
+ "The unfinished response is saved in the session.";
73
+ /** Pi's models.json, shown with ~ for the home folder. */
74
+ function modelsPath(): string {
75
+ try {
76
+ const path = join(getAgentDir(), "models.json"), home = homedir();
77
+ return path.startsWith(home + "/") ? "~" + path.slice(home.length) : path;
78
+ } catch { return "~/.pi/agent/models.json"; }
79
+ }
65
80
  export const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
66
81
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
67
82
  export const CALIBRATION_CEILING = 1.5;
@@ -297,7 +312,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
297
312
  });
298
313
  // The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
299
314
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
300
- let lengthStop: { kind: "thinking" | "output"; cacheMiss: boolean } | undefined;
315
+ let lengthStop: { kind: "thinking" | "output"; cacheMiss: boolean; cap?: { model: string; maxTokens: number } } | undefined;
301
316
  pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= new Run("starting"); if (!failure()) run.transition("admitted"); lengthStop = undefined; calibration.pending = undefined; });
302
317
  // Pi's overflow-recovery rule: a new user message or a good reply grants another recovery.
303
318
  const rearmLengthRetry = (ctx: ExtensionContext) => {
@@ -310,17 +325,21 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
310
325
  lengthStop = event.message.stopReason === "length" ? {
311
326
  kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
312
327
  cacheMiss: event.message.errorMessage === CONTINUATION_CACHE_MISS,
328
+ cap: ctx.model && ctx.model.maxTokens > 0 && event.message.usage?.output === ctx.model.maxTokens
329
+ ? { model: `${ctx.model.provider}/${ctx.model.id}`, maxTokens: ctx.model.maxTokens } : undefined,
313
330
  } : undefined;
314
331
  });
315
332
  pi.on("agent_settled", (_event, ctx) => {
316
333
  try {
317
334
  if (standDown(ctx) || !lengthStop || !active()) return;
318
- const { kind, cacheMiss } = lengthStop;
319
- const message = kind === "thinking"
335
+ const { kind, cacheMiss, cap } = lengthStop;
336
+ // A thinking-only stop exactly at the configured cap: the cap itself, not the context, ended the reply.
337
+ const message = kind === "thinking" && cap ? capStopNotice(cap.model, cap.maxTokens, modelsPath())
338
+ : kind === "thinking"
320
339
  ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
321
340
  : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
322
341
  lengthStop = undefined;
323
- notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + INCIDENT_HINT, "warning");
342
+ notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + (cap && kind === "thinking" ? "" : INCIDENT_HINT), "warning");
324
343
  } finally { resetRun(); }
325
344
  });
326
345
  const active = () => options.active?.() ?? true;
@@ -345,18 +364,37 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
345
364
  // Room still owns every existing cut/clip attempt. Only final capacity admission uses the hard line.
346
365
  let floorMinimum = 1;
347
366
  const limits = (ctx: ExtensionContext) => {
348
- const response = responseReserve(ctx), room = inputRoom(response, ctx);
349
- const floor = options.requestReserve || !ctx.model ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model, floorMinimum);
350
- const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
367
+ const reserve = responseReserve(ctx);
368
+ const floor = options.requestReserve || !ctx.model ? reserve : requestReplyFloor(ctx.sessionManager.getBranch(), reserve, ctx.model, floorMinimum);
369
+ // After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: Pi gives a request
370
+ // min(maxTokens, window - input - margin), so the room is window - margin - raised. Admission (floor, hard line) stays as without a
371
+ // stop: the raise asks cuts for more reply room, it never refuses a request Pi would send. No stop: exactly the reserve, as before.
372
+ const raised = options.requestReserve || !ctx.model ? undefined : stoppedReplyRoom(ctx.sessionManager.getBranch(), ctx.model, contextWindow(ctx), piMargin);
373
+ const response = raised === undefined ? reserve : Math.max(reserve, raised + piMargin), room = inputRoom(response, ctx);
374
+ const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
351
375
  return { response, room, hardLine, replyFloor: floor };
352
376
  };
353
377
  const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
354
378
  options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
355
379
  const decisionBand = (ctx: ExtensionContext, room: number) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
380
+ // Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
381
+ // to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
382
+ // Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
383
+ // room: window - Pi's margin - the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
384
+ // sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
385
+ const triggerLine = (ctx: ExtensionContext, room: number): number | undefined => {
386
+ if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
387
+ const branch = ctx.sessionManager.getBranch();
388
+ if (!thrashing(branch)) return undefined;
389
+ const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
390
+ const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
391
+ const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
392
+ return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
393
+ };
356
394
  /** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
357
395
  const cutPoint = (ctx: ExtensionContext): number | undefined => {
358
396
  if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
359
- try { const band = decisionBand(ctx, limits(ctx).room); return band > 0 ? band : undefined; } catch { return undefined; }
397
+ try { const { room } = limits(ctx), band = Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0); return band > 0 ? band : undefined; } catch { return undefined; }
360
398
  };
361
399
  const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
362
400
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
@@ -557,7 +595,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
557
595
  // cancel (Pi reports it as aborted), never a failure.
558
596
  let thresholdOpportunistic = false;
559
597
  if (event.reason === "threshold") {
560
- const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
598
+ const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
561
599
  if (gate.kind !== "plan") return { cancel: true };
562
600
  thresholdOpportunistic = gate.opportunistic;
563
601
  }
@@ -708,7 +746,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
708
746
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
709
747
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
710
748
  // help: leave it to the complete-context guard, which fails closed.
711
- const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
749
+ const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), fits: (tokens, limit) => fits(tokens, limit, ctx) });
712
750
  if (gate.kind === "none") return;
713
751
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
714
752
  const decide = (targetRoom: number, targetBand: number, opportunistic: boolean) => chooseCut({
@@ -845,7 +883,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
845
883
  floorKept = undefined;
846
884
  const before = measure(saved);
847
885
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan" as const, opportunistic: false } :
848
- gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
886
+ gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, fits: (tokens, limit) => fits(tokens, limit, ctx) });
849
887
  if (gate.kind !== "plan") return gate;
850
888
  return chooseCut({
851
889
  opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: options.cutAt === undefined,
package/src/kept-reads.ts CHANGED
@@ -7,7 +7,7 @@ import type { TranscriptRecord } from "./tuck/core/transcript";
7
7
 
8
8
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
9
9
  export function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
10
- resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
10
+ resolvable: (entry: SessionEntry) => boolean, exclude: ReadonlySet<string> = new Set()): TranscriptRecord[] {
11
11
  const cwd = entries.find((entry): entry is SessionHeader => entry.type === "session")?.cwd;
12
12
  const reads = new Map<string, { path: string; key: string; order: number }>(), mutations = new Map<string, number>();
13
13
  let allMutated = -1;
@@ -42,7 +42,7 @@ export function keptReadCandidates(entries: readonly (SessionEntry | SessionHead
42
42
  const entry = entries[at]!;
43
43
  if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
44
44
  const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
45
- if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order) continue;
45
+ if (!read || seen.has(read.key) || exclude.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order) continue;
46
46
  const text = textOf(entry.message.content);
47
47
  if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
48
48
  seen.add(read.key);
@@ -79,6 +79,23 @@ export function requestReplyFloor(branch: readonly SessionEntry[], reserve: numb
79
79
  return Math.min(limit, Math.ceil(largest));
80
80
  }
81
81
 
82
+ /** Reply room after a length stop on this branch (1.7.0): twice the largest stopped output of this model, bounded by its maxTokens instead of
83
+ * the reserve, and by half of what Pi can give a request (so a small window keeps room for the conversation). Undefined with no length stop:
84
+ * then nothing changes. Read from the branch only; nothing carries across sessions. */
85
+ export function stoppedReplyRoom(branch: readonly SessionEntry[], model: ReplyModel, window: number, margin: number): number | undefined {
86
+ let largest = 0;
87
+ for (const entry of branch) {
88
+ if (entry.type !== 'message' || entry.message.role !== 'assistant') continue;
89
+ const message = entry.message;
90
+ if (message.stopReason !== 'length' || message.model !== model.id || message.provider !== model.provider || message.api !== model.api) continue;
91
+ const output = message.usage?.output;
92
+ if (typeof output === 'number' && Number.isFinite(output) && output > largest) largest = output;
93
+ }
94
+ if (largest <= 0) return undefined;
95
+ const raised = Math.ceil(2 * largest), cap = model.maxTokens > 0 ? model.maxTokens : raised;
96
+ return Math.max(1, Math.min(raised, cap, Math.floor((window - margin) / 2)));
97
+ }
98
+
82
99
  /** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
83
100
  export function carriesPrompt(messages: Messages, prompt: string, role: 'user' | 'custom' = 'user'): boolean {
84
101
  if (!prompt.length) return true;
package/src/thrash.ts ADDED
@@ -0,0 +1,44 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import { isDiscardedResponse } from "./protocol";
3
+ import { pathKey } from "./path-key";
4
+ import { isTextOnly, textOf } from "./tuck/core/content";
5
+ import { extractPath } from "./tuck/core/tool-args";
6
+
7
+ /** A re-read counts when it is issued within this many replies after a cut. */
8
+ export const THRASH_WINDOW_REPLIES = 3;
9
+ /** Re-reads per cut at which a session is thrashing. */
10
+ export const THRASH_BAR = 0.5;
11
+
12
+ /**
13
+ * Whether the branch is thrashing: its cuts drop files the agent then reads again. A re-read is a read with the same path, offset and
14
+ * limit as an earlier read that came before a cut, whose result text is identical to that earlier read's (the file did not change), issued
15
+ * within THRASH_WINDOW_REPLIES replies after the latest cut. The branch thrashes when re-reads per cut reach THRASH_BAR. With no cut, or no
16
+ * such re-read, it never does. Deterministic: it reads only the recorded branch.
17
+ */
18
+ export function thrashing(branch: readonly SessionEntry[]): boolean {
19
+ let cuts = 0, replies = 0, rereads = 0;
20
+ const pending = new Map<string, { key: string; cut: number; soon: boolean }>(), last = new Map<string, { cut: number; text: string }>();
21
+ for (const entry of branch) {
22
+ if (entry.type === "compaction") { cuts++; replies = 0; continue; }
23
+ if (entry.type !== "message") continue;
24
+ const message = entry.message;
25
+ if (message.role === "assistant") {
26
+ if (isDiscardedResponse(message)) continue;
27
+ replies++;
28
+ for (const block of message.content) {
29
+ if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;
30
+ const args = block.arguments as Record<string, unknown>, path = extractPath(args);
31
+ if (!path) continue;
32
+ pending.set(block.id, { key: JSON.stringify([pathKey(path), args.offset ?? null, args.limit ?? null]), cut: cuts, soon: cuts > 0 && replies <= THRASH_WINDOW_REPLIES });
33
+ }
34
+ } else if (message.role === "toolResult") {
35
+ const read = pending.get(message.toolCallId);
36
+ if (!read || message.isError || !isTextOnly(message.content)) continue;
37
+ pending.delete(message.toolCallId);
38
+ const text = textOf(message.content), earlier = last.get(read.key);
39
+ if (read.soon && earlier && earlier.cut < read.cut && earlier.text === text) rereads++;
40
+ last.set(read.key, { cut: read.cut, text });
41
+ }
42
+ }
43
+ return cuts > 0 && rereads / cuts >= THRASH_BAR;
44
+ }
@@ -4,3 +4,14 @@ export const CLOSING_INSTRUCTION = "Only the dialogue and the actions and files
4
4
  "Files created by commands are not listed: Before re-running a command listed above, read its output with tuck_recall instead. Re-read a file before editing it or importing from it. Use tuck_recall for anything else. Treat anything not shown here as unknown.";
5
5
  /** Parsing never depends on this wording (transcript.ts splitSummary). */
6
6
  export const DIALOGUE_SUFFIX = CLOSING_SEPARATOR + CLOSING_INSTRUCTION;
7
+ const REREAD = "Re-read a file before editing it or importing from it.";
8
+ /** The closing words when working files follow: the re-read rule stays for every other file. */
9
+ export const WORKING_FILES_INSTRUCTION = CLOSING_INSTRUCTION.replace(REREAD,
10
+ "Re-read a file before editing it or importing from it, unless it is one of the working files below.");
11
+ /** Opens the working files, after the closing words. Each file follows as one raw block (real line breaks, so its text can be quoted
12
+ * exactly in an edit). The closing section is kept byte for byte by every parser (transcript.ts splitSummary), so raw text is safe there. */
13
+ export const WORKING_FILES_HEADER = "\n\nWorking files: each is the whole file, identical to the file on disk when this summary was made. Edit from these copies.";
14
+ export const workingFileBlock = (file: { path: string; text: string }): string => `\n<file path=${JSON.stringify(file.path)}>\n${file.text}\n</file>`;
15
+ /** The closing section: the dialogue suffix alone, or, with working files, its working-files form followed by each file. */
16
+ export const closingSuffix = (files: readonly { path: string; text: string }[]): string => files.length
17
+ ? CLOSING_SEPARATOR + WORKING_FILES_INSTRUCTION + WORKING_FILES_HEADER + files.map(workingFileBlock).join("") : DIALOGUE_SUFFIX;
package/src/tuck.ts CHANGED
@@ -2,12 +2,13 @@ import { resolveSourceTime, type SourceTime } from "./tuck/core/source-time";
2
2
  import { orderByOriginalSource } from "./tuck/core/source-order";
3
3
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
4
4
  import { parseRecords, serializeTranscript, serializeRecord, splitSummary, TRANSCRIPT_HEADER, type TranscriptRecord } from "./tuck/core/transcript";
5
- import { DIALOGUE_SUFFIX } from "./tuck/core/format";
5
+ import { closingSuffix, DIALOGUE_SUFFIX, workingFileBlock, WORKING_FILES_HEADER, WORKING_FILES_INSTRUCTION, CLOSING_INSTRUCTION } from "./tuck/core/format";
6
6
  import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget";
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content";
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
+ import { workingSetCandidates, type WorkingFile } from "./working-set.js";
11
12
  import { keptSearchCandidates } from "./kept-searches.js";
12
13
  import { fileObservations, thinkingRecords } from "./content-observations";
13
14
  import { pathKey } from "./path-key";
@@ -31,6 +32,8 @@ type Draft = { compaction: Pick<Extract<SessionEntry, { type: "compaction" }>, "
31
32
  export interface RecallContinuation { query: string; throughEntryId: string; offset: number }
32
33
  /** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
33
34
  export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
35
+ /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
36
+ export const WORKING_SET_SHARE = 2 / 3;
34
37
  /** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
35
38
  export interface Tuck {
36
39
  buildOwnCut(entries: SessionEntry[], keep: number): Cut;
@@ -233,8 +236,10 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
233
236
  const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
234
237
  const summaryTokens = (characters: number) => Math.ceil((characters + wrapperCharacters) / 4);
235
238
  const lineCost = (records: readonly TranscriptRecord[]) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
236
- const frameLength = (cost: number, count: number) => TRANSCRIPT_HEADER.length + DIALOGUE_SUFFIX.length + cost + (count ? 0 : 1);
237
- const render = (records: TranscriptRecord[]) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + DIALOGUE_SUFFIX;
239
+ // Working files carried raw in the closing section. Chosen once the boundary is known; until then the suffix is the plain one.
240
+ let carried: WorkingFile[] = [], suffix = DIALOGUE_SUFFIX;
241
+ const frameLength = (cost: number, count: number) => TRANSCRIPT_HEADER.length + suffix.length + cost + (count ? 0 : 1);
242
+ const render = (records: TranscriptRecord[]) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + suffix;
238
243
  type Unit = { position: number; index: number; count: number };
239
244
  const units: Record<"user" | "assistant" | "toolResult", Unit[]> = { user: [], assistant: [], toolResult: [] };
240
245
  for (const row of rows) {
@@ -362,6 +367,21 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
362
367
  const lists = listsAt(boundary);
363
368
  const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
364
369
  const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
370
+ // The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
371
+ // WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
372
+ const resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
373
+ const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
374
+ if (workingSet.files.length) {
375
+ const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
376
+ let cost = WORKING_FILES_INSTRUCTION.length - CLOSING_INSTRUCTION.length + WORKING_FILES_HEADER.length;
377
+ for (const file of workingSet.files) {
378
+ const extra = workingFileBlock(file).length;
379
+ if (cost + extra > allowance) continue;
380
+ carried.push(file); cost += extra;
381
+ }
382
+ suffix = closingSuffix(carried);
383
+ }
384
+ const carriedKeys = new Set(carried.map(file => file.key));
365
385
  let ledger: TranscriptRecord[] = lists.records;
366
386
  let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
367
387
  // List caps are existing ranking policy; only the carried target is a
@@ -381,7 +401,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
381
401
  return row?.message.role === "user" && isTextOnly(row.message.content);
382
402
  }));
383
403
  const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
384
- const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
404
+ const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
385
405
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
386
406
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position]!)),
387
407
  ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
@@ -443,10 +463,10 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
443
463
  let keptResultCost = 0;
444
464
  const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
445
465
  const counts = new Map<string, number>();
446
- const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
466
+ const prefix = [header, ...entries.slice(0, boundary)];
447
467
  // Reads and searches share the lead rank, newest result first, and one
448
468
  // allowance. Keep L2's independent four-item caps and whole-item skips.
449
- const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
469
+ const candidates = [...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
450
470
  .sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
451
471
  for (const record of candidates) {
452
472
  if ((counts.get(record.title!) ?? 0) === 4) continue;
@@ -458,10 +478,10 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
458
478
  if (keptResults.length) offer = assemble(compiled.text, boundary);
459
479
  const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
460
480
  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 => {
481
+ const keptReadPaths = new Set([...carriedKeys, ...keptResults.filter(record => record.title === "Kept-read").map(record => {
462
482
  const heading = record.text!.slice(0, record.text!.indexOf("\n"));
463
483
  return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
464
- }));
484
+ })]);
465
485
  const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
466
486
  const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
467
487
  for (const item of shownFiles) item.definitions = observations.get(item.path);
@@ -533,12 +553,12 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
533
553
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
534
554
  });
535
555
  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));
556
+ const keptResultIndices = new Set([...keptResults.map(record => record.sourceIndex), ...carried.map(file => file.sourceIndex)]);
537
557
  const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
538
558
  const extensionPrice = (at: number) => {
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;
559
+ // Kept results and working files already spend this extension's
560
+ // price. They stay in the compacted prefix, so the native tail never repeats them.
561
+ if (keptResultIndices.size && at <= lastKeptResultPosition) return Infinity;
542
562
  let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
543
563
  let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
544
564
  for (const range of ranges) {
@@ -565,7 +585,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
565
585
  return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
566
586
  const mode: DraftMode = compiled.step === "whole" ? "dialogue" : "shrunk";
567
587
  return { compaction: { summary: offer.summary, firstKeptEntryId: entries[boundary]?.id ?? "", tokensBefore: input.tokensBefore,
568
- details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode } }, after, mode };
588
+ details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode,
589
+ ...(workingSet.files.length || workingSet.rejected ? { workingSet: { carried: carried.map(file => file.path), offered: workingSet.files.length, rejected: workingSet.rejected } } : {}) } }, after, mode };
569
590
  }
570
591
 
571
592
  /** Numeric references use the original session index, then intersect with readable current-branch entries. */
@@ -0,0 +1,66 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, resolve } from "node:path";
4
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
5
+ import { pathKey } from "./path-key";
6
+ import { isTextOnly, textOf } from "./tuck/core/content";
7
+ import { extractPath } from "./tuck/core/tool-args";
8
+
9
+ /** Pi's read tool returns at most 50KB of a file's text, so a larger file can never equal a recorded whole read. */
10
+ const MAX_FILE_BYTES = 64 * 1024;
11
+ /** Reads a file's current text, or undefined when it cannot be read. Never throws. */
12
+ export type FileReader = (absolutePath: string) => string | undefined;
13
+ const diskReader: FileReader = path => {
14
+ try { return statSync(path).size > MAX_FILE_BYTES ? undefined : readFileSync(path, "utf8"); } catch { return undefined; }
15
+ };
16
+ let reader = diskReader;
17
+ /** Test and offline-replay seam: where carried files are checked. Undefined restores the disk. */
18
+ export const setWorkingFileReader = (next?: FileReader): void => { reader = next ?? diskReader; };
19
+
20
+ /** Where Pi's read tool reads a recorded path: an "@" prefix dropped, "~" expanded, relative to the session's folder. */
21
+ export const readPath = (path: string, cwd: string): string => {
22
+ let name = path.startsWith("@") ? path.slice(1) : path;
23
+ if (name === "~") name = homedir(); else if (name.startsWith("~/")) name = homedir() + name.slice(1);
24
+ return isAbsolute(name) ? name : resolve(cwd, name);
25
+ };
26
+
27
+ export interface WorkingFile { path: string; key: string; reads: number; sourceIndex: number; position: number; text: string }
28
+ /**
29
+ * The files the agent has read more than once, most reads first, then most recent last read. A file is carried only when its last read
30
+ * covered the whole file (no offset or limit) and the file on disk holds exactly that read's text now. Pi's read tool returns a whole small
31
+ * file verbatim, so equality proves both that the read was complete and that nothing (an edit, a write, a shell command, a generator) has
32
+ * changed the file since. `rejected` counts the files whose last read was whole but whose disk text differs or cannot be read.
33
+ * Only last reads inside the compacted prefix (before `boundary`) are offered: a later read is still in the native tail.
34
+ */
35
+ export function workingSetCandidates(entries: readonly SessionEntry[], boundary: number, indices: ReadonlyMap<string, number>, cwd: string,
36
+ resolvable: (entry: SessionEntry) => boolean): { files: WorkingFile[]; rejected: number } {
37
+ const calls = new Map<string, { path: string; key: string; whole: boolean }>(), last = new Map<string, string>(), reads = new Map<string, number>();
38
+ const results = new Map<string, { entry: SessionEntry; position: number }>();
39
+ entries.forEach((entry, position) => {
40
+ if (entry.type !== "message") return;
41
+ if (entry.message.role === "toolResult") { results.set(entry.message.toolCallId, { entry, position }); return; }
42
+ if (entry.message.role !== "assistant") return;
43
+ for (const block of entry.message.content) {
44
+ if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;
45
+ const args = block.arguments as Record<string, unknown>, path = extractPath(args);
46
+ if (!path || /[\r\n]/u.test(path)) continue;
47
+ const key = pathKey(path, cwd);
48
+ calls.set(block.id, { path, key, whole: !("offset" in args) && !("limit" in args) });
49
+ last.set(key, block.id); reads.set(key, (reads.get(key) ?? 0) + 1);
50
+ }
51
+ });
52
+ const files: WorkingFile[] = [];
53
+ let rejected = 0;
54
+ for (const [key, id] of last) {
55
+ const count = reads.get(key)!, call = calls.get(id)!, result = results.get(id);
56
+ if (count < 2 || !call.whole || !result || result.position >= boundary) continue;
57
+ const { entry, position } = result;
58
+ if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
59
+ const text = textOf(entry.message.content), sourceIndex = indices.get(entry.id);
60
+ if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
61
+ if (reader(readPath(call.path, cwd)) !== text) { rejected++; continue; }
62
+ files.push({ path: call.path, key, reads: count, sourceIndex, position, text });
63
+ }
64
+ files.sort((a, b) => b.reads - a.reads || b.position - a.position);
65
+ return { files, rejected };
66
+ }