Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

maintenanceResolver.ts

1,221 lines45.1 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Synchronous hashing keeps env values out of cache keys.
2import * as NodeCrypto from "node:crypto";
3export type {
4 ProviderMaintenanceCapabilities,
5 ProviderMaintenanceCommandAction,
6} from "@t3tools/provider-core/server/maintenance";
7import type {
8 ProviderMaintenanceCapabilities,
9 ProviderMaintenanceCommandAction,
10} from "@t3tools/provider-core/server/maintenance";
11import {
12 ProviderDriverKind,
13 type ServerProvider,
14 type ServerProviderVersionAdvisory,
15} from "@t3tools/contracts";
16import { compareSemverVersions, satisfiesSemverRange } from "@t3tools/shared/semver";
17import * as HostProcess from "@t3tools/shared/HostProcess";
18import { causeErrorTag } from "@t3tools/shared/observability";
19import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell";
20import * as Cache from "effect/Cache";
21import * as Config from "effect/Config";
22import * as DateTime from "effect/DateTime";
23import * as Duration from "effect/Duration";
24import * as Effect from "effect/Effect";
25import * as FileSystem from "effect/FileSystem";
26import * as Option from "effect/Option";
27import * as Path from "effect/Path";
28import * as Schema from "effect/Schema";
29import * as Stream from "effect/Stream";
30import * as HttpClient from "effect/http/HttpClient";
31import * as HttpClientRequest from "effect/http/HttpClientRequest";
32import * as HttpClientResponse from "effect/http/HttpClientResponse";
33import * as ChildProcess from "effect/process/ChildProcess";
34import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
35​
36import { collectUint8StreamText } from "./collectStreamText.ts";
37import * as ProviderLatestVersions from "./ProviderLatestVersions.ts";
38​
39const LATEST_VERSION_TIMEOUT_MS = 4_000;
40const PROBE_TIMEOUT_MS = 10_000;
41const PROBE_MAX_BYTES = 256 * 1_024;
42const MISE_WRAPPER_MAX_BYTES = 16 * 1_024;
43const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
44​
45const MAINTENANCE_CAPABILITIES_CACHE_TTL = Duration.hours(1);
46​
47const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
48 Object.fromEntries(
49 Object.entries(input).flatMap(([key, value]) =>
50 Option.match(value, {
51 onNone: () => [],
52 onSome: (resolved) => [[key, resolved]],
53 }),
54 ),
55 );
56​
57const CommandLookupEnvConfig = Config.all({
58 PATH: Config.String("PATH").pipe(Config.option),
59 Path: Config.String("Path").pipe(Config.option),
60 path: Config.String("path").pipe(Config.option),
61 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
62}).pipe(Config.map(compactEnv));
63​
64const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
65​
66export interface ProviderMaintenanceResolutionContext {
67 readonly binaryPath: string;
68 readonly resolvedCommandPath: string;
69 readonly realCommandPath: string;
70 readonly env: NodeJS.ProcessEnv;
71 readonly platform: NodeJS.Platform;
73​
74export type ProviderMaintenanceResolverServices =
75 | FileSystem.FileSystem
76 | Path.Path
77 | ChildProcessSpawner.ChildProcessSpawner;
78​
79export interface ProviderMaintenanceCapabilitiesResolver {
80 readonly resolve: (
81 context: ProviderMaintenanceResolutionContext | null,
82 ) => Effect.Effect<ProviderMaintenanceCapabilities, never, ProviderMaintenanceResolverServices>;
84​
85export interface PackageManagedProviderMaintenanceDefinition {
86 readonly provider: ProviderDriverKind;
87 readonly npmPackageName: string;
88 readonly nativeUpdate: {
89 readonly args: ReadonlyArray<string>;
90 readonly isCommandPath?: (commandPath: string) => boolean;
91 /** The updater cannot detect installs outside `isCommandPath`, so leave those manual-only. */
92 readonly requiresCommandPath?: boolean;
93 readonly env?:
94 | NodeJS.ProcessEnv
95 | ((context: ProviderMaintenanceResolutionContext) => NodeJS.ProcessEnv);
96 } | null;
97 /** The mise registry tool that installs this provider; unset keeps mise installs manual-only. */
98 readonly mise?: MiseProviderTool;
100​
101export interface MiseProviderTool {
102 readonly tool: string;
103 /** False still claims the tool's installs, but keeps them manual-only. */
104 readonly upgrade?: boolean;
106​
107const NpmLatestVersionResponse = Schema.Struct({
108 version: Schema.optional(Schema.String),
109});
110​
111function nonEmptyString(value: unknown): string | null {
112 return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
114​
115function quoteShellWord(word: string, platform: NodeJS.Platform): string {
116 const safeWord = platform === "win32" ? /^[\w./:\\@=-]+$/ : /^[\w./:@=-]+$/;
117 if (safeWord.test(word)) return word;
118 return platform === "win32"
119 ? `'${word.replace(/['\u2018\u2019]/g, "$&$&")}'`
120 : `'${word.replaceAll("'", "'\\''")}'`;
122​
123function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string {
124 const quoted = quoteShellWord(executable, platform);
125 // Windows terminals default to PowerShell, where a quoted executable needs &.
126 return platform === "win32" && quoted !== executable ? `& ${quoted}` : quoted;
128​
129export function makeProviderMaintenanceCapabilities(input: {
130 readonly provider: ProviderDriverKind;
131 readonly packageName: string | null;
132 readonly updateExecutable: string | null;
133 readonly updateArgs: ReadonlyArray<string>;
134 readonly updateLockKey: string | null;
135 readonly updateCommand?: string;
136 readonly platform?: NodeJS.Platform;
137 readonly env?: NodeJS.ProcessEnv;
138 readonly latestVersion?: string | null;
139 readonly lookupLatestVersion?: Effect.Effect<string | null>;
140}): ProviderMaintenanceCapabilities {
141 const platform = input.platform ?? HostProcess.Platform.defaultValue();
142 const update =
143 input.updateExecutable === null || input.updateLockKey === null
144 ? null
145 : {
146 command:
147 input.updateCommand ??
148 [
149 quoteUpdateExecutable(input.updateExecutable, platform),
150 ...input.updateArgs.map((arg) => quoteShellWord(arg, platform)),
151 ].join(" "),
152 executable: input.updateExecutable,
153 args: input.updateArgs,
154 lockKey: input.updateLockKey,
155 ...(input.env ? { env: input.env } : {}),
156 };
157 return {
158 provider: input.provider,
159 packageName: input.packageName,
160 update,
161 ...("latestVersion" in input ? { latestVersion: input.latestVersion } : {}),
162 ...(input.lookupLatestVersion ? { lookupLatestVersion: input.lookupLatestVersion } : {}),
163 };
165​
166export function makeTargetedProviderUpdateAction(
167 capabilities: ProviderMaintenanceCapabilities,
168 version: string,
169): ProviderMaintenanceCommandAction | null {
170 if (!/^\d+\.\d+\.\d+$/.test(version)) return null;
171 const update = capabilities.update;
172 const packageName = capabilities.packageName;
173 if (!update || !packageName) return null;
174 if (
175 !/^(?:npm-global:|bun-global$|pnpm-global$|vite-plus-global$|yarn-global$|volta$)/.test(
176 update.lockKey,
177 )
178 )
179 return null;
180 const packageIndex = update.args.findIndex(
181 (arg) => arg === `${packageName}@latest` || arg === packageName,
182 );
183 if (packageIndex < 0) return null;
184 const args = update.args.map((arg, index) =>
185 index === packageIndex ? `${packageName}@${version}` : arg,
186 );
187 const previous = update.args[packageIndex]!;
188 const commandIndex = update.command.lastIndexOf(previous);
189 const command =
190 commandIndex < 0
191 ? update.command
192 : `${update.command.slice(0, commandIndex)}${packageName}@${version}${update.command.slice(commandIndex + previous.length)}`;
193 return { ...update, args, command };
195​
196// pnpm 11 resolves `@latest` to the newest release older than `minimumReleaseAge`
197// and exits 0, so a release advertised from the npm dist-tag would never install.
198// An exact spec installs it and pnpm records it in `minimumReleaseAgeExclude`.
199export function resolveLatestProviderUpdateAction(
200 capabilities: ProviderMaintenanceCapabilities,
201 latestVersion: string | null,
202): ProviderMaintenanceCommandAction | null {
203 const update = capabilities.update;
204 if (update?.lockKey !== "pnpm-global" || latestVersion === null) return update;
205 return makeTargetedProviderUpdateAction(capabilities, latestVersion) ?? update;
207​
208export function makeManualOnlyProviderMaintenanceCapabilities(input: {
209 readonly provider: ProviderDriverKind;
210 readonly packageName: string | null;
211 readonly installPath?: string;
212 readonly lookupLatestVersion?: Effect.Effect<string | null>;
213 readonly manualCommand?: string;
214}): ProviderMaintenanceCapabilities {
215 return {
216 ...makeProviderMaintenanceCapabilities({
217 provider: input.provider,
218 packageName: input.packageName,
219 updateExecutable: null,
220 updateArgs: [],
221 updateLockKey: null,
222 ...(input.lookupLatestVersion
223 ? { latestVersion: null, lookupLatestVersion: input.lookupLatestVersion }
224 : {}),
225 }),
226 ...(input.installPath ? { installPath: input.installPath } : {}),
227 ...(input.manualCommand ? { manualCommand: input.manualCommand } : {}),
228 };
230​
231export function normalizeCommandPath(commandPath: string): string {
232 return commandPath.replaceAll("\\", "/").toLowerCase();
234​
235/**
236 * Vite+ shims live in `<VP_HOME>/bin`: `~/.vite-plus` by default,
237 * `~/.local/share/vite-plus` with the XDG layout, and `%LOCALAPPDATA%\vite-plus`
238 * on Windows.
239 */
240function isVitePlusGlobalCommandPath(commandPath: string): boolean {
241 return /\/(?:\.vite-plus|\.local\/share\/vite-plus|appdata\/local\/vite-plus)\/bin\//.test(
242 normalizeCommandPath(commandPath),
243 );
245​
246function isBunGlobalCommandPath(commandPath: string): boolean {
247 return normalizeCommandPath(commandPath).includes("/.bun/bin/");
249​
250function isYarnGlobalCommandPath(commandPath: string): boolean {
251 return /\/yarn\/(?:data\/)?global\/node_modules\//.test(normalizeCommandPath(commandPath));
253​
254/**
255 * Paths mise owns. npm globals under mise's own Node belong to npm, which proves their prefix.
256 * A command wrapper is a symlink to the `mise` binary, which dispatches on argv[0].
257 */
258function isMiseCommandPath(commandPath: string): boolean {
259 const normalized = normalizeCommandPath(commandPath);
260 return (
261 (normalized.includes("/mise/installs/") && !normalized.includes("/mise/installs/node/")) ||
262 normalized.includes("/mise/shims/") ||
263 normalized.includes("/mise/command-wrappers/")
264 );
266​
267/** A mise shim or command wrapper is a link to mise itself, wherever mise keeps its data. */
268function isMiseExecutablePath(commandPath: string): boolean {
269 return /(?:^|\/)mise(?:\.exe)?$/.test(normalizeCommandPath(commandPath));
271​
272const winGetClaudeCommandPath =
273 /^[a-z]:\/(?:users\/[^/]+\/appdata\/local\/microsoft|program files(?: \(x86\))?)\/winget\/(?:links|packages\/anthropic\.claudecode_[^/]+)\/claude\.exe$/;
274​
275function isWinGetClaudeCommandPath(commandPath: string): boolean {
276 return winGetClaudeCommandPath.test(normalizeCommandPath(commandPath));
278​
279const CHOCOLATEY_CLAUDE_PACKAGE_ID = "claude-code";
280​
281// Chocolatey's executable shim is not a symlink, so realpath cannot prove its owner.
282const chocolateyClaudeCommandPath = /\/chocolatey\/(?:bin|lib\/claude-code\/tools)\/claude\.exe$/;
283​
284function isChocolateyClaudeCommandPath(commandPath: string, env: NodeJS.ProcessEnv): boolean {
285 const normalized = normalizeCommandPath(commandPath);
286 if (chocolateyClaudeCommandPath.test(normalized)) return true;
287 const root = nonEmptyString(env.ChocolateyInstall);
288 if (!root) return false;
289 const prefix = normalizeCommandPath(root.replace(/[\\/]+$/, ""));
290 return (
291 normalized === `${prefix}/bin/claude.exe` ||
292 normalized === `${prefix}/lib/claude-code/tools/claude.exe`
293 );
295​
296/** `choco search --exact --limit-output` prints `<id>|<version>` for a match and nothing otherwise. */
297export function parseChocolateyLatestVersion(output: string, packageId: string): string | null {
298 for (const line of output.split(/\r?\n/)) {
299 const [id, version] = line.trim().split("|", 2);
300 if (id?.toLowerCase() === packageId.toLowerCase()) return nonEmptyString(version);
301 }
302 return null;
304​
305function isPnpmGlobalCommandPath(commandPath: string): boolean {
306 const normalized = normalizeCommandPath(commandPath);
307 return (
308 normalized.includes("/.local/share/pnpm/") ||
309 normalized.includes("/library/pnpm/") ||
310 normalized.includes("/local/share/pnpm/") ||
311 normalized.includes("/appdata/local/pnpm/") ||
312 normalized.includes("/pnpm/global/")
313 );
315​
316export function npmGlobalPrefixFromCommandPath(
317 realCommandPath: string,
318 packageName: string,
319): string | null {
320 const slashPath = realCommandPath.replaceAll("\\", "/");
321 const normalized = slashPath.toLowerCase();
322 const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`;
323 const packageIndex = normalized.lastIndexOf(packageSegment);
324 if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) {
325 return null;
326 }
327 // Mise tool layouts resemble npm globals; only globals under its Node install belong to npm.
328 const miseTool = /\/mise\/installs\/([^/]+)\/[^/]+$/.exec(normalized.slice(0, packageIndex))?.[1];
329 if (miseTool && miseTool !== "node") {
330 return null;
331 }
332 return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex);
334​
335const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i;
336​
337export interface HomebrewOwnership {
338 readonly kind: "formula" | "cask";
339 readonly name: string;
340 readonly prefix: string;
342​
343export function homebrewOwnershipFromCommandPath(
344 realCommandPath: string,
345): HomebrewOwnership | null {
346 const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));
347 if (!match) {
348 return null;
349 }
350 return {
351 kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask",
352 name: match[3]!,
353 prefix: match[1]!,
354 };
356​
357const HomebrewInfoResponse = Schema.Struct({
358 formulae: Schema.optional(
359 Schema.Array(
360 Schema.Struct({
361 versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })),
362 }),
363 ),
364 ),
365 casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))),
366});
367​
368const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse));
369​
370export function parseHomebrewLatestVersion(
371 infoJson: string,
372 ownership: HomebrewOwnership,
373): string | null {
374 const decoded = decodeHomebrewInfo(infoJson);
375 if (Option.isNone(decoded)) {
376 return null;
377 }
378 const raw =
379 ownership.kind === "formula"
380 ? decoded.value.formulae?.[0]?.versions?.stable
381 : decoded.value.casks?.[0]?.version?.split(",", 1)[0];
382 const version = nonEmptyString(raw);
383 return version === "latest" ? null : version;
385​
386const runProbe = Effect.fn("runProbe")(function* (
387 command: string,
388 args: ReadonlyArray<string>,
389 env: NodeJS.ProcessEnv,
390 okExitCodes: ReadonlyArray<number> = [0],
391) {
392 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
393 const collect = Effect.gen(function* () {
394 // Windows package managers are `.cmd` shims that need the shell.
395 const resolved = yield* resolveSpawnCommand(command, args, { env, extendEnv: true });
396 const child = yield* spawner.spawn(
397 ChildProcess.make(resolved.command, resolved.args, {
398 env,
399 extendEnv: true,
400 shell: resolved.shell,
401 }),
402 );
403 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
404 // stderr is drained so a chatty tool cannot block on a full pipe.
405 const [stdout, exitCode] = yield* Effect.all(
406 [
407 collectUint8StreamText({ stream: child.stdout, maxBytes: PROBE_MAX_BYTES }),
408 child.exitCode,
409 Stream.runDrain(child.stderr),
410 ],
411 { concurrency: "unbounded" },
412 );
413 return !okExitCodes.includes(Number(exitCode)) || stdout.truncated ? null : stdout.text;
414 });
415 return yield* collect.pipe(
416 Effect.scoped,
417 Effect.timeoutOption(Duration.millis(PROBE_TIMEOUT_MS)),
418 Effect.map(Option.getOrNull),
419 Effect.catchCause((cause) =>
420 Effect.logWarning("Maintenance probe failed", {
421 command,
422 subcommand: args[0],
423 errorTag: causeErrorTag(cause),
424 }).pipe(Effect.as(null)),
425 ),
426 );
427});
428​
429const decodePnpmOutdated = Schema.decodeUnknownOption(
430 Schema.fromJsonString(
431 Schema.Record(Schema.String, Schema.Struct({ latest: Schema.optional(Schema.String) })),
432 ),
433);
434const decodePnpmList = Schema.decodeUnknownOption(
435 Schema.fromJsonString(
436 Schema.Array(
437 Schema.Struct({
438 dependencies: Schema.optional(
439 Schema.Record(Schema.String, Schema.Struct({ version: Schema.optional(Schema.String) })),
440 ),
441 }),
442 ),
443 ),
444);
445​
446// Unlike npm's latest tag, pnpm outdated respects minimumReleaseAge and its excludes.
447const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion")(function* (
448 packageName: string,
449 env: NodeJS.ProcessEnv,
450) {
451 // Match the updater's pnpm and environment.
452 const pnpmPath = yield* resolveCommandPath("pnpm", {
453 env: { ...(yield* HostProcess.Environment), ...env },
454 });
455 if (!pnpmPath) return null;
456 // Silent reporting keeps project package-manager warnings out of the JSON.
457 const outdated = yield* runProbe(
458 pnpmPath,
459 ["outdated", "-g", "--reporter=silent", "--format", "json", packageName],
460 env,
461 // pnpm outdated exits 1 when updates are available.
462 [0, 1],
463 );
464 const outdatedEntries = outdated
465 ? Option.getOrUndefined(decodePnpmOutdated(outdated))
466 : undefined;
467 if (!outdatedEntries) return null;
468 const latest = nonEmptyString(outdatedEntries[packageName]?.latest);
469 if (latest) return latest;
470 // An empty result means the installed version is still the eligible release.
471 const listed = yield* runProbe(
472 pnpmPath,
473 ["ls", "-g", "--reporter=silent", "--depth", "0", "--json", packageName],
474 env,
475 );
476 const listedEntries = listed ? Option.getOrUndefined(decodePnpmList(listed)) : undefined;
477 return nonEmptyString(listedEntries?.[0]?.dependencies?.[packageName]?.version);
478});
479​
480const MiseInstall = Schema.Struct({
481 install_path: Schema.String,
482 requested_version: Schema.optional(Schema.NullOr(Schema.String)),
483 active: Schema.optional(Schema.Boolean),
484});
485const decodeMiseToolInstalls = Schema.decodeUnknownOption(
486 Schema.fromJsonString(Schema.Array(MiseInstall)),
487);
488const decodeMiseInstalls = Schema.decodeUnknownOption(
489 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Array(MiseInstall))),
490);
491​
492/** The installs `mise ls --json --installed <tool>` lists, refusing any other tool's. */
493function miseToolInstalls(
494 listing: string,
495 miseTool: string,
496): ReadonlyArray<typeof MiseInstall.Type> {
497 const installs = decodeMiseToolInstalls(listing);
498 if (Option.isSome(installs)) return installs.value;
499 const byTool = Option.getOrUndefined(decodeMiseInstalls(listing));
500 return byTool && Object.keys(byTool).every((tool) => tool === miseTool)
501 ? (byTool[miseTool] ?? [])
502 : [];
504​
505/**
506 * Null when mise does not own the executable. Upgrades need an active `latest` install of the
507 * driver's fixed mise tool, launched through a shim or the `latest` link `mise upgrade` moves;
508 * a fixed version's path would keep running the pruned binary, so it stays manual-only.
509 */
510export const resolveMiseProviderMaintenance = Effect.fn("resolveMiseProviderMaintenance")(
511 function* (
512 owner: { readonly provider: ProviderDriverKind; readonly packageName: string | null },
513 mise: MiseProviderTool | undefined,
514 context: ProviderMaintenanceResolutionContext,
515 ) {
516 const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
517 const isShim = isMiseExecutablePath(context.realCommandPath);
518 const looksMise =
519 isShim || commandPaths.some(isMiseCommandPath) || (yield* isMiseWrapperScript(context));
520 const manual = (installPath: string) =>
521 makeManualOnlyProviderMaintenanceCapabilities({ ...owner, installPath });
522 const notOwned = (installPath: string) => (looksMise ? manual(installPath) : null);
523 const commandName = normalizeCommandPath(context.resolvedCommandPath)
524 .split("/")
525 .at(-1)
526 ?.replace(/\.(?:exe|cmd|bat|ps1)$/, "");
527 if (!mise) return notOwned(context.realCommandPath);
528 const miseTool = mise.tool;
529 // A shim runs whatever mise resolves for its own name, which must be the mapped tool's.
530 if (isShim && commandName !== miseTool) return manual(context.realCommandPath);
531​
532 const fileSystem = yield* FileSystem.FileSystem;
533 const realPath = (target: string) =>
534 fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target));
535 const misePath =
536 (yield* resolveCommandPath("mise", { env: context.env })) ??
537 (isShim ? context.realCommandPath : null);
538 if (!misePath) return notOwned(context.realCommandPath);
539 // Asked even off mise's usual paths, since `MISE_DATA_DIR` can put installs anywhere.
540 const which = nonEmptyString(yield* runProbe(misePath, ["which", miseTool], context.env));
541 const resolvedPath = which ? yield* realPath(which) : null;
542 // Through a shim T3 Code runs whatever mise resolves; otherwise the configured binary.
543 const binaryPath = isShim ? resolvedPath : context.realCommandPath;
544 if (!binaryPath) return manual(context.realCommandPath);
545 const binary = normalizeCommandPath(binaryPath);
546 const runsBinary = resolvedPath !== null && normalizeCommandPath(resolvedPath) === binary;
547 const listing = yield* runProbe(
548 misePath,
549 ["ls", "--json", "--installed", miseTool],
550 context.env,
551 );
552 if (!listing) return runsBinary ? manual(binaryPath) : notOwned(binaryPath);
553 const isUnder = (path: string, dir: string) =>
554 path.startsWith(`${normalizeCommandPath(dir).replace(/\/+$/, "")}/`);
555 // An inactive or shadowed install is still mise's, even when `mise which` resolves another.
556 const owning = yield* Effect.filter(miseToolInstalls(listing, miseTool), (install) =>
557 realPath(install.install_path).pipe(
558 Effect.map((installPath) => isUnder(binary, installPath)),
559 ),
560 );
561 // `mise which` also resolves binaries from other tools, such as npm globals under mise's Node.
562 if (owning.length === 0) return notOwned(binaryPath);
563 if (!runsBinary) return manual(binaryPath);
564 const install = owning.find(
565 (candidate) => candidate.active === true && candidate.requested_version === "latest",
566 );
567 if (!install || mise.upgrade === false) return manual(binaryPath);
568 if (!isShim) {
569 // Keep the path's case: `realPath` needs it on case-sensitive filesystems.
570 const toolDir = install.install_path
571 .replaceAll("\\", "/")
572 .replace(/\/+$/, "")
573 .replace(/\/[^/]+$/, "");
574 const latestDirs = [toolDir, yield* realPath(toolDir)].map((dir) => `${dir}/latest`);
575 const resolved = normalizeCommandPath(context.resolvedCommandPath);
576 if (!latestDirs.some((dir) => isUnder(resolved, dir))) return manual(binaryPath);
577 }
578 const args = ["upgrade", miseTool];
579 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
580 // Mise reads its settings from this environment, so each one gets its own cached answer.
581 const envHash = NodeCrypto.createHash("sha256");
582 for (const [name, value] of Object.entries(context.env).toSorted(([a], [b]) =>
583 a < b ? -1 : 1,
584 )) {
585 envHash.update(`${name}\0${value ?? ""}\0`);
586 }
587 const envKey = envHash.digest("hex");
588 const capabilities = makeProviderMaintenanceCapabilities({
589 ...owner,
590 updateExecutable: misePath,
591 updateArgs: args,
592 updateLockKey: "mise",
593 updateCommand: ["mise", ...args].join(" "),
594 platform: context.platform,
595 // Mise read its config from this environment, so the upgrade runs in it too.
596 env: context.env,
597 // Settings such as `minimum_release_age` can hold mise behind the registry,
598 // so only mise can say what it installs. It may go to the network, so ask lazily.
599 latestVersion: null,
600 lookupLatestVersion: runProbe(misePath, ["latest", miseTool], context.env).pipe(
601 Effect.map((latest) => {
602 const version = nonEmptyString(latest);
603 return version && /^\S+$/.test(version) ? version : null;
604 }),
605 Effect.provideContext(services),
606 ),
607 });
608 return {
609 ...capabilities,
610 latestVersionCacheKey: ["mise", misePath, miseTool, envKey].join("\0"),
611 };
612 },
613);
614​
615export const resolvePackageManagedProviderMaintenance = Effect.fn(
616 "resolvePackageManagedProviderMaintenance",
617)(function* (
618 definition: PackageManagedProviderMaintenanceDefinition,
619 context: ProviderMaintenanceResolutionContext | null,
620) {
621 if (!context) {
622 return makeManualOnlyProviderMaintenanceCapabilities({
623 provider: definition.provider,
624 packageName: definition.npmPackageName,
625 });
626 }
627 const manual = makeManualOnlyProviderMaintenanceCapabilities({
628 provider: definition.provider,
629 packageName: definition.npmPackageName,
630 installPath: context.realCommandPath,
631 });
632 const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
633 const packageName = definition.npmPackageName;
634 // WinGet-managed claude update exits 0 without updating; T3 does not run winget upgrade.
635 if (
636 definition.provider === "claudeAgent" &&
637 context.platform === "win32" &&
638 commandPaths.some(isWinGetClaudeCommandPath)
639 ) {
640 return manual;
641 }
642 // Chocolatey's package directory is writable only by administrators, so an
643 // unelevated server cannot run `choco upgrade`; `claude update` through the
644 // shim installs a native copy elsewhere and leaves the shim's version alone.
645 if (
646 definition.provider === "claudeAgent" &&
647 context.platform === "win32" &&
648 commandPaths.some((commandPath) => isChocolateyClaudeCommandPath(commandPath, context.env))
649 ) {
650 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
651 return makeManualOnlyProviderMaintenanceCapabilities({
652 provider: definition.provider,
653 packageName,
654 installPath: context.realCommandPath,
655 manualCommand: "choco upgrade claude-code",
656 lookupLatestVersion: runProbe(
657 "choco",
658 ["search", CHOCOLATEY_CLAUDE_PACKAGE_ID, "--exact", "--limit-output"],
659 context.env,
660 ).pipe(
661 Effect.map((output) =>
662 output ? parseChocolateyLatestVersion(output, CHOCOLATEY_CLAUDE_PACKAGE_ID) : null,
663 ),
664 Effect.provideContext(services),
665 ),
666 });
667 }
668​
669 const mise = yield* resolveMiseProviderMaintenance(
670 { provider: definition.provider, packageName },
671 definition.mise,
672 context,
673 );
674 if (mise) return mise;
675​
676 const nativeUpdate = definition.nativeUpdate;
677 const nativeEnv = nativeUpdate?.env;
678 const native = nativeUpdate
679 ? makeProviderMaintenanceCapabilities({
680 provider: definition.provider,
681 packageName,
682 updateExecutable: context.resolvedCommandPath,
683 updateArgs: nativeUpdate.args,
684 updateLockKey: `${definition.provider}-native`,
685 platform: context.platform,
686 ...(nativeEnv
687 ? { env: typeof nativeEnv === "function" ? nativeEnv(context) : nativeEnv }
688 : {}),
689 })
690 : manual;
691 // A native-looking launcher can still delegate to an npm-owned install.
692 if (
693 nativeUpdate?.isCommandPath &&
694 commandPaths.some(nativeUpdate.isCommandPath) &&
695 !npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName)
696 ) {
697 return native;
698 }
699 // A `node_modules` path not proven below belongs to another package or a
700 // project, so the provider's own updater could act on the wrong install.
701 const fallback =
702 nativeUpdate?.requiresCommandPath ||
703 commandPaths.some((commandPath) => normalizeCommandPath(commandPath).includes("/node_modules/"))
704 ? manual
705 : native;
706 if (commandPaths.some(isVitePlusGlobalCommandPath)) {
707 return makeProviderMaintenanceCapabilities({
708 provider: definition.provider,
709 packageName,
710 updateExecutable: "vp",
711 updateArgs: ["i", "-g", packageName],
712 updateLockKey: "vite-plus-global",
713 env: context.env,
714 });
715 }
716 if (commandPaths.some(isBunGlobalCommandPath)) {
717 return makeProviderMaintenanceCapabilities({
718 provider: definition.provider,
719 packageName,
720 updateExecutable: "bun",
721 updateArgs: ["i", "-g", `${packageName}@latest`],
722 updateLockKey: "bun-global",
723 env: context.env,
724 });
725 }
726 if (commandPaths.some(isPnpmGlobalCommandPath)) {
727 // pnpm 10 skips unapproved scripts; the approval flag requires 10.4+.
728 const pnpmVersion = yield* runProbe("pnpm", ["--version"], context.env);
729 const allowBuild =
730 pnpmVersion !== null && satisfiesSemverRange(pnpmVersion, ">=10.4.0")
731 ? [`--allow-build=${packageName}`]
732 : [];
733 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
734 return makeProviderMaintenanceCapabilities({
735 provider: definition.provider,
736 packageName,
737 updateExecutable: "pnpm",
738 updateArgs: ["add", "-g", ...allowBuild, `${packageName}@latest`],
739 updateLockKey: "pnpm-global",
740 env: context.env,
741 lookupLatestVersion: resolvePnpmGlobalLatestVersion(packageName, context.env).pipe(
742 Effect.provideContext(services),
743 ),
744 });
745 }
746​
747 if (commandPaths.some(isYarnGlobalCommandPath)) {
748 return makeProviderMaintenanceCapabilities({
749 provider: definition.provider,
750 packageName,
751 updateExecutable: "yarn",
752 updateArgs: ["global", "add", `${packageName}@latest`],
753 updateLockKey: "yarn-global",
754 env: context.env,
755 });
756 }
757 if (yield* isVoltaPackageInstall(context, packageName)) {
758 return makeProviderMaintenanceCapabilities({
759 provider: definition.provider,
760 packageName,
761 updateExecutable: "volta",
762 updateArgs: ["install", `${packageName}@latest`],
763 updateLockKey: "volta",
764 env: context.env,
765 });
766 }
767​
768 // npm proof outranks a containing Homebrew keg; Homebrew Node globals still belong to npm.
769 const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);
770 if (npmPrefix) {
771 // npm 12 requires script approval to install native binaries; older npm only warns about the flag.
772 return makeProviderMaintenanceCapabilities({
773 provider: definition.provider,
774 packageName,
775 updateExecutable: "npm",
776 updateArgs: [
777 "install",
778 "-g",
779 "--prefix",
780 npmPrefix,
781 `--allow-scripts=${packageName}`,
782 `${packageName}@latest`,
783 ],
784 updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,
785 env: context.env,
786 });
787 }
788​
789 const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
790 if (homebrew) {
791 return (
792 (yield* resolveHomebrewProviderMaintenance(
793 { provider: definition.provider, packageName },
794 homebrew,
795 context,
796 )) ?? fallback
797 );
798 }
799​
800 return fallback;
801});
802​
803/**
804 * `brew upgrade` capabilities once the keg's prefix is confirmed by a `brew`
805 * that reports it as its own. Version checks defer `brew info` until needed.
806 * Null when no `brew` is found or it owns another prefix.
807 */
808export const resolveHomebrewProviderMaintenance = Effect.fn("resolveHomebrewProviderMaintenance")(
809 function* (
810 input: { readonly provider: ProviderDriverKind; readonly packageName: string | null },
811 homebrew: HomebrewOwnership,
812 context: ProviderMaintenanceResolutionContext,
813 ) {
814 const fileSystem = yield* FileSystem.FileSystem;
815 const path = yield* Path.Path;
816 // GUI servers may lack Homebrew on PATH; use the keg brew with the same prefix check.
817 const kegBrewPath = path.join(homebrew.prefix, "bin", "brew");
818 const brewPath = (yield* fileSystem.exists(kegBrewPath).pipe(Effect.orElseSucceed(() => false)))
819 ? kegBrewPath
820 : yield* resolveCommandPath("brew", { env: context.env });
821 if (!brewPath) {
822 return null;
823 }
824 const brewPrefix = nonEmptyString(yield* runProbe(brewPath, ["--prefix"], context.env));
825 const realBrewPrefix = brewPrefix
826 ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))
827 : null;
828 if (
829 !realBrewPrefix ||
830 normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)
831 ) {
832 return null;
833 }
834 const args =
835 homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];
836 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
837 return makeProviderMaintenanceCapabilities({
838 provider: input.provider,
839 packageName: input.packageName,
840 updateExecutable: brewPath,
841 updateArgs: args,
842 updateLockKey: "homebrew",
843 updateCommand: ["brew", ...args].join(" "),
844 // Brew's release can lag npm; only its own channel can say what upgrade installs.
845 latestVersion: null,
846 lookupLatestVersion: runProbe(
847 brewPath,
848 ["info", "--json=v2", homebrew.name],
849 context.env,
850 ).pipe(
851 Effect.map((info) => (info ? parseHomebrewLatestVersion(info, homebrew) : null)),
852 Effect.provideContext(services),
853 ),
854 });
855 },
856);
857​
858const isMiseWrapperScript = Effect.fn("isMiseWrapperScript")(function* (
859 context: ProviderMaintenanceResolutionContext,
860) {
861 const fileSystem = yield* FileSystem.FileSystem;
862 const size = yield* fileSystem.stat(context.realCommandPath).pipe(
863 Effect.map((info) => Number(info.size)),
864 Effect.orElseSucceed(() => Infinity),
865 );
866 if (size > MISE_WRAPPER_MAX_BYTES) {
867 return false;
868 }
869 const script = yield* fileSystem
870 .readFileString(context.realCommandPath)
871 .pipe(Effect.orElseSucceed(() => ""));
872 return script.startsWith("#!") && /\bmise\s+(?:x|exec)\b/.test(script);
873});
874​
875// Volta bin links only identify its shim; the package image proves ownership.
876const isVoltaPackageInstall = Effect.fn("isVoltaPackageInstall")(function* (
877 context: ProviderMaintenanceResolutionContext,
878 packageName: string,
879) {
880 const path = yield* Path.Path;
881 if (
882 path.basename(normalizeCommandPath(context.realCommandPath)).replace(/\.exe$/, "") !==
883 "volta-shim"
884 ) {
885 return false;
886 }
887 const voltaHome = path.dirname(path.dirname(context.resolvedCommandPath));
888 const packageDir = path.join(voltaHome, "tools", "image", "packages", ...packageName.split("/"));
889 const fileSystem = yield* FileSystem.FileSystem;
890 return yield* fileSystem.exists(packageDir).pipe(Effect.orElseSucceed(() => false));
891});
892​
893const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (
894 context: ProviderMaintenanceResolutionContext,
895 packageName: string,
896) {
897 const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);
898 if (fromRealPath) {
899 return fromRealPath;
900 }
901 if ((yield* HostProcess.Platform) !== "win32") {
902 return null;
903 }
904 const fileSystem = yield* FileSystem.FileSystem;
905 const path = yield* Path.Path;
906 const shimDir = path.dirname(context.resolvedCommandPath);
907 const manifestPath = path.join(
908 shimDir,
909 "node_modules",
910 ...packageName.split("/"),
911 "package.json",
912 );
913 // Windows npm shims sit beside node_modules; POSIX project checkouts can mimic this layout.
914 const hasManifest = yield* fileSystem
915 .exists(manifestPath)
916 .pipe(Effect.orElseSucceed(() => false));
917 return hasManifest ? shimDir : null;
918});
919​
920export function makePackageManagedProviderMaintenanceResolver(
921 definition: PackageManagedProviderMaintenanceDefinition,
922): ProviderMaintenanceCapabilitiesResolver {
923 return {
924 resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),
925 };
927​
928function makeManualProviderMaintenanceCapabilities(
929 provider: ProviderDriverKind,
930): ProviderMaintenanceCapabilities {
931 return makeManualOnlyProviderMaintenanceCapabilities({
932 provider,
933 packageName: null,
934 });
936​
937const decodeNpmViewVersion = Schema.decodeUnknownOption(
938 Schema.fromJsonString(Schema.Union([Schema.String, Schema.Tuple([Schema.String])])),
939);
940​
941const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup")(function* (
942 capabilities: ProviderMaintenanceCapabilities,
943) {
944 const packageName = capabilities.packageName;
945 if (!packageName || capabilities.latestVersion !== undefined) {
946 return capabilities;
947 }
948 const env = { ...(yield* HostProcess.Environment), ...capabilities.update?.env };
949 const npmPath = yield* resolveCommandPath("npm", { env });
950 if (!npmPath) return capabilities;
951 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
952 const update = capabilities.update;
953 const prefixIndex = update?.lockKey.startsWith("npm-global:")
954 ? update.args.indexOf("--prefix")
955 : -1;
956 const prefix = prefixIndex >= 0 ? update?.args[prefixIndex + 1] : undefined;
957 const lookup = runProbe(
958 npmPath,
959 [
960 "view",
961 "--global",
962 ...(prefix ? ["--prefix", prefix] : []),
963 "--json",
964 `${packageName}@latest`,
965 "version",
966 ],
967 env,
968 ).pipe(
969 Effect.map((stdout) => {
970 const value = stdout ? Option.getOrNull(decodeNpmViewVersion(stdout.trim())) : null;
971 return nonEmptyString(typeof value === "string" ? value : value?.[0]);
972 }),
973 Effect.tap((version) =>
974 version === null
975 ? Effect.logWarning("Configured npm version lookup failed", { packageName })
976 : Effect.void,
977 ),
978 Effect.provideContext(services),
979 );
980 return {
981 ...capabilities,
982 // npm owns registry, scoped auth and proxy configuration; failure must not retry public npm.
983 latestVersion: null,
984 lookupLatestVersion: capabilities.lookupLatestVersion
985 ? capabilities.lookupLatestVersion.pipe(
986 Effect.filterOrElse(
987 (version) => version !== null,
988 () => lookup,
989 ),
990 )
991 : lookup,
992 };
993});
994​
995export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
996 "resolveProviderMaintenanceCapabilitiesEffect",
997)(function* (
998 resolver: ProviderMaintenanceCapabilitiesResolver,
999 options?: {
1000 readonly binaryPath?: string | null;
1001 readonly env?: NodeJS.ProcessEnv;
1002 },
1003) {
1004 const binaryPath = nonEmptyString(options?.binaryPath);
1005 if (!binaryPath) {
1006 return yield* resolver.resolve(null);
1008​
1009 const env = options?.env ?? (yield* readCommandLookupEnv);
1010 const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env });
1011 if (!resolvedCommandPath) {
1012 return yield* resolver.resolve(null);
1014​
1015 const fileSystem = yield* FileSystem.FileSystem;
1016 const realCommandPath = yield* fileSystem
1017 .realPath(resolvedCommandPath)
1018 .pipe(Effect.orElseSucceed(() => null));
1019 if (!realCommandPath) {
1020 return yield* resolver.resolve(null);
1022 return yield* resolver.resolve({
1023 binaryPath,
1024 resolvedCommandPath,
1025 realCommandPath,
1026 env,
1027 platform: yield* HostProcess.Platform,
1028 });
1029}, Effect.flatMap(withConfiguredNpmVersionLookup));
1030​
1031export const makeCachedProviderMaintenanceResolution = Effect.fn(
1032 "makeCachedProviderMaintenanceResolution",
1033)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {
1034 const cache = yield* Cache.make({
1035 capacity: 1,
1036 timeToLive: MAINTENANCE_CAPABILITIES_CACHE_TTL,
1037 lookup: () => resolve,
1038 });
1039 const cached = Cache.get(cache, undefined);
1040 return (options?: { readonly fresh?: boolean }) =>
1041 options?.fresh ? Cache.invalidate(cache, undefined).pipe(Effect.andThen(cached)) : cached;
1042});
1043​
1044function manualUpdateMessage(latestVersion: string, installPath: string | undefined): string {
1045 return installPath
1046 ? `Version ${latestVersion} is out. T3 Code runs ${installPath}; update it with the app or tool that installed it.`
1047 : `Version ${latestVersion} is out. Update it with the app or tool that installed it.`;
1049​
1050function deriveVersionAdvisory(input: {
1051 readonly currentVersion: string | null;
1052 readonly latestVersion: string | null;
1053 readonly capabilities: ProviderMaintenanceCapabilities;
1054}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
1055 if (!input.currentVersion) {
1056 return { status: "unknown", message: null };
1058 if (!input.latestVersion) {
1059 return { status: "unknown", message: null };
1061 if (
1062 (input.capabilities.compareVersions ?? compareSemverVersions)(
1063 input.currentVersion,
1064 input.latestVersion,
1065 ) < 0
1066 ) {
1067 return {
1068 status: "behind_latest",
1069 message:
1070 input.capabilities.update === null
1071 ? manualUpdateMessage(input.latestVersion, input.capabilities.installPath)
1072 : PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
1073 };
1075 return { status: "current", message: null };
1077​
1078export function createProviderVersionAdvisory(input: {
1079 readonly driver: ProviderDriverKind;
1080 readonly currentVersion: string | null;
1081 readonly latestVersion?: string | null;
1082 readonly checkedAt?: string | null;
1083 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
1084}): ServerProviderVersionAdvisory {
1085 const capabilities =
1086 input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
1087 const latestVersion = input.latestVersion ?? null;
1088 const advisory = deriveVersionAdvisory({
1089 currentVersion: input.currentVersion,
1090 latestVersion,
1091 capabilities,
1092 });
1093​
1094 return {
1095 status: advisory.status,
1096 currentVersion: input.currentVersion,
1097 latestVersion,
1098 updateCommand:
1099 resolveLatestProviderUpdateAction(capabilities, latestVersion)?.command ??
1100 capabilities.manualCommand ??
1101 null,
1102 canUpdate: capabilities.update !== null,
1103 canInstallVersion: makeTargetedProviderUpdateAction(capabilities, "0.0.0") !== null,
1104 checkedAt: input.checkedAt ?? null,
1105 message: advisory.message,
1106 };
1108​
1109const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
1110 const client = yield* HttpClient.HttpClient;
1111 const request = HttpClientRequest.get(
1112 `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
1113 ).pipe(HttpClientRequest.setHeader("accept", "application/json"));
1114 // The deadline covers the body too: headers can arrive before the JSON stalls.
1115 const payload = yield* client.execute(request).pipe(
1116 Effect.flatMap(HttpClientResponse.filterStatusOk),
1117 Effect.flatMap(HttpClientResponse.schemaBodyJson(NpmLatestVersionResponse)),
1118 Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
1119 Effect.orElseSucceed(() => Option.none()),
1120 );
1121 return Option.isSome(payload) ? nonEmptyString(payload.value.version) : null;
1122});
1123​
1124/**
1125 * The installer's own answer is cached apart from the npm registry entry. A
1126 * manual-only install has no command to key on, so its executable stands in.
1127 */
1128function installerLatestVersionKey(capabilities: ProviderMaintenanceCapabilities) {
1129 if (!capabilities.lookupLatestVersion) return null;
1130 if (capabilities.latestVersionCacheKey) return capabilities.latestVersionCacheKey;
1131 const update = capabilities.update;
1132 if (update) return [update.lockKey, update.executable, ...update.args].join("\0");
1133 return capabilities.installPath
1134 ? ["manual", capabilities.installPath].join("\0")
1135 : capabilities.packageName && `npm-registry\0${capabilities.packageName}`;
1137​
1138export function latestProviderVersionCacheKeys(
1139 capabilities: ProviderMaintenanceCapabilities,
1140): ReadonlyArray<string> {
1141 return [capabilities.packageName, installerLatestVersionKey(capabilities)].filter(
1142 (key) => key !== null,
1143 );
1145​
1146export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
1147 maintenanceCapabilities: ProviderMaintenanceCapabilities,
1148) {
1149 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
1150 const installerKey = installerLatestVersionKey(maintenanceCapabilities);
1151 if (installerKey && maintenanceCapabilities.lookupLatestVersion) {
1152 const installable = yield* latestVersions.cached(
1153 installerKey,
1154 maintenanceCapabilities.lookupLatestVersion,
1155 );
1156 if (installable !== null) return installable;
1158 if (maintenanceCapabilities.latestVersion !== undefined) {
1159 return maintenanceCapabilities.latestVersion;
1161 const packageName = maintenanceCapabilities.packageName;
1162 if (!packageName) {
1163 return null;
1165​
1166 return yield* latestVersions.cached(packageName, fetchNpmLatestVersion(packageName));
1167});
1168​
1169export const invalidateLatestProviderVersion = Effect.fn("invalidateLatestProviderVersion")(
1170 function* (maintenanceCapabilities: ProviderMaintenanceCapabilities) {
1171 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
1172 yield* Effect.forEach(
1173 latestProviderVersionCacheKeys(maintenanceCapabilities),
1174 latestVersions.invalidate,
1175 { discard: true },
1176 );
1177 },
1179​
1180export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
1181 "enrichProviderSnapshotWithVersionAdvisory",
1182)(function* (
1183 snapshot: ServerProvider,
1184 maintenanceCapabilities?: ProviderMaintenanceCapabilities,
1185 options?: {
1186 readonly enableProviderUpdateChecks: boolean | undefined;
1187 },
1188) {
1189 const capabilities =
1190 maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
1191 const currentVersion =
1192 snapshot.installedVersion !== undefined ? snapshot.installedVersion : snapshot.version;
1193 const shouldResolveLatestVersion =
1194 options?.enableProviderUpdateChecks !== false &&
1195 snapshot.enabled &&
1196 snapshot.installed &&
1197 Boolean(currentVersion);
1198 if (!shouldResolveLatestVersion) {
1199 return {
1200 ...snapshot,
1201 versionAdvisory: createProviderVersionAdvisory({
1202 driver: snapshot.driver,
1203 currentVersion,
1204 checkedAt: snapshot.checkedAt,
1205 maintenanceCapabilities: capabilities,
1206 }),
1207 };
1209​
1210 const latestVersion = yield* resolveLatestProviderVersion(capabilities);
1211 return {
1212 ...snapshot,
1213 versionAdvisory: createProviderVersionAdvisory({
1214 driver: snapshot.driver,
1215 currentVersion,
1216 latestVersion,
1217 checkedAt: DateTime.formatIso(yield* DateTime.now),
1218 maintenanceCapabilities: capabilities,
1219 }),
1220 };
1221});