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.
@@ -0,0 +1,204 @@
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
+ }
@@ -0,0 +1,173 @@
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 MuseEnvelope = {
9
+ schema_version?: unknown;
10
+ payload_type?: unknown;
11
+ stream?: { kind?: unknown; id?: unknown };
12
+ payload?: {
13
+ kind?: unknown;
14
+ command_id?: unknown;
15
+ run_stream?: { kind?: unknown; id?: unknown };
16
+ text?: unknown;
17
+ reason?: unknown;
18
+ correlation_facts?: { tool_name?: unknown };
19
+ event?: { message?: unknown };
20
+ command?: unknown;
21
+ path?: unknown;
22
+ file_path?: unknown;
23
+ query?: unknown;
24
+ };
25
+ };
26
+
27
+ export async function executeMuse(
28
+ request: BackendRequest,
29
+ selection: { model: string; effort?: string },
30
+ signal: AbortSignal,
31
+ onProgress: BackendOnProgress | undefined,
32
+ killEscalationMs: number,
33
+ deadlineMs: number,
34
+ ): Promise<BackendOutcome> {
35
+ const isAdvisor = request.feature === "advisor";
36
+ const isBtw = request.feature === "btw";
37
+ const inspect = request.feature === "review";
38
+ const full = request.access === "workspace-full";
39
+ const action = request.feature === "review" ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
40
+ const timeoutVerb = request.feature === "review" ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
41
+ 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.";
42
+
43
+ if (signal.aborted) return { status: "cancelled", message: "Canceled." };
44
+ const promptDirectory = await mkdtemp(join(tmpdir(), "pi-bro-muse-"));
45
+ let runDirectory: string | undefined;
46
+
47
+ try {
48
+ if (signal.aborted) return { status: "cancelled", message: "Canceled." };
49
+ const promptFile = join(promptDirectory, "prompt.txt");
50
+ await writeFile(promptFile, request.prompt, { encoding: "utf8", mode: 0o600 });
51
+ if (!full && !isBtw && !inspect) runDirectory = await mkdtemp(join(tmpdir(), "pi-bro-"));
52
+ if (signal.aborted) return { status: "cancelled", message: "Canceled." };
53
+ const workspace = runDirectory ?? request.cwd!;
54
+
55
+ const args = [
56
+ "exec",
57
+ "--json",
58
+ "--provider", "meta",
59
+ "--workspace", workspace,
60
+ ...(!isBtw ? ["--no-session-log"] : []),
61
+ ...(full ? ["--yolo"] : ["--disable-approval", "--disable-write", "--disable-shell"]),
62
+ ...(inspect ? ["--disable-web-tools", "--no-foreign-personal-context"] : []),
63
+ ...(isBtw && request.continuation ? ["--session-id", request.continuation.id] : []),
64
+ "--model", selection.model,
65
+ ...(selection.effort ? ["--reasoning-effort", selection.effort] : []),
66
+ "--prompt-file", promptFile,
67
+ ];
68
+
69
+ const { child, attempt, diagnostics } = startCliAttempt("muse", args, {
70
+ cwd: workspace,
71
+ stdio: ["ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
72
+
73
+ let partial = "";
74
+ let rootCommandId: string | undefined;
75
+ let rootRunId: string | undefined;
76
+ let sessionId: string | undefined;
77
+ let final: string | undefined;
78
+ let sawTerminal = false;
79
+ let terminalError: string | undefined;
80
+
81
+ const handleLine = (line: string) => {
82
+ if (!line.trim() || attempt.causeOf()) return;
83
+ let envelope: MuseEnvelope;
84
+ try {
85
+ envelope = JSON.parse(line) as MuseEnvelope;
86
+ } catch {
87
+ throw new Error("Muse emitted invalid JSON output.");
88
+ }
89
+ const payload = envelope.payload;
90
+ if (envelope.stream?.kind === "session" && typeof envelope.stream.id === "string") {
91
+ if (!sessionId) sessionId = envelope.stream.id;
92
+ }
93
+ if (envelope.payload_type === "runtime.command.accepted") {
94
+ if (!rootCommandId && typeof payload?.command_id === "string") {
95
+ rootCommandId = payload.command_id;
96
+ }
97
+ return;
98
+ }
99
+ if (!rootRunId && (envelope.payload_type === "session.run.linked" || envelope.payload_type === "run.lifecycle.started")) {
100
+ const runStream = payload?.run_stream;
101
+ if (runStream?.kind === "run" && typeof runStream.id === "string") {
102
+ if (rootCommandId === undefined || payload?.command_id === rootCommandId) {
103
+ rootRunId = runStream.id;
104
+ if (envelope.stream?.kind === "session" && typeof envelope.stream.id === "string") {
105
+ sessionId = envelope.stream.id;
106
+ }
107
+ }
108
+ }
109
+ return;
110
+ }
111
+ const runStream = payload?.run_stream;
112
+ const isRoot = rootRunId !== undefined && runStream?.kind === "run" && runStream.id === rootRunId;
113
+
114
+ if (isAdvisor || isBtw || (inspect && request.reportReviewTools)) {
115
+ if (envelope.payload_type === "tool.result") {
116
+ const facts = payload?.correlation_facts as { tool_name?: unknown } | undefined;
117
+ const toolName = typeof facts?.tool_name === "string" && facts.tool_name ? facts.tool_name : "tool";
118
+ const candidate = [payload?.text, payload?.command, payload?.path, payload?.file_path, payload?.query]
119
+ .find((v) => typeof v === "string" && v.trim());
120
+ const preview = typeof candidate === "string" ? candidate.replace(/\s+/g, " ").trim() : "";
121
+ const tool = btwToolName(toolName);
122
+ const label = (isBtw || (inspect && request.reportReviewTools)) ? tool : `${toolName}${preview ? ` ${preview}` : ""}`;
123
+ if (label) onProgress?.({ kind: "activity", label, timestamp: Date.now(), ...(tool ? { tool } : {}) });
124
+ } else if (isAdvisor && envelope.payload_type === "task.lifecycle.status") {
125
+ const event = payload?.event as { message?: unknown } | undefined;
126
+ if (typeof event?.message === "string" && event.message.trim()) {
127
+ onProgress?.({ kind: "activity", label: event.message.trim(), timestamp: Date.now() });
128
+ }
129
+ }
130
+ }
131
+ if (!isAdvisor && isRoot && envelope.payload_type === "run.output.delta") {
132
+ if (typeof payload?.text === "string" && payload.text) {
133
+ partial += payload.text;
134
+ onProgress?.({ kind: "text", text: partial });
135
+ }
136
+ }
137
+
138
+ if (!isRoot) return;
139
+ if (envelope.payload_type === "run.terminal.completed") {
140
+ sawTerminal = true;
141
+ if (typeof payload?.text === "string") {
142
+ final = payload.text;
143
+ }
144
+ } else if (envelope.payload_type === "run.terminal.failed") {
145
+ sawTerminal = true;
146
+ const reason = typeof payload?.reason === "string" && payload.reason.trim() ? payload.reason.trim() : "run did not complete";
147
+ terminalError ??= `Muse failed: ${reason}`;
148
+ }
149
+ };
150
+
151
+ const finished = await finishCliAttempt(child, attempt, "Muse", handleLine);
152
+ const code = finished.code!;
153
+ const stopped = stoppedCliOutcome("Muse", attempt, finished, diagnostics,
154
+ `Muse timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
155
+ if (stopped) return stopped;
156
+ const partialText = partial ? { partialText: partial } : {};
157
+ if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
158
+ if (code !== 0) return { status: "failure", message: cliExitFailure("Muse", action, diagnostics.stderr), ...partialText };
159
+ if (!sawTerminal) {
160
+ return { status: "failure", message: withDoctor(`Muse exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
161
+ }
162
+ const text = final?.trim();
163
+ if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
164
+ if (!isBtw) return { status: "success", text };
165
+ const continuation = checkedBtwContinuation("Muse", request.continuation, { id: sessionId });
166
+ if ("error" in continuation)
167
+ return { status: "failure", message: withDoctor(continuation.error), ...partialText };
168
+ return { status: "success", text, continuation };
169
+ } finally {
170
+ if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
171
+ await rm(promptDirectory, { recursive: true, force: true });
172
+ }
173
+ }