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;
62const GROK_ACP_INITIALIZE_TIMEOUT_MS = 8_000;
63const GROK_API_KEY_ENV = "XAI_API_KEY";
64
65const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
66 {
67 slug: GROK_DEFAULT_MODEL_SLUG,
68 name: "Grok Build",
69 isCustom: false,
70 capabilities: EMPTY_CAPABILITIES,
71 },
72];
73
74export function buildInitialGrokProviderSnapshot(
75 grokSettings: GrokSettings,
76): Effect.Effect<ServerProviderDraft> {
77 return Effect.gen(function* () {
78 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
79 const models = grokModelsFromSettings(grokSettings.customModels);
80
81 if (!grokSettings.enabled) {
82 return buildServerProvider({
83 presentation: GROK_PRESENTATION,
84 enabled: false,
85 checkedAt,
86 models,
87 probe: {
88 installed: false,
89 version: null,
90 status: "warning",
91 auth: { status: "unknown" },
92 message: "Grok is disabled in T3 Code settings.",
93 },
94 });
95 }
96
97 return buildServerProvider({
98 presentation: GROK_PRESENTATION,
99 enabled: true,
100 checkedAt,
101 models,
102 probe: {
103 installed: true,
104 version: null,
105 status: "warning",
106 auth: { status: "unknown" },
107 message: "Checking Grok CLI availability...",
108 },
109 });
110 });
111}
112
113function grokModelsFromSettings(
114 customModels: ReadonlyArray<CustomModelSetting> | undefined,
115 builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
116): ReadonlyArray<ServerProviderModel> {
117 return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);
118}
119
120function nonEmptyString(value: unknown): string | undefined {
121 return typeof value === "string" ? value.trim() || undefined : undefined;
122}
123
124function isRecord(value: unknown): value is Record<string, unknown> {
125 return typeof value === "object" && value !== null && !Array.isArray(value);
126}
127
128function grokReasoningOptionsFromModel(model: EffectAcpSchema.ModelInfo): {
129 readonly options: ReadonlyArray<{
130 value: string;
131 label: string;
132 description?: string;
133 isDefault?: boolean;
134 }>;
135 readonly currentValue: string | undefined;
136} {
137 const meta = model._meta;
138 if (!meta || meta.supportsReasoningEffort === false) {
139 return { options: [], currentValue: undefined };
140 }
141
142 const currentEffort = nonEmptyString(meta.reasoningEffort);
143 const advertisedOptions = Array.isArray(meta.reasoningEfforts) ? meta.reasoningEfforts : [];
144 const seen = new Set<string>();
145 const options: Array<{
146 value: string;
147 label: string;
148 description?: string;
149 advertisedDefault: boolean;
150 }> = [];
151
152 for (const entry of advertisedOptions) {
153 if (!isRecord(entry)) {
154 continue;
155 }
156 const rawValue = nonEmptyString(entry.value);
157 const rawId = nonEmptyString(entry.id);
158 const value =
159 rawValue && isValidGrokReasoningEffortToken(rawValue)
160 ? rawValue
161 : rawId && isValidGrokReasoningEffortToken(rawId)
162 ? rawId
163 : undefined;
164 if (value === undefined || seen.has(value)) {
165 continue;
166 }
167 seen.add(value);
168 const description = nonEmptyString(entry.description);
169 options.push({
170 value,
171 label: nonEmptyString(entry.label) ?? value,
172 ...(description ? { description } : {}),
173 advertisedDefault: entry.default === true || entry.isDefault === true,
174 });
175 }
176
177 const currentValue =
178 currentEffort && options.some((option) => option.value === currentEffort)
179 ? currentEffort
180 : undefined;
181 const advertisedDefaults = options.filter((option) => option.advertisedDefault);
182 const selectedDefault =
183 advertisedDefaults.find((option) => option.value === currentValue)?.value ??
184 advertisedDefaults[0]?.value;
185 return {
186 options: options.map(({ value, label, description }) => ({
187 value,
188 label,
189 ...(description ? { description } : {}),
190 ...(value === selectedDefault ? { isDefault: true } : {}),
191 })),
192 currentValue: currentValue ?? selectedDefault,
193 };
194}
195
196export function buildGrokModelCapabilities(model: EffectAcpSchema.ModelInfo): ModelCapabilities {
197 const reasoning = grokReasoningOptionsFromModel(model);
198 return reasoning.options.length > 0
199 ? createModelCapabilities({
200 optionDescriptors: [
201 {
202 id: "reasoningEffort",
203 label: "Reasoning",
204 type: "select",
205 options: reasoning.options.map((option) => ({
206 id: option.value,
207 label: option.label,
208 ...(option.description ? { description: option.description } : {}),
209 ...(option.isDefault ? { isDefault: true } : {}),
210 })),
211 ...(reasoning.currentValue ? { currentValue: reasoning.currentValue } : {}),
212 },
213 ],
214 })
215 : EMPTY_CAPABILITIES;
216}
217
218export function buildGrokModelsFromSessionModelState(
219 modelState: EffectAcpSchema.SessionModelState | null | undefined,
220): ReadonlyArray<ServerProviderModel> {
221 if (!modelState || modelState.availableModels.length === 0) {
222 return [];
223 }
224 const currentModelId = modelState.currentModelId.trim();
225 const seen = new Set<string>();
226 return modelState.availableModels.flatMap((model): ServerProviderModel[] => {
227 const slug = resolveGrokAcpBaseModelId(model.modelId);
228 if (!slug || seen.has(slug)) {
229 return [];
230 }
231 seen.add(slug);
232 return [
233 {
234 slug,
235 name: model.name.trim() || slug,
236 isCustom: false,
237 ...(model.modelId.trim() === currentModelId ? { isDefault: true } : {}),
238 capabilities: buildGrokModelCapabilities(model),
239 },
240 ];
241 });
242}
243
244export interface GrokModelsCliOutput {
245 readonly authenticated: boolean | null;
246 readonly models: ReadonlyArray<ServerProviderModel>;
247}
248
249/**
250 * The command exits 0 whether or not the user is logged in, so the text is the
251 * only signal.
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
307const decodeAvailableCommands = Schema.decodeUnknownOption(Schema.Array(Schema.Unknown));
308const decodeAvailableCommand = Schema.decodeUnknownOption(
309 Schema.Struct({
310 name: Schema.String,
311 description: Schema.String,
312 input: Schema.optional(Schema.NullOr(Schema.Struct({ hint: Schema.String }))),
313 }),
314);
315
316export function grokSlashCommandsFromInitialize(
317 initialized: EffectAcpSchema.InitializeResponse,
318): ReadonlyArray<ServerProviderSlashCommand> {
319 const commands = decodeAvailableCommands(initialized._meta?.availableCommands);
320 const byName = new Map<string, ServerProviderSlashCommand>([
321 [COMPACT_SLASH_COMMAND.name, COMPACT_SLASH_COMMAND],
322 ]);
323 for (const entry of Option.getOrElse(commands, () => [])) {
324 const decoded = decodeAvailableCommand(entry);
325 if (Option.isNone(decoded)) continue;
326 const command = decoded.value;
327 const name = command.name.trim();
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 * This never calls `authenticate` or `session/new`, so it cannot open a browser login or
344 * boot the workspace's MCP servers.
345 */
346const discoverGrokMetadataViaAcpInitialize = (
347 grokSettings: GrokSettings,
348 environment: NodeJS.ProcessEnv,
349) =>
350 Effect.gen(function* () {
351 const acp = yield* makeGrokAcpRuntime({
352 grokSettings,
353 environment,
354 cwd: process.cwd(),
355 clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
356 });
357 const initialized = yield* acp.initialize();
358 return {
359 models: buildGrokModelsFromSessionModelState(sessionModelStateFromInitialize(initialized)),
360 slashCommands: grokSlashCommandsFromInitialize(initialized),
361 };
362 }).pipe(Effect.scoped);
363
364export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
365 grokSettings: GrokSettings,
366 environment: NodeJS.ProcessEnv = process.env,
367 cwd?: string,
368): Effect.fn.Return<
369 ServerProviderDraft,
370 never,
371 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
372> {
373 const checkedAt = DateTime.formatIso(yield* DateTime.now);
374 const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
375
376 if (!grokSettings.enabled) {
377 return buildServerProvider({
378 presentation: GROK_PRESENTATION,
379 enabled: false,
380 checkedAt,
381 models: fallbackModels,
382 probe: {
383 installed: false,
384 version: null,
385 status: "warning",
386 auth: { status: "unknown" },
387 message: "Grok is disabled in T3 Code settings.",
388 },
389 });
390 }
391
392 const probeEnvironment = grokProbeEnvironment(environment);
393
394 const versionResult = yield* runGrokCliCommand(
395 grokSettings,
396 ["--version"],
397 probeEnvironment,
398 ).pipe(Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS), Effect.result);
399
400 if (Result.isFailure(versionResult)) {
401 const error = versionResult.failure;
402 yield* Effect.logWarning("Grok CLI health check failed.", {
403 errorTag: error._tag,
404 });
405 return buildServerProvider({
406 presentation: GROK_PRESENTATION,
407 enabled: grokSettings.enabled,
408 checkedAt,
409 models: fallbackModels,
410 probe: {
411 installed: !isCommandMissingCause(error),
412 version: null,
413 status: "error",
414 auth: { status: "unknown" },
415 message: isCommandMissingCause(error)
416 ? "Grok CLI (`grok`) is not installed or not on PATH."
417 : "Failed to execute Grok CLI health check.",
418 },
419 });
420 }
421
422 if (Option.isNone(versionResult.success)) {
423 return buildServerProvider({
424 presentation: GROK_PRESENTATION,
425 enabled: grokSettings.enabled,
426 checkedAt,
427 models: fallbackModels,
428 probe: {
429 installed: true,
430 version: null,
431 status: "error",
432 auth: { status: "unknown" },
433 message: "Grok CLI is installed but timed out while running `grok --version`.",
434 },
435 });
436 }
437
438 const versionOutput = versionResult.success.value;
439 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
440 if (versionOutput.code !== 0) {
441 yield* Effect.logWarning("Grok CLI version probe exited with a non-zero status.", {
442 exitCode: versionOutput.code,
443 stdoutLength: versionOutput.stdout.length,
444 stderrLength: versionOutput.stderr.length,
445 });
446 return buildServerProvider({
447 presentation: GROK_PRESENTATION,
448 enabled: grokSettings.enabled,
449 checkedAt,
450 models: fallbackModels,
451 probe: {
452 installed: true,
453 version,
454 status: "error",
455 auth: { status: "unknown" },
456 message: "Grok CLI is installed but failed to run.",
457 },
458 });
459 }
460
461 // `grok models` reports login state and model slugs without starting the agent.
462 const modelsResult = yield* runGrokCliCommand(grokSettings, ["models"], probeEnvironment).pipe(
463 Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
464 Effect.result,
465 );
466 // Only a clean exit is parsed. Failed invocations print help or error text that
467 // must not be read as model slugs or as a login verdict.
468 const modelsOutput =
469 Result.isSuccess(modelsResult) &&
470 Option.isSome(modelsResult.success) &&
471 modelsResult.success.value.code === 0
472 ? modelsResult.success.value
473 : undefined;
474 const cliModels: GrokModelsCliOutput = modelsOutput
475 ? parseGrokModelsCliOutput(`${modelsOutput.stdout}\n${modelsOutput.stderr}`)
476 : { authenticated: null, models: [] };
477 if (!modelsOutput) {
478 yield* Effect.logWarning("Grok CLI model listing failed or timed out.", {
479 errorTag: Result.isFailure(modelsResult)
480 ? modelsResult.failure._tag
481 : Option.isNone(modelsResult.success)
482 ? "Timeout"
483 : `ExitCode${modelsResult.success.value.code}`,
484 });
485 }
486
487 const auth: ServerProviderAuth = environment[GROK_API_KEY_ENV]?.trim()
488 ? { status: "authenticated", type: "api_key", label: "xAI API key" }
489 : cliModels.authenticated === true
490 ? { status: "authenticated", type: "cached_token", label: "Grok account" }
491 : cliModels.authenticated === false
492 ? { status: "unauthenticated" }
493 : { status: "unknown" };
494
495 // Skill discovery applies the probe environment itself.
496 const skills = yield* discoverGrokSkills(grokSettings, environment, cwd).pipe(
497 Effect.tapError((cause) => Effect.logDebug("Grok skill discovery failed.", { cause })),
498 Effect.orElseSucceed(() => []),
499 );
500
501 const acpExit = yield* discoverGrokMetadataViaAcpInitialize(grokSettings, probeEnvironment).pipe(
502 Effect.timeoutOption(GROK_ACP_INITIALIZE_TIMEOUT_MS),
503 Effect.exit,
504 );
505 const acpMetadata = Exit.isSuccess(acpExit) ? Option.getOrUndefined(acpExit.value) : undefined;
506 const acpModels = acpMetadata?.models ?? [];
507 const acpFailed = Exit.isFailure(acpExit) || Option.isNone(acpExit.value);
508 if (acpFailed) {
509 yield* Effect.logWarning("Grok ACP initialize probe failed or timed out.", {
510 errorTag: Exit.isFailure(acpExit) ? causeErrorTag(acpExit.cause) : "Timeout",
511 });
512 }
513
514 const discoveredModels = acpModels.length > 0 ? acpModels : cliModels.models;
515 const models =
516 discoveredModels.length > 0
517 ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
518 : fallbackModels;
519
520 if (auth.status === "unauthenticated") {
521 return buildServerProvider({
522 presentation: GROK_PRESENTATION,
523 enabled: grokSettings.enabled,
524 checkedAt,
525 models,
526 skills,
527 probe: {
528 installed: true,
529 version,
530 status: "error",
531 auth,
532 message: "Grok CLI is installed but not logged in. Run `grok login`.",
533 },
534 });
535 }
536
537 return buildServerProvider({
538 presentation: GROK_PRESENTATION,
539 enabled: grokSettings.enabled,
540 checkedAt,
541 models,
542 skills,
543 slashCommands: acpMetadata?.slashCommands ?? [COMPACT_SLASH_COMMAND],
544 probe: {
545 installed: true,
546 version,
547 status: acpFailed ? "warning" : "ready",
548 auth,
549 ...(acpFailed
550 ? {
551 message:
552 "Grok CLI is installed but ACP initialize failed. Model options may be incomplete.",
553 }
554 : {}),
555 },
556 });
557});
558
559export const enrichGrokSnapshot = (input: {
560 readonly snapshot: ServerProvider;
561 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
562 readonly enableProviderUpdateChecks?: boolean;
563 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
564}): Effect.Effect<
565 void,
566 never,
567 HttpClient.HttpClient | ProviderLatestVersions.ProviderLatestVersions
568> => {
569 const { snapshot, publishSnapshot } = input;
570
571 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
572 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
573 }).pipe(
574 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
575 Effect.catchCause((cause) =>
576 Effect.logWarning("Grok version advisory enrichment failed", {
577 errorTag: causeErrorTag(cause),
578 }),
579 ),
580 Effect.asVoid,
581 );
582};