Open History to see the last commit
1export type {
2 ProviderMaintenanceCapabilities,
3 ProviderMaintenanceCommandAction,
4} from "@t3tools/provider-core/server/maintenance";
5import type {
6 ProviderMaintenanceCapabilities,
7 ProviderMaintenanceCommandAction,
8} from "@t3tools/provider-core/server/maintenance";
9import {
10 ProviderDriverKind,
11 type ServerProvider,
12 type ServerProviderVersionAdvisory,
13} from "@t3tools/contracts";
14import { compareSemverVersions, satisfiesSemverRange } from "@t3tools/shared/semver";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import { causeErrorTag } from "@t3tools/shared/observability";
17import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell";
18import * as Cache from "effect/Cache";
19import * as Config from "effect/Config";
20import * as DateTime from "effect/DateTime";
21import * as Duration from "effect/Duration";
22import * as Effect from "effect/Effect";
23import * as FileSystem from "effect/FileSystem";
24import * as Option from "effect/Option";
25import * as Path from "effect/Path";
26import * as Schema from "effect/Schema";
27import * as Stream from "effect/Stream";
28import * as HttpClient from "effect/http/HttpClient";
29import * as HttpClientRequest from "effect/http/HttpClientRequest";
30import * as ChildProcess from "effect/process/ChildProcess";
31import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
32
33import { collectUint8StreamText } from "./collectStreamText.ts";
34import * as ProviderLatestVersions from "./ProviderLatestVersions.ts";
35
36const LATEST_VERSION_TIMEOUT_MS = 4_000;
37const PROBE_TIMEOUT_MS = 10_000;
38const PROBE_MAX_BYTES = 256 * 1_024;
39const MISE_WRAPPER_MAX_BYTES = 16 * 1_024;
40const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
41
42const MAINTENANCE_CAPABILITIES_CACHE_TTL = Duration.hours(1);
43
44const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
45 Object.fromEntries(
46 Object.entries(input).flatMap(([key, value]) =>
47 Option.match(value, {
48 onNone: () => [],
49 onSome: (resolved) => [[key, resolved]],
50 }),
51 ),
52 );
53
54const CommandLookupEnvConfig = Config.all({
55 PATH: Config.String("PATH").pipe(Config.option),
56 Path: Config.String("Path").pipe(Config.option),
57 path: Config.String("path").pipe(Config.option),
58 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
59}).pipe(Config.map(compactEnv));
60
61const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
62
63export interface ProviderMaintenanceResolutionContext {
64 readonly binaryPath: string;
65 readonly resolvedCommandPath: string;
66 readonly realCommandPath: string;
67 readonly env: NodeJS.ProcessEnv;
68 readonly platform: NodeJS.Platform;
69}
70
71export type ProviderMaintenanceResolverServices =
72 | FileSystem.FileSystem
73 | Path.Path
74 | ChildProcessSpawner.ChildProcessSpawner;
75
76export interface ProviderMaintenanceCapabilitiesResolver {
77 readonly resolve: (
78 context: ProviderMaintenanceResolutionContext | null,
79 ) => Effect.Effect<ProviderMaintenanceCapabilities, never, ProviderMaintenanceResolverServices>;
80}
81
82export interface PackageManagedProviderMaintenanceDefinition {
83 readonly provider: ProviderDriverKind;
84 readonly npmPackageName: string;
85 readonly nativeUpdate: {
86 readonly args: ReadonlyArray<string>;
87 readonly isCommandPath?: (commandPath: string) => boolean;
88 /** The updater cannot detect installs outside `isCommandPath`, so leave those manual-only. */
89 readonly requiresCommandPath?: boolean;
90 readonly env?: NodeJS.ProcessEnv;
91 } | null;
92}
93
94const NpmLatestVersionResponse = Schema.Struct({
95 version: Schema.optional(Schema.String),
96});
97
98function nonEmptyString(value: unknown): string | null {
99 return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
100}
101
102function quoteShellWord(word: string, platform: NodeJS.Platform): string {
103 const safeWord = platform === "win32" ? /^[\w./:\\@=-]+$/ : /^[\w./:@=-]+$/;
104 if (safeWord.test(word)) return word;
105 return platform === "win32"
106 ? `'${word.replace(/['\u2018\u2019]/g, "$&$&")}'`
107 : `'${word.replaceAll("'", "'\\''")}'`;
108}
109
110function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string {
111 const quoted = quoteShellWord(executable, platform);
112 // Windows terminals default to PowerShell, where a quoted executable needs &.
113 return platform === "win32" && quoted !== executable ? `& ${quoted}` : quoted;
114}
115
116export function makeProviderMaintenanceCapabilities(input: {
117 readonly provider: ProviderDriverKind;
118 readonly packageName: string | null;
119 readonly updateExecutable: string | null;
120 readonly updateArgs: ReadonlyArray<string>;
121 readonly updateLockKey: string | null;
122 readonly updateCommand?: string;
123 readonly platform?: NodeJS.Platform;
124 readonly env?: NodeJS.ProcessEnv;
125 readonly latestVersion?: string | null;
126 readonly lookupLatestVersion?: Effect.Effect<string | null>;
127}): ProviderMaintenanceCapabilities {
128 const platform = input.platform ?? HostProcess.Platform.defaultValue();
129 const update =
130 input.updateExecutable === null || input.updateLockKey === null
131 ? null
132 : {
133 command:
134 input.updateCommand ??
135 [
136 quoteUpdateExecutable(input.updateExecutable, platform),
137 ...input.updateArgs.map((arg) => quoteShellWord(arg, platform)),
138 ].join(" "),
139 executable: input.updateExecutable,
140 args: input.updateArgs,
141 lockKey: input.updateLockKey,
142 ...(input.env ? { env: input.env } : {}),
143 };
144 return {
145 provider: input.provider,
146 packageName: input.packageName,
147 update,
148 ...("latestVersion" in input ? { latestVersion: input.latestVersion } : {}),
149 ...(input.lookupLatestVersion ? { lookupLatestVersion: input.lookupLatestVersion } : {}),
150 };
151}
152
153export function makeTargetedProviderUpdateAction(
154 capabilities: ProviderMaintenanceCapabilities,
155 version: string,
156): ProviderMaintenanceCommandAction | null {
157 if (!/^\d+\.\d+\.\d+$/.test(version)) return null;
158 const update = capabilities.update;
159 const packageName = capabilities.packageName;
160 if (!update || !packageName) return null;
161 if (
162 !/^(?:npm-global:|bun-global$|pnpm-global$|vite-plus-global$|yarn-global$|volta$)/.test(
163 update.lockKey,
164 )
165 )
166 return null;
167 const packageIndex = update.args.findIndex(
168 (arg) => arg === `${packageName}@latest` || arg === packageName,
169 );
170 if (packageIndex < 0) return null;
171 const args = update.args.map((arg, index) =>
172 index === packageIndex ? `${packageName}@${version}` : arg,
173 );
174 const previous = update.args[packageIndex]!;
175 const commandIndex = update.command.lastIndexOf(previous);
176 const command =
177 commandIndex < 0
178 ? update.command
179 : `${update.command.slice(0, commandIndex)}${packageName}@${version}${update.command.slice(commandIndex + previous.length)}`;
180 return { ...update, args, command };
181}
182
183// pnpm 11 resolves `@latest` to the newest release older than `minimumReleaseAge`
184// and exits 0, so a release advertised from the npm dist-tag would never install.
185// An exact spec installs it and pnpm records it in `minimumReleaseAgeExclude`.
186export function resolveLatestProviderUpdateAction(
187 capabilities: ProviderMaintenanceCapabilities,
188 latestVersion: string | null,
189): ProviderMaintenanceCommandAction | null {
190 const update = capabilities.update;
191 if (update?.lockKey !== "pnpm-global" || latestVersion === null) return update;
192 return makeTargetedProviderUpdateAction(capabilities, latestVersion) ?? update;
193}
194
195export function makeManualOnlyProviderMaintenanceCapabilities(input: {
196 readonly provider: ProviderDriverKind;
197 readonly packageName: string | null;
198 readonly installPath?: string;
199}): ProviderMaintenanceCapabilities {
200 return {
201 ...makeProviderMaintenanceCapabilities({
202 provider: input.provider,
203 packageName: input.packageName,
204 updateExecutable: null,
205 updateArgs: [],
206 updateLockKey: null,
207 }),
208 ...(input.installPath ? { installPath: input.installPath } : {}),
209 };
210}
211
212export function normalizeCommandPath(commandPath: string): string {
213 return commandPath.replaceAll("\\", "/").toLowerCase();
214}
215
216/**
217 * Vite+ shims live in `<VP_HOME>/bin`: `~/.vite-plus` by default,
218 * `~/.local/share/vite-plus` with the XDG layout, and `%LOCALAPPDATA%\vite-plus`
219 * on Windows.
220 */
221function isVitePlusGlobalCommandPath(commandPath: string): boolean {
222 return /\/(?:\.vite-plus|\.local\/share\/vite-plus|appdata\/local\/vite-plus)\/bin\//.test(
223 normalizeCommandPath(commandPath),
224 );
225}
226
227function isBunGlobalCommandPath(commandPath: string): boolean {
228 return normalizeCommandPath(commandPath).includes("/.bun/bin/");
229}
230
231function isYarnGlobalCommandPath(commandPath: string): boolean {
232 return /\/yarn\/(?:data\/)?global\/node_modules\//.test(normalizeCommandPath(commandPath));
233}
234
235/** Version-manager installs are pinned in its config, so updating them means editing that. */
236function isMiseCommandPath(commandPath: string): boolean {
237 const normalized = normalizeCommandPath(commandPath);
238 return normalized.includes("/mise/installs/") || normalized.includes("/mise/shims/");
239}
240
241const winGetClaudeCommandPath =
242 /^[a-z]:\/(?:users\/[^/]+\/appdata\/local\/microsoft|program files(?: \(x86\))?)\/winget\/(?:links|packages\/anthropic\.claudecode_[^/]+)\/claude\.exe$/;
243
244function isWinGetClaudeCommandPath(commandPath: string): boolean {
245 return winGetClaudeCommandPath.test(normalizeCommandPath(commandPath));
246}
247
248function isPnpmGlobalCommandPath(commandPath: string): boolean {
249 const normalized = normalizeCommandPath(commandPath);
250 return (
251 normalized.includes("/.local/share/pnpm/") ||
252 normalized.includes("/library/pnpm/") ||
253 normalized.includes("/local/share/pnpm/") ||
254 normalized.includes("/appdata/local/pnpm/") ||
255 normalized.includes("/pnpm/global/")
256 );
257}
258
259export function npmGlobalPrefixFromCommandPath(
260 realCommandPath: string,
261 packageName: string,
262): string | null {
263 const slashPath = realCommandPath.replaceAll("\\", "/");
264 const normalized = slashPath.toLowerCase();
265 const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`;
266 const packageIndex = normalized.lastIndexOf(packageSegment);
267 if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) {
268 return null;
269 }
270 // Mise tool layouts resemble npm globals; only globals under its Node install belong to npm.
271 const miseTool = /\/mise\/installs\/([^/]+)\/[^/]+$/.exec(normalized.slice(0, packageIndex))?.[1];
272 if (miseTool && miseTool !== "node") {
273 return null;
274 }
275 return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex);
276}
277
278const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i;
279
280export interface HomebrewOwnership {
281 readonly kind: "formula" | "cask";
282 readonly name: string;
283 readonly prefix: string;
284}
285
286export function homebrewOwnershipFromCommandPath(
287 realCommandPath: string,
288): HomebrewOwnership | null {
289 const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));
290 if (!match) {
291 return null;
292 }
293 return {
294 kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask",
295 name: match[3]!,
296 prefix: match[1]!,
297 };
298}
299
300const HomebrewInfoResponse = Schema.Struct({
301 formulae: Schema.optional(
302 Schema.Array(
303 Schema.Struct({
304 versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })),
305 }),
306 ),
307 ),
308 casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))),
309});
310
311const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse));
312
313export function parseHomebrewLatestVersion(
314 infoJson: string,
315 ownership: HomebrewOwnership,
316): string | null {
317 const decoded = decodeHomebrewInfo(infoJson);
318 if (Option.isNone(decoded)) {
319 return null;
320 }
321 const raw =
322 ownership.kind === "formula"
323 ? decoded.value.formulae?.[0]?.versions?.stable
324 : decoded.value.casks?.[0]?.version?.split(",", 1)[0];
325 const version = nonEmptyString(raw);
326 return version === "latest" ? null : version;
327}
328
329const runProbe = Effect.fn("runProbe")(function* (
330 command: string,
331 args: ReadonlyArray<string>,
332 env: NodeJS.ProcessEnv,
333 okExitCodes: ReadonlyArray<number> = [0],
334) {
335 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
336 const collect = Effect.gen(function* () {
337 // Windows package managers are `.cmd` shims that need the shell.
338 const resolved = yield* resolveSpawnCommand(command, args, { env, extendEnv: true });
339 const child = yield* spawner.spawn(
340 ChildProcess.make(resolved.command, resolved.args, {
341 env,
342 extendEnv: true,
343 shell: resolved.shell,
344 }),
345 );
346 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
347 // stderr is drained so a chatty tool cannot block on a full pipe.
348 const [stdout, exitCode] = yield* Effect.all(
349 [
350 collectUint8StreamText({ stream: child.stdout, maxBytes: PROBE_MAX_BYTES }),
351 child.exitCode,
352 Stream.runDrain(child.stderr),
353 ],
354 { concurrency: "unbounded" },
355 );
356 return !okExitCodes.includes(Number(exitCode)) || stdout.truncated ? null : stdout.text;
357 });
358 return yield* collect.pipe(
359 Effect.scoped,
360 Effect.timeoutOption(Duration.millis(PROBE_TIMEOUT_MS)),
361 Effect.map(Option.getOrNull),
362 Effect.catchCause((cause) =>
363 Effect.logWarning("Maintenance probe failed", {
364 command,
365 subcommand: args[0],
366 errorTag: causeErrorTag(cause),
367 }).pipe(Effect.as(null)),
368 ),
369 );
370});
371
372const decodePnpmOutdated = Schema.decodeUnknownOption(
373 Schema.fromJsonString(
374 Schema.Record(Schema.String, Schema.Struct({ latest: Schema.optional(Schema.String) })),
375 ),
376);
377const decodePnpmList = Schema.decodeUnknownOption(
378 Schema.fromJsonString(
379 Schema.Array(
380 Schema.Struct({
381 dependencies: Schema.optional(
382 Schema.Record(Schema.String, Schema.Struct({ version: Schema.optional(Schema.String) })),
383 ),
384 }),
385 ),
386 ),
387);
388
389// Unlike npm's latest tag, pnpm outdated respects minimumReleaseAge and its excludes.
390const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion")(function* (
391 packageName: string,
392) {
393 // Match the updater's pnpm and server environment, rather than the instance's.
394 const pnpmPath = yield* resolveCommandPath("pnpm");
395 if (!pnpmPath) return null;
396 // Silent reporting keeps project package-manager warnings out of the JSON.
397 const outdated = yield* runProbe(
398 pnpmPath,
399 ["outdated", "-g", "--reporter=silent", "--format", "json", packageName],
400 {},
401 // pnpm outdated exits 1 when updates are available.
402 [0, 1],
403 );
404 const outdatedEntries = outdated
405 ? Option.getOrUndefined(decodePnpmOutdated(outdated))
406 : undefined;
407 if (!outdatedEntries) return null;
408 const latest = nonEmptyString(outdatedEntries[packageName]?.latest);
409 if (latest) return latest;
410 // An empty result means the installed version is still the eligible release.
411 const listed = yield* runProbe(
412 pnpmPath,
413 ["ls", "-g", "--reporter=silent", "--depth", "0", "--json", packageName],
414 {},
415 );
416 const listedEntries = listed ? Option.getOrUndefined(decodePnpmList(listed)) : undefined;
417 return nonEmptyString(listedEntries?.[0]?.dependencies?.[packageName]?.version);
418});
419
420export const resolvePackageManagedProviderMaintenance = Effect.fn(
421 "resolvePackageManagedProviderMaintenance",
422)(function* (
423 definition: PackageManagedProviderMaintenanceDefinition,
424 context: ProviderMaintenanceResolutionContext | null,
425) {
426 if (!context) {
427 return makeManualOnlyProviderMaintenanceCapabilities({
428 provider: definition.provider,
429 packageName: definition.npmPackageName,
430 });
431 }
432 const manual = makeManualOnlyProviderMaintenanceCapabilities({
433 provider: definition.provider,
434 packageName: definition.npmPackageName,
435 installPath: context.realCommandPath,
436 });
437 const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
438 const packageName = definition.npmPackageName;
439 // WinGet-managed claude update exits 0 without updating; T3 does not run winget upgrade.
440 if (
441 definition.provider === "claudeAgent" &&
442 context.platform === "win32" &&
443 commandPaths.some(isWinGetClaudeCommandPath)
444 ) {
445 return manual;
446 }
447
448 const nativeUpdate = definition.nativeUpdate;
449 const native = nativeUpdate
450 ? makeProviderMaintenanceCapabilities({
451 provider: definition.provider,
452 packageName,
453 updateExecutable: context.resolvedCommandPath,
454 updateArgs: nativeUpdate.args,
455 updateLockKey: `${definition.provider}-native`,
456 platform: context.platform,
457 ...(nativeUpdate.env ? { env: nativeUpdate.env } : {}),
458 })
459 : manual;
460 // A native-looking launcher can still delegate to a mise-owned install.
461 if (
462 nativeUpdate?.isCommandPath &&
463 commandPaths.some(nativeUpdate.isCommandPath) &&
464 !commandPaths.some(isMiseCommandPath) &&
465 !(yield* isMiseWrapperScript(context))
466 ) {
467 return native;
468 }
469 // A `node_modules` path not proven below belongs to another package or a
470 // project, so the provider's own updater could act on the wrong install.
471 const fallback =
472 nativeUpdate?.requiresCommandPath ||
473 commandPaths.some((commandPath) => normalizeCommandPath(commandPath).includes("/node_modules/"))
474 ? manual
475 : native;
476 if (commandPaths.some(isVitePlusGlobalCommandPath)) {
477 return makeProviderMaintenanceCapabilities({
478 provider: definition.provider,
479 packageName,
480 updateExecutable: "vp",
481 updateArgs: ["i", "-g", packageName],
482 updateLockKey: "vite-plus-global",
483 });
484 }
485 if (commandPaths.some(isBunGlobalCommandPath)) {
486 return makeProviderMaintenanceCapabilities({
487 provider: definition.provider,
488 packageName,
489 updateExecutable: "bun",
490 updateArgs: ["i", "-g", `${packageName}@latest`],
491 updateLockKey: "bun-global",
492 });
493 }
494 if (commandPaths.some(isPnpmGlobalCommandPath)) {
495 // pnpm 10 skips unapproved scripts; the approval flag requires 10.4+.
496 const pnpmVersion = yield* runProbe("pnpm", ["--version"], context.env);
497 const allowBuild =
498 pnpmVersion !== null && satisfiesSemverRange(pnpmVersion, ">=10.4.0")
499 ? [`--allow-build=${packageName}`]
500 : [];
501 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
502 return makeProviderMaintenanceCapabilities({
503 provider: definition.provider,
504 packageName,
505 updateExecutable: "pnpm",
506 updateArgs: ["add", "-g", ...allowBuild, `${packageName}@latest`],
507 updateLockKey: "pnpm-global",
508 lookupLatestVersion: resolvePnpmGlobalLatestVersion(packageName).pipe(
509 Effect.provideContext(services),
510 ),
511 });
512 }
513
514 if (commandPaths.some(isYarnGlobalCommandPath)) {
515 return makeProviderMaintenanceCapabilities({
516 provider: definition.provider,
517 packageName,
518 updateExecutable: "yarn",
519 updateArgs: ["global", "add", `${packageName}@latest`],
520 updateLockKey: "yarn-global",
521 });
522 }
523 if (yield* isVoltaPackageInstall(context, packageName)) {
524 return makeProviderMaintenanceCapabilities({
525 provider: definition.provider,
526 packageName,
527 updateExecutable: "volta",
528 updateArgs: ["install", `${packageName}@latest`],
529 updateLockKey: "volta",
530 });
531 }
532
533 // npm proof outranks a containing Homebrew keg; Homebrew Node globals still belong to npm.
534 const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);
535 if (npmPrefix) {
536 // npm 12 requires script approval to install native binaries; older npm only warns about the flag.
537 return makeProviderMaintenanceCapabilities({
538 provider: definition.provider,
539 packageName,
540 updateExecutable: "npm",
541 updateArgs: [
542 "install",
543 "-g",
544 "--prefix",
545 npmPrefix,
546 `--allow-scripts=${packageName}`,
547 `${packageName}@latest`,
548 ],
549 updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,
550 });
551 }
552
553 const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
554 if (
555 commandPaths.some(isMiseCommandPath) ||
556 // Mise shims resolve to the version manager's keg, not the provider's.
557 (homebrew?.kind === "formula" && homebrew.name.toLowerCase() === "mise") ||
558 (yield* isMiseWrapperScript(context))
559 ) {
560 return manual;
561 }
562 if (homebrew) {
563 return (
564 (yield* resolveHomebrewProviderMaintenance(
565 { provider: definition.provider, packageName },
566 homebrew,
567 context,
568 )) ?? fallback
569 );
570 }
571
572 return fallback;
573});
574
575/**
576 * `brew upgrade` capabilities once the keg's prefix is confirmed by a `brew`
577 * that reports it as its own. Version checks defer `brew info` until needed.
578 * Null when no `brew` is found or it owns another prefix.
579 */
580export const resolveHomebrewProviderMaintenance = Effect.fn("resolveHomebrewProviderMaintenance")(
581 function* (
582 input: { readonly provider: ProviderDriverKind; readonly packageName: string | null },
583 homebrew: HomebrewOwnership,
584 context: ProviderMaintenanceResolutionContext,
585 ) {
586 const fileSystem = yield* FileSystem.FileSystem;
587 const path = yield* Path.Path;
588 // GUI servers may lack Homebrew on PATH; use the keg brew with the same prefix check.
589 const kegBrewPath = path.join(homebrew.prefix, "bin", "brew");
590 const brewPath = (yield* fileSystem.exists(kegBrewPath).pipe(Effect.orElseSucceed(() => false)))
591 ? kegBrewPath
592 : yield* resolveCommandPath("brew", { env: context.env });
593 if (!brewPath) {
594 return null;
595 }
596 const brewPrefix = nonEmptyString(yield* runProbe(brewPath, ["--prefix"], context.env));
597 const realBrewPrefix = brewPrefix
598 ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))
599 : null;
600 if (
601 !realBrewPrefix ||
602 normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)
603 ) {
604 return null;
605 }
606 const args =
607 homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];
608 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
609 return makeProviderMaintenanceCapabilities({
610 provider: input.provider,
611 packageName: input.packageName,
612 updateExecutable: brewPath,
613 updateArgs: args,
614 updateLockKey: "homebrew",
615 updateCommand: ["brew", ...args].join(" "),
616 // Brew's release can lag npm; only its own channel can say what upgrade installs.
617 latestVersion: null,
618 lookupLatestVersion: runProbe(
619 brewPath,
620 ["info", "--json=v2", homebrew.name],
621 context.env,
622 ).pipe(
623 Effect.map((info) => (info ? parseHomebrewLatestVersion(info, homebrew) : null)),
624 Effect.provideContext(services),
625 ),
626 });
627 },
628);
629
630const isMiseWrapperScript = Effect.fn("isMiseWrapperScript")(function* (
631 context: ProviderMaintenanceResolutionContext,
632) {
633 const fileSystem = yield* FileSystem.FileSystem;
634 const size = yield* fileSystem.stat(context.realCommandPath).pipe(
635 Effect.map((info) => Number(info.size)),
636 Effect.orElseSucceed(() => Infinity),
637 );
638 if (size > MISE_WRAPPER_MAX_BYTES) {
639 return false;
640 }
641 const script = yield* fileSystem
642 .readFileString(context.realCommandPath)
643 .pipe(Effect.orElseSucceed(() => ""));
644 return script.startsWith("#!") && /\bmise\s+(?:x|exec)\b/.test(script);
645});
646
647// Volta bin links only identify its shim; the package image proves ownership.
648const isVoltaPackageInstall = Effect.fn("isVoltaPackageInstall")(function* (
649 context: ProviderMaintenanceResolutionContext,
650 packageName: string,
651) {
652 const path = yield* Path.Path;
653 if (
654 path.basename(normalizeCommandPath(context.realCommandPath)).replace(/\.exe$/, "") !==
655 "volta-shim"
656 ) {
657 return false;
658 }
659 const voltaHome = path.dirname(path.dirname(context.resolvedCommandPath));
660 const packageDir = path.join(voltaHome, "tools", "image", "packages", ...packageName.split("/"));
661 const fileSystem = yield* FileSystem.FileSystem;
662 return yield* fileSystem.exists(packageDir).pipe(Effect.orElseSucceed(() => false));
663});
664
665const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (
666 context: ProviderMaintenanceResolutionContext,
667 packageName: string,
668) {
669 const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);
670 if (fromRealPath) {
671 return fromRealPath;
672 }
673 if ((yield* HostProcess.Platform) !== "win32") {
674 return null;
675 }
676 const fileSystem = yield* FileSystem.FileSystem;
677 const path = yield* Path.Path;
678 const shimDir = path.dirname(context.resolvedCommandPath);
679 const manifestPath = path.join(
680 shimDir,
681 "node_modules",
682 ...packageName.split("/"),
683 "package.json",
684 );
685 // Windows npm shims sit beside node_modules; POSIX project checkouts can mimic this layout.
686 const hasManifest = yield* fileSystem
687 .exists(manifestPath)
688 .pipe(Effect.orElseSucceed(() => false));
689 return hasManifest ? shimDir : null;
690});
691
692export function makePackageManagedProviderMaintenanceResolver(
693 definition: PackageManagedProviderMaintenanceDefinition,
694): ProviderMaintenanceCapabilitiesResolver {
695 return {
696 resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),
697 };
698}
699
700function makeManualProviderMaintenanceCapabilities(
701 provider: ProviderDriverKind,
702): ProviderMaintenanceCapabilities {
703 return makeManualOnlyProviderMaintenanceCapabilities({
704 provider,
705 packageName: null,
706 });
707}
708
709export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
710 "resolveProviderMaintenanceCapabilitiesEffect",
711)(function* (
712 resolver: ProviderMaintenanceCapabilitiesResolver,
713 options?: {
714 readonly binaryPath?: string | null;
715 readonly env?: NodeJS.ProcessEnv;
716 },
717) {
718 const binaryPath = nonEmptyString(options?.binaryPath);
719 if (!binaryPath) {
720 return yield* resolver.resolve(null);
721 }
722
723 const env = options?.env ?? (yield* readCommandLookupEnv);
724 const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env });
725 if (!resolvedCommandPath) {
726 return yield* resolver.resolve(null);
727 }
728
729 const fileSystem = yield* FileSystem.FileSystem;
730 const realCommandPath = yield* fileSystem
731 .realPath(resolvedCommandPath)
732 .pipe(Effect.orElseSucceed(() => null));
733 if (!realCommandPath) {
734 return yield* resolver.resolve(null);
735 }
736 return yield* resolver.resolve({
737 binaryPath,
738 resolvedCommandPath,
739 realCommandPath,
740 env,
741 platform: yield* HostProcess.Platform,
742 });
743});
744
745export const makeCachedProviderMaintenanceResolution = Effect.fn(
746 "makeCachedProviderMaintenanceResolution",
747)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {
748 const cache = yield* Cache.make({
749 capacity: 1,
750 timeToLive: MAINTENANCE_CAPABILITIES_CACHE_TTL,
751 lookup: () => resolve,
752 });
753 const cached = Cache.get(cache, undefined);
754 return (options?: { readonly fresh?: boolean }) =>
755 options?.fresh ? Cache.invalidate(cache, undefined).pipe(Effect.andThen(cached)) : cached;
756});
757
758function manualUpdateMessage(latestVersion: string, installPath: string | undefined): string {
759 return installPath
760 ? `Version ${latestVersion} is out. T3 Code runs ${installPath}; update it with the app or tool that installed it.`
761 : `Version ${latestVersion} is out. Update it with the app or tool that installed it.`;
762}
763
764function deriveVersionAdvisory(input: {
765 readonly currentVersion: string | null;
766 readonly latestVersion: string | null;
767 readonly capabilities: ProviderMaintenanceCapabilities;
768}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
769 if (!input.currentVersion) {
770 return { status: "unknown", message: null };
771 }
772 if (!input.latestVersion) {
773 return { status: "unknown", message: null };
774 }
775 if (
776 (input.capabilities.compareVersions ?? compareSemverVersions)(
777 input.currentVersion,
778 input.latestVersion,
779 ) < 0
780 ) {
781 return {
782 status: "behind_latest",
783 message:
784 input.capabilities.update === null
785 ? manualUpdateMessage(input.latestVersion, input.capabilities.installPath)
786 : PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
787 };
788 }
789 return { status: "current", message: null };
790}
791
792export function createProviderVersionAdvisory(input: {
793 readonly driver: ProviderDriverKind;
794 readonly currentVersion: string | null;
795 readonly latestVersion?: string | null;
796 readonly checkedAt?: string | null;
797 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
798}): ServerProviderVersionAdvisory {
799 const capabilities =
800 input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
801 const latestVersion = input.latestVersion ?? null;
802 const advisory = deriveVersionAdvisory({
803 currentVersion: input.currentVersion,
804 latestVersion,
805 capabilities,
806 });
807
808 return {
809 status: advisory.status,
810 currentVersion: input.currentVersion,
811 latestVersion,
812 updateCommand: resolveLatestProviderUpdateAction(capabilities, latestVersion)?.command ?? null,
813 canUpdate: capabilities.update !== null,
814 canInstallVersion: makeTargetedProviderUpdateAction(capabilities, "0.0.0") !== null,
815 checkedAt: input.checkedAt ?? null,
816 message: advisory.message,
817 };
818}
819
820const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
821 const client = yield* HttpClient.HttpClient;
822 const request = HttpClientRequest.get(
823 `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
824 ).pipe(HttpClientRequest.setHeader("accept", "application/json"));
825 const response = yield* client.execute(request).pipe(
826 Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
827 Effect.orElseSucceed(() => Option.none()),
828 );
829 if (Option.isNone(response)) {
830 return null;
831 }
832 const httpResponse = response.value;
833 if (httpResponse.status < 200 || httpResponse.status >= 300) {
834 return null;
835 }
836 const payload = yield* httpResponse.json.pipe(
837 Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
838 Effect.orElseSucceed(() => null),
839 );
840 return payload ? nonEmptyString(payload.version) : null;
841});
842
843/** The installer's own answer is cached apart from the npm registry entry. */
844function installerLatestVersionKey(capabilities: ProviderMaintenanceCapabilities) {
845 const update = capabilities.update;
846 return capabilities.lookupLatestVersion && update
847 ? [update.lockKey, update.executable, ...update.args].join("\0")
848 : null;
849}
850
851export function latestProviderVersionCacheKeys(
852 capabilities: ProviderMaintenanceCapabilities,
853): ReadonlyArray<string> {
854 return [capabilities.packageName, installerLatestVersionKey(capabilities)].filter(
855 (key) => key !== null,
856 );
857}
858
859export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
860 maintenanceCapabilities: ProviderMaintenanceCapabilities,
861) {
862 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
863 const installerKey = installerLatestVersionKey(maintenanceCapabilities);
864 if (installerKey && maintenanceCapabilities.lookupLatestVersion) {
865 const installable = yield* latestVersions.cached(
866 installerKey,
867 maintenanceCapabilities.lookupLatestVersion,
868 );
869 if (installable !== null) return installable;
870 }
871 if (maintenanceCapabilities.latestVersion !== undefined) {
872 return maintenanceCapabilities.latestVersion;
873 }
874 const packageName = maintenanceCapabilities.packageName;
875 if (!packageName) {
876 return null;
877 }
878
879 return yield* latestVersions.cached(packageName, fetchNpmLatestVersion(packageName));
880});
881
882export const invalidateLatestProviderVersion = Effect.fn("invalidateLatestProviderVersion")(
883 function* (maintenanceCapabilities: ProviderMaintenanceCapabilities) {
884 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
885 yield* Effect.forEach(
886 latestProviderVersionCacheKeys(maintenanceCapabilities),
887 latestVersions.invalidate,
888 { discard: true },
889 );
890 },
891);
892
893export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
894 "enrichProviderSnapshotWithVersionAdvisory",
895)(function* (
896 snapshot: ServerProvider,
897 maintenanceCapabilities?: ProviderMaintenanceCapabilities,
898 options?: {
899 readonly enableProviderUpdateChecks: boolean | undefined;
900 },
901) {
902 const capabilities =
903 maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
904 const currentVersion =
905 snapshot.installedVersion !== undefined ? snapshot.installedVersion : snapshot.version;
906 const shouldResolveLatestVersion =
907 options?.enableProviderUpdateChecks !== false &&
908 snapshot.enabled &&
909 snapshot.installed &&
910 Boolean(currentVersion);
911 if (!shouldResolveLatestVersion) {
912 return {
913 ...snapshot,
914 versionAdvisory: createProviderVersionAdvisory({
915 driver: snapshot.driver,
916 currentVersion,
917 checkedAt: snapshot.checkedAt,
918 maintenanceCapabilities: capabilities,
919 }),
920 };
921 }
922
923 const latestVersion = yield* resolveLatestProviderVersion(capabilities);
924 return {
925 ...snapshot,
926 versionAdvisory: createProviderVersionAdvisory({
927 driver: snapshot.driver,
928 currentVersion,
929 latestVersion,
930 checkedAt: DateTime.formatIso(yield* DateTime.now),
931 maintenanceCapabilities: capabilities,
932 }),
933 };
934});