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

providerMaintenance.ts

862 lines31.2 KB

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