Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Config from "effect/Config";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Schedule from "effect/Schedule";
13import { CliError } from "effect/cli";
14import { HttpClient } from "effect/http";
15import * as Schema from "effect/Schema";
16
17import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
18
19import * as ProcessRunner from "../processRunner.ts";
20import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts";
21import {
22 ensurePinnedRuntimeInstalled,
23 launcherOwnsVersionsDir,
24 pinnedRuntimeCommand,
25 pinnedRuntimePaths,
26 pinnedRuntimeVersionsDir,
27 PinnedRuntimeInstallError,
28} from "./pinnedRuntime.ts";
29import {
30 SERVICE_LAUNCHER_PROTOCOL,
31 SERVICE_RESTART_PENDING_FILE,
32 SERVICE_STATE_FILE,
33 SERVICE_UNIT_ENV,
34 compareExactServiceVersions,
35 serviceUnitBaseDirOf as bootServiceBaseDirOf,
36 parseServiceState,
37 serviceStateActiveVersion,
38 serviceStateHasPendingUpdate,
39 type ServiceState,
40} from "./serviceProtocol.ts";
41
42export {
43 serviceUnitBaseDirOf as bootServiceBaseDirOf,
44 serviceUnitProgramOf as bootServiceProgramOf,
45} from "./serviceProtocol.ts";
46
47const BOOT_SERVICE_NAME = "t3code";
48export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
49// `.service` suffix keeps the label distinct from the desktop app's bundle id
50// (com.t3tools.t3code), so launchd and TCC records never collide.
51export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
52export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
53export const BOOT_SERVICE_LOG_FILE = "boot-service.log";
54
55/** systemd expands `%` specifiers, including in unquoted append-log paths. */
56function escapeSystemdSpecifiers(value: string): string {
57 return value.replaceAll("%", "%%");
58}
59
60function quoteSystemdValue(value: string): string {
61 const escaped = escapeSystemdSpecifiers(value);
62 return /[\s"'\\]/.test(escaped)
63 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
64 : escaped;
65}
66
67export interface BootServicePlan {
68 readonly program: ReadonlyArray<string>;
69 readonly baseDir: string;
70 readonly logPath: string;
71 readonly unitPath: string;
72 /** The manager accepted a detached install; its outcome is written to `logPath`. */
73 readonly handedOff?: boolean;
74}
75
76/** Service units cannot rely on the user's shell or PATH. */
77export function renderBootServiceUnit(plan: BootServicePlan): string {
78 // The user manager has no reliable network-online target; server networking retries itself.
79 return [
80 "[Unit]",
81 "Description=T3 Code server",
82 "StartLimitIntervalSec=300",
83 "StartLimitBurst=5",
84 "",
85 "[Service]",
86 "Type=simple",
87 "WorkingDirectory=%h",
88 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
89 `Environment=${SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
90 `ExecStart=${plan.program.map(quoteSystemdValue).join(" ")}`,
91 // Let the launcher mark an explicit stop before it signals the server.
92 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
93 "KillMode=mixed",
94 // Helpers share this cgroup; default OOMPolicy=stop would stop the unit if one is OOM-killed.
95 "OOMPolicy=continue",
96 "Restart=always",
97 "RestartSec=5",
98 // Weights favor the server over the sibling agents slice; IOWeight needs a delegated io controller.
99 "CPUWeight=1000",
100 "IOWeight=1000",
101 // Reclaim takes the agents' unprotected pages first. The kernel caps this at the
102 // protection of user.slice and user@.service, which only root can grant.
103 "MemoryLow=1536M",
104 // A user manager's own score, the lowest it may set: below its other services (200) and agents (800).
105 // `t3 service protect` lowers it further through a drop-in.
106 "OOMScoreAdjust=100",
107 // systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is.
108 "ManagedOOMPreference=avoid",
109 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
110 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
111 "",
112 "[Install]",
113 "WantedBy=default.target",
114 "",
115 ].join("\n");
116}
117
118function escapeXmlText(value: string): string {
119 return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
120}
121
122/** Launch agents cannot rely on the user's shell or PATH. */
123export function renderBootServicePlist(
124 plan: BootServicePlan,
125 options: { readonly homeDir: string; readonly environmentPath: string },
126): string {
127 // Allow 90s stops for update handoffs.
128 // Interactive avoids background throttling.
129 // AbandonProcessGroup=false reaps agents only on launcher exit, preserving them across child updates.
130 return [
131 `<?xml version="1.0" encoding="UTF-8"?>`,
132 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
133 `<plist version="1.0">`,
134 `<dict>`,
135 ` <key>Label</key>`,
136 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
137 ` <key>ProgramArguments</key>`,
138 ` <array>`,
139 ...plan.program.map((argument) => ` <string>${escapeXmlText(argument)}</string>`),
140 ` </array>`,
141 ` <key>EnvironmentVariables</key>`,
142 ` <dict>`,
143 ` <key>PATH</key>`,
144 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
145 ` <key>T3CODE_HOME</key>`,
146 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
147 ` <key>${SERVICE_UNIT_ENV}</key>`,
148 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
149 ` </dict>`,
150 ` <key>WorkingDirectory</key>`,
151 ` <string>${escapeXmlText(options.homeDir)}</string>`,
152 ` <key>RunAtLoad</key>`,
153 ` <true/>`,
154 ` <key>KeepAlive</key>`,
155 ` <true/>`,
156 ` <key>ThrottleInterval</key>`,
157 ` <integer>5</integer>`,
158 ` <key>ExitTimeOut</key>`,
159 ` <integer>90</integer>`,
160 ` <key>ProcessType</key>`,
161 ` <string>Interactive</string>`,
162 ` <key>StandardOutPath</key>`,
163 ` <string>${escapeXmlText(plan.logPath)}</string>`,
164 ` <key>StandardErrorPath</key>`,
165 ` <string>${escapeXmlText(plan.logPath)}</string>`,
166 `</dict>`,
167 `</plist>`,
168 ``,
169 ].join("\n");
170}
171
172export interface BootServiceStep {
173 readonly step: string;
174 readonly command: string;
175 readonly args: ReadonlyArray<string>;
176 /** Non-zero exit is logged and ignored. */
177 readonly optional?: boolean;
178 readonly timeout?: Duration.Input;
179}
180
181/** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */
182const STOP_STEP_TIMEOUT = Duration.seconds(120);
183
184export interface BootServiceManager {
185 readonly kind: "systemd" | "launchd";
186 readonly unitPath: string;
187 readonly render: (plan: BootServicePlan) => string;
188 readonly stop: ReadonlyArray<BootServiceStep>;
189 readonly activate: ReadonlyArray<BootServiceStep>;
190 readonly restart: ReadonlyArray<BootServiceStep>;
191 /** Queue a restart owned by the manager, since stopping would kill the caller. */
192 readonly handoff?: ReadonlyArray<BootServiceStep>;
193 readonly deactivate: ReadonlyArray<BootServiceStep>;
194 readonly finalize: ReadonlyArray<BootServiceStep>;
195}
196
197const defaultSystemdUnitDir = (path: Path.Path, homeDir: string, xdgConfigHome: string) =>
198 path.join(
199 path.isAbsolute(xdgConfigHome) ? xdgConfigHome : path.join(homeDir, ".config"),
200 "systemd",
201 "user",
202 );
203
204const launchdPlistPath = (path: Path.Path, homeDir: string) =>
205 path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE);
206
207function systemdManager(input: {
208 readonly path: Path.Path;
209 readonly unitDir: string;
210}): BootServiceManager {
211 const unitPath = input.path.join(input.unitDir, BOOT_SERVICE_UNIT_FILE);
212 const prepareActivation = [
213 {
214 step: "reloading systemd user units",
215 command: "systemctl",
216 args: ["--user", "daemon-reload"],
217 },
218 {
219 step: "enabling the service",
220 command: "systemctl",
221 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
222 },
223 ];
224 return {
225 kind: "systemd",
226 unitPath,
227 render: renderBootServiceUnit,
228 stop: [
229 {
230 step: "stopping the installed service",
231 command: "systemctl",
232 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
233 timeout: STOP_STEP_TIMEOUT,
234 },
235 ],
236 activate: [
237 ...prepareActivation,
238 {
239 step: "starting the service",
240 command: "systemctl",
241 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
242 },
243 ],
244 restart: [
245 {
246 step: "restarting the service after a failed update",
247 command: "systemctl",
248 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
249 },
250 ],
251 handoff: [
252 ...prepareActivation,
253 {
254 step: "restarting the service",
255 command: "systemctl",
256 args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],
257 },
258 ],
259 deactivate: [
260 {
261 step: "stopping the service",
262 command: "systemctl",
263 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
264 timeout: STOP_STEP_TIMEOUT,
265 },
266 ],
267 finalize: [
268 {
269 step: "reloading systemd user units",
270 command: "systemctl",
271 args: ["--user", "daemon-reload"],
272 },
273 ],
274 };
275}
276
277function launchdManager(input: {
278 readonly path: Path.Path;
279 readonly homeDir: string;
280 readonly uid: number;
281 readonly environmentPath: string;
282}): BootServiceManager {
283 const unitPath = launchdPlistPath(input.path, input.homeDir);
284 const domainTarget = `gui/${input.uid}`;
285 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
286 // Unloaded jobs may reject bootout/enable. Bootstrap starts RunAtLoad/KeepAlive jobs; kickstart would restart them.
287 return {
288 kind: "launchd",
289 unitPath,
290 render: (plan) =>
291 renderBootServicePlist(plan, {
292 homeDir: input.homeDir,
293 environmentPath: input.environmentPath,
294 }),
295 // bootout --wait is undocumented but waits through ExitTimeOut, preventing bootstrap EIO races.
296 stop: [
297 {
298 step: "stopping the installed launch agent",
299 command: "launchctl",
300 args: ["bootout", "--wait", serviceTarget],
301 optional: true,
302 timeout: STOP_STEP_TIMEOUT,
303 },
304 ],
305 activate: [
306 // A persisted `launchctl disable` override refuses bootstrap; clear it.
307 {
308 step: "enabling the launch agent",
309 command: "launchctl",
310 args: ["enable", serviceTarget],
311 optional: true,
312 },
313 {
314 step: "starting the service",
315 command: "launchctl",
316 args: ["bootstrap", domainTarget, unitPath],
317 },
318 ],
319 restart: [
320 {
321 step: "restarting the service after a failed update",
322 command: "launchctl",
323 args: ["bootstrap", domainTarget, unitPath],
324 },
325 ],
326 // Persisted launchctl disable overrides would block reinstall.
327 deactivate: [
328 {
329 step: "stopping the service",
330 command: "launchctl",
331 args: ["bootout", "--wait", serviceTarget],
332 optional: true,
333 timeout: STOP_STEP_TIMEOUT,
334 },
335 ],
336 finalize: [],
337 };
338}
339
340function selectBootServiceManager(input: {
341 readonly platform: NodeJS.Platform;
342 readonly homeDir: string;
343 readonly xdgConfigHome: string;
344 readonly systemdUnitDir: string | undefined;
345 readonly uid: number | undefined;
346 readonly path: Path.Path;
347 readonly environmentPath: string;
348}): BootServiceManager | undefined {
349 if (input.homeDir === "") {
350 return undefined;
351 }
352 if (input.platform === "linux") {
353 return systemdManager({
354 path: input.path,
355 unitDir:
356 input.systemdUnitDir ??
357 defaultSystemdUnitDir(input.path, input.homeDir, input.xdgConfigHome),
358 });
359 }
360 if (input.platform === "darwin" && input.uid !== undefined) {
361 return launchdManager({
362 path: input.path,
363 homeDir: input.homeDir,
364 uid: input.uid,
365 environmentPath: input.environmentPath,
366 });
367 }
368 return undefined;
369}
370
371const decodeSystemdUnitPaths = Schema.decodeUnknownEffect(
372 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
373);
374
375// The manager may not share the installer's environment; JSON preserves spaces in its paths.
376const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit_directory")(
377 function* (runner: ProcessRunner.ProcessRunner["Service"], path: Path.Path) {
378 const result = yield* runner.run({
379 command: "busctl",
380 args: [
381 "--user",
382 "--json=short",
383 "get-property",
384 "org.freedesktop.systemd1",
385 "/org/freedesktop/systemd1",
386 "org.freedesktop.systemd1.Manager",
387 "UnitPath",
388 ],
389 timeout: Duration.seconds(5),
390 });
391 if (result.code !== 0) return undefined;
392 const { data } = yield* decodeSystemdUnitPaths(result.stdout);
393 // The persistent control directory identifies the manager's config root despite UnitPath overrides.
394 const controlDirectory = data.find(
395 (directory) =>
396 path.isAbsolute(directory) &&
397 directory.endsWith("/systemd/user.control") &&
398 data.includes(directory.slice(0, -".control".length)),
399 );
400 return controlDirectory?.slice(0, -".control".length);
401 },
402 Effect.orElseSucceed(() => undefined),
403);
404
405/** Where this platform's service manager keeps the unit, whether or not one is installed. */
406export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(function* () {
407 const path = yield* Path.Path;
408 const platform = yield* HostProcess.Platform;
409 const homeDir = yield* HostProcess.HomeDirectory;
410 if (homeDir === "") return undefined;
411 if (platform === "darwin") return launchdPlistPath(path, homeDir);
412 if (platform !== "linux") return undefined;
413 const unitDir =
414 (yield* readSystemdUnitDirectory()) ??
415 defaultSystemdUnitDir(path, homeDir, (yield* HostProcess.Environment).XDG_CONFIG_HOME ?? "");
416 return path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
417});
418
419export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
420 "BootServiceUnsupportedError",
421 { platform: Schema.String },
422) {
423 override get message(): string {
424 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
425 }
426}
427
428export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
429 "BootServiceCommandError",
430 {
431 step: Schema.String,
432 exitCode: Schema.optional(Schema.Number),
433 stdoutLength: Schema.optional(Schema.Number),
434 stderrLength: Schema.optional(Schema.Number),
435 cause: Schema.optional(Schema.Defect()),
436 },
437) {
438 override get message(): string {
439 return this.exitCode === undefined
440 ? `Background setup failed while ${this.step}.`
441 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
442 }
443}
444
445export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
446 "BootServiceInstallError",
447 { cause: Schema.Defect() },
448) {
449 override get message(): string {
450 return "Could not set up the T3 Code background service.";
451 }
452}
453
454const BootServiceProblem = Schema.Literals([
455 "user-manager-unavailable",
456 "linger-unavailable",
457 "linger-disabled",
458 "service-disabled",
459 "service-stopped",
460 "restart-pending",
461]);
462type BootServiceProblem = typeof BootServiceProblem.Type;
463
464export function formatBootServiceProblem(problem: BootServiceProblem): string {
465 switch (problem) {
466 case "user-manager-unavailable":
467 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.";
468 case "linger-unavailable":
469 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.';
470 case "linger-disabled":
471 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.';
472 case "service-disabled":
473 return "The service is not enabled to start automatically. Run `t3 service install` to repair it.";
474 case "service-stopped":
475 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service install`.";
476 case "restart-pending":
477 return "A newer version is installed but the service is still running the previous one. Run `t3 service restart` to switch.";
478 }
479}
480
481export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
482 "BootServicePrerequisiteError",
483 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
484) {
485 override get message(): string {
486 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
487 }
488}
489
490export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
491 "BootServiceUpdatePendingError",
492 { recoveryCommand: Schema.optional(Schema.String) },
493) {
494 override get message(): string {
495 if (this.recoveryCommand !== undefined) {
496 return `A remote server update is still pending, but its service definition is missing. With the service stopped, run this on the server machine: ${this.recoveryCommand}\nWait for the update to finish or roll back, stop the foreground launcher with Ctrl-C, then retry the install.`;
497 }
498 return "A remote server update is still pending. Wait for it to finish, then retry.";
499 }
500}
501
502export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
503 "BootServiceDowngradeRefusedError",
504 {
505 installedVersion: Schema.String,
506 targetVersion: Schema.String,
507 },
508) {
509 override get message(): string {
510 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
511 }
512}
513
514export const formatBootServiceBaseDirOption = (baseDir: string) =>
515 `--base-dir '${baseDir.replaceAll("'", `'"'"'`)}'`;
516
517export class BootServiceOtherBaseDirError extends Schema.TaggedError<BootServiceOtherBaseDirError>()(
518 "BootServiceOtherBaseDirError",
519 {
520 installedBaseDir: Schema.String,
521 baseDir: Schema.String,
522 },
523) {
524 override get message(): string {
525 return `The T3 Code service on this machine serves ${this.installedBaseDir}, not ${this.baseDir}. Pass ${formatBootServiceBaseDirOption(this.installedBaseDir)} to manage it, or run \`t3 service uninstall ${formatBootServiceBaseDirOption(this.installedBaseDir)}\` first to move it; both data directories are kept.`;
526 }
527
528 // A refusal the user fixes by rerunning, so the CLI prints the message, not a stack trace.
529 override get [CliError.userMessage]() {
530 return this.message;
531 }
532}
533
534export type BootServiceError =
535 | BootServiceUnsupportedError
536 | BootServiceOtherBaseDirError
537 | BootServiceCommandError
538 | BootServiceInstallError
539 | BootServicePrerequisiteError
540 | BootServiceUpdatePendingError
541 | BootServiceDowngradeRefusedError;
542
543export interface BootServiceStatus {
544 readonly supported: boolean;
545 readonly installed: boolean;
546 readonly current: boolean;
547 readonly installedVersion?: string;
548 readonly installedBaseDir?: string;
549 /** Set when the installed unit serves a different T3 home than this CLI. */
550 readonly otherBaseDir?: string;
551 readonly problems?: ReadonlyArray<BootServiceProblem>;
552 readonly unitPath: string;
553 readonly logPath: string;
554}
555
556export class BootService extends Context.Service<
557 BootService,
558 {
559 readonly install: (options?: {
560 readonly allowDowngrade?: boolean;
561 readonly start?: boolean;
562 }) => Effect.Effect<BootServicePlan, BootServiceError>;
563 /**
564 * Only when the unit serves this base dir: the unit name is per user, so
565 * another home's service is left alone, which resolves `skipped`. From
566 * inside the service the restart can only be `queued` with the service
567 * manager, since the stop ends this process.
568 */
569 readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;
570 /**
571 * Runs the operation with this home's service stopped; other homes are left alone.
572 * Restores a previously enabled or loaded service even if stopping failed.
573 * The operation's failure takes precedence over a restart failure.
574 */
575 readonly withStopped: <A, E, R>(
576 operation: Effect.Effect<A, E, R>,
577 ) => Effect.Effect<A, E | BootServiceError, R>;
578 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
579 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
580 }
581>()("t3/cloud/bootService") {}
582
583export interface BootServiceHost {
584 readonly execPath: string;
585}
586
587export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
588 readonly baseDir: string;
589 readonly logsDir: string;
590 readonly cliVersion: string;
591 readonly host?: BootServiceHost;
592}) {
593 const hostExecPath = yield* HostProcess.ExecutablePath;
594 const platform = yield* HostProcess.Platform;
595 const arch = yield* HostProcess.Architecture;
596 const uid = yield* HostProcess.UserId;
597 const httpClient = yield* HttpClient.HttpClient;
598 const releaseBaseUrl = Option.getOrUndefined(
599 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
600 );
601 const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));
602 const xdgConfigHome = yield* Config.String("XDG_CONFIG_HOME").pipe(Config.withDefault(""));
603 const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
604 const xdgRuntimeDir = yield* Config.String("XDG_RUNTIME_DIR").pipe(Config.withDefault(""));
605 // Root under sudo must not reach or start a separate root service.
606 const rootUnderSudo =
607 uid === 0 && (yield* Config.String("SUDO_USER").pipe(Config.withDefault(""))) !== "";
608 const runningInsideService =
609 (yield* Config.String(SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
610 BOOT_SERVICE_UNIT_FILE;
611 const fs = yield* FileSystem.FileSystem;
612 const path = yield* Path.Path;
613 const processRunner = yield* ProcessRunner.ProcessRunner;
614 // Without a login session nothing sets this, so `--user` commands cannot find the user bus.
615 // The directory only appears once lingering starts the manager, so it need not exist yet.
616 const userManagerEnv =
617 platform === "linux" && xdgRuntimeDir === "" && uid !== undefined && !rootUnderSudo
618 ? { XDG_RUNTIME_DIR: `/run/user/${uid}` }
619 : undefined;
620 const runner: ProcessRunner.ProcessRunner["Service"] =
621 userManagerEnv === undefined
622 ? processRunner
623 : {
624 run: (request) =>
625 processRunner.run({ ...request, env: { ...userManagerEnv, ...request.env } }),
626 };
627 const host = input.host ?? { execPath: hostExecPath };
628 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
629 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
630 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
631 (directory) =>
632 directory.length > 0 &&
633 Array.from(directory).every((character) => {
634 const code = character.charCodeAt(0);
635 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
636 }),
637 );
638 // During an update, the running CLI and a PATH inherited from the service name the runtime
639 // being replaced. The service and its agent shells should find the runtime it starts.
640 const environmentPath = Array.from(
641 new Set(
642 [
643 ...xmlSafeInstallerDirectories,
644 path.dirname(host.execPath),
645 "/opt/homebrew/bin",
646 "/usr/local/bin",
647 "/usr/bin",
648 "/bin",
649 "/usr/sbin",
650 "/sbin",
651 ].map((directory) =>
652 launcherOwnsVersionsDir(path, versionsDir, directory) ? runtimePaths.versionDir : directory,
653 ),
654 ),
655 ).join(":");
656
657 const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
658 const resolveTarget = (systemdUnitDir: string | undefined) => {
659 const manager = selectBootServiceManager({
660 platform,
661 homeDir,
662 xdgConfigHome,
663 systemdUnitDir,
664 uid,
665 path,
666 environmentPath,
667 });
668 const unitPath = manager?.unitPath ?? "";
669 const plan: BootServicePlan = {
670 program: [runtimePaths.entryPath, "__service-launcher"],
671 baseDir: input.baseDir,
672 logPath,
673 unitPath,
674 };
675 return { manager, unitPath, plan };
676 };
677 let systemdUnitDir =
678 platform === "linux" ? yield* readSystemdUnitDirectory(runner, path) : undefined;
679 let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir);
680 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
681 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
682 const otherBaseDirOf = (unit: string) => {
683 const installedBaseDir = bootServiceBaseDirOf(unit);
684 return installedBaseDir !== undefined &&
685 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
686 ? installedBaseDir
687 : undefined;
688 };
689 const writeDurably = (filePath: string, contents: string) =>
690 Effect.scoped(
691 Effect.gen(function* () {
692 const directory = path.dirname(filePath);
693 yield* fs.makeDirectory(directory, { recursive: true });
694 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
695 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
696 // Opened read-write: Windows refuses to flush a handle without write access.
697 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
698 yield* fs.rename(tempPath, filePath);
699 // Windows has no directory fsync (EPERM); NTFS journals the rename.
700 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
701 Effect.catchIf(
702 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
703 () => Effect.void,
704 ),
705 );
706 }),
707 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
708 const requireManager = Effect.suspend(() =>
709 detectedManager === undefined
710 ? new BootServiceUnsupportedError({ platform })
711 : Effect.succeed(detectedManager),
712 );
713
714 const logFailure = (error: { readonly message: string }) =>
715 DateTime.now.pipe(
716 Effect.flatMap((now) =>
717 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
718 ),
719 Effect.ignore,
720 );
721
722 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
723 step: string,
724 command: string,
725 args: ReadonlyArray<string>,
726 options?: { readonly timeout?: Duration.Input },
727 ) {
728 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
729 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
730 Effect.filterOrFail(
731 (result) => result.code === 0,
732 (result) =>
733 new BootServiceCommandError({
734 step,
735 exitCode: Number(result.code),
736 stdoutLength: result.stdout.length,
737 stderrLength: result.stderr.length,
738 }),
739 ),
740 Effect.tapError(logFailure),
741 );
742 });
743
744 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
745 Effect.forEach(
746 steps,
747 (entry) => {
748 const run = runStep(
749 entry.step,
750 entry.command,
751 entry.args,
752 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
753 );
754 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
755 },
756 { discard: true },
757 );
758
759 const probe = (command: string, args: ReadonlyArray<string>) =>
760 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
761 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
762 Option.isSome(result) && result.value.code === 0;
763 const lingerArgs = [
764 "show-user",
765 ...(uid === undefined ? [] : [String(uid)]),
766 "--property=Linger",
767 "--value",
768 ];
769 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
770 includeService: boolean,
771 ) {
772 const [manager, linger] = yield* Effect.all(
773 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
774 { concurrency: "unbounded" },
775 );
776 const problems: BootServiceProblem[] = [];
777 if (!succeeded(manager)) problems.push("user-manager-unavailable");
778 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
779 if (lingering !== "yes") {
780 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
781 }
782 if (includeService && succeeded(manager)) {
783 const [enabled, active] = yield* Effect.all(
784 [
785 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
786 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
787 ],
788 { concurrency: "unbounded" },
789 );
790 if (
791 !succeeded(enabled) ||
792 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
793 ) {
794 problems.push("service-disabled");
795 }
796 if (!succeeded(active)) problems.push("service-stopped");
797 }
798 return problems;
799 });
800
801 const requireSystemdPrerequisites = Effect.gen(function* () {
802 const problems = yield* readSystemdProblems(false);
803 const firstProblem = problems[0];
804 if (firstProblem === undefined) return;
805 // Logind reports a user without a session, whose manager is not running yet, as linger-unavailable.
806 const withoutSession =
807 problems.includes("linger-unavailable") && problems.includes("user-manager-unavailable");
808 const lingerDisabled = problems.includes("linger-disabled");
809 if (rootUnderSudo || (!lingerDisabled && !withoutSession)) {
810 return yield* new BootServicePrerequisiteError({ problem: firstProblem });
811 }
812 yield* runStep("enabling lingering for this user", "loginctl", [
813 "enable-linger",
814 "--no-ask-password",
815 ...(uid === undefined ? [] : [String(uid)]),
816 ]).pipe(
817 Effect.mapError(
818 // Without a session this also fails on hosts that do not run systemd at all.
819 (cause) =>
820 new BootServicePrerequisiteError({
821 problem: lingerDisabled ? "linger-disabled" : firstProblem,
822 cause,
823 }),
824 ),
825 );
826 // Lingering starts the user manager asynchronously.
827 const remaining = yield* readSystemdProblems(false).pipe(
828 Effect.repeat({
829 schedule: Schedule.spaced("500 millis"),
830 times: 10,
831 while: (current) => current.includes("user-manager-unavailable"),
832 }),
833 );
834 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
835 });
836
837 const withSelectionLock = <A, E, R>(selectionPath: string, operation: Effect.Effect<A, E, R>) =>
838 Effect.acquireUseRelease(
839 Effect.tryPromise({
840 try: () => acquireServiceSelectionLock(selectionPath),
841 catch: (cause) => new BootServiceInstallError({ cause }),
842 }),
843 () => operation,
844 (release) => Effect.sync(release),
845 );
846
847 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
848 readonly allowDowngrade?: boolean;
849 readonly start?: boolean;
850 }) {
851 let manager = yield* requireManager;
852 // The unit is per user. Rewriting one that serves another home moves the
853 // service onto this home's data, which looks like every thread vanished.
854 const refuseOtherBaseDir = Effect.gen(function* () {
855 const existingUnit = yield* fs.readFileString(unitPath).pipe(Effect.option);
856 const installedBaseDir = Option.isSome(existingUnit)
857 ? otherBaseDirOf(existingUnit.value)
858 : undefined;
859 if (installedBaseDir !== undefined) {
860 return yield* new BootServiceOtherBaseDirError({
861 installedBaseDir,
862 baseDir: input.baseDir,
863 });
864 }
865 });
866 yield* refuseOtherBaseDir;
867 yield* fs
868 .makeDirectory(input.logsDir, { recursive: true })
869 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
870
871 if (manager.kind === "systemd") {
872 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
873 // Without a session the manager was unreachable at construction, and the one lingering
874 // started may use another config root than this shell's XDG_CONFIG_HOME.
875 if (systemdUnitDir === undefined) {
876 systemdUnitDir = yield* readSystemdUnitDirectory(runner, path);
877 ({ manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir));
878 manager = yield* requireManager;
879 yield* refuseOtherBaseDir;
880 }
881 }
882
883 yield* ensurePinnedRuntimeInstalled({
884 baseDir: input.baseDir,
885 version: input.cliVersion,
886 fs,
887 path,
888 runner,
889 httpClient,
890 platform,
891 arch,
892 releaseBaseUrl,
893 validate: (runtime) =>
894 runner
895 .run({
896 command: pinnedRuntimeCommand(runtime).command,
897 args: [...pinnedRuntimeCommand(runtime).args, "--version"],
898 timeout: Duration.seconds(30),
899 })
900 .pipe(
901 Effect.mapError(
902 (cause) =>
903 new PinnedRuntimeInstallError({
904 step: "verifying the pinned t3 runtime",
905 cause,
906 }),
907 ),
908 Effect.flatMap((result) => {
909 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
910 return result.code === 0 && reportedVersion === input.cliVersion
911 ? Effect.void
912 : Effect.fail(
913 new PinnedRuntimeInstallError({
914 step: "verifying the pinned t3 runtime",
915 exitCode: Number(result.code),
916 stdoutLength: result.stdout.length,
917 stderrLength: result.stderr.length,
918 }),
919 );
920 }),
921 ),
922 }).pipe(
923 Effect.mapError((error) =>
924 error._tag === "PinnedRuntimeInstallError"
925 ? new BootServiceCommandError({
926 step: error.step,
927 exitCode: error.exitCode,
928 stdoutLength: error.stdoutLength,
929 stderrLength: error.stderrLength,
930 cause: error,
931 })
932 : new BootServiceInstallError({ cause: error }),
933 ),
934 );
935 const installed = yield* fs
936 .exists(unitPath)
937 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
938 // Stop outside the selection lock: the launcher may be waiting to acquire it.
939 const start = options?.start !== false;
940 if (installed && start && runningInsideService && manager.kind === "systemd") {
941 // Stopping the unit from inside it kills this process before the start.
942 // A transient unit runs the same install from outside, stop first, so it
943 // still serialises with a remote update the launcher may be starting.
944 yield* runStep("handing the install to a transient unit", "systemd-run", [
945 "--user",
946 "--collect",
947 "--quiet",
948 // Transient properties reach systemd literally, unlike unit-file specifiers.
949 `--property=StandardOutput=append:${logPath}`,
950 `--property=StandardError=append:${logPath}`,
951 `--setenv=${SERVICE_UNIT_ENV}=`,
952 runtimePaths.entryPath,
953 "service",
954 "install",
955 "--base-dir",
956 // systemd expands $VAR in arguments (not in the executable path).
957 input.baseDir.replaceAll("$", () => "$$"),
958 ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
959 ]);
960 return { ...plan, handedOff: true };
961 }
962 if (installed && start) {
963 yield* runSteps(manager.stop);
964 }
965
966 // State first, then unit. The launcher acquires only one at a time, and a
967 // failure to lock the unit must never prevent its durable update commit.
968 yield* withSelectionLock(
969 statePath,
970 withSelectionLock(
971 unitPath,
972 Effect.gen(function* () {
973 const currentlyInstalled = yield* fs.exists(unitPath);
974 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
975 if (Option.isSome(previousStateText)) {
976 const installedVersion = serviceStateActiveVersion(previousStateText.value);
977 if (serviceStateHasPendingUpdate(previousStateText.value)) {
978 const quote = (word: string) => `'${word.replaceAll("'", "'\\''")}'`;
979 return yield* new BootServiceUpdatePendingError(
980 !currentlyInstalled && installedVersion !== undefined
981 ? {
982 recoveryCommand: `T3CODE_HOME=${quote(input.baseDir)} ${quote(pinnedRuntimePaths(path, input.baseDir, installedVersion, platform).entryPath)} __service-launcher`,
983 }
984 : {},
985 );
986 }
987 // Read the final version after stopping the launcher; a remote update may finish after the status check.
988 if (
989 installedVersion !== undefined &&
990 options?.allowDowngrade !== true &&
991 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
992 ) {
993 return yield* new BootServiceDowngradeRefusedError({
994 installedVersion,
995 targetVersion: input.cliVersion,
996 });
997 }
998 }
999 yield* fs
1000 .makeDirectory(path.dirname(unitPath), { recursive: true })
1001 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1002 // Files can match the new version even when activation fails; keep that install retryable.
1003 yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
1004 yield* writeDurably(
1005 statePath,
1006 // @effect-diagnostics-next-line globalJsonInEffect:off - fixed launcher-owned document.
1007 `${JSON.stringify(
1008 {
1009 protocol: SERVICE_LAUNCHER_PROTOCOL,
1010 activeVersion: input.cliVersion,
1011 } satisfies ServiceState,
1012 null,
1013 2,
1014 )}\n`,
1015 );
1016 if (!start && (currentlyInstalled || Option.isSome(previousStateText))) {
1017 const written = yield* fs.readFileString(statePath);
1018 if (serviceStateActiveVersion(written) !== input.cliVersion) {
1019 return yield* new BootServiceUpdatePendingError();
1020 }
1021 }
1022 yield* writeDurably(unitPath, manager.render(plan));
1023 }),
1024 ),
1025 ).pipe(
1026 Effect.andThen(
1027 Effect.gen(function* () {
1028 if (start) {
1029 yield* runSteps(manager.activate);
1030 yield* withSelectionLock(
1031 statePath,
1032 Effect.gen(function* () {
1033 // A concurrent deferred install may now be waiting for a newer restart.
1034 const selected = parseServiceState(yield* fs.readFileString(statePath));
1035 if (selected?.activeVersion === input.cliVersion && selected.update === undefined) {
1036 yield* fs.remove(restartPendingPath, { force: true });
1037 }
1038 }),
1039 );
1040 }
1041 }),
1042 ),
1043 Effect.mapError((cause) =>
1044 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
1045 ),
1046 Effect.tapError(() =>
1047 installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
1048 ),
1049 );
1050 return plan;
1051 });
1052
1053 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
1054 const manager = yield* requireManager;
1055 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
1056 if (Option.isNone(unit)) return "skipped" as const;
1057 const installedBaseDir = bootServiceBaseDirOf(unit.value);
1058 if (
1059 installedBaseDir === undefined ||
1060 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
1061 ) {
1062 return "skipped" as const;
1063 }
1064 // Writes no state, and the launcher lets an update transition in flight
1065 // finish before the queued stop tears it down.
1066 if (runningInsideService && manager.handoff !== undefined) {
1067 yield* runSteps(manager.handoff);
1068 return "queued" as const;
1069 }
1070 yield* runSteps(manager.stop);
1071 yield* runSteps(manager.activate).pipe(
1072 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
1073 );
1074 yield* fs.remove(restartPendingPath, { force: true });
1075 return "restarted" as const;
1076 }).pipe(
1077 Effect.mapError((cause) =>
1078 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
1079 ),
1080 Effect.withSpan("cloud.boot_service.restart"),
1081 );
1082
1083 const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(
1084 operation: Effect.Effect<A, E, R>,
1085 ): Effect.fn.Return<A, E | BootServiceError, R> {
1086 if (detectedManager === undefined) return yield* operation;
1087 const manager = detectedManager;
1088 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
1089 if (Option.isNone(unit)) return yield* operation;
1090 const installedBaseDir = bootServiceBaseDirOf(unit.value);
1091 if (
1092 installedBaseDir === undefined ||
1093 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
1094 ) {
1095 return yield* operation;
1096 }
1097 // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid.
1098 // Always stop; restore only if previously active, enabled, or loaded,
1099 // so disabled crash loops stay stopped.
1100 const restore =
1101 manager.kind === "systemd"
1102 ? yield* Effect.map(
1103 Effect.all(
1104 [
1105 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
1106 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
1107 ],
1108 { concurrency: "unbounded" },
1109 ),
1110 ([enabled, active]) => succeeded(active) || succeeded(enabled),
1111 )
1112 : succeeded(
1113 yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
1114 );
1115 return yield* Effect.acquireUseRelease(
1116 // Require every stop before repair when restoring, so the server releases the database.
1117 // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job.
1118 // A failed stop may still stop the service, so restoration runs either way.
1119 runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
1120 (stopped): Effect.Effect<A, E | BootServiceError, R> =>
1121 Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
1122 (_, exit) => {
1123 if (!restore) return Effect.void;
1124 // Start only: `activate` would also enable a unit the user disabled.
1125 // When the operation itself failed, its error is the one worth reporting.
1126 const start = runSteps(manager.restart);
1127 return Exit.isFailure(exit) ? Effect.ignore(start) : start;
1128 },
1129 );
1130 });
1131
1132 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
1133 const manager = yield* requireManager;
1134 if (
1135 !(yield* fs
1136 .exists(unitPath)
1137 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
1138 )
1139 return false;
1140 yield* runSteps(manager.deactivate);
1141 yield* fs
1142 .remove(unitPath)
1143 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1144 yield* runSteps(manager.finalize);
1145 return true;
1146 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
1147
1148 const status: BootService["Service"]["status"] = Effect.gen(function* () {
1149 const manager = detectedManager;
1150 if (manager === undefined) {
1151 return { supported: false, installed: false, current: false, unitPath, logPath };
1152 }
1153 if (!(yield* fs.exists(unitPath))) {
1154 return { supported: true, installed: false, current: false, unitPath, logPath };
1155 }
1156 const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
1157 fs.readFileString(unitPath),
1158 fs.exists(runtimePaths.entryPath),
1159 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
1160 fs.readFileString(statePath).pipe(Effect.option),
1161 ]);
1162 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
1163 const installedVersion = Option.isSome(stateText)
1164 ? serviceStateActiveVersion(stateText.value)
1165 : undefined;
1166 const installedBaseDir = bootServiceBaseDirOf(unit);
1167 const otherBaseDir = otherBaseDirOf(unit);
1168 const normalizeUnit = (contents: string) =>
1169 manager.kind === "launchd"
1170 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
1171 : contents;
1172 const problems: BootServiceProblem[] =
1173 manager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1174 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1175 return {
1176 supported: true,
1177 installed: true,
1178 ...(installedVersion === undefined ? {} : { installedVersion }),
1179 ...(installedBaseDir === undefined ? {} : { installedBaseDir }),
1180 ...(otherBaseDir === undefined ? {} : { otherBaseDir }),
1181 problems,
1182 current:
1183 problems.length === 0 &&
1184 normalizeUnit(unit) === normalizeUnit(manager.render(plan)) &&
1185 runtimeEntryExists &&
1186 Option.isSome(runtimeSentinel) &&
1187 runtimeSentinel.value.trim() === input.cliVersion &&
1188 state?.activeVersion === input.cliVersion &&
1189 state?.update?.status !== "pending",
1190 unitPath,
1191 logPath,
1192 };
1193 }).pipe(
1194 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1195 Effect.withSpan("cloud.boot_service.status"),
1196 );
1197
1198 return BootService.of({ install, restart, withStopped, uninstall, status });
1199});
1200
1201export const layer = (input: {
1202 readonly baseDir: string;
1203 readonly logsDir: string;
1204 readonly cliVersion: string;
1205 readonly host?: BootServiceHost;
1206}) => Layer.effect(BootService, make(input));