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

GrokDriver.ts

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