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 mapCodexModelCapabilities(
164 model: CodexSchema.V2ModelListResponse__Model,
165): ModelCapabilities {
166 const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
167 reasoningEffort ===
168 (codexModelFamily(model.model) === "gpt-6-astra" ? "medium" : model.defaultReasoningEffort)
169 ? {
170 id: reasoningEffort,
171 label: reasoningEffortLabel(reasoningEffort),
172 isDefault: true,
173 }
174 : {
175 id: reasoningEffort,
176 label: reasoningEffortLabel(reasoningEffort),
177 },
178 );
179 const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
180 const serviceTiers =
181 model.serviceTiers && model.serviceTiers.length > 0
182 ? model.serviceTiers
183 : (model.additionalSpeedTiers ?? []).map((id) => ({
184 id,
185 name: id === "fast" ? "Fast" : id,
186 description: "",
187 }));
188 const catalogDefaultServiceTier = serviceTiers.some(
189 (tier) => tier.id === model.defaultServiceTier,
190 )
191 ? model.defaultServiceTier
192 : null;
193 const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
194 const optionDescriptors: ProviderOptionDescriptor[] = [];
195
196 if (reasoningOptions.length > 0) {
197 optionDescriptors.push({
198 id: "reasoningEffort",
199 label: "Reasoning",
200 type: "select",
201 options: reasoningOptions,
202 ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
203 });
204 }
205 if (serviceTiers.length > 0) {
206 optionDescriptors.push({
207 id: "serviceTier",
208 label: "Service Tier",
209 type: "select",
210 options: [
211 {
212 id: DEFAULT_SERVICE_TIER_ID,
213 label: "Standard",
214 ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
215 },
216 ...serviceTiers.map((tier) => {
217 const description = SERVICE_TIER_DESCRIPTIONS[tier.id] ?? tier.description;
218 return {
219 id: tier.id,
220 label: tier.name,
221 ...(description ? { description } : {}),
222 ...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
223 };
224 }),
225 ],
226 currentValue: defaultServiceTier,
227 });
228 }
229
230 return createModelCapabilities({
231 optionDescriptors,
232 });
233}
234
235function parseCodexModelListResponse(
236 response: CodexSchema.V2ModelListResponse,
237): ReadonlyArray<ServerProviderModel> {
238 return response.data.map((model) => ({
239 slug: model.model,
240 name: formatCodexModelName(model.displayName),
241 isCustom: false,
242 ...(model.isDefault ? { isDefault: true } : {}),
243 capabilities: mapCodexModelCapabilities(model),
244 }));
245}
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 });
266}
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 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
278 return providerModelsFromSettings(models, customModels, fallbackCapabilities);
279}
280
281function parseCodexSkillsListResponse(
282 response: CodexSchema.V2SkillsListResponse,
283 cwd: string,
284): ReadonlyArray<ServerProviderSkill> {
285 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
286 const skills = matchingEntry
287 ? matchingEntry.skills
288 : response.data.flatMap((entry) => entry.skills);
289
290 return skills.map((skill) => {
291 const shortDescription =
292 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
293
294 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
295 name: skill.name,
296 path: skill.path,
297 enabled: skill.enabled,
298 };
299
300 if (skill.description) {
301 parsedSkill.description = skill.description;
302 }
303 if (skill.scope) {
304 parsedSkill.scope = skill.scope;
305 }
306 if (skill.interface?.displayName) {
307 parsedSkill.displayName = skill.interface.displayName;
308 }
309 if (shortDescription) {
310 parsedSkill.shortDescription = shortDescription;
311 }
312
313 return parsedSkill;
314 });
315}
316
317const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
318 client: CodexClient.CodexAppServerClient["Service"],
319) {
320 const models: ServerProviderModel[] = [];
321 let cursor: string | null | undefined = undefined;
322
323 do {
324 const response: CodexSchema.V2ModelListResponse = yield* client.request(
325 "model/list",
326 cursor ? { cursor } : {},
327 );
328 models.push(...parseCodexModelListResponse(response));
329 cursor = response.nextCursor;
330 } while (cursor);
331
332 return models;
333});
334
335const decodeCodexModelsCacheStamp = Schema.decodeUnknownOption(
336 Schema.fromJsonString(Schema.Struct({ fetched_at: Schema.String })),
337);
338
339const readCodexModelsCacheFetchedAt = Effect.fn("readCodexModelsCacheFetchedAt")(function* (
340 codexHome: string,
341) {
342 const fileSystem = yield* FileSystem.FileSystem;
343 const path = yield* Path.Path;
344 const text = yield* fileSystem
345 .readFileString(path.join(codexHome, "models_cache.json"))
346 .pipe(Effect.option);
347 return Option.flatMap(text, decodeCodexModelsCacheStamp).pipe(
348 Option.flatMap((stamp) => DateTime.make(stamp.fetched_at)),
349 Option.match({ onNone: () => Number.NaN, onSome: DateTime.toEpochMillis }),
350 );
351});
352
353/**
354 * Every Codex client on the machine shares that file, and the backend tailors
355 * the catalog to each client's originator: the plain CLI does not get Sol
356 * Ultrafast. App-server refreshes the catalog online at startup, so wait until
357 * a write newer than this process's spawn lands, then list again.
358 */
359const requestCodexChatGptModels = Effect.fn("requestCodexChatGptModels")(function* (input: {
360 readonly client: CodexClient.CodexAppServerClient["Service"];
361 readonly codexHome: string;
362 readonly spawnedAtMs: number;
363}) {
364 const models = yield* requestAllCodexModels(input.client);
365 const refreshed = yield* readCodexModelsCacheFetchedAt(input.codexHome).pipe(
366 Effect.repeat({
367 schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL),
368 until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs,
369 }),
370 Effect.timeoutOption(CODEX_CATALOG_REFRESH_TIMEOUT),
371 );
372 if (Option.isNone(refreshed)) {
373 yield* Effect.logWarning(
374 "Codex did not refresh its model catalog in time; using the cached catalog.",
375 );
376 return models;
377 }
378 return yield* requestAllCodexModels(input.client);
379});
380
381/**
382 * App-server starts its catalog refresh before `initialize` names the client,
383 * so that first fetch goes out as the plain CLI, misses tiers like Sol
384 * Ultrafast, and overwrites the shared `models_cache.json`. Naming the
385 * originator at spawn closes that race.
386 */
387export const codexAppServerEnvironment = (
388 environment: NodeJS.ProcessEnv | undefined,
389): NodeJS.ProcessEnv => ({
390 CODEX_INTERNAL_ORIGINATOR_OVERRIDE: CODEX_CLIENT_NAME,
391 ...environment,
392});
393
394export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
395 return {
396 clientInfo: {
397 name: CODEX_CLIENT_NAME,
398 title: CODEX_CLIENT_NAME,
399 version: packageJson.version,
400 },
401 capabilities: {
402 experimentalApi: true,
403 },
404 };
405}
406
407export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(function* (input: {
408 readonly binaryPath: string;
409 readonly homePath?: string | undefined;
410 readonly launchArgs?: string | undefined;
411 readonly cwd: string;
412 readonly environment?: NodeJS.ProcessEnv | undefined;
413}) {
414 // `~` is not shell-expanded when env vars are set via `child_process.spawn`,
415 // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
416 // "CODEX_HOME points to '~/.codex_work', but that path does not exist".
417 const resolvedHomePath = input.homePath
418 ? expandHomePath(input.homePath, yield* HostProcess.HomeDirectory)
419 : undefined;
420 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
421 const environment = {
422 ...codexAppServerEnvironment(input.environment),
423 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
424 };
425 const spawnCommand = yield* resolveSpawnCommand(
426 input.binaryPath,
427 codexAppServerArgs(input.launchArgs),
428 { env: environment, extendEnv: true },
429 );
430 const child = yield* spawner
431 .spawn(
432 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
433 cwd: input.cwd,
434 env: environment,
435 extendEnv: true,
436 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
437 shell: spawnCommand.shell,
438 }),
439 )
440 .pipe(
441 Effect.mapError(
442 (cause) =>
443 new CodexErrors.CodexAppServerSpawnError({
444 command: `${input.binaryPath} app-server`,
445 cause,
446 }),
447 ),
448 );
449 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
450 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
451 Effect.provide(clientContext),
452 );
453 const initialize = yield* client.request("initialize", buildCodexInitializeParams());
454 yield* client.notify("initialized", undefined);
455 return { client, initialize };
456});
457
458const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
459 readonly binaryPath: string;
460 readonly homePath?: string;
461 readonly launchArgs?: string;
462 readonly cwd: string;
463 readonly customModels?: ReadonlyArray<CustomModelSetting>;
464 readonly environment?: NodeJS.ProcessEnv;
465 readonly skipNativeUsage?: boolean;
466}) {
467 const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
468 const { client, initialize } = yield* withCodexAppServerClient(input);
469
470 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
471 const version = versionMatch ? versionMatch[1] : undefined;
472
473 const accountResponse = yield* client.request("account/read", {});
474 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
475 return {
476 account: accountResponse,
477 version,
478 models: appendCustomCodexModels([], input.customModels ?? []),
479 skills: [],
480 } satisfies CodexAppServerProviderSnapshot;
481 }
482
483 const [skillsResponse, models, rateLimits] = yield* Effect.all(
484 [
485 client.request("skills/list", {
486 cwds: [input.cwd],
487 }),
488 accountResponse.account?.type === "chatgpt"
489 ? requestCodexChatGptModels({ client, codexHome: initialize.codexHome, spawnedAtMs })
490 : requestAllCodexModels(client),
491 input.skipNativeUsage
492 ? Effect.succeed(undefined)
493 : client.request("account/rateLimits/read", null).pipe(
494 Effect.map((response): CodexRateLimitsProbe => ({
495 snapshot: response.rateLimits,
496 rateLimitsByLimitId: response.rateLimitsByLimitId,
497 resetCredits: response.rateLimitResetCredits,
498 accountId: response.accountId,
499 })),
500 Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)),
501 Effect.map(
502 Option.getOrElse((): CodexRateLimitsProbe => ({
503 failure: "Codex did not answer the usage request.",
504 })),
505 ),
506 Effect.catch((error) =>
507 Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
508 Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
509 ),
510 ),
511 ),
512 ],
513 { concurrency: "unbounded" },
514 );
515
516 return {
517 account: accountResponse,
518 ...(rateLimits ? { rateLimits } : {}),
519 version,
520 models: applyPreferredCodexDefaultModel(
521 appendCustomCodexModels(models, input.customModels ?? []),
522 ),
523 skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
524 } satisfies CodexAppServerProviderSnapshot;
525});
526
527export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
528 readonly binaryPath: string;
529 readonly homePath?: string;
530 readonly launchArgs?: string;
531 readonly cwd: string;
532 readonly environment?: NodeJS.ProcessEnv;
533}) {
534 const { client } = yield* withCodexAppServerClient(input);
535 const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
536 return parseCodexSkillsListResponse(skillsResponse, input.cwd);
537});
538
539const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
540 appendCustomCodexModels([], codexSettings.customModels);
541
542const makePendingCodexProvider = (
543 codexSettings: CodexSettings,
544): Effect.Effect<ServerProviderDraft> =>
545 Effect.gen(function* () {
546 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
547 const models = emptyCodexModelsFromSettings(codexSettings);
548
549 if (!codexSettings.enabled) {
550 return buildServerProvider({
551 presentation: CODEX_PRESENTATION,
552 enabled: false,
553 checkedAt,
554 models,
555 skills: [],
556 probe: {
557 installed: false,
558 version: null,
559 status: "warning",
560 auth: { status: "unknown" },
561 message: "Codex is disabled in T3 Code settings.",
562 },
563 });
564 }
565
566 return buildServerProvider({
567 presentation: CODEX_PRESENTATION,
568 enabled: true,
569 checkedAt,
570 models,
571 skills: [],
572 probe: {
573 installed: false,
574 version: null,
575 status: "warning",
576 auth: { status: "unknown" },
577 message: "Codex provider status has not been checked in this session yet.",
578 },
579 });
580 });
581
582function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): {
583 readonly status: Exclude<ServerProviderState, "disabled">;
584 readonly auth: ServerProvider["auth"];
585 readonly message?: string;
586} {
587 const authLabel = codexAccountAuthLabel(account.account);
588 const authEmail = codexAccountEmail(account.account);
589 const workspaceId =
590 rateLimits && "accountId" in rateLimits ? rateLimits.accountId?.trim() : undefined;
591 const auth = {
592 status: account.account ? ("authenticated" as const) : ("unknown" as const),
593 ...(account.account?.type ? { type: account.account?.type } : {}),
594 ...(authLabel ? { label: authLabel } : {}),
595 ...(authEmail ? { email: authEmail } : {}),
596 ...(workspaceId ? { workspaceId } : {}),
597 } satisfies ServerProvider["auth"];
598
599 if (account.account) {
600 return { status: "ready", auth };
601 }
602
603 if (account.requiresOpenaiAuth) {
604 return {
605 status: "error",
606 auth: { status: "unauthenticated" },
607 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
608 };
609 }
610
611 return { status: "ready", auth };
612}
613
614export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
615 codexSettings: CodexSettings,
616 probe: (input: {
617 readonly binaryPath: string;
618 readonly homePath?: string;
619 readonly launchArgs?: string;
620 readonly cwd: string;
621 readonly customModels: ReadonlyArray<CustomModelSetting>;
622 readonly environment?: NodeJS.ProcessEnv;
623 readonly skipNativeUsage?: boolean;
624 }) => Effect.Effect<
625 CodexAppServerProviderSnapshot,
626 CodexErrors.CodexAppServerError,
627 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope
628 > = probeCodexAppServerProvider,
629 environment?: NodeJS.ProcessEnv,
630 managedAuth?: ServerProvider["auth"],
631): Effect.fn.Return<
632 ServerProviderDraft,
633 ServerSettingsError,
634 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
635> {
636 const resolvedEnvironment = environment ?? process.env;
637 const checkedAt = DateTime.formatIso(yield* DateTime.now);
638 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
639
640 if (!codexSettings.enabled) {
641 return buildServerProvider({
642 presentation: CODEX_PRESENTATION,
643 enabled: false,
644 checkedAt,
645 models: emptyModels,
646 skills: [],
647 probe: {
648 installed: false,
649 version: null,
650 status: "warning",
651 auth: { status: "unknown" },
652 message: "Codex is disabled in T3 Code settings.",
653 },
654 });
655 }
656
657 const probeResult = yield* probe({
658 binaryPath: codexSettings.binaryPath,
659 homePath: codexSettings.homePath,
660 launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
661 cwd: process.cwd(),
662 customModels: codexSettings.customModels,
663 environment: resolvedEnvironment,
664 ...(managedAuth ? { skipNativeUsage: true } : {}),
665 }).pipe(
666 Effect.scoped,
667 Effect.timeoutOption(Duration.millis(CODEX_AUTH_PROBE_TIMEOUT_MS)),
668 Effect.result,
669 );
670
671 if (Result.isFailure(probeResult)) {
672 const error = probeResult.failure;
673 const installed = !isCodexAppServerSpawnError(error);
674 return buildServerProvider({
675 presentation: CODEX_PRESENTATION,
676 enabled: codexSettings.enabled,
677 checkedAt,
678 models: emptyModels,
679 skills: [],
680 probe: {
681 installed,
682 version: null,
683 status: "error",
684 auth: { status: "unknown" },
685 message: installed
686 ? `Codex app-server provider probe failed: ${error.message}.`
687 : `Could not start Codex CLI (\`${codexSettings.binaryPath}\`). Check Settings → Providers → Codex → Binary path on the server.` +
688 (codexSettings.binaryPath === "codex"
689 ? " Installing ChatGPT or Codex desktop may not add codex to PATH."
690 : " Make sure the configured executable exists and can be run."),
691 },
692 });
693 }
694
695 if (Option.isNone(probeResult.success)) {
696 return buildServerProvider({
697 presentation: CODEX_PRESENTATION,
698 enabled: codexSettings.enabled,
699 checkedAt,
700 models: emptyModels,
701 skills: [],
702 probe: {
703 installed: true,
704 version: null,
705 status: "error",
706 auth: { status: "unknown" },
707 message: "Timed out while checking Codex app-server provider status.",
708 },
709 });
710 }
711
712 const snapshot = probeResult.success.value;
713 const accountStatus = managedAuth
714 ? { status: "ready" as const, auth: managedAuth, message: undefined }
715 : accountProbeStatus(snapshot);
716 const usageLimits =
717 snapshot.account.account?.type === "apiKey"
718 ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" })
719 : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits
720 ? makeUnavailableUsageLimits({
721 checkedAt,
722 reason: "probeFailed",
723 ...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}),
724 })
725 : codexRateLimitsToLimits({
726 snapshot: snapshot.rateLimits.snapshot,
727 rateLimitsByLimitId: snapshot.rateLimits.rateLimitsByLimitId,
728 resetCredits: snapshot.rateLimits.resetCredits,
729 checkedAt,
730 });
731
732 return buildServerProvider({
733 presentation: CODEX_PRESENTATION,
734 enabled: codexSettings.enabled,
735 checkedAt,
736 models: snapshot.models,
737 skills: snapshot.skills,
738 slashCommands: [
739 COMPACT_SLASH_COMMAND,
740 {
741 name: "goal",
742 description: "Set a goal Codex keeps working toward until it is done",
743 input: { hint: "Objective, or pause, resume, clear" },
744 },
745 {
746 name: "feedback",
747 description: "Send this thread and Codex logs to OpenAI",
748 input: { hint: "Describe the issue (optional)" },
749 },
750 ],
751 probe: {
752 installed: true,
753 version: snapshot.version ?? null,
754 status: accountStatus.status,
755 auth: accountStatus.auth,
756 ...(accountStatus.message ? { message: accountStatus.message } : {}),
757 ...(managedAuth ? {} : { usageLimits }),
758 },
759 });
760});
761
762export { makePendingCodexProvider };