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