@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, 03:37 UTC

main
ts 254 lines 9.21 KB
Raw
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 import {
3 buildEnvironmentCaptureCommand,
4 extractEnvironmentValues,
5 listLoginShellCandidates,
6 mergePathEntries,
7 mergePathValues,
8 readEnvironmentFromLoginShell,
9 readPathFromLaunchctl,
10 resolveWindowsEnvironment,
11 setWindowsPath,
12 WindowsShellEnvironment,
13 } from "@t3tools/shared/shell";
14 import * as Duration from "effect/Duration";
15 import * as Effect from "effect/Effect";
16 import * as FileSystem from "effect/FileSystem";
17 import * as Option from "effect/Option";
18 import * as Path from "effect/Path";
19 import * as Stream from "effect/Stream";
20 import * as ChildProcess from "effect/process/ChildProcess";
21 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
22 // @effect-diagnostics-next-line nodeBuiltinImport:off -- the shared login shell probe runs synchronously through execFileSync.
23 import * as NodeChildProcess from "node:child_process";
24 import * as NodeOS from "node:os";
25
26 function logPathHydrationWarning(message: string, error?: unknown): void {
27 process.stderr.write(
28 `[server] ${message} ${error instanceof Error ? error.message : (error ?? "")}\n`,
29 );
30 }
31
32 // __MISE_DIFF is mise's record of the PATH entries it added. It must travel
33 // with the shell's PATH, or `mise x` can rebuild PATH behind a same-named
34 // wrapper (`exec mise x claude -- claude`) that then re-runs itself forever.
35 const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME"] as const;
36 const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
37 const SLOW_LOGIN_SHELL_TIMEOUT_MS = 20_000;
38
39 function readSlowLoginShellEnvironment(shell: string): Partial<Record<string, string>> {
40 return readEnvironmentFromLoginShell(shell, LOGIN_SHELL_ENV_NAMES, (file, args, options) =>
41 NodeChildProcess.execFileSync(file, args, {
42 ...options,
43 timeout: SLOW_LOGIN_SHELL_TIMEOUT_MS,
44 }),
45 );
46 }
47
48 function applyLoginShellEnvironment(
49 env: NodeJS.ProcessEnv,
50 platform: NodeJS.Platform,
51 shellEnvironment: Partial<Record<string, string>>,
52 fallbackPath?: string,
53 ): void {
54 const shellPath = shellEnvironment.PATH;
55 const mergedPath = mergePathEntries(shellPath ?? fallbackPath, env.PATH, platform);
56 if (mergedPath) {
57 env.PATH = mergedPath;
58 }
59 if (shellPath && shellEnvironment.__MISE_DIFF) {
60 env.__MISE_DIFF = shellEnvironment.__MISE_DIFF;
61 }
62 // Android SDK tools are Java programs. A keg-only JDK (Homebrew's openjdk)
63 // is only reachable through the JAVA_HOME the shell profile sets.
64 if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) {
65 env.JAVA_HOME = shellEnvironment.JAVA_HOME;
66 }
67 }
68
69 function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void {
70 let shellEnvironment: Partial<Record<string, string>> = {};
71 let waitedForSlowShell = false;
72 for (const shell of listLoginShellCandidates(platform, env.SHELL)) {
73 try {
74 shellEnvironment = readEnvironmentFromLoginShell(shell, LOGIN_SHELL_ENV_NAMES);
75 } catch (error) {
76 logPathHydrationWarning(`Failed to read PATH from login shell ${shell}.`, error);
77 // A profile can be slow only while the machine boots. Wait for it once,
78 // here: providers copy this env when they are built, so a later read
79 // would never reach them.
80 if (!waitedForSlowShell && (error as NodeJS.ErrnoException | null)?.code === "ETIMEDOUT") {
81 waitedForSlowShell = true;
82 try {
83 shellEnvironment = readSlowLoginShellEnvironment(shell);
84 } catch (retryError) {
85 logPathHydrationWarning(
86 `Failed to read PATH from slow login shell ${shell}.`,
87 retryError,
88 );
89 }
90 }
91 }
92
93 if (shellEnvironment.PATH) break;
94 }
95
96 const launchctlPath =
97 platform === "darwin" && !shellEnvironment.PATH ? readPathFromLaunchctl() : undefined;
98 applyLoginShellEnvironment(env, platform, shellEnvironment, launchctlPath);
99 }
100
101 export function hydratePosixHome(
102 env: NodeJS.ProcessEnv,
103 resolveHomeDir = () => NodeOS.userInfo().homedir,
104 ): void {
105 if ((env.HOME?.trim() ?? "").length > 0) return;
106
107 const homeDir = resolveHomeDir();
108 if (homeDir.length > 0) {
109 env.HOME = homeDir;
110 }
111 }
112
113 export const fixPath = Effect.fn("fixPath")(function* (options?: {
114 readonly shellEnvironmentPrepared?: boolean | undefined;
115 }): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
116 const platform = yield* HostProcess.Platform;
117 const env = yield* HostProcess.Environment;
118
119 if (platform === "win32") {
120 // Desktop already populated the child env; repeating PowerShell probes costs seconds.
121 if (options?.shellEnvironmentPrepared === true) return;
122 const repairedEnvironment = yield* resolveWindowsEnvironment(env).pipe(
123 Effect.catchDefect((defect) =>
124 Effect.sync(() => {
125 logPathHydrationWarning("Failed to hydrate PATH from the user environment.", defect);
126 return {} as Partial<NodeJS.ProcessEnv>;
127 }),
128 ),
129 );
130 for (const [key, value] of Object.entries(repairedEnvironment)) {
131 if (value === undefined) continue;
132 if (key === "PATH") {
133 setWindowsPath(env, value);
134 } else {
135 env[key] = value;
136 }
137 }
138 return;
139 }
140
141 if (platform !== "darwin" && platform !== "linux") return;
142
143 yield* Effect.sync(() => hydratePosixHome(env)).pipe(
144 Effect.catchDefect((defect) =>
145 Effect.sync(() => {
146 logPathHydrationWarning("Failed to hydrate HOME from the user account.", defect);
147 }),
148 ),
149 );
150 if (options?.shellEnvironmentPrepared === true) return;
151 yield* Effect.sync(() => hydratePosixPath(env, platform)).pipe(
152 Effect.catchDefect((defect) =>
153 Effect.sync(() => {
154 logPathHydrationWarning("Failed to hydrate PATH from the user environment.", defect);
155 }),
156 ),
157 );
158 });
159
160 const readLoginShellOutput = Effect.fn("readLoginShellOutput")(
161 function* (shell: string) {
162 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
163 const child = yield* spawner.spawn(
164 ChildProcess.make(
165 shell,
166 ["-ilc", buildEnvironmentCaptureCommand(shell, LOGIN_SHELL_ENV_NAMES)],
167 {
168 stdin: "ignore",
169 stdout: "pipe",
170 stderr: "ignore",
171 // A profile that traps SIGTERM would otherwise hold the scope open
172 // past the timeout while cleanup waits for the exit.
173 forceKillAfter: "1 second",
174 },
175 ),
176 );
177 const [stdout, exitCode] = yield* Effect.all(
178 [Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode],
179 { concurrency: 2 },
180 );
181 if (exitCode === 0) return stdout;
182 yield* Effect.logWarning(
183 `Login shell ${shell} exited with code ${exitCode} while reading PATH.`,
184 );
185 return "";
186 },
187 Effect.scoped,
188 Effect.timeoutOption(LOGIN_SHELL_TIMEOUT),
189 );
190
191 // Runs even when the desktop prepared the environment: that capture was taken
192 // once at launch. Only the user's own shell counts; a fallback shell's PATH is
193 // not their environment. Failure leaves PATH alone.
194 export const refreshPathFromLoginShell = Effect.fn("refreshPathFromLoginShell")(function* () {
195 const platform = yield* HostProcess.Platform;
196 if (platform !== "darwin" && platform !== "linux") return;
197 const env = yield* HostProcess.Environment;
198 const [shell] = listLoginShellCandidates(platform, env.SHELL);
199 if (!shell) return;
200
201 const output = yield* readLoginShellOutput(shell).pipe(
202 Effect.catchCause((cause) =>
203 Effect.logWarning(`Failed to read PATH from login shell ${shell}.`, cause).pipe(
204 Effect.as(Option.some("")),
205 ),
206 ),
207 );
208 if (Option.isNone(output)) {
209 yield* Effect.logWarning(
210 `Timed out reading PATH from login shell ${shell} after ${Duration.format(LOGIN_SHELL_TIMEOUT)}; PATH is unchanged.`,
211 );
212 return;
213 }
214 const shellEnvironment = extractEnvironmentValues(output.value, LOGIN_SHELL_ENV_NAMES);
215 if (shellEnvironment.PATH) {
216 applyLoginShellEnvironment(env, platform, shellEnvironment);
217 } else {
218 yield* Effect.logWarning(`Login shell ${shell} printed no PATH; PATH is unchanged.`);
219 }
220 });
221
222 // Installers write PATH to the registry, which the server's launch-time PATH never sees again.
223 // Returns whether PATH gained a directory.
224 export const refreshWindowsPath = Effect.fn("refreshWindowsPath")(function* () {
225 if ((yield* HostProcess.Platform) !== "win32") return false;
226 const env = yield* HostProcess.Environment;
227 const readEnvironment = yield* WindowsShellEnvironment;
228 const { PATH: registryPath } = yield* readEnvironment(["PATH"], { loadProfile: false });
229 const currentPath = env.PATH ?? env.Path ?? env.path;
230 const mergedPath = mergePathValues(currentPath, registryPath, "win32");
231 if (!mergedPath || mergedPath === currentPath) return false;
232 setWindowsPath(env, mergedPath);
233 return true;
234 });
235
236 export const expandHomePath = Effect.fn(function* (input: string) {
237 const { join } = yield* Path.Path;
238 const home = yield* HostProcess.HomeDirectory;
239 if (input === "~") {
240 return home;
241 }
242 if (input.startsWith("~/") || input.startsWith("~\\")) {
243 return join(home, input.slice(2));
244 }
245 return input;
246 });
247
248 export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
249 const { join, resolve } = yield* Path.Path;
250 if (!raw || raw.trim().length === 0) {
251 return join(yield* HostProcess.HomeDirectory, ".t3");
252 }
253 return resolve(yield* expandHomePath(raw.trim()));
254 });