Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GrokProvider.ts

541 lines17.2 KB

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