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