pi-tuck 1.7.0 → 1.9.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/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,12 +16,16 @@ 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";
21
24
  import { compileDialogue } from "./tuck/core/summarize.js";
22
25
  import { prepareKeywordQuery } from "./tuck/core/keyword-query.js";
23
26
  import { rankRecallRows } from "./tuck/core/search-entries.js";
27
+ /** The share of the brief below which the carried part of a prefix-stable summary keeps only its user and custom records. */
28
+ export const STABLE_CONSOLIDATE_AT = 0.5;
24
29
  export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
25
30
  /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
26
31
  * `_operatorManual` retains the exported positional slot for existing callers. */
@@ -225,8 +230,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
225
230
  const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
226
231
  const summaryTokens = (characters) => Math.ceil((characters + wrapperCharacters) / 4);
227
232
  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;
233
+ // Working files carried raw in the closing section. Chosen once the boundary is known; until then the suffix is the plain one.
234
+ let carried = [], suffix = DIALOGUE_SUFFIX;
235
+ const frameLength = (cost, count) => TRANSCRIPT_HEADER.length + suffix.length + cost + (count ? 0 : 1);
236
+ const render = (records) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + suffix;
230
237
  const units = { user: [], assistant: [], toolResult: [] };
231
238
  for (const row of rows) {
232
239
  if (row.index === undefined)
@@ -382,6 +389,23 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
382
389
  const lists = listsAt(boundary);
383
390
  const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
384
391
  const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
392
+ // The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
393
+ // WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
394
+ const resolvable = (entry) => readable(entry) !== undefined;
395
+ const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
396
+ if (workingSet.files.length) {
397
+ const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
398
+ let cost = WORKING_FILES_INSTRUCTION.length - CLOSING_INSTRUCTION.length + WORKING_FILES_HEADER.length;
399
+ for (const file of workingSet.files) {
400
+ const extra = workingFileBlock(file).length;
401
+ if (cost + extra > allowance)
402
+ continue;
403
+ carried.push(file);
404
+ cost += extra;
405
+ }
406
+ suffix = closingSuffix(carried);
407
+ }
408
+ const carriedKeys = new Set(carried.map(file => file.key));
385
409
  let ledger = lists.records;
386
410
  let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
387
411
  // List caps are existing ranking policy; only the carried target is a
@@ -402,7 +426,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
402
426
  return row?.message.role === "user" && isTextOnly(row.message.content);
403
427
  }));
404
428
  const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
405
- const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
429
+ const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
406
430
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
407
431
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position])),
408
432
  ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
@@ -448,7 +472,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
448
472
  else
449
473
  records[pos] = omissionRecord("user", missing.length, [missing[0].index, missing.at(-1).index], false);
450
474
  }
