pi-bro 0.35.1 → 0.36.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/src/copy.ts ADDED
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Model-free Markdown scratchpad for the last completed Pi reply.
3
+ * Pi Editor is the only editable draft. Preview renders that draft.
4
+ * Unedited copy preserves the original raw message; edited copy uses Pi's
5
+ * expanded editor text, including its normal tab/line-ending conversion.
6
+ */
7
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
8
+ import { copyToClipboard, getMarkdownTheme, getSelectListTheme } from "@earendil-works/pi-coding-agent";
9
+ import { Editor, Markdown, matchesKey, wrapTextWithAnsi, type Component, type EditorTheme, type TUI } from "@earendil-works/pi-tui";
10
+ import { broOverlayArea, delegateMouse, formatNotice, modalHeight, openBroOverlay, renderFrame, Scroller, type Area, type Theme, type TuiLike } from "./modal-kit.ts";
11
+ import { hasBroCustomUi, type BroMouseEvent, type BroMouseResult } from "./ui-capabilities.ts";
12
+ import { errorMessage } from "./util.ts";
13
+ import { latestCompletedAssistantText } from "./last-assistant.ts";
14
+
15
+ type CopyText = (markdown: string) => Promise<void>;
16
+ type CopyView = "edit" | "preview";
17
+
18
+ export class CopyModal implements Component {
19
+ readonly editor: Editor;
20
+ private readonly preview: Markdown;
21
+ private readonly scroller: Scroller;
22
+ private readonly original: string;
23
+ private readonly initialEditorText: string;
24
+ private readonly tui: TUI;
25
+ private readonly theme: Theme;
26
+ private readonly onClose: () => void;
27
+ private readonly copyText: CopyText;
28
+
29
+ private view: CopyView = "edit";
30
+ private showingHelp = false;
31
+ private discardArmed = false;
32
+ private canEdit = false;
33
+ private closed = false;
34
+ private notice = "";
35
+ private editorArea: Area = { top: 0, left: 0, width: 0, height: 0 };
36
+ private modalArea: Area | undefined;
37
+
38
+ constructor(tui: TUI, theme: Theme, markdown: string, onClose: () => void, copyText: CopyText = copyToClipboard) {
39
+ this.tui = tui;
40
+ this.theme = theme;
41
+ this.original = markdown;
42
+ this.onClose = onClose;
43
+ this.copyText = copyText;
44
+ const editorTheme: EditorTheme = {
45
+ borderColor: (value: string) => theme.fg("border", value),
46
+ selectList: getSelectListTheme(),
47
+ };
48
+ this.editor = new Editor(tui, editorTheme);
49
+ this.editor.focused = true;
50
+ this.editor.setText(markdown);
51
+ this.initialEditorText = this.editor.getExpandedText();
52
+ this.editor.onChange = () => {
53
+ this.discardArmed = false;
54
+ this.notice = "";
55
+ this.tui.requestRender();
56
+ };
57
+ this.preview = new Markdown("", 0, 0, getMarkdownTheme());
58
+ this.scroller = new Scroller(() => this.tui.requestRender());
59
+ }
60
+
61
+ private edited(): boolean {
62
+ return this.editor.getExpandedText() !== this.initialEditorText;
63
+ }
64
+
65
+ /** No edit: exact original Markdown. Edited: one authoritative Pi Editor draft. */
66
+ private markdown(): string {
67
+ return this.edited() ? this.editor.getExpandedText() : this.original;
68
+ }
69
+
70
+ private normalizationNotice(): string | undefined {
71
+ if (!this.edited()) return undefined;
72
+ const changes = [
73
+ this.original.includes("\t") ? "tabs become spaces" : undefined,
74
+ this.original.includes("\r") ? "CRLF becomes LF" : undefined,
75
+ ].filter((item): item is string => Boolean(item));
76
+ return changes.length ? "Edited copy: " + changes.join("; ") + "." : undefined;
77
+ }
78
+
79
+ private noticeOf(message: string, tone: "info" | "success" | "warning" | "error"): void {
80
+ if (this.closed) return;
81
+ this.notice = formatNotice(this.theme, message, tone);
82
+ this.tui.requestRender();
83
+ }
84
+
85
+ private copy(): void {
86
+ this.discardArmed = false;
87
+ const markdown = this.markdown();
88
+ // Snapshot before the async clipboard operation; never copy on-screen
89
+ // paste markers or Preview's rendered terminal text.
90
+ void Promise.resolve()
91
+ .then(() => this.copyText(markdown))
92
+ .then(() => this.noticeOf("Copied Markdown.", "success"))
93
+ .catch(error => this.noticeOf("Copy failed: " + errorMessage(error), "error"));
94
+ }
95
+
96
+ private toggleView(): void {
97
+ if (this.closed) return;
98
+ this.showingHelp = false;
99
+ this.discardArmed = false;
100
+ this.notice = "";
101
+ this.view = this.view === "edit" ? "preview" : "edit";
102
+ if (this.view === "preview") {
103
+ this.preview.setText(this.markdown());
104
+ this.scroller.toStart();
105
+ }
106
+ this.tui.requestRender();
107
+ }
108
+
109
+ render(width: number): string[] {
110
+ const height = modalHeight(this.tui);
111
+ const innerWidth = Math.max(1, width - 2);
112
+ this.modalArea = broOverlayArea(this.tui as TuiLike, width, height);
113
+ this.canEdit = false;
114
+ this.editorArea = { top: 0, left: 0, width: 0, height: 0 };
115
+
116
+ const hint = this.showingHelp
117
+ ? "Esc back · F1 back · Ctrl+C copy"
118
+ : this.discardArmed
119
+ ? "Esc again discard · Ctrl+C copy · Ctrl+D preview/edit"
120
+ : this.view === "edit"
121
+ ? "Ctrl+D preview · Ctrl+C copy · F1 help · Esc close"
122
+ : "↑/↓ scroll · Ctrl+D edit · Ctrl+C copy · ? / F1 help · Esc close";
123
+ const editorLines = !this.showingHelp && this.view === "edit" ? this.editor.render(innerWidth) : [];
124
+ const help = [
125
+ "Edit the last completed assistant reply as raw Markdown.",
126
+ "The original Pi conversation is never changed.",
127
+ "",
128
+ "Ctrl+D Switch between Edit and Markdown Preview (replaces forward-delete in Copy)",
129
+ "Ctrl+C Copy full raw Markdown; never rendered terminal text",
130
+ "F1 Help in both views",
131
+ "? Help in Preview; ordinary text in Edit",
132
+ "Esc Back from Help; close (confirm if edited)",
133
+ "",
134
+ "Unedited copy preserves the original; edits follow Pi Editor's tab/CRLF rules.",
135
+ "No model calls, saved drafts, or workspace changes.",
136
+ ];
137
+ const normalizationNotice = this.normalizationNotice();
138
+
139
+ return renderFrame(this.theme, width, height, {
140
+ header: () => this.theme.fg("accent", this.theme.bold("Bro · Copy · " +
141
+ (this.showingHelp ? "Help" : this.view === "edit" ? "Edit" : "Preview"))) +
142
+ (this.edited() ? this.theme.fg("dim", " · edited") : "") +
143
+ (!this.showingHelp && this.view === "preview" && this.scroller.indicator()
144
+ ? this.theme.fg("dim", " · " + this.scroller.indicator()) : ""),
145
+ body: (rows, inner) => {
146
+ if (this.showingHelp) return this.scroller.view(help.flatMap(line => wrapTextWithAnsi(line, inner)), rows);
147
+ if (this.view === "preview") return this.scroller.view(this.preview.render(inner), rows);
148
+ if (rows < editorLines.length) {
149
+ return wrapTextWithAnsi("Enlarge the terminal to edit. Ctrl+D previews; Ctrl+C still copies the draft.", inner).slice(0, rows);
150
+ }
151
+ this.canEdit = true;
152
+ this.editorArea = { top: 3, left: 1, width: inner, height: editorLines.length };
153
+ return editorLines;
154
+ },
155
+ notice: this.notice || (normalizationNotice ? formatNotice(this.theme, normalizationNotice, "warning") : undefined),
156
+ hints: hint,
157
+ minBody: this.showingHelp || this.view === "preview" ? 1 : editorLines.length,
158
+ fill: true,
159
+ });
160
+ }
161
+
162
+ invalidate(): void {
163
+ this.editor.invalidate();
164
+ this.preview.invalidate();
165
+ }
166
+
167
+ handleMouse(event: BroMouseEvent): BroMouseResult {
168
+ if (this.showingHelp || this.view === "preview") return this.scroller.handleMouse(event);
169
+ return delegateMouse(this.editor, event, this.editorArea);
170
+ }
171
+
172
+ handleInput(data: string): void {
173
+ if (this.closed) return;
174
+ if (matchesKey(data, "ctrl+c")) { this.copy(); return; }
175
+ if (matchesKey(data, "escape")) {
176
+ if (this.showingHelp) {
177
+ this.showingHelp = false;
178
+ this.scroller.toStart();
179
+ this.tui.requestRender();
180
+ return;
181
+ }
182
+ if (this.edited() && !this.discardArmed) {
183
+ this.discardArmed = true;
184
+ this.noticeOf("Edits will be discarded. Esc again to close, or Ctrl+C to copy.", "warning");
185
+ return;
186
+ }
187
+ this.closed = true;
188
+ this.onClose();
189
+ return;
190
+ }
191
+ if (matchesKey(data, "ctrl+d")) { this.toggleView(); return; }
192
+ if (matchesKey(data, "f1") || (this.view === "preview" && matchesKey(data, "?"))) {
193
+ this.showingHelp = !this.showingHelp;
194
+ this.scroller.toStart();
195
+ this.notice = "";
196
+ this.discardArmed = false;
197
+ this.tui.requestRender();
198
+ return;
199
+ }
200
+ if (this.showingHelp || this.view === "preview") {
201
+ if (!this.scroller.handleKey(data, this.modalArea)) this.tui.requestRender();
202
+ return;
203
+ }
204
+ if (!this.canEdit) return; // Never change text in an invisible editor.
205
+ this.discardArmed = false;
206
+ this.notice = "";
207
+ if (matchesKey(data, "enter")) this.editor.insertTextAtCursor("\n");
208
+ else this.editor.handleInput(data);
209
+ this.tui.requestRender();
210
+ }
211
+
212
+ dispose(): void { this.closed = true; }
213
+ }
214
+
215
+ export async function openCopyModal(ctx: ExtensionCommandContext): Promise<void> {
216
+ if (!hasBroCustomUi(ctx)) {
217
+ ctx.ui.notify("Use /bro copy in Pi's interactive terminal.", "warning");
218
+ return;
219
+ }
220
+ const markdown = latestCompletedAssistantText(ctx.sessionManager.getBranch());
221
+ if (!markdown) {
222
+ ctx.ui.notify("No completed assistant reply to copy yet.", "warning");
223
+ return;
224
+ }
225
+ await openBroOverlay<void>(
226
+ ctx,
227
+ (tui, theme, _keys, done) => new CopyModal(tui, theme, markdown, () => done()),
228
+ { mouse: true },
229
+ );
230
+ }
package/src/doctor.ts CHANGED
@@ -16,7 +16,8 @@ import {
16
16
  readAdvisorSteering,
17
17
  resolveAdvisorState,
18
18
  } from "./advisor.ts";
