@luxass/pi-btw 0.1.1 → 0.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/README.md CHANGED
@@ -12,12 +12,34 @@ pi install npm:@luxass/pi-btw
12
12
 
13
13
  Run `/btw` to open the side thread, or `/btw <text>` to open it and ask right away. If a thread already exists, `/btw` asks whether to continue it or start fresh.
14
14
 
15
- In the popover, **Enter** asks, **Esc** stops a running answer or closes the popover, and **↑↓** / **PgUp PgDn** scroll. Closing a non-empty thread asks whether to keep it or inject a summary into the main chat.
15
+ In the popover, **Enter** asks, **Esc** stops a running answer or closes the popover, and **↑↓** / **PgUp PgDn** scroll. In fullscreen mode, you can also scroll with the mouse wheel or trackpad, click the scrollbar on the right edge, or drag its thumb. Wheel speed follows Pi's `fullscreenWheelScrollLines` setting. Regular mode keeps terminal-owned mouse scrolling, so use the keyboard inside the popover.
16
16
 
17
- The side thread sees the main conversation up to the moment you ask, using your current model and thinking level. Its tools are read-only (`read`, `grep`, `find`, `ls`), so it can look things up but not change files. Because the side request starts with the same prefix as the main chat, providers with prompt caching can reuse the main conversation's cache.
17
+ Scrolling up holds your place while an answer streams. Scroll back to the bottom to follow new output again. Closing a non-empty thread asks whether to keep it or inject a summary into the main chat.
18
+
19
+ The side thread sees the main conversation up to the moment you ask, using your current model and thinking level. By default, its tools are read-only (`read`, `grep`, `find`, `ls`), so it can look things up but not change files. You can configure its tool access separately from the main chat. Because the side request starts with the same prefix as the main chat, providers with prompt caching can reuse the main conversation's cache.
18
20
 
19
21
  Injecting asks the model for a summary, sends it as a user message, and clears the side thread. If the main agent is busy, the summary is queued as a follow-up.
20
22
 
21
23
  The side thread is stored in the session log, follows branch navigation, and never enters the main agent's context unless you inject it.
22
24
 
23
- Models from providers registered by other extensions are not available in the side thread; it resolves models from Pi's `auth.json` and `models.json`.
25
+ When the popover opens, the side thread copies extension-registered providers from the main session, including their streaming and authentication handlers. Stored credentials still come from Pi's `auth.json`. Provider extensions are not reloaded, so their tools and lifecycle hooks are not enabled in the side thread.
26
+
27
+ ## Tool access
28
+
29
+ Set `btw.tools` in `~/.pi/agent/settings.json`, or in a trusted project's `.pi/settings.json`. Pi merges these settings, with the project's tool list replacing the user-level list.
30
+
31
+ This example adds shell access to the default read-only tools:
32
+
33
+ ```json
34
+ {
35
+ "btw": {
36
+ "tools": ["read", "grep", "find", "ls", "bash"]
37
+ }
38
+ }
39
+ ```
40
+
41
+ The list replaces BTW's defaults. Omit `btw.tools` to use `read`, `grep`, `find`, and `ls`; set it to `[]` to disable all tools. Supported names are `read`, `grep`, `find`, `ls`, `bash`, `powershell`, `edit`, and `write`. Extension and MCP tools are not supported. Invalid tool lists produce an error instead of silently changing tool access.
42
+
43
+ Enabling `bash`, `powershell`, `edit`, or `write` lets the side thread run commands or modify files. The main session's permission hooks and custom tool overrides are not inherited. The tool list is not an operating-system sandbox.
44
+
45
+ Close BTW, run `/reload` after editing settings, and reopen it to apply the new list. Changing BTW's tools does not change the main chat's tools.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luxass/pi-btw",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Ask /btw side questions in a popover without derailing your main Pi conversation.",
5
5
  "keywords": [
6
6
  "btw",
@@ -31,6 +31,7 @@
31
31
  "@earendil-works/pi-tui": "*"
32
32
  },
