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

ProviderHealth.ts

603 lines19.3 KB

1/**
2 * ProviderHealthLive - Startup-time provider health checks.
3 *
4 * Performs one-time provider readiness probes when the server starts and
5 * keeps the resulting snapshot in memory for `server.getConfig`.
6 *
7 * Uses effect's ChildProcessSpawner to run CLI probes natively.
8 *
9 * @module ProviderHealthLive
10 */
11import * as OS from "node:os";
12import type {
13 ServerProviderAuthStatus,
14 ServerProviderStatus,
15 ServerProviderStatusState,
16} from "@t3tools/contracts";
17import { Array, Effect, Fiber, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
18import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
19​
20import {
21 formatCodexCliUpgradeMessage,
22 isCodexCliVersionSupported,
23 parseCodexCliVersion,
24} from "../codexCliVersion";
25import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
26​
27const DEFAULT_TIMEOUT_MS = 4_000;
28const CODEX_PROVIDER = "codex" as const;
29const CLAUDE_AGENT_PROVIDER = "claudeAgent" as const;
30​
31// ── Pure helpers ────────────────────────────────────────────────────
32​
33export interface CommandResult {
34 readonly stdout: string;
35 readonly stderr: string;
36 readonly code: number;
38​
39function nonEmptyTrimmed(value: string | undefined): string | undefined {
40 if (!value) return undefined;
41 const trimmed = value.trim();
42 return trimmed.length > 0 ? trimmed : undefined;
44​
45function isCommandMissingCause(error: unknown): boolean {
46 if (!(error instanceof Error)) return false;
47 const lower = error.message.toLowerCase();
48 return lower.includes("enoent") || lower.includes("notfound");
50​
51function detailFromResult(
52 result: CommandResult & { readonly timedOut?: boolean },
53): string | undefined {
54 if (result.timedOut) return "Timed out while running command.";
55 const stderr = nonEmptyTrimmed(result.stderr);
56 if (stderr) return stderr;
57 const stdout = nonEmptyTrimmed(result.stdout);
58 if (stdout) return stdout;
59 if (result.code !== 0) {
60 return `Command exited with code ${result.code}.`;
61 }
62 return undefined;
64​
65function extractAuthBoolean(value: unknown): boolean | undefined {
66 if (Array.isArray(value)) {
67 for (const entry of value) {
68 const nested = extractAuthBoolean(entry);
69 if (nested !== undefined) return nested;
70 }
71 return undefined;
72 }
73​
74 if (!value || typeof value !== "object") return undefined;
75​
76 const record = value as Record<string, unknown>;
77 for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
78 if (typeof record[key] === "boolean") return record[key];
79 }
80 for (const key of ["auth", "status", "session", "account"] as const) {
81 const nested = extractAuthBoolean(record[key]);
82 if (nested !== undefined) return nested;
83 }
84 return undefined;
86​
87export function parseAuthStatusFromOutput(result: CommandResult): {
88 readonly status: ServerProviderStatusState;
89 readonly authStatus: ServerProviderAuthStatus;
90 readonly message?: string;
91} {
92 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
93​
94 if (
95 lowerOutput.includes("unknown command") ||
96 lowerOutput.includes("unrecognized command") ||
97 lowerOutput.includes("unexpected argument")
98 ) {
99 return {
100 status: "warning",
101 authStatus: "unknown",
102 message: "Codex CLI authentication status command is unavailable in this Codex version.",
103 };
104 }
105​
106 if (
107 lowerOutput.includes("not logged in") ||
108 lowerOutput.includes("login required") ||
109 lowerOutput.includes("authentication required") ||
110 lowerOutput.includes("run `codex login`") ||
111 lowerOutput.includes("run codex login")
112 ) {
113 return {
114 status: "error",
115 authStatus: "unauthenticated",
116 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
117 };
118 }
119​
120 const parsedAuth = (() => {
121 const trimmed = result.stdout.trim();
122 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
123 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
124 }
125 try {
126 return {
127 attemptedJsonParse: true as const,
128 auth: extractAuthBoolean(JSON.parse(trimmed)),
129 };
130 } catch {
131 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
132 }
133 })();
134​
135 if (parsedAuth.auth === true) {
136 return { status: "ready", authStatus: "authenticated" };
137 }
138 if (parsedAuth.auth === false) {
139 return {
140 status: "error",
141 authStatus: "unauthenticated",
142 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
143 };
144 }
145 if (parsedAuth.attemptedJsonParse) {
146 return {
147 status: "warning",
148 authStatus: "unknown",
149 message:
150 "Could not verify Codex authentication status from JSON output (missing auth marker).",
151 };
152 }
153 if (result.code === 0) {
154 return { status: "ready", authStatus: "authenticated" };
155 }
156​
157 const detail = detailFromResult(result);
158 return {
159 status: "warning",
160 authStatus: "unknown",
161 message: detail
162 ? `Could not verify Codex authentication status. ${detail}`
163 : "Could not verify Codex authentication status.",
164 };
166​
167// ── Codex CLI config detection ──────────────────────────────────────
168​
169/**
170 * Providers that use OpenAI-native authentication via `codex login`.
171 * When the configured `model_provider` is one of these, the `codex login
172 * status` probe still runs. For any other provider value the auth probe
173 * is skipped because authentication is handled externally (e.g. via
174 * environment variables like `PORTKEY_API_KEY` or `AZURE_API_KEY`).
175 */
176const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
177​
178/**
179 * Read the `model_provider` value from the Codex CLI config file.
180 *
181 * Looks for the file at `$CODEX_HOME/config.toml` (falls back to
182 * `~/.codex/config.toml`). Uses a simple line-by-line scan rather than
183 * a full TOML parser to avoid adding a dependency for a single key.
184 *
185 * Returns `undefined` when the file does not exist or does not set
186 * `model_provider`.
187 */
188export const readCodexConfigModelProvider = Effect.gen(function* () {
189 const fileSystem = yield* FileSystem.FileSystem;
190 const path = yield* Path.Path;
191 const codexHome = process.env.CODEX_HOME || path.join(OS.homedir(), ".codex");
192 const configPath = path.join(codexHome, "config.toml");
193​
194 const content = yield* fileSystem
195 .readFileString(configPath)
196 .pipe(Effect.orElseSucceed(() => undefined));
197 if (content === undefined) {
198 return undefined;
199 }
200​
201 // We need to find `model_provider = "..."` at the top level of the
202 // TOML file (i.e. before any `[section]` header). Lines inside
203 // `[profiles.*]`, `[model_providers.*]`, etc. are ignored.
204 let inTopLevel = true;
205 for (const line of content.split("\n")) {
206 const trimmed = line.trim();
207 // Skip comments and empty lines.
208 if (!trimmed || trimmed.startsWith("#")) continue;
209 // Detect section headers — once we leave the top level, stop.
210 if (trimmed.startsWith("[")) {
211 inTopLevel = false;
212 continue;
213 }
214 if (!inTopLevel) continue;
215​
216 const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
217 if (match) return match[1];
218 }
219 return undefined;
220});
221​
222/**
223 * Returns `true` when the Codex CLI is configured with a custom
224 * (non-OpenAI) model provider, meaning `codex login` auth is not
225 * required because authentication is handled through provider-specific
226 * environment variables.
227 */
228export const hasCustomModelProvider = Effect.map(
229 readCodexConfigModelProvider,
230 (provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider),
231);
232​
233// ── Effect-native command execution ─────────────────────────────────
234​
235const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
236 Stream.runFold(
237 stream,
238 () => "",
239 (acc, chunk) => acc + new TextDecoder().decode(chunk),
240 );
241​
242const runCodexCommand = (args: ReadonlyArray<string>) =>
243 Effect.gen(function* () {
244 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
245 const command = ChildProcess.make("codex", [...args], {
246 shell: process.platform === "win32",
247 });
248​
249 const child = yield* spawner.spawn(command);
250​
251 const [stdout, stderr, exitCode] = yield* Effect.all(
252 [
253 collectStreamAsString(child.stdout),
254 collectStreamAsString(child.stderr),
255 child.exitCode.pipe(Effect.map(Number)),
256 ],
257 { concurrency: "unbounded" },
258 );
259​
260 return { stdout, stderr, code: exitCode } satisfies CommandResult;
261 }).pipe(Effect.scoped);
262​
263const runClaudeCommand = (args: ReadonlyArray<string>) =>
264 Effect.gen(function* () {
265 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
266 const command = ChildProcess.make("claude", [...args], {
267 shell: process.platform === "win32",
268 });
269​
270 const child = yield* spawner.spawn(command);
271​
272 const [stdout, stderr, exitCode] = yield* Effect.all(
273 [
274 collectStreamAsString(child.stdout),
275 collectStreamAsString(child.stderr),
276 child.exitCode.pipe(Effect.map(Number)),
277 ],
278 { concurrency: "unbounded" },
279 );
280​
281 return { stdout, stderr, code: exitCode } satisfies CommandResult;
282 }).pipe(Effect.scoped);
283​
284// ── Health check ────────────────────────────────────────────────────
285​
286export const checkCodexProviderStatus: Effect.Effect<
287 ServerProviderStatus,
288 never,
289 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
290> = Effect.gen(function* () {
291 const checkedAt = new Date().toISOString();
292​
293 // Probe 1: `codex --version` — is the CLI reachable?
294 const versionProbe = yield* runCodexCommand(["--version"]).pipe(
295 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
296 Effect.result,
297 );
298​
299 if (Result.isFailure(versionProbe)) {
300 const error = versionProbe.failure;
301 return {
302 provider: CODEX_PROVIDER,
303 status: "error" as const,
304 available: false,
305 authStatus: "unknown" as const,
306 checkedAt,
307 message: isCommandMissingCause(error)
308 ? "Codex CLI (`codex`) is not installed or not on PATH."
309 : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
310 };
311 }
312​
313 if (Option.isNone(versionProbe.success)) {
314 return {
315 provider: CODEX_PROVIDER,
316 status: "error" as const,
317 available: false,
318 authStatus: "unknown" as const,
319 checkedAt,
320 message: "Codex CLI is installed but failed to run. Timed out while running command.",
321 };
322 }
323​
324 const version = versionProbe.success.value;
325 if (version.code !== 0) {
326 const detail = detailFromResult(version);
327 return {
328 provider: CODEX_PROVIDER,
329 status: "error" as const,
330 available: false,
331 authStatus: "unknown" as const,
332 checkedAt,
333 message: detail
334 ? `Codex CLI is installed but failed to run. ${detail}`
335 : "Codex CLI is installed but failed to run.",
336 };
337 }
338​
339 const parsedVersion = parseCodexCliVersion(`${version.stdout}\n${version.stderr}`);
340 if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
341 return {
342 provider: CODEX_PROVIDER,
343 status: "error" as const,
344 available: false,
345 authStatus: "unknown" as const,
346 checkedAt,
347 message: formatCodexCliUpgradeMessage(parsedVersion),
348 };
349 }
350​
351 // Probe 2: `codex login status` — is the user authenticated?
352 //
353 // Custom model providers (e.g. Portkey, Azure OpenAI proxy) handle
354 // authentication through their own environment variables, so `codex
355 // login status` will report "not logged in" even when the CLI works
356 // fine. Skip the auth probe entirely for non-OpenAI providers.
357 if (yield* hasCustomModelProvider) {
358 return {
359 provider: CODEX_PROVIDER,
360 status: "ready" as const,
361 available: true,
362 authStatus: "unknown" as const,
363 checkedAt,
364 message: "Using a custom Codex model provider; OpenAI login check skipped.",
365 } satisfies ServerProviderStatus;
366 }
367​
368 const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
369 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
370 Effect.result,
371 );
372​
373 if (Result.isFailure(authProbe)) {
374 const error = authProbe.failure;
375 return {
376 provider: CODEX_PROVIDER,
377 status: "warning" as const,
378 available: true,
379 authStatus: "unknown" as const,
380 checkedAt,
381 message:
382 error instanceof Error
383 ? `Could not verify Codex authentication status: ${error.message}.`
384 : "Could not verify Codex authentication status.",
385 };
386 }
387​
388 if (Option.isNone(authProbe.success)) {
389 return {
390 provider: CODEX_PROVIDER,
391 status: "warning" as const,
392 available: true,
393 authStatus: "unknown" as const,
394 checkedAt,
395 message: "Could not verify Codex authentication status. Timed out while running command.",
396 };
397 }
398​
399 const parsed = parseAuthStatusFromOutput(authProbe.success.value);
400 return {
401 provider: CODEX_PROVIDER,
402 status: parsed.status,
403 available: true,
404 authStatus: parsed.authStatus,
405 checkedAt,
406 ...(parsed.message ? { message: parsed.message } : {}),
407 } satisfies ServerProviderStatus;
408});
409​
410// ── Claude Agent health check ───────────────────────────────────────
411​
412export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
413 readonly status: ServerProviderStatusState;
414 readonly authStatus: ServerProviderAuthStatus;
415 readonly message?: string;
416} {
417 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
418​
419 if (
420 lowerOutput.includes("unknown command") ||
421 lowerOutput.includes("unrecognized command") ||
422 lowerOutput.includes("unexpected argument")
423 ) {
424 return {
425 status: "warning",
426 authStatus: "unknown",
427 message:
428 "Claude Agent authentication status command is unavailable in this version of Claude.",
429 };
430 }
431​
432 if (
433 lowerOutput.includes("not logged in") ||
434 lowerOutput.includes("login required") ||
435 lowerOutput.includes("authentication required") ||
436 lowerOutput.includes("run `claude login`") ||
437 lowerOutput.includes("run claude login")
438 ) {
439 return {
440 status: "error",
441 authStatus: "unauthenticated",
442 message: "Claude is not authenticated. Run `claude auth login` and try again.",
443 };
444 }
445​
446 // `claude auth status` returns JSON with a `loggedIn` boolean.
447 const parsedAuth = (() => {
448 const trimmed = result.stdout.trim();
449 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
450 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
451 }
452 try {
453 return {
454 attemptedJsonParse: true as const,
455 auth: extractAuthBoolean(JSON.parse(trimmed)),
456 };
457 } catch {
458 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
459 }
460 })();
461​
462 if (parsedAuth.auth === true) {
463 return { status: "ready", authStatus: "authenticated" };
464 }
465 if (parsedAuth.auth === false) {
466 return {
467 status: "error",
468 authStatus: "unauthenticated",
469 message: "Claude is not authenticated. Run `claude auth login` and try again.",
470 };
471 }
472 if (parsedAuth.attemptedJsonParse) {
473 return {
474 status: "warning",
475 authStatus: "unknown",
476 message:
477 "Could not verify Claude authentication status from JSON output (missing auth marker).",
478 };
479 }
480 if (result.code === 0) {
481 return { status: "ready", authStatus: "authenticated" };
482 }
483​
484 const detail = detailFromResult(result);
485 return {
486 status: "warning",
487 authStatus: "unknown",
488 message: detail
489 ? `Could not verify Claude authentication status. ${detail}`
490 : "Could not verify Claude authentication status.",
491 };
493​
494export const checkClaudeProviderStatus: Effect.Effect<
495 ServerProviderStatus,
496 never,
497 ChildProcessSpawner.ChildProcessSpawner
498> = Effect.gen(function* () {
499 const checkedAt = new Date().toISOString();
500​
501 // Probe 1: `claude --version` — is the CLI reachable?
502 const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
503 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
504 Effect.result,
505 );
506​
507 if (Result.isFailure(versionProbe)) {
508 const error = versionProbe.failure;
509 return {
510 provider: CLAUDE_AGENT_PROVIDER,
511 status: "error" as const,
512 available: false,
513 authStatus: "unknown" as const,
514 checkedAt,
515 message: isCommandMissingCause(error)
516 ? "Claude Agent CLI (`claude`) is not installed or not on PATH."
517 : `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
518 };
519 }
520​
521 if (Option.isNone(versionProbe.success)) {
522 return {
523 provider: CLAUDE_AGENT_PROVIDER,
524 status: "error" as const,
525 available: false,
526 authStatus: "unknown" as const,
527 checkedAt,
528 message: "Claude Agent CLI is installed but failed to run. Timed out while running command.",
529 };
530 }
531​
532 const version = versionProbe.success.value;
533 if (version.code !== 0) {
534 const detail = detailFromResult(version);
535 return {
536 provider: CLAUDE_AGENT_PROVIDER,
537 status: "error" as const,
538 available: false,
539 authStatus: "unknown" as const,
540 checkedAt,
541 message: detail
542 ? `Claude Agent CLI is installed but failed to run. ${detail}`
543 : "Claude Agent CLI is installed but failed to run.",
544 };
545 }
546​
547 // Probe 2: `claude auth status` — is the user authenticated?
548 const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
549 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
550 Effect.result,
551 );
552​
553 if (Result.isFailure(authProbe)) {
554 const error = authProbe.failure;
555 return {
556 provider: CLAUDE_AGENT_PROVIDER,
557 status: "warning" as const,
558 available: true,
559 authStatus: "unknown" as const,
560 checkedAt,
561 message:
562 error instanceof Error
563 ? `Could not verify Claude authentication status: ${error.message}.`
564 : "Could not verify Claude authentication status.",
565 };
566 }
567​
568 if (Option.isNone(authProbe.success)) {
569 return {
570 provider: CLAUDE_AGENT_PROVIDER,
571 status: "warning" as const,
572 available: true,
573 authStatus: "unknown" as const,
574 checkedAt,
575 message: "Could not verify Claude authentication status. Timed out while running command.",
576 };
577 }
578​
579 const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
580 return {
581 provider: CLAUDE_AGENT_PROVIDER,
582 status: parsed.status,
583 available: true,
584 authStatus: parsed.authStatus,
585 checkedAt,
586 ...(parsed.message ? { message: parsed.message } : {}),
587 } satisfies ServerProviderStatus;
588});
589​
590// ── Layer ───────────────────────────────────────────────────────────
591​
592export const ProviderHealthLive = Layer.effect(
593 ProviderHealth,
594 Effect.gen(function* () {
595 const statusesFiber = yield* Effect.all([checkCodexProviderStatus, checkClaudeProviderStatus], {
596 concurrency: "unbounded",
597 }).pipe(Effect.forkScoped);
598​
599 return {
600 getStatuses: Fiber.join(statusesFiber),
601 } satisfies ProviderHealthShape;
602 }),
603);