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