Open History to see the last commit
1import { pipe } from "effect/Function";
2import * as DateTime from "effect/DateTime";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Result from "effect/Result";
10import * as Schema from "effect/Schema";
11import * as Schedule from "effect/Schedule";
12import * as Scope from "effect/Scope";
13import * as Types from "effect/Types";
14import * as ChildProcess from "effect/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import * as CodexClient from "effect-codex-app-server/client";
17import * as CodexSchema from "effect-codex-app-server/schema";
18import * as CodexErrors from "effect-codex-app-server/errors";
19
20import type {
21 CodexSettings,
22 CustomModelSetting,
23 ServerProvider,
24 ServerProviderState,
25 ModelCapabilities,
26 ProviderOptionDescriptor,
27 ServerProviderModel,
28 ServerProviderSkill,
29} from "@t3tools/contracts";
30import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
31
32import {
33 codexModelFamily,
34 createModelCapabilities,
35 formatCodexModelName,
36} from "@t3tools/shared/model";
37import { resolveSpawnCommand } from "@t3tools/shared/shell";
38import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
39import {
40 buildServerProvider,
41 COMPACT_SLASH_COMMAND,
42 DEFAULT_TIMEOUT_MS,
43 providerModelsFromSettings,
44 providerProbeEnvironment,
45 spawnAndCollect,
46 type ServerProviderDraft,
47} from "@t3tools/provider-core/server/snapshotProbe";
48import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
49import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
50import {
51 codexRateLimitsFailureMessage,
52 codexRateLimitsToLimits,
53 type CodexRateLimitSnapshot,
54 type CodexResetCreditsSummary,
55} from "./codexUsageLimits.ts";
56import * as HostProcess from "@t3tools/shared/HostProcess";
57import packageJson from "../../package.json" with { type: "json" };
58const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
59const RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000;
60
61type CodexRateLimitsProbe =
62 | {
63 readonly snapshot: CodexRateLimitSnapshot;
64 readonly rateLimitsByLimitId?:
65 | Readonly<Record<string, CodexRateLimitSnapshot>>
66 | null
67 | undefined;
68 readonly resetCredits: CodexResetCreditsSummary | null | undefined;
69 readonly accountId?: string | null | undefined;
70 }
71 | { readonly failure: string };
72
73const CodexRoutingConfig = Schema.Struct({
74 model_provider: Schema.optionalKey(Schema.NullOr(Schema.String)),
75 openai_base_url: Schema.optionalKey(Schema.NullOr(Schema.String)),
76 model_providers: Schema.optionalKey(
77 Schema.Record(
78 Schema.String,
79 Schema.Struct({ base_url: Schema.optionalKey(Schema.NullOr(Schema.String)) }),
80 ),
81 ),
82});
83const decodeCodexRoutingConfig = Schema.decodeUnknownOption(CodexRoutingConfig);
84
85function routesToNativeOpenai(config: unknown): boolean {
86 const decoded = decodeCodexRoutingConfig(config);
87 if (Option.isNone(decoded)) return false;
88 const routing = decoded.value;
89 const providerId = routing.model_provider ?? "openai";
90 const provider = routing.model_providers?.[providerId];
91 if (providerId !== "openai" && !provider) return false;
92 const baseUrl =
93 providerId === "openai" ? routing.openai_base_url || undefined : provider?.base_url;
94 // A provider without an override uses Codex's auth-dependent OpenAI default.
95 if (baseUrl == null) return true;
96 if (!URL.canParse(baseUrl)) return false;
97 const url = new URL(baseUrl);
98 return (
99 url.protocol === "https:" &&
100 (url.hostname === "api.openai.com" || url.hostname === "chatgpt.com")
101 );
102}
103
104// A stored login does not mean this provider's traffic spends that login's quota.
105export const codexRoutesSpendNativeQuota = (
106 account: CodexSchema.V2GetAccountResponse,
107 config: unknown,
108): boolean =>
109 account.requiresOpenaiAuth && account.account?.type !== "apiKey" && routesToNativeOpenai(config);
110
111const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
112const CODEX_CATALOG_REFRESH_TIMEOUT_MS = 3_000;
113const CODEX_CONFIG_PROBE_TIMEOUT_MS = 3_000;
114const CODEX_CATALOG_REFRESH_POLL = "100 millis" as const;
115const CODEX_CLIENT_NAME = "T3 Code";
116// Handshake plus account/models/skills requests can exceed the shared 10s probe budget.
117const CODEX_AUTH_PROBE_TIMEOUT_MS = 20_000;
118const CODEX_DISCOVERY_MARGIN_MS = 250;
119// `codex-cli 0.159.0`, `codex-cli 0.160.0-alpha.1` or the npm CLI's bare `0.1.4161006`.
120// Keep a prerelease suffix so compatibility stays unknown for it, as it does for `initialize`.
121const CODEX_CLI_VERSION_PATTERN = /(?:^|\s)v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?=\s|$)/u;
122
123const CODEX_PRESENTATION = {
124 displayName: "Codex",
125 showInteractionModeToggle: true,
126 reportsContextWindow: true,
127} as const;
128
129export interface CodexAppServerProviderSnapshot {
130 readonly account: CodexSchema.V2GetAccountResponse;
131 readonly nativeUsage?: boolean;
132 readonly rateLimits?: CodexRateLimitsProbe;
133 readonly version: string | undefined;
134 readonly models: ReadonlyArray<ServerProviderModel> | undefined;
135 readonly serviceTier?: string | undefined;
136 readonly skills: ReadonlyArray<ServerProviderSkill>;
137}
138
139const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
140 none: "None",
141 minimal: "Minimal",
142 low: "Low",
143 medium: "Medium",
144 high: "High",
145 xhigh: "Extra High",
146 max: "Max",
147 ultra: "Ultra",
148};
149
150const DEFAULT_SERVICE_TIER_ID = "default";
151
152const SERVICE_TIER_DESCRIPTIONS: Readonly<Record<string, string>> = {
153 ultrafast: "Even faster, more expensive",
154};
155
156function reasoningEffortLabel(reasoningEffort: string): string {
157 return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
158}
159
160function codexAccountAuthLabel(
161 account: CodexSchema.V2GetAccountResponse["account"],
162 usagePlanType: string | null | undefined,
163) {
164 if (!account) return undefined;
165 if (account.type === "apiKey") return "OpenAI API Key";
166 if (account.type === "amazonBedrock") return "Amazon Bedrock";
167 if (account.type !== "chatgpt") return undefined;
168 // account/read takes the plan from the cached login token; the usage read asks the backend.
169 const usageLabel = usagePlanType === "unknown" ? undefined : codexPlanLabel(usagePlanType);
170 return usageLabel ?? codexPlanLabel(account.planType);
171}
172
173export function codexPlanLabel(planType: string | null | undefined): string | undefined {
174 switch (planType) {
175 case "free":
176 return "ChatGPT Free Subscription";
177 case "go":
178 return "ChatGPT Go Subscription";
179 case "plus":
180 return "ChatGPT Plus Subscription";
181 case "pro":
182 return "ChatGPT Pro 200 Subscription";
183 case "prolite":
184 return "ChatGPT Pro 100 Subscription";
185 case "promax":
186 return "ChatGPT Pro 500 Subscription";
187 case "self_serve_business_prolite":
188 return "ChatGPT Business Premium Subscription";
189 case "team":
190 case "self_serve_business_usage_based":
191 case "business":
192 return "ChatGPT Business Subscription";
193 case "ent26":
194 case "enterprise_cbp_automation":
195 case "enterprise_cbp_usage_based":
196 case "enterprise":
197 return "ChatGPT Enterprise Subscription";
198 case "edu":
199 case "edu_plus":
200 case "edu_pro":
201 return "ChatGPT Edu Subscription";
202 case "unknown":
203 return "ChatGPT Subscription";
204 default:
205 return undefined;
206 }
207}
208
209function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) {
210 if (!account || account.type !== "chatgpt") return undefined;
211 return account.email;
212}
213
214export function codexDefaultReasoningEffortOverride(model: string): "medium" | undefined {
215 return codexModelFamily(model) === "gpt-6-astra" ? "medium" : undefined;
216}
217
218export function mapCodexModelCapabilities(
219 model: CodexSchema.V2ModelListResponse__Model,
220): ModelCapabilities {
221 const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
222 reasoningEffort ===
223 (codexDefaultReasoningEffortOverride(model.model) ?? model.defaultReasoningEffort)
224 ? {
225 id: reasoningEffort,
226 label: reasoningEffortLabel(reasoningEffort),
227 isDefault: true,
228 }
229 : {
230 id: reasoningEffort,
231 label: reasoningEffortLabel(reasoningEffort),
232 },
233 );
234 const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
235 const serviceTiers =
236 model.serviceTiers && model.serviceTiers.length > 0
237 ? model.serviceTiers
238 : (model.additionalSpeedTiers ?? []).map((id) => ({
239 id,
240 name: id === "fast" ? "Fast" : id,
241 description: "",
242 }));
243 const catalogDefaultServiceTier = serviceTiers.some(
244 (tier) => tier.id === model.defaultServiceTier,
245 )
246 ? model.defaultServiceTier
247 : null;
248 const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
249 const optionDescriptors: ProviderOptionDescriptor[] = [];
250
251 if (reasoningOptions.length > 0) {
252 optionDescriptors.push({
253 id: "reasoningEffort",
254 label: "Reasoning",
255 type: "select",
256 options: reasoningOptions,
257 ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
258 });
259 }
260 if (serviceTiers.length > 0) {
261 optionDescriptors.push({
262 id: "serviceTier",
263 label: "Service Tier",
264 type: "select",
265 options: [
266 {
267 id: DEFAULT_SERVICE_TIER_ID,
268 label: "Standard",
269 ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
270 },
271 ...serviceTiers.map((tier) => {
272 const description = SERVICE_TIER_DESCRIPTIONS[tier.id] ?? tier.description;
273 return {
274 id: tier.id,
275 label: tier.name,
276 ...(description ? { description } : {}),
277 ...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
278 };
279 }),
280 ],
281 currentValue: defaultServiceTier,
282 });
283 }
284
285 return createModelCapabilities({
286 optionDescriptors,
287 });
288}
289
290function parseCodexModelListResponse(
291 response: CodexSchema.V2ModelListResponse,
292): ReadonlyArray<ServerProviderModel> {
293 return response.data.map((model) => ({
294 slug: model.model,
295 name: formatCodexModelName(model.displayName),
296 isCustom: false,
297 ...(model.isDefault ? { isDefault: true } : {}),
298 capabilities: mapCodexModelCapabilities(model),
299 }));
300}
301
302export function applyPreferredCodexDefaultModel(
303 models: ReadonlyArray<ServerProviderModel>,
304): ReadonlyArray<ServerProviderModel> {
305 const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.flatMap((slug) =>
306 models.filter((model) => !model.isCustom && codexModelFamily(model.slug) === slug),
307 )[0]?.slug;
308 if (!preferredSlug) {
309 return models;
310 }
311 return models.map((model) => {
312 if (model.slug === preferredSlug) {
313 return model.isDefault ? model : { ...model, isDefault: true };
314 }
315 if (!model.isDefault) {
316 return model;
317 }
318 const { isDefault: _isDefault, ...rest } = model;
319 return rest;
320 });
321}
322
323function applyConfiguredCodexServiceTier(
324 models: ReadonlyArray<ServerProviderModel>,
325 serviceTier: string | undefined,
326): ReadonlyArray<ServerProviderModel> {
327 if (!serviceTier) return models;
328 return models.map((model) => {
329 if (!model.capabilities?.optionDescriptors) return model;
330 return {
331 ...model,
332 capabilities: {
333 ...model.capabilities,
334 optionDescriptors: model.capabilities.optionDescriptors.map((descriptor) => {
335 if (descriptor.id !== "serviceTier" || descriptor.type !== "select") return descriptor;
336 const value = descriptor.options.find(
337 (option) =>
338 option.id === serviceTier || (serviceTier === "fast" && option.id === "priority"),
339 )?.id;
340 if (!value) return descriptor;
341 return {
342 ...descriptor,
343 currentValue: value,
344 options: descriptor.options.map(({ isDefault: _isDefault, ...option }) =>
345 option.id === value ? { ...option, isDefault: true } : option,
346 ),
347 };
348 }),
349 },
350 };
351 });
352}
353
354/**
355 * Codex has no static default capability set, so a bare custom slug borrows
356 * the first built-in's descriptors; an entry with its own capabilities keeps
357 * them.
358 */
359function appendCustomCodexModels(
360 models: ReadonlyArray<ServerProviderModel>,
361 customModels: ReadonlyArray<CustomModelSetting>,
362): ReadonlyArray<ServerProviderModel> {
363 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
364 return providerModelsFromSettings(models, customModels, fallbackCapabilities);
365}
366
367function parseCodexSkillsListResponse(
368 response: CodexSchema.V2SkillsListResponse,
369 cwd: string,
370): ReadonlyArray<ServerProviderSkill> {
371 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
372 const skills = matchingEntry
373 ? matchingEntry.skills
374 : response.data.flatMap((entry) => entry.skills);
375
376 return skills.map((skill) => {
377 const shortDescription =
378 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
379
380 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
381 name: skill.name,
382 path: skill.path,
383 enabled: skill.enabled,
384 };
385
386 if (skill.description) {
387 parsedSkill.description = skill.description;
388 }
389 if (skill.scope) {
390 parsedSkill.scope = skill.scope;
391 }
392 if (skill.interface?.displayName) {
393 parsedSkill.displayName = skill.interface.displayName;
394 }
395 if (shortDescription) {
396 parsedSkill.shortDescription = shortDescription;
397 }
398
399 return parsedSkill;
400 });
401}
402
403const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
404 client: CodexClient.CodexAppServerClient["Service"],
405) {
406 const models: ServerProviderModel[] = [];
407 let cursor: string | null | undefined = undefined;
408
409 do {
410 const response: CodexSchema.V2ModelListResponse = yield* client.request(
411 "model/list",
412 cursor ? { cursor } : {},
413 );
414 models.push(...parseCodexModelListResponse(response));
415 cursor = response.nextCursor;
416 } while (cursor);
417
418 return models;
419});
420
421const decodeCodexModelsCacheStamp = Schema.decodeUnknownOption(
422 Schema.fromJsonString(Schema.Struct({ fetched_at: Schema.String })),
423);
424
425const readCodexModelsCacheFetchedAt = Effect.fn("readCodexModelsCacheFetchedAt")(function* (
426 codexHome: string,
427) {
428 const fileSystem = yield* FileSystem.FileSystem;
429 const path = yield* Path.Path;
430 const text = yield* fileSystem
431 .readFileString(path.join(codexHome, "models_cache.json"))
432 .pipe(Effect.option);
433 return Option.flatMap(text, decodeCodexModelsCacheStamp).pipe(
434 Option.flatMap((stamp) => DateTime.make(stamp.fetched_at)),
435 Option.match({ onNone: () => Number.NaN, onSome: DateTime.toEpochMillis }),
436 );
437});
438
439const withCodexDiscoveryDeadline = Effect.fnUntraced(function* <A, E, R>(
440 effect: Effect.Effect<A, E, R>,
441 deadlineMs: number,
442 timeoutMs = Infinity,
443) {
444 const remainingMs = Math.min(timeoutMs, deadlineMs - DateTime.toEpochMillis(yield* DateTime.now));
445 if (remainingMs <= 0) return undefined;
446 return yield* effect.pipe(
447 Effect.timeoutOption(Duration.millis(remainingMs)),
448 Effect.map(Option.getOrUndefined),
449 );
450});
451
452/**
453 * Every Codex client on the machine shares that file, and the backend tailors
454 * the catalog to each client's originator: the plain CLI does not get Sol
455 * Ultrafast. App-server refreshes the catalog online at startup, so wait until
456 * a write newer than this process's spawn lands, then list again.
457 */
458const requestCodexChatGptModels = Effect.fn("requestCodexChatGptModels")(function* (input: {
459 readonly client: CodexClient.CodexAppServerClient["Service"];
460 readonly codexHome: string;
461 readonly spawnedAtMs: number;
462 readonly deadlineMs: number;
463}) {
464 const models = yield* withCodexDiscoveryDeadline(
465 requestAllCodexModels(input.client),
466 input.deadlineMs,
467 );
468 if (models === undefined) return undefined;
469 const refreshed = yield* withCodexDiscoveryDeadline(
470 readCodexModelsCacheFetchedAt(input.codexHome).pipe(
471 Effect.repeat({
472 schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL),
473 until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs,
474 }),
475 ),
476 input.deadlineMs,
477 CODEX_CATALOG_REFRESH_TIMEOUT_MS,
478 );
479 if (refreshed === undefined) {
480 yield* Effect.logWarning(
481 "Codex did not refresh its model catalog in time; using the cached catalog.",
482 );
483 return models;
484 }
485 return (
486 (yield* withCodexDiscoveryDeadline(requestAllCodexModels(input.client), input.deadlineMs)) ??
487 models
488 );
489});
490
491/** Set originator at spawn; the pre-initialize refresh otherwise overwrites shared cache with plain-CLI models. */
492export const codexAppServerEnvironment = (
493 environment: NodeJS.ProcessEnv | undefined,
494): NodeJS.ProcessEnv => ({
495 CODEX_INTERNAL_ORIGINATOR_OVERRIDE: CODEX_CLIENT_NAME,
496 ...environment,
497});
498
499export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
500 return {
501 clientInfo: {
502 name: CODEX_CLIENT_NAME,
503 title: CODEX_CLIENT_NAME,
504 version: packageJson.version,
505 },
506 capabilities: {
507 experimentalApi: true,
508 },
509 };
510}
511
512const codexProcessEnvironment = Effect.fn("codexProcessEnvironment")(function* (input: {
513 readonly homePath?: string | undefined;
514 readonly environment?: NodeJS.ProcessEnv | undefined;
515}) {
516 // Expand CODEX_HOME explicitly: spawn passes a literal ~ that Codex rejects.
517 const resolvedHomePath = input.homePath
518 ? expandHomePath(input.homePath, yield* HostProcess.HomeDirectory)
519 : undefined;
520 return {
521 ...codexAppServerEnvironment(input.environment),
522 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
523 };
524});
525
526export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(function* (input: {
527 readonly binaryPath: string;
528 readonly homePath?: string | undefined;
529 readonly launchArgs?: string | undefined;
530 readonly cwd: string;
531 readonly environment?: NodeJS.ProcessEnv | undefined;
532}) {
533 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
534 const environment = yield* codexProcessEnvironment(input);
535 const spawnCommand = yield* resolveSpawnCommand(
536 input.binaryPath,
537 codexAppServerArgs(input.launchArgs),
538 { env: environment, extendEnv: true },
539 );
540 const child = yield* spawner
541 .spawn(
542 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
543 cwd: input.cwd,
544 env: environment,
545 extendEnv: true,
546 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
547 shell: spawnCommand.shell,
548 }),
549 )
550 .pipe(
551 Effect.mapError(
552 (cause) =>
553 new CodexErrors.CodexAppServerSpawnError({
554 command: `${input.binaryPath} app-server`,
555 cause,
556 }),
557 ),
558 );
559 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
560 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
561 Effect.provide(clientContext),
562 );
563 const initialize = yield* client.request("initialize", buildCodexInitializeParams());
564 yield* client.notify("initialized", undefined);
565 return { client, initialize };
566});
567
568// Usage is an enrichment: a failure or a slow answer degrades to "no usage this
569// probe" rather than costing the account and models.
570const readCodexRateLimits = (
571 client: CodexClient.CodexAppServerClient["Service"],
572 deadlineMs: number,
573) =>
574 withCodexDiscoveryDeadline(
575 client.request("account/rateLimits/read", null),
576 deadlineMs,
577 RATE_LIMITS_PROBE_TIMEOUT_MS,
578 ).pipe(
579 Effect.map((response): CodexRateLimitsProbe =>
580 response
581 ? {
582 snapshot: response.rateLimits,
583 rateLimitsByLimitId: response.rateLimitsByLimitId,
584 resetCredits: response.rateLimitResetCredits,
585 accountId: response.accountId,
586 }
587 : { failure: "Codex did not answer the usage request." },
588 ),
589 Effect.catch((error) =>
590 Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
591 Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
592 ),
593 ),
594 );
595
596const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
597 readonly binaryPath: string;
598 readonly homePath?: string;
599 readonly launchArgs?: string;
600 readonly cwd: string;
601 readonly environment?: NodeJS.ProcessEnv;
602 readonly skipNativeUsage?: boolean;
603}) {
604 const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
605 const { client, initialize } = yield* withCodexAppServerClient(input);
606
607 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
608 const version = versionMatch ? versionMatch[1] : undefined;
609
610 const accountResponse = yield* client.request("account/read", {});
611 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
612 return {
613 account: accountResponse,
614 version,
615 models: [],
616 skills: [],
617 } satisfies CodexAppServerProviderSnapshot;
618 }
619
620 // Optional discovery must finish before the outer timeout can discard the account result.
621 const deadlineMs = spawnedAtMs + CODEX_AUTH_PROBE_TIMEOUT_MS - CODEX_DISCOVERY_MARGIN_MS;
622 const [skillsResponse, models, { serviceTier, nativeUsage, rateLimits }] = yield* Effect.all(
623 [
624 withCodexDiscoveryDeadline(client.request("skills/list", { cwds: [input.cwd] }), deadlineMs),
625 accountResponse.account?.type === "chatgpt"
626 ? requestCodexChatGptModels({
627 client,
628 codexHome: initialize.codexHome,
629 spawnedAtMs,
630 deadlineMs,
631 })
632 : withCodexDiscoveryDeadline(requestAllCodexModels(client), deadlineMs),
633 // The shared catalog must exclude config from the server's launch project.
634 withCodexDiscoveryDeadline(
635 client.request("config/read", { includeLayers: false }),
636 deadlineMs,
637 CODEX_CONFIG_PROBE_TIMEOUT_MS,
638 ).pipe(
639 Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined))),
640 Effect.flatMap((config) => {
641 // Only a confirmed native route may probe or publish the login's quota.
642 const nativeUsage =
643 !input.skipNativeUsage &&
644 config !== undefined &&
645 codexRoutesSpendNativeQuota(accountResponse, config.config);
646 const readUsage: Effect.Effect<CodexRateLimitsProbe | undefined> = nativeUsage
647 ? readCodexRateLimits(client, deadlineMs)
648 : Effect.undefined;
649 return readUsage.pipe(
650 Effect.map((rateLimits) => ({
651 serviceTier: config?.config.service_tier ?? undefined,
652 nativeUsage,
653 rateLimits,
654 })),
655 );
656 }),
657 ),
658 ],
659 { concurrency: "unbounded" },
660 );
661
662 return {
663 account: accountResponse,
664 nativeUsage,
665 ...(rateLimits ? { rateLimits } : {}),
666 version,
667 models,
668 serviceTier,
669 skills: skillsResponse ? parseCodexSkillsListResponse(skillsResponse, input.cwd) : [],
670 } satisfies CodexAppServerProviderSnapshot;
671});
672
673// Old CLIs can exit before initialize reports the version needed for compatibility advice.
674const probeCodexCliVersion = Effect.fn("probeCodexCliVersion")(
675 function* (input: {
676 readonly binaryPath: string;
677 readonly homePath?: string | undefined;
678 readonly cwd: string;
679 readonly environment?: NodeJS.ProcessEnv | undefined;
680 }) {
681 const environment = yield* codexProcessEnvironment(input);
682 const spawnCommand = yield* resolveSpawnCommand(input.binaryPath, ["--version"], {
683 env: environment,
684 extendEnv: true,
685 });
686 const result = yield* spawnAndCollect(
687 input.binaryPath,
688 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
689 cwd: input.cwd,
690 env: environment,
691 extendEnv: true,
692 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
693 shell: spawnCommand.shell,
694 }),
695 );
696 if (result.code !== 0) return null;
697 return CODEX_CLI_VERSION_PATTERN.exec(result.stdout)?.[1] ?? null;
698 },
699 Effect.timeoutOption(Duration.millis(DEFAULT_TIMEOUT_MS)),
700 Effect.map(Option.getOrNull),
701 Effect.catch((cause) =>
702 Effect.logDebug("Codex --version fallback failed.", { cause }).pipe(Effect.as(null)),
703 ),
704);
705
706export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
707 readonly binaryPath: string;
708 readonly homePath?: string;
709 readonly launchArgs?: string;
710 readonly cwd: string;
711 readonly environment?: NodeJS.ProcessEnv;
712}) {
713 const { client } = yield* withCodexAppServerClient({
714 ...input,
715 environment: providerProbeEnvironment(input.environment ?? process.env),
716 });
717 const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
718 return parseCodexSkillsListResponse(skillsResponse, input.cwd);
719});
720
721const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
722 appendCustomCodexModels([], codexSettings.customModels);
723
724const makePendingCodexProvider = Effect.fn("CodexProvider.makePendingCodexProvider")(function* (
725 codexSettings: CodexSettings,
726): Effect.fn.Return<ServerProviderDraft> {
727 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
728 const models = emptyCodexModelsFromSettings(codexSettings);
729
730 if (!codexSettings.enabled) {
731 return buildServerProvider({
732 presentation: CODEX_PRESENTATION,
733 enabled: false,
734 checkedAt,
735 models,
736 skills: [],
737 probe: {
738 installed: false,
739 version: null,
740 status: "warning",
741 auth: { status: "unknown" },
742 message: "Codex is disabled in T3 Code settings.",
743 },
744 });
745 }
746
747 return buildServerProvider({
748 presentation: CODEX_PRESENTATION,
749 enabled: true,
750 checkedAt,
751 models,
752 skills: [],
753 probe: {
754 installed: false,
755 version: null,
756 status: "warning",
757 auth: { status: "unknown" },
758 message: "Codex provider status has not been checked in this session yet.",
759 },
760 });
761});
762
763function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): {
764 readonly status: Exclude<ServerProviderState, "disabled">;
765 readonly auth: ServerProvider["auth"];
766 readonly message?: string;
767} {
768 const authLabel = codexAccountAuthLabel(
769 account.account,
770 rateLimits && "snapshot" in rateLimits ? rateLimits.snapshot.planType : undefined,
771 );
772 const authEmail = codexAccountEmail(account.account);
773 const workspaceId =
774 rateLimits && "accountId" in rateLimits ? rateLimits.accountId?.trim() : undefined;
775 const auth = {
776 status: account.account ? ("authenticated" as const) : ("unknown" as const),
777 ...(account.account?.type ? { type: account.account?.type } : {}),
778 ...(authLabel ? { label: authLabel } : {}),
779 ...(authEmail ? { email: authEmail } : {}),
780 ...(workspaceId ? { workspaceId } : {}),
781 } satisfies ServerProvider["auth"];
782
783 if (account.account) {
784 return { status: "ready", auth };
785 }
786
787 if (account.requiresOpenaiAuth) {
788 return {
789 status: "error",
790 auth: { status: "unauthenticated" },
791 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
792 };
793 }
794
795 return { status: "ready", auth };
796}
797
798export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
799 codexSettings: CodexSettings,
800 probe: (input: {
801 readonly binaryPath: string;
802 readonly homePath?: string;
803 readonly launchArgs?: string;
804 readonly cwd: string;
805 readonly environment?: NodeJS.ProcessEnv;
806 readonly skipNativeUsage?: boolean;
807 }) => Effect.Effect<
808 CodexAppServerProviderSnapshot,
809 CodexErrors.CodexAppServerError,
810 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope
811 > = probeCodexAppServerProvider,
812 environment?: NodeJS.ProcessEnv,
813 managedAuth?: ServerProvider["auth"],
814): Effect.fn.Return<
815 ServerProviderDraft,
816 ServerSettingsError,
817 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
818> {
819 const resolvedEnvironment = providerProbeEnvironment(environment ?? process.env);
820 const checkedAt = DateTime.formatIso(yield* DateTime.now);
821 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
822
823 if (!codexSettings.enabled) {
824 return buildServerProvider({
825 presentation: CODEX_PRESENTATION,
826 enabled: false,
827 checkedAt,
828 models: emptyModels,
829 skills: [],
830 probe: {
831 installed: false,
832 version: null,
833 status: "warning",
834 auth: { status: "unknown" },
835 message: "Codex is disabled in T3 Code settings.",
836 },
837 });
838 }
839
840 const probeResult = yield* probe({
841 binaryPath: codexSettings.binaryPath,
842 homePath: codexSettings.homePath,
843 launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
844 cwd: process.cwd(),
845 environment: resolvedEnvironment,
846 ...(managedAuth ? { skipNativeUsage: true } : {}),
847 }).pipe(
848 // Process teardown can outlast the work budget without discarding a completed snapshot.
849 Effect.timeoutOption(Duration.millis(CODEX_AUTH_PROBE_TIMEOUT_MS)),
850 Effect.scoped,
851 Effect.result,
852 );
853
854 if (Result.isFailure(probeResult)) {
855 const error = probeResult.failure;
856 const installed = !isCodexAppServerSpawnError(error);
857 const version = installed
858 ? yield* probeCodexCliVersion({
859 binaryPath: codexSettings.binaryPath,
860 homePath: codexSettings.homePath,
861 cwd: process.cwd(),
862 environment: resolvedEnvironment,
863 })
864 : null;
865 return buildServerProvider({
866 presentation: CODEX_PRESENTATION,
867 enabled: codexSettings.enabled,
868 checkedAt,
869 models: emptyModels,
870 skills: [],
871 probe: {
872 installed,
873 version,
874 status: "error",
875 auth: { status: "unknown" },
876 message: installed
877 ? `Codex app-server provider probe failed: ${error.message}.`
878 : `Could not start Codex CLI (\`${codexSettings.binaryPath}\`). Check Settings → Providers → Codex → Binary path on the server.` +
879 (codexSettings.binaryPath === "codex"
880 ? " Installing ChatGPT or Codex desktop may not add codex to PATH."
881 : " Make sure the configured executable exists and can be run."),
882 },
883 });
884 }
885
886 if (Option.isNone(probeResult.success)) {
887 return buildServerProvider({
888 presentation: CODEX_PRESENTATION,
889 enabled: codexSettings.enabled,
890 checkedAt,
891 models: emptyModels,
892 skills: [],
893 probe: {
894 installed: true,
895 version: null,
896 status: "error",
897 auth: { status: "unknown" },
898 message: "Timed out while checking Codex app-server provider status.",
899 },
900 });
901 }
902
903 const snapshot = probeResult.success.value;
904 const accountStatus = managedAuth
905 ? { status: "ready" as const, auth: managedAuth, message: undefined }
906 : accountProbeStatus(snapshot);
907 // Sign-in guidance still applies when Codex itself says it needs an OpenAI login.
908 const usageLimits =
909 !snapshot.nativeUsage && !accountStatus.message
910 ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" })
911 : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits
912 ? makeUnavailableUsageLimits({
913 checkedAt,
914 reason: "probeFailed",
915 ...(accountStatus.message ? { message: accountStatus.message } : {}),
916 ...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}),
917 })
918 : codexRateLimitsToLimits({
919 snapshot: snapshot.rateLimits.snapshot,
920 rateLimitsByLimitId: snapshot.rateLimits.rateLimitsByLimitId,
921 resetCredits: snapshot.rateLimits.resetCredits,
922 checkedAt,
923 });
924
925 return buildServerProvider({
926 presentation: CODEX_PRESENTATION,
927 enabled: codexSettings.enabled,
928 checkedAt,
929 models: pipe(
930 appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels),
931 applyPreferredCodexDefaultModel,
932 (models) => applyConfiguredCodexServiceTier(models, snapshot.serviceTier),
933 ),
934 skills: snapshot.skills,
935 slashCommands: [
936 COMPACT_SLASH_COMMAND,
937 {
938 name: "goal",
939 description: "Set a goal Codex keeps working toward until it is done",
940 input: { hint: "Objective, or pause, resume, clear" },
941 },
942 {
943 name: "feedback",
944 description: "Send this thread and Codex logs to OpenAI",
945 input: { hint: "Describe the issue (optional)" },
946 },
947 ],
948 probe: {
949 installed: true,
950 version: snapshot.version ?? null,
951 status: snapshot.models === undefined ? "warning" : accountStatus.status,
952 auth: accountStatus.auth,
953 ...(accountStatus.message
954 ? { message: accountStatus.message }
955 : snapshot.models === undefined
956 ? { message: "Codex did not return its model catalog in time." }
957 : {}),
958 ...(managedAuth ? {} : { usageLimits }),
959 },
960 });
961});
962
963export { makePendingCodexProvider };