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

triage.ts

274 lines10.6 KB

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