Open History to see the last commit
1/**
2 * `t3 triage` - hand a misbehaving install to the user's own coding agent.
3 *
4 * The command is deliberately thin: it writes a `context.md` with machine facts
5 * (version, paths, server liveness), then launches claude or codex
6 * interactively, seeded with the playbook from `triagePrompt.ts`. The agent
7 * asks the user what went wrong, investigates, and files the issue; the
8 * harness's own permission prompts gate anything it wants to run. With no
9 * agent CLI installed, the prompt and context are written to disk for the user
10 * to paste into whatever agent they do have.
11 */
12// @effect-diagnostics nodeBuiltinImport:off
13import * as NodeChildProcess from "node:child_process";
14import * as NodeOS from "node:os";
15import * as NodeReadlinePromises from "node:readline/promises";
16
17import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
18import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
19import * as Config from "effect/Config";
20import * as Console from "effect/Console";
21import * as DateTime from "effect/DateTime";
22import * as Effect from "effect/Effect";
23import * as FileSystem from "effect/FileSystem";
24import * as Option from "effect/Option";
25import * as Path from "effect/Path";
26import * as Schema from "effect/Schema";
27import { Command, Flag } from "effect/unstable/cli";
28
29import packageJson from "../../package.json" with { type: "json" };
30import * as ServerConfig from "../config.ts";
31import { resolveBaseDir } from "../os-jank.ts";
32import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
33import { baseDirFlag } from "./config.ts";
34import { resolveCliCommand } from "./invocation.ts";
35import {
36 buildTriageContext,
37 buildTriageLaunchPrompt,
38 buildTriageSeedPrompt,
39} from "./triagePrompt.ts";
40
41interface TriageAgent {
42 readonly id: "claude" | "codex";
43 readonly command: string;
44 readonly label: string;
45}
46
47const TRIAGE_AGENTS: ReadonlyArray<TriageAgent> = [
48 { id: "claude", command: "claude", label: "Claude Code" },
49 { id: "codex", command: "codex", label: "Codex" },
50];
51
52export class TriageAgentUnavailableError extends Schema.TaggedErrorClass<TriageAgentUnavailableError>()(
53 "TriageAgentUnavailableError",
54 { agent: Schema.String },
55) {
56 override get message(): string {
57 return `\`${this.agent}\` is not installed or was not found on PATH.`;
58 }
59}
60
61export class TriageAgentChoiceRequiredError extends Schema.TaggedErrorClass<TriageAgentChoiceRequiredError>()(
62 "TriageAgentChoiceRequiredError",
63 {},
64) {
65 override get message(): string {
66 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.";
67 }
68}
69
70export class TriageAgentSpawnError extends Schema.TaggedErrorClass<TriageAgentSpawnError>()(
71 "TriageAgentSpawnError",
72 { command: Schema.String, cause: Schema.Defect() },
73) {
74 override get message(): string {
75 return `Could not start \`${this.command}\`.`;
76 }
77}
78
79// signal 0 delivers nothing; it only reports whether the pid exists. EPERM
80// means it exists but belongs to another user, which still counts as alive.
81const isProcessAlive = (pid: number): boolean => {
82 try {
83 process.kill(pid, 0);
84 return true;
85 } catch (error) {
86 return error instanceof Error && "code" in error && error.code === "EPERM";
87 }
88};
89
90/** One human-readable line about the local server, for `context.md`. */
91const describeServerProcess = Effect.fn("triage.describeServerProcess")(function* (
92 serverRuntimeStatePath: string,
93) {
94 // readPersistedServerRuntimeState swallows read/decode failures itself and
95 // returns none, so a corrupt state file reads as "not running" here.
96 const state = yield* readPersistedServerRuntimeState(serverRuntimeStatePath);
97 if (Option.isNone(state)) {
98 return "not running (no server-runtime.json; the server may never have started here)";
99 }
100 if (!isProcessAlive(state.value.pid)) {
101 return `not running (state file is stale: pid ${String(state.value.pid)} is dead; last origin ${state.value.origin})`;
102 }
103 return `running (pid ${String(state.value.pid)}, ${state.value.origin})`;
104});
105
106const pickAgent = (agents: ReadonlyArray<TriageAgent>) =>
107 Effect.promise(async () => {
108 const readline = NodeReadlinePromises.createInterface({
109 input: process.stdin,
110 output: process.stdout,
111 });
112 try {
113 const menu = agents
114 .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`)
115 .join("\n");
116 for (;;) {
117 const answer = (await readline.question(`Run triage with:\n${menu}\n> `)).trim();
118 const byNumber = agents[Number.parseInt(answer, 10) - 1];
119 if (byNumber !== undefined) {
120 return byNumber;
121 }
122 const byId = agents.find((agent) => agent.id === answer.toLowerCase());
123 if (byId !== undefined) {
124 return byId;
125 }
126 }
127 } finally {
128 readline.close();
129 }
130 });
131
132/**
133 * Run the agent CLI as a normal interactive session: the user's terminal is
134 * the UI, and the harness's own permission prompts gate every action. Resolves
135 * with the child's exit code.
136 */
137const runInteractiveSession = (input: {
138 readonly command: string;
139 readonly args: ReadonlyArray<string>;
140 readonly shell: boolean;
141 readonly cwd: string;
142}) =>
143 Effect.callback<number, TriageAgentSpawnError>((resume) => {
144 const child = NodeChildProcess.spawn(input.command, [...input.args], {
145 cwd: input.cwd,
146 stdio: "inherit",
147 shell: input.shell,
148 });
149 child.once("error", (cause) =>
150 resume(Effect.fail(new TriageAgentSpawnError({ command: input.command, cause }))),
151 );
152 // Signal death has no exit code; report failure rather than success.
153 child.once("exit", (code, signal) => resume(Effect.succeed(code ?? (signal === null ? 0 : 1))));
154 });
155
156const agentFlag = Flag.choice("agent", ["claude", "codex"]).pipe(
157 Flag.withDescription("Agent CLI to use. Default: ask when both 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 or codex, and help file a good issue.",
173 ),
174 Command.withHandler((flags) =>
175 Effect.gen(function* () {
176 const fs = yield* FileSystem.FileSystem;
177 const path = yield* Path.Path;
178
179 // Triage is a user-facing feature: always the userdata state, never dev.
180 // --base-dir wins; T3CODE_HOME is its documented env equivalent (same
181 // precedence as `t3 pair`).
182 const explicitBaseDir = Option.getOrUndefined(flags.baseDir);
183 const envHome = yield* Config.string("T3CODE_HOME").pipe(Config.option);
184 const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome));
185 const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {});
186
187 const now = yield* DateTime.now;
188 const scratchDir = path.join(
189 paths.stateDir,
190 "triage",
191 // ISO instant, made safe for Windows paths.
192 DateTime.formatIso(now).replaceAll(":", "-").replace(".", "-"),
193 );
194 yield* fs.makeDirectory(scratchDir, { recursive: true });
195
196 const version = packageJson.version;
197 const contextFilePath = path.join(scratchDir, "context.md");
198 yield* fs.writeFileString(
199 contextFilePath,
200 buildTriageContext({
201 generatedAt: DateTime.formatIso(now),
202 version,
203 releaseTag: version.includes("-nightly.")
204 ? `v${version} (nightly build; if this tag does not exist, clone main)`
205 : `v${version}`,
206 os: `${yield* HostProcessPlatform} ${yield* HostProcessArchitecture} (${NodeOS.release()})`,
207 nodeVersion: process.version,
208 launchedAs: yield* resolveCliCommand("triage"),
209 server: yield* describeServerProcess(paths.serverRuntimeStatePath),
210 paths: {
211 stateDir: paths.stateDir,
212 dbPath: paths.dbPath,
213 settingsPath: paths.settingsPath,
214 logsDir: paths.logsDir,
215 serverLogPath: paths.serverLogPath,
216 serverTracePath: paths.serverTracePath,
217 providerEventLogPath: paths.providerEventLogPath,
218 terminalLogsDir: paths.terminalLogsDir,
219 providerStatusCacheDir: paths.providerStatusCacheDir,
220 secretsDir: paths.secretsDir,
221 sourceCacheDir: path.join(baseDir, "source"),
222 },
223 }),
224 );
225
226 const installed: Array<TriageAgent> = [];
227 for (const agent of TRIAGE_AGENTS) {
228 if (yield* isCommandAvailable(agent.command)) {
229 installed.push(agent);
230 }
231 }
232
233 const requested = Option.getOrUndefined(flags.agent);
234 let selected: TriageAgent | undefined;
235 if (requested !== undefined) {
236 selected = installed.find((agent) => agent.id === requested);
237 if (selected === undefined) {
238 return yield* new TriageAgentUnavailableError({ agent: requested });
239 }
240 } else if (installed.length === 1) {
241 selected = installed[0];
242 } else if (installed.length > 1) {
243 // Both streams must be terminals: with stdout redirected the picker
244 // prompt is invisible and the command would hang waiting on it.
245 if (!process.stdin.isTTY || !process.stdout.isTTY) {
246 return yield* new TriageAgentChoiceRequiredError();
247 }
248 selected = yield* pickAgent(installed);
249 }
250
251 // The full seed prompt always goes to disk. The agent is launched with a
252 // one-line pointer at it: Windows `.cmd` shims run through cmd.exe,
253 // which cannot carry the multiline playbook as an argv string, and with
254 // no agent installed the same file is the paste-anywhere fallback.
255 const promptFilePath = path.join(scratchDir, "prompt.md");
256 yield* fs.writeFileString(promptFilePath, buildTriageSeedPrompt(contextFilePath));
257
258 if (selected === undefined) {
259 yield* Console.log(
260 [
261 "No supported agent CLI (claude, codex) was found on this machine.",
262 "",
263 "The triage prompt and machine context were written to:",
264 ` ${promptFilePath}`,
265 ` ${contextFilePath}`,
266 "",
267 "Paste the prompt file into any coding agent to run triage by hand.",
268 ].join("\n"),
269 );
270 return;
271 }
272
273 const model = Option.getOrUndefined(flags.model);
274 const spawnSpec = yield* resolveSpawnCommand(selected.command, [
275 ...(model === undefined ? [] : ["--model", model]),
276 buildTriageLaunchPrompt(promptFilePath),
277 ]);
278 yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);
279 const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: scratchDir });
280 if (exitCode !== 0) {
281 process.exitCode = exitCode;
282 }
283 }),
284 ),
285);