@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 178 lines 7.37 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - execvp's X_OK test has no Effect FileSystem equivalent.
2 import * as NodeFS from "node:fs";
3 import * as NodeFSP from "node:fs/promises";
4
5 import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline";
6 import * as HostProcess from "@t3tools/shared/HostProcess";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
9 import * as Path from "effect/Path";
10 import * as PlatformError from "effect/PlatformError";
11 import * as Redacted from "effect/Redacted";
12 import * as ChildProcess from "effect/process/ChildProcess";
13 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14 import * as CommandLine from "effect/process/CommandLine";
15
16 // libuv's _PATH_DEFPATH, searched when the child environment has no PATH.
17 const DEFAULT_PATH = "/usr/bin:/bin";
18
19 // A check on a hung mount holds a libuv threadpool thread until the mount answers, and the
20 // pool's four threads also compress every WebSocket frame. Checks therefore run one at a time
21 // per directory and two at a time overall; the rest wait without holding a thread.
22 const CHECK_LIMIT = 2;
23 const directoryTails = new Map<string, Promise<unknown>>();
24 const waiting: Array<() => void> = [];
25 let running = 0;
26
27 const access = async (path: string, mode: number) => {
28 if (running < CHECK_LIMIT) running++;
29 else await new Promise<void>((resume) => waiting.push(resume));
30 try {
31 await NodeFSP.access(path, mode);
32 return undefined;
33 } catch (error) {
34 return error as NodeJS.ErrnoException;
35 } finally {
36 // A waiter takes over the slot.
37 const next = waiting.shift();
38 if (next === undefined) running--;
39 else next();
40 }
41 };
42
43 /** The errno error of `access(path, mode)`, or undefined when it passes. */
44 const check = (directory: string, path: string, mode: number) => {
45 const result = (directoryTails.get(directory) ?? Promise.resolve()).then(() =>
46 access(path, mode),
47 );
48 directoryTails.set(directory, result);
49 void result.then(() => {
50 if (directoryTails.get(directory) === result) directoryTails.delete(directory);
51 });
52 return Effect.promise(() => result);
53 };
54
55 // The PATH the child searches, from the environment Effect's Node spawner gives it.
56 const childPath = ({ env, extendEnv }: ChildProcess.CommandOptions) => {
57 if (env === undefined) return process.env.PATH;
58 if (!Object.hasOwn(env, "PATH")) return extendEnv === true ? process.env.PATH : undefined;
59 const value = env.PATH;
60 return value === undefined || !Redacted.isRedacted(value) ? value : Redacted.value(value);
61 };
62
63 // The spawn error Effect's Node spawner reports when execvp fails with `code`.
64 const spawnFailure = (command: ChildProcess.StandardCommand, code: "ENOENT" | "EACCES") => {
65 const syscall = `spawn ${command.command}`;
66 return PlatformError.systemError({
67 _tag: code === "ENOENT" ? "NotFound" : "PermissionDenied",
68 module: "ChildProcess",
69 method: "spawn",
70 pathOrDescriptor: CommandLine.display([command.command, ...command.args], { format: "posix" }),
71 syscall,
72 cause: Object.assign(new Error(`${syscall} ${code}`), {
73 errno: code === "ENOENT" ? -2 : -13,
74 code,
75 syscall,
76 path: command.command,
77 spawnargs: command.args.map((arg) => (Redacted.isRedacted(arg) ? "<redacted>" : arg)),
78 }),
79 });
80 };
81
82 // The error of the `FileSystem.access(cwd)` Effect's Node spawner runs before it spawns.
83 const cwdFailure = (cwd: string, cause: NodeJS.ErrnoException) =>
84 PlatformError.systemError({
85 _tag:
86 cause.code === "ENOENT"
87 ? "NotFound"
88 : cause.code === "EACCES" || cause.code === "EPERM"
89 ? "PermissionDenied"
90 : cause.code === "ENOTDIR" || cause.code === "ELOOP"
91 ? "BadResource"
92 : "Unknown",
93 module: "FileSystem",
94 method: "access",
95 pathOrDescriptor: cwd,
96 syscall: cause.syscall,
97 cause,
98 });
99
100 /**
101 * Fails as a native spawn does when the command is missing or not executable: callers read
102 * that error to tell a CLI that is not installed from one that failed. execvp reports EACCES
103 * when a candidate exists but cannot be run, and ENOENT otherwise.
104 */
105 const findExecutable = Effect.fnUntraced(function* (
106 command: ChildProcess.StandardCommand,
107 cwd: string | undefined,
108 ) {
109 // Joined as text: the kernel resolves `..` after a symlink differently from a normalized path.
110 const fromCwd = (path: string) =>
111 cwd === undefined || path.startsWith("/") ? path : `${cwd}/${path}`;
112 const candidates = command.command.includes("/")
113 ? [fromCwd(command.command)]
114 : (childPath(command.options) ?? DEFAULT_PATH)
115 .split(":")
116 .map((entry) => `${fromCwd(entry || ".")}/${command.command}`);
117 let denied = false;
118 for (const candidate of candidates) {
119 const error = yield* check(
120 candidate.slice(0, candidate.lastIndexOf("/")) || "/",
121 candidate,
122 NodeFS.constants.X_OK,
123 );
124 // Any other errno is left for `env` to report through its exit code.
125 if (error === undefined || (error.code !== "ENOENT" && error.code !== "EACCES")) return;
126 denied ||= error.code === "EACCES";
127 }
128 return yield* spawnFailure(command, denied ? "EACCES" : "ENOENT");
129 });
130
131 const make = Effect.gen(function* () {
132 const native = yield* ChildProcessSpawner.ChildProcessSpawner;
133 if ((yield* HostProcess.Platform) !== "linux") return native;
134 if (!(yield* Effect.promise(supportsEnvChdir))) return native;
135 const path = yield* Path.Path;
136
137 // Runs inside the NonBlockingSpawner.spawn span.
138 const prepareStandard = Effect.fnUntraced(function* (input: ChildProcess.StandardCommand) {
139 const { cwd: givenCwd, shell, ...options } = input.options;
140 // Effect rejects a shell command with arguments, and a NUL, itself.
141 if ((shell && input.args.length > 0) || input.command.includes("\0")) return input;
142 // Node's shell mode on Unix, spelled out so the trampoline can run it.
143 const command = shell
144 ? ChildProcess.make(typeof shell === "string" ? shell : "/bin/sh", ["-c", input.command])
145 : input;
146 // Checked as given and entered resolved, as Effect's Node spawner does.
147 const cwd = givenCwd === undefined ? undefined : path.resolve(givenCwd);
148 const trampoline = envTrampoline(command.command, command.args, cwd);
149 if (trampoline === undefined) return input;
150 if (givenCwd !== undefined && cwd !== undefined) {
151 const error = yield* check(cwd, givenCwd, NodeFS.constants.F_OK);
152 if (error !== undefined) return yield* cwdFailure(givenCwd, error);
153 }
154 yield* findExecutable(ChildProcess.make(command.command, command.args, options), cwd);
155 return ChildProcess.make(trampoline.command, trampoline.args, options);
156 });
157
158 const prepare = (
159 command: ChildProcess.Command,
160 ): Effect.Effect<ChildProcess.Command, PlatformError.PlatformError> =>
161 command._tag === "StandardCommand"
162 ? prepareStandard(command)
163 : Effect.map(Effect.all([prepare(command.left), prepare(command.right)]), ([left, right]) =>
164 ChildProcess.pipeTo(left, right, command.options),
165 );
166
167 return ChildProcessSpawner.make(
168 Effect.fn("NonBlockingSpawner.spawn")(function* (command) {
169 return yield* native.spawn(yield* prepare(command));
170 }),
171 );
172 });
173
174 /**
175 * On Linux with GNU `env`, replaces the provided `ChildProcessSpawner` with one that never
176 * hands libuv a cwd or a PATH search; elsewhere it passes the provided one through.
177 */
178 export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make);