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