pi-bro 0.21.0 → 0.22.1

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
@@ -1,981 +1,153 @@
1
1
  # pi-bro
2
2
 
3
- Turn a dense AI reply, pasted text, local document, or public webpage into a
4
- plain-language explanation — or open a separate side conversation with
5
- `/bro btw` — without adding anything to your main agent's context.
3
+ [![npm](https://img.shields.io/npm/v/pi-bro)](https://www.npmjs.com/package/pi-bro)
4
+ [![tests](https://img.shields.io/github/actions/workflow/status/tranhoangnguyen03/pi-bro/publish.yml?branch=main&label=tests)](https://github.com/tranhoangnguyen03/pi-bro/actions/workflows/publish.yml)
5
+ [![node](https://img.shields.io/node/v/pi-bro)](package.json)
6
+ [![license](https://img.shields.io/npm/l/pi-bro)](LICENSE)
6
7
 
7
- `pi-bro` is an extension for [Earendil Pi](https://github.com/earendil-works/pi).
8
- Experimental [PiG 0.3.0 compatibility](docs/pig-compatibility.md) uses the same npm package and requires Node.js. See the compatibility notes for verified coverage and the PiG RPC tool-exclusion limitation.
9
- It opens explanations in a separate modal and runs them through a CLI backend
10
- you already have installed and signed in to. Explain, show, BTW, and the
11
- advisor all work across five backends:
8
+ A sidekick for you and your Pi agent: plain-language explanations, side
9
+ questions, diagrams, PR review and second opinions, without cluttering the
10
+ agent's context.
12
11
 
13
- - [Google Antigravity CLI](https://antigravity.google/docs/cli-install) (`agy`) — the default for new settings
14
- - [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (`claude`)
15
- - Grok Build (`grok`)
16
- - [Codex CLI](https://github.com/openai/codex) (`codex`)
17
- - Meta Muse Code (`muse`)
18
-
19
- You only need the backend(s) you select; Agy is the default, not a requirement.
20
-
21
- ## Quick start
22
-
23
- You need Earendil Pi `>=0.84.2 <1`, Node.js `>=22.19.0`, and at least one
24
- backend CLI on your `PATH`, signed in once from your terminal (`agy >=1.1.15`
25
- for the default). Then install Bro:
26
-
27
- ```sh
28
- pi install npm:pi-bro
29
- ```
30
-
31
- Restart Pi or run `/reload`. If you use Claude Code, Grok, Codex, or Muse instead of Agy,
32
- choose it in `/bro config` (for everything, or per feature). Then try:
33
-
34
- ```text
35
- /bro
36
- /bro text Paste text here
37
- /bro file docs/report.pdf
38
- /bro url https://example.com/article
39
- /bro btw "what file defines this route?"
40
- ```
41
-
42
- Run `/bro doctor` after installation or whenever Bro is not working.
43
-
44
- To install from GitHub instead, use
45
- `pi install git:github.com/tranhoangnguyen03/pi-bro`. To try Bro without
46
- installing it, use `pi -e npm:pi-bro`.
47
-
48
- ## What Bro can explain
49
-
50
- | Source | Command | What Bro does |
51
- | --- | --- | --- |
52
- | Latest assistant reply | `/bro` | Explains the latest completed reply without adding the result to the conversation. |
53
- | Pasted text | `/bro text <text>` | Explains text supplied directly in the command. |
54
- | Local document | `/bro file <path>` | Extracts text from a workspace-local Markdown, text, PDF, or DOCX file. |
55
- | Public webpage | `/bro url <url>` | Fetches one public HTML page and extracts its main readable content. |
56
- | Recent session turns | `/bro show` | Draws the last turns' conversation text as shapes instead of prose (tool calls, tool results, reasoning, and images are omitted). |
57
- | Any of the above, auto-detected | `/bro <input>` | Routes a lone URL to the webpage reader, an existing workspace file with a supported extension to the document reader, and anything else to pasted text. |
58
-
59
- Pressing **R** simplifies the captured source again in the mode shown, and
60
- **M** re-simplifies it in the next mode. These commands capture a
61
- new source: `/bro text`, `/bro file`, `/bro url`, and `/bro show`. Giving `/bro` a URL, path, or
62
- text directly captures a new source the same way.
63
-
64
- ## Commands
65
-
66
- | Command | Description |
67
- | --- | --- |
68
- | `/bro`, `/bro simplify`, or `/bro text` | Explain the latest completed assistant response. |
69
- | `/bro text <text>` | Explain pasted text. |
70
- | `/bro <input>` | Explain it directly: a lone URL runs the webpage reader, an existing workspace file with a supported extension runs the document reader, and anything else is pasted text. A quoted path with spaces is routed too when the file exists. |
71
- | `/bro file <path>` | Explain a workspace-local `.md`, `.markdown`, `.txt`, `.pdf`, or `.docx` file. |
72
- | `/bro url <url>` | Explain one public, text-based webpage. |
73
- | `/bro open` | Reopen the latest explanation without calling the simplifier again. |
74
- | `/bro show [n-turns] [query]` | Draw recent session turns (default last 1) as shapes instead of prose, from user and assistant conversation text only — tool calls, tool results, reasoning, and images are omitted. An optional query steers what the shapes focus on, with or without a leading turn count. |
75
- | `/bro doctor` | Check Bro's settings, preferences, and each selected backend, with the effective backend/model/effort per feature. |
76
- | `/bro mode [brief\|balanced\|faithful]` | View or choose the explanation mode. |
77
- | `/bro preferences` | View or edit what Bro knows about you and how you like answers; see [Preferences](#preferences). |
78
- | `/bro config` | Open an interactive settings screen for the shared default backend/model/effort, explain mode, show turns, and per-capability (explain/show/btw/advisor) overrides. |
79
- | `/bro btw [question]` | Open a side conversation in a modal, seeded with recent main-session context. Starts conversation-only; type `/mode` inside to toggle full permission (read and edit the workspace) without losing the thread. |
80
- | `/bro advisor` | Quick notice of whether the executor's `bro_advisor` tool is available right now, pointing at `/bro config`, `/bro advisor-steer`, and `/bro doctor`. |
81
- | `/bro advisor-steer` | View, edit, save, or clear the one persistent steering brief the advisor always sees. |
82
- | `/bro help` | Open the built-in quick reference. |
83
-
84
- Giving `/bro` the input directly works the same way:
85
-
86
- ```text
87
- /bro https://example.com/article
88
- /bro docs/report.pdf
89
- /bro any other text is explained as pasted text
90
- ```
91
-
92
- ## Explanation modes
93
-
94
- Bro treats the source as data, rejects embedded instructions, preserves its
95
- language (unless your [preferences](#preferences) name another), and avoids
96
- adding facts, advice, or conclusions in every mode. Choose
97
- a persistent mode with `/bro mode`, or press **M** in an explanation to try the
98
- next mode without saving it:
99
-
100
- - **`brief`**: Uses the original audience-led ELI-simpleton prompt with no fixed
101
- word target.
102
- - **`balanced`**: The default. Keeps important details, conditions, warnings,
103
- context, code, and formatting while trimming fluff and repetition.
104
- - **`faithful`**: Simplifies the language while preserving every claim,
105
- qualification, warning, number, command, code block, and formatting choice.
106
-
107
- ### Modal controls
108
-
109
- - **Mouse wheel / trackpad**: Scroll in regular or fullscreen mode
110
- - **↑ / ↓**: Scroll in any mode
111
- - **C**: Copy the complete explanation
112
- - **R**: Simplify the captured source again in the mode shown, or run the
113
- current Doctor check again
114
- - **M**: Re-simplify the captured source in the next mode (brief → balanced →
115
- faithful → brief). It applies to this explanation only and does not change
116
- the mode saved by `/bro mode`; pressing it again while Bro is working skips
117
- ahead
118
- - **O**: Open the HTML diagram when a show reply contains one
119
- - **Esc**: Close the modal, or cancel while Bro is working
120
-
121
- The modal header shows the model and reasoning effort the explanation or
122
- drawing used (`default` when the model's own effort applies), followed by the
123
- explanation mode, and `prefs` when your [preferences](#preferences) shaped the
124
- result; `/bro open` keeps the original labels, mode, and tag.
125
-
126
- Bro temporarily captures mouse input while its modal is open. Native mouse
127
- selection may be unavailable or visually extend outside the modal depending on
128
- your terminal mode; press **C** to copy the complete explanation reliably.
129
-
130
-
131
- ## Bro btw (side conversation)
132
-
133
- `/bro btw` opens a separate multi-turn conversation in a modal, so you can ask
134
- a quick side question while the main agent keeps working. It runs through the
135
- selected backend and never adds anything to Pi's conversation unless you
136
- explicitly insert it into the editor. Bro writes for a tired reader: the point
137
- first, in plain words, at a length that fits the question, in the language you
138
- asked in.
139
-
140
- - `/bro btw <question>` asks immediately; `/bro btw` opens an empty thread.
141
- Reopening keeps the thread and its mode.
142
- - **Two modes, toggled with `/mode`**: a new thread starts
143
- **conversation-only**; type `/mode` in the modal to switch to **full
144
- permission** (read and edit the workspace, run commands) and again to switch
145
- back. The conversation is kept across switches. How conversation-only is
146
- enforced depends on the backend — see
147
- [Backends: access and retention](#backends-access-and-retention).
148
- - Every new or cleared thread is seeded with up to the last 8 turns of
149
- main-session user/assistant conversation text (40,000 characters max, with a
150
- truncation notice). Later turns continue the backend's native session; in
151
- full permission mode the side agent can also read the repo itself.
152
- - **In the modal**: type a question and press Enter (empty Enter re-asks the
153
- last question). Composer actions trigger only on these exact commands:
154
- - `/mode`: toggles conversation-only / full permission, keeping the thread
155
- - `/copy`: copies the latest answer to the system clipboard
156
- - `/copy-all`: copies the full thread to the system clipboard
157
- - `/insert`: inserts the latest answer into the main editor without submitting
158
- - `/insert-all`: inserts the full thread into the main editor without submitting
159
- - `/retry`: re-asks the last question (empty Enter does the same)
160
- - `/clear`: resets the thread
161
-
162
- `/insert` and `/insert-all` never replace an existing main-editor draft:
163
- edit or clear it first. Any other text, including other slash-prefixed input
164
- such as `/send`, is sent as a question. Esc closes the modal (or cancels a
165
- running turn). The header shows the model and reasoning effort the latest
166
- turn used (`default` when the model's own effort applies) and the current
167
- mode.
168
- - A turn is capped at 2 minutes in conversation-only mode and 10 minutes in
169
- full permission mode.
170
- - Bro's thread lives in memory only — it clears when you switch Pi sessions,
171
- reload extensions, or quit Pi. Changing the BTW backend starts a fresh
172
- thread; native session IDs never cross backends.
173
-
174
- ## Bro advisor
175
-
176
- `bro_advisor` is a tool the **executor agent** — not you — can voluntarily
177
- call mid-task for a second opinion. Unlike `/bro btw`, which is a side
178
- conversation for you, `bro_advisor` is a tool for the model you're working
179
- with; it shows up as a normal tool call/result in the transcript, not a
180
- modal. It is registered like any other tool when the extension loads and has
181
- no on/off switch of its own — whether the executor can actually call it
182
- depends entirely on this host's own tool restrictions.
183
-
184
- `/bro advisor` is a quick notice of whether `bro_advisor` is available right
185
- now, pointing at `/bro config`, `/bro advisor-steer`, and `/bro doctor`.
186
- `/bro doctor` has the full diagnostic: whether this host exposes and
187
- activates `bro_advisor`, its resolved backend/model/effort, steering
188
- presence, and backend compatibility (for Agy, a minimum CLI version with an
189
- `agy update` action when it is too old).
190
-
191
- - **Automatic context, no prep needed**: the executor never assembles a
192
- summary. Bro captures a harness-neutral snapshot — the executor's system
193
- instructions, its active tools, and the conversation so far including tool
194
- calls and results — and sends it, along with an optional `question` the
195
- executor may pass, to a **fresh, standalone process of the selected
196
- backend** for every consultation. Nothing is resumed or reused across calls,
197
- including retries.
198
- - **Instructed to investigate, not implement**: the advisor process has real
199
- tool access in the workspace with permissions auto-approved — there is no
200
- enforced read-only isolation. It is instructed to verify claims itself and
201
- return advice, leaving edits to the executor, but that boundary is a
202
- behavioral prompt instruction rather than an enforced sandbox constraint, so
203
- treat its findings as advice to verify, not a guaranteed hands-off review.
204
- - **Steering**: `/bro advisor-steer` opens an editor for one persistent
205
- steering brief — e.g. "quick prototype; keep A and B careful, everything
206
- else minimal" — that the advisor always reads. **Ctrl+S** saves and keeps
207
- the editor open; **Enter** or **Shift+Enter** inserts a newline; **Ctrl+K**
208
- clears both the saved brief and draft while staying open; **Ctrl+C** copies
209
- the entire current draft, including unsaved edits; and **Esc** closes without
210
- saving unsaved edits. The brief is **never added to Pi's conversation or
211
- sent to the main model** — the advisor is the only thing that reads it.
212
- - **Persistence**: the steering brief persists with the Pi session (not
213
- globally, not per project) as custom extension data in the session file and
214
- is restored on resume or reload. Forking a session inherits it; edits made
215
- after the fork are independent of the original branch.
216
- - **Retries**: on an invocation failure (not a completed answer — "I need
217
- more evidence" is a normal result, not a failure), Bro retries with the
218
- identical snapshot, steering, and question: once after 5 seconds, once more
219
- after 10 seconds, then returns the backend's own diagnostic — including a
220
- context-length error, verbatim — as the failure. Host-imposed deadlines and
221
- cancellation are terminal: neither starts another attempt or a backoff wait.
222
- The advisor CLI is asked to stop at 10 minutes; Bro's host deadline is 610
223
- seconds plus bounded process cleanup. A CLI-reported error before that host
224
- deadline remains an invocation failure and can be retried.
225
- Cancelling the tool call skips any pending retry wait.
226
- - **Progress and provenance**: while an attempt is running, Bro shows the last
227
- thing the advisor actually reported — a tool name or a user-facing response
228
- line, never hidden reasoning — and how long ago it arrived, e.g. `last
229
- reported: Read src/app.ts (2s ago)`, or "awaiting first activity" before
230
- anything arrives. Expanding a running consultation shows up to the last 4
231
- reported activity lines; each retry starts the trail over. The returned
232
- answer starts with backend, model, effort, attempt count, duration,
233
- workspace, steering presence, snapshot size, and known omission/compaction
234
- notes; the advisor's complete answer follows unchanged.
235
- - **Model/effort**: resolved the same way as explain/show/btw, through
236
- `/bro config` (shared default or per-capability override).
237
-
238
- ## Bro show
239
-
240
- Where the explanation modes rewrite dense prose in simpler words, `/bro show`
241
- changes the form: it draws what you and the assistant said in the last few
242
- session turns as a shape instead of paragraphs. Capture keeps only user and
243
- assistant conversation text, including every intermediate assistant message in
244
- a turn — tool calls, tool results, reasoning, and images never leave the
245
- session. It runs the same backend-specific model call and shows the result
246
- in the same modal, never touching your conversation. `/bro show` uses its own
247
- draw prompt; the explanation modes do not affect it. Your
248
- [preferences](#preferences) can change only its wording and language, never
249
- which shapes it draws or its rules.
250
-
251
- Because the draw model only ever sees conversation text, its shapes reflect
252
- what was *reported* in the conversation — what the assistant said it did or
253
- found — not an independent check against the actual code or system state.
254
-
255
- Shapes are terminal-first: pseudocode, call trees, file trees, component
256
- trees, diffs, and types and signatures. Bro picks the shape from what
257
- happened in the session; there is no flag to request a specific one. When the source has no code structure
258
- to draw, Bro falls back to a plain outline instead of forcing a diagram. A
259
- reply that ends in one self-contained HTML block — layout, a state comparison,
260
- anything where position itself carries meaning — is written to a file and
261
- opened with **O**.
262
-
263
- Pressing **R** redraws the same captured turns; running `/bro show` again
264
- captures the latest turns afresh. `/bro show <n-turns>` overrides the default turn
265
- count for a single run.
266
-
267
- Add a query to steer what the shapes focus on, either after a turn count or on
268
- its own: `/bro show what changed in the auth flow`, or `/bro show 3 what
269
- changed in the auth flow`. The query is used as a lens on the captured turns,
270
- not as additional evidence, and its casing is preserved as typed. Pressing
271
- **R** retries with the same turn count and query.
272
-
273
- Any leading whitespace-delimited word that looks like a number is treated as the
274
- requested turn count: for example, `/bro show 3 what changed` captures 3 turns
275
- and steers on "what changed", while `/bro show 404 handler` parses "404" as the
276
- turn count and "handler" as the steering query. To steer on a phrase that starts
277
- with digits while choosing a turn count, specify the turn count explicitly
278
- first: `/bro show 1 404 handler` captures 1 turn and steers on "404 handler".
279
- If the first word is not a number, the whole input is treated as the steering
280
- query using the saved `showTurns` default.
281
-
282
- ### A slow session-create, traced
283
-
284
- The agent followed a two-second delay from the handler down to the worker.
285
- `/bro show` drew the chain:
286
-
287
- ```text
288
- handleCreateSession(req)
289
- ├── validateRequest(req)
290
- ├── SessionStore.insert(req.body)
291
- └── publish('session.created')
292
- └── AgentWorker.run(sessionId)
293
- ├── loadContext(sessionId)
294
- ├── callModel(context)
295
- └── persistResult(sessionId, result)
296
- ```
297
-
298
- ### The shape of code before it exists
299
-
300
- A design discussion agreed on the data model ahead of implementation. `/bro
301
- show` kept just the shape:
302
-
303
- ```typescript
304
- interface Item { id: ItemId; parentId: ItemId | null }
305
- interface Cursor { position: ItemId; direction: 'up' | 'down' }
306
- function resolveTarget(items: Item[], cursor: Cursor): ItemId | null
307
- ```
308
-
309
- ### A layout that collapses at narrow widths
310
-
311
- Text can't show a before/after layout change at a glance, so Bro ends with one
312
- self-contained HTML block and **O** opens it (the terminal first shows
313
- `[HTML diagram saved — press O to open]`):
12
+ `pi-bro` is an extension for [Pi](https://github.com/earendil-works/pi), a
13
+ terminal coding agent. Bro opens its answers in a separate window and runs
14
+ them through an AI coding CLI you already have and are signed in to, so your
15
+ main agent's conversation stays clean. Before you install, see
16
+ [what leaves your machine](#what-leaves-your-machine).
314
17
 
315
18
  <p align="center">
316
- <a href="https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-show-layout.png">
317
- <img alt="A before/after dashboard grid" src="https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-show-layout.png" width="720">
19
+ <a href="https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-response-after.png">
20
+ <img alt="A dense agent reply explained in plain language in the Bro window" src="https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-response-after.png" width="820">
318
21
  </a>
319
22
  </p>
320
23
 
321
- <details>
322
- <summary><strong>More shapes</strong></summary>
323
-
324
- **Diff** — what changed in the save handler:
325
-
326
- ```diff
327
- on(save)
328
- - write content
329
- + if content is unchanged
330
- + return cached result
331
- + write new content
332
- + invalidate cache
333
- ```
334
-
335
- **File layout** — where everything lives, for a refactor:
336
-
337
- ```text
338
- src/
339
- ├── commands/ # user intents
340
- │ ├── registry.ts
341
- │ └── show-me.ts
342
- ├── sessions/ # state and lifecycle
343
- │ ├── events.ts
344
- │ ├── store.ts
345
- │ └── worker.ts
346
- ├── transport/ # API
347
- │ ├── client.ts
348
- │ └── stream.ts
349
- └── config.ts # root config
350
- ```
351
-
352
- **Component tree** — what the session page renders:
353
-
354
- ```text
355
- SessionPage (apps/example/src/routes/session.tsx)
356
- ├── [hook] useSessionEvents
357
- ├── SessionToolbar (packages/ui)
358
- │ └── RunSkillButton
359
- └── SessionTimeline (packages/ui)
360
- └── SkillResultCard
361
- ```
362
-
363
- **Pseudocode** — how scroll capture and restore work:
364
-
365
- ```text
366
- capture(blocks, targetRect, scrollRect) -> Snapshot:
367
- target = focusedBlock ?? firstBlockIntersectingViewportTop(blocks)
368
- anchor = wholeBlockAnchor(blocks, target)
369
- offset = targetRect.top - scrollRect.top
370
- return { anchor, offset, scrollTop, revision + 1 }
371
-
372
- restore(snapshot, blocks) -> number:
373
- placement = resolveAnchor(blocks, snapshot.anchor)
374
- if placement: return scrollRect.top + targetRect.top - snapshot.offset
375
- return snapshot.scrollTop
376
- ```
377
-
378
- </details>
379
-
380
- Prose in, outline out: a purely conversational session with no code to draw
381
- degrades to a plain outline of the discussion — never a forced diagram.
382
-
383
- ## Bro in action
384
-
385
- ### Assistant response
386
-
387
- **Before `/bro`: the original agent response**
388
-
389
- [![A dense assistant response before Bro](https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-response-before.png)](https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-response-before.png)
390
-
391
- **After `/bro`: the plain-language explanation**
24
+ ## Install
392
25
 
393
- [![The assistant response explained in the Bro modal](https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-response-after.png)](https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-response-after.png)
394
-
395
- ### Local document
396
-
397
- **Before: a complex PDF**
398
-
399
- [![A complex PDF before Bro](https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-file-before.png)](https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-file-before.png)
400
-
401
- **After `/bro file <path>`**
402
-
403
- [![The PDF explained in the Bro modal](https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-file-after.png)](https://raw.githubusercontent.com/tranhoangnguyen03/pi-bro/main/docs/images/bro-file-after.png)
404
-
405
- Bro optimizes for understanding, not simply for fewer words. The written
406
- examples below are synthetic and were run through Bro's default prompt. Click
407
- a screenshot to see it at full size.
408
-
409
- <details>
410
- <summary><strong>Short:</strong> TypeScript says a value is <code>never</code></summary>
411
-
412
- ### Before
413
-
414
- > The diagnostic is not evidence that `result` is intrinsically uninhabitable; it is an artifact of TypeScript's intraprocedural control-flow graph. Because `result` is initialized to `null` and only assigned inside the `forEach` callback, the outer scope does not model that callback as definitely executing. After `if (!result) return`, the remaining branch therefore collapses to `never`, producing the property-access error. Replace the callback-driven mutation with a control-flow-visible loop: `for (const item of items) { if (matches(item)) { result = item; break; } }`. Alternatively, derive the value expressionally with `const result = items.find(matches);` and guard `if (!result) return;` before dereferencing it. Avoid an `as Result` assertion; it suppresses the symptom while preserving the unsound state transition that caused the narrowing anomaly.
415
-
416
- ### After `/bro`
417
-
418
- #### What happened
419
-
420
- TypeScript showed an error saying your variable `result` cannot be used or
421
- accessed.
422
-
423
- This happened because `result` was set to `null` outside a `forEach` loop and
424
- then modified inside the loop's helper function (callback). TypeScript tracks
425
- code line by line. It cannot guarantee that code inside a `forEach` callback
426
- will actually run.
427
-
428
- #### What it means
429
-
430
- Because TypeScript assumes the loop's callback might not run:
431
-
432
- 1. It believes `result` might still be `null`.
433
- 2. When you check `if (!result) return`, TypeScript thinks `result` can never
434
- hold a valid value after that check.
435
- 3. It sets the type of `result` to `never` (a special type meaning "impossible
436
- value") and blocks you from reading its properties.
437
-
438
- The error is a limitation in how TypeScript analyzes loops with callbacks.
439
-
440
- #### What you should do next
441
-
442
- Choose one of these two fixes:
443
-
444
- **Option 1: Use a standard `for...of` loop**
445
-
446
- ```ts
447
- for (const item of items) {
448
- if (matches(item)) {
449
- result = item;
450
- break;
451
- }
452
- }
453
- ```
454
-
455
- **Option 2: Use `Array.prototype.find`**
456
-
457
- ```ts
458
- const result = items.find(matches);
459
- if (!result) return;
460
- ```
461
-
462
- Avoid using a type assertion like `as Result`. It only hides the warning
463
- without fixing the underlying tracking issue.
464
-
465
- </details>
466
-
467
- <details>
468
- <summary><strong>Medium:</strong> Login succeeds, but the user is still logged out</summary>
469
-
470
- ### Before
471
-
472
- > What you're observing is almost certainly not an authentication failure in the credential-validation layer; it is a post-authentication session persistence failure caused by an environment-dependent mismatch between Express's transport-security inference and the TLS termination topology in production.
473
- >
474
- > Locally, Express sees the request as plain HTTP and your development cookie configuration probably permits a non-secure session cookie. In production, however, the browser connects over HTTPS to Nginx, a load balancer, or an ingress controller, which terminates TLS and forwards the request to Node over HTTP. Unless Express trusts that intermediary, `req.secure` remains `false`, even when the proxy sends `X-Forwarded-Proto: https`. With `cookie.secure: true`, `express-session` can consequently decline to emit the cookie because it believes the originating request was insecure. The login route may still return `200`, making the credentials appear accepted, but the next request has no session identifier and is treated as anonymous.
475
- >
476
- > Configure proxy trust before registering session middleware, and make the cookie policy reflect whether the frontend and API are same-site or genuinely cross-site:
477
- >
478
- > ```js
479
- > app.set("trust proxy", 1);
480
- >
481
- > app.use(session({
482
- > secret: process.env.SESSION_SECRET,
483
- > resave: false,
484
- > saveUninitialized: false,
485
- > proxy: true,
486
- > cookie: {
487
- > httpOnly: true,
488
- > secure: true,
489
- > sameSite: "lax",
490
- > maxAge: 1000 * 60 * 60 * 24
491
- > }
492
- > }));
493
- > ```
494
- >
495
- > Use `sameSite: "none"` instead of `"lax"` only when the browser must send the cookie in a cross-site context, such as a frontend and API on unrelated registrable domains. Browsers require `Secure` when `SameSite=None`, so that combination must remain HTTPS-only. Separate subdomains such as `app.example.com` and `api.example.com` are usually same-site, though they are still cross-origin.
496
- >
497
- > Also verify that the proxy explicitly forwards `X-Forwarded-Proto`, that the browser receives a `Set-Cookie` response header, and that frontend requests use `credentials: "include"` when crossing origins. If CORS is involved, the server must return the exact allowed origin plus `Access-Control-Allow-Credentials: true`; a wildcard origin is incompatible with credentialed requests.
498
- >
499
- > Avoid setting a cookie `domain` unless sharing across subdomains is intentional. A host-only cookie is safer and eliminates another production-only failure mode.
500
-
501
- ### After `/bro`
502
-
503
- #### What happened
504
-
505
- Your username and password check succeeded, and the login route returned `200
506
- OK`. However, the browser did not receive or return a usable session cookie in
507
- production.
508
-
509
- #### What it means
510
-
511
- In production, secure web traffic (HTTPS) hits an intermediary, such as a load
512
- balancer or Nginx, before reaching your Node/Express app as plain HTTP.
513
-
514
- Because your session cookie requires HTTPS (`secure: true`), Express may withhold
515
- it when it does not trust the proxy forwarding the request. The exact trust
516
- setting must match your deployment's proxy topology.
517
-
518
- #### What you should do next
519
-
520
- 1. Configure Express to trust only your actual proxy topology. Put this before
521
- the session setup. For example, use `1` only when there is exactly one trusted
522
- proxy hop:
523
-
524
- ```js
525
- app.set("trust proxy", 1);
526
-
527
- app.use(session({
528
- secret: process.env.SESSION_SECRET,
529
- resave: false,
530
- saveUninitialized: false,
531
- cookie: {
532
- httpOnly: true,
533
- secure: true,
534
- sameSite: "lax",
535
- maxAge: 1000 * 60 * 60 * 24
536
- }
537
- }));
538
- ```
539
-
540
- 2. Check your cookie settings:
541
- - Keep `sameSite: "lax"` if your frontend and backend share the same main
542
- domain, such as `app.example.com` and `api.example.com`.
543
- - Use `sameSite: "none"` only when the cookie must be sent cross-site.
544
- Browsers require `secure: true` with this setting.
545
- - Avoid defining a custom cookie `domain` unless you deliberately need to
546
- share cookies across subdomains.
547
-
548
- 3. Verify the proxy, browser, and CORS settings:
549
- - Ensure the proxy forwards the `X-Forwarded-Proto` header.
550
- - Check that the response contains a `Set-Cookie` header.
551
- - Include `credentials: "include"` in cross-origin frontend requests.
552
- - Return the exact allowed origin with
553
- `Access-Control-Allow-Credentials: true`. Do not use a wildcard (`*`) for
554
- credentialed requests.
555
-
556
- </details>
557
-
558
- <details>
559
- <summary><strong>Long:</strong> A CI build fails only when its cache is restored</summary>
560
-
561
- ### Before
562
-
563
- > The failure is not a nondeterministic pnpm installation problem, despite the misleading first error being emitted from the test runner immediately after dependency hydration. It is a state-contamination problem at the intersection of the repository cache, the package export map, and an incorrectly scoped cache key. The decisive observation is that the same commit succeeds in a clean checkout and in CI when cache restoration is disabled, but fails when the pre-build workspace cache is restored. That isolates the variable to files materialized outside Git rather than source, Node, or runner image drift.
564
- >
565
- > The affected package, `@acme/config`, was recently migrated from a dual CommonJS/ESM build to an ESM-oriented TypeScript output. Its root `package.json` declares `"type": "module"` and maps the `import` condition to `./dist/index.js`, while the legacy `require` condition still maps to `./dist/index.cjs`. The current compiler emits `index.js` but does not remove the previous build directory first. An older cached `dist` directory therefore contributes two files that no longer belong to the current build graph: `dist/index.cjs` and `dist/package.json`, the latter declaring `"type": "commonjs"`. The new compiler overlays `dist/index.js` but leaves both obsolete files intact. Because nested package boundaries override the root package type, Node interprets the newly emitted ESM `index.js` as CommonJS in that restored workspace and reports `Unexpected token 'export'`. Test processes entering through `require()` instead resolve the obsolete `index.cjs`, which references a removed chunk and can instead produce `MODULE_NOT_FOUND`. These apparently different errors are two projections of the same dirty-output condition.
566
- >
567
- > The cache configuration makes that contaminated state persistent. The workflow computes the key with `hashFiles('packages/**/pnpm-lock.yaml')`, but this workspace has only the root-level `pnpm-lock.yaml`. GitHub Actions consequently evaluates the hash expression to an empty value, yielding a key equivalent to `Linux-node20-workspace-`. A broad restore key then permits an archive produced before the module-format migration to satisfy the lookup. That archive combines the pnpm content-addressable store, Turborepo metadata, and every package's `dist` directory. Those data classes do not share valid invalidation semantics: pnpm store entries are immutable by content, Turborepo artifacts are task-hash addressed, and arbitrary build directories are mutable snapshots whose correctness depends on complete deletion or exact provenance. Treating them as one cache effectively elevates obsolete untracked files into undeclared build inputs.
568
- >
569
- > The evidence is visible by comparing the restored and clean workspaces before compilation. In the failing job, `packages/config/dist/package.json` exists with `"type":"commonjs"` and `packages/config/dist/index.cjs` has a timestamp and checksum predating the current commit. Neither file appears after `git clean -ffdx` followed by installation and build. The Actions cache log also shows the truncated key without a lockfile digest, while `git diff` remains empty because the problematic files are ignored. Finally, deleting only `packages/config/dist` before rerunning the unchanged test command converts the failure to a pass, which excludes dependency resolution and network variability as primary causes.
570
- >
571
- > The minimal durable remediation has three parts. First, stop caching package output directories. Cache the pnpm store separately, using a key that includes the actual root lockfile:
572
- >
573
- > ```yaml
574
- > key: ${{ runner.os }}-node20-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
575
- > restore-keys: |
576
- > ${{ runner.os }}-node20-pnpm-
577
- > ```
578
- >
579
- > A broad fallback is acceptable for the pnpm store because pnpm validates content-addressed entries; it is not acceptable for mutable `dist` snapshots. If remote or local Turborepo caching is retained, cache only `.turbo` and allow Turbo's task hash to govern artifact reuse rather than wrapping raw workspace outputs in a generic archive.
580
- >
581
- > Second, make every package build replace, rather than merge into, its output directory. `@acme/config` should delete `dist` before invoking `tsc`, `tsup`, or the existing bundler. The CI workflow should also run the repository's recursive clean target before the first build as a defense against future cache or runner reuse. This is not a substitute for fixing cache scope, but it restores the invariant that generated output is a function of the checked-out sources and declared toolchain.
582
- >
583
- > Third, make the export contract agree with emitted files. If `@acme/config` is intentionally ESM-only, remove the `require` condition and the obsolete CommonJS metadata. If CommonJS consumers remain supported, restore an explicit CJS build that deterministically emits `dist/index.cjs`; do not let a historical artifact impersonate that support. In either case, package publication should reject export targets that do not exist.
584
- >
585
- > Verification should exercise both cache states and both module entry paths. Run the full pipeline once with no cache, save only the corrected caches, and rerun the identical commit expecting a cache hit and the same result. Inspect the built package to confirm the nested CommonJS `package.json` and legacy chunks are absent unless intentionally generated. Add a lightweight smoke check using dynamic `import('@acme/config')`; if CommonJS remains supported, add a second check through `createRequire`. Finally, change the root lockfile and confirm the logged cache key changes. That matrix validates clean-build reproducibility, restored-cache reproducibility, export-map coherence, and dependency-cache invalidation independently rather than relying on a single green run.
586
-
587
- ### After `/bro`
588
-
589
- #### What happened
590
-
591
- Your build failed because old files were left behind by a broken cache (a saved
592
- snapshot of previous build files).
593
-
594
- The package `@acme/config` recently switched its module format to modern
595
- JavaScript (ESM). However, the build process did not delete the old output
596
- folder (`dist`) before creating new files.
597
-
598
- Because the GitHub Actions setting searches the wrong path
599
- (`hashFiles('packages/**/pnpm-lock.yaml')`), GitHub could not find the root
600
- `pnpm-lock.yaml`. It restored an outdated cache containing `dist/index.cjs` and
601
- a `dist/package.json` configured for older JavaScript (CommonJS). The new build
602
- wrote some files but left the old ones behind, confusing Node and causing errors
603
- such as `Unexpected token 'export'` and `MODULE_NOT_FOUND`.
604
-
605
- A clean checkout without the cache succeeds. This proves the problem is old
606
- cached files, not your source code or dependencies.
607
-
608
- #### What it means
609
-
610
- - **Cache contamination:** The CI workflow restores mutable `dist` folders
611
- alongside package-manager files, mixing obsolete files into new builds.
612
- - **Mismatched module settings:** The package says it supports both modern
613
- (`import`) and legacy (`require`) formats, but it only builds the modern one
614
- while relying on leftover cached files for the legacy one.
615
-
616
- #### What you should do next
617
-
618
- 1. **Fix the GitHub Actions cache:** Stop caching `dist` folders. Cache only the
619
- pnpm store, using the root lockfile:
620
-
621
- ```yaml
622
- key: ${{ runner.os }}-node20-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
623
- restore-keys: |
624
- ${{ runner.os }}-node20-pnpm-
625
- ```
626
-
627
- If you use Turborepo, cache only `.turbo`.
628
-
629
- 2. **Clean output folders before building:** Make `@acme/config` delete `dist`
630
- before running `tsc`, `tsup`, or the bundler. Run the repository's recursive
631
- clean command before CI builds.
632
-
633
- 3. **Update the package exports:**
634
- - If `@acme/config` is ESM-only, remove the `require` entry and old CommonJS
635
- metadata.
636
- - If CommonJS is still needed, add a real build step for `dist/index.cjs`.
637
-
638
- 4. **Verify the fix:**
639
- - Delete the generated `packages/config/dist` folder, then run a clean build.
640
- Do not use `git clean -ffdx` in a working copy with files you need.
641
- - Run the workflow without a cache, save the new cache, and rerun the same
642
- commit to verify that a cache hit also passes.
643
- - Test `import('@acme/config')`, and test `createRequire` if CommonJS is
644
- supported.
645
-
646
- </details>
647
-
648
- ## Explain pasted text
649
-
650
- Paste text directly after the command:
651
-
652
- ```text
653
- /bro text OAuth refresh tokens are rotated after every successful use.
654
- ```
655
-
656
- Bro explains the pasted text instead of the latest assistant reply. With no text
657
- after `/bro text`, it falls back to the latest completed reply. Press **R**
658
- to simplify the same captured text again.
659
-
660
- ## Explain a document
661
-
662
- Use a path relative to Pi's current workspace, or an absolute path inside it:
663
-
664
- ```text
665
- /bro file "docs/incident review.pdf"
26
+ ```sh
27
+ pi install npm:pi-bro
666
28
  ```
667
29
 
668
- Paths may contain spaces; matching single or double quotes are also accepted.
669
- Bro extracts text locally, then sends that text through the same explanation
670
- flow used by `/bro`. Pressing **R** retries the extracted snapshot; running a
671
- new `/bro file <path>` command reads the file again.
672
-
673
- Files are limited to 10 MiB and 100,000 extracted characters. Scanned PDFs are
674
- not supported because Bro does not perform OCR.
675
-
676
- ## Explain a webpage
677
-
678
- Pass one public HTTP or HTTPS page:
30
+ Then restart Pi or run `/reload`, and check your setup:
679
31
 
680
32
  ```text
681
- /bro url https://example.com/complicated-article
33
+ /bro doctor
682
34
  ```
683
35
 
684
- Bro fetches the page, extracts its main readable text locally, and sends only
685
- that text through the existing explanation flow. The completed modal shows the
686
- final website and page title. Pressing **R** retries the captured page without
687
- fetching again; running a new `/bro url <url>` command fetches a fresh copy.
688
-
689
- The first version is intentionally limited to one public, text-based page. It
690
- does not use browser cookies, sign in, run page JavaScript, bypass paywalls or
691
- bot protection, load complete discussion threads, follow pagination, or
692
- understand images and video. Pages that depend on those features may fail.
693
-
694
- If Bro cannot read a page, copy its content into a `.txt` or `.md` file, or save
695
- it as a PDF, then use `/bro file <path>`.
696
-
36
+ To try Bro without installing it, run `pi -e npm:pi-bro`. To install from
37
+ GitHub, use `pi install git:github.com/tranhoangnguyen03/pi-bro`.
697
38
 
698
- ## Check your setup
39
+ ## Try it
699
40
 
700
- Run `/bro doctor` when Bro is newly installed or something is not working. It
701
- checks Bro's settings and preferences, then probes only the backends some feature
702
- actually selects, and reports the effective backend/model/effort for each
703
- feature. Failed checks explain what to fix.
41
+ | Type this in Pi | What happens |
42
+ | --- | --- |
43
+ | `/bro` | Explains the agent's last reply |
44
+ | `/bro file docs/report.pdf` | Explains a document (use your own path) |
45
+ | `/bro url https://example.com/article` | Explains a webpage (use your own link) |
46
+ | `/bro btw "what file defines this route?"` | Asks a side question |
47
+ | `/bro show` | Draws the last turn as a diagram |
704
48
 
705
- - **Agy**: installed version, model catalog, and account access.
706
- - **Claude Code**: installed version and configured authentication.
707
- - **Grok**: installed version only; authentication and connectivity are not
708
- verified.
709
- - **Codex**: installed version and configured authentication.
710
- - **Muse**: installed version only; authentication and connectivity are not
711
- verified.
49
+ ## What it does
712
50
 
713
- Doctor never sends source text or runs a model completion. A successful check
714
- confirms the setup but cannot guarantee that a later provider request will
715
- succeed.
51
+ | Command | What you get |
52
+ | --- | --- |
53
+ | `/bro`, `/bro text`, `/bro file`, `/bro url` | **[Explain](docs/user-guide.md#what-bro-can-explain).** A plain-language version of the agent's last reply, pasted text, a PDF/DOCX/Markdown file, or a public webpage. Three modes: `brief`, `balanced`, `faithful`. |
54
+ | `/bro show` | **[Show](docs/user-guide.md#bro-show).** The last few turns drawn as a shape (call tree, file tree, diff, pseudocode, or an HTML diagram) instead of prose. |
55
+ | `/bro btw` | **[Side questions](docs/user-guide.md#bro-btw-side-conversation).** A separate conversation seeded with recent context, so you can ask without interrupting the agent. ⚠️ [Full-permission mode](#what-leaves-your-machine) can edit files. |
56
+ | `/bro guided-review <PR>` | **[Guided Review](docs/guided-review.md).** An explanation and quality assessment of a GitHub PR, with ranked findings, source evidence and private questions. Needs the Claude or Muse backend. |
57
+ | `bro_advisor` tool | **[Second opinion](docs/user-guide.md#bro-advisor).** A tool your agent can call mid-task; a fresh backend process investigates and returns advice to the agent. ⚠️ [Runs with permissions bypassed](#what-leaves-your-machine). |
58
+ | `/bro config`, `/bro preferences` | **[Settings](docs/user-guide.md#settings) and [preferences](docs/user-guide.md#preferences).** Pick the backend, model and effort per feature, and tell Bro how you like answers. |
716
59
 
717
- ## Settings
60
+ Every command, control and setting is in the **[user guide](docs/user-guide.md)**.
61
+ Guided Review has its own [guide](docs/guided-review.md).
718
62
 
719
- Use `/bro config` to review or change the shared default backend/model/effort
720
- and any per-capability (explain/show/btw/advisor) overrides, the explanation
721
- mode, and the default show turn count. Changes save immediately. Esc inside a
722
- picker cancels that pick; Esc on the settings screen closes it, keeping
723
- whatever was already saved. A failed save (for example, a read-only file) is
724
- shown inline. `/bro mode` changes the mode directly (**M** in an explanation
725
- tries another mode without saving it), and `/bro help` shows the active settings
726
- and file path.
63
+ ## Requirements
727
64
 
728
- Settings live in this user-editable file, created when the extension loads
729
- (under `$PI_CODING_AGENT_DIR` instead when that is set):
65
+ - Pi `>=0.84.2 <1` and Node.js `>=22.19.0`.
66
+ - macOS or Linux. Windows is untested; there, cancelling stops only the
67
+ backend's direct process, not anything it started.
68
+ - At least one backend CLI on your `PATH`, signed in once from your terminal.
69
+ You only need the one you use:
730
70
 
731
- ```text
732
- ~/.pi/agent/bro-settings.json
733
- ```
71
+ | Backend | CLI | Notes |
72
+ | --- | --- | --- |
73
+ | [Google Antigravity](https://antigravity.google/docs/cli-install) | `agy` | Default for new settings. Needs `>=1.1.15`. Not for Guided Review. |
74
+ | [Claude Code](https://docs.anthropic.com/en/docs/claude-code) | `claude` | Works for every feature, including Guided Review. |
75
+ | [Grok Build](https://docs.x.ai/build/overview) | `grok` | Not for Guided Review. |
76
+ | [Codex CLI](https://github.com/openai/codex) | `codex` | Not for Guided Review. |
77
+ | [Muse Code](https://dev.meta.ai/docs/muse-code) | `muse` | Works for every feature, including Guided Review. |
734
78
 
735
- ```json
736
- {
737
- "version": 2,
738
- "default": { "backend": "agy", "model": "gemini-3.7-flash", "effort": "low" },
739
- "mode": "balanced",
740
- "showTurns": 1,
741
- "overrides": {
742
- "explain": { "backend": "claude", "model": "sonnet", "effort": "medium" },
743
- "advisor": { "backend": "grok", "model": "grok-4.7", "effort": "high" }
744
- }
745
- }
746
- ```
79
+ - Guided Review also needs Git and an authenticated [`gh`](https://cli.github.com/).
80
+ Choose Claude or Muse for it in `/bro config`.
81
+ - [PiG](docs/pig-compatibility.md) support is experimental.
747
82
 
748
- Bro reads the file again before each request, so manual edits apply next time.
749
-
750
- - Each selection is one atomic backend/model/effort choice. An override pins
751
- its own complete selection and ignores the shared default, even when it
752
- happens to match it; select **Default** in `/bro config` to inherit again.
753
- Omitted overrides inherit `default`.
754
- - `effort` must be one the backend offers (`default` omits it and lets the
755
- model decide). Agy selections are normalized against Agy's installed model
756
- catalog. Claude, Grok, Codex, and Muse accept seeded or custom model IDs; a model/effort
757
- combination the account does not support fails with the backend's own error
758
- instead of silently falling back.
759
- - `mode` is `brief`, `balanced` (the default), or `faithful`. `showTurns` is
760
- the default number of turns `/bro show` draws (default 1); `/bro show
761
- <n-turns>` overrides it for one run.
762
- - `PI_BRO_MODEL` picks the initial Agy model only when Bro creates a missing
763
- settings file, for example `PI_BRO_MODEL=gemini-3.7-flash-low pi`.
764
- - Older flat settings files (root `model`/`effort`) still load and mean Agy.
765
-
766
- ## Backends: access and retention
767
-
768
- Bro uses each CLI's own account and billing route, never Pi provider
769
- credentials, and does not copy credentials or rewrite backend configuration.
770
- Each backend and your model provider may retain sessions, logs, and request
771
- data under their own settings and policies.
772
-
773
- | | Explain / show | BTW conversation-only | BTW full permission | Advisor |
774
- | --- | --- | --- | --- | --- |
775
- | **Agy** | Temporary directory, Agy sandbox | Temporary directory, Agy sandbox | Workspace, permissions bypassed | Fresh workspace process, permissions bypassed |
776
- | **Claude Code** | Scratch directory, tools/MCP/skills disabled, no session persistence | Workspace, tools disabled | Workspace, permissions bypassed | Fresh workspace process, permissions bypassed |
777
- | **Grok** | Temporary directory, **prompt instruction only** | Workspace, **prompt instruction only** | Workspace, permissions bypassed | Fresh workspace process, permissions bypassed |
778
- | **Codex** | Scratch directory, read-only sandbox, ephemeral session | Workspace, read-only sandbox | Workspace, approvals and sandbox bypassed | Fresh workspace process, approvals and sandbox bypassed |
779
- | **Muse** | Scratch directory, approval/write/shell disabled, no session log | Workspace, approval/write/shell disabled | Workspace, permissions bypassed (`--yolo`) | Fresh workspace process, permissions bypassed (`--yolo`) |
780
-
781
- - Grok always runs with its sandbox off and permissions bypassed; its tools,
782
- hooks, skills, plugins, and MCP may remain available. "Answer only from the
783
- supplied context" is a request, not an enforced restriction.
784
- - Codex's read-only sandbox is not a tool-free mode: workspace reads and
785
- sandboxed commands remain available. Bro does not disable configured MCP
786
- servers or web search; their access is governed by Codex configuration.
787
- - Muse's restricted mode disables write and shell tools and approval prompts,
788
- not all tools: workspace reads and web tools remain available without approval.
789
- It is not a tool-free or network-isolated mode.
790
- - Claude's restrictions are tool/configuration settings (with safe mode), not
791
- an OS sandbox; built-in and managed Claude behavior can remain. Running a
792
- permission-bypassing mode as root may be rejected by Claude.
793
- - BTW continues natively: Agy by conversation ID, Claude and Grok by
794
- `--resume`, Codex by `resume`, and Muse by `--session-id` of the same session,
795
- including across `/mode` switches. An Agy conversation stays bound to the
796
- workspace it started in, so after a `/mode` switch — or whenever a thread
797
- has turns but no native session ID — Bro starts a fresh native session
798
- seeded with the main-session context and every earlier turn.
799
- - Cancellation, deadlines, and invalid output streams stop the backend's
800
- process group on POSIX, escalating after a five-second grace period. On
801
- Windows only the direct child is targeted. Detached shell work or external
802
- services a backend started are not contained. Bro removes its private
803
- temporary prompt files.
804
-
805
- ### Configuration precedence
806
-
807
- When resolving backend, model, and reasoning effort:
808
- 1. **Per-capability override**: `overrides.<capability>` (`explain`, `show`, `btw`, or `advisor`) pins that capability's complete selection.
809
- 2. **Shared default**: otherwise the capability inherits `default` (root `model`/`effort` in older flat files).
810
- 3. **Agy catalog normalization**: for Agy selections, Bro maps suffixed variant IDs and handles fixed-effort models.
811
- 4. **Initial file creation only**: `PI_BRO_MODEL` has no effect once the settings file exists.
812
-
813
- When resolving turn count for `/bro show`:
814
- 1. **Command argument**: an explicit count like `/bro show 3` or `/bro show 1 query` overrides for that run.
815
- 2. **Saved setting**: `showTurns` (defaults to 1).
816
-
817
- When shaping an answer, each part has one owner:
818
-
819
- | Part | Decided by |
820
- | --- | --- |
821
- | Bro's source rules: quoted source treated as data, no added facts, Show's traceability rules, BTW access mode | Built in; nothing overrides them |
822
- | How much of the source an explanation keeps | The mode: **M** for one explanation, otherwise the saved `mode` |
823
- | What a Show drawing focuses on | The steering query |
824
- | Who the answer is for: wording, tone, depth, and answer language | Your [preferences](#preferences), otherwise Bro's built-in defaults |
825
-
826
- ## Preferences
827
-
828
- Tell Bro about yourself and how you like answers. Bro adds what you write to
829
- every explain, `/bro show`, and `/bro btw` prompt as a labelled section,
830
- alongside its own instructions. It never replaces them: modes, **M**, and the
831
- source rules keep working. The advisor never receives your preferences; use
832
- `/bro advisor-steer` for it.
833
-
834
- Run `/bro preferences` to edit them: **Ctrl+S** saves, **Ctrl+K** deletes the
835
- file, **Ctrl+C** copies, and **Esc** closes without saving. The first time,
836
- the editor opens with this starter text, which is not saved until you press
837
- **Ctrl+S**:
838
-
839
- ```md
840
- ## About me
841
- I'm an overworked white-collar worker, and so are my colleagues. By the end of a
842
- hard day our brains are fried and we can only handle simple language, no matter
843
- how sharp we are at our best.
844
-
845
- ## How I like answers
846
- - Explain it like I'm a simpleton: plain, everyday words.
847
- - Go easy on analogies. No forced ones.
848
- ```
849
-
850
- You can also edit the file directly (under `$PI_CODING_AGENT_DIR` instead when
851
- that is set):
83
+ ## What leaves your machine
852
84
 
853
- ```text
854
- ~/.pi/agent/bro-preferences.md
855
- ```
85
+ Each feature sends data to the backend you chose and its model provider,
86
+ which may keep it under their own policies. Paths below are under
87
+ `~/.pi/agent/` (or `$PI_CODING_AGENT_DIR`).
856
88
 
857
- - **Free-form**: no placeholder or structure is required. Bro re-reads the
858
- file on every request, so edits apply next time. A missing or empty file
859
- means no preferences, and Bro's prompts are then exactly the built-in ones.
860
- - **What preferences can change**: wording, tone, technical depth, length in
861
- BTW, and the answer language. If you name a language, code, commands, paths,
862
- names, and numbers still stay exactly as written. In `/bro show`,
863
- preferences only change wording and language. A per-run choice (the mode,
864
- **M**, a Show steering query, or what a BTW question asks for) wins over a
865
- standing preference.
866
- - **Limit**: 4,000 characters, because the text goes with every request. A
867
- longer file stops explain, Show, and BTW with an error until you trim it;
868
- Bro never cuts it silently. `/bro doctor` reports the problem, and the
869
- editor still opens the file so you can fix it.
870
- - **BTW threads**: when your preferences change, the next side question starts
871
- a fresh backend session that is caught up on the thread, so old preferences
872
- don't linger.
873
-
874
- `bro-prompt.md`, the full prompt template from earlier versions, is no longer
875
- read. Move what you want to keep into `/bro preferences`, and choose
876
- `/bro mode brief` for the original ELI-simpleton instruction.
877
-
878
-
879
- ## Privacy and safety
880
-
881
- - **External requests**: Bro sends the latest completed assistant response,
882
- pasted text, extracted document text, extracted webpage text, or recent
883
- session conversation text (tool calls, tool results, reasoning, and images
884
- omitted) to the selected backend and its configured model provider.
885
- - **Side conversation requests**: `/bro btw` sends your side questions and the
886
- seeded main-session conversation text (plus earlier turns when a native
887
- session is reseeded) to the selected backend. In full permission mode the
888
- side agent can additionally read and edit the workspace.
889
- - **Preferences**: `bro-preferences.md` is sent with every explain, Show,
890
- and BTW request to the selected backend. It is never sent to the advisor or
891
- to Pi's main model.
892
- - **Advisor requests**: `bro_advisor` sends the executor agent's system
893
- instructions, active tool list (excluding `bro_advisor`), ordered
894
- conversation history including tool calls and tool results (unlike Show,
895
- which omits them), your steering brief, and the executor's optional question
896
- to the selected backend. Reasoning and image bodies are omitted with explicit
897
- markers (`[reasoning omitted]`, `[image omitted]`). The advisor process runs
898
- in your workspace with auto-approved permissions; its instruction to only
899
- advise is behavioral, not an enforced boundary.
900
- - **Access enforcement** differs by backend; see
901
- [Backends: access and retention](#backends-access-and-retention). Prompt
902
- instructions are not access enforcement.
903
- - **Context isolation**: Bro does not add explanations, BTW answers, or the
904
- steering brief to Pi's conversation history or main-agent context. BTW text
905
- reaches the main editor only through `/insert` or `/insert-all`, and advisor
906
- results appear as normal tool results in the executor's transcript.
907
- - **Memory**: the latest explanation (for `/bro open`) and the BTW thread live
908
- only in process memory and clear when you switch Pi sessions, reload
909
- extensions, or quit Pi. Backend-native sessions can persist independently.
910
- The advisor steering brief is stored as session-scoped extension data
911
- (`bro-advisor-steering`) in the session file.
912
- - **File safety**: `/bro file` reads only regular files whose resolved path is
913
- inside Pi's current workspace, including after resolving symlinks. Bro's
914
- extractor does not modify them.
915
- - **Web requests**: `/bro url` connects directly to the target website. The site
916
- sees your IP address and Bro's user agent. Bro sends no browser cookies,
917
- authorization, or referrer information, and it refuses local, private, and
918
- reserved network destinations, including redirects. Avoid private or signed
919
- URLs whose query string contains secrets.
920
- - **Web extraction**: Bro parses downloaded HTML locally without executing page
921
- scripts or loading page subresources. It sends the extracted readable text,
922
- including links preserved in that text, to the selected backend; it does not
923
- separately send the requested URL or raw page HTML.
924
- - **Show diagrams**: When a show reply ends in one self-contained HTML block,
925
- Bro writes it to `/tmp/pi-bro-<uid>/bro-show-<hash>.html` with a restrictive
926
- Content-Security-Policy, and opens it in your browser only when you press
927
- **O**. **C** copies the full reply, including the HTML.
928
- - **Clipboard**: **C**, `/copy`, and `/copy-all` copy text to your system
929
- clipboard, where your operating system or clipboard manager may retain it.
930
-
931
- ## Troubleshooting and current limits
932
-
933
- If an explanation fails, run `/bro doctor` first. If a webpage cannot be
934
- extracted, copy its content into a supported text file or save it as a PDF and
935
- use `/bro file`. If a PDF contains only scanned images, run OCR with another
936
- tool before giving it to Bro.
937
-
938
- - An unsupported model, effort, or missing backend fails with that backend's
939
- diagnostic; Bro never falls back to another backend.
940
- - Document input supports `.md`, `.markdown`, `.txt`, `.pdf`, and `.docx` only;
941
- it does not perform OCR.
942
- - Webpage input supports one public HTML page, up to 5 MiB downloaded and
943
- 100,000 extracted characters. JavaScript-only, authenticated, paywalled,
944
- blocked, paginated, and media-first pages are not supported.
945
- - Direct webpage fetching does not currently use `HTTP_PROXY`, `HTTPS_PROXY`,
946
- or other proxy environment variables.
947
- - `/bro btw` threads are memory-only and do not survive reloads or restarts.
948
- - The Agy advisor requires Agy CLI `>=1.1.15`.
949
- - Show captures only the conversation text of what already happened in the
950
- current session — the last few turns' user and assistant messages, with
951
- tool calls, tool results, reasoning, and images always omitted; its shapes
952
- reflect what was reported in the conversation, not independent verification.
953
- - HTML diagrams open in your default browser; pressing **O** on a remote or
954
- headless session with no display reports the failure instead of opening
955
- anything.
956
- - Keeps only the latest explanation in memory and does not store history or
957
- export directly to files.
958
- - Bro temporarily captures mouse input while its modal is open so mouse-wheel
959
- and trackpad scrolling work in regular and fullscreen modes. Native mouse
960
- selection may be unavailable or visually extend outside the Bro window;
961
- press **C** to copy the full explanation instead.
962
-
963
- ## Development
89
+ | Feature | What is sent | What Bro keeps on disk |
90
+ | --- | --- | --- |
91
+ | Explain | The agent's last reply, your pasted text, or text extracted from your file or webpage, plus your preferences | Nothing; the last result stays in memory |
92
+ | Show | User and assistant text from recent turns (no tool calls, tool results, reasoning or images), plus your preferences | HTML diagrams in `pi-bro-<uid>/` in your system temp folder |
93
+ | Side questions | Your questions and up to the last 8 turns of conversation text, plus your preferences | Nothing; the thread stays in memory |
94
+ | Guided Review | The PR description and diff, the files the backend reads, your questions, plus your preferences | Reviews and captured source in `bro-reviews/`, with no automatic cleanup |
95
+ | Advisor | The agent's system instructions, tool list and whole conversation, including tool calls and results (reasoning and images omitted), plus your steering | Steering in `bro-advisor.md` and the session file |
96
+
97
+ `/bro url` also connects straight to the website, which sees your IP address.
98
+ Bro runs each CLI as you, with your environment. It never reads or copies Pi's
99
+ provider credentials, but the CLI signs in its own way, which can include API
100
+ keys set in your environment. Nothing Bro produces enters Pi's conversation
101
+ unless you insert it, except advisor answers, which return to the agent as
102
+ tool results.
103
+
104
+ > [!WARNING]
105
+ > These run the backend in your workspace with its permission checks bypassed:
106
+ > - **Advisor:** it can read, edit and run commands. "Advise, don't edit" is
107
+ > only an instruction.
108
+ > - **BTW full-permission mode** (turned on with `/mode` inside BTW): it is
109
+ > meant to edit files and run commands.
110
+ > - **Grok, wherever you use it:** its sandbox is always off. "Answer only from
111
+ > the supplied context" is only an instruction.
112
+
113
+ Details per backend:
114
+ [Backends: access and retention](docs/user-guide.md#backends-access-and-retention)
115
+ and [Privacy and safety](docs/user-guide.md#privacy-and-safety).
116
+
117
+ ## Limits
118
+
119
+ - Documents: `.md`, `.markdown`, `.txt`, `.pdf`, `.docx` only, no OCR, up to 10 MiB.
120
+ → Run OCR elsewhere first.
121
+ - Webpages: one public HTML page; no logins, paywalls, page JavaScript or
122
+ proxy settings. → Save the page as PDF or text and use `/bro file`.
123
+ - No fallback: if the chosen backend, model or effort fails, Bro shows that
124
+ backend's error instead of switching. → Run `/bro doctor`.
125
+ - BTW threads and the last explanation live in memory only and clear on
126
+ reload or restart.
127
+ - Guided Review runs in local interactive Pi only and does not post to
128
+ GitHub.
129
+
130
+ Full list: [Troubleshooting and current limits](docs/user-guide.md#troubleshooting-and-current-limits).
131
+
132
+ ## Stability
133
+
134
+ Bro is `0.x`: a minor version can change commands or settings. Breaking
135
+ changes are listed under **Breaking** in the [changelog](CHANGELOG.md) and the
136
+ [release notes](https://github.com/tranhoangnguyen03/pi-bro/releases). Each
137
+ release is published to npm from CI with
138
+ [provenance](https://docs.npmjs.com/generating-provenance-statements).
139
+
140
+ ## Contributing
964
141
 
965
142
  ```sh
966
- npm install
967
- npm test
143
+ npm ci
144
+ npm test # offline: uses fake backend CLIs, never calls a model
968
145
  pi --tui-mode fullscreen -e ./bro.ts
969
146
  ```
970
147
 
971
- `npm test` uses fake `agy`, `claude`, and `grok` executables and never calls an
972
- external model. See [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) for the code
973
- map and invariants, [docs/TESTING.md](docs/TESTING.md) for the manual
974
- end-to-end checklist, and [docs/README.md](docs/README.md) for the docs index.
975
-
976
- The prompt benchmark is manual and makes live Agy calls. Read
977
- [`benchmark/README.md`](benchmark/README.md) before running it; it is never part
978
- of `npm test`.
148
+ See [CONTRIBUTING.md](CONTRIBUTING.md), the [code map](docs/DEVELOPMENT.md)
149
+ and the [docs index](docs/README.md). Report security problems privately as
150
+ described in [SECURITY.md](SECURITY.md).
979
151
 
980
152
  ## License
981
153