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

driver.ts

252 lines10.0 KB

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