@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, 03:37 UTC

main
ts 368 lines 13.2 KB
Raw
1 import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
2 import * as HostProcess from "@t3tools/shared/HostProcess";
3 import * as Context from "effect/Context";
4 import * as Cause from "effect/Cause";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Layer from "effect/Layer";
8 import * as Option from "effect/Option";
9 import * as Path from "effect/Path";
10 import * as Schema from "effect/Schema";
11
12 import packageJson from "../../package.json" with { type: "json" };
13 import {
14 pinnedRuntimePaths,
15 pinnedRuntimeVersionsDir,
16 readPosixLauncherTarget,
17 writePosixLauncher,
18 } from "./pinnedRuntime.ts";
19 import {
20 decodeServiceLauncherContext,
21 decodeServiceLauncherParentMessage,
22 SERVICE_LAUNCHER_CONTEXT_ENV,
23 type ServiceLauncherChildMessage,
24 type ServiceLauncherParentMessage,
25 type SupportedLauncherProtocol,
26 } from "./serviceProtocol.ts";
27
28 export class ServiceLauncherClientError extends Schema.TaggedError<ServiceLauncherClientError>()(
29 "ServiceLauncherClientError",
30 {
31 operation: Schema.Literals([
32 "decode-context",
33 "version-mismatch",
34 "unmanaged",
35 "send",
36 "disconnect",
37 "timeout",
38 ]),
39 cause: Schema.optional(Schema.Defect()),
40 },
41 ) {
42 override get message(): string {
43 switch (this.operation) {
44 case "decode-context":
45 return "The service launcher supplied invalid startup context.";
46 case "version-mismatch":
47 return "The service launcher started a different t3 version.";
48 case "unmanaged":
49 return "This server is not managed by the launcher.";
50 case "send":
51 return "Could not send a request to the service launcher.";
52 case "disconnect":
53 return "The service launcher disconnected before acknowledging the request.";
54 case "timeout":
55 return "The service launcher did not respond within 30 seconds.";
56 }
57 }
58 }
59
60 export class ServiceLauncherRejectedError extends Schema.TaggedError<ServiceLauncherRejectedError>()(
61 "ServiceLauncherRejectedError",
62 {
63 targetVersion: Schema.String,
64 reason: Schema.String,
65 },
66 ) {
67 override get message(): string {
68 return this.reason;
69 }
70 }
71
72 interface ServiceLauncherProcess {
73 readonly connected: boolean;
74 readonly send: (
75 message: ServiceLauncherChildMessage,
76 callback?: (error: Error | null) => void,
77 ) => boolean;
78 readonly on: (
79 event: "message" | "disconnect",
80 listener: (...args: ReadonlyArray<unknown>) => void,
81 ) => void;
82 readonly off: (
83 event: "message" | "disconnect",
84 listener: (...args: ReadonlyArray<unknown>) => void,
85 ) => void;
86 }
87
88 export const ServiceLauncherHostProcess = Context.Reference<ServiceLauncherProcess>(
89 "t3/cloud/serviceLauncherHostProcess",
90 {
91 defaultValue: () => ({
92 connected: process.connected && process.send !== undefined,
93 send: (message, callback) => {
94 if (process.send === undefined) return false;
95 return callback === undefined ? process.send(message) : process.send(message, callback);
96 },
97 on: (event, listener) => {
98 process.on(event, listener);
99 },
100 off: (event, listener) => {
101 process.off(event, listener);
102 },
103 }),
104 },
105 );
106
107 export class ServiceLauncherClient extends Context.Service<
108 ServiceLauncherClient,
109 {
110 readonly managed: boolean;
111 /** The supervising launcher's protocol. A remote update never replaces the launcher,
112 so it can be older than this runtime's own. */
113 readonly protocol: SupportedLauncherProtocol | undefined;
114 readonly requestUpdate: (input: {
115 readonly targetVersion: string;
116 readonly dbPath: string;
117 }) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;
118 /** Owned `t3` launchers move to the new runtime only when this start commits the trial. */
119 readonly prepareTrial: (input: {
120 readonly baseDir: string;
121 }) => Effect.Effect<ServerSelfUpdateOutcome | undefined, ServiceLauncherClientError>;
122 }
123 >()("t3/cloud/serviceLauncherClient") {}
124
125 const resolveStartup = Effect.fn("cloud.service_launcher_client.resolve_startup")(
126 function* (options?: { readonly currentVersion?: string }) {
127 const host = yield* ServiceLauncherHostProcess;
128 const environment = yield* HostProcess.Environment;
129 const currentVersion = options?.currentVersion ?? packageJson.version;
130 // IPC channels are not inherited; without one, launcher context belongs to an ancestor.
131 const rawContext = host.connected ? environment[SERVICE_LAUNCHER_CONTEXT_ENV] : undefined;
132 const context = rawContext === undefined ? undefined : decodeServiceLauncherContext(rawContext);
133
134 if (rawContext !== undefined && context === undefined) {
135 return yield* new ServiceLauncherClientError({ operation: "decode-context" });
136 }
137 if (context !== undefined && context.childVersion !== currentVersion) {
138 return yield* new ServiceLauncherClientError({ operation: "version-mismatch" });
139 }
140
141 const managed = context !== undefined;
142
143 return { host, context, managed };
144 },
145 );
146
147 export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_client.resolve_mode")(
148 function* () {
149 const { managed } = yield* resolveStartup();
150 return { managed };
151 },
152 );
153
154 export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint_launchers")(
155 function* (input: { readonly baseDir: string; readonly targetVersion: string }) {
156 const fs = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158 const environment = yield* HostProcess.Environment;
159 const platform = yield* HostProcess.Platform;
160 if (platform !== "linux" && platform !== "darwin") return;
161 const installBinDir =
162 environment["T3CODE_INSTALL_BIN_DIR"] ||
163 (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined);
164 const candidates = new Set<string>();
165 if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3"));
166 for (const directory of (environment["PATH"] ?? "").split(":")) {
167 if (directory.length === 0) continue;
168 const candidate = path.join(directory, "t3");
169 if (
170 yield* fs.exists(candidate).pipe(
171 Effect.catch((cause) =>
172 Effect.logWarning("Could not check the t3 command on PATH", {
173 launchedAs: candidate,
174 cause,
175 }).pipe(Effect.as(false)),
176 ),
177 )
178 ) {
179 candidates.add(candidate);
180 break;
181 }
182 }
183 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
184 const target = pinnedRuntimePaths(path, input.baseDir, input.targetVersion, platform);
185 for (const launchedAs of candidates) {
186 yield* Effect.scoped(
187 Effect.gen(function* () {
188 const linkTarget = yield* fs.readLink(launchedAs).pipe(
189 Effect.asSome,
190 Effect.catchIf(
191 (error) =>
192 error.reason._tag === "NotFound" ||
193 (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EINVAL",
194 () => Effect.succeedNone,
195 ),
196 );
197 // A legacy symlink, or the script install.sh and `t3 update` write.
198 const current = Option.isSome(linkTarget)
199 ? path.resolve(path.dirname(launchedAs), linkTarget.value)
200 : yield* readPosixLauncherTarget(launchedAs);
201 if (current === undefined) return;
202 const relative = path.relative(versionsDir, current);
203 if (
204 relative.length === 0 ||
205 relative === ".." ||
206 relative.startsWith(`..${path.sep}`) ||
207 path.isAbsolute(relative)
208 )
209 return;
210 yield* writePosixLauncher({
211 launcher: launchedAs,
212 executable: target.entryPath,
213 exclusive: false,
214 });
215 }),
216 ).pipe(
217 Effect.catchCause((cause) =>
218 Cause.hasInterrupts(cause)
219 ? Effect.interrupt
220 : Effect.logWarning("Could not move the t3 command to the updated version", {
221 launchedAs,
222 cause,
223 }),
224 ),
225 );
226 }
227 },
228 );
229
230 /** Completes when the launcher asks this server to stop, which Windows cannot signal. */
231 export const awaitServiceLauncherStop = Effect.fn("cloud.service_launcher_client.await_stop")(
232 function* (options?: { readonly currentVersion?: string }) {
233 const startup = yield* resolveStartup(options).pipe(Effect.option);
234 if (Option.isNone(startup) || !startup.value.managed) return yield* Effect.never;
235 const { host } = startup.value;
236 return yield* Effect.callback<void>((resume) => {
237 const onMessage = (...args: ReadonlyArray<unknown>) => {
238 if (decodeServiceLauncherParentMessage(args[0])?.type === "stop") resume(Effect.void);
239 };
240 host.on("message", onMessage);
241 return Effect.sync(() => host.off("message", onMessage));
242 });
243 },
244 );
245
246 export const make = Effect.fn("cloud.service_launcher_client.make")(function* (options?: {
247 readonly currentVersion?: string;
248 }) {
249 const { host, context, managed } = yield* resolveStartup(options);
250 // prepareTrial runs later, outside whatever context built the client.
251 const fs = yield* FileSystem.FileSystem;
252 const path = yield* Path.Path;
253 const environment = yield* HostProcess.Environment;
254 const platform = yield* HostProcess.Platform;
255
256 const exchange = (
257 message: ServiceLauncherChildMessage,
258 accept: (reply: ServiceLauncherParentMessage) => boolean,
259 ) =>
260 Effect.callback<ServiceLauncherParentMessage, ServiceLauncherClientError>((resume) => {
261 if (!managed) {
262 resume(Effect.fail(new ServiceLauncherClientError({ operation: "unmanaged" })));
263 return;
264 }
265
266 let settled = false;
267 const cleanup = () => {
268 host.off("message", onMessage);
269 host.off("disconnect", onDisconnect);
270 };
271 const settle = (
272 effect: Effect.Effect<ServiceLauncherParentMessage, ServiceLauncherClientError>,
273 ) => {
274 if (settled) return;
275 settled = true;
276 cleanup();
277 resume(effect);
278 };
279 const onMessage = (...args: ReadonlyArray<unknown>) => {
280 const reply = decodeServiceLauncherParentMessage(args[0]);
281 if (reply !== undefined && accept(reply)) settle(Effect.succeed(reply));
282 };
283 const onDisconnect = () =>
284 settle(Effect.fail(new ServiceLauncherClientError({ operation: "disconnect" })));
285
286 host.on("message", onMessage);
287 host.on("disconnect", onDisconnect);
288 try {
289 host.send(message, (error) => {
290 if (error !== null) {
291 settle(
292 Effect.fail(new ServiceLauncherClientError({ operation: "send", cause: error })),
293 );
294 }
295 });
296 } catch (cause) {
297 settle(Effect.fail(new ServiceLauncherClientError({ operation: "send", cause })));
298 }
299
300 return Effect.sync(cleanup);
301 }).pipe(
302 Effect.timeoutOrElse({
303 duration: "30 seconds",
304 orElse: () => Effect.fail(new ServiceLauncherClientError({ operation: "timeout" })),
305 }),
306 );
307
308 const requestUpdate = (input: { readonly targetVersion: string; readonly dbPath: string }) =>
309 exchange(
310 { type: "request-update", ...input },
311 (reply) => reply.type === "update-accepted" || reply.type === "update-rejected",
312 ).pipe(
313 Effect.flatMap((reply) =>
314 reply.type === "update-accepted"
315 ? Effect.succeed(reply.updateId)
316 : reply.type === "update-rejected"
317 ? Effect.fail(
318 new ServiceLauncherRejectedError({
319 targetVersion: input.targetVersion,
320 reason: reply.reason,
321 }),
322 )
323 : Effect.die("service launcher returned an impossible update response"),
324 ),
325 );
326
327 const pending = context?.update?.status === "pending" ? context.update : undefined;
328 const outcome =
329 context?.update === undefined || context.update.status === "pending"
330 ? undefined
331 : context.update;
332 const prepareTrial = (input: { readonly baseDir: string }) =>
333 pending !== undefined
334 ? exchange(
335 { type: "prepared", updateId: pending.id },
336 (reply) => reply.type === "committed" && reply.updateId === pending.id,
337 ).pipe(
338 Effect.flatMap((reply) =>
339 reply.type !== "committed"
340 ? Effect.die("service launcher returned an impossible prepared response")
341 : repointLaunchers({
342 baseDir: input.baseDir,
343 targetVersion: pending.targetVersion,
344 }).pipe(
345 Effect.provideService(FileSystem.FileSystem, fs),
346 Effect.provideService(Path.Path, path),
347 Effect.provideService(HostProcess.Environment, environment),
348 Effect.provideService(HostProcess.Platform, platform),
349 Effect.as({
350 id: pending.id,
351 fromVersion: pending.fromVersion,
352 targetVersion: pending.targetVersion,
353 status: "committed" as const,
354 }),
355 ),
356 ),
357 )
358 : Effect.succeed(outcome);
359
360 return ServiceLauncherClient.of({
361 managed,
362 protocol: context?.protocol,
363 requestUpdate,
364 prepareTrial,
365 });
366 });
367
368 export const layer = Layer.effect(ServiceLauncherClient, make());