Open History to see the last commit
1import {
2 defaultInstanceIdForDriver,
3 ProviderDriverKind,
4 ServerProviderUpdateError,
5 type ProviderInstanceId,
6 type ServerProvider,
7 type ServerProviderUpdatedPayload,
8 type ServerProviderUpdateState,
9} from "@t3tools/contracts";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as Data from "effect/Data";
14import * as DateTime from "effect/DateTime";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Ref from "effect/Ref";
20import * as Schema from "effect/Schema";
21import { HttpClient } from "effect/unstable/http";
22import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
23
24import * as ModelManifest from "./ModelManifest.ts";
25import { resolveProviderCompatibility } from "./providerCompatibility.ts";
26import * as ProviderRegistry from "./Services/ProviderRegistry.ts";
27import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
28import {
29 enrichProviderSnapshotWithVersionAdvisory,
30 makeTargetedProviderUpdateAction,
31 resolveLatestProviderVersion,
32 type ProviderMaintenanceCommandAction,
33 ProviderVersionCache,
34} from "./providerMaintenance.ts";
35import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
36import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
37const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
38
39const UPDATE_TIMEOUT_MS = 5 * 60_000;
40const UPDATE_OUTPUT_MAX_BYTES = 10_000;
41
42export interface ProviderMaintenanceCommandResult {
43 readonly stdout: string;
44 readonly stderr: string;
45 readonly exitCode: number | null;
46 readonly timedOut: boolean;
47 readonly stdoutTruncated: boolean;
48 readonly stderrTruncated: boolean;
49}
50
51export interface ProviderMaintenanceRunnerShape {
52 readonly updateProvider: (
53 target:
54 | ProviderDriverKind
55 | {
56 readonly provider: ProviderDriverKind;
57 readonly instanceId?: ProviderInstanceId | undefined;
58 readonly targetVersion?: string | undefined;
59 },
60 ) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
61}
62
63export class ProviderMaintenanceRunner extends Context.Service<
64 ProviderMaintenanceRunner,
65 ProviderMaintenanceRunnerShape
66>()("t3/provider/providerMaintenanceRunner") {}
67
68class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{
69 readonly message: string;
70 readonly cause?: unknown;
71}> {}
72
73interface VerifiedProviderRefresh {
74 readonly providers: ReadonlyArray<ServerProvider>;
75 readonly verifiedProviders: ReadonlyArray<ServerProvider>;
76}
77
78const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
79
80const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")(
81 function* (input: {
82 readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
83 readonly command: string;
84 readonly args: ReadonlyArray<string>;
85 readonly env?: NodeJS.ProcessEnv;
86 }) {
87 const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
88 function* () {
89 // Resolve the executable for the host platform before spawning. On
90 // Windows the update tools are batch shims (e.g. `npm` -> `npm.cmd`),
91 // which a bare ChildProcess.spawn cannot launch (spawn npm ENOENT);
92 // resolveSpawnCommand finds the real `.cmd` and routes it through the
93 // shell. On Linux/macOS (incl. the WSL backend) this is a no-op.
94 const resolved = yield* resolveSpawnCommand(input.command, input.args);
95 const child = yield* input.spawner
96 .spawn(
97 ChildProcess.make(resolved.command, resolved.args, {
98 shell: resolved.shell,
99 ...(input.env ? { env: input.env, extendEnv: true } : {}),
100 }),
101 )
102 .pipe(
103 Effect.mapError(
104 (cause) =>
105 new ProviderMaintenanceCommandError({
106 message: `Failed to run update command ${input.command}: ${cause.message}`,
107 cause,
108 }),
109 ),
110 );
111 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
112
113 const [stdout, stderr, exitCode] = yield* Effect.all(
114 [
115 collectUint8StreamText({
116 stream: child.stdout,
117 maxBytes: UPDATE_OUTPUT_MAX_BYTES,
118 }),
119 collectUint8StreamText({
120 stream: child.stderr,
121 maxBytes: UPDATE_OUTPUT_MAX_BYTES,
122 }),
123 child.exitCode,
124 ],
125 { concurrency: "unbounded" },
126 ).pipe(
127 Effect.mapError(
128 (cause) =>
129 new ProviderMaintenanceCommandError({
130 message: cause instanceof Error ? cause.message : "Update command failed to run.",
131 cause,
132 }),
133 ),
134 );
135
136 return {
137 stdout: stdout.text,
138 stderr: stderr.text,
139 exitCode: Number(exitCode),
140 timedOut: false,
141 stdoutTruncated: stdout.truncated,
142 stderrTruncated: stderr.truncated,
143 } satisfies ProviderMaintenanceCommandResult;
144 },
145 );
146
147 return yield* collectCommandResult().pipe(
148 Effect.scoped,
149 Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),
150 Effect.map((result) =>
151 Option.match(result, {
152 onSome: (value) => value,
153 onNone: () =>
154 ({
155 stdout: "",
156 stderr: "",
157 exitCode: null,
158 timedOut: true,
159 stdoutTruncated: false,
160 stderrTruncated: false,
161 }) satisfies ProviderMaintenanceCommandResult,
162 }),
163 ),
164 );
165 },
166);
167
168function trimNullable(value: string): string | null {
169 const trimmed = value.trim();
170 return trimmed.length > 0 ? trimmed : null;
171}
172
173function truncateText(value: string, maxLength: number): string {
174 return value.length <= maxLength ? value : value.slice(0, maxLength);
175}
176
177function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
178 const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
179 if (!output) {
180 return null;
181 }
182 return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
183}
184
185function failureMessage(result: ProviderMaintenanceCommandResult): string {
186 if (result.timedOut) {
187 return "Update timed out.";
188 }
189 if (result.exitCode !== null && result.exitCode !== 0) {
190 return `Update command exited with code ${result.exitCode}.`;
191 }
192 return "Update command failed.";
193}
194
195function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
196 return provider?.versionAdvisory?.status === "behind_latest";
197}
198
199function isStillInstalled(provider: ServerProvider): boolean {
200 return provider.installed;
201}
202
203function makeUpdateState(input: {
204 readonly status: ServerProviderUpdateState["status"];
205 readonly startedAt: string | null;
206 readonly finishedAt: string | null;
207 readonly message: string | null;
208 readonly output?: string | null;
209}): ServerProviderUpdateState {
210 return {
211 status: input.status,
212 startedAt: input.startedAt,
213 finishedAt: input.finishedAt,
214 message: input.message,
215 output: input.output ?? null,
216 };
217}
218
219/** @public Service construction is part of the canonical Effect module API. */
220export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
221 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
222 const manifestService = yield* ModelManifest.ModelManifest;
223 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
224 const httpClient = yield* HttpClient.HttpClient;
225 const versionCache = yield* ProviderVersionCache;
226 const runMaintenanceCommand = (update: ProviderMaintenanceCommandAction) =>
227 runProviderMaintenanceCommandWithSpawner({
228 spawner,
229 command: update.executable,
230 args: update.args,
231 ...(update.env ? { env: update.env } : {}),
232 });
233 const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
234 makeAlreadyRunningError: () =>
235 new ServerProviderUpdateError({
236 provider: ProviderDriverKind.make("unknown"),
237 reason: "An update is already running for this provider.",
238 }),
239 });
240
241 const verifyRefreshedProvider = (
242 provider: ProviderDriverKind,
243 maintenanceCapabilities: ProviderMaintenanceCapabilities,
244 instanceId: ProviderInstanceId,
245 ): Effect.Effect<VerifiedProviderRefresh> =>
246 providerRegistry.getProviders.pipe(
247 Effect.map((providers) => {
248 const instanceIds: Array<ProviderInstanceId> = [];
249 for (const candidate of providers) {
250 if (candidate.driver === provider && candidate.instanceId === instanceId) {
251 instanceIds.push(candidate.instanceId);
252 }
253 }
254 return instanceIds;
255 }),
256 Effect.flatMap((instanceIds) =>
257 instanceIds.length === 0
258 ? providerRegistry.refreshInstance(instanceId)
259 : Effect.forEach(
260 instanceIds,
261 (instanceId) => providerRegistry.refreshInstance(instanceId),
262 {
263 concurrency: "unbounded",
264 discard: true,
265 },
266 ).pipe(Effect.andThen(providerRegistry.getProviders)),
267 ),
268 Effect.flatMap((providers) => {
269 const refreshedProviders = providers.filter(
270 (candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
271 );
272 if (refreshedProviders.length === 0) {
273 return Effect.succeed<VerifiedProviderRefresh>({
274 providers,
275 verifiedProviders: [],
276 });
277 }
278 return Effect.forEach(
279 refreshedProviders,
280 (refreshedProvider) =>
281 enrichProviderSnapshotWithVersionAdvisory(
282 refreshedProvider,
283 maintenanceCapabilities,
284 ).pipe(
285 Effect.provideService(HttpClient.HttpClient, httpClient),
286 Effect.provideService(ProviderVersionCache, versionCache),
287 ),
288 {
289 concurrency: "unbounded",
290 },
291 ).pipe(
292 Effect.map((verifiedProviders): VerifiedProviderRefresh => ({
293 providers,
294 verifiedProviders,
295 })),
296 Effect.catchCause((cause) =>
297 Effect.logWarning("Provider post-update version verification failed", {
298 provider,
299 cause: Cause.pretty(cause),
300 }).pipe(
301 Effect.as<VerifiedProviderRefresh>({
302 providers,
303 verifiedProviders: refreshedProviders,
304 }),
305 ),
306 ),
307 );
308 }),
309 );
310
311 const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
312 "ProviderMaintenanceRunner.updateProvider",
313 )(function* (target) {
314 const provider = typeof target === "string" ? target : target.provider;
315 const instanceId =
316 typeof target === "string"
317 ? defaultInstanceIdForDriver(provider)
318 : (target.instanceId ?? defaultInstanceIdForDriver(provider));
319 const targetVersion = typeof target === "string" ? undefined : target.targetVersion;
320 const targetKey = `instance:${instanceId}`;
321 const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
322 instanceId,
323 provider,
324 );
325 const update = capabilities.update;
326 if (!update) {
327 return yield* new ServerProviderUpdateError({
328 provider,
329 reason: "This provider does not support one-click updates.",
330 });
331 }
332
333 const setUpdateState = (state: ServerProviderUpdateState | null) =>
334 providerRegistry.setProviderMaintenanceActionState({
335 instanceId,
336 action: "update",
337 state,
338 });
339 const setQueuedState = setUpdateState(
340 makeUpdateState({
341 status: "queued",
342 startedAt: null,
343 finishedAt: null,
344 message: "Waiting for another provider update to finish.",
345 }),
346 ).pipe(Effect.asVoid);
347
348 const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
349 function* () {
350 const finish = (state: ServerProviderUpdateState) =>
351 setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));
352 const startedAtRef = yield* Ref.make<string | null>(null);
353
354 const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
355 function* () {
356 const startedAt = yield* nowIso;
357 yield* Ref.set(startedAtRef, startedAt);
358 yield* setUpdateState(
359 makeUpdateState({
360 status: "running",
361 startedAt,
362 finishedAt: null,
363 message: "Updating provider.",
364 }),
365 );
366
367 // The cached capabilities chose the lock; re-derive ownership
368 // now so the command that runs matches the executable as it is
369 // at click time, not as it was at the last health refresh.
370 const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
371 instanceId,
372 provider,
373 { fresh: true },
374 );
375 if (!fresh.update || fresh.update.lockKey !== update.lockKey) {
376 return yield* finish(
377 makeUpdateState({
378 status: "failed",
379 startedAt,
380 finishedAt: yield* nowIso,
381 message: "Provider installation changed. Refresh and try again.",
382 }),
383 );
384 }
385
386 const manifest = yield* manifestService.current;
387 const candidateVersion =
388 targetVersion ??
389 (yield* resolveLatestProviderVersion(fresh).pipe(
390 Effect.provideService(HttpClient.HttpClient, httpClient),
391 Effect.provideService(ProviderVersionCache, versionCache),
392 ));
393 const advisory =
394 resolveProviderCompatibility(manifest.compatibility, provider, candidateVersion) ??
395 resolveProviderCompatibility(
396 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
397 provider,
398 candidateVersion,
399 );
400 const command =
401 targetVersion !== undefined
402 ? makeTargetedProviderUpdateAction(fresh, targetVersion)
403 : fresh.update;
404 const rejected =
405 targetVersion !== undefined
406 ? !command ||
407 advisory?.recommendedVersion !== targetVersion ||
408 advisory.status !== "supported"
409 : advisory?.status === "broken" || advisory?.status === "unsupported";
410 if (rejected || !command) {
411 return yield* finish(
412 makeUpdateState({
413 status: "failed",
414 startedAt,
415 finishedAt: yield* nowIso,
416 message:
417 targetVersion !== undefined
418 ? "This version is no longer recommended or this installer cannot install a specific version. Refresh provider settings."
419 : "The latest provider version is incompatible with this T3 Code release. Review provider settings.",
420 }),
421 );
422 }
423 const result = yield* runMaintenanceCommand(command);
424 const finishedAt = yield* nowIso;
425 if (result.timedOut || result.exitCode !== 0) {
426 return yield* finish(
427 makeUpdateState({
428 status: "failed",
429 startedAt,
430 finishedAt,
431 message: failureMessage(result),
432 output: commandOutput(result),
433 }),
434 );
435 }
436
437 // Homebrew's "latest" moves once the upgrade lands; read it again.
438 const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
439 instanceId,
440 provider,
441 { fresh: true },
442 );
443 const { verifiedProviders } = yield* verifyRefreshedProvider(
444 provider,
445 verified,
446 instanceId,
447 );
448 // "Succeeded" needs the provider to still be installed: an
449 // installer that exits 0 and leaves the binary missing is not a
450 // success. A missing version alone is not held against it, since
451 // Cursor's `about` probe can fail transiently on a healthy binary.
452 const couldNotVerify =
453 verifiedProviders.length === 0 ||
454 verifiedProviders.some(
455 (verifiedProvider) =>
456 !isStillInstalled(verifiedProvider) ||
457 (targetVersion !== undefined &&
458 verifiedProvider.version?.replace(/^v/, "") !== targetVersion),
459 );
460 const stillOutdated =
461 targetVersion === undefined &&
462 verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
463 return yield* finish(
464 makeUpdateState({
465 status: couldNotVerify || stillOutdated ? "unchanged" : "succeeded",
466 startedAt,
467 finishedAt,
468 message: couldNotVerify
469 ? "Update command completed, but T3 Code could not verify the provider version."
470 : stillOutdated
471 ? "Update command completed, but T3 Code still detects an outdated provider version."
472 : "Provider updated.",
473 output: commandOutput(result),
474 }),
475 );
476 },
477 );
478
479 const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
480 function* (cause: Cause.Cause<unknown>) {
481 const failure = Cause.squash(cause);
482 const startedAt = yield* Ref.get(startedAtRef);
483 return yield* finish(
484 makeUpdateState({
485 status: "failed",
486 startedAt,
487 finishedAt: yield* nowIso,
488 message: failure instanceof Error ? failure.message : "Update command failed.",
489 output: null,
490 }),
491 );
492 },
493 );
494
495 return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
496 },
497 );
498
499 return yield* commandCoordinator
500 .withCommandLock({
501 targetKey,
502 lockKey: update.lockKey,
503 onQueued: setQueuedState,
504 run: runProviderUpdate(),
505 })
506 .pipe(
507 Effect.mapError((error) =>
508 isServerProviderUpdateError(error)
509 ? new ServerProviderUpdateError({
510 provider,
511 reason: error.reason,
512 })
513 : error,
514 ),
515 );
516 });
517
518 return ProviderMaintenanceRunner.of({
519 updateProvider,
520 });
521});
522
523export const layer = Layer.effect(ProviderMaintenanceRunner, make());