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

GrokDriver.ts

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