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