fix(server): only run provider updates through the installer that owns the binary #9325
Mergedjuliusmarmingemerged 13 commits into
main fromrefs/pull/9325/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/provider/providerMaintenance.ts lines 366 to 366OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -329,0 +346,21 @@346+ provider: definition.provider,347+ packageName,348+ updateExecutable: "bun",349+ updateArgs: ["i", "-g", `${packageName}@latest`],350+ updateLockKey: "bun-global",351+ });352+ }353+ if (commandPaths.some(isPnpmGlobalCommandPath)) {354+ return makeProviderMaintenanceCapabilities({355+ provider: definition.provider,356+ packageName,357+ updateExecutable: "pnpm",358+ updateArgs: ["add", "-g", `${packageName}@latest`],359+ updateLockKey: "pnpm-global",360+ });361+ }362+363+ const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);364+ if (homebrew) {365+ const brewPath = yield* resolveCommandPath("brew", { env: context.env }).pipe(366+ Effect.catchTag("CommandResolutionError", () => Effect.succeed(null)),
- apps/server/src/provider/Drivers/CursorDriver.ts line 153OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -142,4 +150,4 @@142150143151 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);144152 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({145- maintenanceCapabilities,153+ resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),apps/server/src/provider/providerMaintenance.ts line 265Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -272,11 +213,12 @@272- normalized.startsWith("/usr/local/bin/")273- );213+const HOMEBREW_KEG_PATTERN = /\/(cellar|caskroom)\/([^/]+)\//i;214+215+export interface HomebrewOwnership {216+ readonly kind: "formula" | "cask";217+ readonly name: string;274218 }275219276-export function resolvePackageManagedProviderMaintenance(277- definition: PackageManagedProviderMaintenanceDefinition,278- options?: ProviderMaintenanceCapabilityResolutionOptions,279-): ProviderMaintenanceCapabilities {280- const binaryPath = nonEmptyString(options?.binaryPath);281- if (!binaryPath) {282- return makeNpmGlobalProviderMaintenanceCapabilities(definition);220+/** Homebrew owns an executable when its real path runs through a keg or caskroom entry. */221+export function homebrewOwnershipFromCommandPath(222+ realCommandPath: string,223+): HomebrewOwnership | null {224+ const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));apps/server/src/provider/providerMaintenance.ts line 201OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -252,8 +188,14 @@252188253-function isNpmGlobalCommandPath(commandPath: string): boolean {254- const normalized = normalizeCommandPath(commandPath);255- return (256- normalized.includes("/node_modules/.bin/") ||257- normalized.includes("/lib/node_modules/") ||258- normalized.includes("/npm/node_modules/")259- );189+/**190+ * The npm global prefix that owns a package, derived from the real path of191+ * its entry point: `<prefix>/lib/node_modules/<pkg>/…` on POSIX and192+ * `<prefix>/node_modules/<pkg>/…` on Windows. Returns null when the path does193+ * not go through the package, which is the evidence that npm owns it.194+ */195+export function npmGlobalPrefixFromCommandPath(196+ realCommandPath: string,197+ packageName: string,198+): string | null {199+ const slashPath = realCommandPath.replaceAll("\\", "/");200+ const normalized = slashPath.toLowerCase();201+ const packageSegment = `/node_modules/${packageName.toLowerCase()}/`;
- apps/server/src/provider/Layers/ProviderRegistry.ts line 531OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -523,5 +523,9 @@523523524524 const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(525525 "getProviderMaintenanceCapabilitiesForInstance",526- )(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {526+ )(function* (527+ instanceId: ProviderInstanceId,528+ provider: ProviderDriverKind,529+ options?: { readonly fresh?: boolean },530+ ) {527531 const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(apps/server/src/provider/providerMaintenance.ts line 316Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -324,2 +258,20 @@258+ ? decoded.value.formulae?.[0]?.versions?.stable259+ : decoded.value.casks?.[0]?.version?.split(",", 1)[0];260+ return nonEmptyString(raw);261+}324262325- return makeManualOnlyProviderMaintenanceCapabilities({263+const fetchHomebrewLatestVersion = Effect.fn("fetchHomebrewLatestVersion")(function* (264+ brewPath: string,265+ ownership: HomebrewOwnership,266+ env: NodeJS.ProcessEnv,267+) {268+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;269+ const collect = Effect.gen(function* () {270+ const child = yield* spawner.spawn(271+ ChildProcess.make(brewPath, ["info", "--json=v2", ownership.name], {272+ env,273+ extendEnv: true,274+ }),275+ );276+ yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));277+ const [stdout, exitCode] = yield* Effect.all(
- apps/server/src/provider/providerMaintenance.ts line 438OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -329,0 +418,21 @@418+ context: ProviderMaintenanceResolutionContext,419+ packageName: string,420+) {421+ const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);422+ if (fromRealPath) {423+ return fromRealPath;424+ }425+ const fileSystem = yield* FileSystem.FileSystem;426+ const path = yield* Path.Path;427+ const shimDir = path.dirname(context.resolvedCommandPath);428+ const manifestPath = path.join(429+ shimDir,430+ "node_modules",431+ ...packageName.split("/"),432+ "package.json",433+ );434+ const isShim = /\.(?:cmd|bat|ps1)$/i.test(context.resolvedCommandPath);435+ const hasManifest = yield* fileSystem436+ .exists(manifestPath)437+ .pipe(Effect.orElseSucceed(() => false));438+ return isShim && hasManifest ? shimDir : null;
- apps/server/src/provider/providerMaintenance.ts lines 204 to 204OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -258,2 +186,19 @@258- normalized.includes("/npm/node_modules/")259- );186+/**187+ * The npm global prefix that owns a package, derived from the real path of188+ * its entry point: `<prefix>/lib/node_modules/<pkg>/…`. Windows global189+ * installs have no `lib` segment and are proven by the shim instead (see190+ * `resolveNpmGlobalPrefix`). A project-local `node_modules` is not a global191+ * install and yields null.192+ */193+export function npmGlobalPrefixFromCommandPath(194+ realCommandPath: string,195+ packageName: string,196+): string | null {197+ const slashPath = realCommandPath.replaceAll("\\", "/");198+ const normalized = slashPath.toLowerCase();199+ const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`;200+ const packageIndex = normalized.lastIndexOf(packageSegment);201+ if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) {202+ return null;203+ }204+ const prefix = slashPath.slice(0, packageIndex);
- apps/server/src/provider/Drivers/CursorDriver.ts line 68Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -57,11 +59,13 @@5759 const UPDATE: ProviderMaintenanceCapabilitiesResolver = {58- resolve: (options) =>59- makeProviderMaintenanceCapabilities({60- provider: DRIVER_KIND,61- packageName: null,62- updateExecutable: options?.binaryPath?.trim() || "cursor-agent",63- updateArgs: ["update"],64- updateLockKey: "cursor-agent",65- }),60+ resolve: (context) =>61+ Effect.succeed(62+ makeProviderMaintenanceCapabilities({63+ provider: DRIVER_KIND,64+ packageName: null,65+ updateExecutable: context?.resolvedCommandPath ?? "cursor-agent",66+ updateArgs: ["update"],67+ updateLockKey: "cursor-agent",68+ }),69+ ),6670 };6771apps/server/src/provider/Drivers/CursorDriver.ts line 68Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -57,11 +59,13 @@5759 const UPDATE: ProviderMaintenanceCapabilitiesResolver = {58- resolve: (options) =>59- makeProviderMaintenanceCapabilities({60- provider: DRIVER_KIND,61- packageName: null,62- updateExecutable: options?.binaryPath?.trim() || "cursor-agent",63- updateArgs: ["update"],64- updateLockKey: "cursor-agent",65- }),60+ resolve: (context) =>61+ Effect.succeed(62+ makeProviderMaintenanceCapabilities({63+ provider: DRIVER_KIND,64+ packageName: null,65+ updateExecutable: context?.resolvedCommandPath ?? "cursor-agent",66+ updateArgs: ["update"],67+ updateLockKey: "cursor-agent",68+ }),69+ ),6670 };6771
- apps/server/src/provider/providerMaintenance.ts line 293OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -283,0 +273,21 @@273+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;274+ const collect = Effect.gen(function* () {275+ const child = yield* spawner.spawn(ChildProcess.make(brewPath, args, { env, extendEnv: true }));276+ yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));277+ // stderr is drained so a chatty brew cannot block on a full pipe.278+ const [stdout, exitCode] = yield* Effect.all(279+ [280+ collectUint8StreamText({ stream: child.stdout, maxBytes: HOMEBREW_INFO_MAX_BYTES }),281+ child.exitCode,282+ Stream.runDrain(child.stderr),283+ ],284+ { concurrency: "unbounded" },285+ );286+ return Number(exitCode) !== 0 || stdout.truncated ? null : stdout.text;287+ });288+ return yield* collect.pipe(289+ Effect.scoped,290+ Effect.timeoutOption(Duration.millis(HOMEBREW_INFO_TIMEOUT_MS)),291+ Effect.map(Option.getOrNull),292+ Effect.catchCause((cause) =>293+ Effect.logWarning("Homebrew probe failed", { args, cause }).pipe(Effect.as(null)),
- @@ -55,3 +55,10 @@5555 instructions and tool denial do not create a native sandbox.5656 See [helper constraints](../../apps/server/src/textGeneration/AntigravityTextGeneration.ts).575758+## Provider updates run only through the owning installer59+60+A one-click update is offered only when the resolved executable's real path proves which installer61+owns it: a native installer layout, a versioned keg or cask under `brew --prefix`, or62+`<prefix>/lib/node_modules/<pkg>/` for npm (Windows: the shim beside `node_modules`). Anything63+unproven stays manual-only but still reports the version gap. npm updates pin `--prefix` because64+the `npm` on `PATH` can belong to a different Node than the one that owns the provider. Homebrew
- @@ -55,3 +55,7 @@5555 instructions and tool denial do not create a native sandbox.5656 See [helper constraints](../../apps/server/src/textGeneration/AntigravityTextGeneration.ts).575758+## Provider updates run only through the owning installer59+60+A one-click update is offered only when the resolved executable's real path proves which installer61+owns it: a native installer layout, a versioned keg or cask under `brew --prefix`,
- apps/server/src/provider/Drivers/CodexDriver.ts lines 85 to 88OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -71,8 +73,16 @@7173 const decodeCodexSettings = Schema.decodeSync(CodexSettings);72747375 const DRIVER_KIND = ProviderDriverKind.make("codex");76+// The standalone installer lays out `<CODEX_HOME>/packages/standalone/…`;77+// CODEX_HOME is not always `~/.codex`.78+function isCodexStandaloneCommandPath(commandPath: string): boolean {79+ return normalizeCommandPath(commandPath).includes("/packages/standalone/");80+}81+7482 const UPDATE = makePackageManagedProviderMaintenanceResolver({7583 provider: DRIVER_KIND,7684 npmPackageName: "@openai/codex",77- homebrewFormula: "codex",78- nativeUpdate: null,85+ nativeUpdate: {86+ args: ["update"],87+ isCommandPath: isCodexStandaloneCommandPath,88+ },
- @@ -313,0 +389,21 @@389+ const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);390+ if (npmPrefix) {391+ // npm 12 blocks install scripts by default (empty allow-scripts allowlist)392+ // and still exits 0, so a package whose postinstall finishes the install393+ // (claude copies its native binary over a placeholder stub) is left broken394+ // while the update reports success. Allow this one package's scripts.395+ // Older npm warns about the unknown config and continues.396+ return makeProviderMaintenanceCapabilities({397+ provider: definition.provider,398+ packageName,399+ updateExecutable: "npm",400+ updateArgs: [401+ "install",402+ "-g",403+ "--prefix",404+ npmPrefix,405+ `--allow-scripts=${packageName}`,406+ `${packageName}@latest`,407+ ],408+ updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,409+ });
- @@ -79,0 +78,21 @@78+// CODEX_HOME is not always `~/.codex`.79+function isCodexStandaloneCommandPath(commandPath: string): boolean {80+ return normalizeCommandPath(commandPath).includes("/packages/standalone/");81+}82+83+/**84+ * `codex update` replaces the standalone tree under `CODEX_HOME`, so the85+ * updater must run with this instance's home or it would update `~/.codex`86+ * and leave the instance's binary behind.87+ */88+function makeCodexMaintenanceResolver(homePath: string) {89+ const resolvedHomePath = homePath ? expandHomePath(homePath) : undefined;90+ return makePackageManagedProviderMaintenanceResolver({91+ provider: DRIVER_KIND,92+ npmPackageName: "@openai/codex",93+ nativeUpdate: {94+ args: ["update"],95+ isCommandPath: isCodexStandaloneCommandPath,96+ ...(resolvedHomePath ? { env: { CODEX_HOME: resolvedHomePath } } : {}),97+ },98+ });
juliusmarminge merged this2fb99a7
juliusmarminge closed this
Sign in to join this conversation.








macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed