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

main
ts 238 lines 9.53 KB
Raw
1 import type { EDITORS } from "@t3tools/contracts";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Option from "effect/Option";
5 import * as Path from "effect/Path";
6 import * as Stream from "effect/Stream";
7 import { ChildProcess, ChildProcessSpawner } from "effect/process";
8
9 import * as HostProcess from "./HostProcess.ts";
10 import { isCommandAvailable, resolveCommandPath, resolveCommandPaths } from "./shell.ts";
11
12 type Editor = (typeof EDITORS)[number];
13
14 // The nearest Zed folder identifies the channel, even below a user named zedpreview.
15 const isPrereleaseZedPath = (filePath: string) => {
16 const install = filePath
17 .split(/[\\/]/)
18 .slice(0, -1)
19 .findLast((folder) => folder.toLowerCase().includes("zed"))
20 ?.toLowerCase();
21 return install !== undefined && (install.includes("nightly") || install.includes("preview"));
22 };
23
24 const installNames: Partial<Record<Editor["id"], ReadonlyArray<string>>> = {
25 vscode: ["Visual Studio Code"],
26 "vscode-insiders": ["Visual Studio Code - Insiders"],
27 // `Antigravity.app` is the separate Hub, not the IDE.
28 antigravity: ["Antigravity IDE"],
29 idea: ["IntelliJ IDEA", "IntelliJ IDEA CE", "IntelliJ IDEA Ultimate"],
30 pycharm: ["PyCharm", "PyCharm CE"],
31 rider: ["Rider", "JetBrains Rider"],
32 };
33
34 // Prefix-only matches could select Insiders when resolving stable VS Code.
35 const isVersionedBundle = (entry: string, name: string) => {
36 if (!entry.startsWith(`${name} `) || !entry.endsWith(".app")) return false;
37 return /^\d[\d.]*$/.test(entry.slice(name.length + 1, -".app".length));
38 };
39
40 // OpenZFS's event daemon is also named zed; it rejects `--version` instead of starting.
41 const isZedEditor = Effect.fn("editor.isZedEditor")(
42 function* (command: string) {
43 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
44 const handle = yield* spawner.spawn(
45 ChildProcess.make(command, ["--version"], {
46 stdin: "ignore",
47 stderr: "ignore",
48 forceKillAfter: "1 second",
49 }),
50 );
51 const [stdout, exitCode] = yield* Effect.all(
52 [handle.stdout.pipe(Stream.decodeText(), Stream.runHead), handle.exitCode],
53 { concurrency: "unbounded" },
54 );
55 return exitCode === 0 && Option.getOrElse(stdout, () => "").startsWith("Zed");
56 },
57 Effect.scoped,
58 Effect.timeout("2 seconds"),
59 Effect.catchCause(() => Effect.succeed(false)),
60 );
61
62 export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(function* (
63 editor: Editor,
64 env: NodeJS.ProcessEnv,
65 ) {
66 if (editor.commands === null) return Option.none();
67 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
68 const platform = yield* HostProcess.Platform;
69 // Prefer Zed's macOS bundle because OpenZFS also installs a zed executable.
70 const preferBundle = platform === "darwin" && editor.id === "zed";
71 const preferZeditor = platform === "linux" && editor.id === "zed";
72 if (platform === "win32" && editor.id === "zed") {
73 const isStable = (resolved: string) => !isPrereleaseZedPath(resolved);
74 let firstCommand: string | undefined;
75 for (const command of editor.commands) {
76 const matches = yield* resolveCommandPaths(command, { env, until: isStable });
77 const stable = matches.find(isStable);
78 // Bypass PATH only when stable is behind a prerelease install.
79 if (stable !== undefined) {
80 const isFirst = firstCommand === undefined && stable === matches[0];
81 return Option.some({ command: isFirst ? command : stable, baseArgs });
82 }
83 if (firstCommand === undefined && matches.length > 0) firstCommand = command;
84 }
85 if (firstCommand !== undefined) return Option.some({ command: firstCommand, baseArgs });
86 } else if (!preferBundle && !preferZeditor) {
87 for (const command of editor.commands) {
88 if (yield* isCommandAvailable(command, { env })) return Option.some({ command, baseArgs });
89 }
90 }
91
92 const path = yield* Path.Path;
93 const fs = yield* FileSystem.FileSystem;
94 const home = env.HOME;
95 const names = installNames[editor.id] ?? [editor.label];
96 const command = editor.commands[0];
97 const jetbrains = editor.launchStyle === "line-column";
98 const candidates: string[] = [];
99 let toolbox: { dir: string; suffix: string } | undefined;
100
101 if (platform === "darwin") {
102 const roots = [...(home ? [path.join(home, "Applications")] : []), "/Applications"];
103 for (const root of roots) {
104 // JetBrains Toolbox appends versions to bundle names; accept exact and versioned names.
105 const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
106 const bundles = new Set(names.map((name) => `${name}.app`));
107 for (const entry of entries) {
108 if (names.some((name) => entry === `${name}.app` || isVersionedBundle(entry, name))) {
109 bundles.add(entry);
110 }
111 }
112 for (const bundle of bundles) {
113 const contents = path.join(root, bundle, "Contents");
114 candidates.push(
115 ...(jetbrains || editor.id === "zed"
116 ? [path.join(contents, "MacOS", editor.id === "zed" ? "cli" : command)]
117 : [
118 path.join(contents, "Resources/app/bin", command),
119 path.join(contents, "Resources/app/bin/code"),
120 ]),
121 );
122 }
123 }
124 if (home && jetbrains) {
125 toolbox = {
126 dir: path.join(home, "Library/Application Support/JetBrains/Toolbox/scripts"),
127 suffix: "",
128 };
129 candidates.push(path.join(toolbox.dir, command));
130 }
131 } else if (platform === "win32") {
132 const roots = [
133 ...(env.LOCALAPPDATA ? [path.join(env.LOCALAPPDATA, "Programs")] : []),
134 ...[env.ProgramFiles, env["ProgramFiles(x86)"], env.ProgramW6432].filter(
135 (root): root is string => !!root,
136 ),
137 ];
138 if (jetbrains) {
139 if (env.LOCALAPPDATA) {
140 toolbox = { dir: path.join(env.LOCALAPPDATA, "JetBrains/Toolbox/scripts"), suffix: ".cmd" };
141 candidates.push(path.join(toolbox.dir, `${command}.cmd`));
142 }
143 for (const directory of roots.flatMap((root) => [root, path.join(root, "JetBrains")])) {
144 const entries = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
145 for (const entry of entries) {
146 if (names.some((name) => entry === name || entry.startsWith(`${name} `))) {
147 candidates.push(path.join(directory, entry, "bin", `${command}64.exe`));
148 candidates.push(path.join(directory, entry, "bin", `${command}.exe`));
149 }
150 }
151 }
152 } else {
153 const name =
154 editor.id === "vscode"
155 ? "Microsoft VS Code"
156 : editor.id === "vscode-insiders"
157 ? "Microsoft VS Code Insiders"
158 : editor.label;
159 for (const root of roots) {
160 candidates.push(
161 path.join(root, name, "resources/app/bin", `${command}.cmd`),
162 path.join(root, name, "resources/app/bin/code.cmd"),
163 path.join(root, name, "bin", `${command}.cmd`),
164 path.join(root, name, "bin/code.cmd"),
165 );
166 if (editor.id === "zed") {
167 candidates.push(
168 path.join(root, name, "bin", "zed.exe"),
169 path.join(root, name, "zed.exe"),
170 );
171 }
172 }
173 }
174 } else if (platform === "linux") {
175 const dirs = [
176 ...(home ? [path.join(home, ".local/bin")] : []),
177 "/usr/local/bin",
178 "/usr/bin",
179 "/snap/bin",
180 ];
181 const dataHome = env.XDG_DATA_HOME || (home ? path.join(home, ".local/share") : undefined);
182 if (jetbrains && dataHome) {
183 toolbox = { dir: path.join(dataHome, "JetBrains/Toolbox/scripts"), suffix: "" };
184 dirs.push(toolbox.dir);
185 }
186 if (preferZeditor) {
187 // Linux packages use zeditor because OpenZFS owns the zed command.
188 for (const name of ["zeditor", "zed"]) {
189 candidates.push(name, ...dirs.map((dir) => path.join(dir, name)));
190 }
191 } else {
192 for (const dir of dirs) {
193 for (const name of editor.commands) candidates.push(path.join(dir, name));
194 }
195 }
196 }
197
198 if (preferBundle) candidates.push(...editor.commands);
199 if (toolbox) {
200 // Toolbox names a launch script `idea1`, `idea2`, ... while `idea` is taken, and keeps that
201 // name after the other install is removed. Try these only after every canonical candidate.
202 const { dir, suffix } = toolbox;
203 const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []));
204 candidates.push(
205 ...entries
206 .filter(
207 (entry) =>
208 entry.startsWith(command) &&
209 entry.endsWith(suffix) &&
210 /^\d+$/.test(entry.slice(command.length, entry.length - suffix.length)),
211 )
212 .sort((a, b) => a.length - b.length || a.localeCompare(b))
213 .map((entry) => path.join(dir, entry)),
214 );
215 }
216 const probeZed = editor.id === "zed" && platform !== "win32";
217 const rejected = new Set<string>();
218 for (const candidate of candidates) {
219 // OpenZFS zed can shadow the editor's zed in an earlier PATH entry.
220 const matches =
221 probeZed && candidate === "zed"
222 ? yield* resolveCommandPaths(candidate, { env, until: () => false })
223 : [yield* resolveCommandPath(candidate, { env })];
224 for (const resolved of matches) {
225 if (resolved === null || rejected.has(resolved)) continue;
226 if (probeZed && path.basename(candidate) === "zed" && !(yield* isZedEditor(resolved))) {
227 rejected.add(resolved);
228 continue;
229 }
230 return Option.some({
231 command: resolved === matches[0] ? candidate : resolved,
232 baseArgs:
233 editor.id === "kiro" && (platform === "darwin" || platform === "win32") ? [] : baseArgs,
234 });
235 }
236 }
237 return Option.none();
238 });