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

CodexProvider.ts

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