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