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