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

status.ts

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