Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

triage.ts

275 lines9.7 KB

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>;
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 }
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 }
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 }
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 try {
108 const menu = agents
109 .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`)
110 .join("\n");
111 for (;;) {
112 const answer = await readline.question(`Run triage with:\n${menu}\n> `);
113 const picked = matchAgentAnswer(agents, answer);
114 if (picked !== undefined) {
115 return picked;
116 }
117 }
118 } catch (error) {
119 if (error instanceof Error && error.name === "AbortError") {
120 return undefined;
121 }
122 throw error;
123 } finally {
124 readline.close();
125 }
126 });
127​
128const runInteractiveSession = (input: {
129 readonly command: string;
130 readonly args: ReadonlyArray<string>;
131 readonly shell: boolean;
132 readonly cwd: string;
133}) =>
134 Effect.callback<number, TriageAgentSpawnError>((resume) => {
135 const child = NodeChildProcess.spawn(input.command, [...input.args], {
136 cwd: input.cwd,
137 // The Windows desktop launcher supplies terminal input through the reopened console.
138 stdio: [interactiveStdin(), "inherit", "inherit"],
139 shell: input.shell,
140 });
141 child.once("error", (cause) =>
142 resume(Effect.fail(new TriageAgentSpawnError({ command: input.command, cause }))),
143 );
144 child.once("exit", (code, signal) => resume(Effect.succeed(code ?? (signal === null ? 0 : 1))));
145 });
146​
147const describeTriageFiles = (session: {
148 readonly promptFilePath: string;
149 readonly contextFilePath: string;
150}) => [
151 "The triage prompt and machine context were written to:",
152 ` ${session.promptFilePath}`,
153 ` ${session.contextFilePath}`,
154];
155​
156const agentFlag = Flag.Literals("agent", ["claude", "codex", "antigravity"]).pipe(
157 Flag.withDescription("Agent CLI to use. Default: ask when multiple are installed."),
158 Flag.optional,
159);
160​
161const modelFlag = Flag.String("model").pipe(
162 Flag.withDescription("Model passed through to the agent CLI. Default: the agent's default."),
163 Flag.optional,
164);
165​
166export const triageCommand = Command.make("triage", {
167 baseDir: baseDirFlag,
168 agent: agentFlag,
169 model: modelFlag,
170}).pipe(
171 Command.withDescription(
172 "Investigate a T3 Code problem on this machine with Claude Code, Codex, or Antigravity, and help file a good issue.",
173 ),
174 Command.withHandler((flags) =>
175 Effect.gen(function* () {
176 // Triage is a user-facing feature: always the userdata state, never dev.
177 const explicitBaseDir = Option.getOrUndefined(flags.baseDir);
178 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
179 const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome));
180 const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {});
181​
182 const session = yield* writeTriageSession({
183 baseDir,
184 paths,
185 entry: {
186 kind: "cli",
187 cliVersion: packageJson.version,
188 launchedAs: yield* resolveCliCommand("triage"),
189 },
190 server: yield* describeServerProcess(paths.serverRuntimeStatePath),
191 });
192​
193 const installed: Array<TriageAgent> = [];
194 for (const agent of TRIAGE_AGENTS) {
195 if (yield* isCommandAvailable(agent.command)) {
196 installed.push(agent);
197 }
198 }
199​
200 const requested = Option.getOrUndefined(flags.agent);
201 let selected: TriageAgent | undefined;
202 if (requested !== undefined) {
203 selected = installed.find((agent) => agent.id === requested);
204 if (selected === undefined) {
205 return yield* new TriageAgentUnavailableError({
206 agent: TRIAGE_AGENTS.find((agent) => agent.id === requested)?.command ?? requested,
207 });
208 }
209 } else if (installed.length === 1) {
210 selected = installed[0];
211 } else if (installed.length > 1) {
212 // The picker needs terminal output too, or its invisible prompt hangs.
213 if (!process.stdin.isTTY || !process.stdout.isTTY) {
214 return yield* new TriageAgentChoiceRequiredError();
215 }
216 const picked = yield* pickAgent(installed);
217 if (picked === undefined) {
218 yield* Console.log("\nNo agent started.");
219 return;
220 }
221 selected = picked;
222 }
223​
224 // Windows .cmd shims cannot carry multiline argv; the prompt file also serves as the paste fallback.
225 const { sessionDir, promptFilePath } = session;
226​
227 if (selected === undefined) {
228 yield* Console.log(
229 [
230 "No supported agent CLI (claude, codex, agy) was found on this machine.",
231 "",
232 ...describeTriageFiles(session),
233 "",
234 "Paste the prompt file into any coding agent to run triage by hand.",
235 ].join("\n"),
236 );
237 return;
238 }
239​
240 const model = Option.getOrUndefined(flags.model);
241 const launchPrompt = buildTriageLaunchPrompt(promptFilePath);
242 // The agent starts in the session directory, so a PATH match relative to this one would
243 // be searched from there. Windows keeps the bare name for its .cmd shim handling.
244 const onPath =
245 (yield* HostProcess.Platform) === "win32"
246 ? null
247 : yield* resolveCommandPath(selected.command);
248 const command = onPath === null ? selected.command : NodePath.resolve(onPath);
249 const spawnSpec = yield* resolveSpawnCommand(command, [
250 ...(model === undefined ? [] : ["--model", model]),
251 ...(selected.promptArgs ?? []),
252 launchPrompt,
253 ]);
254 yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);
255 const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: sessionDir });
256 if (exitCode !== 0) {
257 process.exitCode = exitCode;
258 yield* Console.log(
259 [
260 "",
261 `${selected.label} exited with code ${String(exitCode)}.`,
262 "",
263 `${selected.label} keeps its state in ${resolveAgentStateDir(selected)}.`,
264 `If that drive is out of space, free some up or set ${selected.stateDirEnv} to a folder on another drive.`,
265 "",
266 ...describeTriageFiles(session),
267 "",
268 `To retry, start \`${selected.command}\` yourself with any flags it suggested, or use any coding agent, and give it this prompt:`,
269 launchPrompt,
270 ].join("\n"),
271 );
272 }
273 }),
274 ),
275);