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

triage.ts

196 lines7.0 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeReadlinePromises from "node:readline/promises";
4​
5import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
6import * as Config from "effect/Config";
7import * as Console from "effect/Console";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11import { Command, Flag } from "effect/cli";
12​
13import packageJson from "../../package.json" with { type: "json" };
14import * as ServerConfig from "../config.ts";
15import { resolveBaseDir } from "../os-jank.ts";
16import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts";
17import { describeServerProcess, writeTriageSession } from "../triage/triageSession.ts";
18import { baseDirFlag } from "./config.ts";
19import { interactiveStdin } from "./consoleStdin.ts";
20import { resolveCliCommand } from "./invocation.ts";
21​
22interface TriageAgent {
23 readonly id: "claude" | "codex";
24 readonly command: string;
25 readonly label: string;
27​
28const TRIAGE_AGENTS: ReadonlyArray<TriageAgent> = [
29 { id: "claude", command: "claude", label: "Claude Code" },
30 { id: "codex", command: "codex", label: "Codex" },
31];
32​
33export class TriageAgentUnavailableError extends Schema.TaggedError<TriageAgentUnavailableError>()(
34 "TriageAgentUnavailableError",
35 { agent: Schema.String },
36) {
37 override get message(): string {
38 return `\`${this.agent}\` is not installed or was not found on PATH.`;
39 }
41​
42export class TriageAgentChoiceRequiredError extends Schema.TaggedError<TriageAgentChoiceRequiredError>()(
43 "TriageAgentChoiceRequiredError",
44 {},
45) {
46 override get message(): string {
47 return "Both claude and codex are installed and there is no terminal to ask which to use. Re-run with --agent claude or --agent codex.";
48 }
50​
51export class TriageAgentSpawnError extends Schema.TaggedError<TriageAgentSpawnError>()(
52 "TriageAgentSpawnError",
53 { command: Schema.String, cause: Schema.Defect() },
54) {
55 override get message(): string {
56 return `Could not start \`${this.command}\`.`;
57 }
59​
60const pickAgent = (agents: ReadonlyArray<TriageAgent>) =>
61 Effect.promise(async () => {
62 const readline = NodeReadlinePromises.createInterface({
63 input: process.stdin,
64 output: process.stdout,
65 });
66 try {
67 const menu = agents
68 .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`)
69 .join("\n");
70 for (;;) {
71 const answer = (await readline.question(`Run triage with:\n${menu}\n> `)).trim();
72 const byNumber = agents[Number.parseInt(answer, 10) - 1];
73 if (byNumber !== undefined) {
74 return byNumber;
75 }
76 const byId = agents.find((agent) => agent.id === answer.toLowerCase());
77 if (byId !== undefined) {
78 return byId;
79 }
80 }
81 } finally {
82 readline.close();
83 }
84 });
85​
86const runInteractiveSession = (input: {
87 readonly command: string;
88 readonly args: ReadonlyArray<string>;
89 readonly shell: boolean;
90 readonly cwd: string;
91}) =>
92 Effect.callback<number, TriageAgentSpawnError>((resume) => {
93 const child = NodeChildProcess.spawn(input.command, [...input.args], {
94 cwd: input.cwd,
95 // The Windows desktop launcher supplies terminal input through the reopened console.
96 stdio: [interactiveStdin(), "inherit", "inherit"],
97 shell: input.shell,
98 });
99 child.once("error", (cause) =>
100 resume(Effect.fail(new TriageAgentSpawnError({ command: input.command, cause }))),
101 );
102 child.once("exit", (code, signal) => resume(Effect.succeed(code ?? (signal === null ? 0 : 1))));
103 });
104​
105const agentFlag = Flag.Literals("agent", ["claude", "codex"]).pipe(
106 Flag.withDescription("Agent CLI to use. Default: ask when both are installed."),
107 Flag.optional,
108);
109​
110const modelFlag = Flag.String("model").pipe(
111 Flag.withDescription("Model passed through to the agent CLI. Default: the agent's default."),
112 Flag.optional,
113);
114​
115export const triageCommand = Command.make("triage", {
116 baseDir: baseDirFlag,
117 agent: agentFlag,
118 model: modelFlag,
119}).pipe(
120 Command.withDescription(
121 "Investigate a T3 Code problem on this machine with claude or codex, and help file a good issue.",
122 ),
123 Command.withHandler((flags) =>
124 Effect.gen(function* () {
125 // Triage is a user-facing feature: always the userdata state, never dev.
126 const explicitBaseDir = Option.getOrUndefined(flags.baseDir);
127 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
128 const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome));
129 const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {});
130​
131 const session = yield* writeTriageSession({
132 baseDir,
133 paths,
134 entry: {
135 kind: "cli",
136 cliVersion: packageJson.version,
137 launchedAs: yield* resolveCliCommand("triage"),
138 },
139 server: yield* describeServerProcess(paths.serverRuntimeStatePath),
140 });
141​
142 const installed: Array<TriageAgent> = [];
143 for (const agent of TRIAGE_AGENTS) {
144 if (yield* isCommandAvailable(agent.command)) {
145 installed.push(agent);
146 }
147 }
148​
149 const requested = Option.getOrUndefined(flags.agent);
150 let selected: TriageAgent | undefined;
151 if (requested !== undefined) {
152 selected = installed.find((agent) => agent.id === requested);
153 if (selected === undefined) {
154 return yield* new TriageAgentUnavailableError({ agent: requested });
155 }
156 } else if (installed.length === 1) {
157 selected = installed[0];
158 } else if (installed.length > 1) {
159 // The picker needs terminal output too, or its invisible prompt hangs.
160 if (!process.stdin.isTTY || !process.stdout.isTTY) {
161 return yield* new TriageAgentChoiceRequiredError();
162 }
163 selected = yield* pickAgent(installed);
164 }
165​
166 // Windows .cmd shims cannot carry multiline argv; the prompt file also serves as the paste fallback.
167 const { sessionDir, promptFilePath, contextFilePath } = session;
168​
169 if (selected === undefined) {
170 yield* Console.log(
171 [
172 "No supported agent CLI (claude, codex) was found on this machine.",
173 "",
174 "The triage prompt and machine context were written to:",
175 ` ${promptFilePath}`,
176 ` ${contextFilePath}`,
177 "",
178 "Paste the prompt file into any coding agent to run triage by hand.",
179 ].join("\n"),
180 );
181 return;
182 }
183​
184 const model = Option.getOrUndefined(flags.model);
185 const spawnSpec = yield* resolveSpawnCommand(selected.command, [
186 ...(model === undefined ? [] : ["--model", model]),
187 buildTriageLaunchPrompt(promptFilePath),
188 ]);
189 yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);
190 const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: sessionDir });
191 if (exitCode !== 0) {
192 process.exitCode = exitCode;
193 }
194 }),
195 ),
196);