451
- else if (at !== compiledBoundary) {
475
+ else if (at !== compiledBoundary || stable) {
452
476
  const role = record.role;
453
477
  if (role === "assistant" || role === "toolResult") {
454
478
  const missing = units[role].filter(unit => unit.position < at && unit.index >= record.sourceRange.start && unit.index <= record.sourceRange.end &&
@@ -466,17 +490,99 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
466
490
  const summary = render([...records, ...ledger, ...keptResults, ...thoughtOpenings]);
467
491
  return { summary, records: [...records, ...thoughtOpenings] };
468
492
  };
469
- const compiled = tuck.compileDialogue(compileInput);
493
+ // Prefix-stable summary: the previous pi-tuck summary's dialogue records are carried verbatim as the oldest part, and only the sources
494
+ // since that cut are compiled after them; counters, lists and kept results follow the dialogue. Consecutive summaries then share a
495
+ // prefix a provider's prompt cache can read. When the carried part leaves the new sources less than half the brief, it keeps only its
496
+ // user and custom records (a fixed point, so the part already kept that way stays the prefix), and past half the brief its oldest
497
+ // sources go, down to a quarter. With no previous pi-tuck summary, a floor summary, or nothing that fits, the whole history is compiled.
498
+ const stableCompile = () => {
499
+ const whole = () => ({ compiled: tuck.compileDialogue(compileInput), carried: false });
500
+ const previousAt = entries.findLastIndex(entry => entry.type === "compaction");
501
+ const previous = entries[previousAt];
502
+ const details = previous?.type === "compaction" ? previous.details : undefined;
503
+ if (previous?.type !== "compaction" || details?.compactor !== "pi-tuck" || details.deepest)
504
+ return whole();
505
+ const split = splitSummary(previous.summary);
506
+ if (!split || split.version !== 2)
507
+ return whole();
508
+ const from = Math.min(previous.firstKeptEntryId ? positions.get(previous.firstKeptEntryId) ?? previousAt : previousAt, compiledBoundary);
509
+ const indexAt = new Map(rows.map(row => [row.index, row.position]));
510
+ const positionOf = (record) => record.sourceEntryId !== undefined ? positions.get(record.sourceEntryId)
511
+ : record.sourceIndex !== undefined ? indexAt.get(record.sourceIndex) : undefined;
512
+ const dialogue = (record) => record.sourceIndex !== undefined || record.sourceEntryId !== undefined
513
+ ? (record.kind === "excerpt" || record.kind === "omission") && (record.role === "user" || record.role === "assistant" || record.role === "custom") : false;
514
+ let old;
515
+ try {
516
+ old = parseRecords(split.body, 2).filter(record => dialogue(record) && (positionOf(record) ?? Infinity) < from);
517
+ }
518
+ catch {
519
+ return whole();
520
+ }
521
+ // One counter per role over the whole compacted history: what the records leave out (assemble counts it again once the protected
522
+ // prompts are merged). Without `records`, every unit counts: a counter that costs at least as much as any real one.
523
+ const counters = (records) => ["user", "assistant", "toolResult"].flatMap(role => {
524
+ const shown = new Map();
525
+ for (const record of records ?? [])
526
+ if (record.kind === "excerpt" && record.role === role && !record.span && record.sourceIndex !== undefined &&
527
+ (role !== "user" || record.text === userTexts.get(record.sourceIndex)))
528
+ shown.set(record.sourceIndex, (shown.get(record.sourceIndex) ?? 0) + 1);
529
+ const missing = units[role].flatMap(unit => {
530
+ const count = unit.position < compiledBoundary ? unit.count - Math.min(unit.count, shown.get(unit.index) ?? 0) : 0;
531
+ return count ? [{ index: unit.index, count }] : [];
532
+ });
533
+ return missing.length ? [omissionRecord(role, missing.reduce((n, unit) => n + unit.count, 0), [missing[0].index, missing.at(-1).index], false)] : [];
534
+ });
535
+ // A carried prompt that the protected rows quote too is paid for once, in their fixed cost (assemble keeps one of the two).
536
+ const protectedCost = new Map(protectedView.kept.map(record => [sourceKey(record), lineCost([record])]));
537
+ const oldCost = () => old.reduce((n, record) => n + Math.max(0, lineCost([record]) - (record.role === "user" || record.role === "custom" ? protectedCost.get(sourceKey(record)) ?? 0 : 0)), 0);
538
+ const fresh = sourceRows.filter(row => row.position >= from);
539
+ const compileFresh = (reserve) => fresh.length ? tuck.compileDialogue({ messages: fresh.map(row => row.message), sourceIndices: fresh.map(row => row.index),
540
+ sourceEntryIds: fresh.map(row => row.id), sourceTimes: fresh.map(row => resolveSourceTime(entries[row.position])),
541
+ ranking: { maxBriefChars: maxBriefChars - oldCost() - reserve, mandatorySourceIndices: mandatory } }) : { text: "", step: "whole", size: 0 };
542
+ // First as if every new source fits whole: then only the counters the carried part and the tool history need are reserved.
543
+ const freshRecords = (compiled) => {
544
+ const body = compiled.text ? splitSummary(compiled.text) : undefined;
545
+ return body ? parseRecords(body.body, body.version).filter(record => record.kind !== "omission" || record.sourceIndex !== undefined) : undefined;
546
+ };
547
+ const wholeFresh = fresh.flatMap((row) => row.message.role === "user" ? [{ kind: "excerpt", role: "user", sourceIndex: row.index, text: userTexts.get(row.index) ?? "" }]
548
+ : row.message.role === "assistant" ? row.message.content.flatMap(part => part.type === "text" && part.text.trim() ? [{ kind: "excerpt", role: "assistant", sourceIndex: row.index, text: "" }] : []) : []);
549
+ let compiled = compileFresh(lineCost(counters([...old, ...wholeFresh]))), consolidated = false;
550
+ if (compiled.step !== "whole") {
551
+ if (maxBriefChars - oldCost() - lineCost(counters()) < STABLE_CONSOLIDATE_AT * maxBriefChars) {
552
+ consolidated = true;
553
+ old = old.filter(record => record.role === "user" || record.role === "custom");
554
+ if (oldCost() > STABLE_CONSOLIDATE_AT * maxBriefChars) {
555
+ let cost = oldCost(), first = 0;
556
+ while (first < old.length && cost > maxBriefChars / 4) {
557
+ const at = positionOf(old[first]);
558
+ while (first < old.length && positionOf(old[first]) === at)
559
+ cost -= lineCost([old[first++]]);
560
+ }
561
+ old = old.slice(first);
562
+ }
563
+ }
564
+ compiled = compileFresh(lineCost(counters()));
565
+ }
566
+ const added = fresh.length ? freshRecords(compiled) : [];
567
+ if (!added)
568
+ return whole();
569
+ const text = serializeTranscript([...old, ...added, ...counters([...old, ...added])]) + DIALOGUE_SUFFIX;
570
+ if (text.length - lineCost(old) + oldCost() > maxBriefChars)
571
+ return whole();
572
+ const step = !consolidated && compiled.step === "whole" && details.mode === "dialogue" ? "whole" : "ranked";
573
+ return { compiled: { text, step, size: text.length }, carried: true };
574
+ };
575
+ const { compiled, carried: stable } = stableCompile();
470
576
  let offer = assemble(compiled.text);
471
577
  // After the complete dialogue fill, observations spend the remaining
472
578
  // room before the native tail's older end. The pinned tail is untouched.
473
579
  let keptResultCost = 0;
474
580
  const keptResultCap = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
475
581
  const counts = new Map();
476
- const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry) => readable(entry) !== undefined;
582
+ const prefix = [header, ...entries.slice(0, boundary)];
477
583
  // Reads and searches share the lead rank, newest result first, and one
478
584
  // allowance. Keep L2's independent four-item caps and whole-item skips.
479
- const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
585
+ const candidates = [...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
480
586
  .sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
481
587
  for (const record of candidates) {
482
588
  if ((counts.get(record.title) ?? 0) === 4)
@@ -492,10 +598,10 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
492
598
  offer = assemble(compiled.text, boundary);
493
599
  const shownActions = lists.actions.slice(0, Math.min(listedKeep, MAX_ACTION_LINES));
494
600
  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
- }));
601
+ const keptReadPaths = new Set([...carriedKeys, ...keptResults.filter(record => record.title === "Kept-read").map(record => {
602
+ const heading = record.text.slice(0, record.text.indexOf("\n"));
603
+ return pathKey(heading.slice(5, heading.lastIndexOf(` (as recorded at #${record.sourceIndex};`)), header.cwd);
604
+ })]);
499
605
  const filesWithoutKeptReads = shownFiles.filter(item => !keptReadPaths.has(pathKey(item.path, header.cwd)));
500
606
  const observations = fileObservations(new Set(filesWithoutKeptReads.map(item => item.path)), entries, indices, failedCalls);
501
607
  for (const item of shownFiles)
@@ -583,12 +689,12 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
583
689
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
584
690
  });
