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