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

ProviderHealth.ts

407 lines13.1 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;
29​
30// ── Pure helpers ────────────────────────────────────────────────────
31​
32export interface CommandResult {
33 readonly stdout: string;
34 readonly stderr: string;
35 readonly code: number;
37​
38function nonEmptyTrimmed(value: string | undefined): string | undefined {
39 if (!value) return undefined;
40 const trimmed = value.trim();
41 return trimmed.length > 0 ? trimmed : undefined;
43​
44function isCommandMissingCause(error: unknown): boolean {
45 if (!(error instanceof Error)) return false;
46 const lower = error.message.toLowerCase();
47 return (
48 lower.includes("command not found: codex") ||
49 lower.includes("spawn codex enoent") ||
50 lower.includes("enoent") ||
51 lower.includes("notfound")
52 );
54​
55function detailFromResult(
56 result: CommandResult & { readonly timedOut?: boolean },
57): string | undefined {
58 if (result.timedOut) return "Timed out while running command.";
59 const stderr = nonEmptyTrimmed(result.stderr);
60 if (stderr) return stderr;
61 const stdout = nonEmptyTrimmed(result.stdout);
62 if (stdout) return stdout;
63 if (result.code !== 0) {
64 return `Command exited with code ${result.code}.`;
65 }
66 return undefined;
68​
69function extractAuthBoolean(value: unknown): boolean | undefined {
70 if (Array.isArray(value)) {
71 for (const entry of value) {
72 const nested = extractAuthBoolean(entry);
73 if (nested !== undefined) return nested;
74 }
75 return undefined;
76 }
77​
78 if (!value || typeof value !== "object") return undefined;
79​
80 const record = value as Record<string, unknown>;
81 for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
82 if (typeof record[key] === "boolean") return record[key];
83 }
84 for (const key of ["auth", "status", "session", "account"] as const) {
85 const nested = extractAuthBoolean(record[key]);
86 if (nested !== undefined) return nested;
87 }
88 return undefined;
90​
91export function parseAuthStatusFromOutput(result: CommandResult): {
92 readonly status: ServerProviderStatusState;
93 readonly authStatus: ServerProviderAuthStatus;
94 readonly message?: string;
95} {
96 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
97​
98 if (
99 lowerOutput.includes("unknown command") ||
100 lowerOutput.includes("unrecognized command") ||
101 lowerOutput.includes("unexpected argument")
102 ) {
103 return {
104 status: "warning",
105 authStatus: "unknown",
106 message: "Codex CLI authentication status command is unavailable in this Codex version.",
107 };
108 }
109​
110 if (
111 lowerOutput.includes("not logged in") ||
112 lowerOutput.includes("login required") ||
113 lowerOutput.includes("authentication required") ||
114 lowerOutput.includes("run `codex login`") ||
115 lowerOutput.includes("run codex login")
116 ) {
117 return {
118 status: "error",
119 authStatus: "unauthenticated",
120 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
121 };
122 }
123​
124 const parsedAuth = (() => {
125 const trimmed = result.stdout.trim();
126 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
127 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
128 }
129 try {
130 return {
131 attemptedJsonParse: true as const,
132 auth: extractAuthBoolean(JSON.parse(trimmed)),
133 };
134 } catch {
135 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
136 }
137 })();
138​
139 if (parsedAuth.auth === true) {
140 return { status: "ready", authStatus: "authenticated" };
141 }
142 if (parsedAuth.auth === false) {
143 return {
144 status: "error",
145 authStatus: "unauthenticated",
146 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
147 };
148 }
149 if (parsedAuth.attemptedJsonParse) {
150 return {
151 status: "warning",
152 authStatus: "unknown",
153 message:
154 "Could not verify Codex authentication status from JSON output (missing auth marker).",
155 };
156 }
157 if (result.code === 0) {
158 return { status: "ready", authStatus: "authenticated" };
159 }
160​
161 const detail = detailFromResult(result);
162 return {
163 status: "warning",
164 authStatus: "unknown",
165 message: detail
166 ? `Could not verify Codex authentication status. ${detail}`
167 : "Could not verify Codex authentication status.",
168 };
170​
171// ── Codex CLI config detection ──────────────────────────────────────
172​
173/**
174 * Providers that use OpenAI-native authentication via `codex login`.
175 * When the configured `model_provider` is one of these, the `codex login
176 * status` probe still runs. For any other provider value the auth probe
177 * is skipped because authentication is handled externally (e.g. via
178 * environment variables like `PORTKEY_API_KEY` or `AZURE_API_KEY`).
179 */
180const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
181​
182/**
183 * Read the `model_provider` value from the Codex CLI config file.
184 *
185 * Looks for the file at `$CODEX_HOME/config.toml` (falls back to
186 * `~/.codex/config.toml`). Uses a simple line-by-line scan rather than
187 * a full TOML parser to avoid adding a dependency for a single key.
188 *
189 * Returns `undefined` when the file does not exist or does not set
190 * `model_provider`.
191 */
192export const readCodexConfigModelProvider = Effect.gen(function* () {
193 const fileSystem = yield* FileSystem.FileSystem;
194 const path = yield* Path.Path;
195 const codexHome = process.env.CODEX_HOME || path.join(OS.homedir(), ".codex");
196 const configPath = path.join(codexHome, "config.toml");
197​
198 const content = yield* fileSystem
199 .readFileString(configPath)
200 .pipe(Effect.orElseSucceed(() => undefined));
201 if (content === undefined) {
202 return undefined;
203 }
204​
205 // We need to find `model_provider = "..."` at the top level of the
206 // TOML file (i.e. before any `[section]` header). Lines inside
207 // `[profiles.*]`, `[model_providers.*]`, etc. are ignored.
208 let inTopLevel = true;
209 for (const line of content.split("\n")) {
210 const trimmed = line.trim();
211 // Skip comments and empty lines.
212 if (!trimmed || trimmed.startsWith("#")) continue;
213 // Detect section headers — once we leave the top level, stop.
214 if (trimmed.startsWith("[")) {
215 inTopLevel = false;
216 continue;
217 }
218 if (!inTopLevel) continue;
219​
220 const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
221 if (match) return match[1];
222 }
223 return undefined;
224});
225​
226/**
227 * Returns `true` when the Codex CLI is configured with a custom
228 * (non-OpenAI) model provider, meaning `codex login` auth is not
229 * required because authentication is handled through provider-specific
230 * environment variables.
231 */
232export const hasCustomModelProvider = Effect.map(
233 readCodexConfigModelProvider,
234 (provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider),
235);
236​
237// ── Effect-native command execution ─────────────────────────────────
238​
239const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
240 Stream.runFold(
241 stream,
242 () => "",
243 (acc, chunk) => acc + new TextDecoder().decode(chunk),
244 );
245​
246const runCodexCommand = (args: ReadonlyArray<string>) =>
247 Effect.gen(function* () {
248 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
249 const command = ChildProcess.make("codex", [...args], {
250 shell: process.platform === "win32",
251 });
252​
253 const child = yield* spawner.spawn(command);
254​
255 const [stdout, stderr, exitCode] = yield* Effect.all(
256 [
257 collectStreamAsString(child.stdout),
258 collectStreamAsString(child.stderr),
259 child.exitCode.pipe(Effect.map(Number)),
260 ],
261 { concurrency: "unbounded" },
262 );
263​
264 return { stdout, stderr, code: exitCode } satisfies CommandResult;
265 }).pipe(Effect.scoped);
266​
267// ── Health check ────────────────────────────────────────────────────
268​
269export const checkCodexProviderStatus: Effect.Effect<
270 ServerProviderStatus,
271 never,
272 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
273> = Effect.gen(function* () {
274 const checkedAt = new Date().toISOString();
275​
276 // Probe 1: `codex --version` — is the CLI reachable?
277 const versionProbe = yield* runCodexCommand(["--version"]).pipe(
278 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
279 Effect.result,
280 );
281​
282 if (Result.isFailure(versionProbe)) {
283 const error = versionProbe.failure;
284 return {
285 provider: CODEX_PROVIDER,
286 status: "error" as const,
287 available: false,
288 authStatus: "unknown" as const,
289 checkedAt,
290 message: isCommandMissingCause(error)
291 ? "Codex CLI (`codex`) is not installed or not on PATH."
292 : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
293 };
294 }
295​
296 if (Option.isNone(versionProbe.success)) {
297 return {
298 provider: CODEX_PROVIDER,
299 status: "error" as const,
300 available: false,
301 authStatus: "unknown" as const,
302 checkedAt,
303 message: "Codex CLI is installed but failed to run. Timed out while running command.",
304 };
305 }
306​
307 const version = versionProbe.success.value;
308 if (version.code !== 0) {
309 const detail = detailFromResult(version);
310 return {
311 provider: CODEX_PROVIDER,
312 status: "error" as const,
313 available: false,
314 authStatus: "unknown" as const,
315 checkedAt,
316 message: detail
317 ? `Codex CLI is installed but failed to run. ${detail}`
318 : "Codex CLI is installed but failed to run.",
319 };
320 }
321​
322 const parsedVersion = parseCodexCliVersion(`${version.stdout}\n${version.stderr}`);
323 if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
324 return {
325 provider: CODEX_PROVIDER,
326 status: "error" as const,
327 available: false,
328 authStatus: "unknown" as const,
329 checkedAt,
330 message: formatCodexCliUpgradeMessage(parsedVersion),
331 };
332 }
333​
334 // Probe 2: `codex login status` — is the user authenticated?
335 //
336 // Custom model providers (e.g. Portkey, Azure OpenAI proxy) handle
337 // authentication through their own environment variables, so `codex
338 // login status` will report "not logged in" even when the CLI works
339 // fine. Skip the auth probe entirely for non-OpenAI providers.
340 if (yield* hasCustomModelProvider) {
341 return {
342 provider: CODEX_PROVIDER,
343 status: "ready" as const,
344 available: true,
345 authStatus: "unknown" as const,
346 checkedAt,
347 message: "Using a custom Codex model provider; OpenAI login check skipped.",
348 } satisfies ServerProviderStatus;
349 }
350​
351 const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
352 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
353 Effect.result,
354 );
355​
356 if (Result.isFailure(authProbe)) {
357 const error = authProbe.failure;
358 return {
359 provider: CODEX_PROVIDER,
360 status: "warning" as const,
361 available: true,
362 authStatus: "unknown" as const,
363 checkedAt,
364 message:
365 error instanceof Error
366 ? `Could not verify Codex authentication status: ${error.message}.`
367 : "Could not verify Codex authentication status.",
368 };
369 }
370​
371 if (Option.isNone(authProbe.success)) {
372 return {
373 provider: CODEX_PROVIDER,
374 status: "warning" as const,
375 available: true,
376 authStatus: "unknown" as const,
377 checkedAt,
378 message: "Could not verify Codex authentication status. Timed out while running command.",
379 };
380 }
381​
382 const parsed = parseAuthStatusFromOutput(authProbe.success.value);
383 return {
384 provider: CODEX_PROVIDER,
385 status: parsed.status,
386 available: true,
387 authStatus: parsed.authStatus,
388 checkedAt,
389 ...(parsed.message ? { message: parsed.message } : {}),
390 } satisfies ServerProviderStatus;
391});
392​
393// ── Layer ───────────────────────────────────────────────────────────
394​
395export const ProviderHealthLive = Layer.effect(
396 ProviderHealth,
397 Effect.gen(function* () {
398 const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
399 Effect.map(Array.of),
400 Effect.forkScoped,
401 );
402​
403 return {
404 getStatuses: Fiber.join(codexStatusFiber),
405 } satisfies ProviderHealthShape;
406 }),
407);