pi-bro 0.37.1 → 0.38.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +6 -8
- package/docs/examples.md +1 -1
- package/docs/feature-map.md +2 -3
- package/docs/features/explain.md +16 -20
- package/docs/features/show.md +9 -15
- package/docs/getting-started.md +4 -4
- package/docs/piG-agent-shell-qualification.md +1 -1
- package/docs/reference/commands.md +14 -29
- package/docs/reference/data-and-permissions.md +4 -4
- package/docs/reference/settings.md +3 -3
- package/docs/reference/troubleshooting.md +1 -1
- package/docs/user-guide.md +2 -2
- package/package.json +10 -1
- package/src/advisor.ts +1 -4
- package/src/architecture.ts +1 -1
- package/src/backend.ts +24 -1955
- package/src/backends/agy.ts +304 -0
- package/src/backends/claude.ts +169 -0
- package/src/backends/cli-process.ts +247 -0
- package/src/backends/codex.ts +182 -0
- package/src/backends/contract.ts +56 -0
- package/src/backends/grok.ts +204 -0
- package/src/backends/muse.ts +173 -0
- package/src/backends/pi.ts +493 -0
- package/src/bro.ts +47 -185
- package/src/btw.ts +12 -202
- package/src/cli-auth.ts +176 -0
- package/src/composer-modal.ts +197 -0
- package/src/explain-modal.ts +24 -75
- package/src/grill.ts +3 -2
- package/src/remember.ts +3 -2
- package/src/session-state.ts +46 -28
- package/src/simplify-engine.ts +50 -24
- package/src/simplify-ui.ts +165 -126
- package/src/sources.ts +3 -3
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { withDoctor } from "../util.ts";
|
|
5
|
+
import { finishCliAttempt, startCliAttempt, stoppedCliOutcome } from "./cli-process.ts";
|
|
6
|
+
import { btwToolName, type AgySelection, type BackendOnProgress, type BackendOutcome, type BackendRequest } from "./contract.ts";
|
|
7
|
+
|
|
8
|
+
export function agyFailureMessage(action: string, result: { code: number; killed: boolean; stderr: string }): string {
|
|
9
|
+
if (result.killed) return `Agy timed out while trying to ${action}. Run \`/bro doctor\` for setup help.`;
|
|
10
|
+
const detail = result.stderr.trim();
|
|
11
|
+
if (detail) return `Agy could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`;
|
|
12
|
+
return `Agy could not ${action}. Make sure Agy is installed and signed in, then run \`/bro doctor\`.`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Strips a "-low/-medium/-high" suffix from a stored model id and separates it back into a plain
|
|
16
|
+
// Agy `--model`/`--effort` pair; a "default" effort omits --effort entirely (Agy's own default).
|
|
17
|
+
export function agySelection(pair: { model: string; effort: "default" | "low" | "medium" | "high" }): AgySelection {
|
|
18
|
+
if (pair.effort === "default") return { model: pair.model };
|
|
19
|
+
const suffix = (["low", "medium", "high"] as const).find((effort) => pair.model.endsWith(`-${effort}`));
|
|
20
|
+
return {
|
|
21
|
+
model: suffix ? pair.model.slice(0, -suffix.length - 1) : pair.model,
|
|
22
|
+
effort: pair.effort,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type AgyEvent = {
|
|
27
|
+
event?: string;
|
|
28
|
+
conversation_id?: string;
|
|
29
|
+
step_update?: { step_type?: string; text_delta?: unknown; tool_name?: unknown };
|
|
30
|
+
result?: { status?: string; response?: unknown; error?: unknown; conversation_id?: string };
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function parseExplainLine(line: string): { delta?: string; result?: string } {
|
|
34
|
+
let event: AgyEvent;
|
|
35
|
+
try {
|
|
36
|
+
event = JSON.parse(line) as AgyEvent;
|
|
37
|
+
} catch {
|
|
38
|
+
throw new Error("Agy returned invalid streaming data.");
|
|
39
|
+
}
|
|
40
|
+
if (event.event === "step_update" && event.step_update?.step_type === "agent_response" && typeof event.step_update.text_delta === "string") {
|
|
41
|
+
return { delta: event.step_update.text_delta };
|
|
42
|
+
}
|
|
43
|
+
if (event.event === "result") {
|
|
44
|
+
if (event.result?.status !== "SUCCESS" || typeof event.result.response !== "string") {
|
|
45
|
+
throw new Error("Agy did not complete the explanation successfully.");
|
|
46
|
+
}
|
|
47
|
+
return { result: event.result.response };
|
|
48
|
+
}
|
|
49
|
+
return {};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function parseBtwAgyLine(line: string): { delta?: string; result?: string; conversationId?: string; error?: string; activity?: string } {
|
|
53
|
+
let event: AgyEvent;
|
|
54
|
+
try {
|
|
55
|
+
event = JSON.parse(line) as AgyEvent;
|
|
56
|
+
} catch {
|
|
57
|
+
throw new Error("Agy returned invalid streaming data.");
|
|
58
|
+
}
|
|
59
|
+
const conversationId = event.conversation_id ?? event.result?.conversation_id;
|
|
60
|
+
const stepType = event.step_update?.step_type;
|
|
61
|
+
const tool = stepType === "agent_response" || stepType === "assistant" ? undefined : btwToolName(event.step_update?.tool_name);
|
|
62
|
+
if (event.event === "step_update" && tool) {
|
|
63
|
+
return { activity: tool, conversationId };
|
|
64
|
+
}
|
|
65
|
+
if (event.event === "step_update" && event.step_update?.step_type === "agent_response" && typeof event.step_update.text_delta === "string") {
|
|
66
|
+
return { delta: event.step_update.text_delta, conversationId };
|
|
67
|
+
}
|
|
68
|
+
if (event.event === "result") {
|
|
69
|
+
if (event.result?.status !== "SUCCESS" || typeof event.result.response !== "string") {
|
|
70
|
+
const detail = typeof event.result?.error === "string" ? event.result.error : "Agy did not complete the turn successfully.";
|
|
71
|
+
return { error: detail, conversationId };
|
|
72
|
+
}
|
|
73
|
+
return { result: event.result.response, conversationId };
|
|
74
|
+
}
|
|
75
|
+
return { conversationId };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Explain/show and BTW use argv for small prompts and stdin NDJSON for large
|
|
79
|
+
// prompts; sandbox, cwd, timeout, and continuation semantics stay unchanged.
|
|
80
|
+
async function executeArgvPrint(
|
|
81
|
+
request: BackendRequest,
|
|
82
|
+
selection: AgySelection,
|
|
83
|
+
signal: AbortSignal,
|
|
84
|
+
onProgress: BackendOnProgress | undefined,
|
|
85
|
+
killEscalationMs: number,
|
|
86
|
+
deadlineMs: number,
|
|
87
|
+
): Promise<BackendOutcome> {
|
|
88
|
+
// Keep legacy CLI compatibility for small prompts; large inputs use the advisor's
|
|
89
|
+
// stdin protocol rather than risking Linux's per-argument byte limit.
|
|
90
|
+
const stdinPrompt = Buffer.byteLength(request.prompt, "utf8") >= 120_000;
|
|
91
|
+
const isBtw = request.feature === "btw";
|
|
92
|
+
const inspect = request.feature === "review";
|
|
93
|
+
const full = request.access === "workspace-full";
|
|
94
|
+
const printTimeout = full || inspect ? "10m" : "2m";
|
|
95
|
+
const action = inspect ? "complete the guided review request" : isBtw ? "answer the side question" : "simplify the response";
|
|
96
|
+
const timeoutVerb = inspect ? "during the guided review request" : isBtw ? "during the side conversation" : "while simplifying the response";
|
|
97
|
+
const emptyTextMessage = inspect ? "Agy returned no response for Guided Review." : isBtw ? "Agy returned no answer for the side question." : "Agy returned no final explanation.";
|
|
98
|
+
|
|
99
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
100
|
+
|
|
101
|
+
const runDirectory = full || inspect ? undefined : await mkdtemp(join(tmpdir(), "pi-bro-"));
|
|
102
|
+
if (signal.aborted) {
|
|
103
|
+
if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
|
|
104
|
+
return { status: "cancelled", message: "Canceled." };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
const { child, attempt, diagnostics } = startCliAttempt("agy",
|
|
109
|
+
[
|
|
110
|
+
...(full ? ["--dangerously-skip-permissions"] : ["--sandbox"]),
|
|
111
|
+
"--disable-slash-commands",
|
|
112
|
+
"--output-format",
|
|
113
|
+
"stream-json",
|
|
114
|
+
"--model",
|
|
115
|
+
selection.model,
|
|
116
|
+
...(selection.effort ? ["--effort", selection.effort] : []),
|
|
117
|
+
"--print-timeout",
|
|
118
|
+
printTimeout,
|
|
119
|
+
...(isBtw && request.continuation ? ["--conversation", request.continuation.id] : []),
|
|
120
|
+
...(stdinPrompt ? ["--input-format", "stream-json"] : ["--print", request.prompt]),
|
|
121
|
+
],
|
|
122
|
+
{
|
|
123
|
+
cwd: full || inspect ? request.cwd : runDirectory,
|
|
124
|
+
stdio: [stdinPrompt ? "pipe" : "ignore", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
|
|
125
|
+
|
|
126
|
+
let partial = "";
|
|
127
|
+
let final = "";
|
|
128
|
+
let conversationId = request.continuation?.id;
|
|
129
|
+
|
|
130
|
+
if (stdinPrompt) {
|
|
131
|
+
child.stdin?.on("error", () => { /* Report early exits through the close/error path. */ });
|
|
132
|
+
child.stdin?.end(`${JSON.stringify({ event: "user", message: { content: request.prompt } })}\n`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const handleLine = (line: string) => {
|
|
136
|
+
if (!line.trim() || attempt.causeOf()) return;
|
|
137
|
+
if (isBtw) {
|
|
138
|
+
const parsed = parseBtwAgyLine(line);
|
|
139
|
+
if (parsed.conversationId) conversationId = parsed.conversationId;
|
|
140
|
+
if (parsed.activity) onProgress?.({ kind: "activity", label: parsed.activity, timestamp: Date.now(), tool: parsed.activity });
|
|
141
|
+
if (parsed.error) throw new Error(parsed.error);
|
|
142
|
+
if (parsed.delta) {
|
|
143
|
+
partial += parsed.delta;
|
|
144
|
+
onProgress?.({ kind: "text", text: partial });
|
|
145
|
+
}
|
|
146
|
+
if (parsed.result !== undefined) final = parsed.result;
|
|
147
|
+
} else {
|
|
148
|
+
// Review-backed Grill receives tool events without changing review access.
|
|
149
|
+
if (inspect && request.reportReviewTools) {
|
|
150
|
+
const tool = parseBtwAgyLine(line).activity;
|
|
151
|
+
if (tool) onProgress?.({ kind: "activity", label: tool, timestamp: Date.now(), tool });
|
|
152
|
+
}
|
|
153
|
+
const parsed = parseExplainLine(line);
|
|
154
|
+
if (parsed.delta) {
|
|
155
|
+
partial += parsed.delta;
|
|
156
|
+
onProgress?.({ kind: "text", text: partial });
|
|
157
|
+
}
|
|
158
|
+
if (parsed.result !== undefined) final = parsed.result;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const finished = await finishCliAttempt(child, attempt, "Agy", handleLine);
|
|
163
|
+
const code = finished.code!;
|
|
164
|
+
const stopped = stoppedCliOutcome("Agy", attempt, finished, diagnostics,
|
|
165
|
+
`Agy timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
|
|
166
|
+
if (stopped) return stopped;
|
|
167
|
+
if (code !== 0) return { status: "failure", message: stdinPrompt && advisorFlagErrorHint(diagnostics.stderr)
|
|
168
|
+
? withDoctor("Large prompts require Agy 1.1.15+ with stdin support. Run `agy update`. " + diagnostics.stderr.trim())
|
|
169
|
+
: agyFailureMessage(action, { code, killed: false, stderr: diagnostics.stderr }) };
|
|
170
|
+
|
|
171
|
+
const text = final.trim();
|
|
172
|
+
if (!text) return { status: "failure", message: withDoctor(diagnostics.stderr.trim() || emptyTextMessage) };
|
|
173
|
+
return { status: "success", text, continuation: isBtw && conversationId ? { id: conversationId } : undefined };
|
|
174
|
+
} finally {
|
|
175
|
+
if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
type AdvisorAgyEvent = {
|
|
180
|
+
event?: string;
|
|
181
|
+
step_update?: { tool_name?: unknown; step_type?: unknown; text_delta?: unknown };
|
|
182
|
+
result?: { status?: unknown; response?: unknown; error?: unknown };
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// Only a tool_name or a user-facing agent_response/assistant text_delta becomes an activity label
|
|
186
|
+
// -- hidden reasoning/thinking step_types and any other shape stay unreported, never leaked into
|
|
187
|
+
// progress.
|
|
188
|
+
function advisorActivityFromEvent(event: AdvisorAgyEvent): string | undefined {
|
|
189
|
+
if (event.event !== "step_update" || !event.step_update || typeof event.step_update !== "object") return undefined;
|
|
190
|
+
const update = event.step_update;
|
|
191
|
+
if (typeof update.tool_name === "string" && update.tool_name.trim()) return update.tool_name.trim();
|
|
192
|
+
const isUserFacingText = update.step_type === "agent_response" || update.step_type === "assistant";
|
|
193
|
+
if (isUserFacingText && typeof update.text_delta === "string" && update.text_delta.trim()) {
|
|
194
|
+
return update.text_delta.split("\n").find((line) => line.trim())?.trim();
|
|
195
|
+
}
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Older agy CLIs reject --input-format with Go's flag-package usage dump and exit before running
|
|
200
|
+
// the agent at all (no terminal result event). Turn that into an actionable version hint instead
|
|
201
|
+
// of a bare "no terminal result" error.
|
|
202
|
+
export function advisorFlagErrorHint(stderr: string): string | undefined {
|
|
203
|
+
const match = /flags? provided but not defined: -([a-z0-9-]+)/i.exec(stderr);
|
|
204
|
+
if (!match) return undefined;
|
|
205
|
+
return `flag provided but not defined: -${match[1]} (installed Agy CLI is too old; the advisor needs Agy 1.1.15+ for --input-format stream-json — run \`agy update\`, then \`/bro doctor\`)`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Advisor speaks stdin NDJSON (never --print argv) and always runs fresh in the workspace with
|
|
209
|
+
// tools auto-approved; it never resumes and never passes --conversation.
|
|
210
|
+
async function executeAdvisorStdin(
|
|
211
|
+
request: BackendRequest,
|
|
212
|
+
selection: AgySelection,
|
|
213
|
+
signal: AbortSignal,
|
|
214
|
+
onProgress: BackendOnProgress | undefined,
|
|
215
|
+
killEscalationMs: number,
|
|
216
|
+
deadlineMs: number,
|
|
217
|
+
): Promise<BackendOutcome> {
|
|
218
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
219
|
+
|
|
220
|
+
const { child, attempt, diagnostics } = startCliAttempt("agy",
|
|
221
|
+
[
|
|
222
|
+
"--dangerously-skip-permissions",
|
|
223
|
+
"--disable-slash-commands",
|
|
224
|
+
"--output-format",
|
|
225
|
+
"stream-json",
|
|
226
|
+
"--input-format",
|
|
227
|
+
"stream-json",
|
|
228
|
+
"--model",
|
|
229
|
+
selection.model,
|
|
230
|
+
...(selection.effort ? ["--effort", selection.effort] : []),
|
|
231
|
+
"--print-timeout",
|
|
232
|
+
"10m",
|
|
233
|
+
],
|
|
234
|
+
{ cwd: request.cwd, stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
|
|
235
|
+
|
|
236
|
+
let final: string | undefined;
|
|
237
|
+
let terminalError: string | undefined;
|
|
238
|
+
let sawTerminal = false;
|
|
239
|
+
|
|
240
|
+
child.stdin?.on("error", () => {
|
|
241
|
+
// agy exiting before it reads stdin is reported through the close/error path below.
|
|
242
|
+
});
|
|
243
|
+
child.stdin?.end(`${JSON.stringify({ event: "user", message: { content: request.prompt } })}\n`);
|
|
244
|
+
|
|
245
|
+
const handleLine = (line: string) => {
|
|
246
|
+
if (!line.trim() || sawTerminal || attempt.causeOf()) return;
|
|
247
|
+
let event: AdvisorAgyEvent;
|
|
248
|
+
try {
|
|
249
|
+
event = JSON.parse(line) as AdvisorAgyEvent;
|
|
250
|
+
} catch {
|
|
251
|
+
throw new Error("Agy emitted invalid stream-json output.");
|
|
252
|
+
}
|
|
253
|
+
const activity = advisorActivityFromEvent(event);
|
|
254
|
+
if (activity) {
|
|
255
|
+
const step = event.step_update;
|
|
256
|
+
const tool = step?.step_type === "agent_response" || step?.step_type === "assistant"
|
|
257
|
+
? undefined : btwToolName(step?.tool_name);
|
|
258
|
+
onProgress?.({ kind: "activity", label: activity, timestamp: Date.now(), ...(tool ? { tool } : {}) });
|
|
259
|
+
}
|
|
260
|
+
if (event.event !== "result") return;
|
|
261
|
+
sawTerminal = true;
|
|
262
|
+
const result = event.result;
|
|
263
|
+
const status = typeof result?.status === "string" ? result.status.trim().toUpperCase() : undefined;
|
|
264
|
+
if (status === "SUCCESS" && typeof result?.response === "string") {
|
|
265
|
+
final = result.response;
|
|
266
|
+
} else {
|
|
267
|
+
const detail = typeof result?.error === "string" && result.error.trim() ? `: ${result.error.trim()}` : "";
|
|
268
|
+
terminalError = `Agy failed with status ${status ?? "(missing)"}${detail}`;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const finished = await finishCliAttempt(child, attempt, "Agy", handleLine);
|
|
273
|
+
const code = finished.code!;
|
|
274
|
+
const stopped = stoppedCliOutcome("Agy", attempt, finished, diagnostics,
|
|
275
|
+
"Agy timed out during the advisor consultation. Run `/bro doctor` for setup help.");
|
|
276
|
+
if (stopped) return stopped;
|
|
277
|
+
if (!sawTerminal) {
|
|
278
|
+
const hint = advisorFlagErrorHint(diagnostics.stderr);
|
|
279
|
+
return {
|
|
280
|
+
status: "failure",
|
|
281
|
+
message: withDoctor(hint ?? (diagnostics.stderr.trim() ? `Agy exited without a terminal result event: ${diagnostics.stderr.trim()}` : "Agy exited without a terminal result event.")),
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
if (terminalError) return { status: "failure", message: withDoctor(terminalError) };
|
|
285
|
+
if (code !== 0) return { status: "failure", message: agyFailureMessage("complete the advisor consultation", { code, killed: false, stderr: diagnostics.stderr }) };
|
|
286
|
+
|
|
287
|
+
const text = final?.trim();
|
|
288
|
+
if (!text) return { status: "failure", message: withDoctor(diagnostics.stderr.trim() || "Agy returned no advice.") };
|
|
289
|
+
return { status: "success", text };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function executeAgy(
|
|
293
|
+
request: BackendRequest,
|
|
294
|
+
selection: AgySelection,
|
|
295
|
+
signal: AbortSignal,
|
|
296
|
+
onProgress: BackendOnProgress | undefined,
|
|
297
|
+
killEscalationMs: number,
|
|
298
|
+
deadlineMs: number,
|
|
299
|
+
): Promise<BackendOutcome> {
|
|
300
|
+
if (request.feature === "advisor") {
|
|
301
|
+
return executeAdvisorStdin(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
|
|
302
|
+
}
|
|
303
|
+
return executeArgvPrint(request, selection, signal, onProgress, killEscalationMs, deadlineMs);
|
|
304
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { resolveCliChildAuth, verifyCliSubscription } from "../cli-auth.ts";
|
|
5
|
+
import { errorMessage, withDoctor } from "../util.ts";
|
|
6
|
+
import { checkedBtwContinuation, cliExitFailure, finishCliAttempt, startCliAttempt, stoppedCliOutcome } from "./cli-process.ts";
|
|
7
|
+
import { btwToolName, type BackendOnProgress, type BackendOutcome, type BackendRequest } from "./contract.ts";
|
|
8
|
+
|
|
9
|
+
type ClaudeEvent = {
|
|
10
|
+
type?: unknown;
|
|
11
|
+
subtype?: unknown;
|
|
12
|
+
session_id?: unknown;
|
|
13
|
+
is_error?: unknown;
|
|
14
|
+
result?: unknown;
|
|
15
|
+
parent_tool_use_id?: unknown;
|
|
16
|
+
stop_reason?: unknown;
|
|
17
|
+
terminal_reason?: unknown;
|
|
18
|
+
event?: { type?: unknown; delta?: { type?: unknown; text?: unknown } };
|
|
19
|
+
message?: { content?: unknown };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// Every Claude run uses --safe-mode, which disables CLAUDE.md, skills, plugins, hooks and MCP
|
|
23
|
+
// servers but keeps the user's auth (--bare would break OAuth). The prompt goes over stdin.
|
|
24
|
+
// explain/show run fresh and tool-less in a scratch cwd; advisor runs fresh in the caller's
|
|
25
|
+
// workspace with tools auto-approved. btw persists its session (so `--resume` can continue it) and
|
|
26
|
+
// always runs in the caller's workspace, since Claude stores sessions per cwd: restricted turns are
|
|
27
|
+
// tool-less, full turns auto-approve tools, and one session resumes across both. Only the terminal
|
|
28
|
+
// `result` event is authoritative; streamed text_delta events are progress only, and thinking is
|
|
29
|
+
// dropped. btw requires init/result session ids to agree (and to equal the resumed id).
|
|
30
|
+
export async function executeClaude(
|
|
31
|
+
request: BackendRequest,
|
|
32
|
+
selection: { model: string; effort?: string },
|
|
33
|
+
signal: AbortSignal,
|
|
34
|
+
onProgress: BackendOnProgress | undefined,
|
|
35
|
+
killEscalationMs: number,
|
|
36
|
+
deadlineMs: number,
|
|
37
|
+
): Promise<BackendOutcome> {
|
|
38
|
+
const isAdvisor = request.feature === "advisor";
|
|
39
|
+
const isBtw = request.feature === "btw";
|
|
40
|
+
const inspect = request.feature === "review";
|
|
41
|
+
const full = request.access === "workspace-full";
|
|
42
|
+
const action = request.feature === "review" ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
|
|
43
|
+
|
|
44
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
45
|
+
const runDirectory = full || isBtw || inspect ? undefined : await mkdtemp(join(tmpdir(), "pi-bro-"));
|
|
46
|
+
if (signal.aborted) {
|
|
47
|
+
if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
|
|
48
|
+
return { status: "cancelled", message: "Canceled." };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
let auth: ReturnType<typeof resolveCliChildAuth>;
|
|
53
|
+
try { auth = resolveCliChildAuth("claude"); }
|
|
54
|
+
catch (error) { return { status: "failure", message: errorMessage(error) }; }
|
|
55
|
+
if (auth.subscription) {
|
|
56
|
+
const check = await verifyCliSubscription("claude", auth.env, signal, killEscalationMs, deadlineMs);
|
|
57
|
+
if (check) return check;
|
|
58
|
+
}
|
|
59
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
60
|
+
const { child, attempt, diagnostics } = startCliAttempt("claude",
|
|
61
|
+
[
|
|
62
|
+
"-p",
|
|
63
|
+
"--safe-mode",
|
|
64
|
+
...(isBtw ? [] : ["--no-session-persistence"]),
|
|
65
|
+
"--disable-slash-commands",
|
|
66
|
+
"--output-format",
|
|
67
|
+
"stream-json",
|
|
68
|
+
"--verbose",
|
|
69
|
+
"--include-partial-messages",
|
|
70
|
+
...(inspect
|
|
71
|
+
? ["--restricted", "--tools", "Read,Grep,Glob", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--permission-mode", "dontAsk"]
|
|
72
|
+
: full
|
|
73
|
+
? ["--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--dangerously-skip-permissions"]
|
|
74
|
+
: ["--tools", "", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--permission-mode", "dontAsk"]),
|
|
75
|
+
...(isBtw && request.continuation ? ["--resume", request.continuation.id] : []),
|
|
76
|
+
"--model",
|
|
77
|
+
selection.model,
|
|
78
|
+
...(selection.effort ? ["--effort", selection.effort] : []),
|
|
79
|
+
],
|
|
80
|
+
{
|
|
81
|
+
cwd: runDirectory ?? request.cwd,
|
|
82
|
+
stdio: ["pipe", "pipe", "pipe"], env: auth.env }, signal, deadlineMs, killEscalationMs);
|
|
83
|
+
|
|
84
|
+
let partial = "";
|
|
85
|
+
let final: string | undefined;
|
|
86
|
+
let terminalError: string | undefined;
|
|
87
|
+
let initSessionId: string | undefined;
|
|
88
|
+
let resultSessionId: string | undefined;
|
|
89
|
+
|
|
90
|
+
child.stdin?.on("error", () => {
|
|
91
|
+
// claude exiting before it reads stdin is reported through the close/error path below.
|
|
92
|
+
});
|
|
93
|
+
child.stdin?.end(request.prompt);
|
|
94
|
+
|
|
95
|
+
const handleLine = (line: string) => {
|
|
96
|
+
if (!line.trim() || attempt.causeOf()) return;
|
|
97
|
+
let event: ClaudeEvent;
|
|
98
|
+
try {
|
|
99
|
+
event = JSON.parse(line) as ClaudeEvent;
|
|
100
|
+
} catch {
|
|
101
|
+
throw new Error("Claude emitted invalid stream-json output.");
|
|
102
|
+
}
|
|
103
|
+
const topLevel = event.parent_tool_use_id === undefined || event.parent_tool_use_id === null;
|
|
104
|
+
if (topLevel && event.type === "system" && event.subtype === "init" && typeof event.session_id === "string") initSessionId = event.session_id;
|
|
105
|
+
if (!isAdvisor && topLevel && event.type === "stream_event" && event.event?.type === "content_block_delta") {
|
|
106
|
+
const delta = event.event.delta;
|
|
107
|
+
if (delta?.type === "text_delta" && typeof delta.text === "string" && delta.text) {
|
|
108
|
+
partial += delta.text;
|
|
109
|
+
onProgress?.({ kind: "text", text: partial });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if ((isAdvisor || isBtw || (inspect && request.reportReviewTools)) && topLevel && event.type === "assistant" && Array.isArray(event.message?.content)) {
|
|
113
|
+
for (const block of event.message.content as Array<{ type?: unknown; name?: unknown; text?: unknown }>) {
|
|
114
|
+
if (attempt.causeOf()) break;
|
|
115
|
+
if ((isBtw || (inspect && request.reportReviewTools)) && block?.type !== "tool_use") continue;
|
|
116
|
+
const tool = block?.type === "tool_use" ? btwToolName(block.name) : undefined;
|
|
117
|
+
const label =
|
|
118
|
+
block?.type === "tool_use" && typeof block.name === "string"
|
|
119
|
+
? ((isBtw || (inspect && request.reportReviewTools)) ? tool : block.name.trim())
|
|
120
|
+
: block?.type === "text" && typeof block.text === "string"
|
|
121
|
+
? block.text.split("\n").find((text) => text.trim())?.trim()
|
|
122
|
+
: undefined;
|
|
123
|
+
if (label) onProgress?.({ kind: "activity", label, timestamp: Date.now(), ...(tool ? { tool } : {}) });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (event.type !== "result" || !topLevel) return;
|
|
127
|
+
if (typeof event.session_id === "string") resultSessionId = event.session_id;
|
|
128
|
+
if (event.subtype === "success" && event.is_error === false && (event.stop_reason !== "end_turn" || (event.terminal_reason !== undefined && event.terminal_reason !== "completed"))) {
|
|
129
|
+
terminalError ??= `Claude did not complete the answer (stop reason: ${String(event.stop_reason)}, terminal reason: ${String(event.terminal_reason)}).`;
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
// A result ends a model turn, not necessarily the stream; the first failure is latched and
|
|
133
|
+
// otherwise the latest successful result wins once the process exits cleanly.
|
|
134
|
+
if (event.subtype === "success" && event.is_error === false && typeof event.result === "string") {
|
|
135
|
+
final = event.result;
|
|
136
|
+
} else {
|
|
137
|
+
const detail =
|
|
138
|
+
typeof event.subtype === "string" && event.subtype !== "success"
|
|
139
|
+
? event.subtype
|
|
140
|
+
: typeof event.result === "string" && event.result.trim()
|
|
141
|
+
? event.result.trim()
|
|
142
|
+
: "turn failed";
|
|
143
|
+
terminalError ??= `Claude failed: ${detail}`;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const finished = await finishCliAttempt(child, attempt, "Claude", handleLine);
|
|
148
|
+
const code = finished.code!;
|
|
149
|
+
const stopped = stoppedCliOutcome("Claude", attempt, finished, diagnostics,
|
|
150
|
+
`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);
|
|
151
|
+
if (stopped) return stopped;
|
|
152
|
+
const partialText = partial || undefined;
|
|
153
|
+
if (terminalError) return { status: "failure", message: withDoctor(terminalError), partialText };
|
|
154
|
+
if (code !== 0) return { status: "failure", message: cliExitFailure("Claude", action, diagnostics.stderr), partialText };
|
|
155
|
+
if (final === undefined) {
|
|
156
|
+
return { status: "failure", message: withDoctor(`Claude exited without a result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), partialText };
|
|
157
|
+
}
|
|
158
|
+
const text = final.trim();
|
|
159
|
+
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 };
|
|
160
|
+
if (!isBtw) return { status: "success", text };
|
|
161
|
+
const continuation = checkedBtwContinuation("Claude", request.continuation,
|
|
162
|
+
{ init: initSessionId, result: resultSessionId });
|
|
163
|
+
if ("error" in continuation)
|
|
164
|
+
return { status: "failure", message: withDoctor(continuation.error), partialText };
|
|
165
|
+
return { status: "success", text, continuation };
|
|
166
|
+
} finally {
|
|
167
|
+
if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
|
|
168
|
+
}
|
|
169
|
+
}
|