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; readonly environmentPath: 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>PATH</key>`,
131 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
132 ` <key>T3CODE_HOME</key>`,
133 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
134 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
135 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
136 ` </dict>`,
137 ` <key>WorkingDirectory</key>`,
138 ` <string>${escapeXmlText(options.homeDir)}</string>`,
139 ` <key>RunAtLoad</key>`,
140 ` <true/>`,
141 ` <key>KeepAlive</key>`,
142 ` <true/>`,
143 ` <key>ThrottleInterval</key>`,
144 ` <integer>5</integer>`,
145 ` <key>ExitTimeOut</key>`,
146 ` <integer>90</integer>`,
147 ` <key>ProcessType</key>`,
148 ` <string>Interactive</string>`,
149 ` <key>StandardOutPath</key>`,
150 ` <string>${escapeXmlText(plan.logPath)}</string>`,
151 ` <key>StandardErrorPath</key>`,
152 ` <string>${escapeXmlText(plan.logPath)}</string>`,
153 `</dict>`,
154 `</plist>`,
155 ``,
156 ].join("\n");
157}
158
159export interface BootServiceStep {
160 readonly step: string;
161 readonly command: string;
162 readonly args: ReadonlyArray<string>;
163 /**
164 * Non-zero exit is logged and ignored. Reserved for steps whose common
165 * failures (not loaded, already enabled) leave a state a later strict step
166 * either tolerates or fails loudly on.
167 */
168 readonly optional?: boolean;
169 /** Override the ProcessRunner default (60s) for steps that block longer. */
170 readonly timeout?: Duration.Input;
171}
172
173/**
174 * Stop commands block until the service manager gives up: 90s by default for
175 * systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
176 * must stay above both, or the runner cancels the stop mid-shutdown and the
177 * next step races a still-loaded service.
178 */
179const STOP_STEP_TIMEOUT = Duration.seconds(120);
180
181/**
182 * Platform service-manager integration as data: paths, a pure renderer, and
183 * the command steps each flow runs. install/uninstall/status consume this and
184 * never branch on platform.
185 */
186export interface BootServiceManager {
187 readonly kind: "systemd" | "launchd";
188 readonly unitPath: string;
189 readonly render: (plan: BootServicePlan) => string;
190 /** Before rewriting files, when a unit is already installed. */
191 readonly stop: ReadonlyArray<BootServiceStep>;
192 /** After files are written. The last entry starts the service. */
193 readonly activate: ReadonlyArray<BootServiceStep>;
194 /** Best-effort recovery after a failed repair of an installed service. */
195 readonly restart: ReadonlyArray<BootServiceStep>;
196 /** Uninstall, before the unit file is removed. */
197 readonly deactivate: ReadonlyArray<BootServiceStep>;
198 /** Uninstall, after the unit file is removed. */
199 readonly finalize: ReadonlyArray<BootServiceStep>;
200}
201
202export function systemdManager(input: {
203 readonly path: Path.Path;
204 readonly homeDir: string;
205}): BootServiceManager {
206 const unitPath = input.path.join(
207 input.homeDir,
208 ".config",
209 "systemd",
210 "user",
211 BOOT_SERVICE_UNIT_FILE,
212 );
213 return {
214 kind: "systemd",
215 unitPath,
216 render: renderBootServiceUnit,
217 stop: [
218 {
219 step: "stopping the installed service",
220 command: "systemctl",
221 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
222 timeout: STOP_STEP_TIMEOUT,
223 },
224 ],
225 activate: [
226 {
227 step: "reloading systemd user units",
228 command: "systemctl",
229 args: ["--user", "daemon-reload"],
230 },
231 {
232 step: "enabling the service",
233 command: "systemctl",
234 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
235 },
236 { step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },
237 // Start last. No administrative state write occurs after this succeeds.
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 deactivate: [
252 {
253 step: "stopping the service",
254 command: "systemctl",
255 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
256 timeout: STOP_STEP_TIMEOUT,
257 },
258 ],
259 finalize: [
260 {
261 step: "reloading systemd user units",
262 command: "systemctl",
263 args: ["--user", "daemon-reload"],
264 },
265 ],
266 };
267}
268
269export function launchdManager(input: {
270 readonly path: Path.Path;
271 readonly homeDir: string;
272 readonly uid: number;
273 readonly environmentPath: string;
274}): BootServiceManager {
275 const unitPath = input.path.join(
276 input.homeDir,
277 "Library",
278 "LaunchAgents",
279 BOOT_SERVICE_PLIST_FILE,
280 );
281 const domainTarget = `gui/${input.uid}`;
282 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
283 // bootout/enable are optional: they fail on not-loaded states that are fine
284 // to proceed from. The strict `bootstrap` runs last and is also the start:
285 // loading a RunAtLoad/KeepAlive plist starts the job, so a separate
286 // kickstart would kill and restart a server it just booted. A lingering job
287 // that survived bootout, or a gui domain with nobody logged in at the
288 // screen (SSH install), makes bootstrap fail the flow loudly rather than
289 // silently keeping a stale server.
290 return {
291 kind: "launchd",
292 unitPath,
293 render: (plan) =>
294 renderBootServicePlist(plan, {
295 homeDir: input.homeDir,
296 environmentPath: input.environmentPath,
297 }),
298 // Without --wait, bootout returns in milliseconds while the job drains
299 // for up to ExitTimeOut, and a bootstrap during the drain fails EIO.
300 // --wait (present on modern macOS, absent from the man page) blocks until
301 // the job is removed from the domain; STOP_STEP_TIMEOUT outlives it.
302 stop: [
303 {
304 step: "stopping the installed launch agent",
305 command: "launchctl",
306 args: ["bootout", "--wait", serviceTarget],
307 optional: true,
308 timeout: STOP_STEP_TIMEOUT,
309 },
310 ],
311 activate: [
312 // A persisted `launchctl disable` override refuses bootstrap; clear it.
313 {
314 step: "enabling the launch agent",
315 command: "launchctl",
316 args: ["enable", serviceTarget],
317 optional: true,
318 },
319 // Start last. No administrative state write occurs after this succeeds.
320 {
321 step: "starting the service",
322 command: "launchctl",
323 args: ["bootstrap", domainTarget, unitPath],
324 },
325 ],
326 restart: [
327 {
328 step: "restarting the service after a failed update",
329 command: "launchctl",
330 args: ["bootstrap", domainTarget, unitPath],
331 },
332 ],
333 // No `launchctl disable` here: a persisted override would sabotage a
334 // later reinstall. Removing the plist is what stops the next login load.
335 // A bootout that fails for a reason other than "not loaded" leaves the
336 // job running until logout; the failure is in the boot-service log.
337 deactivate: [
338 {
339 step: "stopping the service",
340 command: "launchctl",
341 args: ["bootout", "--wait", serviceTarget],
342 optional: true,
343 timeout: STOP_STEP_TIMEOUT,
344 },
345 ],
346 finalize: [],
347 };
348}
349
350/** Undefined means this host cannot run the background service. */
351export function selectBootServiceManager(input: {
352 readonly platform: NodeJS.Platform;
353 readonly homeDir: string;
354 readonly uid: number | undefined;
355 readonly path: Path.Path;
356 readonly environmentPath: string;
357}): BootServiceManager | undefined {
358 if (input.homeDir === "") {
359 return undefined;
360 }
361 if (input.platform === "linux") {
362 return systemdManager({ path: input.path, homeDir: input.homeDir });
363 }
364 if (input.platform === "darwin" && input.uid !== undefined) {
365 return launchdManager({
366 path: input.path,
367 homeDir: input.homeDir,
368 uid: input.uid,
369 environmentPath: input.environmentPath,
370 });
371 }
372 return undefined;
373}
374
375export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
376 "BootServiceUnsupportedError",
377 { platform: Schema.String },
378) {
379 override get message(): string {
380 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
381 }
382}
383
384export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
385 "BootServiceCommandError",
386 {
387 step: Schema.String,
388 exitCode: Schema.optional(Schema.Number),
389 stdoutLength: Schema.optional(Schema.Number),
390 stderrLength: Schema.optional(Schema.Number),
391 cause: Schema.optional(Schema.Defect()),
392 },
393) {
394 override get message(): string {
395 return this.exitCode === undefined
396 ? `Background setup failed while ${this.step}.`
397 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
398 }
399}
400
401export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
402 "BootServiceInstallError",
403 { cause: Schema.Defect() },
404) {
405 override get message(): string {
406 return "Could not set up the T3 Code background service.";
407 }
408}
409
410export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
411 "BootServiceUpdatePendingError",
412 {},
413) {
414 override get message(): string {
415 return "A remote server update is still pending. Wait for it to finish, then retry.";
416 }
417}
418
419export type BootServiceError =
420 | BootServiceUnsupportedError
421 | BootServiceCommandError
422 | BootServiceInstallError
423 | BootServiceUpdatePendingError;
424
425export interface BootServiceStatus {
426 readonly supported: boolean;
427 readonly installed: boolean;
428 readonly current: boolean;
429 readonly unitPath: string;
430 readonly logPath: string;
431}
432
433export class BootService extends Context.Service<
434 BootService,
435 {
436 readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
437 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
438 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
439 }
440>()("t3/cloud/bootService") {}
441
442export interface BootServiceHost {
443 readonly execPath: string;
444 readonly launcherSourcePath?: string;
445}
446
447export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
448 readonly baseDir: string;
449 readonly logsDir: string;
450 readonly cliVersion: string;
451 readonly host?: BootServiceHost;
452}) {
453 const hostExecPath = yield* HostProcessExecutablePath;
454 const platform = yield* HostProcessPlatform;
455 const uid = yield* HostProcessUserId;
456 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
457 const installerPath = yield* Config.string("PATH").pipe(Config.withDefault(""));
458 const fs = yield* FileSystem.FileSystem;
459 const path = yield* Path.Path;
460 const runner = yield* ProcessRunner.ProcessRunner;
461 const host = input.host ?? { execPath: hostExecPath };
462 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
463 (directory) =>
464 directory.length > 0 &&
465 Array.from(directory).every((character) => {
466 const code = character.charCodeAt(0);
467 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
468 }),
469 );
470 const environmentPath = Array.from(
471 new Set([
472 ...xmlSafeInstallerDirectories,
473 path.dirname(host.execPath),
474 "/opt/homebrew/bin",
475 "/usr/local/bin",
476 "/usr/bin",
477 "/bin",
478 "/usr/sbin",
479 "/sbin",
480 ]),
481 ).join(":");
482
483 const detectedManager = selectBootServiceManager({
484 platform,
485 homeDir,
486 uid,
487 path,
488 environmentPath,
489 });
490 const unitPath = detectedManager?.unitPath ?? "";
491 const logPath = path.join(input.logsDir, "boot-service.log");
492 const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
493 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
494 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
495 const launcherSourcePath =
496 host.launcherSourcePath ??
497 path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
498 const writeDurably = (filePath: string, contents: string) =>
499 Effect.scoped(
500 Effect.gen(function* () {
501 const directory = path.dirname(filePath);
502 yield* fs.makeDirectory(directory, { recursive: true });
503 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
504 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
505 yield* (yield* fs.open(tempPath, { flag: "r" })).sync;
506 yield* fs.rename(tempPath, filePath);
507 yield* (yield* fs.open(directory, { flag: "r" })).sync;
508 }),
509 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
510 const plan: BootServicePlan = {
511 nodePath: host.execPath,
512 launcherPath,
513 baseDir: input.baseDir,
514 logPath,
515 unitPath,
516 };
517
518 const requireManager = Effect.suspend(() =>
519 detectedManager === undefined
520 ? new BootServiceUnsupportedError({ platform })
521 : Effect.succeed(detectedManager),
522 );
523
524 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
525 step: string,
526 command: string,
527 args: ReadonlyArray<string>,
528 options?: { readonly timeout?: Duration.Input },
529 ) {
530 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
531 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
532 Effect.filterOrFail(
533 (result) => result.code === 0,
534 (result) =>
535 new BootServiceCommandError({
536 step,
537 exitCode: Number(result.code),
538 stdoutLength: result.stdout.length,
539 stderrLength: result.stderr.length,
540 }),
541 ),
542 Effect.tapError((error) =>
543 DateTime.now.pipe(
544 Effect.flatMap((now) =>
545 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
546 flag: "a",
547 }),
548 ),
549 Effect.ignore,
550 ),
551 ),
552 );
553 });
554
555 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
556 Effect.forEach(
557 steps,
558 (entry) => {
559 const run = runStep(
560 entry.step,
561 entry.command,
562 entry.args,
563 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
564 );
565 // runStep's tapError already appends the failure to the log, so an
566 // ignored optional step still leaves a trace.
567 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
568 },
569 { discard: true },
570 );
571
572 const install: BootService["Service"]["install"] = Effect.gen(function* () {
573 const manager = yield* requireManager;
574 yield* fs
575 .makeDirectory(input.logsDir, { recursive: true })
576 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
577
578 // Prepare every immutable artifact before stopping the installed unit.
579 yield* ensurePinnedRuntimeInstalled({
580 baseDir: input.baseDir,
581 version: input.cliVersion,
582 fs,
583 path,
584 runner,
585 validate: (runtime) =>
586 runner
587 .run({
588 command: host.execPath,
589 args: [runtime.entryPath, "--version"],
590 timeout: Duration.seconds(30),
591 })
592 .pipe(
593 Effect.mapError(
594 (cause) =>
595 new PinnedRuntimeInstallError({
596 step: "verifying the pinned t3 runtime",
597 cause,
598 }),
599 ),
600 Effect.flatMap((result) => {
601 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
602 return result.code === 0 && reportedVersion === input.cliVersion
603 ? Effect.void
604 : Effect.fail(
605 new PinnedRuntimeInstallError({
606 step: "verifying the pinned t3 runtime",
607 exitCode: Number(result.code),
608 stdoutLength: result.stdout.length,
609 stderrLength: result.stderr.length,
610 }),
611 );
612 }),
613 ),
614 }).pipe(
615 Effect.mapError((error) =>
616 error._tag === "PinnedRuntimeInstallError"
617 ? new BootServiceCommandError({
618 step: error.step,
619 exitCode: error.exitCode,
620 stdoutLength: error.stdoutLength,
621 stderrLength: error.stderrLength,
622 cause: error,
623 })
624 : new BootServiceInstallError({ cause: error }),
625 ),
626 );
627 const launcherSource = yield* fs
628 .readFileString(launcherSourcePath)
629 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
630
631 const installed = yield* fs
632 .exists(unitPath)
633 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
634 if (installed) {
635 yield* runSteps(manager.stop);
636 }
637
638 yield* Effect.gen(function* () {
639 if (installed) {
640 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
641 if (
642 Option.isSome(previousStateText) &&
643 serviceStateHasPendingUpdate(previousStateText.value)
644 ) {
645 return yield* new BootServiceUpdatePendingError();
646 }
647 }
648 yield* fs
649 .makeDirectory(path.dirname(unitPath), { recursive: true })
650 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
651 yield* writeDurably(launcherPath, launcherSource);
652 yield* writeDurably(
653 statePath,
654 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
655 `${JSON.stringify(
656 {
657 protocol: SERVICE_LAUNCHER_PROTOCOL,
658 activeVersion: input.cliVersion,
659 } satisfies ServiceState,
660 null,
661 2,
662 )}\n`,
663 );
664 yield* writeDurably(unitPath, manager.render(plan));
665
666 yield* runSteps(manager.activate);
667 }).pipe(
668 Effect.tapError(() =>
669 installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
670 ),
671 );
672 return plan;
673 }).pipe(Effect.withSpan("cloud.boot_service.install"));
674
675 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
676 const manager = yield* requireManager;
677 if (
678 !(yield* fs
679 .exists(unitPath)
680 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
681 )
682 return false;
683 yield* runSteps(manager.deactivate);
684 yield* fs
685 .remove(unitPath)
686 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
687 yield* runSteps(manager.finalize);
688 return true;
689 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
690
691 const status: BootService["Service"]["status"] = Effect.gen(function* () {
692 if (detectedManager === undefined) {
693 return { supported: false, installed: false, current: false, unitPath, logPath };
694 }
695 if (!(yield* fs.exists(unitPath))) {
696 return { supported: true, installed: false, current: false, unitPath, logPath };
697 }
698 const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
699 yield* Effect.all([
700 fs.readFileString(unitPath),
701 fs.exists(launcherPath),
702 fs.exists(runtimePaths.entryPath),
703 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
704 fs.readFileString(statePath).pipe(Effect.option),
705 ]);
706 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
707 const normalizeUnit = (contents: string) =>
708 detectedManager.kind === "launchd"
709 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
710 : contents;
711 return {
712 supported: true,
713 installed: true,
714 current:
715 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
716 launcherExists &&
717 runtimeEntryExists &&
718 Option.isSome(runtimeSentinel) &&
719 runtimeSentinel.value.trim() === input.cliVersion &&
720 state?.activeVersion === input.cliVersion &&
721 state?.update?.status !== "pending",
722 unitPath,
723 logPath,
724 };
725 }).pipe(
726 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
727 Effect.withSpan("cloud.boot_service.status"),
728 );
729
730 return BootService.of({ install, uninstall, status });
731});
732
733export const layer = (input: {
734 readonly baseDir: string;
735 readonly logsDir: string;
736 readonly cliVersion: string;
737 readonly host?: BootServiceHost;
738}) => Layer.effect(BootService, make(input));