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