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