Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

os-jank.ts

308 lines11.4 KB

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