@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 373 lines 15.2 KB
Raw
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 import { pathSetupCommand, resolveCommandPath } from "@t3tools/shared/shell";
3 import * as Console from "effect/Console";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Option from "effect/Option";
8 import * as Path from "effect/Path";
9 import * as Schema from "effect/Schema";
10 import { Command, Prompt } from "effect/cli";
11 import * as ChildProcess from "effect/process/ChildProcess";
12 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13
14 import packageJson from "../../package.json" with { type: "json" };
15 import {
16 generatedWindowsShimTarget,
17 isVersionExecutable,
18 readPosixLauncherTarget,
19 recordPinnedRuntimeLauncher,
20 writePosixLauncher,
21 } from "../cloud/pinnedRuntime.ts";
22 import { detectCliRunner, resolveCliCommand, resolveEntryPath } from "./invocation.ts";
23
24 export class CliInstallError extends Schema.TaggedError<CliInstallError>()("CliInstallError", {
25 reason: Schema.String,
26 cause: Schema.optional(Schema.Defect()),
27 }) {
28 override get message(): string {
29 return this.reason;
30 }
31 }
32
33 /** `<T3 home>/runtime/versions/<version>/t3`: the layout the install scripts and npm launcher share. */
34 const standaloneRuntime = Effect.gen(function* () {
35 const path = yield* Path.Path;
36 if (!(yield* HostProcess.IsExecutable)) return Option.none();
37 const executable = yield* HostProcess.ExecutablePath;
38 const versionsDir = path.dirname(path.dirname(executable));
39 const runtimeDir = path.dirname(versionsDir);
40 if (path.basename(versionsDir) !== "versions" || path.basename(runtimeDir) !== "runtime") {
41 return Option.none();
42 }
43 return Option.some({ executable, versionsDir, runtimeDir });
44 });
45
46 /** Installs this runtime as the `t3` command the way the install scripts do, replacing only our own launcher. */
47 export const installCli = Effect.fn("cli.install.install")(function* () {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const platform = yield* HostProcess.Platform;
51 const environment = yield* HostProcess.Environment;
52 const home = yield* HostProcess.HomeDirectory;
53 const runtime = yield* standaloneRuntime;
54 const windows = platform === "win32";
55 if (Option.isNone(runtime)) {
56 const script = windows
57 ? "irm https://t3.codes/install.ps1 | iex"
58 : "curl -fsSL https://t3.codes/install.sh | sh";
59 return yield* new CliInstallError({
60 reason: `Only the standalone t3 can install itself. Use \`${script}\`, or Settings in the desktop app.`,
61 });
62 }
63 const { executable, versionsDir, runtimeDir } = runtime.value;
64 // cmd.exe expands `%` and reads the shim in the OEM code page, so such a path would not run.
65 if (windows && /[%\u0080-\uffff]/.test(executable)) {
66 return yield* new CliInstallError({
67 reason: `A t3.cmd cannot run ${executable}, because the path has % or non-ASCII characters. Keep using npx t3.`,
68 });
69 }
70 // Absolute, so the PATH hint never adds a folder that changes with the working directory.
71 const binDir = path.resolve(
72 environment.T3CODE_INSTALL_BIN_DIR?.trim() || path.join(home, ".local", "bin"),
73 );
74 const name = windows ? "t3.cmd" : "t3";
75 const link = path.join(binDir, name);
76 const failed = (reason: string) => (cause: unknown) => new CliInstallError({ reason, cause });
77
78 // Resolve fully so a link through a symlinked T3 home still counts as ours; a dangling one
79 // (a pruned version) falls back to its own text.
80 const realVersionsDir = yield* fs
81 .realPath(versionsDir)
82 .pipe(Effect.orElseSucceed(() => versionsDir));
83 const current = windows
84 ? yield* fs.readFileString(link).pipe(Effect.map(generatedWindowsShimTarget), Effect.option)
85 : yield* fs.readLink(link).pipe(
86 Effect.flatMap((target) =>
87 fs.realPath(link).pipe(Effect.orElseSucceed(() => path.resolve(binDir, target))),
88 ),
89 // Not a link: the script this command and the install scripts write.
90 Effect.catch(() => readPosixLauncherTarget(link)),
91 Effect.option,
92 Effect.map(Option.filter((target) => target !== undefined)),
93 );
94 // A dangling symlink is occupied too: writing the shim would follow it.
95 const occupied =
96 Option.isSome(current) ||
97 (yield* fs.exists(link)) ||
98 Option.isSome(yield* fs.readLink(link).pipe(Effect.option));
99 if (
100 occupied &&
101 !(
102 Option.isSome(current) &&
103 current.value !== undefined &&
104 (isVersionExecutable(path, versionsDir, current.value) ||
105 isVersionExecutable(path, realVersionsDir, current.value) ||
106 // This home's desktop launcher, which install.sh also replaces.
107 current.value === path.join(path.dirname(runtimeDir), "bin", name))
108 )
109 ) {
110 return yield* new CliInstallError({
111 reason: `Another t3 is already at ${link}. Remove it, then run this again.`,
112 });
113 }
114
115 yield* fs
116 .makeDirectory(binDir, { recursive: true })
117 .pipe(Effect.mapError(failed(`Could not create ${binDir}.`)));
118 // An empty spot is created exclusively, so a file that appears after the check above is kept.
119 if (windows) {
120 yield* fs
121 .writeFileString(link, `@echo off\r\n"${executable}" %*`, occupied ? {} : { flag: "wx" })
122 .pipe(Effect.mapError(failed(`Could not write ${link}.`)));
123 } else {
124 yield* writePosixLauncher({ launcher: link, executable, exclusive: !occupied }).pipe(
125 Effect.mapError(failed(`Could not write ${link}.`)),
126 );
127 }
128
129 // Pruning keeps what recorded launchers point at; a background service cannot see binDir otherwise.
130 const recorded = path.join(
131 yield* fs.realPath(binDir).pipe(Effect.orElseSucceed(() => binDir)),
132 name,
133 );
134 yield* recordPinnedRuntimeLauncher({
135 baseDir: path.dirname(runtimeDir),
136 launcher: recorded,
137 }).pipe(
138 Effect.catch(() =>
139 Console.error(
140 `Warning: could not record ${recorded} in ${path.join(runtimeDir, "launchers")}. Cleanup may remove the version it runs.`,
141 ),
142 ),
143 );
144
145 // resolve() drops trailing separators, so `~/.local/bin/` on PATH still matches.
146 const normalize = (value: string) =>
147 windows ? path.resolve(value).toLowerCase() : path.resolve(value);
148 const same = (entry: string) => entry !== "" && normalize(entry) === normalize(binDir);
149 const entries = (environment.PATH ?? environment.Path ?? "").split(windows ? ";" : ":");
150 const onPath = entries.some(same);
151 // A t3 earlier on PATH runs instead, and an added folder goes last. Runner caches (npx's own
152 // .bin) are not installs.
153 const firstOther = Effect.gen(function* () {
154 for (const entry of entries) {
155 if (same(entry)) return undefined;
156 if (!path.isAbsolute(entry) || detectCliRunner(`${entry}/`) !== null) continue;
157 for (const name of windows ? ["t3.cmd", "t3.exe"] : ["t3"]) {
158 const candidate = path.join(entry, name);
159 if (yield* resolveCommandPath(candidate, { env: environment })) return candidate;
160 }
161 }
162 return undefined;
163 });
164 const shadowedBy = yield* firstOther;
165 return {
166 link,
167 onPath: onPath && shadowedBy === undefined,
168 shadowedBy,
169 pathCommand:
170 onPath || shadowedBy !== undefined
171 ? undefined
172 : windows
173 ? // PowerShell; it covers this window only, since changing the saved PATH would flatten
174 // its %VAR% entries. A `;` would split the folder.
175 binDir.includes(";")
176 ? undefined
177 : `$env:Path += ';${binDir.replaceAll("'", "''")}'`
178 : pathSetupCommand({
179 directory: binDir,
180 home,
181 shell: environment.SHELL,
182 platform,
183 configHome: environment.XDG_CONFIG_HOME,
184 zdotdir: environment.ZDOTDIR,
185 }),
186 binDir,
187 };
188 });
189
190 const reportInstalled = Effect.fn("cli.install.report")(function* (
191 installed: Effect.Success<ReturnType<typeof installCli>>,
192 ) {
193 yield* Console.log(`Installed t3 ${packageJson.version} at ${installed.link}.`);
194 if (installed.shadowedBy !== undefined) {
195 return yield* Console.log(
196 `Another t3 at ${installed.shadowedBy} runs first, so run ${installed.link} to use this one.`,
197 );
198 }
199 if (installed.onPath) return yield* Console.log("Run `t3` to get started.");
200 if (installed.pathCommand === undefined) {
201 return yield* Console.log(`Add ${installed.binDir} to your PATH, then run \`t3\`.`);
202 }
203 if ((yield* HostProcess.Platform) === "win32") {
204 yield* Console.log(
205 `${installed.binDir} is not on your PATH yet. In this PowerShell window, run:`,
206 );
207 yield* Console.log(` ${installed.pathCommand}`);
208 return yield* Console.log("Then run `t3`. For new windows, add the folder to your PATH.");
209 }
210 yield* Console.log(`${installed.binDir} is not on your PATH yet. Add it with:`);
211 yield* Console.log(` ${installed.pathCommand}`);
212 yield* Console.log("Then open a new terminal and run `t3`.");
213 });
214
215 export const installCommand = Command.make("install").pipe(
216 Command.withDescription("Install this version as the `t3` command."),
217 Command.withHandler(() => installCli().pipe(Effect.flatMap(reportInstalled))),
218 );
219
220 /** Saying no lasts until the next minor release: `0.2` covers `0.2.5` and `0.2.6-nightly.…`. */
221 const minorRelease = (version: string) => version.split(".").slice(0, 2).join(".");
222
223 const SKIPPED_ARGUMENTS = new Set([
224 "help",
225 "--help",
226 "-h",
227 "--version",
228 "-v",
229 "--completions",
230 // Scripts and machine-readable output; a prompt would stall them or corrupt their output.
231 "--json",
232 "--yes",
233 "-y",
234 ]);
235
236 /** The subcommand, past global flags that may come first (two take a value). */
237 const topLevelCommand = (args: ReadonlyArray<string>) => {
238 for (let index = 0; index < args.length; index++) {
239 const arg = args[index]!;
240 if (arg === "--log-level" || arg === "--completions") index++;
241 else if (!arg.startsWith("-")) return arg;
242 }
243 return undefined;
244 };
245
246 /** Agents can run commands in a terminal that nobody answers; no answer counts as no. */
247 const PROMPT_TIMEOUT = Duration.seconds(30);
248
249 /** `/proc/<pid>/stat` fields after the parenthesized command name: state ppid pgrp session tty_nr tpgid. */
250 export const isForegroundProcStat = (stat: string) => {
251 const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
252 return fields[2] !== undefined && fields[2] !== "" && fields[2] === fields[5];
253 };
254
255 /** Output of `ps -o tpgid=,pgid=`; tpgid is -1 without a controlling terminal. */
256 export const isForegroundPs = (output: string) => {
257 const [tpgid, pgid] = output.trim().split(/\s+/);
258 return tpgid !== undefined && tpgid !== "" && tpgid === pgid;
259 };
260
261 /**
262 * A background job (`npx t3 serve &`) that reads the terminal is stopped by the shell, so only
263 * the terminal's foreground process group may prompt. Unknown counts as background.
264 */
265 export const inTerminalForeground = Effect.gen(function* () {
266 const fs = yield* FileSystem.FileSystem;
267 const platform = yield* HostProcess.Platform;
268 if (platform === "win32") return true;
269 if (platform === "linux") {
270 return isForegroundProcStat(
271 yield* fs.readFileString("/proc/self/stat").pipe(Effect.orElseSucceed(() => "")),
272 );
273 }
274 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
275 return isForegroundPs(
276 yield* spawner
277 .string(
278 // Absolute: under npx, PATH starts with a project's node_modules/.bin.
279 ChildProcess.make("/bin/ps", ["-o", "tpgid=,pgid=", "-p", String(process.pid)], {
280 stdin: "ignore",
281 stderr: "ignore",
282 }),
283 )
284 .pipe(Effect.orElseSucceed(() => "")),
285 );
286 });
287
288 /**
289 * Before a command run through npx, pnpm dlx, or bunx at a terminal, asks to install the `t3`
290 * command. Yes is the default. No, no answer, or a failed install is saved in the T3 home until
291 * the next minor release. Returns false when the user quits the prompt, so the command does not run.
292 */
293 export const offerCliInstall = Effect.fn("cli.install.offer")(function* <E, R, E2, R2>(input: {
294 readonly args: ReadonlyArray<string>;
295 readonly interactive: boolean;
296 readonly foreground: Effect.Effect<boolean, E2, R2>;
297 /** Undefined when the user quits the prompt. */
298 readonly confirm: Effect.Effect<boolean | void, E, R>;
299 }) {
300 const fs = yield* FileSystem.FileSystem;
301 const path = yield* Path.Path;
302 const platform = yield* HostProcess.Platform;
303 const environment = yield* HostProcess.Environment;
304 if (!input.interactive || environment.CI || environment.SUDO_USER) return true;
305 if (environment.TERM === "dumb") return true;
306 // `npx --yes` asks for no prompts; npm passes it on to the command as npm_config_yes.
307 if (environment.npm_config_yes === "true") return true;
308 // `--json=true` and `-y=true` are the same flags.
309 if (input.args.some((arg) => SKIPPED_ARGUMENTS.has(arg.split("=")[0]!))) return true;
310 const command = topLevelCommand(input.args);
311 if (command === "install" || command === "uninstall") return true;
312 if (detectCliRunner(yield* resolveEntryPath) === null) return true;
313 const runtime = yield* standaloneRuntime;
314 if (Option.isNone(runtime)) return true;
315 const { runtimeDir } = runtime.value;
316
317 // Any t3 already installed means no prompt: ours (even when off PATH) or another on PATH.
318 // Runners put their own cache's node_modules/.bin on PATH, so skip those.
319 const windows = platform === "win32";
320 const names = windows ? ["t3.cmd", "t3.exe"] : ["t3"];
321 const launchers = yield* fs
322 .readFileString(path.join(runtimeDir, "launchers"))
323 .pipe(Effect.orElseSucceed(() => ""));
324 const candidates = [
325 ...launchers.split(/\r?\n/).filter(Boolean),
326 path.join(path.dirname(runtimeDir), "bin", windows ? "t3.cmd" : "t3"),
327 ...(environment.PATH ?? environment.Path ?? "")
328 .split(windows ? ";" : ":")
329 .filter(
330 (directory) => path.isAbsolute(directory) && detectCliRunner(`${directory}/`) === null,
331 )
332 .flatMap((directory) => names.map((name) => path.join(directory, name))),
333 ];
334 for (const candidate of candidates) {
335 if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) return true;
336 }
337
338 const declinedFile = path.join(runtimeDir, "install-prompt-declined");
339 const declined = yield* fs.readFileString(declinedFile).pipe(Effect.orElseSucceed(() => ""));
340 const minor = minorRelease(packageJson.version);
341 if (declined.trim() === minor) return true;
342 if (!(yield* input.foreground)) return true;
343
344 const installHint = `Run \`${yield* resolveCliCommand("install")}\` any time.`;
345 const saveDecline = fs.writeFileString(declinedFile, `${minor}\n`).pipe(Effect.ignore);
346 const answer = yield* input.confirm.pipe(Effect.timeoutOption(PROMPT_TIMEOUT));
347 if (Option.isNone(answer)) {
348 yield* saveDecline;
349 yield* Console.log(`\nNo answer, so t3 was not installed. ${installHint}\n`);
350 return true;
351 }
352 if (answer.value === undefined) return false;
353 if (!answer.value) {
354 yield* saveDecline;
355 yield* Console.log(`Skipped. ${installHint}\n`);
356 return true;
357 }
358 yield* installCli().pipe(
359 Effect.flatMap(reportInstalled),
360 Effect.catch((error) =>
361 Effect.andThen(saveDecline, Console.error(`Could not install t3: ${error.message}`)),
362 ),
363 );
364 yield* Console.log("");
365 return true;
366 });
367
368 export const confirmCliInstall = Prompt.run(
369 Prompt.Confirm({
370 message: "Install the t3 command? Then you can run `t3` directly.",
371 initial: true,
372 }),
373 ).pipe(Effect.catchTags({ QuitError: () => Effect.void }));