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

CodexProvider.ts

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