pi-tuck 1.10.3 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +2 -2
  3. package/dist/src/budget.d.ts +0 -2
  4. package/dist/src/budget.js +1 -3
  5. package/dist/src/build-id.d.ts +1 -1
  6. package/dist/src/build-id.js +1 -1
  7. package/dist/src/compaction.d.ts +10 -4
  8. package/dist/src/compaction.js +91 -19
  9. package/dist/src/config-check.d.ts +6 -0
  10. package/dist/src/config-check.js +13 -2
  11. package/dist/src/content-observations.d.ts +0 -6
  12. package/dist/src/content-observations.js +5 -5
  13. package/dist/src/diagnostic-replay.js +6 -6
  14. package/dist/src/diagnostics.d.ts +0 -1
  15. package/dist/src/diagnostics.js +2 -3
  16. package/dist/src/history-image.d.ts +0 -2
  17. package/dist/src/history-image.js +1 -1
  18. package/dist/src/kept-reads.d.ts +0 -2
  19. package/dist/src/kept-reads.js +1 -1
  20. package/dist/src/omissions.d.ts +3 -6
  21. package/dist/src/omissions.js +3 -10
  22. package/dist/src/recall.js +2 -2
  23. package/dist/src/thrash.d.ts +0 -6
  24. package/dist/src/thrash.js +1 -1
  25. package/dist/src/tuck/core/format.d.ts +2 -0
  26. package/dist/src/tuck/core/format.js +3 -0
  27. package/dist/src/tuck/core/token-estimate.d.ts +2 -8
  28. package/dist/src/tuck/core/token-estimate.js +3 -9
  29. package/dist/src/tuck/core/tool-args.d.ts +0 -1
  30. package/dist/src/tuck/core/tool-args.js +1 -1
  31. package/dist/src/tuck/core/transcript.d.ts +3 -2
  32. package/dist/src/tuck/cut.d.ts +0 -1
  33. package/dist/src/tuck/cut.js +0 -3
  34. package/dist/src/tuck.d.ts +2 -2
  35. package/dist/src/tuck.js +11 -8
  36. package/package.json +1 -1
  37. package/src/budget.ts +1 -4
  38. package/src/build-id.ts +1 -1
  39. package/src/compaction.ts +80 -18
  40. package/src/config-check.ts +12 -2
  41. package/src/content-observations.ts +5 -5
  42. package/src/diagnostic-replay.ts +7 -6
  43. package/src/diagnostics.ts +2 -3
  44. package/src/history-image.ts +1 -1
  45. package/src/kept-reads.ts +1 -1
  46. package/src/omissions.ts +3 -10
  47. package/src/recall.ts +3 -3
  48. package/src/thrash.ts +1 -7
  49. package/src/tuck/core/format.ts +3 -0
  50. package/src/tuck/core/token-estimate.ts +4 -20
  51. package/src/tuck/core/tool-args.ts +1 -1
  52. package/src/tuck/core/transcript.ts +2 -2
  53. package/src/tuck/cut.ts +0 -4
  54. package/src/tuck.ts +11 -8
  55. package/dist/src/tuck/core/render-entries.d.ts +0 -6
  56. package/dist/src/tuck/core/render-entries.js +0 -1
  57. package/src/tuck/core/render-entries.ts +0 -6
package/CHANGELOG.md CHANGED
@@ -3,6 +3,32 @@
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.11.0]
7
+
8
+ ### Changed
9
+
10
+ - Act-now turn: on a Chat Completions model, the request that asks the model to act after a thinking-only stop now goes out at the lowest
11
+ thinking effort the server lists (read from its model list at session start; sent top level and in the chat template arguments if Pi sends
12
+ one there) and with at most 20,480 output tokens, above the largest real reply seen on the founder's server. Before, it ran at the
13
+ session's effort and often thought itself into the same stall again. Other requests and other APIs are unchanged. A stop at that
14
+ smaller cap counts as a full-cap stop, so it gets the next act-now turn rather than a length retry.
15
+
16
+ ## [1.10.5]
17
+
18
+ ### Fixed
19
+
20
+ - Thinking-only retry: when a reply is cut short by Pi's own reply limit while it is still thinking, the retry now plans an ordinary trim.
21
+ That trim keeps the action and file lists and the kept results, including prompt-named command outputs, and is made as small as Pi's
22
+ limit allows to give the full reply room. It used to go straight to the smallest possible summary (prompts cut to 80 characters, no
23
+ actions or files), so the agent continued with almost no memory of its work. The smallest summary is now only the fallback when no
24
+ ordinary trim gives the room.
25
+ - Smallest summary: it now carries the outputs of commands a prompt told the agent to run (within the 8,000-character cap), and its
26
+ closing words no longer point to "actions and files listed above", since it keeps none.
27
+
28
+ ## [1.10.4]
29
+
30
+ Not published: its release check failed on a test-only type error. Its fixes ship in 1.10.5.
31
+
6
32
  ## [1.10.3]
7
33
 
8
34
  ### Fixed
package/README.md CHANGED
@@ -12,7 +12,7 @@ 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.10.3. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.10.3` or `pi install git:github.com/galyavin/pi-tuck@v1.10.3`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.11.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.11.0` or `pi install git:github.com/galyavin/pi-tuck@v1.11.0`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
@@ -75,7 +75,7 @@ Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by
75
75
 
76
76
  ## Output exhaustion and small windows
77
77
 
