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