@juicesharp/rpiv-btw 2.1.0 → 2.3.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/btw-budget.ts ADDED
@@ -0,0 +1,403 @@
1
+ /**
2
+ * Context-budget engine for /btw: bounds how much prior side-question history
3
+ * and cloned-primary-branch content ride into a fresh side call so the
4
+ * assembled context stays within the model's window.
5
+ *
6
+ * Pure host-primitive consumers — no ExtensionContext/globalThis access. The
7
+ * caller reads session state and passes plain data in; results are computed
8
+ * value-for-value with reference-identical message elements on the fast path
9
+ * (preserves byte-identical prompt prefix across /btw invocations → cache parity).
10
+ */
11
+
12
+ import type { Api, Message, Model, UserMessage } from "@earendil-works/pi-ai";
13
+ import {
14
+ calculateContextTokens,
15
+ convertToLlm,
16
+ estimateTokens,
17
+ findCutPoint,
18
+ getLastAssistantUsage,
19
+ type SessionEntry,
20
+ sessionEntryToContextMessages,
21
+ } from "@earendil-works/pi-coding-agent";
22
+ import type { BtwTurn } from "./btw.js";
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // Budget constants — the engine's tuning surface. Defined in this leaf module so
26
+ // the btw.ts ↔ btw-budget.ts dependency is type-only at runtime (btw.ts re-exports
27
+ // them for the package's public surface).
28
+ // ---------------------------------------------------------------------------
29
+ export const BTW_HISTORY_TOKEN_BUDGET = 8192; // cap /btw history (newest-suffix of BtwTurn[])
30
+ export const BTW_CONTEXT_RESERVE = 16384; // matches host DEFAULT_COMPACTION_SETTINGS.reserveTokens
31
+ export const BTW_NO_ANCHOR_SAFETY_FACTOR = 1.2; // no-anchor fallback overcount, applied HERE (host does not)
32
+
33
+ /**
34
+ * Result of {@link capHistory}: the newest suffix of `/btw` turns admitted into
35
+ * a fresh side-call context, plus accounting surfaced to the trim-notice overlay.
36
+ */
37
+ export interface CappedHistory {
38
+ /** Newest-suffix turns, reference-identical to the input `history` elements. */
39
+ admitted: BtwTurn[];
40
+ /** Sum of `estimateTokens` over BOTH messages of every admitted turn (chars/4 each). */
41
+ estimate: number;
42
+ /** Older turns dropped to stay within `budget` (=== `history.length - admitted.length`). */
43
+ droppedTurns: number;
44
+ }
45
+
46
+ /**
47
+ * Pure maximal-suffix walk over `/btw` history.
48
+ *
49
+ * Admits the MAXIMAL newest suffix of whole turns (user+assistant, atomic) whose
50
+ * summed `estimateTokens` cost is `≤ budget`. Newer turns are never sacrificed
51
+ * to admit older ones: the walk extends greedily from the newest backward, and
52
+ * the first older turn that would overflow breaks it.
53
+ *
54
+ * Floor guarantee: `history.length >= 1` ⇒ `admitted.length >= 1`. If the newest
55
+ * turn ALONE exceeds `budget`, it is still admitted (a side call carries no
56
+ * history otherwise) and `estimate` carries its over-budget actual cost — never
57
+ * clamped to the budget.
58
+ *
59
+ * `admitted` is `history.slice(k)`: reference-identical elements, no copy/mutate.
60
+ * The caller (the build step) owns reading the session history; this function
61
+ * touches no `ExtensionContext`/`globalThis`/`getSessionHistory`.
62
+ */
63
+ export function capHistory(history: BtwTurn[], budget = BTW_HISTORY_TOKEN_BUDGET): CappedHistory {
64
+ if (history.length === 0) return { admitted: [], estimate: 0, droppedTurns: 0 };
65
+
66
+ // Seed with the newest turn — this IS the floor guarantee: even an over-budget
67
+ // newest turn is admitted (estimate unclamped) so the side call always carries it.
68
+ let estimate =
69
+ estimateTokens(history[history.length - 1].userMessage) +
70
+ estimateTokens(history[history.length - 1].assistantMessage);
71
+ let k = history.length - 1;
72
+
73
+ // Greedily extend backward over older turns while the running sum stays within budget.
74
+ // All turns have positive cost, so the first overflow breaks the maximal suffix.
75
+ for (let i = history.length - 2; i >= 0; i--) {
76
+ const cost = estimateTokens(history[i].userMessage) + estimateTokens(history[i].assistantMessage);
77
+ if (estimate + cost > budget) break;
78
+ estimate += cost;
79
+ k = i;
80
+ }
81
+
82
+ return {
83
+ admitted: history.slice(k),
84
+ estimate,
85
+ droppedTurns: k,
86
+ };
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // Branch-fit engine — pure; no ctx/globalThis access.
91
+ // Value-imports the six host primitives (no re-implementation). Deliberately does
92
+ // NOT reuse the host's backward findTurnStartIndex for the forward turn-start scan
93
+ // (the host scans backward for compaction's summarize-prefix model; /btw cannot
94
+ // summarize, so it drops the prefix and keeps a suffix that opens on a turn-start).
95
+ // ---------------------------------------------------------------------------
96
+
97
+ export interface FitBranchInput {
98
+ /** Raw session entries from the snapshot (findCutPoint/getLastAssistantUsage contract). */
99
+ entries: SessionEntry[];
100
+ /** Cached converted branch messages (type==="message"-filtered via branchToMessages).
101
+ * Returned by reference on the fast path (byte-identical prefix). */
102
+ messages: Message[];
103
+ model: Model<Api>;
104
+ systemPrompt: string;
105
+ question: UserMessage;
106
+ /** capHistory estimate over admitted /btw turns (subtracted from the window). */
107
+ admittedEstimate: number;
108
+ /** Retry override: when set, skip the window formula and trim/stub to this
109
+ * many branch tokens directly; the cached snapshot is NOT re-read. */
110
+ keepBudget?: number;
111
+ }
112
+
113
+ export interface FitBranchResult {
114
+ messages: Message[];
115
+ branchWasTrimmed: boolean;
116
+ stubbed: boolean;
117
+ /** Budget fitBranch applied: window-computed on the default path, the passed-in
118
+ * override on the retry path. Populated on BOTH paths so buildBtwMessages surfaces
119
+ * it for the overflow-retry caller's Math.floor(built.keepBudget / 2). */
120
+ keepBudget: number;
121
+ }
122
+
123
+ // Stub/truncation literals (research-grounded). BTW_STUB_TEXT is exported for the
124
+ // stub-content test assertion; BTW_TRUNCATE_MARKER_FMT stays private (test asserts the marker substring).
125
+ export const BTW_STUB_TEXT = "[tool result elided by /btw to fit the context window]";
126
+ const BTW_TRUNCATE_MARKER_FMT = (truncatedChars: number): string => `[... ${truncatedChars} characters truncated]`;
127
+
128
+ // Turn-start discriminator (message-level, NOT the host's entry-level isTurnStartEntry
129
+ // which excludes compaction). branchSummary/compactionSummary are included so a head
130
+ // compaction/branch summary can open the kept suffix after a cut (hybrid filter).
131
+ const TURN_START_ROLES: ReadonlySet<string> = new Set([
132
+ "user",
133
+ "bashExecution",
134
+ "custom",
135
+ "branchSummary",
136
+ "compactionSummary",
137
+ ]);
138
+
139
+ /** chars/4 heuristic mirror of estimateTokens for the system-prompt STRING (estimateTokens
140
+ * takes a message, not a raw string). Math.ceil matches the host's conservative direction. */
141
+ function estimateTextTokens(text: string): number {
142
+ return Math.ceil(text.length / 4);
143
+ }
144
+
145
+ /** Skip guard: the window is usable only when the reserve fits. */
146
+ function isBudgetable(model: Model<Api>): boolean {
147
+ return model.contextWindow > 0 && model.contextWindow > model.maxTokens + BTW_CONTEXT_RESERVE;
148
+ }
149
+
150
+ /** Sum estimateTokens over an LLM message array (real host primitive, chars/4 per message). */
151
+ function estimateMessagesTokens(messages: Message[]): number {
152
+ let sum = 0;
153
+ for (const m of messages) sum += estimateTokens(m);
154
+ return sum;
155
+ }
156
+
157
+ /** Branch-usage estimate. Anchor = getLastAssistantUsage → calculateContextTokens
158
+ * (safe overcount: includes the main agent's system/tools that /btw omits) PLUS
159
+ * estimateTokens over every context message from entries AFTER the anchor — turns the
160
+ * provider has not metered (the user's latest turn, tool traffic behind an
161
+ * aborted/error assistant) still occupy the window and must count toward it.
162
+ * No anchor → sum(estimateTokens) × BTW_NO_ANCHOR_SAFETY_FACTOR (host applies no factor;
163
+ * btw-budget applies 1.2 itself). */
164
+ function estimateBranchTokens(entries: SessionEntry[]): number {
165
+ const usage = getLastAssistantUsage(entries);
166
+ if (usage) {
167
+ // Locate the anchor entry by Usage-object identity: getLastAssistantUsage returns
168
+ // the stored reference, so identity finds the anchor without re-implementing the
169
+ // host's validity predicate (skip aborted/error/all-zero). Walk newest-first,
170
+ // summing estimates until the anchor — those are exactly the post-anchor entries.
171
+ let tail = 0;
172
+ let anchorFound = false;
173
+ for (let i = entries.length - 1; i >= 0; i--) {
174
+ const e = entries[i];
175
+ if (e.type === "message" && e.message.role === "assistant" && e.message.usage === usage) {
176
+ anchorFound = true;
177
+ break;
178
+ }
179
+ for (const m of sessionEntryToContextMessages(e)) tail += estimateTokens(m);
180
+ }
181
+ // Identity miss (a host returning a derived Usage object) would have made `tail`
182
+ // span the whole branch and double-count the anchored prefix — drop it instead.
183
+ return calculateContextTokens(usage) + (anchorFound ? tail : 0);
184
+ }
185
+ // No-anchor fallback: sum estimateTokens over every context-visible AgentMessage the
186
+ // entries produce (estimateTokens accepts AgentMessage, so no cast is needed), × 1.2.
187
+ let sum = 0;
188
+ for (const e of entries) {
189
+ for (const m of sessionEntryToContextMessages(e)) sum += estimateTokens(m);
190
+ }
191
+ return Math.ceil(sum * BTW_NO_ANCHOR_SAFETY_FACTOR);
192
+ }
193
+
194
+ /** Turn-start test on a raw entry, via the exported message conversion (message-level
195
+ * discriminator — includes compaction/branch summaries). */
196
+ function isTurnStartEntry(entry: SessionEntry): boolean {
197
+ return sessionEntryToContextMessages(entry).some((m) => TURN_START_ROLES.has(m.role));
198
+ }
199
+
200
+ /** Forward scan from `fromIndex` to the first turn-start entry at or after it. Returns
201
+ * the index, or -1 if none exists (caller falls back to stubbing). Scanning forward
202
+ * past a mid-turn assistant also skips its trailing toolResults → atomicity:
203
+ * no toolCall without its toolResult and vice versa. */
204
+ function forwardScanToTurnStart(entries: SessionEntry[], fromIndex: number): number {
205
+ for (let i = fromIndex; i < entries.length; i++) {
206
+ if (isTurnStartEntry(entries[i])) return i;
207
+ }
208
+ return -1;
209
+ }
210
+
211
+ /** Trim: findCutPoint over RAW entries (its contract), then a FORWARD scan to a
212
+ * turn-start (NOT the host's backward findTurnStartIndex), then unfiltered conversion so
213
+ * a head compaction/branch summary survives (hybrid filter). Returns {messages:null} when
214
+ * no valid cut (firstKeptEntryIndex<=0) or no turn-start exists — caller stubs the full cache. */
215
+ function trimBranch(entries: SessionEntry[], keepRecentTokens: number): { messages: Message[] | null } {
216
+ const cut = findCutPoint(entries, 0, entries.length, keepRecentTokens);
217
+ if (cut.firstKeptEntryIndex <= 0) return { messages: null }; // no valid cut → stub the cache
218
+ const startIdx = forwardScanToTurnStart(entries, cut.firstKeptEntryIndex);
219
+ if (startIdx < 0) return { messages: null }; // no turn-start in the kept suffix → stub the cache
220
+ const keptEntries = entries.slice(startIdx);
221
+ // Hybrid filter: after a cut, UNFILTERED sessionEntryToContextMessages (the sibling
222
+ // conversion seam — shares convertToLlm with branchToMessages, no duplication) so a
223
+ // head compaction/branch summary survives, matching the main agent's post-compact context.
224
+ const trimmed = convertToLlm(keptEntries.flatMap((e) => sessionEntryToContextMessages(e)));
225
+ return { messages: trimmed };
226
+ }
227
+
228
+ /** Phase 1 of {@link stubToFit}: oldest-first toolResult stubbing. Operates in-place
229
+ * on `result` (does NOT copy) — re-estimates before each slot via the termination guard
230
+ * and replaces over-budget `msg.role === "toolResult"` slots with the placeholder,
231
+ * preserving toolCallId/toolName/isError via spread (the paired ToolCall in the prior
232
+ * assistant stays). Returns `true` iff at least one slot was stubbed. */
233
+ function stubToolResultsToFit(result: Message[], budget: number): boolean {
234
+ let stubbed = false;
235
+ // Stub toolResult content oldest-first with the placeholder (preserves
236
+ // toolCallId/toolName/isError via spread; the paired ToolCall in the prior assistant stays).
237
+ for (let i = 0; i < result.length; i++) {
238
+ if (estimateMessagesTokens(result) <= budget) break;
239
+ const msg = result[i];
240
+ if (msg.role === "toolResult") {
241
+ result[i] = { ...msg, content: [{ type: "text", text: BTW_STUB_TEXT }] };
242
+ stubbed = true;
243
+ }
244
+ }
245
+ return stubbed;
246
+ }
247
+
248
+ /** Phase 2 of {@link stubToFit}: terminal truncation toward the token gap. Operates in-place
249
+ * on `result` (does NOT copy). One block per iteration, re-estimated each pass; a pass that
250
+ * fails to shrink the estimate breaks the loop — the truncation marker keeps every rewritten
251
+ * block at a floor length, so a budget below that floor (e.g. negative) would otherwise
252
+ * rewrite the same block forever; `priorEstimate` is seeded at +∞ so the first pass always
253
+ * proceeds. Returns `true` iff at least one block was truncated. */
254
+ function truncateToFit(result: Message[], budget: number): boolean {
255
+ let stubbed = false;
256
+ // Terminal fallback: truncate the largest text block toward the token gap
257
+ // (chars ≈ tokens×4, the inverse of estimateTokens' chars/4) with a marker. One block per
258
+ // iteration; re-estimate each pass. A pass that fails to shrink the estimate breaks the
259
+ // loop: the truncation marker keeps every rewritten block at a floor length, so a budget
260
+ // below that floor (e.g. negative) would otherwise rewrite the same block forever.
261
+ let priorEstimate = Number.POSITIVE_INFINITY;
262
+ while (estimateMessagesTokens(result) > budget) {
263
+ const estimate = estimateMessagesTokens(result);
264
+ if (estimate >= priorEstimate) break; // no progress — budget below the marker floor
265
+ priorEstimate = estimate;
266
+ const overTokens = estimate - budget;
267
+ const removeChars = Math.max(1, Math.ceil(overTokens * 4));
268
+
269
+ // Locate the largest text content block (string content OR a {type:"text"} part).
270
+ let target = { mi: -1, ci: -1, len: 0, isString: false };
271
+ for (let i = 0; i < result.length; i++) {
272
+ const content = result[i].content;
273
+ if (typeof content === "string") {
274
+ if (content.length > target.len) target = { mi: i, ci: -1, len: content.length, isString: true };
275
+ continue;
276
+ }
277
+ if (Array.isArray(content)) {
278
+ for (let j = 0; j < content.length; j++) {
279
+ const part = content[j];
280
+ if (part && part.type === "text" && part.text.length > target.len) {
281
+ target = { mi: i, ci: j, len: part.text.length, isString: false };
282
+ }
283
+ }
284
+ }
285
+ }
286
+ if (target.mi < 0 || target.len === 0) break; // nothing left to truncate — minimal result
287
+
288
+ // Reserve room for the marker itself so the rewritten block lands at ~(len - removeChars)
289
+ // chars total; without this the marker's own length leaks back into the estimate.
290
+ const markerReserve = BTW_TRUNCATE_MARKER_FMT(removeChars).length;
291
+ const keepChars = Math.max(0, target.len - removeChars - markerReserve);
292
+ const truncatedChars = target.len - keepChars;
293
+ const marker = BTW_TRUNCATE_MARKER_FMT(truncatedChars);
294
+ const msg = result[target.mi];
295
+ // Rebuild with role narrowing so each spread yields a valid Message variant
296
+ // (Message is a discriminated union — spreading the union and overriding `content`
297
+ // directly does not typecheck). Top-level branches are pure msg.role checks so
298
+ // narrowing flows into each arm; the user arm narrows string-vs-array content.
299
+ if (msg.role === "user") {
300
+ if (typeof msg.content === "string") {
301
+ result[target.mi] = { ...msg, content: `${msg.content.slice(0, keepChars)}${marker}` };
302
+ } else {
303
+ const content = [...msg.content];
304
+ const part = content[target.ci];
305
+ if (part.type === "text") {
306
+ content[target.ci] = { ...part, text: `${part.text.slice(0, keepChars)}${marker}` };
307
+ result[target.mi] = { ...msg, content };
308
+ }
309
+ }
310
+ } else if (msg.role === "assistant") {
311
+ const content = [...msg.content];
312
+ const part = content[target.ci];
313
+ if (part.type === "text") {
314
+ content[target.ci] = { ...part, text: `${part.text.slice(0, keepChars)}${marker}` };
315
+ result[target.mi] = { ...msg, content };
316
+ }
317
+ } else {
318
+ // toolResult (msg narrowed to ToolResultMessage)
319
+ const content = [...msg.content];
320
+ const part = content[target.ci];
321
+ if (part.type === "text") {
322
+ content[target.ci] = { ...part, text: `${part.text.slice(0, keepChars)}${marker}` };
323
+ result[target.mi] = { ...msg, content };
324
+ }
325
+ }
326
+ stubbed = true;
327
+ }
328
+ return stubbed;
329
+ }
330
+
331
+ /** Oversized-turn stubbing + terminal truncation. Operates on a SHALLOW copy
332
+ * (`messages.slice()`) — the copy lives HERE, in one place, and guards both phases —
333
+ * and replaces slots via object spread so the cached snapshot's array AND its message
334
+ * objects are never mutated. Phase 1 ({@link stubToolResultsToFit}) stubs toolResults
335
+ * oldest-first; phase 2 ({@link truncateToFit}) truncates the largest text block toward
336
+ * the token gap. Signature and return shape are unchanged. */
337
+ function stubToFit(messages: Message[], budget: number): { messages: Message[]; stubbed: boolean } {
338
+ const result = messages.slice(); // shallow: new array, shared message objects — one place, guards both phases
339
+ const stubbedTool = stubToolResultsToFit(result, budget);
340
+ const stubbedTruncated = truncateToFit(result, budget);
341
+ return { messages: result, stubbed: stubbedTool || stubbedTruncated };
342
+ }
343
+
344
+ /** Orchestrating pure branch-fit. Fast path returns the cached `messages` by reference
345
+ * (byte-identical prefix). Otherwise forward-scan trim, then stub/truncate. `keepBudget`
346
+ * is populated on every path. */
347
+ export function fitBranch(input: FitBranchInput): FitBranchResult {
348
+ const { entries, messages, model, systemPrompt, question, admittedEstimate } = input;
349
+
350
+ // --- Budget resolution ---
351
+ let branchKeepBudget: number;
352
+ if (input.keepBudget !== undefined) {
353
+ // Retry path: skip the window formula AND the skip guard; trim/stub
354
+ // directly to this many branch tokens. The cached snapshot is not re-read.
355
+ branchKeepBudget = input.keepBudget;
356
+ } else {
357
+ const available = model.contextWindow - model.maxTokens - BTW_CONTEXT_RESERVE;
358
+ const windowBudget = available - estimateTextTokens(systemPrompt) - estimateTokens(question) - admittedEstimate;
359
+ if (!isBudgetable(model)) {
360
+ // Skip guard: window unusable → fast-path the cached messages, no trim.
361
+ // keepBudget is still populated (the window-derived value, possibly negative on an
362
+ // unusable window) so the caller's read never sees undefined — see Notes / Deferred.
363
+ return { messages, branchWasTrimmed: false, stubbed: false, keepBudget: windowBudget };
364
+ }
365
+ branchKeepBudget = windowBudget;
366
+ }
367
+
368
+ // --- Fast path: branch fits → return cached messages by reference (byte-identical prefix) ---
369
+ const branchUsage = estimateBranchTokens(entries);
370
+ if (branchUsage <= branchKeepBudget) {
371
+ return { messages, branchWasTrimmed: false, stubbed: false, keepBudget: branchKeepBudget };
372
+ }
373
+
374
+ // --- Forward-scan trim ---
375
+ const trim = trimBranch(entries, branchKeepBudget);
376
+ if (trim.messages) {
377
+ // Trimmed suffix fits → done (trimmed only).
378
+ if (estimateMessagesTokens(trim.messages) <= branchKeepBudget) {
379
+ return { messages: trim.messages, branchWasTrimmed: true, stubbed: false, keepBudget: branchKeepBudget };
380
+ }
381
+ // Still over after trimming → stub the TRIMMED suffix (branchWasTrimmed stays true).
382
+ const stubbed = stubToFit(trim.messages, branchKeepBudget);
383
+ return {
384
+ messages: stubbed.messages,
385
+ branchWasTrimmed: true,
386
+ stubbed: stubbed.stubbed,
387
+ keepBudget: branchKeepBudget,
388
+ };
389
+ }
390
+
391
+ // --- No-cut-possible fallback: no valid cut or no turn-start → stub the full
392
+ // cached messages (branchWasTrimmed FALSE — findCutPoint found nothing to cut).
393
+ // When stubbing changed nothing (anchor-metered usage over budget but the raw
394
+ // estimates already fit), return the ORIGINAL cached array — best effort, and
395
+ // the reference-parity guarantee holds. ---
396
+ const stubbed = stubToFit(messages, branchKeepBudget);
397
+ return {
398
+ messages: stubbed.stubbed ? stubbed.messages : messages,
399
+ branchWasTrimmed: false,
400
+ stubbed: stubbed.stubbed,
401
+ keepBudget: branchKeepBudget,
402
+ };
403
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Cycle-break leaf module.
3
+ *
4
+ * Owns the `BtwTurn` interface and the `userMessageText` / `assistantMessageText`
5
+ * message-text extractors, moved here from `btw.ts` to sever the sole runtime
6
+ * VALUE back-edge `btw-ui.ts → btw.ts` (the cluster-2 cycle-break, L1-06).
7
+ *
8
+ * This module imports ONLY `type { AssistantMessage, UserMessage }` from
9
+ * `@earendil-works/pi-ai` — it has NO `./btw.js` import, so the leaf introduces
10
+ * no back-edge into `btw.ts`. `btw.ts` re-exports all three symbols so the
11
+ * package surface (and the `*.test.ts` imports from `./btw.js`) is unchanged.
12
+ *
13
+ * The phantom type-only cycle `btw.ts ↔ btw-budget.ts` (`btw-budget.ts:22`
14
+ * `import type { BtwTurn } from "./btw.js"`) is intentionally left in place —
15
+ * it is runtime-inert (erased) and repointing it is owned by no phase in this
16
+ * plan (see plan risk r6).
17
+ */
18
+
19
+ import type { AssistantMessage, UserMessage } from "@earendil-works/pi-ai";
20
+
21
+ // Real messages — no fabrication. userMessage is built at call time; assistantMessage
22
+ // is the unmodified completeSimple response. Stable object references across calls →
23
+ // byte-identical prompt prefix on subsequent /btw invocations (cache parity).
24
+ export interface BtwTurn {
25
+ userMessage: UserMessage;
26
+ assistantMessage: AssistantMessage;
27
+ }
28
+
29
+ // Extract text from a UserMessage's content.
30
+ export function userMessageText(msg: UserMessage): string {
31
+ if (typeof msg.content === "string") return msg.content;
32
+ return msg.content
33
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
34
+ .map((c) => c.text)
35
+ .join("\n");
36
+ }
37
+
38
+ // Extract text from an AssistantMessage's content (text parts only).
39
+ export function assistantMessageText(msg: AssistantMessage): string {
40
+ return msg.content
41
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
42
+ .map((c) => c.text)
43
+ .join("\n");
44
+ }
package/btw-ui.ts CHANGED
@@ -35,7 +35,7 @@ import {
35
35
  visibleWidth,
36
36
  wrapTextWithAnsi,
37
37
  } from "@earendil-works/pi-tui";
38
- import { type BtwTurn, userMessageText } from "./btw.js";
38
+ import { type BtwTurn, userMessageText } from "./btw-messages.js";
39
39
 
40
40
  const BTW_MAX_HEIGHT_RATIO = 0.85;
41
41
 
@@ -54,6 +54,7 @@ const FOOTER_SCROLL = "↑/↓ to scroll";
54
54
  const FOOTER_CLEAR = "x to clear history";
55
55
  const FOOTER_DISMISS = "Esc to dismiss";
56
56
  const FOOTER_SEP = " · ";
57
+ const MSG_TRIMMED = "context trimmed to fit budget";
57
58
 
58
59
  type Mode = "pending" | "answer" | "error";
59
60
 
@@ -75,6 +76,7 @@ export class BtwOverlayController implements Component {
75
76
  private answer = "";
76
77
  private error = "";
77
78
  private scrollOffset = 0;
79
+ private trimmed = false;
78
80
  private history: BtwTurn[];
79
81
 
80
82
  constructor(
@@ -101,6 +103,14 @@ export class BtwOverlayController implements Component {
101
103
  this.tui.requestRender();
102
104
  }
103
105
 
106
+ // Orthogonal to mode: a trimmed result is also a successful answer.
107
+ // Idempotent; a fresh controller is built per /btw command in showBtwOverlay,
108
+ // so there is no reset path.
109
+ setTrimmed(): void {
110
+ this.trimmed = true;
111
+ this.tui.requestRender();
112
+ }
113
+
104
114
  handleInput(data: string): void {
105
115
  if (matchesKey(data, Key.escape)) {
106
116
  this.controller.abort();
@@ -139,8 +149,28 @@ export class BtwOverlayController implements Component {
139
149
  const footer =
140
150
  SIDE_PAD + truncateToWidth(this.theme.fg("dim", footerParts.join(FOOTER_SEP)), footerAvail, "…", false);
141
151
 
142
- // Natural content: banner + blank + history + echo + blank + answer + blank + footer
143
- const natural: string[] = [banner, "", ...historyLines, echoLine, "", ...answerLines, "", footer];
152
+ // Natural content: banner + blank + history + echo + blank + answer [+ trim notice] + blank + footer
153
+ const natural: string[] = [
154
+ banner,
155
+ "",
156
+ ...historyLines,
157
+ echoLine,
158
+ "",
159
+ ...answerLines,
160
+ ...(this.trimmed
161
+ ? [
162
+ ANSWER_PAD +
163
+ truncateToWidth(
164
+ this.theme.fg("warning", MSG_TRIMMED),
165
+ Math.max(1, width - ANSWER_PAD.length),
166
+ "…",
167
+ false,
168
+ ),
169
+ ]
170
+ : []),
171
+ "",
172
+ footer,
173
+ ];
144
174
 
145
175
  // Clip to terminal height if we overflow. Bottom-anchor keeps footer+answer visible;
146
176
  // ↑/↓ scrolls the top (history) up into the clipped region.
package/btw.ts CHANGED
@@ -17,8 +17,10 @@ import {
17
17
  type ExtensionContext,
18
18
  type SessionEntry,
19
19
  } from "@earendil-works/pi-coding-agent";
20
+ import { type CappedHistory, capHistory, type FitBranchResult, fitBranch } from "./btw-budget.js";
21
+ import { assistantMessageText, type BtwTurn, userMessageText } from "./btw-messages.js";
20
22
  import { showBtwOverlay } from "./btw-ui.js";
21
- import { loadCompleteSimple } from "./pi-compat.js";
23
+ import { loadCompleteSimple, loadIsContextOverflow } from "./pi-compat.js";
22
24
 
23
25
  // ---------------------------------------------------------------------------
24
26
  // Constants — flat named consts, grouped by concern (advisor pattern, b9428e9)
@@ -48,24 +50,28 @@ const errNoApiKey = (label: string) => `/btw model (${label}) has no API key ava
48
50
  const errCallFailed = (err: string | undefined) => `/btw call failed: ${err ?? "unknown error"}`;
49
51
  const errCallThrew = (msg: string) => `/btw call threw: ${msg}`;
50
52
 
53
+ // Budget (context-budgeting) constants — defined in btw-budget.ts (the leaf budget
54
+ // module; keeps the module cycle type-only at runtime), re-exported here so the
55
+ // package surface is unchanged.
56
+ export { BTW_CONTEXT_RESERVE, BTW_HISTORY_TOKEN_BUDGET, BTW_NO_ANCHOR_SAFETY_FACTOR } from "./btw-budget.js";
57
+ // BtwTurn + the message-text extractors live in the cycle-break leaf
58
+ // (packages/rpiv-btw/btw-messages.ts); re-exported here so the package surface is
59
+ // unchanged (packages/rpiv-btw/btw.test.ts / btw-ui.test.ts / btw-budget.test.ts still
60
+ // import them from "./btw.js"). Import-then-re-export (not `export … from`) because
61
+ // btw.ts consumes all three internally (userMessageText at :166,
62
+ // assistantMessageText at :341, BtwTurn in BtwState/getSessionHistory/pushSessionTurn).
63
+ export { assistantMessageText, type BtwTurn, userMessageText };
64
+
51
65
  // ---------------------------------------------------------------------------
52
66
  // Types
53
67
  // ---------------------------------------------------------------------------
54
68
 
55
- // Real messages — no fabrication. userMessage is built at call time; assistantMessage
56
- // is the unmodified completeSimple response. Stable object references across calls →
57
- // byte-identical prompt prefix on subsequent /btw invocations (cache parity).
58
- export interface BtwTurn {
59
- userMessage: UserMessage;
60
- assistantMessage: AssistantMessage;
61
- }
62
-
63
69
  interface BtwState {
64
70
  histories: Map<string, BtwTurn[]>;
65
- snapshots: Map<string, { messages: Message[] }>;
71
+ snapshots: Map<string, { messages: Message[]; entries: SessionEntry[] }>;
66
72
  }
67
73
 
68
- function branchToMessages(branch: SessionEntry[]): Message[] {
74
+ export function branchToMessages(branch: SessionEntry[]): Message[] {
69
75
  const agentMessages = branch
70
76
  .filter((e): e is SessionEntry & { type: "message" } => e.type === "message")
71
77
  .map((e) => e.message);
@@ -123,11 +129,11 @@ export function clearSessionHistory(ctx: ExtensionContext): void {
123
129
  getState().histories.set(getSessionFile(ctx), []);
124
130
  }
125
131
 
126
- function getSnapshot(ctx: ExtensionContext): { messages: Message[] } | undefined {
132
+ function getSnapshot(ctx: ExtensionContext): { messages: Message[]; entries: SessionEntry[] } | undefined {
127
133
  return getState().snapshots.get(getSessionFile(ctx));
128
134
  }
129
135
 
130
- function setSnapshot(ctx: ExtensionContext, snapshot: { messages: Message[] }): void {
136
+ function setSnapshot(ctx: ExtensionContext, snapshot: { messages: Message[]; entries: SessionEntry[] }): void {
131
137
  getState().snapshots.set(getSessionFile(ctx), snapshot);
132
138
  }
133
139
 
@@ -135,23 +141,6 @@ export function invalidateSnapshot(ctx: ExtensionContext): void {
135
141
  getState().snapshots.delete(getSessionFile(ctx));
136
142
  }
137
143
 
138
- // Extract text from a UserMessage's content.
139
- export function userMessageText(msg: UserMessage): string {
140
- if (typeof msg.content === "string") return msg.content;
141
- return msg.content
142
- .filter((c): c is { type: "text"; text: string } => c.type === "text")
143
- .map((c) => c.text)
144
- .join("\n");
145
- }
146
-
147
- // Extract text from an AssistantMessage's content (text parts only).
148
- export function assistantMessageText(msg: AssistantMessage): string {
149
- return msg.content
150
- .filter((c): c is { type: "text"; text: string } => c.type === "text")
151
- .map((c) => c.text)
152
- .join("\n");
153
- }
154
-
155
144
  // Cross-session pattern hint — last N question-strings across ALL sessions.
156
145
  function getCrossSessionHint(): string {
157
146
  const allTurns: { q: string; ts: number }[] = [];
@@ -172,25 +161,83 @@ function getCrossSessionHint(): string {
172
161
  // ---------------------------------------------------------------------------
173
162
 
174
163
  export type BtwExecResult =
175
- | { ok: true; answer: string; userMessage: UserMessage; assistantMessage: AssistantMessage; stopReason: StopReason }
176
- | { ok: false; error: string; stopReason?: StopReason }
177
- | { ok: false; aborted: true; stopReason: StopReason };
178
-
179
- function readBranchMessages(ctx: ExtensionContext): Message[] {
164
+ | {
165
+ kind: "success";
166
+ answer: string;
167
+ userMessage: UserMessage;
168
+ assistantMessage: AssistantMessage;
169
+ stopReason: StopReason;
170
+ trimmed?: boolean;
171
+ }
172
+ | { kind: "error"; error: string; stopReason?: StopReason }
173
+ | { kind: "aborted"; stopReason: StopReason };
174
+
175
+ function readBranchSnapshot(ctx: ExtensionContext): { messages: Message[]; entries: SessionEntry[] } {
180
176
  const cached = getSnapshot(ctx);
181
- if (cached) return cached.messages;
182
- // Cold start (no message_end fired yet) — fall back to live read
177
+ if (cached) return cached;
178
+ // Cold start (no message_end fired yet) — fall back to a single live read.
183
179
  const branch = ctx.sessionManager.getBranch() as SessionEntry[];
184
- return branchToMessages(branch);
180
+ return { messages: branchToMessages(branch), entries: branch };
185
181
  }
186
182
 
187
- function buildBtwMessages(ctx: ExtensionContext, userMessage: UserMessage): Message[] {
188
- const branchMessages = readBranchMessages(ctx);
183
+ export interface BtwBuiltContext {
184
+ messages: Message[];
185
+ systemPrompt: string;
186
+ droppedTurns: number;
187
+ branchWasTrimmed: boolean;
188
+ stubbed: boolean;
189
+ keepBudget: number; // halved by the overflow-retry caller to tighten the branch budget
190
+ }
191
+
192
+ export function buildBtwMessages(
193
+ ctx: ExtensionContext,
194
+ userMessage: UserMessage,
195
+ keepBudget?: number,
196
+ ): BtwBuiltContext {
197
+ // ctx.model is non-null here — executeBtw returns early on !model before calling.
198
+ const model = ctx.model!;
189
199
  const history = getSessionHistory(ctx);
190
- // Reusing stored real UserMessage/AssistantMessage object references across calls
191
- // preserves byte-identical prompt prefix (cache parity).
192
- const historyMessages: Message[] = history.flatMap((h) => [h.userMessage, h.assistantMessage]);
193
- return [...branchMessages, ...historyMessages, userMessage];
200
+ const { messages, entries } = readBranchSnapshot(ctx);
201
+ const systemPrompt = buildSystemPrompt();
202
+ const fitInput = { entries, messages, model, systemPrompt, question: userMessage };
203
+
204
+ let capped: CappedHistory;
205
+ let fit: FitBranchResult;
206
+ if (keepBudget === undefined) {
207
+ // Fast-path parity: attempt the FULL history first (an Infinity budget admits
208
+ // every turn) — when the whole request fits the window, the build is
209
+ // byte-identical to the pre-budgeting assembly and the history cap never engages.
210
+ capped = capHistory(history, Number.POSITIVE_INFINITY);
211
+ fit = fitBranch({ ...fitInput, admittedEstimate: capped.estimate });
212
+ if (fit.branchWasTrimmed || fit.stubbed) {
213
+ // Over budget with full history → apply the history cap BEFORE branch
214
+ // trimming, then re-fit the branch against the freed window. When the cap
215
+ // drops nothing the inputs are identical — keep the first fit.
216
+ const recapped = capHistory(history);
217
+ if (recapped.droppedTurns > 0) {
218
+ capped = recapped;
219
+ fit = fitBranch({ ...fitInput, admittedEstimate: recapped.estimate });
220
+ }
221
+ }
222
+ } else {
223
+ // Overflow retry: the sent request has already proven too large — take the
224
+ // capped history and trim/stub the branch straight to the halved budget.
225
+ capped = capHistory(history);
226
+ fit = fitBranch({ ...fitInput, admittedEstimate: capped.estimate, keepBudget });
227
+ }
228
+ const assembled: Message[] = [
229
+ ...fit.messages,
230
+ ...capped.admitted.flatMap((t) => [t.userMessage, t.assistantMessage]),
231
+ userMessage,
232
+ ];
233
+ return {
234
+ messages: assembled,
235
+ systemPrompt,
236
+ droppedTurns: capped.droppedTurns,
237
+ branchWasTrimmed: fit.branchWasTrimmed,
238
+ stubbed: fit.stubbed,
239
+ keepBudget: fit.keepBudget,
240
+ };
194
241
  }
195
242
 
196
243
  function buildSystemPrompt(): string {
@@ -204,16 +251,16 @@ export async function executeBtw(
204
251
  ): Promise<BtwExecResult> {
205
252
  const model = ctx.model;
206
253
  if (!model) {
207
- return { ok: false, error: MSG_NO_MODEL };
254
+ return { kind: "error", error: MSG_NO_MODEL };
208
255
  }
209
256
  const modelLabel = `${model.provider}:${model.id}`;
210
257
 
211
258
  const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
212
259
  if (!auth.ok) {
213
- return { ok: false, error: errMisconfigured(modelLabel, auth.error) };
260
+ return { kind: "error", error: errMisconfigured(modelLabel, auth.error) };
214
261
  }
215
262
  if (!auth.apiKey) {
216
- return { ok: false, error: errNoApiKey(modelLabel) };
263
+ return { kind: "error", error: errNoApiKey(modelLabel) };
217
264
  }
218
265
 
219
266
  const userMessage: UserMessage = {
@@ -221,27 +268,52 @@ export async function executeBtw(
221
268
  content: [{ type: "text", text: question }],
222
269
  timestamp: Date.now(),
223
270
  };
224
- const messages = buildBtwMessages(ctx, userMessage);
225
- const systemPrompt = buildSystemPrompt();
271
+ // `let` because the overflow retry reassigns `built` with a halved budget;
272
+ // buildBtwMessages returns BtwBuiltContext { messages, systemPrompt,
273
+ // droppedTurns, branchWasTrimmed, stubbed, keepBudget }.
274
+ let built = buildBtwMessages(ctx, userMessage);
226
275
 
227
276
  try {
228
277
  const completeSimple = await loadCompleteSimple();
229
- const response = await completeSimple(
230
- model,
231
- { systemPrompt, messages, tools: [] },
232
- {
233
- apiKey: auth.apiKey,
234
- headers: auth.headers,
235
- signal: controller.signal, // own AbortController, NOT ctx.signal (Decision 8)
236
- },
237
- );
238
-
239
- if (response.stopReason === "aborted") {
240
- return { ok: false, aborted: true, stopReason: response.stopReason };
278
+ const overflowFn = await loadIsContextOverflow();
279
+ let retried = false;
280
+ const callCompleteSimple = async (
281
+ built: BtwBuiltContext,
282
+ ): Promise<{ kind: "aborted"; stopReason: StopReason } | { kind: "completed"; response: AssistantMessage }> => {
283
+ const response = await completeSimple(
284
+ model,
285
+ { systemPrompt: built.systemPrompt, messages: built.messages, tools: [] },
286
+ {
287
+ apiKey: auth.apiKey,
288
+ headers: auth.headers,
289
+ signal: controller.signal, // own AbortController, NOT ctx.signal (Decision 8)
290
+ },
291
+ );
292
+ if (response.stopReason === "aborted") {
293
+ return { kind: "aborted", stopReason: response.stopReason };
294
+ }
295
+ return { kind: "completed", response };
296
+ };
297
+ let outcome = await callCompleteSimple(built);
298
+ if (outcome.kind === "aborted") return outcome;
299
+ let response = outcome.response;
300
+ // Overflow gate — exactly one retry. On the first response the host flags
301
+ // as context overflow (any stopReason), rebuild the branch context with a
302
+ // halved keepBudget and re-call once. A flag bounds it to one retry; the
303
+ // recall's throw and the loader's rethrow both land in the surrounding
304
+ // catch. /btw's fresh side call retries all three overflow stopReasons
305
+ // (error/stop/length), a deliberate divergence from the host's
306
+ // stopReason-based willRetry.
307
+ if (overflowFn && !retried && overflowFn(response, model.contextWindow)) {
308
+ retried = true;
309
+ built = buildBtwMessages(ctx, userMessage, Math.floor(built.keepBudget / 2));
310
+ outcome = await callCompleteSimple(built);
311
+ if (outcome.kind === "aborted") return outcome;
312
+ response = outcome.response;
241
313
  }
242
314
  if (response.stopReason === "error") {
243
315
  return {
244
- ok: false,
316
+ kind: "error",
245
317
  error: errCallFailed(response.errorMessage),
246
318
  stopReason: response.stopReason,
247
319
  };
@@ -249,22 +321,23 @@ export async function executeBtw(
249
321
 
250
322
  const answerText = assistantMessageText(response).trim();
251
323
  if (!answerText) {
252
- return { ok: false, error: ERR_EMPTY_RESPONSE, stopReason: response.stopReason };
324
+ return { kind: "error", error: ERR_EMPTY_RESPONSE, stopReason: response.stopReason };
253
325
  }
254
326
 
255
327
  return {
256
- ok: true,
328
+ kind: "success",
257
329
  answer: answerText,
258
330
  userMessage,
259
331
  assistantMessage: response,
260
332
  stopReason: response.stopReason,
333
+ trimmed: built.droppedTurns > 0 || built.branchWasTrimmed || built.stubbed,
261
334
  };
262
335
  } catch (err) {
263
336
  const message = err instanceof Error ? err.message : String(err);
264
337
  if (controller.signal.aborted) {
265
- return { ok: false, aborted: true, stopReason: "aborted" as const };
338
+ return { kind: "aborted", stopReason: "aborted" as const };
266
339
  }
267
- return { ok: false, error: errCallThrew(message) };
340
+ return { kind: "error", error: errCallThrew(message) };
268
341
  }
269
342
  }
270
343
 
@@ -278,7 +351,7 @@ export function registerMessageEndSnapshot(pi: ExtensionAPI): void {
278
351
  if (msg.role !== "assistant") return;
279
352
  if ((msg as AssistantMessage).stopReason === "toolUse") return;
280
353
  const branch = ctx.sessionManager.getBranch() as SessionEntry[];
281
- setSnapshot(ctx, { messages: branchToMessages(branch) });
354
+ setSnapshot(ctx, { messages: branchToMessages(branch), entries: branch });
282
355
  });
283
356
  }
284
357
 
@@ -342,17 +415,25 @@ async function handleBtwCommand(_pi: ExtensionAPI, args: string, ctx: ExtensionC
342
415
  const overlayCtl = await controllerReady;
343
416
  const result = await executeBtw(question, ctx, controller);
344
417
 
345
- if (result.ok) {
346
- overlayCtl.setAnswer(result.answer);
347
- pushSessionTurn(ctx, {
348
- userMessage: result.userMessage,
349
- assistantMessage: result.assistantMessage,
350
- });
351
- // No disk persistence — process-scoped only (Decision 4)
352
- } else if ("aborted" in result) {
353
- // User Esc'd — overlay already dismissed via done(); no further action
354
- } else {
355
- overlayCtl.setError(result.error);
418
+ switch (result.kind) {
419
+ case "success": {
420
+ overlayCtl.setAnswer(result.answer);
421
+ if (result.trimmed) overlayCtl.setTrimmed(); // success-only: TS narrows result here
422
+ pushSessionTurn(ctx, {
423
+ userMessage: result.userMessage,
424
+ assistantMessage: result.assistantMessage,
425
+ });
426
+ // No disk persistence — process-scoped only (Decision 4)
427
+ break;
428
+ }
429
+ case "aborted": {
430
+ // User Esc'd — overlay already dismissed via done(); no further action
431
+ break;
432
+ }
433
+ case "error": {
434
+ overlayCtl.setError(result.error);
435
+ break;
436
+ }
356
437
  }
357
438
 
358
439
  await overlayPromise;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-btw",
3
- "version": "2.1.0",
3
+ "version": "2.3.0",
4
4
  "description": "Pi extension. The /btw slash command, for putting a one-off side question to the same primary model without polluting the main conversation.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -31,6 +31,8 @@
31
31
  "files": [
32
32
  "index.ts",
33
33
  "btw.ts",
34
+ "btw-budget.ts",
35
+ "btw-messages.ts",
34
36
  "btw-ui.ts",
35
37
  "pi-compat.ts",
36
38
  "prompts/",
package/pi-compat.ts CHANGED
@@ -17,6 +17,7 @@
17
17
  */
18
18
 
19
19
  type CompleteSimpleFn = typeof import("@earendil-works/pi-ai/compat").completeSimple;
20
+ type IsContextOverflowFn = typeof import("@earendil-works/pi-ai/compat").isContextOverflow;
20
21
 
21
22
  /**
22
23
  * Error codes meaning "the /compat entrypoint is not resolvable on this host":
@@ -62,3 +63,33 @@ export async function loadCompleteSimple(): Promise<CompleteSimpleFn> {
62
63
  }
63
64
  return completeSimple;
64
65
  }
66
+
67
+ /**
68
+ * Host-version-tolerant loader for pi-ai's `isContextOverflow` — the overflow
69
+ * detector that gates the /btw single-retry.
70
+ *
71
+ * `isContextOverflow` is re-exported from BOTH the `/compat` entrypoint and the
72
+ * package root (defined in pi-ai's `utils/overflow`), so the resolution path
73
+ * mirrors `loadCompleteSimple`: try `/compat`, fall back to the root only on a
74
+ * module-resolution failure, and rethrow a real `/compat` init failure so it is
75
+ * not masked by the fallback. Unlike `completeSimple`, the export's ABSENCE is
76
+ * an expected host state (older pi-ai, or a host that surfaces it from neither
77
+ * entrypoint), not an unsupported-host error: per the Option-3 refinement the
78
+ * missing-export case returns `undefined` so the caller degrades gracefully
79
+ * (skips the retry) instead of crashing. A non-resolution `/compat` failure
80
+ * still rethrows.
81
+ */
82
+ export async function loadIsContextOverflow(): Promise<IsContextOverflowFn | undefined> {
83
+ let mod: { isContextOverflow?: IsContextOverflowFn };
84
+ try {
85
+ mod = (await import("@earendil-works/pi-ai/compat")) as { isContextOverflow?: IsContextOverflowFn };
86
+ } catch (err) {
87
+ if (!isModuleNotFound(err)) throw err; // a real /compat failure must surface, not mask as a fallback
88
+ mod = (await import("@earendil-works/pi-ai")) as { isContextOverflow?: IsContextOverflowFn };
89
+ }
90
+ const isContextOverflow = mod.isContextOverflow;
91
+ if (typeof isContextOverflow !== "function") {
92
+ return undefined; // expected absence on a host lacking the export — degrade, don't crash
93
+ }
94
+ return isContextOverflow;
95
+ }