Open History to see the last commit
1import {
2 type GrokSettings,
3 type ModelCapabilities,
4 type ServerProvider,
5 type ServerProviderModel,
6} from "@t3tools/contracts";
7import type * as EffectAcpSchema from "effect-acp/schema";
8import { causeErrorTag } from "@t3tools/shared/observability";
9import * as Crypto from "effect/Crypto";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Option from "effect/Option";
14import * as Result from "effect/Result";
15import { HttpClient } from "effect/unstable/http";
16import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
17import { createModelCapabilities } from "@t3tools/shared/model";
18import { resolveSpawnCommand } from "@t3tools/shared/shell";
19
20import {
21 buildServerProvider,
22 isCommandMissingCause,
23 parseGenericCliVersion,
24 providerModelsFromSettings,
25 spawnAndCollect,
26 type ServerProviderDraft,
27} from "../providerSnapshot.ts";
28import {
29 enrichProviderSnapshotWithVersionAdvisory,
30 type ProviderMaintenanceCapabilities,
31} from "../providerMaintenance.ts";
32import {
33 isValidGrokReasoningEffortToken,
34 makeGrokAcpRuntime,
35 resolveGrokAcpBaseModelId,
36} from "../acp/GrokAcpSupport.ts";
37import { discoverGrokSkills } from "../Drivers/GrokSkills.ts";
38
39const GROK_PRESENTATION = {
40 displayName: "Grok",
41 showInteractionModeToggle: false,
42} as const;
43const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
44 optionDescriptors: [],
45});
46
47const VERSION_PROBE_TIMEOUT_MS = 4_000;
48const GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
49
50const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
51 {
52 slug: "grok-build",
53 name: "Grok Build",
54 isCustom: false,
55 capabilities: EMPTY_CAPABILITIES,
56 },
57];
58
59export function buildInitialGrokProviderSnapshot(
60 grokSettings: GrokSettings,
61): Effect.Effect<ServerProviderDraft> {
62 return Effect.gen(function* () {
63 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
64 const models = grokModelsFromSettings(grokSettings.customModels);
65
66 if (!grokSettings.enabled) {
67 return buildServerProvider({
68 presentation: GROK_PRESENTATION,
69 enabled: false,
70 checkedAt,
71 models,
72 probe: {
73 installed: false,
74 version: null,
75 status: "warning",
76 auth: { status: "unknown" },
77 message: "Grok is disabled in T3 Code settings.",
78 },
79 });
80 }
81
82 return buildServerProvider({
83 presentation: GROK_PRESENTATION,
84 enabled: true,
85 checkedAt,
86 models,
87 probe: {
88 installed: true,
89 version: null,
90 status: "warning",
91 auth: { status: "unknown" },
92 message: "Checking Grok CLI availability...",
93 },
94 });
95 });
96}
97
98function grokModelsFromSettings(
99 customModels: ReadonlyArray<string> | undefined,
100 builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
101): ReadonlyArray<ServerProviderModel> {
102 return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);
103}
104
105function nonEmptyString(value: unknown): string | undefined {
106 return typeof value === "string" ? value.trim() || undefined : undefined;
107}
108
109function isRecord(value: unknown): value is Record<string, unknown> {
110 return typeof value === "object" && value !== null && !Array.isArray(value);
111}
112
113function grokReasoningOptionsFromModel(model: EffectAcpSchema.ModelInfo): {
114 readonly options: ReadonlyArray<{
115 value: string;
116 label: string;
117 description?: string;
118 isDefault?: boolean;
119 }>;
120 readonly currentValue: string | undefined;
121} {
122 const meta = model._meta;
123 if (!meta || meta.supportsReasoningEffort === false) {
124 return { options: [], currentValue: undefined };
125 }
126
127 const currentEffort = nonEmptyString(meta.reasoningEffort);
128 const advertisedOptions = Array.isArray(meta.reasoningEfforts) ? meta.reasoningEfforts : [];
129 const seen = new Set<string>();
130 const options: Array<{
131 value: string;
132 label: string;
133 description?: string;
134 advertisedDefault: boolean;
135 }> = [];
136
137 for (const entry of advertisedOptions) {
138 if (!isRecord(entry)) {
139 continue;
140 }
141 const rawValue = nonEmptyString(entry.value);
142 const rawId = nonEmptyString(entry.id);
143 const value =
144 rawValue && isValidGrokReasoningEffortToken(rawValue)
145 ? rawValue
146 : rawId && isValidGrokReasoningEffortToken(rawId)
147 ? rawId
148 : undefined;
149 if (value === undefined || seen.has(value)) {
150 continue;
151 }
152 seen.add(value);
153 const description = nonEmptyString(entry.description);
154 options.push({
155 value,
156 label: nonEmptyString(entry.label) ?? value,
157 ...(description ? { description } : {}),
158 advertisedDefault: entry.default === true || entry.isDefault === true,
159 });
160 }
161
162 const currentValue =
163 currentEffort && options.some((option) => option.value === currentEffort)
164 ? currentEffort
165 : undefined;
166 const advertisedDefaults = options.filter((option) => option.advertisedDefault);
167 const selectedDefault =
168 advertisedDefaults.find((option) => option.value === currentValue)?.value ??
169 advertisedDefaults[0]?.value;
170 return {
171 options: options.map(({ value, label, description }) => ({
172 value,
173 label,
174 ...(description ? { description } : {}),
175 ...(value === selectedDefault ? { isDefault: true } : {}),
176 })),
177 currentValue: currentValue ?? selectedDefault,
178 };
179}
180
181export function buildGrokModelCapabilities(model: EffectAcpSchema.ModelInfo): ModelCapabilities {
182 const reasoning = grokReasoningOptionsFromModel(model);
183 return reasoning.options.length > 0
184 ? createModelCapabilities({
185 optionDescriptors: [
186 {
187 id: "reasoningEffort",
188 label: "Reasoning",
189 type: "select",
190 options: reasoning.options.map((option) => ({
191 id: option.value,
192 label: option.label,
193 ...(option.description ? { description: option.description } : {}),
194 ...(option.isDefault ? { isDefault: true } : {}),
195 })),
196 ...(reasoning.currentValue ? { currentValue: reasoning.currentValue } : {}),
197 },
198 ],
199 })
200 : EMPTY_CAPABILITIES;
201}
202
203function buildGrokDiscoveredModelsFromSessionModelState(
204 modelState: EffectAcpSchema.SessionModelState | null | undefined,
205): ReadonlyArray<ServerProviderModel> {
206 if (!modelState || modelState.availableModels.length === 0) {
207 return [];
208 }
209 const seen = new Set<string>();
210 return modelState.availableModels
211 .map((model): ServerProviderModel | undefined => {
212 const slug = resolveGrokAcpBaseModelId(model.modelId);
213 if (!slug || seen.has(slug)) {
214 return undefined;
215 }
216 seen.add(slug);
217 return {
218 slug,
219 name: model.name.trim() || slug,
220 isCustom: false,
221 capabilities: buildGrokModelCapabilities(model),
222 };
223 })
224 .filter((model): model is ServerProviderModel => model !== undefined);
225}
226
227const discoverGrokModelsViaAcp = (
228 grokSettings: GrokSettings,
229 environment: NodeJS.ProcessEnv = process.env,
230) =>
231 Effect.gen(function* () {
232 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
233 const acp = yield* makeGrokAcpRuntime({
234 grokSettings,
235 environment,
236 childProcessSpawner,
237 cwd: process.cwd(),
238 clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
239 });
240 const started = yield* acp.start();
241 return buildGrokDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);
242 }).pipe(Effect.scoped);
243
244const runGrokVersionCommand = (
245 grokSettings: GrokSettings,
246 environment: NodeJS.ProcessEnv = process.env,
247) =>
248 Effect.gen(function* () {
249 const command = grokSettings.binaryPath || "grok";
250 const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
251 env: environment,
252 });
253 return yield* spawnAndCollect(
254 command,
255 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
256 env: environment,
257 shell: spawnCommand.shell,
258 }),
259 );
260 });
261
262export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
263 grokSettings: GrokSettings,
264 environment: NodeJS.ProcessEnv = process.env,
265 cwd?: string,
266): Effect.fn.Return<
267 ServerProviderDraft,
268 never,
269 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
270> {
271 const checkedAt = DateTime.formatIso(yield* DateTime.now);
272 const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
273
274 if (!grokSettings.enabled) {
275 return buildServerProvider({
276 presentation: GROK_PRESENTATION,
277 enabled: false,
278 checkedAt,
279 models: fallbackModels,
280 probe: {
281 installed: false,
282 version: null,
283 status: "warning",
284 auth: { status: "unknown" },
285 message: "Grok is disabled in T3 Code settings.",
286 },
287 });
288 }
289
290 const versionResult = yield* runGrokVersionCommand(grokSettings, environment).pipe(
291 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
292 Effect.result,
293 );
294
295 if (Result.isFailure(versionResult)) {
296 const error = versionResult.failure;
297 yield* Effect.logWarning("Grok CLI health check failed.", {
298 errorTag: error._tag,
299 });
300 return buildServerProvider({
301 presentation: GROK_PRESENTATION,
302 enabled: grokSettings.enabled,
303 checkedAt,
304 models: fallbackModels,
305 probe: {
306 installed: !isCommandMissingCause(error),
307 version: null,
308 status: "error",
309 auth: { status: "unknown" },
310 message: isCommandMissingCause(error)
311 ? "Grok CLI (`grok`) is not installed or not on PATH."
312 : "Failed to execute Grok CLI health check.",
313 },
314 });
315 }
316
317 if (Option.isNone(versionResult.success)) {
318 return buildServerProvider({
319 presentation: GROK_PRESENTATION,
320 enabled: grokSettings.enabled,
321 checkedAt,
322 models: fallbackModels,
323 probe: {
324 installed: true,
325 version: null,
326 status: "error",
327 auth: { status: "unknown" },
328 message: "Grok CLI is installed but timed out while running `grok --version`.",
329 },
330 });
331 }
332
333 const versionOutput = versionResult.success.value;
334 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
335 if (versionOutput.code !== 0) {
336 yield* Effect.logWarning("Grok CLI version probe exited with a non-zero status.", {
337 exitCode: versionOutput.code,
338 stdoutLength: versionOutput.stdout.length,
339 stderrLength: versionOutput.stderr.length,
340 });
341 return buildServerProvider({
342 presentation: GROK_PRESENTATION,
343 enabled: grokSettings.enabled,
344 checkedAt,
345 models: fallbackModels,
346 probe: {
347 installed: true,
348 version,
349 status: "error",
350 auth: { status: "unknown" },
351 message: "Grok CLI is installed but failed to run.",
352 },
353 });
354 }
355
356 const skills = yield* discoverGrokSkills(grokSettings, environment, cwd);
357
358 const discoveryExit = yield* discoverGrokModelsViaAcp(grokSettings, environment).pipe(
359 Effect.timeoutOption(GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
360 Effect.exit,
361 );
362 if (Exit.isFailure(discoveryExit)) {
363 yield* Effect.logWarning("Grok ACP model discovery failed", {
364 errorTag: causeErrorTag(discoveryExit.cause),
365 });
366 return buildServerProvider({
367 presentation: GROK_PRESENTATION,
368 enabled: grokSettings.enabled,
369 checkedAt,
370 models: fallbackModels,
371 skills,
372 probe: {
373 installed: true,
374 version,
375 status: "error",
376 auth: { status: "unknown" },
377 message: "Grok CLI is installed but ACP startup failed. Check server logs for details.",
378 },
379 });
380 }
381 if (Option.isNone(discoveryExit.value)) {
382 yield* Effect.logWarning(
383 `Grok ACP model discovery timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
384 );
385 return buildServerProvider({
386 presentation: GROK_PRESENTATION,
387 enabled: grokSettings.enabled,
388 checkedAt,
389 models: fallbackModels,
390 skills,
391 probe: {
392 installed: true,
393 version,
394 status: "error",
395 auth: { status: "unknown" },
396 message: `Grok CLI is installed but ACP startup timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
397 },
398 });
399 }
400 const discoveredModels = discoveryExit.value.value;
401 const models =
402 discoveredModels.length > 0
403 ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
404 : fallbackModels;
405
406 return buildServerProvider({
407 presentation: GROK_PRESENTATION,
408 enabled: grokSettings.enabled,
409 checkedAt,
410 models,
411 skills,
412 probe: {
413 installed: true,
414 version,
415 status: "ready",
416 auth: { status: "unknown" },
417 },
418 });
419});
420
421export const enrichGrokSnapshot = (input: {
422 readonly snapshot: ServerProvider;
423 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
424 readonly enableProviderUpdateChecks?: boolean;
425 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
426 readonly httpClient: HttpClient.HttpClient;
427}): Effect.Effect<void> => {
428 const { snapshot, publishSnapshot } = input;
429
430 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
431 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
432 }).pipe(
433 Effect.provideService(HttpClient.HttpClient, input.httpClient),
434 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
435 Effect.catchCause((cause) =>
436 Effect.logWarning("Grok version advisory enrichment failed", {
437 errorTag: causeErrorTag(cause),
438 }),
439 ),
440 Effect.asVoid,
441 );
442};