78
- - 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). When such a stop is not retried, pi-tuck queues one more user turn asking the model to act: "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning." The stopped reply stays saved but leaves that request's context. At most two such turns go out in a row until a reply finishes, and only when the request fits and no message is already queued; if the second also stops, the notice below stands. 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.
78
+ - 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). When such a stop is not retried, pi-tuck queues one more user turn asking the model to act: "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning." The stopped reply stays saved but leaves that request's context. On a Chat Completions model, that request alone goes out at the lowest thinking effort the server lists (pi-tuck reads the list at session start) and with at most 20,480 output tokens; a stop at that cap counts as a full-cap stop. At most two such turns go out in a row until a reply finishes, and only when the request fits and no message is already queued; if the second also stops, the notice below stands. 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.
79
79
  - 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.
80
80
  - 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.
81
81
 
@@ -55,8 +55,6 @@ export declare const incomingEventTokens: (event: BeforeAgentStartEvent) => numb
55
55
  export declare const requestTokens: (messages: Messages, systemPrompt: string) => number;
56
56
  /** The saved conversation as the model receives it from this compactor, counted after Pi's conversion. This is the planner's measure too. */
57
57
  export declare const projectedConversationTokens: (messages: Messages, ctx: ExtensionContext, policy?: RecallPolicy) => number;
58
- /** As `projectedConversationTokens`, but a summary that is not in this compactor's format is counted as it is instead of failing: what the planner measures with, so that a cut can replace one. */
59
- export declare const measurableConversationTokens: (messages: Messages, ctx: ExtensionContext, policy?: RecallPolicy) => number;
60
58
  /** Raw reserve for the cut planner: the window less the raw tokens that fit the target room, plus the input no cut can remove. */
61
59
  export declare const planningReserve: (window: number, targetRoom: number, factor: number, mandatory: number) => number;
62
60
  export type Target = "band" | "room";
@@ -1,6 +1,6 @@
1
1
  import { getCurrentSystemMessage } from "@earendil-works/pi-ai";
2
2
  import { convertToLlm, estimateTokens } from "@earendil-works/pi-coding-agent";
3
- import { measurableMessages, projectedMessages } from "./omissions.js";
3
+ import { projectedMessages } from "./omissions.js";
4
4
  import { isDiscardedResponse } from "./protocol.js";
5
5
  import { MAX_TAIL_TOKENS } from "./tuck/cut.js";
6
6
  /** Triggers fire this fraction of the room early. The margin absorbs request growth a boundary cannot see; it never enters the calibration factor. */
@@ -74,8 +74,6 @@ export const requestTokens = (messages, systemPrompt) => {
74
74
  };
75
75
  /** The saved conversation as the model receives it from this compactor, counted after Pi's conversion. This is the planner's measure too. */
76
76
  export const projectedConversationTokens = (messages, ctx, policy) => conversationTokens(projectedMessages(messages, ctx, policy));
77
- /** As `projectedConversationTokens`, but a summary that is not in this compactor's format is counted as it is instead of failing: what the planner measures with, so that a cut can replace one. */
78
- export const measurableConversationTokens = (messages, ctx, policy) => conversationTokens(measurableMessages(messages, ctx, policy));
79
77
  /** Raw reserve for the cut planner: the window less the raw tokens that fit the target room, plus the input no cut can remove. */
80
78
  export const planningReserve = (window, targetRoom, factor, mandatory) => window - Math.floor(targetRoom / factor) + mandatory;
81
79
  /** The least share of the saved conversation a cut due only at the lean line must free. */
@@ -1 +1 @@
1
- export declare const BUILD_ID = "b7162b2a60e8357e1abeb6decc9b739a75077207592f169e6db105b5e2647e90";
1
+ export declare const BUILD_ID = "e11927281c0dc22058687647b4d0658d8a588470b4fae558169cc0532bb02d4e";
@@ -1 +1 @@
1
- export const BUILD_ID = "b7162b2a60e8357e1abeb6decc9b739a75077207592f169e6db105b5e2647e90";
1
+ export const BUILD_ID = "e11927281c0dc22058687647b4d0658d8a588470b4fae558169cc0532bb02d4e";
@@ -2,18 +2,24 @@ import { Run } from "./run.js";
2
2
  import { type RecorderOptions } from "./diagnostics.js";
3
3
  import { type AgentMessage } from "./budget.js";
