TypeScript
fix(server): only run provider updates through the installer that owns the binary (#9325)
Julius Marminge2fb99a7a664f
diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.tsindex efcf19e9d6b..56cb1cb06f0 100644--- a/apps/server/src/provider/Drivers/ClaudeDriver.ts+++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts@@ -48,6 +48,7 @@ import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {enrichProviderSnapshotWithVersionAdvisory,+ makeCachedProviderMaintenanceResolution,makePackageManagedProviderMaintenanceResolver,normalizeCommandPath,resolveProviderMaintenanceCapabilitiesEffect,@@ -76,11 +77,8 @@ function isClaudeNativeCommandPath(commandPath: string): boolean {const UPDATE = makePackageManagedProviderMaintenanceResolver({provider: DRIVER_KIND,npmPackageName: "@anthropic-ai/claude-code",- homebrewFormula: "claude-code",nativeUpdate: {- executable: "claude",args: ["update"],- lockKey: "claude-native",isCommandPath: isClaudeNativeCommandPath,},});@@ -122,10 +120,16 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {instanceId,});const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;- const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- });+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,+ }).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),+ );const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);const stampIdentity = withInstanceIdentity({instanceId,@@ -189,7 +193,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({- maintenanceCapabilities,+ resolveMaintenance,getSettings: snapshotSettings.getSettings,streamSettings: snapshotSettings.streamSettings,haveSettingsChanged: haveProviderSnapshotSettingsChanged,@@ -202,9 +206,12 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {),checkProvider,enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>- enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- }).pipe(+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,+ }),+ ),Effect.provideService(HttpClient.HttpClient, httpClient),Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),),diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.tsnew file mode 100644index 00000000000..003c6f53d31--- /dev/null+++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts@@ -0,0 +1,105 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeServices from "@effect/platform-node/NodeServices";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";+import { expect, it } from "@effect/vitest";+import { ProviderInstanceId } from "@t3tools/contracts";+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import { HttpClient } from "effect/unstable/http";+import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";++import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";+import { ServerConfig } from "../../config.ts";+import { ServerSettingsService } from "../../serverSettings.ts";+import { layerTest as codexResetCreditLayerTest } from "../Layers/codexResetCredit.ts";+import { NoOpProviderEventLoggers, ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";+import * as ModelManifest from "../ModelManifest.ts";+import { CodexDriver } from "./CodexDriver.ts";++const testLayer = ServerConfig.layerTest(process.cwd(), {+ prefix: "t3-codex-driver-maintenance-",+}).pipe(+ Layer.provideMerge(NodeServices.layer),+ Layer.provideMerge(ServerSettingsService.layerTest()),+ Layer.provideMerge(ModelManifest.layerTest),+ Layer.provideMerge(codexResetCreditLayerTest),+ Layer.provideMerge(+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({+ shouldRunScopeWork: () => Effect.succeed(false),+ }),+ ),+ Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),+ Layer.provideMerge(+ Layer.succeed(+ HttpClient.HttpClient,+ HttpClient.make(() => Effect.die("Disabled Codex must not make an HTTP request")),+ ),+ ),+);++// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.+const windowsHost = HostProcessPlatform.defaultValue() === "win32";++const noSpawn = ChildProcessSpawner.make(() =>+ Effect.die("Disabled Codex must not spawn a process"),+);++it.layer(testLayer)("CodexDriver", (it) => {+ it.effect.skipIf(windowsHost)(+ "runs the standalone updater against the shared home, not the shadow home",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-driver-" });+ const sharedHome = NodePath.join(tempDir, "codex-home");+ const shadowHome = NodePath.join(tempDir, "codex-shadow");+ const binaryPath = NodePath.join(sharedHome, "packages", "standalone", "bin", "codex");+ yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });+ yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");+ yield* fs.chmod(binaryPath, 0o755);++ const instance = yield* CodexDriver.create({+ instanceId: ProviderInstanceId.make("codex-shadow"),+ displayName: "Codex test",+ enabled: false,+ environment: [],+ config: {+ ...CodexDriver.defaultConfig(),+ binaryPath,+ homePath: sharedHome,+ shadowHomePath: shadowHome,+ },+ });++ const capabilities = yield* instance.snapshot.resolveMaintenance();+ expect(capabilities.update).toMatchObject({+ executable: binaryPath,+ args: ["update"],+ lockKey: "codex-native",+ env: { CODEX_HOME: sharedHome },+ });+ }).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),+ Effect.scoped,+ ),+ );++ it.effect("stays manual-only when the configured executable does not exist", () =>+ Effect.gen(function* () {+ const instance = yield* CodexDriver.create({+ instanceId: ProviderInstanceId.make("codex-missing"),+ displayName: "Codex test",+ enabled: false,+ environment: [],+ config: {+ ...CodexDriver.defaultConfig(),+ binaryPath: NodePath.join(NodeOS.tmpdir(), "t3-codex-missing", "codex"),+ },+ });+ expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),+ );+});diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.tsindex 04dad8d9c78..d7fd1e9c569 100644--- a/apps/server/src/provider/Drivers/CodexDriver.ts+++ b/apps/server/src/provider/Drivers/CodexDriver.ts@@ -55,7 +55,9 @@ import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {enrichProviderSnapshotWithVersionAdvisory,+ makeCachedProviderMaintenanceResolution,makePackageManagedProviderMaintenanceResolver,+ normalizeCommandPath,resolveProviderMaintenanceCapabilitiesEffect,} from "../providerMaintenance.ts";import {@@ -71,12 +73,29 @@ import {const decodeCodexSettings = Schema.decodeSync(CodexSettings);const DRIVER_KIND = ProviderDriverKind.make("codex");-const UPDATE = makePackageManagedProviderMaintenanceResolver({- provider: DRIVER_KIND,- npmPackageName: "@openai/codex",- homebrewFormula: "codex",- nativeUpdate: null,-});+// The standalone installer lays out `<CODEX_HOME>/packages/standalone/…`;+// CODEX_HOME is not always `~/.codex`.+function isCodexStandaloneCommandPath(commandPath: string): boolean {+ return normalizeCommandPath(commandPath).includes("/packages/standalone/");+}++/**+ * `codex update` replaces the standalone tree under `CODEX_HOME`. That tree+ * lives in the shared home even when an auth-overlay shadow home is in use+ * (the overlay only carries auth and a few local entries), so the updater+ * runs against `sharedHomePath` rather than the instance's effective home.+ */+function makeCodexMaintenanceResolver(sharedHomePath: string) {+ return makePackageManagedProviderMaintenanceResolver({+ provider: DRIVER_KIND,+ npmPackageName: "@openai/codex",+ nativeUpdate: {+ args: ["update"],+ isCommandPath: isCodexStandaloneCommandPath,+ env: { CODEX_HOME: sharedHomePath },+ },+ });+}/*** Services the driver needs to materialize an instance. Surfaced as the@@ -108,6 +127,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {Effect.gen(function* () {const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;const resetCreditCoordinator = yield* CodexResetCreditCoordinator;+ const fileSystem = yield* FileSystem.FileSystem;+ const pathService = yield* Path.Path;const httpClient = yield* HttpClient.HttpClient;const serverSettings = yield* ServerSettingsService;const eventLoggers = yield* ProviderEventLoggers;@@ -138,10 +159,19 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {enabled,homePath: homeLayout.effectiveHomePath ?? "",} satisfies CodexSettings;- const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- });+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(+ makeCodexMaintenanceResolver(homeLayout.sharedHomePath),+ {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,+ },+ ).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, pathService),+ ),+ );// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error// channels at construction time — their failure modes are all on the@@ -177,7 +207,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {);const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({- maintenanceCapabilities,+ resolveMaintenance,getSettings: snapshotSettings.getSettings,streamSettings: snapshotSettings.streamSettings,haveSettingsChanged: haveProviderSnapshotSettingsChanged,@@ -190,9 +220,12 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {),checkProvider,enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>- enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- }).pipe(+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,+ }),+ ),Effect.provideService(HttpClient.HttpClient, httpClient),Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),),diff --git a/apps/server/src/provider/Drivers/CursorDriver.test.ts b/apps/server/src/provider/Drivers/CursorDriver.test.tsindex f92a5884c11..4b9dc529c11 100644--- a/apps/server/src/provider/Drivers/CursorDriver.test.ts+++ b/apps/server/src/provider/Drivers/CursorDriver.test.ts@@ -1,8 +1,12 @@+// @effect-diagnostics nodeBuiltinImport:offimport * as NodeServices from "@effect/platform-node/NodeServices";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";import { expect, it } from "@effect/vitest";import { ProviderInstanceId } from "@t3tools/contracts";import { HostProcessPlatform } from "@t3tools/shared/hostProcess";import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import { HttpClient } from "effect/unstable/http";import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";@@ -32,26 +36,59 @@ const testLayer = ServerConfig.layerTest(process.cwd(), {),);+// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.+const windowsHost = HostProcessPlatform.defaultValue() === "win32";+it.layer(testLayer)("CursorDriver", (it) => {- it.effect("formats a copied update command for the injected Windows environment", () =>+ it.effect.skipIf(windowsHost)(+ "quotes a configured executable path in the copyable update command",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-driver-" });+ const binaryPath = NodePath.join(tempDir, "Cursor Tools", "bin", "cursor-agent");+ yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });+ yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");+ yield* fs.chmod(binaryPath, 0o755);++ const instance = yield* CursorDriver.create({+ instanceId: ProviderInstanceId.make("cursor-copy-command"),+ displayName: "Cursor test",+ enabled: false,+ environment: [],+ config: { ...CursorDriver.defaultConfig(), binaryPath },+ });++ const capabilities = yield* instance.snapshot.resolveMaintenance();+ expect(capabilities.update).toMatchObject({+ command: `'${binaryPath}' update`,+ executable: binaryPath,+ args: ["update"],+ });+ expect((yield* instance.snapshot.refresh).status).toBe("disabled");+ }).pipe(+ Effect.provideService(+ ChildProcessSpawner.ChildProcessSpawner,+ ChildProcessSpawner.make(() => Effect.die("Disabled Cursor must not spawn a process")),+ ),+ Effect.scoped,+ ),+ );++ it.effect("stays manual-only when the configured executable does not exist", () =>Effect.gen(function* () {- const binaryPath = "C:\\Users\\Example User\\.local\\bin\\cursor-agent.exe";const instance = yield* CursorDriver.create({- instanceId: ProviderInstanceId.make("cursor-copy-command"),+ instanceId: ProviderInstanceId.make("cursor-missing"),displayName: "Cursor test",enabled: false,environment: [],- config: { ...CursorDriver.defaultConfig(), binaryPath },- });-- expect(instance.snapshot.maintenanceCapabilities.update).toMatchObject({- command: `& '${binaryPath}' update`,- executable: binaryPath,- args: ["update"],+ config: {+ ...CursorDriver.defaultConfig(),+ binaryPath: NodePath.join(NodeOS.tmpdir(), "t3-cursor-missing", "cursor-agent"),+ },});- expect((yield* instance.snapshot.refresh).status).toBe("disabled");+ expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();}).pipe(- Effect.provideService(HostProcessPlatform, "win32"),Effect.provideService(ChildProcessSpawner.ChildProcessSpawner,ChildProcessSpawner.make(() => Effect.die("Disabled Cursor must not spawn a process")),diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.tsindex e140155a3c4..ddfda0f9133 100644--- a/apps/server/src/provider/Drivers/CursorDriver.ts+++ b/apps/server/src/provider/Drivers/CursorDriver.ts@@ -41,6 +41,8 @@ import {import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {+ makeCachedProviderMaintenanceResolution,+ makeManualOnlyProviderMaintenanceCapabilities,makeProviderMaintenanceCapabilities,type ProviderMaintenanceCapabilitiesResolver,resolveProviderMaintenanceCapabilitiesEffect,@@ -54,16 +56,25 @@ import { probeCursorSkills } from "./CursorSkills.ts";const decodeCursorSettings = Schema.decodeSync(CursorSettings);const DRIVER_KIND = ProviderDriverKind.make("cursor");+// cursor-agent updates itself, so the resolved executable is its own updater.+// No executable means nothing to update, not "whatever is on PATH".const UPDATE: ProviderMaintenanceCapabilitiesResolver = {- resolve: (options) =>- makeProviderMaintenanceCapabilities({- provider: DRIVER_KIND,- packageName: null,- updateExecutable: options?.binaryPath?.trim() || "cursor-agent",- updateArgs: ["update"],- updateLockKey: "cursor-agent",- ...(options?.platform ? { platform: options.platform } : {}),- }),+ resolve: (context) =>+ Effect.succeed(+ context+ ? makeProviderMaintenanceCapabilities({+ provider: DRIVER_KIND,+ packageName: null,+ updateExecutable: context.resolvedCommandPath,+ updateArgs: ["update"],+ updateLockKey: "cursor-agent",+ platform: context.platform,+ })+ : makeManualOnlyProviderMaintenanceCapabilities({+ provider: DRIVER_KIND,+ packageName: null,+ }),+ ),};export type CursorDriverEnv =@@ -107,10 +118,16 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {continuationGroupKey: continuationIdentity.continuationKey,});const effectiveConfig = { ...config, enabled } satisfies CursorSettings;- const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- });+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,+ }).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),+ );const adapter = yield* makeCursorAdapter(effectiveConfig, {environment: processEnv,@@ -129,7 +146,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({- maintenanceCapabilities,+ resolveMaintenance,getSettings: snapshotSettings.getSettings,streamSettings: snapshotSettings.streamSettings,haveSettingsChanged: haveProviderSnapshotSettingsChanged,@@ -139,15 +156,20 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {// Model catalog and capabilities come exclusively from Cursor's// list_available_models extension method during provider checks.enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>- enrichCursorSnapshot({- settings: settings.provider,- snapshot: currentSnapshot,- maintenanceCapabilities,- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- publishSnapshot,- stampIdentity,- httpClient,- }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichCursorSnapshot({+ settings: settings.provider,+ snapshot: currentSnapshot,+ maintenanceCapabilities,+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,+ publishSnapshot,+ stampIdentity,+ httpClient,+ }),+ ),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ ),}).pipe(Effect.mapError((cause) =>diff --git a/apps/server/src/provider/Drivers/GrokDriver.ts b/apps/server/src/provider/Drivers/GrokDriver.tsindex 8957b4c6778..066d0a6b63a 100644--- a/apps/server/src/provider/Drivers/GrokDriver.ts+++ b/apps/server/src/provider/Drivers/GrokDriver.ts@@ -28,11 +28,7 @@ import {import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import { discoverGrokSkills } from "./GrokSkills.ts";-import {- makeManualOnlyProviderMaintenanceCapabilities,- makeStaticProviderMaintenanceResolver,- resolveProviderMaintenanceCapabilitiesEffect,-} from "../providerMaintenance.ts";+import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";import {haveProviderSnapshotSettingsChanged,makeProviderSnapshotSettingsSource,@@ -41,12 +37,10 @@ import {const decodeGrokSettings = Schema.decodeSync(GrokSettings);const DRIVER_KIND = ProviderDriverKind.make("grok");-const UPDATE = makeStaticProviderMaintenanceResolver(- makeManualOnlyProviderMaintenanceCapabilities({- provider: DRIVER_KIND,- packageName: null,- }),-);+const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({+ provider: DRIVER_KIND,+ packageName: null,+});export type GrokDriverEnv =| BackgroundPolicy.BackgroundPolicy@@ -88,11 +82,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {continuationGroupKey: continuationIdentity.continuationKey,});const effectiveConfig = { ...config, enabled } satisfies GrokSettings;- const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- });-const adapter = yield* makeGrokAdapter(effectiveConfig, {environment: processEnv,...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),@@ -108,7 +97,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),getSettings: snapshotSettings.getSettings,streamSettings: snapshotSettings.streamSettings,haveSettingsChanged: haveProviderSnapshotSettingsChanged,@@ -118,7 +107,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>enrichGrokSnapshot({snapshot: currentSnapshot,- maintenanceCapabilities,+ maintenanceCapabilities: MAINTENANCE_CAPABILITIES,enableProviderUpdateChecks: settings.enableProviderUpdateChecks,publishSnapshot,httpClient,diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.tsindex 08a4d220787..72c1c0683de 100644--- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts+++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts@@ -45,6 +45,7 @@ import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {enrichProviderSnapshotWithVersionAdvisory,+ makeCachedProviderMaintenanceResolution,makePackageManagedProviderMaintenanceResolver,normalizeCommandPath,resolveProviderMaintenanceCapabilitiesEffect,@@ -69,11 +70,8 @@ function isOpenCodeNativeCommandPath(commandPath: string): boolean {const UPDATE = makePackageManagedProviderMaintenanceResolver({provider: DRIVER_KIND,npmPackageName: "opencode-ai",- homebrewFormula: "anomalyco/tap/opencode",nativeUpdate: {- executable: "opencode",args: ["upgrade"],- lockKey: "opencode-native",isCommandPath: isOpenCodeNativeCommandPath,},});@@ -100,6 +98,9 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>Effect.gen(function* () {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const fileSystem = yield* FileSystem.FileSystem;+ const pathService = yield* Path.Path;const openCodeRuntime = yield* OpenCodeRuntime;const serverConfig = yield* ServerConfig;const httpClient = yield* HttpClient.HttpClient;@@ -118,10 +119,16 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>continuationGroupKey: continuationIdentity.continuationKey,});const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;- const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- });+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,+ }).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, pathService),+ ),+ );const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {instanceId,@@ -195,7 +202,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>({- maintenanceCapabilities,+ resolveMaintenance,getSettings: snapshotSettings.getSettings,streamSettings: snapshotSettings.streamSettings,haveSettingsChanged: haveProviderSnapshotSettingsChanged,@@ -205,9 +212,12 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),checkProvider,enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>- enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- }).pipe(+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,+ }),+ ),Effect.provideService(HttpClient.HttpClient, httpClient),Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),),diff --git a/apps/server/src/provider/Layers/AntigravityProvider.ts b/apps/server/src/provider/Layers/AntigravityProvider.tsindex 62bd224cd4d..bd886a12380 100644--- a/apps/server/src/provider/Layers/AntigravityProvider.ts+++ b/apps/server/src/provider/Layers/AntigravityProvider.ts@@ -232,13 +232,14 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(funcreturn yield* options.stampIdentity(next.draft);});+ const maintenanceCapabilities =+ options.maintenanceCapabilities ??+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: ProviderDriverKind.make("antigravity"),+ packageName: null,+ });const managed = yield* makeManagedServerProvider({- maintenanceCapabilities:- options.maintenanceCapabilities ??- makeManualOnlyProviderMaintenanceCapabilities({- provider: ProviderDriverKind.make("antigravity"),- packageName: null,- }),+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed(settings),streamSettings: Stream.empty,haveSettingsChanged: () => false,diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.tsindex 18d94ebd0e1..bb8ff7835c8 100644--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts@@ -111,10 +111,13 @@ const makeFakeInstance = (displayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: driverKind,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: driverKind,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed({} as unknown as ServerProvider),refresh: Effect.succeed({} as unknown as ServerProvider),streamChanges: Stream.empty,diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.tsindex c687fc2fe98..cf3fe15ea9a 100644--- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts+++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts@@ -1033,10 +1033,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: cachedProvider.driver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: cachedProvider.driver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(pendingProvider),refresh: Ref.get(nextProvider),streamChanges: Stream.empty,@@ -1288,10 +1291,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: codexDriver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: codexDriver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(initialProvider),refresh: Ref.update(refreshCalls, (count) => count + 1).pipe(Effect.andThen(Effect.never),@@ -1380,10 +1386,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: driver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: driver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(provider),refresh: Effect.succeed(provider),streamChanges: Stream.empty,@@ -1569,10 +1578,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: codexDriver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: codexDriver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(codexProvider),refresh: Ref.update(codexRefreshCalls, (count) => count + 1).pipe(Effect.as(codexProvider),@@ -1593,10 +1605,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: openCodeDriver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: openCodeDriver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(failedOpenCodeProvider),refresh: Ref.update(openCodeRefreshCalls, (count) => count + 1).pipe(Effect.andThen(Ref.get(catalogSnapshot)),@@ -1717,10 +1732,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: cursorDriver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: cursorDriver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(initialProvider),refresh: Effect.succeed(refreshedProvider),streamChanges: Stream.fromPubSub(changes),@@ -1839,10 +1857,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: openCodeDriver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: openCodeDriver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(initialProvider),refresh: Effect.succeed(authoritativeProvider),streamChanges: Stream.fromPubSub(changes),@@ -1939,10 +1960,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: codexDriver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: codexDriver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(cachedProvider),refresh: Effect.die(new Error("simulated refresh failure")),streamChanges: Stream.empty,@@ -2033,10 +2057,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TedisplayName: undefined,enabled: true,snapshot: {- maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({- provider: provider.driver,- packageName: null,- }),+ resolveMaintenance: () =>+ Effect.succeed(+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: provider.driver,+ packageName: null,+ }),+ ),getSnapshot: Effect.succeed(provider),refresh: Effect.succeed(provider),streamChanges: Stream.empty,diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.tsindex bc972d7a655..2fd4278f3c5 100644--- a/apps/server/src/provider/Layers/ProviderRegistry.ts+++ b/apps/server/src/provider/Layers/ProviderRegistry.ts@@ -532,14 +532,19 @@ export const ProviderRegistryLive = Layer.effect(const getProviderMaintenanceCapabilitiesForInstance = Effect.fn("getProviderMaintenanceCapabilitiesForInstance",- )(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {- const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(- (candidate) => candidate.instanceId === instanceId,- );- return (- instance?.snapshot.maintenanceCapabilities ??- makeManualProviderMaintenanceCapabilities(provider)- );+ )(function* (+ instanceId: ProviderInstanceId,+ provider: ProviderDriverKind,+ options?: { readonly fresh?: boolean },+ ) {+ // Read the instance registry, not `liveSubsRef`: the latter trails+ // reconciliation, and an update must never run a retired instance's+ // command against a freshly configured executable.+ const instance = yield* instanceRegistry.getInstance(instanceId);+ if (!instance || instance.driverKind !== provider) {+ return makeManualProviderMaintenanceCapabilities(provider);+ }+ return yield* instance.snapshot.resolveMaintenance(options);});/**diff --git a/apps/server/src/provider/Services/ProviderRegistry.ts b/apps/server/src/provider/Services/ProviderRegistry.tsindex a1ea0c083ac..bd917834e97 100644--- a/apps/server/src/provider/Services/ProviderRegistry.ts+++ b/apps/server/src/provider/Services/ProviderRegistry.ts@@ -56,10 +56,12 @@ export interface ProviderRegistryShape {/*** Resolve the maintenance capabilities owned by one live provider instance.* Falls back to manual-only capabilities when the instance is not live.+ * `fresh` re-derives ownership from the executable instead of the cache.*/readonly getProviderMaintenanceCapabilitiesForInstance: (instanceId: ProviderInstanceId,provider: ProviderDriverKind,+ options?: { readonly fresh?: boolean },) => Effect.Effect<ProviderMaintenanceCapabilities>;/**diff --git a/apps/server/src/provider/Services/ServerProvider.ts b/apps/server/src/provider/Services/ServerProvider.tsindex 5d0486d87ca..dfea57cd93b 100644--- a/apps/server/src/provider/Services/ServerProvider.ts+++ b/apps/server/src/provider/Services/ServerProvider.ts@@ -4,7 +4,14 @@ import type * as Stream from "effect/Stream";import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";export interface ServerProviderShape {- readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;+ /**+ * Ownership-derived update capabilities. Cached between reads; pass+ * `{ fresh: true }` before executing an update so it never trusts a+ * resolution older than the click.+ */+ readonly resolveMaintenance: (options?: {+ readonly fresh?: boolean;+ }) => Effect.Effect<ProviderMaintenanceCapabilities>;readonly getSnapshot: Effect.Effect<ServerProvider>;readonly refresh: Effect.Effect<ServerProvider>;readonly streamChanges: Stream.Stream<ServerProvider>;diff --git a/apps/server/src/provider/makeManagedServerProvider.test.ts b/apps/server/src/provider/makeManagedServerProvider.test.tsindex aa0828e048c..292ef66ff2e 100644--- a/apps/server/src/provider/makeManagedServerProvider.test.ts+++ b/apps/server/src/provider/makeManagedServerProvider.test.ts@@ -158,7 +158,7 @@ describe("makeManagedServerProvider", () => {const checkCalls = yield* Ref.make(0);const releaseCheck = yield* Deferred.make<void>();const provider = yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -198,7 +198,7 @@ describe("makeManagedServerProvider", () => {const checkCalls = yield* Ref.make(0);const initialCheckDone = yield* Deferred.make<void>();yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -229,7 +229,7 @@ describe("makeManagedServerProvider", () => {const checkCalls = yield* Ref.make(0);const initialCheckDone = yield* Deferred.make<void>();yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -256,7 +256,7 @@ describe("makeManagedServerProvider", () => {const checkCalls = yield* Ref.make(0);const initialCheckDone = yield* Deferred.make<void>();const provider = yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -311,7 +311,7 @@ describe("makeManagedServerProvider", () => {const periodicCheckDone = yield* Deferred.make<void>();yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -353,7 +353,7 @@ describe("makeManagedServerProvider", () => {const releaseInitialCheck = yield* Deferred.make<void>();const releaseSettingsCheck = yield* Deferred.make<void>();const provider = yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Ref.get(settingsRef),streamSettings: Stream.fromPubSub(settingsChanges),haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -397,7 +397,7 @@ describe("makeManagedServerProvider", () => {const initialCheckDone = yield* Deferred.make<void>();const enrichmentCalls = yield* Ref.make(0);yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.fromPubSub(settingsChanges),haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -430,7 +430,7 @@ describe("makeManagedServerProvider", () => {const releaseEnrichment = yield* Deferred.make<void>();const releaseCheck = yield* Deferred.make<void>();const provider = yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -471,7 +471,7 @@ describe("makeManagedServerProvider", () => {const secondCallbackReady = yield* Deferred.make<void>();const allowFirstRefresh = yield* Deferred.make<void>();const provider = yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -527,7 +527,7 @@ describe("makeManagedServerProvider", () => {Effect.scoped(Effect.gen(function* () {const provider = yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,@@ -595,7 +595,7 @@ describe("makeManagedServerProvider", () => {windows: [{ id: "primary", kind: "session", label: "Session", usedPercent: 10 }],} as const;const provider = yield* makeManagedServerProvider<TestSettings>({- maintenanceCapabilities,+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),getSettings: Effect.succeed({ enabled: true }),streamSettings: Stream.empty,haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.tsindex ec3d26e6c87..c180412ec42 100644--- a/apps/server/src/provider/makeManagedServerProvider.ts+++ b/apps/server/src/provider/makeManagedServerProvider.ts@@ -39,7 +39,7 @@ function withUsageLimits(export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <Settings,>(input: {- readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];+ readonly resolveMaintenance: ServerProviderShape["resolveMaintenance"];readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;readonly streamSettings: Stream.Stream<Settings>;readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;@@ -283,7 +283,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")();return {- maintenanceCapabilities: input.maintenanceCapabilities,+ resolveMaintenance: input.resolveMaintenance,getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),applyUsageLimits,diff --git a/apps/server/src/provider/providerMaintenance.test.ts b/apps/server/src/provider/providerMaintenance.test.tsindex ac84b31d307..94fc376f227 100644--- a/apps/server/src/provider/providerMaintenance.test.ts+++ b/apps/server/src/provider/providerMaintenance.test.ts@@ -1,7 +1,7 @@// @effect-diagnostics nodeBuiltinImport:offimport { expect, it } from "@effect/vitest";-import * as NodeFS from "node:fs";import * as NodeChildProcess from "node:child_process";+import * as NodeFS from "node:fs";import * as NodeServices from "@effect/platform-node/NodeServices";import * as NodeOS from "node:os";import * as NodePath from "node:path";@@ -9,26 +9,31 @@ import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3import { HostProcessPlatform } from "@t3tools/shared/hostProcess";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";-import * as FileSystem from "effect/FileSystem";+import * as Sink from "effect/Sink";+import * as Stream from "effect/Stream";import { HttpClient } from "effect/unstable/http";+import { ChildProcessSpawner } from "effect/unstable/process";import {createProviderVersionAdvisory,enrichProviderSnapshotWithVersionAdvisory,+ homebrewOwnershipFromCommandPath,+ makeCachedProviderMaintenanceResolution,makePackageManagedProviderMaintenanceResolver,makeProviderMaintenanceCapabilities,- makeStaticProviderMaintenanceResolver,normalizeCommandPath,+ npmGlobalPrefixFromCommandPath,+ parseHomebrewLatestVersion,ProviderVersionCache,resolveLatestProviderVersion,resolveProviderMaintenanceCapabilitiesEffect,+ type ProviderMaintenanceCapabilities,} from "./providerMaintenance.ts";import { symlinksSupported } from "@t3tools/shared/testing/symlinks";const driver = (value: string) => ProviderDriverKind.make(value);-// These write `#!/bin/sh` stubs and resolve them through a darwin-mocked-// PATH walk; a Windows temp path cannot be split on `:`.+// These write `#!/bin/sh` stubs and evaluate them with darwin/linux path+// semantics; a Windows temp path cannot be split on `:`.const windowsHost = HostProcessPlatform.defaultValue() === "win32";-const makeTempDir = (name: string) =>Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4),@@ -41,40 +46,16 @@ const isNativeTestCommandPath =const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({provider: driver("packageTool"),npmPackageName: "@example/package-tool",- homebrewFormula: "package-tool",nativeUpdate: null,});const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({provider: driver("nativePackageTool"),npmPackageName: "@example/native-package-tool",- homebrewFormula: "native-package-tool",nativeUpdate: {- executable: "native-package-tool",args: ["update"],- lockKey: "native-package-tool-native",isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),},});-const scopedPackageToolUpdate = makePackageManagedProviderMaintenanceResolver({- provider: driver("scopedPackageTool"),- npmPackageName: "@example/scoped-package-tool",- homebrewFormula: "example/tap/scoped-package-tool",- nativeUpdate: {- executable: "scoped-package-tool",- args: ["upgrade"],- lockKey: "scoped-package-tool-native",- isCommandPath: isNativeTestCommandPath("/.scoped-package-tool/bin/scoped-package-tool"),- },-});-const staticToolUpdate = makeStaticProviderMaintenanceResolver(- makeProviderMaintenanceCapabilities({- provider: driver("staticTool"),- packageName: null,- updateExecutable: "static-tool",- updateArgs: ["update"],- updateLockKey: "static-tool",- }),-);const installedPackageToolProvider: ServerProvider = {instanceId: ProviderInstanceId.make("packageTool"),driver: driver("packageTool"),@@ -88,10 +69,59 @@ const installedPackageToolProvider: ServerProvider = {slashCommands: [],skills: [],};+const manualPackageTool: ProviderMaintenanceCapabilities = {+ provider: driver("packageTool"),+ packageName: "@example/package-tool",+ update: null,+};++function writeExecutable(path: string) {+ NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });+ NodeFS.writeFileSync(path, "#!/bin/sh\n");+ NodeFS.chmodSync(path, 0o755);+}++/** Symlink `<tempDir>/bin/<name>` into a package entry point, like npm/pnpm do. */+function linkIntoPackage(tempDir: string, name: string, packageSegments: ReadonlyArray<string>) {+ const target = NodePath.join(tempDir, ...packageSegments, "bin", `${name}.js`);+ writeExecutable(target);+ const link = NodePath.join(tempDir, "bin", name);+ NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });+ NodeFS.symlinkSync(target, link);+ return link;+}++const noSpawn = ChildProcessSpawner.make(() =>+ Effect.die("maintenance resolution should not spawn a process here"),+);++function stdoutSpawner(onSpawn: (command: string, args: ReadonlyArray<string>) => string) {+ return ChildProcessSpawner.make((command) => {+ const { command: executable, args } = command as unknown as {+ readonly command: string;+ readonly args: ReadonlyArray<string>;+ };+ return Effect.succeed(+ ChildProcessSpawner.makeHandle({+ pid: ChildProcessSpawner.ProcessId(1),+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),+ isRunning: Effect.succeed(false),+ kill: () => Effect.void,+ unref: Effect.succeed(Effect.void),+ stdin: Sink.drain,+ stdout: Stream.encodeText(Stream.make(onSpawn(executable, args))),+ stderr: Stream.empty,+ all: Stream.empty,+ getInputFd: () => Sink.drain,+ getOutputFd: () => Stream.empty,+ }),+ );+ });+}it.layer(NodeServices.layer)("providerMaintenance", (it) => {it.effect("reads cached versions through the injectable cache reference", () =>- resolveLatestProviderVersion(packageToolUpdate.resolve()).pipe(+ resolveLatestProviderVersion(manualPackageTool).pipe(Effect.provideService(ProviderVersionCache,new Map([@@ -116,14 +146,25 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {),);+ it.effect("prefers the installer's own latest version over the npm registry", () =>+ resolveLatestProviderVersion({ ...manualPackageTool, latestVersion: "1.2.0" }).pipe(+ Effect.provideService(ProviderVersionCache, new Map()),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make(() =>+ Effect.die("installer-reported latest should not make an HTTP request"),+ ),+ ),+ Effect.map((version) => {+ expect(version).toBe("1.2.0");+ }),+ ),+ );+it.effect("does not fetch latest provider versions when update checks are disabled", () =>- enrichProviderSnapshotWithVersionAdvisory(- installedPackageToolProvider,- packageToolUpdate.resolve(),- {- enableProviderUpdateChecks: false,- },- ).pipe(+ enrichProviderSnapshotWithVersionAdvisory(installedPackageToolProvider, manualPackageTool, {+ enableProviderUpdateChecks: false,+ }).pipe(Effect.provideService(ProviderVersionCache, new Map()),Effect.provideService(HttpClient.HttpClient,@@ -171,562 +212,525 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {});});- it("marks installed providers behind latest when a newer provider version is available", () => {+ it("keeps the manual update hint when the install is behind but unowned", () => {expect(createProviderVersionAdvisory({- driver: driver("nativePackageTool"),+ driver: driver("packageTool"),currentVersion: "2.1.110",latestVersion: "2.1.117",- maintenanceCapabilities: nativePackageToolUpdate.resolve(),+ maintenanceCapabilities: manualPackageTool,}),).toMatchObject({status: "behind_latest",- currentVersion: "2.1.110",latestVersion: "2.1.117",- updateCommand:- "npm install -g --allow-scripts=@example/native-package-tool @example/native-package-tool@latest",- canUpdate: true,+ updateCommand: null,+ canUpdate: false,message: "Install the update now or review provider settings.",});});- it("keeps update commands owned by provider maintenance capabilities", () => {- expect(staticToolUpdate.resolve()).toEqual({- provider: driver("staticTool"),- packageName: null,- update: {- command: "static-tool update",-- executable: "static-tool",-- args: ["update"],-- lockKey: "static-tool",- },- });- });+ it.effect("stays manual-only when the binary cannot be located", () =>+ resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {+ binaryPath: "package-tool",+ env: { PATH: "" },+ }).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),+ Effect.map((capabilities) => {+ expect(capabilities).toEqual(manualPackageTool);+ }),+ ),+ );- it.effect.skipIf(windowsHost)(- "switches package-managed providers to vite-plus updates when the resolved binary lives in vite-plus global bin",+ it.effect.skipIf(!symlinksSupported)(+ "pins npm updates to the global prefix that owns the package",() =>Effect.gen(function* () {- const tempDir = yield* makeTempDir("t3-vite-plus-capabilities");- const vitePlusBinDir = NodePath.join(tempDir, ".vite-plus", "bin");- NodeFS.mkdirSync(vitePlusBinDir, { recursive: true });- const packageToolPath = NodePath.join(vitePlusBinDir, "package-tool");- NodeFS.writeFileSync(packageToolPath, "#!/bin/sh\n");- NodeFS.chmodSync(packageToolPath, 0o755);+ const tempDir = yield* makeTempDir("t3-npm-capabilities");+ const link = linkIntoPackage(tempDir, "package-tool", [+ "lib",+ "node_modules",+ "@example",+ "package-tool",+ ]);const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate,{- binaryPath: "package-tool",- env: {- PATH: vitePlusBinDir,- },+ binaryPath: link,+ env: { PATH: "" },},- ).pipe(Effect.provideService(HostProcessPlatform, "darwin"));+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));expect(capabilities).toEqual({provider: driver("packageTool"),packageName: "@example/package-tool",update: {- command: "vp i -g @example/package-tool",-- executable: "vp",-- args: ["i", "-g", "@example/package-tool"],-- lockKey: "vite-plus-global",+ command: `npm install -g --prefix ${tempDir} --allow-scripts=@example/package-tool @example/package-tool@latest`,+ executable: "npm",+ args: [+ "install",+ "-g",+ "--prefix",+ tempDir,+ "--allow-scripts=@example/package-tool",+ "@example/package-tool@latest",+ ],+ lockKey: `npm-global:${normalizeCommandPath(tempDir)}`,},});}),);- it.effect(- "switches package-managed providers to bun updates when the resolved binary lives in bun's global bin",- () =>- Effect.gen(function* () {- const tempDir = yield* makeTempDir("t3-bun-capabilities");- const bunBinDir = NodePath.join(tempDir, ".bun", "bin");- NodeFS.mkdirSync(bunBinDir, { recursive: true });- NodeFS.writeFileSync(NodePath.join(bunBinDir, "native-package-tool.exe"), "MZ");-- const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(- nativePackageToolUpdate,- {- binaryPath: "native-package-tool",- env: {- PATH: bunBinDir,- PATHEXT: ".COM;.EXE;.BAT;.CMD",- },- },- ).pipe(Effect.provideService(HostProcessPlatform, "win32"));+ it("derives the npm prefix only from the global lib/node_modules layout", () => {+ expect(+ npmGlobalPrefixFromCommandPath(+ "/usr/local/lib/node_modules/@openai/codex/bin/codex.js",+ "@openai/codex",+ ),+ ).toBe("/usr/local");+ // A copy nested inside another package is not a global install.+ expect(+ npmGlobalPrefixFromCommandPath(+ "/usr/local/lib/node_modules/other/node_modules/@openai/codex/bin/codex.js",+ "@openai/codex",+ ),+ ).toBeNull();+ expect(+ npmGlobalPrefixFromCommandPath(+ "/lib/node_modules/@openai/codex/bin/codex.js",+ "@openai/codex",+ ),+ ).toBe("/");+ // Neither is a project-local dependency.+ expect(+ npmGlobalPrefixFromCommandPath(+ "/work/app/node_modules/@openai/codex/bin/codex.js",+ "@openai/codex",+ ),+ ).toBeNull();+ });- expect(capabilities).toEqual({- provider: driver("nativePackageTool"),- packageName: "@example/native-package-tool",- update: {- command: "bun i -g @example/native-package-tool@latest",+ it.effect("proves Windows npm ownership from the package manifest beside the shim", () =>+ Effect.gen(function* () {+ const tempDir = yield* makeTempDir("t3-npm-windows-capabilities");+ const shim = NodePath.join(tempDir, "package-tool.cmd");+ NodeFS.mkdirSync(tempDir, { recursive: true });+ NodeFS.writeFileSync(shim, "@echo off\r\n");+ NodeFS.mkdirSync(NodePath.join(tempDir, "node_modules", "@example", "package-tool"), {+ recursive: true,+ });+ NodeFS.writeFileSync(+ NodePath.join(tempDir, "node_modules", "@example", "package-tool", "package.json"),+ "{}",+ );- executable: "bun",+ const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {+ binaryPath: shim,+ env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },+ }).pipe(+ Effect.provideService(HostProcessPlatform, "win32"),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),+ );- args: ["i", "-g", "@example/native-package-tool@latest"],+ expect(capabilities.update).toMatchObject({+ executable: "npm",+ args: ["install", "-g", "--prefix", tempDir, expect.any(String), expect.any(String)],+ });- lockKey: "bun-global",- },- });- }),+ // The same layout on POSIX is a project checkout, not a global install.+ const script = NodePath.join(tempDir, "package-tool");+ writeExecutable(script);+ const posix = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {+ binaryPath: script,+ env: { PATH: "" },+ }).pipe(+ Effect.provideService(HostProcessPlatform, "linux"),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),+ );+ expect(posix.update).toBeNull();+ }),);- it.effect.skipIf(windowsHost)(- "switches package-managed providers to pnpm updates when the resolved binary lives in pnpm's global bin",+ it.effect.skipIf(!symlinksSupported)(+ "switches to pnpm updates when the real path lives in pnpm's global store",() =>Effect.gen(function* () {const tempDir = yield* makeTempDir("t3-pnpm-capabilities");- const pnpmHomeDir = NodePath.join(tempDir, ".local", "share", "pnpm");- NodeFS.mkdirSync(pnpmHomeDir, { recursive: true });- const scopedPackageToolPath = NodePath.join(pnpmHomeDir, "scoped-package-tool");- NodeFS.writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");- NodeFS.chmodSync(scopedPackageToolPath, 0o755);+ const link = linkIntoPackage(tempDir, "package-tool", [+ ".local",+ "share",+ "pnpm",+ "global",+ "5",+ "node_modules",+ "@example",+ "package-tool",+ ]);const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(- scopedPackageToolUpdate,+ packageToolUpdate,{- binaryPath: "scoped-package-tool",- env: {- PATH: pnpmHomeDir,- },+ binaryPath: link,+ env: { PATH: "" },},- ).pipe(Effect.provideService(HostProcessPlatform, "darwin"));+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));- expect(capabilities).toEqual({- provider: driver("scopedPackageTool"),- packageName: "@example/scoped-package-tool",- update: {- command: "pnpm add -g @example/scoped-package-tool@latest",-- executable: "pnpm",-- args: ["add", "-g", "@example/scoped-package-tool@latest"],-- lockKey: "pnpm-global",- },+ expect(capabilities.update).toMatchObject({+ command: "pnpm add -g @example/package-tool@latest",+ lockKey: "pnpm-global",});}),);- it("switches package-tool to Homebrew updates when the binary resolves through Homebrew", () => {- expect(- packageToolUpdate.resolve({- binaryPath: "/opt/homebrew/bin/package-tool",- env: {- PATH: "",- },- }),- ).toEqual({- provider: driver("packageTool"),- packageName: "@example/package-tool",- update: {- command: "brew upgrade package-tool",-- executable: "brew",-- args: ["upgrade", "package-tool"],-- lockKey: "homebrew",- },- });- });-it.effect.skipIf(windowsHost)(- "switches native-package-tool to native updates when the binary resolves through the native installer",+ "switches to bun updates when the resolved binary lives in bun's global bin",() =>Effect.gen(function* () {- const tempDir = yield* makeTempDir("t3-native-package-tool-native-capabilities");- const nativeBinDir = NodePath.join(tempDir, ".local", "bin");- NodeFS.mkdirSync(nativeBinDir, { recursive: true });- const nativePackageToolPath = NodePath.join(nativeBinDir, "native-package-tool");- NodeFS.writeFileSync(nativePackageToolPath, "#!/bin/sh\n");- NodeFS.chmodSync(nativePackageToolPath, 0o755);+ const tempDir = yield* makeTempDir("t3-bun-capabilities");+ const bunBinDir = NodePath.join(tempDir, ".bun", "bin");+ writeExecutable(NodePath.join(bunBinDir, "package-tool"));const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(- nativePackageToolUpdate,+ packageToolUpdate,{- binaryPath: "native-package-tool",- env: {- PATH: nativeBinDir,- },+ binaryPath: "package-tool",+ env: { PATH: bunBinDir },},- ).pipe(Effect.provideService(HostProcessPlatform, "darwin"));-- expect(capabilities).toEqual({- provider: driver("nativePackageTool"),- packageName: "@example/native-package-tool",- update: {- command: `${nativePackageToolPath} update`,-- executable: nativePackageToolPath,-- args: ["update"],+ ).pipe(+ Effect.provideService(HostProcessPlatform, "darwin"),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),+ );- lockKey: "native-package-tool-native",- },+ expect(capabilities.update).toMatchObject({+ command: "bun i -g @example/package-tool@latest",+ lockKey: "bun-global",});}),);- it.effect.skipIf(windowsHost)(- "switches scoped-package-tool to native upgrades when the binary resolves through the standalone installer",- () =>- Effect.gen(function* () {- const tempDir = yield* makeTempDir("t3-scoped-package-tool-native-capabilities");- const nativeBinDir = NodePath.join(tempDir, ".scoped-package-tool", "bin");- NodeFS.mkdirSync(nativeBinDir, { recursive: true });- const scopedPackageToolPath = NodePath.join(nativeBinDir, "scoped-package-tool");- NodeFS.writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");- NodeFS.chmodSync(scopedPackageToolPath, 0o755);-- const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(- scopedPackageToolUpdate,- {- binaryPath: "scoped-package-tool",- env: {- PATH: nativeBinDir,- },- },- ).pipe(Effect.provideService(HostProcessPlatform, "darwin"));-- expect(capabilities).toEqual({- provider: driver("scopedPackageTool"),- packageName: "@example/scoped-package-tool",- update: {- command: `${scopedPackageToolPath} upgrade`,-- executable: scopedPackageToolPath,+ it.effect.skipIf(windowsHost)("switches to native updates and runs the resolved executable", () =>+ Effect.gen(function* () {+ const tempDir = yield* makeTempDir("t3-native-capabilities");+ const nativeBinDir = NodePath.join(tempDir, ".local", "bin");+ const nativePath = NodePath.join(nativeBinDir, "native-package-tool");+ writeExecutable(nativePath);- args: ["upgrade"],+ const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(+ nativePackageToolUpdate,+ {+ binaryPath: "native-package-tool",+ env: { PATH: nativeBinDir },+ },+ ).pipe(+ Effect.provideService(HostProcessPlatform, "darwin"),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),+ );- lockKey: "scoped-package-tool-native",- },- });- }),+ expect(capabilities).toEqual({+ provider: driver("nativePackageTool"),+ packageName: "@example/native-package-tool",+ update: {+ command: `${nativePath} update`,+ executable: nativePath,+ args: ["update"],+ lockKey: "nativePackageTool-native",+ },+ });+ }),);+ // Regression for #9850: an explicit native path outside PATH, with spaces,+ // must be what actually gets spawned.it.effect.skipIf(windowsHost)("runs an explicit native updater outside PATH", () =>Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-native-update-" });- const nativeBinDir = NodePath.join(tempDir, "with spaces", ".scoped-package-tool", "bin");- yield* fs.makeDirectory(nativeBinDir, { recursive: true });- const binaryPath = NodePath.join(nativeBinDir, "scoped-package-tool");- yield* fs.writeFileString(binaryPath, "#!/bin/sh\nprintf '%s' \"$1\"\n");- yield* fs.chmod(binaryPath, 0o755);+ const tempDir = yield* makeTempDir("t3-native-update");+ const nativePath = NodePath.join(+ tempDir,+ "with spaces",+ ".local",+ "bin",+ "native-package-tool",+ );+ NodeFS.mkdirSync(NodePath.dirname(nativePath), { recursive: true });+ NodeFS.writeFileSync(nativePath, "#!/bin/sh\nprintf '%s' \"$1\"\n");+ NodeFS.chmodSync(nativePath, 0o755);const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(- scopedPackageToolUpdate,- { binaryPath, env: { PATH: "" } },+ nativePackageToolUpdate,+ { binaryPath: nativePath, env: { PATH: "" } },+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));++ expect(capabilities.update?.executable).toBe(nativePath);+ const result = NodeChildProcess.spawnSync(+ capabilities.update!.executable,+ capabilities.update!.args,+ { env: { PATH: "" }, encoding: "utf8" },);- const update = capabilities.update;- expect(update).not.toBeNull();- if (!update) return;- const result = NodeChildProcess.spawnSync(update.executable, update.args, {- env: { PATH: "" },- encoding: "utf8",- });- expect(result.error).toBeUndefined();expect(result.status).toBe(0);- expect(result.stdout).toBe("upgrade");- }).pipe(Effect.scoped),+ expect(result.stdout).toBe("update");+ }),);- it.each([- "/Users/example/.local/bin/native-package-tool",- "C:\\Users\\Example User\\.local\\bin\\native-package-tool.exe",- ])("preserves a configured native executable path: %s", (binaryPath) => {- expect(nativePackageToolUpdate.resolve({ binaryPath }).update?.executable).toBe(binaryPath);- });+ it.effect.skipIf(!symlinksSupported)(+ "prefers npm ownership over the Node keg the package lives under",+ () =>+ Effect.gen(function* () {+ // `brew install node` keeps npm globals inside the node keg.+ const tempDir = yield* makeTempDir("t3-homebrew-node-capabilities");+ const keg = NodePath.join(tempDir, "Cellar", "node", "22.1.0");+ const target = NodePath.join(+ keg,+ "lib",+ "node_modules",+ "@example",+ "package-tool",+ "bin",+ "package-tool.js",+ );+ writeExecutable(target);+ const link = NodePath.join(tempDir, "bin", "package-tool");+ NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });+ NodeFS.symlinkSync(target, link);- for (const directoryName of ["plain", "with spaces", "with 'quotes' and $dollars"]) {- it.effect.skipIf(windowsHost)(- `runs the copied native update command from a ${directoryName} path`,- () =>- Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-copy-native-update-" });- const binDir = NodePath.join(tempDir, directoryName, ".scoped-package-tool", "bin");- yield* fs.makeDirectory(binDir, { recursive: true });- const binaryPath = NodePath.join(binDir, "scoped-package-tool");- yield* fs.writeFileString(binaryPath, '#!/bin/sh\nprintf "%s" "$1"\n');- yield* fs.chmod(binaryPath, 0o755);-- const capabilities = scopedPackageToolUpdate.resolve({ binaryPath });- const advisory = createProviderVersionAdvisory({- driver: driver("scopedPackageTool"),- currentVersion: "1.0.0",- latestVersion: "2.0.0",- maintenanceCapabilities: capabilities,- });- expect(advisory.updateCommand).not.toBeNull();- if (!advisory.updateCommand) return;- const result = NodeChildProcess.spawnSync("/bin/sh", ["-c", advisory.updateCommand], {+ const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(+ packageToolUpdate,+ {+ binaryPath: link,env: { PATH: "" },- encoding: "utf8",- });- expect(result.error).toBeUndefined();- expect(result.status, result.stderr).toBe(0);- expect(result.stdout).toBe("upgrade");- }).pipe(Effect.scoped),- );- }-- it.each([- {- binaryPath: "C:\\Users\\Example\\.local\\bin\\native-package-tool.exe",- command: "C:\\Users\\Example\\.local\\bin\\native-package-tool.exe update",- },- {- binaryPath: "C:\\Users\\Example User\\.local\\bin\\native-package-tool.exe",- command: "& 'C:\\Users\\Example User\\.local\\bin\\native-package-tool.exe' update",- },- {- binaryPath: "C:\\Users\\O'Connor\\.local\\bin\\native-package-tool.exe",- command: "& 'C:\\Users\\O''Connor\\.local\\bin\\native-package-tool.exe' update",- },- {- binaryPath: "C:\\Users\\O\u2019Connor\\.local\\bin\\native-package-tool.exe",- command: "& 'C:\\Users\\O\u2019\u2019Connor\\.local\\bin\\native-package-tool.exe' update",- },- ])("formats a copied PowerShell native update for $binaryPath", ({ binaryPath, command }) => {- expect(nativePackageToolUpdate.resolve({ binaryPath, platform: "win32" }).update).toEqual({- command,- executable: binaryPath,- args: ["update"],- lockKey: "native-package-tool-native",- });- });+ },+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));- it.effect("uses the environment's platform for copied native update commands", () =>- Effect.gen(function* () {- const binaryPath = "C:\\Users\\Example User\\.local\\bin\\native-package-tool.exe";- const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(- nativePackageToolUpdate,- { binaryPath, env: { PATH: "" } },- );- expect(capabilities.update?.command).toBe(`& '${binaryPath}' update`);- expect(capabilities.update?.executable).toBe(binaryPath);- }).pipe(Effect.provideService(HostProcessPlatform, "win32")),+ expect(capabilities.update).toMatchObject({+ executable: "npm",+ args: expect.arrayContaining(["--prefix", keg]),+ lockKey: `npm-global:${normalizeCommandPath(keg)}`,+ });+ }),);- it("uses the resolved launcher when its symlink target identifies a native install", () => {- const launcher = "/custom tools/native-launcher";- const capabilities = nativePackageToolUpdate.resolve({- binaryPath: launcher,- resolvedCommandPath: launcher,- realCommandPath: "/Users/example/.local/bin/native-package-tool",+ it("quotes copyable command words the shell would split", () => {+ const posix = makeProviderMaintenanceCapabilities({+ provider: driver("packageTool"),+ packageName: "@example/package-tool",+ updateExecutable: "npm",+ updateArgs: [+ "install",+ "-g",+ "--prefix",+ "/Users/Jane Doe/.npm-global",+ "@example/package-tool@latest",+ ],+ updateLockKey: "npm-global",+ platform: "darwin",+ });+ expect(posix.update?.command).toBe(+ "npm install -g --prefix '/Users/Jane Doe/.npm-global' @example/package-tool@latest",+ );+ const windows = makeProviderMaintenanceCapabilities({+ provider: driver("packageTool"),+ packageName: null,+ updateExecutable: "C:\\Program Files\\Tool\\tool.exe",+ updateArgs: ["update"],+ updateLockKey: "tool",+ platform: "win32",});- expect(capabilities.update?.executable).toBe(launcher);+ expect(windows.update?.command).toBe("& 'C:\\Program Files\\Tool\\tool.exe' update");});- it("switches native-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {- expect(- nativePackageToolUpdate.resolve({- binaryPath: "/opt/homebrew/bin/native-package-tool",- env: {- PATH: "",+ it.effect.skipIf(windowsHost)("carries the native updater's environment into the action", () =>+ Effect.gen(function* () {+ const tempDir = yield* makeTempDir("t3-native-env");+ const nativePath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");+ writeExecutable(nativePath);+ const resolver = makePackageManagedProviderMaintenanceResolver({+ provider: driver("nativePackageTool"),+ npmPackageName: "@example/native-package-tool",+ nativeUpdate: {+ args: ["update"],+ isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),+ env: { TOOL_HOME: tempDir },},- }),- ).toEqual({- provider: driver("nativePackageTool"),- packageName: "@example/native-package-tool",- update: {- command: "brew upgrade native-package-tool",+ });- executable: "brew",+ const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(resolver, {+ binaryPath: nativePath,+ env: { PATH: "" },+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));- args: ["upgrade", "native-package-tool"],+ expect(capabilities.update?.env).toEqual({ TOOL_HOME: tempDir });+ }),+ );- lockKey: "homebrew",- },+ it("recognizes Homebrew kegs and casks from the real executable path", () => {+ expect(+ homebrewOwnershipFromCommandPath("/opt/homebrew/Cellar/claude-code@latest/2.1.0/bin/claude"),+ ).toEqual({ kind: "formula", name: "claude-code@latest", prefix: "/opt/homebrew" });+ expect(homebrewOwnershipFromCommandPath("/usr/local/Caskroom/codex/0.148.0/codex")).toEqual({+ kind: "cask",+ name: "codex",+ prefix: "/usr/local",+ });+ // A plain /usr/local/bin binary is not evidence of Homebrew (#8832).+ expect(homebrewOwnershipFromCommandPath("/usr/local/bin/codex")).toBeNull();+ // A keg elsewhere reports its prefix so the resolver can reject it against+ // `brew --prefix`.+ expect(homebrewOwnershipFromCommandPath("/srv/Cellar/claude/1.0.0/bin/claude")).toMatchObject({+ prefix: "/srv",});});- it("switches scoped-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {- expect(- scopedPackageToolUpdate.resolve({- binaryPath: "/opt/homebrew/bin/scoped-package-tool",- env: {- PATH: "",- },- }),- ).toEqual({- provider: driver("scopedPackageTool"),- packageName: "@example/scoped-package-tool",- update: {- command: "brew upgrade example/tap/scoped-package-tool",-- executable: "brew",+ it.effect.skipIf(windowsHost)(+ "stays manual-only for an explicit binary path that does not exist",+ () =>+ Effect.gen(function* () {+ const tempDir = yield* makeTempDir("t3-missing-native-capabilities");+ const missingPath = NodePath.join(tempDir, ".local", "bin", "native-package-tool");- args: ["upgrade", "example/tap/scoped-package-tool"],+ const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(+ nativePackageToolUpdate,+ { binaryPath: missingPath, env: { PATH: "" } },+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));- lockKey: "homebrew",- },- });- });+ expect(capabilities.update).toBeNull();+ }),+ );it.effect.skipIf(!symlinksSupported)(- "keeps npm updates for binaries symlinked into npm's global node_modules tree",+ "upgrades the Homebrew cask that owns the binary and compares against its version",() =>Effect.gen(function* () {- const tempDir = yield* makeTempDir("t3-npm-capabilities");- const binDir = NodePath.join(tempDir, "bin");- const packageBinDir = NodePath.join(+ const tempDir = yield* makeTempDir("t3-homebrew-capabilities");+ const brewBinDir = NodePath.join(tempDir, "brew-bin");+ const brewPath = NodePath.join(brewBinDir, "brew");+ writeExecutable(brewPath);+ const caskBinary = NodePath.join(tempDir,- "lib",- "node_modules",- "@example",+ "Caskroom",+ "package-tool",+ "0.148.0","package-tool",- "bin",);- NodeFS.mkdirSync(binDir, { recursive: true });- NodeFS.mkdirSync(packageBinDir, { recursive: true });- const packageBinPath = NodePath.join(packageBinDir, "package-tool.js");- const symlinkPath = NodePath.join(binDir, "package-tool");- NodeFS.writeFileSync(packageBinPath, "#!/usr/bin/env node\n");- NodeFS.chmodSync(packageBinPath, 0o755);- NodeFS.symlinkSync(packageBinPath, symlinkPath);+ writeExecutable(caskBinary);+ const link = NodePath.join(tempDir, "bin", "package-tool");+ NodeFS.mkdirSync(NodePath.dirname(link), { recursive: true });+ NodeFS.symlinkSync(caskBinary, link);+ const spawned: Array<ReadonlyArray<string>> = [];const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate,{- binaryPath: symlinkPath,- env: {- PATH: "",- },+ binaryPath: link,+ env: { PATH: brewBinDir },},+ ).pipe(+ Effect.provideService(HostProcessPlatform, "darwin"),+ Effect.provideService(+ ChildProcessSpawner.ChildProcessSpawner,+ stdoutSpawner((command, args) => {+ spawned.push([command, ...args]);+ return args[0] === "--prefix"+ ? `${tempDir}\n`+ : JSON.stringify({ casks: [{ version: "0.148.0,42" }] });+ }),+ ),);+ expect(spawned).toEqual([+ [brewPath, "--prefix"],+ [brewPath, "info", "--json=v2", "package-tool"],+ ]);expect(capabilities).toEqual({provider: driver("packageTool"),packageName: "@example/package-tool",+ latestVersion: "0.148.0",update: {- command:- "npm install -g --allow-scripts=@example/package-tool @example/package-tool@latest",-- executable: "npm",-- args: [- "install",- "-g",- "--allow-scripts=@example/package-tool",- "@example/package-tool@latest",- ],-- lockKey: "npm-global",+ command: "brew upgrade --cask package-tool",+ executable: brewPath,+ args: ["upgrade", "--cask", "package-tool"],+ lockKey: "homebrew",},});}),);- it.effect.skipIf(!symlinksSupported)(- "uses Effect FileSystem realPath when detecting pnpm global symlinks",+ it.effect.skipIf(windowsHost)(+ "stays manual-only when the keg is not under the resolved brew's prefix",() =>Effect.gen(function* () {- const tempDir = yield* makeTempDir("t3-pnpm-realpath-capabilities");- const binDir = NodePath.join(tempDir, "bin");- const packageBinDir = NodePath.join(+ const tempDir = yield* makeTempDir("t3-homebrew-foreign-prefix");+ const brewBinDir = NodePath.join(tempDir, "brew-bin");+ writeExecutable(NodePath.join(brewBinDir, "brew"));+ const kegBinary = NodePath.join(tempDir,- ".local",- "share",- "pnpm",- "global",- "5",- "node_modules",- "@example",+ "elsewhere",+ "Cellar","package-tool",+ "1.0.0","bin",+ "package-tool",);- NodeFS.mkdirSync(binDir, { recursive: true });- NodeFS.mkdirSync(packageBinDir, { recursive: true });- const packageBinPath = NodePath.join(packageBinDir, "package-tool.js");- const symlinkPath = NodePath.join(binDir, "package-tool");- NodeFS.writeFileSync(packageBinPath, "#!/usr/bin/env node\n");- NodeFS.chmodSync(packageBinPath, 0o755);- NodeFS.symlinkSync(packageBinPath, symlinkPath);+ writeExecutable(kegBinary);const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate,{- binaryPath: symlinkPath,- env: {- PATH: "",- },+ binaryPath: kegBinary,+ env: { PATH: brewBinDir },},+ ).pipe(+ Effect.provideService(HostProcessPlatform, "darwin"),+ Effect.provideService(+ ChildProcessSpawner.ChildProcessSpawner,+ stdoutSpawner(() => "/opt/homebrew\n"),+ ),);- expect(capabilities).toEqual({- provider: driver("packageTool"),- packageName: "@example/package-tool",- update: {- command: "pnpm add -g @example/package-tool@latest",-- executable: "pnpm",-- args: ["add", "-g", "@example/package-tool@latest"],-- lockKey: "pnpm-global",- },- });+ expect(capabilities).toEqual(manualPackageTool);}),);- it("allows the package's own install scripts in npm global updates", () => {- const claudeUpdate = makePackageManagedProviderMaintenanceResolver({- provider: driver("claudeAgent"),- npmPackageName: "@anthropic-ai/claude-code",- homebrewFormula: "claude-code",- nativeUpdate: {- executable: "claude",- args: ["update"],- lockKey: "claude-native",- isCommandPath: isNativeTestCommandPath("/.local/bin/claude"),- },- });-- expect(claudeUpdate.resolve()).toEqual({- provider: driver("claudeAgent"),- packageName: "@anthropic-ai/claude-code",- update: {- command:- "npm install -g --allow-scripts=@anthropic-ai/claude-code @anthropic-ai/claude-code@latest",-- executable: "npm",+ it("reads the stable formula version from brew info", () => {+ const info = JSON.stringify({ formulae: [{ versions: { stable: "2.1.5" } }] });+ const formula = { kind: "formula", name: "claude-code", prefix: "/opt/homebrew" } as const;+ expect(parseHomebrewLatestVersion(info, formula)).toBe("2.1.5");+ expect(parseHomebrewLatestVersion("not json", formula)).toBeNull();+ });- args: [- "install",- "-g",- "--allow-scripts=@anthropic-ai/claude-code",- "@anthropic-ai/claude-code@latest",- ],+ it.effect.skipIf(windowsHost)(+ "disables one-click updates for explicit custom binary paths it cannot safely map",+ () =>+ Effect.gen(function* () {+ const tempDir = yield* makeTempDir("t3-custom-capabilities");+ const customPath = NodePath.join(tempDir, "tools", "package-tool");+ writeExecutable(customPath);- lockKey: "npm-global",- },- });- });+ const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(+ packageToolUpdate,+ {+ binaryPath: customPath,+ env: { PATH: "" },+ },+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn));- it("disables one-click updates for explicit custom binary paths it cannot safely map", () => {- expect(- packageToolUpdate.resolve({- binaryPath: "C:\\Tools\\package-tool\\package-tool.exe",- env: {- PATH: "",- PATHEXT: ".COM;.EXE;.BAT;.CMD",- },+ expect(capabilities).toEqual(manualPackageTool);}),- ).toEqual({- provider: driver("packageTool"),- packageName: "@example/package-tool",- update: null,- });- });+ );++ it.effect("caches resolution until a fresh read is requested", () =>+ Effect.gen(function* () {+ let resolutions = 0;+ const resolve = yield* makeCachedProviderMaintenanceResolution(+ Effect.sync(() => {+ resolutions += 1;+ return manualPackageTool;+ }),+ );+ yield* resolve();+ yield* resolve();+ expect(resolutions).toBe(1);+ yield* resolve({ fresh: true });+ yield* resolve();+ expect(resolutions).toBe(2);+ }),+ );});diff --git a/apps/server/src/provider/providerMaintenance.ts b/apps/server/src/provider/providerMaintenance.tsindex 2a28c381bf5..a09c94b61f6 100644--- a/apps/server/src/provider/providerMaintenance.ts+++ b/apps/server/src/provider/providerMaintenance.ts@@ -4,21 +4,37 @@ import {type ServerProviderVersionAdvisory,} from "@t3tools/contracts";import { compareSemverVersions } from "@t3tools/shared/semver";-import { resolveCommandPath } from "@t3tools/shared/shell";import { HostProcessPlatform } from "@t3tools/shared/hostProcess";+import { causeErrorTag } from "@t3tools/shared/observability";+import { resolveCommandPath } from "@t3tools/shared/shell";import * as Config from "effect/Config";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Option from "effect/Option";+import * as Path from "effect/Path";import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";import { HttpClient, HttpClientRequest } from "effect/unstable/http";+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";++import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;const LATEST_VERSION_TIMEOUT_MS = 4_000;+const HOMEBREW_INFO_TIMEOUT_MS = 10_000;+const HOMEBREW_INFO_MAX_BYTES = 256 * 1_024;const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";+/**+ * Ownership is re-derived from the executable this often. Installs do not+ * move on their own, so this mostly bounds how stale a Homebrew "latest" can+ * get; the npm registry check keeps its own cache.+ */+export const MAINTENANCE_CAPABILITIES_CACHE_TTL = Duration.hours(1);+const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>Object.fromEntries(Object.entries(input).flatMap(([key, value]) =>@@ -42,6 +58,13 @@ export interface ProviderMaintenanceCapabilities {readonly provider: ProviderDriverKind;readonly packageName: string | null;readonly update: ProviderMaintenanceCommandAction | null;+ /**+ * Latest version reported by the installer that owns the executable.+ * `undefined` means the installer has no channel of its own and the npm+ * registry entry for `packageName` is authoritative; `null` means the+ * installer was asked and did not know.+ */+ readonly latestVersion?: string | null;}export interface ProviderMaintenanceCommandAction {@@ -49,31 +72,44 @@ export interface ProviderMaintenanceCommandAction {readonly executable: string;readonly args: ReadonlyArray<string>;readonly lockKey: string;+ /**+ * Extra environment for the spawned updater, on top of the server's own.+ * A native updater finds its install through the same variables the+ * provider runs with (e.g. `CODEX_HOME`), so an instance with a custom home+ * must update that home and not the default one.+ */+ readonly env?: NodeJS.ProcessEnv;}-export interface ProviderMaintenanceCapabilityResolutionOptions {- readonly binaryPath?: string | null;- readonly platform?: NodeJS.Platform;- readonly env?: NodeJS.ProcessEnv;- readonly resolvedCommandPath?: string | null;- readonly realCommandPath?: string | null;+/** Where the provider executable was found; every path is absolute. */+export interface ProviderMaintenanceResolutionContext {+ readonly binaryPath: string;+ readonly resolvedCommandPath: string;+ readonly realCommandPath: string;+ readonly env: NodeJS.ProcessEnv;+ /** Host platform; decides how the copyable command quotes the executable. */+ readonly platform: NodeJS.Platform;}+export type ProviderMaintenanceResolverServices =+ | FileSystem.FileSystem+ | Path.Path+ | ChildProcessSpawner.ChildProcessSpawner;+export interface ProviderMaintenanceCapabilitiesResolver {readonly resolve: (- options?: ProviderMaintenanceCapabilityResolutionOptions,- ) => ProviderMaintenanceCapabilities;+ context: ProviderMaintenanceResolutionContext | null,+ ) => Effect.Effect<ProviderMaintenanceCapabilities, never, ProviderMaintenanceResolverServices>;}export interface PackageManagedProviderMaintenanceDefinition {readonly provider: ProviderDriverKind;readonly npmPackageName: string;- readonly homebrewFormula: string | null;readonly nativeUpdate: {- readonly executable: string;readonly args: ReadonlyArray<string>;- readonly lockKey: string;readonly isCommandPath: (commandPath: string) => boolean;+ /** Environment the native updater needs to target this instance's install. */+ readonly env?: NodeJS.ProcessEnv;} | null;}@@ -96,13 +132,22 @@ function nonEmptyString(value: unknown): string | null {return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;}+/**+ * The copyable command must paste into a shell as-is, so an executable path+ * with spaces or quotes is quoted for the host's default shell.+ */+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("'", "'\\''")}'`;+}+function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string {- const safePath = platform === "win32" ? /^[\w./:\\-]+$/ : /^[\w./:-]+$/;- if (safePath.test(executable)) return executable;+ const quoted = quoteShellWord(executable, platform);// Windows terminals default to PowerShell, where a quoted executable needs &.- return platform === "win32"- ? `& '${executable.replace(/['\u2018\u2019]/g, "$&$&")}'`- : `'${executable.replaceAll("'", "'\\''")}'`;+ return platform === "win32" && quoted !== executable ? `& ${quoted}` : quoted;}export function makeProviderMaintenanceCapabilities(input: {@@ -111,27 +156,33 @@ export function makeProviderMaintenanceCapabilities(input: {readonly updateExecutable: string | null;readonly updateArgs: ReadonlyArray<string>;readonly updateLockKey: string | null;+ /** Shown to the user instead of `<executable> <args>`; use for a bare tool name like `brew`. */+ readonly updateCommand?: string;readonly platform?: NodeJS.Platform;+ readonly env?: NodeJS.ProcessEnv;+ readonly latestVersion?: string | null;}): ProviderMaintenanceCapabilities {+ const platform = input.platform ?? HostProcessPlatform.defaultValue();const update =input.updateExecutable === null || input.updateLockKey === null? null: {- command: [- quoteUpdateExecutable(- input.updateExecutable,- input.platform ?? HostProcessPlatform.defaultValue(),- ),- ...input.updateArgs,- ].join(" "),+ command:+ input.updateCommand ??+ [+ quoteUpdateExecutable(input.updateExecutable, platform),+ ...input.updateArgs.map((arg) => quoteShellWord(arg, platform)),+ ].join(" "),executable: input.updateExecutable,args: input.updateArgs,lockKey: input.updateLockKey,+ ...(input.env ? { env: input.env } : {}),};return {provider: input.provider,packageName: input.packageName,update,+ ...("latestVersion" in input ? { latestVersion: input.latestVersion } : {}),};}@@ -148,118 +199,18 @@ export function makeManualOnlyProviderMaintenanceCapabilities(input: {});}-function makeNpmGlobalProviderMaintenanceCapabilities(- definition: PackageManagedProviderMaintenanceDefinition,-): ProviderMaintenanceCapabilities {- return makeProviderMaintenanceCapabilities({- provider: definition.provider,- packageName: definition.npmPackageName,- updateExecutable: "npm",- // npm 12 blocks install scripts by default (empty allow-scripts allowlist)- // and still exits 0, so a package whose postinstall finishes the install- // (claude copies its native binary over a placeholder stub) is left broken- // while the update reports success. Allow this one package's scripts.- // Older npm warns about the unknown config and continues.- updateArgs: [- "install",- "-g",- `--allow-scripts=${definition.npmPackageName}`,- `${definition.npmPackageName}@latest`,- ],- updateLockKey: "npm-global",- });-}--function makeBunGlobalProviderMaintenanceCapabilities(- definition: PackageManagedProviderMaintenanceDefinition,-): ProviderMaintenanceCapabilities {- return makeProviderMaintenanceCapabilities({- provider: definition.provider,- packageName: definition.npmPackageName,- updateExecutable: "bun",- updateArgs: ["i", "-g", `${definition.npmPackageName}@latest`],- updateLockKey: "bun-global",- });-}--function makePnpmGlobalProviderMaintenanceCapabilities(- definition: PackageManagedProviderMaintenanceDefinition,-): ProviderMaintenanceCapabilities {- return makeProviderMaintenanceCapabilities({- provider: definition.provider,- packageName: definition.npmPackageName,- updateExecutable: "pnpm",- updateArgs: ["add", "-g", `${definition.npmPackageName}@latest`],- updateLockKey: "pnpm-global",- });-}--function makeVitePlusGlobalProviderMaintenanceCapabilities(- definition: PackageManagedProviderMaintenanceDefinition,-): ProviderMaintenanceCapabilities {- return makeProviderMaintenanceCapabilities({- provider: definition.provider,- packageName: definition.npmPackageName,- updateExecutable: "vp",- updateArgs: ["i", "-g", definition.npmPackageName],- updateLockKey: "vite-plus-global",- });-}--function makeHomebrewProviderMaintenanceCapabilities(- definition: PackageManagedProviderMaintenanceDefinition,-): ProviderMaintenanceCapabilities {- if (!definition.homebrewFormula) {- return makeManualOnlyProviderMaintenanceCapabilities({- provider: definition.provider,- packageName: definition.npmPackageName,- });- }-- return makeProviderMaintenanceCapabilities({- provider: definition.provider,- packageName: definition.npmPackageName,- updateExecutable: "brew",- updateArgs: ["upgrade", definition.homebrewFormula],- updateLockKey: "homebrew",- });-}--function makeNativeProviderMaintenanceCapabilities(- definition: PackageManagedProviderMaintenanceDefinition,- commandPath: string,- platform: NodeJS.Platform,-): ProviderMaintenanceCapabilities | null {- if (!definition.nativeUpdate) {- return null;- }-- return makeProviderMaintenanceCapabilities({- provider: definition.provider,- packageName: definition.npmPackageName,- updateExecutable: commandPath,- updateArgs: definition.nativeUpdate.args,- updateLockKey: definition.nativeUpdate.lockKey,- platform,- });-}--export function hasPathSeparator(value: string): boolean {- return value.includes("/") || value.includes("\\");-}-export function normalizeCommandPath(commandPath: string): string {return commandPath.replaceAll("\\", "/").toLowerCase();}-function isBunGlobalCommandPath(commandPath: string): boolean {- return normalizeCommandPath(commandPath).includes("/.bun/bin/");-}-function isVitePlusGlobalCommandPath(commandPath: string): boolean {return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");}+function isBunGlobalCommandPath(commandPath: string): boolean {+ return normalizeCommandPath(commandPath).includes("/.bun/bin/");+}+function isPnpmGlobalCommandPath(commandPath: string): boolean {const normalized = normalizeCommandPath(commandPath);return (@@ -271,100 +222,287 @@ function isPnpmGlobalCommandPath(commandPath: string): boolean {);}-function isNpmGlobalCommandPath(commandPath: string): boolean {- const normalized = normalizeCommandPath(commandPath);- return (- normalized.includes("/node_modules/.bin/") ||- normalized.includes("/lib/node_modules/") ||- normalized.includes("/npm/node_modules/")- );+/**+ * The npm global prefix that owns a package, derived from the real path of+ * its entry point: `<prefix>/lib/node_modules/<pkg>/…`. Windows global+ * installs have no `lib` segment and are proven by the shim instead (see+ * `resolveNpmGlobalPrefix`). A project-local `node_modules` is not a global+ * install and yields null.+ */+export function npmGlobalPrefixFromCommandPath(+ realCommandPath: string,+ packageName: string,+): string | null {+ const slashPath = realCommandPath.replaceAll("\\", "/");+ const normalized = slashPath.toLowerCase();+ const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`;+ const packageIndex = normalized.lastIndexOf(packageSegment);+ if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) {+ return null;+ }+ return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex);}-function isHomebrewCommandPath(commandPath: string): boolean {- const normalized = normalizeCommandPath(commandPath);- return (- normalized.includes("/opt/homebrew/cellar/") ||- normalized.includes("/usr/local/cellar/") ||- normalized.includes("/homebrew/cellar/") ||- normalized.includes("/opt/homebrew/caskroom/") ||- normalized.includes("/usr/local/caskroom/") ||- normalized.includes("/homebrew/caskroom/") ||- normalized.startsWith("/opt/homebrew/bin/") ||- normalized.startsWith("/usr/local/bin/")- );+// `<prefix>/Cellar/<name>/<version>/…` or `<prefix>/Caskroom/<name>/<version>/…`.+// Homebrew always nests a version directory under the keg.+const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i;++export interface HomebrewOwnership {+ readonly kind: "formula" | "cask";+ readonly name: string;+ /** The Homebrew prefix the keg sits under; must match `brew --prefix`. */+ readonly prefix: string;+}++/**+ * Homebrew looks like the owner when the real path runs through a versioned+ * keg or cask. It is only proven once the prefix matches the `brew` that will+ * run the upgrade (see `resolvePackageManagedProviderMaintenance`).+ */+export function homebrewOwnershipFromCommandPath(+ realCommandPath: string,+): HomebrewOwnership | null {+ const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));+ if (!match) {+ return null;+ }+ return {+ kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask",+ name: match[3]!,+ prefix: match[1]!,+ };}-export function resolvePackageManagedProviderMaintenance(+const HomebrewInfoResponse = Schema.Struct({+ formulae: Schema.optional(+ Schema.Array(+ Schema.Struct({+ versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })),+ }),+ ),+ ),+ casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))),+});++const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse));++/** Cask versions may carry a build suffix after a comma (`1.2.3,456`). */+export function parseHomebrewLatestVersion(+ infoJson: string,+ ownership: HomebrewOwnership,+): string | null {+ const decoded = decodeHomebrewInfo(infoJson);+ if (Option.isNone(decoded)) {+ return null;+ }+ const raw =+ ownership.kind === "formula"+ ? decoded.value.formulae?.[0]?.versions?.stable+ : decoded.value.casks?.[0]?.version?.split(",", 1)[0];+ return nonEmptyString(raw);+}++/** Run `brew <args>` and return stdout, or null on failure, timeout, or oversized output. */+const runHomebrew = Effect.fn("runHomebrew")(function* (+ brewPath: string,+ args: ReadonlyArray<string>,+ env: NodeJS.ProcessEnv,+) {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const collect = Effect.gen(function* () {+ const child = yield* spawner.spawn(ChildProcess.make(brewPath, args, { env, extendEnv: true }));+ yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));+ // stderr is drained so a chatty brew cannot block on a full pipe.+ const [stdout, exitCode] = yield* Effect.all(+ [+ collectUint8StreamText({ stream: child.stdout, maxBytes: HOMEBREW_INFO_MAX_BYTES }),+ child.exitCode,+ Stream.runDrain(child.stderr),+ ],+ { concurrency: "unbounded" },+ );+ return Number(exitCode) !== 0 || stdout.truncated ? null : stdout.text;+ });+ return yield* collect.pipe(+ Effect.scoped,+ Effect.timeoutOption(Duration.millis(HOMEBREW_INFO_TIMEOUT_MS)),+ Effect.map(Option.getOrNull),+ Effect.catchCause((cause) =>+ Effect.logWarning("Homebrew probe failed", {+ subcommand: args[0],+ errorTag: causeErrorTag(cause),+ }).pipe(Effect.as(null)),+ ),+ );+});++/**+ * Derive update capabilities from where the executable actually lives. Every+ * branch that yields a one-click command has evidence that the named tool+ * owns that path; anything unproven stays manual-only so T3 Code never runs+ * a package manager against an install it did not create.+ */+export const resolvePackageManagedProviderMaintenance = Effect.fn(+ "resolvePackageManagedProviderMaintenance",+)(function* (definition: PackageManagedProviderMaintenanceDefinition,- options?: ProviderMaintenanceCapabilityResolutionOptions,-): ProviderMaintenanceCapabilities {- const binaryPath = nonEmptyString(options?.binaryPath);- if (!binaryPath) {- return makeNpmGlobalProviderMaintenanceCapabilities(definition);+ context: ProviderMaintenanceResolutionContext | null,+) {+ const manual = makeManualOnlyProviderMaintenanceCapabilities({+ provider: definition.provider,+ packageName: definition.npmPackageName,+ });+ if (!context) {+ return manual;}+ const commandPaths = [context.resolvedCommandPath, context.realCommandPath];+ const packageName = definition.npmPackageName;- const resolvedCommandPath =- options?.resolvedCommandPath ?? (hasPathSeparator(binaryPath) ? binaryPath : null);+ const nativeUpdate = definition.nativeUpdate;+ if (nativeUpdate && commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))) {+ return makeProviderMaintenanceCapabilities({+ provider: definition.provider,+ packageName,+ updateExecutable: context.resolvedCommandPath,+ updateArgs: nativeUpdate.args,+ updateLockKey: `${definition.provider}-native`,+ platform: context.platform,+ ...(nativeUpdate.env ? { env: nativeUpdate.env } : {}),+ });+ }+ if (commandPaths.some(isVitePlusGlobalCommandPath)) {+ return makeProviderMaintenanceCapabilities({+ provider: definition.provider,+ packageName,+ updateExecutable: "vp",+ updateArgs: ["i", "-g", packageName],+ updateLockKey: "vite-plus-global",+ });+ }+ if (commandPaths.some(isBunGlobalCommandPath)) {+ return makeProviderMaintenanceCapabilities({+ provider: definition.provider,+ packageName,+ updateExecutable: "bun",+ updateArgs: ["i", "-g", `${packageName}@latest`],+ updateLockKey: "bun-global",+ });+ }+ if (commandPaths.some(isPnpmGlobalCommandPath)) {+ return makeProviderMaintenanceCapabilities({+ provider: definition.provider,+ packageName,+ updateExecutable: "pnpm",+ updateArgs: ["add", "-g", `${packageName}@latest`],+ updateLockKey: "pnpm-global",+ });+ }- if (resolvedCommandPath) {- const commandPaths = [- resolvedCommandPath,- ...(options?.realCommandPath ? [options.realCommandPath] : []),- ];+ // npm proof names the package, so it outranks a keg the path merely passes+ // through: a Homebrew-installed Node keeps its globals under+ // `Cellar/node/<ver>/lib/node_modules/`, and that is npm's install, not brew's.+ const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);+ if (npmPrefix) {+ // npm 12 blocks install scripts by default (empty allow-scripts allowlist)+ // and still exits 0, so a package whose postinstall finishes the install+ // (claude copies its native binary over a placeholder stub) is left broken+ // while the update reports success. Allow this one package's scripts.+ // Older npm warns about the unknown config and continues.+ return makeProviderMaintenanceCapabilities({+ provider: definition.provider,+ packageName,+ updateExecutable: "npm",+ updateArgs: [+ "install",+ "-g",+ "--prefix",+ npmPrefix,+ `--allow-scripts=${packageName}`,+ `${packageName}@latest`,+ ],+ updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,+ });+ }- const nativeUpdate = definition.nativeUpdate;+ const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);+ if (homebrew) {+ const brewPath = yield* resolveCommandPath("brew", { env: context.env }).pipe(+ Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),+ );+ if (!brewPath) {+ return manual;+ }+ // A keg-shaped path is only Homebrew's if it sits under the prefix of the+ // `brew` that would upgrade it; `brew --prefix` is a cheap shell script.+ const fileSystem = yield* FileSystem.FileSystem;+ const brewPrefix = nonEmptyString(yield* runHomebrew(brewPath, ["--prefix"], context.env));+ const realBrewPrefix = brewPrefix+ ? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))+ : null;if (- nativeUpdate &&- commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))+ !realBrewPrefix ||+ normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)) {- return (- makeNativeProviderMaintenanceCapabilities(- definition,- resolvedCommandPath,- options?.platform ?? HostProcessPlatform.defaultValue(),- ) ?? makeNpmGlobalProviderMaintenanceCapabilities(definition)- );- }- if (commandPaths.some(isVitePlusGlobalCommandPath)) {- return makeVitePlusGlobalProviderMaintenanceCapabilities(definition);- }- if (commandPaths.some(isBunGlobalCommandPath)) {- return makeBunGlobalProviderMaintenanceCapabilities(definition);- }- if (commandPaths.some(isPnpmGlobalCommandPath)) {- return makePnpmGlobalProviderMaintenanceCapabilities(definition);- }- if (commandPaths.some(isNpmGlobalCommandPath)) {- return makeNpmGlobalProviderMaintenanceCapabilities(definition);- }- if (commandPaths.some(isHomebrewCommandPath)) {- return makeHomebrewProviderMaintenanceCapabilities(definition);+ return manual;}+ const args =+ homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];+ // Homebrew lags npm by hours on every release, so compare against what+ // `brew upgrade` can actually deliver.+ const info = yield* runHomebrew(brewPath, ["info", "--json=v2", homebrew.name], context.env);+ return makeProviderMaintenanceCapabilities({+ provider: definition.provider,+ packageName,+ updateExecutable: brewPath,+ updateArgs: args,+ updateLockKey: "homebrew",+ updateCommand: ["brew", ...args].join(" "),+ latestVersion: info ? parseHomebrewLatestVersion(info, homebrew) : null,+ });}- if (!hasPathSeparator(binaryPath)) {- return makeNpmGlobalProviderMaintenanceCapabilities(definition);- }+ return manual;+});- return makeManualOnlyProviderMaintenanceCapabilities({- provider: definition.provider,- packageName: definition.npmPackageName,- });-}+/**+ * POSIX npm links `<prefix>/bin/<cmd>` into the package, so the real path is+ * proof. Windows npm writes `.cmd` shims beside `node_modules`, so the proof+ * is the package manifest next to the shim.+ */+const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (+ context: ProviderMaintenanceResolutionContext,+ packageName: string,+) {+ const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);+ if (fromRealPath) {+ return fromRealPath;+ }+ if ((yield* HostProcessPlatform) !== "win32") {+ return null;+ }+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const shimDir = path.dirname(context.resolvedCommandPath);+ const manifestPath = path.join(+ shimDir,+ "node_modules",+ ...packageName.split("/"),+ "package.json",+ );+ // npm writes both `<cmd>.cmd` and an extensionless sh script into the+ // Windows prefix; either one sits directly beside `node_modules`. A POSIX+ // project checkout has the same shape, which is why this is Windows-only.+ const hasManifest = yield* fileSystem+ .exists(manifestPath)+ .pipe(Effect.orElseSucceed(() => false));+ return hasManifest ? shimDir : null;+});export function makePackageManagedProviderMaintenanceResolver(definition: PackageManagedProviderMaintenanceDefinition,): ProviderMaintenanceCapabilitiesResolver {return {- resolve: (options) => resolvePackageManagedProviderMaintenance(definition, options),- };-}--export function makeStaticProviderMaintenanceResolver(- capabilities: ProviderMaintenanceCapabilities,-): ProviderMaintenanceCapabilitiesResolver {- return {- resolve: () => capabilities,+ resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),};}@@ -377,40 +515,68 @@ function makeManualProviderMaintenanceCapabilities(});}+/**+ * Locate the configured provider executable, follow symlinks, and hand the+ * result to the resolver. A binary that cannot be found yields the resolver's+ * no-context answer.+ */export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn("resolveProviderMaintenanceCapabilitiesEffect",)(function* (resolver: ProviderMaintenanceCapabilitiesResolver,- options?: Omit<ProviderMaintenanceCapabilityResolutionOptions, "realCommandPath">,+ options?: {+ readonly binaryPath?: string | null;+ readonly env?: NodeJS.ProcessEnv;+ },) {const binaryPath = nonEmptyString(options?.binaryPath);- const platform = options?.platform ?? (yield* HostProcessPlatform);if (!binaryPath) {- return resolver.resolve({ ...options, platform });+ return yield* resolver.resolve(null);}const env = options?.env ?? (yield* readCommandLookupEnv);- const resolvedCommandPath =- (yield* resolveCommandPath(binaryPath, { env }).pipe(- Effect.catchTag("CommandResolutionError", () => Effect.succeed(null)),- )) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);+ // resolveCommandPath checks explicit paths for existence too, so a missing+ // binary always lands in the no-context branch and never gets an update+ // command it cannot run.+ const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }).pipe(+ Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),+ );if (!resolvedCommandPath) {- return resolver.resolve({ ...options, platform });+ return yield* resolver.resolve(null);}const fileSystem = yield* FileSystem.FileSystem;const realCommandPath = yield* fileSystem.realPath(resolvedCommandPath)- .pipe(Effect.orElseSucceed(() => resolvedCommandPath));- return resolver.resolve({- ...options,- platform,- env,+ .pipe(Effect.orElseSucceed(() => null));+ if (!realCommandPath) {+ return yield* resolver.resolve(null);+ }+ return yield* resolver.resolve({+ binaryPath,resolvedCommandPath,realCommandPath,+ env,+ platform: yield* HostProcessPlatform,});});+/**+ * Turn a one-shot resolution into the shape drivers expose: a cached read for+ * advisories and a `fresh` read that update execution uses so it never trusts+ * ownership derived before the user clicked.+ */+export const makeCachedProviderMaintenanceResolution = Effect.fn(+ "makeCachedProviderMaintenanceResolution",+)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {+ const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(+ resolve,+ MAINTENANCE_CAPABILITIES_CACHE_TTL,+ );+ return (options?: { readonly fresh?: boolean }) =>+ options?.fresh ? invalidate.pipe(Effect.andThen(cached)) : cached;+});+function deriveVersionAdvisory(input: {readonly currentVersion: string | null;readonly latestVersion: string | null;@@ -482,6 +648,9 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packexport const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (maintenanceCapabilities: ProviderMaintenanceCapabilities,) {+ if (maintenanceCapabilities.latestVersion !== undefined) {+ return maintenanceCapabilities.latestVersion;+ }const packageName = maintenanceCapabilities.packageName;if (!packageName) {return null;diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.tsindex c45f1f7406c..19af22c882a 100644--- a/apps/server/src/provider/providerMaintenanceRunner.test.ts+++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts@@ -70,7 +70,7 @@ const baseProvider: ServerProvider = {driver: CODEX_DRIVER,enabled: true,installed: true,- version: null,+ version: "0.0.0",status: "ready",auth: { status: "authenticated" },checkedAt: "2026-04-10T00:00:00.000Z",@@ -129,6 +129,7 @@ function mockSpawnerLayer(handler: (command: string,args: ReadonlyArray<string>,+ options: { readonly env?: NodeJS.ProcessEnv | undefined },) => {readonly stdout?: string;readonly stderr?: string;@@ -142,8 +143,11 @@ function mockSpawnerLayer(const childProcess = command as unknown as {readonly command: string;readonly args: ReadonlyArray<string>;+ readonly options: { readonly env?: NodeJS.ProcessEnv | undefined };};- return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));+ return Effect.succeed(+ mockHandle(handler(childProcess.command, childProcess.args, childProcess.options)),+ );}),);}@@ -198,6 +202,7 @@ function makeRegistry(return {registry,+ providersRef,updateStatesRef,};});@@ -210,7 +215,8 @@ const makeTestRunner = (registry: ProviderRegistryShape) =>Layer.provide(Layer.mergeAll(Layer.succeed(ProviderRegistry, registry),- Layer.succeed(ProviderVersionCache, new Map()),+ // Fresh per runner so a version cached by one test cannot leak into another.+ Layer.sync(ProviderVersionCache, () => new Map()),),),),@@ -250,6 +256,182 @@ describe("providerMaintenanceRunner", () => {);});+ it.effect("reports unchanged when the updater exits 0 but the provider is gone", () => {+ return Effect.gen(function* () {+ const { registry, providersRef } = yield* makeRegistry(baseProvider);+ // After the update, the refreshed snapshot no longer sees an install.+ const updater = yield* makeTestRunner({+ ...registry,+ refreshInstance: () =>+ Ref.updateAndGet(providersRef, (providers) =>+ providers.map((provider) => ({ ...provider, installed: false, version: null })),+ ),+ });++ const result = yield* updater.updateProvider(CODEX_DRIVER);+ assert.strictEqual(result.providers[0]?.updateState?.status, "unchanged");+ assert.match(result.providers[0]?.updateState?.message ?? "", /could not verify/);+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ NonWindowsPlatform,+ latestVersionHttpClient("0.0.0"),+ mockSpawnerLayer(() => ({ stdout: "updated" })),+ ),+ ),+ );+ });++ it.effect(+ "keeps a successful update when the binary is present but its version is unreadable",+ () => {+ return Effect.gen(function* () {+ const { registry, providersRef } = yield* makeRegistry(baseCursorProvider);+ // Cursor's `agent about` probe can fail right after an update while the+ // new binary is perfectly fine.+ const updater = yield* makeTestRunner({+ ...registry,+ refreshInstance: () =>+ Ref.updateAndGet(providersRef, (providers) =>+ providers.map((provider) => ({ ...provider, installed: true, version: null })),+ ),+ });++ const result = yield* updater.updateProvider(CURSOR_DRIVER);+ assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ NonWindowsPlatform,+ latestVersionHttpClient("0.0.0"),+ mockSpawnerLayer(() => ({ stdout: "updated" })),+ ),+ ),+ );+ },+ );++ it.effect("spawns the updater with the environment its capabilities declare", () => {+ const seen: Array<NodeJS.ProcessEnv | undefined> = [];+ return Effect.gen(function* () {+ const { registry } = yield* makeRegistry(baseProvider);+ const updater = yield* makeTestRunner({+ ...registry,+ getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>+ Effect.succeed({+ ...lifecycleFor(provider),+ update: {+ command: "codex update",+ executable: "/work/codex-home/packages/standalone/bin/codex",+ args: ["update"],+ lockKey: "codex-native",+ env: { CODEX_HOME: "/work/codex-home" },+ },+ }),+ });++ yield* updater.updateProvider(CODEX_DRIVER);+ assert.deepStrictEqual(seen, [{ CODEX_HOME: "/work/codex-home" }]);+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ NonWindowsPlatform,+ latestVersionHttpClient("0.0.0"),+ mockSpawnerLayer((_command, _args, options) => {+ seen.push(options.env);+ return { stdout: "updated" };+ }),+ ),+ ),+ );+ });++ it.effect("re-resolves ownership before running and executes the fresh command", () => {+ const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];+ const fresh: Array<boolean> = [];+ return Effect.gen(function* () {+ const { registry } = yield* makeRegistry(baseProvider);+ const updater = yield* makeTestRunner({+ ...registry,+ getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider, options) => {+ fresh.push(options?.fresh === true);+ return Effect.succeed(+ makeProviderMaintenanceCapabilities({+ provider,+ packageName: "@openai/codex",+ updateExecutable: options?.fresh ? "/opt/homebrew/bin/brew" : "brew",+ updateArgs: ["upgrade", "--cask", "codex"],+ updateLockKey: "homebrew",+ }),+ );+ },+ });++ yield* updater.updateProvider(CODEX_DRIVER);+ // Cached read picks the lock; the two fresh reads bracket the command.+ assert.deepStrictEqual(fresh, [false, true, true]);+ assert.deepStrictEqual(calls, [+ { command: "/opt/homebrew/bin/brew", args: ["upgrade", "--cask", "codex"] },+ ]);+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ NonWindowsPlatform,+ latestVersionHttpClient("0.0.0"),+ mockSpawnerLayer((command, args) => {+ calls.push({ command, args });+ return { stdout: "updated" };+ }),+ ),+ ),+ );+ });++ it.effect("aborts without running when the installation changed since the advisory", () => {+ const calls: Array<string> = [];+ return Effect.gen(function* () {+ const { registry, updateStatesRef } = yield* makeRegistry(baseProvider);+ const updater = yield* makeTestRunner({+ ...registry,+ getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider, options) =>+ Effect.succeed(+ options?.fresh+ ? makeProviderMaintenanceCapabilities({+ provider,+ packageName: "@openai/codex",+ updateExecutable: null,+ updateArgs: [],+ updateLockKey: null,+ })+ : lifecycleFor(provider),+ ),+ });++ const result = yield* updater.updateProvider(CODEX_DRIVER);+ assert.deepStrictEqual(calls, []);+ assert.strictEqual(result.providers[0]?.updateState?.status, "failed");+ assert.strictEqual(+ result.providers[0]?.updateState?.message,+ "Provider installation changed. Refresh and try again.",+ );+ assert.deepStrictEqual(+ (yield* Ref.get(updateStatesRef)).map((state) => state.status),+ ["queued", "running", "failed"],+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ NonWindowsPlatform,+ latestVersionHttpClient("0.0.0"),+ mockSpawnerLayer((command) => {+ calls.push(command);+ return { stdout: "updated" };+ }),+ ),+ ),+ );+ });+it.effect("uses the resolved provider capabilities when choosing the update executable", () => {const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];return Effect.gen(function* () {diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.tsindex 4ac4401ffe2..e9156031256 100644--- a/apps/server/src/provider/providerMaintenanceRunner.ts+++ b/apps/server/src/provider/providerMaintenanceRunner.ts@@ -23,7 +23,11 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";import { ProviderRegistry } from "./Services/ProviderRegistry.ts";import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";-import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";+import {+ enrichProviderSnapshotWithVersionAdvisory,+ type ProviderMaintenanceCommandAction,+ ProviderVersionCache,+} from "./providerMaintenance.ts";import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);@@ -73,6 +77,7 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRreadonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];readonly command: string;readonly args: ReadonlyArray<string>;+ readonly env?: NodeJS.ProcessEnv;}) {const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(function* () {@@ -83,7 +88,12 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR// shell. On Linux/macOS (incl. the WSL backend) this is a no-op.const resolved = yield* resolveSpawnCommand(input.command, input.args);const child = yield* input.spawner- .spawn(ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell }))+ .spawn(+ ChildProcess.make(resolved.command, resolved.args, {+ shell: resolved.shell,+ ...(input.env ? { env: input.env, extendEnv: true } : {}),+ }),+ ).pipe(Effect.mapError((cause) =>@@ -181,6 +191,10 @@ function isOutdatedProvider(provider: ServerProvider | undefined): boolean {return provider?.versionAdvisory?.status === "behind_latest";}+function isStillInstalled(provider: ServerProvider): boolean {+ return provider.installed;+}+function makeUpdateState(input: {readonly status: ServerProviderUpdateState["status"];readonly startedAt: string | null;@@ -201,11 +215,13 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {const providerRegistry = yield* ProviderRegistry;const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;const httpClient = yield* HttpClient.HttpClient;- const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>+ const versionCache = yield* ProviderVersionCache;+ const runMaintenanceCommand = (update: ProviderMaintenanceCommandAction) =>runProviderMaintenanceCommandWithSpawner({spawner,- command,- args,+ command: update.executable,+ args: update.args,+ ...(update.env ? { env: update.env } : {}),});const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({makeAlreadyRunningError: () =>@@ -258,7 +274,10 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {enrichProviderSnapshotWithVersionAdvisory(refreshedProvider,maintenanceCapabilities,- ).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),+ ).pipe(+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(ProviderVersionCache, versionCache),+ ),{concurrency: "unbounded",},@@ -337,7 +356,26 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {}),);- const result = yield* runMaintenanceCommand(update.executable, update.args);+ // The cached capabilities chose the lock; re-derive ownership+ // now so the command that runs matches the executable as it is+ // at click time, not as it was at the last health refresh.+ const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(+ instanceId,+ provider,+ { fresh: true },+ );+ if (!fresh.update || fresh.update.lockKey !== update.lockKey) {+ return yield* finish(+ makeUpdateState({+ status: "failed",+ startedAt,+ finishedAt: yield* nowIso,+ message: "Provider installation changed. Refresh and try again.",+ }),+ );+ }++ const result = yield* runMaintenanceCommand(fresh.update);const finishedAt = yield* nowIso;if (result.timedOut || result.exitCode !== 0) {return yield* finish(@@ -351,18 +389,30 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {);}+ // Homebrew's "latest" moves once the upgrade lands; read it again.+ const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(+ instanceId,+ provider,+ { fresh: true },+ );const { verifiedProviders } = yield* verifyRefreshedProvider(provider,- capabilities,+ verified,instanceId,);- const couldNotVerify = verifiedProviders.length === 0;- const stillOutdated =- couldNotVerify ||- verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));+ // "Succeeded" needs the provider to still be installed: an+ // installer that exits 0 and leaves the binary missing is not a+ // success. A missing version alone is not held against it, since+ // Cursor's `about` probe can fail transiently on a healthy binary.+ const couldNotVerify =+ verifiedProviders.length === 0 ||+ verifiedProviders.some((verifiedProvider) => !isStillInstalled(verifiedProvider));+ const stillOutdated = verifiedProviders.some((verifiedProvider) =>+ isOutdatedProvider(verifiedProvider),+ );return yield* finish(makeUpdateState({- status: stillOutdated ? "unchanged" : "succeeded",+ status: couldNotVerify || stillOutdated ? "unchanged" : "succeeded",startedAt,finishedAt,message: couldNotVerifydiff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts b/apps/web/src/components/ProviderUpdateLaunchNotification.logic.tsindex e9ed26f1ee8..10c2f144bff 100644--- a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts+++ b/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts@@ -19,6 +19,13 @@ export type ProviderUpdateCandidate = ServerProvider & {};};+export type ProviderSettingsUpdateCandidate = ServerProvider & {+ readonly versionAdvisory: NonNullable<ServerProvider["versionAdvisory"]> & {+ readonly canUpdate: true;+ readonly updateCommand: string;+ };+};+export type ProviderUpdateToastType = "warning" | "loading" | "error" | "success";export type ProviderUpdateToastPhase = "initial" | "running" | "failed" | "unchanged" | "succeeded";@@ -149,6 +156,17 @@ export function collectProviderUpdateCandidates(return dedupeProvidersByDriver(providers.filter(isProviderUpdateCandidate));}+export function isProviderSettingsUpdateCandidate(+ provider: ServerProvider,+): provider is ProviderSettingsUpdateCandidate {+ return (+ provider.enabled &&+ provider.versionAdvisory?.status === "behind_latest" &&+ provider.versionAdvisory.canUpdate === true &&+ provider.versionAdvisory.updateCommand !== null+ );+}+export function hasOneClickUpdateProviderCandidate(candidate: ProviderUpdateCandidate,providers: ReadonlyArray<ServerProvider>,diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsxindex e5575ee9f78..fb4620b054c 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx@@ -49,11 +49,9 @@ import {connectionPhasePingClassName,} from "../ConnectionStatusDot";import {- canOneClickUpdateProviderCandidate,- collectProviderUpdateCandidates,- hasOneClickUpdateProviderCandidate,+ isProviderSettingsUpdateCandidate,isProviderUpdateActive,- type ProviderUpdateCandidate,+ type ProviderSettingsUpdateCandidate,} from "../ProviderUpdateLaunchNotification.logic";import { Button } from "../ui/button";import {@@ -574,19 +572,20 @@ export function EnvironmentProviderSettings({const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | null>(targetInstanceId ?? null,);- const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<- ReadonlySet<ProviderDriverKind>+ const [updatingProviderInstanceIds, setUpdatingProviderInstanceIds] = useState<+ ReadonlySet<ProviderInstanceId>>(() => new Set());const refreshingRef = useRef(false);- const updatingDriversRef = useRef<Set<ProviderDriverKind>>(new Set());+ const updatingInstanceIdsRef = useRef<Set<ProviderInstanceId>>(new Set());- const providerUpdateCandidates = useMemo(- () => collectProviderUpdateCandidates(serverProviders),- [serverProviders],- );const providerUpdateCandidateByInstanceId = useMemo(- () => new Map(providerUpdateCandidates.map((candidate) => [candidate.instanceId, candidate])),- [providerUpdateCandidates],+ () =>+ new Map(+ serverProviders+ .filter(isProviderSettingsUpdateCandidate)+ .map((candidate) => [candidate.instanceId, candidate]),+ ),+ [serverProviders],);const visibleProviderSettings = PROVIDER_SETTINGS.filter((providerSettings) =>@@ -636,14 +635,14 @@ export function EnvironmentProviderSettings({}, [environmentId, refreshServerProviders]);const runProviderUpdate = useCallback(- async (candidate: ProviderUpdateCandidate) => {+ async (candidate: ProviderSettingsUpdateCandidate) => {// Ref-based re-entry guard, mirroring refreshProviders: a state updater// may run after this function returns, so it cannot gate the dispatch.- if (updatingDriversRef.current.has(candidate.driver)) {+ if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {return;}- updatingDriversRef.current.add(candidate.driver);- setUpdatingProviderDrivers((previous) => new Set(previous).add(candidate.driver));+ updatingInstanceIdsRef.current.add(candidate.instanceId);+ setUpdatingProviderInstanceIds((previous) => new Set(previous).add(candidate.instanceId));const result = await updateProvider({environmentId,@@ -665,13 +664,13 @@ export function EnvironmentProviderSettings({}),);}- updatingDriversRef.current.delete(candidate.driver);- setUpdatingProviderDrivers((previous) => {- if (!previous.has(candidate.driver)) {+ updatingInstanceIdsRef.current.delete(candidate.instanceId);+ setUpdatingProviderInstanceIds((previous) => {+ if (!previous.has(candidate.instanceId)) {return previous;}const next = new Set(previous);- next.delete(candidate.driver);+ next.delete(candidate.instanceId);return next;});},@@ -872,23 +871,13 @@ export function EnvironmentProviderSettings({const liveProvider = serverProviders.find((candidate) => candidate.instanceId === row.instanceId,);- const updateCandidate = liveProvider- ? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)- : undefined;- const isDriverUpdateRunning =+ const updateCandidate = providerUpdateCandidateByInstanceId.get(row.instanceId);+ const isInstanceUpdateRunning =updateCandidate !== undefined &&- (updatingProviderDrivers.has(updateCandidate.driver) ||- serverProviders.some(- (provider) =>- provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),- ));- const showInlineUpdateButton =- updateCandidate !== undefined &&- hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);- const canRunInlineUpdate =- updateCandidate !== undefined &&- canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&- !updatingProviderDrivers.has(updateCandidate.driver);+ (updatingProviderInstanceIds.has(updateCandidate.instanceId) ||+ isProviderUpdateActive(updateCandidate));+ const showInlineUpdateButton = updateCandidate !== undefined;+ const canRunInlineUpdate = updateCandidate !== undefined && !isInstanceUpdateRunning;const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {hiddenModels: [],modelOrder: [],@@ -975,7 +964,9 @@ export function EnvironmentProviderSettings({}: undefined}- isUpdating={mode === "editor" && showInlineUpdateButton ? isDriverUpdateRunning : undefined}+ isUpdating={+ mode === "editor" && showInlineUpdateButton ? isInstanceUpdateRunning : undefined+ }/>);};diff --git a/docs/internals/providers.md b/docs/internals/providers.mdindex 30c1d00802c..6d7582aad8d 100644--- a/docs/internals/providers.md+++ b/docs/internals/providers.md@@ -55,6 +55,25 @@ run before the prompt. They reject profiles with such configuration before launcinstructions and tool denial do not create a native sandbox.See [helper constraints](../../apps/server/src/textGeneration/AntigravityTextGeneration.ts).+## Provider updates run only through the owning installer++A one-click update is offered only when the resolved executable's path proves which installer owns+it. Homebrew and npm are proven by the real path (symlinks followed): a versioned keg or cask under+`brew --prefix`, or `<prefix>/lib/node_modules/<pkg>/` (Windows: the shim beside `node_modules`).+Native installer layouts and the global bin directories of pnpm, Bun, and Vite+ may match on either+the resolved path or its real target, since those installers place real files or their own symlinks+there. Anything unproven stays manual-only but still reports the version gap. npm updates pin+`--prefix` because the `npm` on `PATH` can belong to a different Node than the one that owns the+provider. Homebrew+compares against `brew info` since casks trail npm by hours; native installs share npm's version+train, so the registry stays authoritative for them.+See the [resolver](../../apps/server/src/provider/providerMaintenance.ts).++Ownership is cached per instance and re-read immediately before an update runs. The+[runner](../../apps/server/src/provider/providerMaintenanceRunner.ts) refuses when the lock key+changed since the advisory, and reports success only when the refreshed provider is still installed+with a readable, current version.+## Protocol trapsCodex async questions arrive as notifications and are answered with a new user message. There isdiff --git a/docs/user/install.md b/docs/user/install.mdindex 10f1fdf164c..17e9291bf1a 100644--- a/docs/user/install.md+++ b/docs/user/install.md@@ -81,6 +81,13 @@ Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set itCursor's executable is `cursor-agent`, although its login command is`agent login`. Antigravity can use its managed runtime without a `PATH` entry.+When a provider CLI is behind its latest release, its provider card shows the+available version. **Update now** appears only when T3 Code can tell which+installer owns the CLI (its own update command, Homebrew, or a global npm, pnpm,+bun, or Vite+ install) and runs that installer. Otherwise update the CLI the same+way you installed it. Homebrew installs compare against the version Homebrew+offers, which can trail the npm release by a few hours.+Add another provider instance for a separate account or configuration. Eachinstance can have its own environment variables, such as API keys or a custombase URL. Mark secret values as sensitive; after saving, T3 Code does not display