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

CodexProvider.ts

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