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
241/**
242 * WinGet's Claude Code install under its user root (`<drive>:\Users\<name>\AppData\Local\Microsoft\WinGet`)
243 * or machine root (`<drive>:\Program Files\WinGet`): the `Links\claude.exe` link or the binary in the
244 * `Packages\Anthropic.ClaudeCode_…` directory.
245 */
246const winGetClaudeCommandPath =
247 /^[a-z]:\/(?:users\/[^/]+\/appdata\/local\/microsoft|program files(?: \(x86\))?)\/winget\/(?:links|packages\/anthropic\.claudecode_[^/]+)\/claude\.exe$/;
248
249function isWinGetClaudeCommandPath(commandPath: string): boolean {
250 return winGetClaudeCommandPath.test(normalizeCommandPath(commandPath));
251}
252
253function isPnpmGlobalCommandPath(commandPath: string): boolean {
254 const normalized = normalizeCommandPath(commandPath);
255 return (
256 normalized.includes("/.local/share/pnpm/") ||
257 normalized.includes("/library/pnpm/") ||
258 normalized.includes("/local/share/pnpm/") ||
259 normalized.includes("/appdata/local/pnpm/") ||
260 normalized.includes("/pnpm/global/")
261 );
262}
263
264export function npmGlobalPrefixFromCommandPath(
265 realCommandPath: string,
266 packageName: string,
267): string | null {
268 const slashPath = realCommandPath.replaceAll("\\", "/");
269 const normalized = slashPath.toLowerCase();
270 const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`;
271 const packageIndex = normalized.lastIndexOf(packageSegment);
272 if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) {
273 return null;
274 }
275 // Mise's npm backend uses a global-looking layout inside a tool version.
276 // Globals under its Node installation still belong to npm.
277 const miseTool = /\/mise\/installs\/([^/]+)\/[^/]+$/.exec(normalized.slice(0, packageIndex))?.[1];
278 if (miseTool && miseTool !== "node") {
279 return null;
280 }
281 return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex);
282}
283
284const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i;
285
286export interface HomebrewOwnership {
287 readonly kind: "formula" | "cask";
288 readonly name: string;
289 readonly prefix: string;
290}
291
292export function homebrewOwnershipFromCommandPath(
293 realCommandPath: string,
294): HomebrewOwnership | null {
295 const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));
296 if (!match) {
297 return null;
298 }
299 return {
300 kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask",
301 name: match[3]!,
302 prefix: match[1]!,
303 };
304}
305
306const HomebrewInfoResponse = Schema.Struct({
307 formulae: Schema.optional(
308 Schema.Array(
309 Schema.Struct({
310 versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })),
311 }),
312 ),
313 ),
314 casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))),
315});
316
317const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse));
318
319/** Cask versions may carry a build suffix after a comma (`1.2.3,456`). */
320export function parseHomebrewLatestVersion(
321 infoJson: string,
322 ownership: HomebrewOwnership,
323): string | null {
324 const decoded = decodeHomebrewInfo(infoJson);
325 if (Option.isNone(decoded)) {
326 return null;
327 }
328 const raw =
329 ownership.kind === "formula"
330 ? decoded.value.formulae?.[0]?.versions?.stable
331 : decoded.value.casks?.[0]?.version?.split(",", 1)[0];
332 const version = nonEmptyString(raw);
333 return version === "latest" ? null : version;
334}
335
336const runProbe = Effect.fn("runProbe")(function* (
337 command: string,
338 args: ReadonlyArray<string>,
339 env: NodeJS.ProcessEnv,
340 okExitCodes: ReadonlyArray<number> = [0],
341) {
342 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
343 const collect = Effect.gen(function* () {
344 // Windows package managers are `.cmd` shims that need the shell.
345 const resolved = yield* resolveSpawnCommand(command, args, { env, extendEnv: true });
346 const child = yield* spawner.spawn(
347 ChildProcess.make(resolved.command, resolved.args, {
348 env,
349 extendEnv: true,
350 shell: resolved.shell,
351 }),
352 );
353 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
354 // stderr is drained so a chatty tool cannot block on a full pipe.
355 const [stdout, exitCode] = yield* Effect.all(
356 [
357 collectUint8StreamText({ stream: child.stdout, maxBytes: PROBE_MAX_BYTES }),
358 child.exitCode,
359 Stream.runDrain(child.stderr),
360 ],
361 { concurrency: "unbounded" },
362 );
363 return !okExitCodes.includes(Number(exitCode)) || stdout.truncated ? null : stdout.text;
364 });
365 return yield* collect.pipe(
366 Effect.scoped,
367 Effect.timeoutOption(Duration.millis(PROBE_TIMEOUT_MS)),
368 Effect.map(Option.getOrNull),
369 Effect.catchCause((cause) =>
370 Effect.logWarning("Maintenance probe failed", {
371 command,
372 subcommand: args[0],
373 errorTag: causeErrorTag(cause),
374 }).pipe(Effect.as(null)),
375 ),
376 );
377});
378
379const decodePnpmOutdated = Schema.decodeUnknownOption(
380 Schema.fromJsonString(
381 Schema.Record(Schema.String, Schema.Struct({ latest: Schema.optional(Schema.String) })),
382 ),
383);
384const decodePnpmList = Schema.decodeUnknownOption(
385 Schema.fromJsonString(
386 Schema.Array(
387 Schema.Struct({
388 dependencies: Schema.optional(
389 Schema.Record(Schema.String, Schema.Struct({ version: Schema.optional(Schema.String) })),
390 ),
391 }),
392 ),
393 ),
394);
395
396// Unlike npm's latest tag, pnpm outdated respects minimumReleaseAge and its excludes.
397const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion")(function* (
398 packageName: string,
399) {
400 // Match the updater's pnpm and server environment, rather than the instance's.
401 const pnpmPath = yield* resolveCommandPath("pnpm");
402 if (!pnpmPath) return null;
403 // Silent reporting keeps project package-manager warnings out of the JSON.
404 const outdated = yield* runProbe(
405 pnpmPath,
406 ["outdated", "-g", "--reporter=silent", "--format", "json", packageName],
407 {},
408 // pnpm outdated exits 1 when updates are available.
409 [0, 1],
410 );
411 const outdatedEntries = outdated
412 ? Option.getOrUndefined(decodePnpmOutdated(outdated))
413 : undefined;
414 if (!outdatedEntries) return null;
415 const latest = nonEmptyString(outdatedEntries[packageName]?.latest);
416 if (latest) return latest;
417 // An empty result means the installed version is still the eligible release.
418 const listed = yield* runProbe(
419 pnpmPath,
420 ["ls", "-g", "--reporter=silent", "--depth", "0", "--json", packageName],
421 {},
422 );
423 const listedEntries = listed ? Option.getOrUndefined(decodePnpmList(listed)) : undefined;
424 return nonEmptyString(listedEntries?.[0]?.dependencies?.[packageName]?.version);
425});
426
427export const resolvePackageManagedProviderMaintenance = Effect.fn(
428 "resolvePackageManagedProviderMaintenance",
429)(function* (
430 definition: PackageManagedProviderMaintenanceDefinition,
431 context: ProviderMaintenanceResolutionContext | null,
432) {
433 if (!context) {
434 return makeManualOnlyProviderMaintenanceCapabilities({
435 provider: definition.provider,
436 packageName: definition.npmPackageName,
437 });
438 }
439 const manual = makeManualOnlyProviderMaintenanceCapabilities({
440 provider: definition.provider,
441 packageName: definition.npmPackageName,
442 installPath: context.realCommandPath,
443 });
444 const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
445 const packageName = definition.npmPackageName;
446 // WinGet owns these files: `claude update` only reports "managed by winget"
447 // and exits 0, and T3 Code does not run `winget upgrade` itself.
448 if (
449 definition.provider === "claudeAgent" &&
450 context.platform === "win32" &&
451 commandPaths.some(isWinGetClaudeCommandPath)
452 ) {
453 return manual;
454 }
455
456 const nativeUpdate = definition.nativeUpdate;
457 const native = nativeUpdate
458 ? makeProviderMaintenanceCapabilities({
459 provider: definition.provider,
460 packageName,
461 updateExecutable: context.resolvedCommandPath,
462 updateArgs: nativeUpdate.args,
463 updateLockKey: `${definition.provider}-native`,
464 platform: context.platform,
465 ...(nativeUpdate.env ? { env: nativeUpdate.env } : {}),
466 })
467 : manual;
468 // A native-looking launcher can still delegate to a mise-owned install.
469 if (
470 nativeUpdate?.isCommandPath &&
471 commandPaths.some(nativeUpdate.isCommandPath) &&
472 !commandPaths.some(isMiseCommandPath) &&
473 !(yield* isMiseWrapperScript(context))
474 ) {
475 return native;
476 }
477 // A `node_modules` path not proven below belongs to another package or a
478 // project, so the provider's own updater could act on the wrong install.
479 const fallback =
480 nativeUpdate?.requiresCommandPath ||
481 commandPaths.some((commandPath) => normalizeCommandPath(commandPath).includes("/node_modules/"))
482 ? manual
483 : native;
484 if (commandPaths.some(isVitePlusGlobalCommandPath)) {
485 return makeProviderMaintenanceCapabilities({
486 provider: definition.provider,
487 packageName,
488 updateExecutable: "vp",
489 updateArgs: ["i", "-g", packageName],
490 updateLockKey: "vite-plus-global",
491 });
492 }
493 if (commandPaths.some(isBunGlobalCommandPath)) {
494 return makeProviderMaintenanceCapabilities({
495 provider: definition.provider,
496 packageName,
497 updateExecutable: "bun",
498 updateArgs: ["i", "-g", `${packageName}@latest`],
499 updateLockKey: "bun-global",
500 });
501 }
502 if (commandPaths.some(isPnpmGlobalCommandPath)) {
503 // pnpm 10 skips unapproved install scripts and still exits 0, leaving a
504 // package whose postinstall finishes the install broken. Global installs
505 // can only approve on the command line, and pnpm before 10.4 rejects the
506 // flag as an unknown option.
507 const pnpmVersion = yield* runProbe("pnpm", ["--version"], context.env);
508 const allowBuild =
509 pnpmVersion !== null && satisfiesSemverRange(pnpmVersion, ">=10.4.0")
510 ? [`--allow-build=${packageName}`]
511 : [];
512 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
513 return makeProviderMaintenanceCapabilities({
514 provider: definition.provider,
515 packageName,
516 updateExecutable: "pnpm",
517 updateArgs: ["add", "-g", ...allowBuild, `${packageName}@latest`],
518 updateLockKey: "pnpm-global",
519 lookupLatestVersion: resolvePnpmGlobalLatestVersion(packageName).pipe(
520 Effect.provideContext(services),
521 ),
522 });
523 }
524
525 if (commandPaths.some(isYarnGlobalCommandPath)) {
526 return makeProviderMaintenanceCapabilities({
527 provider: definition.provider,
528 packageName,
529 updateExecutable: "yarn",
530 updateArgs: ["global", "add", `${packageName}@latest`],
531 updateLockKey: "yarn-global",
532 });
533 }
534 if (yield* isVoltaPackageInstall(context, packageName)) {
535 return makeProviderMaintenanceCapabilities({
536 provider: definition.provider,
537 packageName,
538 updateExecutable: "volta",
539 updateArgs: ["install", `${packageName}@latest`],
540 updateLockKey: "volta",
541 });
542 }
543
544 // npm proof names the package, so it outranks a keg the path merely passes
545 // through: a Homebrew-installed Node keeps its globals under
546 // `Cellar/node/<ver>/lib/node_modules/`, and that is npm's install, not brew's.
547 const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);
548 if (npmPrefix) {
549 // npm 12 blocks install scripts by default (empty allow-scripts allowlist)
550 // and still exits 0, so a package whose postinstall finishes the install
551 // (claude copies its native binary over a placeholder stub) is left broken
552 // while the update reports success. Older npm warns about the unknown
553 // config and continues.
554 return makeProviderMaintenanceCapabilities({
555 provider: definition.provider,
556 packageName,
557 updateExecutable: "npm",
558 updateArgs: [
559 "install",
560 "-g",
561 "--prefix",
562 npmPrefix,
563 `--allow-scripts=${packageName}`,
564 `${packageName}@latest`,
565 ],
566 updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,
567 });
568 }
569
570 const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
571 if (
572 commandPaths.some(isMiseCommandPath) ||
573 // Mise shims resolve to the version manager's keg, not the provider's.
574 (homebrew?.kind === "formula" && homebrew.name.toLowerCase() === "mise") ||
575 (yield* isMiseWrapperScript(context))
576 ) {
577 return manual;
578 }
579 if (homebrew) {
580 return (
581 (yield* resolveHomebrewProviderMaintenance(
582 { provider: definition.provider, packageName },
583 homebrew,
584 context,
585 )) ?? fallback
586 );
587 }
588
589 return fallback;
590});
591
592/**
593 * `brew upgrade` capabilities once the keg's prefix is confirmed by a `brew`
594 * that reports it as its own. Version checks defer `brew info` until needed.
595 * Null when no `brew` is found or it owns another prefix.
596 */
597export const resolveHomebrewProviderMaintenance = Effect.fn("resolveHomebrewProviderMaintenance")(
598 function* (
599 input: { readonly provider: ProviderDriverKind; readonly packageName: string | null },
600 homebrew: HomebrewOwnership,
601 context: ProviderMaintenanceResolutionContext,
602 ) {
603 const fileSystem = yield* FileSystem.FileSystem;
604 const path = yield* Path.Path;
605 // The keg's own brew works even when a GUI-launched server has no
606 // Homebrew on PATH; the prefix check below still applies to it.
607 const kegBrewPath = path.join(homebrew.prefix, "bin", "brew");
608 const brewPath = (yield* fileSystem.exists(kegBrewPath).pipe(Effect.orElseSucceed(() => false)))
609 ? kegBrewPath
610 : yield* resolveCommandPath("brew", { env: context.env });
611 if (!brewPath) {
612 return null;
613 }
614 const brewPrefix = nonEmptyString(yield* runProbe(brewPath, ["--prefix"], context.env));
615 const realBrewPrefix = brewPrefix
616 ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))
617 : null;
618 if (
619 !realBrewPrefix ||
620 normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)
621 ) {
622 return null;
623 }
624 const args =
625 homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];
626 const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
627 return makeProviderMaintenanceCapabilities({
628 provider: input.provider,
629 packageName: input.packageName,
630 updateExecutable: brewPath,
631 updateArgs: args,
632 updateLockKey: "homebrew",
633 updateCommand: ["brew", ...args].join(" "),
634 // Brew's release can lag npm; only its own channel can say what upgrade installs.
635 latestVersion: null,
636 lookupLatestVersion: runProbe(
637 brewPath,
638 ["info", "--json=v2", homebrew.name],
639 context.env,
640 ).pipe(
641 Effect.map((info) => (info ? parseHomebrewLatestVersion(info, homebrew) : null)),
642 Effect.provideContext(services),
643 ),
644 });
645 },
646);
647
648const isMiseWrapperScript = Effect.fn("isMiseWrapperScript")(function* (
649 context: ProviderMaintenanceResolutionContext,
650) {
651 const fileSystem = yield* FileSystem.FileSystem;
652 const size = yield* fileSystem.stat(context.realCommandPath).pipe(
653 Effect.map((info) => Number(info.size)),
654 Effect.orElseSucceed(() => Infinity),
655 );
656 if (size > MISE_WRAPPER_MAX_BYTES) {
657 return false;
658 }
659 const script = yield* fileSystem
660 .readFileString(context.realCommandPath)
661 .pipe(Effect.orElseSucceed(() => ""));
662 return script.startsWith("#!") && /\bmise\s+(?:x|exec)\b/.test(script);
663});
664
665/**
666 * Volta's `bin/<cmd>` is a link to its `volta-shim`, which picks the package
667 * at run time; the package's own image directory proves Volta installed it.
668 */
669const isVoltaPackageInstall = Effect.fn("isVoltaPackageInstall")(function* (
670 context: ProviderMaintenanceResolutionContext,
671 packageName: string,
672) {
673 const path = yield* Path.Path;
674 if (
675 path.basename(normalizeCommandPath(context.realCommandPath)).replace(/\.exe$/, "") !==
676 "volta-shim"
677 ) {
678 return false;
679 }
680 const voltaHome = path.dirname(path.dirname(context.resolvedCommandPath));
681 const packageDir = path.join(voltaHome, "tools", "image", "packages", ...packageName.split("/"));
682 const fileSystem = yield* FileSystem.FileSystem;
683 return yield* fileSystem.exists(packageDir).pipe(Effect.orElseSucceed(() => false));
684});
685
686const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (
687 context: ProviderMaintenanceResolutionContext,
688 packageName: string,
689) {
690 const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);
691 if (fromRealPath) {
692 return fromRealPath;
693 }
694 if ((yield* HostProcess.Platform) !== "win32") {
695 return null;
696 }
697 const fileSystem = yield* FileSystem.FileSystem;
698 const path = yield* Path.Path;
699 const shimDir = path.dirname(context.resolvedCommandPath);
700 const manifestPath = path.join(
701 shimDir,
702 "node_modules",
703 ...packageName.split("/"),
704 "package.json",
705 );
706 // npm writes both `<cmd>.cmd` and an extensionless sh script into the
707 // Windows prefix; either one sits directly beside `node_modules`. A POSIX
708 // project checkout has the same shape, which is why this is Windows-only.
709 const hasManifest = yield* fileSystem
710 .exists(manifestPath)
711 .pipe(Effect.orElseSucceed(() => false));
712 return hasManifest ? shimDir : null;
713});
714
715export function makePackageManagedProviderMaintenanceResolver(
716 definition: PackageManagedProviderMaintenanceDefinition,
717): ProviderMaintenanceCapabilitiesResolver {
718 return {
719 resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),
720 };
721}
722
723function makeManualProviderMaintenanceCapabilities(
724 provider: ProviderDriverKind,
725): ProviderMaintenanceCapabilities {
726 return makeManualOnlyProviderMaintenanceCapabilities({
727 provider,
728 packageName: null,
729 });
730}
731
732export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
733 "resolveProviderMaintenanceCapabilitiesEffect",
734)(function* (
735 resolver: ProviderMaintenanceCapabilitiesResolver,
736 options?: {
737 readonly binaryPath?: string | null;
738 readonly env?: NodeJS.ProcessEnv;
739 },
740) {
741 const binaryPath = nonEmptyString(options?.binaryPath);
742 if (!binaryPath) {
743 return yield* resolver.resolve(null);
744 }
745
746 const env = options?.env ?? (yield* readCommandLookupEnv);
747 const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env });
748 if (!resolvedCommandPath) {
749 return yield* resolver.resolve(null);
750 }
751
752 const fileSystem = yield* FileSystem.FileSystem;
753 const realCommandPath = yield* fileSystem
754 .realPath(resolvedCommandPath)
755 .pipe(Effect.orElseSucceed(() => null));
756 if (!realCommandPath) {
757 return yield* resolver.resolve(null);
758 }
759 return yield* resolver.resolve({
760 binaryPath,
761 resolvedCommandPath,
762 realCommandPath,
763 env,
764 platform: yield* HostProcess.Platform,
765 });
766});
767
768/**
769 * Turn a one-shot resolution into the shape drivers expose: a cached read for
770 * advisories and a `fresh` read that update execution uses so it never trusts
771 * ownership derived before the user clicked.
772 */
773export const makeCachedProviderMaintenanceResolution = Effect.fn(
774 "makeCachedProviderMaintenanceResolution",
775)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {
776 const cache = yield* Cache.make({
777 capacity: 1,
778 timeToLive: MAINTENANCE_CAPABILITIES_CACHE_TTL,
779 lookup: () => resolve,
780 });
781 const cached = Cache.get(cache, undefined);
782 return (options?: { readonly fresh?: boolean }) =>
783 options?.fresh ? Cache.invalidate(cache, undefined).pipe(Effect.andThen(cached)) : cached;
784});
785
786/**
787 * An install T3 Code cannot update gets no Update button or command, so its
788 * message names the version and the executable instead.
789 */
790function manualUpdateMessage(latestVersion: string, installPath: string | undefined): string {
791 return installPath
792 ? `Version ${latestVersion} is out. T3 Code runs ${installPath}; update it with the app or tool that installed it.`
793 : `Version ${latestVersion} is out. Update it with the app or tool that installed it.`;
794}
795
796function deriveVersionAdvisory(input: {
797 readonly currentVersion: string | null;
798 readonly latestVersion: string | null;
799 readonly capabilities: ProviderMaintenanceCapabilities;
800}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
801 if (!input.currentVersion) {
802 return { status: "unknown", message: null };
803 }
804 if (!input.latestVersion) {
805 return { status: "unknown", message: null };
806 }
807 if (
808 (input.capabilities.compareVersions ?? compareSemverVersions)(
809 input.currentVersion,
810 input.latestVersion,
811 ) < 0
812 ) {
813 return {
814 status: "behind_latest",
815 message:
816 input.capabilities.update === null
817 ? manualUpdateMessage(input.latestVersion, input.capabilities.installPath)
818 : PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
819 };
820 }
821 return { status: "current", message: null };
822}
823
824export function createProviderVersionAdvisory(input: {
825 readonly driver: ProviderDriverKind;
826 readonly currentVersion: string | null;
827 readonly latestVersion?: string | null;
828 readonly checkedAt?: string | null;
829 readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
830}): ServerProviderVersionAdvisory {
831 const capabilities =
832 input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
833 const latestVersion = input.latestVersion ?? null;
834 const advisory = deriveVersionAdvisory({
835 currentVersion: input.currentVersion,
836 latestVersion,
837 capabilities,
838 });
839
840 return {
841 status: advisory.status,
842 currentVersion: input.currentVersion,
843 latestVersion,
844 updateCommand: resolveLatestProviderUpdateAction(capabilities, latestVersion)?.command ?? null,
845 canUpdate: capabilities.update !== null,
846 canInstallVersion: makeTargetedProviderUpdateAction(capabilities, "0.0.0") !== null,
847 checkedAt: input.checkedAt ?? null,
848 message: advisory.message,
849 };
850}
851
852const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
853 const client = yield* HttpClient.HttpClient;
854 const request = HttpClientRequest.get(
855 `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
856 ).pipe(HttpClientRequest.setHeader("accept", "application/json"));
857 const response = yield* client.execute(request).pipe(
858 Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
859 Effect.orElseSucceed(() => Option.none()),
860 );
861 if (Option.isNone(response)) {
862 return null;
863 }
864 const httpResponse = response.value;
865 if (httpResponse.status < 200 || httpResponse.status >= 300) {
866 return null;
867 }
868 const payload = yield* httpResponse.json.pipe(
869 Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
870 Effect.orElseSucceed(() => null),
871 );
872 return payload ? nonEmptyString(payload.version) : null;
873});
874
875/** The installer's own answer is cached apart from the npm registry entry. */
876function installerLatestVersionKey(capabilities: ProviderMaintenanceCapabilities) {
877 const update = capabilities.update;
878 return capabilities.lookupLatestVersion && update
879 ? [update.lockKey, update.executable, ...update.args].join("\0")
880 : null;
881}
882
883export function latestProviderVersionCacheKeys(
884 capabilities: ProviderMaintenanceCapabilities,
885): ReadonlyArray<string> {
886 return [capabilities.packageName, installerLatestVersionKey(capabilities)].filter(
887 (key) => key !== null,
888 );
889}
890
891export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
892 maintenanceCapabilities: ProviderMaintenanceCapabilities,
893) {
894 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
895 const installerKey = installerLatestVersionKey(maintenanceCapabilities);
896 if (installerKey && maintenanceCapabilities.lookupLatestVersion) {
897 const installable = yield* latestVersions.cached(
898 installerKey,
899 maintenanceCapabilities.lookupLatestVersion,
900 );
901 if (installable !== null) return installable;
902 }
903 if (maintenanceCapabilities.latestVersion !== undefined) {
904 return maintenanceCapabilities.latestVersion;
905 }
906 const packageName = maintenanceCapabilities.packageName;
907 if (!packageName) {
908 return null;
909 }
910
911 return yield* latestVersions.cached(packageName, fetchNpmLatestVersion(packageName));
912});
913
914export const invalidateLatestProviderVersion = Effect.fn("invalidateLatestProviderVersion")(
915 function* (maintenanceCapabilities: ProviderMaintenanceCapabilities) {
916 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
917 yield* Effect.forEach(
918 latestProviderVersionCacheKeys(maintenanceCapabilities),
919 latestVersions.invalidate,
920 { discard: true },
921 );
922 },
923);
924
925export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
926 "enrichProviderSnapshotWithVersionAdvisory",
927)(function* (
928 snapshot: ServerProvider,
929 maintenanceCapabilities?: ProviderMaintenanceCapabilities,
930 options?: {
931 readonly enableProviderUpdateChecks: boolean | undefined;
932 },
933) {
934 const capabilities =
935 maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
936 const currentVersion =
937 snapshot.installedVersion !== undefined ? snapshot.installedVersion : snapshot.version;
938 const shouldResolveLatestVersion =
939 options?.enableProviderUpdateChecks !== false &&
940 snapshot.enabled &&
941 snapshot.installed &&
942 Boolean(currentVersion);
943 if (!shouldResolveLatestVersion) {
944 return {
945 ...snapshot,
946 versionAdvisory: createProviderVersionAdvisory({
947 driver: snapshot.driver,
948 currentVersion,
949 checkedAt: snapshot.checkedAt,
950 maintenanceCapabilities: capabilities,
951 }),
952 };
953 }
954
955 const latestVersion = yield* resolveLatestProviderVersion(capabilities);
956 return {
957 ...snapshot,
958 versionAdvisory: createProviderVersionAdvisory({
959 driver: snapshot.driver,
960 currentVersion,
961 latestVersion,
962 checkedAt: DateTime.formatIso(yield* DateTime.now),
963 maintenanceCapabilities: capabilities,
964 }),
965 };
966});