19
- import { agyFailureMessage, bridgePiRuntimeForCatalog, piEffectiveEffort, reviewBackendNotice, splitPiModel } from "./backend.ts";
19
+ import { agyFailureMessage, bridgePiRuntimeForCatalog, piEffectiveEffort, reviewBackendNotice, splitPiModel, verifyCliSubscription } from "./backend.ts";
20
+ import { resolveCliChildAuth } from "./cli-auth.ts";
20
21
  import { createConfigModal } from "./config-ui.ts";
21
22
  import { createConfigNavigationModal } from "./config-navigation-ui.ts";
22
23
  import { type ConfigNavAction, type ConfigNavState } from "./config-navigation.ts";
@@ -124,16 +125,47 @@ export async function listPiModels(
124
125
  if (signal?.aborted) throw new Error("Canceled.");
125
126
 
126
127
  const patterns = settingsManager.getEnabledModels() ?? [];
128
+ const hostScoped = ctx.scopedModels;
129
+ // The host has already resolved --models / enabledModels. A nonempty host
130
+ // scope wins even if the on-disk patterns disagree or do not exist.
131
+ if (hostScoped?.length) {
132
+ const effective = hostScoped.flatMap(({ model, thinkingLevel }) => {
133
+ const selected = ctx.modelRegistry.find(model.provider, model.id);
134
+ return selected && ctx.modelRegistry.hasConfiguredAuth(selected)
135
+ ? [{ model: selected, thinkingLevel }] : [];
136
+ });
137
+ return {
138
+ models: toPiModelChoices(effective),
139
+ scope: "scoped",
140
+ diagnostics: effective.length < hostScoped.length
141
+ ? ["A model in the active host scope is no longer available or authenticated. Refresh the host selection."] : [],
142
+ modelRuntime,
143
+ };
144
+ }
127
145
  if (patterns.length) {
146
+ if (hostScoped !== undefined) {
147
+ // The host explicitly reports an empty resolved scope. Never turn it
148
+ // into an unscoped picker, or recompute options from newer disk files.
149
+ return {
150
+ models: [], scope: "scoped",
151
+ diagnostics: ["The active host has no scoped models. Check its --models / enabledModels selection; reload the host after editing settings."],
152
+ modelRuntime,
153
+ };
154
+ }
155
+ // Old test hosts without scopedModels can still resolve file patterns;
156
+ // use only the host-backed catalog for both choices and diagnostics.
128
157
  const resolved = await resolveModelScopeWithDiagnostics(patterns, modelRuntime);
129
- const diagnostics = resolved.diagnostics.map((entry) => entry.message);
130
- // A configured scope is authoritative even when it resolves to nothing: silently substituting
131
- // every authenticated model would offer choices the user never scoped in, and would hide the
132
- // diagnostics that explain why. The caller shows them.
133
- return { models: toPiModelChoices(resolved.scopedModels), scope: "scoped", diagnostics, modelRuntime };
158
+ return {
159
+ models: toPiModelChoices(resolved.scopedModels),
160
+ scope: "scoped",
161
+ diagnostics: resolved.diagnostics.map((entry) => entry.message),
162
+ modelRuntime,
163
+ };
134
164
  }
135
-
136
- const available = modelRuntime.getAvailableSnapshot().map((model) => ({ model }));
165
+ // SDK documents [] as "no scope" when there are no enabledModels.
166
+ // The API cannot distinguish this from a failed CLI --models scope that
167
+ // resolved to [], since it does not expose the CLI source patterns.
168
+ const available = ctx.modelRegistry.getAvailable().map((model) => ({ model }));
137
169
  return { models: toPiModelChoices(available), scope: "available", diagnostics: [], modelRuntime };
138
170
  }
