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/src/backend.ts CHANGED
@@ -1,24 +1,26 @@
1
- import { type ChildProcess, type SpawnOptions, spawn } from "node:child_process";
2
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { stripVTControlCharacters } from "node:util";
6
- import { codexSubscriptionRouteProblem, isSubscriptionStatus, resolveCliChildAuth, type CliAuthBackend } from "./cli-auth.ts";
1
+ import { executeAgy } from "./backends/agy.ts";
2
+ import { executeClaude } from "./backends/claude.ts";
3
+ import { DEFAULT_KILL_ESCALATION_MS } from "./backends/cli-process.ts";
4
+ import { executeCodex } from "./backends/codex.ts";
7
5
  import {
8
- createAgentSession,
9
- DefaultResourceLoader,
10
- getAgentDir,
11
- ModelRuntime,
12
- SessionManager,
13
- SettingsManager,
14
- type ExtensionContext,
15
- type SessionEntry,
16
- } from "@earendil-works/pi-coding-agent";
17
- // clampThinkingLevel and the Model type are the only things Bro needs from pi-ai, which is the
18
- // lower-level LLM engine pi-coding-agent is built on. Bro imports it directly, so it is declared as
19
- // a peer dependency alongside pi-coding-agent and pi-tui rather than relied on transitively.
20
- import { clampThinkingLevel, type Model as PiAiModel } from "@earendil-works/pi-ai";
21
- import { errorMessage, withDoctor } from "./util.ts";
6
+ CLAUDE_EFFORTS, CODEX_EFFORTS, GROK_EFFORTS, MUSE_EFFORTS, PI_EFFORTS,
7
+ type BackendAccess, type BackendExecuteOptions, type BackendFeature, type BackendOnProgress,
8
+ type BackendOutcome, type BackendProgress, type BackendRequest, type BackendSelection,
9
+ } from "./backends/contract.ts";
10
+ import { executeGrok } from "./backends/grok.ts";
11
+ import { executeMuse } from "./backends/muse.ts";
12
+ import { executePi, getPiHostContext, type PiHostContext } from "./backends/pi.ts";
13
+
14
+ export * from "./backends/contract.ts";
15
+ export { agyFailureMessage, agySelection, advisorFlagErrorHint, parseBtwAgyLine } from "./backends/agy.ts";
16
+ export { beginAttempt, frameStdoutLines, MAX_STDOUT_LINE_CHARS } from "./backends/cli-process.ts";
17
+ export { GROK_RESTRICTED_PREFIX } from "./backends/grok.ts";
18
+ export {
19
+ bridgePiRuntimeForCatalog, getPiHostContext, piEffectiveEffort, piPhysicalModel,
20
+ piScopedThinkingLevel, piToolAllowlist, setPiHostContext, splitPiModel,
21
+ type PiHostContext, type PiPhysicalModel,
22
+ } from "./backends/pi.ts";
23
+ export { verifyCliSubscription } from "./cli-auth.ts";
22
24
 
23
25
  // Shared internal execution boundary for explain, show, btw, advisor, and review.
24
26
  // This implements docs/plans/2026-09-22-shared-backend-design.md across all supported backends
@@ -29,8 +31,6 @@ import { errorMessage, withDoctor } from "./util.ts";
29
31
  // Agy, Grok, and Codex run inside their own sandbox with shell available, and the UI owns telling
30
32
  // the user via `reviewBackendNotice`.
31
33
 
32
- export type BackendFeature = "explain" | "show" | "btw" | "advisor" | "review";
33
- export type BackendAccess = "restricted" | "workspace-full";
34
34
  // Per-backend truth, not one shared sentence: Codex and Grok have a read-only sandbox, Agy's
35
35
  // sandbox only restricts terminal commands and still lets it write inside the project. Kept short
36
36
  // enough that the whole notice fits the review window's advisory rows on a narrow terminal.
@@ -47,1934 +47,6 @@ export function backendDeadlineMs(feature: BackendFeature, access: BackendAccess
47
47
  return feature === "btw" ? 130_000 : 125_000;
48
48
  }
49
49
 
