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

CodexProvider.ts

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