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

os-jank.ts

282 lines10.2 KB

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