pi-bro 0.31.0 → 0.33.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/CHANGELOG.md CHANGED
@@ -2,6 +2,25 @@
2
2
 
3
3
  All notable changes to pi-bro are documented here.
4
4
 
5
+ ## [0.33.0] - 2026-11-07
6
+
7
+ ### Highlights
8
+
9
+ - Feature discovery now starts from four human needs: understand what exists, explore what could exist, assess existing work, and guide the agent.
10
+ - BTW and Grill Me use clipboard-only manual handoff. The old Insert commands no longer modify the main Pi editor; they point users to Copy instead.
11
+ - Elevate copies the revised assignment without replacing the unsent main-editor draft. Obsolete insertion code and its tests are removed.
12
+ - Built-in help, command completion, feature guides and developer checks align around common interaction meanings while retaining each feature's special actions.
13
+ - The read-only `about_user` agent tool and `bro_advisor` tool are unchanged. Session recovery, Guided Review lifecycle, and Overthink/Architecture PRs remain separate work.
14
+
15
+ ## [0.32.0] - 2026-11-07
16
+
17
+ ### Highlights
18
+
19
+ - BTW and Grill Me preserve completed private discussions, access choices and drafts across ordinary Pi reload/restart/resume through non-model-facing custom session entries.
20
+ - Simplify restores its most recent source and explanation; Show restores the last rendered result and focus. Cleared state stays cleared.
21
+ - Session branches inherit their prior private state but later edits remain separate. No global user memory database or automatic context injection.
22
+ - Added session restore validation and test coverage. Recovery still depends on Pi saving its session entries; abrupt host crashes during an active call are not guaranteed.
23
+
5
24
  ## [0.31.0] - 2026-11-07
6
25
 
7
26
  ### Added
package/README.md CHANGED
@@ -66,14 +66,14 @@ File and webpage examples need your own real path or URL; see [how to explain th
66
66
  | `/bro elevate` or **Ctrl+Shift+E** | **[Elevate](docs/elevate.md).** Discover missing expert considerations, select useful improvements, and rewrite your task without submitting it. Shares BTW backend settings. |
67
67
  | `/bro remember-me [thought]` | **[Remember Me](docs/remember-me.md).** Privately clarify and approve short personal memories with unfoldable background. Agents can call `about_user` to read summaries and expand IDs. |
68
68
  | `/bro overthink` | **[Overthink](docs/overthink.md).** Quietly checks meaningful work with the active Pi model, using editable global/session questions and a private notes modal. Automatic checks can be switched off in config. No separate backend. |
69
- | `/bro grill-me` | **[Grill Me](docs/grill-me.md) (experimental).** A private, opinionated decision interview: light, balanced or exhaustive; one question per round; `/consolidate` drafts a brief without ending the interview; `/insert-last-message` explicitly returns the latest reply to the editor. Uses BTW model settings; read-only restrictions vary by backend. |
69
+ | `/bro grill-me` | **[Grill Me](docs/grill-me.md) (experimental).** A private, opinionated decision interview: light, balanced or exhaustive; one question per round; `/consolidate` drafts a brief without ending the interview; `/copy` returns the latest reply or decision brief to the clipboard. Uses BTW model settings; read-only restrictions vary by backend. |
70
70
  | `/bro btw` | **[Side questions](docs/features/btw.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. |
71
71
  | `/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. Claude, Muse, or Pi is recommended for untrusted PRs. |
72
72
  | `bro_advisor` tool | **[Second opinion](docs/features/advisor.md#bro-advisor).** A tool your agent can call mid-task; a fresh backend process reviews the session snapshot, can inspect the workspace when needed, and returns advice to the agent. ⚠️ [Runs with permissions bypassed](#what-leaves-your-machine). |
73
73
  | `/bro config`, `/bro preferences` | **[Settings](docs/reference/settings.md#settings) and [preferences](docs/user-guide.md#preferences).** Pick the backend, model and effort per feature, and tell Bro how you like answers. |
74
74
 
75
- For help by task, start at the **[docs home](docs/README.md)**; see the [command reference](docs/reference/commands.md) for syntax.
76
- **Elevate, in practice:** Bro points out expert questions or tests you may have missed before you ask Pi to do the work. Review the suggestions, approve only what matters, then edit or submit the resulting request yourself. See the [walkthrough](docs/elevate.md) for limits, privacy, and editor replacement.
75
+ For help by task, start with the **[four human-intent states](docs/feature-map.md)** or the **[docs home](docs/README.md)**; see the [command reference](docs/reference/commands.md) for syntax.
76
+ **Elevate, in practice:** Bro points out expert questions or tests you may have missed before you ask Pi to do the work. Review the suggestions, approve only what matters, then edit or submit the resulting request yourself. See the [walkthrough](docs/elevate.md) for limits, privacy, and copy-only handoff.
77
77
 
78
78
  Guided Review has its own [guide](docs/guided-review.md).
79
79
 
@@ -105,23 +105,25 @@ which may keep it under their own policies. Paths below are under
105
105
 
106
106
  | Feature | What is sent | What Bro keeps on disk |
107
107
  | --- | --- | --- |
108
- | 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 |
108
+ | Explain | The agent's last reply, your pasted text, or text extracted from your file or webpage, plus your preferences | Last result as a private Pi session entry |
109
109
  | Architecture Docs | Repository source, existing architecture docs, focus and preferences; only selected backend can see snapshot files | Generated Markdown, JSON graph and offline HTML in `docs/architecture/`; temporary inspection copy is removed |
110
- | Show | User and assistant text from recent turns (no tool calls, tool results, reasoning or images), plus your preferences | Diagram pages in `pi-bro-<uid>/` in your system temp folder |
111
- | Side questions | Your questions and up to the last 8 turns of conversation text, plus your preferences | Nothing; the thread stays in memory |
112
- | Grill Me | Topic, interview turns, up to the last 8 main-session text turns and preferences; any workspace files the selected inspector reads | Nothing; interview and brief are in memory |
110
+ | Show | User and assistant text from recent turns (no tool calls, tool results, reasoning or images), plus your preferences | Last result in the private Pi session, plus temporary diagram pages in `pi-bro-<uid>/` |
111
+ | Side questions | Your questions and up to the last 8 turns of conversation text, plus your preferences | Private Pi session entries with completed turns, mode and draft |
112
+ | Grill Me | Topic, interview turns, up to the last 8 main-session text turns and preferences; any workspace files the selected inspector reads | Private Pi session entries with the interview and brief |
113
113
  | Overthink | Current session projection, including tool evidence, plus private user-editable questions, to the active Pi provider | Global questions in `bro-overthink-defaults.json`; per-session questions and latest private note in Pi session custom entries |
114
114
  | Elevate | Your objective, selected findings, all current-branch user/assistant text; Full also includes tool-call arguments and text results, and preferences | Nothing; the workflow stays in memory |
115
115
  | 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 |
116
116
  | 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 |
117
117
 
118
+ Session-scoped Bro entries live **inside Pi's session file**. They stay out of the model's conversation, but are not secret from someone who can read, back up, export, or share that file. Check the session content before sharing it; this feature does not encrypt or redact exports.
119
+
118
120
  `/bro url` also connects straight to the website, which sees your IP address.
119
121
  Bro runs each CLI as you, with your environment. It never reads or copies an
120
122
  external CLI's provider credentials, but a CLI signs in its own way, which can
121
123
  include API keys set in your environment. The built-in **Pi** backend is the
122
124
  exception: it runs in-process, so it reads your Pi `auth.json` and reuses your
123
125
  Pi provider credentials for the model you select. Nothing Bro produces enters
124
- Pi's conversation unless you insert it, except advisor answers, which return to
126
+ Pi's conversation unless you paste and submit it, except advisor answers, which return to
125
127
  the agent as tool results.
126
128
 
127
129
  > [!WARNING]
@@ -148,8 +150,7 @@ and [Privacy and safety](docs/reference/data-and-permissions.md#privacy-and-safe
148
150
  - No fallback: if the chosen backend, model or effort fails, Bro shows that
149
151
  backend's error instead of switching. → Run `/bro doctor`.
150
152
  - Elevate runs fresh restricted calls through the BTW model setting. Restricted does not always mean sandboxed; see [access and retention](docs/reference/data-and-permissions.md). The shortcut may not work in all terminals: use `/bro elevate` instead.
151
- - BTW and Grill Me threads and the last explanation live in memory only and clear on
152
- reload or restart.
153
+ - BTW, Grill Me and the latest explanation/Show result use private session entries; they survive normal Pi reload/resume. A new session starts fresh and later fork changes stay separate. Abrupt crashes during active calls are not guaranteed.
153
154
  - Guided Review runs in local interactive Pi only and does not post to
154
155
  GitHub.
155
156
 
package/docs/README.md CHANGED
@@ -5,6 +5,7 @@ Start with what you want to do. The [README](../README.md) explains the product,
5
5
  ## I'm new
6
6
 
7
7
  - [Getting started](getting-started.md) — install, check your backend, and complete a working first example.
8
+ - [Choose by your current need](feature-map.md) — four intent states, expected results, and handoff rules.
8
9
  - [Command lookup](reference/commands.md#commands) — find the right command.
9
10
 
10
11
  ## I want to do something
package/docs/elevate.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  Elevate is useful before a design, research task, implementation, plan, or important decision. It is not a way to turn every small request into a large project. Sometimes the best result is: *Your original request is good enough.*
6
6
 
7
- Elevate works inside Pi's **separate Bro modal**. It does not post its discussion to the main agent or execute the revised assignment. You control whether the final text goes into the main editor, and you still press Enter to send it.
7
+ Elevate works inside Pi's **separate Bro modal**. It does not post its discussion to the main agent or execute the revised assignment. Copy and paste the revised assignment when you choose; Elevate never edits or submits Pi's main draft.
8
8
 
9
9
  ## Start here (one minute)
10
10
 
@@ -24,7 +24,7 @@ Elevate works inside Pi's **separate Bro modal**. It does not post its discussio
24
24
 
25
25
  If the main editor contains a draft, Bro pre-fills the objective with that draft. Elevate always opens Compose first so you can choose context before any model call. Otherwise, it shows a multi-line objective field: type or paste the objective and choose **Ctrl+S** (or `Ctrl+Enter` on terminals that send it, or the `[Discover gaps]` button). `Enter` adds a new line, so a pasted multi-line task keeps its structure.
26
26
 
27
- When both an explicit `/bro elevate <request>` argument and a draft exist, the **explicit argument takes priority**. The main editor is left untouched unless you later choose to insert the revision.
27
+ When both an explicit `/bro elevate <request>` argument and a draft exist, the **explicit argument takes priority**. The main editor stays untouched throughout.
28
28
 
29
29
  ## Conversation context and retry
30
30
 
@@ -41,7 +41,7 @@ The **Context: Messages** button toggles to **Context: Full**. Use Tab to focus
41
41
  1. **Discover:** “Given my objective, what would a skilled expert know, question, investigate, or test that I haven't accounted for?” Bro looks across **altitude** (right problem), **depth** (evidence, methods, tests), and **range** (useful ideas from other fields). It offers up to **five** non-overlapping suggestions, with a reason and an expert action for each. It can also report **zero** suggestions.
42
42
  2. **Upgrade:** “Rewrite my request using only the insights I approve. Keep my outcome, constraints, and scope. Improve the quality of the work, not the amount of work.” Bro returns the improved assignment for **you to review**.
43
43
 
44
- The flow is **Discover → Select → Upgrade → Insert or Copy**. It typically makes **two model calls** (discovery and rewrite); if Bro finds no useful changes, it makes only the discovery call and keeps the original request.
44
+ The flow is **Discover → Select → Upgrade → Copy**. It typically makes **two model calls** (discovery and rewrite); if Bro finds no useful changes, it makes only the discovery call and keeps the original request.
45
45
 
46
46
  ## Example: before and after
47
47
 
@@ -67,7 +67,7 @@ Bro has **not designed the system** here. It has improved the assignment you can
67
67
 
68
68
  ## Controls in the modal
69
69
 
70
- Every consequential action is a **button** on the action row. `Tab` / `Shift+Tab` move between the text/list area and the buttons, `←`/`→` move between buttons, and `Enter` activates the focused one. The focused button is marked with `›`. Nothing that changes your request or your editor happens on a stray keypress.
70
+ Every consequential action is a **button** on the action row. `Tab` / `Shift+Tab` move between the text/list area and the buttons, `←`/`→` move between buttons, and `Enter` activates the focused one. The focused button is marked with `›`. Nothing changes your main Pi editor or sends a request.
71
71
 
72
72
  | Screen | Key | Effect |
73
73
  | --- | --- | --- |
@@ -78,7 +78,6 @@ Every consequential action is a **button** on the action row. `Tab` / `Shift+Tab
78
78
  | Review discoveries | `Tab` | Move focus to the buttons. |
79
79
  | Review discoveries | `[Rewrite with N selected]` | Generate a revised request using only the ticked findings. With nothing ticked it explains why instead of proceeding. |
80
80
  | Review discoveries | `[Select all]` / `[Select none]` | Change every tick at once. |
81
- | Revised request | `[Insert into editor]` | Insert the revised request into Pi's main editor, **without sending it**. See editor behavior below. |
82
81
  | Revised request | `[Copy]` | Copy the revised request to the system clipboard. |
83
82
  | Revised request | `[Back]` | Return to the findings and change your choices. |
84
83
  | Failed step | `[Retry]` | Repeat **the step that failed**: a failed rewrite retries the rewrite with the same approved findings, so your choices are not lost. |
@@ -86,14 +85,11 @@ Every consequential action is a **button** on the action row. `Tab` / `Shift+Tab
86
85
  | Any screen | `Esc` | Cancel/close. A running backend request is asked to stop. |
87
86
  | Read long content | `↑`/`↓`, Page Up/Down, wheel | Scroll. In the findings list, `↑`/`↓` move the highlight and Page Up/Down scroll. |
88
87
 
89
- If there are **no material findings**, the revised-request screen displays your original text unchanged. You may copy, insert, or close it; no rewrite model call is made.
88
+ If there are **no material findings**, the revised-request screen displays your original text unchanged. You may copy or close it; no rewrite model call is made.
90
89
 
91
90
  ### What happens to the original editor draft?
92
91
 
93
- - **Before you insert:** Opening, selecting, copying, cancelling, or retrying Elevate does **not** change the main editor.
94
- - **In Pi terminal (TUI):** The `[Insert into editor]` button replaces the editor text with the revised request. It only replaces the draft Elevate was opened on, and only if that text has not changed since it opened; if you opened Elevate with an explicit request, the editor must be empty. Otherwise insertion is refused and you can copy instead. There is no built-in undo of this replacement in Elevate—copy the original first if you want to keep both versions.
95
- - **In compatible Pi Desktop/RPC:** The adapter only inserts when the editor is empty and confirms atomic insertion support. If the editor contains a draft or insertion isn't supported, use `[Copy]` and paste manually. It does **not** replace a Desktop draft.
96
- - **After insertion:** The new text remains editable. **Nothing is sent to Pi's main agent** until *you* submit it.
92
+ Elevate never writes to Pi's editor. It may use the unsent draft as its starting objective, but Copy only writes to the clipboard. Paste the revised request yourself and submit when ready. If you have an unsent draft, it stays unchanged.
97
93
 
98
94
  ## What Elevate can and cannot do
99
95
 
@@ -116,7 +112,6 @@ If there are **no material findings**, the revised-request screen displays your
116
112
  | Nothing to work on | Type the objective into the modal and choose `[Discover gaps]`, or pass it with `/bro elevate <request>`. |
117
113
  | “Invalid discovery JSON” | The model didn't follow the required response format. Choose `[Retry]` to repeat the step; consider a different BTW model in `/bro config`. |
118
114
  | Backend/model/effort fails | Run `/bro doctor`; Elevate does not silently switch models. |
119
- | If `[Insert into editor]` is refused | Your editor changed while Elevate was open, or Desktop can't safely insert into a non-empty editor. Use `[Copy]`, then paste. |
120
115
  | The rewrite added unwanted scope | Use `[Back]` to approve fewer findings, or `Esc` to keep your original request. |
121
116
  | You need source-backed research | Ask the main agent to investigate after you submit the improved request. Elevate's discovery alone does not verify source facts. |
122
117
 
@@ -7,7 +7,7 @@
7
7
  `/bro btw` opens a separate multi-turn conversation in a modal, so you can ask
8
8
  a quick side question while the main agent keeps working. It runs through the
9
9
  selected backend and never adds anything to Pi's conversation unless you
10
- explicitly insert it into the editor. Bro writes for a tired reader: the point
10
+ copy it, paste it and send it yourself. Bro writes for a tired reader: the point
11
11
  first, in plain words, at a length that fits the question, in the language you
12
12
  asked in.
13
13
 
@@ -32,20 +32,20 @@ asked in.
32
32
  - `/mode`: toggles conversation-only / full permission, keeping the thread
33
33
  - `/copy`: copies the latest answer to the system clipboard
34
34
  - `/copy-all`: copies the full thread to the system clipboard
35
- - `/insert`: inserts the latest answer into the main editor without submitting
36
- - `/insert-all`: inserts the full thread into the main editor without submitting
37
35
  - `/retry`: re-asks the last question (empty Enter does the same)
36
+ - `/help`: shows available controls
38
37
  - `/clear`: resets the thread
39
38
 
40
- `/insert` and `/insert-all` never replace an existing main-editor draft:
41
- edit or clear it first. Any other text, including other slash-prefixed input
42
- such as `/send`, is sent as a question. Esc closes the modal and stops a
39
+ `/insert` and `/insert-all` are retired: Bro points you to `/copy` or `/copy-all`
40
+ instead. Any other text, including other slash-prefixed input such as `/send`,
41
+ is sent as a question. Esc closes the modal and stops a
43
42
  running turn; the thread is kept. The view follows the newest text while you
44
43
  are at the bottom; scroll up to read earlier turns. The header shows the model and reasoning effort the latest
45
44
  turn used (`default` when the model's own effort applies) and the current
46
45
  mode.
47
46
  - A turn is capped at 2 minutes in conversation-only mode and 10 minutes in
48
47
  full permission mode.
49
- - Bro's thread lives in memory only — it clears when you switch Pi sessions,
50
- reload extensions, or quit Pi. Changing the BTW backend starts a fresh
48
+ - Bro saves its completed thread, mode and draft as private Pi session entries.
49
+ Reloading or continuing the same session restores them. `/tree` restores the selected branch's state, and an aborted reply is discarded rather than saved as `…`. Reopening unchanged state adds no new disk entry. A new session starts fresh;
50
+ a fork initially inherits the shared history then changes independently. Changing the BTW backend starts a fresh
51
51
  thread; native session IDs never cross backends.
package/docs/grill-me.md CHANGED
@@ -28,11 +28,11 @@ This takes inspiration from the context-rich **Elephant** in Google's [Elephant
28
28
  | Command inside the modal | Effect |
29
29
  | --- | --- |
30
30
  | `/consolidate` | Generate a current decision brief. Does not end the interview or insert anything. |
31
- | `/insert-last-message` | Insert the latest completed Bro reply, including a consolidated brief, into an empty Pi editor **without sending**. No model call. |
31
+ | `/copy` | Copy the latest reply or consolidated brief to the clipboard. No model call or editor changes. |
32
32
  | `/depth light` | Quick, focused questioning |
33
33
  | `/depth balanced` | Default: material assumptions and trade-offs |
34
34
  | `/depth exhaustive` | Deeper alternatives, evidence and failure cases |
35
- | `/retry` | Retry the failed/cancelled operation, otherwise regenerate the latest reply. Never repeats insertion. |
35
+ | `/retry` | Retry the failed/cancelled operation, otherwise regenerate the latest reply. Never repeats copying. |
36
36
  | `/new <topic>` | Start over after confirmation. Resets depth to balanced and access to inspection. |
37
37
  | `/access inspect` | Request inspection tools; enforcement depends on backend |
38
38
  | `/access full` | Request full permissions; requires typing `yes` after a warning |
@@ -41,9 +41,9 @@ This takes inspiration from the context-rich **Elephant** in Google's [Elephant
41
41
 
42
42
  Type `/` to see matching commands; keep typing to narrow suggestions and press **Tab** to complete the first match. Completion never submits. From help, Esc returns to the discussion; a second Esc closes the modal.
43
43
 
44
- For confirmation prompts, type `yes` to proceed; anything else cancels. Depth can change between replies without losing the discussion. There are no question quotas or finished/locked states. Consolidate whenever useful, inspect the brief, then explicitly insert it or continue talking. The brief includes the current position, reasons, objections, unresolved questions and next actions. Insertion never overwrites a draft or submits it.
44
+ For confirmation prompts, type `yes` to proceed; anything else cancels. Depth can change between replies without losing the discussion. There are no question quotas or finished/locked states. Consolidate whenever useful, inspect the brief, then copy it or continue talking. The brief includes the current position, reasons, objections, unresolved questions and next actions. Copy never edits or submits the Pi draft.
45
45
 
46
- The old `/finish`, `/copy`, `/copy-all`, `/insert`, `/insert-all`, `/clear`, and entry depth flags have been removed from this experimental interface. BTW commands are unchanged.
46
+ The old `/finish`, `/copy-all`, `/insert`, `/insert-all`, `/insert-last-message`, `/clear`, and entry depth flags are not supported. Use `/copy` for the latest reply or brief; paste it where you choose. BTW also uses copy-only handoffs.
47
47
 
48
48
  Grill Me uses the **BTW model/backend/effort** selection from `/bro config`, but has its own independent thread. The header shows depth and effective access; `/help` keeps the footer short. Full access and Agy write risks remain visible in the header even when another notice is shown.
49
49
 
@@ -53,7 +53,7 @@ Grill Me uses the **BTW model/backend/effort** selection from `/bro config`, but
53
53
  - Full access can read, edit and execute commands. Bro instructs the model not to make changes, but cannot enforce that instruction. There is no automatic escalation.
54
54
  - Each turn makes a fresh backend call replaying the complete interview. Long interviews cost more and may exceed context limits; there is no hidden truncation or fallback.
55
55
  - The provider receives your topic, interview history, Bro preferences and up to eight recent main-session user/assistant text turns (40,000 characters). Captured context excludes tool calls/results, hidden reasoning and images. Backend tools can inspect additional workspace content.
56
- - Bro keeps the interview in memory, lost on reload, session change or exit. Backend/provider retention is separate; see [backend retention](reference/data-and-permissions.md#backends-access-and-retention).
56
+ - Bro stores completed interview turns, depth, access choice and drafts in private Pi session entries. The current Pi session restores them after reload or resume; a new session starts fresh, and forks diverge after inheriting earlier choices. Backend/provider retention is separate; see [backend retention](reference/data-and-permissions.md#backends-access-and-retention).
57
57
  - Closing discards partial output, preserves completed replies, and restores cancelled input unless a newer draft exists. Retry preserves the previous reply until replacement succeeds. Cancellation cannot undo backend changes; descendant cleanup on Windows and abrupt host shutdown are not guaranteed.
58
58
 
59
59
  ## Comparison
@@ -22,7 +22,7 @@ Bro follows the host's `getAgentDir()`: normally `~/.pi/agent` on Pi and `~/.pig
22
22
 
23
23
  - **PiG 0.3.0 RPC does not enforce `--exclude-tools`.** Excluded tools may remain active and reach provider requests. This is not a sandbox boundary. Use an explicit `--tools` allowlist instead; do not rely on `/bro doctor` to prove exclusion. Bro does not mask this defect by falsely reporting an active tool as unavailable.
24
24
  - The smoke suite retains Pi's strict exclusion assertion. The PiG lane has an explicit version-specific expected failure; a changed result fails the lane so the exception must be reviewed/removed.
25
- - Elevate is not yet qualified end-to-end on PiG. Interactive behavior, keyboard shortcut delivery and guarded editor insertion must be checked on PiG before claiming support.
25
+ - Elevate is not yet qualified end-to-end on PiG. Interactive behavior, keyboard shortcut delivery and clipboard Copy must be checked on PiG before claiming support.
26
26
  - Guided Review currently targets local Pi interactive mode. Its capture/reading/question/regeneration journey is not qualified on PiG or RPC/Desktop; existing Bro PiG checks do not establish review support. See [current review scope](guided-review.md#not-available-yet).
27
27
  - Mouse-wheel forwarding is not qualified; use keyboard scrolling.
28
28
  - Remote/SSH OSC 52 clipboard forwarding is not qualified. Local clipboard behavior depends on the host and installed platform utilities.
@@ -43,9 +43,9 @@ Typing `/bro ` displays ten task-level suggestions: `simplify`, `show`, `btw`, `
43
43
  | `/bro guided-review` | List saved reviews; `resume` is an alias. |
44
44
  | `/bro remember-me [thought]` | Start a private memory-writing conversation, browse and expand memories, and approve saves explicitly. [Guide](../remember-me.md). |
45
45
  | `/bro overthink` | View the latest private automatic second-look notes, without a model call. Ctrl+R retry, Ctrl+E edit session questions, ? help, Ctrl+C copy. [Guide](../overthink.md). |
46
- | `/bro grill-me [topic]` | Private one-question-at-a-time decision interview. Supply a topic to start fresh; omit it to resume. `/consolidate` drafts a brief; `/insert-last-message` inserts explicitly without sending. `/help` lists modal controls. [Guide](../grill-me.md). |
47
- | `/bro elevate [request]` | Improve an assignment before execution. Discover up to five gaps, choose useful findings, and insert a revised request without submitting it. **Ctrl+Shift+E** can use your unsent draft. See [Elevate](../elevate.md). |
48
- | `/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. |
46
+ | `/bro grill-me [topic]` | Private one-question-at-a-time decision interview. Supply a topic to start fresh; omit it to resume. `/consolidate` drafts a brief; `/copy` copies the latest reply or brief; Pi's editor stays untouched. `/help` lists modal controls. [Guide](../grill-me.md). |
47
+ | `/bro elevate [request]` | Improve an assignment before execution. Discover up to five gaps, choose useful findings, and copy the revised request. Pi's editor is never changed. **Ctrl+Shift+E** can use your unsent draft. See [Elevate](../elevate.md). |
48
+ | `/bro btw [question]` | Open a side conversation in a modal, seeded with recent main-session context. Starts conversation-only; `/mode` toggles full workspace access; `/copy` and `/copy-all` copy the latest answer or full thread. |
49
49
  | `/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`. |
50
50
  | `/bro advisor-steer` | View, edit, save, or clear the one persistent steering brief the advisor always sees. |
51
51
  | `/bro help` | Open the built-in quick reference. |
@@ -100,7 +100,7 @@ See [feature guide](../features/architecture.md).
100
100
  pasted text, extracted document text, extracted webpage text, or recent
101
101
  session conversation text (tool calls, tool results, reasoning, and images
102
102
  omitted) to the selected backend and its configured model provider.
103
- - **Elevate requests**: `/bro elevate` sends your objective, preferences, and all user/assistant text on the current branch by default, without a fixed history cap. Its visible Context switch can include tool-call arguments and text results (Full), potentially including sensitive file contents or command output. Both modes exclude hidden reasoning and image binaries. Only explicit Retry after a context-overload error trims older history; the UI discloses reduced context. Its optional rewrite call includes only approved findings. It makes fresh restricted calls through the BTW model setting, but a backend's restricted mode is not a universal file/network sandbox (Grok restrictions are prompt-only). It does not insert or submit anything to Pi unless you approve insertion. In the terminal, insertion can replace the draft Elevate was opened on, if it is unchanged; an explicit `/bro elevate <request>` requires an empty editor. See the [Elevate guide](../elevate.md).
103
+ - **Elevate requests**: `/bro elevate` sends your objective, preferences, and all user/assistant text on the current branch by default, without a fixed history cap. Its visible Context switch can include tool-call arguments and text results (Full), potentially including sensitive file contents or command output. Both modes exclude hidden reasoning and image binaries. Only explicit Retry after a context-overload error trims older history; the UI discloses reduced context. Its optional rewrite call includes only approved findings. It makes fresh restricted calls through the BTW model setting, but a backend's restricted mode is not a universal file/network sandbox (Grok restrictions are prompt-only). Elevate never edits or submits Pi's main draft. The user may copy the revision and paste it manually. See the [Elevate guide](../elevate.md).
104
104
  - **Side conversation requests**: `/bro btw` sends your side questions and the
105
105
  seeded main-session conversation text (plus earlier turns when a native
106
106
  session is reseeded) to the selected backend. In full permission mode the
@@ -123,15 +123,12 @@ See [feature guide](../features/architecture.md).
123
123
  instructions are not access enforcement.
124
124
  - **Context isolation**: Bro does not add explanations, BTW answers, or the
125
125
  steering brief to Pi's conversation history or main-agent context. BTW text
126
- reaches the main editor only through `/insert` or `/insert-all`, and advisor
126
+ reaches the main conversation only after the user copies, pastes, and submits it, and advisor
127
127
  results appear as normal tool results in the executor's transcript.
128
128
  - **Saved reviews**: Guided Review records, questions, drafts and captured Git source persist under the host's `getAgentDir()/bro-reviews/`. No automatic cleanup or sync is provided; see [storage and removal](../guided-review.md#access-privacy-and-storage).
129
- - **Memory**: the latest explanation (for `/bro open`) and the BTW thread live
130
- only in process memory and clear when you switch Pi sessions, reload
131
- extensions, or quit Pi. Backend-native sessions can persist independently.
132
- Standing advisor priorities are stored in `~/.pi/agent/bro-advisor.md`, and
133
- the session steering brief is stored as session-scoped extension data
134
- (`bro-advisor-steering`) in the session file.
129
+ - **Private session continuity**: completed BTW and Grill Me turns, modes, drafts, the latest Simplify state and the last Show result are saved as Pi `custom` entries inside the current session file. They survive normal reload/restart and are never added to the main model or Advisor snapshot. A fork initially inherits earlier entries; later updates stay on its own branch. This is local disk storage, not a global memory store or an abrupt-crash guarantee. Backend-native sessions may persist independently.
130
+ Standing Advisor priorities are stored in `~/.pi/agent/bro-advisor.md`, and
131
+ the session steering brief uses another `custom` entry (`bro-advisor-steering`). Session entries remain readable to anyone with the session file; export/sharing may include them. The private boundary is model-context isolation, not encrypted storage or export redaction.
135
132
  - **File safety**: `/bro file` reads only regular files whose resolved path is
136
133
  inside Pi's current workspace, including after resolving symlinks. Bro's
137
134
  extractor does not modify them.
@@ -43,7 +43,7 @@ tool before giving it to Bro.
43
43
  - Direct webpage fetching does not currently use `HTTP_PROXY`, `HTTPS_PROXY`,
44
44
  or other proxy environment variables.
45
45
  - `/bro elevate` is pre-execution only. It does not validate expert claims, run source research or keep a persistent thread. Invalid discovery JSON can be retried with the [Retry] button; if it recurs, choose another BTW backend/model in `/bro config`. See [Elevate](../elevate.md).
46
- - `/bro btw` threads are memory-only and do not survive reloads or restarts.
46
+ - `/bro btw` threads are saved in the Pi session file and restored on reload/restart. With the Pi backend, the native side session is memory-only, so the first turn after a restart reseeds it from the saved transcript and shows an expiry notice.
47
47
  - The Agy advisor requires Agy CLI `>=1.1.15`.
48
48
  - Show captures only the conversation text of what already happened in the
49
49
  current session — the last few turns' user and assistant messages, with
@@ -32,7 +32,7 @@ See [Guided Review](guided-review.md#guided-review).
32
32
 
33
33
  ## Bro Elevate — improve a task before sending it
34
34
 
35
- See [Elevate: Discover → Select → Upgrade](elevate.md). Elevate does not execute a task or send it to the main agent. It helps find gaps, lets you approve suggestions, then offers a revised request. In the terminal, insertion can replace your unchanged original draft; see the [editor-safety rules](elevate.md#what-happens-to-the-original-editor-draft).
35
+ See [Elevate: Discover → Select → Upgrade](elevate.md). Elevate does not execute a task or send it to the main agent. It helps find gaps, lets you approve suggestions, then offers a revised request. Elevate never edits your Pi draft; copy and paste the revision if you wish.
36
36
 
37
37
  ## Bro btw (side conversation)
38
38
 
@@ -166,7 +166,7 @@ See [Troubleshooting and current limits](reference/troubleshooting.md#troublesho
166
166
 
167
167
  ## Simplify modal
168
168
 
169
- `/bro` opens Simplify and explains the latest completed assistant reply. `/bro simplify` returns to the most recent Simplify screen without another model request. Inside, `/simplify`, `/text <text>`, `/file <path>` and `/url <url>` produce one explanation at a time; `/copy` copies the answer, `/clear` clears it, and `/help` shows controls. Press **M** with an empty composer to change the explanation mode and rerun; **R** retries. The saved default mode remains unchanged. The current screen is kept only within the Pi session. Old `/bro text|file|url|open` forms remain callable for compatibility.
169
+ `/bro` opens Simplify and explains the latest completed assistant reply. `/bro simplify` returns to the most recent Simplify screen without another model request. Inside, `/simplify`, `/text <text>`, `/file <path>` and `/url <url>` produce one explanation at a time; `/copy` copies the answer, `/clear` clears it, and `/help` shows controls. Press **M** with an empty composer to change the explanation mode and rerun; **R** retries. The saved default mode remains unchanged. The latest result is preserved in private Pi session entries across reload/restart and stays off the main model's context. Old `/bro text|file|url|open` forms remain callable for compatibility.
170
170
 
171
171
  ## Bro command discovery and Config navigation
172
172
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-bro",
3
- "version": "0.31.0",
3
+ "version": "0.33.0",
4
4
  "description": "A sidekick for you and your Pi agent: plain-language explanations, side questions, diagrams, PR review and second opinions, without cluttering the agent's context.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -61,6 +61,7 @@
61
61
  "src/remember.ts",
62
62
  "src/simplify-engine.ts",
63
63
  "src/simplify-ui.ts",
64
+ "src/session-state.ts",
64
65
  "src/explain-modal.ts",
65
66
  "src/review.ts",
66
67
  "src/review-source.ts",
@@ -104,7 +105,7 @@
104
105
  "scripts": {
105
106
  "docs:check": "node scripts/check-docs.mjs && node --test test/docs-quality.test.mjs",
106
107
  "typecheck": "tsc --noEmit",
107
- "test": "npm run typecheck && npm run docs:check && node .github/scripts/release-utils.mjs selftest && node --test test/architecture.test.mjs test/architecture-review.test.mjs test/architecture-controller.test.mjs test/elevate-docs.test.mjs test/elevate.test.ts test/overthink.test.ts test/simplify.test.ts test/simplify-modal.test.mjs test/grill.test.ts test/config-navigation.test.ts test/config-navigation-modal.test.mjs test/remember.test.ts test/remember-modal.test.mjs test/review-ux.test.mjs test/review-doctor.test.mjs test/review-versions.test.mjs test/review-regeneration.test.mjs test/review-modal.test.mjs test/review.test.ts test/review-ui.test.mjs test/review-session.test.mjs test/helpers.test.mjs test/prompt.test.ts test/backend.test.ts test/claude.test.ts test/grok.test.ts test/codex.test.ts test/muse.test.ts test/settings.test.ts test/sources.test.ts test/release.test.ts test/show-html.test.ts test/smoke-rpc.test.ts test/ui-capabilities.test.ts test/modal-contract.test.mjs benchmark/*.test.ts && sh ./test/smoke-test.sh",
108
+ "test": "npm run typecheck && npm run docs:check && node .github/scripts/release-utils.mjs selftest && node --test test/architecture.test.mjs test/architecture-review.test.mjs test/architecture-controller.test.mjs test/elevate-docs.test.mjs test/elevate.test.ts test/overthink.test.ts test/simplify.test.ts test/simplify-modal.test.mjs test/session-state.test.ts test/session-lifecycle.test.mjs test/grill.test.ts test/config-navigation.test.ts test/config-navigation-modal.test.mjs test/remember.test.ts test/remember-modal.test.mjs test/review-ux.test.mjs test/review-doctor.test.mjs test/review-versions.test.mjs test/review-regeneration.test.mjs test/review-modal.test.mjs test/review.test.ts test/review-ui.test.mjs test/review-session.test.mjs test/helpers.test.mjs test/prompt.test.ts test/backend.test.ts test/claude.test.ts test/grok.test.ts test/codex.test.ts test/muse.test.ts test/settings.test.ts test/sources.test.ts test/release.test.ts test/show-html.test.ts test/smoke-rpc.test.ts test/ui-capabilities.test.ts test/modal-contract.test.mjs benchmark/*.test.ts && sh ./test/smoke-test.sh",
108
109
  "benchmark:dry-run": "node benchmark/run.ts dry-run",
109
110
  "benchmark:run": "node benchmark/run.ts run",
110
111
  "benchmark:report": "node benchmark/run.ts report",
package/src/bro.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { ADVISOR_STEERING_FILE, ADVISOR_TOOL_NAME, registerAdvisorTool } from "./advisor.ts";
3
3
  import {
4
4
  type BtwThread,
@@ -50,6 +50,7 @@ import {
50
50
  } from "./sources.ts";
51
51
  import { hasBroCustomUi } from "./ui-capabilities.ts";
52
52
  import { errorMessage, unquote, withDoctor } from "./util.ts";
53
+ import { BTW_SESSION_ENTRY, GRILL_SESSION_ENTRY, SIMPLIFY_SESSION_ENTRY, LAST_RESULT_SESSION_ENTRY, restorePrivateBroState, privateSessionEntrySnapshots } from "./session-state.ts";
53
54
 
54
55
  export * from "./util.ts";
55
56
  export * from "./ui-capabilities.ts";
@@ -71,6 +72,7 @@ export * from "./simplify-engine.ts";
71
72
  export * from "./simplify-ui.ts";
72
73
  export * from "./overthink-state.ts";
73
74
  export * from "./overthink.ts";
75
+ export * from "./session-state.ts";
74
76
 
75
77
  const COMMANDS = [
76
78
  { value: "architecture", label: "architecture", description: "Document this repository in docs/architecture/ with diagrams and an offline map" },
@@ -80,18 +82,18 @@ const COMMANDS = [
80
82
  { value: "url", label: "url", description: "Explain a public webpage" },
81
83
  { value: "open", label: "open", description: "Reopen the last explanation" },
82
84
  { value: "doctor", label: "doctor", description: "Check whether Bro is ready" },
83
- { value: "show", label: "show", description: "Draw what happened in recent session turns as shapes" },
85
+ { value: "show", label: "show", description: "Need to see how recent turns fit together? Get a visual outline or diagram" },
84
86
  { value: "mode", label: "mode", description: "View or choose explanation mode (brief, balanced, faithful)" },
85
- { value: "preferences", label: "preferences", description: "View or edit what Bro knows about you and how you like answers" },
86
- { value: "guided-review", label: "guided-review", description: "Understand and assess a PR with captured code and optional private questions" },
87
- { value: "btw", label: "btw", description: "Open a side conversation (starts conversation-only; /mode toggles full permission)" },
88
- { value: "elevate", label: "elevate", description: "Discover missing expert considerations, then improve a request" },
89
- { value: "remember-me", label: "remember-me", description: "Help write and review personal memories; agents can unfold them on demand" },
90
- { value: "grill-me", label: "grill-me", description: "A private, one-question-at-a-time decision interview" },
91
- { value: "overthink", label: "overthink", description: "View private automatic second-look notes and session questions" },
87
+ { value: "preferences", label: "preferences", description: "Want Bro to follow your style? Edit saved response preferences" },
88
+ { value: "guided-review", label: "guided-review", description: "Need to assess a PR? Get source-backed findings and saved private questions" },
89
+ { value: "btw", label: "btw", description: "Want to explore a side question? Get a private conversation" },
90
+ { value: "elevate", label: "elevate", description: "Have an assignment for Pi? Get an improved request to copy and send" },
91
+ { value: "remember-me", label: "remember-me", description: "Want Pi to remember your preferences? Save approved memories for about_user" },
92
+ { value: "grill-me", label: "grill-me", description: "Facing a decision? Get focused challenges and an optional decision brief" },
93
+ { value: "overthink", label: "overthink", description: "Want a quiet second look after big work? Get private notes from the active model" },
92
94
  { value: "config", label: "config", description: "Global defaults, diagnostics and feature settings" },
93
95
  { value: "advisor", label: "advisor", description: "Check whether the executor's advisor tool is available right now" },
94
- { value: "advisor-steer", label: "advisor-steer", description: "View, edit, save, or clear the advisor's persistent steering brief" },
96
+ { value: "advisor-steer", label: "advisor-steer", description: "Want to shape future advice? Save priorities for the advisor" },
95
97
  { value: "help", label: "help", description: "Learn what Bro does and what it can access" },
96
98
  ];
97
99
  const KNOWN_ACTIONS = new Set(COMMANDS.map((command) => command.value));
@@ -107,21 +109,54 @@ export default async function bro(pi: ExtensionAPI) {
107
109
  let lastShowSteering: string | undefined;
108
110
  let btwThread: BtwThread | undefined;
109
111
  let grillThread: GrillThread | undefined;
112
+ let savedSnapshots = new Map<string, string>();
113
+ // Pi custom entries are append-only. Save a new snapshot only if its content changed.
114
+ // Reset the comparison on /tree: a new branch must never inherit the old branch's state.
115
+ const appendChanged = (type: string, value: unknown) => {
116
+ const data = structuredClone(value);
117
+ const serialized = JSON.stringify(data);
118
+ if (savedSnapshots.get(type) === serialized) return;
119
+ pi.appendEntry(type, data);
120
+ savedSnapshots.set(type, serialized);
121
+ };
110
122
  const remember = (result: ModalResult, showSteering?: string) => {
111
123
  if (result.source) {
112
124
  lastResult = result;
113
125
  lastShowSteering = showSteering;
126
+ appendChanged(LAST_RESULT_SESSION_ENTRY, { result, steering: showSteering });
114
127
  }
115
128
  };
129
+ const saveSimplify = () => {
130
+ if (!savedSnapshots.has(SIMPLIFY_SESSION_ENTRY) && !simplifyState.result && !simplifyState.draft) return;
131
+ appendChanged(SIMPLIFY_SESSION_ENTRY, { state: simplifyState });
132
+ };
133
+ const saveBtw = () => {
134
+ if (!btwThread) return;
135
+ // Visiting an empty BTW modal does not need a disk entry.
136
+ if (!savedSnapshots.has(BTW_SESSION_ENTRY) &&
137
+ !btwThread.turns.length && !btwThread.draft && !btwThread.full) return;
138
+ appendChanged(BTW_SESSION_ENTRY, { thread: btwThread });
139
+ };
140
+ const saveGrill = () => {
141
+ if (!grillThread) return;
142
+ if (!savedSnapshots.has(GRILL_SESSION_ENTRY) &&
143
+ !grillThread.topic && !grillThread.turns.length && !grillThread.draft) return;
144
+ appendChanged(GRILL_SESSION_ENTRY, { thread: grillThread });
145
+ };
146
+ const restore = (ctx: ExtensionContext) => {
147
+ const branch = ctx.sessionManager.getBranch();
148
+ const restored = restorePrivateBroState(branch);
149
+ savedSnapshots = privateSessionEntrySnapshots(branch);
150
+ lastResult = restored.lastResult;
151
+ lastShowSteering = restored.lastShowSteering;
152
+ simplifyState = restored.simplify;
153
+ btwThread = restored.btw;
154
+ grillThread = restored.grill;
155
+ };
116
156
 
117
157
  pi.on("session_shutdown", async () => { stopGuidedReviews(); });
118
-
119
- pi.on("session_start", async (_event, _ctx) => {
120
- lastResult = undefined;
121
- simplifyState = {};
122
- btwThread = undefined;
123
- grillThread = undefined;
124
- });
158
+ pi.on("session_start", async (_event, ctx) => { restore(ctx); });
159
+ pi.on("session_tree", async (_event, ctx) => { restore(ctx); });
125
160
 
126
161
  registerAdvisorTool(pi);
127
162
  registerAboutUserTool(pi);
@@ -146,7 +181,7 @@ export default async function bro(pi: ExtensionAPI) {
146
181
 
147
182
  if (action === "simplify") {
148
183
  if (value) { ctx.ui.notify("Use /bro simplify to reopen the last Simplify view; use /text, /file or /url inside it.", "warning"); return; }
149
- try { await openSimplifyWorkflow(ctx, simplifyState, {kind:"resume"}); if (simplifyState.result) remember(simplifyState.result); }
184
+ try { await openSimplifyWorkflow(ctx, simplifyState, {kind:"resume"}); saveSimplify(); if (simplifyState.result) remember(simplifyState.result); }
150
185
  catch (error) { ctx.ui.notify(withDoctor(error), "error"); }
151
186
  return;
152
187
  }
@@ -183,6 +218,7 @@ export default async function bro(pi: ExtensionAPI) {
183
218
  : {kind:action as "text" | "file" | "url", input:value};
184
219
  try {
185
220
  await openSimplifyWorkflow(ctx, simplifyState, initial);
221
+ saveSimplify();
186
222
  if (simplifyState.result) remember(simplifyState.result);
187
223
  } catch (error) { ctx.ui.notify(withDoctor(error), "error"); }
188
224
  return;
@@ -298,9 +334,14 @@ export default async function bro(pi: ExtensionAPI) {
298
334
  try {
299
335
  const btwBackend = capabilityBackend(await readSettings(), "btw");
300
336
  const thread = resolveBtwThread(btwThread);
301
- if (bindBtwBackend(thread, btwBackend)) ctx.ui.notify("Backend changed — started a fresh side thread.", "info");
337
+ const backendChanged = bindBtwBackend(thread, btwBackend);
338
+ if (backendChanged) ctx.ui.notify("Backend changed — started a fresh side thread.", "info");
302
339
  btwThread = thread;
303
- await openBtwModal(ctx, { thread, initialQuestion: parsed.question });
340
+ if (backendChanged) saveBtw();
341
+ await openBtwModal(ctx, {
342
+ thread, initialQuestion: parsed.question,
343
+ onChange: () => { if (btwThread === thread) saveBtw(); },
344
+ });
304
345
  } catch (error) {
305
346
  ctx.ui.notify(withDoctor(error), "error");
306
347
  }
@@ -321,7 +362,9 @@ export default async function bro(pi: ExtensionAPI) {
321
362
  const start = Boolean(parsed.topic);
322
363
  if (start) grillThread = { topic: parsed.topic, depth: parsed.depth, turns: [], fullAccess: false };
323
364
  else grillThread ??= { topic: "", depth: parsed.depth, turns: [], fullAccess: false };
324
- try { await openGrillModal(ctx, grillThread, { start }); }
365
+ const thread = grillThread;
366
+ if (start) saveGrill();
367
+ try { await openGrillModal(ctx, thread, { start, onChange: () => { if (grillThread === thread) saveGrill(); } }); }
325
368
  catch (error) { ctx.ui.notify(withDoctor(error), "error"); }
326
369
  return;
327
370
  }
package/src/btw.ts CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  } from "./settings.ts";
15
15
  import { captureShowTranscript } from "./show.ts";
16
16
  import { BRO_OVERLAY, broOverlayArea, formatNotice, modalHeight, openBroOverlay, renderFrame, Scroller, type Area, type NoticeTone, type Theme, type TuiLike } from "./modal-kit.ts";
17
- import { canBroInsertIntoEditor, insertBroDesktopText, type BroMouseEvent, type BroMouseResult } from "./ui-capabilities.ts";
17
+ import { type BroMouseEvent, type BroMouseResult } from "./ui-capabilities.ts";
18
18
  import { errorMessage } from "./util.ts";
19
19
 
20
20
  export const BTW_CONTEXT_TURNS = 8;
@@ -109,7 +109,7 @@ export type BtwComposerAction =
109
109
  | { kind: "mode" }
110
110
  | { kind: "retry" }
111
111
  | { kind: "clipboard"; all: boolean }
112
- | { kind: "insert"; all: boolean }
112
+ | { kind: "help" }
113
113
  | { kind: "removed"; command: string }
114
114
  | { kind: "question"; text: string };
115
115
 
@@ -121,8 +121,8 @@ export function parseBtwComposerCommand(value: string): BtwComposerAction {
121
121
  if (command === "/copy" || command === "/copy-all") {
122
122
  return { kind: "clipboard", all: command === "/copy-all" };
123
123
  }
124
- if (command === "/insert" || command === "/insert-all") return { kind: "insert", all: command === "/insert-all" };
125
- if (command === "/insert!" || command === "/insert-all!") return { kind: "removed", command };
124
+ if (command === "/help") return { kind: "help" };
125
+ if (["/insert", "/insert-all", "/insert!", "/insert-all!"].includes(command)) return { kind: "removed", command };
126
126
  return { kind: "question", text: command };
127
127
  }
128
128
 
@@ -330,7 +330,7 @@ export class BtwModal implements Focusable {
330
330
  body: (rows, innerWidth) => this.scroller.view(this.markdown.render(innerWidth), rows),
331
331
  // The frame drops lines from the top when space runs out, so the composer goes last.
332
332
  footer: [
333
- ...(this.appearance.commands === "" ? [] : wrapTextWithAnsi(this.appearance.commands ?? "Commands: /mode · /copy · /copy-all · /insert · /insert-all · /clear · /retry", inner)),
333
+ ...(this.appearance.commands === "" ? [] : wrapTextWithAnsi(this.appearance.commands ?? "Commands: /mode · /copy · /copy-all · /clear · /retry · /help", inner)),
334
334
  ...(this.suggestions ? wrapTextWithAnsi(this.theme.fg("accent", this.suggestions), inner) : []),
335
335
  this.theme.fg("accent", this.theme.bold(this.appearance.inputLabel ?? "Your message to Bro")),
336
336
  this.input.render(inner)[0] ?? "",
@@ -349,7 +349,7 @@ export class BtwModal implements Focusable {
349
349
 
350
350
  export async function openBtwModal(
351
351
  ctx: ExtensionCommandContext,
352
- options: { thread: BtwThread; initialQuestion?: string },
352
+ options: { thread: BtwThread; initialQuestion?: string; onChange?: () => void },
353
353
  ): Promise<void> {
354
354
  const thread = options.thread;
355
355
 
@@ -358,6 +358,25 @@ export async function openBtwModal(
358
358
  (tui, theme, _keybindings, done) => {
359
359
  let closed = false;
360
360
  let controller: AbortController | undefined;
361
+ let activeTurn: { pending?: BtwTurn; original?: BtwTurn } | undefined;
362
+ // Discard an unfinished reply immediately on close, before another modal can
363
+ // reuse the same thread. A cancelled retry restores the completed old turn.
364
+ const discardUnfinished = () => {
365
+ const work = activeTurn;
366
+ if (!work) return;
367
+ let position = thread.turns.length;
368
+ if (work.pending) {
369
+ const index = thread.turns.indexOf(work.pending);
370
+ if (index >= 0) {
371
+ position = index;
372
+ thread.turns.splice(index, 1);
373
+ }
374
+ }
375
+ if (work.original && !thread.turns.includes(work.original)) {
376
+ thread.turns.splice(position, 0, work.original);
377
+ }
378
+ activeTurn = undefined;
379
+ };
361
380
 
362
381
  const transcript = () => formatBtwTranscript(thread.turns);
363
382
 
@@ -376,13 +395,18 @@ export async function openBtwModal(
376
395
  closed = true;
377
396
  saveDraft();
378
397
  controller?.abort();
398
+ discardUnfinished();
399
+ options.onChange?.();
379
400
  done(undefined);
380
401
  };
381
402
 
382
403
  const modal = new BtwModal(tui, theme, close, submit, () => {
404
+ if (closed) return; // Close already saved and cleaned this thread.
383
405
  closed = true;
384
406
  saveDraft();
385
407
  controller?.abort();
408
+ discardUnfinished();
409
+ options.onChange?.();
386
410
  });
387
411
  modal.onInput = () => {
388
412
  composerTouched = true;
@@ -393,6 +417,8 @@ export async function openBtwModal(
393
417
  const runTurn = async (question: string, replaced?: BtwTurn) => {
394
418
  if (controller) return;
395
419
  const turnController = new AbortController();
420
+ const work: { pending?: BtwTurn; original?: BtwTurn } = { original: replaced };
421
+ activeTurn = work;
396
422
  controller = turnController;
397
423
  modal.setRunning(true);
398
424
 
@@ -402,20 +428,22 @@ export async function openBtwModal(
402
428
  settings = await readSettings();
403
429
  preferences = await readPreferences();
404
430
  } catch (error) {
405
- if (replaced) thread.turns.push(replaced);
406
- if (!replaced && !options.initialQuestion) modal.setComposerText(question);
431
+ if (activeTurn === work) discardUnfinished();
432
+ if (!closed && !replaced && !options.initialQuestion) modal.setComposerText(question);
407
433
  if (controller === turnController) controller = undefined;
408
- if (!closed) { modal.setRunning(false); modal.setNotice(errorMessage(error), "error"); }
434
+ if (!closed) { modal.setRunning(false); modal.setNotice(errorMessage(error), "error"); options.onChange?.(); }
409
435
  return;
410
436
  }
411
- // Closing (or reopening) during the reads above must not touch the shared thread.
437
+ // Do not restore a cancelled retry twice after close/dispose.
412
438
  if (closed || turnController.signal.aborted) {
413
- if (replaced) thread.turns.push(replaced);
414
- if (!replaced && !options.initialQuestion) modal.setComposerText(question);
439
+ if (activeTurn === work) discardUnfinished();
415
440
  if (controller === turnController) controller = undefined;
416
441
  return;
417
442
  }
418
- if (bindBtwBackend(thread, capabilityBackend(settings, "btw"))) modal.setNotice("Backend changed — started a fresh side thread.", "warning");
443
+ if (bindBtwBackend(thread, capabilityBackend(settings, "btw"))) {
444
+ work.original = undefined; // An old-backend retry must not recreate discarded history.
445
+ modal.setNotice("Backend changed — started a fresh side thread.", "warning");
446
+ }
419
447
  if (thread.turns.length === 0) {
420
448
  thread.conversationId = undefined;
421
449
  const context = captureShowTranscript(ctx, BTW_CONTEXT_TURNS, BTW_CONTEXT_MAX)?.text;
@@ -428,7 +456,9 @@ export async function openBtwModal(
428
456
  const context = conversationId ? undefined : thread.context;
429
457
  const full = thread.full;
430
458
 
431
- thread.turns.push({ question, answer: "…" });
459
+ const pending = { question, answer: "…" };
460
+ work.pending = pending;
461
+ thread.turns.push(pending);
432
462
  modal.setText(transcript());
433
463
  modal.scrollToEnd();
434
464
 
@@ -444,11 +474,11 @@ export async function openBtwModal(
444
474
  turnController.signal,
445
475
  (partial) => {
446
476
  if (closed || turnController.signal.aborted) return;
447
- thread.turns[thread.turns.length - 1]!.answer = partial;
477
+ pending.answer = partial;
448
478
  modal.setText(transcript());
449
479
  },
450
480
  );
451
- if (turnController.signal.aborted) return;
481
+ if (closed || turnController.signal.aborted) return;
452
482
  if (result.expiredContinuation) {
453
483
  // The native session is gone. Drop the dead id, rebuild the prompt from this thread's own
454
484
  // transcript AND its captured main-session context (the local `context` is undefined
@@ -462,7 +492,7 @@ export async function openBtwModal(
462
492
  turnController.signal,
463
493
  (partial) => {
464
494
  if (closed || turnController.signal.aborted) return;
465
- thread.turns[thread.turns.length - 1]!.answer = partial;
495
+ pending.answer = partial;
466
496
  modal.setText(transcript());
467
497
  },
468
498
  );
@@ -473,16 +503,21 @@ export async function openBtwModal(
473
503
  thread.sessionFull = full;
474
504
  thread.sessionPreferences = preferences;
475
505
  }
476
- thread.turns[thread.turns.length - 1]!.answer = result.text;
506
+ pending.answer = result.text;
477
507
  } catch (error) {
478
508
  if (turnController.signal.aborted || closed) return;
479
- thread.turns[thread.turns.length - 1]!.answer = `_${errorMessage(error)}_`;
509
+ pending.answer = `_${errorMessage(error)}_`;
480
510
  modal.setNotice(errorMessage(error), "error");
481
511
  } finally {
482
512
  if (controller === turnController) controller = undefined;
513
+ if (activeTurn === work) {
514
+ if (closed || turnController.signal.aborted) discardUnfinished();
515
+ else activeTurn = undefined;
516
+ }
483
517
  if (!closed) {
484
518
  modal.setRunning(false);
485
519
  modal.setText(transcript());
520
+ options.onChange?.();
486
521
  }
487
522
  }
488
523
  };
@@ -491,6 +526,7 @@ export async function openBtwModal(
491
526
  toggleBtwMode(thread);
492
527
  modal.setFull(thread.full);
493
528
  modal.setNotice(`Mode: ${btwModeLabel(thread.full)}`, "info");
529
+ options.onChange?.();
494
530
  };
495
531
 
496
532
  const clear = () => {
@@ -503,6 +539,7 @@ export async function openBtwModal(
503
539
  modal.clearComposer();
504
540
  modal.setNotice("");
505
541
  modal.setText("");
542
+ options.onChange?.();
506
543
  };
507
544
 
508
545
  const retry = () => {
@@ -530,25 +567,6 @@ export async function openBtwModal(
530
567
  }
531
568
  };
532
569
 
533
- const insert = async (all: boolean) => {
534
- const text = all ? transcript() : (thread.turns.at(-1)?.answer ?? "");
535
- if (!text.trim()) {
536
- modal.setNotice("Nothing to insert yet.", "warning");
537
- return;
538
- }
539
- if (!canBroInsertIntoEditor(ctx)) {
540
- const result = await insertBroDesktopText(ctx, text);
541
- modal.setNotice(result === "inserted" ? "Inserted into the main editor. Review it before sending." : result === "not_empty" ? "Main editor has a draft or attachment. Clear it first, then insert again." : "Could not confirm insertion. Check the main editor before trying again.", result === "inserted" ? "success" : result === "not_empty" ? "warning" : "error");
542
- return;
543
- }
544
- if (ctx.ui.getEditorText().trim()) {
545
- modal.setNotice("Main editor has a draft. Edit or clear it first, then insert again.", "warning");
546
- return;
547
- }
548
- ctx.ui.setEditorText(text);
549
- modal.setNotice(all ? "Inserted the full thread into the main editor." : "Inserted the latest answer into the main editor.", "success");
550
- };
551
-
552
570
  function submit(value: string): void {
553
571
  const action = parseBtwComposerCommand(value);
554
572
  if (action.kind === "clear") {
@@ -566,14 +584,14 @@ export async function openBtwModal(
566
584
  void copyOut(action.all);
567
585
  return;
568
586
  }
569
- if (action.kind === "insert") {
587
+ if (action.kind === "removed") {
570
588
  modal.clearComposer();
571
- void insert(action.all);
589
+ modal.setNotice(`${action.command} was removed. Use /copy or /copy-all, then paste where you want it.`, "warning");
572
590
  return;
573
591
  }
574
- if (action.kind === "removed") {
592
+ if (action.kind === "help") {
575
593
  modal.clearComposer();
576
- modal.setNotice(`${action.command} was removed. Edit or clear the main editor draft, then use /insert or /insert-all.`);
594
+ modal.setNotice("Commands: /mode, /copy, /copy-all, /clear, /retry, /help. Esc closes; completed turns stay private.");
577
595
  return;
578
596
  }
579
597
  if (action.kind === "retry") {
@@ -71,18 +71,6 @@ export function stripElevateFence(value: string): string {
71
71
  return fence ? fence[1]!.trim() : raw;
72
72
  }
73
73
 
74
- /**
75
- * The one rule that protects unsent work: insertion may replace the editor draft Elevate was
76
- * opened on, and may fill an empty editor, but must never overwrite an unrelated draft.
77
- */
78
- export function elevateInsertAllowed(
79
- elevatingEditorDraft: boolean,
80
- initialEditor: string,
81
- currentEditor: string,
82
- ): boolean {
83
- return elevatingEditorDraft ? currentEditor === initialEditor : !currentEditor.trim();
84
- }
85
-
86
74
  /** Deliberately strict: invalid model output must not create an unchecked selection. */
87
75
  export function parseElevateDiscovery(response: string): ElevateDiscovery {
88
76
  // Take the only discovery payload in the reply. Choosing between several would mean guessing
package/src/elevate.ts CHANGED
@@ -4,12 +4,12 @@ import { Editor, Markdown, matchesKey, wrapTextWithAnsi, type EditorTheme, type
4
4
  import { runBackendText } from "./backend.ts";
5
5
  import {
6
6
  buildElevateDiscoveryPrompt, buildElevateUpgradePrompt, parseElevateDiscovery,
7
- selectedFindings, stripElevateFence, elevateInsertAllowed, captureElevateContext, isElevateContextOverflow,
7
+ selectedFindings, stripElevateFence, captureElevateContext, isElevateContextOverflow,
8
8
  reduceElevateContext, elevateDisplayText, type ElevateContextMode, type ElevateDiscovery, type ElevateInput,
9
9
  } from "./elevate-engine.ts";
10
10
  import { BRO_OVERLAY, broOverlayArea, buttonLabels, delegateMouse, formatNotice, modalHeight, openBroOverlay, renderFrame, Scroller, wrapButtons, type Area, type Theme, type TuiLike } from "./modal-kit.ts";
11
11
  import { readPreferences, readSettings, selectionForCapability, selectionLabel } from "./settings.ts";
12
- import { canBroInsertIntoEditor, insertBroDesktopText, type BroMouseEvent, type BroMouseResult } from "./ui-capabilities.ts";
12
+ import { type BroMouseEvent, type BroMouseResult } from "./ui-capabilities.ts";
13
13
  import { errorMessage } from "./util.ts";
14
14
 
15
15
  type Stage = "compose" | "discovering" | "review" | "upgrading" | "ready" | "failed";
@@ -65,7 +65,6 @@ export class ElevateModal implements Focusable {
65
65
  private readonly onClose: () => void,
66
66
  private readonly onDiscover: (objective: string) => void,
67
67
  private readonly onUpgrade: (indexes: ReadonlySet<number>) => void,
68
- private readonly onInsert: (text: string) => void,
69
68
  private readonly onRetry: () => void,
70
69
  private readonly onDispose: () => void,
71
70
  private readonly onContextChange: (mode: ElevateContextMode) => void = () => {},
@@ -169,7 +168,7 @@ export class ElevateModal implements Focusable {
169
168
  // the checklist itself, which is the part the user acts on.
170
169
  text = this.discovery.assessment;
171
170
  } else if (this.stage === "upgrading") text = "## Upgrading your request\n\nPreserving your outcome and constraints. Incorporating only the ideas you approved…";
172
- else if (this.stage === "ready") text = `## Revised request\n\n${this.revised}\n\n*Review before inserting. Nothing has been submitted to Pi.*`;
171
+ else if (this.stage === "ready") text = `## Revised request\n\n${this.revised}\n\n*Copy and paste where you want it. Nothing has been submitted to Pi.*`;
173
172
  else if (this.stage === "failed") text = "## Elevate stopped\n\nYour original request has not changed. Retry, or close this window.";
174
173
  this.markdown.setText(text);
175
174
  this.tui.requestRender();
@@ -211,7 +210,6 @@ export class ElevateModal implements Focusable {
211
210
  ];
212
211
  }
213
212
  if (this.stage === "ready") return [
214
- { label: "Insert into editor", short: "Insert", run: () => this.onInsert(this.revised) },
215
213
  { label: "Copy", short: "Copy", run: () => void this.copy(this.revised, "Copied revised request.") },
216
214
  contextButton,
217
215
  // Back to the findings with the approvals intact, so a rewrite can be reconsidered without
@@ -455,13 +453,10 @@ export class ElevateModal implements Focusable {
455
453
  export async function openElevateModal(ctx: ExtensionCommandContext, request = ""): Promise<void> {
456
454
  const initialEditor = ctx.ui.getEditorText();
457
455
  const initialObjective = request.trim() || initialEditor.trim();
458
- // Whether the editor draft is the thing being elevated. Only then may insertion replace it.
459
- const elevatingEditorDraft = !request.trim() && !!initialEditor.trim();
460
456
  const branch = ctx.sessionManager.getBranch();
461
457
  await openBroOverlay<void>(ctx, (tui, theme, _keybindings, done) => {
462
458
  let closed = false;
463
459
  let controller: AbortController | undefined;
464
- let inserting = false;
465
460
  let original = initialObjective;
466
461
  let contextMessages = captureElevateContext(branch, "messages");
467
462
  let reduced = false;
@@ -477,7 +472,7 @@ export async function openElevateModal(ctx: ExtensionCommandContext, request = "
477
472
  done(undefined);
478
473
  };
479
474
 
480
- const modal = new ElevateModal(tui, theme, close, discover, upgrade, insert, retryStage, close, (mode) => {
475
+ const modal = new ElevateModal(tui, theme, close, discover, upgrade, retryStage, close, (mode) => {
481
476
  contextMessages = captureElevateContext(branch, mode);
482
477
  reduced = false;
483
478
  reduceOnRetry = false;
@@ -562,35 +557,6 @@ export async function openElevateModal(ctx: ExtensionCommandContext, request = "
562
557
  else void discover(original);
563
558
  }
564
559
 
565
- async function insert(text: string): Promise<void> {
566
- if (closed || inserting) return;
567
- if (canBroInsertIntoEditor(ctx)) {
568
- const current = ctx.ui.getEditorText();
569
- if (!elevateInsertAllowed(elevatingEditorDraft, initialEditor, current)) {
570
- modal.setNotice(elevatingEditorDraft
571
- ? "Main editor changed. Copy instead; your draft was not overwritten."
572
- : "Main editor has a draft. Clear it first, or press Copy instead.");
573
- return;
574
- }
575
- ctx.ui.setEditorText(text);
576
- close();
577
- ctx.ui.notify("Elevate inserted the revised request. Review it before submitting.", "info");
578
- return;
579
- }
580
- // Desktop has an atomic empty-editor insertion API. Never overwrite a draft there.
581
- inserting = true;
582
- let result: Awaited<ReturnType<typeof insertBroDesktopText>>;
583
- try { result = await insertBroDesktopText(ctx, text); }
584
- finally { inserting = false; }
585
- if (closed) return;
586
- modal.setNotice(result === "inserted"
587
- ? "Inserted into the main editor. Review it before submitting."
588
- : result === "not_empty"
589
- ? "Desktop editor has a draft; copy the revised request instead."
590
- : "Desktop cannot insert here; copy the revised request instead.");
591
- if (result === "inserted") close();
592
- }
593
-
594
560
  modal.setCompose(initialObjective);
595
561
  return modal;
596
562
  }, { mouse: true });
@@ -382,6 +382,15 @@ export function helpText(settings?: BroSettings, settingsError?: string, prefere
382
382
 
383
383
  Quick reference. Full user guide: https://github.com/tranhoangnguyen03/pi-bro/blob/main/docs/user-guide.md
384
384
 
385
+ ## Pick by need
386
+
387
+ - **Understand what already exists:** Simplify and Show; Architecture for this repository.
388
+ - **Explore what could exist:** BTW for side questions; Grill Me for decisions.
389
+ - **Get advice on existing work:** Guided Review; Overthink for automatic second looks; agent-facing Advisor.
390
+ - **Guide the agent:** Elevate for assignments; Remember Me for approved context (about_user); Advisor Steering for priorities.
391
+
392
+ These are needs, not modes. Copied text does not enter Pi until you paste and submit it.
393
+
385
394
  ## Explain and show
386
395
 
387
396
  - \`/bro\` — open Simplify and explain the latest completed assistant reply
@@ -412,17 +421,16 @@ Quick reference. Full user guide: https://github.com/tranhoangnguyen03/pi-bro/bl
412
421
 
413
422
  ## Grill Me (experimental)
414
423
 
415
- - \`/bro grill-me [topic]\` — private decision interview. Use /consolidate, /insert-last-message or /help. Full-access risk: docs/grill-me.md.
424
+ - \`/bro grill-me [topic]\` — private decision interview. Use /consolidate, /copy or /help. Full-access risk: docs/grill-me.md.
416
425
 
417
426
  ## Overthink
418
427
 
419
- - \`/bro overthink\` — view private automatic second-look notes without running a model. Ctrl+R forces retry; Ctrl+E edits this session's questions; ? shows help; Ctrl+C copies. Uses the active Pi model and thinking level only. No separate backend settings.
420
- - \`/bro config\` → Features → Overthink provides automatic on/off and editable global starting questions; session edits stay with their Pi session. See docs/overthink.md.
428
+ - \`/bro overthink\` — view private automatic second-look notes without a model call. Ctrl+R retries; Ctrl+E edits session questions; Ctrl+C copies. Uses the active Pi model. Turn off or edit defaults in \`/bro config\` → Features → Overthink. See docs/overthink.md.
421
429
 
422
430
  ## Side conversation
423
431
 
424
432
  - \`/bro btw [question]\` — open a side conversation seeded with recent main-session context. It starts conversation-only; reopening keeps the thread and its mode.
425
- - Enter asks; empty Enter or \`/retry\` re-asks. \`/mode\` toggles conversation-only/full workspace access, retaining the thread. \`/copy\`, \`/copy-all\` copy; \`/insert\`, \`/insert-all\` fill an empty main editor without submitting. \`/clear\` resets; Esc closes.
433
+ - Enter asks; empty Enter or \`/retry\` re-asks. \`/mode\` toggles conversation-only/full workspace access, retaining the thread. \`/copy\`, \`/copy-all\` copy. \`/clear\` resets; \`/help\` shows controls; Esc closes.
426
434
 
427
435
  ## Advisor
428
436
 
@@ -466,7 +474,7 @@ The mode decides how much of the source to keep; your preferences decide who it'
466
474
 
467
475
  ## Privacy
468
476
 
469
- Bro sends the captured source (or, for the advisor, the executor's instructions, tools, and conversation) to the selected backend and its model provider, which may retain it under their own policies. Your preferences go with every explain, show, btw, and Guided Review request. Guided Review sends PR data/diff and relevant private questions; records/source remain locally under getAgentDir()/bro-reviews. Copy finding goes to the system clipboard, not GitHub. Nothing is added to Pi's conversation unless you insert it, except advisor answers, which return to the agent as tool results. Access controls differ by backend; see the user guide.`;
477
+ Bro sends the captured source (or, for the advisor, the executor's instructions, tools, and conversation) to the selected backend and its model provider, which may retain it under their own policies. Your preferences go with every explain, show, btw, and Guided Review request. Guided Review sends PR data/diff and relevant private questions; records/source remain locally under getAgentDir()/bro-reviews. Copy finding goes to the system clipboard, not GitHub. Nothing is added to Pi's conversation unless you paste and send it, except advisor answers and approved memories read through about_user, which return to the agent as tool results. Access controls differ by backend; see the user guide.`;
470
478
  }
471
479
 
472
480
  // The overlay framing pattern is adapted from pi-btw (MIT); see THIRD_PARTY_NOTICES.md.
@@ -24,7 +24,7 @@ export function parseGrillArguments(raw: string): { topic: string; depth: GrillD
24
24
  }
25
25
 
26
26
  export const GRILL_COMMANDS = [
27
- "/consolidate", "/insert-last-message", "/depth light", "/depth balanced",
27
+ "/consolidate", "/copy", "/depth light", "/depth balanced",
28
28
  "/depth exhaustive", "/retry", "/new ", "/access inspect", "/access full", "/help",
29
29
  ] as const;
30
30
 
@@ -36,7 +36,7 @@ export type GrillAction =
36
36
  | { kind: "message"; text: string }
37
37
  | { kind: "depth"; value: GrillDepth }
38
38
  | { kind: "access"; value: "inspect" | "full" }
39
- | { kind: "consolidate" | "insert" | "help" | "retry" | "empty" }
39
+ | { kind: "consolidate" | "copy" | "help" | "retry" | "empty" }
40
40
  | { kind: "new"; topic: string }
41
41
  | { kind: "invalid"; message: string };
42
42
 
@@ -47,7 +47,8 @@ export function parseGrillCommand(value: string): GrillAction {
47
47
  if (text === "/help") return { kind: "help" };
48
48
  if (text.startsWith("/new ") && text.slice(5).trim()) return { kind: "new", topic: text.slice(5).trim() };
49
49
  if (text === "/retry") return { kind: "retry" };
50
- if (text === "/insert-last-message") return { kind: "insert" };
50
+ if (text === "/copy") return { kind: "copy" };
51
+ if (text === "/insert-last-message") return { kind: "invalid", message: "/insert-last-message was removed. Use /copy, then paste the result where you want it." };
51
52
  if (text.startsWith("/depth")) {
52
53
  const tokens = text.split(/\s+/);
53
54
  return tokens.length === 2 && GRILL_DEPTHS.some((v) => v === tokens[1])
package/src/grill.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { matchesKey } from "@earendil-works/pi-tui";
2
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { copyToClipboard, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
3
  import { execute as executeBackend } from "./backend.ts";
4
4
  import { BtwModal, BTW_CONTEXT_MAX, BTW_CONTEXT_TURNS, formatBtwTranscript } from "./btw.ts";
5
5
  import {
@@ -9,7 +9,6 @@ import {
9
9
  import { readPreferences, readSettings, selectionForCapability, selectionLabel, capabilityBackend } from "./settings.ts";
10
10
  import { captureShowTranscript } from "./show.ts";
11
11
  import { openBroOverlay } from "./modal-kit.ts";
12
- import { canBroInsertIntoEditor, insertBroDesktopText } from "./ui-capabilities.ts";
13
12
  import { errorMessage } from "./util.ts";
14
13
 
15
14
  /**
@@ -20,7 +19,7 @@ import { errorMessage } from "./util.ts";
20
19
  export async function openGrillModal(
21
20
  ctx: ExtensionCommandContext,
22
21
  thread: GrillThread,
23
- options: { start?: boolean } = {},
22
+ options: { start?: boolean; onChange?: () => void; copy?: (text: string) => Promise<void> } = {},
24
23
  ): Promise<void> {
25
24
  const openingBackend = capabilityBackend(await readSettings(), "btw");
26
25
  await openBroOverlay<void>(
@@ -35,7 +34,7 @@ export async function openGrillModal(
35
34
  let activeBackend = openingBackend;
36
35
  let showingHelp = false;
37
36
  let confirmation: "full" | string | undefined;
38
- const help = "## Commands\n\n- /consolidate — draft a decision brief; keep talking afterward\n- /insert-last-message — insert the latest Bro reply into an empty Pi editor, without sending\n- /depth light|balanced|exhaustive — change depth\n- /retry — retry a failed operation or regenerate the latest reply\n- /new <topic> — start over (confirmation required)\n- /access inspect|full — choose access (full requires confirmation)\n- /help — show this list\n\nAnswer with a letter or your own words. Esc returns to the interview. Type / and use Tab to complete a command.";
37
+ const help = "## Commands\n\n- /consolidate — draft a decision brief; keep talking afterward\n- /copy — copy the latest Bro reply or consolidated brief to the clipboard\n- /depth light|balanced|exhaustive — change depth\n- /retry — retry a failed operation or regenerate the latest reply\n- /new <topic> — start over (confirmation required)\n- /access inspect|full — choose access (full requires confirmation)\n- /help — show this list\n\nAnswer with a letter or your own words. Esc returns to the interview. Type / and use Tab to complete a command.";
39
38
 
40
39
  const transcript = () => {
41
40
  const conversation = formatBtwTranscript(pendingTurn ? [...thread.turns, pendingTurn] : thread.turns);
@@ -55,12 +54,14 @@ export async function openGrillModal(
55
54
  if (closed) return;
56
55
  closed = true;
57
56
  saveDraft();
57
+ if (!controller) options.onChange?.();
58
58
  controller?.abort();
59
59
  done(undefined);
60
60
  };
61
61
  const modal = new BtwModal(tui, theme, close, submit, () => {
62
62
  closed = true;
63
63
  saveDraft();
64
+ if (!controller) options.onChange?.();
64
65
  controller?.abort();
65
66
  }, {
66
67
  title: "Bro · grill-me",
@@ -153,7 +154,7 @@ export async function openGrillModal(
153
154
  pendingTurn = undefined;
154
155
  pendingReply = undefined;
155
156
  if (controller === attempt) controller = undefined;
156
- if (!closed) { modal.setRunning(false); modal.setText(transcript()); }
157
+ if (!closed) { modal.setRunning(false); modal.setText(transcript()); options.onChange?.(); }
157
158
  }
158
159
  };
159
160
 
@@ -191,28 +192,25 @@ export async function openGrillModal(
191
192
  if (replace) thread.turns.pop();
192
193
  thread.turns.push({ question: "/consolidate", answer: outcome.text });
193
194
  delete thread.retry;
194
- modal.setNotice("Brief ready. Keep talking or /insert-last-message.", "success");
195
+ modal.setNotice("Brief ready. Keep talking or use /copy.", "success");
195
196
  } catch (error) {
196
197
  if (!closed && !attempt.signal.aborted) modal.setNotice(errorMessage(error), "error");
197
198
  } finally {
198
199
  pendingSummary = undefined;
199
200
  if (controller === attempt) controller = undefined;
200
- if (!closed) { modal.setRunning(false); modal.setText(transcript()); }
201
+ if (!closed) { modal.setRunning(false); modal.setText(transcript()); options.onChange?.(); }
201
202
  }
202
203
  };
203
204
 
204
- const insert = async () => {
205
+ const copy = async () => {
205
206
  const text = thread.turns.at(-1)?.answer || "";
206
- if (!thread.turns.length || !text.trim()) { modal.setNotice("Nothing to insert yet.", "warning"); return; }
207
- if (!canBroInsertIntoEditor(ctx)) {
208
- const result = await insertBroDesktopText(ctx, text);
209
- modal.setNotice(result === "inserted" ? "Inserted into main editor without sending." : result === "not_empty"
210
- ? "Main editor is not empty; clear it first." : "Insertion could not be confirmed.", result === "inserted" ? "success" : "warning");
211
- return;
207
+ if (!text.trim()) { modal.setNotice("Nothing to copy yet.", "warning"); return; }
208
+ try {
209
+ await (options.copy ?? copyToClipboard)(text);
210
+ if (!closed) modal.setNotice("Copied the latest reply to the clipboard.", "success");
211
+ } catch (error) {
212
+ if (!closed) modal.setNotice(`Copy failed: ${errorMessage(error)}`, "error");
212
213
  }
213
- if (ctx.ui.getEditorText().trim()) { modal.setNotice("Main editor has a draft. Clear it first.", "warning"); return; }
214
- ctx.ui.setEditorText(text);
215
- modal.setNotice("Inserted into main editor without sending.", "success");
216
214
  };
217
215
  const clear = (topic: string) => {
218
216
  thread.topic = topic;
@@ -225,6 +223,7 @@ export async function openGrillModal(
225
223
  delete thread.draft;
226
224
  modal.clearComposer();
227
225
  modal.setText(transcript());
226
+ options.onChange?.();
228
227
  void runTurn(topic);
229
228
  };
230
229
 
@@ -241,6 +240,7 @@ export async function openGrillModal(
241
240
  thread.fullAccess = true;
242
241
  refreshHeader();
243
242
  modal.setNotice(permissionNotice(activeBackend), "warning");
243
+ options.onChange?.();
244
244
  } else clear(pending.slice(4));
245
245
  return;
246
246
  }
@@ -252,6 +252,7 @@ export async function openGrillModal(
252
252
  refreshHeader();
253
253
  modal.clearComposer();
254
254
  modal.setNotice(`Depth: ${thread.depth}. Applies to the next question.`);
255
+ options.onChange?.();
255
256
  return;
256
257
  }
257
258
  if (action.kind === "access") {
@@ -263,6 +264,7 @@ export async function openGrillModal(
263
264
  thread.fullAccess = action.value === "full";
264
265
  refreshHeader();
265
266
  modal.setNotice(permissionNotice(activeBackend));
267
+ options.onChange?.();
266
268
  }
267
269
  return;
268
270
  }
@@ -275,7 +277,7 @@ export async function openGrillModal(
275
277
  } else clear(action.topic);
276
278
  return;
277
279
  }
278
- if (action.kind === "insert") { modal.clearComposer(); void insert(); return; }
280
+ if (action.kind === "copy") { modal.clearComposer(); void copy(); return; }
279
281
  if (action.kind === "consolidate") { modal.clearComposer(); void consolidate(); return; }
280
282
  if (action.kind === "retry") {
281
283
  modal.clearComposer();
@@ -0,0 +1,91 @@
1
+ /** Private per-session Bro state. Custom entries are not sent to the main model or advisor. */
2
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { BtwThread } from "./btw.ts";
4
+ import type { GrillThread } from "./grill-engine.ts";
5
+ import type { ModalResult } from "./explain-modal.ts";
6
+ import type { SimplifyState } from "./simplify-ui.ts";
7
+ import { isRecord } from "./util.ts";
8
+
9
+ export const BTW_SESSION_ENTRY = "bro-btw-thread";
10
+ export const GRILL_SESSION_ENTRY = "bro-grill-thread";
11
+ export const SIMPLIFY_SESSION_ENTRY = "bro-simplify-state";
12
+ export const LAST_RESULT_SESSION_ENTRY = "bro-last-result";
13
+
14
+ /** Last on-branch snapshot per feature, used to avoid duplicate append-only writes.
15
+ * A tree move rebuilds these signatures from its own branch, not the old one.
16
+ */
17
+ export function privateSessionEntrySnapshots(branch: readonly SessionEntry[]): Map<string, string> {
18
+ const types = new Set<string>([
19
+ BTW_SESSION_ENTRY, GRILL_SESSION_ENTRY, SIMPLIFY_SESSION_ENTRY, LAST_RESULT_SESSION_ENTRY,
20
+ ]);
21
+ const saved = new Map<string, string>();
22
+ for (const entry of branch) {
23
+ if (entry.type === "custom" && types.has(entry.customType) && isRecord(entry.data)) {
24
+ saved.set(entry.customType, JSON.stringify(entry.data));
25
+ }
26
+ }
27
+ return saved;
28
+ }
29
+
30
+
31
+ export type PrivateBroSessionState = {
32
+ btw?: BtwThread;
33
+ grill?: GrillThread;
34
+ simplify: SimplifyState;
35
+ lastResult?: ModalResult;
36
+ lastShowSteering?: string;
37
+ };
38
+
39
+ const textTurns = (value: unknown): boolean =>
40
+ Array.isArray(value) && value.every(turn =>
41
+ isRecord(turn) && typeof turn.question === "string" && typeof turn.answer === "string");
42
+
43
+ function btwThread(value: unknown): BtwThread | undefined {
44
+ if (!isRecord(value) || !textTurns(value.turns) || typeof value.full !== "boolean") return undefined;
45
+ if (value.backend !== undefined && typeof value.backend !== "string") return undefined;
46
+ return value as unknown as BtwThread;
47
+ }
48
+
49
+ function grillThread(value: unknown): GrillThread | undefined {
50
+ if (!isRecord(value) || typeof value.topic !== "string" || !textTurns(value.turns) ||
51
+ !["light", "balanced", "exhaustive"].includes(String(value.depth)) ||
52
+ typeof value.fullAccess !== "boolean") return undefined;
53
+ return value as unknown as GrillThread;
54
+ }
55
+
56
+ function modalResult(value: unknown): ModalResult | undefined {
57
+ if (!isRecord(value) || typeof value.text !== "string") return undefined;
58
+ if (value.source !== undefined && (!isRecord(value.source) || typeof value.source.text !== "string")) return undefined;
59
+ return value as unknown as ModalResult;
60
+ }
61
+
62
+ function simplifyState(value: unknown): SimplifyState {
63
+ if (!isRecord(value)) return {};
64
+ const result = modalResult(value.result);
65
+ if (value.result !== undefined && !result?.source) return {};
66
+ return {
67
+ ...(result ? { result: result as SimplifyState["result"] } : {}),
68
+ ...(value.view === "result" || value.view === "help" || value.view === "empty" ? { view: value.view } : {}),
69
+ ...(typeof value.draft === "string" ? { draft: value.draft } : {}),
70
+ ...(typeof value.error === "string" ? { error: value.error } : {}),
71
+ };
72
+ }
73
+
74
+ /** Last matching entry on the active branch wins. A cleared state cannot resurrect. */
75
+ export function restorePrivateBroState(branch: readonly SessionEntry[]): PrivateBroSessionState {
76
+ const restored: PrivateBroSessionState = { simplify: {} };
77
+ for (const entry of branch) {
78
+ if (entry.type !== "custom" || !isRecord(entry.data)) continue;
79
+ const value = entry.data;
80
+ switch (entry.customType) {
81
+ case BTW_SESSION_ENTRY: restored.btw = btwThread(value.thread); break;
82
+ case GRILL_SESSION_ENTRY: restored.grill = grillThread(value.thread); break;
83
+ case SIMPLIFY_SESSION_ENTRY: restored.simplify = simplifyState(value.state); break;
84
+ case LAST_RESULT_SESSION_ENTRY:
85
+ restored.lastResult = modalResult(value.result);
86
+ restored.lastShowSteering = typeof value.steering === "string" ? value.steering : undefined;
87
+ break;
88
+ }
89
+ }
90
+ return restored;
91
+ }
@@ -22,18 +22,6 @@ export function broModalRows(tui: unknown, terminalRows: number | undefined): nu
22
22
  return typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0 ? Math.floor(candidate) : 30;
23
23
  }
24
24
 
25
- export async function insertBroDesktopText(ctx: UiContext, text: string): Promise<"inserted" | "not_empty" | "unavailable"> {
26
- if (!hasBroCustomUi(ctx) || ctx.mode !== "rpc") return "unavailable";
27
- const ui = ctx.ui as DesktopUi & { insertEditorTextIfEmpty?: (text: string) => Promise<"inserted" | "not_empty" | "unavailable"> };
28
- try {
29
- const caps = ui.getDesktopUiCapabilities?.() as { atomicEditorInsert?: boolean } | undefined;
30
- return caps?.atomicEditorInsert === true && ui.insertEditorTextIfEmpty ? await ui.insertEditorTextIfEmpty(text) : "unavailable";
31
- } catch { return "unavailable"; }
32
- }
33
-
34
- /** Only terminal mode uses synchronous insertion; Desktop uses insertBroDesktopText instead. */
35
- export function canBroInsertIntoEditor(ctx: UiContext): boolean { return ctx.mode === "tui"; }
36
-
37
25
  /** Any raw SGR mouse report; regular-mode reporting delivers these to handleInput. */
38
26
  export const SGR_MOUSE = /^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/;
39
27