Open History to see the last commit
1import { ProviderDriverKind } from "@t3tools/contracts";
2import { GrokSettings } from "../settings.ts";
3import * as SecureRandom from "effect/crypto/SecureRandom";
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 resolveMiseProviderMaintenance,
41 resolveProviderMaintenanceCapabilitiesEffect,
42} from "@t3tools/provider-core/server/maintenanceResolver";
43import {
44 haveProviderSnapshotSettingsChanged,
45 makeProviderSnapshotSettingsSource,
46 type ProviderSnapshotSettings,
47} from "@t3tools/provider-core/server/snapshotSettings";
48const decodeGrokSettings = Schema.decodeSync(GrokSettings);
49
50const DRIVER_KIND = ProviderDriverKind.make("grok");
51// npm latest matches the stable channel installed by grok update.
52const GROK_NPM_PACKAGE = "@xai-official/grok";
53// `grok update` installs under `GROK_HOME` from the resolved executable and instance environment.
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.
57const 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 const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
72 // Only a cask is Grok's: a formula keg such as `node` holding an npm global is not.
73 if (homebrew?.kind === "cask") {
74 return (
75 (yield* resolveHomebrewProviderMaintenance(
76 { provider: DRIVER_KIND, packageName: GROK_NPM_PACKAGE },
77 homebrew,
78 context,
79 )) ??
80 makeManualOnlyProviderMaintenanceCapabilities({
81 provider: DRIVER_KIND,
82 packageName: GROK_NPM_PACKAGE,
83 installPath: context.realCommandPath,
84 })
85 );
86 }
87 return makeProviderMaintenanceCapabilities({
88 provider: DRIVER_KIND,
89 packageName: GROK_NPM_PACKAGE,
90 updateExecutable: context.resolvedCommandPath,
91 updateArgs: ["update"],
92 updateLockKey: "grok",
93 platform: context.platform,
94 env: { ...context.env, npm_config_allow_scripts: GROK_NPM_PACKAGE },
95 });
96 }),
97};
98
99export type GrokDriverEnv =
100 | GrokAdapterV2DriverEnv
101 | ProviderHost.ProviderHost
102 | ChildProcessSpawner.ChildProcessSpawner
103 | SecureRandom.SecureRandom
104 | FileSystem.FileSystem
105 | HttpClient.HttpClient
106 | ProviderLatestVersions.ProviderLatestVersions
107 | Path.Path
108 | ProviderEventLoggers.ProviderEventLoggers;
109
110export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv, Path.Path> = {
111 driverKind: DRIVER_KIND,
112 metadata: {
113 displayName: "Grok",
114 supportsMultipleInstances: true,
115 },
116 configSchema: GrokSettings,
117 defaultConfig: (): GrokSettings => decodeGrokSettings({}),
118 usage: grokUsageReader,
119 create: Effect.fn("GrokDriver.create")(function* ({
120 instanceId,
121 displayName,
122 accentColor,
123 environment,
124 enabled,
125 config,
126 }) {
127 const random = yield* SecureRandom.SecureRandom;
128 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
129 const httpClient = yield* HttpClient.HttpClient;
130 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
131 const fileSystem = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const host = yield* ProviderHost.ProviderHost;
134 const { cwd } = host.paths;
135 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
136 const continuationIdentity = defaultProviderContinuationIdentity({
137 driverKind: DRIVER_KIND,
138 instanceId,
139 });
140 const stampIdentity = withInstanceIdentity({
141 instanceId,
142 driverKind: DRIVER_KIND,
143 displayName,
144 accentColor,
145 continuationGroupKey: continuationIdentity.continuationKey,
146 });
147 const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
148 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
149 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
150 binaryPath: effectiveConfig.binaryPath,
151 env: processEnv,
152 }).pipe(
153 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
154 Effect.provideService(FileSystem.FileSystem, fileSystem),
155 Effect.provideService(Path.Path, path),
156 ),
157 );
158 const orchestrationAdapter = yield* GrokAdapterV2Driver.create({
159 instanceId,
160 displayName,
161 accentColor,
162 environment,
163 enabled,
164 config,
165 }).pipe(
166 Effect.mapError(
167 (cause) =>
168 new ProviderDriverError({
169 driver: DRIVER_KIND,
170 instanceId,
171 detail: "Failed to build Grok orchestration adapter.",
172 cause,
173 }),
174 ),
175 );
176 const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
177
178 const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(
179 Effect.filterOrElse(
180 (snapshot) =>
181 !(
182 effectiveConfig.enabled &&
183 snapshot.installed &&
184 snapshot.auth.status === "authenticated"
185 ),
186 (snapshot) =>
187 readGrokAccount(processEnv).pipe(
188 Effect.map(({ email, usageLimits }) => ({
189 ...snapshot,
190 auth: email ? { ...snapshot.auth, email } : snapshot.auth,
191 usageLimits,
192 })),
193 ),
194 ),
195 Effect.map(stampIdentity),
196 Effect.provideService(HttpClient.HttpClient, httpClient),
197 Effect.provideService(FileSystem.FileSystem, fileSystem),
198 Effect.provideService(Path.Path, path),
199 Effect.provideService(SecureRandom.SecureRandom, random),
200 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
201 );
202
203 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
204 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({
205 resolveMaintenance,
206 getSettings: snapshotSettings.getSettings,
207 streamSettings: snapshotSettings.streamSettings,
208 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
209 initialSnapshot: (settings) =>
210 buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
211 checkProvider,
212 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
213 resolveMaintenance().pipe(
214 Effect.flatMap((maintenanceCapabilities) =>
215 enrichGrokSnapshot({
216 snapshot: currentSnapshot,
217 maintenanceCapabilities,
218 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
219 publishSnapshot,
220 }),
221 ),
222 Effect.provideService(HttpClient.HttpClient, httpClient),
223 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
224 ),
225 }).pipe(
226 Effect.mapError(
227 (cause) =>
228 new ProviderDriverError({
229 driver: DRIVER_KIND,
230 instanceId,
231 detail: "Failed to build Grok snapshot.",
232 cause,
233 }),
234 ),
235 );
236 const snapshotForCwd = (workspaceCwd: string) =>
237 !effectiveConfig.enabled
238 ? snapshot.getSnapshot
239 : Effect.all([
240 snapshot.getSnapshot,
241 discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(
242 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
243 Effect.mapError(
244 (cause) =>
245 new ProviderDriverError({
246 driver: DRIVER_KIND,
247 instanceId,
248 detail: `Failed to discover Grok skills for '${workspaceCwd}'`,
249 cause,
250 }),
251 ),
252 ),
253 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));
254
255 return {
256 instanceId,
257 driverKind: DRIVER_KIND,
258 continuationIdentity,
259 displayName,
260 accentColor,
261 enabled,
262 snapshot,
263 snapshotForCwd,
264 orchestrationAdapter,
265 textGeneration,
266 } satisfies ProviderInstance;
267 }),
268};