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,247 @@
|
|
|
1
|
+
import { type ChildProcess, type SpawnOptions, spawn } from "node:child_process";
|
|
2
|
+
import { errorMessage, withDoctor } from "../util.ts";
|
|
3
|
+
import type { BackendContinuation, BackendOutcome } from "./contract.ts";
|
|
4
|
+
|
|
5
|
+
export function processStartMessage(processError: NodeJS.ErrnoException, cli = "Agy"): string {
|
|
6
|
+
if (processError.code === "ENOENT") {
|
|
7
|
+
return cli === "Agy"
|
|
8
|
+
? "Agy could not start. Make sure Agy is installed and on PATH, then run `/bro doctor`."
|
|
9
|
+
: cli === "Grok"
|
|
10
|
+
? "Grok could not start. Make sure `grok` is installed and on PATH, then run `/bro doctor`."
|
|
11
|
+
: cli === "Codex"
|
|
12
|
+
? "Codex could not start. Make sure `codex` is installed and on PATH, then run `/bro doctor`."
|
|
13
|
+
: cli === "Muse"
|
|
14
|
+
? "Muse could not start. Make sure `muse` is installed and on PATH, then run `/bro doctor`."
|
|
15
|
+
: "Claude Code could not start. Make sure `claude` is installed and on PATH, then run `/bro doctor`.";
|
|
16
|
+
}
|
|
17
|
+
return `${cli} could not start: ${processError.message}\n\nRun \`/bro doctor\` for setup help.`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function unexpectedSignalMessage(exitSignal: NodeJS.Signals | null, cli = "Agy"): string {
|
|
21
|
+
return withDoctor(`${cli} exited unexpectedly${exitSignal ? ` (signal ${exitSignal})` : ""}, not from a request Bro made.`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Sends to the whole POSIX process group when possible so a misbehaving grandchild dies too, not
|
|
25
|
+
// just the immediate child process -- child.kill() alone only ever reaches the immediate child.
|
|
26
|
+
function killProcessGroup(child: ChildProcess, signalName: NodeJS.Signals): void {
|
|
27
|
+
if (process.platform !== "win32" && typeof child.pid === "number") {
|
|
28
|
+
try {
|
|
29
|
+
process.kill(-child.pid, signalName);
|
|
30
|
+
return;
|
|
31
|
+
} catch {
|
|
32
|
+
// Group may already be gone (e.g. the child already exited) -- fall through.
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
child.kill(signalName);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The three causes that stop an in-flight attempt: user cancellation, the host-imposed deadline,
|
|
39
|
+
// and a protocol failure (malformed/inconsistent backend output). Exactly one is latched -- the first
|
|
40
|
+
// to occur -- and it is never relabeled by a later signal (e.g. a cancel arriving after a deadline
|
|
41
|
+
// already fired stays a timeout, not a cancellation).
|
|
42
|
+
type StopCause = "cancelled" | "timeout" | "protocol";
|
|
43
|
+
|
|
44
|
+
type Attempt = {
|
|
45
|
+
causeOf: () => StopCause | undefined;
|
|
46
|
+
stop: (cause: StopCause) => void;
|
|
47
|
+
closed: Promise<{ code: number | null; exitSignal: NodeJS.Signals | null }>;
|
|
48
|
+
dispose: () => void;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const DEFAULT_KILL_ESCALATION_MS = 5_000;
|
|
52
|
+
|
|
53
|
+
// CLI adapters own their protocols; this shared runner owns process setup, diagnostics, and lifecycle.
|
|
54
|
+
export function startCliAttempt(
|
|
55
|
+
command: string,
|
|
56
|
+
args: string[],
|
|
57
|
+
options: SpawnOptions,
|
|
58
|
+
signal: AbortSignal,
|
|
59
|
+
deadlineMs: number,
|
|
60
|
+
killEscalationMs: number,
|
|
61
|
+
) {
|
|
62
|
+
const child = spawn(command, args, { ...options, windowsHide: true, detached: process.platform !== "win32" });
|
|
63
|
+
const attempt = beginAttempt(child, signal, deadlineMs, killEscalationMs);
|
|
64
|
+
const diagnostics: { stderr: string; processError?: Error } = { stderr: "" };
|
|
65
|
+
child.stderr?.setEncoding("utf8");
|
|
66
|
+
child.stderr?.on("data", (chunk: string) => { diagnostics.stderr += chunk; });
|
|
67
|
+
child.once("error", (error) => { diagnostics.processError = error; });
|
|
68
|
+
return { child, attempt, diagnostics };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Begins bounded lifecycle management for one already-spawned child: on cancellation, deadline, or
|
|
72
|
+
// protocol failure it signals the whole POSIX process group (SIGTERM, then SIGKILL after
|
|
73
|
+
// `killEscalationMs` if the child or a misbehaving grandchild ignores it). Windows only ever
|
|
74
|
+
// reaches the immediate child directly -- there is no process-tree guarantee there.
|
|
75
|
+
export function beginAttempt(child: ChildProcess, signal: AbortSignal, deadlineMs: number, killEscalationMs: number): Attempt {
|
|
76
|
+
let cause: StopCause | undefined;
|
|
77
|
+
let killTimer: ReturnType<typeof setTimeout> | undefined;
|
|
78
|
+
let isClosed = false;
|
|
79
|
+
let finishClose: (value: { code: number | null; exitSignal: NodeJS.Signals | null }) => void;
|
|
80
|
+
const closed = new Promise<{ code: number | null; exitSignal: NodeJS.Signals | null }>((resolve) => {
|
|
81
|
+
finishClose = (val) => {
|
|
82
|
+
isClosed = true;
|
|
83
|
+
resolve(val);
|
|
84
|
+
};
|
|
85
|
+
child.once("close", (code, exitSignal) => finishClose({ code, exitSignal }));
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const stop = (next: StopCause) => {
|
|
89
|
+
if (cause) return; // latched: the first stop cause wins
|
|
90
|
+
cause = next;
|
|
91
|
+
if (isClosed) return;
|
|
92
|
+
killProcessGroup(child, "SIGTERM");
|
|
93
|
+
killTimer = setTimeout(() => {
|
|
94
|
+
killProcessGroup(child, "SIGKILL");
|
|
95
|
+
// Detached descendants (or Windows grandchildren) may retain inherited pipes.
|
|
96
|
+
// Stop waiting on those pipes after escalation; never promote this stop to success.
|
|
97
|
+
child.stdin?.destroy();
|
|
98
|
+
child.stdout?.destroy();
|
|
99
|
+
child.stderr?.destroy();
|
|
100
|
+
finishClose({ code: null, exitSignal: "SIGKILL" });
|
|
101
|
+
}, killEscalationMs);
|
|
102
|
+
killTimer.unref?.();
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const onAbort = () => stop("cancelled");
|
|
106
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
107
|
+
if (signal.aborted) onAbort();
|
|
108
|
+
|
|
109
|
+
const deadlineTimer = setTimeout(() => stop("timeout"), deadlineMs);
|
|
110
|
+
deadlineTimer.unref?.();
|
|
111
|
+
|
|
112
|
+
const dispose = () => {
|
|
113
|
+
signal.removeEventListener("abort", onAbort);
|
|
114
|
+
clearTimeout(deadlineTimer);
|
|
115
|
+
if (killTimer) clearTimeout(killTimer);
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
return { causeOf: () => cause, stop, closed, dispose };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Guards only against a single runaway line with no newline (a protocol break, not a real
|
|
122
|
+
// response size) -- real NDJSON lines across all backends are far smaller than this.
|
|
123
|
+
export const MAX_STDOUT_LINE_CHARS = 2_000_000;
|
|
124
|
+
|
|
125
|
+
export function frameStdoutLines(
|
|
126
|
+
child: ChildProcess,
|
|
127
|
+
attempt: Attempt,
|
|
128
|
+
backendName: string,
|
|
129
|
+
onLine: (line: string) => void,
|
|
130
|
+
): () => string | undefined {
|
|
131
|
+
const oversize = `${backendName} emitted a stdout line over ${MAX_STDOUT_LINE_CHARS} characters; the stream is unparseable.`;
|
|
132
|
+
let buffer = "";
|
|
133
|
+
let protocolError: string | undefined;
|
|
134
|
+
|
|
135
|
+
const fail = (message: string) => {
|
|
136
|
+
protocolError ??= message;
|
|
137
|
+
buffer = "";
|
|
138
|
+
attempt.stop("protocol");
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
child.stdout?.setEncoding("utf8");
|
|
142
|
+
|
|
143
|
+
child.stdout?.on("error", (error) => {
|
|
144
|
+
fail(`${backendName} stdout error: ${errorMessage(error)}`);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
148
|
+
if (attempt.causeOf()) return;
|
|
149
|
+
const parts = (buffer + chunk).split(/\r?\n/);
|
|
150
|
+
buffer = parts.pop() ?? "";
|
|
151
|
+
|
|
152
|
+
const pendingLen = buffer.endsWith("\r") ? buffer.length - 1 : buffer.length;
|
|
153
|
+
if (pendingLen > MAX_STDOUT_LINE_CHARS || parts.some((line) => line.length > MAX_STDOUT_LINE_CHARS)) {
|
|
154
|
+
return fail(oversize);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
for (const line of parts) {
|
|
158
|
+
if (attempt.causeOf()) return;
|
|
159
|
+
if (!line.trim()) continue;
|
|
160
|
+
try {
|
|
161
|
+
onLine(line);
|
|
162
|
+
} catch (error) {
|
|
163
|
+
return fail(errorMessage(error));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
return (): string | undefined => {
|
|
169
|
+
if (!attempt.causeOf() && buffer.trim()) {
|
|
170
|
+
const line = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
|
|
171
|
+
if (line.length > MAX_STDOUT_LINE_CHARS) {
|
|
172
|
+
fail(oversize);
|
|
173
|
+
} else if (line.trim()) {
|
|
174
|
+
try {
|
|
175
|
+
onLine(line);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
fail(errorMessage(error));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
buffer = "";
|
|
182
|
+
return protocolError;
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Every CLI adapter frames stdout immediately, awaits the process, then releases stop timers.
|
|
187
|
+
// Keep this lifecycle in one place: adapter-specific parsing and exit rules stay in each adapter.
|
|
188
|
+
export async function finishCliAttempt(
|
|
189
|
+
child: ChildProcess,
|
|
190
|
+
attempt: Attempt,
|
|
191
|
+
name: string,
|
|
192
|
+
handleLine: (line: string) => void,
|
|
193
|
+
): Promise<{ code: number | null; exitSignal: NodeJS.Signals | null; protocolError?: string }> {
|
|
194
|
+
const finishFraming = frameStdoutLines(child, attempt, name, handleLine);
|
|
195
|
+
try {
|
|
196
|
+
const { code, exitSignal } = await attempt.closed;
|
|
197
|
+
return { code, exitSignal, protocolError: finishFraming() };
|
|
198
|
+
} finally {
|
|
199
|
+
attempt.dispose();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Common stop/error precedence. Backend adapters only decide terminal protocol and success. */
|
|
204
|
+
export function stoppedCliOutcome(
|
|
205
|
+
name: string,
|
|
206
|
+
attempt: Attempt,
|
|
207
|
+
finished: { code: number | null; exitSignal: NodeJS.Signals | null; protocolError?: string },
|
|
208
|
+
diagnostics: { stderr: string; processError?: Error },
|
|
209
|
+
timeoutMessage: string,
|
|
210
|
+
partial?: string,
|
|
211
|
+
): BackendOutcome | undefined {
|
|
212
|
+
const partialText = partial ? { partialText: partial } : {};
|
|
213
|
+
if (attempt.causeOf() === "cancelled") return { status: "cancelled", message: "Canceled.", ...partialText };
|
|
214
|
+
if (attempt.causeOf() === "timeout") return { status: "timeout", message: timeoutMessage, ...partialText };
|
|
215
|
+
if (finished.protocolError) return { status: "failure", message: withDoctor(finished.protocolError), ...partialText };
|
|
216
|
+
if (diagnostics.processError) return { status: "failure", message: processStartMessage(diagnostics.processError as NodeJS.ErrnoException, name) };
|
|
217
|
+
if (finished.exitSignal || finished.code === null) {
|
|
218
|
+
return { status: "failure", message: unexpectedSignalMessage(finished.exitSignal, name), ...partialText };
|
|
219
|
+
}
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Session continuity is a shared BTW promise, even though CLIs report IDs differently. */
|
|
224
|
+
export function checkedBtwContinuation(
|
|
225
|
+
name: "Claude" | "Grok" | "Codex" | "Muse",
|
|
226
|
+
requested: BackendContinuation | undefined,
|
|
227
|
+
observed: { id?: string; init?: string; result?: string },
|
|
228
|
+
): BackendContinuation | { error: string } {
|
|
229
|
+
const id = observed.id ?? observed.result ?? observed.init;
|
|
230
|
+
if (id && (!observed.init || observed.init === id) && (!requested || requested.id === id)) return { id };
|
|
231
|
+
const details = "id" in observed ? `got ${observed.id ?? "none"}`
|
|
232
|
+
: `init ${observed.init ?? "none"}, result ${observed.result ?? "none"}`;
|
|
233
|
+
return { error: `${name} reported an inconsistent session id (expected ${requested?.id ?? "one id"}, ${details}).` };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Exit diagnostics share framing, while each backend still owns its prompt and protocol. */
|
|
237
|
+
export function cliExitFailure(name: "Claude" | "Grok" | "Codex" | "Muse", action: string, stderr: string): string {
|
|
238
|
+
const detail = stderr.trim();
|
|
239
|
+
if (detail) return `${name} could not ${action}: ${detail}\n\nRun \`/bro doctor\` for setup help.`;
|
|
240
|
+
const installation = {
|
|
241
|
+
Claude: "Claude Code",
|
|
242
|
+
Grok: "`grok`",
|
|
243
|
+
Codex: "`codex`",
|
|
244
|
+
Muse: "`muse`",
|
|
245
|
+
}[name];
|
|
246
|
+
return `${name} could not ${action}. Make sure ${installation} is installed and signed in, then run \`/bro doctor\`.`;
|
|
247
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
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 CodexEvent = {
|
|
10
|
+
type?: unknown;
|
|
11
|
+
thread_id?: unknown;
|
|
12
|
+
item?: {
|
|
13
|
+
id?: unknown;
|
|
14
|
+
type?: unknown;
|
|
15
|
+
text?: unknown;
|
|
16
|
+
message?: unknown;
|
|
17
|
+
content?: unknown;
|
|
18
|
+
command?: unknown;
|
|
19
|
+
cmd?: unknown;
|
|
20
|
+
path?: unknown;
|
|
21
|
+
pattern?: unknown;
|
|
22
|
+
query?: unknown;
|
|
23
|
+
};
|
|
24
|
+
error?: { message?: unknown };
|
|
25
|
+
message?: unknown;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function extractCodexItemText(item: CodexEvent["item"]): string | undefined {
|
|
29
|
+
if (!item) return undefined;
|
|
30
|
+
if (typeof item.text === "string") return item.text;
|
|
31
|
+
if (typeof item.message === "string") return item.message;
|
|
32
|
+
if (typeof item.content === "string") return item.content;
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function codexActivityFromEvent(event: CodexEvent): string | undefined {
|
|
37
|
+
const item = event.item;
|
|
38
|
+
if (!item || item.type === "reasoning") return undefined;
|
|
39
|
+
if (event.type === "item.started" || event.type === "item.completed") {
|
|
40
|
+
if (item.type !== "agent_message") {
|
|
41
|
+
const itemType = typeof item.type === "string" ? item.type : "item";
|
|
42
|
+
const candidate = [item.command, item.cmd, item.path, item.pattern, item.query]
|
|
43
|
+
.find((v) => typeof v === "string" && v.trim());
|
|
44
|
+
const preview = typeof candidate === "string" ? candidate.replace(/\s+/g, " ").trim() : "";
|
|
45
|
+
return `${itemType}${preview ? ` ${preview}` : ""}`;
|
|
46
|
+
}
|
|
47
|
+
if (item.type === "agent_message") {
|
|
48
|
+
const text = extractCodexItemText(item);
|
|
49
|
+
return text?.split("\n").find((line) => line.trim())?.trim();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function executeCodex(
|
|
56
|
+
request: BackendRequest,
|
|
57
|
+
selection: { model: string; effort?: string },
|
|
58
|
+
signal: AbortSignal,
|
|
59
|
+
onProgress: BackendOnProgress | undefined,
|
|
60
|
+
killEscalationMs: number,
|
|
61
|
+
deadlineMs: number,
|
|
62
|
+
): Promise<BackendOutcome> {
|
|
63
|
+
const isAdvisor = request.feature === "advisor";
|
|
64
|
+
const isBtw = request.feature === "btw";
|
|
65
|
+
const inspect = request.feature === "review";
|
|
66
|
+
const full = request.access === "workspace-full";
|
|
67
|
+
const action = inspect ? "complete the guided review request" : isAdvisor ? "complete the advisor consultation" : isBtw ? "answer the side question" : "simplify the response";
|
|
68
|
+
const timeoutVerb = inspect ? "during the guided review request" : isAdvisor ? "during the advisor consultation" : isBtw ? "during the side conversation" : "while simplifying the response";
|
|
69
|
+
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.";
|
|
70
|
+
|
|
71
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
72
|
+
const runDirectory = full || isBtw || inspect ? undefined : await mkdtemp(join(tmpdir(), "pi-bro-"));
|
|
73
|
+
if (signal.aborted) {
|
|
74
|
+
if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
|
|
75
|
+
return { status: "cancelled", message: "Canceled." };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
let auth: ReturnType<typeof resolveCliChildAuth>;
|
|
80
|
+
try { auth = resolveCliChildAuth("codex"); }
|
|
81
|
+
catch (error) { return { status: "failure", message: errorMessage(error) }; }
|
|
82
|
+
if (auth.subscription) {
|
|
83
|
+
const check = await verifyCliSubscription("codex", auth.env, signal, killEscalationMs, deadlineMs, runDirectory ?? request.cwd);
|
|
84
|
+
if (check) return check;
|
|
85
|
+
}
|
|
86
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
87
|
+
const permissionArgs = full ? ["--dangerously-bypass-approvals-and-sandbox"] : ["--sandbox", "read-only"];
|
|
88
|
+
const resume = isBtw && request.continuation;
|
|
89
|
+
const args = [
|
|
90
|
+
"exec",
|
|
91
|
+
...(auth.subscription ? ["-c", 'forced_login_method="chatgpt"', "-c", 'model_provider="openai"'] : []),
|
|
92
|
+
...permissionArgs,
|
|
93
|
+
...(resume ? ["resume"] : []),
|
|
94
|
+
"--json",
|
|
95
|
+
"--skip-git-repo-check",
|
|
96
|
+
...(!isBtw ? ["--ephemeral"] : []),
|
|
97
|
+
"--model",
|
|
98
|
+
selection.model,
|
|
99
|
+
...(selection.effort ? ["-c", `model_reasoning_effort="${selection.effort}"`] : []),
|
|
100
|
+
...(resume ? [request.continuation!.id, "-"] : ["--", "-"]),
|
|
101
|
+
];
|
|
102
|
+
|
|
103
|
+
const { child, attempt, diagnostics } = startCliAttempt("codex", args, {
|
|
104
|
+
cwd: runDirectory ?? request.cwd,
|
|
105
|
+
stdio: ["pipe", "pipe", "pipe"], env: auth.env }, signal, deadlineMs, killEscalationMs);
|
|
106
|
+
|
|
107
|
+
let partial = "";
|
|
108
|
+
let threadId: string | undefined;
|
|
109
|
+
let final: string | undefined;
|
|
110
|
+
let sawTerminal = false;
|
|
111
|
+
let terminalError: string | undefined;
|
|
112
|
+
|
|
113
|
+
child.stdin?.on("error", () => {
|
|
114
|
+
// codex exiting before reading stdin is reported through the close/error path.
|
|
115
|
+
});
|
|
116
|
+
child.stdin?.end(request.prompt);
|
|
117
|
+
|
|
118
|
+
const handleLine = (line: string) => {
|
|
119
|
+
if (!line.trim() || attempt.causeOf()) return;
|
|
120
|
+
let event: CodexEvent;
|
|
121
|
+
try {
|
|
122
|
+
event = JSON.parse(line) as CodexEvent;
|
|
123
|
+
} catch {
|
|
124
|
+
throw new Error("Codex emitted invalid JSON output.");
|
|
125
|
+
}
|
|
126
|
+
if (event.type === "thread.started" && typeof event.thread_id === "string") {
|
|
127
|
+
threadId = event.thread_id;
|
|
128
|
+
}
|
|
129
|
+
if (event.type === "error") {
|
|
130
|
+
terminalError ??= `Codex error: ${typeof event.message === "string" && event.message.trim() ? event.message.trim() : "unknown error"}`;
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (event.type === "turn.failed") {
|
|
134
|
+
sawTerminal = true;
|
|
135
|
+
const err = event.error as { message?: unknown } | undefined;
|
|
136
|
+
terminalError ??= `Codex failed: ${typeof err?.message === "string" && err.message.trim() ? err.message.trim() : "turn failed"}`;
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (event.type === "turn.completed") {
|
|
140
|
+
sawTerminal = true;
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const item = event.item;
|
|
144
|
+
if ((isAdvisor || isBtw || (inspect && request.reportReviewTools)) && (event.type === "item.started" || event.type === "item.completed")) {
|
|
145
|
+
const tool = item?.type !== "agent_message" && item?.type !== "reasoning" ? btwToolName(item?.type) : undefined;
|
|
146
|
+
const activity = (isBtw || (inspect && request.reportReviewTools)) ? tool : codexActivityFromEvent(event);
|
|
147
|
+
if (activity) onProgress?.({ kind: "activity", label: activity, timestamp: Date.now(), ...(tool ? { tool } : {}) });
|
|
148
|
+
}
|
|
149
|
+
if (event.type === "item.completed" && item?.type === "agent_message") {
|
|
150
|
+
const text = extractCodexItemText(item);
|
|
151
|
+
if (text !== undefined) {
|
|
152
|
+
final = text;
|
|
153
|
+
if (!isAdvisor) {
|
|
154
|
+
partial += `${partial ? "\n\n" : ""}${text}`;
|
|
155
|
+
onProgress?.({ kind: "text", text: partial });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
const finished = await finishCliAttempt(child, attempt, "Codex", handleLine);
|
|
162
|
+
const code = finished.code!;
|
|
163
|
+
const stopped = stoppedCliOutcome("Codex", attempt, finished, diagnostics,
|
|
164
|
+
`Codex timed out ${timeoutVerb}. Run \`/bro doctor\` for setup help.`, partial);
|
|
165
|
+
if (stopped) return stopped;
|
|
166
|
+
const partialText = partial ? { partialText: partial } : {};
|
|
167
|
+
if (terminalError) return { status: "failure", message: withDoctor(terminalError), ...partialText };
|
|
168
|
+
if (code !== 0) return { status: "failure", message: cliExitFailure("Codex", action, diagnostics.stderr), ...partialText };
|
|
169
|
+
if (!sawTerminal) {
|
|
170
|
+
return { status: "failure", message: withDoctor(`Codex exited without a terminal result event${diagnostics.stderr.trim() ? `: ${diagnostics.stderr.trim()}` : "."}`), ...partialText };
|
|
171
|
+
}
|
|
172
|
+
const text = final?.trim();
|
|
173
|
+
if (!text) return { status: "failure", message: withDoctor(emptyTextMessage), ...partialText };
|
|
174
|
+
if (!isBtw) return { status: "success", text };
|
|
175
|
+
const continuation = checkedBtwContinuation("Codex", request.continuation, { id: threadId });
|
|
176
|
+
if ("error" in continuation)
|
|
177
|
+
return { status: "failure", message: withDoctor(continuation.error), ...partialText };
|
|
178
|
+
return { status: "success", text, continuation };
|
|
179
|
+
} finally {
|
|
180
|
+
if (runDirectory) await rm(runDirectory, { recursive: true, force: true });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from "node:util";
|
|
2
|
+
import type { createAgentSession } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
export type BackendFeature = "explain" | "show" | "btw" | "advisor" | "review";
|
|
5
|
+
export type BackendAccess = "restricted" | "workspace-full";
|
|
6
|
+
|
|
7
|
+
export type AgySelection = { model: string; effort?: "low" | "medium" | "high" };
|
|
8
|
+
export const CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
9
|
+
export const GROK_EFFORTS = ["low", "medium", "high", "xhigh"] as const;
|
|
10
|
+
export const CODEX_EFFORTS = ["low", "medium", "high", "xhigh"] as const;
|
|
11
|
+
export const MUSE_EFFORTS = ["minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
12
|
+
export const PI_EFFORTS = ["minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
13
|
+
export type BackendSelection =
|
|
14
|
+
| ({ backend?: "agy" } & AgySelection)
|
|
15
|
+
| { backend: "claude"; model: string; effort?: (typeof CLAUDE_EFFORTS)[number] }
|
|
16
|
+
| { backend: "grok"; model: string; effort?: (typeof GROK_EFFORTS)[number] }
|
|
17
|
+
| { backend: "codex"; model: string; effort?: (typeof CODEX_EFFORTS)[number] }
|
|
18
|
+
| { backend: "muse"; model: string; effort?: (typeof MUSE_EFFORTS)[number] }
|
|
19
|
+
| { backend: "pi"; model: string; effort?: (typeof PI_EFFORTS)[number] };
|
|
20
|
+
export type BackendContinuation = { id: string };
|
|
21
|
+
export type BackendProgress = { kind: "text"; text: string } | { kind: "activity"; label: string; timestamp: number; tool?: string };
|
|
22
|
+
export type BackendOnProgress = (progress: BackendProgress) => void;
|
|
23
|
+
|
|
24
|
+
/** BTW reports a tool name/type, not a command, argument, or assistant message.
|
|
25
|
+
* All six adapters use this extraction before events cross into the UI. */
|
|
26
|
+
export function btwToolName(value: unknown): string | undefined {
|
|
27
|
+
if (typeof value !== "string") return undefined;
|
|
28
|
+
// Restrict to the initial identifier. Agy may supply "Read /path" (or
|
|
29
|
+
// "Read(/path)"); neither should expose the path in a status hint.
|
|
30
|
+
return /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(
|
|
31
|
+
stripVTControlCharacters(value).replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim(),
|
|
32
|
+
)?.[0];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type BackendRequest = {
|
|
36
|
+
feature: BackendFeature;
|
|
37
|
+
prompt: string;
|
|
38
|
+
access: BackendAccess;
|
|
39
|
+
cwd?: string; // required for workspace-full
|
|
40
|
+
continuation?: BackendContinuation;
|
|
41
|
+
/** Opt-in tool-only activity for Grill on the review path; Guided Review stays unchanged. */
|
|
42
|
+
reportReviewTools?: boolean;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type BackendOutcome =
|
|
46
|
+
| { status: "success"; text: string; continuation?: BackendContinuation }
|
|
47
|
+
| { status: "failure" | "cancelled" | "timeout"; message: string; partialText?: string; continuationExpired?: true };
|
|
48
|
+
|
|
49
|
+
export type BackendExecuteOptions = {
|
|
50
|
+
// Injectable for offline tests only -- production always uses the defaults below.
|
|
51
|
+
killEscalationMs?: number;
|
|
52
|
+
deadlineMs?: number;
|
|
53
|
+
// Injectable for offline tests only: stands in for the SDK's createAgentSession so the Pi adapter's
|
|
54
|
+
// setup, cancellation, timeout and terminal-verification paths can be exercised without a model.
|
|
55
|
+
piCreateSession?: typeof createAgentSession;
|
|
56
|
+
};
|