Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Console from "effect/Console";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Path from "effect/Path";
6import * as Terminal from "effect/Terminal";
7import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
8import { FetchHttpClient } from "effect/http";
9
10import packageJson from "../../package.json" with { type: "json" };
11import * as BootService from "../cloud/bootService.ts";
12import * as ServiceProtection from "../cloud/serviceProtection.ts";
13import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
14import type * as ServerConfig from "../config.ts";
15import * as ProcessRunner from "../processRunner.ts";
16import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
17import { resolveEntryPath } from "./invocation.ts";
18
19export const layer = (config: ServerConfig.ServerConfig["Service"]) =>
20 BootService.layer({
21 baseDir: config.baseDir,
22 logsDir: config.logsDir,
23 cliVersion: packageJson.version,
24 }).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(FetchHttpClient.layer));
25
26export type ServiceReconcileResult =
27 | {
28 readonly changed: false;
29 readonly status: BootService.BootServiceStatus;
30 }
31 | {
32 readonly changed: true;
33 readonly previouslyInstalled: boolean;
34 readonly plan: BootService.BootServicePlan;
35 };
36
37const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
38 readonly allowDowngrade?: boolean;
39 readonly start?: boolean;
40}) {
41 const service = yield* BootService.BootService;
42 const status = yield* service.status;
43 if (status.installed && status.current) {
44 return { changed: false, status } satisfies ServiceReconcileResult;
45 }
46 if (
47 status.installedVersion !== undefined &&
48 options?.allowDowngrade !== true &&
49 compareExactServiceVersions(packageJson.version, status.installedVersion) < 0
50 ) {
51 return yield* new BootService.BootServiceDowngradeRefusedError({
52 installedVersion: status.installedVersion,
53 targetVersion: packageJson.version,
54 });
55 }
56 const plan = yield* service.install(options);
57 return {
58 changed: true,
59 previouslyInstalled: status.installed,
60 plan,
61 } satisfies ServiceReconcileResult;
62});
63
64function formatServiceChange(
65 result: Extract<ServiceReconcileResult, { readonly changed: true }>,
66): string {
67 if (result.plan.handedOff === true) {
68 return `Handed the T3 Code service switch to t3@${packageJson.version} to a separate systemd unit, since this session runs inside the service and disconnects when it restarts.\nResult: ${result.plan.logPath}`;
69 }
70 return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`;
71}
72
73function formatProtection(
74 protection: ServiceProtection.ServiceProtectionState | undefined,
75): ReadonlyArray<string> {
76 if (protection === undefined) return [];
77 return [
78 protection.unprotected === undefined
79 ? ` Memory protection: on${protection.setByProtect ? " (t3 service protect)" : ""}`
80 : ` Memory protection: off, ${protection.unprotected} grants none. Run \`t3 service protect\`.`,
81 ...(protection.oomScoreAdj === undefined ? [] : [` OOM score: ${protection.oomScoreAdj}`]),
82 ];
83}
84
85function formatServiceStatus(
86 status: BootService.BootServiceStatus,
87 cliVersion: string,
88 protection?: ServiceProtection.ServiceProtectionState,
89): string {
90 if (!status.supported) {
91 return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
92 }
93 if (!status.installed) {
94 return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
95 }
96 const installedVersion = status.installedVersion ?? cliVersion;
97 const problems = (status.problems ?? []).map(
98 (problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem)}`,
99 );
100 if (
101 !status.current &&
102 status.installedVersion !== undefined &&
103 compareExactServiceVersions(status.installedVersion, cliVersion) > 0
104 ) {
105 return [
106 "T3 Code service",
107 ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
108 ` Unit: ${status.unitPath}`,
109 ` Logs: ${status.logPath}`,
110 ...formatProtection(protection),
111 ...problems,
112 ` Next: Run \`t3 update ${installedVersion}\` to match it, or pass \`--allow-downgrade\` to \`t3 service install\` explicitly.`,
113 ].join("\n");
114 }
115 return [
116 "T3 Code service",
117 ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
118 ` Unit: ${status.unitPath}`,
119 ` Logs: ${status.logPath}`,
120 ...formatProtection(protection),
121 ...problems,
122 ...(status.current ? [] : [" Next: Run `t3 service install` to repair it."]),
123 ].join("\n");
124}
125
126const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E, R>(
127 flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
128 run: Effect.Effect<A, E, R>,
129) {
130 const logLevel = yield* GlobalFlag.LogLevel;
131 const config = yield* resolveCliAuthConfig(flags, logLevel);
132 return yield* run.pipe(Effect.provide(layer(config)));
133});
134
135const serviceReconcileFlags = {
136 ...projectLocationFlags,
137 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
138 Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
139 Flag.withDefault(false),
140 ),
141};
142
143const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
144 Command.withDescription("Install T3 Code as a background service for this user."),
145 Command.withHandler((flags) =>
146 runServiceCommand(
147 flags,
148 Effect.gen(function* () {
149 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
150 if (!result.changed) {
151 yield* Console.log(
152 `T3 Code service is already installed with t3@${packageJson.version} (${yield* resolveEntryPath}).`,
153 );
154 return;
155 }
156 yield* Console.log(formatServiceChange(result));
157 }),
158 ),
159 ),
160);
161
162const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
163 Command.withDescription("Deprecated. Run `t3 update` to move to a newer release."),
164 Command.unlisted,
165 Command.withHandler((flags) =>
166 runServiceCommand(
167 flags,
168 Effect.gen(function* () {
169 yield* Console.log(
170 "`t3 service update` is deprecated: run `t3 update` to move to a newer release, or `t3 service install` to repair the service. Repairing now.",
171 );
172 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
173 if (!result.changed) {
174 yield* Console.log(
175 `T3 Code service is already using t3@${packageJson.version} (${yield* resolveEntryPath}).`,
176 );
177 return;
178 }
179 yield* Console.log(formatServiceChange(result));
180 }),
181 ),
182 ),
183);
184
185const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe(
186 Command.withDescription(
187 "Restart the background service. Picks up a version installed by `t3 update` that was not restarted at the time.",
188 ),
189 Command.withHandler((flags) =>
190 runServiceCommand(
191 flags,
192 Effect.gen(function* () {
193 const service = yield* BootService.BootService;
194 const status = yield* service.status;
195 const outcome = yield* service.restart;
196 const onVersion =
197 status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`;
198 yield* Console.log(
199 outcome === "restarted"
200 ? `Restarted the T3 Code service${onVersion}.`
201 : outcome === "queued"
202 ? `Queued a restart of the T3 Code service${onVersion}. This session runs inside the service and disconnects when it goes down.\nLogs: ${status.logPath}`
203 : "T3 Code service is not installed.",
204 );
205 }),
206 ),
207 ),
208);
209
210const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
211 Command.withDescription("Stop and remove the T3 Code background service."),
212 Command.withHandler((flags) =>
213 runServiceCommand(
214 flags,
215 Effect.gen(function* () {
216 const service = yield* BootService.BootService;
217 const removed = yield* service.uninstall;
218 yield* Console.log(
219 removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
220 );
221 }),
222 ),
223 ),
224);
225
226const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
227 Command.withDescription("Show whether the T3 Code background service is installed."),
228 Command.withHandler((flags) =>
229 runServiceCommand(
230 flags,
231 Effect.gen(function* () {
232 const service = yield* BootService.BootService;
233 const path = yield* Path.Path;
234 const status = yield* service.status;
235 const protection =
236 status.installed && (yield* HostProcess.Platform) === "linux"
237 ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe(
238 Effect.provide(ProcessRunner.layer),
239 )
240 : undefined;
241 yield* Console.log(formatServiceStatus(status, packageJson.version, protection));
242 }),
243 ),
244 ),
245);
246
247const formatDropIns = (dropIns: ReadonlyArray<ServiceProtection.DropIn>) =>
248 dropIns.map(
249 ({ path, contents }) => ` ${path}: ${contents.trimEnd().split("\n").slice(1).join(" ")}`,
250 );
251
252const confirm = (yes: boolean, message: string) =>
253 yes ? Effect.succeed(true) : Prompt.run(Prompt.Confirm({ message, initial: false }));
254
255const serviceProtectCommand = Command.make("protect", {
256 ...projectLocationFlags,
257 undo: Flag.Boolean("undo").pipe(
258 Flag.withDescription("Remove the protection this command set up."),
259 Flag.withDefault(false),
260 ),
261 yes: Flag.Boolean("yes").pipe(
262 Flag.withDescription("Answer yes to every question, including SSH and Tailscale."),
263 Flag.withDefault(false),
264 ),
265}).pipe(
266 Command.withDescription(
267 "Protect the T3 Code server from agents under memory pressure (Linux with systemd). Asks for sudo.",
268 ),
269 Command.withHandler((flags) =>
270 Effect.gen(function* () {
271 const unsupported = "Service protection needs Linux with systemd.";
272 if ((yield* HostProcess.Platform) !== "linux") return yield* Console.log(unsupported);
273 // Before resolving config, which creates T3 directories that root would then own.
274 if ((yield* HostProcess.UserId) === 0) {
275 return yield* Console.log(
276 "Run `t3 service protect` as the user that runs T3 Code, without sudo. It asks for sudo when it needs root.",
277 );
278 }
279 return yield* runServiceCommand(
280 flags,
281 Effect.gen(function* () {
282 const uid = yield* HostProcess.UserId;
283 const remote = yield* ServiceProtection.detectRemoteAccessUnits;
284 const { unitPath } = yield* (yield* BootService.BootService).status;
285 if (uid === undefined || remote === undefined || unitPath === "") {
286 return yield* Console.log(unsupported);
287 }
288 const userUnitDir = (yield* Path.Path).dirname(unitPath);
289
290 if (flags.undo) {
291 const installed = yield* ServiceProtection.installedProtection(
292 ServiceProtection.protectionPlan({
293 uid,
294 userUnitDir,
295 remoteAccessUnits: ServiceProtection.REMOTE_ACCESS_UNITS,
296 }),
297 );
298 if (installed === undefined) {
299 return yield* Console.log("T3 Code service protection is not set up.");
300 }
301 yield* Console.log(
302 [
303 "Removes:",
304 ...[...installed.system, ...installed.user, installed.managerDefaults].map(
305 ({ path, shared }) =>
306 ` ${path}${shared === true ? " (kept while another user is protected)" : ""}`,
307 ),
308 ].join("\n"),
309 );
310 if (!(yield* confirm(flags.yes, "Remove T3 Code service protection?"))) return;
311 yield* ServiceProtection.removeProtection(installed);
312 return yield* Console.log(
313 "Removed T3 Code service protection. The server's OOM score returns to normal after `t3 service restart`.",
314 );
315 }
316
317 const names = remote.map((unit) => unit.replace(/\.service$/, "")).join(" and ");
318 const protectRemote =
319 remote.length > 0 &&
320 (yield* confirm(
321 flags.yes,
322 `Also protect ${names} so you can still reach this machine under memory pressure?`,
323 ));
324 const plan = ServiceProtection.protectionPlan({
325 uid,
326 userUnitDir,
327 remoteAccessUnits: protectRemote ? remote : [],
328 });
329 yield* Console.log(
330 [
331 "As root, through sudo:",
332 ...formatDropIns(plan.system),
333 "As you:",
334 ...formatDropIns([plan.managerDefaults, ...plan.user]),
335 ].join("\n"),
336 );
337 if (!(yield* confirm(flags.yes, "Apply these settings?"))) return;
338 yield* ServiceProtection.applyProtection(plan);
339 yield* Console.log(
340 "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`.",
341 );
342 }).pipe(Effect.provide(ProcessRunner.layer)),
343 );
344 }),
345 ),
346);
347
348export type ServiceOnboardingOutcome = "ready" | "pending" | "skipped";
349
350export const offerServiceDuringOnboarding = Effect.gen(function* () {
351 const service = yield* BootService.BootService;
352 const status = yield* service.status;
353 const { supported, installed, current } = status;
354 if (!supported) {
355 return "skipped" as const;
356 }
357 if (installed && current) {
358 yield* Console.log("T3 Code is already set up to run in the background on this machine.");
359 return "ready" as const;
360 }
361 for (const problem of status.problems ?? []) {
362 yield* Console.warn(`[${problem}] ${BootService.formatBootServiceProblem(problem)}`);
363 }
364 if (
365 installed &&
366 status.installedVersion !== undefined &&
367 compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
368 ) {
369 yield* Console.log(
370 `A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,
371 );
372 return "skipped" as const;
373 }
374 const platform = yield* HostProcess.Platform;
375 const wanted = yield* Prompt.run(
376 Prompt.Confirm({
377 message: installed
378 ? "The installed T3 Code service needs an update or repair. Update it now?"
379 : platform === "darwin"
380 ? "Run T3 Code in the background whenever you log in to this Mac? " +
381 "It stays reachable through T3 Connect while you are logged in."
382 : "Run T3 Code in the background whenever this machine boots? " +
383 "It stays reachable through T3 Connect even after you log out.",
384 initial: true,
385 }),
386 );
387 if (!wanted) {
388 return "skipped" as const;
389 }
390 const result = yield* reconcileService();
391 if (result.changed) {
392 yield* Console.log(
393 result.plan.handedOff === true
394 ? formatServiceChange(result)
395 : `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
396 );
397 }
398 return result.changed && result.plan.handedOff === true
399 ? ("pending" as const)
400 : ("ready" as const);
401});
402
403const reportServiceSetupFailure = (error: BootService.BootServiceError) =>
404 Console.warn(`Background setup did not finish: ${error.message}`).pipe(
405 Effect.as("skipped" as const),
406 );
407
408export const recoverServiceOnboardingOffer = <R>(
409 offer: Effect.Effect<
410 ServiceOnboardingOutcome,
411 BootService.BootServiceError | Terminal.QuitError,
412 R
413 >,
414) =>
415 offer.pipe(
416 Effect.catchTags({
417 QuitError: () => Effect.succeed("skipped" as const),
418 BootServiceUnsupportedError: (error) =>
419 Console.log(`Skipping background setup: ${error.message}`).pipe(
420 Effect.as("skipped" as const),
421 ),
422 BootServiceCommandError: reportServiceSetupFailure,
423 BootServiceInstallError: reportServiceSetupFailure,
424 BootServicePrerequisiteError: reportServiceSetupFailure,
425 BootServiceUpdatePendingError: reportServiceSetupFailure,
426 BootServiceDowngradeRefusedError: reportServiceSetupFailure,
427 }),
428 );
429
430export const serviceCommand = Command.make("service").pipe(
431 Command.withDescription("Manage the T3 Code background service."),
432 Command.withSubcommands([
433 serviceInstallCommand,
434 serviceRestartCommand,
435 serviceUninstallCommand,
436 serviceStatusCommand,
437 serviceProtectCommand,
438 serviceUpdateCommand,
439 ]),
440);