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

status.ts

597 lines19.5 KB

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