pi-bro 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/backend.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ChildProcess, spawn } from "node:child_process";
1
+ import { type ChildProcess, type SpawnOptions, spawn } from "node:child_process";
2
2
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
@@ -16,6 +16,7 @@ import {
16
16
  // lower-level LLM engine pi-coding-agent is built on. Bro imports it directly, so it is declared as
17
17
  // a peer dependency alongside pi-coding-agent and pi-tui rather than relied on transitively.
18
18
  import { clampThinkingLevel, type Model as PiAiModel } from "@earendil-works/pi-ai";
19
+ import { errorMessage, withDoctor } from "./util.ts";
19
20
 
20
21
  // Shared internal execution boundary for explain, show, btw, advisor, and review.
21
22
  // This implements docs/plans/2026-09-22-shared-backend-design.md across all supported backends
@@ -82,14 +83,6 @@ export type BackendExecuteOptions = {
82
83
  piCreateSession?: typeof createAgentSession;
83
84
  };
84
85
 
85
- function errorMessage(error: unknown): string {
86
- return error instanceof Error ? error.message : String(error);
87
- }
88
-
89
- function withDoctor(message: string): string {
90
- return message.includes("/bro doctor") ? message : `${message}\n\nRun \`/bro doctor\` for setup help.`;
91
- }
92
-
93
86
  export function agyFailureMessage(action: string, result: { code: number; killed: boolean; stderr: string }): string {
94
87
  if (result.killed) return `Agy timed out while trying to ${action}. Run \`/bro doctor\` for setup help.`;
95
88
  const detail = result.stderr.trim();
@@ -156,6 +149,24 @@ type Attempt = {
156
149
 
157
150
  const DEFAULT_KILL_ESCALATION_MS = 5_000;
158
151
 
152
+ // CLI adapters own their protocols; this shared runner owns process setup, diagnostics, and lifecycle.
153
+ function startCliAttempt(
154
+ command: string,
155
+ args: string[],
156
+ options: SpawnOptions,
157
+ signal: AbortSignal,
158
+ deadlineMs: number,
159
+ killEscalationMs: number,
160
+ ) {
161
+ const child = spawn(command, args, { ...options, windowsHide: true, detached: process.platform !== "win32" });
162
+ const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
163
+ const diagnostics: { stderr: string; processError?: Error } = { stderr: "" };
164
+ child.stderr?.setEncoding("utf8");
165
+ child.stderr?.on("data", (chunk: string) => { diagnostics.stderr += chunk; });
166
+ child.once("error", (error) => { diagnostics.processError = error; });
167
+ return { child, attempt, diagnostics };
168
+ }
169
+
159
170
  // Begins bounded lifecycle management for one already-spawned child: on cancellation, deadline, or
160
171
  // protocol failure it signals the whole POSIX process group (SIGTERM, then SIGKILL after
161
172
  // `killEscalationMs` if the child or a misbehaving grandchild ignores it). Windows only ever
@@ -253,6 +264,69 @@ export function parseBtwAgyLine(line: string): { delta?: string; result?: string
253
264
  return { conversationId };
254
265
  }
255
266
 
267
+ // Every CLI adapter frames stdout immediately, awaits the process, then releases stop timers.
268
+ // Keep this lifecycle in one place: adapter-specific parsing and exit rules stay in each adapter.
269
+ async function finishCliAttempt(
270
+ child: ChildProcess,
271
+ attempt: Attempt,
272
+ name: string,
273
+ handleLine: (line: string) => void,
274
+ ): Promise<{ code: number | null; exitSignal: NodeJS.Signals | null; protocolError?: string }> {
275
+ const finishFraming = frameStdoutLines(child, attempt, name, handleLine);
276
+ try {
277
+ const { code, exitSignal } = await attempt.closed;
278
+ return { code, exitSignal, protocolError: finishFraming() };
279
+ } finally {
280
+ attempt.dispose();
281
+ }
282
+ }
283
+
284
+ /** Common stop/error precedence. Backend adapters only decide terminal protocol and success. */
285
+ function stoppedCliOutcome(
286
+ name: string,
287
+ attempt: Attempt,
288
+ finished: { code: number | null; exitSignal: NodeJS.Signals | null; protocolError?: string },
289
+ diagnostics: { stderr: string; processError?: Error },
290
+ timeoutMessage: string,
291
+ partial?: string,
292
+ ): BackendOutcome | undefined {
293
+ const partialText = partial ? { partialText: partial } : {};
294
+ if (attempt.causeOf() === "cancelled") return { status: "cancelled", message: "Canceled.", ...partialText };
295
+ if (attempt.causeOf() === "timeout") return { status: "timeout", message: timeoutMessage, ...partialText };
296
+ if (finished.protocolError) return { status: "failure", message: withDoctor(finished.protocolError), ...partialText };
297
+ if (diagnostics.processError) return { status: "failure", message: processStartMessage(diagnostics.processError as NodeJS.ErrnoException, name) };
298
+ if (finished.exitSignal || finished.code === null) {
299
+ return { status: "failure", message: unexpectedSignalMessage(finished.exitSignal, name), ...partialText };
300
+ }
301
+ return undefined;
302
+ }
303
+
304
+ /** Session continuity is a shared BTW promise, even though CLIs report IDs differently. */
305
+ function checkedBtwContinuation(
306
+ name: "Claude" | "Grok" | "Codex" | "Muse",
307
+ requested: BackendContinuation | undefined,
308
+ observed: { id?: string; init?: string; result?: string },
309
+ ): BackendContinuation | { error: string } {
310
+ const id = observed.id ?? observed.result ?? observed.init;
311
+ if (id && (!observed.init || observed.init === id) && (!requested || requested.id === id)) return { id };
312
+ const details = "id" in observed ? `got ${observed.id ?? "none"}`
313
+ : `init ${observed.init ?? "none"}, result ${observed.result ?? "none"}`;
314
+ return { error: `${name} reported an inconsistent session id (expected ${requested?.id ?? "one id"}, ${details}).` };
315
+ }
316
+
317
+ /** Exit diagnostics share framing, while each backend still owns its prompt and protocol. */
318
+ function cliExitFailure(name: "Claude" | "Grok" | "Codex" | "Muse", action: string, stderr: string): string {
319
+ const detail = stderr.trim();
320
+ if (detail) return `${name} could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`;
321
+ const installation = {
322
+ Claude: "Claude Code",
323
+ Grok: "`grok`",
324
+ Codex: "`codex`",
325
+ Muse: "`muse`",
326
+ }[name];
327
+ return `${name} could not ${action}. Make sure ${installation} is installed and signed in, then run \`/bro doctor\`.`;
328
+ }
329
+
256
330
  // Explain/show and BTW use argv for small prompts and stdin NDJSON for large
257
331
  // prompts; sandbox, cwd, timeout, and continuation semantics stay unchanged.
258
332
  async function executeArgvPrint(
@@ -261,7 +335,7 @@ async function executeArgvPrint(
261
335
  signal: AbortSignal,
262
336
  onProgress: BackendOnProgress | undefined,
263
337
  killEscalationMs: number,
264
- deadlineMsOverride: number | undefined,
338
+ deadlineMs: number,
265
339
  ): Promise<BackendOutcome> {
266
340
  // Keep legacy CLI compatibility for small prompts; large inputs use the advisor's
267
341
  // stdin protocol rather than risking Linux's per-argument byte limit.
@@ -269,7 +343,6 @@ async function executeArgvPrint(
269
343
  const isBtw = request.feature === "btw";
270
344
  const inspect = request.feature === "review";
271
345
  const full = request.access === "workspace-full";
272
- const deadlineMs = deadlineMsOverride ?? backendDeadlineMs(request.feature, request.access);
273
346
  const printTimeout = full || inspect ? "10m" : "2m";
274
347
  const action = inspect ? "complete the guided review request" : isBtw ? "answer the side question" : "simplify the response";
275
348
  const timeoutVerb = inspect ? "during the guided review request" : isBtw ? "during the side conversation" : "while simplifying the response";
@@ -284,8 +357,7 @@ async function executeArgvPrint(
284
357
  }
285
358
 
286
359
  try {
287
- const child = spawn(
288
- "agy",
360
+ const { child, attempt, diagnostics } = startCliAttempt("agy",
289
361
  [
290
362
  ...(full ? ["--dangerously-skip-permissions"] : ["--sandbox"]),
291
363
  "--disable-slash-commands",
@@ -301,27 +373,12 @@ async function executeArgvPrint(
301
373
  ],
302
374
  {
303
375
  cwd: full || inspect ? request.cwd : runDirectory,
304
- stdio: [stdinPrompt ? "pipe" : "ignore", "pipe", "pipe"],
305
- windowsHide: true,
306
- detached: process.platform !== "win32",
307
- },
308
- );
309
-
310
- const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
311
- let processError: Error | undefined;
312
- let stderr = "";
376
+ stdio: [stdinPrompt ? "pipe" : "ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
377
+
313
378
  let partial = "";
314
379
  let final = "";
315
380
  let conversationId = request.continuation?.id;
316
381
 
317
- child.stderr?.setEncoding("utf8");
318
- child.stderr?.on("data", (chunk: string) => {
319
- stderr += chunk;
320
- });
321
- child.once("error", (error) => {
322
- processError = error;
323
- });
324
-
325
382
  if (stdinPrompt) {
326
383
  child.stdin?.on("error", () => { /* Report early exits through the close/error path. */ });
327
384
  child.stdin?.end(`${JSON.stringify({ event: "user", message: { content: request.prompt } })}\n`);
@@ -348,28 +405,17 @@ async function executeArgvPrint(
348
405
  }
349
406
  };
350
407
 
351
- const finishFraming = frameStdoutLines(child, attempt, "Agy", handleLine);
352
-
353
- const { code, exitSignal } = await attempt.closed;
354
- const parseError = finishFraming();
355
- attempt.dispose();
356
- const cause = attempt.causeOf();
357
-
358
- if (cause === "cancelled") return { status: "cancelled", message: "Canceled.", partialText: partial || undefined };
359
- if (cause === "timeout") {
360
- return { status: "timeout", message: `Agy timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partialText: partial || undefined };
361
- }
362
- if (parseError) return { status: "failure", message: withDoctor(parseError), partialText: partial || undefined };
363
- if (processError) return { status: "failure", message: processStartMessage(processError as NodeJS.ErrnoException) };
364
- if (exitSignal || code === null) {
365
- return { status: "failure", message: unexpectedSignalMessage(exitSignal), partialText: partial || undefined };
366
- }
367
- if (code !== 0) return { status: "failure", message: stdinPrompt && advisorFlagErrorHint(stderr)
368
- ? withDoctor("Large prompts require Agy 1.1.15+ with stdin support. Run `agy update`. " + stderr.trim())
369
- : agyFailureMessage(action, { code, killed: false, stderr }) };
408
+ const finished = await finishCliAttempt(child, attempt, "Agy", handleLine);
409
+ const code = finished.code!;
410
+ const stopped = stoppedCliOutcome("Agy", attempt, finished, diagnostics,
411
+ `Agy timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
412
+ if (stopped) return stopped;
413
+ if (code !== 0) return { status: "failure", message: stdinPrompt && advisorFlagErrorHint(diagnostics.stderr)
414
+ ? withDoctor("Large prompts require Agy 1.1.15+ with stdin support. Run `agy update`. " + diagnostics.stderr.trim())
415
+ : agyFailureMessage(action, { code, killed: false, stderr: diagnostics.stderr }) };
370
416
 
371
417
  const text = final.trim();
372
- if (!text) return { status: "failure", message: withDoctor(stderr.trim() || emptyTextMessage) };
418
+ if (!text) return { status: "failure", message: withDoctor(diagnostics.stderr.trim() || emptyTextMessage) };
373
419
  return { status: "success", text, continuation: isBtw && conversationId ? { id: conversationId } : undefined };
374
420
  } finally {
375
421
  if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
@@ -478,13 +524,11 @@ async function executeAdvisorStdin(
478
524
  signal: AbortSignal,
479
525
  onProgress: BackendOnProgress | undefined,
480
526
  killEscalationMs: number,
481
- deadlineMsOverride: number | undefined,
527
+ deadlineMs: number,
482
528
  ): Promise<BackendOutcome> {
483
529
  if (signal.aborted) return { status: "cancelled", message: "Canceled." };
484
530
 
485
- const deadlineMs = deadlineMsOverride ?? backendDeadlineMs(request.feature, request.access);
486
- const child = spawn(
487
- "agy",
531
+ const { child, attempt, diagnostics } = startCliAttempt("agy",
488
532
  [
489
533
  "--dangerously-skip-permissions",
490
534
  "--disable-slash-commands",
@@ -498,24 +542,12 @@ async function executeAdvisorStdin(
498
542
  "--print-timeout",
499
543
  "10m",
500
544
  ],
501
- { cwd: request.cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" },
502
- );
545
+ { cwd: request.cwd, stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
503
546
 
504
- const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
505
-
506
- let processError: Error | undefined;
507
- let stderr = "";
508
547
  let final: string | undefined;
509
548
  let terminalError: string | undefined;
510
549
  let sawTerminal = false;
511
550
 
512
- child.stderr?.setEncoding("utf8");
513
- child.stderr?.on("data", (chunk: string) => {
514
- stderr += chunk;
515
- });
516
- child.once("error", (error) => {
517
- processError = error;
518
- });
519
551
  child.stdin?.on("error", () => {
520
552
  // agy exiting before it reads stdin is reported through the close/error path below.
521
553
  });
@@ -543,36 +575,26 @@ async function executeAdvisorStdin(
543
575
  }
544
576
  };
545
577
 
546
- const finishFraming = frameStdoutLines(child, attempt, "Agy", handleLine);
547
-
548
- const { code, exitSignal } = await attempt.closed;
549
- const protocolError = finishFraming();
550
- attempt.dispose();
551
-
552
- const cause = attempt.causeOf();
553
- if (cause === "cancelled") return { status: "cancelled", message: "Canceled." };
554
- if (cause === "timeout") {
555
- return { status: "timeout", message: "Agy timed out during the advisor consultation. Run `/bro doctor` for setup help." };
556
- }
557
- if (protocolError) return { status: "failure", message: withDoctor(protocolError) };
558
- if (processError) return { status: "failure", message: processStartMessage(processError as NodeJS.ErrnoException) };
559
- if (exitSignal || code === null) return { status: "failure", message: unexpectedSignalMessage(exitSignal) };
578
+ const finished = await finishCliAttempt(child, attempt, "Agy", handleLine);
579
+ const code = finished.code!;
580
+ const stopped = stoppedCliOutcome("Agy", attempt, finished, diagnostics,
581
+ "Agy timed out during the advisor consultation. Run `/bro doctor` for setup help.");
582
+ if (stopped) return stopped;
560
583
  if (!sawTerminal) {
561
- const hint = advisorFlagErrorHint(stderr);
584
+ const hint = advisorFlagErrorHint(diagnostics.stderr);
562
585
  return {
563
586
  status: "failure",
564
- message: withDoctor(hint ?? (stderr.trim() ? `Agy exited without a terminal result event: ${stderr.trim()}` : "Agy exited without a terminal result event.")),
587
+ message: withDoctor(hint ?? (diagnostics.stderr.trim() ? `Agy exited without a terminal result event: ${diagnostics.stderr.trim()}` : "Agy exited without a terminal result event.")),
565
588
  };
566
589
  }
567
590
  if (terminalError) return { status: "failure", message: withDoctor(terminalError) };
568
- if (code !== 0) return { status: "failure", message: agyFailureMessage("complete the advisor consultation", { code, killed: false, stderr }) };
591
+ if (code !== 0) return { status: "failure", message: agyFailureMessage("complete the advisor consultation", { code, killed: false, stderr: diagnostics.stderr }) };
569
592
 
570
593
  const text = final?.trim();
571
- if (!text) return { status: "failure", message: withDoctor(stderr.trim() || "Agy returned no advice.") };
594
+ if (!text) return { status: "failure", message: withDoctor(diagnostics.stderr.trim() || "Agy returned no advice.") };
572
595
  return { status: "success", text };
573
596
  }
574
597
 
575
-
576
598
  type ClaudeEvent = {
577
599
  type?: unknown;
578
600
  subtype?: unknown;
@@ -600,13 +622,12 @@ async function executeClaude(
600
622
  signal: AbortSignal,
601
623
  onProgress: BackendOnProgress | undefined,
602
624
  killEscalationMs: number,
603
- deadlineMsOverride: number | undefined,
625
+ deadlineMs: number,
604
626
  ): Promise<BackendOutcome> {
605
627
  const isAdvisor = request.feature === "advisor";
606
628
  const isBtw = request.feature === "btw";
607
629
  const inspect = request.feature === "review";
608
630
  const full = request.access === "workspace-full";
609
- const deadlineMs = deadlineMsOverride ?? backendDeadlineMs(request.feature, request.access);
610
631
  const action = request.feature === "review" ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
611
632
 
612
633
  if (signal.aborted) return { status: "cancelled", message: "Canceled." };
@@ -617,8 +638,7 @@ async function executeClaude(
617
638
  }
618
639
 
619
640
  try {
620
- const child = spawn(
621
- "claude",
641
+ const { child, attempt, diagnostics } = startCliAttempt("claude",
622
642
  [
623
643
  "-p",
624
644
  "--safe-mode",
@@ -640,28 +660,14 @@ async function executeClaude(
640
660
  ],
641
661
  {
642
662
  cwd: runDirectory ?? request.cwd,
643
- stdio: ["pipe", "pipe", "pipe"],
644
- windowsHide: true,
645
- detached: process.platform !== "win32",
646
- },
647
- );
648
-
649
- const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
650
- let processError: Error | undefined;
651
- let stderr = "";
663
+ stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
664
+
652
665
  let partial = "";
653
666
  let final: string | undefined;
654
667
  let terminalError: string | undefined;
655
668
  let initSessionId: string | undefined;
656
669
  let resultSessionId: string | undefined;
657
670
 
658
- child.stderr?.setEncoding("utf8");
659
- child.stderr?.on("data", (chunk: string) => {
660
- stderr += chunk;
661
- });
662
- child.once("error", (error) => {
663
- processError = error;
664
- });
665
671
  child.stdin?.on("error", () => {
666
672
  // claude exiting before it reads stdin is reported through the close/error path below.
667
673
  });
@@ -717,49 +723,25 @@ async function executeClaude(
717
723
  }
718
724
  };
719
725
 
720
- const finishFraming = frameStdoutLines(child, attempt, "Claude", handleLine);
721
-
722
- const { code, exitSignal } = await attempt.closed;
723
- const protocolError = finishFraming();
724
- attempt.dispose();
725
-
726
+ const finished = await finishCliAttempt(child, attempt, "Claude", handleLine);
727
+ const code = finished.code!;
728
+ const stopped = stoppedCliOutcome("Claude", attempt, finished, diagnostics,
729
+ `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);
730
+ if (stopped) return stopped;
726
731
  const partialText = partial || undefined;
727
- const cause = attempt.causeOf();
728
- if (cause === "cancelled") return { status: "cancelled", message: "Canceled.", partialText };
729
- if (cause === "timeout") {
730
- const during = request.feature === "review" ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
731
- return { status: "timeout", message: `Claude timed out ${during}. Run \`/bro doctor\` for setup help.`, partialText };
732
- }
733
- if (protocolError) return { status: "failure", message: withDoctor(protocolError), partialText };
734
- if (processError) return { status: "failure", message: processStartMessage(processError as NodeJS.ErrnoException, "Claude") };
735
- if (exitSignal || code === null) return { status: "failure", message: unexpectedSignalMessage(exitSignal, "Claude"), partialText };
736
732
  if (terminalError) return { status: "failure", message: withDoctor(terminalError), partialText };
737
- if (code !== 0) {
738
- const detail = stderr.trim();
739
- return {
740
- status: "failure",
741
- message: detail
742
- ? `Claude could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`
743
- : `Claude could not ${action}. Make sure Claude Code is installed and signed in, then run \`/bro doctor\`.`,
744
- partialText,
745
- };
746
- }
733
+ if (code !== 0) return { status: "failure", message: cliExitFailure("Claude", action, diagnostics.stderr), partialText };
747
734
  if (final === undefined) {
748
- return { status: "failure", message: withDoctor(`Claude exited without a result event${stderr.trim() ? `: ${stderr.trim()}` : "."}`), partialText };
735
+ return { status: "failure", message: withDoctor(`Claude exited without a result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), partialText };
749
736
  }
750
737
  const text = final.trim();
751
738
  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 };
752
739
  if (!isBtw) return { status: "success", text };
753
- // btw continuation: the session id must be reported, consistent, and (on resume) unchanged.
754
- const sessionId = resultSessionId ?? initSessionId;
755
- if (!sessionId || (initSessionId !== undefined && initSessionId !== sessionId) || (request.continuation && sessionId !== request.continuation.id)) {
756
- return {
757
- status: "failure",
758
- message: withDoctor(`Claude reported an inconsistent session id (expected ${request.continuation?.id ?? "one id"}, init ${initSessionId ?? "none"}, result ${resultSessionId ?? "none"}).`),
759
- partialText,
760
- };
761
- }
762
- return { status: "success", text, continuation: { id: sessionId } };
740
+ const continuation = checkedBtwContinuation("Claude", request.continuation,
741
+ { init: initSessionId, result: resultSessionId });
742
+ if ("error" in continuation)
743
+ return { status: "failure", message: withDoctor(continuation.error), partialText };
744
+ return { status: "success", text, continuation };
763
745
  } finally {
764
746
  if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
765
747
  }
@@ -808,12 +790,11 @@ async function executeGrok(
808
790
  signal: AbortSignal,
809
791
  onProgress: BackendOnProgress | undefined,
810
792
  killEscalationMs: number,
811
- deadlineMsOverride: number | undefined,
793
+ deadlineMs: number,
812
794
  ): Promise<BackendOutcome> {
813
795
  const isAdvisor = request.feature === "advisor";
814
796
  const isBtw = request.feature === "btw";
815
797
  const inspect = request.feature === "review";
816
- const deadlineMs = deadlineMsOverride ?? backendDeadlineMs(request.feature, request.access);
817
798
  const action = inspect ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
818
799
  const timeoutVerb = inspect ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
819
800
  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.";
@@ -830,8 +811,7 @@ async function executeGrok(
830
811
  if (request.access !== "workspace-full" && !isBtw && !inspect) runDirectory = await mkdtemp(join(tmpdir(), "pi-bro-"));
831
812
  if (signal.aborted) return { status: "cancelled", message: "Canceled." };
832
813
 
833
- const child = spawn(
834
- "grok",
814
+ const { child, attempt, diagnostics } = startCliAttempt("grok",
835
815
  [
836
816
  // 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.
837
817
  ...(inspect ? ["--sandbox", "read-only", "--permission-mode", "dontAsk"] : ["--sandbox", "off", "--permission-mode", "bypassPermissions"]),
@@ -844,12 +824,8 @@ async function executeGrok(
844
824
  "--prompt-file",
845
825
  promptFile,
846
826
  ],
847
- { cwd: runDirectory ?? request.cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" },
848
- );
827
+ { cwd: runDirectory ?? request.cwd, stdio: ["ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
849
828
 
850
- const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
851
- let processError: Error | undefined;
852
- let stderr = "";
853
829
  let partial = "";
854
830
  let streamedSinceAssistant = false;
855
831
  let initSessionId: string | undefined;
@@ -857,14 +833,6 @@ async function executeGrok(
857
833
  let final: string | undefined;
858
834
  let terminalError: string | undefined;
859
835
 
860
- child.stderr?.setEncoding("utf8");
861
- child.stderr?.on("data", (chunk: string) => {
862
- stderr += chunk;
863
- });
864
- child.once("error", (error) => {
865
- processError = error;
866
- });
867
-
868
836
  const handleLine = (line: string) => {
869
837
  if (!line.trim() || attempt.causeOf()) return;
870
838
  let event: GrokEvent;
@@ -950,46 +918,25 @@ async function executeGrok(
950
918
  terminalError ??= `Grok failed: ${detail}`;
951
919
  };
952
920
 
953
- const finishFraming = frameStdoutLines(child, attempt, "Grok", handleLine);
954
-
955
- const { code, exitSignal } = await attempt.closed;
956
- const protocolError = finishFraming();
957
- attempt.dispose();
958
-
921
+ const finished = await finishCliAttempt(child, attempt, "Grok", handleLine);
922
+ const code = finished.code!;
923
+ const stopped = stoppedCliOutcome("Grok", attempt, finished, diagnostics,
924
+ `Grok timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
925
+ if (stopped) return stopped;
959
926
  const partialText = partial ? { partialText: partial } : {};
960
- const cause = attempt.causeOf();
961
- if (cause === "cancelled") return { status: "cancelled", message: "Canceled.", ...partialText };
962
- if (cause === "timeout") return { status: "timeout", message: `Grok timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, ...partialText };
963
- if (protocolError) return { status: "failure", message: withDoctor(protocolError), ...partialText };
964
- if (processError) return { status: "failure", message: processStartMessage(processError as NodeJS.ErrnoException, "Grok") };
965
- if (exitSignal || code === null) return { status: "failure", message: unexpectedSignalMessage(exitSignal, "Grok"), ...partialText };
966
927
  if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
967
- if (code !== 0) {
968
- const detail = stderr.trim();
969
- return {
970
- status: "failure",
971
- message: detail
972
- ? `Grok could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`
973
- : `Grok could not ${action}. Make sure \`grok\` is installed and signed in, then run \`/bro doctor\`.`,
974
- ...partialText,
975
- };
976
- }
928
+ if (code !== 0) return { status: "failure", message: cliExitFailure("Grok", action, diagnostics.stderr), ...partialText };
977
929
  if (final === undefined) {
978
- return { status: "failure", message: withDoctor(`Grok exited without a terminal result event${stderr.trim() ? `: ${stderr.trim()}` : "."}`), ...partialText };
930
+ return { status: "failure", message: withDoctor(`Grok exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
979
931
  }
980
932
  const text = final.trim();
981
933
  if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
982
934
  if (!isBtw) return { status: "success", text };
983
- // btw continuation: the session id must be reported, consistent, and (on resume) unchanged.
984
- const sessionId = resultSessionId ?? initSessionId;
985
- if (!sessionId || (initSessionId !== undefined && initSessionId !== sessionId) || (request.continuation && sessionId !== request.continuation.id)) {
986
- return {
987
- status: "failure",
988
- message: withDoctor(`Grok reported an inconsistent session id (expected ${request.continuation?.id ?? "one id"}, init ${initSessionId ?? "none"}, result ${resultSessionId ?? "none"}).`),
989
- ...partialText,
990
- };
991
- }
992
- return { status: "success", text, continuation: { id: sessionId } };
935
+ const continuation = checkedBtwContinuation("Grok", request.continuation,
936
+ { init: initSessionId, result: resultSessionId });
937
+ if ("error" in continuation)
938
+ return { status: "failure", message: withDoctor(continuation.error), ...partialText };
939
+ return { status: "success", text, continuation };
993
940
  } finally {
994
941
  if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
995
942
  await rm(promptDirectory, { recursive: true, force: true });
@@ -1048,13 +995,12 @@ async function executeCodex(
1048
995
  signal: AbortSignal,
1049
996
  onProgress: BackendOnProgress | undefined,
1050
997
  killEscalationMs: number,
1051
- deadlineMsOverride: number | undefined,
998
+ deadlineMs: number,
1052
999
  ): Promise<BackendOutcome> {
1053
1000
  const isAdvisor = request.feature === "advisor";
1054
1001
  const isBtw = request.feature === "btw";
1055
1002
  const inspect = request.feature === "review";
1056
1003
  const full = request.access === "workspace-full";
1057
- const deadlineMs = deadlineMsOverride ?? backendDeadlineMs(request.feature, request.access);
1058
1004
  const action = inspect ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
1059
1005
  const timeoutVerb = inspect ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
1060
1006
  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.";
@@ -1082,29 +1028,16 @@ async function executeCodex(
1082
1028
  ...(resume ? [request.continuation!.id, "-"] : ["--", "-"]),
1083
1029
  ];
1084
1030
 
1085
- const child = spawn("codex", args, {
1031
+ const { child, attempt, diagnostics } = startCliAttempt("codex", args, {
1086
1032
  cwd: runDirectory ?? request.cwd,
1087
- stdio: ["pipe", "pipe", "pipe"],
1088
- windowsHide: true,
1089
- detached: process.platform !== "win32",
1090
- });
1033
+ stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
1091
1034
 
1092
- const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
1093
- let processError: Error | undefined;
1094
- let stderr = "";
1095
1035
  let partial = "";
1096
1036
  let threadId: string | undefined;
1097
1037
  let final: string | undefined;
1098
1038
  let sawTerminal = false;
1099
1039
  let terminalError: string | undefined;
1100
1040
 
1101
- child.stderr?.setEncoding("utf8");
1102
- child.stderr?.on("data", (chunk: string) => {
1103
- stderr += chunk;
1104
- });
1105
- child.once("error", (error) => {
1106
- processError = error;
1107
- });
1108
1041
  child.stdin?.on("error", () => {
1109
1042
  // codex exiting before reading stdin is reported through the close/error path.
1110
1043
  });
@@ -1152,44 +1085,24 @@ async function executeCodex(
1152
1085
  }
1153
1086
  };
1154
1087
 
1155
- const finishFraming = frameStdoutLines(child, attempt, "Codex", handleLine);
1156
-
1157
- const { code, exitSignal } = await attempt.closed;
1158
- const protocolError = finishFraming();
1159
- attempt.dispose();
1160
-
1088
+ const finished = await finishCliAttempt(child, attempt, "Codex", handleLine);
1089
+ const code = finished.code!;
1090
+ const stopped = stoppedCliOutcome("Codex", attempt, finished, diagnostics,
1091
+ `Codex timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
1092
+ if (stopped) return stopped;
1161
1093
  const partialText = partial ? { partialText: partial } : {};
1162
- const cause = attempt.causeOf();
1163
- if (cause === "cancelled") return { status: "cancelled", message: "Canceled.", ...partialText };
1164
- if (cause === "timeout") return { status: "timeout", message: `Codex timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, ...partialText };
1165
- if (protocolError) return { status: "failure", message: withDoctor(protocolError), ...partialText };
1166
- if (processError) return { status: "failure", message: processStartMessage(processError as NodeJS.ErrnoException, "Codex") };
1167
- if (exitSignal || code === null) return { status: "failure", message: unexpectedSignalMessage(exitSignal, "Codex"), ...partialText };
1168
1094
  if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
1169
- if (code !== 0) {
1170
- const detail = stderr.trim();
1171
- return {
1172
- status: "failure",
1173
- message: detail
1174
- ? `Codex could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`
1175
- : `Codex could not ${action}. Make sure \`codex\` is installed and signed in, then run \`/bro doctor\`.`,
1176
- ...partialText,
1177
- };
1178
- }
1095
+ if (code !== 0) return { status: "failure", message: cliExitFailure("Codex", action, diagnostics.stderr), ...partialText };
1179
1096
  if (!sawTerminal) {
1180
- return { status: "failure", message: withDoctor(`Codex exited without a terminal result event${stderr.trim() ? `: ${stderr.trim()}` : "."}`), ...partialText };
1097
+ return { status: "failure", message: withDoctor(`Codex exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
1181
1098
  }
1182
1099
  const text = final?.trim();
1183
1100
  if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
1184
1101
  if (!isBtw) return { status: "success", text };
1185
- if (!threadId || (request.continuation && threadId !== request.continuation.id)) {
1186
- return {
1187
- status: "failure",
1188
- message: withDoctor(`Codex reported an inconsistent session id (expected ${request.continuation?.id ?? "one id"}, got ${threadId ?? "none"}).`),
1189
- ...partialText,
1190
- };
1191
- }
1192
- return { status: "success", text, continuation: { id: threadId } };
1102
+ const continuation = checkedBtwContinuation("Codex", request.continuation, { id: threadId });
1103
+ if ("error" in continuation)
1104
+ return { status: "failure", message: withDoctor(continuation.error), ...partialText };
1105
+ return { status: "success", text, continuation };
1193
1106
  } finally {
1194
1107
  if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
1195
1108
  }
@@ -1220,13 +1133,12 @@ async function executeMuse(
1220
1133
  signal: AbortSignal,
1221
1134
  onProgress: BackendOnProgress | undefined,
1222
1135
  killEscalationMs: number,
1223
- deadlineMsOverride: number | undefined,
1136
+ deadlineMs: number,
1224
1137
  ): Promise<BackendOutcome> {
1225
1138
  const isAdvisor = request.feature === "advisor";
1226
1139
  const isBtw = request.feature === "btw";
1227
1140
  const inspect = request.feature === "review";
1228
1141
  const full = request.access === "workspace-full";
1229
- const deadlineMs = deadlineMsOverride ?? backendDeadlineMs(request.feature, request.access);
1230
1142
  const action = request.feature === "review" ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
1231
1143
  const timeoutVerb = request.feature === "review" ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
1232
1144
  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.";
@@ -1257,16 +1169,10 @@ async function executeMuse(
1257
1169
  "--prompt-file", promptFile,
1258
1170
  ];
1259
1171
 
1260
- const child = spawn("muse", args, {
1172
+ const { child, attempt, diagnostics } = startCliAttempt("muse", args, {
1261
1173
  cwd: workspace,
1262
- stdio: ["ignore", "pipe", "pipe"],
1263
- windowsHide: true,
1264
- detached: process.platform !== "win32",
1265
- });
1174
+ stdio: ["ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
1266
1175
 
1267
- const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
1268
- let processError: Error | undefined;
1269
- let stderr = "";
1270
1176
  let partial = "";
1271
1177
  let rootCommandId: string | undefined;
1272
1178
  let rootRunId: string | undefined;
@@ -1275,14 +1181,6 @@ async function executeMuse(
1275
1181
  let sawTerminal = false;
1276
1182
  let terminalError: string | undefined;
1277
1183
 
1278
- child.stderr?.setEncoding("utf8");
1279
- child.stderr?.on("data", (chunk: string) => {
1280
- stderr += chunk;
1281
- });
1282
- child.once("error", (error) => {
1283
- processError = error;
1284
- });
1285
-
1286
1184
  const handleLine = (line: string) => {
1287
1185
  if (!line.trim() || attempt.causeOf()) return;
1288
1186
  let envelope: MuseEnvelope;
@@ -1351,44 +1249,24 @@ async function executeMuse(
1351
1249
  }
1352
1250
  };
1353
1251
 
1354
- const finishFraming = frameStdoutLines(child, attempt, "Muse", handleLine);
1355
-
1356
- const { code, exitSignal } = await attempt.closed;
1357
- const protocolError = finishFraming();
1358
- attempt.dispose();
1359
-
1252
+ const finished = await finishCliAttempt(child, attempt, "Muse", handleLine);
1253
+ const code = finished.code!;
1254
+ const stopped = stoppedCliOutcome("Muse", attempt, finished, diagnostics,
1255
+ `Muse timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
1256
+ if (stopped) return stopped;
1360
1257
  const partialText = partial ? { partialText: partial } : {};
1361
- const cause = attempt.causeOf();
1362
- if (cause === "cancelled") return { status: "cancelled", message: "Canceled.", ...partialText };
1363
- if (cause === "timeout") return { status: "timeout", message: `Muse timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, ...partialText };
1364
- if (protocolError) return { status: "failure", message: withDoctor(protocolError), ...partialText };
1365
- if (processError) return { status: "failure", message: processStartMessage(processError as NodeJS.ErrnoException, "Muse") };
1366
- if (exitSignal || code === null) return { status: "failure", message: unexpectedSignalMessage(exitSignal, "Muse"), ...partialText };
1367
1258
  if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
1368
- if (code !== 0) {
1369
- const detail = stderr.trim();
1370
- return {
1371
- status: "failure",
1372
- message: detail
1373
- ? `Muse could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`
1374
- : `Muse could not ${action}. Make sure \`muse\` is installed and signed in, then run \`/bro doctor\`.`,
1375
- ...partialText,
1376
- };
1377
- }
1259
+ if (code !== 0) return { status: "failure", message: cliExitFailure("Muse", action, diagnostics.stderr), ...partialText };
1378
1260
  if (!sawTerminal) {
1379
- return { status: "failure", message: withDoctor(`Muse exited without a terminal result event${stderr.trim() ? `: ${stderr.trim()}` : "."}`), ...partialText };
1261
+ return { status: "failure", message: withDoctor(`Muse exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
1380
1262
  }
1381
1263
  const text = final?.trim();
1382
1264
  if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
1383
1265
  if (!isBtw) return { status: "success", text };
1384
- if (!sessionId || (request.continuation && sessionId !== request.continuation.id)) {
1385
- return {
1386
- status: "failure",
1387
- message: withDoctor(`Muse reported an inconsistent session id (expected ${request.continuation?.id ?? "one id"}, got ${sessionId ?? "none"}).`),
1388
- ...partialText,
1389
- };
1390
- }
1391
- return { status: "success", text, continuation: { id: sessionId } };
1266
+ const continuation = checkedBtwContinuation("Muse", request.continuation, { id: sessionId });
1267
+ if ("error" in continuation)
1268
+ return { status: "failure", message: withDoctor(continuation.error), ...partialText };
1269
+ return { status: "success", text, continuation };
1392
1270
  } finally {
1393
1271
  if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
1394
1272
  await rm(promptDirectory, { recursive: true, force: true });
@@ -1618,12 +1496,11 @@ async function executePi(
1618
1496
  signal: AbortSignal,
1619
1497
  onProgress: BackendOnProgress | undefined,
1620
1498
  killEscalationMs: number,
1621
- deadlineMsOverride: number | undefined,
1499
+ deadlineMs: number,
1622
1500
  host: PiHostContext | undefined,
1623
1501
  createSession: typeof createAgentSession = createAgentSession,
1624
1502
  ): Promise<BackendOutcome> {
1625
1503
  void killEscalationMs; // in-process: abort() is cooperative, there is no process group to kill
1626
- const deadlineMs = deadlineMsOverride ?? backendDeadlineMs(request.feature, request.access);
1627
1504
  const parts = splitPiModel(selection.model);
1628
1505
  if (!parts) return { status: "failure", message: piErrorMessage(request.feature, `\`${selection.model}\` is not a \`<provider>/<id>\` model.`) };
1629
1506
 
@@ -1867,11 +1744,19 @@ async function executePi(
1867
1744
  }
1868
1745
  }
1869
1746
 
1747
+ /** Validate every backend's model/effort pair before an adapter accesses it. */
1748
+ function invalidModelEffortSelection(
1749
+ pair: { model: unknown; effort?: unknown }, allowedEfforts: readonly string[],
1750
+ ): boolean {
1751
+ return typeof pair.model !== "string" || !pair.model.trim() ||
1752
+ (pair.effort !== undefined && (typeof pair.effort !== "string" || !allowedEfforts.includes(pair.effort)));
1753
+ }
1754
+
1870
1755
  // Single-attempt executor shared by all features. Never retries; never spawns a pre-aborted
1871
1756
  // request; on cancellation, host deadline, or a protocol failure, stops the whole POSIX process
1872
1757
  // group (SIGTERM, then SIGKILL after a bounded grace period) before resolving. `options` is for
1873
1758
  // offline tests only -- production callers never override the deadline or kill-escalation delay.
1874
- export async function execute(
1759
+ async function executeOnce(
1875
1760
  request: BackendRequest,
1876
1761
  selection: BackendSelection,
1877
1762
  signal: AbortSignal,
@@ -1891,59 +1776,102 @@ export async function execute(
1891
1776
  if (backend !== undefined && backend !== "agy" && backend !== "claude" && backend !== "grok" && backend !== "codex" && backend !== "muse" && backend !== "pi") {
1892
1777
  return { status: "failure", message: `Unknown backend ${JSON.stringify(backend)}: pick Agy, Claude, Grok, Codex, Muse or Pi in \`/bro config\`.` };
1893
1778
  }
1779
+ // Review requires cwd above; restricted BTW also keeps native external sessions in the caller's workspace.
1780
+ if (request.feature === "btw" && !request.cwd?.trim() &&
1781
+ (backend === "codex" || backend === "muse" || backend === "grok" || backend === "claude")) {
1782
+ return { status: "failure", message: "Unsupported execution request: check feature access, workspace cwd and continuation." };
1783
+ }
1894
1784
  const killEscalationMs = options?.killEscalationMs ?? DEFAULT_KILL_ESCALATION_MS;
1785
+ const deadlineMs = options?.deadlineMs ?? backendDeadlineMs(request.feature, request.access);
1895
1786
  if (selection.backend === "pi") {
1896
1787
  // Same shape checks every other adapter performs, so a corrupt runtime tag fails as an outcome
1897
1788
  // instead of throwing a TypeError out of execute().
1898
- if (typeof selection.model !== "string" || !selection.model.trim() || (selection.effort !== undefined && !PI_EFFORTS.includes(selection.effort as never))) {
1789
+ if (invalidModelEffortSelection(selection, PI_EFFORTS)) {
1899
1790
  return { status: "failure", message: "Unsupported Pi selection: check the model (<provider>/<id>) and effort (minimal, low, medium, high, xhigh or max)." };
1900
1791
  }
1901
- return executePi(request, selection, signal, onProgress, killEscalationMs, options?.deadlineMs, host ?? currentPiHost, options?.piCreateSession);
1792
+ return executePi(request, selection, signal, onProgress, killEscalationMs, deadlineMs, host ?? currentPiHost, options?.piCreateSession);
1902
1793
  }
1903
1794
  if (selection.backend === "codex") {
1904
1795
  // Codex btw always runs (and resumes) in the caller's workspace, even restricted.
1905
- if ((request.feature === "btw" || request.feature === "review") && !request.cwd?.trim()) {
1906
- return { status: "failure", message: "Unsupported execution request: check feature access, workspace cwd and continuation." };
1907
- }
1908
- if (typeof selection.model !== "string" || !selection.model.trim() || (selection.effort !== undefined && !CODEX_EFFORTS.includes(selection.effort))) {
1796
+
1797
+ if (invalidModelEffortSelection(selection, CODEX_EFFORTS)) {
1909
1798
  return { status: "failure", message: "Unsupported Codex selection: check the model and effort (low, medium, high or xhigh)." };
1910
1799
  }
1911
- return executeCodex(request, selection, signal, onProgress, killEscalationMs, options?.deadlineMs);
1800
+ return executeCodex(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
1912
1801
  }
1913
1802
  if (selection.backend === "muse") {
1914
1803
  // Muse btw always runs (and resumes) in the caller's workspace, even restricted.
1915
- if ((request.feature === "btw" || request.feature === "review") && !request.cwd?.trim()) {
1916
- return { status: "failure", message: "Unsupported execution request: check feature access, workspace cwd and continuation." };
1917
- }
1918
- if (typeof selection.model !== "string" || !selection.model.trim() || (selection.effort !== undefined && !MUSE_EFFORTS.includes(selection.effort))) {
1804
+
1805
+ if (invalidModelEffortSelection(selection, MUSE_EFFORTS)) {
1919
1806
  return { status: "failure", message: "Unsupported Muse selection: check the model and effort (minimal, low, medium, high, xhigh or max)." };
1920
1807
  }
1921
- return executeMuse(request, selection, signal, onProgress, killEscalationMs, options?.deadlineMs);
1808
+ return executeMuse(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
1922
1809
  }
1923
1810
  if (selection.backend === "grok") {
1924
1811
  // Grok btw always runs (and resumes) in the caller's workspace, even restricted.
1925
- if ((request.feature === "btw" || request.feature === "review") && !request.cwd?.trim()) {
1926
- return { status: "failure", message: "Unsupported execution request: check feature access, workspace cwd and continuation." };
1927
- }
1928
- if (typeof selection.model !== "string" || !selection.model.trim() || (selection.effort !== undefined && !GROK_EFFORTS.includes(selection.effort))) {
1812
+
1813
+ if (invalidModelEffortSelection(selection, GROK_EFFORTS)) {
1929
1814
  return { status: "failure", message: "Unsupported Grok selection: check the model and effort (low, medium, high or xhigh)." };
1930
1815
  }
1931
- return executeGrok(request, selection, signal, onProgress, killEscalationMs, options?.deadlineMs);
1816
+ return executeGrok(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
1932
1817
  }
1933
1818
  if (selection.backend === "claude") {
1934
1819
  // Claude btw always runs (and resumes) in the caller's workspace, even restricted.
1935
- if ((request.feature === "btw" || request.feature === "review") && !request.cwd?.trim()) {
1936
- return { status: "failure", message: "Unsupported execution request: check feature access, workspace cwd and continuation." };
1937
- }
1938
- if (!selection.model.trim() || (selection.effort !== undefined && !CLAUDE_EFFORTS.includes(selection.effort))) {
1820
+
1821
+ if (invalidModelEffortSelection(selection, CLAUDE_EFFORTS)) {
1939
1822
  return { status: "failure", message: "Unsupported Claude selection: check the model and effort (low, medium, high, xhigh or max)." };
1940
1823
  }
1941
- return executeClaude(request, selection, signal, onProgress, killEscalationMs, options?.deadlineMs);
1824
+ return executeClaude(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
1942
1825
  }
1943
1826
  if (request.feature === "advisor") {
1944
- return executeAdvisorStdin(request, selection, signal, onProgress, killEscalationMs, options?.deadlineMs);
1827
+ return executeAdvisorStdin(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
1945
1828
  }
1946
- return executeArgvPrint(request, selection, signal, onProgress, killEscalationMs, options?.deadlineMs);
1829
+ return executeArgvPrint(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
1830
+ }
1831
+
1832
+ // The extension owns only operations that are still running. This covers both
1833
+ // pre-spawn CLI preparation and in-process Pi sessions without a second process
1834
+ // registry. Shutdown aborts the request signal and awaits normal adapter cleanup.
1835
+ const activeBackendExecutions = new Map<AbortController, Promise<BackendOutcome>>();
1836
+
1837
+ export async function stopActiveBackendExecutions(): Promise<void> {
1838
+ const active = [...activeBackendExecutions];
1839
+ for (const [controller] of active) controller.abort();
1840
+ const finished = await Promise.allSettled(active.map(([, result]) => result));
1841
+ for (const result of finished) if (result.status === "rejected") throw result.reason;
1842
+ }
1843
+
1844
+ export function execute(
1845
+ request: BackendRequest,
1846
+ selection: BackendSelection,
1847
+ signal: AbortSignal,
1848
+ onProgress?: BackendOnProgress,
1849
+ options?: BackendExecuteOptions,
1850
+ host?: PiHostContext,
1851
+ ): Promise<BackendOutcome> {
1852
+ const controller = new AbortController();
1853
+ const combinedSignal = AbortSignal.any([signal, controller.signal]);
1854
+ const pending = executeOnce(request, selection, combinedSignal, onProgress, options, host);
1855
+ activeBackendExecutions.set(controller, pending);
1856
+ return pending.finally(() => { activeBackendExecutions.delete(controller); });
1857
+ }
1858
+
1859
+ /** Coalesce text-only progress without leaving a timer after cancellation.
1860
+ * Shared by Explain/Show and BTW, which expose the same 75 ms UI contract. */
1861
+ export function textProgressThrottle(signal: AbortSignal, onProgress?: (text: string) => void) {
1862
+ let timer: ReturnType<typeof setTimeout> | undefined;
1863
+ let latest: string | undefined;
1864
+ const receive = onProgress ? (progress: BackendProgress) => {
1865
+ if (progress.kind !== "text") return;
1866
+ latest = progress.text;
1867
+ if (!timer) {
1868
+ timer = setTimeout(() => {
1869
+ timer = undefined;
1870
+ if (!signal.aborted && latest !== undefined) onProgress(latest);
1871
+ }, 75);
1872
+ }
1873
+ } : undefined;
1874
+ return { receive, dispose: () => { if (timer) clearTimeout(timer); } };
1947
1875
  }
1948
1876
 
1949
1877
  // Thin presentation-boundary wrapper around the shared backend: coalesces raw text progress to the
@@ -1956,27 +1884,14 @@ export async function runBackendText(
1956
1884
  onProgress?: (text: string) => void,
1957
1885
  feature: "explain" | "show" = "explain",
1958
1886
  ): Promise<string> {
1959
- let updateTimer: ReturnType<typeof setTimeout> | undefined;
1960
- let latest: string | undefined;
1961
- const throttledProgress = onProgress
1962
- ? (progress: BackendProgress) => {
1963
- if (progress.kind !== "text") return;
1964
- latest = progress.text;
1965
- if (!updateTimer) {
1966
- updateTimer = setTimeout(() => {
1967
- updateTimer = undefined;
1968
- if (!signal.aborted && latest !== undefined) onProgress(latest);
1969
- }, 75);
1970
- }
1971
- }
1972
- : undefined;
1887
+ const progress = textProgressThrottle(signal, onProgress);
1973
1888
 
1974
1889
  try {
1975
- const outcome = await execute({ feature, prompt, access: "restricted" }, selection, signal, throttledProgress);
1890
+ const outcome = await execute({ feature, prompt, access: "restricted" }, selection, signal, progress.receive);
1976
1891
  if (outcome.status === "success") return outcome.text;
1977
1892
  throw new Error(outcome.message);
1978
1893
  } finally {
1979
- if (updateTimer) clearTimeout(updateTimer);
1894
+ progress.dispose();
1980
1895
  }
1981
1896
  }
1982
1897