585
691
  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));
692
+ const keptResultIndices = new Set([...keptResults.map(record => record.sourceIndex), ...carried.map(file => file.sourceIndex)]);
587
693
  const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
588
694
  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)
695
+ // Kept results and working files already spend this extension's
696
+ // price. They stay in the compacted prefix, so the native tail never repeats them.
697
+ if (keptResultIndices.size && at <= lastKeptResultPosition)
592
698
  return Infinity;
593
699
  let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
594
700
  let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
@@ -623,7 +729,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
623
729
  return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
624
730
  const mode = compiled.step === "whole" ? "dialogue" : "shrunk";
625
731
  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 };
732
+ details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode,
733
+ ...(workingSet.files.length || workingSet.rejected ? { workingSet: { carried: carried.map(file => file.path), offered: workingSet.files.length, rejected: workingSet.rejected } } : {}) } }, after, mode };
627
734
  }
628
735
  /** Numeric references use the original session index, then intersect with readable current-branch entries. */
629
736
  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.7.0",
3
+ "version": "1.9.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,11 @@ 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. `lean`, when below that line, moves
155
+ * it down: a cut becomes due there too, as an opportunistic cut inside the band. */
156
+ export function gateCut(input: { total: number; mandatory: number; room: number; band: number; trigger?: number; lean?: number; fits: CutInput["fits"] }): Gate {
155
157
  const { total, mandatory, room, band, fits } = input;
156
- if (fits(total, band)) return { kind: "none" };
158
+ if (fits(total, Math.min(Math.max(band, input.trigger ?? band), input.lean ?? Infinity))) return { kind: "none" };
157
159
  const inBand = fits(total, room);
158
160
  if (!fits(mandatory, room)) return { kind: "defer" };
159
161
  return { kind: "plan", opportunistic: inBand };
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "5e89e04df1c0af56b4fb2cc148ddf76e5f4e6c3efa14782e034b41e424b27796";
1
+ export const BUILD_ID = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
package/src/compaction.ts CHANGED
@@ -12,7 +12,7 @@ import { isDeepStrictEqual } from "node:util";
12
12
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
13
13
  import { projectedMessages } from "./omissions.js";
14
14
  import { applyClips, clipBudgets, clipFor, type Clip } from "./clip.js";
15
- 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,
16
16
  type AgentMessage, type Decision, type Messages, type Plan, type Target } from "./budget.js";
