The best way to control Claude Code, Codex and more from any computer or phone

main
ts 249 lines 8.67 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off
2 import * as NodeChildProcess from "node:child_process";
3 import * as NodeOS from "node:os";
4 import * as NodePath from "node:path";
5 import * as NodeReadlinePromises from "node:readline/promises";
6
7 import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
8 import * as Config from "effect/Config";
9 import * as Console from "effect/Console";
10 import * as Effect from "effect/Effect";
11 import * as Option from "effect/Option";
12 import * as Schema from "effect/Schema";
13 import { Command, Flag } from "effect/cli";
14
15 import packageJson from "../../package.json" with { type: "json" };
16 import * as ServerConfig from "../config.ts";
17 import { resolveBaseDir } from "../os-jank.ts";
18 import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts";
19 import { describeServerProcess, writeTriageSession } from "../triage/triageSession.ts";
20 import { baseDirFlag } from "./config.ts";
21 import { interactiveStdin } from "./consoleStdin.ts";
22 import { resolveCliCommand } from "./invocation.ts";
23
24 interface TriageAgent {
25 readonly id: "claude" | "codex" | "antigravity";
26 readonly command: string;
27 readonly label: string;
28 readonly stateDirEnv: string;
29 readonly defaultStateDir: string;
30 readonly promptArgs?: ReadonlyArray<string>;
31 }
32
33 const TRIAGE_AGENTS: ReadonlyArray<TriageAgent> = [
34 {
35 id: "claude",
36 command: "claude",
37 label: "Claude Code",
38 stateDirEnv: "CLAUDE_CONFIG_DIR",
39 defaultStateDir: ".claude",
40 },
41 {
42 id: "codex",
43 command: "codex",
44 label: "Codex",
45 stateDirEnv: "CODEX_HOME",
46 defaultStateDir: ".codex",
47 },
48 {
49 id: "antigravity",
50 command: "agy",
51 label: "Antigravity",
52 stateDirEnv: "GEMINI_HOME",
53 defaultStateDir: ".gemini",
54 promptArgs: ["--prompt-interactive"],
55 },
56 ];
57
58 const resolveAgentStateDir = (agent: TriageAgent) =>
59 process.env[agent.stateDirEnv]?.trim() || NodePath.join(NodeOS.homedir(), agent.defaultStateDir);
60
61 export class TriageAgentUnavailableError extends Schema.TaggedError<TriageAgentUnavailableError>()(
62 "TriageAgentUnavailableError",
63 { agent: Schema.String },
64 ) {
65 override get message(): string {
66 return `\`${this.agent}\` is not installed or was not found on PATH.`;
67 }
68 }
69
70 export class TriageAgentChoiceRequiredError extends Schema.TaggedError<TriageAgentChoiceRequiredError>()(
71 "TriageAgentChoiceRequiredError",
72 {},
73 ) {
74 override get message(): string {
75 return "Multiple supported agent CLIs are installed and there is no terminal to ask which to use. Re-run with --agent claude, --agent codex, or --agent antigravity.";
76 }
77 }
78
79 export class TriageAgentSpawnError extends Schema.TaggedError<TriageAgentSpawnError>()(
80 "TriageAgentSpawnError",
81 { command: Schema.String, cause: Schema.Defect() },
82 ) {
83 override get message(): string {
84 return `Could not start \`${this.command}\`.`;
85 }
86 }
87
88 const pickAgent = (agents: ReadonlyArray<TriageAgent>) =>
89 Effect.promise(async () => {
90 const readline = NodeReadlinePromises.createInterface({
91 input: process.stdin,
92 output: process.stdout,
93 });
94 try {
95 const menu = agents
96 .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`)
97 .join("\n");
98 for (;;) {
99 const answer = (await readline.question(`Run triage with:\n${menu}\n> `)).trim();
100 const byNumber = agents[Number.parseInt(answer, 10) - 1];
101 if (byNumber !== undefined) {
102 return byNumber;
103 }
104 const byId = agents.find((agent) => agent.id === answer.toLowerCase());
105 if (byId !== undefined) {
106 return byId;
107 }
108 }
109 } finally {
110 readline.close();
111 }
112 });
113
114 const runInteractiveSession = (input: {
115 readonly command: string;
116 readonly args: ReadonlyArray<string>;
117 readonly shell: boolean;
118 readonly cwd: string;
119 }) =>
120 Effect.callback<number, TriageAgentSpawnError>((resume) => {
121 const child = NodeChildProcess.spawn(input.command, [...input.args], {
122 cwd: input.cwd,
123 // The Windows desktop launcher supplies terminal input through the reopened console.
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 child.once("exit", (code, signal) => resume(Effect.succeed(code ?? (signal === null ? 0 : 1))));
131 });
132
133 const describeTriageFiles = (session: {
134 readonly promptFilePath: string;
135 readonly contextFilePath: string;
136 }) => [
137 "The triage prompt and machine context were written to:",
138 ` ${session.promptFilePath}`,
139 ` ${session.contextFilePath}`,
140 ];
141
142 const agentFlag = Flag.Literals("agent", ["claude", "codex", "antigravity"]).pipe(
143 Flag.withDescription("Agent CLI to use. Default: ask when multiple are installed."),
144 Flag.optional,
145 );
146
147 const modelFlag = Flag.String("model").pipe(
148 Flag.withDescription("Model passed through to the agent CLI. Default: the agent's default."),
149 Flag.optional,
150 );
151
152 export const triageCommand = Command.make("triage", {
153 baseDir: baseDirFlag,
154 agent: agentFlag,
155 model: modelFlag,
156 }).pipe(
157 Command.withDescription(
158 "Investigate a T3 Code problem on this machine with Claude Code, Codex, or Antigravity, and help file a good issue.",
159 ),
160 Command.withHandler((flags) =>
161 Effect.gen(function* () {
162 // Triage is a user-facing feature: always the userdata state, never dev.
163 const explicitBaseDir = Option.getOrUndefined(flags.baseDir);
164 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
165 const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome));
166 const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {});
167
168 const session = yield* writeTriageSession({
169 baseDir,
170 paths,
171 entry: {
172 kind: "cli",
173 cliVersion: packageJson.version,
174 launchedAs: yield* resolveCliCommand("triage"),
175 },
176 server: yield* describeServerProcess(paths.serverRuntimeStatePath),
177 });
178
179 const installed: Array<TriageAgent> = [];
180 for (const agent of TRIAGE_AGENTS) {
181 if (yield* isCommandAvailable(agent.command)) {
182 installed.push(agent);
183 }
184 }
185
186 const requested = Option.getOrUndefined(flags.agent);
187 let selected: TriageAgent | undefined;
188 if (requested !== undefined) {
189 selected = installed.find((agent) => agent.id === requested);
190 if (selected === undefined) {
191 return yield* new TriageAgentUnavailableError({
192 agent: TRIAGE_AGENTS.find((agent) => agent.id === requested)?.command ?? requested,
193 });
194 }
195 } else if (installed.length === 1) {
196 selected = installed[0];
197 } else if (installed.length > 1) {
198 // The picker needs terminal output too, or its invisible prompt hangs.
199 if (!process.stdin.isTTY || !process.stdout.isTTY) {
200 return yield* new TriageAgentChoiceRequiredError();
201 }
202 selected = yield* pickAgent(installed);
203 }
204
205 // Windows .cmd shims cannot carry multiline argv; the prompt file also serves as the paste fallback.
206 const { sessionDir, promptFilePath } = session;
207
208 if (selected === undefined) {
209 yield* Console.log(
210 [
211 "No supported agent CLI (claude, codex, agy) was found on this machine.",
212 "",
213 ...describeTriageFiles(session),
214 "",
215 "Paste the prompt file into any coding agent to run triage by hand.",
216 ].join("\n"),
217 );
218 return;
219 }
220
221 const model = Option.getOrUndefined(flags.model);
222 const launchPrompt = buildTriageLaunchPrompt(promptFilePath);
223 const spawnSpec = yield* resolveSpawnCommand(selected.command, [
224 ...(model === undefined ? [] : ["--model", model]),
225 ...(selected.promptArgs ?? []),
226 launchPrompt,
227 ]);
228 yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);
229 const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: sessionDir });
230 if (exitCode !== 0) {
231 process.exitCode = exitCode;
232 yield* Console.log(
233 [
234 "",
235 `${selected.label} exited with code ${String(exitCode)}.`,
236 "",
237 `${selected.label} keeps its state in ${resolveAgentStateDir(selected)}.`,
238 `If that drive is out of space, free some up or set ${selected.stateDirEnv} to a folder on another drive.`,
239 "",
240 ...describeTriageFiles(session),
241 "",
242 `To retry, start \`${selected.command}\` yourself with any flags it suggested, or use any coding agent, and give it this prompt:`,
243 launchPrompt,
244 ].join("\n"),
245 );
246 }
247 }),
248 ),
249 );