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 { step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },
239 // Start last. No administrative state write occurs after this succeeds.
240 {
241 step: "starting the service",
242 command: "systemctl",
243 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
244 },
245 ],
246 restart: [
247 {
248 step: "restarting the service after a failed update",
249 command: "systemctl",
250 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
251 },
252 ],
253 deactivate: [
254 {
255 step: "stopping the service",
256 command: "systemctl",
257 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
258 timeout: STOP_STEP_TIMEOUT,
259 },
260 ],
261 finalize: [
262 {
263 step: "reloading systemd user units",
264 command: "systemctl",
265 args: ["--user", "daemon-reload"],
266 },
267 ],
268 };
269}
270
271function launchdManager(input: {
272 readonly path: Path.Path;
273 readonly homeDir: string;
274 readonly uid: number;
275 readonly environmentPath: string;
276}): BootServiceManager {
277 const unitPath = input.path.join(
278 input.homeDir,
279 "Library",
280 "LaunchAgents",
281 BOOT_SERVICE_PLIST_FILE,
282 );
283 const domainTarget = `gui/${input.uid}`;
284 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
285 // bootout/enable are optional: they fail on not-loaded states that are fine
286 // to proceed from. The strict `bootstrap` runs last and is also the start:
287 // loading a RunAtLoad/KeepAlive plist starts the job, so a separate
288 // kickstart would kill and restart a server it just booted. A lingering job
289 // that survived bootout, or a gui domain with nobody logged in at the
290 // screen (SSH install), makes bootstrap fail the flow loudly rather than
291 // silently keeping a stale server.
292 return {
293 kind: "launchd",
294 unitPath,
295 render: (plan) =>
296 renderBootServicePlist(plan, {
297 homeDir: input.homeDir,
298 environmentPath: input.environmentPath,
299 }),
300 // Without --wait, bootout returns in milliseconds while the job drains
301 // for up to ExitTimeOut, and a bootstrap during the drain fails EIO.
302 // --wait (present on modern macOS, absent from the man page) blocks until
303 // the job is removed from the domain; STOP_STEP_TIMEOUT outlives it.
304 stop: [
305 {
306 step: "stopping the installed launch agent",
307 command: "launchctl",
308 args: ["bootout", "--wait", serviceTarget],
309 optional: true,
310 timeout: STOP_STEP_TIMEOUT,
311 },
312 ],
313 activate: [
314 // A persisted `launchctl disable` override refuses bootstrap; clear it.
315 {
316 step: "enabling the launch agent",
317 command: "launchctl",
318 args: ["enable", serviceTarget],
319 optional: true,
320 },
321 // Start last. No administrative state write occurs after this succeeds.
322 {
323 step: "starting the service",
324 command: "launchctl",
325 args: ["bootstrap", domainTarget, unitPath],
326 },
327 ],
328 restart: [
329 {
330 step: "restarting the service after a failed update",
331 command: "launchctl",
332 args: ["bootstrap", domainTarget, unitPath],
333 },
334 ],
335 // No `launchctl disable` here: a persisted override would sabotage a
336 // later reinstall. Removing the plist is what stops the next login load.
337 // A bootout that fails for a reason other than "not loaded" leaves the
338 // job running until logout; the failure is in the boot-service log.
339 deactivate: [
340 {
341 step: "stopping the service",
342 command: "launchctl",
343 args: ["bootout", "--wait", serviceTarget],
344 optional: true,
345 timeout: STOP_STEP_TIMEOUT,
346 },
347 ],
348 finalize: [],
349 };
350}
351
352/** Undefined means this host cannot run the background service. */
353function selectBootServiceManager(input: {
354 readonly platform: NodeJS.Platform;
355 readonly homeDir: string;
356 readonly uid: number | undefined;
357 readonly path: Path.Path;
358 readonly environmentPath: string;
359}): BootServiceManager | undefined {
360 if (input.homeDir === "") {
361 return undefined;
362 }
363 if (input.platform === "linux") {
364 return systemdManager({ path: input.path, homeDir: input.homeDir });
365 }
366 if (input.platform === "darwin" && input.uid !== undefined) {
367 return launchdManager({
368 path: input.path,
369 homeDir: input.homeDir,
370 uid: input.uid,
371 environmentPath: input.environmentPath,
372 });
373 }
374 return undefined;
375}
376
377export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
378 "BootServiceUnsupportedError",
379 { platform: Schema.String },
380) {
381 override get message(): string {
382 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
383 }
384}
385
386export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
387 "BootServiceCommandError",
388 {
389 step: Schema.String,
390 exitCode: Schema.optional(Schema.Number),
391 stdoutLength: Schema.optional(Schema.Number),
392 stderrLength: Schema.optional(Schema.Number),
393 cause: Schema.optional(Schema.Defect()),
394 },
395) {
396 override get message(): string {
397 return this.exitCode === undefined
398 ? `Background setup failed while ${this.step}.`
399 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
400 }
401}
402
403export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
404 "BootServiceInstallError",
405 { cause: Schema.Defect() },
406) {
407 override get message(): string {
408 return "Could not set up the T3 Code background service.";
409 }
410}
411
412export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
413 "BootServiceUpdatePendingError",
414 {},
415) {
416 override get message(): string {
417 return "A remote server update is still pending. Wait for it to finish, then retry.";
418 }
419}
420
421export class BootServiceDowngradeRefusedError extends Schema.TaggedErrorClass<BootServiceDowngradeRefusedError>()(
422 "BootServiceDowngradeRefusedError",
423 {
424 installedVersion: Schema.String,
425 targetVersion: Schema.String,
426 },
427) {
428 override get message(): string {
429 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
430 }
431}
432
433export type BootServiceError =
434 | BootServiceUnsupportedError
435 | BootServiceCommandError
436 | BootServiceInstallError
437 | BootServiceUpdatePendingError
438 | BootServiceDowngradeRefusedError;
439
440export interface BootServiceStatus {
441 readonly supported: boolean;
442 readonly installed: boolean;
443 readonly current: boolean;
444 readonly installedVersion?: string;
445 readonly unitPath: string;
446 readonly logPath: string;
447}
448
449export class BootService extends Context.Service<
450 BootService,
451 {
452 readonly install: (options?: {
453 readonly allowDowngrade?: boolean;
454 }) => Effect.Effect<BootServicePlan, BootServiceError>;
455 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
456 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
457 }
458>()("t3/cloud/bootService") {}
459
460export interface BootServiceHost {
461 readonly execPath: string;
462 readonly launcherSourcePath?: string;
463}
464
465export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
466 readonly baseDir: string;
467 readonly logsDir: string;
468 readonly cliVersion: string;
469 readonly host?: BootServiceHost;
470}) {
471 const hostExecPath = yield* HostProcessExecutablePath;
472 const platform = yield* HostProcessPlatform;
473 const uid = yield* HostProcessUserId;
474 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
475 const installerPath = yield* Config.string("PATH").pipe(Config.withDefault(""));
476 const fs = yield* FileSystem.FileSystem;
477 const path = yield* Path.Path;
478 const runner = yield* ProcessRunner.ProcessRunner;
479 const host = input.host ?? { execPath: hostExecPath };
480 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
481 (directory) =>
482 directory.length > 0 &&
483 Array.from(directory).every((character) => {
484 const code = character.charCodeAt(0);
485 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
486 }),
487 );
488 const environmentPath = Array.from(
489 new Set([
490 ...xmlSafeInstallerDirectories,
491 path.dirname(host.execPath),
492 "/opt/homebrew/bin",
493 "/usr/local/bin",
494 "/usr/bin",
495 "/bin",
496 "/usr/sbin",
497 "/sbin",
498 ]),
499 ).join(":");
500
501 const detectedManager = selectBootServiceManager({
502 platform,
503 homeDir,
504 uid,
505 path,
506 environmentPath,
507 });
508 const unitPath = detectedManager?.unitPath ?? "";
509 const logPath = path.join(input.logsDir, "boot-service.log");
510 const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
511 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
512 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
513 const launcherSourcePath =
514 host.launcherSourcePath ??
515 path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
516 const writeDurably = (filePath: string, contents: string) =>
517 Effect.scoped(
518 Effect.gen(function* () {
519 const directory = path.dirname(filePath);
520 yield* fs.makeDirectory(directory, { recursive: true });
521 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
522 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
523 yield* (yield* fs.open(tempPath, { flag: "r" })).sync;
524 yield* fs.rename(tempPath, filePath);
525 yield* (yield* fs.open(directory, { flag: "r" })).sync;
526 }),
527 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
528 const plan: BootServicePlan = {
529 nodePath: host.execPath,
530 launcherPath,
531 baseDir: input.baseDir,
532 logPath,
533 unitPath,
534 };
535
536 const requireManager = Effect.suspend(() =>
537 detectedManager === undefined
538 ? new BootServiceUnsupportedError({ platform })
539 : Effect.succeed(detectedManager),
540 );
541
542 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
543 step: string,
544 command: string,
545 args: ReadonlyArray<string>,
546 options?: { readonly timeout?: Duration.Input },
547 ) {
548 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
549 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
550 Effect.filterOrFail(
551 (result) => result.code === 0,
552 (result) =>
553 new BootServiceCommandError({
554 step,
555 exitCode: Number(result.code),
556 stdoutLength: result.stdout.length,
557 stderrLength: result.stderr.length,
558 }),
559 ),
560 Effect.tapError((error) =>
561 DateTime.now.pipe(
562 Effect.flatMap((now) =>
563 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
564 flag: "a",
565 }),
566 ),
567 Effect.ignore,
568 ),
569 ),
570 );
571 });
572
573 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
574 Effect.forEach(
575 steps,
576 (entry) => {
577 const run = runStep(
578 entry.step,
579 entry.command,
580 entry.args,
581 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
582 );
583 // runStep's tapError already appends the failure to the log, so an
584 // ignored optional step still leaves a trace.
585 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
586 },
587 { discard: true },
588 );
589
590 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
591 readonly allowDowngrade?: boolean;
592 }) {
593 const manager = yield* requireManager;
594 yield* fs
595 .makeDirectory(input.logsDir, { recursive: true })
596 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
597
598 // Prepare every immutable artifact before stopping the installed unit.
599 yield* ensurePinnedRuntimeInstalled({
600 baseDir: input.baseDir,
601 version: input.cliVersion,
602 fs,
603 path,
604 runner,
605 validate: (runtime) =>
606 runner
607 .run({
608 command: host.execPath,
609 args: [runtime.entryPath, "--version"],
610 timeout: Duration.seconds(30),
611 })
612 .pipe(
613 Effect.mapError(
614 (cause) =>
615 new PinnedRuntimeInstallError({
616 step: "verifying the pinned t3 runtime",
617 cause,
618 }),
619 ),
620 Effect.flatMap((result) => {
621 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
622 return result.code === 0 && reportedVersion === input.cliVersion
623 ? Effect.void
624 : Effect.fail(
625 new PinnedRuntimeInstallError({
626 step: "verifying the pinned t3 runtime",
627 exitCode: Number(result.code),
628 stdoutLength: result.stdout.length,
629 stderrLength: result.stderr.length,
630 }),
631 );
632 }),
633 ),
634 }).pipe(
635 Effect.mapError((error) =>
636 error._tag === "PinnedRuntimeInstallError"
637 ? new BootServiceCommandError({
638 step: error.step,
639 exitCode: error.exitCode,
640 stdoutLength: error.stdoutLength,
641 stderrLength: error.stderrLength,
642 cause: error,
643 })
644 : new BootServiceInstallError({ cause: error }),
645 ),
646 );
647 const launcherSource = yield* fs
648 .readFileString(launcherSourcePath)
649 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
650
651 const installed = yield* fs
652 .exists(unitPath)
653 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
654 if (installed) {
655 yield* runSteps(manager.stop);
656 }
657
658 yield* Effect.gen(function* () {
659 if (installed) {
660 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
661 if (Option.isSome(previousStateText)) {
662 if (serviceStateHasPendingUpdate(previousStateText.value)) {
663 return yield* new BootServiceUpdatePendingError();
664 }
665 // A remote update can finish after the CLI checks status. Read its
666 // final version after the launcher stops and before changing files.
667 const installedVersion = serviceStateActiveVersion(previousStateText.value);
668 if (
669 installedVersion !== undefined &&
670 options?.allowDowngrade !== true &&
671 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
672 ) {
673 return yield* new BootServiceDowngradeRefusedError({
674 installedVersion,
675 targetVersion: input.cliVersion,
676 });
677 }
678 }
679 }
680 yield* fs
681 .makeDirectory(path.dirname(unitPath), { recursive: true })
682 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
683 yield* writeDurably(launcherPath, launcherSource);
684 yield* writeDurably(
685 statePath,
686 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
687 `${JSON.stringify(
688 {
689 protocol: SERVICE_LAUNCHER_PROTOCOL,
690 activeVersion: input.cliVersion,
691 } satisfies ServiceState,
692 null,
693 2,
694 )}\n`,
695 );
696 yield* writeDurably(unitPath, manager.render(plan));
697
698 yield* runSteps(manager.activate);
699 }).pipe(
700 Effect.tapError(() =>
701 installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
702 ),
703 );
704 return plan;
705 });
706
707 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
708 const manager = yield* requireManager;
709 if (
710 !(yield* fs
711 .exists(unitPath)
712 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
713 )
714 return false;
715 yield* runSteps(manager.deactivate);
716 yield* fs
717 .remove(unitPath)
718 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
719 yield* runSteps(manager.finalize);
720 return true;
721 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
722
723 const status: BootService["Service"]["status"] = Effect.gen(function* () {
724 if (detectedManager === undefined) {
725 return { supported: false, installed: false, current: false, unitPath, logPath };
726 }
727 if (!(yield* fs.exists(unitPath))) {
728 return { supported: true, installed: false, current: false, unitPath, logPath };
729 }
730 const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
731 yield* Effect.all([
732 fs.readFileString(unitPath),
733 fs.exists(launcherPath),
734 fs.exists(runtimePaths.entryPath),
735 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
736 fs.readFileString(statePath).pipe(Effect.option),
737 ]);
738 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
739 const installedVersion = Option.isSome(stateText)
740 ? serviceStateActiveVersion(stateText.value)
741 : undefined;
742 const normalizeUnit = (contents: string) =>
743 detectedManager.kind === "launchd"
744 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
745 : contents;
746 return {
747 supported: true,
748 installed: true,
749 ...(installedVersion === undefined ? {} : { installedVersion }),
750 current:
751 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
752 launcherExists &&
753 runtimeEntryExists &&
754 Option.isSome(runtimeSentinel) &&
755 runtimeSentinel.value.trim() === input.cliVersion &&
756 state?.activeVersion === input.cliVersion &&
757 state?.update?.status !== "pending",
758 unitPath,
759 logPath,
760 };
761 }).pipe(
762 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
763 Effect.withSpan("cloud.boot_service.status"),
764 );
765
766 return BootService.of({ install, uninstall, status });
767});
768
769export const layer = (input: {
770 readonly baseDir: string;
771 readonly logsDir: string;
772 readonly cliVersion: string;
773 readonly host?: BootServiceHost;
774}) => Layer.effect(BootService, make(input));