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