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

CodexProvider.ts

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