pi-bro 0.38.1 → 0.40.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.
@@ -131,10 +131,6 @@ export function rememberBackendNotice(backend: string): string {
131
131
  return "Claude uses the restricted explain path: disabled tools, strict empty MCP config, no session persistence and a temporary working directory.";
132
132
  case "pi":
133
133
  return "Pi uses a fresh isolated SDK session with no tools, extensions, skills or project context files. It runs the configured physical Pi model.";
134
- case "muse":
135
- return "Muse runs with write and shell actions disabled and approval disabled, from a temporary working directory. Other available capabilities may differ by Muse version.";
136
- case "grok":
137
- return "Grok's restricted explain path uses an advisory instruction, but its CLI runs with the sandbox off and permissions bypassed. This is not a technical tool or write restriction.";
138
134
  default:
139
135
  return "Uses this backend's existing restricted explain execution path; see /bro doctor and backend-specific permissions. No stronger guarantee is implied.";
140
136
  }
package/src/settings.ts CHANGED
@@ -4,28 +4,25 @@ import { lstat, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "n
4
4
  import { join } from "node:path";
5
5
  import {
6
6
  type BackendSelection,
7
+ AGY_EFFORTS,
7
8
  agySelection,
8
9
  CLAUDE_EFFORTS,
9
10
  getPiHostContext,
10
- GROK_EFFORTS,
11
11
  CODEX_EFFORTS,
12
- MUSE_EFFORTS,
13
12
  PI_EFFORTS,
14
13
  piPhysicalModel,
15
14
  } from "./backend.ts";
16
15
  import { type BroMode, DEFAULT_BRO_MODE, MAX_PREFERENCES_CHARS, parseBroMode } from "./prompt.ts";
17
16
  import { errorMessage, isRecord } from "./util.ts";
18
17
 
19
- export const EFFORTS = ["default", "low", "medium", "high"] as const;
20
- export const BACKENDS = ["agy", "claude", "grok", "codex", "muse", "pi"] as const;
18
+ export const EFFORTS = ["default", ...AGY_EFFORTS] as const;
19
+ export const BACKENDS = ["agy", "claude", "codex", "pi"] as const;
21
20
  export type BackendName = (typeof BACKENDS)[number];
22
21
  export type BroEffort = "default" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
23
- export type AgyEffort = Exclude<BroEffort, "default" | "minimal" | "xhigh" | "max">;
22
+ export type AgyEffort = (typeof AGY_EFFORTS)[number];
24
23
  export type ClaudeEffort = (typeof CLAUDE_EFFORTS)[number];
25
- export { GROK_EFFORTS, CODEX_EFFORTS, MUSE_EFFORTS, PI_EFFORTS };
26
- export type GrokEffort = (typeof GROK_EFFORTS)[number];
24
+ export { AGY_EFFORTS, CODEX_EFFORTS, PI_EFFORTS };
27
25
  export type CodexEffort = (typeof CODEX_EFFORTS)[number];
28
- export type MuseEffort = (typeof MUSE_EFFORTS)[number];
29
26
  export type PiEffort = (typeof PI_EFFORTS)[number];
30
27
 
31
28
  export const CAPABILITIES = ["explain", "show", "btw", "advisor", "review"] as const;
@@ -53,20 +50,10 @@ export const CLAUDE_MODELS = [
53
50
  { id: "opus", label: "Claude Opus" },
54
51
  ] as const;
55
52
 
56
- export const GROK_MODELS = [
57
- { id: "grok-4.7", label: "Grok 4.7" },
58
- { id: "grok-4.7-build-fast", label: "Grok 4.7 Build Fast" },
59
- ] as const;
60
-
61
- export const CODEX_MODELS = [
62
- { id: "gpt-5.5", label: "GPT-5.5" },
63
- { id: "gpt-5.4", label: "GPT-5.4" },
64
- ] as const;
65
-
66
- export const MUSE_MODELS = [
67
- { id: "muse-spark-1.3-contributor", label: "Muse Spark 1.3 Contributor" },
68
- { id: "muse-spark-1.3", label: "Muse Spark 1.3" },
69
- ] as const;
53
+ export type CodexModelChoice = {
54
+ value: string;
55
+ label: string;
56
+ };
70
57
 
71
58
  export type AgyModelFamily = {
72
59
  id: string;
@@ -79,7 +66,7 @@ export const DEFAULT_SHOW_TURNS = 1;
79
66
 
80
67
  export function parseBackend(value: unknown, context: string): BackendName {
81
68
  if (typeof value !== "string" || !BACKENDS.some((backend) => backend === value)) {
82
- throw new Error(`${context} backend must be "agy", "claude", "grok", "codex", "muse", or "pi".`);
69
+ throw new Error(`${context} backend must be "agy", "claude", "codex", or "pi".`);
83
70
  }
84
71
  return value as BackendName;
85
72
  }
@@ -92,18 +79,10 @@ export function isClaudeEffort(effort: unknown): effort is ClaudeEffort | "defau
92
79
  return effort === "default" || CLAUDE_EFFORTS.some((item) => item === effort);
93
80
  }
94
81
 
95
- export function isGrokEffort(effort: unknown): effort is GrokEffort | "default" {
96
- return effort === "default" || GROK_EFFORTS.some((item) => item === effort);
97
- }
98
-
99
82
  export function isCodexEffort(effort: unknown): effort is CodexEffort | "default" {
100
83
  return effort === "default" || CODEX_EFFORTS.some((item) => item === effort);
101
84
  }
102
85
 
103
- export function isMuseEffort(effort: unknown): effort is MuseEffort | "default" {
104
- return effort === "default" || MUSE_EFFORTS.some((item) => item === effort);
105
- }
106
-
107
86
  // The in-process Pi backend accepts the whole BroEffort range; createAgentSession clamps it to
108
87
  // what the chosen physical model actually supports.
109
88
  export function isPiEffort(effort: unknown): effort is BroEffort {
@@ -119,27 +98,11 @@ export function resolveClaudeModel(input: string): string {
119
98
  return alias ? alias.id : trimmed;
120
99
  }
121
100
 
122
- // Grok seeds resolve to themselves; any other non-empty string passes through
123
- // untouched as an explicit user-entered model ID (installed `grok models` confirms).
124
- export function resolveGrokModel(input: string): string {
125
- const trimmed = input.trim();
126
- if (!trimmed) throw new Error("Grok model must be a non-empty model ID (grok-4.7, grok-4.7-build-fast, or an explicit model ID).");
127
- return trimmed;
128
- }
129
-
130
- // Codex seeds resolve to themselves; any other non-empty string passes through
131
- // untouched as an explicit user-entered model ID.
101
+ // Codex models are discovered live from Codex's local models_cache.json, and any
102
+ // non-empty string passes through untouched as an explicit model ID.
132
103
  export function resolveCodexModel(input: string): string {
133
104
  const trimmed = input.trim();
134
- if (!trimmed) throw new Error("Codex model must be a non-empty model ID (gpt-5.5, gpt-5.4, or an explicit model ID).");
135
- return trimmed;
136
- }
137
-
138
- // Muse seeds resolve to themselves; any other non-empty string passes through
139
- // untouched as an explicit user-entered model ID.
140
- export function resolveMuseModel(input: string): string {
141
- const trimmed = input.trim();
142
- if (!trimmed) throw new Error("Muse model must be a non-empty model ID (muse-spark-1.3-contributor, muse-spark-1.3, or an explicit model ID).");
105
+ if (!trimmed) throw new Error("Codex model must be a non-empty model ID.");
143
106
  return trimmed;
144
107
  }
145
108
 
@@ -154,7 +117,7 @@ export function resolvePiModel(input: string): string {
154
117
  return trimmed;
155
118
  }
156
119
 
157
- export type ExternalBackend = "claude" | "grok" | "codex" | "muse" | "pi";
120
+ export type ExternalBackend = "claude" | "codex" | "pi";
158
121
 
159
122
  export interface ExternalBackendMeta {
160
123
  readonly name: ExternalBackend;
@@ -180,36 +143,16 @@ export const EXTERNAL_BACKENDS: Record<ExternalBackend, ExternalBackendMeta> = {
180
143
  isEffort: isClaudeEffort,
181
144
  resolveModel: resolveClaudeModel,
182
145
  },
183
- grok: {
184
- name: "grok",
185
- label: "Grok",
186
- prefix: "grok:",
187
- efforts: GROK_EFFORTS,
188
- models: GROK_MODELS,
189
- effortHelp: '"default", "low", "medium", "high", or "xhigh"',
190
- isEffort: isGrokEffort,
191
- resolveModel: resolveGrokModel,
192
- },
193
146
  codex: {
194
147
  name: "codex",
195
148
  label: "Codex",
196
149
  prefix: "codex:",
197
150
  efforts: CODEX_EFFORTS,
198
- models: CODEX_MODELS,
199
- effortHelp: '"default", "low", "medium", "high", or "xhigh"',
151
+ models: [],
152
+ effortHelp: '"default", "low", "medium", "high", "xhigh", or "max"',
200
153
  isEffort: isCodexEffort,
201
154
  resolveModel: resolveCodexModel,
202
155
  },
203
- muse: {
204
- name: "muse",
205
- label: "Muse",
206
- prefix: "muse:",
207
- efforts: MUSE_EFFORTS,
208
- models: MUSE_MODELS,
209
- effortHelp: '"default", "minimal", "low", "medium", "high", "xhigh", or "max"',
210
- isEffort: isMuseEffort,
211
- resolveModel: resolveMuseModel,
212
- },
213
156
  // Pi models are addressed by "<provider>/<id>" and resolved live from the host registry,
214
157
  // so there are no fixed seed models and no prefix form. The `pi:` prefix is only the transport
215
158
  // tag the picker uses to carry the choice back into applyModelChange; the stored and displayed
@@ -279,9 +222,11 @@ export function toPiModelChoices(
279
222
  return choices;
280
223
  }
281
224
 
225
+ const AGY_EFFORT_HELP = '"default", "low", "medium", "high", "xhigh", or "max"';
226
+
282
227
  export function parseModelEffortPair(value: unknown, context: string): ModelEffortPair {
283
228
  if (!isRecord(value) || typeof value.model !== "string" || !value.model.trim()) {
284
- throw new Error(`${context} must contain a model and effort set to "default", "low", "medium", or "high".`);
229
+ throw new Error(`${context} must contain a model and effort set to ${AGY_EFFORT_HELP}.`);
285
230
  }
286
231
  const backend = value.backend === undefined ? undefined : parseBackend(value.backend, context);
287
232
  if (backend && backend in EXTERNAL_BACKENDS) {
@@ -292,7 +237,7 @@ export function parseModelEffortPair(value: unknown, context: string): ModelEffo
292
237
  return { backend, model: value.model.trim(), effort: value.effort };
293
238
  }
294
239
  if (!isAgyEffort(value.effort)) {
295
- throw new Error(`${context} must contain a model and effort set to "default", "low", "medium", or "high".`);
240
+ throw new Error(`${context} must contain a model and effort set to ${AGY_EFFORT_HELP}.`);
296
241
  }
297
242
  const pair: ModelEffortPair = { model: value.model.trim(), effort: value.effort };
298
243
  if (backend !== undefined) pair.backend = backend;
@@ -312,7 +257,7 @@ export function parseOverrides(value: unknown): Partial<Record<Capability, Model
312
257
 
313
258
  export function parseBroSettings(value: unknown): BroSettings {
314
259
  if (!isRecord(value)) {
315
- throw new Error('Settings must contain a model and effort set to "default", "low", "medium", or "high".');
260
+ throw new Error(`Settings must contain a model and effort set to ${AGY_EFFORT_HELP}.`);
316
261
  }
317
262
  // v2 disk shape: { version: 2, default: { backend, model, effort }, mode, showTurns, overrides }.
318
263
  // Reads never rewrite: a legacy flat file keeps parsing into backend-less (Agy) settings.
@@ -353,11 +298,24 @@ export function applyModelChange(
353
298
  }
354
299
 
355
300
  const family = families.find((item) => item.id === newValue || item.variants.some((variant) => variant.id === newValue));
356
- if (!family) return undefined;
301
+ const isCurrentAgy = (currentPair.backend ?? "agy") === "agy";
302
+ if (!family) {
303
+ const trimmed = newValue.trim();
304
+ if (!trimmed) return undefined;
305
+ return {
306
+ model: trimmed,
307
+ effort: isCurrentAgy && isAgyEffort(currentPair.effort) ? currentPair.effort : "default",
308
+ };
309
+ }
310
+
311
+ // If the user explicitly entered a variant ID (e.g. "gemini-neon-xhigh"), honor its effort.
312
+ const explicitVariant = family.variants.find((variant) => variant.id === newValue && variant.effort !== undefined);
313
+ if (explicitVariant?.effort) {
314
+ return { model: family.id, effort: explicitVariant.effort };
315
+ }
357
316
 
358
317
  // Resolve current pair first so variant suffixes (e.g. gemini-a-high) resolve to their canonical effort
359
318
  const resolved = resolveModelEffort(currentPair, families as AgyModelFamily[]);
360
- const isCurrentAgy = (currentPair.backend ?? "agy") === "agy";
361
319
  const effectiveEffort = (isCurrentAgy && resolved.family) ? resolved.pair.effort : currentPair.effort;
362
320
 
363
321
  const keepCurrent = isCurrentAgy && (
@@ -425,7 +383,7 @@ export function resolveModelEffort(
425
383
  pair: ModelEffortPair,
426
384
  families: AgyModelFamily[],
427
385
  ): { pair: ModelEffortPair; family?: AgyModelFamily } {
428
- // Claude/Grok/Codex/Muse selections never resolve through the Agy catalog; they pass through untouched.
386
+ // Claude/Codex/Pi selections never resolve through the Agy catalog; they pass through untouched.
429
387
  if (pair.backend && pair.backend !== "agy") return { pair };
430
388
  const family = families.find((item) => item.id === pair.model || item.variants.some((variant) => variant.id === pair.model));
431
389
  if (!family) return { pair };
@@ -448,7 +406,7 @@ export function capabilityBackend(settings: BroSettings, capability: Capability)
448
406
  }
449
407
 
450
408
  // Routes one capability's whole pair to its backend execution selection. Agy keeps the
451
- // existing model/effort split; Claude/Grok/Codex/Muse carry the model plus an optional effort
409
+ // existing model/effort split; Claude/Codex/Pi carry the model plus an optional effort
452
410
  // ("default" means the CLI's own default and is omitted). Throws for an effort the
453
411
  // resolved backend does not support instead of silently sending a mismatched pair.
454
412
  export function selectionForCapability(settings: BroSettings, capability: Capability): BackendSelection {
@@ -494,7 +452,7 @@ export function effortDisplay(resolved: { pair: ModelEffortPair; family?: AgyMod
494
452
  const meta = EXTERNAL_BACKENDS[backend as ExternalBackend];
495
453
  return meta.isEffort(resolved.pair.effort) ? resolved.pair.effort : `${resolved.pair.effort} (unsupported)`;
496
454
  }
497
- if (!resolved.family) return "unavailable";
455
+ if (!resolved.family) return isAgyEffort(resolved.pair.effort) ? resolved.pair.effort : `${resolved.pair.effort} (unsupported)`;
498
456
  const fixed = !resolved.family.efforts.length;
499
457
  const valid = fixed ? resolved.pair.effort === "default" : resolved.family.efforts.includes(resolved.pair.effort as AgyEffort);
500
458
  if (!valid) return `${resolved.pair.effort} (unsupported)`;
@@ -544,6 +502,65 @@ export async function readSettings(): Promise<BroSettings> {
544
502
  }
545
503
  }
546
504
 
505
+ const RETIRED_BACKENDS = new Set(["grok", "muse"]);
506
+
507
+ /**
508
+ * In-memory recovery for `/bro config` only when `bro-settings.json` still names
509
+ * a retired backend (`grok` or `muse`). Never rewrites disk and never relaxes
510
+ * `readSettings()` for execution.
511
+ */
512
+ export function recoverRetiredBackendSettings(value: unknown): { settings: BroSettings; retired: string[] } | undefined {
513
+ if (!isRecord(value) || (value.version !== undefined && value.version !== 2)) return undefined;
514
+ const retired = new Set<string>();
515
+ const clone: Record<string, unknown> = { ...value };
516
+ const fallbackDefault = () => {
517
+ const host = getPiHostContext();
518
+ const active = host?.model;
519
+ return active && piPhysicalModel(host?.modelRegistry, active.provider, active.id)
520
+ ? { backend: "pi", model: piModelValue(active.provider, active.id), effort: "default" }
521
+ : { backend: "agy", model: "gemini-3.7-flash", effort: "low" };
522
+ };
523
+ if (isRecord(value.default) && typeof value.default.backend === "string" && RETIRED_BACKENDS.has(value.default.backend)) {
524
+ retired.add(value.default.backend);
525
+ clone.default = fallbackDefault();
526
+ } else if (value.default === undefined && typeof value.backend === "string" && RETIRED_BACKENDS.has(value.backend)) {
527
+ retired.add(value.backend);
528
+ Object.assign(clone, fallbackDefault());
529
+ }
530
+ if (isRecord(value.overrides)) {
531
+ const nextOverrides: Record<string, unknown> = {};
532
+ for (const [cap, pair] of Object.entries(value.overrides)) {
533
+ if (isRecord(pair) && typeof pair.backend === "string" && RETIRED_BACKENDS.has(pair.backend)) {
534
+ retired.add(pair.backend);
535
+ continue;
536
+ }
537
+ nextOverrides[cap] = pair;
538
+ }
539
+ clone.overrides = nextOverrides;
540
+ }
541
+ if (!retired.size) return undefined;
542
+ return { settings: parseBroSettings(clone), retired: [...retired] };
543
+ }
544
+
545
+ export async function readSettingsForConfig(): Promise<{ settings: BroSettings; notice?: string }> {
546
+ try {
547
+ return { settings: await readSettings() };
548
+ } catch (error) {
549
+ try {
550
+ const raw = JSON.parse(await readFile(settingsFile(), "utf8")) as unknown;
551
+ const recovered = recoverRetiredBackendSettings(raw);
552
+ if (recovered) {
553
+ const names = recovered.retired.join(" and ");
554
+ return {
555
+ settings: recovered.settings,
556
+ notice: `Removed retired backend (${names}) from config view — pick a replacement and save.`,
557
+ };
558
+ }
559
+ } catch { /* Fall through to the original settings error. */ }
560
+ throw error;
561
+ }
562
+ }
563
+
547
564
  // Exported so persistence stays testable without touching the filesystem. This only ever omits
548
565
  // the `overrides` key itself when there are no overrides at all — it does NOT deduplicate or drop
549
566
  // any individual override that happens to match the shared default; see withCapabilityOverride
@@ -1,204 +0,0 @@
1
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import { withDoctor } from "../util.ts";
5
- import { checkedBtwContinuation, cliExitFailure, finishCliAttempt, startCliAttempt, stoppedCliOutcome } from "./cli-process.ts";
6
- import { btwToolName, type BackendOnProgress, type BackendOutcome, type BackendRequest } from "./contract.ts";
7
-
8
- type GrokEvent = {
9
- permissionMode?: unknown;
10
- type?: unknown;
11
- subtype?: unknown;
12
- is_error?: unknown;
13
- result?: unknown;
14
- errors?: unknown;
15
- message?: unknown;
16
- parent_tool_use_id?: unknown;
17
- stop_reason?: unknown;
18
- session_id?: unknown;
19
- event?: { type?: unknown; delta?: { type?: unknown; text?: unknown } };
20
- };
21
-
22
- // Grok's "restricted" access is a request in the prompt, NOT technical enforcement: every Grok run
23
- // has all tools on (--sandbox off, bypassPermissions, subagents/web/scheduler available), so the
24
- // model can still read, write or reach out if it ignores this. The parent UI owns telling the user
25
- // that truthfully.
26
- export const GROK_RESTRICTED_PREFIX =
27
- "Bro restricted mode (a request, not a technical restriction): answer only from the context supplied in this prompt. " +
28
- "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.";
29
-
30
- // Grok runs explain, show, btw, and advisor with all capabilities on (--sandbox off,
31
- // bypassPermissions, no tool blacklist); Guided Review (`review`) runs in the caller's workspace
32
- // under Grok's read-only sandbox (--sandbox read-only, --permission-mode dontAsk).
33
- // explain/show run in a fresh mkdtemp scratch cwd removed afterwards (the Agy pattern);
34
- // btw (both accesses) runs in the caller's workspace cwd and continues natively with --resume, whose
35
- // session keeps the cwd it was created in; the advisor and review run fresh in the workspace.
36
- // Restricted requests other than review get GROK_RESTRICTED_PREFIX (review must be allowed to
37
- // inspect the captured checkout). The prompt goes through a private 0600 file in its own mkdtemp
38
- // directory, removed once the attempt ends.
39
- // Only a top-level terminal `result` with success/is_error false/end_turn is authoritative; the
40
- // first failure (a failed result or a top-level `error` event, even after a success) is latched.
41
- // Nested (subagent) frames are ignored. The advisor reports activity labels only; explain/show/btw/review
42
- // report top-level text_delta progress, falling back to an assistant message's text
43
- // blocks only when no delta streamed for it. Thinking is never reported. btw requires init/result
44
- // session ids to agree (and to equal the resumed id) and returns that id as the continuation.
45
- export async function executeGrok(
46
- request: BackendRequest,
47
- selection: { model: string; effort?: string },
48
- signal: AbortSignal,
49
- onProgress: BackendOnProgress | undefined,
50
- killEscalationMs: number,
51
- deadlineMs: number,
52
- ): Promise<BackendOutcome> {
53
- const isAdvisor = request.feature === "advisor";
54
- const isBtw = request.feature === "btw";
55
- const inspect = request.feature === "review";
56
- const action = inspect ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
57
- const timeoutVerb = inspect ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
58
- 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.";
59
- // Review inspects the captured checkout, so it must not carry the "do not inspect" restriction.
60
- const prompt = request.access === "restricted" && !inspect ? `${GROK_RESTRICTED_PREFIX}\n\n${request.prompt}` : request.prompt;
61
-
62
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
63
- const promptDirectory = await mkdtemp(join(tmpdir(), "pi-bro-grok-"));
64
- let runDirectory: string | undefined;
65
- try {
66
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
67
- const promptFile = join(promptDirectory, "prompt.txt");
68
- await writeFile(promptFile, prompt, { encoding: "utf8", mode: 0o600 });
69
- if (request.access !== "workspace-full" && !isBtw && !inspect) runDirectory = await mkdtemp(join(tmpdir(), "pi-bro-"));
70
- if (signal.aborted) return { status: "cancelled", message: "Canceled." };
71
-
72
- const { child, attempt, diagnostics } = startCliAttempt("grok",
73
- [
74
- // 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.
75
- ...(inspect ? ["--sandbox", "read-only", "--permission-mode", "dontAsk"] : ["--sandbox", "off", "--permission-mode", "bypassPermissions"]),
76
- "--output-format",
77
- "streaming-messages-json",
78
- "--include-partial-messages",
79
- "--model", selection.model,
80
- ...(selection.effort ? ["--reasoning-effort", selection.effort] : []),
81
- ...(isBtw && request.continuation ? ["--resume", request.continuation.id] : []),
82
- "--prompt-file",
83
- promptFile,
84
- ],
85
- { cwd: runDirectory ?? request.cwd, stdio: ["ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
86
-
87
- let partial = "";
88
- let streamedSinceAssistant = false;
89
- let initSessionId: string | undefined;
90
- let resultSessionId: string | undefined;
91
- let final: string | undefined;
92
- let terminalError: string | undefined;
93
-
94
- const handleLine = (line: string) => {
95
- if (!line.trim() || attempt.causeOf()) return;
96
- let event: GrokEvent;
97
- try {
98
- event = JSON.parse(line) as GrokEvent;
99
- } catch {
100
- throw new Error("Grok emitted invalid streaming-messages-json output.");
101
- }
102
- if (event.parent_tool_use_id !== undefined && event.parent_tool_use_id !== null) return;
103
- if (event.type === "system" && event.subtype === "init") {
104
- // Review asks for dontAsk, but `--sandbox read-only` in argv is the real boundary: another
105
- // restricting mode is not a downgrade, and only auto-approval means the request was
106
- // ignored. Both paths fail closed when the mode is missing, exactly like explain/btw.
107
- const escalated = event.permissionMode === "bypassPermissions" || event.permissionMode === "always-approve";
108
- if (inspect ? typeof event.permissionMode !== "string" || escalated : event.permissionMode !== "bypassPermissions") {
109
- throw new Error(
110
- `Grok did not apply the required ${inspect ? "restricted" : "bypassPermissions"} mode; check Grok policy/configuration.`,
111
- );
112
- }
113
- if (typeof event.session_id === "string") initSessionId = event.session_id;
114
- }
115
- if (!isAdvisor && event.type === "stream_event" && event.event?.type === "content_block_delta") {
116
- const delta = event.event.delta;
117
- if (delta?.type === "text_delta" && typeof delta.text === "string" && delta.text) {
118
- partial += delta.text;
119
- streamedSinceAssistant = true;
120
- onProgress?.({ kind: "text", text: partial });
121
- }
122
- }
123
- if (event.type === "error") {
124
- terminalError ??= `Grok error: ${typeof event.message === "string" && event.message.trim() ? event.message.trim() : "unknown error"}`;
125
- return;
126
- }
127
- const message = event.message as { content?: unknown } | undefined;
128
- if (!isAdvisor && event.type === "assistant" && Array.isArray(message?.content)) {
129
- // Fallback only: an assistant message whose text already streamed as deltas is not re-appended.
130
- if (!streamedSinceAssistant) {
131
- const text = (message.content as Array<{ type?: unknown; text?: unknown }>)
132
- .map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : ""))
133
- .join("");
134
- if (text) {
135
- partial += text;
136
- onProgress?.({ kind: "text", text: partial });
137
- }
138
- }
139
- streamedSinceAssistant = false;
140
- }
141
- if ((isAdvisor || isBtw || (inspect && request.reportReviewTools)) && event.type === "assistant" && Array.isArray(message?.content)) {
142
- for (const block of message.content as Array<{ type?: unknown; name?: unknown; text?: unknown }>) {
143
- if (attempt.causeOf()) break;
144
- if ((isBtw || (inspect && request.reportReviewTools)) && block?.type !== "tool_use") continue;
145
- const tool = block?.type === "tool_use" ? btwToolName(block.name) : undefined;
146
- const label =
147
- block?.type === "tool_use" && typeof block.name === "string"
148
- ? ((isBtw || (inspect && request.reportReviewTools)) ? tool : block.name.trim())
149
- : block?.type === "text" && typeof block.text === "string"
150
- ? block.text.split("\n").find((text) => text.trim())?.trim()
151
- : undefined;
152
- if (label) onProgress?.({ kind: "activity", label, timestamp: Date.now(), ...(tool ? { tool } : {}) });
153
- }
154
- }
155
- if (event.type !== "result") return;
156
- if (typeof event.session_id === "string") resultSessionId = event.session_id;
157
- if (event.subtype === "success" && event.is_error === false) {
158
- if (event.stop_reason !== "end_turn") {
159
- terminalError ??= `Grok did not complete the ${isAdvisor ? "advice" : "answer"} (stop reason: ${String(event.stop_reason)}).`;
160
- } else if (typeof event.result === "string") {
161
- final = event.result;
162
- } else {
163
- terminalError ??= "Grok reported success without a final result.";
164
- }
165
- return;
166
- }
167
- const firstError = Array.isArray(event.errors)
168
- ? event.errors.map((item) => (typeof item === "string" ? item : (item as { message?: unknown })?.message)).find((item) => typeof item === "string" && item.trim())
169
- : undefined;
170
- const detail =
171
- typeof firstError === "string"
172
- ? firstError.trim()
173
- : typeof event.subtype === "string" && event.subtype !== "success"
174
- ? event.subtype
175
- : typeof event.result === "string" && event.result.trim()
176
- ? event.result.trim()
177
- : "turn failed";
178
- terminalError ??= `Grok failed: ${detail}`;
179
- };
180
-
181
- const finished = await finishCliAttempt(child, attempt, "Grok", handleLine);
182
- const code = finished.code!;
183
- const stopped = stoppedCliOutcome("Grok", attempt, finished, diagnostics,
184
- `Grok timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
185
- if (stopped) return stopped;
186
- const partialText = partial ? { partialText: partial } : {};
187
- if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
188
- if (code !== 0) return { status: "failure", message: cliExitFailure("Grok", action, diagnostics.stderr), ...partialText };
189
- if (final === undefined) {
190
- return { status: "failure", message: withDoctor(`Grok exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
191
- }
192
- const text = final.trim();
193
- if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
194
- if (!isBtw) return { status: "success", text };
195
- const continuation = checkedBtwContinuation("Grok", request.continuation,
196
- { init: initSessionId, result: resultSessionId });
197
- if ("error" in continuation)
198
- return { status: "failure", message: withDoctor(continuation.error), ...partialText };
199
- return { status: "success", text, continuation };
200
- } finally {
201
- if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
202
- await rm(promptDirectory, { recursive: true, force: true });
203
- }
204
- }