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