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