4
4
  import { SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
5
- import type { RecallPolicy } from "./recall.js";
5
+ import { type RecallPolicy } from "./recall.js";
6
6
  /** Explain a high planning factor, which can come from reported usage or an overflow estimate. */
7
7
  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
- /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
11
10
  /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
12
11
  export declare const capStopNotice: (model: string, maxTokens: number, file: string) => string;
13
12
  /** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
14
13
  export declare const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
15
- /** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
16
- export declare const ACT_NOW_LIMIT = 2;
14
+ /** The act-now request's reply cap: above the largest real reply seen on mac-studio (18.6k tokens in 476 replies), well under the 32k-65k caps
15
+ * a thinking runaway fills. */
16
+ export declare const ACT_NOW_MAX_TOKENS = 20480;
17
+ /** The act-now request, rewritten (Chat Completions payloads only): the lowest effort the server lists, top level (where vLLM-style servers
18
+ * read it) and in chat_template_kwargs if Pi sent one there, and an output cap of at most ACT_NOW_MAX_TOKENS. Undefined for any other request. */
19
+ export declare function actNowPayload(payload: unknown, effort: string | undefined): {
20
+ payload: Record<string, unknown>;
21
+ cap?: number;
22
+ } | undefined;
17
23
  /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
18
24
  * or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
19
25
  export declare function actNowsInARow(branch: readonly SessionEntry[]): number;
@@ -2,7 +2,8 @@ import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run } from "./run.js";
3
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
- import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
5
+ import { lowestEffort, pendingCheck, serverEfforts } from "./config-check.js";
6
+ import { IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
6
7
  import { createHash } from "node:crypto";
7
8
  import { readFileSync } from "node:fs";
8
9
  import { homedir } from "node:os";
@@ -12,7 +13,7 @@ import { isDeepStrictEqual } from "node:util";
12
13
  import { assertNativeToolRounds, isDiscardedResponse } from "./protocol.js";
13
14
  import { projectedMessages } from "./omissions.js";
14
15
  import { applyClips, clipBudgets, clipFor } from "./clip.js";
15
- import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, measurableConversationTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
16
+ import { DEFAULT_CUT_AT, TRIGGER_MARGIN_FRACTION, bandOf, chooseCut, conversationTokens, gateCut, incomingEventTokens, incomingTokens, planningReserve, projectedConversationTokens, systemPart, validCutAt } from "./budget.js";
16
17
  import { getCurrentSystemMessage, isContextOverflow, normalizeContext } from "@earendil-works/pi-ai";
17
18
  import { calculateContextTokens, convertToLlm, estimateTokens, getAgentDir, shouldCompact, SettingsManager } from "@earendil-works/pi-coding-agent";
18
19
  import { Type } from "typebox";
@@ -62,15 +63,43 @@ export const refusalNotice = (message, factor) => message + "; shorten the input
62
63
  /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
63
64
  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.` +
64
65
  (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
65
- /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
66
66
  /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
67
67
  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. ` +
68
68
  `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. ` +
69
69
  "The unfinished response is saved in the session.";
70
70
  /** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
71
71
  export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
72
+ /** The act-now request's reply cap: above the largest real reply seen on mac-studio (18.6k tokens in 476 replies), well under the 32k-65k caps
73
+ * a thinking runaway fills. */
74
+ export const ACT_NOW_MAX_TOKENS = 20_480;
75
+ /** The act-now request, rewritten (Chat Completions payloads only): the lowest effort the server lists, top level (where vLLM-style servers
76
+ * read it) and in chat_template_kwargs if Pi sent one there, and an output cap of at most ACT_NOW_MAX_TOKENS. Undefined for any other request. */
77
+ export function actNowPayload(payload, effort) {
78
+ const body = payload;
79
+ const messages = body?.messages;
80
+ if (!Array.isArray(messages))
81
+ return undefined;
82
+ const last = messages.at(-1);
83
+ const text = typeof last?.content === "string" ? last.content
84
+ : Array.isArray(last?.content) ? last.content.map(part => part?.type === "text" ? String(part.text) : "").join("") : undefined;
85
+ if (last?.role !== "user" || text !== ACT_NOW)
86
+ return undefined;
87
+ const out = { ...body };
88
+ let cap;
89
+ for (const field of ["max_tokens", "max_completion_tokens"]) {
90
+ if (typeof out[field] === "number")
91
+ cap = out[field] = Math.min(out[field], ACT_NOW_MAX_TOKENS);
92
+ }
93
+ if (effort) {
94
+ out.reasoning_effort = effort;
95
+ const kwargs = out.chat_template_kwargs;
96
+ if (kwargs && typeof kwargs === "object" && "reasoning_effort" in kwargs)
97
+ out.chat_template_kwargs = { ...kwargs, reasoning_effort: effort };
98
+ }
99
+ return { payload: out, cap };
100
+ }
72
101
  /** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
73
- export const ACT_NOW_LIMIT = 2;
102
+ const ACT_NOW_LIMIT = 2;
74
103
  /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
75
104
  * or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
76
105
  export function actNowsInARow(branch) {
@@ -183,11 +212,6 @@ export async function installCompaction(pi, options = {}) {
183
212
  const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
184
213
  if (!validCutAt(cutAt))
185
214
  throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
186
- const hostAccess = () => {
187
- if (!active())
188
- throw new Error("Compaction host is inactive");
189
- options.assertAccess?.();
190
- };
191
215
  const view = (ctx, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
192
216
  const liveCut = new PendingCut();
193
217
  const recorder = new IncidentRecorder(options.diagnostics);
@@ -210,7 +234,7 @@ export async function installCompaction(pi, options = {}) {
210
234
  if (recorder.enabled) {
211
235
  try {
212
236
  const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
213
- recorder.capture("replay-input", "reconstruction-from-existing-native-history", { build: DIAGNOSTIC_BUILD, receiptId: proposalId, entries: filtered.entries, branchEntryIds: ctx.sessionManager.getBranch().map(e => e.id), header: ctx.sessionManager.getHeader(), contextWindow: ctx.model?.contextWindow, reserve, tokensBefore, retainCurrentInput, operatorManual, previousSummary }, filtered.partial || Boolean(options.recallPolicy?.readAttemptMarker));
237
+ recorder.capture("replay-input", "reconstruction-from-existing-native-history", { build: BUILD_ID, receiptId: proposalId, entries: filtered.entries, branchEntryIds: ctx.sessionManager.getBranch().map(e => e.id), header: ctx.sessionManager.getHeader(), contextWindow: ctx.model?.contextWindow, reserve, tokensBefore, retainCurrentInput, operatorManual, previousSummary }, filtered.partial || Boolean(options.recallPolicy?.readAttemptMarker));
214
238
  recorder.capture("proposal", "selected-draft-not-saved", attached);
215
239
  }
216
240
  catch {
@@ -359,6 +383,20 @@ export async function installCompaction(pi, options = {}) {
359
383
  if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel)
360
384
  run?.rearmLengthRetry();
361
385
  };
386
+ // The act-now request asks for a short act, so it goes out at the server's lowest effort with a smaller cap. The cap sent is kept: a stop
387
+ // at it is a full-cap stop, not a squeezed one.
388
+ let actNowCap;
389
+ pi.on("before_provider_request", async (event, ctx) => {
390
+ const model = ctx.model;
391
+ if (model?.api !== "openai-completions" || !actNowPayload(event.payload, undefined)) {
392
+ actNowCap = undefined;
393
+ return undefined;
394
+ }
395
+ await pendingCheck;
396
+ const rewritten = actNowPayload(event.payload, lowestEffort(serverEfforts.get(`${model.provider}/${model.id}`)));
397
+ actNowCap = rewritten.cap;
398
+ return rewritten.payload;
399
+ });
362
400
  // The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
363
401
  pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW)
364
402
  rearmLengthRetry(ctx); });
@@ -483,7 +521,7 @@ export async function installCompaction(pi, options = {}) {
483
521
  const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
484
522
  // The planner counts with the same function, except that it does not fail on a summary in another format: a cut can replace one
485
523
  // (an operator's /compact repairs a session whose saved summary is foreign). Identical to the strict one for this compactor's summaries.
486
- const plannerMeasureFor = (ctx) => Object.assign((messages) => measurableConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy), { messageTokens: (message) => conversationTokens(applyClips([message], clips())) });
524
+ const plannerMeasureFor = (ctx) => Object.assign((messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy), { messageTokens: (message) => conversationTokens(applyClips([message], clips())) });
487
525
  const hostMessages = (ctx) => options.hostMessages?.(ctx) ?? [];
488
526
  const toolShapes = (names) => {
489
527
  const selected = new Set(names);
@@ -612,7 +650,9 @@ export async function installCompaction(pi, options = {}) {
612
650
  const access = () => {
613
651
  if (failure())
614
652
  throw failure();
615
- hostAccess();
653
+ if (!active())
654
+ throw new Error("Compaction host is inactive");
655
+ options.assertAccess?.();
616
656
  };
617
657
  pi.on("input", async (event, ctx) => {
618
658
  if (!ctx.isIdle() || run?.phase === "starting")
@@ -1195,6 +1235,40 @@ export async function installCompaction(pi, options = {}) {
1195
1235
  markBoundary(entries);
1196
1236
  return { entries, continue: false };
1197
1237
  };
1238
+ // A retry's cut is an ordinary planned cut (summary with the action and file lists and kept results), shrunk until Pi's own clamp gives
1239
+ // the raised reply room, at most three times. Only when no such plan exists does the retry fall back to the deepest floor.
1240
+ const retryDecision = (ctx, asIs, host, pending) => {
1241
+ const saved = ctx.sessionManager.buildSessionProjection().messages, before = conversationTokens(projectContext(saved, ctx));
1242
+ const mandatory = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), asIs, ctx.getSystemPrompt()) + conversationTokens(host) + conversationTokens(pending);
1243
+ const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
1244
+ const { response, room } = limits(ctx), want = response - piMargin, band = decisionBand(ctx, room);
1245
+ let target = room;
1246
+ for (let attempt = 0; attempt < 4 && fits(mandatory, target, ctx); attempt++) {
1247
+ const targetBand = target === room ? band : target;
1248
+ const decision = chooseCut({ before, mandatory, room: target, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), opportunistic: false,
1249
+ unreduced: "Length-retry compaction did not reduce context within the estimated request budget",
1250
+ plan: (kind) => {
1251
+ const reserve = planReserve(kind, target, targetBand, mandatory, ctx);
1252
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
1253
+ protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
1254
+ if (!draft.compaction)
1255
+ return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
1256
+ const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
1257
+ assertNativeToolRounds(kept);
1258
+ return { draft: true, after: measureFor(ctx)(kept), compaction: draft.compaction, reserve, messages: kept };
1259
+ },
1260
+ });
1261
+ if (decision.kind !== "cut")
1262
+ return undefined;
1263
+ const check = requestClamp(projectedRequest(decision.plan.messages, ctx, host, pending, ctx.getSystemPrompt(), pi.getActiveTools(), true), ctx);
1264
+ if (check.cap === undefined)
1265
+ return undefined;
1266
+ if (check.leavesFloor && check.cap >= want)
1267
+ return decision;
1268
+ target = Math.floor(target * (check.estimate - (want - check.cap)) / check.estimate);
1269
+ }
1270
+ return undefined;
1271
+ };
1198
1272
  const retryLength = (event, ctx) => {
1199
1273
  // Exhausting the full per-request allowance is not evidence that input is too large.
1200
1274
  // Preserve the unfinished response; provider-native continuation owns this case.
@@ -1202,7 +1276,7 @@ export async function installCompaction(pi, options = {}) {
1202
1276
  if (event.message.role !== "assistant" || !ctx.model)
1203
1277
  return;
1204
1278
  const stoppedOutput = event.message.usage?.output;
1205
- if (stoppedOutput >= ctx.model.maxTokens) {
1279
+ if (stoppedOutput >= (actNowCap ?? ctx.model.maxTokens)) {
1206
1280
  return { entries: event.entries, continue: false };
1207
1281
  }
1208
1282
  // Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
@@ -1219,7 +1293,7 @@ export async function installCompaction(pi, options = {}) {
1219
1293
  const asIs = projectedRequest(preview.buildSessionProjection().messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), false);
1220
1294
  const asIsCheck = requestClamp(asIs, view);
1221
1295
  const previousClips = new Map(clips());
1222
- const decision = deepestDecision(view, false, true);
1296
+ const decision = retryDecision(view, asIs, hostInput, event.context.pendingMessages) ?? deepestDecision(view, false, true);
1223
1297
  const cut = decision.kind === "cut" ? {
1224
1298
  ...decision,
1225
1299
  messages: projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true),
@@ -1319,7 +1393,7 @@ export async function installCompaction(pi, options = {}) {
1319
1393
  };
1320
1394
  // A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
1321
1395
  // atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
1322
- const guardCut = (messages, tokens, system, ctx) => {
1396
+ const guardCut = (messages, tokens, ctx) => {
1323
1397
  const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
1324
1398
  const before = conversationTokens(source), mandatory = tokens - before;
1325
1399
  const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room);
@@ -1429,9 +1503,7 @@ export async function installCompaction(pi, options = {}) {
1429
1503
  return void fail(new CommitFault("Native tool-loop boundary cut was not saved in the session file"), ctx);
1430
1504
  }
1431
1505
  }
1432
- if (run) {
1433
- run.pendingBoundaryReceipts = [];
1434
- }
1506
+ run.pendingBoundaryReceipts = [];
1435
1507
  }
1436
1508
  // Pi commits these entries before the run settles.
1437
1509
  try {
@@ -1474,7 +1546,7 @@ export async function installCompaction(pi, options = {}) {
1474
1546
  const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
1475
1547
  piClamp && !requestClamp(messages, ctx).leavesFloor;
1476
1548
  if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1477
- const cut = guardCut(messages, tokens, system, ctx);
1549
+ const cut = guardCut(messages, tokens, ctx);
1478
1550
  messages = cut.messages;
1479
1551
  native = Boolean(cut.native);
1480
1552
  system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
@@ -12,6 +12,12 @@ export interface ServerModel {
12
12
  window?: number;
13
13
  efforts?: string[];
14
14
  }
15
+ /** The lowest ranked effort a server lists, or undefined. */
16
+ export declare const lowestEffort: (efforts: readonly string[] | undefined) => string | undefined;
17
+ /** The efforts each provider/model's server listed at this process's check; the act-now request reads them. */
18
+ export declare const serverEfforts: globalThis.Map<string, string[]>;
19
+ /** This process's check while it runs; the act-now request waits for it rather than go out without the efforts. */
20
+ export declare let pendingCheck: Promise<void> | undefined;
15
21
  export declare function serverModel(body: unknown, id: string): ServerModel | undefined;
16
22
  export interface Finding {
17
23
  kind: "window" | "thinking";
@@ -9,6 +9,14 @@ import { join } from "node:path";
9
9
  export const CONFIG_CHECK_ENTRY = "pi-tuck-config-check";
10
10
  /** Pi's thinking levels that a server can list; "off" is never a server effort. */
11
11
  const LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"];
12
+ /** Server efforts from low to high, for the names pi-tuck can rank; "none" and "off" turn thinking off and are never picked. */
13
+ const EFFORT_RANK = ["xlow", "minimal", "low", "medium", "xmedium", "high", "xhigh", "max"];
14
+ /** The lowest ranked effort a server lists, or undefined. */
15
+ export const lowestEffort = (efforts) => EFFORT_RANK.find(e => efforts?.includes(e));
16
+ /** The efforts each provider/model's server listed at this process's check; the act-now request reads them. */
17
+ export const serverEfforts = new Map();
18
+ /** This process's check while it runs; the act-now request waits for it rather than go out without the efforts. */
19
+ export let pendingCheck;
12
20
  export function serverModel(body, id) {
13
21
  const data = body?.data;
14
22
  const entry = Array.isArray(data) ? data.find(m => m?.id === id) : undefined;
@@ -157,7 +165,10 @@ export async function checkModel(pi, ctx, deps) {
157
165
  const server = serverModel(await response.json(), model.id);
158
166
  if (!server)
159
167
  return;
160
- const ref = `${model.provider}/${model.id}`, no = declined(settingsPath)[ref] ?? {};
168
+ const ref = `${model.provider}/${model.id}`;
169
+ if (server.efforts)
170
+ serverEfforts.set(ref, server.efforts);
171
+ const no = declined(settingsPath)[ref] ?? {};
161
172
  const open = findings(model, server).filter(f => no[f.kind] !== f.server);
162
173
  if (!open.length)
163
174
  return;
@@ -191,6 +202,6 @@ export function installConfigCheck(pi, deps) {
191
202
  if (done)
192
203
  return;
193
204
  done = true;
194
- void checkModel(pi, ctx, deps);
205
+ pendingCheck = checkModel(pi, ctx, deps).finally(() => { pendingCheck = undefined; });
195
206
  });
196
207
  }
@@ -1,11 +1,5 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
2
  import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
- export declare const MAX_OUTPUT_TAIL_LINES = 3;
4
- export declare const MAX_OUTPUT_TAIL_CHARACTERS = 200;
5
- export declare const MAX_DEFINITION_LINES = 40;
6
- export declare const MAX_DEFINITION_CHARACTERS = 800;
7
- /** Mechanical line matches only; no language detection or inferred symbols. */
8
- export declare const DEFINITION_PATTERNS: readonly RegExp[];
9
3
  /** The last nonempty physical lines, with a leading marker whenever earlier text was cut.
10
4
  * The marker and embedded newlines spend the same 200-character allowance. */
11
5
  export declare function outputTail(output: string): string | undefined;
@@ -3,12 +3,12 @@ import { isTextOnly, textOf } from "./tuck/core/content.js";
3
3
  import { extractPath } from "./tuck/core/tool-args.js";
4
4
  import { readableContentParts } from "./tuck/core/readable-content.js";
5
5
  import { MAX_RECALL_CHARACTERS } from "./recall.js";
6
- export const MAX_OUTPUT_TAIL_LINES = 3;
7
- export const MAX_OUTPUT_TAIL_CHARACTERS = 200;
8
- export const MAX_DEFINITION_LINES = 40;
9
- export const MAX_DEFINITION_CHARACTERS = 800;
6
+ const MAX_OUTPUT_TAIL_LINES = 3;
7
+ const MAX_OUTPUT_TAIL_CHARACTERS = 200;
8
+ const MAX_DEFINITION_LINES = 40;
9
+ const MAX_DEFINITION_CHARACTERS = 800;
10
10
  /** Mechanical line matches only; no language detection or inferred symbols. */
11
- export const DEFINITION_PATTERNS = [
11
+ const DEFINITION_PATTERNS = [
12
12
  /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:func|def|function)\b/u,
13
13
  /^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:type|struct|interface|class)\b/u,
14
14
  /^\s*export\s+(?:const|let)\b/u,
@@ -1,23 +1,23 @@
1
1
  import { SessionManager } from '@earendil-works/pi-coding-agent';
2
2
  import { tuck, tuckObservedDraft } from './tuck.js';
3
- import { measurableConversationTokens } from './budget.js';
4
- import { DIAGNOSTIC_BUILD } from './diagnostics.js';
3
+ import { projectedConversationTokens } from './budget.js';
4
+ import { BUILD_ID } from './build-id.js';
5
5
  export function inspectIncident(records) {
6
6
  const inputs = records.filter(r => r.kind === 'replay-input');
7
7
  const results = inputs.map(record => {
8
8
  const i = record.data;
9
- if (record.partial || i.build !== DIAGNOSTIC_BUILD || !i.entries || !i.header || !Array.isArray(i.branchEntryIds) || i.branchEntryIds.some(id => typeof id !== 'string') || !Number.isSafeInteger(i.contextWindow) || !Number.isSafeInteger(i.reserve) || !Number.isSafeInteger(i.tokensBefore))
9
+ if (record.partial || i.build !== BUILD_ID || !i.entries || !i.header || !Array.isArray(i.branchEntryIds) || i.branchEntryIds.some(id => typeof id !== 'string') || !Number.isSafeInteger(i.contextWindow) || !Number.isSafeInteger(i.reserve) || !Number.isSafeInteger(i.tokensBefore))
10
10
  return { mode: 'partial-inspection', notice: 'Missing/redacted inputs or nonmatching build; no deterministic replay claim.' };
11
11
  const manager = SessionManager.inMemory('/offline-compaction-replay', undefined, [i.header, ...i.entries]);
12
- if (i.branchEntryIds?.length)
12
+ if (i.branchEntryIds.length)
13
13
  manager.branch(i.branchEntryIds.at(-1));
14
14
  const ctx = { sessionManager: manager, cwd: '/offline-compaction-replay', model: { contextWindow: i.contextWindow } };
15
- const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore, previousSummary: i.previousSummary }, ctx, i.reserve, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
15
+ const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore, previousSummary: i.previousSummary }, ctx, i.reserve, messages => projectedConversationTokens(messages, ctx), {}, i.retainCurrentInput);
16
16
  const proposal = records.find(r => r.kind === 'proposal' && r.data?.details?.diagnosticReceipt?.id === i.receiptId)?.data;
17
17
  const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
18
18
  return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference, meaning preservation, persistence or transmission claim.' };
19
19
  });
