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