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

CodexProvider.ts

758 lines25.0 KB

1import * as DateTime from "effect/DateTime";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Result from "effect/Result";
9import * as Schema from "effect/Schema";
10import * as Schedule from "effect/Schedule";
11import * as Scope from "effect/Scope";
12import * as Types from "effect/Types";
13import * as ChildProcess from "effect/process/ChildProcess";
14import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15import * as CodexClient from "effect-codex-app-server/client";
16import * as CodexSchema from "effect-codex-app-server/schema";
17import * as CodexErrors from "effect-codex-app-server/errors";
18​
19import type {
20 CodexSettings,
21 CustomModelSetting,
22 ServerProvider,
23 ServerProviderState,
24 ModelCapabilities,
25 ProviderOptionDescriptor,
26 ServerProviderModel,
27 ServerProviderSkill,
28} from "@t3tools/contracts";
29import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
30​
31import {
32 codexModelFamily,
33 createModelCapabilities,
34 formatCodexModelName,
35} from "@t3tools/shared/model";
36import { resolveSpawnCommand } from "@t3tools/shared/shell";
37import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
38import {
39 AUTH_PROBE_TIMEOUT_MS,
40 buildServerProvider,
41 COMPACT_SLASH_COMMAND,
42 providerModelsFromSettings,
43 type ServerProviderDraft,
44} from "@t3tools/provider-core/server/snapshotProbe";
45import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
46import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
47import {
48 codexRateLimitsFailureMessage,
49 codexRateLimitsToLimits,
50 type CodexRateLimitSnapshot,
51 type CodexResetCreditsSummary,
52} from "./codexUsageLimits.ts";
53import * as HostProcess from "@t3tools/shared/HostProcess";
54import packageJson from "../../package.json" with { type: "json" };
55const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
56const RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000;
57​
58type CodexRateLimitsProbe =
59 | {
60 readonly snapshot: CodexRateLimitSnapshot;
61 readonly rateLimitsByLimitId?:
62 | Readonly<Record<string, CodexRateLimitSnapshot>>
63 | null
64 | undefined;
65 readonly resetCredits: CodexResetCreditsSummary | null | undefined;
66 readonly accountId?: string | null | undefined;
67 }
68 | { readonly failure: string };
69​
70const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
71const CODEX_CATALOG_REFRESH_TIMEOUT = "3 seconds" as const;
72const CODEX_CATALOG_REFRESH_POLL = "100 millis" as const;
73const CODEX_CLIENT_NAME = "T3 Code";
74​
75const CODEX_PRESENTATION = {
76 displayName: "Codex",
77 showInteractionModeToggle: true,
78 reportsContextWindow: true,
79} as const;
80​
81export interface CodexAppServerProviderSnapshot {
82 readonly account: CodexSchema.V2GetAccountResponse;
83 readonly rateLimits?: CodexRateLimitsProbe;
84 readonly version: string | undefined;
85 readonly models: ReadonlyArray<ServerProviderModel>;
86 readonly skills: ReadonlyArray<ServerProviderSkill>;
88​
89const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
90 none: "None",
91 minimal: "Minimal",
92 low: "Low",
93 medium: "Medium",
94 high: "High",
95 xhigh: "Extra High",
96 max: "Max",
97 ultra: "Ultra",
98};
99​
100const DEFAULT_SERVICE_TIER_ID = "default";
101​
102const SERVICE_TIER_DESCRIPTIONS: Readonly<Record<string, string>> = {
103 ultrafast: "Even faster, more expensive",
104};
105​
106function reasoningEffortLabel(reasoningEffort: string): string {
107 return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
109​
110function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
111 if (!account) return undefined;
112 if (account.type === "apiKey") return "OpenAI API Key";
113 if (account.type === "amazonBedrock") return "Amazon Bedrock";
114 if (account.type !== "chatgpt") return undefined;
115 return codexPlanLabel(account.planType);
117​
118export function codexPlanLabel(planType: string | null | undefined): string | undefined {
119 switch (planType) {
120 case "free":
121 return "ChatGPT Free Subscription";
122 case "go":
123 return "ChatGPT Go Subscription";
124 case "plus":
125 return "ChatGPT Plus Subscription";
126 case "pro":
127 return "ChatGPT Pro 20x Subscription";
128 case "prolite":
129 return "ChatGPT Pro 5x Subscription";
130 case "promax":
131 return "ChatGPT Pro Max Subscription";
132 case "team":
133 return "ChatGPT Team Subscription";
134 case "self_serve_business_prolite":
135 case "self_serve_business_usage_based":
136 case "business":
137 return "ChatGPT Business Subscription";
138 case "ent26":
139 case "enterprise_cbp_automation":
140 case "enterprise_cbp_usage_based":
141 case "enterprise":
142 return "ChatGPT Enterprise Subscription";
143 case "edu":
144 case "edu_plus":
145 case "edu_pro":
146 return "ChatGPT Edu Subscription";
147 case "unknown":
148 return "ChatGPT Subscription";
149 default:
150 return undefined;
151 }
153​
154function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) {
155 if (!account || account.type !== "chatgpt") return undefined;
156 return account.email;
158​
159export function mapCodexModelCapabilities(
160 model: CodexSchema.V2ModelListResponse__Model,
161): ModelCapabilities {
162 const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
163 reasoningEffort ===
164 (codexModelFamily(model.model) === "gpt-6-astra" ? "medium" : model.defaultReasoningEffort)
165 ? {
166 id: reasoningEffort,
167 label: reasoningEffortLabel(reasoningEffort),
168 isDefault: true,
169 }
170 : {
171 id: reasoningEffort,
172 label: reasoningEffortLabel(reasoningEffort),
173 },
174 );
175 const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
176 const serviceTiers =
177 model.serviceTiers && model.serviceTiers.length > 0
178 ? model.serviceTiers
179 : (model.additionalSpeedTiers ?? []).map((id) => ({
180 id,
181 name: id === "fast" ? "Fast" : id,
182 description: "",
183 }));
184 const catalogDefaultServiceTier = serviceTiers.some(
185 (tier) => tier.id === model.defaultServiceTier,
186 )
187 ? model.defaultServiceTier
188 : null;
189 const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
190 const optionDescriptors: ProviderOptionDescriptor[] = [];
191​
192 if (reasoningOptions.length > 0) {
193 optionDescriptors.push({
194 id: "reasoningEffort",
195 label: "Reasoning",
196 type: "select",
197 options: reasoningOptions,
198 ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
199 });
200 }
201 if (serviceTiers.length > 0) {
202 optionDescriptors.push({
203 id: "serviceTier",
204 label: "Service Tier",
205 type: "select",
206 options: [
207 {
208 id: DEFAULT_SERVICE_TIER_ID,
209 label: "Standard",
210 ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
211 },
212 ...serviceTiers.map((tier) => {
213 const description = SERVICE_TIER_DESCRIPTIONS[tier.id] ?? tier.description;
214 return {
215 id: tier.id,
216 label: tier.name,
217 ...(description ? { description } : {}),
218 ...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
219 };
220 }),
221 ],
222 currentValue: defaultServiceTier,
223 });
224 }
225​
226 return createModelCapabilities({
227 optionDescriptors,
228 });
230​
231function parseCodexModelListResponse(
232 response: CodexSchema.V2ModelListResponse,
233): ReadonlyArray<ServerProviderModel> {
234 return response.data.map((model) => ({
235 slug: model.model,
236 name: formatCodexModelName(model.displayName),
237 isCustom: false,
238 ...(model.isDefault ? { isDefault: true } : {}),
239 capabilities: mapCodexModelCapabilities(model),
240 }));
242​
243export function applyPreferredCodexDefaultModel(
244 models: ReadonlyArray<ServerProviderModel>,
245): ReadonlyArray<ServerProviderModel> {
246 const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.flatMap((slug) =>
247 models.filter((model) => !model.isCustom && codexModelFamily(model.slug) === slug),
248 )[0]?.slug;
249 if (!preferredSlug) {
250 return models;
251 }
252 return models.map((model) => {
253 if (model.slug === preferredSlug) {
254 return model.isDefault ? model : { ...model, isDefault: true };
255 }
256 if (!model.isDefault) {
257 return model;
258 }
259 const { isDefault: _isDefault, ...rest } = model;
260 return rest;
261 });
263​
264/**
265 * Codex has no static default capability set, so a bare custom slug borrows
266 * the first built-in's descriptors; an entry with its own capabilities keeps
267 * them.
268 */
269function appendCustomCodexModels(
270 models: ReadonlyArray<ServerProviderModel>,
271 customModels: ReadonlyArray<CustomModelSetting>,
272): ReadonlyArray<ServerProviderModel> {
273 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
274 return providerModelsFromSettings(models, customModels, fallbackCapabilities);
276​
277function parseCodexSkillsListResponse(
278 response: CodexSchema.V2SkillsListResponse,
279 cwd: string,
280): ReadonlyArray<ServerProviderSkill> {
281 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
282 const skills = matchingEntry
283 ? matchingEntry.skills
284 : response.data.flatMap((entry) => entry.skills);
285​
286 return skills.map((skill) => {
287 const shortDescription =
288 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
289​
290 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
291 name: skill.name,
292 path: skill.path,
293 enabled: skill.enabled,
294 };
295​
296 if (skill.description) {
297 parsedSkill.description = skill.description;
298 }
299 if (skill.scope) {
300 parsedSkill.scope = skill.scope;
301 }
302 if (skill.interface?.displayName) {
303 parsedSkill.displayName = skill.interface.displayName;
304 }
305 if (shortDescription) {
306 parsedSkill.shortDescription = shortDescription;
307 }
308​
309 return parsedSkill;
310 });
312​
313const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
314 client: CodexClient.CodexAppServerClient["Service"],
315) {
316 const models: ServerProviderModel[] = [];
317 let cursor: string | null | undefined = undefined;
318​
319 do {
320 const response: CodexSchema.V2ModelListResponse = yield* client.request(
321 "model/list",
322 cursor ? { cursor } : {},
323 );
324 models.push(...parseCodexModelListResponse(response));
325 cursor = response.nextCursor;
326 } while (cursor);
327​
328 return models;
329});
330​
331const decodeCodexModelsCacheStamp = Schema.decodeUnknownOption(
332 Schema.fromJsonString(Schema.Struct({ fetched_at: Schema.String })),
333);
334​
335const readCodexModelsCacheFetchedAt = Effect.fn("readCodexModelsCacheFetchedAt")(function* (
336 codexHome: string,
337) {
338 const fileSystem = yield* FileSystem.FileSystem;
339 const path = yield* Path.Path;
340 const text = yield* fileSystem
341 .readFileString(path.join(codexHome, "models_cache.json"))
342 .pipe(Effect.option);
343 return Option.flatMap(text, decodeCodexModelsCacheStamp).pipe(
344 Option.flatMap((stamp) => DateTime.make(stamp.fetched_at)),
345 Option.match({ onNone: () => Number.NaN, onSome: DateTime.toEpochMillis }),
346 );
347});
348​
349/**
350 * Every Codex client on the machine shares that file, and the backend tailors
351 * the catalog to each client's originator: the plain CLI does not get Sol
352 * Ultrafast. App-server refreshes the catalog online at startup, so wait until
353 * a write newer than this process's spawn lands, then list again.
354 */
355const requestCodexChatGptModels = Effect.fn("requestCodexChatGptModels")(function* (input: {
356 readonly client: CodexClient.CodexAppServerClient["Service"];
357 readonly codexHome: string;
358 readonly spawnedAtMs: number;
359}) {
360 const models = yield* requestAllCodexModels(input.client);
361 const refreshed = yield* readCodexModelsCacheFetchedAt(input.codexHome).pipe(
362 Effect.repeat({
363 schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL),
364 until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs,
365 }),
366 Effect.timeoutOption(CODEX_CATALOG_REFRESH_TIMEOUT),
367 );
368 if (Option.isNone(refreshed)) {
369 yield* Effect.logWarning(
370 "Codex did not refresh its model catalog in time; using the cached catalog.",
371 );
372 return models;
373 }
374 return yield* requestAllCodexModels(input.client);
375});
376​
377/**
378 * App-server starts its catalog refresh before `initialize` names the client,
379 * so that first fetch goes out as the plain CLI, misses tiers like Sol
380 * Ultrafast, and overwrites the shared `models_cache.json`. Naming the
381 * originator at spawn closes that race.
382 */
383export const codexAppServerEnvironment = (
384 environment: NodeJS.ProcessEnv | undefined,
385): NodeJS.ProcessEnv => ({
386 CODEX_INTERNAL_ORIGINATOR_OVERRIDE: CODEX_CLIENT_NAME,
387 ...environment,
388});
389​
390export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
391 return {
392 clientInfo: {
393 name: CODEX_CLIENT_NAME,
394 title: CODEX_CLIENT_NAME,
395 version: packageJson.version,
396 },
397 capabilities: {
398 experimentalApi: true,
399 },
400 };
402​
403export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(function* (input: {
404 readonly binaryPath: string;
405 readonly homePath?: string | undefined;
406 readonly launchArgs?: string | undefined;
407 readonly cwd: string;
408 readonly environment?: NodeJS.ProcessEnv | undefined;
409}) {
410 // `~` is not shell-expanded when env vars are set via `child_process.spawn`,
411 // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
412 // "CODEX_HOME points to '~/.codex_work', but that path does not exist".
413 const resolvedHomePath = input.homePath
414 ? expandHomePath(input.homePath, yield* HostProcess.HomeDirectory)
415 : undefined;
416 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
417 const environment = {
418 ...codexAppServerEnvironment(input.environment),
419 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
420 };
421 const spawnCommand = yield* resolveSpawnCommand(
422 input.binaryPath,
423 codexAppServerArgs(input.launchArgs),
424 { env: environment, extendEnv: true },
425 );
426 const child = yield* spawner
427 .spawn(
428 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
429 cwd: input.cwd,
430 env: environment,
431 extendEnv: true,
432 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
433 shell: spawnCommand.shell,
434 }),
435 )
436 .pipe(
437 Effect.mapError(
438 (cause) =>
439 new CodexErrors.CodexAppServerSpawnError({
440 command: `${input.binaryPath} app-server`,
441 cause,
442 }),
443 ),
444 );
445 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
446 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
447 Effect.provide(clientContext),
448 );
449 const initialize = yield* client.request("initialize", buildCodexInitializeParams());
450 yield* client.notify("initialized", undefined);
451 return { client, initialize };
452});
453​
454const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
455 readonly binaryPath: string;
456 readonly homePath?: string;
457 readonly launchArgs?: string;
458 readonly cwd: string;
459 readonly customModels?: ReadonlyArray<CustomModelSetting>;
460 readonly environment?: NodeJS.ProcessEnv;
461 readonly skipNativeUsage?: boolean;
462}) {
463 const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
464 const { client, initialize } = yield* withCodexAppServerClient(input);
465​
466 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
467 const version = versionMatch ? versionMatch[1] : undefined;
468​
469 const accountResponse = yield* client.request("account/read", {});
470 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
471 return {
472 account: accountResponse,
473 version,
474 models: appendCustomCodexModels([], input.customModels ?? []),
475 skills: [],
476 } satisfies CodexAppServerProviderSnapshot;
477 }
478​
479 const [skillsResponse, models, rateLimits] = yield* Effect.all(
480 [
481 client.request("skills/list", {
482 cwds: [input.cwd],
483 }),
484 accountResponse.account?.type === "chatgpt"
485 ? requestCodexChatGptModels({ client, codexHome: initialize.codexHome, spawnedAtMs })
486 : requestAllCodexModels(client),
487 input.skipNativeUsage
488 ? Effect.succeed(undefined)
489 : client.request("account/rateLimits/read", null).pipe(
490 Effect.map((response): CodexRateLimitsProbe => ({
491 snapshot: response.rateLimits,
492 rateLimitsByLimitId: response.rateLimitsByLimitId,
493 resetCredits: response.rateLimitResetCredits,
494 accountId: response.accountId,
495 })),
496 Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)),
497 Effect.map(
498 Option.getOrElse((): CodexRateLimitsProbe => ({
499 failure: "Codex did not answer the usage request.",
500 })),
501 ),
502 Effect.catch((error) =>
503 Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
504 Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
505 ),
506 ),
507 ),
508 ],
509 { concurrency: "unbounded" },
510 );
511​
512 return {
513 account: accountResponse,
514 ...(rateLimits ? { rateLimits } : {}),
515 version,
516 models: applyPreferredCodexDefaultModel(
517 appendCustomCodexModels(models, input.customModels ?? []),
518 ),
519 skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
520 } satisfies CodexAppServerProviderSnapshot;
521});
522​
523export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
524 readonly binaryPath: string;
525 readonly homePath?: string;
526 readonly launchArgs?: string;
527 readonly cwd: string;
528 readonly environment?: NodeJS.ProcessEnv;
529}) {
530 const { client } = yield* withCodexAppServerClient(input);
531 const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
532 return parseCodexSkillsListResponse(skillsResponse, input.cwd);
533});
534​
535const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
536 appendCustomCodexModels([], codexSettings.customModels);
537​
538const makePendingCodexProvider = (
539 codexSettings: CodexSettings,
540): Effect.Effect<ServerProviderDraft> =>
541 Effect.gen(function* () {
542 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
543 const models = emptyCodexModelsFromSettings(codexSettings);
544​
545 if (!codexSettings.enabled) {
546 return buildServerProvider({
547 presentation: CODEX_PRESENTATION,
548 enabled: false,
549 checkedAt,
550 models,
551 skills: [],
552 probe: {
553 installed: false,
554 version: null,
555 status: "warning",
556 auth: { status: "unknown" },
557 message: "Codex is disabled in T3 Code settings.",
558 },
559 });
560 }
561​
562 return buildServerProvider({
563 presentation: CODEX_PRESENTATION,
564 enabled: true,
565 checkedAt,
566 models,
567 skills: [],
568 probe: {
569 installed: false,
570 version: null,
571 status: "warning",
572 auth: { status: "unknown" },
573 message: "Codex provider status has not been checked in this session yet.",
574 },
575 });
576 });
577​
578function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): {
579 readonly status: Exclude<ServerProviderState, "disabled">;
580 readonly auth: ServerProvider["auth"];
581 readonly message?: string;
582} {
583 const authLabel = codexAccountAuthLabel(account.account);
584 const authEmail = codexAccountEmail(account.account);
585 const workspaceId =
586 rateLimits && "accountId" in rateLimits ? rateLimits.accountId?.trim() : undefined;
587 const auth = {
588 status: account.account ? ("authenticated" as const) : ("unknown" as const),
589 ...(account.account?.type ? { type: account.account?.type } : {}),
590 ...(authLabel ? { label: authLabel } : {}),
591 ...(authEmail ? { email: authEmail } : {}),
592 ...(workspaceId ? { workspaceId } : {}),
593 } satisfies ServerProvider["auth"];
594​
595 if (account.account) {
596 return { status: "ready", auth };
597 }
598​
599 if (account.requiresOpenaiAuth) {
600 return {
601 status: "error",
602 auth: { status: "unauthenticated" },
603 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
604 };
605 }
606​
607 return { status: "ready", auth };
609​
610export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
611 codexSettings: CodexSettings,
612 probe: (input: {
613 readonly binaryPath: string;
614 readonly homePath?: string;
615 readonly launchArgs?: string;
616 readonly cwd: string;
617 readonly customModels: ReadonlyArray<CustomModelSetting>;
618 readonly environment?: NodeJS.ProcessEnv;
619 readonly skipNativeUsage?: boolean;
620 }) => Effect.Effect<
621 CodexAppServerProviderSnapshot,
622 CodexErrors.CodexAppServerError,
623 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope
624 > = probeCodexAppServerProvider,
625 environment?: NodeJS.ProcessEnv,
626 managedAuth?: ServerProvider["auth"],
627): Effect.fn.Return<
628 ServerProviderDraft,
629 ServerSettingsError,
630 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
631> {
632 const resolvedEnvironment = environment ?? process.env;
633 const checkedAt = DateTime.formatIso(yield* DateTime.now);
634 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
635​
636 if (!codexSettings.enabled) {
637 return buildServerProvider({
638 presentation: CODEX_PRESENTATION,
639 enabled: false,
640 checkedAt,
641 models: emptyModels,
642 skills: [],
643 probe: {
644 installed: false,
645 version: null,
646 status: "warning",
647 auth: { status: "unknown" },
648 message: "Codex is disabled in T3 Code settings.",
649 },
650 });
651 }
652​
653 const probeResult = yield* probe({
654 binaryPath: codexSettings.binaryPath,
655 homePath: codexSettings.homePath,
656 launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
657 cwd: process.cwd(),
658 customModels: codexSettings.customModels,
659 environment: resolvedEnvironment,
660 ...(managedAuth ? { skipNativeUsage: true } : {}),
661 }).pipe(
662 Effect.scoped,
663 Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),
664 Effect.result,
665 );
666​
667 if (Result.isFailure(probeResult)) {
668 const error = probeResult.failure;
669 const installed = !isCodexAppServerSpawnError(error);
670 return buildServerProvider({
671 presentation: CODEX_PRESENTATION,
672 enabled: codexSettings.enabled,
673 checkedAt,
674 models: emptyModels,
675 skills: [],
676 probe: {
677 installed,
678 version: null,
679 status: "error",
680 auth: { status: "unknown" },
681 message: installed
682 ? `Codex app-server provider probe failed: ${error.message}.`
683 : `Could not start Codex CLI (\`${codexSettings.binaryPath}\`). Check Settings → Providers → Codex → Binary path on the server.` +
684 (codexSettings.binaryPath === "codex"
685 ? " Installing ChatGPT or Codex desktop may not add codex to PATH."
686 : " Make sure the configured executable exists and can be run."),
687 },
688 });
689 }
690​
691 if (Option.isNone(probeResult.success)) {
692 return buildServerProvider({
693 presentation: CODEX_PRESENTATION,
694 enabled: codexSettings.enabled,
695 checkedAt,
696 models: emptyModels,
697 skills: [],
698 probe: {
699 installed: true,
700 version: null,
701 status: "error",
702 auth: { status: "unknown" },
703 message: "Timed out while checking Codex app-server provider status.",
704 },
705 });
706 }
707​
708 const snapshot = probeResult.success.value;
709 const accountStatus = managedAuth
710 ? { status: "ready" as const, auth: managedAuth, message: undefined }
711 : accountProbeStatus(snapshot);
712 const usageLimits =
713 snapshot.account.account?.type === "apiKey"
714 ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" })
715 : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits
716 ? makeUnavailableUsageLimits({
717 checkedAt,
718 reason: "probeFailed",
719 ...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}),
720 })
721 : codexRateLimitsToLimits({
722 snapshot: snapshot.rateLimits.snapshot,
723 rateLimitsByLimitId: snapshot.rateLimits.rateLimitsByLimitId,
724 resetCredits: snapshot.rateLimits.resetCredits,
725 checkedAt,
726 });
727​
728 return buildServerProvider({
729 presentation: CODEX_PRESENTATION,
730 enabled: codexSettings.enabled,
731 checkedAt,
732 models: snapshot.models,
733 skills: snapshot.skills,
734 slashCommands: [
735 COMPACT_SLASH_COMMAND,
736 {
737 name: "goal",
738 description: "Set a goal Codex keeps working toward until it is done",
739 input: { hint: "Objective, or pause, resume, clear" },
740 },
741 {
742 name: "feedback",
743 description: "Send this thread and Codex logs to OpenAI",
744 input: { hint: "Describe the issue (optional)" },
745 },
746 ],
747 probe: {
748 installed: true,
749 version: snapshot.version ?? null,
750 status: accountStatus.status,
751 auth: accountStatus.auth,
752 ...(accountStatus.message ? { message: accountStatus.message } : {}),
753 ...(managedAuth ? {} : { usageLimits }),
754 },
755 });
756});
757​
758export { makePendingCodexProvider };