20
- return { build: DIAGNOSTIC_BUILD, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
20
+ return { build: BUILD_ID, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
21
21
  }
22
22
  export function readableIncident(records) {
23
23
  return '# Compaction incident\n\n' + JSON.stringify(inspectIncident(records), null, 2) + '\n\n' + records.map(r => `## ${r.kind} (${r.scope})${r.partial ? ' — PARTIAL' : ''}\n\n${JSON.stringify(r.data, null, 2)}`).join('\n\n');
@@ -1,6 +1,5 @@
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 = "b7162b2a60e8357e1abeb6decc9b739a75077207592f169e6db105b5e2647e90";
4
3
  export interface Receipt {
5
4
  id: string;
6
5
  build: string;
@@ -6,10 +6,9 @@ import { join, resolve, relative, isAbsolute, dirname, basename } from 'node:pat
6
6
  import { homedir } from 'node:os';
7
7
  import { createRecall } from './recall.js';
8
8
  import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
9
- export const DIAGNOSTIC_BUILD = BUILD_ID;
10
9
  export function attachReceipt(draft, reason, reserveTokens, contextWindow, resolved = {}) {
11
10
  const details = draft.details && typeof draft.details === 'object' ? draft.details : {};
12
- const receipt = { id: randomUUID(), build: DIAGNOSTIC_BUILD, reason, selectedView: typeof details.view === 'string' ? details.view : 'deterministic-selected-draft', boundary: draft.firstKeptEntryId, settings: { draftReservedTokens: reserveTokens, contextWindow, ...resolved }, before: { value: draft.tokensBefore, unit: 'estimated-input-tokens', scope: reason === 'tool-loop' || reason === 'run-end' || reason === 'prompt' ? 'public-conversation' : 'native-preparation' }, after: { value: typeof details.tokensAfter === 'number' ? details.tokensAfter : null, unit: 'estimated-input-tokens', scope: 'draft-preview' } };
11
+ const receipt = { id: randomUUID(), build: BUILD_ID, reason, selectedView: typeof details.view === 'string' ? details.view : 'deterministic-selected-draft', boundary: draft.firstKeptEntryId, settings: { draftReservedTokens: reserveTokens, contextWindow, ...resolved }, before: { value: draft.tokensBefore, unit: 'estimated-input-tokens', scope: reason === 'tool-loop' || reason === 'run-end' || reason === 'prompt' ? 'public-conversation' : 'native-preparation' }, after: { value: typeof details.tokensAfter === 'number' ? details.tokensAfter : null, unit: 'estimated-input-tokens', scope: 'draft-preview' } };
13
12
  return { ...draft, details: { ...details, diagnosticReceipt: receipt } };
14
13
  }
15
14
  export function receiptId(entry) {
@@ -154,7 +153,7 @@ export class IncidentRecorder {
154
153
  this.path = join(this.directory, 'tuck-incident-' + this.id + '.jsonl');
155
154
  this.timer = setTimeout(() => this.stop(this.sawCut ? 'duration-exhausted' : 'no-cut-expired'), this.options.durationMs);
156
155
  this.timer.unref();
157
- this.capture('start', 'operator-session-control', { id: this.id, build: DIAGNOSTIC_BUILD, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. Secrets without recognizable patterns may remain.' });
156
+ this.capture('start', 'operator-session-control', { id: this.id, build: BUILD_ID, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. Secrets without recognizable patterns may remain.' });
158
157
  }
159
158
  measureInline(operation) { if (!this.enabled)
160
159
  return operation(); const started = performance.now(); try {
@@ -49,8 +49,6 @@ export type HistoryAroundPage = {
49
49
  omitted: number;
50
50
  };
51
51
  };
52
- /** Factual locators only; no interpretation of pixels or claim of current truth. */
53
- export declare function imageSource(entry: SessionEntry): ImageSource | undefined;
54
52
  /** Explicit one-block delivery from the supplied branch; no path reads or resize. */
55
53
  export declare function historyImage(branch: readonly SessionEntry[], input: ImageRead, policy?: RecallPolicy): {
56
54
  content: (TextContent | ImageContent)[];
@@ -14,7 +14,7 @@ function images(entry) {
14
14
  return entry.message.content.filter((block) => block.type === "image");
15
15
  }
16
16
  /** Factual locators only; no interpretation of pixels or claim of current truth. */
17
- export function imageSource(entry) {
17
+ function imageSource(entry) {
18
18
  const imageCount = images(entry).length;
19
19
  if (!imageCount || entry.type !== "message" || (entry.message.role !== "user" && entry.message.role !== "toolResult"))
20
20
  return;
@@ -2,8 +2,6 @@ import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agen
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
4
  export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, exclude?: ReadonlySet<string>): TranscriptRecord[];
5
- /** At most this many outputs, newest first, holding at most this much output text in all; the rest is cut with a pointer. */
6
- export declare const MAX_PROMPT_OUTPUTS = 4, MAX_PROMPT_OUTPUT_CHARACTERS = 8000;
7
5
  /** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
8
6
  * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
9
7
  export declare function promptOutputCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
@@ -67,7 +67,7 @@ export function keptReadCandidates(entries, indices, resolvable, exclude = new S
67
67
  return records;
68
68
  }
69
69
  /** At most this many outputs, newest first, holding at most this much output text in all; the rest is cut with a pointer. */
70
- export const MAX_PROMPT_OUTPUTS = 4, MAX_PROMPT_OUTPUT_CHARACTERS = 8000;
70
+ const MAX_PROMPT_OUTPUTS = 4, MAX_PROMPT_OUTPUT_CHARACTERS = 8000;
71
71
  const words = (text) => text.replace(/\s+/gu, " ").trim();
72
72
  /** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
73
73
  * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
@@ -1,13 +1,10 @@
1
1
  import type { ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';
2
2
  import { type RecallPolicy } from './recall.js';
3
- /** Native branch edits supply exclusion; original global indices supply provenance. */
4
- export declare function omittedSourceIndices(entries: readonly SessionEntry[], branch: readonly SessionEntry[]): ReadonlySet<number>;
5
3
  /** Preserve surviving record bytes/order, and the summary's format (a v1 summary stays v1). No text matching or inference about meaning. */
6
4
  export declare function filterOmittedSummary(summary: string, omitted: ReadonlySet<number>, sources?: readonly SessionEntry[], rangeOmitted?: ReadonlySet<number>): string;
7
- /** Custom quotes carry native entry identity; no text matching or legacy fallback. */
8
- export declare function filterCustomQuotes(summary: string, entries: readonly SessionEntry[], branch: readonly SessionEntry[], policy?: RecallPolicy): string;
9
5
  type ProjectedMessages = ReturnType<ExtensionContext['sessionManager']['buildSessionProjection']>['messages'];
6
+ /** The saved conversation as this compactor delivers it: native omissions and ineligible custom quotes removed from its own summaries. A
7
+ * summary of another format (Pi's own /compact before pi-tuck was loaded, an empty draft) cannot be filtered and goes out as it is, as
8
+ * native Pi sends it; the next pi-tuck cut replaces it. Failing closed on it left such a session unable to send any prompt (issue #1). */
10
9
  export declare function projectedMessages(messages: ProjectedMessages, ctx: ExtensionContext, policy?: RecallPolicy): ProjectedMessages;
11
- /** The planner's name for the same projection (kept for its callers). */
12
- export declare function measurableMessages(messages: ProjectedMessages, ctx: ExtensionContext, policy?: RecallPolicy): ProjectedMessages;
13
10
  export {};
@@ -4,7 +4,7 @@ import { textOf } from "./tuck/core/content.js";
4
4
  import { isDiscardedResponse } from "./protocol.js";
5
5
  import { createRecall } from './recall.js';
6
6
  /** Native branch edits supply exclusion; original global indices supply provenance. */
7
- export function omittedSourceIndices(entries, branch) {
7
+ function omittedSourceIndices(entries, branch) {
8
8
  const edits = new Set();
9
9
  for (const entry of branch)
10
10
  if (entry.type === 'context_edit') {
@@ -94,7 +94,7 @@ export function filterOmittedSummary(summary, omitted, sources, rangeOmitted = o
94
94
  return transcriptHeader(version) + '\n' + retained.join('\n') + closing;
95
95
  }
96
96
  /** Custom quotes carry native entry identity; no text matching or legacy fallback. */
97
- export function filterCustomQuotes(summary, entries, branch, policy = {}) {
97
+ function filterCustomQuotes(summary, entries, branch, policy = {}) {
98
98
  const split = splitSummary(summary);
99
99
  if (!split)
100
100
  throw new Error('Cannot resolve custom sources in an unsupported compaction summary');
@@ -131,7 +131,7 @@ export function filterCustomQuotes(summary, entries, branch, policy = {}) {
131
131
  /** The saved conversation as this compactor delivers it: native omissions and ineligible custom quotes removed from its own summaries. A
132
132
  * summary of another format (Pi's own /compact before pi-tuck was loaded, an empty draft) cannot be filtered and goes out as it is, as
133
133
  * native Pi sends it; the next pi-tuck cut replaces it. Failing closed on it left such a session unable to send any prompt (issue #1). */
134
- function projectMessages(messages, ctx, policy) {
134
+ export function projectedMessages(messages, ctx, policy) {
135
135
  const entries = ctx.sessionManager.getEntries(), branch = ctx.sessionManager.getBranch();
136
136
  const omitted = omittedSourceIndices(entries, branch);
137
137
  const lastCut = branch.findLastIndex(entry => entry.type === 'compaction');
@@ -149,10 +149,3 @@ function projectMessages(messages, ctx, policy) {
149
149
  return messages.map(message => message.role === 'compactionSummary' && splitSummary(message.summary) !== undefined
150
150
  ? { ...message, summary: filterCustomQuotes(filterOmittedSummary(message.summary, omitted, entries, cut?.type === 'compaction' && cut.summary === message.summary ? afterCut : new Set()), entries, branch, policy) } : message);
151
151
  }
152
- export function projectedMessages(messages, ctx, policy) {
153
- return projectMessages(messages, ctx, policy);
154
- }
155
- /** The planner's name for the same projection (kept for its callers). */
156
- export function measurableMessages(messages, ctx, policy) {
157
- return projectMessages(messages, ctx, policy);
158
- }
@@ -69,7 +69,7 @@ export function createRecall(policy = {}) {
69
69
  else if (entry.type === "custom_message")
70
70
  value = { role: "custom", text: textContent(entry.content) };
71
71
  else if (entry.type === "message") {
72
- const message = entry.message;
72
+ const message = entry.message, link = links?.get(entry.id);
73
73
  if (message.role === "user" || message.role === "assistant" || message.role === "custom")
74
74
  value = { role: message.role, text: textContent(message.content, message.role === "assistant"),
75
75
  ...(message.role === "assistant" && message.stopReason !== undefined ? { stopReason: message.stopReason } : {}) };
@@ -81,7 +81,7 @@ export function createRecall(policy = {}) {
81
81
  toolName: message.toolName.slice(0, MAX_TOOL_METADATA),
82
82
  toolCallId: message.toolCallId.slice(0, MAX_TOOL_METADATA),
83
83
  isError: message.isError,
84
- ...(links?.has(entry.id) ? { producerRead: { entryId: links.get(entry.id).entryId, offset: links.get(entry.id).offset, limit: links.get(entry.id).limit }, producerTime: links.get(entry.id).sourceTime } : {}),
84
+ ...(link ? { producerRead: { entryId: link.entryId, offset: link.offset, limit: link.limit }, producerTime: link.sourceTime } : {}),
85
85
  ...(message.toolName.length > MAX_TOOL_METADATA || message.toolCallId.length > MAX_TOOL_METADATA
86
86
  ? { metadataTruncated: true } : {}),
87
87
  };