50
- export type AgySelection = { model: string; effort?: "low" | "medium" | "high" };
51
- export const CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
52
- export const GROK_EFFORTS = ["low", "medium", "high", "xhigh"] as const;
53
- export const CODEX_EFFORTS = ["low", "medium", "high", "xhigh"] as const;
54
- export const MUSE_EFFORTS = ["minimal", "low", "medium", "high", "xhigh", "max"] as const;
55
- export const PI_EFFORTS = ["minimal", "low", "medium", "high", "xhigh", "max"] as const;
56
- export type BackendSelection =
57
- | ({ backend?: "agy" } & AgySelection)
58
- | { backend: "claude"; model: string; effort?: (typeof CLAUDE_EFFORTS)[number] }
59
- | { backend: "grok"; model: string; effort?: (typeof GROK_EFFORTS)[number] }
60
- | { backend: "codex"; model: string; effort?: (typeof CODEX_EFFORTS)[number] }
61
- | { backend: "muse"; model: string; effort?: (typeof MUSE_EFFORTS)[number] }
62
- | { backend: "pi"; model: string; effort?: (typeof PI_EFFORTS)[number] };
63
- export type BackendContinuation = { id: string };
64
- export type BackendProgress = { kind: "text"; text: string } | { kind: "activity"; label: string; timestamp: number; tool?: string };
65
- export type BackendOnProgress = (progress: BackendProgress) => void;
66
-
67
- /** BTW reports a tool name/type, not a command, argument, or assistant message.
68
- * All six adapters use this extraction before events cross into the UI. */
69
- export function btwToolName(value: unknown): string | undefined {
70
- if (typeof value !== "string") return undefined;
71
- // Restrict to the initial identifier. Agy may supply "Read /path" (or
72
- // "Read(/path)"); neither should expose the path in a status hint.
73
- return /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(
74
- stripVTControlCharacters(value).replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim(),
75
- )?.[0];
76
- }
77
-
78
- export type BackendRequest = {
79
- feature: BackendFeature;
80
- prompt: string;
81
- access: BackendAccess;
82
- cwd?: string; // required for workspace-full
83
- continuation?: BackendContinuation;
84
- /** Opt-in tool-only activity for Grill on the review path; Guided Review stays unchanged. */
85
- reportReviewTools?: boolean;
86
- };
87
-
88
- export type BackendOutcome =
89
- | { status: "success"; text: string; continuation?: BackendContinuation }
90
- | { status: "failure" | "cancelled" | "timeout"; message: string; partialText?: string; continuationExpired?: true };
91
-
92
- export type BackendExecuteOptions = {
93
- // Injectable for offline tests only -- production always uses the defaults below.
94
- killEscalationMs?: number;
95
- deadlineMs?: number;
96
- // Injectable for offline tests only: stands in for the SDK's createAgentSession so the Pi adapter's
97
- // setup, cancellation, timeout and terminal-verification paths can be exercised without a model.
98
- piCreateSession?: typeof createAgentSession;
99
- };
100
-
101
- export function agyFailureMessage(action: string, result: { code: number; killed: boolean; stderr: string }): string {
102
- if (result.killed) return `Agy timed out while trying to ${action}. Run \`/bro doctor\` for setup help.`;
103
- const detail = result.stderr.trim();
104
- if (detail) return `Agy could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`;
105
- return `Agy could not ${action}. Make sure Agy is installed and signed in, then run \`/bro doctor\`.`;
106
- }
107
-
108
- // Strips a "-low/-medium/-high" suffix from a stored model id and separates it back into a plain
109
- // Agy `--model`/`--effort` pair; a "default" effort omits --effort entirely (Agy's own default).
110
- export function agySelection(pair: { model: string; effort: "default" | "low" | "medium" | "high" }): AgySelection {
111
- if (pair.effort === "default") return { model: pair.model };
112
- const suffix = (["low", "medium", "high"] as const).find((effort) => pair.model.endsWith(`-${effort}`));
113
- return {
114
- model: suffix ? pair.model.slice(0, -suffix.length - 1) : pair.model,
115
- effort: pair.effort,
116
- };
117
- }
118
-
119
- function processStartMessage(processError: NodeJS.ErrnoException, cli = "Agy"): string {
120
- if (processError.code === "ENOENT") {
121
- return cli === "Agy"
122
- ? "Agy could not start. Make sure Agy is installed and on PATH, then run `/bro doctor`."
123
- : cli === "Grok"
124
- ? "Grok could not start. Make sure `grok` is installed and on PATH, then run `/bro doctor`."
125
- : cli === "Codex"
126
- ? "Codex could not start. Make sure `codex` is installed and on PATH, then run `/bro doctor`."
127
- : cli === "Muse"
128
- ? "Muse could not start. Make sure `muse` is installed and on PATH, then run `/bro doctor`."
129
- : "Claude Code could not start. Make sure `claude` is installed and on PATH, then run `/bro doctor`.";
130
- }
131
- return `${cli} could not start: ${processError.message}\n\nRun \`/bro doctor\` for setup help.`;
132
- }
133
-
134
- function unexpectedSignalMessage(exitSignal: NodeJS.Signals | null, cli = "Agy"): string {
135
- return withDoctor(`${cli} exited unexpectedly${exitSignal ? ` (signal ${exitSignal})` : ""}, not from a request Bro made.`);
136
- }
137
-
138
- // Sends to the whole POSIX process group when possible so a misbehaving grandchild dies too, not
139
- // just the immediate child process -- child.kill() alone only ever reaches the immediate child.
140
- function killProcessGroup(child: ChildProcess, signalName: NodeJS.Signals): void {
141
- if (process.platform !== "win32" && typeof child.pid === "number") {
142
- try {
143
- process.kill(-child.pid, signalName);
144
- return;
145
- } catch {
146
- // Group may already be gone (e.g. the child already exited) -- fall through.
147
- }
148
- }
149
- child.kill(signalName);
150
- }
151
-
152
- // The three causes that stop an in-flight attempt: user cancellation, the host-imposed deadline,
153
- // and a protocol failure (malformed/inconsistent backend output). Exactly one is latched -- the first
154
- // to occur -- and it is never relabeled by a later signal (e.g. a cancel arriving after a deadline
155
- // already fired stays a timeout, not a cancellation).
156
- type StopCause = "cancelled" | "timeout" | "protocol";
157
-
158
- type Attempt = {
159
- causeOf: () => StopCause | undefined;
160
- stop: (cause: StopCause) => void;
161
- closed: Promise<{ code: number | null; exitSignal: NodeJS.Signals | null }>;
162
- dispose: () => void;
163
- };
164
-
165
- const DEFAULT_KILL_ESCALATION_MS = 5_000;
166
-
167
- // CLI adapters own their protocols; this shared runner owns process setup, diagnostics, and lifecycle.
168
- function startCliAttempt(
169
- command: string,
170
- args: string[],
171
- options: SpawnOptions,
172
- signal: AbortSignal,
173
- deadlineMs: number,
174
- killEscalationMs: number,
175
- ) {
176
- const child = spawn(command, args, { ...options, windowsHide: true, detached: process.platform !== "win32" });
177
- const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
178
- const diagnostics: { stderr: string; processError?: Error } = { stderr: "" };
179
- child.stderr?.setEncoding("utf8");
180
- child.stderr?.on("data", (chunk: string) => { diagnostics.stderr += chunk; });
181
- child.once("error", (error) => { diagnostics.processError = error; });
182
- return { child, attempt, diagnostics };
183
- }
184
-
185
- // Begins bounded lifecycle management for one already-spawned child: on cancellation, deadline, or
186
- // protocol failure it signals the whole POSIX process group (SIGTERM, then SIGKILL after
187
- // `killEscalationMs` if the child or a misbehaving grandchild ignores it). Windows only ever
188
- // reaches the immediate child directly -- there is no process-tree guarantee there.
189
- export function beginAttempt(child: ChildProcess, signal: AbortSignal, deadlineMs: number, killEscalationMs: number): Attempt {
190
- let cause: StopCause | undefined;
191
- let killTimer: ReturnType<typeof setTimeout> | undefined;
192
- let isClosed = false;
193
- let finishClose: (value: { code: number | null; exitSignal: NodeJS.Signals | null }) => void;
194
- const closed = new Promise<{ code: number | null; exitSignal: NodeJS.Signals | null }>((resolve) => {
195
- finishClose = (val) => {
196
- isClosed = true;
197
- resolve(val);
198
- };
199
- child.once("close", (code, exitSignal) => finishClose({ code, exitSignal }));
200
- });
201
-
202
- const stop = (next: StopCause) => {
203
- if (cause) return; // latched: the first stop cause wins
204
- cause = next;
205
- if (isClosed) return;
206
- killProcessGroup(child, "SIGTERM");
207
- killTimer = setTimeout(() => {
208
- killProcessGroup(child, "SIGKILL");
209
- // Detached descendants (or Windows grandchildren) may retain inherited pipes.
210
- // Stop waiting on those pipes after escalation; never promote this stop to success.
211
- child.stdin?.destroy();
212
- child.stdout?.destroy();
213
- child.stderr?.destroy();
214
- finishClose({ code: null, exitSignal: "SIGKILL" });
215
- }, killEscalationMs);
216
- killTimer.unref?.();
217
- };
218
-
219
- const onAbort = () => stop("cancelled");
220
- signal.addEventListener("abort", onAbort, { once: true });
221
- if (signal.aborted) onAbort();
222
-
223
- const deadlineTimer = setTimeout(() => stop("timeout"), deadlineMs);
224
- deadlineTimer.unref?.();
225
-
226
- const dispose = () => {
227
- signal.removeEventListener("abort", onAbort);
228
- clearTimeout(deadlineTimer);
229
- if (killTimer) clearTimeout(killTimer);
230
- };
231
-
232
- return { causeOf: () => cause, stop, closed, dispose };
233
- }
234
-
235
- type AgyEvent = {
236
- event?: string;
237
- conversation_id?: string;
238
- step_update?: { step_type?: string; text_delta?: unknown; tool_name?: unknown };
239
- result?: { status?: string; response?: unknown; error?: unknown; conversation_id?: string };
240
- };
241
-
242
- function parseExplainLine(line: string): { delta?: string; result?: string } {
243
- let event: AgyEvent;
244
- try {
245
- event = JSON.parse(line) as AgyEvent;
246
- } catch {
247
- throw new Error("Agy returned invalid streaming data.");
248
- }
249
- if (event.event === "step_update" && event.step_update?.step_type === "agent_response" && typeof event.step_update.text_delta === "string") {
250
- return { delta: event.step_update.text_delta };
251
- }
252
- if (event.event === "result") {
253
- if (event.result?.status !== "SUCCESS" || typeof event.result.response !== "string") {
254
- throw new Error("Agy did not complete the explanation successfully.");
255
- }
256
- return { result: event.result.response };
257
- }
258
- return {};
259
- }
260
-
261
- export function parseBtwAgyLine(line: string): { delta?: string; result?: string; conversationId?: string; error?: string; activity?: string } {
262
- let event: AgyEvent;
263
- try {
264
- event = JSON.parse(line) as AgyEvent;
265
- } catch {
266
- throw new Error("Agy returned invalid streaming data.");
267
- }
268
- const conversationId = event.conversation_id ?? event.result?.conversation_id;
269
- const stepType = event.step_update?.step_type;
270
- const tool = stepType === "agent_response" || stepType === "assistant" ? undefined : btwToolName(event.step_update?.tool_name);
271
- if (event.event === "step_update" && tool) {
272
- return { activity: tool, conversationId };
273
- }
274
- if (event.event === "step_update" && event.step_update?.step_type === "agent_response" && typeof event.step_update.text_delta === "string") {
275
- return { delta: event.step_update.text_delta, conversationId };
276
- }
277
- if (event.event === "result") {
278
- if (event.result?.status !== "SUCCESS" || typeof event.result.response !== "string") {
279
- const detail = typeof event.result?.error === "string" ? event.result.error : "Agy did not complete the turn successfully.";
280
- return { error: detail, conversationId };
281
- }
282
- return { result: event.result.response, conversationId };
283
- }
284
- return { conversationId };
285
- }
286
-
287
- // Every CLI adapter frames stdout immediately, awaits the process, then releases stop timers.
288
- // Keep this lifecycle in one place: adapter-specific parsing and exit rules stay in each adapter.
289
- async function finishCliAttempt(
290
- child: ChildProcess,
291
- attempt: Attempt,
292
- name: string,
293
- handleLine: (line: string) => void,
294
- ): Promise<{ code: number | null; exitSignal: NodeJS.Signals | null; protocolError?: string }> {
295
- const finishFraming = frameStdoutLines(child, attempt, name, handleLine);
296
- try {
297
- const { code, exitSignal } = await attempt.closed;
298
- return { code, exitSignal, protocolError: finishFraming() };
299
- } finally {
300
- attempt.dispose();
301
- }
302
- }
303
-
304
- /** Common stop/error precedence. Backend adapters only decide terminal protocol and success. */
305
- function stoppedCliOutcome(
306
- name: string,
307
- attempt: Attempt,
308
- finished: { code: number | null; exitSignal: NodeJS.Signals | null; protocolError?: string },
309
- diagnostics: { stderr: string; processError?: Error },
310
- timeoutMessage: string,
311
- partial?: string,
312
- ): BackendOutcome | undefined {
313
- const partialText = partial ? { partialText: partial } : {};
314
- if (attempt.causeOf() === "cancelled") return { status: "cancelled", message: "Canceled.", ...partialText };
315
- if (attempt.causeOf() === "timeout") return { status: "timeout", message: timeoutMessage, ...partialText };
316
- if (finished.protocolError) return { status: "failure", message: withDoctor(finished.protocolError), ...partialText };
317
- if (diagnostics.processError) return { status: "failure", message: processStartMessage(diagnostics.processError as NodeJS.ErrnoException, name) };
318
- if (finished.exitSignal || finished.code === null) {
319
- return { status: "failure", message: unexpectedSignalMessage(finished.exitSignal, name), ...partialText };
320
- }
321
- return undefined;
322
- }
323
-
324
- /** Session continuity is a shared BTW promise, even though CLIs report IDs differently. */
325
- function checkedBtwContinuation(
326
- name: "Claude" | "Grok" | "Codex" | "Muse",
327
- requested: BackendContinuation | undefined,
328
- observed: { id?: string; init?: string; result?: string },
329
- ): BackendContinuation | { error: string } {
330
- const id = observed.id ?? observed.result ?? observed.init;
331
- if (id && (!observed.init || observed.init === id) && (!requested || requested.id === id)) return { id };
332
- const details = "id" in observed ? `got ${observed.id ?? "none"}`
333
- : `init ${observed.init ?? "none"}, result ${observed.result ?? "none"}`;
334
- return { error: `${name} reported an inconsistent session id (expected ${requested?.id ?? "one id"}, ${details}).` };
335
- }
336
-
337
- /** Exit diagnostics share framing, while each backend still owns its prompt and protocol. */
338
- function cliExitFailure(name: "Claude" | "Grok" | "Codex" | "Muse", action: string, stderr: string): string {
339
- const detail = stderr.trim();
340
- if (detail) return `${name} could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`;
341
- const installation = {
342
- Claude: "Claude Code",
343
- Grok: "`grok`",
344
- Codex: "`codex`",
345
- Muse: "`muse`",
346
- }[name];
347
- return `${name} could not ${action}. Make sure ${installation} is installed and signed in, then run \`/bro doctor\`.`;
348
- }
349
-
350
- // Explain/show and BTW use argv for small prompts and stdin NDJSON for large
351
- // prompts; sandbox, cwd, timeout, and continuation semantics stay unchanged.
352
- async function executeArgvPrint(
353
- request: BackendRequest,
354
- selection: AgySelection,
355
- signal: AbortSignal,
356
- onProgress: BackendOnProgress | undefined,
357
- killEscalationMs: number,
358
- deadlineMs: number,
359
- ): Promise<BackendOutcome> {
360
- // Keep legacy CLI compatibility for small prompts; large inputs use the advisor's
361
- // stdin protocol rather than risking Linux's per-argument byte limit.
362
- const stdinPrompt = Buffer.byteLength(request.prompt, "utf8") >= 120_000;
363
- const isBtw = request.feature === "btw";
364
- const inspect = request.feature === "review";
365
- const full = request.access === "workspace-full";
366
- const printTimeout = full || inspect ? "10m" : "2m";
367
- const action = inspect ? "complete the guided review request" : isBtw ? "answer the side question" : "simplify the response";
368
- const timeoutVerb = inspect ? "during the guided review request" : isBtw ? "during the side conversation" : "while simplifying the response";
369
- const emptyTextMessage = inspect ? "Agy returned no response for Guided Review." : isBtw ? "Agy returned no answer for the side question." : "Agy returned no final explanation.";
370
-
371
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
372
-
373
- const runDirectory = full || inspect ? undefined : await mkdtemp(join(tmpdir(), "pi-bro-"));
374
- if (signal.aborted) {
375
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
376
- return { status: "cancelled", message: "Canceled." };
377
- }
378
-
379
- try {
380
- const { child, attempt, diagnostics } = startCliAttempt("agy",
381
- [
382
- ...(full ? ["--dangerously-skip-permissions"] : ["--sandbox"]),
383
- "--disable-slash-commands",
384
- "--output-format",
385
- "stream-json",
386
- "--model",
387
- selection.model,
388
- ...(selection.effort ? ["--effort", selection.effort] : []),
389
- "--print-timeout",
390
- printTimeout,
391
- ...(isBtw && request.continuation ? ["--conversation", request.continuation.id] : []),
392
- ...(stdinPrompt ? ["--input-format", "stream-json"] : ["--print", request.prompt]),
393
- ],
394
- {
395
- cwd: full || inspect ? request.cwd : runDirectory,
396
- stdio: [stdinPrompt ? "pipe" : "ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
397
-
398
- let partial = "";
399
- let final = "";
400
- let conversationId = request.continuation?.id;
401
-
402
- if (stdinPrompt) {
403
- child.stdin?.on("error", () => { /* Report early exits through the close/error path. */ });
404
- child.stdin?.end(`${JSON.stringify({ event: "user", message: { content: request.prompt } })}\n`);
405
- }
406
-
407
- const handleLine = (line: string) => {
408
- if (!line.trim() || attempt.causeOf()) return;
409
- if (isBtw) {
410
- const parsed = parseBtwAgyLine(line);
411
- if (parsed.conversationId) conversationId = parsed.conversationId;
412
- if (parsed.activity) onProgress?.({ kind: "activity", label: parsed.activity, timestamp: Date.now(), tool: parsed.activity });
413
- if (parsed.error) throw new Error(parsed.error);
414
- if (parsed.delta) {
415
- partial += parsed.delta;
416
- onProgress?.({ kind: "text", text: partial });
417
- }
418
- if (parsed.result !== undefined) final = parsed.result;
419
- } else {
420
- // Review-backed Grill receives tool events without changing review access.
421
- if (inspect && request.reportReviewTools) {
422
- const tool = parseBtwAgyLine(line).activity;
423
- if (tool) onProgress?.({ kind: "activity", label: tool, timestamp: Date.now(), tool });
424
- }
425
- const parsed = parseExplainLine(line);
426
- if (parsed.delta) {
427
- partial += parsed.delta;
428
- onProgress?.({ kind: "text", text: partial });
429
- }
430
- if (parsed.result !== undefined) final = parsed.result;
431
- }
432
- };
433
-
434
- const finished = await finishCliAttempt(child, attempt, "Agy", handleLine);
435
- const code = finished.code!;
436
- const stopped = stoppedCliOutcome("Agy", attempt, finished, diagnostics,
437
- `Agy timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
438
- if (stopped) return stopped;
439
- if (code !== 0) return { status: "failure", message: stdinPrompt && advisorFlagErrorHint(diagnostics.stderr)
440
- ? withDoctor("Large prompts require Agy 1.1.15+ with stdin support. Run `agy update`. " + diagnostics.stderr.trim())
441
- : agyFailureMessage(action, { code, killed: false, stderr: diagnostics.stderr }) };
442
-
443
- const text = final.trim();
444
- if (!text) return { status: "failure", message: withDoctor(diagnostics.stderr.trim() || emptyTextMessage) };
445
- return { status: "success", text, continuation: isBtw && conversationId ? { id: conversationId } : undefined };
446
- } finally {
447
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
448
- }
449
- }
450
-
451
- // Guards only against a single runaway line with no newline (a protocol break, not a real
452
- // response size) -- real NDJSON lines across all backends are far smaller than this.
453
- export const MAX_STDOUT_LINE_CHARS = 2_000_000;
454
-
455
- export function frameStdoutLines(
456
- child: ChildProcess,
457
- attempt: Attempt,
458
- backendName: string,
459
- onLine: (line: string) => void,
460
- ): () => string | undefined {
461
- const oversize = `${backendName} emitted a stdout line over ${MAX_STDOUT_LINE_CHARS} characters; the stream is unparseable.`;
462
- let buffer = "";
463
- let protocolError: string | undefined;
464
-
465
- const fail = (message: string) => {
466
- protocolError ??= message;
467
- buffer = "";
468
- attempt.stop("protocol");
469
- };
470
-
471
- child.stdout?.setEncoding("utf8");
472
-
473
- child.stdout?.on("error", (error) => {
474
- fail(`${backendName} stdout error: ${errorMessage(error)}`);
475
- });
476
-
477
- child.stdout?.on("data", (chunk: string) => {
478
- if (attempt.causeOf()) return;
479
- const parts = (buffer + chunk).split(/\r?\n/);
480
- buffer = parts.pop() ?? "";
481
-
482
- const pendingLen = buffer.endsWith("\r") ? buffer.length - 1 : buffer.length;
483
- if (pendingLen > MAX_STDOUT_LINE_CHARS || parts.some((line) => line.length > MAX_STDOUT_LINE_CHARS)) {
484
- return fail(oversize);
485
- }
486
-
487
- for (const line of parts) {
488
- if (attempt.causeOf()) return;
489
- if (!line.trim()) continue;
490
- try {
491
- onLine(line);
492
- } catch (error) {
493
- return fail(errorMessage(error));
494
- }
495
- }
496
- });
497
-
498
- return (): string | undefined => {
499
- if (!attempt.causeOf() && buffer.trim()) {
500
- const line = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
501
- if (line.length > MAX_STDOUT_LINE_CHARS) {
502
- fail(oversize);
503
- } else if (line.trim()) {
504
- try {
505
- onLine(line);
506
- } catch (error) {
507
- fail(errorMessage(error));
508
- }
509
- }
510
- }
511
- buffer = "";
512
- return protocolError;
513
- };
514
- }
515
-
516
- type AdvisorAgyEvent = {
517
- event?: string;
518
- step_update?: { tool_name?: unknown; step_type?: unknown; text_delta?: unknown };
519
- result?: { status?: unknown; response?: unknown; error?: unknown };
520
- };
521
-
522
- // Only a tool_name or a user-facing agent_response/assistant text_delta becomes an activity label
523
- // -- hidden reasoning/thinking step_types and any other shape stay unreported, never leaked into
524
- // progress.
525
- function advisorActivityFromEvent(event: AdvisorAgyEvent): string | undefined {
526
- if (event.event !== "step_update" || !event.step_update || typeof event.step_update !== "object") return undefined;
527
- const update = event.step_update;
528
- if (typeof update.tool_name === "string" && update.tool_name.trim()) return update.tool_name.trim();
529
- const isUserFacingText = update.step_type === "agent_response" || update.step_type === "assistant";
530
- if (isUserFacingText && typeof update.text_delta === "string" && update.text_delta.trim()) {
531
- return update.text_delta.split("\n").find((line) => line.trim())?.trim();
532
- }
533
- return undefined;
534
- }
535
-
536
- // Older agy CLIs reject --input-format with Go's flag-package usage dump and exit before running
537
- // the agent at all (no terminal result event). Turn that into an actionable version hint instead
538
- // of a bare "no terminal result" error.
539
- export function advisorFlagErrorHint(stderr: string): string | undefined {
540
- const match = /flags? provided but not defined: -([a-z0-9-]+)/i.exec(stderr);
541
- if (!match) return undefined;
542
- return `flag provided but not defined: -${match[1]} (installed Agy CLI is too old; the advisor needs Agy 1.1.15+ for --input-format stream-json — run \`agy update\`, then \`/bro doctor\`)`;
543
- }
544
-
545
- // Advisor speaks stdin NDJSON (never --print argv) and always runs fresh in the workspace with
546
- // tools auto-approved; it never resumes and never passes --conversation.
547
- async function executeAdvisorStdin(
548
- request: BackendRequest,
549
- selection: AgySelection,
550
- signal: AbortSignal,
551
- onProgress: BackendOnProgress | undefined,
552
- killEscalationMs: number,
553
- deadlineMs: number,
554
- ): Promise<BackendOutcome> {
555
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
556
-
557
- const { child, attempt, diagnostics } = startCliAttempt("agy",
558
- [
559
- "--dangerously-skip-permissions",
560
- "--disable-slash-commands",
561
- "--output-format",
562
- "stream-json",
563
- "--input-format",
564
- "stream-json",
565
- "--model",
566
- selection.model,
567
- ...(selection.effort ? ["--effort", selection.effort] : []),
568
- "--print-timeout",
569
- "10m",
570
- ],
571
- { cwd: request.cwd, stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
572
-
573
- let final: string | undefined;
574
- let terminalError: string | undefined;
575
- let sawTerminal = false;
576
-
577
- child.stdin?.on("error", () => {
578
- // agy exiting before it reads stdin is reported through the close/error path below.
579
- });
580
- child.stdin?.end(`${JSON.stringify({ event: "user", message: { content: request.prompt } })}\n`);
581
-
582
- const handleLine = (line: string) => {
583
- if (!line.trim() || sawTerminal || attempt.causeOf()) return;
584
- let event: AdvisorAgyEvent;
585
- try {
586
- event = JSON.parse(line) as AdvisorAgyEvent;
587
- } catch {
588
- throw new Error("Agy emitted invalid stream-json output.");
589
- }
590
- const activity = advisorActivityFromEvent(event);
591
- if (activity) {
592
- const step = event.step_update;
593
- const tool = step?.step_type === "agent_response" || step?.step_type === "assistant"
594
- ? undefined : btwToolName(step?.tool_name);
595
- onProgress?.({ kind: "activity", label: activity, timestamp: Date.now(), ...(tool ? { tool } : {}) });
596
- }
597
- if (event.event !== "result") return;
598
- sawTerminal = true;
599
- const result = event.result;
600
- const status = typeof result?.status === "string" ? result.status.trim().toUpperCase() : undefined;
601
- if (status === "SUCCESS" && typeof result?.response === "string") {
602
- final = result.response;
603
- } else {
604
- const detail = typeof result?.error === "string" && result.error.trim() ? `: ${result.error.trim()}` : "";
605
- terminalError = `Agy failed with status ${status ?? "(missing)"}${detail}`;
606
- }
607
- };
608
-
609
- const finished = await finishCliAttempt(child, attempt, "Agy", handleLine);
610
- const code = finished.code!;
611
- const stopped = stoppedCliOutcome("Agy", attempt, finished, diagnostics,
612
- "Agy timed out during the advisor consultation. Run `/bro doctor` for setup help.");
613
- if (stopped) return stopped;
614
- if (!sawTerminal) {
615
- const hint = advisorFlagErrorHint(diagnostics.stderr);
616
- return {
617
- status: "failure",
618
- message: withDoctor(hint ?? (diagnostics.stderr.trim() ? `Agy exited without a terminal result event: ${diagnostics.stderr.trim()}` : "Agy exited without a terminal result event.")),
619
- };
620
- }
621
- if (terminalError) return { status: "failure", message: withDoctor(terminalError) };
622
- if (code !== 0) return { status: "failure", message: agyFailureMessage("complete the advisor consultation", { code, killed: false, stderr: diagnostics.stderr }) };
623
-
624
- const text = final?.trim();
625
- if (!text) return { status: "failure", message: withDoctor(diagnostics.stderr.trim() || "Agy returned no advice.") };
626
- return { status: "success", text };
627
- }
628
-
629
- /**
630
- * Ask the official Codex app-server for the effective provider configuration.
631
- * This is the same Codex CLI, CODEX_HOME, and working directory used for exec.
632
- * A login status alone cannot detect custom provider env_key API billing.
633
- *
634
- * Inspection never makes a model request. Missing, unreadable or unsupported
635
- * app-server/config/read support fails closed when subscription is explicit.
636
- */
637
- // Codex 0.165.0 app-server starts an online catalog refresh on boot,
638
- // even if the only client method is config/read. Supply a disposable static
639
- // catalog for this *inspection process only* so the refresh worker cannot
640
- // contact a configured provider. The override does NOT select a provider,
641
- // change account credentials, or go into the real codex exec arguments.
642
- // The provider is still read from Codex's effective config for the same cwd.
643
- const CODEX_INSPECTION_CATALOG = {
644
- models: [{
645
- slug: "bro-config-inspection-only",
646
- display_name: "Bro configuration inspection only",
647
- description: "Local offline catalog; never used for inference",
648
- base_instructions: "Local configuration inspection only; never used for inference.",
649
- default_reasoning_level: "medium",
650
- supported_reasoning_levels: [{ effort: "medium", description: "medium" }],
651
- shell_type: "shell_command",
652
- visibility: "none",
653
- supported_in_api: true,
654
- priority: 0,
655
- support_verbosity: false,
656
- default_verbosity: null,
657
- apply_patch_tool_type: null,
658
- truncation_policy: { mode: "bytes", limit: 10_000 },
659
- experimental_supported_tools: [],
660
- }],
661
- };
662
-
663
- async function inspectCodexSubscriptionRoute(
664
- env: NodeJS.ProcessEnv, cwd: string | undefined, signal: AbortSignal,
665
- deadlineMs: number, killEscalationMs: number,
666
- ): Promise<BackendOutcome | undefined> {
667
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
668
- const probeDir = await mkdtemp(join(tmpdir(), "pi-bro-codex-inspect-"));
669
- try {
670
- const catalogPath = join(probeDir, "catalog.json");
671
- await writeFile(catalogPath, JSON.stringify(CODEX_INSPECTION_CATALOG), { mode: 0o600 });
672
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
673
- const { child, attempt, diagnostics } = startCliAttempt(
674
- "codex", ["-c", `model_catalog_json=${JSON.stringify(catalogPath)}`, "app-server"],
675
- { env, cwd, stdio: ["pipe", "pipe", "pipe"] },
676
- signal, Math.min(deadlineMs, 15_000), killEscalationMs,
677
- );
678
- let buffer = "";
679
- let decided = false;
680
- let finish: (problem: string | undefined) => void = () => {};
681
- const decision = new Promise<string | undefined>(resolve => { finish = resolve; });
682
- const settle = (problem: string | undefined) => {
683
- if (decided) return;
684
- decided = true;
685
- finish(problem);
686
- };
687
- const send = (value: object) => {
688
- if (decided || attempt.causeOf()) return;
689
- try { child.stdin?.write(JSON.stringify(value) + "\n"); }
690
- catch { settle("Codex app-server could not accept the configuration query"); }
691
- };
692
- // An app-server may close its input pipe while its buffered response is
693
- // still readable. The close race below decides whether the query succeeded.
694
- child.stdin?.on("error", () => {});
695
- child.stdout?.setEncoding("utf8");
696
- child.stdout?.on("data", (chunk: string) => {
697
- if (decided || attempt.causeOf()) return;
698
- buffer += chunk;
699
- if (buffer.length > 2_000_000) { settle("Codex returned an oversized configuration response"); return; }
700
- for (;;) {
701
- const index = buffer.indexOf("\n");
702
- if (index < 0) break;
703
- const line = buffer.slice(0, index);
704
- buffer = buffer.slice(index + 1);
705
- if (!line.trim()) continue;
706
- let message: Record<string, unknown>;
707
- try {
708
- message = JSON.parse(line) as Record<string, unknown>;
709
- } catch {
710
- settle("Codex app-server returned invalid JSON");
711
- return;
712
- }
713
- if (message.id === 0) {
714
- if (!message.result || message.error) {
715
- settle("Codex app-server initialization failed");
716
- return;
717
- }
718
- send({ method: "initialized", params: {} });
719
- send({ method: "config/read", id: 1, params: { includeLayers: false, ...(cwd ? { cwd } : {}) } });
720
- } else if (message.id === 1) {
721
- if (message.error || !message.result || typeof message.result !== "object") {
722
- settle("Codex app-server did not support config/read for this account/profile");
723
- return;
724
- }
725
- const config = (message.result as { config?: unknown }).config;
726
- settle(codexSubscriptionRouteProblem(config));
727
- return;
728
- }
729
- }
730
- });
731
- send({ method: "initialize", id: 0,
732
- params: { clientInfo: { name: "pi_bro", title: "Pi Bro", version: "0.36.1" } } });
733
- const result = await Promise.race([
734
- decision.then(problem => ({ kind: "decision" as const, problem })),
735
- attempt.closed.then(() => ({ kind: "closed" as const })),
736
- ]);
737
- // The probe is not a long-running provider connection.
738
- if (!attempt.causeOf()) attempt.stop("protocol");
739
- await attempt.closed;
740
- attempt.dispose();
741
- if (signal.aborted || attempt.causeOf() === "cancelled")
742
- return { status: "cancelled", message: "Canceled." };
743
- if (attempt.causeOf() === "timeout")
744
- return { status: "timeout", message: "Codex effective subscription configuration check timed out." };
745
- const problem = result.kind === "decision"
746
- ? result.problem
747
- : diagnostics.processError
748
- ? "Codex app-server could not start"
749
- : "Codex app-server closed without returning the effective configuration" +
750
- (diagnostics.stderr.trim() ? ": " + diagnostics.stderr.trim().slice(0, 700) : "");
751
- return problem
752
- ? { status: "failure", message: "Codex subscription selection is not safe: " + problem +
753
- ". 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." }
754
- : undefined;
755
- } finally {
756
- await rm(probeDir, { recursive: true, force: true });
757
- }
758
- }
759
-
760
- // Only a deliberate subscription choice gets an auth-method preflight.
761
- // CLI status is not proof of account identity or a paid model call.
762
- export async function verifyCliSubscription(
763
- backend: CliAuthBackend,
764
- env: NodeJS.ProcessEnv,
765
- signal: AbortSignal,
766
- killEscalationMs: number,
767
- deadlineMs: number,
768
- cwd?: string,
769
- ): Promise<BackendOutcome | undefined> {
770
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
771
- const label = backend === "claude" ? "Claude Code" : "Codex";
772
- const args = backend === "claude" ? ["auth", "status"] : ["login", "status"];
773
- const { child, attempt, diagnostics } = startCliAttempt(backend, args,
774
- { env, stdio: ["ignore", "pipe", "pipe"] },
775
- signal, Math.min(deadlineMs, 15_000), killEscalationMs);
776
- let stdout = "";
777
- child.stdout?.on("data", (chunk: Buffer) => {
778
- stdout = (stdout + chunk.toString()).slice(0, 32_768);
779
- });
780
- const { code, exitSignal } = await attempt.closed;
781
- attempt.dispose();
782
- if (attempt.causeOf() === "cancelled") return { status: "cancelled", message: "Canceled." };
783
- if (attempt.causeOf() === "timeout") return { status: "timeout", message: label + " subscription login check timed out." };
784
- if (diagnostics.processError)
785
- return { status: "failure", message: processStartMessage(diagnostics.processError as NodeJS.ErrnoException, label) };
786
- const status = backend === "codex" ? stdout + "\n" + diagnostics.stderr : stdout;
787
- if (code !== 0 || exitSignal || !isSubscriptionStatus(backend, status)) {
788
- const command = backend === "claude" ? "claude auth status" : "codex login status";
789
- const profile = backend === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
790
- return { status: "failure", message: label +
791
- " did not confirm subscription login in the selected profile. Run `" + command +
792
- "` with that " + profile + " and sign in to the intended subscription; Bro will not switch to API billing." };
793
- }
794
- return backend === "codex"
795
- ? inspectCodexSubscriptionRoute(env, cwd, signal, deadlineMs, killEscalationMs)
796
- : undefined;
797
- }
798
-
799
- type ClaudeEvent = {
800
- type?: unknown;
801
- subtype?: unknown;
802
- session_id?: unknown;
803
- is_error?: unknown;
804
- result?: unknown;
805
- parent_tool_use_id?: unknown;
806
- stop_reason?: unknown;
807
- terminal_reason?: unknown;
808
- event?: { type?: unknown; delta?: { type?: unknown; text?: unknown } };
809
- message?: { content?: unknown };
810
- };
811
-
812
- // Every Claude run uses --safe-mode, which disables CLAUDE.md, skills, plugins, hooks and MCP
813
- // servers but keeps the user's auth (--bare would break OAuth). The prompt goes over stdin.
814
- // explain/show run fresh and tool-less in a scratch cwd; advisor runs fresh in the caller's
815
- // workspace with tools auto-approved. btw persists its session (so `--resume` can continue it) and
816
- // always runs in the caller's workspace, since Claude stores sessions per cwd: restricted turns are
817
- // tool-less, full turns auto-approve tools, and one session resumes across both. Only the terminal
818
- // `result` event is authoritative; streamed text_delta events are progress only, and thinking is
819
- // dropped. btw requires init/result session ids to agree (and to equal the resumed id).
820
- async function executeClaude(
821
- request: BackendRequest,
822
- selection: { model: string; effort?: string },
823
- signal: AbortSignal,
824
- onProgress: BackendOnProgress | undefined,
825
- killEscalationMs: number,
826
- deadlineMs: number,
827
- ): Promise<BackendOutcome> {
828
- const isAdvisor = request.feature === "advisor";
829
- const isBtw = request.feature === "btw";
830
- const inspect = request.feature === "review";
831
- const full = request.access === "workspace-full";
832
- const action = request.feature === "review" ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
833
-
834
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
835
- const runDirectory = full || isBtw || inspect ? undefined : await mkdtemp(join(tmpdir(), "pi-bro-"));
836
- if (signal.aborted) {
837
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
838
- return { status: "cancelled", message: "Canceled." };
839
- }
840
-
841
- try {
842
- let auth: ReturnType<typeof resolveCliChildAuth>;
843
- try { auth = resolveCliChildAuth("claude"); }
844
- catch (error) { return { status: "failure", message: errorMessage(error) }; }
845
- if (auth.subscription) {
846
- const check = await verifyCliSubscription("claude", auth.env, signal, killEscalationMs, deadlineMs);
847
- if (check) return check;
848
- }
849
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
850
- const { child, attempt, diagnostics } = startCliAttempt("claude",
851
- [
852
- "-p",
853
- "--safe-mode",
854
- ...(isBtw ? [] : ["--no-session-persistence"]),
855
- "--disable-slash-commands",
856
- "--output-format",
857
- "stream-json",
858
- "--verbose",
859
- "--include-partial-messages",
860
- ...(inspect
861
- ? ["--restricted", "--tools", "Read,Grep,Glob", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--permission-mode", "dontAsk"]
862
- : full
863
- ? ["--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--dangerously-skip-permissions"]
864
- : ["--tools", "", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--permission-mode", "dontAsk"]),
865
- ...(isBtw && request.continuation ? ["--resume", request.continuation.id] : []),
866
- "--model",
867
- selection.model,
868
- ...(selection.effort ? ["--effort", selection.effort] : []),
869
- ],
870
- {
871
- cwd: runDirectory ?? request.cwd,
872
- stdio: ["pipe", "pipe", "pipe"], env: auth.env }, signal, deadlineMs, killEscalationMs);
873
-
874
- let partial = "";
875
- let final: string | undefined;
876
- let terminalError: string | undefined;
877
- let initSessionId: string | undefined;
878
- let resultSessionId: string | undefined;
879
-
880
- child.stdin?.on("error", () => {
881
- // claude exiting before it reads stdin is reported through the close/error path below.
882
- });
883
- child.stdin?.end(request.prompt);
884
-
885
- const handleLine = (line: string) => {
886
- if (!line.trim() || attempt.causeOf()) return;
887
- let event: ClaudeEvent;
888
- try {
889
- event = JSON.parse(line) as ClaudeEvent;
890
- } catch {
891
- throw new Error("Claude emitted invalid stream-json output.");
892
- }
893
- const topLevel = event.parent_tool_use_id === undefined || event.parent_tool_use_id === null;
894
- if (topLevel && event.type === "system" && event.subtype === "init" && typeof event.session_id === "string") initSessionId = event.session_id;
895
- if (!isAdvisor && topLevel && event.type === "stream_event" && event.event?.type === "content_block_delta") {
896
- const delta = event.event.delta;
897
- if (delta?.type === "text_delta" && typeof delta.text === "string" && delta.text) {
898
- partial += delta.text;
899
- onProgress?.({ kind: "text", text: partial });
900
- }
901
- }
902
- if ((isAdvisor || isBtw || (inspect && request.reportReviewTools)) && topLevel && event.type === "assistant" && Array.isArray(event.message?.content)) {
903
- for (const block of event.message.content as Array<{ type?: unknown; name?: unknown; text?: unknown }>) {
904
- if (attempt.causeOf()) break;
905
- if ((isBtw || (inspect && request.reportReviewTools)) && block?.type !== "tool_use") continue;
906
- const tool = block?.type === "tool_use" ? btwToolName(block.name) : undefined;
907
- const label =
908
- block?.type === "tool_use" && typeof block.name === "string"
909
- ? ((isBtw || (inspect && request.reportReviewTools)) ? tool : block.name.trim())
910
- : block?.type === "text" && typeof block.text === "string"
911
- ? block.text.split("\n").find((text) => text.trim())?.trim()
912
- : undefined;
913
- if (label) onProgress?.({ kind: "activity", label, timestamp: Date.now(), ...(tool ? { tool } : {}) });
914
- }
915
- }
916
- if (event.type !== "result" || !topLevel) return;
917
- if (typeof event.session_id === "string") resultSessionId = event.session_id;
918
- if (event.subtype === "success" && event.is_error === false && (event.stop_reason !== "end_turn" || (event.terminal_reason !== undefined && event.terminal_reason !== "completed"))) {
919
- terminalError ??= `Claude did not complete the answer (stop reason: ${String(event.stop_reason)}, terminal reason: ${String(event.terminal_reason)}).`;
920
- return;
921
- }
922
- // A result ends a model turn, not necessarily the stream; the first failure is latched and
923
- // otherwise the latest successful result wins once the process exits cleanly.
924
- if (event.subtype === "success" && event.is_error === false && typeof event.result === "string") {
925
- final = event.result;
926
- } else {
927
- const detail =
928
- typeof event.subtype === "string" && event.subtype !== "success"
929
- ? event.subtype
930
- : typeof event.result === "string" && event.result.trim()
931
- ? event.result.trim()
932
- : "turn failed";
933
- terminalError ??= `Claude failed: ${detail}`;
934
- }
935
- };
936
-
937
- const finished = await finishCliAttempt(child, attempt, "Claude", handleLine);
938
- const code = finished.code!;
939
- const stopped = stoppedCliOutcome("Claude", attempt, finished, diagnostics,
940
- `Claude timed out ${request.feature === "review" ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response"}. Run \`/bro doctor\` for setup help.`, partial);
941
- if (stopped) return stopped;
942
- const partialText = partial || undefined;
943
- if (terminalError) return { status: "failure", message: withDoctor(terminalError), partialText };
944
- if (code !== 0) return { status: "failure", message: cliExitFailure("Claude", action, diagnostics.stderr), partialText };
945
- if (final === undefined) {
946
- return { status: "failure", message: withDoctor(`Claude exited without a result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), partialText };
947
- }
948
- const text = final.trim();
949
- if (!text) return { status: "failure", message: withDoctor(request.feature === "review" ? "Claude returned no response for Guided Review." : isBtw ? "Claude returned no answer for the side question." : "Claude returned no final answer."), partialText };
950
- if (!isBtw) return { status: "success", text };
951
- const continuation = checkedBtwContinuation("Claude", request.continuation,
952
- { init: initSessionId, result: resultSessionId });
953
- if ("error" in continuation)
954
- return { status: "failure", message: withDoctor(continuation.error), partialText };
955
- return { status: "success", text, continuation };
956
- } finally {
957
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
958
- }
959
- }
960
-
961
- type GrokEvent = {
962
- permissionMode?: unknown;
963
- type?: unknown;
964
- subtype?: unknown;
965
- is_error?: unknown;
966
- result?: unknown;
967
- errors?: unknown;
968
- message?: unknown;
969
- parent_tool_use_id?: unknown;
970
- stop_reason?: unknown;
971
- session_id?: unknown;
972
- event?: { type?: unknown; delta?: { type?: unknown; text?: unknown } };
973
- };
974
-
975
- // Grok's "restricted" access is a request in the prompt, NOT technical enforcement: every Grok run
976
- // has all tools on (--sandbox off, bypassPermissions, subagents/web/scheduler available), so the
977
- // model can still read, write or reach out if it ignores this. The parent UI owns telling the user
978
- // that truthfully.
979
- export const GROK_RESTRICTED_PREFIX =
980
- "Bro restricted mode (a request, not a technical restriction): answer only from the context supplied in this prompt. " +
981
- "Do not inspect, read, or write workspace files, run commands, or use web or other external tools unless the user explicitly asks you to in this prompt.";
982
-
983
- // Grok runs explain, show, btw, and advisor with all capabilities on (--sandbox off,
984
- // bypassPermissions, no tool blacklist); Guided Review (`review`) runs in the caller's workspace
985
- // under Grok's read-only sandbox (--sandbox read-only, --permission-mode dontAsk).
986
- // explain/show run in a fresh mkdtemp scratch cwd removed afterwards (the Agy pattern);
987
- // btw (both accesses) runs in the caller's workspace cwd and continues natively with --resume, whose
988
- // session keeps the cwd it was created in; the advisor and review run fresh in the workspace.
989
- // Restricted requests other than review get GROK_RESTRICTED_PREFIX (review must be allowed to
990
- // inspect the captured checkout). The prompt goes through a private 0600 file in its own mkdtemp
991
- // directory, removed once the attempt ends.
992
- // Only a top-level terminal `result` with success/is_error false/end_turn is authoritative; the
993
- // first failure (a failed result or a top-level `error` event, even after a success) is latched.
994
- // Nested (subagent) frames are ignored. The advisor reports activity labels only; explain/show/btw/review
995
- // report top-level text_delta progress, falling back to an assistant message's text
996
- // blocks only when no delta streamed for it. Thinking is never reported. btw requires init/result
997
- // session ids to agree (and to equal the resumed id) and returns that id as the continuation.
998
- async function executeGrok(
999
- request: BackendRequest,
1000
- selection: { model: string; effort?: string },
1001
- signal: AbortSignal,
1002
- onProgress: BackendOnProgress | undefined,
1003
- killEscalationMs: number,
1004
- deadlineMs: number,
1005
- ): Promise<BackendOutcome> {
1006
- const isAdvisor = request.feature === "advisor";
1007
- const isBtw = request.feature === "btw";
1008
- const inspect = request.feature === "review";
1009
- const action = inspect ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
1010
- const timeoutVerb = inspect ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
1011
- const emptyTextMessage = inspect ? "Grok returned no response for Guided Review." : isAdvisor ? "Grok returned no advice." : isBtw ? "Grok returned no answer for the side question." : "Grok returned no final explanation.";
1012
- // Review inspects the captured checkout, so it must not carry the "do not inspect" restriction.
1013
- const prompt = request.access === "restricted" && !inspect ? `${GROK_RESTRICTED_PREFIX}\n\n${request.prompt}` : request.prompt;
1014
-
1015
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1016
- const promptDirectory = await mkdtemp(join(tmpdir(), "pi-bro-grok-"));
1017
- let runDirectory: string | undefined;
1018
- try {
1019
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1020
- const promptFile = join(promptDirectory, "prompt.txt");
1021
- await writeFile(promptFile, prompt, { encoding: "utf8", mode: 0o600 });
1022
- if (request.access !== "workspace-full" && !isBtw && !inspect) runDirectory = await mkdtemp(join(tmpdir(), "pi-bro-"));
1023
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1024
-
1025
- const { child, attempt, diagnostics } = startCliAttempt("grok",
1026
- [
1027
- // Review never auto-approves: dontAsk denies unpromptable asks instead of bypassing them. Unverified against a local grok CLI; an unsupported flag fails visibly rather than falling back to --sandbox off.
1028
- ...(inspect ? ["--sandbox", "read-only", "--permission-mode", "dontAsk"] : ["--sandbox", "off", "--permission-mode", "bypassPermissions"]),
1029
- "--output-format",
1030
- "streaming-messages-json",
1031
- "--include-partial-messages",
1032
- "--model", selection.model,
1033
- ...(selection.effort ? ["--reasoning-effort", selection.effort] : []),
1034
- ...(isBtw && request.continuation ? ["--resume", request.continuation.id] : []),
1035
- "--prompt-file",
1036
- promptFile,
1037
- ],
1038
- { cwd: runDirectory ?? request.cwd, stdio: ["ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
1039
-
1040
- let partial = "";
1041
- let streamedSinceAssistant = false;
1042
- let initSessionId: string | undefined;
1043
- let resultSessionId: string | undefined;
1044
- let final: string | undefined;
1045
- let terminalError: string | undefined;
1046
-
1047
- const handleLine = (line: string) => {
1048
- if (!line.trim() || attempt.causeOf()) return;
1049
- let event: GrokEvent;
1050
- try {
1051
- event = JSON.parse(line) as GrokEvent;
1052
- } catch {
1053
- throw new Error("Grok emitted invalid streaming-messages-json output.");
1054
- }
1055
- if (event.parent_tool_use_id !== undefined && event.parent_tool_use_id !== null) return;
1056
- if (event.type === "system" && event.subtype === "init") {
1057
- // Review asks for dontAsk, but `--sandbox read-only` in argv is the real boundary: another
1058
- // restricting mode is not a downgrade, and only auto-approval means the request was
1059
- // ignored. Both paths fail closed when the mode is missing, exactly like explain/btw.
1060
- const escalated = event.permissionMode === "bypassPermissions" || event.permissionMode === "always-approve";
1061
- if (inspect ? typeof event.permissionMode !== "string" || escalated : event.permissionMode !== "bypassPermissions") {
1062
- throw new Error(
1063
- `Grok did not apply the required ${inspect ? "restricted" : "bypassPermissions"} mode; check Grok policy/configuration.`,
1064
- );
1065
- }
1066
- if (typeof event.session_id === "string") initSessionId = event.session_id;
1067
- }
1068
- if (!isAdvisor && event.type === "stream_event" && event.event?.type === "content_block_delta") {
1069
- const delta = event.event.delta;
1070
- if (delta?.type === "text_delta" && typeof delta.text === "string" && delta.text) {
1071
- partial += delta.text;
1072
- streamedSinceAssistant = true;
1073
- onProgress?.({ kind: "text", text: partial });
1074
- }
1075
- }
1076
- if (event.type === "error") {
1077
- terminalError ??= `Grok error: ${typeof event.message === "string" && event.message.trim() ? event.message.trim() : "unknown error"}`;
1078
- return;
1079
- }
1080
- const message = event.message as { content?: unknown } | undefined;
1081
- if (!isAdvisor && event.type === "assistant" && Array.isArray(message?.content)) {
1082
- // Fallback only: an assistant message whose text already streamed as deltas is not re-appended.
1083
- if (!streamedSinceAssistant) {
1084
- const text = (message.content as Array<{ type?: unknown; text?: unknown }>)
1085
- .map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : ""))
1086
- .join("");
1087
- if (text) {
1088
- partial += text;
1089
- onProgress?.({ kind: "text", text: partial });
1090
- }
1091
- }
1092
- streamedSinceAssistant = false;
1093
- }
1094
- if ((isAdvisor || isBtw || (inspect && request.reportReviewTools)) && event.type === "assistant" && Array.isArray(message?.content)) {
1095
- for (const block of message.content as Array<{ type?: unknown; name?: unknown; text?: unknown }>) {
1096
- if (attempt.causeOf()) break;
1097
- if ((isBtw || (inspect && request.reportReviewTools)) && block?.type !== "tool_use") continue;
1098
- const tool = block?.type === "tool_use" ? btwToolName(block.name) : undefined;
1099
- const label =
1100
- block?.type === "tool_use" && typeof block.name === "string"
1101
- ? ((isBtw || (inspect && request.reportReviewTools)) ? tool : block.name.trim())
1102
- : block?.type === "text" && typeof block.text === "string"
1103
- ? block.text.split("\n").find((text) => text.trim())?.trim()
1104
- : undefined;
1105
- if (label) onProgress?.({ kind: "activity", label, timestamp: Date.now(), ...(tool ? { tool } : {}) });
1106
- }
1107
- }
1108
- if (event.type !== "result") return;
1109
- if (typeof event.session_id === "string") resultSessionId = event.session_id;
1110
- if (event.subtype === "success" && event.is_error === false) {
1111
- if (event.stop_reason !== "end_turn") {
1112
- terminalError ??= `Grok did not complete the ${isAdvisor ? "advice" : "answer"} (stop reason: ${String(event.stop_reason)}).`;
1113
- } else if (typeof event.result === "string") {
1114
- final = event.result;
1115
- } else {
1116
- terminalError ??= "Grok reported success without a final result.";
1117
- }
1118
- return;
1119
- }
1120
- const firstError = Array.isArray(event.errors)
1121
- ? event.errors.map((item) => (typeof item === "string" ? item : (item as { message?: unknown })?.message)).find((item) => typeof item === "string" && item.trim())
1122
- : undefined;
1123
- const detail =
1124
- typeof firstError === "string"
1125
- ? firstError.trim()
1126
- : typeof event.subtype === "string" && event.subtype !== "success"
1127
- ? event.subtype
1128
- : typeof event.result === "string" && event.result.trim()
1129
- ? event.result.trim()
1130
- : "turn failed";
1131
- terminalError ??= `Grok failed: ${detail}`;
1132
- };
1133
-
1134
- const finished = await finishCliAttempt(child, attempt, "Grok", handleLine);
1135
- const code = finished.code!;
1136
- const stopped = stoppedCliOutcome("Grok", attempt, finished, diagnostics,
1137
- `Grok timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
1138
- if (stopped) return stopped;
1139
- const partialText = partial ? { partialText: partial } : {};
1140
- if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
1141
- if (code !== 0) return { status: "failure", message: cliExitFailure("Grok", action, diagnostics.stderr), ...partialText };
1142
- if (final === undefined) {
1143
- return { status: "failure", message: withDoctor(`Grok exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
1144
- }
1145
- const text = final.trim();
1146
- if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
1147
- if (!isBtw) return { status: "success", text };
1148
- const continuation = checkedBtwContinuation("Grok", request.continuation,
1149
- { init: initSessionId, result: resultSessionId });
1150
- if ("error" in continuation)
1151
- return { status: "failure", message: withDoctor(continuation.error), ...partialText };
1152
- return { status: "success", text, continuation };
1153
- } finally {
1154
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
1155
- await rm(promptDirectory, { recursive: true, force: true });
1156
- }
1157
- }
1158
-
1159
- type CodexEvent = {
1160
- type?: unknown;
1161
- thread_id?: unknown;
1162
- item?: {
1163
- id?: unknown;
1164
- type?: unknown;
1165
- text?: unknown;
1166
- message?: unknown;
1167
- content?: unknown;
1168
- command?: unknown;
1169
- cmd?: unknown;
1170
- path?: unknown;
1171
- pattern?: unknown;
1172
- query?: unknown;
1173
- };
1174
- error?: { message?: unknown };
1175
- message?: unknown;
1176
- };
1177
-
1178
- function extractCodexItemText(item: CodexEvent["item"]): string | undefined {
1179
- if (!item) return undefined;
1180
- if (typeof item.text === "string") return item.text;
1181
- if (typeof item.message === "string") return item.message;
1182
- if (typeof item.content === "string") return item.content;
1183
- return undefined;
1184
- }
1185
-
1186
- function codexActivityFromEvent(event: CodexEvent): string | undefined {
1187
- const item = event.item;
1188
- if (!item || item.type === "reasoning") return undefined;
1189
- if (event.type === "item.started" || event.type === "item.completed") {
1190
- if (item.type !== "agent_message") {
1191
- const itemType = typeof item.type === "string" ? item.type : "item";
1192
- const candidate = [item.command, item.cmd, item.path, item.pattern, item.query]
1193
- .find((v) => typeof v === "string" && v.trim());
1194
- const preview = typeof candidate === "string" ? candidate.replace(/\s+/g, " ").trim() : "";
1195
- return `${itemType}${preview ? ` ${preview}` : ""}`;
1196
- }
1197
- if (item.type === "agent_message") {
1198
- const text = extractCodexItemText(item);
1199
- return text?.split("\n").find((line) => line.trim())?.trim();
1200
- }
1201
- }
1202
- return undefined;
1203
- }
1204
-
1205
- async function executeCodex(
1206
- request: BackendRequest,
1207
- selection: { model: string; effort?: string },
1208
- signal: AbortSignal,
1209
- onProgress: BackendOnProgress | undefined,
1210
- killEscalationMs: number,
1211
- deadlineMs: number,
1212
- ): Promise<BackendOutcome> {
1213
- const isAdvisor = request.feature === "advisor";
1214
- const isBtw = request.feature === "btw";
1215
- const inspect = request.feature === "review";
1216
- const full = request.access === "workspace-full";
1217
- const action = inspect ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
1218
- const timeoutVerb = inspect ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
1219
- const emptyTextMessage = inspect ? "Codex returned no response for Guided Review." : isAdvisor ? "Codex returned no advice." : isBtw ? "Codex returned no answer for the side question." : "Codex returned no final explanation.";
1220
-
1221
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1222
- const runDirectory = full || isBtw || inspect ? undefined : await mkdtemp(join(tmpdir(), "pi-bro-"));
1223
- if (signal.aborted) {
1224
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
1225
- return { status: "cancelled", message: "Canceled." };
1226
- }
1227
-
1228
- try {
1229
- let auth: ReturnType<typeof resolveCliChildAuth>;
1230
- try { auth = resolveCliChildAuth("codex"); }
1231
- catch (error) { return { status: "failure", message: errorMessage(error) }; }
1232
- if (auth.subscription) {
1233
- const check = await verifyCliSubscription("codex", auth.env, signal, killEscalationMs, deadlineMs, runDirectory ?? request.cwd);
1234
- if (check) return check;
1235
- }
1236
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1237
- const permissionArgs = full ? ["--dangerously-bypass-approvals-and-sandbox"] : ["--sandbox", "read-only"];
1238
- const resume = isBtw && request.continuation;
1239
- const args = [
1240
- "exec",
1241
- ...(auth.subscription ? ["-c", 'forced_login_method="chatgpt"', "-c", 'model_provider="openai"'] : []),
1242
- ...permissionArgs,
1243
- ...(resume ? ["resume"] : []),
1244
- "--json",
1245
- "--skip-git-repo-check",
1246
- ...(!isBtw ? ["--ephemeral"] : []),
1247
- "--model",
1248
- selection.model,
1249
- ...(selection.effort ? ["-c", `model_reasoning_effort="${selection.effort}"`] : []),
1250
- ...(resume ? [request.continuation!.id, "-"] : ["--", "-"]),
1251
- ];
1252
-
1253
- const { child, attempt, diagnostics } = startCliAttempt("codex", args, {
1254
- cwd: runDirectory ?? request.cwd,
1255
- stdio: ["pipe", "pipe", "pipe"], env: auth.env }, signal, deadlineMs, killEscalationMs);
1256
-
1257
- let partial = "";
1258
- let threadId: string | undefined;
1259
- let final: string | undefined;
1260
- let sawTerminal = false;
1261
- let terminalError: string | undefined;
1262
-
1263
- child.stdin?.on("error", () => {
1264
- // codex exiting before reading stdin is reported through the close/error path.
1265
- });
1266
- child.stdin?.end(request.prompt);
1267
-
1268
- const handleLine = (line: string) => {
1269
- if (!line.trim() || attempt.causeOf()) return;
1270
- let event: CodexEvent;
1271
- try {
1272
- event = JSON.parse(line) as CodexEvent;
1273
- } catch {
1274
- throw new Error("Codex emitted invalid JSON output.");
1275
- }
1276
- if (event.type === "thread.started" && typeof event.thread_id === "string") {
1277
- threadId = event.thread_id;
1278
- }
1279
- if (event.type === "error") {
1280
- terminalError ??= `Codex error: ${typeof event.message === "string" && event.message.trim() ? event.message.trim() : "unknown error"}`;
1281
- return;
1282
- }
1283
- if (event.type === "turn.failed") {
1284
- sawTerminal = true;
1285
- const err = event.error as { message?: unknown } | undefined;
1286
- terminalError ??= `Codex failed: ${typeof err?.message === "string" && err.message.trim() ? err.message.trim() : "turn failed"}`;
1287
- return;
1288
- }
1289
- if (event.type === "turn.completed") {
1290
- sawTerminal = true;
1291
- return;
1292
- }
1293
- const item = event.item;
1294
- if ((isAdvisor || isBtw || (inspect && request.reportReviewTools)) && (event.type === "item.started" || event.type === "item.completed")) {
1295
- const tool = item?.type !== "agent_message" && item?.type !== "reasoning" ? btwToolName(item?.type) : undefined;
1296
- const activity = (isBtw || (inspect && request.reportReviewTools)) ? tool : codexActivityFromEvent(event);
1297
- if (activity) onProgress?.({ kind: "activity", label: activity, timestamp: Date.now(), ...(tool ? { tool } : {}) });
1298
- }
1299
- if (event.type === "item.completed" && item?.type === "agent_message") {
1300
- const text = extractCodexItemText(item);
1301
- if (text !== undefined) {
1302
- final = text;
1303
- if (!isAdvisor) {
1304
- partial += `${partial ? "\n\n" : ""}${text}`;
1305
- onProgress?.({ kind: "text", text: partial });
1306
- }
1307
- }
1308
- }
1309
- };
1310
-
1311
- const finished = await finishCliAttempt(child, attempt, "Codex", handleLine);
1312
- const code = finished.code!;
1313
- const stopped = stoppedCliOutcome("Codex", attempt, finished, diagnostics,
1314
- `Codex timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
1315
- if (stopped) return stopped;
1316
- const partialText = partial ? { partialText: partial } : {};
1317
- if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
1318
- if (code !== 0) return { status: "failure", message: cliExitFailure("Codex", action, diagnostics.stderr), ...partialText };
1319
- if (!sawTerminal) {
1320
- return { status: "failure", message: withDoctor(`Codex exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
1321
- }
1322
- const text = final?.trim();
1323
- if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
1324
- if (!isBtw) return { status: "success", text };
1325
- const continuation = checkedBtwContinuation("Codex", request.continuation, { id: threadId });
1326
- if ("error" in continuation)
1327
- return { status: "failure", message: withDoctor(continuation.error), ...partialText };
1328
- return { status: "success", text, continuation };
1329
- } finally {
1330
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
1331
- }
1332
- }
1333
-
1334
- type MuseEnvelope = {
1335
- schema_version?: unknown;
1336
- payload_type?: unknown;
1337
- stream?: { kind?: unknown; id?: unknown };
1338
- payload?: {
1339
- kind?: unknown;
1340
- command_id?: unknown;
1341
- run_stream?: { kind?: unknown; id?: unknown };
1342
- text?: unknown;
1343
- reason?: unknown;
1344
- correlation_facts?: { tool_name?: unknown };
1345
- event?: { message?: unknown };
1346
- command?: unknown;
1347
- path?: unknown;
1348
- file_path?: unknown;
1349
- query?: unknown;
1350
- };
1351
- };
1352
-
1353
- async function executeMuse(
1354
- request: BackendRequest,
1355
- selection: { model: string; effort?: string },
1356
- signal: AbortSignal,
1357
- onProgress: BackendOnProgress | undefined,
1358
- killEscalationMs: number,
1359
- deadlineMs: number,
1360
- ): Promise<BackendOutcome> {
1361
- const isAdvisor = request.feature === "advisor";
1362
- const isBtw = request.feature === "btw";
1363
- const inspect = request.feature === "review";
1364
- const full = request.access === "workspace-full";
1365
- const action = request.feature === "review" ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
1366
- const timeoutVerb = request.feature === "review" ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
1367
- const emptyTextMessage = request.feature === "review" ? "Muse returned no response for Guided Review." : isAdvisor ? "Muse returned no advice." : isBtw ? "Muse returned no answer for the side question." : "Muse returned no final explanation.";
1368
-
1369
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1370
- const promptDirectory = await mkdtemp(join(tmpdir(), "pi-bro-muse-"));
1371
- let runDirectory: string | undefined;
1372
-
1373
- try {
1374
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1375
- const promptFile = join(promptDirectory, "prompt.txt");
1376
- await writeFile(promptFile, request.prompt, { encoding: "utf8", mode: 0o600 });
1377
- if (!full && !isBtw && !inspect) runDirectory = await mkdtemp(join(tmpdir(), "pi-bro-"));
1378
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1379
- const workspace = runDirectory ?? request.cwd!;
1380
-
1381
- const args = [
1382
- "exec",
1383
- "--json",
1384
- "--provider", "meta",
1385
- "--workspace", workspace,
1386
- ...(!isBtw ? ["--no-session-log"] : []),
1387
- ...(full ? ["--yolo"] : ["--disable-approval", "--disable-write", "--disable-shell"]),
1388
- ...(inspect ? ["--disable-web-tools", "--no-foreign-personal-context"] : []),
1389
- ...(isBtw && request.continuation ? ["--session-id", request.continuation.id] : []),
1390
- "--model", selection.model,
1391
- ...(selection.effort ? ["--reasoning-effort", selection.effort] : []),
1392
- "--prompt-file", promptFile,
1393
- ];
1394
-
1395
- const { child, attempt, diagnostics } = startCliAttempt("muse", args, {
1396
- cwd: workspace,
1397
- stdio: ["ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
1398
-
1399
- let partial = "";
1400
- let rootCommandId: string | undefined;
1401
- let rootRunId: string | undefined;
1402
- let sessionId: string | undefined;
1403
- let final: string | undefined;
1404
- let sawTerminal = false;
1405
- let terminalError: string | undefined;
1406
-
1407
- const handleLine = (line: string) => {
1408
- if (!line.trim() || attempt.causeOf()) return;
1409
- let envelope: MuseEnvelope;
1410
- try {
1411
- envelope = JSON.parse(line) as MuseEnvelope;
1412
- } catch {
1413
- throw new Error("Muse emitted invalid JSON output.");
1414
- }
1415
- const payload = envelope.payload;
1416
- if (envelope.stream?.kind === "session" && typeof envelope.stream.id === "string") {
1417
- if (!sessionId) sessionId = envelope.stream.id;
1418
- }
1419
- if (envelope.payload_type === "runtime.command.accepted") {
1420
- if (!rootCommandId && typeof payload?.command_id === "string") {
1421
- rootCommandId = payload.command_id;
1422
- }
1423
- return;
1424
- }
1425
- if (!rootRunId && (envelope.payload_type === "session.run.linked" || envelope.payload_type === "run.lifecycle.started")) {
1426
- const runStream = payload?.run_stream;
1427
- if (runStream?.kind === "run" && typeof runStream.id === "string") {
1428
- if (rootCommandId === undefined || payload?.command_id === rootCommandId) {
1429
- rootRunId = runStream.id;
1430
- if (envelope.stream?.kind === "session" && typeof envelope.stream.id === "string") {
1431
- sessionId = envelope.stream.id;
1432
- }
1433
- }
1434
- }
1435
- return;
1436
- }
1437
- const runStream = payload?.run_stream;
1438
- const isRoot = rootRunId !== undefined && runStream?.kind === "run" && runStream.id === rootRunId;
1439
-
1440
- if (isAdvisor || isBtw || (inspect && request.reportReviewTools)) {
1441
- if (envelope.payload_type === "tool.result") {
1442
- const facts = payload?.correlation_facts as { tool_name?: unknown } | undefined;
1443
- const toolName = typeof facts?.tool_name === "string" && facts.tool_name ? facts.tool_name : "tool";
1444
- const candidate = [payload?.text, payload?.command, payload?.path, payload?.file_path, payload?.query]
1445
- .find((v) => typeof v === "string" && v.trim());
1446
- const preview = typeof candidate === "string" ? candidate.replace(/\s+/g, " ").trim() : "";
1447
- const tool = btwToolName(toolName);
1448
- const label = (isBtw || (inspect && request.reportReviewTools)) ? tool : `${toolName}${preview ? ` ${preview}` : ""}`;
1449
- if (label) onProgress?.({ kind: "activity", label, timestamp: Date.now(), ...(tool ? { tool } : {}) });
1450
- } else if (isAdvisor && envelope.payload_type === "task.lifecycle.status") {
1451
- const event = payload?.event as { message?: unknown } | undefined;
1452
- if (typeof event?.message === "string" && event.message.trim()) {
1453
- onProgress?.({ kind: "activity", label: event.message.trim(), timestamp: Date.now() });
1454
- }
1455
- }
1456
- }
1457
- if (!isAdvisor && isRoot && envelope.payload_type === "run.output.delta") {
1458
- if (typeof payload?.text === "string" && payload.text) {
1459
- partial += payload.text;
1460
- onProgress?.({ kind: "text", text: partial });
1461
- }
1462
- }
1463
-
1464
- if (!isRoot) return;
1465
- if (envelope.payload_type === "run.terminal.completed") {
1466
- sawTerminal = true;
1467
- if (typeof payload?.text === "string") {
1468
- final = payload.text;
1469
- }
1470
- } else if (envelope.payload_type === "run.terminal.failed") {
1471
- sawTerminal = true;
1472
- const reason = typeof payload?.reason === "string" && payload.reason.trim() ? payload.reason.trim() : "run did not complete";
1473
- terminalError ??= `Muse failed: ${reason}`;
1474
- }
1475
- };
1476
-
1477
- const finished = await finishCliAttempt(child, attempt, "Muse", handleLine);
1478
- const code = finished.code!;
1479
- const stopped = stoppedCliOutcome("Muse", attempt, finished, diagnostics,
1480
- `Muse timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
1481
- if (stopped) return stopped;
1482
- const partialText = partial ? { partialText: partial } : {};
1483
- if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
1484
- if (code !== 0) return { status: "failure", message: cliExitFailure("Muse", action, diagnostics.stderr), ...partialText };
1485
- if (!sawTerminal) {
1486
- return { status: "failure", message: withDoctor(`Muse exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
1487
- }
1488
- const text = final?.trim();
1489
- if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
1490
- if (!isBtw) return { status: "success", text };
1491
- const continuation = checkedBtwContinuation("Muse", request.continuation, { id: sessionId });
1492
- if ("error" in continuation)
1493
- return { status: "failure", message: withDoctor(continuation.error), ...partialText };
1494
- return { status: "success", text, continuation };
1495
- } finally {
1496
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
1497
- await rm(promptDirectory, { recursive: true, force: true });
1498
- }
1499
- }
1500
-
1501
- // ----------------------------------------------------------------------------
1502
- // In-process Pi SDK backend ("pi")
1503
- //
1504
- // Runs a real AgentSession inside this process instead of spawning a CLI. It is deliberately
1505
- // isolated from the host session: its own resource loader (no extensions, skills, prompt
1506
- // templates, themes or context files), its own SettingsManager with auto-retry and compaction
1507
- // switched off in memory, and an explicit tool allowlist per feature. The host model registry is
1508
- // rehydrated into a fresh ModelRuntime so in-memory provider registrations and runtime keys
1509
- // (e.g. OAuth shorthand) still resolve, exactly as a spawned subagent would.
1510
- // ----------------------------------------------------------------------------
1511
-
1512
- // Host-side dependencies the CLI adapters get for free from their process environment. Optional so
1513
- // offline tests (and callers with no registry) still compile; a missing registry fails loudly at
1514
- // model-resolution time rather than silently in the registry.
1515
- // The host facts the in-process Pi backend needs. `scopedModels` carries a `provider/model:high`
1516
- // pattern's thinking level, which createAgentSession cannot recover on its own, and
1517
- // `isProjectTrusted` decides whether the workspace's `.pi/settings.json` may apply.
1518
- export type PiHostContext = Pick<ExtensionContext, "modelRegistry" | "scopedModels"> & {
1519
- model?: ExtensionContext["model"];
1520
- isProjectTrusted?: () => boolean;
1521
- };
1522
-
1523
- // The most recent host context Bro saw (set by /bro commands and the advisor tool). A module-level
1524
- // binding, like pi-flow-external's execution context, keeps the host registry reachable from the
1525
- // shared feature helpers without threading it through every call site; Bro runs one host session
1526
- // at a time.
1527
- let currentPiHost: PiHostContext | undefined;
1528
-
1529
- export function setPiHostContext(host: PiHostContext | undefined): void {
1530
- currentPiHost = host;
1531
- }
1532
-
1533
- export function getPiHostContext(): PiHostContext | undefined {
1534
- return currentPiHost;
1535
- }
1536
-
1537
- const PI_EXCLUDED_TOOLS = ["bro_advisor", "external_delegate", "external_workflow", "mcp__*"];
1538
-
1539
- /** Tools a Pi session may use for a given feature/access pair. Empty means "no tools at all". */
1540
- export function piToolAllowlist(feature: BackendFeature, access: BackendAccess): { tools: string[]; excludeTools?: string[] } {
1541
- if (feature === "advisor" || access === "workspace-full") {
1542
- return { tools: ["read", "bash", "edit", "write"], excludeTools: [...PI_EXCLUDED_TOOLS] };
1543
- }
1544
- if (feature === "review") return { tools: ["read", "grep", "find", "ls"] };
1545
- // explain, show, elevate and restricted btw only ever see the prompt.
1546
- return { tools: [] };
1547
- }
1548
-
1549
- // The thinking level a scoped model pattern asked for (e.g. "provider/model:high"), if any. Only
1550
- // used when the Bro effort is "default": an explicit Bro effort must win, because it is the user's
1551
- // current choice. Verified against the SDK: createAgentSession does not derive thinkingLevel from
1552
- // scopedModels, so a `:thinking` suffix would otherwise be silently dropped.
1553
- export function piScopedThinkingLevel(
1554
- scoped: readonly { model: { provider: string; id: string }; thinkingLevel?: string }[] | undefined,
1555
- providerId: string,
1556
- modelId: string,
1557
- ): string | undefined {
1558
- return scoped?.find((entry) => entry.model.provider === providerId && entry.model.id === modelId)?.thinkingLevel;
1559
- }
1560
-
1561
- /** The physical model a stored `pi` selection names, or undefined when it is unknown/virtual. */
1562
- export function piPhysicalModel(
1563
- registry: PiHostContext["modelRegistry"] | ModelRuntime | undefined,
1564
- providerId: string,
1565
- modelId: string,
1566
- ): PiPhysicalModel | undefined {
1567
- if (!registry || !providerId || !modelId) return undefined;
1568
- const model = "find" in registry ? registry.find(providerId, modelId) : registry.getModel(providerId, modelId);
1569
- if (!model) return undefined;
1570
- // Virtual models route to another model at request time; a spawned-style child needs a physical one.
1571
- if ((model as { api?: string }).api === "pi-virtual") return undefined;
1572
- return model as PiPhysicalModel;
1573
- }
1574
-
1575
- /** Splits a stored Pi model string on the FIRST "/" only, so IDs containing slashes survive. */
1576
- export function splitPiModel(model: string): { providerId: string; modelId: string } | undefined {
1577
- const separator = model.indexOf("/");
1578
- if (separator <= 0 || separator === model.length - 1) return undefined;
1579
- return { providerId: model.slice(0, separator), modelId: model.slice(separator + 1) };
1580
- }
1581
-
1582
- // The shape both a Pi registry entry and a resolved scoped model present for effort clamping.
1583
- export type PiPhysicalModel = PiAiModel<string> | { reasoning?: boolean; thinkingLevelMap?: unknown };
1584
-
1585
- // The requested and effective Pi effort for a model. "default" is resolved by the SDK from settings
1586
- // (and any scoped `:thinking` suffix), so it is reported as such rather than guessed at. Used by
1587
- // `/bro doctor` so its clamp claim is computed rather than assumed.
1588
- export function piEffectiveEffort(model: PiPhysicalModel | undefined, effort: string): string {
1589
- if (!model) return effort;
1590
- return piClampEffort(model, effort);
1591
- }
1592
-
1593
- // Why a Pi attempt stopped, latched first-wins exactly like beginAttempt's StopCause.
1594
- type PiStopCause = "cancelled" | "timeout";
1595
-
1596
- // The terminal stop reasons pi-ai can report. Anything other than "stop" means the turn did not
1597
- // finish normally, so it must not be reported as a complete answer. "toolUse" only appears on an
1598
- // intermediate turn, so a *final* assistant message carrying it is also incomplete.
1599
- const PI_INCOMPLETE_STOP_REASONS = new Set(["length", "pending", "deferred", "toolUse"]);
1600
-
1601
- // Our own levels (plus "default") are a superset of pi-ai's, and "default" is resolved by the SDK
1602
- // from settings per model, so it cannot be clamped here.
1603
- function piClampEffort(model: PiPhysicalModel | undefined, effort: string): string {
1604
- if (effort === "default" || !model) return effort;
1605
- try {
1606
- return clampThinkingLevel(model as never, effort as never) as string;
1607
- } catch {
1608
- return effort;
1609
- }
1610
- }
1611
-
1612
- // In-memory btw sessions, keyed by the session id handed back as a continuation id. Nothing here
1613
- // ever reaches the filesystem: btw side conversations must not appear in ~/.pi/agent/sessions.
1614
- const piBtwSessions = new Map<string, SessionEntry[]>();
1615
- const PI_BTW_SESSIONS_MAX = 20;
1616
-
1617
- function rememberPiBtwSession(sessionId: string, entries: SessionEntry[]): void {
1618
- piBtwSessions.delete(sessionId);
1619
- piBtwSessions.set(sessionId, entries);
1620
- while (piBtwSessions.size > PI_BTW_SESSIONS_MAX) {
1621
- const oldest = piBtwSessions.keys().next().value;
1622
- if (oldest === undefined) break;
1623
- piBtwSessions.delete(oldest);
1624
- }
1625
- }
1626
-
1627
- function piErrorMessage(feature: BackendFeature, message: string): string {
1628
- const action =
1629
- feature === "review"
1630
- ? "complete the guided review request"
1631
- : feature === "advisor"
1632
- ? "complete the advisor consultation"
1633
- : feature === "btw"
1634
- ? "answer the side question"
1635
- : "simplify the response";
1636
- return `Pi could not ${action}: ${message}`;
1637
- }
1638
-
1639
- function piTimeoutMessage(feature: BackendFeature, seconds: number): string {
1640
- const during =
1641
- feature === "review"
1642
- ? "during the guided review request"
1643
- : feature === "advisor"
1644
- ? "during the advisor consultation"
1645
- : feature === "btw"
1646
- ? "during the side conversation"
1647
- : "while simplifying the response";
1648
- return `Pi timed out ${during} after ${Math.round(seconds / 1000)}s. Run \`/bro doctor\` for setup help.`;
1649
- }
1650
-
1651
- function piAssistantText(message: { content?: unknown }): string {
1652
- const content = message.content;
1653
- if (!Array.isArray(content)) return "";
1654
- return content
1655
- .map((part) => (part && typeof part === "object" && (part as { type?: string }).type === "text" ? String((part as { text?: unknown }).text ?? "") : ""))
1656
- .join("")
1657
- .trim();
1658
- }
1659
-
1660
- /**
1661
- * The Pi SDK asks for a ModelRuntime even when its physical model is explicit.
1662
- * Bind every auth/model/stream read to the host's existing registry instead of
1663
- * rebuilding a second provider from models.json. In particular, an on-disk edit
1664
- * must never combine a host-old endpoint with a freshly read API key.
1665
- *
1666
- * The SDK runtime here only supplies agent/session mechanics; it does not own
1667
- * credentials, source selection or refresh. No models.json is read by this child.
1668
- */
1669
- async function bridgePiModelRuntime(host: PiHostContext | undefined, _agentDir: string): Promise<ModelRuntime> {
1670
- const registry = host?.modelRegistry;
1671
- if (!registry) throw new Error("The Pi host model registry is unavailable; reopen Bro from a live Pi session.");
1672
- // The SDK requires a ModelRuntime, but it must not read an independent auth.json
1673
- // or models.json. All real auth and model calls below delegate to the host.
1674
- const credentials = {
1675
- read: async () => undefined,
1676
- list: async () => [],
1677
- modify: async (): Promise<never> => { throw new Error("The Pi host owns credential writes."); },
1678
- delete: async (): Promise<never> => { throw new Error("The Pi host owns credential deletion."); },
1679
- };
1680
- const runtime = await ModelRuntime.create({
1681
- credentials,
1682
- modelsPath: null,
1683
- refreshOnCreate: false,
1684
- });
1685
- const models = (provider?: string) => registry.getAll().filter((m) => !provider || m.provider === provider);
1686
- const available = (provider?: string) => registry.getAvailable().filter((m) => !provider || m.provider === provider);
1687
- // Use the same registry for the SDK's preflight, model lookup and final stream.
1688
- // Resolving auth from provider alone is intentional: ModelRegistry.getProviderAuth()
1689
- // is the public host API, and its underlying runtime still applies model-specific
1690
- // headers and request overrides inside streamSimple().
1691
- Object.assign(runtime, {
1692
- getModel: (provider: string, id: string) => registry.find(provider, id),
1693
- getModels: models,
1694
- getAllModels: models,
1695
- getAvailableSnapshot: () => available(),
1696
- getAvailable: async (provider?: string) => available(provider),
1697
- getProvider: (provider: string) => registry.getProvider(provider),
1698
- getProviderAuthStatus: (provider: string) => registry.getProviderAuthStatus(provider),
1699
- getAuth: async (modelOrProvider: string | { provider: string }) =>
1700
- registry.getProviderAuth(typeof modelOrProvider === "string" ? modelOrProvider : modelOrProvider.provider),
1701
- hasConfiguredAuth: (provider: string) => models(provider).some((model) => registry.hasConfiguredAuth(model)),
1702
- checkAuth: async (provider: string) =>
1703
- (await registry.getProviderAuth(provider)) ? { type: "api_key", source: "host registry" } : undefined,
1704
- isUsingOAuth: (provider: string) => models(provider).some((model) => registry.isUsingOAuth(model)),
1705
- streamSimple: (
1706
- model: Parameters<ModelRuntime["streamSimple"]>[0],
1707
- context: Parameters<ModelRuntime["streamSimple"]>[1],
1708
- options: Parameters<ModelRuntime["streamSimple"]>[2],
1709
- ) => {
1710
- // Neither another runtime nor child options may override the host's auth.
1711
- const { apiKey: _key, env: _env, ...rest } = options ?? {};
1712
- return registry.streamSimple(model, context, rest);
1713
- },
1714
- });
1715
- return runtime;
1716
- }
1717
-
1718
- /** The picker and the executor use this same host-backed model/auth view. */
1719
- export async function bridgePiRuntimeForCatalog(host: PiHostContext | undefined, agentDir: string): Promise<ModelRuntime> {
1720
- return bridgePiModelRuntime(host, agentDir);
1721
- }
1722
-
1723
- async function executePi(
1724
- request: BackendRequest,
1725
- selection: { model: string; effort?: string },
1726
- signal: AbortSignal,
1727
- onProgress: BackendOnProgress | undefined,
1728
- killEscalationMs: number,
1729
- deadlineMs: number,
1730
- host: PiHostContext | undefined,
1731
- createSession: typeof createAgentSession = createAgentSession,
1732
- ): Promise<BackendOutcome> {
1733
- void killEscalationMs; // in-process: abort() is cooperative, there is no process group to kill
1734
- const parts = splitPiModel(selection.model);
1735
- if (!parts) return { status: "failure", message: piErrorMessage(request.feature, `\`${selection.model}\` is not a \`<provider>/<id>\` model.`) };
1736
-
1737
- const agentDir = getAgentDir();
1738
- // Full-access features run in the caller's workspace; restricted explain/show have no workspace at all,
1739
- // and btw runs in the workspace in both modes.
1740
- const cwd = request.cwd ?? process.cwd();
1741
-
1742
- let session: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;
1743
- let unsubscribe: (() => void) | undefined;
1744
- let stopCause: PiStopCause | undefined;
1745
- let sawAgentEnd = false;
1746
- let willRetry = false;
1747
- let partial = "";
1748
-
1749
- // Settles the moment a stop is latched. Runtime preparation, session construction and the model
1750
- // turn are all raced against it, so a cancellation or deadline is reported at the deadline instead
1751
- // of after an uncooperative provider finally returns.
1752
- let settleStop: (() => void) | undefined;
1753
- const stopped = new Promise<void>((resolve) => {
1754
- settleStop = resolve;
1755
- });
1756
-
1757
- const stop = (cause: PiStopCause) => {
1758
- if (stopCause) return; // latched: the first cause wins
1759
- stopCause = cause;
1760
- settleStop?.();
1761
- void session?.abort();
1762
- };
1763
- // The stop outcome for the active cause, or undefined when this attempt is still running.
1764
- const stoppedOutcome = (): BackendOutcome | undefined => {
1765
- if (stopCause === "cancelled") return { status: "cancelled", message: "Canceled.", ...(partial ? { partialText: partial } : {}) };
1766
- if (stopCause === "timeout") return { status: "timeout", message: piTimeoutMessage(request.feature, deadlineMs), ...(partial ? { partialText: partial } : {}) };
1767
- return undefined;
1768
- };
1769
- // Same, for the sites that have already established a cause was latched.
1770
- const latchedOutcome = (): BackendOutcome => stoppedOutcome() ?? { status: "failure", message: piErrorMessage(request.feature, "the attempt stopped without a cause.") };
1771
- const onAbort = () => stop("cancelled");
1772
- signal.addEventListener("abort", onAbort, { once: true });
1773
- // An abort signal that is already aborted never fires its listeners, so latch it explicitly.
1774
- if (signal.aborted) onAbort();
1775
- // The deadline covers runtime preparation too: it is real (if small) I/O, and a hanging credential
1776
- // lookup must not hold a cancelled request forever.
1777
- // Deliberately NOT unref'd, unlike the CLI adapters' timers: there the child process keeps the
1778
- // event loop alive, but here an awaited in-process promise is not a handle, so an unref'd timer
1779
- // could let the loop drain and the timeout silently never fire. It is cleared in `finally`, so it
1780
- // cannot outlive the attempt.
1781
- const deadlineTimer = setTimeout(() => stop("timeout"), deadlineMs);
1782
-
1783
- try {
1784
- if (stopCause) return latchedOutcome();
1785
-
1786
- // Resolve the physical model before paying for session construction, inside the latch so a slow
1787
- // or throwing host credential lookup becomes an ordinary outcome rather than a rejection.
1788
- const modelRuntime = await Promise.race([bridgePiModelRuntime(host, agentDir), stopped.then(() => undefined)]);
1789
- if (!modelRuntime) return latchedOutcome();
1790
- // Use the effective host model for its exact identity, endpoint and metadata.
1791
- // The SDK child uses the same host model, auth resolver and streaming transport.
1792
- const model = host?.modelRegistry?.find(parts.providerId, parts.modelId);
1793
- if (!model) {
1794
- return { status: "failure", message: piErrorMessage(request.feature, `model \`${selection.model}\` is not in your Pi model catalog. Run \`/bro doctor\`.`) };
1795
- }
1796
- if ((model as { api?: string }).api === "pi-virtual") {
1797
- return { status: "failure", message: piErrorMessage(request.feature, `\`${selection.model}\` is a virtual model; choose a physical model in \`/bro config\`.`) };
1798
- }
1799
-
1800
- // Guided Review runs on an untrusted PR checkout, so its `.pi/settings.json` must never be merged.
1801
- // Elsewhere the host's own trust decision decides: a repo the user declined to trust must not get
1802
- // to steer thinking levels, budgets, transport or the shell the bash tool runs with.
1803
- // A host that predates isProjectTrusted() (or a test stub) falls back to Pi's own default.
1804
- const hostTrustsProject = (() => {
1805
- try { return host?.isProjectTrusted?.() ?? true; } catch { return false; }
1806
- })();
1807
- // An in-memory manager seeded from the effective on-disk settings, rather than one that keeps
1808
- // reading them. It gives two things a file-backed manager cannot:
1809
- // - the single-attempt and no-warming overrides cannot be discarded by a later reload(), and
1810
- // - nothing this child does can write the user's global settings.json.
1811
- // cacheWarming must be set here: getCacheWarmingMode() reads globalSettings directly, so an
1812
- // applyOverrides({cacheWarming}) would be ignored, and the warmer replays the prompt (another
1813
- // paid request) once a prompt-cache TTL is close to expiring.
1814
- const projectTrusted = request.feature !== "review" && hostTrustsProject;
1815
- const baseSettings = SettingsManager.create(cwd, agentDir, { projectTrusted }).getSettings();
1816
- const settingsManager = SettingsManager.inMemory({
1817
- ...baseSettings,
1818
- retry: { ...baseSettings.retry, enabled: false, provider: { ...baseSettings.retry?.provider, maxRetries: 0 } },
1819
- compaction: { ...baseSettings.compaction, enabled: false },
1820
- cacheWarming: "off",
1821
- }, { projectTrusted });
1822
- const resourceLoader = new DefaultResourceLoader({
1823
- cwd,
1824
- agentDir,
1825
- settingsManager,
1826
- noExtensions: true,
1827
- disabledBuiltinExtensions: ["mcp", "codemode"],
1828
- noSkills: true,
1829
- noPromptTemplates: true,
1830
- noThemes: true,
1831
- noContextFiles: true,
1832
- });
1833
-
1834
- // reload() re-reads settings from disk into the resource loader; the in-memory manager above is
1835
- // unaffected, so the overrides survive it.
1836
- // A deadline that fires during reload or session construction must stop the attempt here: the
1837
- // timer has already latched (and abort() was a no-op with no session yet), and a timeout does
1838
- // not set signal.aborted, so checking the latch is the only thing that prevents a paid model
1839
- // request from starting after its deadline.
1840
- await Promise.race([resourceLoader.reload(), stopped]);
1841
- if (stopCause) return latchedOutcome();
1842
-
1843
- // btw resumes the retained in-memory transcript; every other feature starts fresh. A thread whose
1844
- // retained entries are gone must fail loudly rather than silently answering without its history.
1845
- const continuationId = request.feature === "btw" ? request.continuation?.id : undefined;
1846
- // Bro keeps exactly one side thread, so a btw turn with no continuation id means the previous
1847
- // thread was reset (backend/mode/preferences change or /clear) and its retained transcript is now
1848
- // unreachable. Drop it instead of holding the entries until the cap evicts them.
1849
- if (request.feature === "btw" && !continuationId) piBtwSessions.clear();
1850
- const retained = continuationId ? piBtwSessions.get(continuationId) : undefined;
1851
- if (continuationId && !retained) {
1852
- // Tagged so the caller can drop the dead id: without that, every later turn resends it and
1853
- // the thread stays stuck until the user clears it.
1854
- return { status: "failure", continuationExpired: true, message: piErrorMessage(request.feature, "the side conversation expired before it could be continued; ask the question again to start a fresh thread.") };
1855
- }
1856
- const sessionManager = retained && continuationId
1857
- ? SessionManager.inMemory(cwd, { id: continuationId }, retained)
1858
- : SessionManager.inMemory(cwd);
1859
- const allowlist = piToolAllowlist(request.feature, request.access);
1860
- // An explicit Bro effort wins; with "default" the SDK resolves the level from settings, but it
1861
- // cannot see a scoped pattern's `:thinking` suffix, so carry that through ourselves.
1862
- const thinkingLevel = selection.effort && selection.effort !== "default"
1863
- ? selection.effort
1864
- : piScopedThinkingLevel(host?.scopedModels, parts.providerId, parts.modelId);
1865
-
1866
- const sessionPromise = createSession({
1867
- cwd,
1868
- agentDir,
1869
- model,
1870
- modelRuntime,
1871
- settingsManager,
1872
- sessionManager,
1873
- resourceLoader,
1874
- ...(allowlist.tools.length ? { tools: allowlist.tools } : { noTools: "all" as const }),
1875
- ...(allowlist.excludeTools ? { excludeTools: allowlist.excludeTools } : {}),
1876
- ...(thinkingLevel ? { thinkingLevel: thinkingLevel as NonNullable<Parameters<typeof createAgentSession>[0]>["thinkingLevel"] } : {}),
1877
- });
1878
- const created = await Promise.race([sessionPromise, stopped.then(() => undefined)]);
1879
- if (!created) {
1880
- // The latch won the race, but construction may still resolve afterwards. That session is
1881
- // never prompted and cannot be disposed through `session` below, so tear it down here.
1882
- void sessionPromise.then(
1883
- (late) => { try { late.session.dispose(); } catch { /* best-effort teardown */ } },
1884
- () => { /* construction failed; nothing to dispose */ },
1885
- );
1886
- return latchedOutcome();
1887
- }
1888
- session = created.session;
1889
- if (stopCause) {
1890
- // The attempt was stopped while the session was being built, so abort it directly; the latch
1891
- // already fired its own abort before this session existed.
1892
- void session.abort();
1893
- return latchedOutcome();
1894
- }
1895
-
1896
- unsubscribe = session.subscribe((event) => {
1897
- if (stopCause) return;
1898
- if (event.type === "agent_end") {
1899
- sawAgentEnd = true;
1900
- // The SDK reports its own retry decision here; a retrying turn must never count as settled.
1901
- willRetry = (event as { willRetry?: boolean }).willRetry === true;
1902
- } else if (event.type === "message_update" && event.message.role === "assistant") {
1903
- const text = piAssistantText(event.message);
1904
- if (text) {
1905
- partial = text;
1906
- onProgress?.({ kind: "text", text });
1907
- }
1908
- } else if (event.type === "tool_execution_start" && onProgress) {
1909
- const tool = btwToolName(event.toolName);
1910
- const label = request.feature === "btw" || (request.feature === "review" && request.reportReviewTools) ? tool : event.toolName;
1911
- if (label) onProgress({ kind: "activity", label, timestamp: Date.now(), ...(tool ? { tool } : {}) });
1912
- }
1913
- });
1914
-
1915
- // Race the turn against the stop latch so a non-cooperative provider cannot hold the caller.
1916
- //
1917
- // Racing alone is not enough: session.prompt() awaits an auth check before any run exists, and
1918
- // abort() only latches when a run is already active (the SDK's _startRun then clears that flag).
1919
- // A stop latched during that window would otherwise be forgotten and the request would still go
1920
- // out. preflightResult fires once the run is about to start, so re-issuing abort there lands on
1921
- // the SDK's own agent_start cancellation path and stops the first request.
1922
- const prompted = Promise.resolve(
1923
- session.prompt(request.prompt, {
1924
- source: "extension",
1925
- preflightResult: (disposition) => {
1926
- if (disposition === "started" && stopCause) void session?.abort();
1927
- },
1928
- }),
1929
- ).then(() => "done" as const);
1930
- await Promise.race([prompted, stopped.then(() => "stopped" as const)]);
1931
- if (stopCause) return latchedOutcome();
1932
-
1933
- // pi-ai encodes provider failures as a final assistant turn rather than throwing.
1934
- const messages = session.messages;
1935
- const lastAssistant = [...messages].reverse().find((message) => message.role === "assistant");
1936
- const stopReason = (lastAssistant as { stopReason?: string } | undefined)?.stopReason;
1937
- if (stopReason === "error" || stopReason === "aborted") {
1938
- const detail = (lastAssistant as { errorMessage?: string } | undefined)?.errorMessage ?? `Pi turn did not complete (stopReason: ${stopReason}).`;
1939
- return { status: "failure", message: withDoctor(piErrorMessage(request.feature, detail)), ...(partial ? { partialText: partial } : {}) };
1940
- }
1941
- // A truncated or unfinished turn is not a complete answer; its text is partial at best.
1942
- if (stopReason !== undefined && PI_INCOMPLETE_STOP_REASONS.has(stopReason)) {
1943
- return { status: "failure", message: withDoctor(piErrorMessage(request.feature, `Pi stopped before finishing (stopReason: ${stopReason}).`)), ...(partial ? { partialText: partial } : {}) };
1944
- }
1945
- // Success needs an observed agent_end with no pending retry: without one this code cannot
1946
- // confirm the turn settled, and a retrying turn is still inside Bro's single attempt.
1947
- if (!sawAgentEnd) return { status: "failure", message: withDoctor(piErrorMessage(request.feature, "the turn ended without an agent_end event.")), ...(partial ? { partialText: partial } : {}) };
1948
- if (willRetry) return { status: "failure", message: withDoctor(piErrorMessage(request.feature, "the turn ended but the SDK still intended to retry.")), ...(partial ? { partialText: partial } : {}) };
1949
- const text = lastAssistant ? piAssistantText(lastAssistant) : "";
1950
- if (!text) return { status: "failure", message: withDoctor(piErrorMessage(request.feature, "Pi returned no final explanation.")), ...(partial ? { partialText: partial } : {}) };
1951
-
1952
- // btw continuation uses the in-memory session id, which never touches disk.
1953
- if (request.feature === "btw") {
1954
- rememberPiBtwSession(session.sessionId, session.sessionManager.getEntries());
1955
- return { status: "success", text, continuation: { id: session.sessionId } };
1956
- }
1957
- return { status: "success", text };
1958
- } catch (error) {
1959
- const stoppedResult = stoppedOutcome();
1960
- if (stoppedResult) return stoppedResult;
1961
- return { status: "failure", message: withDoctor(piErrorMessage(request.feature, errorMessage(error))), ...(partial ? { partialText: partial } : {}) };
1962
- } finally {
1963
- signal.removeEventListener("abort", onAbort);
1964
- clearTimeout(deadlineTimer);
1965
- try {
1966
- unsubscribe?.();
1967
- } catch {
1968
- // A listener that throws during teardown must not mask the real outcome.
1969
- }
1970
- try {
1971
- session?.dispose();
1972
- } catch {
1973
- // dispose() is best-effort; a failure here cannot change the already-decided outcome.
1974
- }
1975
- }
1976
- }
1977
-
1978
50
  /** Validate every backend's model/effort pair before an adapter accesses it. */
1979
51
  function invalidModelEffortSelection(
1980
52
  pair: { model: unknown; effort?: unknown }, allowedEfforts: readonly string[],
@@ -2020,7 +92,7 @@ async function executeOnce(
2020
92
  if (invalidModelEffortSelection(selection, PI_EFFORTS)) {
2021
93
  return { status: "failure", message: "Unsupported Pi selection: check the model (<provider>/<id>) and effort (minimal, low, medium, high, xhigh or max)." };
2022
94
  }
2023
- return executePi(request, selection, signal, onProgress, killEscalationMs, deadlineMs, host ?? currentPiHost, options?.piCreateSession);
95
+ return executePi(request, selection, signal, onProgress, killEscalationMs, deadlineMs, host ?? getPiHostContext(), options?.piCreateSession);
2024
96
  }
2025
97
  if (selection.backend === "codex") {
2026
98
  // Codex btw always runs (and resumes) in the caller's workspace, even restricted.
@@ -2054,10 +126,7 @@ async function executeOnce(
2054
126
  }
2055
127
  return executeClaude(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
2056
128
  }
2057
- if (request.feature === "advisor") {
2058
- return executeAdvisorStdin(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
2059
- }
2060
- return executeArgvPrint(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
129
+ return executeAgy(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
2061
130
  }
2062
131
 
2063
132
  // The extension owns only operations that are still running. This covers both