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

CodexProvider.ts

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