The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,650 lines 63.6 KB
Raw
1 import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts";
2 import * as HostProcess from "@t3tools/shared/HostProcess";
3 import * as Config from "effect/Config";
4 import * as Context from "effect/Context";
5 import * as DateTime from "effect/DateTime";
6 import * as Duration from "effect/Duration";
7 import * as Effect from "effect/Effect";
8 import * as Exit from "effect/Exit";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Path from "effect/Path";
13 import * as Schedule from "effect/Schedule";
14 import { CliError } from "effect/cli";
15 import { HttpClient } from "effect/http";
16 import * as Schema from "effect/Schema";
17
18 import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
19
20 import * as ProcessRunner from "../processRunner.ts";
21 import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts";
22 import {
23 serviceLauncherIsRunning,
24 serviceLauncherLockPath,
25 serviceTaskName,
26 waitForServiceLauncherExit,
27 } from "../serviceLauncher.ts";
28 import {
29 ensurePinnedRuntimeInstalled,
30 launcherOwnsVersionsDir,
31 pinnedRuntimeCommand,
32 pinnedRuntimePaths,
33 pinnedRuntimeVersionsDir,
34 PinnedRuntimeInstallError,
35 } from "./pinnedRuntime.ts";
36 import {
37 SERVICE_LAUNCHER_PROTOCOL,
38 SERVICE_RESTART_PENDING_FILE,
39 SERVICE_STATE_FILE,
40 SERVICE_UNIT_ENV,
41 compareExactServiceVersions,
42 decodeServiceUnit,
43 disabledServiceTask,
44 encodeServiceTask,
45 serviceTaskIsDisabled,
46 serviceUnitBaseDirOf as bootServiceBaseDirOf,
47 serviceUnitEnvironmentValueOf,
48 parseServiceState,
49 serviceStateActiveVersion,
50 serviceStateHasPendingUpdate,
51 systemdUnitDirectoryOf,
52 type ServiceState,
53 } from "./serviceProtocol.ts";
54
55 export {
56 serviceUnitBaseDirOf as bootServiceBaseDirOf,
57 serviceUnitProgramOf as bootServiceProgramOf,
58 } from "./serviceProtocol.ts";
59
60 const BOOT_SERVICE_NAME = "t3code";
61 export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
62 // `.service` suffix keeps the label distinct from the desktop app's bundle id
63 // (com.t3tools.t3code), so launchd and TCC records never collide.
64 export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
65 export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
66 export const BOOT_SERVICE_LOG_FILE = "boot-service.log";
67 /** `schtasks /Query /HRESULT` exits with this when the task is not registered. */
68 const WINDOWS_TASK_NOT_FOUND = 0x80070002;
69 /** Task Scheduler keeps its own copy; this one lets status and repair read the task back. */
70 const BOOT_SERVICE_TASK_FILE = `${BOOT_SERVICE_NAME}-task.xml`;
71
72 /** systemd expands `%` specifiers, including in unquoted append-log paths. */
73 function escapeSystemdSpecifiers(value: string): string {
74 return value.replaceAll("%", "%%");
75 }
76
77 function quoteSystemdValue(value: string): string {
78 const escaped = escapeSystemdSpecifiers(value);
79 return /[\s"'\\]/.test(escaped)
80 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
81 : escaped;
82 }
83
84 /** Windows paths cannot contain `"`; only backslashes before the closing quote need doubling. */
85 const quoteWindowsArgument = (value: string) => `"${value.replace(/(\\+)$/, "$1$1")}"`;
86
87 export interface BootServicePlan {
88 readonly program: ReadonlyArray<string>;
89 readonly baseDir: string;
90 readonly logPath: string;
91 readonly unitPath: string;
92 readonly installBinDir?: string;
93 /** The manager accepted a detached install; its outcome is written to `logPath`. */
94 readonly handedOff?: boolean;
95 }
96
97 // systemd refuses an executable with a quote, backslash or control character even when
98 // quoted. The executable lives under the T3 home, so this also catches a home with a newline.
99 const systemdUnsafeValue = (plan: BootServicePlan) =>
100 /[\x00-\x1f\x7f"'\\]/.test(plan.program[0] ?? "");
101
102 /** Service units cannot rely on the user's shell or PATH. */
103 export function renderBootServiceUnit(plan: BootServicePlan): string {
104 if (systemdUnsafeValue(plan)) {
105 throw new BootServiceBaseDirUnsupportedError({ baseDir: plan.baseDir });
106 }
107 // The user manager has no reliable network-online target; server networking retries itself.
108 return [
109 "[Unit]",
110 "Description=T3 Code server",
111 "StartLimitIntervalSec=300",
112 "StartLimitBurst=5",
113 "",
114 "[Service]",
115 "Type=simple",
116 "WorkingDirectory=%h",
117 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
118 ...(plan.installBinDir === undefined
119 ? []
120 : [`Environment=T3CODE_INSTALL_BIN_DIR=${quoteSystemdValue(plan.installBinDir)}`]),
121 `Environment=${SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
122 `ExecStart=${plan.program.map(quoteSystemdValue).join(" ")}`,
123 // Let the launcher mark an explicit stop before it signals the server.
124 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
125 "KillMode=mixed",
126 // Helpers share this cgroup; default OOMPolicy=stop would stop the unit if one is OOM-killed.
127 "OOMPolicy=continue",
128 "Restart=always",
129 "RestartSec=5",
130 // Weights favor the server over the sibling agents slice; IOWeight needs a delegated io controller.
131 "CPUWeight=1000",
132 "IOWeight=1000",
133 // Reclaim takes the agents' unprotected pages first. The kernel caps this at the
134 // protection of user.slice and user@.service, which only root can grant.
135 "MemoryLow=1536M",
136 // A user manager's own score, the lowest it may set: below its other services (200) and agents (800).
137 // `t3 service protect` lowers it further through a drop-in.
138 "OOMScoreAdjust=100",
139 // systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is.
140 "ManagedOOMPreference=avoid",
141 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
142 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
143 "",
144 "[Install]",
145 "WantedBy=default.target",
146 "",
147 ].join("\n");
148 }
149
150 function escapeXmlText(value: string): string {
151 return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
152 }
153
154 /** Launch agents cannot rely on the user's shell or PATH. */
155 export function renderBootServicePlist(
156 plan: BootServicePlan,
157 options: { readonly homeDir: string; readonly environmentPath: string },
158 ): string {
159 // Allow 90s stops for update handoffs.
160 // Interactive avoids background throttling.
161 // AbandonProcessGroup=false reaps agents only on launcher exit, preserving them across child updates.
162 return [
163 `<?xml version="1.0" encoding="UTF-8"?>`,
164 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
165 `<plist version="1.0">`,
166 `<dict>`,
167 ` <key>Label</key>`,
168 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
169 ` <key>ProgramArguments</key>`,
170 ` <array>`,
171 ...plan.program.map((argument) => ` <string>${escapeXmlText(argument)}</string>`),
172 ` </array>`,
173 ` <key>EnvironmentVariables</key>`,
174 ` <dict>`,
175 ` <key>PATH</key>`,
176 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
177 ` <key>T3CODE_HOME</key>`,
178 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
179 ...(plan.installBinDir === undefined
180 ? []
181 : [
182 ` <key>T3CODE_INSTALL_BIN_DIR</key>`,
183 ` <string>${escapeXmlText(plan.installBinDir)}</string>`,
184 ]),
185 ` <key>${SERVICE_UNIT_ENV}</key>`,
186 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
187 ` </dict>`,
188 ` <key>WorkingDirectory</key>`,
189 ` <string>${escapeXmlText(options.homeDir)}</string>`,
190 ` <key>RunAtLoad</key>`,
191 ` <true/>`,
192 ` <key>KeepAlive</key>`,
193 ` <true/>`,
194 ` <key>ThrottleInterval</key>`,
195 ` <integer>5</integer>`,
196 ` <key>ExitTimeOut</key>`,
197 ` <integer>90</integer>`,
198 ` <key>ProcessType</key>`,
199 ` <string>Interactive</string>`,
200 ` <key>StandardOutPath</key>`,
201 ` <string>${escapeXmlText(plan.logPath)}</string>`,
202 ` <key>StandardErrorPath</key>`,
203 ` <string>${escapeXmlText(plan.logPath)}</string>`,
204 `</dict>`,
205 `</plist>`,
206 ``,
207 ].join("\n");
208 }
209
210 /**
211 * Task Scheduler can neither set variables nor redirect output, so the launcher takes them as
212 * flags. A console program started by a task opens a window unless a headless console hosts it.
213 * No XML declaration: the file is written as UTF-16LE with a BOM (see `encodeServiceTask`).
214 */
215 export function renderBootServiceTask(
216 plan: BootServicePlan,
217 options: { readonly userId: string; readonly homeDir: string; readonly conhostPath: string },
218 ): string {
219 const launcherArguments = [
220 ...plan.program,
221 "--base-dir",
222 plan.baseDir,
223 "--log-file",
224 plan.logPath,
225 "--service-unit",
226 BOOT_SERVICE_TASK_FILE,
227 ]
228 .map(quoteWindowsArgument)
229 .join(" ");
230 // conhost reports exit code 0 whatever the launcher returns, so restart-on-failure never
231 // fires. A repeating trigger with IgnoreNew starts the task again within a minute instead.
232 // Priority 5 is normal; the default 7 runs below it.
233 return [
234 `<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">`,
235 ` <RegistrationInfo>`,
236 ` <Description>T3 Code server</Description>`,
237 ` </RegistrationInfo>`,
238 ` <Triggers>`,
239 ` <LogonTrigger>`,
240 ` <UserId>${escapeXmlText(options.userId)}</UserId>`,
241 ` </LogonTrigger>`,
242 ` <TimeTrigger>`,
243 ` <StartBoundary>2000-01-01T00:00:00</StartBoundary>`,
244 ` <Repetition>`,
245 ` <Interval>PT1M</Interval>`,
246 ` </Repetition>`,
247 ` </TimeTrigger>`,
248 ` </Triggers>`,
249 ` <Principals>`,
250 ` <Principal id="Author">`,
251 ` <UserId>${escapeXmlText(options.userId)}</UserId>`,
252 ` <LogonType>InteractiveToken</LogonType>`,
253 ` <RunLevel>LeastPrivilege</RunLevel>`,
254 ` </Principal>`,
255 ` </Principals>`,
256 ` <Settings>`,
257 ` <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>`,
258 ` <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>`,
259 ` <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>`,
260 ` <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>`,
261 ` <Priority>5</Priority>`,
262 ` </Settings>`,
263 ` <Actions Context="Author">`,
264 ` <Exec>`,
265 ` <Command>${escapeXmlText(options.conhostPath)}</Command>`,
266 ` <Arguments>--headless ${escapeXmlText(launcherArguments)}</Arguments>`,
267 ` <WorkingDirectory>${escapeXmlText(options.homeDir)}</WorkingDirectory>`,
268 ` </Exec>`,
269 ` </Actions>`,
270 `</Task>`,
271 ``,
272 ].join("\n");
273 }
274
275 export type BootServiceStep = {
276 readonly step: string;
277 /** Non-zero exit is logged and ignored. */
278 readonly optional?: boolean;
279 readonly timeout?: Duration.Input;
280 } & (
281 | { readonly command: string; readonly args: ReadonlyArray<string> }
282 /** A step no command can do, such as waiting for the Windows launcher to exit. */
283 | { readonly run: Effect.Effect<void, BootServiceCommandError> }
284 );
285
286 /** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */
287 const STOP_STEP_TIMEOUT = Duration.seconds(120);
288
289 interface BootServiceHandoff {
290 readonly prepare: ReadonlyArray<BootServiceStep>;
291 readonly restart: ReadonlyArray<BootServiceStep>;
292 }
293
294 export interface BootServiceManager {
295 readonly kind: "systemd" | "launchd" | "schtasks";
296 readonly unitPath: string;
297 readonly render: (plan: BootServicePlan) => string;
298 readonly stop: ReadonlyArray<BootServiceStep>;
299 readonly activate: ReadonlyArray<BootServiceStep>;
300 readonly restart: ReadonlyArray<BootServiceStep>;
301 /** Queue a restart owned by the manager, since stopping would kill the caller. */
302 readonly handoff?: BootServiceHandoff;
303 readonly deactivate: ReadonlyArray<BootServiceStep>;
304 readonly finalize: ReadonlyArray<BootServiceStep>;
305 }
306
307 const defaultSystemdUnitDir = (path: Path.Path, homeDir: string, xdgConfigHome: string) =>
308 path.join(
309 path.isAbsolute(xdgConfigHome) ? xdgConfigHome : path.join(homeDir, ".config"),
310 "systemd",
311 "user",
312 );
313
314 const scheduledTaskPath = (path: Path.Path, localAppData: string) =>
315 path.join(localAppData, "t3code", BOOT_SERVICE_TASK_FILE);
316
317 const launchdPlistPath = (path: Path.Path, homeDir: string) =>
318 path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE);
319
320 function systemdManager(input: {
321 readonly path: Path.Path;
322 readonly unitDir: string;
323 }): BootServiceManager {
324 const unitPath = input.path.join(input.unitDir, BOOT_SERVICE_UNIT_FILE);
325 // Once StartLimitBurst trips, systemd refuses every start until the failed state is cleared.
326 const resetFailed = {
327 step: "clearing the service's failed state",
328 optional: true,
329 command: "systemctl",
330 args: ["--user", "reset-failed", BOOT_SERVICE_UNIT_FILE],
331 };
332 const prepareActivation = [
333 {
334 step: "reloading systemd user units",
335 command: "systemctl",
336 args: ["--user", "daemon-reload"],
337 },
338 {
339 step: "enabling the service",
340 command: "systemctl",
341 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
342 },
343 resetFailed,
344 ];
345 return {
346 kind: "systemd",
347 unitPath,
348 render: renderBootServiceUnit,
349 stop: [
350 {
351 step: "stopping the installed service",
352 command: "systemctl",
353 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
354 timeout: STOP_STEP_TIMEOUT,
355 },
356 ],
357 activate: [
358 ...prepareActivation,
359 {
360 step: "starting the service",
361 command: "systemctl",
362 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
363 },
364 ],
365 restart: [
366 resetFailed,
367 {
368 step: "restarting the service after a failed update",
369 command: "systemctl",
370 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
371 },
372 ],
373 handoff: {
374 prepare: prepareActivation,
375 restart: [
376 {
377 step: "restarting the service",
378 command: "systemctl",
379 args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],
380 },
381 ],
382 },
383 deactivate: [
384 {
385 step: "stopping the service",
386 command: "systemctl",
387 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
388 timeout: STOP_STEP_TIMEOUT,
389 },
390 ],
391 finalize: [
392 {
393 step: "reloading systemd user units",
394 command: "systemctl",
395 args: ["--user", "daemon-reload"],
396 },
397 ],
398 };
399 }
400
401 function launchdManager(input: {
402 readonly path: Path.Path;
403 readonly homeDir: string;
404 readonly uid: number;
405 readonly environmentPath: string;
406 }): BootServiceManager {
407 const unitPath = launchdPlistPath(input.path, input.homeDir);
408 const domainTarget = `gui/${input.uid}`;
409 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
410 // Unloaded jobs may reject bootout/enable. Bootstrap starts RunAtLoad/KeepAlive jobs; kickstart would restart them.
411 return {
412 kind: "launchd",
413 unitPath,
414 render: (plan) =>
415 renderBootServicePlist(plan, {
416 homeDir: input.homeDir,
417 environmentPath: input.environmentPath,
418 }),
419 // bootout --wait is undocumented but waits through ExitTimeOut, preventing bootstrap EIO races.
420 stop: [
421 {
422 step: "stopping the installed launch agent",
423 command: "launchctl",
424 args: ["bootout", "--wait", serviceTarget],
425 optional: true,
426 timeout: STOP_STEP_TIMEOUT,
427 },
428 ],
429 activate: [
430 // A persisted `launchctl disable` override refuses bootstrap; clear it.
431 {
432 step: "enabling the launch agent",
433 command: "launchctl",
434 args: ["enable", serviceTarget],
435 optional: true,
436 },
437 {
438 step: "starting the service",
439 command: "launchctl",
440 args: ["bootstrap", domainTarget, unitPath],
441 },
442 ],
443 restart: [
444 {
445 step: "restarting the service after a failed update",
446 command: "launchctl",
447 args: ["bootstrap", domainTarget, unitPath],
448 },
449 ],
450 // Persisted launchctl disable overrides would block reinstall.
451 deactivate: [
452 {
453 step: "stopping the service",
454 command: "launchctl",
455 args: ["bootout", "--wait", serviceTarget],
456 optional: true,
457 timeout: STOP_STEP_TIMEOUT,
458 },
459 ],
460 finalize: [],
461 };
462 }
463
464 export interface WindowsSession {
465 readonly localAppData: string;
466 /** `DOMAIN\user`, the account whose logon starts the task. */
467 readonly userId: string;
468 readonly taskName: string;
469 readonly systemRoot: string;
470 }
471
472 /** The steps one `schtasks` command cannot do. */
473 interface WindowsTaskSteps {
474 /** Disables the task, or the repeating trigger restarts a service that should stay stopped. */
475 readonly disable: Effect.Effect<void, BootServiceCommandError>;
476 /** Ends the task and waits for its launcher to exit; Task Scheduler does not wait. */
477 readonly stopLauncher: Effect.Effect<void, BootServiceCommandError>;
478 readonly remove: Effect.Effect<void, BootServiceCommandError>;
479 }
480
481 function schtasksManager(input: {
482 readonly path: Path.Path;
483 readonly homeDir: string;
484 readonly session: WindowsSession;
485 readonly steps: WindowsTaskSteps;
486 }): BootServiceManager {
487 const unitPath = scheduledTaskPath(input.path, input.session.localAppData);
488 const task = ["/TN", input.session.taskName];
489 const register = {
490 step: "registering the scheduled task",
491 command: "schtasks",
492 args: ["/Create", "/XML", unitPath, ...task, "/F"],
493 };
494 const run = { step: "starting the service", command: "schtasks", args: ["/Run", ...task] };
495 const stop: ReadonlyArray<BootServiceStep> = [
496 { step: "disabling the scheduled task", run: input.steps.disable },
497 {
498 step: "stopping the installed service",
499 run: input.steps.stopLauncher,
500 timeout: STOP_STEP_TIMEOUT,
501 },
502 ];
503 return {
504 kind: "schtasks",
505 unitPath,
506 render: (plan) =>
507 renderBootServiceTask(plan, {
508 userId: input.session.userId,
509 homeDir: input.homeDir,
510 conhostPath: input.path.join(input.session.systemRoot, "System32", "conhost.exe"),
511 }),
512 stop,
513 // Registration also enables the task.
514 activate: [register, run],
515 restart: [
516 {
517 step: "enabling the scheduled task",
518 command: "schtasks",
519 args: ["/Change", ...task, "/ENABLE"],
520 },
521 { ...run, step: "restarting the service after a failed update" },
522 ],
523 // Ending the task kills only its console host; the launcher sees the console close and
524 // stops gracefully while the replacement waits for its lock.
525 handoff: {
526 prepare: [register],
527 restart: [
528 {
529 step: "ending the scheduled task",
530 command: "schtasks",
531 args: ["/End", ...task],
532 optional: true,
533 },
534 { ...run, step: "restarting the service" },
535 ],
536 },
537 deactivate: [...stop, { step: "removing the scheduled task", run: input.steps.remove }],
538 finalize: [],
539 };
540 }
541
542 function selectBootServiceManager(input: {
543 readonly platform: NodeJS.Platform;
544 readonly homeDir: string;
545 readonly xdgConfigHome: string;
546 readonly systemdUnitDir: string | undefined;
547 readonly uid: number | undefined;
548 readonly path: Path.Path;
549 readonly environmentPath: string;
550 readonly windows?: { readonly session: WindowsSession; readonly steps: WindowsTaskSteps };
551 }): BootServiceManager | undefined {
552 if (input.homeDir === "") {
553 return undefined;
554 }
555 if (input.platform === "win32" && input.windows !== undefined) {
556 return schtasksManager({ path: input.path, homeDir: input.homeDir, ...input.windows });
557 }
558 if (input.platform === "linux") {
559 return systemdManager({
560 path: input.path,
561 unitDir:
562 input.systemdUnitDir ??
563 defaultSystemdUnitDir(input.path, input.homeDir, input.xdgConfigHome),
564 });
565 }
566 if (input.platform === "darwin" && input.uid !== undefined) {
567 return launchdManager({
568 path: input.path,
569 homeDir: input.homeDir,
570 uid: input.uid,
571 environmentPath: input.environmentPath,
572 });
573 }
574 return undefined;
575 }
576
577 const decodeSystemdUnitPaths = Schema.decodeUnknownEffect(
578 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
579 );
580
581 // The manager may not share the installer's environment; JSON preserves spaces in its paths.
582 const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit_directory")(
583 function* (runner: ProcessRunner.ProcessRunner["Service"]) {
584 const result = yield* runner.run({
585 command: "busctl",
586 args: [
587 "--user",
588 "--json=short",
589 "get-property",
590 "org.freedesktop.systemd1",
591 "/org/freedesktop/systemd1",
592 "org.freedesktop.systemd1.Manager",
593 "UnitPath",
594 ],
595 timeout: Duration.seconds(5),
596 });
597 if (result.code !== 0) return undefined;
598 const { data } = yield* decodeSystemdUnitPaths(result.stdout);
599 return systemdUnitDirectoryOf(data);
600 },
601 Effect.orElseSucceed(() => undefined),
602 );
603
604 /** Where this platform's service manager keeps the unit, whether or not one is installed. */
605 export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(function* () {
606 const path = yield* Path.Path;
607 const platform = yield* HostProcess.Platform;
608 const homeDir = yield* HostProcess.HomeDirectory;
609 if (homeDir === "") return undefined;
610 if (platform === "darwin") return launchdPlistPath(path, homeDir);
611 if (platform === "win32") {
612 const localAppData = (yield* HostProcess.Environment).LOCALAPPDATA ?? "";
613 return localAppData === "" ? undefined : scheduledTaskPath(path, localAppData);
614 }
615 if (platform !== "linux") return undefined;
616 const unitDir =
617 (yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner)) ??
618 defaultSystemdUnitDir(path, homeDir, (yield* HostProcess.Environment).XDG_CONFIG_HOME ?? "");
619 return path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
620 });
621
622 export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
623 "BootServiceUnsupportedError",
624 { platform: Schema.String },
625 ) {
626 override get message(): string {
627 return `Background setup supports Linux with systemd, macOS with launchd, and Windows with Task Scheduler; this machine reports '${this.platform}'.`;
628 }
629 }
630
631 export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
632 "BootServiceCommandError",
633 {
634 step: Schema.String,
635 exitCode: Schema.optional(Schema.Number),
636 stdoutLength: Schema.optional(Schema.Number),
637 stderrLength: Schema.optional(Schema.Number),
638 cause: Schema.optional(Schema.Defect()),
639 },
640 ) {
641 override get message(): string {
642 return this.exitCode === undefined
643 ? `Background setup failed while ${this.step}.`
644 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
645 }
646 }
647
648 export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
649 "BootServiceInstallError",
650 { cause: Schema.Defect() },
651 ) {
652 override get message(): string {
653 return "Could not set up the T3 Code background service.";
654 }
655 }
656
657 const BootServiceProblem = Schema.Literals([
658 "user-manager-unavailable",
659 "linger-unavailable",
660 "linger-disabled",
661 "service-disabled",
662 "service-stopped",
663 "restart-pending",
664 ]);
665 type BootServiceProblem = typeof BootServiceProblem.Type;
666
667 export function formatBootServiceProblem(
668 problem: BootServiceProblem,
669 commands: { readonly install: string; readonly restart: string } = {
670 install: "t3 service install",
671 restart: "t3 service restart",
672 },
673 ): string {
674 switch (problem) {
675 case "user-manager-unavailable":
676 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.";
677 case "linger-unavailable":
678 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.';
679 case "linger-disabled":
680 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.';
681 case "service-disabled":
682 return `The service is not enabled to start automatically. Run \`${commands.install}\` to repair it.`;
683 case "service-stopped":
684 return `The service is not running. Check the service log (on Linux, also \`systemctl --user status t3code.service\`), then run \`${commands.install}\`.`;
685 case "restart-pending":
686 return `A newer version is installed but the service is still running the previous one. Run \`${commands.restart}\` to switch.`;
687 }
688 }
689
690 export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
691 "BootServicePrerequisiteError",
692 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
693 ) {
694 override get message(): string {
695 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
696 }
697 }
698
699 export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
700 "BootServiceUpdatePendingError",
701 { recoveryCommand: Schema.optional(Schema.String) },
702 ) {
703 override get message(): string {
704 if (this.recoveryCommand !== undefined) {
705 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.`;
706 }
707 return "A remote server update is still pending. Wait for it to finish, then retry.";
708 }
709 }
710
711 export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
712 "BootServiceDowngradeRefusedError",
713 {
714 installedVersion: Schema.String,
715 targetVersion: Schema.String,
716 },
717 ) {
718 override get message(): string {
719 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
720 }
721 }
722
723 export const formatBootServiceBaseDirOption = (baseDir: string) =>
724 `--base-dir '${baseDir.replaceAll("'", `'"'"'`)}'`;
725
726 export class BootServiceOtherBaseDirError extends Schema.TaggedError<BootServiceOtherBaseDirError>()(
727 "BootServiceOtherBaseDirError",
728 {
729 installedBaseDir: Schema.String,
730 baseDir: Schema.String,
731 },
732 ) {
733 override get message(): string {
734 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.`;
735 }
736
737 // A refusal the user fixes by rerunning, so the CLI prints the message, not a stack trace.
738 override get [CliError.userMessage]() {
739 return this.message;
740 }
741 }
742
743 export class BootServiceBaseDirUnsupportedError extends Schema.TaggedError<BootServiceBaseDirUnsupportedError>()(
744 "BootServiceBaseDirUnsupportedError",
745 { baseDir: Schema.String },
746 ) {
747 override get message(): string {
748 return `systemd cannot run T3 Code from ${JSON.stringify(this.baseDir)}: the path contains a quote, backslash or control character. Choose another T3 home with --base-dir.`;
749 }
750
751 override get [CliError.userMessage]() {
752 return this.message;
753 }
754 }
755
756 export type BootServiceError =
757 | BootServiceUnsupportedError
758 | BootServiceBaseDirUnsupportedError
759 | BootServiceOtherBaseDirError
760 | BootServiceCommandError
761 | BootServiceInstallError
762 | BootServicePrerequisiteError
763 | BootServiceUpdatePendingError
764 | BootServiceDowngradeRefusedError;
765
766 export interface BootServiceStatus {
767 readonly supported: boolean;
768 readonly installed: boolean;
769 readonly current: boolean;
770 readonly installedVersion?: string;
771 readonly installedBaseDir?: string;
772 /** Set when the installed unit serves a different T3 home than this CLI. */
773 readonly otherBaseDir?: string;
774 readonly problems?: ReadonlyArray<BootServiceProblem>;
775 readonly unitPath: string;
776 readonly logPath: string;
777 }
778
779 export class BootService extends Context.Service<
780 BootService,
781 {
782 readonly install: (options?: {
783 readonly allowDowngrade?: boolean;
784 readonly start?: boolean;
785 }) => Effect.Effect<BootServicePlan, BootServiceError>;
786 /**
787 * Only when the unit serves this base dir: the unit name is per user, so
788 * another home's service is left alone, which resolves `skipped`. From
789 * inside the service the restart can only be `queued` with the service
790 * manager, since the stop ends this process.
791 */
792 readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;
793 /**
794 * Runs the operation with this home's service stopped; other homes are left alone.
795 * Restores a previously enabled or loaded service even if stopping failed.
796 * The operation's failure takes precedence over a restart failure.
797 */
798 readonly withStopped: <A, E, R>(
799 operation: Effect.Effect<A, E, R>,
800 ) => Effect.Effect<A, E | BootServiceError, R>;
801 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
802 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
803 }
804 >()("t3/cloud/bootService") {}
805
806 export interface BootServiceHost {
807 readonly execPath: string;
808 }
809
810 export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
811 readonly baseDir: string;
812 readonly logsDir: string;
813 readonly cliVersion: string;
814 readonly host?: BootServiceHost;
815 }) {
816 const hostExecPath = yield* HostProcess.ExecutablePath;
817 const platform = yield* HostProcess.Platform;
818 const arch = yield* HostProcess.Architecture;
819 const uid = yield* HostProcess.UserId;
820 const httpClient = yield* HttpClient.HttpClient;
821 const releaseBaseUrl = Option.getOrUndefined(
822 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
823 );
824 const homeDir = yield* Config.String(platform === "win32" ? "USERPROFILE" : "HOME").pipe(
825 Config.withDefault(""),
826 );
827 const xdgConfigHome = yield* Config.String("XDG_CONFIG_HOME").pipe(Config.withDefault(""));
828 const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
829 const installBinDir = Option.getOrUndefined(
830 yield* Config.String("T3CODE_INSTALL_BIN_DIR").pipe(Config.option),
831 );
832 const xdgRuntimeDir = yield* Config.String("XDG_RUNTIME_DIR").pipe(Config.withDefault(""));
833 // Root under sudo must not reach or start a separate root service.
834 const rootUnderSudo =
835 uid === 0 && (yield* Config.String("SUDO_USER").pipe(Config.withDefault(""))) !== "";
836 const runningInsideService = [BOOT_SERVICE_UNIT_FILE, BOOT_SERVICE_TASK_FILE].includes(
837 yield* Config.String(SERVICE_UNIT_ENV).pipe(Config.withDefault("")),
838 );
839 const fs = yield* FileSystem.FileSystem;
840 const path = yield* Path.Path;
841 const processRunner = yield* ProcessRunner.ProcessRunner;
842 // Without a login session nothing sets this, so `--user` commands cannot find the user bus.
843 // The directory only appears once lingering starts the manager, so it need not exist yet.
844 const userManagerEnv =
845 platform === "linux" && xdgRuntimeDir === "" && uid !== undefined && !rootUnderSudo
846 ? { XDG_RUNTIME_DIR: `/run/user/${uid}` }
847 : undefined;
848 const runner: ProcessRunner.ProcessRunner["Service"] =
849 userManagerEnv === undefined
850 ? processRunner
851 : {
852 run: (request) =>
853 processRunner.run({ ...request, env: { ...userManagerEnv, ...request.env } }),
854 };
855 const host = input.host ?? { execPath: hostExecPath };
856 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
857 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
858 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
859 (directory) =>
860 directory.length > 0 &&
861 Array.from(directory).every((character) => {
862 const code = character.charCodeAt(0);
863 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
864 }),
865 );
866 // During an update, the running CLI and a PATH inherited from the service name the runtime
867 // being replaced. The service and its agent shells should find the runtime it starts.
868 const environmentPath = Array.from(
869 new Set(
870 [
871 ...xmlSafeInstallerDirectories,
872 path.dirname(host.execPath),
873 "/opt/homebrew/bin",
874 "/usr/local/bin",
875 "/usr/bin",
876 "/bin",
877 "/usr/sbin",
878 "/sbin",
879 ].map((directory) =>
880 launcherOwnsVersionsDir(path, versionsDir, directory) ? runtimePaths.versionDir : directory,
881 ),
882 ),
883 ).join(":");
884
885 const windowsVariable = (name: string) =>
886 platform === "win32" ? Config.String(name).pipe(Config.withDefault("")) : Config.succeed("");
887 const windowsSession: WindowsSession = {
888 localAppData: yield* windowsVariable("LOCALAPPDATA"),
889 userId: `${yield* windowsVariable("USERDOMAIN")}\\${yield* windowsVariable("USERNAME")}`,
890 taskName: serviceTaskName(
891 yield* windowsVariable("USERDOMAIN"),
892 yield* windowsVariable("USERNAME"),
893 ),
894 systemRoot: (yield* windowsVariable("SystemRoot")) || "C:\\Windows",
895 };
896 // The unit is per user, so the launcher to stop is the one serving the installed unit's home.
897 const launcherLockPath = (unit: Option.Option<string>) =>
898 serviceLauncherLockPath(
899 Option.getOrUndefined(Option.flatMapNullishOr(unit, bootServiceBaseDirOf)) ?? input.baseDir,
900 );
901 const windowsTask = ["/TN", windowsSession.taskName];
902 /** Runs a command that changes the task; a task that is not registered has nothing to change. */
903 const changeWindowsTask = Effect.fn("cloud.boot_service.change_windows_task")(function* (
904 step: string,
905 verb: string,
906 flag: string,
907 ) {
908 const toError = (cause: unknown) => new BootServiceCommandError({ step, cause });
909 const changed = yield* runner
910 .run({ command: "schtasks", args: [verb, ...windowsTask, flag] })
911 .pipe(Effect.mapError(toError));
912 if (changed.code === 0) return;
913 const queried = yield* runner
914 .run({
915 command: "schtasks",
916 args: ["/Query", ...windowsTask, "/HRESULT"],
917 timeout: Duration.seconds(5),
918 })
919 .pipe(Effect.mapError(toError));
920 if (Number(queried.code) >>> 0 === WINDOWS_TASK_NOT_FOUND) return;
921 return yield* new BootServiceCommandError({
922 step,
923 exitCode: Number(changed.code),
924 stdoutLength: changed.stdout.length,
925 stderrLength: changed.stderr.length,
926 });
927 });
928 // Under the unit lease: a launcher registering its task again reads whether it is disabled
929 // first, and must not do that around this.
930 const disableWindowsTask = Effect.suspend(() =>
931 Effect.acquireUseRelease(
932 Effect.tryPromise({
933 try: () => acquireServiceSelectionLock(unitPath),
934 catch: (cause) =>
935 new BootServiceCommandError({ step: "disabling the scheduled task", cause }),
936 }),
937 () => changeWindowsTask("disabling the scheduled task", "/Change", "/DISABLE"),
938 (release) => Effect.sync(release),
939 ),
940 );
941 const readUnit = () => fs.readFile(unitPath).pipe(Effect.map(decodeServiceUnit));
942 /**
943 * Task Scheduler runs its own copy of the task, so an install that starts nothing still
944 * registers the new one. A task that was disabled or absent stays stopped.
945 */
946 const refreshWindowsTask = Effect.fn("cloud.boot_service.refresh_windows_task")(function* (
947 unit: string,
948 ) {
949 const register = (xmlPath: string) =>
950 runStep("registering the scheduled task", "schtasks", [
951 "/Create",
952 "/XML",
953 xmlPath,
954 ...windowsTask,
955 "/F",
956 ]);
957 const registered = yield* probe("schtasks", ["/Query", ...windowsTask, "/XML"]);
958 if (
959 Option.isSome(registered) &&
960 registered.value.code === 0 &&
961 !serviceTaskIsDisabled(registered.value.stdout)
962 ) {
963 return yield* register(unitPath);
964 }
965 return yield* Effect.scoped(
966 Effect.gen(function* () {
967 const disabledPath = yield* fs.makeTempFileScoped({
968 directory: path.dirname(unitPath),
969 prefix: ".service-task-",
970 });
971 yield* fs.writeFile(disabledPath, encodeServiceTask(disabledServiceTask(unit)));
972 yield* register(disabledPath);
973 }),
974 );
975 });
976 // Ending the task closes the launcher's console, which the launcher takes as its SIGTERM.
977 // Task Scheduler then reports the task stopped at once, so the lock says when it really is.
978 const stopWindowsLauncher = Effect.gen(function* () {
979 const unit = yield* readUnit().pipe(Effect.option);
980 yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore);
981 yield* Effect.tryPromise({
982 try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal),
983 catch: (cause) =>
984 new BootServiceCommandError({ step: "stopping the installed service", cause }),
985 });
986 });
987 const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
988 const resolveTarget = (systemdUnitDir: string | undefined) => {
989 const manager = selectBootServiceManager({
990 platform,
991 homeDir,
992 xdgConfigHome,
993 systemdUnitDir,
994 uid,
995 path,
996 environmentPath,
997 ...(windowsSession.localAppData === "" || windowsSession.userId === "\\"
998 ? {}
999 : {
1000 windows: {
1001 session: windowsSession,
1002 steps: {
1003 disable: disableWindowsTask,
1004 stopLauncher: stopWindowsLauncher,
1005 remove: changeWindowsTask("removing the scheduled task", "/Delete", "/F"),
1006 },
1007 },
1008 }),
1009 });
1010 const unitPath = manager?.unitPath ?? "";
1011 const plan: BootServicePlan = {
1012 program: [runtimePaths.entryPath, "__service-launcher"],
1013 baseDir: input.baseDir,
1014 logPath,
1015 unitPath,
1016 };
1017 return { manager, unitPath, plan };
1018 };
1019 let systemdUnitDir = platform === "linux" ? yield* readSystemdUnitDirectory(runner) : undefined;
1020 let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir);
1021 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
1022 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
1023 const otherBaseDirOf = (unit: string) => {
1024 const installedBaseDir = bootServiceBaseDirOf(unit);
1025 return installedBaseDir !== undefined &&
1026 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
1027 ? installedBaseDir
1028 : undefined;
1029 };
1030 const writeDurably = (filePath: string, contents: string | Uint8Array) =>
1031 Effect.scoped(
1032 Effect.gen(function* () {
1033 const directory = path.dirname(filePath);
1034 yield* fs.makeDirectory(directory, { recursive: true });
1035 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
1036 yield* typeof contents === "string"
1037 ? fs.writeFileString(tempPath, contents, { mode: 0o600 })
1038 : fs.writeFile(tempPath, contents, { mode: 0o600 });
1039 // Opened read-write: Windows refuses to flush a handle without write access.
1040 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
1041 yield* fs.rename(tempPath, filePath);
1042 // Windows has no directory fsync (EPERM); NTFS journals the rename.
1043 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
1044 Effect.catchIf(
1045 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
1046 () => Effect.void,
1047 ),
1048 );
1049 }),
1050 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1051 const planForUnit = (unit: string): BootServicePlan => {
1052 const effectiveInstallBinDir =
1053 installBinDir || serviceUnitEnvironmentValueOf(unit, "T3CODE_INSTALL_BIN_DIR");
1054 return effectiveInstallBinDir ? { ...plan, installBinDir: effectiveInstallBinDir } : plan;
1055 };
1056 const requireManager = Effect.suspend(() =>
1057 detectedManager === undefined
1058 ? new BootServiceUnsupportedError({ platform })
1059 : Effect.succeed(detectedManager),
1060 );
1061
1062 const logFailure = (error: { readonly message: string }) =>
1063 DateTime.now.pipe(
1064 Effect.flatMap((now) =>
1065 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
1066 ),
1067 Effect.ignore,
1068 );
1069
1070 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
1071 step: string,
1072 command: string,
1073 args: ReadonlyArray<string>,
1074 options?: { readonly timeout?: Duration.Input },
1075 ) {
1076 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
1077 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
1078 Effect.filterOrFail(
1079 (result) => result.code === 0,
1080 (result) =>
1081 new BootServiceCommandError({
1082 step,
1083 exitCode: Number(result.code),
1084 stdoutLength: result.stdout.length,
1085 stderrLength: result.stderr.length,
1086 }),
1087 ),
1088 Effect.tapError(logFailure),
1089 );
1090 });
1091
1092 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
1093 Effect.forEach(
1094 steps,
1095 (entry) => {
1096 const run =
1097 "run" in entry
1098 ? entry.run.pipe(
1099 Effect.timeoutOrElse({
1100 duration: entry.timeout ?? Duration.seconds(60),
1101 orElse: () => Effect.fail(new BootServiceCommandError({ step: entry.step })),
1102 }),
1103 Effect.tapError(logFailure),
1104 )
1105 : runStep(
1106 entry.step,
1107 entry.command,
1108 entry.args,
1109 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
1110 );
1111 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
1112 },
1113 { discard: true },
1114 );
1115
1116 const probe = (command: string, args: ReadonlyArray<string>) =>
1117 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
1118 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
1119 Option.isSome(result) && result.value.code === 0;
1120 const lingerArgs = [
1121 "show-user",
1122 ...(uid === undefined ? [] : [String(uid)]),
1123 "--property=Linger",
1124 "--value",
1125 ];
1126 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
1127 includeService: boolean,
1128 ) {
1129 const [manager, linger] = yield* Effect.all(
1130 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
1131 { concurrency: "unbounded" },
1132 );
1133 const problems: BootServiceProblem[] = [];
1134 if (!succeeded(manager)) problems.push("user-manager-unavailable");
1135 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
1136 if (lingering !== "yes") {
1137 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
1138 }
1139 if (includeService && succeeded(manager)) {
1140 const [enabled, active] = yield* Effect.all(
1141 [
1142 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
1143 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
1144 ],
1145 { concurrency: "unbounded" },
1146 );
1147 if (
1148 !succeeded(enabled) ||
1149 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
1150 ) {
1151 problems.push("service-disabled");
1152 }
1153 if (!succeeded(active)) problems.push("service-stopped");
1154 }
1155 return problems;
1156 });
1157
1158 const requireSystemdPrerequisites = Effect.gen(function* () {
1159 const problems = yield* readSystemdProblems(false);
1160 const firstProblem = problems[0];
1161 if (firstProblem === undefined) return;
1162 // Logind reports a user without a session, whose manager is not running yet, as linger-unavailable.
1163 const withoutSession =
1164 problems.includes("linger-unavailable") && problems.includes("user-manager-unavailable");
1165 const lingerDisabled = problems.includes("linger-disabled");
1166 if (rootUnderSudo || (!lingerDisabled && !withoutSession)) {
1167 return yield* new BootServicePrerequisiteError({ problem: firstProblem });
1168 }
1169 yield* runStep("enabling lingering for this user", "loginctl", [
1170 "enable-linger",
1171 "--no-ask-password",
1172 ...(uid === undefined ? [] : [String(uid)]),
1173 ]).pipe(
1174 Effect.mapError(
1175 // Without a session this also fails on hosts that do not run systemd at all.
1176 (cause) =>
1177 new BootServicePrerequisiteError({
1178 problem: lingerDisabled ? "linger-disabled" : firstProblem,
1179 cause,
1180 }),
1181 ),
1182 );
1183 // Lingering starts the user manager asynchronously.
1184 const remaining = yield* readSystemdProblems(false).pipe(
1185 Effect.repeat({
1186 schedule: Schedule.spaced("500 millis"),
1187 times: 10,
1188 while: (current) => current.includes("user-manager-unavailable"),
1189 }),
1190 );
1191 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
1192 });
1193
1194 const withSelectionLock = <A, E, R>(selectionPath: string, operation: Effect.Effect<A, E, R>) =>
1195 Effect.acquireUseRelease(
1196 Effect.tryPromise({
1197 try: () => acquireServiceSelectionLock(selectionPath),
1198 catch: (cause) => new BootServiceInstallError({ cause }),
1199 }),
1200 () => operation,
1201 (release) => Effect.sync(release),
1202 );
1203
1204 // Running means the launcher holds its lock: a task can stay running after the
1205 // launcher exits, while agents it left behind hold the console host open.
1206 const readSchtasksProblems = Effect.fn("cloud.boot_service.read_schtasks_problems")(function* (
1207 unit: Option.Option<string>,
1208 ) {
1209 const [task, running] = yield* Effect.all(
1210 [
1211 probe("schtasks", ["/Query", "/TN", windowsSession.taskName, "/XML"]),
1212 Effect.promise(() => serviceLauncherIsRunning(launcherLockPath(unit))),
1213 ],
1214 { concurrency: "unbounded" },
1215 );
1216 const problems: BootServiceProblem[] = [];
1217 if (Option.isNone(task) || task.value.code !== 0 || serviceTaskIsDisabled(task.value.stdout)) {
1218 problems.push("service-disabled");
1219 }
1220 if (!running) problems.push("service-stopped");
1221 return problems;
1222 });
1223
1224 // Reuse the desktop marker so already released servers recognize the restart.
1225 const restartMarker = path.join(input.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE);
1226 const markRestart = fs.writeFileString(restartMarker, "", { mode: 0o600 }).pipe(
1227 Effect.as(true),
1228 Effect.catch((error) =>
1229 Effect.logWarning("Could not mark the service restart to preserve its relay tunnel", {
1230 errorTag: error._tag,
1231 }).pipe(Effect.as(false)),
1232 ),
1233 );
1234 const stopForRestart = (steps: ReadonlyArray<BootServiceStep>, queued = false) =>
1235 Effect.acquireUseRelease(
1236 markRestart,
1237 () => runSteps(steps),
1238 (marked, exit) =>
1239 // When a restart is queued, the outgoing server still needs to read the marker.
1240 marked && (!queued || Exit.isFailure(exit))
1241 ? fs.remove(restartMarker, { force: true }).pipe(Effect.ignore)
1242 : Effect.void,
1243 );
1244 const handOffRestart = (handoff: BootServiceHandoff) =>
1245 runSteps(handoff.prepare).pipe(Effect.andThen(stopForRestart(handoff.restart, true)));
1246
1247 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
1248 readonly allowDowngrade?: boolean;
1249 readonly start?: boolean;
1250 }) {
1251 let manager = yield* requireManager;
1252 if (manager.kind === "systemd" && systemdUnsafeValue(plan)) {
1253 return yield* new BootServiceBaseDirUnsupportedError({ baseDir: input.baseDir });
1254 }
1255 // The unit is per user. Rewriting one that serves another home moves the
1256 // service onto this home's data, which looks like every thread vanished.
1257 const refuseOtherBaseDir = Effect.gen(function* () {
1258 const existingUnit = yield* readUnit().pipe(Effect.option);
1259 const installedBaseDir = Option.isSome(existingUnit)
1260 ? otherBaseDirOf(existingUnit.value)
1261 : undefined;
1262 if (installedBaseDir !== undefined) {
1263 return yield* new BootServiceOtherBaseDirError({
1264 installedBaseDir,
1265 baseDir: input.baseDir,
1266 });
1267 }
1268 });
1269 yield* refuseOtherBaseDir;
1270 yield* fs
1271 .makeDirectory(input.logsDir, { recursive: true })
1272 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1273
1274 if (manager.kind === "systemd") {
1275 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
1276 // Without a session the manager was unreachable at construction, and the one lingering
1277 // started may use another config root than this shell's XDG_CONFIG_HOME.
1278 if (systemdUnitDir === undefined) {
1279 systemdUnitDir = yield* readSystemdUnitDirectory(runner);
1280 ({ manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir));
1281 manager = yield* requireManager;
1282 yield* refuseOtherBaseDir;
1283 }
1284 }
1285
1286 yield* ensurePinnedRuntimeInstalled({
1287 baseDir: input.baseDir,
1288 version: input.cliVersion,
1289 fs,
1290 path,
1291 runner,
1292 httpClient,
1293 platform,
1294 arch,
1295 releaseBaseUrl,
1296 validate: (runtime) =>
1297 runner
1298 .run({
1299 command: pinnedRuntimeCommand(runtime).command,
1300 args: [...pinnedRuntimeCommand(runtime).args, "--version"],
1301 timeout: Duration.seconds(30),
1302 })
1303 .pipe(
1304 Effect.mapError(
1305 (cause) =>
1306 new PinnedRuntimeInstallError({
1307 step: "verifying the pinned t3 runtime",
1308 cause,
1309 }),
1310 ),
1311 Effect.flatMap((result) => {
1312 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
1313 return result.code === 0 && reportedVersion === input.cliVersion
1314 ? Effect.void
1315 : Effect.fail(
1316 new PinnedRuntimeInstallError({
1317 step: "verifying the pinned t3 runtime",
1318 exitCode: Number(result.code),
1319 stdoutLength: result.stdout.length,
1320 stderrLength: result.stderr.length,
1321 }),
1322 );
1323 }),
1324 ),
1325 }).pipe(
1326 Effect.mapError((error) =>
1327 error._tag === "PinnedRuntimeInstallError"
1328 ? new BootServiceCommandError({
1329 step: error.step,
1330 exitCode: error.exitCode,
1331 stdoutLength: error.stdoutLength,
1332 stderrLength: error.stderrLength,
1333 cause: error,
1334 })
1335 : new BootServiceInstallError({ cause: error }),
1336 ),
1337 );
1338 const installed = yield* fs
1339 .exists(unitPath)
1340 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1341 // Stop outside the selection lock: the launcher may be waiting to acquire it.
1342 const start = options?.start !== false;
1343 if (installed && start && runningInsideService && manager.kind === "systemd") {
1344 // Stopping the unit from inside it kills this process before the start.
1345 // A transient unit runs the same install from outside, stop first, so it
1346 // still serialises with a remote update the launcher may be starting.
1347 yield* runStep("handing the install to a transient unit", "systemd-run", [
1348 "--user",
1349 "--collect",
1350 "--quiet",
1351 // Transient properties reach systemd literally, unlike unit-file specifiers.
1352 `--property=StandardOutput=append:${logPath}`,
1353 `--property=StandardError=append:${logPath}`,
1354 `--setenv=${SERVICE_UNIT_ENV}=`,
1355 runtimePaths.entryPath,
1356 "service",
1357 "install",
1358 "--base-dir",
1359 // systemd expands $VAR in arguments (not in the executable path).
1360 input.baseDir.replaceAll("$", () => "$$"),
1361 ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
1362 ]);
1363 const unit = yield* readUnit().pipe(
1364 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1365 );
1366 return { ...planForUnit(unit), handedOff: true };
1367 }
1368 // Task Scheduler restarts the task itself, so the files are written as for a deferred
1369 // restart while this launcher keeps running, then the restart is handed to the manager.
1370 const handoff =
1371 installed && start && runningInsideService && manager.kind === "schtasks"
1372 ? manager.handoff
1373 : undefined;
1374 if (installed && start && handoff === undefined) {
1375 yield* stopForRestart(manager.stop);
1376 }
1377
1378 // State first, then unit. The launcher acquires only one at a time, and a
1379 // failure to lock the unit must never prevent its durable update commit.
1380 const installedPlan = yield* withSelectionLock(
1381 statePath,
1382 withSelectionLock(
1383 unitPath,
1384 Effect.gen(function* () {
1385 const currentlyInstalled = yield* fs.exists(unitPath);
1386 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
1387 if (Option.isSome(previousStateText)) {
1388 const installedVersion = serviceStateActiveVersion(previousStateText.value);
1389 if (serviceStateHasPendingUpdate(previousStateText.value)) {
1390 const windows = platform === "win32";
1391 const quote = (word: string) => `'${word.replaceAll("'", windows ? "''" : "'\\''")}'`;
1392 const launcher = (version: string) =>
1393 quote(pinnedRuntimePaths(path, input.baseDir, version, platform).entryPath);
1394 return yield* new BootServiceUpdatePendingError(
1395 !currentlyInstalled && installedVersion !== undefined
1396 ? {
1397 // PowerShell has no inline variable assignment; the launcher takes a flag.
1398 recoveryCommand: windows
1399 ? `& ${launcher(installedVersion)} __service-launcher --base-dir ${quote(input.baseDir)}`
1400 : `T3CODE_HOME=${quote(input.baseDir)} ${launcher(installedVersion)} __service-launcher`,
1401 }
1402 : {},
1403 );
1404 }
1405 // Read the final version after stopping the launcher; a remote update may finish after the status check.
1406 if (
1407 installedVersion !== undefined &&
1408 options?.allowDowngrade !== true &&
1409 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
1410 ) {
1411 return yield* new BootServiceDowngradeRefusedError({
1412 installedVersion,
1413 targetVersion: input.cliVersion,
1414 });
1415 }
1416 }
1417 yield* fs
1418 .makeDirectory(path.dirname(unitPath), { recursive: true })
1419 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1420 // Files can match the new version even when activation fails; keep that install retryable.
1421 yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
1422 const plan = planForUnit(currentlyInstalled ? yield* readUnit() : "");
1423 yield* writeDurably(
1424 statePath,
1425 // @effect-diagnostics-next-line globalJsonInEffect:off - fixed launcher-owned document.
1426 `${JSON.stringify(
1427 {
1428 protocol: SERVICE_LAUNCHER_PROTOCOL,
1429 activeVersion: input.cliVersion,
1430 } satisfies ServiceState,
1431 null,
1432 2,
1433 )}\n`,
1434 );
1435 if (
1436 (!start || handoff !== undefined) &&
1437 (currentlyInstalled || Option.isSome(previousStateText))
1438 ) {
1439 const written = yield* fs.readFileString(statePath);
1440 if (serviceStateActiveVersion(written) !== input.cliVersion) {
1441 return yield* new BootServiceUpdatePendingError();
1442 }
1443 }
1444 const unit = manager.render(plan);
1445 yield* writeDurably(
1446 unitPath,
1447 manager.kind === "schtasks" ? encodeServiceTask(unit) : unit,
1448 );
1449 if (!start && manager.kind === "schtasks") yield* refreshWindowsTask(unit);
1450 return plan;
1451 }),
1452 ),
1453 ).pipe(
1454 Effect.tap(
1455 Effect.gen(function* () {
1456 if (handoff !== undefined) {
1457 yield* handOffRestart(handoff);
1458 } else if (start) {
1459 yield* runSteps(manager.activate);
1460 yield* withSelectionLock(
1461 statePath,
1462 Effect.gen(function* () {
1463 // A concurrent deferred install may now be waiting for a newer restart.
1464 const selected = parseServiceState(yield* fs.readFileString(statePath));
1465 if (selected?.activeVersion === input.cliVersion && selected.update === undefined) {
1466 yield* fs.remove(restartPendingPath, { force: true });
1467 }
1468 }),
1469 );
1470 }
1471 }),
1472 ),
1473 Effect.mapError((cause) =>
1474 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
1475 ),
1476 Effect.tapError(() =>
1477 installed && start && handoff === undefined
1478 ? runSteps(manager.restart).pipe(Effect.ignore)
1479 : Effect.void,
1480 ),
1481 );
1482 return handoff !== undefined ? { ...installedPlan, handedOff: true } : installedPlan;
1483 });
1484
1485 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
1486 const manager = yield* requireManager;
1487 const unit = yield* readUnit().pipe(Effect.option);
1488 if (Option.isNone(unit)) return "skipped" as const;
1489 const installedBaseDir = bootServiceBaseDirOf(unit.value);
1490 if (
1491 installedBaseDir === undefined ||
1492 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
1493 ) {
1494 return "skipped" as const;
1495 }
1496 // Writes no state, and the launcher lets an update transition in flight
1497 // finish before the queued stop tears it down.
1498 if (runningInsideService && manager.handoff !== undefined) {
1499 yield* handOffRestart(manager.handoff);
1500 return "queued" as const;
1501 }
1502 yield* stopForRestart(manager.stop);
1503 yield* runSteps(manager.activate).pipe(
1504 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
1505 );
1506 yield* fs.remove(restartPendingPath, { force: true });
1507 return "restarted" as const;
1508 }).pipe(
1509 Effect.mapError((cause) =>
1510 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
1511 ),
1512 Effect.withSpan("cloud.boot_service.restart"),
1513 );
1514
1515 const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(
1516 operation: Effect.Effect<A, E, R>,
1517 ): Effect.fn.Return<A, E | BootServiceError, R> {
1518 if (detectedManager === undefined) return yield* operation;
1519 const manager = detectedManager;
1520 const unit = yield* readUnit().pipe(Effect.option);
1521 if (Option.isNone(unit)) return yield* operation;
1522 const installedBaseDir = bootServiceBaseDirOf(unit.value);
1523 if (
1524 installedBaseDir === undefined ||
1525 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
1526 ) {
1527 return yield* operation;
1528 }
1529 // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid.
1530 // Always stop; restore only if previously active, enabled, or loaded,
1531 // so disabled crash loops stay stopped.
1532 const restore =
1533 manager.kind === "systemd"
1534 ? yield* Effect.map(
1535 Effect.all(
1536 [
1537 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
1538 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
1539 ],
1540 { concurrency: "unbounded" },
1541 ),
1542 ([enabled, active]) => succeeded(active) || succeeded(enabled),
1543 )
1544 : manager.kind === "schtasks"
1545 ? // A task disabled while its launcher runs was left that way by an interrupted stop.
1546 yield* Effect.map(
1547 readSchtasksProblems(unit),
1548 (problems) =>
1549 !problems.includes("service-disabled") || !problems.includes("service-stopped"),
1550 )
1551 : succeeded(
1552 yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
1553 );
1554 return yield* Effect.acquireUseRelease(
1555 // Require every stop before repair when restoring, so the server releases the database.
1556 // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job.
1557 // A failed stop may still stop the service, so restoration runs either way.
1558 runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
1559 (stopped): Effect.Effect<A, E | BootServiceError, R> =>
1560 Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
1561 (_, exit) => {
1562 if (!restore) return Effect.void;
1563 // Start only: `activate` would also enable a unit the user disabled.
1564 // When the operation itself failed, its error is the one worth reporting.
1565 const start = runSteps(manager.restart);
1566 return Exit.isFailure(exit) ? Effect.ignore(start) : start;
1567 },
1568 );
1569 });
1570
1571 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
1572 const manager = yield* requireManager;
1573 if (
1574 !(yield* fs
1575 .exists(unitPath)
1576 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
1577 )
1578 return false;
1579 yield* runSteps(manager.deactivate);
1580 yield* fs
1581 .remove(unitPath)
1582 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1583 yield* runSteps(manager.finalize);
1584 return true;
1585 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
1586
1587 const status: BootService["Service"]["status"] = Effect.gen(function* () {
1588 const manager = detectedManager;
1589 if (manager === undefined) {
1590 return { supported: false, installed: false, current: false, unitPath, logPath };
1591 }
1592 if (!(yield* fs.exists(unitPath))) {
1593 return { supported: true, installed: false, current: false, unitPath, logPath };
1594 }
1595 const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
1596 readUnit(),
1597 fs.exists(runtimePaths.entryPath),
1598 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
1599 fs.readFileString(statePath).pipe(Effect.option),
1600 ]);
1601 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
1602 const installedVersion = Option.isSome(stateText)
1603 ? serviceStateActiveVersion(stateText.value)
1604 : undefined;
1605 const installedBaseDir = bootServiceBaseDirOf(unit);
1606 const otherBaseDir = otherBaseDirOf(unit);
1607 const normalizeUnit = (contents: string) =>
1608 manager.kind === "launchd"
1609 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
1610 : contents;
1611 const problems: BootServiceProblem[] =
1612 manager.kind === "systemd"
1613 ? [...(yield* readSystemdProblems(true))]
1614 : manager.kind === "schtasks"
1615 ? [...(yield* readSchtasksProblems(Option.some(unit)))]
1616 : [];
1617 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1618 return {
1619 supported: true,
1620 installed: true,
1621 ...(installedVersion === undefined ? {} : { installedVersion }),
1622 ...(installedBaseDir === undefined ? {} : { installedBaseDir }),
1623 ...(otherBaseDir === undefined ? {} : { otherBaseDir }),
1624 problems,
1625 current:
1626 problems.length === 0 &&
1627 !(manager.kind === "systemd" && systemdUnsafeValue(planForUnit(unit))) &&
1628 normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) &&
1629 runtimeEntryExists &&
1630 Option.isSome(runtimeSentinel) &&
1631 runtimeSentinel.value.trim() === input.cliVersion &&
1632 state?.activeVersion === input.cliVersion &&
1633 state?.update?.status !== "pending",
1634 unitPath,
1635 logPath,
1636 };
1637 }).pipe(
1638 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1639 Effect.withSpan("cloud.boot_service.status"),
1640 );
1641
1642 return BootService.of({ install, restart, withStopped, uninstall, status });
1643 });
1644
1645 export const layer = (input: {
1646 readonly baseDir: string;
1647 readonly logsDir: string;
1648 readonly cliVersion: string;
1649 readonly host?: BootServiceHost;
1650 }) => Layer.effect(BootService, make(input));