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