@juicesharp/rpiv-btw 0.1.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/LICENSE +21 -0
- package/README.md +88 -0
- package/btw-ui.ts +263 -0
- package/btw.ts +353 -0
- package/index.ts +21 -0
- package/package.json +36 -0
- package/prompts/btw-system.txt +9 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 juicesharp
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# @juicesharp/rpiv-btw
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@juicesharp/rpiv-btw)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
|
|
6
|
+
Ask a side question without polluting the main conversation. `rpiv-btw` adds `/btw <question>` to [Pi Agent](https://github.com/badlogic/pi-mono) — a lightweight side agent picks up a **read-only clone** of your current conversation and answers in a panel at the bottom of the terminal. The side agent remembers its own `/btw` thread for follow-ups, while your main chat keeps going — its transcript is never polluted.
|
|
7
|
+
|
|
8
|
+

|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pi install npm:@juicesharp/rpiv-btw
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Or, if you already have [`@juicesharp/rpiv-pi`](https://github.com/juicesharp/rpiv-pi) loaded, run `/rpiv-setup` from any Pi session — it installs this and the other siblings in one go.
|
|
17
|
+
|
|
18
|
+
Restart your Pi Agent session, then type `/btw` followed by your question:
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
/btw why did we switch from sockets to SSE last week?
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
### What you see
|
|
27
|
+
|
|
28
|
+
A panel opens at the bottom of the terminal with:
|
|
29
|
+
|
|
30
|
+
- your question on a banner,
|
|
31
|
+
- a `…` while the model is thinking,
|
|
32
|
+
- the answer when it arrives.
|
|
33
|
+
|
|
34
|
+
Prior `/btw` questions from the same session appear above the banner, so follow-ups have context.
|
|
35
|
+
|
|
36
|
+
### Keys
|
|
37
|
+
|
|
38
|
+
| Key | Action |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `↑` / `↓` | Scroll the panel (when its content overflows) |
|
|
41
|
+
| `x` | Clear this session's `/btw` history (hidden until you have a prior entry) |
|
|
42
|
+
| `Esc` | Close the panel; cancel the request if it's still running |
|
|
43
|
+
|
|
44
|
+
### What the model sees
|
|
45
|
+
|
|
46
|
+
The side agent is a fresh, tool-less instance of the same primary model, handed a read-only clone of your current conversation. When you press enter, `/btw` sends it:
|
|
47
|
+
|
|
48
|
+
1. A snapshot of your main conversation so far — so it knows what you've been working on. The side agent only reads the clone, so nothing it does pollutes your main transcript.
|
|
49
|
+
2. Your previous `/btw` questions and answers in this session — so follow-ups make sense.
|
|
50
|
+
3. The question you just typed.
|
|
51
|
+
|
|
52
|
+
### What it does *not* do
|
|
53
|
+
|
|
54
|
+
- Your main conversation is never polluted. The side answer lives only in the panel and in memory — it's not written to the agent's transcript or to disk.
|
|
55
|
+
- `/btw` has no tools. The model answers in plain text.
|
|
56
|
+
- History is lost when you exit Pi Agent. Your main session is unaffected.
|
|
57
|
+
|
|
58
|
+
## Commands
|
|
59
|
+
|
|
60
|
+
| Command | Description |
|
|
61
|
+
|---|---|
|
|
62
|
+
| `/btw <question>` | Ask a side question without polluting the main conversation |
|
|
63
|
+
|
|
64
|
+
## Architecture
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
rpiv-btw/
|
|
68
|
+
├── index.ts — extension entry; registers command + hooks
|
|
69
|
+
├── btw.ts — state, message threading, model call
|
|
70
|
+
├── btw-ui.ts — bottom panel renderer
|
|
71
|
+
└── prompts/
|
|
72
|
+
└── btw-system.txt — system prompt for the side call
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Pi Agent discovers the extension via `"pi": { "extensions": ["./index.ts"] }` in `package.json`.
|
|
76
|
+
|
|
77
|
+
## Troubleshooting
|
|
78
|
+
|
|
79
|
+
| Symptom | Cause | Fix |
|
|
80
|
+
|---|---|---|
|
|
81
|
+
| `/btw requires interactive mode` | Running in `pi --print …` or RPC mode | `/btw` needs a terminal — run Pi interactively |
|
|
82
|
+
| `/btw requires an active model` | No primary model configured | Set one with `/login` or edit `~/.pi/agent/models.json` |
|
|
83
|
+
| Panel opens but answer never arrives | Model call failed or network dropped | Press `Esc` to cancel; check your provider credentials |
|
|
84
|
+
| History missing after restart | Expected — no disk persistence | `/btw` history is per-Pi-process by design |
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
MIT
|
package/btw-ui.ts
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* btw-ui — dynamic-height bottom-slot overlay for /btw.
|
|
3
|
+
*
|
|
4
|
+
* Layout (grows with content, bottom-anchored, max = terminal height):
|
|
5
|
+
* banner (theme.bg stripe, padded to width) sticky top
|
|
6
|
+
* blank
|
|
7
|
+
* history — "/btw <q>" (accent prefix + muted text), left-padded 2 cols
|
|
8
|
+
* echo — "/btw <q>" (accent prefix + muted text), left-padded 2 cols
|
|
9
|
+
* blank
|
|
10
|
+
* answer — body wrapped at width-2, left-padded 2 cols
|
|
11
|
+
* blank
|
|
12
|
+
* footer — key hints (dim) sticky bottom
|
|
13
|
+
*
|
|
14
|
+
* Natural height = fixed(5: banner, 3 blanks, footer) + 2 (echo + 1 blank before answer)
|
|
15
|
+
* + history.length + answerLines.length.
|
|
16
|
+
* Pi-tui bottom-anchors the overlay so it grows upward with each /btw message.
|
|
17
|
+
* If natural height > terminal rows, we clip from the top (older history scrolls off)
|
|
18
|
+
* and ↑/↓ scroll the clip window.
|
|
19
|
+
*
|
|
20
|
+
* Keys (via matchesKey — handles ANSI + Kitty):
|
|
21
|
+
* Esc → abort in-flight call + dismiss
|
|
22
|
+
* ↑/↓ → scroll (when content exceeds terminal)
|
|
23
|
+
* x → clear current-session /btw history
|
|
24
|
+
* (f fork key deferred)
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import type {
|
|
28
|
+
ExtensionCommandContext,
|
|
29
|
+
Theme,
|
|
30
|
+
} from "@mariozechner/pi-coding-agent";
|
|
31
|
+
import {
|
|
32
|
+
Key,
|
|
33
|
+
matchesKey,
|
|
34
|
+
visibleWidth,
|
|
35
|
+
truncateToWidth,
|
|
36
|
+
wrapTextWithAnsi,
|
|
37
|
+
type Component,
|
|
38
|
+
type TUI,
|
|
39
|
+
} from "@mariozechner/pi-tui";
|
|
40
|
+
import type { OverlayOptions } from "@mariozechner/pi-tui";
|
|
41
|
+
import { userMessageText, type BtwTurn } from "./btw.js";
|
|
42
|
+
|
|
43
|
+
const BTW_OVERLAY_OPTIONS: OverlayOptions = {
|
|
44
|
+
anchor: "bottom-center",
|
|
45
|
+
width: "100%",
|
|
46
|
+
maxHeight: "85%",
|
|
47
|
+
margin: { left: 0, right: 0, bottom: 0 },
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const BTW_MAX_HEIGHT_RATIO = 0.85;
|
|
51
|
+
|
|
52
|
+
const SIDE_PAD = " "; // 2-col left gutter for history, echo, footer
|
|
53
|
+
const ANSWER_PAD = " "; // 4-col left gutter for answer body (double of SIDE_PAD)
|
|
54
|
+
const BTW_LITERAL = "/btw";
|
|
55
|
+
const PENDING_GLYPH = "…";
|
|
56
|
+
const FOOTER_SCROLL = "↑/↓ to scroll";
|
|
57
|
+
const FOOTER_CLEAR = "x to clear history";
|
|
58
|
+
const FOOTER_DISMISS = "Esc to dismiss";
|
|
59
|
+
const FOOTER_SEP = " · ";
|
|
60
|
+
|
|
61
|
+
type Mode = "pending" | "answer" | "error";
|
|
62
|
+
|
|
63
|
+
export interface ShowBtwOverlayParams {
|
|
64
|
+
ctx: ExtensionCommandContext;
|
|
65
|
+
question: string;
|
|
66
|
+
history: BtwTurn[];
|
|
67
|
+
controller: AbortController;
|
|
68
|
+
onClearHistory: () => void;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface ShowBtwOverlayResult {
|
|
72
|
+
overlayPromise: Promise<void>;
|
|
73
|
+
controllerReady: Promise<BtwOverlayController>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export class BtwOverlayController implements Component {
|
|
77
|
+
private mode: Mode = "pending";
|
|
78
|
+
private answer = "";
|
|
79
|
+
private error = "";
|
|
80
|
+
private scrollOffset = 0;
|
|
81
|
+
private history: BtwTurn[];
|
|
82
|
+
|
|
83
|
+
constructor(
|
|
84
|
+
private readonly question: string,
|
|
85
|
+
history: BtwTurn[],
|
|
86
|
+
private readonly theme: Theme,
|
|
87
|
+
private readonly tui: TUI,
|
|
88
|
+
private readonly done: (result: void) => void,
|
|
89
|
+
private readonly controller: AbortController,
|
|
90
|
+
private readonly onClearHistory: () => void,
|
|
91
|
+
) {
|
|
92
|
+
this.history = [...history];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
setAnswer(text: string): void {
|
|
96
|
+
this.mode = "answer";
|
|
97
|
+
this.answer = text;
|
|
98
|
+
this.tui.requestRender();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
setError(message: string): void {
|
|
102
|
+
this.mode = "error";
|
|
103
|
+
this.error = message;
|
|
104
|
+
this.tui.requestRender();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
handleInput(data: string): void {
|
|
108
|
+
if (matchesKey(data, Key.escape)) {
|
|
109
|
+
this.controller.abort();
|
|
110
|
+
this.done();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (matchesKey(data, Key.up)) {
|
|
114
|
+
this.scrollOffset = Math.max(0, this.scrollOffset - 1);
|
|
115
|
+
this.tui.requestRender();
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (matchesKey(data, Key.down)) {
|
|
119
|
+
this.scrollOffset = this.scrollOffset + 1;
|
|
120
|
+
this.tui.requestRender();
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (data === "x") {
|
|
124
|
+
this.history = [];
|
|
125
|
+
this.onClearHistory();
|
|
126
|
+
this.scrollOffset = 0;
|
|
127
|
+
this.tui.requestRender();
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
render(width: number): string[] {
|
|
133
|
+
const banner = this.renderBanner(width);
|
|
134
|
+
const historyLines = this.history.map((h) =>
|
|
135
|
+
this.historyLine(userMessageText(h.userMessage), width),
|
|
136
|
+
);
|
|
137
|
+
const echoLine = this.echoLine(this.question, width);
|
|
138
|
+
const answerLines = this.renderAnswer(width);
|
|
139
|
+
const footerAvail = Math.max(1, width - SIDE_PAD.length);
|
|
140
|
+
const footerParts: string[] = [];
|
|
141
|
+
if (this.mode !== "pending") footerParts.push(FOOTER_SCROLL);
|
|
142
|
+
if (this.history.length > 0) footerParts.push(FOOTER_CLEAR);
|
|
143
|
+
footerParts.push(FOOTER_DISMISS);
|
|
144
|
+
const footer =
|
|
145
|
+
SIDE_PAD +
|
|
146
|
+
truncateToWidth(
|
|
147
|
+
this.theme.fg("dim", footerParts.join(FOOTER_SEP)),
|
|
148
|
+
footerAvail,
|
|
149
|
+
"…",
|
|
150
|
+
false,
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
// Natural content: banner + blank + history + echo + blank + answer + blank + footer
|
|
154
|
+
const natural: string[] = [
|
|
155
|
+
banner,
|
|
156
|
+
"",
|
|
157
|
+
...historyLines,
|
|
158
|
+
echoLine,
|
|
159
|
+
"",
|
|
160
|
+
...answerLines,
|
|
161
|
+
"",
|
|
162
|
+
footer,
|
|
163
|
+
];
|
|
164
|
+
|
|
165
|
+
// Clip to terminal height if we overflow. Bottom-anchor keeps footer+answer visible;
|
|
166
|
+
// ↑/↓ scrolls the top (history) up into the clipped region.
|
|
167
|
+
const termRows = (this.tui.terminal as { rows?: number }).rows ?? 24;
|
|
168
|
+
const maxRows = Math.max(4, Math.floor(termRows * BTW_MAX_HEIGHT_RATIO));
|
|
169
|
+
if (natural.length <= maxRows) {
|
|
170
|
+
return natural;
|
|
171
|
+
}
|
|
172
|
+
const excess = natural.length - maxRows;
|
|
173
|
+
if (this.scrollOffset > excess) this.scrollOffset = excess;
|
|
174
|
+
// scrollOffset=0 shows the BOTTOM (newest). Scrolling up reveals older history.
|
|
175
|
+
const start = excess - this.scrollOffset;
|
|
176
|
+
return natural.slice(start, start + maxRows);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
invalidate(): void {
|
|
180
|
+
// no-op — render recomputes from state each cycle
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private renderBanner(width: number): string {
|
|
184
|
+
const prefix = `${SIDE_PAD}${BTW_LITERAL} `;
|
|
185
|
+
const prefixWidth = visibleWidth(prefix);
|
|
186
|
+
const qAvail = Math.max(0, width - prefixWidth);
|
|
187
|
+
const qTrunc = truncateToWidth(this.question, qAvail, "…", false);
|
|
188
|
+
const raw = prefix + qTrunc;
|
|
189
|
+
const padded = raw + " ".repeat(Math.max(0, width - visibleWidth(raw)));
|
|
190
|
+
return this.theme.bg("customMessageBg", this.theme.fg("customMessageText", padded));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private historyLine(question: string, width: number): string {
|
|
194
|
+
const qAvail = Math.max(0, width - SIDE_PAD.length);
|
|
195
|
+
const qClean = question.replace(/\s+/g, " ").trim();
|
|
196
|
+
const raw = `${BTW_LITERAL} ${qClean}`;
|
|
197
|
+
const trunc = truncateToWidth(raw, qAvail, "…", false);
|
|
198
|
+
return SIDE_PAD + this.theme.fg("muted", trunc);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private echoLine(question: string, width: number): string {
|
|
202
|
+
const bodyAvail = Math.max(1, width - SIDE_PAD.length);
|
|
203
|
+
const prefixWidth = visibleWidth(BTW_LITERAL) + 1; // "/btw "
|
|
204
|
+
const qAvail = Math.max(0, bodyAvail - prefixWidth);
|
|
205
|
+
const qClean = question.replace(/\s+/g, " ").trim();
|
|
206
|
+
const qTrunc = truncateToWidth(qClean, qAvail, "…", false);
|
|
207
|
+
return (
|
|
208
|
+
SIDE_PAD +
|
|
209
|
+
this.theme.fg("accent", BTW_LITERAL) +
|
|
210
|
+
" " +
|
|
211
|
+
this.theme.fg("muted", qTrunc)
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private renderAnswer(width: number): string[] {
|
|
216
|
+
const bodyWidth = Math.max(1, width - ANSWER_PAD.length);
|
|
217
|
+
const indent = (lines: string[]) => lines.map((l) => ANSWER_PAD + l);
|
|
218
|
+
|
|
219
|
+
if (this.mode === "pending") {
|
|
220
|
+
return indent([this.theme.fg("warning", PENDING_GLYPH)]);
|
|
221
|
+
}
|
|
222
|
+
if (this.mode === "error") {
|
|
223
|
+
const out: string[] = [];
|
|
224
|
+
for (const ln of this.error.split("\n")) {
|
|
225
|
+
const src = ln.length === 0 ? " " : ln;
|
|
226
|
+
out.push(...wrapTextWithAnsi(this.theme.fg("error", src), bodyWidth));
|
|
227
|
+
}
|
|
228
|
+
return indent(out);
|
|
229
|
+
}
|
|
230
|
+
const out: string[] = [];
|
|
231
|
+
for (const ln of this.answer.split("\n")) {
|
|
232
|
+
const src = ln.length === 0 ? " " : ln;
|
|
233
|
+
out.push(...wrapTextWithAnsi(src, bodyWidth));
|
|
234
|
+
}
|
|
235
|
+
return indent(out);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function showBtwOverlay(params: ShowBtwOverlayParams): ShowBtwOverlayResult {
|
|
240
|
+
let resolveReady!: (controller: BtwOverlayController) => void;
|
|
241
|
+
const controllerReady = new Promise<BtwOverlayController>((resolve) => {
|
|
242
|
+
resolveReady = resolve;
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
const overlayPromise = params.ctx.ui.custom<void>(
|
|
246
|
+
(tui, theme, _kb, done) => {
|
|
247
|
+
const controller = new BtwOverlayController(
|
|
248
|
+
params.question,
|
|
249
|
+
params.history,
|
|
250
|
+
theme,
|
|
251
|
+
tui,
|
|
252
|
+
done,
|
|
253
|
+
params.controller,
|
|
254
|
+
params.onClearHistory,
|
|
255
|
+
);
|
|
256
|
+
resolveReady(controller);
|
|
257
|
+
return controller;
|
|
258
|
+
},
|
|
259
|
+
{ overlay: true, overlayOptions: BTW_OVERLAY_OPTIONS },
|
|
260
|
+
);
|
|
261
|
+
|
|
262
|
+
return { overlayPromise, controllerReady };
|
|
263
|
+
}
|
package/btw.ts
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @juicesharp/rpiv-btw — /btw side-question slash command.
|
|
3
|
+
*
|
|
4
|
+
* Asks the same primary model a one-off side question using the cloned primary
|
|
5
|
+
* conversation as context. Answer is rendered ephemerally in a bottom-slot
|
|
6
|
+
* overlay (never enters main agent's messages). History persists per-session-file
|
|
7
|
+
* via globalThis-keyed storage; process-scoped only (no disk persistence).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readFileSync } from "node:fs";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import {
|
|
13
|
+
completeSimple,
|
|
14
|
+
type AssistantMessage,
|
|
15
|
+
type Message,
|
|
16
|
+
type StopReason,
|
|
17
|
+
type UserMessage,
|
|
18
|
+
} from "@mariozechner/pi-ai";
|
|
19
|
+
import {
|
|
20
|
+
convertToLlm,
|
|
21
|
+
type ExtensionAPI,
|
|
22
|
+
type ExtensionCommandContext,
|
|
23
|
+
type ExtensionContext,
|
|
24
|
+
type SessionEntry,
|
|
25
|
+
} from "@mariozechner/pi-coding-agent";
|
|
26
|
+
import { showBtwOverlay } from "./btw-ui.js";
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Constants — flat named consts, grouped by concern (advisor pattern, b9428e9)
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
// Identity
|
|
33
|
+
export const BTW_COMMAND_NAME = "btw";
|
|
34
|
+
|
|
35
|
+
// Storage — globalThis-keyed survives module re-import on /new, /fork, /resume.
|
|
36
|
+
// Lost on Pi process exit (intentional — no disk persistence).
|
|
37
|
+
export const BTW_STATE_KEY = Symbol.for("rpiv-btw");
|
|
38
|
+
|
|
39
|
+
// Cross-session pattern hint: how many recent question-strings to inject
|
|
40
|
+
export const CROSS_SESSION_HINT_LIMIT = 10;
|
|
41
|
+
|
|
42
|
+
// Messages (static)
|
|
43
|
+
const MSG_REQUIRES_INTERACTIVE = "/btw requires interactive mode";
|
|
44
|
+
const MSG_USAGE = "Usage: /btw <question>";
|
|
45
|
+
const MSG_NO_MODEL = "/btw requires an active model";
|
|
46
|
+
|
|
47
|
+
// Errors (static)
|
|
48
|
+
const ERR_EMPTY_RESPONSE = "/btw returned no text content.";
|
|
49
|
+
|
|
50
|
+
// Errors (parameterized)
|
|
51
|
+
const errMisconfigured = (label: string, err: string) => `/btw model (${label}) is misconfigured: ${err}`;
|
|
52
|
+
const errNoApiKey = (label: string) => `/btw model (${label}) has no API key available.`;
|
|
53
|
+
const errCallFailed = (err: string | undefined) => `/btw call failed: ${err ?? "unknown error"}`;
|
|
54
|
+
const errCallThrew = (msg: string) => `/btw call threw: ${msg}`;
|
|
55
|
+
|
|
56
|
+
// ---------------------------------------------------------------------------
|
|
57
|
+
// Types
|
|
58
|
+
// ---------------------------------------------------------------------------
|
|
59
|
+
|
|
60
|
+
// Real messages — no fabrication. userMessage is built at call time; assistantMessage
|
|
61
|
+
// is the unmodified completeSimple response. Stable object references across calls →
|
|
62
|
+
// byte-identical prompt prefix on subsequent /btw invocations (cache parity).
|
|
63
|
+
export interface BtwTurn {
|
|
64
|
+
userMessage: UserMessage;
|
|
65
|
+
assistantMessage: AssistantMessage;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface BtwState {
|
|
69
|
+
histories: Map<string, BtwTurn[]>;
|
|
70
|
+
snapshots: Map<string, { messages: Message[] }>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// System prompt — loaded once at module init from prompts/btw-system.txt
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
export const BTW_SYSTEM_PROMPT = readFileSync(
|
|
78
|
+
fileURLToPath(new URL("./prompts/btw-system.txt", import.meta.url)),
|
|
79
|
+
"utf-8",
|
|
80
|
+
).trimEnd();
|
|
81
|
+
|
|
82
|
+
// ---------------------------------------------------------------------------
|
|
83
|
+
// Storage — globalThis-keyed, survives module re-import on /new, /fork, /resume
|
|
84
|
+
// Mirrors @tintinweb/pi-subagents/src/index.ts:413-422 pattern
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
function getState(): BtwState {
|
|
88
|
+
const g = globalThis as unknown as { [k: symbol]: BtwState | undefined };
|
|
89
|
+
let state = g[BTW_STATE_KEY];
|
|
90
|
+
if (!state) {
|
|
91
|
+
state = {
|
|
92
|
+
histories: new Map(),
|
|
93
|
+
snapshots: new Map(),
|
|
94
|
+
};
|
|
95
|
+
g[BTW_STATE_KEY] = state;
|
|
96
|
+
}
|
|
97
|
+
return state;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function getSessionFile(ctx: ExtensionContext): string {
|
|
101
|
+
return ctx.sessionManager.getSessionFile() ?? `memory:${ctx.sessionManager.getSessionId()}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function getSessionHistory(ctx: ExtensionContext): BtwTurn[] {
|
|
105
|
+
const key = getSessionFile(ctx);
|
|
106
|
+
const state = getState();
|
|
107
|
+
let turns = state.histories.get(key);
|
|
108
|
+
if (!turns) {
|
|
109
|
+
turns = [];
|
|
110
|
+
state.histories.set(key, turns);
|
|
111
|
+
}
|
|
112
|
+
return turns;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function pushSessionTurn(ctx: ExtensionContext, turn: BtwTurn): void {
|
|
116
|
+
getSessionHistory(ctx).push(turn);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function clearSessionHistory(ctx: ExtensionContext): void {
|
|
120
|
+
getState().histories.set(getSessionFile(ctx), []);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function getSnapshot(ctx: ExtensionContext): { messages: Message[] } | undefined {
|
|
124
|
+
return getState().snapshots.get(getSessionFile(ctx));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function setSnapshot(ctx: ExtensionContext, snapshot: { messages: Message[] }): void {
|
|
128
|
+
getState().snapshots.set(getSessionFile(ctx), snapshot);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function invalidateSnapshot(ctx: ExtensionContext): void {
|
|
132
|
+
getState().snapshots.delete(getSessionFile(ctx));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Extract text from a UserMessage's content.
|
|
136
|
+
export function userMessageText(msg: UserMessage): string {
|
|
137
|
+
if (typeof msg.content === "string") return msg.content;
|
|
138
|
+
return msg.content
|
|
139
|
+
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
140
|
+
.map((c) => c.text)
|
|
141
|
+
.join("\n");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Extract text from an AssistantMessage's content (text parts only).
|
|
145
|
+
export function assistantMessageText(msg: AssistantMessage): string {
|
|
146
|
+
return msg.content
|
|
147
|
+
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
148
|
+
.map((c) => c.text)
|
|
149
|
+
.join("\n");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Cross-session pattern hint — last N question-strings across ALL sessions.
|
|
153
|
+
function getCrossSessionHint(): string {
|
|
154
|
+
const allTurns: { q: string; ts: number }[] = [];
|
|
155
|
+
for (const turns of getState().histories.values()) {
|
|
156
|
+
for (const t of turns) {
|
|
157
|
+
allTurns.push({ q: userMessageText(t.userMessage), ts: t.userMessage.timestamp });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (allTurns.length === 0) return "";
|
|
161
|
+
const recent = allTurns
|
|
162
|
+
.sort((a, b) => a.ts - b.ts)
|
|
163
|
+
.slice(-CROSS_SESSION_HINT_LIMIT);
|
|
164
|
+
const lines = recent.map((t, i) => `${i + 1}. ${t.q.replace(/\s+/g, " ").slice(0, 200)}`);
|
|
165
|
+
return `\n\n## Recent /btw questions across sessions (oldest first)\n\n${lines.join("\n")}`;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---------------------------------------------------------------------------
|
|
169
|
+
// Executor — auth, message threading, completeSimple, four StopReason branches
|
|
170
|
+
// Modeled after rpiv-advisor/advisor.ts:225-336
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
export interface BtwExecResult {
|
|
174
|
+
ok: boolean;
|
|
175
|
+
answer?: string;
|
|
176
|
+
userMessage?: UserMessage;
|
|
177
|
+
assistantMessage?: AssistantMessage;
|
|
178
|
+
error?: string;
|
|
179
|
+
stopReason?: StopReason;
|
|
180
|
+
aborted?: boolean;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function readBranchMessages(ctx: ExtensionContext): Message[] {
|
|
184
|
+
const cached = getSnapshot(ctx);
|
|
185
|
+
if (cached) return cached.messages;
|
|
186
|
+
// Cold start (no message_end fired yet) — fall back to live read
|
|
187
|
+
const branch = ctx.sessionManager.getBranch() as SessionEntry[];
|
|
188
|
+
const agentMessages = branch
|
|
189
|
+
.filter((e): e is SessionEntry & { type: "message" } => e.type === "message")
|
|
190
|
+
.map((e) => e.message);
|
|
191
|
+
return convertToLlm(agentMessages);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function buildBtwMessages(ctx: ExtensionContext, userMessage: UserMessage): Message[] {
|
|
195
|
+
const branchMessages = readBranchMessages(ctx);
|
|
196
|
+
const history = getSessionHistory(ctx);
|
|
197
|
+
// Reusing stored real UserMessage/AssistantMessage object references across calls
|
|
198
|
+
// preserves byte-identical prompt prefix (cache parity).
|
|
199
|
+
const historyMessages: Message[] = history.flatMap((h) => [h.userMessage, h.assistantMessage]);
|
|
200
|
+
return [...branchMessages, ...historyMessages, userMessage];
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function buildSystemPrompt(): string {
|
|
204
|
+
return BTW_SYSTEM_PROMPT + getCrossSessionHint();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export async function executeBtw(
|
|
208
|
+
question: string,
|
|
209
|
+
ctx: ExtensionContext,
|
|
210
|
+
controller: AbortController,
|
|
211
|
+
): Promise<BtwExecResult> {
|
|
212
|
+
const model = ctx.model;
|
|
213
|
+
if (!model) {
|
|
214
|
+
return { ok: false, error: MSG_NO_MODEL };
|
|
215
|
+
}
|
|
216
|
+
const modelLabel = `${model.provider}:${model.id}`;
|
|
217
|
+
|
|
218
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
219
|
+
if (!auth.ok) {
|
|
220
|
+
return { ok: false, error: errMisconfigured(modelLabel, auth.error) };
|
|
221
|
+
}
|
|
222
|
+
if (!auth.apiKey) {
|
|
223
|
+
return { ok: false, error: errNoApiKey(modelLabel) };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const userMessage: UserMessage = {
|
|
227
|
+
role: "user",
|
|
228
|
+
content: [{ type: "text", text: question }],
|
|
229
|
+
timestamp: Date.now(),
|
|
230
|
+
};
|
|
231
|
+
const messages = buildBtwMessages(ctx, userMessage);
|
|
232
|
+
const systemPrompt = buildSystemPrompt();
|
|
233
|
+
|
|
234
|
+
try {
|
|
235
|
+
const response = await completeSimple(
|
|
236
|
+
model,
|
|
237
|
+
{ systemPrompt, messages, tools: [] },
|
|
238
|
+
{
|
|
239
|
+
apiKey: auth.apiKey,
|
|
240
|
+
headers: auth.headers,
|
|
241
|
+
signal: controller.signal, // own AbortController, NOT ctx.signal (Decision 8)
|
|
242
|
+
},
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
if (response.stopReason === "aborted") {
|
|
246
|
+
return { ok: false, aborted: true, stopReason: response.stopReason };
|
|
247
|
+
}
|
|
248
|
+
if (response.stopReason === "error") {
|
|
249
|
+
return {
|
|
250
|
+
ok: false,
|
|
251
|
+
error: errCallFailed(response.errorMessage),
|
|
252
|
+
stopReason: response.stopReason,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const answerText = assistantMessageText(response).trim();
|
|
257
|
+
if (!answerText) {
|
|
258
|
+
return { ok: false, error: ERR_EMPTY_RESPONSE, stopReason: response.stopReason };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return {
|
|
262
|
+
ok: true,
|
|
263
|
+
answer: answerText,
|
|
264
|
+
userMessage,
|
|
265
|
+
assistantMessage: response,
|
|
266
|
+
stopReason: response.stopReason,
|
|
267
|
+
};
|
|
268
|
+
} catch (err) {
|
|
269
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
270
|
+
if (controller.signal.aborted) {
|
|
271
|
+
return { ok: false, aborted: true };
|
|
272
|
+
}
|
|
273
|
+
return { ok: false, error: errCallThrew(message) };
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// ---------------------------------------------------------------------------
|
|
278
|
+
// Registrars — 3 hooks total: command + message_end snapshot + compact/tree invalidate
|
|
279
|
+
// ---------------------------------------------------------------------------
|
|
280
|
+
|
|
281
|
+
export function registerMessageEndSnapshot(pi: ExtensionAPI): void {
|
|
282
|
+
pi.on("message_end", async (event, ctx) => {
|
|
283
|
+
const msg = event.message;
|
|
284
|
+
if (msg.role !== "assistant") return;
|
|
285
|
+
if ((msg as AssistantMessage).stopReason === "toolUse") return;
|
|
286
|
+
const branch = ctx.sessionManager.getBranch() as SessionEntry[];
|
|
287
|
+
const agentMessages = branch
|
|
288
|
+
.filter((e): e is SessionEntry & { type: "message" } => e.type === "message")
|
|
289
|
+
.map((e) => e.message);
|
|
290
|
+
setSnapshot(ctx, { messages: convertToLlm(agentMessages) });
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export function registerInvalidationHooks(pi: ExtensionAPI): void {
|
|
295
|
+
pi.on("session_compact", async (_e, ctx) => invalidateSnapshot(ctx));
|
|
296
|
+
pi.on("session_tree", async (_e, ctx) => invalidateSnapshot(ctx));
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function registerBtwCommand(pi: ExtensionAPI): void {
|
|
300
|
+
pi.registerCommand(BTW_COMMAND_NAME, {
|
|
301
|
+
description: "Ask a side question without polluting the main conversation",
|
|
302
|
+
handler: (args: string, ctx: ExtensionCommandContext) => handleBtwCommand(pi, args, ctx),
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async function handleBtwCommand(
|
|
307
|
+
_pi: ExtensionAPI,
|
|
308
|
+
args: string,
|
|
309
|
+
ctx: ExtensionCommandContext,
|
|
310
|
+
): Promise<void> {
|
|
311
|
+
if (!ctx.hasUI) {
|
|
312
|
+
ctx.ui.notify(MSG_REQUIRES_INTERACTIVE, "error");
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
const question = args.trim();
|
|
316
|
+
if (!question) {
|
|
317
|
+
ctx.ui.notify(MSG_USAGE, "warning");
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (!ctx.model) {
|
|
321
|
+
ctx.ui.notify(MSG_NO_MODEL, "error");
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const controller = new AbortController();
|
|
326
|
+
const historySnapshot = [...getSessionHistory(ctx)];
|
|
327
|
+
|
|
328
|
+
const { overlayPromise, controllerReady } = showBtwOverlay({
|
|
329
|
+
ctx,
|
|
330
|
+
question,
|
|
331
|
+
history: historySnapshot,
|
|
332
|
+
controller,
|
|
333
|
+
onClearHistory: () => clearSessionHistory(ctx),
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
const overlayCtl = await controllerReady;
|
|
337
|
+
const result = await executeBtw(question, ctx, controller);
|
|
338
|
+
|
|
339
|
+
if (result.ok && result.answer && result.userMessage && result.assistantMessage) {
|
|
340
|
+
overlayCtl.setAnswer(result.answer);
|
|
341
|
+
pushSessionTurn(ctx, {
|
|
342
|
+
userMessage: result.userMessage,
|
|
343
|
+
assistantMessage: result.assistantMessage,
|
|
344
|
+
});
|
|
345
|
+
// No disk persistence — process-scoped only (Decision 4)
|
|
346
|
+
} else if (result.aborted) {
|
|
347
|
+
// User Esc'd — overlay already dismissed via done(); no further action
|
|
348
|
+
} else if (result.error) {
|
|
349
|
+
overlayCtl.setError(result.error);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
await overlayPromise;
|
|
353
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @juicesharp/rpiv-btw — Pi extension entry point.
|
|
3
|
+
*
|
|
4
|
+
* Registers /btw command + 2 lifecycle hooks (message_end snapshot,
|
|
5
|
+
* session_compact/tree invalidation). No tool, no model picker, no disk
|
|
6
|
+
* persistence. History lives in process-scoped globalThis state — survives
|
|
7
|
+
* /new, /fork, /reload, /resume; lost on Pi process exit.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
11
|
+
import {
|
|
12
|
+
registerBtwCommand,
|
|
13
|
+
registerInvalidationHooks,
|
|
14
|
+
registerMessageEndSnapshot,
|
|
15
|
+
} from "./btw.js";
|
|
16
|
+
|
|
17
|
+
export default function (pi: ExtensionAPI): void {
|
|
18
|
+
registerBtwCommand(pi);
|
|
19
|
+
registerMessageEndSnapshot(pi);
|
|
20
|
+
registerInvalidationHooks(pi);
|
|
21
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@juicesharp/rpiv-btw",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Pi extension: /btw side-question slash command — ask the same primary model a one-off side question without polluting the main conversation",
|
|
5
|
+
"keywords": ["pi-package", "pi-extension", "rpiv", "btw", "side-question", "overlay"],
|
|
6
|
+
"type": "module",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "juicesharp",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/juicesharp/rpiv-btw.git"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/juicesharp/rpiv-btw#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/juicesharp/rpiv-btw/issues"
|
|
16
|
+
},
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"index.ts",
|
|
22
|
+
"btw.ts",
|
|
23
|
+
"btw-ui.ts",
|
|
24
|
+
"prompts/",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"pi": {
|
|
29
|
+
"extensions": ["./index.ts"]
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@mariozechner/pi-ai": "*",
|
|
33
|
+
"@mariozechner/pi-coding-agent": "*",
|
|
34
|
+
"@mariozechner/pi-tui": "*"
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
You are answering a quick side question while the user's main pi session continues working.
|
|
2
|
+
|
|
3
|
+
You are given the user's primary conversation as the message context — treat it as background. Do NOT try to "continue" the assistant's prior work or pick up a tool call mid-flight; the side question is its own self-contained ask.
|
|
4
|
+
|
|
5
|
+
Answer directly and concisely. Prefer compact bullets or short paragraphs. Cite files, functions, and line numbers when grounding a claim in the context. If the context is insufficient to answer, say so briefly instead of guessing.
|
|
6
|
+
|
|
7
|
+
You have NO tools available. You will NOT call tools, even if the prior assistant turns demonstrate tool use. Reply in plain text only.
|
|
8
|
+
|
|
9
|
+
When a "Recent /btw questions across sessions" appendix is present below, treat it as a high-level pattern hint about what the user has been thinking about lately — useful only when the side question explicitly asks about patterns, trends, or recent topics.
|