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 type * as CodexClient from "effect-codex-app-server/client";
16import type * 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 CodexClient = yield* Effect.promise(() => import("effect-codex-app-server/client"));
450 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
451 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
452 Effect.provide(clientContext),
453 );
454 const initialize = yield* client.request("initialize", buildCodexInitializeParams());
455 yield* client.notify("initialized", undefined);
456 return { client, initialize };
457});
458
459const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
460 readonly binaryPath: string;
461 readonly homePath?: string;
462 readonly launchArgs?: string;
463 readonly cwd: string;
464 readonly customModels?: ReadonlyArray<CustomModelSetting>;
465 readonly environment?: NodeJS.ProcessEnv;
466 readonly skipNativeUsage?: boolean;
467}) {
468 const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
469 const { client, initialize } = yield* withCodexAppServerClient(input);
470
471 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
472 const version = versionMatch ? versionMatch[1] : undefined;
473
474 const accountResponse = yield* client.request("account/read", {});
475 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
476 return {
477 account: accountResponse,
478 version,
479 models: appendCustomCodexModels([], input.customModels ?? []),
480 skills: [],
481 } satisfies CodexAppServerProviderSnapshot;
482 }
483
484 const [skillsResponse, models, rateLimits] = yield* Effect.all(
485 [
486 client.request("skills/list", {
487 cwds: [input.cwd],
488 }),
489 accountResponse.account?.type === "chatgpt"
490 ? requestCodexChatGptModels({ client, codexHome: initialize.codexHome, spawnedAtMs })
491 : requestAllCodexModels(client),
492 input.skipNativeUsage
493 ? Effect.succeed(undefined)
494 : client.request("account/rateLimits/read", null).pipe(
495 Effect.map((response): CodexRateLimitsProbe => ({
496 snapshot: response.rateLimits,
497 rateLimitsByLimitId: response.rateLimitsByLimitId,
498 resetCredits: response.rateLimitResetCredits,
499 accountId: response.accountId,
500 })),
501 Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)),
502 Effect.map(
503 Option.getOrElse((): CodexRateLimitsProbe => ({
504 failure: "Codex did not answer the usage request.",
505 })),
506 ),
507 Effect.catch((error) =>
508 Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
509 Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
510 ),
511 ),
512 ),
513 ],
514 { concurrency: "unbounded" },
515 );
516
517 return {
518 account: accountResponse,
519 ...(rateLimits ? { rateLimits } : {}),
520 version,
521 models: applyPreferredCodexDefaultModel(
522 appendCustomCodexModels(models, input.customModels ?? []),
523 ),
524 skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
525 } satisfies CodexAppServerProviderSnapshot;
526});
527
528export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
529 readonly binaryPath: string;
530 readonly homePath?: string;
531 readonly launchArgs?: string;
532 readonly cwd: string;
533 readonly environment?: NodeJS.ProcessEnv;
534}) {
535 const { client } = yield* withCodexAppServerClient(input);
536 const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
537 return parseCodexSkillsListResponse(skillsResponse, input.cwd);
538});
539
540const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
541 appendCustomCodexModels([], codexSettings.customModels);
542
543const makePendingCodexProvider = (
544 codexSettings: CodexSettings,
545): Effect.Effect<ServerProviderDraft> =>
546 Effect.gen(function* () {
547 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
548 const models = emptyCodexModelsFromSettings(codexSettings);
549
550 if (!codexSettings.enabled) {
551 return buildServerProvider({
552 presentation: CODEX_PRESENTATION,
553 enabled: false,
554 checkedAt,
555 models,
556 skills: [],
557 probe: {
558 installed: false,
559 version: null,
560 status: "warning",
561 auth: { status: "unknown" },
562 message: "Codex is disabled in T3 Code settings.",
563 },
564 });
565 }
566
567 return buildServerProvider({
568 presentation: CODEX_PRESENTATION,
569 enabled: true,
570 checkedAt,
571 models,
572 skills: [],
573 probe: {
574 installed: false,
575 version: null,
576 status: "warning",
577 auth: { status: "unknown" },
578 message: "Codex provider status has not been checked in this session yet.",
579 },
580 });
581 });
582
583function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): {
584 readonly status: Exclude<ServerProviderState, "disabled">;
585 readonly auth: ServerProvider["auth"];
586 readonly message?: string;
587} {
588 const authLabel = codexAccountAuthLabel(account.account);
589 const authEmail = codexAccountEmail(account.account);
590 const workspaceId =
591 rateLimits && "accountId" in rateLimits ? rateLimits.accountId?.trim() : undefined;
592 const auth = {
593 status: account.account ? ("authenticated" as const) : ("unknown" as const),
594 ...(account.account?.type ? { type: account.account?.type } : {}),
595 ...(authLabel ? { label: authLabel } : {}),
596 ...(authEmail ? { email: authEmail } : {}),
597 ...(workspaceId ? { workspaceId } : {}),
598 } satisfies ServerProvider["auth"];
599
600 if (account.account) {
601 return { status: "ready", auth };
602 }
603
604 if (account.requiresOpenaiAuth) {
605 return {
606 status: "error",
607 auth: { status: "unauthenticated" },
608 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
609 };
610 }
611
612 return { status: "ready", auth };
613}
614
615export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
616 codexSettings: CodexSettings,
617 probe: (input: {
618 readonly binaryPath: string;
619 readonly homePath?: string;
620 readonly launchArgs?: string;
621 readonly cwd: string;
622 readonly customModels: ReadonlyArray<CustomModelSetting>;
623 readonly environment?: NodeJS.ProcessEnv;
624 readonly skipNativeUsage?: boolean;
625 }) => Effect.Effect<
626 CodexAppServerProviderSnapshot,
627 CodexErrors.CodexAppServerError,
628 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope
629 > = probeCodexAppServerProvider,
630 environment?: NodeJS.ProcessEnv,
631 managedAuth?: ServerProvider["auth"],
632): Effect.fn.Return<
633 ServerProviderDraft,
634 ServerSettingsError,
635 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
636> {
637 const resolvedEnvironment = environment ?? process.env;
638 const checkedAt = DateTime.formatIso(yield* DateTime.now);
639 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
640
641 if (!codexSettings.enabled) {
642 return buildServerProvider({
643 presentation: CODEX_PRESENTATION,
644 enabled: false,
645 checkedAt,
646 models: emptyModels,
647 skills: [],
648 probe: {
649 installed: false,
650 version: null,
651 status: "warning",
652 auth: { status: "unknown" },
653 message: "Codex is disabled in T3 Code settings.",
654 },
655 });
656 }
657
658 const probeResult = yield* probe({
659 binaryPath: codexSettings.binaryPath,
660 homePath: codexSettings.homePath,
661 launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
662 cwd: process.cwd(),
663 customModels: codexSettings.customModels,
664 environment: resolvedEnvironment,
665 ...(managedAuth ? { skipNativeUsage: true } : {}),
666 }).pipe(
667 Effect.scoped,
668 Effect.timeoutOption(Duration.millis(CODEX_AUTH_PROBE_TIMEOUT_MS)),
669 Effect.result,
670 );
671
672 if (Result.isFailure(probeResult)) {
673 const error = probeResult.failure;
674 const installed = !isCodexAppServerSpawnError(error);
675 return buildServerProvider({
676 presentation: CODEX_PRESENTATION,
677 enabled: codexSettings.enabled,
678 checkedAt,
679 models: emptyModels,
680 skills: [],
681 probe: {
682 installed,
683 version: null,
684 status: "error",
685 auth: { status: "unknown" },
686 message: installed
687 ? `Codex app-server provider probe failed: ${error.message}.`
688 : `Could not start Codex CLI (\`${codexSettings.binaryPath}\`). Check Settings → Providers → Codex → Binary path on the server.` +
689 (codexSettings.binaryPath === "codex"
690 ? " Installing ChatGPT or Codex desktop may not add codex to PATH."
691 : " Make sure the configured executable exists and can be run."),
692 },
693 });
694 }
695
696 if (Option.isNone(probeResult.success)) {
697 return buildServerProvider({
698 presentation: CODEX_PRESENTATION,
699 enabled: codexSettings.enabled,
700 checkedAt,
701 models: emptyModels,
702 skills: [],
703 probe: {
704 installed: true,
705 version: null,
706 status: "error",
707 auth: { status: "unknown" },
708 message: "Timed out while checking Codex app-server provider status.",
709 },
710 });
711 }
712
713 const snapshot = probeResult.success.value;
714 const accountStatus = managedAuth
715 ? { status: "ready" as const, auth: managedAuth, message: undefined }
716 : accountProbeStatus(snapshot);
717 const usageLimits =
718 snapshot.account.account?.type === "apiKey"
719 ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" })
720 : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits
721 ? makeUnavailableUsageLimits({
722 checkedAt,
723 reason: "probeFailed",
724 ...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}),
725 })
726 : codexRateLimitsToLimits({
727 snapshot: snapshot.rateLimits.snapshot,
728 rateLimitsByLimitId: snapshot.rateLimits.rateLimitsByLimitId,
729 resetCredits: snapshot.rateLimits.resetCredits,
730 checkedAt,
731 });
732
733 return buildServerProvider({
734 presentation: CODEX_PRESENTATION,
735 enabled: codexSettings.enabled,
736 checkedAt,
737 models: snapshot.models,
738 skills: snapshot.skills,
739 slashCommands: [
740 COMPACT_SLASH_COMMAND,
741 {
742 name: "goal",
743 description: "Set a goal Codex keeps working toward until it is done",
744 input: { hint: "Objective, or pause, resume, clear" },
745 },
746 {
747 name: "feedback",
748 description: "Send this thread and Codex logs to OpenAI",
749 input: { hint: "Describe the issue (optional)" },
750 },
751 ],
752 probe: {
753 installed: true,
754 version: snapshot.version ?? null,
755 status: accountStatus.status,
756 auth: accountStatus.auth,
757 ...(accountStatus.message ? { message: accountStatus.message } : {}),
758 ...(managedAuth ? {} : { usageLimits }),
759 },
760 });
761});
762
763export { makePendingCodexProvider };