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

CodexProvider.ts

839 lines28.2 KB

1import { pipe } from "effect/Function";
2import * as DateTime from "effect/DateTime";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Result from "effect/Result";
10import * as Schema from "effect/Schema";
11import * as Schedule from "effect/Schedule";
12import * as Scope from "effect/Scope";
13import * as Types from "effect/Types";
14import * as ChildProcess from "effect/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import * as CodexClient from "effect-codex-app-server/client";
17import * as CodexSchema from "effect-codex-app-server/schema";
18import * as CodexErrors from "effect-codex-app-server/errors";
19​
20import type {
21 CodexSettings,
22 CustomModelSetting,
23 ServerProvider,
24 ServerProviderState,
25 ModelCapabilities,
26 ProviderOptionDescriptor,
27 ServerProviderModel,
28 ServerProviderSkill,
29} from "@t3tools/contracts";
30import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
31​
32import {
33 codexModelFamily,
34 createModelCapabilities,
35 formatCodexModelName,
36} from "@t3tools/shared/model";
37import { resolveSpawnCommand } from "@t3tools/shared/shell";
38import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
39import {
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_MS = 3_000;
72const CODEX_CONFIG_PROBE_TIMEOUT_MS = 3_000;
73const CODEX_CATALOG_REFRESH_POLL = "100 millis" as const;
74const CODEX_CLIENT_NAME = "T3 Code";
75// Handshake plus account/models/skills requests can exceed the shared 10s probe budget.
76const CODEX_AUTH_PROBE_TIMEOUT_MS = 20_000;
77const CODEX_DISCOVERY_MARGIN_MS = 250;
78​
79const CODEX_PRESENTATION = {
80 displayName: "Codex",
81 showInteractionModeToggle: true,
82 reportsContextWindow: true,
83} as const;
84​
85export interface CodexAppServerProviderSnapshot {
86 readonly account: CodexSchema.V2GetAccountResponse;
87 readonly rateLimits?: CodexRateLimitsProbe;
88 readonly version: string | undefined;
89 readonly models: ReadonlyArray<ServerProviderModel> | undefined;
90 readonly serviceTier?: string | undefined;
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 200 Subscription";
133 case "prolite":
134 return "ChatGPT Pro 100 Subscription";
135 case "promax":
136 return "ChatGPT Pro 500 Subscription";
137 case "self_serve_business_prolite":
138 return "ChatGPT Business Premium Subscription";
139 case "team":
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​
389const withCodexDiscoveryDeadline = Effect.fnUntraced(function* <A, E, R>(
390 effect: Effect.Effect<A, E, R>,
391 deadlineMs: number,
392 timeoutMs = Infinity,
393) {
394 const remainingMs = Math.min(timeoutMs, deadlineMs - DateTime.toEpochMillis(yield* DateTime.now));
395 if (remainingMs <= 0) return undefined;
396 return yield* effect.pipe(
397 Effect.timeoutOption(Duration.millis(remainingMs)),
398 Effect.map(Option.getOrUndefined),
399 );
400});
401​
402/**
403 * Every Codex client on the machine shares that file, and the backend tailors
404 * the catalog to each client's originator: the plain CLI does not get Sol
405 * Ultrafast. App-server refreshes the catalog online at startup, so wait until
406 * a write newer than this process's spawn lands, then list again.
407 */
408const requestCodexChatGptModels = Effect.fn("requestCodexChatGptModels")(function* (input: {
409 readonly client: CodexClient.CodexAppServerClient["Service"];
410 readonly codexHome: string;
411 readonly spawnedAtMs: number;
412 readonly deadlineMs: number;
413}) {
414 const models = yield* withCodexDiscoveryDeadline(
415 requestAllCodexModels(input.client),
416 input.deadlineMs,
417 );
418 if (models === undefined) return undefined;
419 const refreshed = yield* withCodexDiscoveryDeadline(
420 readCodexModelsCacheFetchedAt(input.codexHome).pipe(
421 Effect.repeat({
422 schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL),
423 until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs,
424 }),
425 ),
426 input.deadlineMs,
427 CODEX_CATALOG_REFRESH_TIMEOUT_MS,
428 );
429 if (refreshed === undefined) {
430 yield* Effect.logWarning(
431 "Codex did not refresh its model catalog in time; using the cached catalog.",
432 );
433 return models;
434 }
435 return (
436 (yield* withCodexDiscoveryDeadline(requestAllCodexModels(input.client), input.deadlineMs)) ??
437 models
438 );
439});
440​
441/** Set originator at spawn; the pre-initialize refresh otherwise overwrites shared cache with plain-CLI models. */
442export const codexAppServerEnvironment = (
443 environment: NodeJS.ProcessEnv | undefined,
444): NodeJS.ProcessEnv => ({
445 CODEX_INTERNAL_ORIGINATOR_OVERRIDE: CODEX_CLIENT_NAME,
446 ...environment,
447});
448​
449export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
450 return {
451 clientInfo: {
452 name: CODEX_CLIENT_NAME,
453 title: CODEX_CLIENT_NAME,
454 version: packageJson.version,
455 },
456 capabilities: {
457 experimentalApi: true,
458 },
459 };
461​
462export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(function* (input: {
463 readonly binaryPath: string;
464 readonly homePath?: string | undefined;
465 readonly launchArgs?: string | undefined;
466 readonly cwd: string;
467 readonly environment?: NodeJS.ProcessEnv | undefined;
468}) {
469 // Expand CODEX_HOME explicitly: spawn passes a literal ~ that Codex rejects.
470 const resolvedHomePath = input.homePath
471 ? expandHomePath(input.homePath, yield* HostProcess.HomeDirectory)
472 : undefined;
473 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
474 const environment = {
475 ...codexAppServerEnvironment(input.environment),
476 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
477 };
478 const spawnCommand = yield* resolveSpawnCommand(
479 input.binaryPath,
480 codexAppServerArgs(input.launchArgs),
481 { env: environment, extendEnv: true },
482 );
483 const child = yield* spawner
484 .spawn(
485 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
486 cwd: input.cwd,
487 env: environment,
488 extendEnv: true,
489 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
490 shell: spawnCommand.shell,
491 }),
492 )
493 .pipe(
494 Effect.mapError(
495 (cause) =>
496 new CodexErrors.CodexAppServerSpawnError({
497 command: `${input.binaryPath} app-server`,
498 cause,
499 }),
500 ),
501 );
502 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
503 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
504 Effect.provide(clientContext),
505 );
506 const initialize = yield* client.request("initialize", buildCodexInitializeParams());
507 yield* client.notify("initialized", undefined);
508 return { client, initialize };
509});
510​
511const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
512 readonly binaryPath: string;
513 readonly homePath?: string;
514 readonly launchArgs?: string;
515 readonly cwd: string;
516 readonly environment?: NodeJS.ProcessEnv;
517 readonly skipNativeUsage?: boolean;
518}) {
519 const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
520 const { client, initialize } = yield* withCodexAppServerClient(input);
521​
522 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
523 const version = versionMatch ? versionMatch[1] : undefined;
524​
525 const accountResponse = yield* client.request("account/read", {});
526 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
527 return {
528 account: accountResponse,
529 version,
530 models: [],
531 skills: [],
532 } satisfies CodexAppServerProviderSnapshot;
533 }
534​
535 // Optional discovery must finish before the outer timeout can discard the account result.
536 const deadlineMs = spawnedAtMs + CODEX_AUTH_PROBE_TIMEOUT_MS - CODEX_DISCOVERY_MARGIN_MS;
537 const [skillsResponse, models, serviceTier, rateLimits] = yield* Effect.all(
538 [
539 withCodexDiscoveryDeadline(client.request("skills/list", { cwds: [input.cwd] }), deadlineMs),
540 accountResponse.account?.type === "chatgpt"
541 ? requestCodexChatGptModels({
542 client,
543 codexHome: initialize.codexHome,
544 spawnedAtMs,
545 deadlineMs,
546 })
547 : withCodexDiscoveryDeadline(requestAllCodexModels(client), deadlineMs),
548 // The shared catalog must exclude config from the server's launch project.
549 withCodexDiscoveryDeadline(
550 client.request("config/read", { includeLayers: false }),
551 deadlineMs,
552 CODEX_CONFIG_PROBE_TIMEOUT_MS,
553 ).pipe(
554 Effect.map((response) => response?.config.service_tier ?? undefined),
555 Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined))),
556 ),
557 // Usage is an enrichment: a failure or a slow answer degrades to "no
558 // usage this probe" rather than costing the account and models.
559 input.skipNativeUsage
560 ? // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
561 Effect.succeed(undefined)
562 : withCodexDiscoveryDeadline(
563 client.request("account/rateLimits/read", null),
564 deadlineMs,
565 RATE_LIMITS_PROBE_TIMEOUT_MS,
566 ).pipe(
567 Effect.map((response): CodexRateLimitsProbe =>
568 response
569 ? {
570 snapshot: response.rateLimits,
571 rateLimitsByLimitId: response.rateLimitsByLimitId,
572 resetCredits: response.rateLimitResetCredits,
573 accountId: response.accountId,
574 }
575 : { failure: "Codex did not answer the usage request." },
576 ),
577 Effect.catch((error) =>
578 Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
579 Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
580 ),
581 ),
582 ),
583 ],
584 { concurrency: "unbounded" },
585 );
586​
587 return {
588 account: accountResponse,
589 ...(rateLimits ? { rateLimits } : {}),
590 version,
591 models,
592 serviceTier,
593 skills: skillsResponse ? parseCodexSkillsListResponse(skillsResponse, input.cwd) : [],
594 } satisfies CodexAppServerProviderSnapshot;
595});
596​
597export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
598 readonly binaryPath: string;
599 readonly homePath?: string;
600 readonly launchArgs?: string;
601 readonly cwd: string;
602 readonly environment?: NodeJS.ProcessEnv;
603}) {
604 const { client } = yield* withCodexAppServerClient(input);
605 const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
606 return parseCodexSkillsListResponse(skillsResponse, input.cwd);
607});
608​
609const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
610 appendCustomCodexModels([], codexSettings.customModels);
611​
612const makePendingCodexProvider = Effect.fn("CodexProvider.makePendingCodexProvider")(function* (
613 codexSettings: CodexSettings,
614): Effect.fn.Return<ServerProviderDraft> {
615 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
616 const models = emptyCodexModelsFromSettings(codexSettings);
617​
618 if (!codexSettings.enabled) {
619 return buildServerProvider({
620 presentation: CODEX_PRESENTATION,
621 enabled: false,
622 checkedAt,
623 models,
624 skills: [],
625 probe: {
626 installed: false,
627 version: null,
628 status: "warning",
629 auth: { status: "unknown" },
630 message: "Codex is disabled in T3 Code settings.",
631 },
632 });
633 }
634​
635 return buildServerProvider({
636 presentation: CODEX_PRESENTATION,
637 enabled: true,
638 checkedAt,
639 models,
640 skills: [],
641 probe: {
642 installed: false,
643 version: null,
644 status: "warning",
645 auth: { status: "unknown" },
646 message: "Codex provider status has not been checked in this session yet.",
647 },
648 });
649});
650​
651function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): {
652 readonly status: Exclude<ServerProviderState, "disabled">;
653 readonly auth: ServerProvider["auth"];
654 readonly message?: string;
655} {
656 const authLabel = codexAccountAuthLabel(account.account);
657 const authEmail = codexAccountEmail(account.account);
658 const workspaceId =
659 rateLimits && "accountId" in rateLimits ? rateLimits.accountId?.trim() : undefined;
660 const auth = {
661 status: account.account ? ("authenticated" as const) : ("unknown" as const),
662 ...(account.account?.type ? { type: account.account?.type } : {}),
663 ...(authLabel ? { label: authLabel } : {}),
664 ...(authEmail ? { email: authEmail } : {}),
665 ...(workspaceId ? { workspaceId } : {}),
666 } satisfies ServerProvider["auth"];
667​
668 if (account.account) {
669 return { status: "ready", auth };
670 }
671​
672 if (account.requiresOpenaiAuth) {
673 return {
674 status: "error",
675 auth: { status: "unauthenticated" },
676 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
677 };
678 }
679​
680 return { status: "ready", auth };
682​
683export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
684 codexSettings: CodexSettings,
685 probe: (input: {
686 readonly binaryPath: string;
687 readonly homePath?: string;
688 readonly launchArgs?: string;
689 readonly cwd: string;
690 readonly environment?: NodeJS.ProcessEnv;
691 readonly skipNativeUsage?: boolean;
692 }) => Effect.Effect<
693 CodexAppServerProviderSnapshot,
694 CodexErrors.CodexAppServerError,
695 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope
696 > = probeCodexAppServerProvider,
697 environment?: NodeJS.ProcessEnv,
698 managedAuth?: ServerProvider["auth"],
699): Effect.fn.Return<
700 ServerProviderDraft,
701 ServerSettingsError,
702 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
703> {
704 const resolvedEnvironment = environment ?? process.env;
705 const checkedAt = DateTime.formatIso(yield* DateTime.now);
706 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
707​
708 if (!codexSettings.enabled) {
709 return buildServerProvider({
710 presentation: CODEX_PRESENTATION,
711 enabled: false,
712 checkedAt,
713 models: emptyModels,
714 skills: [],
715 probe: {
716 installed: false,
717 version: null,
718 status: "warning",
719 auth: { status: "unknown" },
720 message: "Codex is disabled in T3 Code settings.",
721 },
722 });
723 }
724​
725 const probeResult = yield* probe({
726 binaryPath: codexSettings.binaryPath,
727 homePath: codexSettings.homePath,
728 launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
729 cwd: process.cwd(),
730 environment: resolvedEnvironment,
731 ...(managedAuth ? { skipNativeUsage: true } : {}),
732 }).pipe(
733 // Process teardown can outlast the work budget without discarding a completed snapshot.
734 Effect.timeoutOption(Duration.millis(CODEX_AUTH_PROBE_TIMEOUT_MS)),
735 Effect.scoped,
736 Effect.result,
737 );
738​
739 if (Result.isFailure(probeResult)) {
740 const error = probeResult.failure;
741 const installed = !isCodexAppServerSpawnError(error);
742 return buildServerProvider({
743 presentation: CODEX_PRESENTATION,
744 enabled: codexSettings.enabled,
745 checkedAt,
746 models: emptyModels,
747 skills: [],
748 probe: {
749 installed,
750 version: null,
751 status: "error",
752 auth: { status: "unknown" },
753 message: installed
754 ? `Codex app-server provider probe failed: ${error.message}.`
755 : `Could not start Codex CLI (\`${codexSettings.binaryPath}\`). Check Settings → Providers → Codex → Binary path on the server.` +
756 (codexSettings.binaryPath === "codex"
757 ? " Installing ChatGPT or Codex desktop may not add codex to PATH."
758 : " Make sure the configured executable exists and can be run."),
759 },
760 });
761 }
762​
763 if (Option.isNone(probeResult.success)) {
764 return buildServerProvider({
765 presentation: CODEX_PRESENTATION,
766 enabled: codexSettings.enabled,
767 checkedAt,
768 models: emptyModels,
769 skills: [],
770 probe: {
771 installed: true,
772 version: null,
773 status: "error",
774 auth: { status: "unknown" },
775 message: "Timed out while checking Codex app-server provider status.",
776 },
777 });
778 }
779​
780 const snapshot = probeResult.success.value;
781 const accountStatus = managedAuth
782 ? { status: "ready" as const, auth: managedAuth, message: undefined }
783 : accountProbeStatus(snapshot);
784 const usageLimits =
785 snapshot.account.account?.type === "apiKey"
786 ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" })
787 : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits
788 ? makeUnavailableUsageLimits({
789 checkedAt,
790 reason: "probeFailed",
791 ...(accountStatus.message ? { message: accountStatus.message } : {}),
792 ...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}),
793 })
794 : codexRateLimitsToLimits({
795 snapshot: snapshot.rateLimits.snapshot,
796 rateLimitsByLimitId: snapshot.rateLimits.rateLimitsByLimitId,
797 resetCredits: snapshot.rateLimits.resetCredits,
798 checkedAt,
799 });
800​
801 return buildServerProvider({
802 presentation: CODEX_PRESENTATION,
803 enabled: codexSettings.enabled,
804 checkedAt,
805 models: pipe(
806 appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels),
807 applyPreferredCodexDefaultModel,
808 (models) => applyConfiguredCodexServiceTier(models, snapshot.serviceTier),
809 ),
810 skills: snapshot.skills,
811 slashCommands: [
812 COMPACT_SLASH_COMMAND,
813 {
814 name: "goal",
815 description: "Set a goal Codex keeps working toward until it is done",
816 input: { hint: "Objective, or pause, resume, clear" },
817 },
818 {
819 name: "feedback",
820 description: "Send this thread and Codex logs to OpenAI",
821 input: { hint: "Describe the issue (optional)" },
822 },
823 ],
824 probe: {
825 installed: true,
826 version: snapshot.version ?? null,
827 status: snapshot.models === undefined ? "warning" : accountStatus.status,
828 auth: accountStatus.auth,
829 ...(accountStatus.message
830 ? { message: accountStatus.message }
831 : snapshot.models === undefined
832 ? { message: "Codex did not return its model catalog in time." }
833 : {}),
834 ...(managedAuth ? {} : { usageLimits }),
835 },
836 });
837});
838​
839export { makePendingCodexProvider };