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

GrokDriver.ts

233 lines8.9 KB

1import { GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
2import * as Crypto from "effect/Crypto";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as Schema from "effect/Schema";
7import { HttpClient } from "effect/unstable/http";
8import { ChildProcessSpawner } from "effect/unstable/process";
9​
10import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
11import * as ServerConfig from "../../config.ts";
12import * as ProviderEventLoggers from "../Layers/ProviderEventLoggers.ts";
13import * as ServerSettings from "../../serverSettings.ts";
14import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
15import {
16 GrokAdapterV2Driver,
17 type GrokAdapterV2DriverEnv,
18} from "../../orchestration-v2/Adapters/GrokAdapterV2.ts";
19import { ProviderDriverError } from "../Errors.ts";
20import {
21 buildInitialGrokProviderSnapshot,
22 checkGrokProviderStatus,
23 enrichGrokSnapshot,
24} from "../Layers/GrokProvider.ts";
25import { readGrokAccount } from "../Layers/grokUsageLimits.ts";
26import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
27import {
28 defaultProviderContinuationIdentity,
29 type ProviderDriver,
30 type ProviderInstance,
31} from "../ProviderDriver.ts";
32import { withInstanceIdentity } from "./instanceIdentity.ts";
33import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
34import { discoverGrokSkills } from "./GrokSkills.ts";
35import {
36 makeCachedProviderMaintenanceResolution,
37 makeManualOnlyProviderMaintenanceCapabilities,
38 makeProviderMaintenanceCapabilities,
39 type ProviderMaintenanceCapabilitiesResolver,
40 resolveProviderMaintenanceCapabilitiesEffect,
41} from "../providerMaintenance.ts";
42import {
43 haveProviderSnapshotSettingsChanged,
44 makeProviderSnapshotSettingsSource,
45 type ProviderSnapshotSettings,
46} from "../providerUpdateSettings.ts";
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. No executable means nothing to update,
56// not "whatever is on PATH".
57const UPDATE: ProviderMaintenanceCapabilitiesResolver = {
58 resolve: (context) =>
59 Effect.succeed(
60 context
61 ? makeProviderMaintenanceCapabilities({
62 provider: DRIVER_KIND,
63 packageName: GROK_NPM_PACKAGE,
64 updateExecutable: context.resolvedCommandPath,
65 updateArgs: ["update"],
66 updateLockKey: "grok",
67 platform: context.platform,
68 env: context.env,
69 })
70 : makeManualOnlyProviderMaintenanceCapabilities({
71 provider: DRIVER_KIND,
72 packageName: GROK_NPM_PACKAGE,
73 }),
74 ),
75};
76​
77export type GrokDriverEnv =
78 | GrokAdapterV2DriverEnv
79 | BackgroundPolicy.BackgroundPolicy
80 | ChildProcessSpawner.ChildProcessSpawner
81 | Crypto.Crypto
82 | FileSystem.FileSystem
83 | HttpClient.HttpClient
84 | Path.Path
85 | ProviderEventLoggers.ProviderEventLoggers
86 | ServerConfig.ServerConfig
87 | ServerSettings.ServerSettingsService;
88​
89export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
90 driverKind: DRIVER_KIND,
91 metadata: {
92 displayName: "Grok",
93 supportsMultipleInstances: true,
94 },
95 configSchema: GrokSettings,
96 defaultConfig: (): GrokSettings => decodeGrokSettings({}),
97 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
98 Effect.gen(function* () {
99 const crypto = yield* Crypto.Crypto;
100 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
101 const httpClient = yield* HttpClient.HttpClient;
102 const fileSystem = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 const serverSettings = yield* ServerSettings.ServerSettingsService;
105 const { cwd } = yield* ServerConfig.ServerConfig;
106 const processEnv = mergeProviderInstanceEnvironment(environment);
107 const continuationIdentity = defaultProviderContinuationIdentity({
108 driverKind: DRIVER_KIND,
109 instanceId,
110 });
111 const stampIdentity = withInstanceIdentity({
112 instanceId,
113 driverKind: DRIVER_KIND,
114 displayName,
115 accentColor,
116 continuationGroupKey: continuationIdentity.continuationKey,
117 });
118 const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
119 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
120 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
121 binaryPath: effectiveConfig.binaryPath,
122 env: processEnv,
123 }).pipe(
124 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
125 Effect.provideService(FileSystem.FileSystem, fileSystem),
126 Effect.provideService(Path.Path, path),
127 ),
128 );
129 const orchestrationAdapter = yield* GrokAdapterV2Driver.create({
130 instanceId,
131 displayName,
132 accentColor,
133 environment,
134 enabled,
135 config,
136 }).pipe(
137 Effect.mapError(
138 (cause) =>
139 new ProviderDriverError({
140 driver: DRIVER_KIND,
141 instanceId,
142 detail: "Failed to build Grok orchestration adapter.",
143 cause,
144 }),
145 ),
146 );
147 const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
148​
149 const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(
150 Effect.flatMap((snapshot) =>
151 effectiveConfig.enabled && snapshot.installed && snapshot.auth.status === "authenticated"
152 ? readGrokAccount(processEnv).pipe(
153 Effect.map(({ email, usageLimits }) => ({
154 ...snapshot,
155 auth: email ? { ...snapshot.auth, email } : snapshot.auth,
156 usageLimits,
157 })),
158 )
159 : Effect.succeed(snapshot),
160 ),
161 Effect.map(stampIdentity),
162 Effect.provideService(HttpClient.HttpClient, httpClient),
163 Effect.provideService(FileSystem.FileSystem, fileSystem),
164 Effect.provideService(Path.Path, path),
165 Effect.provideService(Crypto.Crypto, crypto),
166 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
167 );
168​
169 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
170 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({
171 resolveMaintenance,
172 getSettings: snapshotSettings.getSettings,
173 streamSettings: snapshotSettings.streamSettings,
174 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
175 initialSnapshot: (settings) =>
176 buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
177 checkProvider,
178 enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
179 resolveMaintenance().pipe(
180 Effect.flatMap((maintenanceCapabilities) =>
181 enrichGrokSnapshot({
182 snapshot: currentSnapshot,
183 maintenanceCapabilities,
184 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
185 publishSnapshot,
186 httpClient,
187 }),
188 ),
189 ),
190 }).pipe(
191 Effect.mapError(
192 (cause) =>
193 new ProviderDriverError({
194 driver: DRIVER_KIND,
195 instanceId,
196 detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,
197 cause,
198 }),
199 ),
200 );
201 const snapshotForCwd = (workspaceCwd: string) =>
202 !effectiveConfig.enabled
203 ? snapshot.getSnapshot
204 : Effect.all([
205 snapshot.getSnapshot,
206 discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(
207 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
208 Effect.mapError(
209 (cause) =>
210 new ProviderDriverError({
211 driver: DRIVER_KIND,
212 instanceId,
213 detail: `Failed to discover Grok skills for '${workspaceCwd}'`,
214 cause,
215 }),
216 ),
217 ),
218 ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));
219​
220 return {
221 instanceId,
222 driverKind: DRIVER_KIND,
223 continuationIdentity,
224 displayName,
225 accentColor,
226 enabled,
227 snapshot,
228 snapshotForCwd,
229 orchestrationAdapter,
230 textGeneration,
231 } satisfies ProviderInstance;
232 }),
233};