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