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

triage.ts

257 lines9.7 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeOS from "node:os";
4import * as NodeReadlinePromises from "node:readline/promises";
5​
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
8import * as Config from "effect/Config";
9import * as Console from "effect/Console";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import { Command, Flag } from "effect/cli";
17​
18import packageJson from "../../package.json" with { type: "json" };
19import * as BootService from "../cloud/bootService.ts";
20import * as ServerConfig from "../config.ts";
21import { resolveBaseDir } from "../os-jank.ts";
22import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
23import { baseDirFlag } from "./config.ts";
24import { interactiveStdin } from "./consoleStdin.ts";
25import { resolveCliCommand } from "./invocation.ts";
26import {
27 buildTriageContext,
28 buildTriageLaunchPrompt,
29 buildTriageSeedPrompt,
30} from "./triagePrompt.ts";
31​
32interface TriageAgent {
33 readonly id: "claude" | "codex";
34 readonly command: string;
35 readonly label: string;
37​
38const TRIAGE_AGENTS: ReadonlyArray<TriageAgent> = [
39 { id: "claude", command: "claude", label: "Claude Code" },
40 { id: "codex", command: "codex", label: "Codex" },
41];
42​
43export class TriageAgentUnavailableError extends Schema.TaggedError<TriageAgentUnavailableError>()(
44 "TriageAgentUnavailableError",
45 { agent: Schema.String },
46) {
47 override get message(): string {
48 return `\`${this.agent}\` is not installed or was not found on PATH.`;
49 }
51​
52export class TriageAgentChoiceRequiredError extends Schema.TaggedError<TriageAgentChoiceRequiredError>()(
53 "TriageAgentChoiceRequiredError",
54 {},
55) {
56 override get message(): string {
57 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.";
58 }
60​
61export class TriageAgentSpawnError extends Schema.TaggedError<TriageAgentSpawnError>()(
62 "TriageAgentSpawnError",
63 { command: Schema.String, cause: Schema.Defect() },
64) {
65 override get message(): string {
66 return `Could not start \`${this.command}\`.`;
67 }
69​
70export const describeServerProcess = Effect.fn("triage.describeServerProcess")(function* (
71 serverRuntimeStatePath: string,
72) {
73 const state = yield* readPersistedServerRuntimeState(serverRuntimeStatePath);
74 if (Option.isNone(state)) {
75 return "not running (no server-runtime.json; the server may never have started here)";
76 }
77 const version =
78 state.value.serverVersion === undefined
79 ? "version not recorded"
80 : `version ${state.value.serverVersion}`;
81 if (!isProcessAlive(state.value.pid)) {
82 return `not running (state file is stale: pid ${String(state.value.pid)} is dead; last origin ${state.value.origin}, ${version})`;
83 }
84 return `running (pid ${String(state.value.pid)}, ${state.value.origin}, ${version})`;
85});
86​
87const pickAgent = (agents: ReadonlyArray<TriageAgent>) =>
88 Effect.promise(async () => {
89 const readline = NodeReadlinePromises.createInterface({
90 input: process.stdin,
91 output: process.stdout,
92 });
93 try {
94 const menu = agents
95 .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`)
96 .join("\n");
97 for (;;) {
98 const answer = (await readline.question(`Run triage with:\n${menu}\n> `)).trim();
99 const byNumber = agents[Number.parseInt(answer, 10) - 1];
100 if (byNumber !== undefined) {
101 return byNumber;
102 }
103 const byId = agents.find((agent) => agent.id === answer.toLowerCase());
104 if (byId !== undefined) {
105 return byId;
106 }
107 }
108 } finally {
109 readline.close();
110 }
111 });
112​
113const runInteractiveSession = (input: {
114 readonly command: string;
115 readonly args: ReadonlyArray<string>;
116 readonly shell: boolean;
117 readonly cwd: string;
118}) =>
119 Effect.callback<number, TriageAgentSpawnError>((resume) => {
120 const child = NodeChildProcess.spawn(input.command, [...input.args], {
121 cwd: input.cwd,
122 // The agent reads the user's terminal; under the desktop app's Windows
123 // launcher that is the reopened console, not the (missing) inherited stdin.
124 stdio: [interactiveStdin(), "inherit", "inherit"],
125 shell: input.shell,
126 });
127 child.once("error", (cause) =>
128 resume(Effect.fail(new TriageAgentSpawnError({ command: input.command, cause }))),
129 );
130 // Signal death has no exit code; report failure rather than success.
131 child.once("exit", (code, signal) => resume(Effect.succeed(code ?? (signal === null ? 0 : 1))));
132 });
133​
134const agentFlag = Flag.Literals("agent", ["claude", "codex"]).pipe(
135 Flag.withDescription("Agent CLI to use. Default: ask when both are installed."),
136 Flag.optional,
137);
138​
139const modelFlag = Flag.String("model").pipe(
140 Flag.withDescription("Model passed through to the agent CLI. Default: the agent's default."),
141 Flag.optional,
142);
143​
144export const triageCommand = Command.make("triage", {
145 baseDir: baseDirFlag,
146 agent: agentFlag,
147 model: modelFlag,
148}).pipe(
149 Command.withDescription(
150 "Investigate a T3 Code problem on this machine with claude or codex, and help file a good issue.",
151 ),
152 Command.withHandler((flags) =>
153 Effect.gen(function* () {
154 const fs = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156​
157 // Triage is a user-facing feature: always the userdata state, never dev.
158 const explicitBaseDir = Option.getOrUndefined(flags.baseDir);
159 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
160 const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome));
161 const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {});
162​
163 const now = yield* DateTime.now;
164 const scratchDir = path.join(
165 paths.stateDir,
166 "triage",
167 DateTime.formatIso(now).replaceAll(":", "-").replace(".", "-"),
168 );
169 yield* fs.makeDirectory(scratchDir, { recursive: true });
170​
171 const contextFilePath = path.join(scratchDir, "context.md");
172 yield* fs.writeFileString(
173 contextFilePath,
174 buildTriageContext({
175 generatedAt: DateTime.formatIso(now),
176 cliVersion: packageJson.version,
177 os: `${yield* HostProcess.Platform} ${yield* HostProcess.Architecture} (${NodeOS.release()})`,
178 nodeVersion: process.version,
179 launchedAs: yield* resolveCliCommand("triage"),
180 server: yield* describeServerProcess(paths.serverRuntimeStatePath),
181 paths: {
182 stateDir: paths.stateDir,
183 dbPath: paths.dbPath,
184 settingsPath: paths.settingsPath,
185 logsDir: paths.logsDir,
186 serviceLogPath: path.join(paths.logsDir, BootService.BOOT_SERVICE_LOG_FILE),
187 desktopBackendLogGlob: path.join(paths.logsDir, "server-child*.log*"),
188 serverTracePath: paths.serverTracePath,
189 providerEventLogPath: paths.providerEventLogPath,
190 terminalLogsDir: paths.terminalLogsDir,
191 providerStatusCacheDir: paths.providerStatusCacheDir,
192 secretsDir: paths.secretsDir,
193 sourceCacheDir: path.join(baseDir, "source"),
194 },
195 }),
196 );
197​
198 const installed: Array<TriageAgent> = [];
199 for (const agent of TRIAGE_AGENTS) {
200 if (yield* isCommandAvailable(agent.command)) {
201 installed.push(agent);
202 }
203 }
204​
205 const requested = Option.getOrUndefined(flags.agent);
206 let selected: TriageAgent | undefined;
207 if (requested !== undefined) {
208 selected = installed.find((agent) => agent.id === requested);
209 if (selected === undefined) {
210 return yield* new TriageAgentUnavailableError({ agent: requested });
211 }
212 } else if (installed.length === 1) {
213 selected = installed[0];
214 } else if (installed.length > 1) {
215 // Both streams must be terminals: with stdout redirected the picker
216 // prompt is invisible and the command would hang waiting on it.
217 if (!process.stdin.isTTY || !process.stdout.isTTY) {
218 return yield* new TriageAgentChoiceRequiredError();
219 }
220 selected = yield* pickAgent(installed);
221 }
222​
223 // The agent is launched with a one-line pointer at it: Windows `.cmd`
224 // shims run through cmd.exe, which cannot carry the multiline playbook as
225 // an argv string, and with no agent installed the same file is the
226 // paste-anywhere fallback.
227 const promptFilePath = path.join(scratchDir, "prompt.md");
228 yield* fs.writeFileString(promptFilePath, buildTriageSeedPrompt(contextFilePath));
229​
230 if (selected === undefined) {
231 yield* Console.log(
232 [
233 "No supported agent CLI (claude, codex) was found on this machine.",
234 "",
235 "The triage prompt and machine context were written to:",
236 ` ${promptFilePath}`,
237 ` ${contextFilePath}`,
238 "",
239 "Paste the prompt file into any coding agent to run triage by hand.",
240 ].join("\n"),
241 );
242 return;
243 }
244​
245 const model = Option.getOrUndefined(flags.model);
246 const spawnSpec = yield* resolveSpawnCommand(selected.command, [
247 ...(model === undefined ? [] : ["--model", model]),
248 buildTriageLaunchPrompt(promptFilePath),
249 ]);
250 yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);
251 const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: scratchDir });
252 if (exitCode !== 0) {
253 process.exitCode = exitCode;
254 }
255 }),
256 ),
257);