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

driver.ts

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