Open History to see the last commit
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 type {
12 ServerProviderAuthStatus,
13 ServerProviderStatus,
14 ServerProviderStatusState,
15} from "@t3tools/contracts";
16import { Effect, Layer, Option, Result, Stream } from "effect";
17import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
18
19import {
20 formatCodexCliUpgradeMessage,
21 isCodexCliVersionSupported,
22 parseCodexCliVersion,
23} from "../codexCliVersion";
24import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
25
26const DEFAULT_TIMEOUT_MS = 4_000;
27const CODEX_PROVIDER = "codex" as const;
28
29// ── Pure helpers ────────────────────────────────────────────────────
30
31export interface CommandResult {
32 readonly stdout: string;
33 readonly stderr: string;
34 readonly code: number;
35}
36
37function nonEmptyTrimmed(value: string | undefined): string | undefined {
38 if (!value) return undefined;
39 const trimmed = value.trim();
40 return trimmed.length > 0 ? trimmed : undefined;
41}
42
43function isCommandMissingCause(error: unknown): boolean {
44 if (!(error instanceof Error)) return false;
45 const lower = error.message.toLowerCase();
46 return (
47 lower.includes("command not found: codex") ||
48 lower.includes("spawn codex enoent") ||
49 lower.includes("enoent") ||
50 lower.includes("notfound")
51 );
52}
53
54function detailFromResult(
55 result: CommandResult & { readonly timedOut?: boolean },
56): string | undefined {
57 if (result.timedOut) return "Timed out while running command.";
58 const stderr = nonEmptyTrimmed(result.stderr);
59 if (stderr) return stderr;
60 const stdout = nonEmptyTrimmed(result.stdout);
61 if (stdout) return stdout;
62 if (result.code !== 0) {
63 return `Command exited with code ${result.code}.`;
64 }
65 return undefined;
66}
67
68function extractAuthBoolean(value: unknown): boolean | undefined {
69 if (Array.isArray(value)) {
70 for (const entry of value) {
71 const nested = extractAuthBoolean(entry);
72 if (nested !== undefined) return nested;
73 }
74 return undefined;
75 }
76
77 if (!value || typeof value !== "object") return undefined;
78
79 const record = value as Record<string, unknown>;
80 for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
81 if (typeof record[key] === "boolean") return record[key];
82 }
83 for (const key of ["auth", "status", "session", "account"] as const) {
84 const nested = extractAuthBoolean(record[key]);
85 if (nested !== undefined) return nested;
86 }
87 return undefined;
88}
89
90export function parseAuthStatusFromOutput(result: CommandResult): {
91 readonly status: ServerProviderStatusState;
92 readonly authStatus: ServerProviderAuthStatus;
93 readonly message?: string;
94} {
95 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
96
97 if (
98 lowerOutput.includes("unknown command") ||
99 lowerOutput.includes("unrecognized command") ||
100 lowerOutput.includes("unexpected argument")
101 ) {
102 return {
103 status: "warning",
104 authStatus: "unknown",
105 message: "Codex CLI authentication status command is unavailable in this Codex version.",
106 };
107 }
108
109 if (
110 lowerOutput.includes("not logged in") ||
111 lowerOutput.includes("login required") ||
112 lowerOutput.includes("authentication required") ||
113 lowerOutput.includes("run `codex login`") ||
114 lowerOutput.includes("run codex login")
115 ) {
116 return {
117 status: "error",
118 authStatus: "unauthenticated",
119 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
120 };
121 }
122
123 const parsedAuth = (() => {
124 const trimmed = result.stdout.trim();
125 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
126 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
127 }
128 try {
129 return {
130 attemptedJsonParse: true as const,
131 auth: extractAuthBoolean(JSON.parse(trimmed)),
132 };
133 } catch {
134 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
135 }
136 })();
137
138 if (parsedAuth.auth === true) {
139 return { status: "ready", authStatus: "authenticated" };
140 }
141 if (parsedAuth.auth === false) {
142 return {
143 status: "error",
144 authStatus: "unauthenticated",
145 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
146 };
147 }
148 if (parsedAuth.attemptedJsonParse) {
149 return {
150 status: "warning",
151 authStatus: "unknown",
152 message:
153 "Could not verify Codex authentication status from JSON output (missing auth marker).",
154 };
155 }
156 if (result.code === 0) {
157 return { status: "ready", authStatus: "authenticated" };
158 }
159
160 const detail = detailFromResult(result);
161 return {
162 status: "warning",
163 authStatus: "unknown",
164 message: detail
165 ? `Could not verify Codex authentication status. ${detail}`
166 : "Could not verify Codex authentication status.",
167 };
168}
169
170// ── Effect-native command execution ─────────────────────────────────
171
172const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
173 Stream.runFold(
174 stream,
175 () => "",
176 (acc, chunk) => acc + new TextDecoder().decode(chunk),
177 );
178
179const runCodexCommand = (args: ReadonlyArray<string>) =>
180 Effect.gen(function* () {
181 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
182 const command = ChildProcess.make("codex", [...args], {
183 shell: process.platform === "win32",
184 });
185
186 const child = yield* spawner.spawn(command);
187
188 const [stdout, stderr, exitCode] = yield* Effect.all(
189 [
190 collectStreamAsString(child.stdout),
191 collectStreamAsString(child.stderr),
192 child.exitCode.pipe(Effect.map(Number)),
193 ],
194 { concurrency: "unbounded" },
195 );
196
197 return { stdout, stderr, code: exitCode } satisfies CommandResult;
198 }).pipe(Effect.scoped);
199
200// ── Health check ────────────────────────────────────────────────────
201
202export const checkCodexProviderStatus: Effect.Effect<
203 ServerProviderStatus,
204 never,
205 ChildProcessSpawner.ChildProcessSpawner
206> = Effect.gen(function* () {
207 const checkedAt = new Date().toISOString();
208
209 // Probe 1: `codex --version` — is the CLI reachable?
210 const versionProbe = yield* runCodexCommand(["--version"]).pipe(
211 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
212 Effect.result,
213 );
214
215 if (Result.isFailure(versionProbe)) {
216 const error = versionProbe.failure;
217 return {
218 provider: CODEX_PROVIDER,
219 status: "error" as const,
220 available: false,
221 authStatus: "unknown" as const,
222 checkedAt,
223 message: isCommandMissingCause(error)
224 ? "Codex CLI (`codex`) is not installed or not on PATH."
225 : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
226 };
227 }
228
229 if (Option.isNone(versionProbe.success)) {
230 return {
231 provider: CODEX_PROVIDER,
232 status: "error" as const,
233 available: false,
234 authStatus: "unknown" as const,
235 checkedAt,
236 message: "Codex CLI is installed but failed to run. Timed out while running command.",
237 };
238 }
239
240 const version = versionProbe.success.value;
241 if (version.code !== 0) {
242 const detail = detailFromResult(version);
243 return {
244 provider: CODEX_PROVIDER,
245 status: "error" as const,
246 available: false,
247 authStatus: "unknown" as const,
248 checkedAt,
249 message: detail
250 ? `Codex CLI is installed but failed to run. ${detail}`
251 : "Codex CLI is installed but failed to run.",
252 };
253 }
254
255 const parsedVersion = parseCodexCliVersion(`${version.stdout}\n${version.stderr}`);
256 if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
257 return {
258 provider: CODEX_PROVIDER,
259 status: "error" as const,
260 available: false,
261 authStatus: "unknown" as const,
262 checkedAt,
263 message: formatCodexCliUpgradeMessage(parsedVersion),
264 };
265 }
266
267 // Probe 2: `codex login status` — is the user authenticated?
268 const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
269 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
270 Effect.result,
271 );
272
273 if (Result.isFailure(authProbe)) {
274 const error = authProbe.failure;
275 return {
276 provider: CODEX_PROVIDER,
277 status: "warning" as const,
278 available: true,
279 authStatus: "unknown" as const,
280 checkedAt,
281 message:
282 error instanceof Error
283 ? `Could not verify Codex authentication status: ${error.message}.`
284 : "Could not verify Codex authentication status.",
285 };
286 }
287
288 if (Option.isNone(authProbe.success)) {
289 return {
290 provider: CODEX_PROVIDER,
291 status: "warning" as const,
292 available: true,
293 authStatus: "unknown" as const,
294 checkedAt,
295 message: "Could not verify Codex authentication status. Timed out while running command.",
296 };
297 }
298
299 const parsed = parseAuthStatusFromOutput(authProbe.success.value);
300 return {
301 provider: CODEX_PROVIDER,
302 status: parsed.status,
303 available: true,
304 authStatus: parsed.authStatus,
305 checkedAt,
306 ...(parsed.message ? { message: parsed.message } : {}),
307 } satisfies ServerProviderStatus;
308});
309
310// ── Layer ───────────────────────────────────────────────────────────
311
312export const ProviderHealthLive = Layer.effect(
313 ProviderHealth,
314 Effect.gen(function* () {
315 const codexStatus = yield* checkCodexProviderStatus;
316 return {
317 getStatuses: Effect.succeed([codexStatus]),
318 } satisfies ProviderHealthShape;
319 }),
320);