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