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