Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import {
3 CLI_RELEASE_BASE_URL_ENV,
4 CLI_RELEASE_CHANNELS,
5 cliReleaseIndexPageUrl,
6 cliReleaseChannelOf,
7 newestCliReleaseVersion,
8 type CliReleaseChannel,
9} from "@t3tools/shared/cliRelease";
10import * as Console from "effect/Console";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as Schema from "effect/Schema";
18import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/cli";
19import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
20
21import packageJson from "../../package.json" with { type: "json" };
22import * as BootService from "../cloud/bootService.ts";
23import {
24 ensurePinnedRuntimeInstalled,
25 launcherOwnsVersionsDir,
26 pinnedRuntimeCommand,
27 PinnedRuntimeInstallError,
28 pinnedRuntimePaths,
29 prunePinnedRuntimes,
30 windowsShimTarget,
31} from "../cloud/pinnedRuntime.ts";
32import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
33import * as ProcessRunner from "../processRunner.ts";
34import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
35import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
36import { createUpdateProgress } from "./updateProgress.ts";
37import * as CliService from "./service.ts";
38
39export class CliUpdateError extends Schema.TaggedError<CliUpdateError>()("CliUpdateError", {
40 reason: Schema.String,
41}) {
42 override get message(): string {
43 return this.reason;
44 }
45}
46
47const ReleaseIndex = Schema.Array(
48 Schema.Struct({
49 tag_name: Schema.String,
50 draft: Schema.optional(Schema.Boolean),
51 }),
52);
53const decodeReleaseIndex = Schema.decodeUnknownEffect(Schema.fromJsonString(ReleaseIndex));
54
55const RELEASE_INDEX_TIMEOUT = Duration.seconds(30);
56const RELEASE_INDEX_MAX_PAGES = 10;
57
58export const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(function* (
59 channel: CliReleaseChannel,
60) {
61 const httpClient = yield* HttpClient.HttpClient;
62 const environment = yield* HostProcess.Environment;
63 const githubToken = environment.GH_TOKEN?.trim() || environment.GITHUB_TOKEN?.trim() || undefined;
64 for (let page = 1; page <= RELEASE_INDEX_MAX_PAGES; page += 1) {
65 const request = HttpClientRequest.get(cliReleaseIndexPageUrl(page)).pipe(
66 HttpClientRequest.setHeader("Accept", "application/vnd.github+json"),
67 );
68 const authenticatedRequest =
69 githubToken === undefined
70 ? request
71 : HttpClientRequest.setHeader(request, "Authorization", `Bearer ${githubToken}`);
72 const body = yield* httpClient.execute(authenticatedRequest).pipe(
73 Effect.flatMap(HttpClientResponse.filterStatusOk),
74 Effect.flatMap((response) => response.text),
75 Effect.mapError(() => new CliUpdateError({ reason: "Could not list t3 releases." })),
76 Effect.timeoutOrElse({
77 duration: RELEASE_INDEX_TIMEOUT,
78 orElse: () => Effect.fail(new CliUpdateError({ reason: "Timed out listing t3 releases." })),
79 }),
80 );
81 const releases = yield* decodeReleaseIndex(body).pipe(
82 Effect.mapError(
83 () => new CliUpdateError({ reason: "The t3 release index had an unexpected shape." }),
84 ),
85 );
86 const version = newestCliReleaseVersion(releases, channel);
87 if (version !== undefined) return version;
88 if (releases.length === 0) break;
89 }
90 return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` });
91});
92
93/**
94 * Only a launcher that already points into this home's `runtime/versions` tree is touched; a
95 * plain copy of the executable, or a launcher for some other install, is left alone.
96 */
97export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function* (input: {
98 readonly launchedAs: string | undefined;
99 readonly versionsDir: string;
100 readonly targetEntryPath: string;
101}) {
102 const fs = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 const platform = yield* HostProcess.Platform;
105 if (input.launchedAs === undefined) return Option.none<string>();
106 const ownsTarget = (candidate: string) =>
107 launcherOwnsVersionsDir(path, input.versionsDir, candidate);
108
109 if (platform === "win32") {
110 const shimPath = yield* findWindowsShim(input.launchedAs);
111 if (shimPath === undefined) return Option.none<string>();
112 const current = yield* fs.readFileString(shimPath).pipe(Effect.option);
113 const quoted = Option.isSome(current) ? windowsShimTarget(current.value) : undefined;
114 if (quoted === undefined || !ownsTarget(quoted)) return Option.none<string>();
115 yield* fs
116 .writeFileString(shimPath, `@echo off\r\n"${input.targetEntryPath}" %*`)
117 .pipe(
118 Effect.mapError(
119 () => new CliUpdateError({ reason: `Could not rewrite the t3 launcher at ${shimPath}.` }),
120 ),
121 );
122 return Option.some(shimPath);
123 }
124
125 const linkTarget = yield* fs.readLink(input.launchedAs).pipe(Effect.option);
126 if (Option.isNone(linkTarget)) return Option.none<string>();
127 const resolvedTarget = path.resolve(path.dirname(input.launchedAs), linkTarget.value);
128 if (!ownsTarget(resolvedTarget)) return Option.none<string>();
129 const tempLink = `${input.launchedAs}.${process.pid}.tmp`;
130 yield* fs.symlink(input.targetEntryPath, tempLink).pipe(
131 Effect.andThen(fs.rename(tempLink, input.launchedAs)),
132 Effect.mapError(
133 () =>
134 new CliUpdateError({ reason: `Could not repoint the t3 launcher at ${input.launchedAs}.` }),
135 ),
136 );
137 return Option.some(input.launchedAs);
138});
139
140/** Node preserves argv0's spelling; resolve bare names on PATH to find the launcher symlink. */
141export const resolveLauncherPath = Effect.gen(function* () {
142 const path = yield* Path.Path;
143 const fs = yield* FileSystem.FileSystem;
144 const invokedAs = yield* HostProcess.InvokedAs;
145 const cwd = yield* HostProcess.WorkingDirectory;
146 const environment = yield* HostProcess.Environment;
147 const platform = yield* HostProcess.Platform;
148 if (invokedAs.includes("/") || invokedAs.includes("\\")) {
149 return path.resolve(cwd, invokedAs);
150 }
151 const delimiter = platform === "win32" ? ";" : ":";
152 for (const directory of (environment["PATH"] ?? "").split(delimiter)) {
153 if (directory.length === 0) continue;
154 const candidate = path.join(directory, invokedAs);
155 if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
156 return candidate;
157 }
158 }
159 return undefined;
160});
161
162/** Windows executables see their own path, so find the installer shim by matching t3.cmd targets on PATH. */
163export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* (
164 executablePath: string,
165) {
166 const fs = yield* FileSystem.FileSystem;
167 const path = yield* Path.Path;
168 const environment = yield* HostProcess.Environment;
169 const candidates = [
170 ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []),
171 ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"),
172 ].filter((entry) => entry.trim().length > 0);
173 for (const directory of candidates) {
174 const shimPath = path.join(directory, "t3.cmd");
175 const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
176 if (Option.isNone(contents)) continue;
177 const target = windowsShimTarget(contents.value);
178 if (
179 target !== undefined &&
180 path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase()
181 ) {
182 return shimPath;
183 }
184 }
185 return undefined;
186});
187
188const updateFlags = {
189 ...projectLocationFlags,
190 channel: Flag.Literals("channel", CLI_RELEASE_CHANNELS).pipe(
191 Flag.withDescription(
192 "Release channel to follow. Defaults to the channel this t3 was published on.",
193 ),
194 Flag.optional,
195 ),
196 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
197 Flag.withDescription("Allow moving to an older version than the one running."),
198 Flag.withDefault(false),
199 ),
200 yes: Flag.Boolean("yes").pipe(
201 Flag.withAlias("y"),
202 Flag.withDescription(
203 "Restart the background service without asking. Required to restart it from a script, where there is no prompt.",
204 ),
205 Flag.withDefault(false),
206 ),
207};
208
209const versionArgument = Argument.String("version").pipe(
210 Argument.withDescription(
211 "Exact version to install. Defaults to the newest release on the channel.",
212 ),
213 Argument.optional,
214);
215
216export const updateCommand = Command.make("update", {
217 ...updateFlags,
218 version: versionArgument,
219}).pipe(
220 Command.withDescription(
221 "Download a newer t3 and switch this machine to it, including the background service when one is installed.",
222 ),
223 Command.withHandler((flags) =>
224 Effect.gen(function* () {
225 const logLevel = yield* GlobalFlag.LogLevel;
226 const config = yield* resolveCliAuthConfig(flags, logLevel);
227 return yield* runUpdate({
228 baseDir: config.baseDir,
229 logsDir: config.logsDir,
230 serverRuntimeStatePath: config.serverRuntimeStatePath,
231 channel: Option.getOrUndefined(flags.channel),
232 requestedVersion: Option.getOrUndefined(flags.version),
233 allowDowngrade: flags.allowDowngrade,
234 assumeYes: flags.yes,
235 }).pipe(
236 Effect.provide(
237 Layer.mergeAll(CliService.layer(config), ProcessRunner.layer, FetchHttpClient.layer),
238 ),
239 );
240 }),
241 ),
242);
243
244const findForegroundServer = Effect.fn("cli.update.find_foreground_server")(function* (input: {
245 readonly serverRuntimeStatePath: string;
246 readonly serviceInstalled: boolean;
247}) {
248 const state = yield* readPersistedServerRuntimeState(input.serverRuntimeStatePath);
249 if (Option.isNone(state) || state.value.serviceManaged || !isProcessAlive(state.value.pid)) {
250 return undefined;
251 }
252 if (input.serviceInstalled && (yield* belongsToBootService(state.value.pid))) return undefined;
253 return state.value;
254});
255
256const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(function* (
257 pid: number,
258) {
259 const platform = yield* HostProcess.Platform;
260 const fs = yield* FileSystem.FileSystem;
261 const runner = yield* ProcessRunner.ProcessRunner;
262 if (platform === "linux") {
263 const cgroup = yield* fs.readFileString(`/proc/${pid}/cgroup`).pipe(Effect.option);
264 return Option.isSome(cgroup) && cgroup.value.includes("/t3code.service");
265 }
266 if (platform === "darwin") {
267 const parent = yield* runner
268 .run({
269 command: "ps",
270 args: ["-o", "ppid=", "-p", String(pid)],
271 timeout: Duration.seconds(5),
272 })
273 .pipe(Effect.option);
274 const ppid = Option.isSome(parent) && parent.value.code === 0 ? parent.value.stdout.trim() : "";
275 if (!/^\d+$/.test(ppid)) return false;
276 const command = yield* runner
277 .run({ command: "ps", args: ["-o", "command=", "-p", ppid], timeout: Duration.seconds(5) })
278 .pipe(
279 Effect.map((result) => (result.code === 0 ? result.stdout : "")),
280 Effect.orElseSucceed(() => ""),
281 );
282 return /__service-launcher/.test(command);
283 }
284 return false;
285});
286
287const runUpdate = Effect.fn("cli.update.run")(function* (input: {
288 readonly baseDir: string;
289 readonly logsDir: string;
290 readonly serverRuntimeStatePath: string;
291 readonly channel: CliReleaseChannel | undefined;
292 readonly requestedVersion: string | undefined;
293 readonly allowDowngrade: boolean;
294 readonly assumeYes: boolean;
295}) {
296 const fs = yield* FileSystem.FileSystem;
297 const path = yield* Path.Path;
298 const runner = yield* ProcessRunner.ProcessRunner;
299 const platform = yield* HostProcess.Platform;
300 const arch = yield* HostProcess.Architecture;
301 const environment = yield* HostProcess.Environment;
302 const httpClient = yield* HttpClient.HttpClient;
303 const service = yield* BootService.BootService;
304
305 const currentVersion = packageJson.version;
306 const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
307 if (input.requestedVersion !== undefined && !isExactServiceVersion(input.requestedVersion)) {
308 return yield* new CliUpdateError({
309 reason: `'${input.requestedVersion}' is not an exact t3 version.`,
310 });
311 }
312 const progress = createUpdateProgress();
313 progress.status("Checking for updates...");
314 const targetVersion = yield* (
315 input.requestedVersion === undefined
316 ? resolveNewestVersion(channel)
317 : Effect.succeed(input.requestedVersion)
318 ).pipe(Effect.ensuring(Effect.sync(progress.finish)));
319 const targetChannel = cliReleaseChannelOf(targetVersion);
320
321 const currentChannel = cliReleaseChannelOf(currentVersion);
322 if (targetChannel === "preview" && currentChannel !== "preview") {
323 yield* Console.log(
324 [
325 `t3@${targetVersion} is a preview build.`,
326 " Preview builds are cut by maintainers from unreleased branches to exercise the release",
327 " pipeline. They can be broken, receive no fixes, and are never offered as updates; you",
328 ` will have to switch back to ${currentChannel} yourself with \`t3 update --channel ${currentChannel} --allow-downgrade\`.`,
329 ].join("\n"),
330 );
331 if (!(process.stdin.isTTY && process.stdout.isTTY)) {
332 return yield* new CliUpdateError({
333 reason:
334 "Refusing to install a preview build without confirmation. Run this from a terminal to confirm, or pass --channel preview from an interactive shell.",
335 });
336 }
337 const confirmed = yield* Prompt.run(
338 Prompt.Confirm({ message: "Install the preview build anyway?", initial: false }),
339 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
340 if (!confirmed) {
341 yield* Console.log("Left as is.");
342 return;
343 }
344 }
345
346 const status = yield* service.status;
347 // Service names are per user, so another home's unit belongs to a different install.
348 const servesThisHome =
349 status.installedBaseDir !== undefined &&
350 path.resolve(status.installedBaseDir) === path.resolve(input.baseDir);
351 const serviceInstalled = status.supported && status.installed && servesThisHome;
352 const foreground = yield* findForegroundServer({
353 serverRuntimeStatePath: input.serverRuntimeStatePath,
354 serviceInstalled,
355 });
356 const serviceVersion = serviceInstalled ? status.installedVersion : undefined;
357 const executableCurrent = targetVersion === currentVersion;
358 const restartPending = status.problems?.includes("restart-pending") === true;
359 const serviceCurrent =
360 !serviceInstalled ||
361 (serviceVersion === targetVersion &&
362 (executableCurrent ? status.current : (status.problems ?? []).length === 0));
363 const newestInstalled =
364 serviceVersion !== undefined && compareExactServiceVersions(serviceVersion, currentVersion) > 0
365 ? serviceVersion
366 : currentVersion;
367
368 if (executableCurrent && serviceCurrent) {
369 yield* Console.log(
370 serviceVersion !== undefined
371 ? `t3 and its background service are already on ${targetVersion} (${targetChannel}).`
372 : `t3 is already on ${targetVersion} (${targetChannel}).`,
373 );
374 return;
375 }
376 if (!input.allowDowngrade && compareExactServiceVersions(targetVersion, newestInstalled) < 0) {
377 return yield* new CliUpdateError({
378 reason: `t3@${targetVersion} is older than the installed ${newestInstalled}. Pass --allow-downgrade to install it anyway.`,
379 });
380 }
381
382 const alreadyOnDisk = yield* fs
383 .readFileString(pinnedRuntimePaths(path, input.baseDir, targetVersion, platform).sentinelPath)
384 .pipe(
385 Effect.map((sentinel) => sentinel.trim() === targetVersion),
386 Effect.orElseSucceed(() => false),
387 );
388
389 progress.heading(
390 executableCurrent && restartPending
391 ? `The background service is still running the version before ${targetVersion} (${targetChannel}).`
392 : executableCurrent
393 ? `Updating the background service ${serviceVersion ?? "(unknown version)"} -> ${targetVersion} (${targetChannel}).`
394 : alreadyOnDisk
395 ? "Switching T3 Code"
396 : "Updating T3 Code",
397 executableCurrent
398 ? ""
399 : `${currentVersion} → ${targetVersion}${targetChannel === "stable" ? "" : ` (${targetChannel})`}`,
400 );
401 let restartService = false;
402 if (serviceInstalled && !serviceCurrent) {
403 yield* Console.log(
404 " A background service is installed for this T3 home. Restarting it interrupts anything running in it: agent turns, terminals, remote clients.",
405 );
406 if (input.assumeYes) {
407 restartService = true;
408 } else if (process.stdin.isTTY && process.stdout.isTTY) {
409 restartService = yield* Prompt.run(
410 Prompt.Confirm({
411 message: "Restart the background service once the download is verified?",
412 initial: true,
413 }),
414 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
415 } else {
416 yield* Console.log(
417 " Not a terminal, so the service keeps running its current version. Rerun with --yes to restart it now, or run `t3 service restart` later.",
418 );
419 }
420 }
421
422 const runtime = yield* ensurePinnedRuntimeInstalled({
423 onProgress: progress.report,
424 baseDir: input.baseDir,
425 version: targetVersion,
426 fs,
427 path,
428 runner,
429 httpClient,
430 platform,
431 arch,
432 releaseBaseUrl: environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined,
433 validate: (paths) =>
434 runner
435 .run({
436 command: pinnedRuntimeCommand(paths).command,
437 args: [...pinnedRuntimeCommand(paths).args, "--version"],
438 timeout: Duration.seconds(30),
439 })
440 .pipe(
441 Effect.mapError(
442 (cause) =>
443 new PinnedRuntimeInstallError({ step: "verifying the downloaded t3", cause }),
444 ),
445 Effect.flatMap((result) =>
446 result.code === 0 && /\bv(\S+)\s*$/.exec(result.stdout)?.[1] === targetVersion
447 ? Effect.void
448 : Effect.fail(
449 new PinnedRuntimeInstallError({
450 step: "verifying the downloaded t3",
451 exitCode: Number(result.code),
452 }),
453 ),
454 ),
455 ),
456 }).pipe(
457 Effect.ensuring(Effect.sync(progress.finish)),
458 Effect.catchIf(
459 (error): error is PinnedRuntimeInstallError =>
460 error._tag === "PinnedRuntimeInstallError" &&
461 error.step.startsWith("downloading the t3 release checksums") &&
462 String(error.cause).includes("404"),
463 () =>
464 Effect.fail(
465 new CliUpdateError({
466 reason: `No release archive was published for t3@${targetVersion}.`,
467 }),
468 ),
469 ),
470 );
471
472 const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined;
473 const repointed = yield* repointLauncher({
474 launchedAs,
475 versionsDir: path.dirname(runtime.versionDir),
476 targetEntryPath: runtime.entryPath,
477 });
478
479 // Use today's service manager for the target version. Inside the service it hands off to
480 // the target CLI, so stopping this process cannot interrupt the switch.
481 let servicePlan: BootService.BootServicePlan | undefined;
482 if (serviceInstalled && !serviceCurrent) {
483 yield* Console.log(
484 restartService
485 ? "Restarting the background service..."
486 : "Updating the background service...",
487 );
488 servicePlan = yield* BootService.BootService.pipe(
489 Effect.flatMap((target) =>
490 target.install({ allowDowngrade: input.allowDowngrade, start: restartService }),
491 ),
492 Effect.provide(
493 BootService.layer({
494 baseDir: input.baseDir,
495 logsDir: input.logsDir,
496 cliVersion: targetVersion,
497 }),
498 ),
499 Effect.mapError(
500 (error) =>
501 new CliUpdateError({
502 reason: `t3@${targetVersion} is installed but the background service could not be ${restartService ? "updated" : "pointed at it"}: ${error.message}`,
503 }),
504 ),
505 );
506 }
507
508 // A handed-off service install rewrites the unit later, while the old launcher may be stopped.
509 if (servicePlan?.handedOff !== true) {
510 // A stopped service's unit still names the launcher runtime it will start.
511 const unit = yield* fs.readFileString(status.unitPath).pipe(Effect.option);
512 yield* prunePinnedRuntimes({
513 baseDir: input.baseDir,
514 keep: [currentVersion, targetVersion],
515 references: Option.toArray(Option.flatMapNullishOr(unit, BootService.bootServiceProgramOf)),
516 });
517 }
518
519 progress.success(`Installed T3 Code ${targetVersion}`);
520 if (Option.isSome(repointed)) {
521 yield* Console.log(" Run t3 to get started.\n");
522 } else {
523 yield* Console.log(` Run ${runtime.entryPath}\n`);
524 }
525 if (servicePlan?.handedOff === true) {
526 yield* Console.log(
527 ` Background service switching to ${targetVersion} from a separate systemd unit, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`,
528 );
529 } else if (servicePlan !== undefined && restartService) {
530 yield* Console.log(` Background service restarted on ${targetVersion}`);
531 } else if (serviceInstalled && serviceCurrent) {
532 yield* Console.log(` Background service already on ${targetVersion}`);
533 } else if (serviceInstalled) {
534 yield* Console.log(
535 ` Background service still running ${serviceVersion ?? "an unknown version"}. Run \`t3 service restart\` when you are ready to switch it to ${targetVersion}.`,
536 );
537 } else if (status.installed && !servesThisHome) {
538 yield* Console.log(
539 ` The background service serves ${status.installedBaseDir ?? "another T3 home"} and was left unchanged.`,
540 );
541 }
542 if (foreground !== undefined) {
543 yield* Console.log(
544 ` A server started by hand is still running at ${foreground.origin} (pid ${foreground.pid}). Stop it and start it again to pick up ${targetVersion}.`,
545 );
546 }
547});