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 parseServiceState,
28 serviceStateHasPendingUpdate,
29 type ServiceState,
30} from "./serviceProtocol.ts";
31
32const BOOT_SERVICE_NAME = "t3code";
33export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
34// `.service` suffix keeps the label distinct from the desktop app's bundle id
35// (com.t3tools.t3code), so launchd and TCC records never collide.
36export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
37export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
38export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
39
40/** systemd expands `%` specifiers, including in unquoted append-log paths. */
41export function escapeSystemdSpecifiers(value: string): string {
42 return value.replaceAll("%", "%%");
43}
44
45export function quoteSystemdValue(value: string): string {
46 const escaped = escapeSystemdSpecifiers(value);
47 return /[\s"'\\]/.test(escaped)
48 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
49 : escaped;
50}
51
52export interface BootServicePlan {
53 readonly nodePath: string;
54 readonly launcherPath: string;
55 readonly baseDir: string;
56 readonly logPath: string;
57 readonly unitPath: string;
58}
59
60/** Pure renderer: service units cannot rely on the user's shell or PATH. */
61export function renderBootServiceUnit(plan: BootServicePlan): string {
62 // The user manager has no reliable network-online target; server networking retries itself.
63 return [
64 "[Unit]",
65 "Description=T3 Code server",
66 "StartLimitIntervalSec=300",
67 "StartLimitBurst=5",
68 "",
69 "[Service]",
70 "Type=simple",
71 "WorkingDirectory=%h",
72 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
73 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
74 `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
75 // Let the launcher mark an explicit stop before it signals the server.
76 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
77 "KillMode=mixed",
78 // Agent tool calls run as children of the server, so they share this cgroup.
79 // With the systemd default of OOMPolicy=stop, the kernel killing one greedy
80 // child stops the whole unit: the server, every live agent, and the user's
81 // connection. Keep running and let Restart=always cover the main process.
82 "OOMPolicy=continue",
83 "Restart=always",
84 "RestartSec=5",
85 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
86 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
87 "",
88 "[Install]",
89 "WantedBy=default.target",
90 "",
91 ].join("\n");
92}
93
94/** Plist values are emitted as XML text nodes; only these three need escaping. */
95export function escapeXmlText(value: string): string {
96 return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
97}
98
99/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
100export function renderBootServicePlist(
101 plan: BootServicePlan,
102 options: { readonly homeDir: string },
103): string {
104 // KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
105 // has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
106 // ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
107 // completes within the launcher's 5s child grace, but a stop that queues
108 // behind an in-flight update transition can take much longer; launchd's
109 // system-defined default (5s on current macOS) would SIGKILL the launcher
110 // (and, with it, the process group) mid-handoff.
111 // ProcessType Interactive opts out of background-job resource throttling.
112 // AbandonProcessGroup stays at its default (false): launchd reaps leftover
113 // process-group members only when the launcher itself exits — the analog of
114 // KillMode=mixed's final cgroup kill — and not when the launcher restarts its
115 // child, so agent children survive server updates.
116 return [
117 `<?xml version="1.0" encoding="UTF-8"?>`,
118 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
119 `<plist version="1.0">`,
120 `<dict>`,
121 ` <key>Label</key>`,
122 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
123 ` <key>ProgramArguments</key>`,
124 ` <array>`,
125 ` <string>${escapeXmlText(plan.nodePath)}</string>`,
126 ` <string>${escapeXmlText(plan.launcherPath)}</string>`,
127 ` </array>`,
128 ` <key>EnvironmentVariables</key>`,
129 ` <dict>`,
130 ` <key>T3CODE_HOME</key>`,
131 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
132 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
133 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
134 ` </dict>`,
135 ` <key>WorkingDirectory</key>`,
136 ` <string>${escapeXmlText(options.homeDir)}</string>`,
137 ` <key>RunAtLoad</key>`,
138 ` <true/>`,
139 ` <key>KeepAlive</key>`,
140 ` <true/>`,
141 ` <key>ThrottleInterval</key>`,
142 ` <integer>5</integer>`,
143 ` <key>ExitTimeOut</key>`,
144 ` <integer>90</integer>`,
145 ` <key>ProcessType</key>`,
146 ` <string>Interactive</string>`,
147 ` <key>StandardOutPath</key>`,
148 ` <string>${escapeXmlText(plan.logPath)}</string>`,
149 ` <key>StandardErrorPath</key>`,
150 ` <string>${escapeXmlText(plan.logPath)}</string>`,
151 `</dict>`,
152 `</plist>`,
153 ``,
154 ].join("\n");
155}
156
157export interface BootServiceStep {
158 readonly step: string;
159 readonly command: string;
160 readonly args: ReadonlyArray<string>;
161 /**
162 * Non-zero exit is logged and ignored. Reserved for steps whose common
163 * failures (not loaded, already enabled) leave a state a later strict step
164 * either tolerates or fails loudly on.
165 */
166 readonly optional?: boolean;
167 /** Override the ProcessRunner default (60s) for steps that block longer. */
168 readonly timeout?: Duration.Input;
169}
170
171/**
172 * Stop commands block until the service manager gives up: 90s by default for
173 * systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
174 * must stay above both, or the runner cancels the stop mid-shutdown and the
175 * next step races a still-loaded service.
176 */
177const STOP_STEP_TIMEOUT = Duration.seconds(120);
178
179/**
180 * Platform service-manager integration as data: paths, a pure renderer, and
181 * the command steps each flow runs. install/uninstall/status consume this and
182 * never branch on platform.
183 */
184export interface BootServiceManager {
185 readonly kind: "systemd" | "launchd";
186 readonly unitPath: string;
187 readonly render: (plan: BootServicePlan) => string;
188 /** Before rewriting files, when a unit is already installed. */
189 readonly stop: ReadonlyArray<BootServiceStep>;
190 /** After files are written. The last entry starts the service. */
191 readonly activate: ReadonlyArray<BootServiceStep>;
192 /** Best-effort recovery after a failed repair of an installed service. */
193 readonly restart: ReadonlyArray<BootServiceStep>;
194 /** Uninstall, before the unit file is removed. */
195 readonly deactivate: ReadonlyArray<BootServiceStep>;
196 /** Uninstall, after the unit file is removed. */
197 readonly finalize: ReadonlyArray<BootServiceStep>;
198}
199
200export function systemdManager(input: {
201 readonly path: Path.Path;
202 readonly homeDir: string;
203}): BootServiceManager {
204 const unitPath = input.path.join(
205 input.homeDir,
206 ".config",
207 "systemd",
208 "user",
209 BOOT_SERVICE_UNIT_FILE,
210 );
211 return {
212 kind: "systemd",
213 unitPath,
214 render: renderBootServiceUnit,
215 stop: [
216 {
217 step: "stopping the installed service",
218 command: "systemctl",
219 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
220 timeout: STOP_STEP_TIMEOUT,
221 },
222 ],
223 activate: [
224 {
225 step: "reloading systemd user units",
226 command: "systemctl",
227 args: ["--user", "daemon-reload"],
228 },
229 {
230 step: "enabling the service",
231 command: "systemctl",
232 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
233 },
234 { step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },
235 // Start last. No administrative state write occurs after this succeeds.
236 {
237 step: "starting the service",
238 command: "systemctl",
239 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
240 },
241 ],
242 restart: [
243 {
244 step: "restarting the service after a failed update",
245 command: "systemctl",
246 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
247 },
248 ],
249 deactivate: [
250 {
251 step: "stopping the service",
252 command: "systemctl",
253 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
254 timeout: STOP_STEP_TIMEOUT,
255 },
256 ],
257 finalize: [
258 {
259 step: "reloading systemd user units",
260 command: "systemctl",
261 args: ["--user", "daemon-reload"],
262 },
263 ],
264 };
265}
266
267export function launchdManager(input: {
268 readonly path: Path.Path;
269 readonly homeDir: string;
270 readonly uid: number;
271}): BootServiceManager {
272 const unitPath = input.path.join(
273 input.homeDir,
274 "Library",
275 "LaunchAgents",
276 BOOT_SERVICE_PLIST_FILE,
277 );
278 const domainTarget = `gui/${input.uid}`;
279 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
280 // bootout/enable are optional: they fail on not-loaded states that are fine
281 // to proceed from. The strict `bootstrap` runs last and is also the start:
282 // loading a RunAtLoad/KeepAlive plist starts the job, so a separate
283 // kickstart would kill and restart a server it just booted. A lingering job
284 // that survived bootout, or a gui domain with nobody logged in at the
285 // screen (SSH install), makes bootstrap fail the flow loudly rather than
286 // silently keeping a stale server.
287 return {
288 kind: "launchd",
289 unitPath,
290 render: (plan) => renderBootServicePlist(plan, { homeDir: input.homeDir }),
291 // Without --wait, bootout returns in milliseconds while the job drains
292 // for up to ExitTimeOut, and a bootstrap during the drain fails EIO.
293 // --wait (present on modern macOS, absent from the man page) blocks until
294 // the job is removed from the domain; STOP_STEP_TIMEOUT outlives it.
295 stop: [
296 {
297 step: "stopping the installed launch agent",
298 command: "launchctl",
299 args: ["bootout", "--wait", serviceTarget],
300 optional: true,
301 timeout: STOP_STEP_TIMEOUT,
302 },
303 ],
304 activate: [
305 // A persisted `launchctl disable` override refuses bootstrap; clear it.
306 {
307 step: "enabling the launch agent",
308 command: "launchctl",
309 args: ["enable", serviceTarget],
310 optional: true,
311 },
312 // Start last. No administrative state write occurs after this succeeds.
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 // No `launchctl disable` here: a persisted override would sabotage a
327 // later reinstall. Removing the plist is what stops the next login load.
328 // A bootout that fails for a reason other than "not loaded" leaves the
329 // job running until logout; the failure is in the boot-service log.
330 deactivate: [
331 {
332 step: "stopping the service",
333 command: "launchctl",
334 args: ["bootout", "--wait", serviceTarget],
335 optional: true,
336 timeout: STOP_STEP_TIMEOUT,
337 },
338 ],
339 finalize: [],
340 };
341}
342
343/** Undefined means this host cannot run the background service. */
344export function selectBootServiceManager(input: {
345 readonly platform: NodeJS.Platform;
346 readonly homeDir: string;
347 readonly uid: number | undefined;
348 readonly path: Path.Path;
349}): BootServiceManager | undefined {
350 if (input.homeDir === "") {
351 return undefined;
352 }
353 if (input.platform === "linux") {
354 return systemdManager({ path: input.path, homeDir: input.homeDir });
355 }
356 if (input.platform === "darwin" && input.uid !== undefined) {
357 return launchdManager({ path: input.path, homeDir: input.homeDir, uid: input.uid });
358 }
359 return undefined;
360}
361
362export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
363 "BootServiceUnsupportedError",
364 { platform: Schema.String },
365) {
366 override get message(): string {
367 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
368 }
369}
370
371export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
372 "BootServiceCommandError",
373 {
374 step: Schema.String,
375 exitCode: Schema.optional(Schema.Number),
376 stdoutLength: Schema.optional(Schema.Number),
377 stderrLength: Schema.optional(Schema.Number),
378 cause: Schema.optional(Schema.Defect()),
379 },
380) {
381 override get message(): string {
382 return this.exitCode === undefined
383 ? `Background setup failed while ${this.step}.`
384 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
385 }
386}
387
388export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
389 "BootServiceInstallError",
390 { cause: Schema.Defect() },
391) {
392 override get message(): string {
393 return "Could not set up the T3 Code background service.";
394 }
395}
396
397export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
398 "BootServiceUpdatePendingError",
399 {},
400) {
401 override get message(): string {
402 return "A remote server update is still pending. Wait for it to finish, then retry.";
403 }
404}
405
406export type BootServiceError =
407 | BootServiceUnsupportedError
408 | BootServiceCommandError
409 | BootServiceInstallError
410 | BootServiceUpdatePendingError;
411
412export interface BootServiceStatus {
413 readonly supported: boolean;
414 readonly installed: boolean;
415 readonly current: boolean;
416 readonly unitPath: string;
417 readonly logPath: string;
418}
419
420export class BootService extends Context.Service<
421 BootService,
422 {
423 readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
424 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
425 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
426 }
427>()("t3/cloud/bootService") {}
428
429export interface BootServiceHost {
430 readonly execPath: string;
431 readonly launcherSourcePath?: string;
432}
433
434export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
435 readonly baseDir: string;
436 readonly logsDir: string;
437 readonly cliVersion: string;
438 readonly host?: BootServiceHost;
439}) {
440 const hostExecPath = yield* HostProcessExecutablePath;
441 const platform = yield* HostProcessPlatform;
442 const uid = yield* HostProcessUserId;
443 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
444 const fs = yield* FileSystem.FileSystem;
445 const path = yield* Path.Path;
446 const runner = yield* ProcessRunner.ProcessRunner;
447 const host = input.host ?? { execPath: hostExecPath };
448
449 const detectedManager = selectBootServiceManager({ platform, homeDir, uid, path });
450 const unitPath = detectedManager?.unitPath ?? "";
451 const logPath = path.join(input.logsDir, "boot-service.log");
452 const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
453 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
454 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
455 const launcherSourcePath =
456 host.launcherSourcePath ??
457 path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
458 const writeDurably = (filePath: string, contents: string) =>
459 Effect.scoped(
460 Effect.gen(function* () {
461 const directory = path.dirname(filePath);
462 yield* fs.makeDirectory(directory, { recursive: true });
463 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
464 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
465 yield* (yield* fs.open(tempPath, { flag: "r" })).sync;
466 yield* fs.rename(tempPath, filePath);
467 yield* (yield* fs.open(directory, { flag: "r" })).sync;
468 }),
469 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
470 const plan: BootServicePlan = {
471 nodePath: host.execPath,
472 launcherPath,
473 baseDir: input.baseDir,
474 logPath,
475 unitPath,
476 };
477
478 const requireManager = Effect.suspend(() =>
479 detectedManager === undefined
480 ? new BootServiceUnsupportedError({ platform })
481 : Effect.succeed(detectedManager),
482 );
483
484 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
485 step: string,
486 command: string,
487 args: ReadonlyArray<string>,
488 options?: { readonly timeout?: Duration.Input },
489 ) {
490 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
491 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
492 Effect.filterOrFail(
493 (result) => result.code === 0,
494 (result) =>
495 new BootServiceCommandError({
496 step,
497 exitCode: Number(result.code),
498 stdoutLength: result.stdout.length,
499 stderrLength: result.stderr.length,
500 }),
501 ),
502 Effect.tapError((error) =>
503 DateTime.now.pipe(
504 Effect.flatMap((now) =>
505 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
506 flag: "a",
507 }),
508 ),
509 Effect.ignore,
510 ),
511 ),
512 );
513 });
514
515 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
516 Effect.forEach(
517 steps,
518 (entry) => {
519 const run = runStep(
520 entry.step,
521 entry.command,
522 entry.args,
523 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
524 );
525 // runStep's tapError already appends the failure to the log, so an
526 // ignored optional step still leaves a trace.
527 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
528 },
529 { discard: true },
530 );
531
532 const install: BootService["Service"]["install"] = Effect.gen(function* () {
533 const manager = yield* requireManager;
534 yield* fs
535 .makeDirectory(input.logsDir, { recursive: true })
536 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
537
538 // Prepare every immutable artifact before stopping the installed unit.
539 yield* ensurePinnedRuntimeInstalled({
540 baseDir: input.baseDir,
541 version: input.cliVersion,
542 fs,
543 path,
544 runner,
545 validate: (runtime) =>
546 runner
547 .run({
548 command: host.execPath,
549 args: [runtime.entryPath, "--version"],
550 timeout: Duration.seconds(30),
551 })
552 .pipe(
553 Effect.mapError(
554 (cause) =>
555 new PinnedRuntimeInstallError({
556 step: "verifying the pinned t3 runtime",
557 cause,
558 }),
559 ),
560 Effect.flatMap((result) => {
561 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
562 return result.code === 0 && reportedVersion === input.cliVersion
563 ? Effect.void
564 : Effect.fail(
565 new PinnedRuntimeInstallError({
566 step: "verifying the pinned t3 runtime",
567 exitCode: Number(result.code),
568 stdoutLength: result.stdout.length,
569 stderrLength: result.stderr.length,
570 }),
571 );
572 }),
573 ),
574 }).pipe(
575 Effect.mapError((error) =>
576 error._tag === "PinnedRuntimeInstallError"
577 ? new BootServiceCommandError({
578 step: error.step,
579 exitCode: error.exitCode,
580 stdoutLength: error.stdoutLength,
581 stderrLength: error.stderrLength,
582 cause: error,
583 })
584 : new BootServiceInstallError({ cause: error }),
585 ),
586 );
587 const launcherSource = yield* fs
588 .readFileString(launcherSourcePath)
589 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
590
591 const installed = yield* fs
592 .exists(unitPath)
593 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
594 if (installed) {
595 yield* runSteps(manager.stop);
596 }
597
598 yield* Effect.gen(function* () {
599 if (installed) {
600 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
601 if (
602 Option.isSome(previousStateText) &&
603 serviceStateHasPendingUpdate(previousStateText.value)
604 ) {
605 return yield* new BootServiceUpdatePendingError();
606 }
607 }
608 yield* fs
609 .makeDirectory(path.dirname(unitPath), { recursive: true })
610 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
611 yield* writeDurably(launcherPath, launcherSource);
612 yield* writeDurably(
613 statePath,
614 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
615 `${JSON.stringify(
616 {
617 protocol: SERVICE_LAUNCHER_PROTOCOL,
618 activeVersion: input.cliVersion,
619 } satisfies ServiceState,
620 null,
621 2,
622 )}\n`,
623 );
624 yield* writeDurably(unitPath, manager.render(plan));
625
626 yield* runSteps(manager.activate);
627 }).pipe(
628 Effect.tapError(() =>
629 installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
630 ),
631 );
632 return plan;
633 }).pipe(Effect.withSpan("cloud.boot_service.install"));
634
635 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
636 const manager = yield* requireManager;
637 if (
638 !(yield* fs
639 .exists(unitPath)
640 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
641 )
642 return false;
643 yield* runSteps(manager.deactivate);
644 yield* fs
645 .remove(unitPath)
646 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
647 yield* runSteps(manager.finalize);
648 return true;
649 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
650
651 const status: BootService["Service"]["status"] = Effect.gen(function* () {
652 if (detectedManager === undefined) {
653 return { supported: false, installed: false, current: false, unitPath, logPath };
654 }
655 if (!(yield* fs.exists(unitPath))) {
656 return { supported: true, installed: false, current: false, unitPath, logPath };
657 }
658 const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
659 yield* Effect.all([
660 fs.readFileString(unitPath),
661 fs.exists(launcherPath),
662 fs.exists(runtimePaths.entryPath),
663 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
664 fs.readFileString(statePath).pipe(Effect.option),
665 ]);
666 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
667 return {
668 supported: true,
669 installed: true,
670 current:
671 unit === detectedManager.render(plan) &&
672 launcherExists &&
673 runtimeEntryExists &&
674 Option.isSome(runtimeSentinel) &&
675 runtimeSentinel.value.trim() === input.cliVersion &&
676 state?.activeVersion === input.cliVersion &&
677 state?.update?.status !== "pending",
678 unitPath,
679 logPath,
680 };
681 }).pipe(
682 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
683 Effect.withSpan("cloud.boot_service.status"),
684 );
685
686 return BootService.of({ install, uninstall, status });
687});
688
689export const layer = (input: {
690 readonly baseDir: string;
691 readonly logsDir: string;
692 readonly cliVersion: string;
693 readonly host?: BootServiceHost;
694}) => Layer.effect(BootService, make(input));