@juicesharp/rpiv-btw 2.0.0 → 2.2.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-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;
@@ -0,0 +1,161 @@
1
+ # rpiv-btw architecture
2
+
3
+ Module layout, what the extension registers with Pi, how the overlay is laid out,
4
+ how state is stored, and how the package tolerates different Pi host versions.
5
+
6
+ ## Modules
7
+
8
+ ```
9
+ rpiv-btw/
10
+ ├── index.ts — extension entry; registers the command + 3 hooks
11
+ ├── btw.ts — state, snapshotting, message threading, the model call
12
+ ├── btw-ui.ts — bottom-anchored overlay component and key handling
13
+ ├── pi-compat.ts — host-version-tolerant loader for pi-ai's completeSimple
14
+ └── prompts/
15
+ └── btw-system.txt — system prompt for the side call
16
+ ```
17
+
18
+ Pi discovers the extension through the manifest block in `package.json`:
19
+
20
+ ```json
21
+ "pi": { "extensions": ["./index.ts"] }
22
+ ```
23
+
24
+ That is the entire registration surface. The package ships no skills, no agents,
25
+ no `bin`, and declares no `exports` or `main`. A test (`ship-manifest.test.ts`)
26
+ asserts that the published `files` list covers every production module.
27
+
28
+ ## What gets registered
29
+
30
+ One slash command:
31
+
32
+ | Command | Description string |
33
+ | --- | --- |
34
+ | `/btw <question>` | `Ask a side question without polluting the main conversation` |
35
+
36
+ Three lifecycle hooks:
37
+
38
+ | Event | Behavior |
39
+ | --- | --- |
40
+ | `message_end` | Snapshots the branch, only for assistant messages whose `stopReason` is not `toolUse` |
41
+ | `session_compact` | Invalidates this session's cached snapshot |
42
+ | `session_tree` | Invalidates this session's cached snapshot |
43
+
44
+ No tools are registered. No CLI flags are added.
45
+
46
+ ## State
47
+
48
+ All state lives on a single process-wide cell:
49
+
50
+ ```ts
51
+ export const BTW_STATE_KEY = Symbol.for("rpiv-btw");
52
+ ```
53
+
54
+ It holds two maps — `histories` and `snapshots` — both keyed by
55
+ `ctx.sessionManager.getSessionFile()`, with `memory:<sessionId>` as the fallback
56
+ key when there is no session file.
57
+
58
+ Using `globalThis` plus `Symbol.for()` (the same idiom OpenTelemetry uses for
59
+ cross-import-graph singletons) means the cell survives module re-import, so
60
+ `/btw` history outlives `/new`, `/fork`, `/resume`, and `/reload`. It is lost
61
+ when the Pi process exits — by design. Nothing is persisted to disk, and the
62
+ package reads no environment variables and no config files.
63
+
64
+ ## Overlay
65
+
66
+ `showBtwOverlay` mounts a `Component` through `ctx.ui.custom` with these options:
67
+
68
+ | Option | Value |
69
+ | --- | --- |
70
+ | `anchor` | `bottom-center` |
71
+ | `width` | `100%` |
72
+ | `maxHeight` | `85%` (`BTW_MAX_HEIGHT_RATIO = 0.85`) |
73
+ | `margin` | `{ left: 0, right: 0, bottom: 0 }` |
74
+
75
+ Render order, top to bottom:
76
+
77
+ ```
78
+ banner — your question on a themed stripe, padded to full width
79
+ (blank)
80
+ history — prior "/btw <q>" lines for this session
81
+ echo — "/btw <q>" for the current question
82
+ (blank)
83
+ answer — "…" while pending, the answer text, or the error in red
84
+ (blank)
85
+ footer — key hints
86
+ ```
87
+
88
+ History and echo use a 2-column left gutter; the answer body uses 4. The panel
89
+ grows upward with content. When the natural height exceeds
90
+ `floor(terminalRows × 0.85)` (terminal rows default to 24 if unknown, with a
91
+ floor of 4 rows), it clips from the top and `↑`/`↓` scroll that window —
92
+ offset `0` shows the newest content.
93
+
94
+ ### Keys and footer gates
95
+
96
+ | Key | Action | Matching |
97
+ | --- | --- | --- |
98
+ | `Esc` | Aborts the in-flight call and dismisses the overlay | `matchesKey` (ANSI + Kitty) |
99
+ | `↑` | Scroll up one row, clamped at 0 | `matchesKey` |
100
+ | `↓` | Scroll down one row, clamped to the overflow amount | `matchesKey` |
101
+ | `x` | Clears this session's `/btw` history and resets scroll | raw `data === "x"` — uppercase `X` is not bound |
102
+
103
+ | Footer hint | Shown when |
104
+ | --- | --- |
105
+ | `↑/↓ to scroll` | the call is no longer pending (an answer or error has arrived) |
106
+ | `x to clear history` | this session has at least one prior `/btw` turn |
107
+ | `Esc to dismiss` | always |
108
+
109
+ Hints are joined with `" · "` and truncated to the panel width.
110
+
111
+ ## Host-version tolerance
112
+
113
+ pi-ai resolves at runtime against the *host's* copy (all three pi peers are
114
+ declared `"*"`), and pi moved the global dispatch API to a `/compat` entrypoint
115
+ in 0.80.1. `pi-compat.ts` therefore resolves `completeSimple` lazily:
116
+
117
+ 1. `import("@earendil-works/pi-ai/compat")` — pi >= 0.80.1.
118
+ 2. On a **module-resolution** failure only, fall back to
119
+ `import("@earendil-works/pi-ai")` — pi <= 0.79.x, which has no `/compat`
120
+ subpath at all.
121
+
122
+ The fallback is gated on the error codes `ERR_PACKAGE_PATH_NOT_EXPORTED`,
123
+ `ERR_MODULE_NOT_FOUND`, and `MODULE_NOT_FOUND`, walked down the `cause` chain
124
+ (bounded at 16 links, because ESM loaders and test mock layers nest the real
125
+ code). Any other `/compat` error — the entrypoint exists but throws at module
126
+ init — rethrows, so a real failure surfaces instead of being masked by a root
127
+ import that may not have the export.
128
+
129
+ If neither entrypoint exposes the function, the call fails with
130
+ `pi-ai does not expose completeSimple on /compat or the package root — unsupported host pi-ai version`.
131
+
132
+ `/compat` is documented upstream as temporary, so this module is the single place
133
+ to migrate when it is removed.
134
+
135
+ ## Messages and errors
136
+
137
+ Every user-visible string the package can produce:
138
+
139
+ | String | When |
140
+ | --- | --- |
141
+ | `/btw requires interactive mode` (error) | `ctx.hasUI` is false — `pi --print`, RPC |
142
+ | `Usage: /btw <question>` (warning) | the argument is empty or whitespace-only |
143
+ | `/btw requires an active model` (error) | there is no `ctx.model` |
144
+ | `/btw model (<provider>:<id>) is misconfigured: <err>` | credential lookup returned an error |
145
+ | `/btw model (<provider>:<id>) has no API key available.` | lookup succeeded but the API key is empty |
146
+ | `/btw call failed: <err ?? "unknown error">` | the completion returned `stopReason: "error"` |
147
+ | `/btw call threw: <message>` | the completion threw and the call was not aborted |
148
+ | `/btw returned no text content.` | the response contained no text parts |
149
+
150
+ The first three are `ctx.ui.notify` toasts raised before the overlay opens; the
151
+ rest render inside the overlay in the error style.
152
+
153
+ ## Boundaries
154
+
155
+ - **No runtime dependencies.** No `dependencies`, no `devDependencies` — only the
156
+ three `@earendil-works` peers.
157
+ - **No sibling imports at runtime.** `pi-compat.ts` deliberately duplicates
158
+ rpiv-core's `isModuleNotFound` rather than importing it, because the rpiv
159
+ packages never import each other at runtime.
160
+ - **Standalone.** rpiv-btw is excluded from `rpiv-pi`'s auto-install sibling list,
161
+ and a test asserts that exclusion.
@@ -0,0 +1,95 @@
1
+ # What `/btw` sends to the model
2
+
3
+ Exactly what every `/btw` call puts in front of your primary model, where each
4
+ piece comes from, and what is guaranteed never to leave the panel.
5
+
6
+ ## The request
7
+
8
+ Each `/btw` call is a single non-streaming completion against `ctx.model` — the
9
+ same primary model driving your session. There is no model picker and no
10
+ lighter-weight side model.
11
+
12
+ | Part | Value |
13
+ | --- | --- |
14
+ | Model | `ctx.model`, with credentials from `ctx.modelRegistry.getApiKeyAndHeaders(model)` |
15
+ | System prompt | the bundled `prompts/btw-system.txt`, plus the cross-session hint appendix |
16
+ | Messages | `[...branch clone, ...this-session /btw turns, your question]` |
17
+ | Tools | `[]` — none, always |
18
+ | Abort signal | a fresh `AbortController` owned by `/btw`, never `ctx.signal` |
19
+
20
+ ## The branch clone
21
+
22
+ The first block of messages is a read-only clone of your current session branch,
23
+ so you do not have to re-explain what you have been working on.
24
+
25
+ - The `message_end` hook takes the snapshot: it reads `ctx.sessionManager.getBranch()`
26
+ and converts it with `convertToLlm`.
27
+ - It snapshots **only** on `role === "assistant"` messages, and **only** when
28
+ `stopReason !== "toolUse"` — so mid-tool-call states never become the context.
29
+ - Snapshots are cached per session, keyed by `ctx.sessionManager.getSessionFile()`,
30
+ falling back to `memory:<sessionId>` when there is no session file.
31
+ - Cold start: if no `message_end` has fired yet, `/btw` reads the branch live
32
+ instead of using a cache.
33
+
34
+ ### Invalidation
35
+
36
+ The cached snapshot is deleted on both `session_compact` and `session_tree`, so a
37
+ `/btw` issued after compaction or a branch switch never answers off a stale view
38
+ of the conversation.
39
+
40
+ Auto-compaction races session disposal in pi-core: `session_compact` can fire
41
+ with an already-invalidated `ctx` proxy. `/btw` swallows only that specific stale
42
+ error (`stale after session replacement`) — the session being compacted has no
43
+ snapshot worth invalidating. Every other error propagates, because it is a bug.
44
+
45
+ ## The `/btw` history
46
+
47
+ After a successful answer, the turn is appended to this session's `/btw` history,
48
+ and every later `/btw` call in the same session replays that history between the
49
+ branch clone and your new question. Follow-ups therefore work: the side thread
50
+ has its own memory.
51
+
52
+ History stores the **actual** `UserMessage` and `AssistantMessage` object
53
+ references returned by the call — nothing is reconstructed or re-serialised.
54
+ Concatenated in a fixed order, this keeps the prompt prefix byte-identical
55
+ across calls, so provider-side prompt caching keeps hitting.
56
+
57
+ Press `x` in the overlay to clear this session's history. It is also dropped when
58
+ the Pi process exits.
59
+
60
+ ## The cross-session hint
61
+
62
+ The system prompt gets an appendix listing the last **10** `/btw` *question
63
+ strings* from **all** sessions in the current Pi process, oldest first, under the
64
+ heading `## Recent /btw questions across sessions (oldest first)`. Each is
65
+ whitespace-collapsed and truncated to 200 characters.
66
+
67
+ - Only your question text crosses sessions — never answers, never branch content.
68
+ - The system prompt tells the model to treat it as a pattern hint, useful only
69
+ when the side question is itself about recent topics or trends.
70
+ - Clearing a session's history with `x` removes its contributions to the hint.
71
+ - It lives on the same process-scoped state, so it is gone when Pi exits.
72
+
73
+ ## The system prompt
74
+
75
+ `prompts/btw-system.txt` tells the side call to:
76
+
77
+ - treat the primary conversation as background, not as work to continue — the
78
+ side question is self-contained, and it must not pick up a tool call mid-flight;
79
+ - answer directly and concisely, in compact bullets or short paragraphs;
80
+ - cite files, functions, and line numbers when grounding a claim in the context;
81
+ - say so briefly when the context is insufficient, rather than guessing;
82
+ - use no tools and reply in plain text only, even if prior assistant turns in the
83
+ context demonstrate tool use.
84
+
85
+ ## What never happens
86
+
87
+ - **No transcript entry.** The answer is rendered through `ctx.ui.custom` as an
88
+ overlay component. It is never emitted as an agent message.
89
+ - **No disk writes.** History and snapshots live on `globalThis[Symbol.for("rpiv-btw")]`.
90
+ The package's only filesystem access is one read of its own bundled prompt file
91
+ at module init.
92
+ - **No tool use.** The call runs with `tools: []`, so a side question cannot edit
93
+ a file or run a command even if it wanted to.
94
+ - **No effect on the main session.** `Esc` aborts the `/btw` controller only; the
95
+ main agent's signal is never touched.