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

CodexProvider.ts

734 lines24.2 KB

1import * as DateTime from "effect/DateTime";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Result from "effect/Result";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9import * as Types from "effect/Types";
10import * as ChildProcess from "effect/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12import * as CodexClient from "effect-codex-app-server/client";
13import * as CodexSchema from "effect-codex-app-server/schema";
14import * as CodexErrors from "effect-codex-app-server/errors";
15​
16import type {
17 CodexSettings,
18 CustomModelSetting,
19 ServerProvider,
20 ServerProviderState,
21 ModelCapabilities,
22 ProviderOptionDescriptor,
23 ServerProviderModel,
24 ServerProviderSkill,
25} from "@t3tools/contracts";
26import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
27​
28import {
29 codexModelFamily,
30 createModelCapabilities,
31 formatCodexModelName,
32 readCustomModelEntries,
33} from "@t3tools/shared/model";
34import { resolveSpawnCommand } from "@t3tools/shared/shell";
35import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
36import {
37 AUTH_PROBE_TIMEOUT_MS,
38 buildServerProvider,
39 COMPACT_SLASH_COMMAND,
40 type ServerProviderDraft,
41} from "@t3tools/provider-core/server/snapshotProbe";
42import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
43import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
44import {
45 codexRateLimitsFailureMessage,
46 codexRateLimitsToLimits,
47 type CodexRateLimitSnapshot,
48 type CodexResetCreditsSummary,
49} from "./codexUsageLimits.ts";
50import * as HostProcess from "@t3tools/shared/HostProcess";
51import packageJson from "../../package.json" with { type: "json" };
52const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
53const RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000;
54​
55type CodexRateLimitsProbe =
56 | {
57 readonly snapshot: CodexRateLimitSnapshot;
58 readonly rateLimitsByLimitId?:
59 | Readonly<Record<string, CodexRateLimitSnapshot>>
60 | null
61 | undefined;
62 readonly resetCredits: CodexResetCreditsSummary | null | undefined;
63 /** The ChatGPT workspace the usage belongs to, when the backend names it. */
64 readonly accountId?: string | null | undefined;
65 }
66 | { readonly failure: string };
67​
68const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
69​
70const CODEX_PRESENTATION = {
71 displayName: "Codex",
72 showInteractionModeToggle: true,
73 reportsContextWindow: true,
74} as const;
75​
76export interface CodexAppServerProviderSnapshot {
77 readonly account: CodexSchema.V2GetAccountResponse;
78 readonly rateLimits?: CodexRateLimitsProbe;
79 readonly version: string | undefined;
80 readonly models: ReadonlyArray<ServerProviderModel>;
81 readonly skills: ReadonlyArray<ServerProviderSkill>;
83​
84const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
85 none: "None",
86 minimal: "Minimal",
87 low: "Low",
88 medium: "Medium",
89 high: "High",
90 xhigh: "Extra High",
91 max: "Max",
92 ultra: "Ultra",
93};
94​
95const DEFAULT_SERVICE_TIER_ID = "default";
96​
97/** Shorter copy for tiers whose catalog description wraps in the traits menu. */
98const SERVICE_TIER_DESCRIPTIONS: Readonly<Record<string, string>> = {
99 ultrafast: "Even faster, more expensive",
100};
101​
102function reasoningEffortLabel(reasoningEffort: string): string {
103 return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
105​
106function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
107 if (!account) return undefined;
108 if (account.type === "apiKey") return "OpenAI API Key";
109 if (account.type === "amazonBedrock") return "Amazon Bedrock";
110 if (account.type !== "chatgpt") return undefined;
111 return codexPlanLabel(account.planType);
113​
114/** Shared with usage-limit sources, which report the same `planType` slugs. */
115export function codexPlanLabel(planType: string | null | undefined): string | undefined {
116 switch (planType) {
117 case "free":
118 return "ChatGPT Free Subscription";
119 case "go":
120 return "ChatGPT Go Subscription";
121 case "plus":
122 return "ChatGPT Plus Subscription";
123 case "pro":
124 return "ChatGPT Pro 20x Subscription";
125 case "prolite":
126 return "ChatGPT Pro 5x Subscription";
127 case "promax":
128 return "ChatGPT Pro Max Subscription";
129 case "team":
130 return "ChatGPT Team Subscription";
131 case "self_serve_business_prolite":
132 case "self_serve_business_usage_based":
133 case "business":
134 return "ChatGPT Business Subscription";
135 case "ent26":
136 case "enterprise_cbp_automation":
137 case "enterprise_cbp_usage_based":
138 case "enterprise":
139 return "ChatGPT Enterprise Subscription";
140 case "edu":
141 case "edu_plus":
142 case "edu_pro":
143 return "ChatGPT Edu Subscription";
144 case "unknown":
145 return "ChatGPT Subscription";
146 default:
147 return undefined;
148 }
150​
151function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) {
152 if (!account || account.type !== "chatgpt") return undefined;
153 return account.email;
155​
156export function mapCodexModelCapabilities(
157 model: CodexSchema.V2ModelListResponse__Model,
158): ModelCapabilities {
159 const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
160 reasoningEffort ===
161 (codexModelFamily(model.model) === "gpt-6-astra" ? "medium" : model.defaultReasoningEffort)
162 ? {
163 id: reasoningEffort,
164 label: reasoningEffortLabel(reasoningEffort),
165 isDefault: true,
166 }
167 : {
168 id: reasoningEffort,
169 label: reasoningEffortLabel(reasoningEffort),
170 },
171 );
172 const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
173 const serviceTiers =
174 model.serviceTiers && model.serviceTiers.length > 0
175 ? model.serviceTiers
176 : (model.additionalSpeedTiers ?? []).map((id) => ({
177 id,
178 name: id === "fast" ? "Fast" : id,
179 description: "",
180 }));
181 const catalogDefaultServiceTier = serviceTiers.some(
182 (tier) => tier.id === model.defaultServiceTier,
183 )
184 ? model.defaultServiceTier
185 : null;
186 const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
187 const optionDescriptors: ProviderOptionDescriptor[] = [];
188​
189 if (reasoningOptions.length > 0) {
190 optionDescriptors.push({
191 id: "reasoningEffort",
192 label: "Reasoning",
193 type: "select",
194 options: reasoningOptions,
195 ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
196 });
197 }
198 if (serviceTiers.length > 0) {
199 optionDescriptors.push({
200 id: "serviceTier",
201 label: "Service Tier",
202 type: "select",
203 options: [
204 {
205 id: DEFAULT_SERVICE_TIER_ID,
206 label: "Standard",
207 ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
208 },
209 ...serviceTiers.map((tier) => {
210 const description = SERVICE_TIER_DESCRIPTIONS[tier.id] ?? tier.description;
211 return {
212 id: tier.id,
213 label: tier.name,
214 ...(description ? { description } : {}),
215 ...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
216 };
217 }),
218 ],
219 currentValue: defaultServiceTier,
220 });
221 }
222​
223 return createModelCapabilities({
224 optionDescriptors,
225 });
227​
228function parseCodexModelListResponse(
229 response: CodexSchema.V2ModelListResponse,
230): ReadonlyArray<ServerProviderModel> {
231 return response.data.map((model) => ({
232 slug: model.model,
233 name: formatCodexModelName(model.displayName),
234 isCustom: false,
235 ...(model.isDefault ? { isDefault: true } : {}),
236 capabilities: mapCodexModelCapabilities(model),
237 }));
239​
240/**
241 * Prefer our own default-model ranking when one of the preferred slugs is in
242 * the live catalog; otherwise keep whatever Codex itself flagged as default.
243 */
244export function applyPreferredCodexDefaultModel(
245 models: ReadonlyArray<ServerProviderModel>,
246): ReadonlyArray<ServerProviderModel> {
247 const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.flatMap((slug) =>
248 models.filter((model) => !model.isCustom && codexModelFamily(model.slug) === slug),
249 )[0]?.slug;
250 if (!preferredSlug) {
251 return models;
252 }
253 return models.map((model) => {
254 if (model.slug === preferredSlug) {
255 return model.isDefault ? model : { ...model, isDefault: true };
256 }
257 if (!model.isDefault) {
258 return model;
259 }
260 const { isDefault: _isDefault, ...rest } = model;
261 return rest;
262 });
264​
265/**
266 * Codex has no static default capability set, so a bare custom slug borrows
267 * the first built-in's descriptors; an entry with its own capabilities keeps
268 * them.
269 */
270function appendCustomCodexModels(
271 models: ReadonlyArray<ServerProviderModel>,
272 customModels: ReadonlyArray<CustomModelSetting>,
273): ReadonlyArray<ServerProviderModel> {
274 if (customModels.length === 0) {
275 return models;
276 }
277​
278 const seen = new Set(models.map((model) => model.slug));
279 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
280 const customEntries: ServerProviderModel[] = [];
281 for (const entry of readCustomModelEntries(customModels)) {
282 if (seen.has(entry.slug)) {
283 continue;
284 }
285 seen.add(entry.slug);
286 customEntries.push({
287 slug: entry.slug,
288 name: entry.name,
289 isCustom: true,
290 capabilities: entry.capabilities ?? fallbackCapabilities,
291 });
292 }
293 return customEntries.length === 0 ? models : [...models, ...customEntries];
295​
296function parseCodexSkillsListResponse(
297 response: CodexSchema.V2SkillsListResponse,
298 cwd: string,
299): ReadonlyArray<ServerProviderSkill> {
300 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
301 const skills = matchingEntry
302 ? matchingEntry.skills
303 : response.data.flatMap((entry) => entry.skills);
304​
305 return skills.map((skill) => {
306 const shortDescription =
307 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
308​
309 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
310 name: skill.name,
311 path: skill.path,
312 enabled: skill.enabled,
313 };
314​
315 if (skill.description) {
316 parsedSkill.description = skill.description;
317 }
318 if (skill.scope) {
319 parsedSkill.scope = skill.scope;
320 }
321 if (skill.interface?.displayName) {
322 parsedSkill.displayName = skill.interface.displayName;
323 }
324 if (shortDescription) {
325 parsedSkill.shortDescription = shortDescription;
326 }
327​
328 return parsedSkill;
329 });
331​
332const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
333 client: CodexClient.CodexAppServerClient["Service"],
334) {
335 const models: ServerProviderModel[] = [];
336 let cursor: string | null | undefined = undefined;
337​
338 do {
339 const response: CodexSchema.V2ModelListResponse = yield* client.request(
340 "model/list",
341 cursor ? { cursor } : {},
342 );
343 models.push(...parseCodexModelListResponse(response));
344 cursor = response.nextCursor;
345 } while (cursor);
346​
347 return models;
348});
349​
350export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
351 return {
352 clientInfo: {
353 name: "T3 Code",
354 title: "T3 Code",
355 version: packageJson.version,
356 },
357 capabilities: {
358 experimentalApi: true,
359 },
360 };
362​
363/**
364 * Spawns a short-lived `codex app-server`, runs the initialize handshake, and
365 * hands the caller a connected client. Scoped: the process is killed when
366 * the caller's scope closes. Shared by the status probe, the skills probe,
367 * and account-level requests such as reset-credit redemption.
368 */
369export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(function* (input: {
370 readonly binaryPath: string;
371 readonly homePath?: string | undefined;
372 readonly launchArgs?: string | undefined;
373 readonly cwd: string;
374 readonly environment?: NodeJS.ProcessEnv | undefined;
375}) {
376 // `~` is not shell-expanded when env vars are set via `child_process.spawn`,
377 // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
378 // "CODEX_HOME points to '~/.codex_work', but that path does not exist".
379 // Expand here for parity with `CodexTextGeneration`.
380 const resolvedHomePath = input.homePath
381 ? expandHomePath(input.homePath, yield* HostProcess.HomeDirectory)
382 : undefined;
383 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
384 const environment = {
385 ...input.environment,
386 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
387 };
388 const spawnCommand = yield* resolveSpawnCommand(
389 input.binaryPath,
390 codexAppServerArgs(input.launchArgs),
391 { env: environment, extendEnv: true },
392 );
393 const child = yield* spawner
394 .spawn(
395 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
396 cwd: input.cwd,
397 env: environment,
398 extendEnv: true,
399 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
400 shell: spawnCommand.shell,
401 }),
402 )
403 .pipe(
404 Effect.mapError(
405 (cause) =>
406 new CodexErrors.CodexAppServerSpawnError({
407 command: `${input.binaryPath} app-server`,
408 cause,
409 }),
410 ),
411 );
412 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
413 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
414 Effect.provide(clientContext),
415 );
416 const initialize = yield* client.request("initialize", buildCodexInitializeParams());
417 yield* client.notify("initialized", undefined);
418 return { client, initialize };
419});
420​
421const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
422 readonly binaryPath: string;
423 readonly homePath?: string;
424 readonly launchArgs?: string;
425 readonly cwd: string;
426 readonly customModels?: ReadonlyArray<CustomModelSetting>;
427 readonly environment?: NodeJS.ProcessEnv;
428 readonly skipNativeUsage?: boolean;
429}) {
430 const { client, initialize } = yield* withCodexAppServerClient(input);
431​
432 // Extract the version string after the first '/' in userAgent, up to the next space or the end
433 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
434 const version = versionMatch ? versionMatch[1] : undefined;
435​
436 const accountResponse = yield* client.request("account/read", {});
437 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
438 return {
439 account: accountResponse,
440 version,
441 models: appendCustomCodexModels([], input.customModels ?? []),
442 skills: [],
443 } satisfies CodexAppServerProviderSnapshot;
444 }
445​
446 const [skillsResponse, models, rateLimits] = yield* Effect.all(
447 [
448 client.request("skills/list", {
449 cwds: [input.cwd],
450 }),
451 requestAllCodexModels(client),
452 // Usage is an enrichment: a failure or a slow answer degrades to "no
453 // usage this probe" rather than costing the account and models.
454 input.skipNativeUsage
455 ? Effect.succeed(undefined)
456 : client.request("account/rateLimits/read", null).pipe(
457 Effect.map((response): CodexRateLimitsProbe => ({
458 snapshot: response.rateLimits,
459 rateLimitsByLimitId: response.rateLimitsByLimitId,
460 resetCredits: response.rateLimitResetCredits,
461 accountId: response.accountId,
462 })),
463 Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)),
464 Effect.map(
465 Option.getOrElse((): CodexRateLimitsProbe => ({
466 failure: "Codex did not answer the usage request.",
467 })),
468 ),
469 Effect.catch((error) =>
470 Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
471 Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
472 ),
473 ),
474 ),
475 ],
476 { concurrency: "unbounded" },
477 );
478​
479 return {
480 account: accountResponse,
481 ...(rateLimits ? { rateLimits } : {}),
482 version,
483 models: applyPreferredCodexDefaultModel(
484 appendCustomCodexModels(models, input.customModels ?? []),
485 ),
486 skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
487 } satisfies CodexAppServerProviderSnapshot;
488});
489​
490export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
491 readonly binaryPath: string;
492 readonly homePath?: string;
493 readonly launchArgs?: string;
494 readonly cwd: string;
495 readonly environment?: NodeJS.ProcessEnv;
496}) {
497 const { client } = yield* withCodexAppServerClient(input);
498 const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
499 return parseCodexSkillsListResponse(skillsResponse, input.cwd);
500});
501​
502const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
503 appendCustomCodexModels([], codexSettings.customModels);
504​
505const makePendingCodexProvider = (
506 codexSettings: CodexSettings,
507): Effect.Effect<ServerProviderDraft> =>
508 Effect.gen(function* () {
509 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
510 const models = emptyCodexModelsFromSettings(codexSettings);
511​
512 if (!codexSettings.enabled) {
513 return buildServerProvider({
514 presentation: CODEX_PRESENTATION,
515 enabled: false,
516 checkedAt,
517 models,
518 skills: [],
519 probe: {
520 installed: false,
521 version: null,
522 status: "warning",
523 auth: { status: "unknown" },
524 message: "Codex is disabled in T3 Code settings.",
525 },
526 });
527 }
528​
529 return buildServerProvider({
530 presentation: CODEX_PRESENTATION,
531 enabled: true,
532 checkedAt,
533 models,
534 skills: [],
535 probe: {
536 installed: false,
537 version: null,
538 status: "warning",
539 auth: { status: "unknown" },
540 message: "Codex provider status has not been checked in this session yet.",
541 },
542 });
543 });
544​
545function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): {
546 readonly status: Exclude<ServerProviderState, "disabled">;
547 readonly auth: ServerProvider["auth"];
548 readonly message?: string;
549} {
550 const authLabel = codexAccountAuthLabel(account.account);
551 const authEmail = codexAccountEmail(account.account);
552 // One email can hold several workspaces, each with its own quota; the usage
553 // read names the one this login draws on.
554 const workspaceId =
555 rateLimits && "accountId" in rateLimits ? rateLimits.accountId?.trim() : undefined;
556 const auth = {
557 status: account.account ? ("authenticated" as const) : ("unknown" as const),
558 ...(account.account?.type ? { type: account.account?.type } : {}),
559 ...(authLabel ? { label: authLabel } : {}),
560 ...(authEmail ? { email: authEmail } : {}),
561 ...(workspaceId ? { workspaceId } : {}),
562 } satisfies ServerProvider["auth"];
563​
564 if (account.account) {
565 return { status: "ready", auth };
566 }
567​
568 if (account.requiresOpenaiAuth) {
569 return {
570 status: "error",
571 auth: { status: "unauthenticated" },
572 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
573 };
574 }
575​
576 return { status: "ready", auth };
578​
579export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
580 codexSettings: CodexSettings,
581 probe: (input: {
582 readonly binaryPath: string;
583 readonly homePath?: string;
584 readonly launchArgs?: string;
585 readonly cwd: string;
586 readonly customModels: ReadonlyArray<CustomModelSetting>;
587 readonly environment?: NodeJS.ProcessEnv;
588 readonly skipNativeUsage?: boolean;
589 }) => Effect.Effect<
590 CodexAppServerProviderSnapshot,
591 CodexErrors.CodexAppServerError,
592 ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
593 > = probeCodexAppServerProvider,
594 environment?: NodeJS.ProcessEnv,
595 managedAuth?: ServerProvider["auth"],
596): Effect.fn.Return<
597 ServerProviderDraft,
598 ServerSettingsError,
599 ChildProcessSpawner.ChildProcessSpawner
600> {
601 const resolvedEnvironment = environment ?? process.env;
602 const checkedAt = DateTime.formatIso(yield* DateTime.now);
603 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
604​
605 if (!codexSettings.enabled) {
606 return buildServerProvider({
607 presentation: CODEX_PRESENTATION,
608 enabled: false,
609 checkedAt,
610 models: emptyModels,
611 skills: [],
612 probe: {
613 installed: false,
614 version: null,
615 status: "warning",
616 auth: { status: "unknown" },
617 message: "Codex is disabled in T3 Code settings.",
618 },
619 });
620 }
621​
622 const probeResult = yield* probe({
623 binaryPath: codexSettings.binaryPath,
624 homePath: codexSettings.homePath,
625 launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
626 cwd: process.cwd(),
627 customModels: codexSettings.customModels,
628 environment: resolvedEnvironment,
629 ...(managedAuth ? { skipNativeUsage: true } : {}),
630 }).pipe(
631 Effect.scoped,
632 Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),
633 Effect.result,
634 );
635​
636 if (Result.isFailure(probeResult)) {
637 const error = probeResult.failure;
638 const installed = !isCodexAppServerSpawnError(error);
639 return buildServerProvider({
640 presentation: CODEX_PRESENTATION,
641 enabled: codexSettings.enabled,
642 checkedAt,
643 models: emptyModels,
644 skills: [],
645 probe: {
646 installed,
647 version: null,
648 status: "error",
649 auth: { status: "unknown" },
650 message: installed
651 ? `Codex app-server provider probe failed: ${error.message}.`
652 : `Could not start Codex CLI (\`${codexSettings.binaryPath}\`). Check Settings → Providers → Codex → Binary path on the server.` +
653 (codexSettings.binaryPath === "codex"
654 ? " Installing ChatGPT or Codex desktop may not add codex to PATH."
655 : " Make sure the configured executable exists and can be run."),
656 },
657 });
658 }
659​
660 if (Option.isNone(probeResult.success)) {
661 return buildServerProvider({
662 presentation: CODEX_PRESENTATION,
663 enabled: codexSettings.enabled,
664 checkedAt,
665 models: emptyModels,
666 skills: [],
667 probe: {
668 installed: true,
669 version: null,
670 status: "error",
671 auth: { status: "unknown" },
672 message: "Timed out while checking Codex app-server provider status.",
673 },
674 });
675 }
676​
677 const snapshot = probeResult.success.value;
678 const accountStatus = managedAuth
679 ? { status: "ready" as const, auth: managedAuth, message: undefined }
680 : accountProbeStatus(snapshot);
681 const usageLimits =
682 snapshot.account.account?.type === "apiKey"
683 ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" })
684 : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits
685 ? makeUnavailableUsageLimits({
686 checkedAt,
687 reason: "probeFailed",
688 ...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}),
689 })
690 : codexRateLimitsToLimits({
691 snapshot: snapshot.rateLimits.snapshot,
692 rateLimitsByLimitId: snapshot.rateLimits.rateLimitsByLimitId,
693 resetCredits: snapshot.rateLimits.resetCredits,
694 checkedAt,
695 });
696​
697 return buildServerProvider({
698 presentation: CODEX_PRESENTATION,
699 enabled: codexSettings.enabled,
700 checkedAt,
701 models: snapshot.models,
702 skills: snapshot.skills,
703 slashCommands: [
704 COMPACT_SLASH_COMMAND,
705 {
706 name: "goal",
707 description: "Set a goal Codex keeps working toward until it is done",
708 input: { hint: "Objective, or pause, resume, clear" },
709 },
710 {
711 name: "feedback",
712 description: "Send this thread and Codex logs to OpenAI",
713 input: { hint: "Describe the issue (optional)" },
714 },
715 ],
716 probe: {
717 installed: true,
718 version: snapshot.version ?? null,
719 status: accountStatus.status,
720 auth: accountStatus.auth,
721 ...(accountStatus.message ? { message: accountStatus.message } : {}),
722 ...(managedAuth ? {} : { usageLimits }),
723 },
724 });
725});
726​
727// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of
728// the per-instance-driver refactor. `CodexDriver.create()` builds a managed
729// snapshot per instance (each with its own `CodexSettings`) and hands the
730// resulting `ManagedServerProvider` back as `ProviderInstance.snapshot`.
731//
732// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are
733// re-exported for use by `CodexDriver`.
734export { makePendingCodexProvider };