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

GrokProvider.ts

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