@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 506 lines 20.4 KB
Raw
1 import * as NodeUtil from "node:util";
2
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Console from "effect/Console";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Layer from "effect/Layer";
8 import * as Path from "effect/Path";
9 import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
10 import { FetchHttpClient } from "effect/http";
11
12 import packageJson from "../../package.json" with { type: "json" };
13 import * as BootService from "../cloud/bootService.ts";
14 import * as ServiceProtection from "../cloud/serviceProtection.ts";
15 import { compareExactServiceVersions, SERVICE_ENV_FILE } from "../cloud/serviceProtocol.ts";
16 import * as ServerConfig from "../config.ts";
17 import * as ProcessRunner from "../processRunner.ts";
18 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
19 import { resolveEntryPath, resolveHostCliHint } from "./invocation.ts";
20
21 export const layer = (config: ServerConfig.ServerConfig["Service"]) =>
22 BootService.layer({
23 baseDir: config.baseDir,
24 logsDir: config.logsDir,
25 cliVersion: packageJson.version,
26 }).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(FetchHttpClient.layer));
27
28 export type ServiceReconcileResult =
29 | {
30 readonly changed: false;
31 readonly status: BootService.BootServiceStatus;
32 }
33 | {
34 readonly changed: true;
35 readonly previouslyInstalled: boolean;
36 readonly plan: BootService.BootServicePlan;
37 };
38
39 const SERVICE_ENV_KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/u;
40
41 /**
42 * Sets or removes (`undefined`) entries in `service.env` text and keeps every
43 * other line, including comments, as the user wrote it.
44 */
45 export const upsertServiceEnv = (
46 contents: string,
47 entries: Readonly<Record<string, string | undefined>>,
48 ): string => {
49 const written = new Set<string>();
50 const source = contents.split("\n");
51 const lines: string[] = [];
52 for (let index = 0, offset = 0; index < source.length;) {
53 const line = source[index]!;
54 const match = SERVICE_ENV_KEY.exec(line);
55 let end = index + 1;
56 if (match !== null) {
57 // util.parseEnv lets a quoted value run to its closing quote across lines,
58 // skipping only spaces, tabs and CRs before the opening quote.
59 const rest = line.slice(match[0].length).replace(/^[ \t\r]+/u, "");
60 const quote = rest[0];
61 if ((quote === '"' || quote === "'" || quote === "`") && !rest.includes(quote, 1)) {
62 const closing = contents.indexOf(quote, offset + line.length);
63 if (closing !== -1) {
64 end += contents.slice(offset + line.length, closing).split("\n").length - 1;
65 }
66 }
67 }
68 const span = source.slice(index, end);
69 offset += span.reduce((length, part) => length + part.length + 1, 0);
70 index = end;
71 const key = match?.[1];
72 if (key === undefined || !Object.hasOwn(entries, key)) {
73 lines.push(span.join("\n"));
74 continue;
75 }
76 const value = entries[key];
77 if (value === undefined || written.has(key)) continue;
78 written.add(key);
79 lines.push(`${key}=${value}`);
80 }
81 while (lines.at(-1) === "") lines.pop();
82 for (const [key, value] of Object.entries(entries)) {
83 if (value !== undefined && !written.has(key)) lines.push(`${key}=${value}`);
84 }
85 return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
86 };
87
88 /** `service.env` under `baseDir`, parsed as the service launcher parses it. */
89 export const readServiceEnv = Effect.fn("cli.service.read_env")(function* (baseDir: string) {
90 const fs = yield* FileSystem.FileSystem;
91 const path = (yield* Path.Path).join(baseDir, SERVICE_ENV_FILE);
92 const contents = (yield* fs.exists(path)) ? yield* fs.readFileString(path) : "";
93 const entries = Object.entries(NodeUtil.parseEnv(contents)).flatMap(([key, value]) =>
94 value === undefined ? [] : [[key, value] as const],
95 );
96 return { path, contents, entries: Object.fromEntries(entries) };
97 });
98
99 export const writeServiceEnv = Effect.fn("cli.service.write_env")(function* (
100 baseDir: string,
101 entries: Readonly<Record<string, string | undefined>>,
102 ) {
103 const fs = yield* FileSystem.FileSystem;
104 const current = yield* readServiceEnv(baseDir);
105 const next = upsertServiceEnv(current.contents, entries);
106 if (next === current.contents) return;
107 yield* fs.makeDirectory(baseDir, { recursive: true });
108 yield* fs.writeFileString(current.path, next);
109 });
110
111 export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
112 readonly allowDowngrade?: boolean;
113 readonly start?: boolean;
114 }) {
115 const { baseDir } = yield* ServerConfig.ServerConfig;
116 const service = yield* BootService.BootService;
117 const status = yield* service.status;
118 // Before the downgrade check, which reads this home's state, not the service's.
119 if (status.otherBaseDir !== undefined) {
120 return yield* new BootService.BootServiceOtherBaseDirError({
121 installedBaseDir: status.otherBaseDir,
122 baseDir,
123 });
124 }
125 if (status.installed && status.current) {
126 return { changed: false, status } satisfies ServiceReconcileResult;
127 }
128 if (status.supported && !status.installed) {
129 // A new service listens on this machine only, until `t3 up` opens the local network.
130 const { entries } = yield* readServiceEnv(baseDir);
131 if (entries.T3CODE_LAN === undefined && entries.T3CODE_HOST === undefined) {
132 yield* writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
133 }
134 }
135 if (
136 status.installedVersion !== undefined &&
137 options?.allowDowngrade !== true &&
138 compareExactServiceVersions(packageJson.version, status.installedVersion) < 0
139 ) {
140 return yield* new BootService.BootServiceDowngradeRefusedError({
141 installedVersion: status.installedVersion,
142 targetVersion: packageJson.version,
143 });
144 }
145 const plan = yield* service.install(options);
146 return {
147 changed: true,
148 previouslyInstalled: status.installed,
149 plan,
150 } satisfies ServiceReconcileResult;
151 });
152
153 export function formatServiceChange(
154 result: Extract<ServiceReconcileResult, { readonly changed: true }>,
155 ): string {
156 if (result.plan.handedOff === true) {
157 return `Service update to t3@${packageJson.version} queued. This session will disconnect.\nLog: ${result.plan.logPath}`;
158 }
159 return `Service ${result.previouslyInstalled ? "updated" : "installed"} · t3@${packageJson.version}\nLog: ${result.plan.logPath}`;
160 }
161
162 const MEMORY_CONTROLLER_DISABLED =
163 "the kernel's memory cgroup controller is disabled. Add `cgroup_enable=memory` to the kernel command line and reboot.";
164
165 function formatProtection(
166 protection: ServiceProtection.ServiceProtectionState | undefined,
167 ): ReadonlyArray<string> {
168 if (protection === undefined) return [];
169 return [
170 !protection.memoryControllerAvailable
171 ? ` Memory protection: unavailable, ${MEMORY_CONTROLLER_DISABLED}`
172 : protection.unprotected === undefined
173 ? ` Memory protection: on${protection.setByProtect ? " (t3 service protect)" : ""}`
174 : ` Memory protection: off, ${protection.unprotected} grants none. Run \`t3 service protect\`.`,
175 ...(protection.oomScoreAdj === undefined ? [] : [` OOM score: ${protection.oomScoreAdj}`]),
176 ];
177 }
178
179 function formatServiceStatus(
180 status: BootService.BootServiceStatus,
181 cliVersion: string,
182 commands: { readonly install: string; readonly restart: string; readonly update: string },
183 protection?: ServiceProtection.ServiceProtectionState,
184 ): string {
185 if (!status.supported) {
186 return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd, Windows with Task Scheduler";
187 }
188 if (!status.installed) {
189 return `T3 Code service\n Status: not installed\n Next: Run \`${commands.install}\`.`;
190 }
191 if (status.otherBaseDir !== undefined) {
192 return [
193 "T3 Code service",
194 " Status: installed for another T3 home",
195 ` Base dir: ${status.otherBaseDir}`,
196 ` Next: Pass \`${BootService.formatBootServiceBaseDirOption(status.otherBaseDir)}\` to manage it.`,
197 ].join("\n");
198 }
199 const installedVersion = status.installedVersion ?? cliVersion;
200 const problems = (status.problems ?? []).map(
201 (problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem, commands)}`,
202 );
203 if (
204 !status.current &&
205 status.installedVersion !== undefined &&
206 compareExactServiceVersions(status.installedVersion, cliVersion) > 0
207 ) {
208 return [
209 "T3 Code service",
210 ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
211 ` Unit: ${status.unitPath}`,
212 ` Logs: ${status.logPath}`,
213 ...formatProtection(protection),
214 ...problems,
215 ` Next: Run \`${commands.update}\` to match it, or pass \`--allow-downgrade\` to \`${commands.install}\` explicitly.`,
216 ].join("\n");
217 }
218 return [
219 "T3 Code service",
220 ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
221 ` Unit: ${status.unitPath}`,
222 ` Logs: ${status.logPath}`,
223 ...formatProtection(protection),
224 ...problems,
225 ...(status.current ? [] : [` Next: Run \`${commands.install}\` to repair it.`]),
226 ].join("\n");
227 }
228
229 const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E, R>(
230 flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
231 run: Effect.Effect<A, E, R>,
232 ) {
233 const logLevel = yield* GlobalFlag.LogLevel;
234 const config = yield* resolveCliAuthConfig(flags, logLevel);
235 return yield* run.pipe(Effect.provide(Layer.merge(layer(config), ServerConfig.layer(config))));
236 });
237
238 const serviceReconcileFlags = {
239 ...projectLocationFlags,
240 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
241 Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
242 Flag.withDefault(false),
243 ),
244 };
245
246 const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
247 Command.withDescription(
248 "Install T3 Code as a background service for this user. `t3 up` also chooses how your other devices reach it.",
249 ),
250 Command.withHandler((flags) =>
251 runServiceCommand(
252 flags,
253 Effect.gen(function* () {
254 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
255 if (!result.changed) {
256 yield* Console.log(
257 `T3 Code service is already installed with t3@${packageJson.version} (${yield* resolveEntryPath}).`,
258 );
259 return;
260 }
261 yield* Console.log(formatServiceChange(result));
262 if (!result.previouslyInstalled) {
263 const upCommand = yield* resolveHostCliHint("up", flags.baseDir);
264 yield* Console.log(`Run \`${upCommand}\` to choose how your other devices reach it.`);
265 }
266 }),
267 ),
268 ),
269 );
270
271 const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
272 Command.withDescription("Deprecated. Run `t3 update` to move to a newer release."),
273 Command.unlisted,
274 Command.withHandler((flags) =>
275 runServiceCommand(
276 flags,
277 Effect.gen(function* () {
278 yield* Console.log(
279 "`t3 service update` is deprecated: run `t3 update` to move to a newer release, or `t3 service install` to repair the service. Repairing now.",
280 );
281 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
282 if (!result.changed) {
283 yield* Console.log(
284 `T3 Code service is already using t3@${packageJson.version} (${yield* resolveEntryPath}).`,
285 );
286 return;
287 }
288 yield* Console.log(formatServiceChange(result));
289 }),
290 ),
291 ),
292 );
293
294 const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe(
295 Command.withDescription(
296 "Restart the background service. Picks up a version installed by `t3 update` that was not restarted at the time.",
297 ),
298 Command.withHandler((flags) =>
299 runServiceCommand(
300 flags,
301 Effect.gen(function* () {
302 const service = yield* BootService.BootService;
303 const status = yield* service.status;
304 const outcome = yield* service.restart;
305 const onVersion =
306 status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`;
307 yield* Console.log(
308 outcome === "restarted"
309 ? `Restarted the T3 Code service${onVersion}.`
310 : outcome === "queued"
311 ? `Queued a restart of the T3 Code service${onVersion}. This session runs inside the service and disconnects when it goes down.\nLogs: ${status.logPath}`
312 : status.otherBaseDir !== undefined
313 ? `The T3 Code service serves ${status.otherBaseDir}, so it was not restarted. Pass \`${BootService.formatBootServiceBaseDirOption(status.otherBaseDir)}\` to restart it.`
314 : "T3 Code service is not installed.",
315 );
316 }),
317 ),
318 ),
319 );
320
321 const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
322 Command.withDescription("Stop and remove the T3 Code background service."),
323 Command.withHandler((flags) =>
324 runServiceCommand(
325 flags,
326 Effect.gen(function* () {
327 const service = yield* BootService.BootService;
328 const path = yield* Path.Path;
329 const { baseDir } = yield* ServerConfig.ServerConfig;
330 // An unreadable unit stays removable; only a unit known to serve another home is kept.
331 const installedBaseDir = yield* service.status.pipe(
332 Effect.map((status) => status.installedBaseDir),
333 Effect.orElseSucceed(() => undefined),
334 );
335 if (
336 installedBaseDir !== undefined &&
337 path.resolve(installedBaseDir) !== path.resolve(baseDir)
338 ) {
339 yield* Console.log(
340 `The T3 Code service serves ${installedBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(installedBaseDir)}\` to remove it.`,
341 );
342 return;
343 }
344 const removed = yield* service.uninstall;
345 yield* Console.log(
346 removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
347 );
348 }),
349 ),
350 ),
351 );
352
353 const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
354 Command.withDescription("Show whether the T3 Code background service is installed."),
355 Command.withHandler((flags) =>
356 runServiceCommand(
357 flags,
358 Effect.gen(function* () {
359 const service = yield* BootService.BootService;
360 const path = yield* Path.Path;
361 const status = yield* service.status;
362 const protection =
363 status.installed && (yield* HostProcess.Platform) === "linux"
364 ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe(
365 Effect.provide(ProcessRunner.layer),
366 )
367 : undefined;
368 const commands = {
369 install: yield* resolveHostCliHint("service install", flags.baseDir),
370 restart: yield* resolveHostCliHint("service restart", flags.baseDir),
371 update: yield* resolveHostCliHint("update", flags.baseDir, [
372 status.installedVersion ?? packageJson.version,
373 ]),
374 };
375 yield* Console.log(formatServiceStatus(status, packageJson.version, commands, protection));
376 }),
377 ),
378 ),
379 );
380
381 const formatDropIns = (dropIns: ReadonlyArray<ServiceProtection.DropIn>) =>
382 dropIns.map(
383 ({ path, contents }) => ` ${path}: ${contents.trimEnd().split("\n").slice(1).join(" ")}`,
384 );
385
386 const confirm = (yes: boolean, message: string) =>
387 yes ? Effect.succeed(true) : Prompt.run(Prompt.Confirm({ message, initial: false }));
388
389 const serviceProtectCommand = Command.make("protect", {
390 ...projectLocationFlags,
391 undo: Flag.Boolean("undo").pipe(
392 Flag.withDescription("Remove the protection this command set up."),
393 Flag.withDefault(false),
394 ),
395 yes: Flag.Boolean("yes").pipe(
396 Flag.withDescription("Answer yes to every question, including SSH and Tailscale."),
397 Flag.withDefault(false),
398 ),
399 }).pipe(
400 Command.withDescription(
401 "Protect the T3 Code server from agents under memory pressure (Linux with systemd). Asks for sudo.",
402 ),
403 Command.withHandler((flags) =>
404 Effect.gen(function* () {
405 const unsupported = "Service protection needs Linux with systemd.";
406 if ((yield* HostProcess.Platform) !== "linux") return yield* Console.log(unsupported);
407 // Before resolving config, which creates T3 directories that root would then own.
408 if ((yield* HostProcess.UserId) === 0) {
409 return yield* Console.log(
410 "Run `t3 service protect` as the user that runs T3 Code, without sudo. It asks for sudo when it needs root.",
411 );
412 }
413 return yield* runServiceCommand(
414 flags,
415 Effect.gen(function* () {
416 const uid = yield* HostProcess.UserId;
417 const remote = yield* ServiceProtection.detectRemoteAccessUnits;
418 const { unitPath } = yield* (yield* BootService.BootService).status;
419 if (uid === undefined || remote === undefined || unitPath === "") {
420 return yield* Console.log(unsupported);
421 }
422 const userUnitDir = (yield* Path.Path).dirname(unitPath);
423
424 if (flags.undo) {
425 const installed = yield* ServiceProtection.installedProtection(
426 ServiceProtection.protectionPlan({
427 uid,
428 userUnitDir,
429 remoteAccessUnits: ServiceProtection.REMOTE_ACCESS_UNITS,
430 }),
431 );
432 if (installed === undefined) {
433 return yield* Console.log("T3 Code service protection is not set up.");
434 }
435 yield* Console.log(
436 [
437 "Removes:",
438 ...[...installed.system, ...installed.user, installed.managerDefaults].map(
439 ({ path, shared }) =>
440 ` ${path}${shared === true ? " (kept while another user is protected)" : ""}`,
441 ),
442 ].join("\n"),
443 );
444 if (!(yield* confirm(flags.yes, "Remove T3 Code service protection?"))) return;
445 yield* ServiceProtection.removeProtection(installed);
446 return yield* Console.log(
447 "Removed T3 Code service protection. The server's OOM score returns to normal after `t3 service restart`.",
448 );
449 }
450
451 yield* Console.log(
452 [
453 "Keeps T3 Code running when agents fill this machine's memory:",
454 " - reserves memory for the T3 Code server, so the kernel takes memory from agents first",
455 " - makes the out-of-memory killer pick agents before the server",
456 "It adds systemd drop-in files and changes nothing else. Undo with `t3 service protect --undo`.",
457 ].join("\n"),
458 );
459 const names = remote.map((unit) => unit.replace(/\.service$/, "")).join(" and ");
460 const protectRemote =
461 remote.length > 0 &&
462 (yield* confirm(
463 flags.yes,
464 `Also protect ${names} so you can still reach this machine under memory pressure?`,
465 ));
466 const plan = ServiceProtection.protectionPlan({
467 uid,
468 userUnitDir,
469 remoteAccessUnits: protectRemote ? remote : [],
470 });
471 yield* Console.log(
472 [
473 "Drop-ins it writes, as root through sudo:",
474 ...formatDropIns(plan.system),
475 "As you:",
476 ...formatDropIns([plan.managerDefaults, ...plan.user]),
477 ].join("\n"),
478 );
479 const memoryController = yield* ServiceProtection.memoryControllerAvailable;
480 if (!memoryController) {
481 yield* Console.log(`Only the OOM scores can apply: ${MEMORY_CONTROLLER_DISABLED}`);
482 }
483 if (!(yield* confirm(flags.yes, "Apply these settings?"))) return;
484 yield* ServiceProtection.applyProtection(plan);
485 yield* Console.log(
486 memoryController
487 ? "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`."
488 : "Protected T3 Code's OOM score; the server takes it after `t3 service restart`. Memory protection applies once the kernel's memory controller is enabled. Undo with `t3 service protect --undo`.",
489 );
490 }).pipe(Effect.provide(ProcessRunner.layer)),
491 );
492 }),
493 ),
494 );
495
496 export const serviceCommand = Command.make("service").pipe(
497 Command.withDescription("Manage the T3 Code background service."),
498 Command.withSubcommands([
499 serviceInstallCommand,
500 serviceRestartCommand,
501 serviceUninstallCommand,
502 serviceStatusCommand,
503 serviceProtectCommand,
504 serviceUpdateCommand,
505 ]),
506 );