17
17
  import { getCurrentSystemMessage, isContextOverflow, normalizeContext, type ImageContent, type ToolResultMessage } from "@earendil-works/pi-ai";
18
18
  import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft, type TurnEndEvent } from "@earendil-works/pi-coding-agent";
@@ -22,6 +22,8 @@ import type { RecallPolicy } from "./recall.js";
22
22
  import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
23
23
 
24
24
  import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
25
+ import { thrashing } from "./thrash.js";
26
+ import { leanLine } from "./lean.js";
25
27
  import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
26
28
  import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
27
29
  import { notify } from "./notify.js";
@@ -219,7 +221,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
219
221
  pi.on("session_compact", (_event, ctx) => observe(ctx));
220
222
  pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
221
223
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
222
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx) }), "info");
224
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx), trigger: activeTrigger(ctx) }), "info");
223
225
  } });
224
226
  // Pi's native start/settled events bracket the run and its post-turn cuts.
225
227
  let run: Run | undefined;
@@ -376,10 +378,43 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
376
378
  const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
377
379
  options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
378
380
  const decisionBand = (ctx: ExtensionContext, room: number) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
381
+ // Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
382
+ // to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
383
+ // 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
384
+ // 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-
385
+ // 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.
386
+ const triggerLine = (ctx: ExtensionContext, room: number): number | undefined => {
387
+ if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
388
+ const branch = ctx.sessionManager.getBranch();
389
+ if (!thrashing(branch)) return undefined;
390
+ const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
391
+ const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
392
+ const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
393
+ return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
394
+ };
395
+ // Lean line (lean.ts): once the branch has a cut and a measured growth rate, a cut also becomes due at K + sqrt(2(K + R)·δ / h), the
396
+ // economic order quantity of the context, when that is below the line above. Never later than it, and admission is unchanged: a cut it
397
+ // asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off.
398
+ const leanLimit = (ctx: ExtensionContext): number | undefined => {
399
+ if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
400
+ return leanLine(ctx.sessionManager.getBranch());
401
+ };
402
+ // A cut the lean line makes due inside the band is sized by that line, not by the tenth-of-the-room rule for opportunistic cuts.
403
+ const usefulOnlyAt = (total: number, band: number, lean: number | undefined, ctx: ExtensionContext) =>
404
+ options.cutAt === undefined && !(lean !== undefined && fits(total, band, ctx));
379
405
  /** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
380
406
  const cutPoint = (ctx: ExtensionContext): number | undefined => {
381
407
  if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
382
- try { const band = decisionBand(ctx, limits(ctx).room); return band > 0 ? band : undefined; } catch { return undefined; }
408
+ try { const { room } = limits(ctx), band = Math.min(Math.max(decisionBand(ctx, room), triggerLine(ctx, room) ?? 0), leanLimit(ctx) ?? Infinity); return band > 0 ? band : undefined; } catch { return undefined; }
409
+ };
410
+ /** Which line sets the cut point now, for `/tuck`: the lean line, the thrash line, or neither (the band). Reads only. */
411
+ const activeTrigger = (ctx: ExtensionContext): "lean" | "thrash" | undefined => {
412
+ if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
413
+ try {
414
+ const { room } = limits(ctx), band = decisionBand(ctx, room), thrash = triggerLine(ctx, room), lean = leanLimit(ctx);
415
+ const line = Math.max(band, thrash ?? 0);
416
+ return lean !== undefined && lean < line ? "lean" : thrash !== undefined && thrash > band ? "thrash" : undefined;
417
+ } catch { return undefined; }
383
418
  };
