The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { ProviderDriverKind } from "@t3tools/contracts"; |
| 2 | import { GrokSettings } from "../settings.ts"; |
| 3 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Path from "effect/Path"; |
| 7 | import * as Schema from "effect/Schema"; |
| 8 | import * as HttpClient from "effect/http/HttpClient"; |
| 9 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 10 | |
| 11 | import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; |
| 12 | import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; |
| 13 | import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; |
| 14 | import { makeGrokTextGeneration } from "./textGeneration.ts"; |
| 15 | import { GrokAdapterV2Driver, type GrokAdapterV2DriverEnv } from "./adapter.ts"; |
| 16 | import { ProviderDriverError } from "@t3tools/provider-core/server/errors"; |
| 17 | import { |
| 18 | buildInitialGrokProviderSnapshot, |
| 19 | checkGrokProviderStatus, |
| 20 | enrichGrokSnapshot, |
| 21 | } from "./status.ts"; |
| 22 | import { grokUsageReader } from "./usage.ts"; |
| 23 | import { readGrokAccount } from "./usageLimits.ts"; |
| 24 | import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider"; |
| 25 | import { |
| 26 | defaultProviderContinuationIdentity, |
| 27 | type ProviderDriver, |
| 28 | type ProviderInstance, |
| 29 | } from "@t3tools/provider-core/server/driver"; |
| 30 | import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity"; |
| 31 | import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; |
| 32 | import { discoverGrokSkills } from "./skills.ts"; |
| 33 | import { |
| 34 | homebrewOwnershipFromCommandPath, |
| 35 | isNixStoreCommandPath, |
| 36 | makeCachedProviderMaintenanceResolution, |
| 37 | makeManualOnlyProviderMaintenanceCapabilities, |
| 38 | makeProviderMaintenanceCapabilities, |
| 39 | type ProviderMaintenanceCapabilitiesResolver, |
| 40 | resolveHomebrewProviderMaintenance, |
| 41 | resolveMiseProviderMaintenance, |
| 42 | resolveProviderMaintenanceCapabilitiesEffect, |
| 43 | } from "@t3tools/provider-core/server/maintenanceResolver"; |
| 44 | import { |
| 45 | haveProviderSnapshotSettingsChanged, |
| 46 | makeProviderSnapshotSettingsSource, |
| 47 | type ProviderSnapshotSettings, |
| 48 | } from "@t3tools/provider-core/server/snapshotSettings"; |
| 49 | const decodeGrokSettings = Schema.decodeSync(GrokSettings); |
| 50 | |
| 51 | const DRIVER_KIND = ProviderDriverKind.make("grok"); |
| 52 | // npm latest matches the stable channel installed by grok update. |
| 53 | const GROK_NPM_PACKAGE = "@xai-official/grok"; |
| 54 | // npm 12 blocks the postinstall that moves the new binary in, yet exits 0, so allow it by env. |
| 55 | // Mise and Homebrew casks upgrade through their manager; `grok update` would install a second |
| 56 | // copy, so a cask its brew cannot vouch for stays manual, as does a Nix store install. |
| 57 | const UPDATE: ProviderMaintenanceCapabilitiesResolver = { |
| 58 | resolve: Effect.fn("resolveGrokMaintenance")(function* (context) { |
| 59 | if (!context) { |
| 60 | return makeManualOnlyProviderMaintenanceCapabilities({ |
| 61 | provider: DRIVER_KIND, |
| 62 | packageName: GROK_NPM_PACKAGE, |
| 63 | }); |
| 64 | } |
| 65 | const mise = yield* resolveMiseProviderMaintenance( |
| 66 | { provider: DRIVER_KIND, packageName: GROK_NPM_PACKAGE }, |
| 67 | { tool: "grok" }, |
| 68 | context, |
| 69 | ); |
| 70 | if (mise) return mise; |
| 71 | if ([context.resolvedCommandPath, context.realCommandPath].some(isNixStoreCommandPath)) { |
| 72 | return makeManualOnlyProviderMaintenanceCapabilities({ |
| 73 | provider: DRIVER_KIND, |
| 74 | packageName: GROK_NPM_PACKAGE, |
| 75 | installPath: context.realCommandPath, |
| 76 | }); |
| 77 | } |
| 78 | const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath); |
| 79 | // Only a cask is Grok's: a formula keg such as `node` holding an npm global is not. |
| 80 | if (homebrew?.kind === "cask") { |
| 81 | return ( |
| 82 | (yield* resolveHomebrewProviderMaintenance( |
| 83 | { provider: DRIVER_KIND, packageName: GROK_NPM_PACKAGE }, |
| 84 | homebrew, |
| 85 | context, |
| 86 | )) ?? |
| 87 | makeManualOnlyProviderMaintenanceCapabilities({ |
| 88 | provider: DRIVER_KIND, |
| 89 | packageName: GROK_NPM_PACKAGE, |
| 90 | installPath: context.realCommandPath, |
| 91 | }) |
| 92 | ); |
| 93 | } |
| 94 | const path = yield* Path.Path; |
| 95 | const fileSystem = yield* FileSystem.FileSystem; |
| 96 | const name = path.basename(context.realCommandPath).toLowerCase(); |
| 97 | const installDir = path.dirname(context.realCommandPath); |
| 98 | const installDirName = path.basename(installDir).toLowerCase(); |
| 99 | const home = path.dirname(installDir); |
| 100 | // `grok update` installs under `$GROK_HOME`, so a script install keeps its own home even if the |
| 101 | // instance sets another: `<home>/bin/grok` links into `<home>/downloads`, or on Windows is a copy |
| 102 | // beside it. Only an install script creates `downloads`, so a bare `bin/grok` elsewhere is not one. |
| 103 | const isScriptInstall = |
| 104 | (installDirName === "downloads" && name.startsWith("grok-")) || |
| 105 | (installDirName === "bin" && |
| 106 | (/^grok-\d/.test(name) || |
| 107 | ((name === "grok" || name === "grok.exe") && |
| 108 | (yield* fileSystem |
| 109 | .exists(path.join(home, "downloads")) |
| 110 | .pipe(Effect.orElseSucceed(() => false)))))); |
| 111 | const scriptHome = isScriptInstall ? { GROK_HOME: home } : {}; |
| 112 | return makeProviderMaintenanceCapabilities({ |
| 113 | provider: DRIVER_KIND, |
| 114 | packageName: GROK_NPM_PACKAGE, |
| 115 | updateExecutable: context.resolvedCommandPath, |
| 116 | updateArgs: ["update"], |
| 117 | updateLockKey: "grok", |
| 118 | platform: context.platform, |
| 119 | env: { |
| 120 | ...context.env, |
| 121 | ...scriptHome, |
| 122 | npm_config_allow_scripts: GROK_NPM_PACKAGE, |
| 123 | // An npx-launched server's npm_config_user_agent outranks Grok's `[cli] installer`, steering |
| 124 | // a script install to npm. The runner extends process.env; only undefined removes a key. |
| 125 | npm_config_user_agent: undefined, |
| 126 | }, |
| 127 | }); |
| 128 | }), |
| 129 | }; |
| 130 | |
| 131 | export type GrokDriverEnv = |
| 132 | | GrokAdapterV2DriverEnv |
| 133 | | ProviderHost.ProviderHost |
| 134 | | ChildProcessSpawner.ChildProcessSpawner |
| 135 | | SecureRandom.SecureRandom |
| 136 | | FileSystem.FileSystem |
| 137 | | HttpClient.HttpClient |
| 138 | | ProviderLatestVersions.ProviderLatestVersions |
| 139 | | Path.Path |
| 140 | | ProviderEventLoggers.ProviderEventLoggers; |
| 141 | |
| 142 | export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv, Path.Path> = { |
| 143 | driverKind: DRIVER_KIND, |
| 144 | metadata: { |
| 145 | displayName: "Grok", |
| 146 | supportsMultipleInstances: true, |
| 147 | }, |
| 148 | configSchema: GrokSettings, |
| 149 | defaultConfig: (): GrokSettings => decodeGrokSettings({}), |
| 150 | usage: grokUsageReader, |
| 151 | create: Effect.fn("GrokDriver.create")(function* ({ |
| 152 | instanceId, |
| 153 | displayName, |
| 154 | accentColor, |
| 155 | environment, |
| 156 | enabled, |
| 157 | config, |
| 158 | }) { |
| 159 | const random = yield* SecureRandom.SecureRandom; |
| 160 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 161 | const httpClient = yield* HttpClient.HttpClient; |
| 162 | const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; |
| 163 | const fileSystem = yield* FileSystem.FileSystem; |
| 164 | const path = yield* Path.Path; |
| 165 | const host = yield* ProviderHost.ProviderHost; |
| 166 | const { cwd } = host.paths; |
| 167 | const processEnv = yield* mergeProviderInstanceEnvironment(environment); |
| 168 | const continuationIdentity = defaultProviderContinuationIdentity({ |
| 169 | driverKind: DRIVER_KIND, |
| 170 | instanceId, |
| 171 | }); |
| 172 | const stampIdentity = withInstanceIdentity({ |
| 173 | instanceId, |
| 174 | driverKind: DRIVER_KIND, |
| 175 | displayName, |
| 176 | accentColor, |
| 177 | continuationGroupKey: continuationIdentity.continuationKey, |
| 178 | }); |
| 179 | const effectiveConfig = { ...config, enabled } satisfies GrokSettings; |
| 180 | const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution( |
| 181 | resolveProviderMaintenanceCapabilitiesEffect(UPDATE, { |
| 182 | binaryPath: effectiveConfig.binaryPath, |
| 183 | env: processEnv, |
| 184 | }).pipe( |
| 185 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 186 | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 187 | Effect.provideService(Path.Path, path), |
| 188 | ), |
| 189 | ); |
| 190 | const orchestrationAdapter = yield* GrokAdapterV2Driver.create({ |
| 191 | instanceId, |
| 192 | displayName, |
| 193 | accentColor, |
| 194 | environment, |
| 195 | enabled, |
| 196 | config, |
| 197 | }).pipe( |
| 198 | Effect.mapError( |
| 199 | (cause) => |
| 200 | new ProviderDriverError({ |
| 201 | driver: DRIVER_KIND, |
| 202 | instanceId, |
| 203 | detail: "Failed to build Grok orchestration adapter.", |
| 204 | cause, |
| 205 | }), |
| 206 | ), |
| 207 | ); |
| 208 | const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv); |
| 209 | |
| 210 | const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe( |
| 211 | Effect.filterOrElse( |
| 212 | (snapshot) => |
| 213 | !( |
| 214 | effectiveConfig.enabled && |
| 215 | snapshot.installed && |
| 216 | snapshot.auth.status === "authenticated" |
| 217 | ), |
| 218 | (snapshot) => |
| 219 | readGrokAccount(processEnv).pipe( |
| 220 | Effect.map(({ email, usageLimits }) => ({ |
| 221 | ...snapshot, |
| 222 | auth: email ? { ...snapshot.auth, email } : snapshot.auth, |
| 223 | usageLimits, |
| 224 | })), |
| 225 | ), |
| 226 | ), |
| 227 | Effect.map(stampIdentity), |
| 228 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 229 | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 230 | Effect.provideService(Path.Path, path), |
| 231 | Effect.provideService(SecureRandom.SecureRandom, random), |
| 232 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 233 | ); |
| 234 | |
| 235 | const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); |
| 236 | const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({ |
| 237 | resolveMaintenance, |
| 238 | getSettings: snapshotSettings.getSettings, |
| 239 | streamSettings: snapshotSettings.streamSettings, |
| 240 | haveSettingsChanged: haveProviderSnapshotSettingsChanged, |
| 241 | // Each check starts the Grok CLI four times. A ready instance is rechecked on refresh or a |
| 242 | // settings change; only an unhealthy one keeps polling until it recovers. |
| 243 | refreshOnInterval: (snapshot) => snapshot.status !== "ready", |
| 244 | initialSnapshot: (settings) => |
| 245 | buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)), |
| 246 | checkProvider, |
| 247 | enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) => |
| 248 | resolveMaintenance().pipe( |
| 249 | Effect.flatMap((maintenanceCapabilities) => |
| 250 | enrichGrokSnapshot({ |
| 251 | snapshot: currentSnapshot, |
| 252 | maintenanceCapabilities, |
| 253 | enableProviderUpdateChecks: settings.enableProviderUpdateChecks, |
| 254 | publishSnapshot, |
| 255 | }), |
| 256 | ), |
| 257 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 258 | Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions), |
| 259 | ), |
| 260 | }).pipe( |
| 261 | Effect.mapError( |
| 262 | (cause) => |
| 263 | new ProviderDriverError({ |
| 264 | driver: DRIVER_KIND, |
| 265 | instanceId, |
| 266 | detail: "Failed to build Grok snapshot.", |
| 267 | cause, |
| 268 | }), |
| 269 | ), |
| 270 | ); |
| 271 | const snapshotForCwd = (workspaceCwd: string) => |
| 272 | !effectiveConfig.enabled |
| 273 | ? snapshot.getSnapshot |
| 274 | : Effect.all([ |
| 275 | snapshot.getSnapshot, |
| 276 | discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe( |
| 277 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 278 | Effect.mapError( |
| 279 | (cause) => |
| 280 | new ProviderDriverError({ |
| 281 | driver: DRIVER_KIND, |
| 282 | instanceId, |
| 283 | detail: `Failed to discover Grok skills for '${workspaceCwd}'`, |
| 284 | cause, |
| 285 | }), |
| 286 | ), |
| 287 | ), |
| 288 | ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))); |
| 289 | |
| 290 | return { |
| 291 | instanceId, |
| 292 | driverKind: DRIVER_KIND, |
| 293 | continuationIdentity, |
| 294 | displayName, |
| 295 | accentColor, |
| 296 | enabled, |
| 297 | snapshot, |
| 298 | snapshotForCwd, |
| 299 | orchestrationAdapter, |
| 300 | textGeneration, |
| 301 | } satisfies ProviderInstance; |
| 302 | }), |
| 303 | }; |