Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import * as NodeReadlinePromises from "node:readline/promises";
6
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import { isCommandAvailable, resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell";
9import * as Config from "effect/Config";
10import * as Console from "effect/Console";
11import * as Effect from "effect/Effect";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14import { Command, Flag } from "effect/cli";
15
16import packageJson from "../../package.json" with { type: "json" };
17import * as ServerConfig from "../config.ts";
18import { resolveBaseDir } from "../os-jank.ts";
19import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts";
20import { describeServerProcess, writeTriageSession } from "../triage/triageSession.ts";
21import { baseDirFlag } from "./config.ts";
22import { interactiveStdin } from "./consoleStdin.ts";
23import { resolveCliCommand } from "./invocation.ts";
24
25interface TriageAgent {
26 readonly id: "claude" | "codex" | "antigravity";
27 readonly command: string;
28 readonly label: string;
29 readonly stateDirEnv: string;
30 readonly defaultStateDir: string;
31 readonly promptArgs?: ReadonlyArray<string>;
32}
33
34const TRIAGE_AGENTS: ReadonlyArray<TriageAgent> = [
35 {
36 id: "claude",
37 command: "claude",
38 label: "Claude Code",
39 stateDirEnv: "CLAUDE_CONFIG_DIR",
40 defaultStateDir: ".claude",
41 },
42 {
43 id: "codex",
44 command: "codex",
45 label: "Codex",
46 stateDirEnv: "CODEX_HOME",
47 defaultStateDir: ".codex",
48 },
49 {
50 id: "antigravity",
51 command: "agy",
52 label: "Antigravity",
53 stateDirEnv: "GEMINI_HOME",
54 defaultStateDir: ".gemini",
55 promptArgs: ["--prompt-interactive"],
56 },
57];
58
59const resolveAgentStateDir = (agent: TriageAgent) =>
60 process.env[agent.stateDirEnv]?.trim() || NodePath.join(NodeOS.homedir(), agent.defaultStateDir);
61
62export class TriageAgentUnavailableError extends Schema.TaggedError<TriageAgentUnavailableError>()(
63 "TriageAgentUnavailableError",
64 { agent: Schema.String },
65) {
66 override get message(): string {
67 return `\`${this.agent}\` is not installed or was not found on PATH.`;
68 }
69}
70
71export class TriageAgentChoiceRequiredError extends Schema.TaggedError<TriageAgentChoiceRequiredError>()(
72 "TriageAgentChoiceRequiredError",
73 {},
74) {
75 override get message(): string {
76 return "Multiple supported agent CLIs are installed and there is no terminal to ask which to use. Re-run with --agent claude, --agent codex, or --agent antigravity.";
77 }
78}
79
80export class TriageAgentSpawnError extends Schema.TaggedError<TriageAgentSpawnError>()(
81 "TriageAgentSpawnError",
82 { command: Schema.String, cause: Schema.Defect() },
83) {
84 override get message(): string {
85 return `Could not start \`${this.command}\`.`;
86 }
87}
88
89export const matchAgentAnswer = <Agent extends { readonly id: string }>(
90 agents: ReadonlyArray<Agent>,
91 answer: string,
92) => {
93 const trimmed = answer.trim();
94 return (
95 agents.find((_, index) => String(index + 1) === trimmed) ??
96 agents.find((agent) => agent.id === trimmed.toLowerCase())
97 );
98};
99
100export const pickAgent = <Agent extends { readonly id: string; readonly label: string }>(
101 agents: ReadonlyArray<Agent>,
102 input: NodeJS.ReadableStream = process.stdin,
103 output: NodeJS.WritableStream = process.stdout,
104) =>
105 Effect.promise(async () => {
106 const readline = NodeReadlinePromises.createInterface({ input, output });
107 // A readline closed by ended input leaves a pending question unsettled, and asking after a
108 // close throws, so closing aborts every question.
109 const closed = new AbortController();
110 readline.once("close", () => closed.abort());
111 try {
112 const menu = agents
113 .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`)
114 .join("\n");
115 for (;;) {
116 const answer = await readline.question(`Run triage with:\n${menu}\n> `, {
117 signal: closed.signal,
118 });
119 const picked = matchAgentAnswer(agents, answer);
120 if (picked !== undefined) {
121 return picked;
122 }
123 }
124 } catch (error) {
125 if (error instanceof Error && error.name === "AbortError") {
126 return undefined;
127 }
128 throw error;
129 } finally {
130 readline.close();
131 }
132 });
133
134const runInteractiveSession = (input: {
135 readonly command: string;
136 readonly args: ReadonlyArray<string>;
137 readonly shell: boolean;
138 readonly cwd: string;
139}) =>
140 Effect.callback<number, TriageAgentSpawnError>((resume) => {
141 const child = NodeChildProcess.spawn(input.command, [...input.args], {
142 cwd: input.cwd,
143 // The Windows desktop launcher supplies terminal input through the reopened console.
144 stdio: [interactiveStdin(), "inherit", "inherit"],
145 shell: input.shell,
146 });
147 child.once("error", (cause) =>
148 resume(Effect.fail(new TriageAgentSpawnError({ command: input.command, cause }))),
149 );
150 child.once("exit", (code, signal) => resume(Effect.succeed(code ?? (signal === null ? 0 : 1))));
151 });
152
153const describeTriageFiles = (session: {
154 readonly promptFilePath: string;
155 readonly contextFilePath: string;
156}) => [
157 "The triage prompt and machine context were written to:",
158 ` ${session.promptFilePath}`,
159 ` ${session.contextFilePath}`,
160];
161
162const agentFlag = Flag.Literals("agent", ["claude", "codex", "antigravity"]).pipe(
163 Flag.withDescription("Agent CLI to use. Default: ask when multiple are installed."),
164 Flag.optional,
165);
166
167const modelFlag = Flag.String("model").pipe(
168 Flag.withDescription("Model passed through to the agent CLI. Default: the agent's default."),
169 Flag.optional,
170);
171
172export const triageCommand = Command.make("triage", {
173 baseDir: baseDirFlag,
174 agent: agentFlag,
175 model: modelFlag,
176}).pipe(
177 Command.withDescription(
178 "Investigate a T3 Code problem on this machine with Claude Code, Codex, or Antigravity, and help file a good issue.",
179 ),
180 Command.withHandler((flags) =>
181 Effect.gen(function* () {
182 // Triage is a user-facing feature: always the userdata state, never dev.
183 const explicitBaseDir = Option.getOrUndefined(flags.baseDir);
184 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
185 const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome));
186 const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {});
187
188 const session = yield* writeTriageSession({
189 baseDir,
190 paths,
191 entry: {
192 kind: "cli",
193 cliVersion: packageJson.version,
194 launchedAs: yield* resolveCliCommand("triage"),
195 },
196 server: yield* describeServerProcess(paths.serverRuntimeStatePath),
197 });
198
199 const installed: Array<TriageAgent> = [];
200 for (const agent of TRIAGE_AGENTS) {
201 if (yield* isCommandAvailable(agent.command)) {
202 installed.push(agent);
203 }
204 }
205
206 const requested = Option.getOrUndefined(flags.agent);
207 let selected: TriageAgent | undefined;
208 if (requested !== undefined) {
209 selected = installed.find((agent) => agent.id === requested);
210 if (selected === undefined) {
211 return yield* new TriageAgentUnavailableError({
212 agent: TRIAGE_AGENTS.find((agent) => agent.id === requested)?.command ?? requested,
213 });
214 }
215 } else if (installed.length === 1) {
216 selected = installed[0];
217 } else if (installed.length > 1) {
218 // The picker needs terminal output too, or its invisible prompt hangs.
219 if (!process.stdin.isTTY || !process.stdout.isTTY) {
220 return yield* new TriageAgentChoiceRequiredError();
221 }
222 const picked = yield* pickAgent(installed);
223 if (picked === undefined) {
224 yield* Console.log("\nNo agent started.");
225 return;
226 }
227 selected = picked;
228 }
229
230 // Windows .cmd shims cannot carry multiline argv; the prompt file also serves as the paste fallback.
231 const { sessionDir, promptFilePath } = session;
232
233 if (selected === undefined) {
234 yield* Console.log(
235 [
236 "No supported agent CLI (claude, codex, agy) was found on this machine.",
237 "",
238 ...describeTriageFiles(session),
239 "",
240 "Paste the prompt file into any coding agent to run triage by hand.",
241 ].join("\n"),
242 );
243 return;
244 }
245
246 const model = Option.getOrUndefined(flags.model);
247 const launchPrompt = buildTriageLaunchPrompt(promptFilePath);
248 // The agent starts in the session directory, so a PATH match relative to this one would
249 // be searched from there. Windows keeps the bare name for its .cmd shim handling.
250 const onPath =
251 (yield* HostProcess.Platform) === "win32"
252 ? null
253 : yield* resolveCommandPath(selected.command);
254 const command = onPath === null ? selected.command : NodePath.resolve(onPath);
255 const spawnSpec = yield* resolveSpawnCommand(command, [
256 ...(model === undefined ? [] : ["--model", model]),
257 ...(selected.promptArgs ?? []),
258 launchPrompt,
259 ]);
260 yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);
261 const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: sessionDir });
262 if (exitCode !== 0) {
263 process.exitCode = exitCode;
264 yield* Console.log(
265 [
266 "",
267 `${selected.label} exited with code ${String(exitCode)}.`,
268 "",
269 `${selected.label} keeps its state in ${resolveAgentStateDir(selected)}.`,
270 `If that drive is out of space, free some up or set ${selected.stateDirEnv} to a folder on another drive.`,
271 "",
272 ...describeTriageFiles(session),
273 "",
274 `To retry, start \`${selected.command}\` yourself with any flags it suggested, or use any coding agent, and give it this prompt:`,
275 launchPrompt,
276 ].join("\n"),
277 );
278 }
279 }),
280 ),
281);