33
33
  "pi": {
34
+ "image": "https://raw.githubusercontent.com/luxass/pi-extensions/main/packages/btw/docs/cover.png",
34
35
  "extensions": [
35
36
  "./src/index.ts"
36
37
  ]
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ import type {
8
8
 
9
9
  import { createOverlay } from "./overlay";
10
10
  import { answerText, createSideSession, summarize, type BtwState, type Exchange } from "./session";
11
+ import { getBtwTools, type BtwToolName } from "./settings.ts";
11
12
 
12
13
  const EXCHANGE_ENTRY = "btw-exchange";
13
14
  const RESET_ENTRY = "btw-reset";
@@ -17,6 +18,16 @@ const FRESH = "Start fresh";
17
18
  const KEEP = "Keep side thread";
18
19
  const INJECT = "Inject summary into main chat";
19
20
 
21
+ type ToolDetailArgs = {
22
+ pattern?: string;
23
+ path?: string;
24
+ command?: string;
25
+ };
26
+
27
+ function toolDetail({ args }: { args: ToolDetailArgs }): string {
28
+ return args.pattern ?? args.path ?? args.command ?? "";
29
+ }
30
+
20
31
  export default function btw(pi: ExtensionAPI) {
21
32
  const state: BtwState = { thread: [], busy: false };
22
33
 
@@ -41,11 +52,10 @@ export default function btw(pi: ExtensionAPI) {
41
52
  if (event.type === "message_update" && event.message.role === "assistant") {
42
53
  pending.text = answerText(event.message);
43
54
  } else if (event.type === "tool_execution_start") {
44
- const { path, pattern } = event.args as { path?: string; pattern?: string };
45
55
  pending.tools.push({
46
56
  id: event.toolCallId,
47
57
  name: event.toolName,
48
- detail: pattern ?? path ?? "",
58
+ detail: toolDetail(event),
49
59
  status: "running",
50
60
  });
51
61
  } else if (event.type === "tool_execution_end") {
@@ -54,7 +64,11 @@ export default function btw(pi: ExtensionAPI) {
54
64
  }
55
65
  }
56
66
 
57
- async function open(ctx: ExtensionCommandContext, initial: string): Promise<void> {
67
+ async function open(
68
+ ctx: ExtensionCommandContext,
69
+ initial: string,
70
+ tools: readonly BtwToolName[],
71
+ ): Promise<void> {
58
72
  // Lives only while the overlay is open, so each opening sees the latest main conversation.
59
73
  let side: AgentSession | undefined;
60
74
 
@@ -67,7 +81,12 @@ export default function btw(pi: ExtensionAPI) {
67
81
  tui.requestRender();
68
82
  try {
69
83
  if (side == null) {
70
- side = await createSideSession(ctx, pi.getThinkingLevel(), state.thread);
84
+ side = await createSideSession({
85
+ ctx,
86
+ thinkingLevel: pi.getThinkingLevel(),
87
+ thread: state.thread,
88
+ tools,
89
+ });
71
90
  side.subscribe((event) => {
72
91
  track(event);
73
92
  tui.requestRender();
@@ -127,13 +146,14 @@ export default function btw(pi: ExtensionAPI) {
127
146
  pi.registerCommand("btw", {
128
147
  description: "ask a side question without derailing the main conversation",
129
148
  handler: async (args, ctx) => {
149
+ const tools = getBtwTools(pi.getSettings());
130
150
  const question = args.trim();
131
151
  if (!question && state.thread.length > 0) {
132
152
  const choice = await ctx.ui.select("btw", [CONTINUE, FRESH]);
133
153
  if (choice == null) return;
134
154
  if (choice === FRESH) reset();
135
155
  }
136
- await open(ctx, question);
156
+ await open(ctx, question, tools);
137
157
  },
138
158
  });
139
159
 
package/src/overlay.ts CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  type TUI,
13
13
  } from "@earendil-works/pi-tui";
14
14
 
15
- import { answerText, type BtwState, type ToolRow } from "./session";
15
+ import { answerText, type BtwState, type ToolRow } from "./session.ts";
16
16
 
17
17
  const TOOL_ICONS = { running: "⚙", done: "✓", error: "✗" };
18
18
  const TOOL_COLORS = { running: "dim", done: "success", error: "error" } as const;
@@ -38,15 +38,32 @@ export function createOverlay({
38
38
  }: OverlayOptions): Component & Focusable {
39
39
  const input = new Input();
40
40
  let answers = new WeakMap<AssistantMessage, Markdown>();
41
- // Lines scrolled up from the bottom; 0 follows new output.
42
- let scroll = 0;
41
+ let scrollTop = 0;
42
+ let followEnd = true;
43
43
  let page = 1;
44
+ let lineCount = 0;
45
+ let thumbTop = 0;
46
+ let thumbHeight = 1;
47
+ let dragOffset: number | undefined;
48
+
49
+ function scrollTo(top: number): void {
50
+ const maxScroll = Math.max(0, lineCount - page);
51
+ scrollTop = Math.max(0, Math.min(maxScroll, top));
52
+ followEnd = scrollTop === maxScroll;
53
+ tui.requestRender();
54
+ }
55
+
56
+ function dragThumb(y: number, offset: number): void {
57
+ const track = page - thumbHeight;
58
+ const ratio = track > 0 ? (y - 1 - offset) / track : 0;
59
+ scrollTo(Math.round(ratio * Math.max(0, lineCount - page)));
60
+ }
44
61
 
45
62
  input.onSubmit = (value) => {
46
63
  const question = value.trim();
47
64
  if (!question || state.busy) return;
48
65
  input.setValue("");
49
- scroll = 0;
66
+ followEnd = true;
50
67
  onAsk(question);
51
68
  };
52
69
 
@@ -111,15 +128,22 @@ export function createOverlay({
111
128
  );
112
129
  }
113
130
 
114
- function row(content: string, width: number): string {
131
+ function row(content: string, width: number, right = border("│")): string {
115
132
  const fitted = truncateToWidth(content, width, "");
116
- return `${border("│")} ${fitted}${" ".repeat(Math.max(0, width - visibleWidth(fitted)))} ${border("│")}`;
133
+ return `${border("│")} ${fitted}${" ".repeat(Math.max(0, width - visibleWidth(fitted)))} ${right}`;
117
134
  }
118
135
 
119
136
  function edge(left: string, right: string, label: string, info: string, width: number): string {
120
- const fill = Math.max(0, width - visibleWidth(label) - visibleWidth(info) - 2);
121
- const line = border(`${left}─`) + label + border("─".repeat(fill)) + info + border(`─${right}`);
122
- return truncateToWidth(line, width + 2, "");
137
+ const fittedInfo = truncateToWidth(info, Math.max(0, width - 2), "");
138
+ const fittedLabel = truncateToWidth(
139
+ label,
140
+ Math.max(0, width - 2 - visibleWidth(fittedInfo)),
141
+ "…",
142
+ );
143
+ const fill = Math.max(0, width - visibleWidth(fittedLabel) - visibleWidth(fittedInfo) - 2);
144
+ return (
145
+ border(`${left}─`) + fittedLabel + border("─".repeat(fill)) + fittedInfo + border(`─${right}`)
146
+ );
123
147
  }
124
148
 
125
149
  return {
@@ -131,27 +155,44 @@ export function createOverlay({
131
155
  },
132
156
 
133
157
  render(width) {
158
+ if (width < 5) return [truncateToWidth("btw", Math.max(0, width), "")];
159
+
134
160
  const inner = width - 2;
135
161
  const content = inner - 2;
136
- const height = Math.max(4, Math.floor(tui.terminal.rows * 0.8) - 4);
162
+ const height = Math.max(1, Math.floor(tui.terminal.rows * 0.8) - 4);
137
163
  page = height;
138
164
 
139
165
  const lines = transcript(content);
140
- scroll = Math.min(scroll, Math.max(0, lines.length - height));
141
- const end = lines.length - scroll;
142
- const visible = lines.slice(Math.max(0, end - height), end);
166
+ lineCount = lines.length;
167
+ const maxScroll = Math.max(0, lineCount - height);
168
+ scrollTop = followEnd ? maxScroll : Math.min(scrollTop, maxScroll);
169
+ thumbHeight = Math.max(1, Math.floor((height * height) / Math.max(height, lineCount)));
170
+ thumbTop = maxScroll > 0 ? Math.round((scrollTop / maxScroll) * (height - thumbHeight)) : 0;
171
+ const end = Math.min(lineCount, scrollTop + height);
172
+ const visible = lines.slice(scrollTop, end);
143
173
  while (visible.length < height) visible.push("");
144
- const position = lines.length > height ? ` ${end}/${lines.length} ` : "";
174
+ const position = maxScroll > 0 ? ` ${scrollTop + 1}-${end}/${lineCount} ` : "";
145
175
 
146
176
  return [
147
177
  edge("┌", "┐", theme.fg("accent", ` btw · ${title} `), "", inner),
148
- ...visible.map((line) => row(line, content)),
178
+ ...visible.map((line, index) => {
179
+ if (maxScroll === 0) return row(line, content);
180
+ const thumb = index >= thumbTop && index < thumbTop + thumbHeight;
181
+ return row(
182
+ line,
183
+ content,
184
+ theme.fg(thumb ? "scrollbarThumb" : "scrollbarTrack", thumb ? "┃" : "│"),
185
+ );
186
+ }),
149
187
  border(`├${"─".repeat(inner)}┤`),
150
188
  row(input.render(content)[0] ?? "", content),
151
189
  edge(
152
190
  "└",
153
191
  "┘",
154
- theme.fg("dim", " enter ask · esc close · ↑↓ scroll "),
192
+ theme.fg(
193
+ "dim",
194
+ ` enter ask · esc close · ${tui.mode === "fullscreen" ? "wheel/↑↓" : "↑↓"} scroll `,
195
+ ),
155
196
  theme.fg("dim", position),
156
197
  inner,
157
198
  ),
@@ -163,15 +204,45 @@ export function createOverlay({
163
204
  onEscape();
164
205
  return;
165
206
  }
166
- if (keybindings.matches(data, "tui.select.up")) scroll += 1;
167
- else if (keybindings.matches(data, "tui.select.down")) scroll = Math.max(0, scroll - 1);
168
- else if (keybindings.matches(data, "tui.select.pageUp")) scroll += page;
169
- else if (keybindings.matches(data, "tui.select.pageDown"))
170
- scroll = Math.max(0, scroll - page);
207
+ if (keybindings.matches(data, "tui.select.up")) scrollTo(scrollTop - 1);
208
+ else if (keybindings.matches(data, "tui.select.down")) scrollTo(scrollTop + 1);
209
+ else if (keybindings.matches(data, "tui.select.pageUp")) scrollTo(scrollTop - page);
210
+ else if (keybindings.matches(data, "tui.select.pageDown")) scrollTo(scrollTop + page);
171
211
  else input.handleInput(data);
172
212
  tui.requestRender();
173
213
  },
174
214
 
215
+ handleMouse(event) {
216
+ if (event.type === "wheel") {
217
+ scrollTo(scrollTop + (event.wheelDelta ?? 0));
218
+ return { handled: true };
219
+ }
220
+ if (dragOffset != null) {
221
+ if (event.type === "drag") {
222
+ dragThumb(event.y, dragOffset);
223
+ return { handled: true };
224
+ }
225
+ if (event.type === "release") {
226
+ dragOffset = undefined;
227
+ return { handled: true, render: false };
228
+ }
229
+ }
230
+ if (
231
+ event.type === "press" &&
232
+ event.button === "left" &&
233
+ event.x === event.width - 1 &&
234
+ event.y >= 1 &&
235
+ event.y <= page &&
236
+ lineCount > page
237
+ ) {
238
+ const thumb = event.y - 1 >= thumbTop && event.y - 1 < thumbTop + thumbHeight;
239
+ dragOffset = thumb ? event.y - 1 - thumbTop : Math.floor(thumbHeight / 2);
240
+ if (!thumb) dragThumb(event.y, dragOffset);
241
+ return { handled: true, capture: true };
242
+ }
243
+ return undefined;
244
+ },
245
+
175
246
  invalidate() {
176
247
  answers = new WeakMap();
177
248
  },
package/src/session.ts CHANGED
@@ -3,14 +3,17 @@ import {
3
3
  createAgentSession,
4
4
  DefaultResourceLoader,
5
5
  getAgentDir,
6
+ ModelRuntime,
6
7
  SessionManager,
7
8
  type AgentSession,
8
9
  type ExtensionAPI,
9
10
  type ExtensionContext,
10
11
  } from "@earendil-works/pi-coding-agent";
11
12
 
13
+ import { DEFAULT_BTW_TOOLS, type BtwToolName } from "./settings.ts";
14
+
12
15
  const SIDE_PROMPT =
13
- "The user is asking a side question (a 'btw') about the conversation above. The main agent keeps its own thread; you only answer here. Answer directly and briefly. Your tools are read-only.";
16
+ "The user is asking a side question (a 'btw') about the conversation above. The main agent keeps its own thread; handle the side question here. Answer directly and briefly.";
14
17
 
15
18
  const SUMMARY_PROMPT =
16
19
  "Summarize this side conversation for the main agent. Keep decisions, findings, open questions, and next steps. Output only the summary.";
@@ -40,21 +43,39 @@ export function answerText(message: AssistantMessage): string {
40
43
  .trim();
41
44
  }
42
45
 
43
- export async function createSideSession(
44
- ctx: ExtensionContext,
45
- thinkingLevel: ReturnType<ExtensionAPI["getThinkingLevel"]>,
46
- thread: Exchange[],
47
- ): Promise<AgentSession> {
46
+ interface SideSessionOptions {
47
+ ctx: ExtensionContext;
48
+ thinkingLevel: ReturnType<ExtensionAPI["getThinkingLevel"]>;
49
+ thread: readonly Exchange[];
50
+ tools: readonly BtwToolName[];
51
+ }
52
+
53
+ export async function createSideSession({
54
+ ctx,
55
+ thinkingLevel,
56
+ thread,
57
+ tools,
58
+ }: SideSessionOptions): Promise<AgentSession> {
59
+ const toolAccess =
60
+ tools.length === 0
61
+ ? "No tools are enabled in this side session."
62
+ : `Your enabled tools are: ${tools.join(", ")}. ${
63
+ tools.every((tool) => DEFAULT_BTW_TOOLS.includes(tool))
64
+ ? "Your tools are read-only."
65
+ : "Use tools only for actions requested in this side conversation."
66
+ }`;
48
67
  const resourceLoader = new DefaultResourceLoader({
49
68
  cwd: ctx.cwd,
50
69
  agentDir: getAgentDir(),
51
70
  noExtensions: true,
52
- appendSystemPrompt: [SIDE_PROMPT],
71
+ appendSystemPrompt: [
72
+ `${SIDE_PROMPT} ${toolAccess} Do not assume tools from the main conversation are available here.`,
73
+ ],
53
74
  });
54
75
  await resourceLoader.reload();
55
76
 
56
77
  // Seeding with the main branch keeps its system prompt in front, so the request shares the
57
- // main chat's prefix and Pi only appends a patch for SIDE_PROMPT and the read-only tools.
78
+ // main chat's prefix and Pi only appends a patch for SIDE_PROMPT and the configured tools.
58
79
  const sessionManager = SessionManager.inMemory(
59
80
  ctx.cwd,
60
81
  undefined,
@@ -65,11 +86,22 @@ export async function createSideSession(
65
86
  sessionManager.appendMessage(answer);
66
87
  }
67
88
 
89
+ // A fresh SDK runtime only knows built-ins and models.json. Copy provider registrations
90
+ // without reloading their extensions, which would also enable unrelated tools and hooks.
91
+ const modelRuntime = await ModelRuntime.create();
92
+ for (const providerId of ctx.modelRegistry.getRegisteredProviderIds()) {
93
+ const provider = ctx.modelRegistry.getRegisteredNativeProvider(providerId);
94
+ if (provider) modelRuntime.registerNativeProvider(provider);
95
+ const config = ctx.modelRegistry.getRegisteredProviderConfig(providerId);
96
+ if (config) modelRuntime.registerProvider(providerId, config);
97
+ }
98
+
68
99
  const { session } = await createAgentSession({
69
100
  cwd: ctx.cwd,
101
+ modelRuntime,
70
102
  model: ctx.model,
71
103
  thinkingLevel,
72
- tools: ["read", "grep", "find", "ls"],
104
+ tools: [...tools],
73
105
  resourceLoader,
74
106
  sessionManager,
75
107
  });
@@ -0,0 +1,34 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ type PiSettings = ReturnType<ExtensionAPI["getSettings"]>;
4
+ type BtwSettings = PiSettings & { btw?: { tools?: unknown } };
5
+
6
+ const SUPPORTED_TOOLS = {
7
+ read: true,
8
+ grep: true,
9
+ find: true,
10
+ ls: true,
11
+ bash: true,
12
+ powershell: true,
13
+ edit: true,
14
+ write: true,
15
+ };
16
+
17
+ export type BtwToolName = keyof typeof SUPPORTED_TOOLS;
18
+
19
+ export const DEFAULT_BTW_TOOLS: readonly BtwToolName[] = ["read", "grep", "find", "ls"];
20
+
21
+ function isBtwTool(value: unknown): value is BtwToolName {
22
+ return typeof value === "string" && Object.hasOwn(SUPPORTED_TOOLS, value);
23
+ }
24
+
25
+ export function getBtwTools({ btw }: BtwSettings): BtwToolName[] {
26
+ const tools = btw?.tools;
27
+ if (tools != null && (!Array.isArray(tools) || !tools.every(isBtwTool))) {
28
+ throw new Error(
29
+ `Invalid BTW settings: btw.tools must be an array of: ${Object.keys(SUPPORTED_TOOLS).join(", ")}.`,
30
+ );
31
+ }
32
+
33
+ return [...new Set(tools ?? DEFAULT_BTW_TOOLS)];
34
+ }