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

CodexProvider.ts

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