Open History to see the last commit
1import { ProviderDriverKind } from "@t3tools/contracts";
2import { GrokSettings } from "../settings.ts";
3import * as Crypto from "effect/Crypto";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8import * as HttpClient from "effect/http/HttpClient";
9import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
10
11import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
12import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
13import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
14import { makeGrokTextGeneration } from "./textGeneration.ts";
15import { GrokAdapterV2Driver, type GrokAdapterV2DriverEnv } from "./adapter.ts";
16import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
17import {
18 buildInitialGrokProviderSnapshot,
19 checkGrokProviderStatus,
20 enrichGrokSnapshot,
21} from "./status.ts";
22import { grokUsageReader } from "./usage.ts";
23import { readGrokAccount } from "./usageLimits.ts";
24import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
25import {
26 defaultProviderContinuationIdentity,
27 type ProviderDriver,
28 type ProviderInstance,
29} from "@t3tools/provider-core/server/driver";
30import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
31import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
32import { discoverGrokSkills } from "./skills.ts";
33import {
34 homebrewOwnershipFromCommandPath,
35 makeCachedProviderMaintenanceResolution,
36 makeManualOnlyProviderMaintenanceCapabilities,
37 makeProviderMaintenanceCapabilities,
38 type ProviderMaintenanceCapabilitiesResolver,
39 resolveHomebrewProviderMaintenance,
40 resolveProviderMaintenanceCapabilitiesEffect,
41} from "@t3tools/provider-core/server/maintenanceResolver";
42import {
43 haveProviderSnapshotSettingsChanged,
44 makeProviderSnapshotSettingsSource,
45 type ProviderSnapshotSettings,
46} from "@t3tools/provider-core/server/snapshotSettings";
47const decodeGrokSettings = Schema.decodeSync(GrokSettings);
48
49const DRIVER_KIND = ProviderDriverKind.make("grok");
50// npm's `latest` tracks Grok's stable channel, the one `grok update` installs
51// by default, so the registry stays the source for "latest".
52const GROK_NPM_PACKAGE = "@xai-official/grok";
53// `grok update` finds the installer that owns the binary itself, so the
54// resolved executable is its own updater. It installs under `GROK_HOME`, so it
55// runs with the instance's environment. The exception is a Homebrew cask
56// (normally `grok-build`), which brew upgrades and versions: `grok update` would install
57// a second copy beside it, so a cask its brew cannot vouch for stays manual.
58const UPDATE: ProviderMaintenanceCapabilitiesResolver = {
59 resolve: Effect.fn("resolveGrokMaintenance")(function* (context) {
60 if (!context) {
61 return makeManualOnlyProviderMaintenanceCapabilities({
62 provider: DRIVER_KIND,
63 packageName: GROK_NPM_PACKAGE,
64 });
65 }
66 const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
67 // Only a cask is Grok's: a formula keg such as `node` holding an npm global is not.
68 if (homebrew?.kind === "cask") {
69 return (
70 (yield* resolveHomebrewProviderMaintenance(
71 { provider: DRIVER_KIND, packageName: GROK_NPM_PACKAGE },
72 homebrew,
73 context,
74 )) ??
75 makeManualOnlyProviderMaintenanceCapabilities({
76 provider: DRIVER_KIND,
77 packageName: GROK_NPM_PACKAGE,
78 installPath: context.realCommandPath,
79 })
80 );
81 }
82 return makeProviderMaintenanceCapabilities({
83 provider: DRIVER_KIND,
84 packageName: GROK_NPM_PACKAGE,
85 updateExecutable: context.resolvedCommandPath,
86 updateArgs: ["update"],
87 updateLockKey: "grok",
88 platform: context.platform,
89 env: context.env,
90 });
91 }),
92};
93
94export type GrokDriverEnv =
95 | GrokAdapterV2DriverEnv
96 | ProviderHost.ProviderHost
97 | ChildProcessSpawner.ChildProcessSpawner
98 | Crypto.Crypto
99 | FileSystem.FileSystem
100 | HttpClient.HttpClient
101 | ProviderLatestVersions.ProviderLatestVersions
102 | Path.Path
103 | ProviderEventLoggers.ProviderEventLoggers;
104
105export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv, Path.Path> = {
106 driverKind: DRIVER_KIND,
107 metadata: {
108 displayName: "Grok",
109 supportsMultipleInstances: true,
110 },
111 configSchema: GrokSettings,
112 defaultConfig: (): GrokSettings => decodeGrokSettings({}),
113 usage: grokUsageReader,
114 create: Effect.fn("GrokDriver.create")(function* ({
115 instanceId,
116 displayName,
117 accentColor,
118 environment,
119 enabled,
120 config,
121 }) {
122 const crypto = yield* Crypto.Crypto;
123 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
124 const httpClient = yield* HttpClient.HttpClient;
125 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
126 const fileSystem = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128 const host = yield* ProviderHost.ProviderHost;
129 const { cwd } = host.paths;
130 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
131 const continuationIdentity = defaultProviderContinuationIdentity({
132 driverKind: DRIVER_KIND,
133 instanceId,
134 });
135 const stampIdentity = withInstanceIdentity({
136 instanceId,
137 driverKind: DRIVER_KIND,
138 displayName,
139 accentColor,
140 continuationGroupKey: continuationIdentity.continuationKey,
141 });
142 const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
143 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
144 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
145 binaryPath: effectiveConfig.binaryPath,
146 env: processEnv,
147 }).pipe(
148 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
149 Effect.provideService(FileSystem.FileSystem, fileSystem),
150 Effect.provideService(Path.Path, path),
151 ),
152 );
153 const orchestrationAdapter = yield* GrokAdapterV2Driver.create({
154 instanceId,
155 displayName,
156 accentColor,
157 environment,
158 enabled,
159 config,
160 }).pipe(
161 Effect.mapError(
162 (cause) =>
163 new ProviderDriverError({
164 driver: DRIVER_KIND,
165 instanceId,
166 detail: "Failed to build Grok orchestration adapter.",
167 cause,
168 }),
169 ),
170 );
171 const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
172
173 const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(
174 Effect.flatMap((snapshot) =>
175 effectiveConfig.enabled && snapshot.installed && snapshot.auth.status === "authenticated"
176 ? readGrokAccount(processEnv).pipe(
177 Effect.map(({ email, usageLimits }) => ({
178 ...snapshot,
179 auth: email ? { ...snapshot.auth, email } : snapshot.auth,
180 usageLimits,
181 })),
182 )
183 : Effect.succeed(snapshot),
184 ),
185 Effect.map(stampIdentity),
186 Effect.provideService(HttpClient.HttpClient, httpClient),
187 Effect.provideService(FileSystem.FileSystem, fileSystem),
188 Effect.provideService(Path.Path, path),
189 Effect.provideService(Crypto.Crypto, crypto),
190 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
191 );
192
193 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
194 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({
195 resolveMaintenance,
196 getSettings: snapshotSettings.getSettings,
197 streamSettings: snapshotSettings.streamSettings,
198 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
199 initialSnapshot: (settings) =>
200 buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
201 checkProvider,
202 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
203 resolveMaintenance().pipe(
204 Effect.flatMap((maintenanceCapabilities) =>
205 enrichGrokSnapshot({
206 snapshot: currentSnapshot,
207 maintenanceCapabilities,
208 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
209 publishSnapshot,
210 }),
211 ),
212 Effect.provideService(HttpClient.HttpClient, httpClient),
213 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
214 ),
215 }).pipe(
216 Effect.mapError(
217 (cause) =>
218 new ProviderDriverError({
219 driver: DRIVER_KIND,
220 instanceId,
221 detail: "Failed to build Grok snapshot.",
222 cause,
223 }),
224 ),
225 );
226 const snapshotForCwd = (workspaceCwd: string) =>
227 !effectiveConfig.enabled
228 ? snapshot.getSnapshot
229 : Effect.all([
230 snapshot.getSnapshot,
231 discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(
232 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
233 Effect.mapError(
234 (cause) =>
235 new ProviderDriverError({
236 driver: DRIVER_KIND,
237 instanceId,
238 detail: `Failed to discover Grok skills for '${workspaceCwd}'`,
239 cause,
240 }),
241 ),
242 ),
243 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));
244
245 return {
246 instanceId,
247 driverKind: DRIVER_KIND,
248 continuationIdentity,
249 displayName,
250 accentColor,
251 enabled,
252 snapshot,
253 snapshotForCwd,
254 orchestrationAdapter,
255 textGeneration,
256 } satisfies ProviderInstance;
257 }),
258};