Open History to see the last commit
1import {
2 HostProcessExecutablePath,
3 HostProcessPlatform,
4 HostProcessUserId,
5} from "@t3tools/shared/hostProcess";
6import * as Config from "effect/Config";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16
17import * as ProcessRunner from "../processRunner.ts";
18import {
19 ensurePinnedRuntimeInstalled,
20 pinnedRuntimePaths,
21 PinnedRuntimeInstallError,
22} from "./pinnedRuntime.ts";
23import {
24 SERVICE_LAUNCHER_FILE,
25 SERVICE_LAUNCHER_PROTOCOL,
26 SERVICE_STATE_FILE,
27 compareExactServiceVersions,
28 parseServiceState,
29 serviceStateActiveVersion,
30 serviceStateHasPendingUpdate,
31 type ServiceState,
32} from "./serviceProtocol.ts";
33
34const BOOT_SERVICE_NAME = "t3code";
35const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
36// `.service` suffix keeps the label distinct from the desktop app's bundle id
37// (com.t3tools.t3code), so launchd and TCC records never collide.
38const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
39const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
40const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
41
42/** systemd expands `%` specifiers, including in unquoted append-log paths. */
43function escapeSystemdSpecifiers(value: string): string {
44 return value.replaceAll("%", "%%");
45}
46
47function quoteSystemdValue(value: string): string {
48 const escaped = escapeSystemdSpecifiers(value);
49 return /[\s"'\\]/.test(escaped)
50 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
51 : escaped;
52}
53
54export interface BootServicePlan {
55 readonly nodePath: string;
56 readonly launcherPath: string;
57 readonly baseDir: string;
58 readonly logPath: string;
59 readonly unitPath: string;
60}
61
62/** Pure renderer: service units cannot rely on the user's shell or PATH. */
63export function renderBootServiceUnit(plan: BootServicePlan): string {
64 // The user manager has no reliable network-online target; server networking retries itself.
65 return [
66 "[Unit]",
67 "Description=T3 Code server",
68 "StartLimitIntervalSec=300",
69 "StartLimitBurst=5",
70 "",
71 "[Service]",
72 "Type=simple",
73 "WorkingDirectory=%h",
74 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
75 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
76 `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
77 // Let the launcher mark an explicit stop before it signals the server.
78 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
79 "KillMode=mixed",
80 // Agent tool calls run as children of the server, so they share this cgroup.
81 // With the systemd default of OOMPolicy=stop, the kernel killing one greedy
82 // child stops the whole unit: the server, every live agent, and the user's
83 // connection. Keep running and let Restart=always cover the main process.
84 "OOMPolicy=continue",
85 "Restart=always",
86 "RestartSec=5",
87 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
88 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
89 "",
90 "[Install]",
91 "WantedBy=default.target",
92 "",
93 ].join("\n");
94}
95
96/** Plist values are emitted as XML text nodes; only these three need escaping. */
97function escapeXmlText(value: string): string {
98 return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
99}
100
101/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
102export function renderBootServicePlist(
103 plan: BootServicePlan,
104 options: { readonly homeDir: string; readonly environmentPath: string },
105): string {
106 // KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
107 // has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
108 // ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
109 // completes within the launcher's 5s child grace, but a stop that queues
110 // behind an in-flight update transition can take much longer; launchd's
111 // system-defined default (5s on current macOS) would SIGKILL the launcher
112 // (and, with it, the process group) mid-handoff.
113 // ProcessType Interactive opts out of background-job resource throttling.
114 // AbandonProcessGroup stays at its default (false): launchd reaps leftover
115 // process-group members only when the launcher itself exits — the analog of
116 // KillMode=mixed's final cgroup kill — and not when the launcher restarts its
117 // child, so agent children survive server updates.
118 return [
119 `<?xml version="1.0" encoding="UTF-8"?>`,
120 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
121 `<plist version="1.0">`,
122 `<dict>`,
123 ` <key>Label</key>`,
124 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
125 ` <key>ProgramArguments</key>`,
126 ` <array>`,
127 ` <string>${escapeXmlText(plan.nodePath)}</string>`,
128 ` <string>${escapeXmlText(plan.launcherPath)}</string>`,
129 ` </array>`,
130 ` <key>EnvironmentVariables</key>`,
131 ` <dict>`,
132 ` <key>PATH</key>`,
133 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
134 ` <key>T3CODE_HOME</key>`,
135 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
136 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
137 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
138 ` </dict>`,
139 ` <key>WorkingDirectory</key>`,
140 ` <string>${escapeXmlText(options.homeDir)}</string>`,
141 ` <key>RunAtLoad</key>`,
142 ` <true/>`,
143 ` <key>KeepAlive</key>`,
144 ` <true/>`,
145 ` <key>ThrottleInterval</key>`,
146 ` <integer>5</integer>`,
147 ` <key>ExitTimeOut</key>`,
148 ` <integer>90</integer>`,
149 ` <key>ProcessType</key>`,
150 ` <string>Interactive</string>`,
151 ` <key>StandardOutPath</key>`,
152 ` <string>${escapeXmlText(plan.logPath)}</string>`,
153 ` <key>StandardErrorPath</key>`,
154 ` <string>${escapeXmlText(plan.logPath)}</string>`,
155 `</dict>`,
156 `</plist>`,
157 ``,
158 ].join("\n");
159}
160
161export interface BootServiceStep {
162 readonly step: string;
163 readonly command: string;
164 readonly args: ReadonlyArray<string>;
165 /**
166 * Non-zero exit is logged and ignored. Reserved for steps whose common
167 * failures (not loaded, already enabled) leave a state a later strict step
168 * either tolerates or fails loudly on.
169 */
170 readonly optional?: boolean;
171 /** Override the ProcessRunner default (60s) for steps that block longer. */
172 readonly timeout?: Duration.Input;
173}
174
175/**
176 * Stop commands block until the service manager gives up: 90s by default for
177 * systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
178 * must stay above both, or the runner cancels the stop mid-shutdown and the
179 * next step races a still-loaded service.
180 */
181const STOP_STEP_TIMEOUT = Duration.seconds(120);
182
183/**
184 * Platform service-manager integration as data: paths, a pure renderer, and
185 * the command steps each flow runs. install/uninstall/status consume this and
186 * never branch on platform.
187 */
188export interface BootServiceManager {
189 readonly kind: "systemd" | "launchd";
190 readonly unitPath: string;
191 readonly render: (plan: BootServicePlan) => string;
192 /** Before rewriting files, when a unit is already installed. */
193 readonly stop: ReadonlyArray<BootServiceStep>;
194 /** After files are written. The last entry starts the service. */
195 readonly activate: ReadonlyArray<BootServiceStep>;
196 /** Best-effort recovery after a failed repair of an installed service. */
197 readonly restart: ReadonlyArray<BootServiceStep>;
198 /** Uninstall, before the unit file is removed. */
199 readonly deactivate: ReadonlyArray<BootServiceStep>;
200 /** Uninstall, after the unit file is removed. */
201 readonly finalize: ReadonlyArray<BootServiceStep>;
202}
203
204function systemdManager(input: {
205 readonly path: Path.Path;
206 readonly homeDir: string;
207}): BootServiceManager {
208 const unitPath = input.path.join(
209 input.homeDir,
210 ".config",
211 "systemd",
212 "user",
213 BOOT_SERVICE_UNIT_FILE,
214 );
215 return {
216 kind: "systemd",
217 unitPath,
218 render: renderBootServiceUnit,
219 stop: [
220 {
221 step: "stopping the installed service",
222 command: "systemctl",
223 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
224 timeout: STOP_STEP_TIMEOUT,
225 },
226 ],
227 activate: [
228 {
229 step: "reloading systemd user units",
230 command: "systemctl",
231 args: ["--user", "daemon-reload"],
232 },
233 {
234 step: "enabling the service",
235 command: "systemctl",
236 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
237 },
238 // Start last. No administrative state write occurs after this succeeds.
239 {
240 step: "starting the service",
241 command: "systemctl",
242 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
243 },
244 ],
245 restart: [
246 {
247 step: "restarting the service after a failed update",
248 command: "systemctl",
249 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
250 },
251 ],
252 deactivate: [
253 {
254 step: "stopping the service",
255 command: "systemctl",
256 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
257 timeout: STOP_STEP_TIMEOUT,
258 },
259 ],
260 finalize: [
261 {
262 step: "reloading systemd user units",
263 command: "systemctl",
264 args: ["--user", "daemon-reload"],
265 },
266 ],
267 };
268}
269
270function launchdManager(input: {
271 readonly path: Path.Path;
272 readonly homeDir: string;
273 readonly uid: number;
274 readonly environmentPath: string;
275}): BootServiceManager {
276 const unitPath = input.path.join(
277 input.homeDir,
278 "Library",
279 "LaunchAgents",
280 BOOT_SERVICE_PLIST_FILE,
281 );
282 const domainTarget = `gui/${input.uid}`;
283 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
284 // bootout/enable are optional: they fail on not-loaded states that are fine
285 // to proceed from. The strict `bootstrap` runs last and is also the start:
286 // loading a RunAtLoad/KeepAlive plist starts the job, so a separate
287 // kickstart would kill and restart a server it just booted. A lingering job
288 // that survived bootout, or a gui domain with nobody logged in at the
289 // screen (SSH install), makes bootstrap fail the flow loudly rather than
290 // silently keeping a stale server.
291 return {
292 kind: "launchd",
293 unitPath,
294 render: (plan) =>
295 renderBootServicePlist(plan, {
296 homeDir: input.homeDir,
297 environmentPath: input.environmentPath,
298 }),
299 // Without --wait, bootout returns in milliseconds while the job drains
300 // for up to ExitTimeOut, and a bootstrap during the drain fails EIO.
301 // --wait (present on modern macOS, absent from the man page) blocks until
302 // the job is removed from the domain; STOP_STEP_TIMEOUT outlives it.
303 stop: [
304 {
305 step: "stopping the installed launch agent",
306 command: "launchctl",
307 args: ["bootout", "--wait", serviceTarget],
308 optional: true,
309 timeout: STOP_STEP_TIMEOUT,
310 },
311 ],
312 activate: [
313 // A persisted `launchctl disable` override refuses bootstrap; clear it.
314 {
315 step: "enabling the launch agent",
316 command: "launchctl",
317 args: ["enable", serviceTarget],
318 optional: true,
319 },
320 // Start last. No administrative state write occurs after this succeeds.
321 {
322 step: "starting the service",
323 command: "launchctl",
324 args: ["bootstrap", domainTarget, unitPath],
325 },
326 ],
327 restart: [
328 {
329 step: "restarting the service after a failed update",
330 command: "launchctl",
331 args: ["bootstrap", domainTarget, unitPath],
332 },
333 ],
334 // No `launchctl disable` here: a persisted override would sabotage a
335 // later reinstall. Removing the plist is what stops the next login load.
336 // A bootout that fails for a reason other than "not loaded" leaves the
337 // job running until logout; the failure is in the boot-service log.
338 deactivate: [
339 {
340 step: "stopping the service",
341 command: "launchctl",
342 args: ["bootout", "--wait", serviceTarget],
343 optional: true,
344 timeout: STOP_STEP_TIMEOUT,
345 },
346 ],
347 finalize: [],
348 };
349}
350
351/** Undefined means this host cannot run the background service. */
352function selectBootServiceManager(input: {
353 readonly platform: NodeJS.Platform;
354 readonly homeDir: string;
355 readonly uid: number | undefined;
356 readonly path: Path.Path;
357 readonly environmentPath: string;
358}): BootServiceManager | undefined {
359 if (input.homeDir === "") {
360 return undefined;
361 }
362 if (input.platform === "linux") {
363 return systemdManager({ path: input.path, homeDir: input.homeDir });
364 }
365 if (input.platform === "darwin" && input.uid !== undefined) {
366 return launchdManager({
367 path: input.path,
368 homeDir: input.homeDir,
369 uid: input.uid,
370 environmentPath: input.environmentPath,
371 });
372 }
373 return undefined;
374}
375
376export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
377 "BootServiceUnsupportedError",
378 { platform: Schema.String },
379) {
380 override get message(): string {
381 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
382 }
383}
384
385export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
386 "BootServiceCommandError",
387 {
388 step: Schema.String,
389 exitCode: Schema.optional(Schema.Number),
390 stdoutLength: Schema.optional(Schema.Number),
391 stderrLength: Schema.optional(Schema.Number),
392 cause: Schema.optional(Schema.Defect()),
393 },
394) {
395 override get message(): string {
396 return this.exitCode === undefined
397 ? `Background setup failed while ${this.step}.`
398 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
399 }
400}
401
402export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
403 "BootServiceInstallError",
404 { cause: Schema.Defect() },
405) {
406 override get message(): string {
407 return "Could not set up the T3 Code background service.";
408 }
409}
410
411const BootServiceProblem = Schema.Literals([
412 "user-manager-unavailable",
413 "linger-unavailable",
414 "linger-disabled",
415 "service-disabled",
416 "service-stopped",
417]);
418type BootServiceProblem = typeof BootServiceProblem.Type;
419
420/** These codes and recovery steps are documented in docs/user/background-service.md. */
421export function formatBootServiceProblem(problem: BootServiceProblem): string {
422 switch (problem) {
423 case "user-manager-unavailable":
424 return "Cannot reach the systemd user manager. Run `systemctl --user status` in a login session for the service user. Install your distribution's systemd user-session support if it is missing; do not run T3 with sudo.";
425 case "linger-unavailable":
426 return 'Cannot check whether this user can run services after logout. Run `loginctl show-user "$(id -un)" --property=Linger` and check that systemd-logind is available.';
427 case "linger-disabled":
428 return 'Lingering is disabled. T3 Code will stop when your last login session ends and will not start at boot. Run `sudo loginctl enable-linger "$(id -un)"` on this machine, then retry the service command as your normal user.';
429 case "service-disabled":
430 return "The service is not enabled to start automatically. Run `t3 service update` to repair it.";
431 case "service-stopped":
432 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service update`.";
433 }
434}
435
436export class BootServicePrerequisiteError extends Schema.TaggedErrorClass<BootServicePrerequisiteError>()(
437 "BootServicePrerequisiteError",
438 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
439) {
440 override get message(): string {
441 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
442 }
443}
444
445export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
446 "BootServiceUpdatePendingError",
447 {},
448) {
449 override get message(): string {
450 return "A remote server update is still pending. Wait for it to finish, then retry.";
451 }
452}
453
454export class BootServiceDowngradeRefusedError extends Schema.TaggedErrorClass<BootServiceDowngradeRefusedError>()(
455 "BootServiceDowngradeRefusedError",
456 {
457 installedVersion: Schema.String,
458 targetVersion: Schema.String,
459 },
460) {
461 override get message(): string {
462 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
463 }
464}
465
466export type BootServiceError =
467 | BootServiceUnsupportedError
468 | BootServiceCommandError
469 | BootServiceInstallError
470 | BootServicePrerequisiteError
471 | BootServiceUpdatePendingError
472 | BootServiceDowngradeRefusedError;
473
474export interface BootServiceStatus {
475 readonly supported: boolean;
476 readonly installed: boolean;
477 readonly current: boolean;
478 readonly installedVersion?: string;
479 readonly problems?: ReadonlyArray<BootServiceProblem>;
480 readonly unitPath: string;
481 readonly logPath: string;
482}
483
484export class BootService extends Context.Service<
485 BootService,
486 {
487 readonly install: (options?: {
488 readonly allowDowngrade?: boolean;
489 }) => Effect.Effect<BootServicePlan, BootServiceError>;
490 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
491 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
492 }
493>()("t3/cloud/bootService") {}
494
495export interface BootServiceHost {
496 readonly execPath: string;
497 readonly launcherSourcePath?: string;
498}
499
500export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
501 readonly baseDir: string;
502 readonly logsDir: string;
503 readonly cliVersion: string;
504 readonly host?: BootServiceHost;
505}) {
506 const hostExecPath = yield* HostProcessExecutablePath;
507 const platform = yield* HostProcessPlatform;
508 const uid = yield* HostProcessUserId;
509 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
510 const installerPath = yield* Config.string("PATH").pipe(Config.withDefault(""));
511 const fs = yield* FileSystem.FileSystem;
512 const path = yield* Path.Path;
513 const runner = yield* ProcessRunner.ProcessRunner;
514 const host = input.host ?? { execPath: hostExecPath };
515 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
516 (directory) =>
517 directory.length > 0 &&
518 Array.from(directory).every((character) => {
519 const code = character.charCodeAt(0);
520 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
521 }),
522 );
523 const environmentPath = Array.from(
524 new Set([
525 ...xmlSafeInstallerDirectories,
526 path.dirname(host.execPath),
527 "/opt/homebrew/bin",
528 "/usr/local/bin",
529 "/usr/bin",
530 "/bin",
531 "/usr/sbin",
532 "/sbin",
533 ]),
534 ).join(":");
535
536 const detectedManager = selectBootServiceManager({
537 platform,
538 homeDir,
539 uid,
540 path,
541 environmentPath,
542 });
543 const unitPath = detectedManager?.unitPath ?? "";
544 const logPath = path.join(input.logsDir, "boot-service.log");
545 const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
546 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
547 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
548 const launcherSourcePath =
549 host.launcherSourcePath ??
550 path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
551 const writeDurably = (filePath: string, contents: string) =>
552 Effect.scoped(
553 Effect.gen(function* () {
554 const directory = path.dirname(filePath);
555 yield* fs.makeDirectory(directory, { recursive: true });
556 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
557 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
558 yield* (yield* fs.open(tempPath, { flag: "r" })).sync;
559 yield* fs.rename(tempPath, filePath);
560 yield* (yield* fs.open(directory, { flag: "r" })).sync;
561 }),
562 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
563 const plan: BootServicePlan = {
564 nodePath: host.execPath,
565 launcherPath,
566 baseDir: input.baseDir,
567 logPath,
568 unitPath,
569 };
570
571 const requireManager = Effect.suspend(() =>
572 detectedManager === undefined
573 ? new BootServiceUnsupportedError({ platform })
574 : Effect.succeed(detectedManager),
575 );
576
577 const logFailure = (error: { readonly message: string }) =>
578 DateTime.now.pipe(
579 Effect.flatMap((now) =>
580 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
581 ),
582 Effect.ignore,
583 );
584
585 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
586 step: string,
587 command: string,
588 args: ReadonlyArray<string>,
589 options?: { readonly timeout?: Duration.Input },
590 ) {
591 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
592 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
593 Effect.filterOrFail(
594 (result) => result.code === 0,
595 (result) =>
596 new BootServiceCommandError({
597 step,
598 exitCode: Number(result.code),
599 stdoutLength: result.stdout.length,
600 stderrLength: result.stderr.length,
601 }),
602 ),
603 Effect.tapError(logFailure),
604 );
605 });
606
607 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
608 Effect.forEach(
609 steps,
610 (entry) => {
611 const run = runStep(
612 entry.step,
613 entry.command,
614 entry.args,
615 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
616 );
617 // runStep's tapError already appends the failure to the log, so an
618 // ignored optional step still leaves a trace.
619 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
620 },
621 { discard: true },
622 );
623
624 const probe = (command: string, args: ReadonlyArray<string>) =>
625 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
626 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
627 Option.isSome(result) && result.value.code === 0;
628 const lingerArgs = [
629 "show-user",
630 ...(uid === undefined ? [] : [String(uid)]),
631 "--property=Linger",
632 "--value",
633 ];
634 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
635 includeService: boolean,
636 ) {
637 const [manager, linger] = yield* Effect.all(
638 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
639 { concurrency: "unbounded" },
640 );
641 const problems: BootServiceProblem[] = [];
642 if (!succeeded(manager)) problems.push("user-manager-unavailable");
643 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
644 if (lingering !== "yes") {
645 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
646 }
647 if (includeService && succeeded(manager)) {
648 const [enabled, active] = yield* Effect.all(
649 [
650 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
651 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
652 ],
653 { concurrency: "unbounded" },
654 );
655 if (
656 !succeeded(enabled) ||
657 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
658 ) {
659 problems.push("service-disabled");
660 }
661 if (!succeeded(active)) problems.push("service-stopped");
662 }
663 return problems;
664 });
665
666 const requireSystemdPrerequisites = Effect.gen(function* () {
667 const problems = yield* readSystemdProblems(false);
668 const unavailable = problems.find((problem) => problem !== "linger-disabled");
669 if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
670 if (!problems.includes("linger-disabled")) return;
671 yield* runStep("enabling lingering for this user", "loginctl", [
672 "enable-linger",
673 "--no-ask-password",
674 ...(uid === undefined ? [] : [String(uid)]),
675 ]).pipe(
676 Effect.mapError(
677 (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
678 ),
679 );
680 const remaining = yield* readSystemdProblems(false);
681 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
682 });
683
684 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
685 readonly allowDowngrade?: boolean;
686 }) {
687 const manager = yield* requireManager;
688 yield* fs
689 .makeDirectory(input.logsDir, { recursive: true })
690 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
691
692 // A permissions failure must not leave a partial install or stop a working server.
693 if (manager.kind === "systemd") {
694 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
695 }
696
697 // Prepare every immutable artifact before stopping the installed unit.
698 yield* ensurePinnedRuntimeInstalled({
699 baseDir: input.baseDir,
700 version: input.cliVersion,
701 fs,
702 path,
703 runner,
704 validate: (runtime) =>
705 runner
706 .run({
707 command: host.execPath,
708 args: [runtime.entryPath, "--version"],
709 timeout: Duration.seconds(30),
710 })
711 .pipe(
712 Effect.mapError(
713 (cause) =>
714 new PinnedRuntimeInstallError({
715 step: "verifying the pinned t3 runtime",
716 cause,
717 }),
718 ),
719 Effect.flatMap((result) => {
720 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
721 return result.code === 0 && reportedVersion === input.cliVersion
722 ? Effect.void
723 : Effect.fail(
724 new PinnedRuntimeInstallError({
725 step: "verifying the pinned t3 runtime",
726 exitCode: Number(result.code),
727 stdoutLength: result.stdout.length,
728 stderrLength: result.stderr.length,
729 }),
730 );
731 }),
732 ),
733 }).pipe(
734 Effect.mapError((error) =>
735 error._tag === "PinnedRuntimeInstallError"
736 ? new BootServiceCommandError({
737 step: error.step,
738 exitCode: error.exitCode,
739 stdoutLength: error.stdoutLength,
740 stderrLength: error.stderrLength,
741 cause: error,
742 })
743 : new BootServiceInstallError({ cause: error }),
744 ),
745 );
746 const launcherSource = yield* fs
747 .readFileString(launcherSourcePath)
748 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
749
750 const installed = yield* fs
751 .exists(unitPath)
752 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
753 if (installed) {
754 yield* runSteps(manager.stop);
755 }
756
757 yield* Effect.gen(function* () {
758 if (installed) {
759 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
760 if (Option.isSome(previousStateText)) {
761 if (serviceStateHasPendingUpdate(previousStateText.value)) {
762 return yield* new BootServiceUpdatePendingError();
763 }
764 // A remote update can finish after the CLI checks status. Read its
765 // final version after the launcher stops and before changing files.
766 const installedVersion = serviceStateActiveVersion(previousStateText.value);
767 if (
768 installedVersion !== undefined &&
769 options?.allowDowngrade !== true &&
770 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
771 ) {
772 return yield* new BootServiceDowngradeRefusedError({
773 installedVersion,
774 targetVersion: input.cliVersion,
775 });
776 }
777 }
778 }
779 yield* fs
780 .makeDirectory(path.dirname(unitPath), { recursive: true })
781 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
782 yield* writeDurably(launcherPath, launcherSource);
783 yield* writeDurably(
784 statePath,
785 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
786 `${JSON.stringify(
787 {
788 protocol: SERVICE_LAUNCHER_PROTOCOL,
789 activeVersion: input.cliVersion,
790 } satisfies ServiceState,
791 null,
792 2,
793 )}\n`,
794 );
795 yield* writeDurably(unitPath, manager.render(plan));
796
797 yield* runSteps(manager.activate);
798 }).pipe(
799 Effect.tapError(() =>
800 installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
801 ),
802 );
803 return plan;
804 });
805
806 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
807 const manager = yield* requireManager;
808 if (
809 !(yield* fs
810 .exists(unitPath)
811 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
812 )
813 return false;
814 yield* runSteps(manager.deactivate);
815 yield* fs
816 .remove(unitPath)
817 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
818 yield* runSteps(manager.finalize);
819 return true;
820 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
821
822 const status: BootService["Service"]["status"] = Effect.gen(function* () {
823 if (detectedManager === undefined) {
824 return { supported: false, installed: false, current: false, unitPath, logPath };
825 }
826 if (!(yield* fs.exists(unitPath))) {
827 return { supported: true, installed: false, current: false, unitPath, logPath };
828 }
829 const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
830 yield* Effect.all([
831 fs.readFileString(unitPath),
832 fs.exists(launcherPath),
833 fs.exists(runtimePaths.entryPath),
834 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
835 fs.readFileString(statePath).pipe(Effect.option),
836 ]);
837 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
838 const installedVersion = Option.isSome(stateText)
839 ? serviceStateActiveVersion(stateText.value)
840 : undefined;
841 const normalizeUnit = (contents: string) =>
842 detectedManager.kind === "launchd"
843 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
844 : contents;
845 const problems = detectedManager.kind === "systemd" ? yield* readSystemdProblems(true) : [];
846 return {
847 supported: true,
848 installed: true,
849 ...(installedVersion === undefined ? {} : { installedVersion }),
850 problems,
851 current:
852 problems.length === 0 &&
853 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
854 launcherExists &&
855 runtimeEntryExists &&
856 Option.isSome(runtimeSentinel) &&
857 runtimeSentinel.value.trim() === input.cliVersion &&
858 state?.activeVersion === input.cliVersion &&
859 state?.update?.status !== "pending",
860 unitPath,
861 logPath,
862 };
863 }).pipe(
864 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
865 Effect.withSpan("cloud.boot_service.status"),
866 );
867
868 return BootService.of({ install, uninstall, status });
869});
870
871export const layer = (input: {
872 readonly baseDir: string;
873 readonly logsDir: string;
874 readonly cliVersion: string;
875 readonly host?: BootServiceHost;
876}) => Layer.effect(BootService, make(input));