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