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