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