From 338e48ccb9efc40fa5f675f3e7cf52df531fb403 Mon Sep 17 00:00:00 2001 From: Karl Von Richter Date: Sun, 1 Nov 2026 09:21:16 +1000 Subject: [PATCH] fix(providers): allow a separate CLI path for updates Codex and Claude launchers can configure routing or accounts without owning the underlying CLI installation. Resolving maintenance from the launcher can disable updates or invoke the wrong executable. Resolve update ownership and advisories from an optional maintenance path. Keep session launch, snapshot versions and post-update verification on the session executable. Use the maintenance version for the pre-update check. Bind Bun updates to the proven global and binary directories and carry those paths into copied commands. Include the owning home in standalone Codex commands. Leave unproven installations manual-only. Model: GPT-6.1-sol. Harness: Codex in T3 Code. --- .../src/provider/Drivers/ClaudeDriver.ts | 4 + .../src/provider/Drivers/CodexDriver.test.ts | 2 +- .../src/provider/Drivers/CodexDriver.ts | 6 +- .../providerMaintenanceRunner.test.ts | 33 ++- .../src/provider/providerMaintenanceRunner.ts | 3 + docs/user/install.md | 7 + packages/contracts/src/settings.ts | 22 +- .../provider-core/src/server/maintenance.ts | 2 + .../src/server/maintenanceResolver.test.ts | 240 +++++++++++++++--- .../src/server/maintenanceResolver.ts | 134 ++++++++-- 10 files changed, 391 insertions(+), 62 deletions(-) diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index 5bedffe9242b4..a9c6905689a6d 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -130,6 +130,9 @@ export const ClaudeDriver: ProviderDriver enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, { enableProviderUpdateChecks: settings.enableProviderUpdateChecks, + useMaintenanceVersion: true, }), ), Effect.provideService(HttpClient.HttpClient, httpClient), diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index 1462d051346f1..7009d1a5962d8 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -424,7 +424,7 @@ it.layer(layerTest)("CodexDriver", (it) => { for (const update of updates) { expect(update).toMatchObject({ - command: `${binaryPath} update`, + command: `env CODEX_HOME='${installHome}' ${binaryPath} update`, args: ["update"], lockKey: "codex-native", env: { CODEX_HOME: installHome }, diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 03245ba46d6c1..aaa81b3b2e0e3 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -91,7 +91,7 @@ function makeCodexMaintenanceResolver(sharedHomePath: string) { args: ["update"], isCommandPath: (commandPath) => codexStandaloneHome(commandPath) !== null, requiresCommandPath: true, - env: (context) => ({ + installationEnv: (context) => ({ CODEX_HOME: codexStandaloneHome(context.realCommandPath) ?? codexStandaloneHome(context.resolvedCommandPath) ?? @@ -225,6 +225,9 @@ export const CodexDriver: ProviderDriver< makeCodexMaintenanceResolver(homeLayout.sharedHomePath), { binaryPath: effectiveConfig.binaryPath, + maintenanceBinaryPath: config.maintenanceBinaryPath + ? expandHomePath(config.maintenanceBinaryPath, yield* HostProcess.HomeDirectory) + : null, env: processEnv, }, ).pipe( @@ -299,6 +302,7 @@ export const CodexDriver: ProviderDriver< Effect.flatMap((maintenanceCapabilities) => enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, { enableProviderUpdateChecks: settings.enableProviderUpdateChecks, + useMaintenanceVersion: true, }), ), Effect.provideService(HttpClient.HttpClient, httpClient), diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 985347a66e96b..eb3fc702774bf 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -340,7 +340,22 @@ describe("providerMaintenanceRunner", () => { }, { name: "installed behind", probe: { installedVersion: "2.1.309" }, skip: false }, { name: "installed unknown", probe: { installedVersion: null }, skip: false }, - ] as const)("only skips a successful fresh current probe: $name", ({ probe, skip }) => { + { name: "maintenance behind", probe: {}, maintenanceVersion: "2.1.309", skip: false }, + { + name: "maintenance current", + probe: { version: "2.1.309" }, + maintenanceVersion: "2.1.310", + skip: true, + }, + { + name: "maintenance updated but session behind", + probe: { version: "2.1.309" }, + maintenanceVersion: "2.1.309", + skip: false, + }, + ] as const)("only skips a successful fresh current probe: $name", (fixture) => { + const { probe, skip } = fixture; + let maintenanceVersion = "maintenanceVersion" in fixture ? fixture.maintenanceVersion : null; const calls: Array<{ command: string; args: ReadonlyArray }> = []; const refreshedInstanceIds: Array = []; return Effect.gen(function* () { @@ -375,20 +390,29 @@ describe("providerMaintenanceRunner", () => { ); }, getProviderMaintenanceCapabilitiesForInstance: () => - Effect.succeed( - makeProviderMaintenanceCapabilities({ + Effect.succeed({ + ...makeProviderMaintenanceCapabilities({ provider: CODEX_DRIVER, packageName: "@anthropic-ai/claude-code", updateExecutable: "claude", updateArgs: ["update"], updateLockKey: "claudeAgent-native", }), - ), + ...("maintenanceVersion" in fixture + ? { lookupMaintenanceVersion: Effect.sync(() => maintenanceVersion) } + : {}), + }), }); const result = yield* updater.updateProvider(CODEX_DRIVER); assert.deepStrictEqual(refreshedInstanceIds, [CODEX_INSTANCE_ID]); assert.deepStrictEqual(calls, skip ? [] : [{ command: "claude", args: ["update"] }]); + if ("maintenanceVersion" in fixture && !skip) { + assert.strictEqual( + result.providers[0]?.updateState?.status, + fixture.name === "maintenance updated but session behind" ? "unchanged" : "succeeded", + ); + } if (!skip) return; assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded"); assert.strictEqual(result.providers[0]?.updateState?.message, "Already up to date."); @@ -407,6 +431,7 @@ describe("providerMaintenanceRunner", () => { layerLatestVersionHttpClient("2.1.310"), layerMockSpawner((command, args) => { calls.push({ command, args }); + maintenanceVersion = "2.1.310"; return { stdout: "updated" }; }), ), diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index 9ac62dca70419..3342f9b25ffeb 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -391,6 +391,9 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { enrichProviderSnapshotWithVersionAdvisory( refreshedProvider, maintenanceCapabilities, + phase === "pre-update" + ? { enableProviderUpdateChecks: undefined, useMaintenanceVersion: true } + : undefined, ).pipe( Effect.provideService(HttpClient.HttpClient, httpClient), Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions), diff --git a/docs/user/install.md b/docs/user/install.md index 2842006053035..5a667f6856751 100644 --- a/docs/user/install.md +++ b/docs/user/install.md @@ -238,6 +238,13 @@ The managed runtimes for Antigravity and for Codex connected through ChatGPT first install the release T3 Code tested. When T3 Code finds a newer compatible release, their setup in **Settings → Providers** offers an update. +If Codex or Claude uses a launcher as its **Binary path**, set **Maintenance binary path** +to the underlying CLI installation in web or desktop Settings. Sessions keep using the +launcher; Update now uses the maintenance installation and still verifies the session +binary's version afterward. Clear the maintenance path to update the session binary again. +When T3 can determine the installer, the copyable command also targets that installation. +Run it in a terminal on the environment where the provider is installed. + Add another provider instance for a separate account or configuration. Each instance can have its own environment variables, such as API keys or a custom base URL. Mark secret values as sensitive; after saving, T3 Code does not display diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7bbb03595d4bb..1e63f137f492c 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -702,6 +702,15 @@ export function makeProviderSettingsSchema; /** undefined defers to npm; null means the installer could not determine the latest version. */ readonly latestVersion?: string | null; /** diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts index 737f2984fb644..3a8dee34281f0 100644 --- a/packages/provider-core/src/server/maintenanceResolver.test.ts +++ b/packages/provider-core/src/server/maintenanceResolver.test.ts @@ -119,13 +119,18 @@ const noSpawn = ChildProcessSpawner.make(() => ); function stdoutSpawner( - onSpawn: (command: string, args: ReadonlyArray) => string, + onSpawn: (command: string, args: ReadonlyArray, env?: NodeJS.ProcessEnv) => string, exitCodeOf: (args: ReadonlyArray) => number = () => 0, ) { return ChildProcessSpawner.make((command) => { - const { command: executable, args } = command as unknown as { + const { + command: executable, + args, + options, + } = command as unknown as { readonly command: string; readonly args: ReadonlyArray; + readonly options: { readonly env?: NodeJS.ProcessEnv }; }; return Effect.succeed( ChildProcessSpawner.makeHandle({ @@ -135,7 +140,7 @@ function stdoutSpawner( kill: () => Effect.void, unref: Effect.succeed(Effect.void), stdin: Sink.drain, - stdout: Stream.encodeText(Stream.make(onSpawn(executable, args))), + stdout: Stream.encodeText(Stream.make(onSpawn(executable, args, options.env))), stderr: Stream.empty, all: Stream.empty, getInputFd: () => Sink.drain, @@ -332,6 +337,74 @@ it.layer( }), ); + it.effect.each([ + { output: "codex-cli 2.0.0", exitCode: 0, expected: "2.0.0" }, + { output: "2.0.0 (Claude Code)", exitCode: 0, expected: "2.0.0" }, + { output: "unavailable", exitCode: 0, expected: null }, + { output: "codex-cli 2.0.0", exitCode: 1, expected: null }, + { output: "missing executable", exitCode: 0, expected: null, missing: true }, + ])( + "uses the selected CLI version only for advisories ($output, exit $exitCode)", + (fixture) => + Effect.gen(function* () { + const tempDir = yield* makeTempDir("t3-maintenance-advisory"); + const maintenancePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool"); + if (!fixture.missing) writeExecutable(maintenancePath); + let probes = 0; + const capabilities = { + ...(yield* resolveProviderMaintenanceCapabilitiesEffect(nativePackageToolUpdate, { + binaryPath: NodePath.join(tempDir, "runtime-launcher"), + maintenanceBinaryPath: maintenancePath, + env: { PATH: "", SELECTED_INSTALL: "fixture" }, + }).pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + stdoutSpawner( + (command, args) => { + expect(command).toBe(maintenancePath); + expect(args).toEqual(["--version"]); + probes++; + return fixture.output; + }, + () => fixture.exitCode, + ), + ), + )), + latestVersion: "3.0.0", + }; + const snapshot = { + ...installedPackageToolProvider, + version: "3.0.0", + installedVersion: "3.0.0", + }; + const enrich = (useMaintenanceVersion: boolean, enableProviderUpdateChecks = true) => + enrichProviderSnapshotWithVersionAdvisory(snapshot, capabilities, { + enableProviderUpdateChecks, + useMaintenanceVersion, + }); + yield* enrich(true, false); + expect(probes).toBe(0); + const verification = yield* enrich(false); + expect(verification.versionAdvisory?.currentVersion).toBe("3.0.0"); + expect(probes).toBe(0); + const advisory = yield* enrich(true); + expect(advisory.version).toBe("3.0.0"); + expect(advisory.installedVersion).toBe("3.0.0"); + expect(advisory.versionAdvisory).toMatchObject({ + currentVersion: fixture.expected, + status: fixture.expected ? "behind_latest" : "unknown", + }); + expect(probes).toBe(fixture.missing ? 0 : 1); + }).pipe( + Effect.provide(ProviderLatestVersions.layer), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("fixture latest version must not make an HTTP request")), + ), + ), + { skip: windowsHost }, + ); + it.effect("does not fetch latest provider versions when update checks are disabled", () => enrichProviderSnapshotWithVersionAdvisory( { ...installedPackageToolProvider, installedVersion: "1.1.0" }, @@ -618,7 +691,27 @@ it.layer( updateCommand: null, canUpdate: false, message: - "Version 2.1.117 is out. T3 Code runs /Applications/Tool.app/Contents/Resources/bin/package-tool; update it with the app or tool that installed it.", + "Version 2.1.117 is out. Update /Applications/Tool.app/Contents/Resources/bin/package-tool with the app or tool that installed it.", + }); + }); + + it("copies a PowerShell update with a quoted install path and restores the terminal environment", () => { + const capabilities = makeProviderMaintenanceCapabilities({ + provider: driver("codex"), + packageName: "@openai/codex", + platform: "win32", + updateExecutable: String.raw`C:\Karl's Tools\codex.exe`, + updateArgs: ["update"], + updateLockKey: "codex-native", + env: { CODEX_HOME: String.raw`C:\Default`, PROVIDER_TOKEN: "fixture-secret" }, + installationEnv: { CODEX_HOME: String.raw`C:\Karl's Tools\$codex` }, + }); + expect(capabilities.update).toMatchObject({ + command: + "& { $previous0 = $env:CODEX_HOME; try { " + + String.raw`$env:CODEX_HOME = 'C:\Karl''s Tools\$codex'; & 'C:\Karl''s Tools\codex.exe' update` + + " } finally { $env:CODEX_HOME = $previous0 } }", + env: { CODEX_HOME: String.raw`C:\Karl's Tools\$codex`, PROVIDER_TOKEN: "fixture-secret" }, }); }); @@ -1533,8 +1626,13 @@ it.layer( Effect.gen(function* () { const tempDir = yield* makeTempDir("t3-bun-latest"); const bunBinDir = NodePath.join(tempDir, ".bun", "bin"); - writeExecutable(NodePath.join(bunBinDir, "bun")); - writeExecutable(NodePath.join(bunBinDir, "package-tool")); + const bunPath = NodePath.join(bunBinDir, "bun"); + const globalDir = NodePath.join(tempDir, ".bun", "install", "global"); + const packagePath = NodePath.join(globalDir, "node_modules/@example/package-tool/bin/cli"); + const maintenanceBinaryPath = NodePath.join(bunBinDir, "package-tool"); + writeExecutable(bunPath); + writeExecutable(packagePath); + NodeFS.symlinkSync(packagePath, maintenanceBinaryPath); const outdated = [ "bun outdated v1.3.3 (274e01c7)", ...(fixture.row === null ? [] : bunOutdatedTable(fixture.row)), @@ -1543,17 +1641,25 @@ it.layer( const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( packageToolUpdate, - { binaryPath: "package-tool", env: { PATH: bunBinDir } }, + { + binaryPath: "session-launcher", + maintenanceBinaryPath, + env: { PATH: bunBinDir, BUN_INSTALL_GLOBAL_DIR: NodePath.join(tempDir, "other") }, + }, ).pipe( Effect.provideService(HostProcess.Platform, "darwin"), Effect.provideService(HostProcess.Environment, { PATH: "" }), Effect.provideService( ChildProcessSpawner.ChildProcessSpawner, - stdoutSpawner((_command, args) => - args[0] === "outdated" - ? outdated - : `${tempDir} node_modules (1)\n└── @example/package-tool@1.0.0\n`, - ), + stdoutSpawner((command, args, env) => { + expect(command).toBe(bunPath); + expect(args).toEqual(["outdated", "-g", "@example/package-tool"]); + expect(env).toMatchObject({ + BUN_INSTALL_GLOBAL_DIR: globalDir, + BUN_INSTALL_BIN: bunBinDir, + }); + return outdated; + }), ), ); @@ -1576,32 +1682,108 @@ it.layer( latestVersion: fixture.expected, }); }), - { skip: windowsHost }, + { skip: !symlinksSupported || windowsHost }, ); - it.effect.skipIf(windowsHost)( - "switches to bun updates when the resolved binary lives in bun's global bin", + it.effect.skipIf(windowsHost || !symlinksSupported)( + "binds bun updates to the selected global installation and rejects unproven ownership", () => Effect.gen(function* () { const tempDir = yield* makeTempDir("t3-bun-capabilities"); - const bunBinDir = NodePath.join(tempDir, ".bun", "bin"); - writeExecutable(NodePath.join(bunBinDir, "package-tool")); - - const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( - packageToolUpdate, - { - binaryPath: "package-tool", - env: { PATH: bunBinDir }, - }, - ).pipe( - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), + const selected = "selected's install"; + const bunBinDir = NodePath.join(tempDir, selected, ".bun", "bin"); + const globalDir = NodePath.join(tempDir, selected, ".bun", "install", "global"); + const packagePath = NodePath.join( + globalDir, + "node_modules", + "@example", + "package-tool", + "bin", + "package-tool.js", ); + writeExecutable(packagePath); + const maintenancePath = NodePath.join(bunBinDir, "package-tool"); + NodeFS.mkdirSync(bunBinDir, { recursive: true }); + NodeFS.symlinkSync(packagePath, maintenancePath); + const runtimePath = NodePath.join(tempDir, "default", ".bun", "bin", "package-tool"); + writeExecutable(runtimePath); + const env = { + PATH: NodePath.dirname(runtimePath), + BUN_INSTALL_GLOBAL_DIR: NodePath.join(tempDir, "default", ".bun", "install", "global"), + BUN_INSTALL_BIN: NodePath.dirname(runtimePath), + PROVIDER_TOKEN: "fixture-secret", + }; + + const resolve = () => + resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, { + binaryPath: runtimePath, + maintenanceBinaryPath: maintenancePath, + env, + }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, env), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), + ); + const capabilities = yield* resolve(); + const commandPrefix = `env BUN_INSTALL_GLOBAL_DIR='${tempDir}/selected'\\''s install/.bun/install/global' BUN_INSTALL_BIN='${tempDir}/selected'\\''s install/.bun/bin' bun i -g`; expect(capabilities.update).toMatchObject({ - command: "bun i -g @example/package-tool@latest", - lockKey: "bun-global", + command: `${commandPrefix} @example/package-tool@latest`, + lockKey: `bun-global:${normalizeCommandPath(globalDir)}`, + env: { ...env, BUN_INSTALL_GLOBAL_DIR: globalDir, BUN_INSTALL_BIN: bunBinDir }, + }); + expect(makeTargetedProviderUpdateAction(capabilities, "2.0.0")).toMatchObject({ + command: `${commandPrefix} @example/package-tool@2.0.0`, + args: ["i", "-g", "@example/package-tool@2.0.0"], + env: capabilities.update?.env, + }); + + for (const target of [ + NodePath.join(globalDir, "node_modules", "@example", "other-package", "bin", "tool"), + NodePath.join( + tempDir, + "project", + "node_modules", + "@example", + "package-tool", + "bin", + "tool", + ), + maintenancePath, + ]) { + NodeFS.unlinkSync(maintenancePath); + writeExecutable(target); + if (target !== maintenancePath) NodeFS.symlinkSync(target, maintenancePath); + expect(yield* resolve()).toMatchObject({ update: null, installPath: target }); + } + }), + ); + + it.effect.skipIf(windowsHost)( + "updates the explicit maintenance installation while keeping the runtime wrapper separate", + () => + Effect.gen(function* () { + const tempDir = yield* makeTempDir("t3-wrapper-maintenance"); + const wrapper = NodePath.join(tempDir, "agentfleet-launcher"); + const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool"); + writeExecutable(wrapper); + writeExecutable(nativePath); + const resolve = (maintenanceBinaryPath: string) => + resolveProviderMaintenanceCapabilitiesEffect(nativePackageToolUpdate, { + binaryPath: wrapper, + maintenanceBinaryPath, + env: { PATH: "" }, + }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), + ); + expect((yield* resolve(nativePath)).update).toMatchObject({ + command: `${nativePath} update`, + executable: nativePath, + args: ["update"], }); + expect((yield* resolve(NodePath.join(tempDir, "missing"))).update).toBeNull(); + expect((yield* resolve(" ")).update?.executable).toBe(wrapper); }), ); diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index cacce437cf08a..d426d8eef8f20 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -93,6 +93,9 @@ export interface PackageManagedProviderMaintenanceDefinition { readonly env?: | NodeJS.ProcessEnv | ((context: ProviderMaintenanceResolutionContext) => NodeJS.ProcessEnv); + readonly installationEnv?: ( + context: ProviderMaintenanceResolutionContext, + ) => Readonly>; } | null; /** The mise registry tool that installs this provider; unset keeps mise installs manual-only. */ readonly mise?: MiseProviderTool; @@ -112,12 +115,14 @@ function nonEmptyString(value: unknown): string | null { return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; } +function quotePowerShellLiteral(value: string): string { + return `'${value.replace(/['\u2018\u2019]/g, "$&$&")}'`; +} + function quoteShellWord(word: string, platform: NodeJS.Platform): string { const safeWord = platform === "win32" ? /^[\w./:\\@=-]+$/ : /^[\w./:@=-]+$/; if (safeWord.test(word)) return word; - return platform === "win32" - ? `'${word.replace(/['\u2018\u2019]/g, "$&$&")}'` - : `'${word.replaceAll("'", "'\\''")}'`; + return platform === "win32" ? quotePowerShellLiteral(word) : `'${word.replaceAll("'", "'\\''")}'`; } function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string { @@ -126,6 +131,31 @@ function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): s return platform === "win32" && quoted !== executable ? `& ${quoted}` : quoted; } +function formatUpdateCommand( + executable: string, + args: ReadonlyArray, + platform: NodeJS.Platform, + installationEnv: Readonly> | undefined, +): string { + const command = [ + quoteUpdateExecutable(executable, platform), + ...args.map((arg) => quoteShellWord(arg, platform)), + ].join(" "); + const entries = Object.entries(installationEnv ?? {}); + if (entries.length === 0) return command; + if (platform !== "win32") { + return [ + "env", + ...entries.map(([key, value]) => `${key}=${quoteShellWord(value, platform)}`), + command, + ].join(" "); + } + const save = entries.map(([key], i) => `$previous${i} = $env:${key}`); + const set = entries.map(([key, value]) => `$env:${key} = ${quotePowerShellLiteral(value)}`); + const restore = entries.map(([key], i) => `$env:${key} = $previous${i}`); + return `& { ${save.join("; ")}; try { ${[...set, command].join("; ")} } finally { ${restore.join("; ")} } }`; +} + export function makeProviderMaintenanceCapabilities(input: { readonly provider: ProviderDriverKind; readonly packageName: string | null; @@ -135,6 +165,8 @@ export function makeProviderMaintenanceCapabilities(input: { readonly updateCommand?: string; readonly platform?: NodeJS.Platform; readonly env?: NodeJS.ProcessEnv; + /** Public paths required to target the installation; also shown in the copied command. */ + readonly installationEnv?: Readonly>; readonly latestVersion?: string | null; readonly lookupLatestVersion?: Effect.Effect; }): ProviderMaintenanceCapabilities { @@ -145,14 +177,20 @@ export function makeProviderMaintenanceCapabilities(input: { : { command: input.updateCommand ?? - [ - quoteUpdateExecutable(input.updateExecutable, platform), - ...input.updateArgs.map((arg) => quoteShellWord(arg, platform)), - ].join(" "), + formatUpdateCommand( + input.updateExecutable, + input.updateArgs, + platform, + input.installationEnv, + ), executable: input.updateExecutable, args: input.updateArgs, lockKey: input.updateLockKey, - ...(input.env ? { env: input.env } : {}), + ...(input.installationEnv + ? { env: { ...input.env, ...input.installationEnv } } + : input.env + ? { env: input.env } + : {}), }; return { provider: input.provider, @@ -172,7 +210,7 @@ export function makeTargetedProviderUpdateAction( const packageName = capabilities.packageName; if (!update || !packageName) return null; if ( - !/^(?:npm-global:|bun-global$|pnpm-global$|vite-plus-global$|yarn-global$|volta$)/.test( + !/^(?:npm-global:|bun-global:|pnpm-global$|vite-plus-global$|yarn-global$|volta$)/.test( update.lockKey, ) ) @@ -853,6 +891,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( const nativeUpdate = definition.nativeUpdate; const nativeEnv = nativeUpdate?.env; + const nativeInstallationEnv = nativeUpdate?.installationEnv?.(context); const native = nativeUpdate ? makeProviderMaintenanceCapabilities({ provider: definition.provider, @@ -864,6 +903,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( ...(nativeEnv ? { env: typeof nativeEnv === "function" ? nativeEnv(context) : nativeEnv } : {}), + ...(nativeInstallationEnv ? { installationEnv: nativeInstallationEnv } : {}), }) : manual; // A native-looking launcher can still delegate to an npm-owned install. @@ -906,17 +946,38 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( }; } if (commandPaths.some(isBunGlobalCommandPath)) { + const path = yield* Path.Path; + const binDir = path.dirname(context.resolvedCommandPath); + if (!normalizeCommandPath(binDir).endsWith("/.bun/bin")) return manual; + const fileSystem = yield* FileSystem.FileSystem; + const globalDir = yield* fileSystem + .realPath(path.join(binDir, "..", "install", "global")) + .pipe(Effect.orElseSucceed(() => null)); + // A bin entry alone may be a wrapper or a link into a local project. + if ( + !globalDir || + !path + .relative(globalDir, context.realCommandPath) + .replaceAll("\\", "/") + .startsWith(`node_modules/${packageName}/`) + ) { + return manual; + } + const installationEnv = { BUN_INSTALL_GLOBAL_DIR: globalDir, BUN_INSTALL_BIN: binDir }; const services = yield* Effect.context(); return makeProviderMaintenanceCapabilities({ provider: definition.provider, packageName, updateExecutable: "bun", updateArgs: ["i", "-g", `${packageName}@latest`], - updateLockKey: "bun-global", + updateLockKey: `bun-global:${normalizeCommandPath(globalDir)}`, + platform: context.platform, env: context.env, - lookupLatestVersion: resolveBunGlobalLatestVersion(packageName, context.env).pipe( - Effect.provideContext(services), - ), + installationEnv, + lookupLatestVersion: resolveBunGlobalLatestVersion(packageName, { + ...context.env, + ...installationEnv, + }).pipe(Effect.provideContext(services)), }); } if (commandPaths.some(isPnpmGlobalCommandPath)) { @@ -1245,18 +1306,29 @@ export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn( resolver: ProviderMaintenanceCapabilitiesResolver, options?: { readonly binaryPath?: string | null; + readonly maintenanceBinaryPath?: string | null; readonly env?: NodeJS.ProcessEnv; }, ) { - const binaryPath = nonEmptyString(options?.binaryPath); + const maintenanceBinaryPath = nonEmptyString(options?.maintenanceBinaryPath); + const binaryPath = maintenanceBinaryPath ?? nonEmptyString(options?.binaryPath); + const unresolved = resolver + .resolve(null) + .pipe( + Effect.map((capabilities) => + maintenanceBinaryPath + ? { ...capabilities, lookupMaintenanceVersion: Effect.succeed(null) } + : capabilities, + ), + ); if (!binaryPath) { - return yield* resolver.resolve(null); + return yield* unresolved; } const env = options?.env ?? (yield* readCommandLookupEnv); const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }); if (!resolvedCommandPath) { - return yield* resolver.resolve(null); + return yield* unresolved; } const fileSystem = yield* FileSystem.FileSystem; @@ -1264,15 +1336,24 @@ export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn( .realPath(resolvedCommandPath) .pipe(Effect.orElseSucceed(() => null)); if (!realCommandPath) { - return yield* resolver.resolve(null); + return yield* unresolved; } - return yield* resolver.resolve({ + const capabilities = yield* resolver.resolve({ binaryPath, resolvedCommandPath, realCommandPath, env, platform: yield* HostProcess.Platform, }); + if (!maintenanceBinaryPath) return capabilities; + const services = yield* Effect.context(); + return { + ...capabilities, + lookupMaintenanceVersion: runProbe(resolvedCommandPath, ["--version"], env).pipe( + Effect.map((output) => output?.match(/\bv?(\d+\.\d+\.\d+)\b/)?.[1] ?? null), + Effect.provideContext(services), + ), + }; }, Effect.flatMap(withConfiguredNpmVersionLookup)); export const makeCachedProviderMaintenanceResolution = Effect.fn( @@ -1290,7 +1371,7 @@ export const makeCachedProviderMaintenanceResolution = Effect.fn( function manualUpdateMessage(latestVersion: string, installPath: string | undefined): string { return installPath - ? `Version ${latestVersion} is out. T3 Code runs ${installPath}; update it with the app or tool that installed it.` + ? `Version ${latestVersion} is out. Update ${installPath} with the app or tool that installed it.` : `Version ${latestVersion} is out. Update it with the app or tool that installed it.`; } @@ -1431,17 +1512,20 @@ export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn( maintenanceCapabilities?: ProviderMaintenanceCapabilities, options?: { readonly enableProviderUpdateChecks: boolean | undefined; + readonly useMaintenanceVersion?: boolean; }, ) { const capabilities = maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver); + const shouldCheck = + options?.enableProviderUpdateChecks !== false && snapshot.enabled && snapshot.installed; const currentVersion = - snapshot.installedVersion !== undefined ? snapshot.installedVersion : snapshot.version; - const shouldResolveLatestVersion = - options?.enableProviderUpdateChecks !== false && - snapshot.enabled && - snapshot.installed && - Boolean(currentVersion); + shouldCheck && options?.useMaintenanceVersion && capabilities.lookupMaintenanceVersion + ? yield* capabilities.lookupMaintenanceVersion + : snapshot.installedVersion !== undefined + ? snapshot.installedVersion + : snapshot.version; + const shouldResolveLatestVersion = shouldCheck && Boolean(currentVersion); if (!shouldResolveLatestVersion) { return { ...snapshot,