Open History to see the last commit
1import {
2 type GrokSettings,
3 type ModelCapabilities,
4 type ServerProvider,
5 type ServerProviderAuth,
6 type ServerProviderModel,
7} from "@t3tools/contracts";
8import type * as EffectAcpSchema from "effect-acp/schema";
9import { causeErrorTag } from "@t3tools/shared/observability";
10import * as Crypto from "effect/Crypto";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Option from "effect/Option";
15import * as Result from "effect/Result";
16import { HttpClient } from "effect/unstable/http";
17import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
18import { createModelCapabilities } from "@t3tools/shared/model";
19import { resolveSpawnCommand } from "@t3tools/shared/shell";
20
21import {
22 AUTH_PROBE_TIMEOUT_MS,
23 buildServerProvider,
24 isCommandMissingCause,
25 parseGenericCliVersion,
26 providerModelsFromSettings,
27 spawnAndCollect,
28 type ServerProviderDraft,
29} from "../providerSnapshot.ts";
30import {
31 enrichProviderSnapshotWithVersionAdvisory,
32 type ProviderMaintenanceCapabilities,
33} from "../providerMaintenance.ts";
34import {
35 GROK_DEFAULT_MODEL_SLUG,
36 isValidGrokReasoningEffortToken,
37 makeGrokAcpRuntime,
38 resolveGrokAcpBaseModelId,
39} from "../acp/GrokAcpSupport.ts";
40import { sessionModelStateFromInitialize } from "../acp/AcpRuntimeModel.ts";
41import { discoverGrokSkills } from "../Drivers/GrokSkills.ts";
42
43const GROK_PRESENTATION = {
44 displayName: "Grok",
45 badgeLabel: "Early Access",
46 showInteractionModeToggle: false,
47} as const;
48const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
49 optionDescriptors: [],
50});
51
52const VERSION_PROBE_TIMEOUT_MS = 4_000;
53// `initialize` is a single local round trip, so this is generous even on slow machines.
54const GROK_ACP_INITIALIZE_TIMEOUT_MS = 8_000;
55const GROK_API_KEY_ENV = "XAI_API_KEY";
56
57const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
58 {
59 slug: GROK_DEFAULT_MODEL_SLUG,
60 name: "Grok Build",
61 isCustom: false,
62 capabilities: EMPTY_CAPABILITIES,
63 },
64];
65
66export function buildInitialGrokProviderSnapshot(
67 grokSettings: GrokSettings,
68): Effect.Effect<ServerProviderDraft> {
69 return Effect.gen(function* () {
70 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
71 const models = grokModelsFromSettings(grokSettings.customModels);
72
73 if (!grokSettings.enabled) {
74 return buildServerProvider({
75 presentation: GROK_PRESENTATION,
76 enabled: false,
77 checkedAt,
78 models,
79 probe: {
80 installed: false,
81 version: null,
82 status: "warning",
83 auth: { status: "unknown" },
84 message: "Grok is disabled in T3 Code settings.",
85 },
86 });
87 }
88
89 return buildServerProvider({
90 presentation: GROK_PRESENTATION,
91 enabled: true,
92 checkedAt,
93 models,
94 probe: {
95 installed: true,
96 version: null,
97 status: "warning",
98 auth: { status: "unknown" },
99 message: "Checking Grok CLI availability...",
100 },
101 });
102 });
103}
104
105function grokModelsFromSettings(
106 customModels: ReadonlyArray<string> | undefined,
107 builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
108): ReadonlyArray<ServerProviderModel> {
109 return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);
110}
111
112function nonEmptyString(value: unknown): string | undefined {
113 return typeof value === "string" ? value.trim() || undefined : undefined;
114}
115
116function isRecord(value: unknown): value is Record<string, unknown> {
117 return typeof value === "object" && value !== null && !Array.isArray(value);
118}
119
120function grokReasoningOptionsFromModel(model: EffectAcpSchema.ModelInfo): {
121 readonly options: ReadonlyArray<{
122 value: string;
123 label: string;
124 description?: string;
125 isDefault?: boolean;
126 }>;
127 readonly currentValue: string | undefined;
128} {
129 const meta = model._meta;
130 if (!meta || meta.supportsReasoningEffort === false) {
131 return { options: [], currentValue: undefined };
132 }
133
134 const currentEffort = nonEmptyString(meta.reasoningEffort);
135 const advertisedOptions = Array.isArray(meta.reasoningEfforts) ? meta.reasoningEfforts : [];
136 const seen = new Set<string>();
137 const options: Array<{
138 value: string;
139 label: string;
140 description?: string;
141 advertisedDefault: boolean;
142 }> = [];
143
144 for (const entry of advertisedOptions) {
145 if (!isRecord(entry)) {
146 continue;
147 }
148 const rawValue = nonEmptyString(entry.value);
149 const rawId = nonEmptyString(entry.id);
150 const value =
151 rawValue && isValidGrokReasoningEffortToken(rawValue)
152 ? rawValue
153 : rawId && isValidGrokReasoningEffortToken(rawId)
154 ? rawId
155 : undefined;
156 if (value === undefined || seen.has(value)) {
157 continue;
158 }
159 seen.add(value);
160 const description = nonEmptyString(entry.description);
161 options.push({
162 value,
163 label: nonEmptyString(entry.label) ?? value,
164 ...(description ? { description } : {}),
165 advertisedDefault: entry.default === true || entry.isDefault === true,
166 });
167 }
168
169 const currentValue =
170 currentEffort && options.some((option) => option.value === currentEffort)
171 ? currentEffort
172 : undefined;
173 const advertisedDefaults = options.filter((option) => option.advertisedDefault);
174 const selectedDefault =
175 advertisedDefaults.find((option) => option.value === currentValue)?.value ??
176 advertisedDefaults[0]?.value;
177 return {
178 options: options.map(({ value, label, description }) => ({
179 value,
180 label,
181 ...(description ? { description } : {}),
182 ...(value === selectedDefault ? { isDefault: true } : {}),
183 })),
184 currentValue: currentValue ?? selectedDefault,
185 };
186}
187
188export function buildGrokModelCapabilities(model: EffectAcpSchema.ModelInfo): ModelCapabilities {
189 const reasoning = grokReasoningOptionsFromModel(model);
190 return reasoning.options.length > 0
191 ? createModelCapabilities({
192 optionDescriptors: [
193 {
194 id: "reasoningEffort",
195 label: "Reasoning",
196 type: "select",
197 options: reasoning.options.map((option) => ({
198 id: option.value,
199 label: option.label,
200 ...(option.description ? { description: option.description } : {}),
201 ...(option.isDefault ? { isDefault: true } : {}),
202 })),
203 ...(reasoning.currentValue ? { currentValue: reasoning.currentValue } : {}),
204 },
205 ],
206 })
207 : EMPTY_CAPABILITIES;
208}
209
210/** Models advertised by the ACP agent, with the session's current model marked as default. */
211export function buildGrokModelsFromSessionModelState(
212 modelState: EffectAcpSchema.SessionModelState | null | undefined,
213): ReadonlyArray<ServerProviderModel> {
214 if (!modelState || modelState.availableModels.length === 0) {
215 return [];
216 }
217 const currentModelId = modelState.currentModelId.trim();
218 const seen = new Set<string>();
219 return modelState.availableModels.flatMap((model): ServerProviderModel[] => {
220 const slug = resolveGrokAcpBaseModelId(model.modelId);
221 if (!slug || seen.has(slug)) {
222 return [];
223 }
224 seen.add(slug);
225 return [
226 {
227 slug,
228 name: model.name.trim() || slug,
229 isCustom: false,
230 ...(model.modelId.trim() === currentModelId ? { isDefault: true } : {}),
231 capabilities: buildGrokModelCapabilities(model),
232 },
233 ];
234 });
235}
236
237export interface GrokModelsCliOutput {
238 /** True or false when the CLI printed a login line, null when it printed neither. */
239 readonly authenticated: boolean | null;
240 readonly models: ReadonlyArray<ServerProviderModel>;
241}
242
243/**
244 * Parses `grok models`. The command exits 0 whether or not the user is logged in, so the
245 * text is the only signal. Current output looks like:
246 *
247 * You are logged in with grok.com.
248 * Default model: grok-4.6
249 * Available models:
250 * * grok-4.6 (default)
251 * - grok-4.5
252 */
253export function parseGrokModelsCliOutput(output: string): GrokModelsCliOutput {
254 const authenticated = /you are logged in/i.test(output)
255 ? true
256 : /not authenticated|not logged in/i.test(output)
257 ? false
258 : null;
259
260 const seen = new Set<string>();
261 const models: ServerProviderModel[] = [];
262 for (const line of output.split(/\r?\n/)) {
263 const bullet = line.match(/^\s*[*-]\s+(\S+)(.*)$/);
264 if (!bullet?.[1]) {
265 continue;
266 }
267 const slug = resolveGrokAcpBaseModelId(bullet[1]);
268 if (seen.has(slug)) {
269 continue;
270 }
271 seen.add(slug);
272 models.push({
273 slug,
274 name: displayNameFromGrokModelSlug(slug),
275 isCustom: false,
276 ...(/\(default\)/i.test(bullet[2] ?? "") ? { isDefault: true } : {}),
277 capabilities: EMPTY_CAPABILITIES,
278 });
279 }
280 return { authenticated, models };
281}
282
283function displayNameFromGrokModelSlug(slug: string): string {
284 return slug
285 .split(/[-_]/g)
286 .map((part) => (part.toLowerCase() === "grok" ? "Grok" : part))
287 .join(" ");
288}
289
290const runGrokCliCommand = (
291 grokSettings: GrokSettings,
292 args: ReadonlyArray<string>,
293 environment: NodeJS.ProcessEnv,
294) =>
295 Effect.gen(function* () {
296 const command = grokSettings.binaryPath || "grok";
297 const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });
298 return yield* spawnAndCollect(
299 command,
300 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
301 env: environment,
302 shell: spawnCommand.shell,
303 }),
304 );
305 });
306
307/**
308 * Reads model metadata from `initialize._meta.modelState`. This never calls `authenticate`
309 * or `session/new`, so it cannot open a browser login or boot the workspace's MCP servers.
310 */
311const discoverGrokModelsViaAcpInitialize = (
312 grokSettings: GrokSettings,
313 environment: NodeJS.ProcessEnv,
314) =>
315 Effect.gen(function* () {
316 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
317 const acp = yield* makeGrokAcpRuntime({
318 grokSettings,
319 environment,
320 childProcessSpawner,
321 cwd: process.cwd(),
322 clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
323 });
324 const initialized = yield* acp.initialize();
325 return buildGrokModelsFromSessionModelState(sessionModelStateFromInitialize(initialized));
326 }).pipe(Effect.scoped);
327
328export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
329 grokSettings: GrokSettings,
330 environment: NodeJS.ProcessEnv = process.env,
331 cwd?: string,
332): Effect.fn.Return<
333 ServerProviderDraft,
334 never,
335 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
336> {
337 const checkedAt = DateTime.formatIso(yield* DateTime.now);
338 const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
339
340 if (!grokSettings.enabled) {
341 return buildServerProvider({
342 presentation: GROK_PRESENTATION,
343 enabled: false,
344 checkedAt,
345 models: fallbackModels,
346 probe: {
347 installed: false,
348 version: null,
349 status: "warning",
350 auth: { status: "unknown" },
351 message: "Grok is disabled in T3 Code settings.",
352 },
353 });
354 }
355
356 const versionResult = yield* runGrokCliCommand(grokSettings, ["--version"], environment).pipe(
357 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
358 Effect.result,
359 );
360
361 if (Result.isFailure(versionResult)) {
362 const error = versionResult.failure;
363 yield* Effect.logWarning("Grok CLI health check failed.", {
364 errorTag: error._tag,
365 });
366 return buildServerProvider({
367 presentation: GROK_PRESENTATION,
368 enabled: grokSettings.enabled,
369 checkedAt,
370 models: fallbackModels,
371 probe: {
372 installed: !isCommandMissingCause(error),
373 version: null,
374 status: "error",
375 auth: { status: "unknown" },
376 message: isCommandMissingCause(error)
377 ? "Grok CLI (`grok`) is not installed or not on PATH."
378 : "Failed to execute Grok CLI health check.",
379 },
380 });
381 }
382
383 if (Option.isNone(versionResult.success)) {
384 return buildServerProvider({
385 presentation: GROK_PRESENTATION,
386 enabled: grokSettings.enabled,
387 checkedAt,
388 models: fallbackModels,
389 probe: {
390 installed: true,
391 version: null,
392 status: "error",
393 auth: { status: "unknown" },
394 message: "Grok CLI is installed but timed out while running `grok --version`.",
395 },
396 });
397 }
398
399 const versionOutput = versionResult.success.value;
400 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
401 if (versionOutput.code !== 0) {
402 yield* Effect.logWarning("Grok CLI version probe exited with a non-zero status.", {
403 exitCode: versionOutput.code,
404 stdoutLength: versionOutput.stdout.length,
405 stderrLength: versionOutput.stderr.length,
406 });
407 return buildServerProvider({
408 presentation: GROK_PRESENTATION,
409 enabled: grokSettings.enabled,
410 checkedAt,
411 models: fallbackModels,
412 probe: {
413 installed: true,
414 version,
415 status: "error",
416 auth: { status: "unknown" },
417 message: "Grok CLI is installed but failed to run.",
418 },
419 });
420 }
421
422 // `grok models` reports login state and model slugs without starting the agent.
423 const modelsResult = yield* runGrokCliCommand(grokSettings, ["models"], environment).pipe(
424 Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
425 Effect.result,
426 );
427 // Only a clean exit is parsed. Failed invocations print help or error text that
428 // must not be read as model slugs or as a login verdict.
429 const modelsOutput =
430 Result.isSuccess(modelsResult) &&
431 Option.isSome(modelsResult.success) &&
432 modelsResult.success.value.code === 0
433 ? modelsResult.success.value
434 : undefined;
435 const cliModels: GrokModelsCliOutput = modelsOutput
436 ? parseGrokModelsCliOutput(`${modelsOutput.stdout}\n${modelsOutput.stderr}`)
437 : { authenticated: null, models: [] };
438 if (!modelsOutput) {
439 yield* Effect.logWarning("Grok CLI model listing failed or timed out.", {
440 errorTag: Result.isFailure(modelsResult)
441 ? modelsResult.failure._tag
442 : Option.isNone(modelsResult.success)
443 ? "Timeout"
444 : `ExitCode${modelsResult.success.value.code}`,
445 });
446 }
447
448 const auth: ServerProviderAuth = environment[GROK_API_KEY_ENV]?.trim()
449 ? { status: "authenticated", type: "api_key", label: "xAI API key" }
450 : cliModels.authenticated === true
451 ? { status: "authenticated", type: "cached_token", label: "Grok account" }
452 : cliModels.authenticated === false
453 ? { status: "unauthenticated" }
454 : { status: "unknown" };
455
456 const skills = yield* discoverGrokSkills(grokSettings, environment, cwd).pipe(
457 Effect.tapError((cause) => Effect.logDebug("Grok skill discovery failed.", { cause })),
458 Effect.orElseSucceed(() => []),
459 );
460
461 const acpExit = yield* discoverGrokModelsViaAcpInitialize(grokSettings, environment).pipe(
462 Effect.timeoutOption(GROK_ACP_INITIALIZE_TIMEOUT_MS),
463 Effect.exit,
464 );
465 const acpModels = Exit.isSuccess(acpExit) ? Option.getOrElse(acpExit.value, () => []) : [];
466 const acpFailed = Exit.isFailure(acpExit) || Option.isNone(acpExit.value);
467 if (acpFailed) {
468 yield* Effect.logWarning("Grok ACP initialize probe failed or timed out.", {
469 errorTag: Exit.isFailure(acpExit) ? causeErrorTag(acpExit.cause) : "Timeout",
470 });
471 }
472
473 const discoveredModels = acpModels.length > 0 ? acpModels : cliModels.models;
474 const models =
475 discoveredModels.length > 0
476 ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
477 : fallbackModels;
478
479 if (auth.status === "unauthenticated") {
480 return buildServerProvider({
481 presentation: GROK_PRESENTATION,
482 enabled: grokSettings.enabled,
483 checkedAt,
484 models,
485 skills,
486 probe: {
487 installed: true,
488 version,
489 status: "error",
490 auth,
491 message: "Grok CLI is installed but not logged in. Run `grok login`.",
492 },
493 });
494 }
495
496 return buildServerProvider({
497 presentation: GROK_PRESENTATION,
498 enabled: grokSettings.enabled,
499 checkedAt,
500 models,
501 skills,
502 probe: {
503 installed: true,
504 version,
505 // A failed metadata probe degrades the model picker, it does not make chats fail.
506 status: acpFailed ? "warning" : "ready",
507 auth,
508 ...(acpFailed
509 ? {
510 message:
511 "Grok CLI is installed but ACP initialize failed. Model options may be incomplete.",
512 }
513 : {}),
514 },
515 });
516});
517
518export const enrichGrokSnapshot = (input: {
519 readonly snapshot: ServerProvider;
520 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
521 readonly enableProviderUpdateChecks?: boolean;
522 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
523 readonly httpClient: HttpClient.HttpClient;
524}): Effect.Effect<void> => {
525 const { snapshot, publishSnapshot } = input;
526
527 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
528 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
529 }).pipe(
530 Effect.provideService(HttpClient.HttpClient, input.httpClient),
531 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
532 Effect.catchCause((cause) =>
533 Effect.logWarning("Grok version advisory enrichment failed", {
534 errorTag: causeErrorTag(cause),
535 }),
536 ),
537 Effect.asVoid,
538 );
539};