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