Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

driver.ts

304 lines11.9 KB

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 isNixStoreCommandPath,
36 makeCachedProviderMaintenanceResolution,
37 makeManualOnlyProviderMaintenanceCapabilities,
38 makeProviderMaintenanceCapabilities,
39 type ProviderMaintenanceCapabilitiesResolver,
40 resolveHomebrewProviderMaintenance,
41 resolveMiseProviderMaintenance,
42 resolveProviderMaintenanceCapabilitiesEffect,
43} from "@t3tools/provider-core/server/maintenanceResolver";
44import {
45 haveProviderSnapshotSettingsChanged,
46 makeProviderSnapshotSettingsSource,
47 type ProviderSnapshotSettings,
48} from "@t3tools/provider-core/server/snapshotSettings";
49const decodeGrokSettings = Schema.decodeSync(GrokSettings);
50​
51const DRIVER_KIND = ProviderDriverKind.make("grok");
52// npm latest matches the stable channel installed by grok update.
53const 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.
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 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​
131export 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​
142export 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 npmCacheDir: path.join(host.paths.providerStatusCacheDir, "npm"),
185 }).pipe(
186 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
187 Effect.provideService(FileSystem.FileSystem, fileSystem),
188 Effect.provideService(Path.Path, path),
189 ),
190 );
191 const orchestrationAdapter = yield* GrokAdapterV2Driver.create({
192 instanceId,
193 displayName,
194 accentColor,
195 environment,
196 enabled,
197 config,
198 }).pipe(
199 Effect.mapError(
200 (cause) =>
201 new ProviderDriverError({
202 driver: DRIVER_KIND,
203 instanceId,
204 detail: "Failed to build Grok orchestration adapter.",
205 cause,
206 }),
207 ),
208 );
209 const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
210​
211 const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(
212 Effect.filterOrElse(
213 (snapshot) =>
214 !(
215 effectiveConfig.enabled &&
216 snapshot.installed &&
217 snapshot.auth.status === "authenticated"
218 ),
219 (snapshot) =>
220 readGrokAccount(processEnv).pipe(
221 Effect.map(({ email, usageLimits }) => ({
222 ...snapshot,
223 auth: email ? { ...snapshot.auth, email } : snapshot.auth,
224 usageLimits,
225 })),
226 ),
227 ),
228 Effect.map(stampIdentity),
229 Effect.provideService(HttpClient.HttpClient, httpClient),
230 Effect.provideService(FileSystem.FileSystem, fileSystem),
231 Effect.provideService(Path.Path, path),
232 Effect.provideService(SecureRandom.SecureRandom, random),
233 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
234 );
235​
236 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
237 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({
238 resolveMaintenance,
239 getSettings: snapshotSettings.getSettings,
240 streamSettings: snapshotSettings.streamSettings,
241 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
242 // Each check starts the Grok CLI four times. A ready instance is rechecked on refresh or a
243 // settings change; only an unhealthy one keeps polling until it recovers.
244 refreshOnInterval: (snapshot) => snapshot.status !== "ready",
245 initialSnapshot: (settings) =>
246 buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
247 checkProvider,
248 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
249 resolveMaintenance().pipe(
250 Effect.flatMap((maintenanceCapabilities) =>
251 enrichGrokSnapshot({
252 snapshot: currentSnapshot,
253 maintenanceCapabilities,
254 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
255 publishSnapshot,
256 }),
257 ),
258 Effect.provideService(HttpClient.HttpClient, httpClient),
259 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
260 ),
261 }).pipe(
262 Effect.mapError(
263 (cause) =>
264 new ProviderDriverError({
265 driver: DRIVER_KIND,
266 instanceId,
267 detail: "Failed to build Grok snapshot.",
268 cause,
269 }),
270 ),
271 );
272 const snapshotForCwd = (workspaceCwd: string) =>
273 !effectiveConfig.enabled
274 ? snapshot.getSnapshot
275 : Effect.all([
276 snapshot.getSnapshot,
277 discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(
278 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
279 Effect.mapError(
280 (cause) =>
281 new ProviderDriverError({
282 driver: DRIVER_KIND,
283 instanceId,
284 detail: `Failed to discover Grok skills for '${workspaceCwd}'`,
285 cause,
286 }),
287 ),
288 ),
289 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));
290​
291 return {
292 instanceId,
293 driverKind: DRIVER_KIND,
294 continuationIdentity,
295 displayName,
296 accentColor,
297 enabled,
298 snapshot,
299 snapshotForCwd,
300 orchestrationAdapter,
301 textGeneration,
302 } satisfies ProviderInstance;
303 }),
304};