139
171
 
@@ -195,6 +227,12 @@ async function checkCliVersion(pi: ExtensionAPI, binary: string, displayName: st
195
227
  // Auth status only: a version/auth answer without a model request. A passing answer here
196
228
  // says the CLI starts and reports signed-in state -- it does not imply connectivity.
197
229
  async function checkClaudeAuth(pi: ExtensionAPI, signal: AbortSignal): Promise<string> {
230
+ const auth = resolveCliChildAuth("claude");
231
+ if (auth.subscription) {
232
+ const outcome = await verifyCliSubscription("claude", auth.env, signal, 5_000, 15_000);
233
+ if (outcome) throw new Error("message" in outcome ? outcome.message : "Unexpected subscription preflight outcome");
234
+ return "subscription login verified (not a model request or account identity check)";
235
+ }
198
236
  const result = await probeCli(pi, "claude", ["auth", "status"], signal, 15_000);
199
237
  if (result.killed || result.code !== 0) {
200
238
  const detail = result.stderr.trim() || result.stdout.trim();
@@ -208,7 +246,13 @@ async function checkClaudeAuth(pi: ExtensionAPI, signal: AbortSignal): Promise<s
208
246
 
209
247
  // Auth status only: a version/auth answer without a model request. A passing answer here
210
248
  // says the CLI starts and reports signed-in state -- it does not imply connectivity.
211
- async function checkCodexAuth(pi: ExtensionAPI, signal: AbortSignal): Promise<string> {
249
+ async function checkCodexAuth(pi: ExtensionAPI, signal: AbortSignal, cwd: string): Promise<string> {
250
+ const auth = resolveCliChildAuth("codex");
251
+ if (auth.subscription) {
252
+ const outcome = await verifyCliSubscription("codex", auth.env, signal, 5_000, 15_000, cwd);
253
+ if (outcome) throw new Error("message" in outcome ? outcome.message : "Unexpected subscription preflight outcome");
254
+ return "ChatGPT login and built-in OpenAI provider route verified (not a model request or billing proof)";
255
+ }
212
256
  const result = await probeCli(pi, "codex", ["login", "status"], signal, 15_000);
213
257
  if (result.killed || result.code !== 0) {
214
258
  const detail = result.stderr.trim() || result.stdout.trim();
@@ -235,13 +279,12 @@ export async function doctorReport(pi: ExtensionAPI, ctx: ExtensionCommandContex
235
279
  let settings: BroSettings | undefined;
236
280
  let models: AgyModelFamily[] | undefined;
237
281
  let agyVersion: string | undefined;
238
- let piRuntime: Awaited<ReturnType<typeof bridgePiRuntimeForCatalog>> | undefined;
239
282
  const findPiModel = (provider: string, id: string) => {
240
- const model = piRuntime?.getModel(provider, id) ?? ctx.modelRegistry.find(provider, id);
283
+ const model = ctx.modelRegistry.find(provider, id);
241
284
  return model?.api === "pi-virtual" ? undefined : model;
242
285
  };
243
286
  const hasPiAuth = (model: NonNullable<ReturnType<typeof findPiModel>>) =>
244
- piRuntime?.hasConfiguredAuth(model.provider) || ctx.modelRegistry.hasConfiguredAuth(model);
287
+ ctx.modelRegistry.hasConfiguredAuth(model);
245
288
  const pass = (name: string, detail: string) => lines.push(`- ✓ **${name}:** ${detail}`);
246
289
  const fail = (name: string, error: unknown) => {
247
290
  failed = true;
@@ -318,7 +361,7 @@ export async function doctorReport(pi: ExtensionAPI, ctx: ExtensionCommandContex
318
361
  }
319
362
  if (backend === "claude" || backend === "codex") {
320
363
  try {
321
- pass(`${label} auth`, await (backend === "claude" ? checkClaudeAuth(pi, signal) : checkCodexAuth(pi, signal)));
364
+ pass(`${label} auth`, await (backend === "claude" ? checkClaudeAuth(pi, signal) : checkCodexAuth(pi, signal, ctx.cwd)));
322
365
  } catch (error) {
323
366
  if (signal.aborted) throw error;
324
367
  fail(`${label} auth`, error);
@@ -328,13 +371,12 @@ export async function doctorReport(pi: ExtensionAPI, ctx: ExtensionCommandContex
328
371
  }
329
372
  }
330
373
 
331
- // Pi is in-process: validate the selected physical model against the bridged runtime without a
374
+ // Pi is in-process: validate the host-selected physical model without a
332
375
  // CLI spawn or a live model turn. A passing answer means the model resolves and has configured
333
376
  // auth; it is not a connectivity test.
334
377
  if (piInUse) {
335
378
  try {
336
- const { models: piModels, scope, diagnostics, modelRuntime } = await listPiModels(ctx, signal);
337
- piRuntime = modelRuntime;
379
+ const { models: piModels, scope, diagnostics } = await listPiModels(ctx, signal);
338
380
  pass("Pi model catalog", `${piModels.length} physical model${piModels.length === 1 ? "" : "s"} selectable · ${scope === "scoped" ? "from enabledModels (scoped)" : "all models with configured auth"}`);
339
381
  for (const diagnostic of diagnostics) lines.push(`- ℹ **Pi scoped models:** ${diagnostic}`);
340
382
  } catch (error) {
@@ -39,6 +39,7 @@ import type { BroSource } from "./sources.ts";
39
39
  import { BRO_OVERLAY, broOverlayArea, delegateMouse, formatNotice, modalHeight, openBroOverlay, renderFrame, Scroller, type Area, type NoticeTone, type Theme, type TuiLike } from "./modal-kit.ts";
40
40
  import { hasBroCustomUi, type BroMouseEvent, type BroMouseResult } from "./ui-capabilities.ts";
41
41
  import { errorMessage } from "./util.ts";
42
+ import { latestCompletedAssistantText } from "./last-assistant.ts";
42
43
 
43
44
  const LOADING_TEXT = "Simplifying for my bro…";
44
45
 
@@ -49,22 +50,8 @@ export type BroResult = { source: BroSource; text: string; model?: string; mode?
49
50
  export type ModalResult = { source?: BroSource; text: string; htmlPath?: string; model?: string; mode?: BroMode; preferences?: boolean };
50
51
 
51
52
  export function latestAssistant(ctx: ExtensionCommandContext): BroSource | undefined {
52
- const branch = ctx.sessionManager.getBranch();
53
-
54
- for (let i = branch.length - 1; i >= 0; i--) {
55
- const entry = branch[i];
56
- if (entry.type !== "message" || entry.message.role !== "assistant" || entry.message.stopReason !== "stop") {
57
- continue;
58
- }
59
-
60
- const text = entry.message.content
61
- .filter((part): part is { type: "text"; text: string } => part.type === "text")
62
- .map((part) => part.text)
63
- .join("\n")
64
- .trim();
65
-
66
- if (text) return { text };
67
- }
53
+ const text = latestCompletedAssistantText(ctx.sessionManager.getBranch())?.trim();
54
+ return text ? { text } : undefined;
68
55
  }
69
56
 
70
57
  export async function simplify(
@@ -403,6 +390,8 @@ These are needs, not modes. Copied text does not enter Pi until you paste and su
403
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)
404
391
  - \`/bro show [n-turns] [query]\` — draw recent turns' conversation text as shapes; an optional query steers the focus
405
392
 
393
+ - \`/bro copy\` — edit and preview the last reply before copying raw Markdown.
394
+
406
395
  ## Architecture documentation
407
396
 
408
397
  - \`/bro architecture [focus]\` — create source-backed docs and an offline map in \`docs/architecture/\` using the BTW model. See docs/features/architecture.md.
@@ -0,0 +1,23 @@
1
+ /**
2
+ * One authoritative selection rule for the last completed assistant reply.
3
+ * Simplify intentionally trims its result; Copy keeps the untrimmed text.
4
+ */
5
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
6
+
7
+ /**
8
+ * Multiple text content blocks are flattened with one LF, matching Bro's
9
+ * existing Simplify convention (the LF is a separator, not an original block).
10
+ * Ignore reasoning, images, unfinished replies and non-text messages.
11
+ */
12
+ export function latestCompletedAssistantText(branch: readonly SessionEntry[]): string | undefined {
13
+ for (let i = branch.length - 1; i >= 0; i--) {
14
+ const entry = branch[i]!;
15
+ if (entry.type !== "message" || entry.message.role !== "assistant" || entry.message.stopReason !== "stop") continue;
16
+ const text = entry.message.content
17
+ .filter((part): part is { type: "text"; text: string } => part.type === "text")
18
+ .map(part => part.text)
19
+ .join("\n");
20
+ if (text.trim()) return text;
21
+ }
22
+ return undefined;
23
+ }