Open History to see the last commit
1import {
2 ProviderDriverKind,
3 type ServerProvider,
4 type ServerProviderVersionAdvisory,
5} from "@t3tools/contracts";
6import { compareSemverVersions } from "@t3tools/shared/semver";
7import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
8import { causeErrorTag } from "@t3tools/shared/observability";
9import { resolveCommandPath } from "@t3tools/shared/shell";
10import * as Config from "effect/Config";
11import * as Context from "effect/Context";
12import * as DateTime from "effect/DateTime";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19import * as Stream from "effect/Stream";
20import { HttpClient, HttpClientRequest } from "effect/unstable/http";
21import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
22
23import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
24
25const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
26const LATEST_VERSION_TIMEOUT_MS = 4_000;
27const HOMEBREW_INFO_TIMEOUT_MS = 10_000;
28const HOMEBREW_INFO_MAX_BYTES = 256 * 1_024;
29const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
30
31/**
32 * Ownership is re-derived from the executable this often. Installs do not
33 * move on their own, so this mostly bounds how stale a Homebrew "latest" can
34 * get; the npm registry check keeps its own cache.
35 */
36const MAINTENANCE_CAPABILITIES_CACHE_TTL = Duration.hours(1);
37
38const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
39 Object.fromEntries(
40 Object.entries(input).flatMap(([key, value]) =>
41 Option.match(value, {
42 onNone: () => [],
43 onSome: (resolved) => [[key, resolved]],
44 }),
45 ),
46 );
47
48const CommandLookupEnvConfig = Config.all({
49 PATH: Config.String("PATH").pipe(Config.option),
50 Path: Config.String("Path").pipe(Config.option),
51 path: Config.String("path").pipe(Config.option),
52 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
53}).pipe(Config.map(compactEnv));
54
55const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
56
57export interface ProviderMaintenanceCapabilities {
58 readonly provider: ProviderDriverKind;
59 readonly packageName: string | null;
60 readonly update: ProviderMaintenanceCommandAction | null;
61 /**
62 * Latest version reported by the installer that owns the executable.
63 * `undefined` means the installer has no channel of its own and the npm
64 * registry entry for `packageName` is authoritative; `null` means the
65 * installer was asked and did not know.
66 */
67 readonly latestVersion?: string | null;
68}
69
70export interface ProviderMaintenanceCommandAction {
71 readonly command: string;
72 readonly executable: string;
73 readonly args: ReadonlyArray<string>;
74 readonly lockKey: string;
75 /**
76 * Extra environment for the spawned updater, on top of the server's own.
77 * A native updater finds its install through the same variables the
78 * provider runs with (e.g. `CODEX_HOME`), so an instance with a custom home
79 * must update that home and not the default one.
80 */
81 readonly env?: NodeJS.ProcessEnv;
82}
83
84/** Where the provider executable was found; every path is absolute. */
85export interface ProviderMaintenanceResolutionContext {
86 readonly binaryPath: string;
87 readonly resolvedCommandPath: string;
88 readonly realCommandPath: string;
89 readonly env: NodeJS.ProcessEnv;
90 /** Host platform; decides how the copyable command quotes the executable. */
91 readonly platform: NodeJS.Platform;
92}
93
94export type ProviderMaintenanceResolverServices =
95 | FileSystem.FileSystem
96 | Path.Path
97 | ChildProcessSpawner.ChildProcessSpawner;
98
99export interface ProviderMaintenanceCapabilitiesResolver {
100 readonly resolve: (
101 context: ProviderMaintenanceResolutionContext | null,
102 ) => Effect.Effect<ProviderMaintenanceCapabilities, never, ProviderMaintenanceResolverServices>;
103}
104
105export interface PackageManagedProviderMaintenanceDefinition {
106 readonly provider: ProviderDriverKind;
107 readonly npmPackageName: string;
108 readonly nativeUpdate: {
109 readonly args: ReadonlyArray<string>;
110 readonly isCommandPath: (commandPath: string) => boolean;
111 /** Environment the native updater needs to target this instance's install. */
112 readonly env?: NodeJS.ProcessEnv;
113 } | null;
114}
115
116export interface ProviderVersionCacheEntry {
117 readonly expiresAt: number;
118 readonly version: string | null;
119}
120
121export const ProviderVersionCache = Context.Reference<Map<string, ProviderVersionCacheEntry>>(
122 "@t3tools/server/providerMaintenance/ProviderVersionCache",
123 {
124 defaultValue: () => new Map(),
125 },
126);
127const NpmLatestVersionResponse = Schema.Struct({
128 version: Schema.optional(Schema.String),
129});
130
131function nonEmptyString(value: unknown): string | null {
132 return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
133}
134
135/**
136 * The copyable command must paste into a shell as-is, so an executable path
137 * with spaces or quotes is quoted for the host's default shell.
138 */
139function quoteShellWord(word: string, platform: NodeJS.Platform): string {
140 const safeWord = platform === "win32" ? /^[\w./:\\@=-]+$/ : /^[\w./:@=-]+$/;
141 if (safeWord.test(word)) return word;
142 return platform === "win32"
143 ? `'${word.replace(/['\u2018\u2019]/g, "$&$&")}'`
144 : `'${word.replaceAll("'", "'\\''")}'`;
145}
146
147function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string {
148 const quoted = quoteShellWord(executable, platform);
149 // Windows terminals default to PowerShell, where a quoted executable needs &.
150 return platform === "win32" && quoted !== executable ? `& ${quoted}` : quoted;
151}
152
153export function makeProviderMaintenanceCapabilities(input: {
154 readonly provider: ProviderDriverKind;
155 readonly packageName: string | null;
156 readonly updateExecutable: string | null;
157 readonly updateArgs: ReadonlyArray<string>;
158 readonly updateLockKey: string | null;
159 /** Shown to the user instead of `<executable> <args>`; use for a bare tool name like `brew`. */
160 readonly updateCommand?: string;
161 readonly platform?: NodeJS.Platform;
162 readonly env?: NodeJS.ProcessEnv;
163 readonly latestVersion?: string | null;
164}): ProviderMaintenanceCapabilities {
165 const platform = input.platform ?? HostProcessPlatform.defaultValue();
166 const update =
167 input.updateExecutable === null || input.updateLockKey === null
168 ? null
169 : {
170 command:
171 input.updateCommand ??
172 [
173 quoteUpdateExecutable(input.updateExecutable, platform),
174 ...input.updateArgs.map((arg) => quoteShellWord(arg, platform)),
175 ].join(" "),
176 executable: input.updateExecutable,
177 args: input.updateArgs,
178 lockKey: input.updateLockKey,
179 ...(input.env ? { env: input.env } : {}),
180 };
181 return {
182 provider: input.provider,
183 packageName: input.packageName,
184 update,
185 ...("latestVersion" in input ? { latestVersion: input.latestVersion } : {}),
186 };
187}
188
189/** Pin only package-manager actions we own, preserving prefix, scripts, env and lock. */
190export function makeTargetedProviderUpdateAction(
191 capabilities: ProviderMaintenanceCapabilities,
192 version: string,
193): ProviderMaintenanceCommandAction | null {
194 if (!/^\d+\.\d+\.\d+$/.test(version)) return null;
195 const update = capabilities.update;
196 const packageName = capabilities.packageName;
197 if (!update || !packageName) return null;
198 if (!/^(?:npm-global:|bun-global$|pnpm-global$|vite-plus-global$)/.test(update.lockKey))
199 return null;
200 const packageIndex = update.args.findIndex(
201 (arg) => arg === `${packageName}@latest` || arg === packageName,
202 );
203 if (packageIndex < 0) return null;
204 const args = update.args.map((arg, index) =>
205 index === packageIndex ? `${packageName}@${version}` : arg,
206 );
207 const previous = update.args[packageIndex]!;
208 const commandIndex = update.command.lastIndexOf(previous);
209 const command =
210 commandIndex < 0
211 ? update.command
212 : `${update.command.slice(0, commandIndex)}${packageName}@${version}${update.command.slice(commandIndex + previous.length)}`;
213 return { ...update, args, command };
214}
215
216export function makeManualOnlyProviderMaintenanceCapabilities(input: {
217 readonly provider: ProviderDriverKind;
218 readonly packageName: string | null;
219}): ProviderMaintenanceCapabilities {
220 return makeProviderMaintenanceCapabilities({
221 provider: input.provider,
222 packageName: input.packageName,
223 updateExecutable: null,
224 updateArgs: [],
225 updateLockKey: null,
226 });
227}
228
229export function normalizeCommandPath(commandPath: string): string {
230 return commandPath.replaceAll("\\", "/").toLowerCase();
231}
232
233function isVitePlusGlobalCommandPath(commandPath: string): boolean {
234 return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");
235}
236
237function isBunGlobalCommandPath(commandPath: string): boolean {
238 return normalizeCommandPath(commandPath).includes("/.bun/bin/");
239}
240
241function isPnpmGlobalCommandPath(commandPath: string): boolean {
242 const normalized = normalizeCommandPath(commandPath);
243 return (
244 normalized.includes("/.local/share/pnpm/") ||
245 normalized.includes("/library/pnpm/") ||
246 normalized.includes("/local/share/pnpm/") ||
247 normalized.includes("/appdata/local/pnpm/") ||
248 normalized.includes("/pnpm/global/")
249 );
250}
251
252/**
253 * The npm global prefix that owns a package, derived from the real path of
254 * its entry point: `<prefix>/lib/node_modules/<pkg>/…`. Windows global
255 * installs have no `lib` segment and are proven by the shim instead (see
256 * `resolveNpmGlobalPrefix`). A project-local `node_modules` is not a global
257 * install and yields null.
258 */
259export function npmGlobalPrefixFromCommandPath(
260 realCommandPath: string,
261 packageName: string,
262): string | null {
263 const slashPath = realCommandPath.replaceAll("\\", "/");
264 const normalized = slashPath.toLowerCase();
265 const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`;
266 const packageIndex = normalized.lastIndexOf(packageSegment);
267 if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) {
268 return null;
269 }
270 // Mise's npm backend uses a global-looking layout inside a tool version.
271 // Globals under its Node installation still belong to npm.
272 const miseTool = /\/mise\/installs\/([^/]+)\/[^/]+$/.exec(normalized.slice(0, packageIndex))?.[1];
273 if (miseTool && miseTool !== "node") {
274 return null;
275 }
276 return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex);
277}
278
279// `<prefix>/Cellar/<name>/<version>/…` or `<prefix>/Caskroom/<name>/<version>/…`.
280// Homebrew always nests a version directory under the keg.
281const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i;
282
283export interface HomebrewOwnership {
284 readonly kind: "formula" | "cask";
285 readonly name: string;
286 /** The Homebrew prefix the keg sits under; must match `brew --prefix`. */
287 readonly prefix: string;
288}
289
290/**
291 * Homebrew looks like the owner when the real path runs through a versioned
292 * keg or cask. It is only proven once the prefix matches the `brew` that will
293 * run the upgrade (see `resolvePackageManagedProviderMaintenance`).
294 */
295export function homebrewOwnershipFromCommandPath(
296 realCommandPath: string,
297): HomebrewOwnership | null {
298 const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));
299 if (!match) {
300 return null;
301 }
302 return {
303 kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask",
304 name: match[3]!,
305 prefix: match[1]!,
306 };
307}
308
309const HomebrewInfoResponse = Schema.Struct({
310 formulae: Schema.optional(
311 Schema.Array(
312 Schema.Struct({
313 versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })),
314 }),
315 ),
316 ),
317 casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))),
318});
319
320const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse));
321
322/** Cask versions may carry a build suffix after a comma (`1.2.3,456`). */
323export function parseHomebrewLatestVersion(
324 infoJson: string,
325 ownership: HomebrewOwnership,
326): string | null {
327 const decoded = decodeHomebrewInfo(infoJson);
328 if (Option.isNone(decoded)) {
329 return null;
330 }
331 const raw =
332 ownership.kind === "formula"
333 ? decoded.value.formulae?.[0]?.versions?.stable
334 : decoded.value.casks?.[0]?.version?.split(",", 1)[0];
335 return nonEmptyString(raw);
336}
337
338/** Run `brew <args>` and return stdout, or null on failure, timeout, or oversized output. */
339const runHomebrew = Effect.fn("runHomebrew")(function* (
340 brewPath: string,
341 args: ReadonlyArray<string>,
342 env: NodeJS.ProcessEnv,
343) {
344 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
345 const collect = Effect.gen(function* () {
346 const child = yield* spawner.spawn(ChildProcess.make(brewPath, args, { env, extendEnv: true }));
347 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
348 // stderr is drained so a chatty brew cannot block on a full pipe.
349 const [stdout, exitCode] = yield* Effect.all(
350 [
351 collectUint8StreamText({ stream: child.stdout, maxBytes: HOMEBREW_INFO_MAX_BYTES }),
352 child.exitCode,
353 Stream.runDrain(child.stderr),
354 ],
355 { concurrency: "unbounded" },
356 );
357 return Number(exitCode) !== 0 || stdout.truncated ? null : stdout.text;
358 });
359 return yield* collect.pipe(
360 Effect.scoped,
361 Effect.timeoutOption(Duration.millis(HOMEBREW_INFO_TIMEOUT_MS)),
362 Effect.map(Option.getOrNull),
363 Effect.catchCause((cause) =>
364 Effect.logWarning("Homebrew probe failed", {
365 subcommand: args[0],
366 errorTag: causeErrorTag(cause),
367 }).pipe(Effect.as(null)),
368 ),
369 );
370});
371
372/**
373 * Derive update capabilities from where the executable actually lives. Every
374 * branch that yields a one-click command has evidence that the named tool
375 * owns that path; anything unproven stays manual-only so T3 Code never runs
376 * a package manager against an install it did not create.
377 */
378export const resolvePackageManagedProviderMaintenance = Effect.fn(
379 "resolvePackageManagedProviderMaintenance",
380)(function* (
381 definition: PackageManagedProviderMaintenanceDefinition,
382 context: ProviderMaintenanceResolutionContext | null,
383) {
384 const manual = makeManualOnlyProviderMaintenanceCapabilities({
385 provider: definition.provider,
386 packageName: definition.npmPackageName,
387 });
388 if (!context) {
389 return manual;
390 }
391 const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
392 const packageName = definition.npmPackageName;
393
394 const nativeUpdate = definition.nativeUpdate;
395 if (nativeUpdate && commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))) {
396 return makeProviderMaintenanceCapabilities({
397 provider: definition.provider,
398 packageName,
399 updateExecutable: context.resolvedCommandPath,
400 updateArgs: nativeUpdate.args,
401 updateLockKey: `${definition.provider}-native`,
402 platform: context.platform,
403 ...(nativeUpdate.env ? { env: nativeUpdate.env } : {}),
404 });
405 }
406 if (commandPaths.some(isVitePlusGlobalCommandPath)) {
407 return makeProviderMaintenanceCapabilities({
408 provider: definition.provider,
409 packageName,
410 updateExecutable: "vp",
411 updateArgs: ["i", "-g", packageName],
412 updateLockKey: "vite-plus-global",
413 });
414 }
415 if (commandPaths.some(isBunGlobalCommandPath)) {
416 return makeProviderMaintenanceCapabilities({
417 provider: definition.provider,
418 packageName,
419 updateExecutable: "bun",
420 updateArgs: ["i", "-g", `${packageName}@latest`],
421 updateLockKey: "bun-global",
422 });
423 }
424 if (commandPaths.some(isPnpmGlobalCommandPath)) {
425 return makeProviderMaintenanceCapabilities({
426 provider: definition.provider,
427 packageName,
428 updateExecutable: "pnpm",
429 updateArgs: ["add", "-g", `${packageName}@latest`],
430 updateLockKey: "pnpm-global",
431 });
432 }
433
434 // npm proof names the package, so it outranks a keg the path merely passes
435 // through: a Homebrew-installed Node keeps its globals under
436 // `Cellar/node/<ver>/lib/node_modules/`, and that is npm's install, not brew's.
437 const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);
438 if (npmPrefix) {
439 // npm 12 blocks install scripts by default (empty allow-scripts allowlist)
440 // and still exits 0, so a package whose postinstall finishes the install
441 // (claude copies its native binary over a placeholder stub) is left broken
442 // while the update reports success. Allow this one package's scripts.
443 // Older npm warns about the unknown config and continues.
444 return makeProviderMaintenanceCapabilities({
445 provider: definition.provider,
446 packageName,
447 updateExecutable: "npm",
448 updateArgs: [
449 "install",
450 "-g",
451 "--prefix",
452 npmPrefix,
453 `--allow-scripts=${packageName}`,
454 `${packageName}@latest`,
455 ],
456 updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,
457 });
458 }
459
460 const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
461 if (homebrew) {
462 // Mise shims resolve to the version manager, not the provider.
463 if (homebrew.kind === "formula" && homebrew.name.toLowerCase() === "mise") {
464 return manual;
465 }
466 const brewPath = yield* resolveCommandPath("brew", { env: context.env }).pipe(
467 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
468 );
469 if (!brewPath) {
470 return manual;
471 }
472 // A keg-shaped path is only Homebrew's if it sits under the prefix of the
473 // `brew` that would upgrade it; `brew --prefix` is a cheap shell script.
474 const fileSystem = yield* FileSystem.FileSystem;
475 const brewPrefix = nonEmptyString(yield* runHomebrew(brewPath, ["--prefix"], context.env));
476 const realBrewPrefix = brewPrefix
477 ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))
478 : null;
479 if (
480 !realBrewPrefix ||
481 normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)
482 ) {
483 return manual;
484 }
485 const args =
486 homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];
487 // Homebrew lags npm by hours on every release, so compare against what
488 // `brew upgrade` can actually deliver.
489 const info = yield* runHomebrew(brewPath, ["info", "--json=v2", homebrew.name], context.env);
490 return makeProviderMaintenanceCapabilities({
491 provider: definition.provider,
492 packageName,
493 updateExecutable: brewPath,
494 updateArgs: args,
495 updateLockKey: "homebrew",
496 updateCommand: ["brew", ...args].join(" "),
497 latestVersion: info ? parseHomebrewLatestVersion(info, homebrew) : null,
498 });
499 }
500
501 return manual;
502});
503
504/**
505 * POSIX npm links `<prefix>/bin/<cmd>` into the package, so the real path is
506 * proof. Windows npm writes `.cmd` shims beside `node_modules`, so the proof
507 * is the package manifest next to the shim.
508 */
509const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (
510 context: ProviderMaintenanceResolutionContext,
511 packageName: string,
512) {
513 const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);
514 if (fromRealPath) {
515 return fromRealPath;
516 }
517 if ((yield* HostProcessPlatform) !== "win32") {
518 return null;
519 }
520 const fileSystem = yield* FileSystem.FileSystem;
521 const path = yield* Path.Path;
522 const shimDir = path.dirname(context.resolvedCommandPath);
523 const manifestPath = path.join(
524 shimDir,
525 "node_modules",
526 ...packageName.split("/"),
527 "package.json",
528 );
529 // npm writes both `<cmd>.cmd` and an extensionless sh script into the
530 // Windows prefix; either one sits directly beside `node_modules`. A POSIX
531 // project checkout has the same shape, which is why this is Windows-only.
532 const hasManifest = yield* fileSystem
533 .exists(manifestPath)
534 .pipe(Effect.orElseSucceed(() => false));
535 return hasManifest ? shimDir : null;
536});
537
538export function makePackageManagedProviderMaintenanceResolver(
539 definition: PackageManagedProviderMaintenanceDefinition,
540): ProviderMaintenanceCapabilitiesResolver {
541 return {
542 resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),
543 };
544}
545
546function makeManualProviderMaintenanceCapabilities(
547 provider: ProviderDriverKind,
548): ProviderMaintenanceCapabilities {
549 return makeManualOnlyProviderMaintenanceCapabilities({
550 provider,
551 packageName: null,
552 });
553}
554
555/**
556 * Locate the configured provider executable, follow symlinks, and hand the
557 * result to the resolver. A binary that cannot be found yields the resolver's
558 * no-context answer.
559 */
560export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
561 "resolveProviderMaintenanceCapabilitiesEffect",
562)(function* (
563 resolver: ProviderMaintenanceCapabilitiesResolver,
564 options?: {
565 readonly binaryPath?: string | null;
566 readonly env?: NodeJS.ProcessEnv;
567 },
568) {
569 const binaryPath = nonEmptyString(options?.binaryPath);
570 if (!binaryPath) {
571 return yield* resolver.resolve(null);
572 }
573
574 const env = options?.env ?? (yield* readCommandLookupEnv);
575 // resolveCommandPath checks explicit paths for existence too, so a missing
576 // binary always lands in the no-context branch and never gets an update
577 // command it cannot run.
578 const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }).pipe(
579 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
580 );
581 if (!resolvedCommandPath) {
582 return yield* resolver.resolve(null);
583 }
584
585 const fileSystem = yield* FileSystem.FileSystem;
586 const realCommandPath = yield* fileSystem
587 .realPath(resolvedCommandPath)
588 .pipe(Effect.orElseSucceed(() => null));
589 if (!realCommandPath) {
590 return yield* resolver.resolve(null);
591 }
592 return yield* resolver.resolve({
593 binaryPath,
594 resolvedCommandPath,
595 realCommandPath,
596 env,
597 platform: yield* HostProcessPlatform,
598 });
599});
600
601/**
602 * Turn a one-shot resolution into the shape drivers expose: a cached read for
603 * advisories and a `fresh` read that update execution uses so it never trusts
604 * ownership derived before the user clicked.
605 */
606export const makeCachedProviderMaintenanceResolution = Effect.fn(
607 "makeCachedProviderMaintenanceResolution",
608)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {
609 const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(
610 resolve,
611 MAINTENANCE_CAPABILITIES_CACHE_TTL,
612 );
613 return (options?: { readonly fresh?: boolean }) =>
614 options?.fresh ? invalidate.pipe(Effect.andThen(cached)) : cached;
615});
616
617function deriveVersionAdvisory(input: {
618 readonly currentVersion: string | null;
619 readonly latestVersion: string | null;
620}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
621 if (!input.currentVersion) {
622 return { status: "unknown", message: null };
623 }
624 if (!input.latestVersion) {
625 return { status: "unknown", message: null };
626 }
627 if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {
628 return {
629 status: "behind_latest",
630 message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
631 };
632 }
633 return { status: "current", message: null };
634}
635
636export function createProviderVersionAdvisory(input: {
637 readonly driver: ProviderDriverKind;
638 readonly currentVersion: string | null;
639 readonly latestVersion?: string | null;
640 readonly checkedAt?: string | null;
641 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
642}): ServerProviderVersionAdvisory {
643 const capabilities =
644 input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
645 const latestVersion = input.latestVersion ?? null;
646 const advisory = deriveVersionAdvisory({
647 currentVersion: input.currentVersion,
648 latestVersion,
649 });
650
651 return {
652 status: advisory.status,
653 currentVersion: input.currentVersion,
654 latestVersion,
655 updateCommand: capabilities.update?.command ?? null,
656 canUpdate: capabilities.update !== null,
657 canInstallVersion: makeTargetedProviderUpdateAction(capabilities, "0.0.0") !== null,
658 checkedAt: input.checkedAt ?? null,
659 message: advisory.message,
660 };
661}
662
663const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
664 const client = yield* HttpClient.HttpClient;
665 const request = HttpClientRequest.get(
666 `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
667 ).pipe(HttpClientRequest.setHeader("accept", "application/json"));
668 const response = yield* client.execute(request).pipe(
669 Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
670 Effect.orElseSucceed(() => Option.none()),
671 );
672 if (Option.isNone(response)) {
673 return null;
674 }
675 const httpResponse = response.value;
676 if (httpResponse.status < 200 || httpResponse.status >= 300) {
677 return null;
678 }
679 const payload = yield* httpResponse.json.pipe(
680 Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
681 Effect.orElseSucceed(() => null),
682 );
683 return payload ? nonEmptyString(payload.version) : null;
684});
685
686export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
687 maintenanceCapabilities: ProviderMaintenanceCapabilities,
688) {
689 if (maintenanceCapabilities.latestVersion !== undefined) {
690 return maintenanceCapabilities.latestVersion;
691 }
692 const packageName = maintenanceCapabilities.packageName;
693 if (!packageName) {
694 return null;
695 }
696
697 const latestVersionCache = yield* ProviderVersionCache;
698 const cached = latestVersionCache.get(packageName);
699 const now = DateTime.toEpochMillis(yield* DateTime.now);
700 if (cached && cached.expiresAt > now) {
701 return cached.version;
702 }
703
704 const version = yield* fetchNpmLatestVersion(packageName);
705 latestVersionCache.set(packageName, {
706 expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,
707 version,
708 });
709 return version;
710});
711
712export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
713 "enrichProviderSnapshotWithVersionAdvisory",
714)(function* (
715 snapshot: ServerProvider,
716 maintenanceCapabilities?: ProviderMaintenanceCapabilities,
717 options?: {
718 readonly enableProviderUpdateChecks: boolean | undefined;
719 },
720) {
721 const capabilities =
722 maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
723 const shouldResolveLatestVersion =
724 options?.enableProviderUpdateChecks !== false &&
725 snapshot.enabled &&
726 snapshot.installed &&
727 Boolean(snapshot.version);
728 if (!shouldResolveLatestVersion) {
729 return {
730 ...snapshot,
731 versionAdvisory: createProviderVersionAdvisory({
732 driver: snapshot.driver,
733 currentVersion: snapshot.version,
734 checkedAt: snapshot.checkedAt,
735 maintenanceCapabilities: capabilities,
736 }),
737 };
738 }
739
740 const latestVersion = yield* resolveLatestProviderVersion(capabilities);
741 return {
742 ...snapshot,
743 versionAdvisory: createProviderVersionAdvisory({
744 driver: snapshot.driver,
745 currentVersion: snapshot.version,
746 latestVersion,
747 checkedAt: DateTime.formatIso(yield* DateTime.now),
748 maintenanceCapabilities: capabilities,
749 }),
750 };
751});