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

status.ts

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