Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexProvider.ts

1,340 lines47.3 KB

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