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

CodexProvider.ts

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