The best way to control Claude Code, Codex and more from any computer or phone

main
ts 259 lines 10.5 KB
Raw
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 import * as Console from "effect/Console";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Option from "effect/Option";
6 import * as Path from "effect/Path";
7 import * as Schema from "effect/Schema";
8 import { Command } from "effect/cli";
9 import * as ChildProcess from "effect/process/ChildProcess";
10 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11
12 import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
13 import { resolveBaseDir } from "../os-jank.ts";
14 import { baseDirFlag } from "./config.ts";
15 import { resolveRootCliCommand } from "./invocation.ts";
16
17 export class BrowserSetupStepError extends Schema.TaggedError<BrowserSetupStepError>()(
18 "BrowserSetupStepError",
19 { step: Schema.String, detail: Schema.String },
20 ) {
21 override get message(): string {
22 return `Could not ${this.step}: ${this.detail}`;
23 }
24 }
25
26 const runStep = Effect.fn("browserSetup.runStep")(function* (
27 step: string,
28 command: string,
29 args: ReadonlyArray<string>,
30 ) {
31 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
32 const exitCode = yield* spawner
33 .exitCode(
34 ChildProcess.make(command, args, { stdin: "inherit", stdout: "inherit", stderr: "inherit" }),
35 )
36 .pipe(Effect.mapError((cause) => new BrowserSetupStepError({ step, detail: String(cause) })));
37 if (exitCode !== 0) {
38 return yield* new BrowserSetupStepError({ step, detail: `${command} exited with ${exitCode}` });
39 }
40 });
41
42 /** Under sudo, an unspecified home uses the invoking user's ~/.t3. */
43 const setupBaseDir = Effect.fn("browserSetup.baseDir")(function* (explicit: Option.Option<string>) {
44 const env = yield* HostProcess.Environment;
45 const raw = Option.getOrUndefined(explicit) ?? env.T3CODE_HOME;
46 if (raw !== undefined || env.SUDO_USER === undefined) return yield* resolveBaseDir(raw);
47 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
48 const entry = yield* spawner
49 .string(
50 ChildProcess.make("getent", ["passwd", env.SUDO_USER], { stdin: "ignore", stderr: "ignore" }),
51 )
52 .pipe(Effect.orElseSucceed(() => ""));
53 const home = entry.trim().split(":")[5];
54 const path = yield* Path.Path;
55 return home ? path.join(home, ".t3") : yield* resolveBaseDir(undefined);
56 });
57
58 const aptOffers = Effect.fn("browserSetup.aptOffers")(function* (name: string) {
59 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
60 const policy = yield* spawner
61 .string(ChildProcess.make("apt-cache", ["policy", name], { stdin: "ignore", stderr: "ignore" }))
62 .pipe(Effect.orElseSucceed(() => ""));
63 const candidate = /Candidate:\s*(\S+)/.exec(policy)?.[1];
64 return candidate !== undefined && candidate !== "(none)";
65 });
66
67 const installedBrowser = Effect.fn("browserSetup.installedBrowser")(function* (baseDir: string) {
68 const fs = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const root = path.join(baseDir, "tools", "chrome-headless-shell");
71 for (const platform of yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []))) {
72 for (const version of yield* fs
73 .readDirectory(path.join(root, platform))
74 .pipe(Effect.orElseSucceed(() => []))) {
75 const executable = path.join(root, platform, version, "chrome-headless-shell");
76 if (yield* fs.exists(executable).pipe(Effect.orElseSucceed(() => false))) {
77 return Option.some(executable);
78 }
79 }
80 }
81 return Option.none<string>();
82 });
83
84 /**
85 * Chrome starts without fonts, but pages then render no text. Without
86 * fontconfig there is no `fc-match` at all, which counts as no font.
87 */
88 const fontAvailable = Effect.gen(function* () {
89 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
90 const font = yield* spawner
91 .string(
92 ChildProcess.make("fc-match", ["--format=%{file}", "sans-serif"], {
93 stdin: "ignore",
94 stderr: "ignore",
95 }),
96 )
97 .pipe(
98 Effect.timeout("5 seconds"),
99 Effect.orElseSucceed(() => ""),
100 );
101 return font.trim() !== "";
102 }).pipe(Effect.withSpan("browserSetup.fontAvailable"));
103
104 const FONT_PACKAGES = ["fontconfig", "fonts-liberation"];
105
106 const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe(
107 Command.withDescription(
108 "Set up this Linux host for T3's browser: allow Chrome's sandbox and install its libraries and fonts.",
109 ),
110 Command.withHandler(({ baseDir }) =>
111 Effect.gen(function* () {
112 if ((yield* HostProcess.Platform) !== "linux") {
113 return yield* Console.log("Nothing to set up: T3's browser runs as is on this system.");
114 }
115 const fs = yield* FileSystem.FileSystem;
116 const isRoot = (yield* HostProcess.UserId) === 0;
117 const env = yield* HostProcess.Environment;
118 const baseDirPath = yield* setupBaseDir(baseDir);
119 // sudo resets the environment, so a chosen home has to be on the command line.
120 const setupCommand = yield* resolveRootCliCommand(
121 PreviewBrowserHost.SETUP_SUBCOMMAND,
122 Option.isSome(baseDir) || env.T3CODE_HOME !== undefined ? ["--base-dir", baseDirPath] : [],
123 );
124 // Root, unless sudo came from another user, is likely the server's own account.
125 const rootWarning =
126 isRoot && (env.SUDO_USER ?? "root") === "root" && !PreviewBrowserHost.sandboxDisabled(env)
127 ? new PreviewBrowserHost.PreviewBrowserRootError().message
128 : undefined;
129
130 const restricted = yield* PreviewBrowserHost.usernsRestricted;
131 // The kernel can lack a profile that is on disk, as on a host restored from an image,
132 // and only root can read the loaded list, so root reloads it on every run.
133 const needsProfile = isRoot ? restricted : yield* PreviewBrowserHost.sandboxBlocked;
134 const reloadHint =
135 restricted && !isRoot
136 ? `\nIf the browser still reports a blocked sandbox, the AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} is not loaded. To load it, run:\n\n ${setupCommand}\n`
137 : "";
138 const browser = yield* installedBrowser(baseDirPath);
139 const missing = Option.isSome(browser)
140 ? yield* PreviewBrowserHost.missingLibraries(browser.value)
141 : [];
142 const needsFonts = !(yield* fontAvailable);
143 const hasApt = yield* fs.exists("/usr/bin/apt-get").pipe(Effect.orElseSucceed(() => false));
144
145 if (!needsProfile && missing.length === 0 && !needsFonts) {
146 return yield* Console.log(
147 rootWarning ??
148 (Option.isSome(browser)
149 ? "This host is ready for T3's browser."
150 : "Chrome's sandbox is allowed here. T3's browser installs on first use; if it then reports missing libraries, run this again.") +
151 reloadHint,
152 );
153 }
154
155 if (!isRoot) {
156 if (needsProfile) {
157 yield* Console.log(
158 `This host blocks the sandbox T3's browser runs in. Setup installs an AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows it.`,
159 );
160 }
161 if (missing.length > 0) {
162 yield* Console.log(`T3's browser is missing ${missing.join(", ")}; setup installs them.`);
163 }
164 if (needsFonts) {
165 yield* Console.log(
166 "T3's browser needs fontconfig and system fonts; setup installs them.",
167 );
168 }
169 return yield* Console.log(`\nThis needs root. Run:\n\n ${setupCommand}\n`);
170 }
171
172 if (needsProfile) {
173 // An existing profile may carry an administrator's edits, so it is reloaded as is.
174 const profileOnDisk = yield* fs
175 .exists(PreviewBrowserHost.APPARMOR_PROFILE_PATH)
176 .pipe(Effect.orElseSucceed(() => false));
177 if (!profileOnDisk) {
178 yield* fs
179 .writeFileString(
180 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
181 PreviewBrowserHost.APPARMOR_PROFILE,
182 )
183 .pipe(
184 Effect.mapError(
185 (cause) =>
186 new BrowserSetupStepError({
187 step: `write ${PreviewBrowserHost.APPARMOR_PROFILE_PATH}`,
188 detail: cause.message,
189 }),
190 ),
191 );
192 }
193 yield* runStep("load the AppArmor profile", "apparmor_parser", [
194 "-r",
195 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
196 ]);
197 yield* Console.log(
198 profileOnDisk
199 ? `Reloaded the AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows Chrome's sandbox for T3's browser.`
200 : `Wrote and loaded the AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows Chrome's sandbox for T3's browser.`,
201 );
202 }
203
204 if ((missing.length > 0 || needsFonts) && !hasApt) {
205 if (missing.length > 0) {
206 yield* Console.log(
207 `T3's browser is missing ${missing.join(", ")}. Install them with your package manager, then run this again.`,
208 );
209 }
210 if (needsFonts) {
211 yield* Console.log(
212 "T3's browser needs fontconfig and system fonts. Install them with your package manager, then run this again.",
213 );
214 }
215 return;
216 }
217 if (missing.length > 0 || needsFonts) {
218 yield* runStep("refresh the package lists", "apt-get", ["update"]);
219 }
220
221 if (missing.length > 0) {
222 const packages = yield* Effect.forEach(PreviewBrowserHost.DEBIAN_PACKAGES, (names) =>
223 Effect.findFirst(names, aptOffers).pipe(Effect.map(Option.getOrElse(() => names[0]!))),
224 );
225 yield* runStep("install the browser's libraries", "apt-get", [
226 "install",
227 "-y",
228 "--no-install-recommends",
229 ...packages,
230 ]);
231 yield* Console.log("Installed the browser's libraries.");
232 }
233
234 if (needsFonts) {
235 yield* runStep("install the browser's fonts", "apt-get", [
236 "install",
237 "-y",
238 "--no-install-recommends",
239 ...FONT_PACKAGES,
240 ]);
241 if (!(yield* fontAvailable)) {
242 return yield* Console.log(
243 "Font packages are installed, but Fontconfig still finds no system font. Check its configuration and run setup again.",
244 );
245 }
246 yield* Console.log(
247 "Installed the browser's fonts. Restart the T3 server if browser tabs were already open.",
248 );
249 }
250
251 yield* Console.log(rootWarning ?? "This host is ready for T3's browser.");
252 }),
253 ),
254 );
255
256 export const browserCommand = Command.make("browser").pipe(
257 Command.withDescription("Manage T3's headless browser on this host."),
258 Command.withSubcommands([browserSetupCommand]),
259 );