384
419
  const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
385
420
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
@@ -579,14 +614,15 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
579
614
  // trigger would: nothing below the band, an opportunistic cut inside it, a due cut at or above the room. A refusal is a plain
580
615
  // cancel (Pi reports it as aborted), never a failure.
581
616
  let thresholdOpportunistic = false;
617
+ const lean = leanLimit(ctx);
582
618
  if (event.reason === "threshold") {
583
- const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
619
+ const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
584
620
  if (gate.kind !== "plan") return { cancel: true };
585
621
  thresholdOpportunistic = gate.opportunistic;
586
622
  }
587
623
  // Pi checks old history before appending a new idle prompt. During an active run/manual cut the latest admitted input stays protected.
588
624
  const decide = (targetRoom = room, targetBand = band) => chooseCut({
589
- before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: options.cutAt === undefined,
625
+ before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
590
626
  opportunistic: thresholdOpportunistic,
591
627
  unreduced: "Compaction did not reduce context within the estimated request budget",
592
628
  plan: (target): Plan<CutPlan> => {
@@ -731,11 +767,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
731
767
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
732
768
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
733
769
  // help: leave it to the complete-context guard, which fails closed.
734
- const gate = gateCut({ total: before + mandatory, mandatory, room, band, fits: (tokens, limit) => fits(tokens, limit, ctx) });
770
+ const lean = leanLimit(ctx);
771
+ const gate = gateCut({ total: before + mandatory, mandatory, room, band, trigger: triggerLine(ctx, room), lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
735
772
  if (gate.kind === "none") return;
736
773
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
737
774
  const decide = (targetRoom: number, targetBand: number, opportunistic: boolean) => chooseCut({
738
- before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: options.cutAt === undefined, opportunistic,
775
+ before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx), opportunistic,
739
776
  unreduced: "Incoming prompt compaction did not reduce context within the estimated request budget",
740
777
  plan: (target): Plan<CutPlan> => {
741
778
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
@@ -866,12 +903,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
866
903
  const decide = (targetRoom = room, targetBand = band, required = false) => {
867
904
  previews = [];
868
905
  floorKept = undefined;
869
- const before = measure(saved);
906
+ const before = measure(saved), lean = targetBand === band ? leanLimit(ctx) : undefined;
870
907
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan" as const, opportunistic: false } :
871
- gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
908
+ gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, trigger: targetBand === band ? triggerLine(ctx, room) : undefined, lean, fits: (tokens, limit) => fits(tokens, limit, ctx) });
872
909
  if (gate.kind !== "plan") return gate;
873
910
  return chooseCut({
874
- opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: options.cutAt === undefined,
911
+ opportunistic: gate.opportunistic, mandatory, before, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), usefulOnly: usefulOnlyAt(before + mandatory, targetBand, lean, ctx),
875
912
  unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
876
913
  plan: (target): Plan<CutPlan> => {
877
914
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
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);
package/src/lean.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import { isDiscardedResponse } from "./protocol";
3
+ import { rereadsAfterCuts } from "./thrash";
4
+
5
+ /** Holding cost of a context token per request, as a share of its fresh price: a cached re-send costs about a tenth. */
6
+ export const LEAN_HOLDING = 0.1;
7
+ /** Growth samples (consecutive replies with no cut between) needed before the growth rate counts. */
8
+ export const LEAN_MIN_SAMPLES = 4;
9
+
10
+ const promptTokens = (entry: SessionEntry): number | undefined => {
11
+ if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message)) return undefined;
12
+ const message = entry.message;
13
+ if (message.stopReason === "error" || message.stopReason === "aborted") return undefined;
14
+ const u = message.usage;
15
+ const total = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0);
16
+ return Number.isFinite(total) && total > 0 ? total : undefined;
17
+ };
18
+
19
+ export interface LeanInputs { kept: number; growth: number; rereads: number; samples: number; cuts: number }
20
+ /** The quantities the lean line is built from, read from the branch's recorded usage only. `kept` (K): the prompt of the first reply after
21
+ * the latest cut, what that cut left (system, summary, kept turns, carried files). `growth` (δ): the mean rise of the prompt between
22
+ * consecutive replies with no cut between. `rereads` (R): the mean tokens per cut of unchanged files re-read soon after it (thrash.ts). */
23
+ export function leanInputs(branch: readonly SessionEntry[]): LeanInputs {
24
+ let kept = 0, previous: number | undefined, afterCut = false, sum = 0, samples = 0;
25
+ for (const entry of branch) {
26
+ if (entry.type === "compaction") { previous = undefined; afterCut = true; continue; }
27
+ const prompt = promptTokens(entry);
28
+ if (prompt === undefined) continue;
29
+ if (afterCut) { kept = prompt; afterCut = false; }
30
+ if (previous !== undefined) { sum += prompt - previous; samples++; }
31
+ previous = prompt;
32
+ }
33
+ const { cuts, tokens } = rereadsAfterCuts(branch);
34
+ return { kept, growth: samples ? sum / samples : 0, rereads: cuts ? tokens / cuts : 0, samples, cuts };
35
+ }
36
+
37
+ /**
38
+ * The lean cut line: the economic order quantity of a context. Each cut costs a fresh re-send of what it keeps (K) and the re-reads it causes
39
+ * (R); each token held costs LEAN_HOLDING per request; the context grows by δ per request. The cheapest cycle cuts every
40
+ * n* = sqrt(2(K + R) / (h·δ)) requests, so the line is K + δ·n* = K + sqrt(2(K + R)·δ / h). Rising re-reads raise R and so the line.
41
+ * Undefined until the branch has a cut with a measured reply after it and LEAN_MIN_SAMPLES growth samples with a positive mean.
42
+ */
43
+ export function leanLine(branch: readonly SessionEntry[]): number | undefined {
44
+ const { kept, growth, rereads, samples, cuts } = leanInputs(branch);
45
+ if (!cuts || kept <= 0 || samples < LEAN_MIN_SAMPLES || !(growth > 0)) return undefined;
46
+ return Math.ceil(kept + Math.sqrt(2 * (kept + rereads) * growth / LEAN_HOLDING));
47
+ }
package/src/status.ts CHANGED
@@ -27,6 +27,8 @@ export function statusText(input: {
27
27
  cacheSensitive?: boolean;
28
28
  /** The trim point in tokens for the current model, the footer's full bar; absent when it cannot be computed. */
29
29
  cutPoint?: number;
30
+ /** The line that sets the trim point now, when it is not the default band: the lean line or the thrash line. */
31
+ trigger?: "lean" | "thrash";
30
32
  }): string {
31
33
  if (!input.active) return `pi-tuck ${input.version} is inactive in this host.`;
32
34
  if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version} is standing down (${input.compaction.reason}). Pi controls compaction.`;
@@ -48,7 +50,9 @@ export function statusText(input: {
48
50
  ...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
49
51
  ...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
50
52
  input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
51
- ? `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
53
+ ? input.trigger === "lean" ? `Trim point: this session's lean line, set by its growth per request and the size of its last trim${now}.`
54
+ : input.trigger === "thrash" ? `Trim point: native Pi's line, because this session's trims keep dropping files it then re-reads${now}.`
55
+ : `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
52
56
  "Search: by keyword.",
53
57
  ...checkLines,
54
58
  ].join("\n");