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

GrokProvider.ts

584 lines18.9 KB

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