Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Config from "effect/Config";
3import * as DateTime from "effect/DateTime";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11
12import {
13 HostProcessArguments,
14 HostProcessExecutablePath,
15 HostProcessPlatform,
16} from "@t3tools/shared/hostProcess";
17
18import * as ProcessRunner from "../processRunner.ts";
19import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
20
21/**
22 * Installs T3 Code as a per-user boot service. Linux-only for now: systemd
23 * user unit + loginctl enable-linger. The service runs a stable or pinned
24 * runtime — never an ephemeral `npx t3` cache whose eviction could break
25 * startup.
26 */
27
28const BOOT_SERVICE_NAME = "t3code";
29
30export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
31export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
32
33const EPHEMERAL_CACHE_SEGMENTS = [
34 "/_npx/", // npx
35 "\\_npx\\",
36 "/pnpm/dlx/", // pnpm dlx (~/.cache/pnpm/dlx and $PNPM_HOME/.pnpm/dlx)
37 "/.pnpm/dlx/",
38 "/.bun/install/cache/", // bunx
39];
40
41/**
42 * `npx t3` (and pnpm dlx / bunx) run out of ephemeral package-manager
43 * caches that can be evicted at any time — a boot service must never point
44 * there. Global installs, repo checkouts, and the pinned runtime below are
45 * all stable.
46 */
47export function isEphemeralCacheEntry(entryPath: string): boolean {
48 return EPHEMERAL_CACHE_SEGMENTS.some((segment) => entryPath.includes(segment));
49}
50
51/**
52 * systemd expands `%` specifiers in most directive values, including the
53 * `append:` file paths, which take the rest of the line literally and must
54 * NOT be quoted.
55 */
56export function escapeSystemdSpecifiers(value: string): string {
57 return value.replaceAll("%", "%%");
58}
59
60/**
61 * systemd word-splits ExecStart and Environment values and expands `%`
62 * specifiers, so paths with spaces or percents must be quoted and escaped.
63 */
64export function quoteSystemdValue(value: string): string {
65 const escaped = escapeSystemdSpecifiers(value);
66 return /[\s"'\\]/.test(escaped)
67 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
68 : escaped;
69}
70
71export interface BootServicePlan {
72 /** Absolute path of the node binary running this CLI. */
73 readonly nodePath: string;
74 /** Absolute path of the pinned t3 entry point the unit will run. */
75 readonly t3EntryPath: string;
76 readonly baseDir: string;
77 readonly logPath: string;
78 readonly unitPath: string;
79}
80
81/**
82 * Pure so it is testable byte-for-byte. systemd user units run with a
83 * minimal environment: every path must be absolute, and the service must
84 * not rely on PATH, nvm shims, or shell profiles. Failures land in
85 * `logPath` because `systemctl --user` failures are otherwise invisible.
86 */
87export function renderBootServiceUnit(plan: BootServicePlan): string {
88 // No After=network-online.target: it does not exist in the systemd *user*
89 // manager, so ordering on it is silently ignored. The server retries its
90 // relay connection, and Restart=always covers early-boot failures.
91 return [
92 "[Unit]",
93 "Description=T3 Code server",
94 // Give up after 5 crashes in 5 minutes so a persistently broken install
95 // (deleted runtime, broken workspace) stops instead of restarting every
96 // 5s forever and growing the unrotated append log without bound.
97 "StartLimitIntervalSec=300",
98 "StartLimitBurst=5",
99 "",
100 "[Service]",
101 "Type=simple",
102 "WorkingDirectory=%h",
103 // A systemd user unit inherits the user manager's minimal PATH, which does
104 // NOT include ~/.local/bin — the directory Ubuntu's ~/.profile prepends and
105 // where user-scoped provider CLIs (claude, codex) land on a headless
106 // install. Without this, `t3 serve` finds every provider by hand from a
107 // login shell but the service starts with zero providers. Prepend the
108 // user-local bins to the standard system PATH; %h expands to the home dir
109 // (like WorkingDirectory), and absent entries (e.g. /snap/bin on non-Debian
110 // distros) are simply skipped during lookup.
111 "Environment=PATH=%h/.local/bin:%h/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin",
112 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
113 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
114 `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
115 "Restart=always",
116 "RestartSec=5",
117 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
118 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
119 "",
120 "[Install]",
121 "WantedBy=default.target",
122 "",
123 ].join("\n");
124}
125
126export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
127 "BootServiceUnsupportedError",
128 { platform: Schema.String },
129) {
130 override get message(): string {
131 return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
132 }
133}
134
135export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
136 "BootServiceCommandError",
137 {
138 step: Schema.String,
139 exitCode: Schema.optional(Schema.Number),
140 stdoutLength: Schema.optional(Schema.Number),
141 stderrLength: Schema.optional(Schema.Number),
142 cause: Schema.optional(Schema.Defect()),
143 },
144) {
145 override get message(): string {
146 return this.exitCode === undefined
147 ? `Background setup failed while ${this.step}.`
148 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
149 }
150}
151
152export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
153 "BootServiceInstallError",
154 { cause: Schema.Defect() },
155) {
156 override get message(): string {
157 return "Could not set up the T3 Code background service.";
158 }
159}
160
161export type BootServiceError =
162 | BootServiceUnsupportedError
163 | BootServiceCommandError
164 | BootServiceInstallError;
165
166export interface BootServiceStatus {
167 readonly supported: boolean;
168 readonly installed: boolean;
169 /** False when the installed unit no longer matches what install would write. */
170 readonly current: boolean;
171 readonly unitPath: string;
172 readonly logPath: string;
173}
174
175export class BootService extends Context.Service<
176 BootService,
177 {
178 /** Installs the pinned runtime + unit, enables linger, starts the service. */
179 readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
180 /**
181 * Stops and removes the unit; leaves the pinned runtime for reuse.
182 * Returns whether a unit was actually removed.
183 */
184 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
185 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
186 }
187>()("t3/cloud/bootService") {}
188
189export interface BootServiceHost {
190 readonly execPath: string;
191 readonly cliEntryPath: string;
192}
193
194export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
195 readonly baseDir: string;
196 readonly logsDir: string;
197 readonly cliVersion: string;
198 readonly host?: BootServiceHost;
199}) {
200 const hostExecPath = yield* HostProcessExecutablePath;
201 const hostArguments = yield* HostProcessArguments;
202 const host = input.host ?? {
203 execPath: hostExecPath,
204 // When running the packed CLI this is dist/bin.mjs; when stable (global
205 // install, repo checkout) the boot service runs this same artifact.
206 cliEntryPath: hostArguments[1] ?? "",
207 };
208 const platform = yield* HostProcessPlatform;
209 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
210 const fs = yield* FileSystem.FileSystem;
211 const path = yield* Path.Path;
212 const runner = yield* ProcessRunner.ProcessRunner;
213
214 const unitDir = path.join(homeDir, ".config", "systemd", "user");
215 const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
216 const logPath = path.join(input.logsDir, "boot-service.log");
217 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
218
219 const requireSystemdLinux = Effect.gen(function* () {
220 if (platform !== "linux" || homeDir === "") {
221 return yield* new BootServiceUnsupportedError({ platform });
222 }
223 });
224
225 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
226 step: string,
227 command: string,
228 args: ReadonlyArray<string>,
229 options?: { readonly timeout?: Duration.Input },
230 ) {
231 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
232 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
233 Effect.filterOrFail(
234 (result) => result.code === 0,
235 (result) =>
236 new BootServiceCommandError({
237 step,
238 exitCode: Number(result.code),
239 stdoutLength: result.stdout.length,
240 stderrLength: result.stderr.length,
241 }),
242 ),
243 Effect.tapError((error) =>
244 DateTime.now.pipe(
245 Effect.flatMap((now) =>
246 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
247 flag: "a",
248 }),
249 ),
250 Effect.ignore,
251 ),
252 ),
253 );
254 });
255
256 /**
257 * Ensures plannedEntryPath exists before the unit points at it. A stable
258 * install (global bin, repo checkout) is used as-is; an ephemeral cache
259 * entry is replaced by `npm install --prefix`-ing the exact running
260 * version into <baseDir>/runtime/versions/<v>. A real install (not a copy
261 * of bin.mjs) because t3 ships native deps like node-pty.
262 */
263 const ensurePinnedRuntime = Effect.gen(function* () {
264 if (!isEphemeralCacheEntry(host.cliEntryPath)) {
265 return;
266 }
267 yield* ensurePinnedRuntimeInstalled({
268 baseDir: input.baseDir,
269 version: input.cliVersion,
270 fs,
271 path,
272 runner,
273 }).pipe(
274 Effect.mapError((error) =>
275 error.step.startsWith("installing")
276 ? new BootServiceCommandError({
277 step: error.step,
278 exitCode: error.exitCode,
279 stdoutLength: error.stdoutLength,
280 stderrLength: error.stderrLength,
281 cause: error.cause,
282 })
283 : new BootServiceInstallError({ cause: error }),
284 ),
285 Effect.tapError((error) =>
286 DateTime.now.pipe(
287 Effect.flatMap((now) =>
288 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
289 flag: "a",
290 }),
291 ),
292 Effect.ignore,
293 ),
294 ),
295 );
296 });
297
298 // Where the unit will point: derivable without touching the network, so
299 // status can compare units purely; install materializes it first.
300 const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
301 ? runtimePaths.entryPath
302 : host.cliEntryPath;
303 const plan: BootServicePlan = {
304 nodePath: host.execPath,
305 t3EntryPath: plannedEntryPath,
306 baseDir: input.baseDir,
307 logPath,
308 unitPath,
309 };
310
311 const install: BootService["Service"]["install"] = Effect.gen(function* () {
312 yield* requireSystemdLinux;
313 yield* fs
314 .makeDirectory(input.logsDir, { recursive: true })
315 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
316
317 yield* ensurePinnedRuntime;
318
319 const previousUnit = yield* fs.exists(unitPath).pipe(
320 Effect.flatMap((exists) =>
321 exists
322 ? fs.readFileString(unitPath).pipe(Effect.map(Option.some))
323 : Effect.succeed(Option.none<string>()),
324 ),
325 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
326 );
327
328 yield* fs.makeDirectory(unitDir, { recursive: true }).pipe(
329 Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))),
330 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
331 );
332
333 // If any activation step fails, remove the unit again: a leftover file
334 // would make service status report it as installed even though it was
335 // never enabled or lingered.
336 yield* Effect.gen(function* () {
337 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
338 yield* runStep("enabling the service", "systemctl", [
339 "--user",
340 "enable",
341 BOOT_SERVICE_UNIT_FILE,
342 ]);
343 // restart rather than enable --now: --now does not replace an already
344 // running process, so repairing a stale unit would leave the old
345 // server running until reboot. restart also starts a stopped service.
346 yield* runStep("starting the service", "systemctl", [
347 "--user",
348 "restart",
349 BOOT_SERVICE_UNIT_FILE,
350 ]);
351 // Linger keeps the user manager (and this service) running without an
352 // open session — the whole point on a box reached over SSH. No
353 // username argument: loginctl defaults to the calling user, which is
354 // always right, while $USER can be stale (su without -l) or unset.
355 yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
356 }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit)));
357
358 return plan;
359 }).pipe(Effect.withSpan("cloud.boot_service.install"));
360
361 // If activation fails partway (e.g. enable succeeds but restart/linger
362 // fails), leave nothing behind: disable removes the enable symlink, remove
363 // deletes the file, daemon-reload clears the stale definition — otherwise a
364 // dangling wants/ symlink logs "Failed to load unit" at every boot and the
365 // next lifecycle command misreports the state.
366 const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
367 previousUnit: Option.Option<string>,
368 ) {
369 if (Option.isSome(previousUnit)) {
370 yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore);
371 } else {
372 yield* runStep("cleaning up the service", "systemctl", [
373 "--user",
374 "disable",
375 "--now",
376 BOOT_SERVICE_UNIT_FILE,
377 ]).pipe(Effect.ignore);
378 yield* fs.remove(unitPath).pipe(Effect.ignore);
379 }
380 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]).pipe(
381 Effect.ignore,
382 );
383 if (Option.isSome(previousUnit)) {
384 yield* runStep("restoring the previous service", "systemctl", [
385 "--user",
386 "restart",
387 BOOT_SERVICE_UNIT_FILE,
388 ]).pipe(Effect.ignore);
389 }
390 });
391
392 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
393 yield* requireSystemdLinux;
394 const exists = yield* fs
395 .exists(unitPath)
396 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
397 if (!exists) {
398 return false;
399 }
400 yield* runStep("stopping the service", "systemctl", [
401 "--user",
402 "disable",
403 "--now",
404 BOOT_SERVICE_UNIT_FILE,
405 ]);
406 yield* fs
407 .remove(unitPath)
408 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
409 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
410 return true;
411 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
412
413 const status: BootService["Service"]["status"] = Effect.gen(function* () {
414 if (platform !== "linux" || homeDir === "") {
415 return { supported: false, installed: false, current: false, unitPath, logPath };
416 }
417 const unitExists = yield* fs.exists(unitPath);
418 if (!unitExists) {
419 return { supported: true, installed: false, current: false, unitPath, logPath };
420 }
421 const unit = yield* fs.readFileString(unitPath);
422 // A unit is current only if it matches what install would write now (an
423 // older CLI wrote a different runtime/node path) AND the entry point it
424 // references still exists (a pinned runtime under ~/.t3 can be deleted to
425 // reclaim space). Either mismatch makes connect offer a repair.
426 const entryExists = yield* fs.exists(plannedEntryPath);
427 const current = unit === renderBootServiceUnit(plan) && entryExists;
428 return { supported: true, installed: true, current, unitPath, logPath };
429 }).pipe(
430 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
431 Effect.withSpan("cloud.boot_service.status"),
432 );
433
434 return BootService.of({ install, uninstall, status });
435});
436
437export const layer = (input: {
438 readonly baseDir: string;
439 readonly logsDir: string;
440 readonly cliVersion: string;
441 readonly host?: BootServiceHost;
442}) => Layer.effect(BootService, make(input));