pi-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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dan Bachelder
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,89 @@
1
+ # pi-btw
2
+
3
+ A small [pi](https://github.com/badlogic/pi-mono) extension that adds a `/btw` command for side questions.
4
+
5
+ `/btw` runs immediately, even while the main agent is still busy.
6
+
7
+ ![BTW overlay example](docs/btw-overlay.png)
8
+
9
+ ## What it does
10
+
11
+ - asks a one-off side question using the current session context
12
+ - returns an answer immediately in an overlay
13
+ - does **not** disturb the running agent
14
+ - does **not** save anything by default
15
+ - optionally saves the result into the session with `--save`
16
+
17
+ Saved BTW notes are visible in the session transcript, but excluded from future LLM context.
18
+
19
+ ## Install
20
+
21
+ ### From npm (after publish)
22
+
23
+ ```bash
24
+ pi install npm:pi-btw
25
+ ```
26
+
27
+ ### From git
28
+
29
+ ```bash
30
+ pi install git:github.com/dbachelder/pi-btw
31
+ ```
32
+
33
+ Then reload pi:
34
+
35
+ ```text
36
+ /reload
37
+ ```
38
+
39
+ ### From a local checkout
40
+
41
+ ```bash
42
+ pi install /absolute/path/to/pi-btw
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ```text
48
+ /btw what file defines this route?
49
+ /btw --save what file defines this route?
50
+ /btw -s summarize the last error in one sentence
51
+ ```
52
+
53
+ ## Behavior
54
+
55
+ ### `/btw <question>`
56
+
57
+ - runs right away
58
+ - shows the answer in an overlay
59
+ - does not save it to the session
60
+
61
+ ### `/btw --save <question>`
62
+
63
+ - if pi is idle: saves the BTW note immediately
64
+ - if pi is busy: queues the BTW note and saves it after the current turn finishes
65
+ - does not steer or interrupt the current agent run
66
+
67
+ ## Why
68
+
69
+ Sometimes you want to ask a quick side question without:
70
+
71
+ - interrupting the current turn
72
+ - adding noise to the main transcript
73
+ - waiting for another user turn
74
+
75
+ ## Development
76
+
77
+ The extension entrypoint is:
78
+
79
+ - `extensions/btw.ts`
80
+
81
+ To use it without installing:
82
+
83
+ ```bash
84
+ pi -e /path/to/pi-btw
85
+ ```
86
+
87
+ ## License
88
+
89
+ MIT
Binary file
@@ -0,0 +1,350 @@
1
+ import {
2
+ BorderedLoader,
3
+ buildSessionContext,
4
+ type ExtensionAPI,
5
+ type ExtensionCommandContext,
6
+ type Theme,
7
+ } from "@mariozechner/pi-coding-agent";
8
+ import { streamSimple, type AssistantMessage, type ThinkingLevel as AiThinkingLevel } from "@mariozechner/pi-ai";
9
+ import { Box, Key, Text, matchesKey } from "@mariozechner/pi-tui";
10
+
11
+ const BTW_MESSAGE_TYPE = "btw-note";
12
+
13
+ type SessionThinkingLevel = "off" | AiThinkingLevel;
14
+
15
+ type BtwDetails = {
16
+ question: string;
17
+ answer: string;
18
+ provider: string;
19
+ model: string;
20
+ thinkingLevel: SessionThinkingLevel;
21
+ timestamp: number;
22
+ usage?: AssistantMessage["usage"];
23
+ };
24
+
25
+ type ParsedBtwArgs = {
26
+ question: string;
27
+ save: boolean;
28
+ };
29
+
30
+ type SaveState = "not-saved" | "saved" | "queued";
31
+
32
+ class BtwAnswerOverlay {
33
+ private box: Box;
34
+
35
+ constructor(
36
+ private theme: Theme,
37
+ private question: string,
38
+ private answer: string,
39
+ private saveState: SaveState,
40
+ private done: () => void,
41
+ ) {
42
+ this.box = this.buildBox();
43
+ }
44
+
45
+ handleInput(data: string): void {
46
+ if (matchesKey(data, Key.enter) || matchesKey(data, Key.escape)) {
47
+ this.done();
48
+ }
49
+ }
50
+
51
+ render(width: number): string[] {
52
+ return this.box.render(width);
53
+ }
54
+
55
+ invalidate(): void {
56
+ this.box = this.buildBox();
57
+ this.box.invalidate();
58
+ }
59
+
60
+ dispose(): void {}
61
+
62
+ private buildBox(): Box {
63
+ const footer =
64
+ this.saveState === "saved"
65
+ ? this.theme.fg("success", "Saved to the session.")
66
+ : this.saveState === "queued"
67
+ ? this.theme.fg("success", "Will be saved after the current turn finishes.")
68
+ : this.theme.fg("dim", "Not saved. Run /btw --save ... to persist it.");
69
+
70
+ const lines = [
71
+ this.theme.fg("accent", this.theme.bold("[BTW]")),
72
+ "",
73
+ this.theme.fg("dim", "Q:"),
74
+ this.question,
75
+ "",
76
+ this.theme.fg("dim", "A:"),
77
+ this.answer,
78
+ "",
79
+ footer,
80
+ this.theme.fg("dim", "Enter/Esc to dismiss"),
81
+ ];
82
+
83
+ const box = new Box(1, 1, (text) => this.theme.bg("customMessageBg", text));
84
+ box.addChild(new Text(lines.join("\n"), 0, 0));
85
+ return box;
86
+ }
87
+ }
88
+
89
+ function isBtwMessage(message: { role: string; customType?: string }): boolean {
90
+ return message.role === "custom" && message.customType === BTW_MESSAGE_TYPE;
91
+ }
92
+
93
+ function toReasoning(level: SessionThinkingLevel): AiThinkingLevel | undefined {
94
+ return level === "off" ? undefined : level;
95
+ }
96
+
97
+ function extractAnswer(message: AssistantMessage): string {
98
+ const text = message.content
99
+ .filter((part): part is { type: "text"; text: string } => part.type === "text")
100
+ .map((part) => part.text)
101
+ .join("\n")
102
+ .trim();
103
+
104
+ return text || "(No text response)";
105
+ }
106
+
107
+ function parseBtwArgs(args: string): ParsedBtwArgs {
108
+ const save = /(?:^|\s)(?:--save|-s)(?=\s|$)/.test(args);
109
+ const question = args.replace(/(?:^|\s)(?:--save|-s)(?=\s|$)/g, " ").trim();
110
+ return { question, save };
111
+ }
112
+
113
+ function buildBtwContext(ctx: ExtensionCommandContext, question: string) {
114
+ const sessionContext = buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId());
115
+ const messages = sessionContext.messages.filter((message) => !isBtwMessage(message));
116
+
117
+ return {
118
+ systemPrompt: ctx.getSystemPrompt(),
119
+ messages: [
120
+ ...messages,
121
+ {
122
+ role: "user" as const,
123
+ content: [{ type: "text" as const, text: question }],
124
+ timestamp: Date.now(),
125
+ },
126
+ ],
127
+ };
128
+ }
129
+
130
+ async function runBtw(
131
+ ctx: ExtensionCommandContext,
132
+ question: string,
133
+ thinkingLevel: SessionThinkingLevel,
134
+ signal?: AbortSignal,
135
+ ): Promise<AssistantMessage | null> {
136
+ const model = ctx.model;
137
+ if (!model) {
138
+ throw new Error("No active model selected.");
139
+ }
140
+
141
+ const apiKey = await ctx.modelRegistry.getApiKey(model);
142
+ if (!apiKey) {
143
+ throw new Error(`No credentials available for ${model.provider}/${model.id}.`);
144
+ }
145
+
146
+ const stream = streamSimple(model, buildBtwContext(ctx, question), {
147
+ apiKey,
148
+ reasoning: toReasoning(thinkingLevel),
149
+ signal,
150
+ });
151
+
152
+ const response = await stream.result();
153
+ if (response.stopReason === "aborted") {
154
+ return null;
155
+ }
156
+ if (response.stopReason === "error") {
157
+ throw new Error(response.errorMessage || "BTW request failed.");
158
+ }
159
+
160
+ return response;
161
+ }
162
+
163
+ function buildBtwMessageContent(question: string, answer: string): string {
164
+ return `Q: ${question}\n\nA: ${answer}`;
165
+ }
166
+
167
+ function saveBtwNote(
168
+ pi: ExtensionAPI,
169
+ details: BtwDetails,
170
+ saveRequested: boolean,
171
+ wasBusy: boolean,
172
+ ): SaveState {
173
+ if (!saveRequested) {
174
+ return "not-saved";
175
+ }
176
+
177
+ const message = {
178
+ customType: BTW_MESSAGE_TYPE,
179
+ content: buildBtwMessageContent(details.question, details.answer),
180
+ display: true,
181
+ details,
182
+ };
183
+
184
+ if (wasBusy) {
185
+ pi.sendMessage(message, { deliverAs: "followUp" });
186
+ return "queued";
187
+ }
188
+
189
+ pi.sendMessage(message);
190
+ return "saved";
191
+ }
192
+
193
+ async function showBtwAnswer(
194
+ ctx: ExtensionCommandContext,
195
+ question: string,
196
+ answer: string,
197
+ saveState: SaveState,
198
+ ): Promise<void> {
199
+ if (!ctx.hasUI) {
200
+ return;
201
+ }
202
+
203
+ await ctx.ui.custom<void>(
204
+ (_tui, theme, _kb, done) => new BtwAnswerOverlay(theme, question, answer, saveState, () => done(undefined)),
205
+ {
206
+ overlay: true,
207
+ overlayOptions: {
208
+ width: "70%",
209
+ maxHeight: "80%",
210
+ minWidth: 50,
211
+ anchor: "center",
212
+ margin: 1,
213
+ },
214
+ },
215
+ );
216
+ }
217
+
218
+ export default function (pi: ExtensionAPI) {
219
+ pi.registerMessageRenderer(BTW_MESSAGE_TYPE, (message, { expanded }, theme) => {
220
+ const details = message.details as BtwDetails | undefined;
221
+ const content = typeof message.content === "string" ? message.content : "[non-text btw message]";
222
+ const lines = [theme.fg("accent", theme.bold("[BTW]")), content];
223
+
224
+ if (expanded && details) {
225
+ lines.push(
226
+ theme.fg(
227
+ "dim",
228
+ `model: ${details.provider}/${details.model} · thinking: ${details.thinkingLevel}`,
229
+ ),
230
+ );
231
+
232
+ if (details.usage) {
233
+ lines.push(
234
+ theme.fg(
235
+ "dim",
236
+ `tokens: in ${details.usage.input} · out ${details.usage.output} · total ${details.usage.totalTokens}`,
237
+ ),
238
+ );
239
+ }
240
+ }
241
+
242
+ const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
243
+ box.addChild(new Text(lines.join("\n"), 0, 0));
244
+ return box;
245
+ });
246
+
247
+ pi.on("context", async (event) => {
248
+ return {
249
+ messages: event.messages.filter((message) => !isBtwMessage(message)),
250
+ };
251
+ });
252
+
253
+ pi.registerCommand("btw", {
254
+ description: "Ask a side question now. Add --save to persist the answer in the session.",
255
+ handler: async (args, ctx) => {
256
+ const { question, save } = parseBtwArgs(args);
257
+ if (!question) {
258
+ if (ctx.hasUI) {
259
+ ctx.ui.notify("Usage: /btw [--save] <question>", "warning");
260
+ }
261
+ return;
262
+ }
263
+
264
+ if (!ctx.model) {
265
+ if (ctx.hasUI) {
266
+ ctx.ui.notify("No active model selected.", "error");
267
+ }
268
+ return;
269
+ }
270
+
271
+ const wasBusy = !ctx.isIdle();
272
+ const model = ctx.model;
273
+ const thinkingLevel = pi.getThinkingLevel() as SessionThinkingLevel;
274
+
275
+ try {
276
+ let response: AssistantMessage | null;
277
+
278
+ if (ctx.hasUI) {
279
+ response = await ctx.ui.custom<AssistantMessage | null>(
280
+ (tui, theme, _kb, done) => {
281
+ const status = wasBusy ? "in parallel with the current turn" : "now";
282
+ const loader = new BorderedLoader(
283
+ tui,
284
+ theme,
285
+ `Running /btw ${status} with ${model.provider}/${model.id} (${thinkingLevel})...`,
286
+ { cancellable: true },
287
+ );
288
+
289
+ loader.onAbort = () => done(null);
290
+
291
+ runBtw(ctx, question, thinkingLevel, loader.signal)
292
+ .then(done)
293
+ .catch((error) => {
294
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
295
+ done(null);
296
+ });
297
+
298
+ return loader;
299
+ },
300
+ {
301
+ overlay: true,
302
+ overlayOptions: {
303
+ width: "60%",
304
+ minWidth: 40,
305
+ anchor: "center",
306
+ margin: 1,
307
+ },
308
+ },
309
+ );
310
+ } else {
311
+ response = await runBtw(ctx, question, thinkingLevel);
312
+ }
313
+
314
+ if (!response) {
315
+ if (ctx.hasUI) {
316
+ ctx.ui.notify("/btw cancelled", "info");
317
+ }
318
+ return;
319
+ }
320
+
321
+ const answer = extractAnswer(response);
322
+ const details: BtwDetails = {
323
+ question,
324
+ answer,
325
+ provider: model.provider,
326
+ model: model.id,
327
+ thinkingLevel,
328
+ timestamp: Date.now(),
329
+ usage: response.usage,
330
+ };
331
+
332
+ const saveState = saveBtwNote(pi, details, save, wasBusy);
333
+
334
+ if (ctx.hasUI) {
335
+ await showBtwAnswer(ctx, question, answer, saveState);
336
+
337
+ if (saveState === "saved") {
338
+ ctx.ui.notify("Saved BTW note to the session.", "info");
339
+ } else if (saveState === "queued") {
340
+ ctx.ui.notify("BTW note queued to save after the current turn finishes.", "info");
341
+ }
342
+ }
343
+ } catch (error) {
344
+ if (ctx.hasUI) {
345
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
346
+ }
347
+ }
348
+ },
349
+ });
350
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "pi-btw",
3
+ "version": "0.1.0",
4
+ "description": "A pi extension that answers side questions immediately with /btw",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Dan Bachelder",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/dbachelder/pi-btw.git"
11
+ },
12
+ "homepage": "https://github.com/dbachelder/pi-btw#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/dbachelder/pi-btw/issues"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi-extension",
19
+ "pi-coding-agent",
20
+ "agent",
21
+ "tui"
22
+ ],
23
+ "files": [
24
+ "extensions",
25
+ "docs",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "pi": {
33
+ "extensions": [
34
+ "./extensions"
35
+ ],
36
+ "image": "https://raw.githubusercontent.com/dbachelder/pi-btw/main/docs/btw-overlay.png"
37
+ },
38
+ "peerDependencies": {
39
+ "@mariozechner/pi-ai": "*",
40
+ "@mariozechner/pi-coding-agent": "*",
41
+ "@mariozechner/pi-tui": "*"
42
+ }
43
+ }