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

main
ts 328 lines 13.4 KB
Raw
1 import {
2 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
3 ServerSelfUpdateError,
4 type ServerSelfUpdateCapability,
5 type ServerSelfUpdateInput,
6 type ServerSelfUpdateProgressEvent,
7 type ServerSelfUpdateProgressStage,
8 type ServerSelfUpdateResult,
9 } from "@t3tools/contracts";
10 import * as HostProcess from "@t3tools/shared/HostProcess";
11 import * as Config from "effect/Config";
12 import * as Context from "effect/Context";
13 import * as Effect from "effect/Effect";
14 import * as Option from "effect/Option";
15 import * as Ref from "effect/Ref";
16 import * as FileSystem from "effect/FileSystem";
17 import * as Layer from "effect/Layer";
18 import * as Path from "effect/Path";
19 import * as Queue from "effect/Queue";
20 import * as Stream from "effect/Stream";
21 import { HttpClient } from "effect/http";
22
23 import {
24 CLI_RELEASE_BASE_URL_ENV,
25 cliReleaseChannelOf,
26 crossesReleaseTrack,
27 } from "@t3tools/shared/cliRelease";
28
29 import packageJson from "../../package.json" with { type: "json" };
30 import * as ServerConfig from "../config.ts";
31 import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
32 import * as DesktopUpdateMarker from "../desktopUpdate/DesktopUpdateMarker.ts";
33 import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
34 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
35 import { managedUpdateMirror, managedUpdateRefusal } from "../policy/managedUpdates.ts";
36 import * as ProcessRunner from "../processRunner.ts";
37 import {
38 ensurePinnedRuntimeInstalled,
39 isUnpublishedRelease,
40 pinnedRuntimePaths,
41 prunePinnedRuntimes,
42 } from "./pinnedRuntime.ts";
43 import { bootServiceProgramOf, bootServiceUnitPath } from "./bootService.ts";
44 import { runStagedServicePreflight } from "./servicePreflight.ts";
45 import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
46 import { decodeServiceUnit, isExactServiceVersion } from "./serviceProtocol.ts";
47
48 export function resolveServerSelfUpdateCapability(input: {
49 readonly desktopManaged: boolean;
50 readonly launcherManaged: boolean;
51 }): ServerSelfUpdateCapability | null {
52 if (input.desktopManaged) return "desktop-managed" as const;
53 return input.launcherManaged ? ("boot-service" as const) : null;
54 }
55
56 export class ServerSelfUpdate extends Context.Service<
57 ServerSelfUpdate,
58 {
59 readonly update: (
60 input: ServerSelfUpdateInput,
61 reportProgress?: (
62 stage: ServerSelfUpdateProgressStage,
63 ) => Effect.Effect<void, ServerSelfUpdateError>,
64 onHandoffAccepted?: () => Effect.Effect<void>,
65 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
66 readonly commitDesktopUpdate: (
67 requestId: string,
68 onHandoffAccepted?: () => Effect.Effect<void>,
69 ) => Effect.Effect<never, ServerSelfUpdateError>;
70 }
71 >()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
72
73 /**
74 * A server starting from the runtime its launcher settled on means runtimes left by earlier
75 * updates can go. The boot service says so through its IPC context. The SSH launcher and the
76 * install script's `t3` start this home's pinned runtime directly, without one.
77 */
78 export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on_start")(
79 function* (input: { readonly baseDir: string; readonly managed: boolean }) {
80 const fs = yield* FileSystem.FileSystem;
81 const path = yield* Path.Path;
82 const platform = yield* HostProcess.Platform;
83 const executablePath = yield* HostProcess.ExecutablePath;
84 const { entryPath } = pinnedRuntimePaths(path, input.baseDir, packageJson.version, platform);
85 // The executable path is resolved, so it names the real path of a symlinked T3 home.
86 const realEntryPath = yield* fs.realPath(entryPath).pipe(Effect.orElseSucceed(() => entryPath));
87 if (!input.managed && executablePath !== entryPath && executablePath !== realEntryPath) {
88 return [];
89 }
90 const unitPath = yield* bootServiceUnitPath();
91 // A stopped service's unit still names the launcher runtime it will start.
92 const unit =
93 unitPath === undefined
94 ? Option.none<string>()
95 : yield* fs.readFile(unitPath).pipe(Effect.map(decodeServiceUnit), Effect.option);
96 const program = Option.flatMapNullishOr(unit, bootServiceProgramOf);
97 // The unit may name it through another spelling of a symlinked T3 home.
98 const references = Option.isNone(program)
99 ? []
100 : [
101 program.value,
102 yield* fs.realPath(program.value).pipe(Effect.orElseSucceed(() => program.value)),
103 ];
104 const removed = yield* prunePinnedRuntimes({
105 baseDir: input.baseDir,
106 keep: [packageJson.version],
107 references,
108 });
109 if (removed.length > 0) {
110 yield* Effect.logInfo("Removed unused t3 runtimes.", { versions: removed });
111 }
112 return removed;
113 },
114 );
115
116 /** The client checks this when planning; the host checks again because its database may have
117 * moved on since (another client updated it). Stable and Nightly each build their own commits,
118 * so crossing tracks needs the target release to know every migration this database holds. */
119 export function trackSwitchBlockReason(input: {
120 readonly serverVersion: string;
121 readonly targetVersion: string;
122 readonly targetDatabaseMigration: number | undefined;
123 /** Read only for a crossing; undefined when the database cannot be read. */
124 readonly databaseMigration: () => number | undefined;
125 }): string | null {
126 if (!crossesReleaseTrack(input.serverVersion, input.targetVersion)) return null;
127 const databaseMigration = input.databaseMigration();
128 if (input.targetDatabaseMigration === undefined || databaseMigration === undefined) {
129 return `Cannot confirm this database works with t3@${input.targetVersion}. Switch tracks from Settings → About → Update track, which checks it first.`;
130 }
131 return input.targetDatabaseMigration < databaseMigration
132 ? `This database has changes t3@${input.targetVersion} does not support yet; it stays on this release.`
133 : null;
134 }
135
136 export const make = Effect.fn("cloud.server_self_update.make")(function* () {
137 const serverConfig = yield* ServerConfig.ServerConfig;
138 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
139 const policy = yield* ManagedPolicy.ManagedPolicy;
140 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
141 const runner = yield* ProcessRunner.ProcessRunner;
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const platform = yield* HostProcess.Platform;
145 const arch = yield* HostProcess.Architecture;
146 const httpClient = yield* HttpClient.HttpClient;
147 const mirror = managedUpdateMirror(policy.document);
148 const releaseBaseUrl =
149 mirror?.feedUrl ??
150 Option.getOrUndefined(yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option));
151 const inFlight = yield* Ref.make(false);
152
153 yield* pruneRuntimesOnStart({ baseDir: serverConfig.baseDir, managed: launcher.managed }).pipe(
154 Effect.forkScoped,
155 );
156
157 const capability: ServerSelfUpdateCapability | null =
158 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
159 const failWith = (reason: string, cause?: unknown) =>
160 cause === undefined
161 ? new ServerSelfUpdateError({ reason })
162 : new ServerSelfUpdateError({ reason, cause });
163
164 const crossesTrackUnsafely = (input: ServerSelfUpdateInput) =>
165 trackSwitchBlockReason({
166 serverVersion: packageJson.version,
167 targetVersion: input.targetVersion,
168 targetDatabaseMigration: input.targetDatabaseMigration,
169 databaseMigration: () => databaseMigrationHead(serverConfig.dbPath),
170 });
171
172 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
173 "cloud.server_self_update.update",
174 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
175 const policyRefusal = managedUpdateRefusal(
176 policy.document,
177 capability === "boot-service" ? cliReleaseChannelOf(input.targetVersion.trim()) : undefined,
178 );
179 if (policyRefusal !== undefined) {
180 return yield* failWith(policyRefusal);
181 }
182 if (capability === "desktop-managed") {
183 const unsafeCrossing = input.channel === undefined ? null : crossesTrackUnsafely(input);
184 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
185 if (desktopAppUpdate.available) {
186 return yield* desktopAppUpdate.run(
187 reportProgress,
188 input.channel === undefined
189 ? undefined
190 : { channel: input.channel, targetVersion: input.targetVersion },
191 );
192 }
193 return yield* failWith(
194 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
195 );
196 }
197 // The target must accept the launcher that will run it, which can be older than this server.
198 const launcherProtocol = launcher.protocol;
199 if (capability === null || launcherProtocol === undefined) {
200 return yield* failWith(
201 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
202 );
203 }
204
205 const unsafeCrossing = crossesTrackUnsafely(input);
206 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
207 const targetVersion = input.targetVersion.trim();
208 if (!isExactServiceVersion(targetVersion)) {
209 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
210 }
211 if (yield* Ref.getAndSet(inFlight, true)) {
212 return yield* failWith("A server update is already in progress.");
213 }
214
215 return yield* Effect.gen(function* () {
216 yield* reportProgress("downloading");
217 const paths = yield* ensurePinnedRuntimeInstalled({
218 baseDir: serverConfig.baseDir,
219 version: targetVersion,
220 fs,
221 path,
222 runner,
223 httpClient,
224 platform,
225 arch,
226 releaseBaseUrl,
227 requirePublishedRelease: mirror !== undefined,
228 validate: (runtime) =>
229 runStagedServicePreflight({
230 runner,
231 runtime,
232 targetVersion,
233 databasePath: serverConfig.dbPath,
234 launcherProtocol,
235 }),
236 }).pipe(
237 Effect.mapError((error) => {
238 if (error._tag === "PinnedRuntimePreflightBlockedError") {
239 return failWith(error.reason, error);
240 }
241 if (mirror !== undefined && isUnpublishedRelease(error)) {
242 return failWith(
243 `${mirror.organization}'s update mirror has no t3@${targetVersion} for this machine.`,
244 error,
245 );
246 }
247 const downloadFailure = [
248 error.httpStatus === undefined ? undefined : `HTTP ${error.httpStatus}`,
249 error.downloadHost === undefined ? undefined : `from ${error.downloadHost}`,
250 ]
251 .filter((part) => part !== undefined)
252 .join(" ");
253 return failWith(
254 `Could not prepare t3@${targetVersion} while ${error.step}${downloadFailure ? ` (${downloadFailure})` : ""}.`,
255 error,
256 );
257 }),
258 );
259
260 if (input.stageOnly === true) {
261 yield* Ref.set(inFlight, false);
262 return { targetVersion, method: "boot-service" as const };
263 }
264 yield* reportProgress("installing");
265 const updateId = yield* Effect.uninterruptible(
266 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
267 Effect.mapError((error) =>
268 failWith(
269 error._tag === "ServiceLauncherRejectedError"
270 ? error.reason
271 : "Could not ask the service launcher to activate the prepared update.",
272 error,
273 ),
274 ),
275 // The launcher stops this server next; one from before its serving lock holds nothing
276 // until the new server starts, so this marker is what an SSH launch waits on.
277 Effect.tap(() =>
278 DesktopUpdateMarker.publish(
279 path.join(serverConfig.baseDir, "runtime", DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE),
280 ).pipe(Effect.provideService(FileSystem.FileSystem, fs), Effect.ignore({ log: true })),
281 ),
282 Effect.tap(() => onHandoffAccepted()),
283 ),
284 );
285
286 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
287 updateId,
288 targetVersion,
289 runtimePath: paths.entryPath,
290 });
291 return { targetVersion, method: "boot-service" as const, updateId };
292 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
293 });
294
295 return ServerSelfUpdate.of({
296 update,
297 commitDesktopUpdate: Effect.fn("ServerSelfUpdate.commitDesktopUpdate")(
298 function (requestId, onHandoffAccepted) {
299 return desktopAppUpdate.commit(requestId, onHandoffAccepted);
300 },
301 ),
302 });
303 });
304
305 export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
306 Layer.provide(ProcessRunner.layer),
307 );
308
309 // The update outlives client sockets; progress offers to a closed queue are ignored.
310 export const updateProgressStream = (
311 selfUpdate: ServerSelfUpdate["Service"],
312 input: ServerSelfUpdateInput,
313 ) =>
314 Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) => {
315 const offer = (event: ServerSelfUpdateProgressEvent) =>
316 Queue.offer(queue, event).pipe(Effect.ignore);
317
318 return selfUpdate
319 .update(input, (stage) => offer({ type: "progress", stage }))
320 .pipe(
321 Effect.flatMap((result) => offer({ type: "complete", result })),
322 Effect.catchTags({
323 ServerSelfUpdateError: (error) => Queue.fail(queue, error).pipe(Effect.ignore),
324 }),
325 Effect.andThen(Queue.end(queue).pipe(Effect.ignore)),
326 Effect.forkDetach,
327 );
328 });