TypeScript
fix(grok): a Homebrew-installed Grok updates through brew and is compared against the cask (#18772)
Igor Makowski393a9f8950f4
diff --git a/docs/internals/providers.md b/docs/internals/providers.mdindex 5f9642c2db2..4121a349dcb 100644--- a/docs/internals/providers.md+++ b/docs/internals/providers.md@@ -89,7 +89,8 @@ symlinks there. Volta is proven by its `volta-shim` link plus the package's imagnothing is proven, the provider's own updater (`claude update`, `codex update`, `opencode upgrade`,`pi update --self`, `grok update`) runs instead, because each one detects its installer itself;the runner's version check catches an updater that exits 0 without updating. Mise installs stay-manual-only because their version is pinned in mise's config. npm updates pin `--prefix` because the+manual-only because their version is pinned in mise's config. A Grok cask whose Homebrew prefix+cannot be verified also stays manual-only: `grok update` would install a second copy. npm updates pin `--prefix` because the`npm` on `PATH` can belong to a different Node than the one that owns the provider. Homebrewcompares against `brew info` since casks trail npm by hours; native installs share npm's versiontrain, so the registry stays authoritative for them.diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.tsindex c0ea2f5d0ac..bb5e2d3d675 100644--- a/packages/provider-core/src/server/maintenanceResolver.ts+++ b/packages/provider-core/src/server/maintenanceResolver.ts@@ -485,16 +485,39 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn(});}- if (commandPaths.some(isMiseCommandPath) || (yield* isMiseWrapperScript(context))) {+ const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);+ if (+ commandPaths.some(isMiseCommandPath) ||+ // Mise shims resolve to the version manager's keg, not the provider's.+ (homebrew?.kind === "formula" && homebrew.name.toLowerCase() === "mise") ||+ (yield* isMiseWrapperScript(context))+ ) {return manual;}-- const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);if (homebrew) {- // Mise shims resolve to the version manager, not the provider.- if (homebrew.kind === "formula" && homebrew.name.toLowerCase() === "mise") {- return manual;- }+ return (+ (yield* resolveHomebrewProviderMaintenance(+ { provider: definition.provider, packageName },+ homebrew,+ context,+ )) ?? fallback+ );+ }++ return fallback;+});++/**+ * `brew upgrade` capabilities once the keg's prefix is confirmed by a `brew`+ * that reports it as its own, with `latestVersion` from `brew info`. Null when+ * no `brew` is found or it owns another prefix.+ */+export const resolveHomebrewProviderMaintenance = Effect.fn("resolveHomebrewProviderMaintenance")(+ function* (+ input: { readonly provider: ProviderDriverKind; readonly packageName: string | null },+ homebrew: HomebrewOwnership,+ context: ProviderMaintenanceResolutionContext,+ ) {const fileSystem = yield* FileSystem.FileSystem;const path = yield* Path.Path;// The keg's own brew works even when a GUI-launched server has no@@ -504,7 +527,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn(? kegBrewPath: yield* resolveCommandPath("brew", { env: context.env });if (!brewPath) {- return fallback;+ return null;}const brewPrefix = nonEmptyString(yield* runProbe(brewPath, ["--prefix"], context.env));const realBrewPrefix = brewPrefix@@ -514,7 +537,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn(!realBrewPrefix ||normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)) {- return fallback;+ return null;}const args =homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];@@ -522,18 +545,16 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn(// `brew upgrade` can actually deliver.const info = yield* runProbe(brewPath, ["info", "--json=v2", homebrew.name], context.env);return makeProviderMaintenanceCapabilities({- provider: definition.provider,- packageName,+ provider: input.provider,+ packageName: input.packageName,updateExecutable: brewPath,updateArgs: args,updateLockKey: "homebrew",updateCommand: ["brew", ...args].join(" "),latestVersion: info ? parseHomebrewLatestVersion(info, homebrew) : null,});- }-- return fallback;-});+ },+);const isMiseWrapperScript = Effect.fn("isMiseWrapperScript")(function* (context: ProviderMaintenanceResolutionContext,diff --git a/packages/provider-grok/src/server/driver.test.ts b/packages/provider-grok/src/server/driver.test.tsindex 1962f0b6cd1..02e222af673 100644--- a/packages/provider-grok/src/server/driver.test.ts+++ b/packages/provider-grok/src/server/driver.test.ts@@ -6,6 +6,8 @@ import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Path from "effect/Path";+import * as Sink from "effect/Sink";+import * as Stream from "effect/Stream";import * as HttpClient from "effect/http/HttpClient";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";@@ -40,6 +42,31 @@ const noSpawner = ChildProcessSpawner.make(() =>Effect.die("Disabled Grok must not spawn a process"),);+/** Answers every spawn with `onSpawn(command, args)` on stdout, like a stub `brew`. */+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,+ }),+ );+ });+}+// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.const windowsHost = HostProcess.Platform.defaultValue() === "win32";@@ -77,6 +104,101 @@ it.layer(layerTest)("GrokDriver", (it) => {),);+ // Each case puts a stub `brew` at `<prefix>/bin/brew` beside the Grok binary.+ const homebrewCases = [+ {+ name: "upgrades a Homebrew grok-build cask through brew",+ binary: ["Caskroom", "grok-build", "1.2.3,456", "grok"],+ reportedPrefix: "own",+ brewArgs: [["--prefix"], ["info", "--json=v2", "grok-build"]],+ latestVersion: "1.2.4",+ update: (brewPath: string, _binaryPath: string) => ({+ command: "brew upgrade --cask grok-build",+ executable: brewPath,+ args: ["upgrade", "--cask", "grok-build"],+ lockKey: "homebrew",+ }),+ },+ {+ // `grok update` would install a second copy beside the cask.+ name: "stays manual-only for a cask another brew prefix owns",+ binary: ["Caskroom", "grok-build", "1.2.3", "grok"],+ reportedPrefix: "/opt/homebrew",+ brewArgs: [["--prefix"]],+ latestVersion: undefined,+ update: () => null,+ },+ {+ // A formula keg such as `node` holding an npm global is not Grok's owner.+ name: "keeps grok update for an npm global inside a Homebrew node keg",+ binary: [+ "Cellar",+ "node",+ "22",+ "lib",+ "node_modules",+ "@xai-official",+ "grok",+ "bin",+ "grok",+ ],+ reportedPrefix: "own",+ brewArgs: [],+ latestVersion: undefined,+ update: (_brewPath: string, binaryPath: string) => ({+ executable: binaryPath,+ args: ["update"],+ lockKey: "grok",+ }),+ },+ ] as const;++ for (const testCase of homebrewCases) {+ it.effect.skipIf(windowsHost)(testCase.name, () => {+ const brewArgs: Array<ReadonlyArray<string>> = [];+ let prefix = "";+ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ prefix = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "t3-grok-brew-" }));+ const brewPath = path.join(prefix, "bin", "brew");+ const binaryPath = path.join(prefix, ...testCase.binary);+ for (const executable of [brewPath, binaryPath]) {+ yield* fs.makeDirectory(path.dirname(executable), { recursive: true });+ yield* fs.writeFileString(executable, "#!/bin/sh\n");+ yield* fs.chmod(executable, 0o755);+ }++ const instance = yield* GrokDriver.create({+ instanceId: ProviderInstanceId.make("grok-homebrew"),+ displayName: "Grok test",+ enabled: false,+ environment: [],+ config: { ...GrokDriver.defaultConfig(), binaryPath },+ });+ const capabilities = yield* instance.snapshot.resolveMaintenance();++ const update = testCase.update(brewPath, binaryPath);+ expect(brewArgs).toEqual(testCase.brewArgs);+ expect(capabilities.latestVersion).toBe(testCase.latestVersion);+ expect(capabilities.update).toEqual(update && expect.objectContaining(update));+ }).pipe(+ Effect.provideService(+ ChildProcessSpawner.ChildProcessSpawner,+ stdoutSpawner((command, args) => {+ expect(command).toBe(`${prefix}/bin/brew`);+ brewArgs.push(args);+ if (args[0] === "--prefix") {+ return `${testCase.reportedPrefix === "own" ? prefix : testCase.reportedPrefix}\n`;+ }+ return JSON.stringify({ casks: [{ version: "1.2.4,789" }] });+ }),+ ),+ Effect.scoped,+ );+ });+ }+it.effect("stays manual-only when the configured executable does not exist", () =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;diff --git a/packages/provider-grok/src/server/driver.ts b/packages/provider-grok/src/server/driver.tsindex 9be2dd85b9e..4b7fb8de3b7 100644--- a/packages/provider-grok/src/server/driver.ts+++ b/packages/provider-grok/src/server/driver.ts@@ -31,10 +31,12 @@ import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdenimport { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";import { discoverGrokSkills } from "./skills.ts";import {+ homebrewOwnershipFromCommandPath,makeCachedProviderMaintenanceResolution,makeManualOnlyProviderMaintenanceCapabilities,makeProviderMaintenanceCapabilities,type ProviderMaintenanceCapabilitiesResolver,+ resolveHomebrewProviderMaintenance,resolveProviderMaintenanceCapabilitiesEffect,} from "@t3tools/provider-core/server/maintenanceResolver";import {@@ -50,25 +52,43 @@ const DRIVER_KIND = ProviderDriverKind.make("grok");const GROK_NPM_PACKAGE = "@xai-official/grok";// `grok update` finds the installer that owns the binary itself, so the// resolved executable is its own updater. It installs under `GROK_HOME`, so it-// runs with the instance's environment.+// runs with the instance's environment. The exception is a Homebrew cask+// (normally `grok-build`), which brew upgrades and versions: `grok update` would install+// a second copy beside it, so a cask its brew cannot vouch for stays manual.const UPDATE: ProviderMaintenanceCapabilitiesResolver = {- resolve: (context) =>- Effect.succeed(- context- ? makeProviderMaintenanceCapabilities({- provider: DRIVER_KIND,- packageName: GROK_NPM_PACKAGE,- updateExecutable: context.resolvedCommandPath,- updateArgs: ["update"],- updateLockKey: "grok",- platform: context.platform,- env: context.env,- })- : makeManualOnlyProviderMaintenanceCapabilities({- provider: DRIVER_KIND,- packageName: GROK_NPM_PACKAGE,- }),- ),+ resolve: Effect.fn("resolveGrokMaintenance")(function* (context) {+ if (!context) {+ return makeManualOnlyProviderMaintenanceCapabilities({+ provider: DRIVER_KIND,+ packageName: GROK_NPM_PACKAGE,+ });+ }+ const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);+ // Only a cask is Grok's: a formula keg such as `node` holding an npm global is not.+ if (homebrew?.kind === "cask") {+ return (+ (yield* resolveHomebrewProviderMaintenance(+ { provider: DRIVER_KIND, packageName: GROK_NPM_PACKAGE },+ homebrew,+ context,+ )) ??+ makeManualOnlyProviderMaintenanceCapabilities({+ provider: DRIVER_KIND,+ packageName: GROK_NPM_PACKAGE,+ installPath: context.realCommandPath,+ })+ );+ }+ return makeProviderMaintenanceCapabilities({+ provider: DRIVER_KIND,+ packageName: GROK_NPM_PACKAGE,+ updateExecutable: context.resolvedCommandPath,+ updateArgs: ["update"],+ updateLockKey: "grok",+ platform: context.platform,+ env: context.env,+ });+ }),};export type GrokDriverEnv =