pi-bro 0.37.1 → 0.38.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/CHANGELOG.md +18 -0
- package/README.md +6 -8
- package/docs/examples.md +1 -1
- package/docs/feature-map.md +2 -3
- package/docs/features/explain.md +16 -20
- package/docs/features/show.md +9 -15
- package/docs/getting-started.md +4 -4
- package/docs/piG-agent-shell-qualification.md +1 -1
- package/docs/reference/commands.md +14 -29
- package/docs/reference/data-and-permissions.md +4 -4
- package/docs/reference/settings.md +3 -3
- package/docs/reference/troubleshooting.md +1 -1
- package/docs/user-guide.md +2 -2
- package/package.json +10 -1
- package/src/advisor.ts +1 -4
- package/src/architecture.ts +1 -1
- package/src/backend.ts +24 -1955
- package/src/backends/agy.ts +304 -0
- package/src/backends/claude.ts +169 -0
- package/src/backends/cli-process.ts +247 -0
- package/src/backends/codex.ts +182 -0
- package/src/backends/contract.ts +56 -0
- package/src/backends/grok.ts +204 -0
- package/src/backends/muse.ts +173 -0
- package/src/backends/pi.ts +493 -0
- package/src/bro.ts +47 -185
- package/src/btw.ts +12 -202
- package/src/cli-auth.ts +176 -0
- package/src/composer-modal.ts +197 -0
- package/src/explain-modal.ts +24 -75
- package/src/grill.ts +3 -2
- package/src/remember.ts +3 -2
- package/src/session-state.ts +46 -28
- package/src/simplify-engine.ts +50 -24
- package/src/simplify-ui.ts +165 -126
- package/src/sources.ts +3 -3
package/src/cli-auth.ts
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { processStartMessage, startCliAttempt } from "./backends/cli-process.ts";
|
|
5
|
+
import type { BackendOutcome } from "./backends/contract.ts";
|
|
6
|
+
|
|
1
7
|
/** The shell chooses CLI account profiles. Bro only enforces the choice in each child. */
|
|
2
8
|
export type CliAuthBackend = "claude" | "codex";
|
|
3
9
|
export type CliChildAuth = { env: NodeJS.ProcessEnv; subscription: boolean };
|
|
@@ -83,3 +89,173 @@ export function codexSubscriptionRouteProblem(config: unknown): string | undefin
|
|
|
83
89
|
}
|
|
84
90
|
return undefined;
|
|
85
91
|
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Ask the official Codex app-server for the effective provider configuration.
|
|
95
|
+
* This is the same Codex CLI, CODEX_HOME, and working directory used for exec.
|
|
96
|
+
* A login status alone cannot detect custom provider env_key API billing.
|
|
97
|
+
*
|
|
98
|
+
* Inspection never makes a model request. Missing, unreadable or unsupported
|
|
99
|
+
* app-server/config/read support fails closed when subscription is explicit.
|
|
100
|
+
*/
|
|
101
|
+
// Codex 0.165.0 app-server starts an online catalog refresh on boot,
|
|
102
|
+
// even if the only client method is config/read. Supply a disposable static
|
|
103
|
+
// catalog for this *inspection process only* so the refresh worker cannot
|
|
104
|
+
// contact a configured provider. The override does NOT select a provider,
|
|
105
|
+
// change account credentials, or go into the real codex exec arguments.
|
|
106
|
+
// The provider is still read from Codex's effective config for the same cwd.
|
|
107
|
+
const CODEX_INSPECTION_CATALOG = {
|
|
108
|
+
models: [{
|
|
109
|
+
slug: "bro-config-inspection-only",
|
|
110
|
+
display_name: "Bro configuration inspection only",
|
|
111
|
+
description: "Local offline catalog; never used for inference",
|
|
112
|
+
base_instructions: "Local configuration inspection only; never used for inference.",
|
|
113
|
+
default_reasoning_level: "medium",
|
|
114
|
+
supported_reasoning_levels: [{ effort: "medium", description: "medium" }],
|
|
115
|
+
shell_type: "shell_command",
|
|
116
|
+
visibility: "none",
|
|
117
|
+
supported_in_api: true,
|
|
118
|
+
priority: 0,
|
|
119
|
+
support_verbosity: false,
|
|
120
|
+
default_verbosity: null,
|
|
121
|
+
apply_patch_tool_type: null,
|
|
122
|
+
truncation_policy: { mode: "bytes", limit: 10_000 },
|
|
123
|
+
experimental_supported_tools: [],
|
|
124
|
+
}],
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
async function inspectCodexSubscriptionRoute(
|
|
128
|
+
env: NodeJS.ProcessEnv, cwd: string | undefined, signal: AbortSignal,
|
|
129
|
+
deadlineMs: number, killEscalationMs: number,
|
|
130
|
+
): Promise<BackendOutcome | undefined> {
|
|
131
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
132
|
+
const probeDir = await mkdtemp(join(tmpdir(), "pi-bro-codex-inspect-"));
|
|
133
|
+
try {
|
|
134
|
+
const catalogPath = join(probeDir, "catalog.json");
|
|
135
|
+
await writeFile(catalogPath, JSON.stringify(CODEX_INSPECTION_CATALOG), { mode: 0o600 });
|
|
136
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
137
|
+
const { child, attempt, diagnostics } = startCliAttempt(
|
|
138
|
+
"codex", ["-c", `model_catalog_json=${JSON.stringify(catalogPath)}`, "app-server"],
|
|
139
|
+
{ env, cwd, stdio: ["pipe", "pipe", "pipe"] },
|
|
140
|
+
signal, Math.min(deadlineMs, 15_000), killEscalationMs,
|
|
141
|
+
);
|
|
142
|
+
let buffer = "";
|
|
143
|
+
let decided = false;
|
|
144
|
+
let finish: (problem: string | undefined) => void = () => {};
|
|
145
|
+
const decision = new Promise<string | undefined>(resolve => { finish = resolve; });
|
|
146
|
+
const settle = (problem: string | undefined) => {
|
|
147
|
+
if (decided) return;
|
|
148
|
+
decided = true;
|
|
149
|
+
finish(problem);
|
|
150
|
+
};
|
|
151
|
+
const send = (value: object) => {
|
|
152
|
+
if (decided || attempt.causeOf()) return;
|
|
153
|
+
try { child.stdin?.write(JSON.stringify(value) + "\n"); }
|
|
154
|
+
catch { settle("Codex app-server could not accept the configuration query"); }
|
|
155
|
+
};
|
|
156
|
+
// An app-server may close its input pipe while its buffered response is
|
|
157
|
+
// still readable. The close race below decides whether the query succeeded.
|
|
158
|
+
child.stdin?.on("error", () => {});
|
|
159
|
+
child.stdout?.setEncoding("utf8");
|
|
160
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
161
|
+
if (decided || attempt.causeOf()) return;
|
|
162
|
+
buffer += chunk;
|
|
163
|
+
if (buffer.length > 2_000_000) { settle("Codex returned an oversized configuration response"); return; }
|
|
164
|
+
for (;;) {
|
|
165
|
+
const index = buffer.indexOf("\n");
|
|
166
|
+
if (index < 0) break;
|
|
167
|
+
const line = buffer.slice(0, index);
|
|
168
|
+
buffer = buffer.slice(index + 1);
|
|
169
|
+
if (!line.trim()) continue;
|
|
170
|
+
let message: Record<string, unknown>;
|
|
171
|
+
try {
|
|
172
|
+
message = JSON.parse(line) as Record<string, unknown>;
|
|
173
|
+
} catch {
|
|
174
|
+
settle("Codex app-server returned invalid JSON");
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (message.id === 0) {
|
|
178
|
+
if (!message.result || message.error) {
|
|
179
|
+
settle("Codex app-server initialization failed");
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
send({ method: "initialized", params: {} });
|
|
183
|
+
send({ method: "config/read", id: 1, params: { includeLayers: false, ...(cwd ? { cwd } : {}) } });
|
|
184
|
+
} else if (message.id === 1) {
|
|
185
|
+
if (message.error || !message.result || typeof message.result !== "object") {
|
|
186
|
+
settle("Codex app-server did not support config/read for this account/profile");
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const config = (message.result as { config?: unknown }).config;
|
|
190
|
+
settle(codexSubscriptionRouteProblem(config));
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
send({ method: "initialize", id: 0,
|
|
196
|
+
params: { clientInfo: { name: "pi_bro", title: "Pi Bro", version: "0.36.1" } } });
|
|
197
|
+
const result = await Promise.race([
|
|
198
|
+
decision.then(problem => ({ kind: "decision" as const, problem })),
|
|
199
|
+
attempt.closed.then(() => ({ kind: "closed" as const })),
|
|
200
|
+
]);
|
|
201
|
+
// The probe is not a long-running provider connection.
|
|
202
|
+
if (!attempt.causeOf()) attempt.stop("protocol");
|
|
203
|
+
await attempt.closed;
|
|
204
|
+
attempt.dispose();
|
|
205
|
+
if (signal.aborted || attempt.causeOf() === "cancelled")
|
|
206
|
+
return { status: "cancelled", message: "Canceled." };
|
|
207
|
+
if (attempt.causeOf() === "timeout")
|
|
208
|
+
return { status: "timeout", message: "Codex effective subscription configuration check timed out." };
|
|
209
|
+
const problem = result.kind === "decision"
|
|
210
|
+
? result.problem
|
|
211
|
+
: diagnostics.processError
|
|
212
|
+
? "Codex app-server could not start"
|
|
213
|
+
: "Codex app-server closed without returning the effective configuration" +
|
|
214
|
+
(diagnostics.stderr.trim() ? ": " + diagnostics.stderr.trim().slice(0, 700) : "");
|
|
215
|
+
return problem
|
|
216
|
+
? { status: "failure", message: "Codex subscription selection is not safe: " + problem +
|
|
217
|
+
". No Codex model execution was started; the inspection uses a temporary local catalog to suppress ordinary model discovery. Use a subscription-compatible CODEX_HOME profile or select inherited/API authentication explicitly." }
|
|
218
|
+
: undefined;
|
|
219
|
+
} finally {
|
|
220
|
+
await rm(probeDir, { recursive: true, force: true });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Only a deliberate subscription choice gets an auth-method preflight.
|
|
225
|
+
// CLI status is not proof of account identity or a paid model call.
|
|
226
|
+
export async function verifyCliSubscription(
|
|
227
|
+
backend: CliAuthBackend,
|
|
228
|
+
env: NodeJS.ProcessEnv,
|
|
229
|
+
signal: AbortSignal,
|
|
230
|
+
killEscalationMs: number,
|
|
231
|
+
deadlineMs: number,
|
|
232
|
+
cwd?: string,
|
|
233
|
+
): Promise<BackendOutcome | undefined> {
|
|
234
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
235
|
+
const label = backend === "claude" ? "Claude Code" : "Codex";
|
|
236
|
+
const args = backend === "claude" ? ["auth", "status"] : ["login", "status"];
|
|
237
|
+
const { child, attempt, diagnostics } = startCliAttempt(backend, args,
|
|
238
|
+
{ env, stdio: ["ignore", "pipe", "pipe"] },
|
|
239
|
+
signal, Math.min(deadlineMs, 15_000), killEscalationMs);
|
|
240
|
+
let stdout = "";
|
|
241
|
+
child.stdout?.on("data", (chunk: Buffer) => {
|
|
242
|
+
stdout = (stdout + chunk.toString()).slice(0, 32_768);
|
|
243
|
+
});
|
|
244
|
+
const { code, exitSignal } = await attempt.closed;
|
|
245
|
+
attempt.dispose();
|
|
246
|
+
if (attempt.causeOf() === "cancelled") return { status: "cancelled", message: "Canceled." };
|
|
247
|
+
if (attempt.causeOf() === "timeout") return { status: "timeout", message: label + " subscription login check timed out." };
|
|
248
|
+
if (diagnostics.processError)
|
|
249
|
+
return { status: "failure", message: processStartMessage(diagnostics.processError as NodeJS.ErrnoException, label) };
|
|
250
|
+
const status = backend === "codex" ? stdout + "\n" + diagnostics.stderr : stdout;
|
|
251
|
+
if (code !== 0 || exitSignal || !isSubscriptionStatus(backend, status)) {
|
|
252
|
+
const command = backend === "claude" ? "claude auth status" : "codex login status";
|
|
253
|
+
const profile = backend === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
|
|
254
|
+
return { status: "failure", message: label +
|
|
255
|
+
" did not confirm subscription login in the selected profile. Run `" + command +
|
|
256
|
+
"` with that " + profile + " and sign in to the intended subscription; Bro will not switch to API billing." };
|
|
257
|
+
}
|
|
258
|
+
return backend === "codex"
|
|
259
|
+
? inspectCodexSubscriptionRoute(env, cwd, signal, deadlineMs, killEscalationMs)
|
|
260
|
+
: undefined;
|
|
261
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Input, Markdown, matchesKey, wrapTextWithAnsi, type Focusable } from "@earendil-works/pi-tui";
|
|
3
|
+
import { BRO_OVERLAY, broOverlayArea, formatNotice, modalHeight, renderFrame, runningHint, Scroller, type Area, type NoticeTone, type Theme, type TuiLike } from "./modal-kit.ts";
|
|
4
|
+
import type { BroMouseEvent, BroMouseResult } from "./ui-capabilities.ts";
|
|
5
|
+
|
|
6
|
+
export class ComposerModal implements Focusable {
|
|
7
|
+
private _focused = false;
|
|
8
|
+
private readonly markdown = new Markdown("", 0, 0, getMarkdownTheme());
|
|
9
|
+
private readonly input = new Input();
|
|
10
|
+
private noticeText = "";
|
|
11
|
+
private noticeTone: NoticeTone = "info";
|
|
12
|
+
private rawArea: Area | undefined;
|
|
13
|
+
// Follows the newest text until the reader scrolls up; scrolling back to the end follows again.
|
|
14
|
+
private readonly scroller = new Scroller(
|
|
15
|
+
() => {
|
|
16
|
+
this.noticeText = "";
|
|
17
|
+
this.tui.requestRender();
|
|
18
|
+
},
|
|
19
|
+
{ followEnd: true },
|
|
20
|
+
);
|
|
21
|
+
private running = false;
|
|
22
|
+
private progressText = "";
|
|
23
|
+
private trailingMode?: { label: string; emphasized: boolean };
|
|
24
|
+
private model = "";
|
|
25
|
+
private customMode = "";
|
|
26
|
+
private disposed = false;
|
|
27
|
+
onInput?: () => void;
|
|
28
|
+
onKey?: (data: string) => boolean;
|
|
29
|
+
private suggestions = "";
|
|
30
|
+
|
|
31
|
+
setSuggestions(text: string): void {
|
|
32
|
+
this.suggestions = text;
|
|
33
|
+
this.tui.requestRender();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get focused(): boolean {
|
|
37
|
+
return this._focused;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
set focused(value: boolean) {
|
|
41
|
+
this._focused = value;
|
|
42
|
+
this.input.focused = value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
constructor(
|
|
46
|
+
private readonly tui: TuiLike,
|
|
47
|
+
private readonly theme: Theme,
|
|
48
|
+
private readonly onClose: () => void,
|
|
49
|
+
private readonly onSubmit: (value: string) => void,
|
|
50
|
+
private readonly onDispose: () => void,
|
|
51
|
+
private readonly appearance: { title?: string; commands?: string; inputLabel?: string; idleHint?: string | (() => string) } = {},
|
|
52
|
+
) {
|
|
53
|
+
this.input.onSubmit = (value) => {
|
|
54
|
+
if (!this.running) this.onSubmit(value);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Keeps the reader's place; the scroller clamps when the text shrinks (e.g. /clear).
|
|
59
|
+
setText(text: string): void {
|
|
60
|
+
this.markdown.setText(text);
|
|
61
|
+
this.tui.requestRender();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Start at the top of a static or single-document view. */
|
|
65
|
+
scrollToStart(): void {
|
|
66
|
+
this.scroller.toStart();
|
|
67
|
+
this.tui.requestRender();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Show the newest text and keep following it while a reply streams. */
|
|
71
|
+
scrollToEnd(): void {
|
|
72
|
+
this.scroller.toEnd();
|
|
73
|
+
this.tui.requestRender();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
get notice(): string {
|
|
77
|
+
return this.noticeText;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
set notice(notice: string) {
|
|
81
|
+
this.setNotice(notice);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
setNotice(notice: string, tone: NoticeTone = "info"): void {
|
|
85
|
+
if (this.disposed) return;
|
|
86
|
+
this.noticeText = notice;
|
|
87
|
+
this.noticeTone = tone;
|
|
88
|
+
this.tui.requestRender();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
setRunning(running: boolean): void {
|
|
92
|
+
this.running = running;
|
|
93
|
+
if (!running) this.progressText = "";
|
|
94
|
+
this.tui.requestRender();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Ephemeral in-flight status; never enters the thread or clipboard. */
|
|
98
|
+
setProgress(text: string): void {
|
|
99
|
+
if (this.disposed || !this.running) return;
|
|
100
|
+
this.progressText = text;
|
|
101
|
+
this.tui.requestRender();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
setModel(model: string): void {
|
|
105
|
+
this.model = model;
|
|
106
|
+
this.tui.requestRender();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
setTrailingMode(label: string, emphasized = false): void {
|
|
110
|
+
this.trailingMode = { label, emphasized };
|
|
111
|
+
this.tui.requestRender();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
setCustomMode(label: string): void {
|
|
115
|
+
this.customMode = label;
|
|
116
|
+
this.tui.requestRender();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
clearComposer(): void {
|
|
120
|
+
this.input.setValue("");
|
|
121
|
+
this.tui.requestRender();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
getComposerText(): string {
|
|
125
|
+
return this.input.getValue();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
setComposerText(text: string): void {
|
|
129
|
+
this.input.setValue(text);
|
|
130
|
+
(this.input as unknown as { cursor: number }).cursor = text.length;
|
|
131
|
+
this.tui.requestRender();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
invalidate(): void {
|
|
135
|
+
this.markdown.invalidate();
|
|
136
|
+
this.input.invalidate();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
handleMouse(event: BroMouseEvent): BroMouseResult {
|
|
140
|
+
return this.scroller.handleMouse(event);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
handleInput(data: string): void {
|
|
144
|
+
if (this.onKey?.(data)) return;
|
|
145
|
+
if (matchesKey(data, "escape")) {
|
|
146
|
+
this.onClose();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (this.scroller.handleKey(data, this.rawArea)) return;
|
|
150
|
+
this.input.handleInput(data);
|
|
151
|
+
this.onInput?.();
|
|
152
|
+
this.tui.requestRender();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
render(width: number): string[] {
|
|
156
|
+
const inner = Math.max(1, width - 2);
|
|
157
|
+
const height = modalHeight(this.tui, BRO_OVERLAY, 34);
|
|
158
|
+
this.rawArea = broOverlayArea(this.tui, width, height);
|
|
159
|
+
return renderFrame(this.theme, width, height, {
|
|
160
|
+
header: () => {
|
|
161
|
+
const scroll = this.scroller.indicator();
|
|
162
|
+
const model = this.model ? this.theme.fg("dim", ` · ${this.model}`) : "";
|
|
163
|
+
const mode = this.customMode
|
|
164
|
+
? this.theme.fg("dim", this.customMode)
|
|
165
|
+
: this.trailingMode
|
|
166
|
+
? this.theme.fg("dim", " · ") + (this.trailingMode.emphasized ? this.theme.fg("accent", this.theme.bold(this.trailingMode.label)) : this.theme.fg("dim", this.trailingMode.label))
|
|
167
|
+
: "";
|
|
168
|
+
const title = this.theme.fg("accent", this.theme.bold(this.appearance.title ?? "Bro"));
|
|
169
|
+
// A leading label stays visible when the title and model must be truncated.
|
|
170
|
+
const header = this.customMode ? `${mode} · ${title}${model}` : title + model + mode;
|
|
171
|
+
return header + this.theme.fg("dim", scroll ? ` · ${scroll}` : "");
|
|
172
|
+
},
|
|
173
|
+
body: (rows, innerWidth) => this.scroller.view(this.markdown.render(innerWidth), rows),
|
|
174
|
+
// The frame drops lines from the top when space runs out, so the composer goes last.
|
|
175
|
+
footer: [
|
|
176
|
+
...(this.appearance.commands ? wrapTextWithAnsi(this.appearance.commands, inner) : []),
|
|
177
|
+
...(this.suggestions ? wrapTextWithAnsi(this.theme.fg("accent", this.suggestions), inner) : []),
|
|
178
|
+
this.theme.fg("accent", this.theme.bold(this.appearance.inputLabel ?? "Your message")),
|
|
179
|
+
this.input.render(inner)[0] ?? "",
|
|
180
|
+
],
|
|
181
|
+
notice: this.noticeText ? formatNotice(this.theme, this.noticeText, this.noticeTone) : undefined,
|
|
182
|
+
// A tool label may be long. Preserve the elapsed seconds and Esc
|
|
183
|
+
// on one line; shorten only the stage so transcript height stays put.
|
|
184
|
+
hints: this.running
|
|
185
|
+
? runningHint(this.progressText || "Bro is thinking…", inner, [
|
|
186
|
+
" · Esc close (stops reply)", " · Esc close",
|
|
187
|
+
])
|
|
188
|
+
: (typeof this.appearance.idleHint === "function" ? this.appearance.idleHint() : this.appearance.idleHint ?? "Enter send · Esc close"),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
dispose(): void {
|
|
193
|
+
if (this.disposed) return;
|
|
194
|
+
this.disposed = true;
|
|
195
|
+
this.onDispose();
|
|
196
|
+
}
|
|
197
|
+
}
|
package/src/explain-modal.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { rm, writeFile } from "node:fs/promises";
|
|
2
|
-
import { stripVTControlCharacters } from "node:util";
|
|
3
2
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
4
3
|
import { copyToClipboard, getMarkdownTheme, getSelectListTheme } from "@earendil-works/pi-coding-agent";
|
|
5
4
|
import {
|
|
@@ -19,7 +18,6 @@ import {
|
|
|
19
18
|
MAX_PREFERENCES_CHARS,
|
|
20
19
|
STARTER_PREFERENCES,
|
|
21
20
|
buildDefaultPrompt,
|
|
22
|
-
nextBroMode,
|
|
23
21
|
} from "./prompt.ts";
|
|
24
22
|
import {
|
|
25
23
|
type BroSettings,
|
|
@@ -34,20 +32,20 @@ import {
|
|
|
34
32
|
selectionLabel,
|
|
35
33
|
settingsFile,
|
|
36
34
|
} from "./settings.ts";
|
|
37
|
-
import { openShowHtml
|
|
35
|
+
import { openShowHtml } from "./show.ts";
|
|
38
36
|
import type { BroSource } from "./sources.ts";
|
|
39
37
|
import { BRO_OVERLAY, broOverlayArea, delegateMouse, formatNotice, modalHeight, openBroOverlay, renderFrame, runningHint, Scroller, startProgressClock, type Area, type NoticeTone, type Theme, type TuiLike } from "./modal-kit.ts";
|
|
40
38
|
import { hasBroCustomUi, type BroMouseEvent, type BroMouseResult } from "./ui-capabilities.ts";
|
|
41
39
|
import { errorMessage } from "./util.ts";
|
|
42
40
|
import { latestCompletedAssistantText } from "./last-assistant.ts";
|
|
43
41
|
|
|
44
|
-
const LOADING_TEXT = "
|
|
42
|
+
const LOADING_TEXT = "Working…";
|
|
45
43
|
|
|
46
44
|
export type ModalKind = "loading" | "streaming" | "result" | "help" | "empty" | "error";
|
|
47
45
|
// `mode` is the built-in explain mode that produced the text; absent for Show and Doctor.
|
|
48
46
|
// `preferences` records whether bro-preferences.md shaped this result; like `mode`, it belongs to the result.
|
|
49
47
|
export type BroResult = { source: BroSource; text: string; model?: string; mode?: BroMode; preferences?: boolean };
|
|
50
|
-
export type ModalResult = {
|
|
48
|
+
export type ModalResult = { text: string; htmlPath?: string; model?: string; preferences?: boolean };
|
|
51
49
|
|
|
52
50
|
export function latestAssistant(ctx: ExtensionCommandContext): BroSource | undefined {
|
|
53
51
|
const text = latestCompletedAssistantText(ctx.sessionManager.getBranch())?.trim();
|
|
@@ -372,23 +370,19 @@ Quick reference. Full user guide: https://github.com/tranhoangnguyen03/pi-bro/bl
|
|
|
372
370
|
|
|
373
371
|
## Pick by need
|
|
374
372
|
|
|
375
|
-
- **Understand what already exists:** Simplify
|
|
373
|
+
- **Understand what already exists:** Simplify for plain words or diagrams; Architecture for this repository.
|
|
376
374
|
- **Explore what could exist:** BTW for side questions; Grill Me for decisions.
|
|
377
375
|
- **Get advice on existing work:** Guided Review; Overthink for automatic second looks; agent-facing Advisor.
|
|
378
376
|
- **Guide the agent:** Elevate for assignments; Remember Me for approved context (about_user); Advisor Steering for priorities.
|
|
379
377
|
|
|
380
378
|
These are needs, not modes. Copied text does not enter Pi until you paste and submit it.
|
|
381
379
|
|
|
382
|
-
##
|
|
380
|
+
## Simplify: understand in words or diagrams
|
|
383
381
|
|
|
384
|
-
- \`/bro\` —
|
|
385
|
-
- \`/
|
|
386
|
-
- \`/bro
|
|
387
|
-
- \`/
|
|
388
|
-
- \`/bro url <url>\` — explain one public webpage
|
|
389
|
-
- \`/bro <input>\` — a lone URL, an existing supported file, or anything else as pasted text
|
|
390
|
-
- Inside Simplify: \`/simplify\`, \`/text <text>\`, \`/file <path>\`, \`/url <url>\`, \`/copy\`, \`/clear\`, \`/help\`. **M** changes the mode and re-explains; **R** retries. One source at a time, no chat thread.\n- \`/bro open\` — legacy last-result view (retained for compatibility)
|
|
391
|
-
- \`/bro show [n-turns] [query]\` — draw recent turns' conversation text as shapes; an optional query steers the focus
|
|
382
|
+
- \`/bro\` or \`/bro simplify\` — reopen the saved result, or help if empty; no new model call.
|
|
383
|
+
- Inside Simplify, \`/simplify\` explains the latest reply; \`/text <text>\`, \`/file <path>\` and \`/url <url>\` explain another source. \`/show [n-turns] [query]\` draws recent conversation text.
|
|
384
|
+
- Use \`/bro simplify latest\` or \`/bro simplify text|file|url|show …\` to run directly, including without the viewer.
|
|
385
|
+
- \`/copy\`, \`/clear\`, and \`/help\` apply to both forms. One source and one saved result, no chat thread.
|
|
392
386
|
|
|
393
387
|
- \`/bro copy\` — edit and preview the last reply before copying raw Markdown.
|
|
394
388
|
|
|
@@ -473,7 +467,6 @@ export class BroModal implements Focusable {
|
|
|
473
467
|
private readonly markdown = new Markdown("", 0, 0, getMarkdownTheme());
|
|
474
468
|
private kind: ModalKind = "loading";
|
|
475
469
|
private rawText = "";
|
|
476
|
-
private sourceLabel = "";
|
|
477
470
|
private modelLabel = "";
|
|
478
471
|
private noticeText = "";
|
|
479
472
|
private noticeTone: NoticeTone = "info";
|
|
@@ -487,8 +480,6 @@ export class BroModal implements Focusable {
|
|
|
487
480
|
private retryable = false;
|
|
488
481
|
private disposed = false;
|
|
489
482
|
private htmlPath = "";
|
|
490
|
-
// Survives loading/streaming so the header names the mode being produced; empty disables M.
|
|
491
|
-
private modeLabel = "";
|
|
492
483
|
// Set only with a result, so the tag never claims preferences for work still in flight.
|
|
493
484
|
private preferencesUsed = false;
|
|
494
485
|
|
|
@@ -499,7 +490,6 @@ export class BroModal implements Focusable {
|
|
|
499
490
|
private readonly onRetry: () => void,
|
|
500
491
|
private readonly onDispose: () => void,
|
|
501
492
|
private readonly retryLabel: string,
|
|
502
|
-
private readonly onSwitchMode: () => void = () => {},
|
|
503
493
|
) {}
|
|
504
494
|
|
|
505
495
|
setLoading(text = LOADING_TEXT): void {
|
|
@@ -518,8 +508,8 @@ export class BroModal implements Focusable {
|
|
|
518
508
|
this.setNotice(text);
|
|
519
509
|
}
|
|
520
510
|
|
|
521
|
-
setResult(text: string, retryable: boolean, notice = "",
|
|
522
|
-
this.setContent("result", text,
|
|
511
|
+
setResult(text: string, retryable: boolean, notice = "", modelLabel = "", noticeTone: NoticeTone = "info"): void {
|
|
512
|
+
this.setContent("result", text, text, true, retryable, notice, modelLabel, noticeTone);
|
|
523
513
|
}
|
|
524
514
|
|
|
525
515
|
setNotice(text: string, tone: NoticeTone = "info"): void {
|
|
@@ -540,11 +530,6 @@ export class BroModal implements Focusable {
|
|
|
540
530
|
this.tui.requestRender();
|
|
541
531
|
}
|
|
542
532
|
|
|
543
|
-
setMode(mode: BroMode | undefined): void {
|
|
544
|
-
this.modeLabel = mode ?? "";
|
|
545
|
-
this.tui.requestRender();
|
|
546
|
-
}
|
|
547
|
-
|
|
548
533
|
setPreferences(used: boolean): void {
|
|
549
534
|
this.preferencesUsed = used;
|
|
550
535
|
this.tui.requestRender();
|
|
@@ -565,7 +550,6 @@ export class BroModal implements Focusable {
|
|
|
565
550
|
copyable: boolean,
|
|
566
551
|
retryable: boolean,
|
|
567
552
|
notice = "",
|
|
568
|
-
sourceLabel = "",
|
|
569
553
|
modelLabel = "",
|
|
570
554
|
noticeTone: NoticeTone = "info",
|
|
571
555
|
): void {
|
|
@@ -577,33 +561,24 @@ export class BroModal implements Focusable {
|
|
|
577
561
|
this.retryable = retryable;
|
|
578
562
|
this.noticeText = notice;
|
|
579
563
|
this.noticeTone = noticeTone;
|
|
580
|
-
this.sourceLabel = stripVTControlCharacters(sourceLabel)
|
|
581
|
-
.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
|
|
582
|
-
.replace(/\s+/g, " ")
|
|
583
|
-
.trim();
|
|
584
564
|
this.modelLabel = modelLabel;
|
|
585
565
|
if (kind !== "streaming") this.scroller.toStart();
|
|
586
566
|
this.markdown.setText(text);
|
|
587
567
|
this.tui.requestRender();
|
|
588
568
|
}
|
|
589
569
|
|
|
590
|
-
private canSwitchMode(): boolean {
|
|
591
|
-
return Boolean(this.modeLabel) && (this.kind === "loading" || this.kind === "streaming" || this.kind === "result");
|
|
592
|
-
}
|
|
593
|
-
|
|
594
570
|
private controls(innerWidth: number): string {
|
|
595
|
-
const mode = this.canSwitchMode() ? " · M mode" : "";
|
|
596
571
|
if (this.kind === "loading" || this.kind === "streaming") {
|
|
597
572
|
// The elapsed seconds and Esc matter more than a long stage name.
|
|
598
573
|
// Keep one hint row so the body never jumps as that stage changes.
|
|
599
574
|
const scroll = this.kind === "streaming" ? " · ↑/↓ scroll" : "";
|
|
600
575
|
const phase = this.progressText || (this.kind === "loading" ? "Working…" : "Receiving output…");
|
|
601
576
|
return runningHint(phase, innerWidth, [
|
|
602
|
-
`${scroll}
|
|
577
|
+
`${scroll} · Esc cancel`, " · Esc cancel",
|
|
603
578
|
], 12);
|
|
604
579
|
}
|
|
605
580
|
if (this.kind === "result") {
|
|
606
|
-
return `↑/↓ scroll · C copy${this.htmlPath ? " · O open diagram" : ""}${
|
|
581
|
+
return `↑/↓ scroll · C copy${this.htmlPath ? " · O open diagram" : ""}${this.retryable ? ` · R ${this.retryLabel}` : ""} · Esc close`;
|
|
607
582
|
}
|
|
608
583
|
if (this.kind === "help") return "↑/↓ scroll · C copy · Esc close";
|
|
609
584
|
if (this.kind === "error") return "R try again · Esc close";
|
|
@@ -617,8 +592,8 @@ export class BroModal implements Focusable {
|
|
|
617
592
|
header: () => {
|
|
618
593
|
const scroll = this.scroller.indicator();
|
|
619
594
|
return (
|
|
620
|
-
this.theme.fg("accent", this.theme.bold(
|
|
621
|
-
this.theme.fg("dim", `${this.modelLabel ? ` · ${this.modelLabel}` : ""}${this.
|
|
595
|
+
this.theme.fg("accent", this.theme.bold("Bro")) +
|
|
596
|
+
this.theme.fg("dim", `${this.modelLabel ? ` · ${this.modelLabel}` : ""}${this.preferencesUsed ? " · prefs" : ""}${scroll ? ` · ${scroll}` : ""}`)
|
|
622
597
|
);
|
|
623
598
|
},
|
|
624
599
|
body: (rows, innerWidth) => this.scroller.view(this.markdown.render(innerWidth), rows),
|
|
@@ -663,11 +638,6 @@ export class BroModal implements Focusable {
|
|
|
663
638
|
return;
|
|
664
639
|
}
|
|
665
640
|
|
|
666
|
-
if ((matchesKey(data, "m") || matchesKey(data, "shift+m")) && this.canSwitchMode()) {
|
|
667
|
-
this.onSwitchMode();
|
|
668
|
-
return;
|
|
669
|
-
}
|
|
670
|
-
|
|
671
641
|
if ((matchesKey(data, "o") || matchesKey(data, "shift+o")) && this.htmlPath && this.kind === "result") {
|
|
672
642
|
const opened = openShowHtml(this.htmlPath);
|
|
673
643
|
this.setNotice(
|
|
@@ -691,9 +661,7 @@ export interface BroModalOptions {
|
|
|
691
661
|
result?: ModalResult;
|
|
692
662
|
run?: (
|
|
693
663
|
signal: AbortSignal,
|
|
694
|
-
source?: BroSource,
|
|
695
664
|
onProgress?: (text: string) => void,
|
|
696
|
-
mode?: BroMode,
|
|
697
665
|
) => Promise<ModalResult>;
|
|
698
666
|
onResult?: (result: ModalResult) => void;
|
|
699
667
|
loadingText?: string;
|
|
@@ -717,8 +685,7 @@ export async function showBroModal(ctx: ExtensionCommandContext, options: BroMod
|
|
|
717
685
|
let controller: AbortController | undefined;
|
|
718
686
|
let stopProgress: (() => void) | undefined;
|
|
719
687
|
let current = options.result;
|
|
720
|
-
|
|
721
|
-
let execute: (source?: BroSource, mode?: BroMode, notice?: string, noticeTone?: NoticeTone) => void = () => {};
|
|
688
|
+
|
|
722
689
|
|
|
723
690
|
const close = () => {
|
|
724
691
|
if (closed) return;
|
|
@@ -732,41 +699,27 @@ export async function showBroModal(ctx: ExtensionCommandContext, options: BroMod
|
|
|
732
699
|
tui,
|
|
733
700
|
theme,
|
|
734
701
|
close,
|
|
735
|
-
() => execute(
|
|
702
|
+
() => execute(),
|
|
736
703
|
() => {
|
|
737
704
|
closed = true;
|
|
738
705
|
stopProgress?.();
|
|
739
706
|
controller?.abort();
|
|
740
707
|
},
|
|
741
|
-
options.retryLabel ?? "
|
|
742
|
-
// M advances from the mode in flight, so repeated presses cancel and skip ahead; the saved default is untouched.
|
|
743
|
-
() => {
|
|
744
|
-
const from = inFlightMode ?? current?.mode;
|
|
745
|
-
if (!from || !current?.source || closed) return;
|
|
746
|
-
const next = nextBroMode(from);
|
|
747
|
-
stopProgress?.();
|
|
748
|
-
controller?.abort();
|
|
749
|
-
controller = undefined;
|
|
750
|
-
execute(current.source, next, `Mode: ${next} (not saved)`);
|
|
751
|
-
},
|
|
708
|
+
options.retryLabel ?? "try again",
|
|
752
709
|
);
|
|
753
710
|
|
|
754
711
|
const present = (result: ModalResult, notice = "", noticeTone: NoticeTone = "info") => {
|
|
755
|
-
|
|
756
|
-
modal.setResult(display, options.retryable ?? Boolean(options.run), notice, result.source?.label, result.text, result.model, noticeTone);
|
|
712
|
+
modal.setResult(result.text, options.retryable ?? Boolean(options.run), notice, result.model, noticeTone);
|
|
757
713
|
modal.setHtmlPath(result.htmlPath ?? "");
|
|
758
|
-
modal.setMode(result.mode);
|
|
759
714
|
modal.setPreferences(Boolean(result.preferences));
|
|
760
715
|
};
|
|
761
716
|
|
|
762
|
-
execute = (
|
|
717
|
+
const execute = () => {
|
|
763
718
|
if (!options.run || controller || closed) return;
|
|
764
719
|
const previous = current;
|
|
765
720
|
const nextController = new AbortController();
|
|
766
721
|
controller = nextController;
|
|
767
|
-
inFlightMode = mode;
|
|
768
722
|
modal.setLoading(options.loadingText);
|
|
769
|
-
modal.setMode(mode);
|
|
770
723
|
modal.setPreferences(false);
|
|
771
724
|
const phase = options.loadingText ?? "Working";
|
|
772
725
|
const stop = startProgressClock(nextController.signal, seconds => {
|
|
@@ -775,17 +728,17 @@ export async function showBroModal(ctx: ExtensionCommandContext, options: BroMod
|
|
|
775
728
|
stopProgress = stop;
|
|
776
729
|
|
|
777
730
|
void options
|
|
778
|
-
.run(nextController.signal,
|
|
731
|
+
.run(nextController.signal, (text) => {
|
|
779
732
|
if (closed || nextController.signal.aborted || controller !== nextController) return;
|
|
780
733
|
// This callback may be a workflow stage (Architecture), not
|
|
781
734
|
// a streaming answer. The body owns the stage; keep the hint neutral.
|
|
782
735
|
modal.setStreaming(text);
|
|
783
|
-
}
|
|
736
|
+
})
|
|
784
737
|
.then((result) => {
|
|
785
738
|
if (closed || nextController.signal.aborted) return;
|
|
786
739
|
current = result;
|
|
787
740
|
options.onResult?.(result);
|
|
788
|
-
present(result
|
|
741
|
+
present(result);
|
|
789
742
|
})
|
|
790
743
|
.catch((error) => {
|
|
791
744
|
if (closed || nextController.signal.aborted) return;
|
|
@@ -794,17 +747,13 @@ export async function showBroModal(ctx: ExtensionCommandContext, options: BroMod
|
|
|
794
747
|
current = previous;
|
|
795
748
|
present(previous, `Retry failed: ${message}`, "error");
|
|
796
749
|
} else {
|
|
797
|
-
modal.setMode(undefined);
|
|
798
750
|
modal.setError(message);
|
|
799
751
|
}
|
|
800
752
|
})
|
|
801
753
|
.finally(() => {
|
|
802
754
|
stop();
|
|
803
755
|
if (stopProgress === stop) stopProgress = undefined;
|
|
804
|
-
if (controller === nextController)
|
|
805
|
-
controller = undefined;
|
|
806
|
-
inFlightMode = undefined;
|
|
807
|
-
}
|
|
756
|
+
if (controller === nextController) controller = undefined;
|
|
808
757
|
});
|
|
809
758
|
};
|
|
810
759
|
|