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