Open History to see the last commit
1import { DateTime, Duration, Effect, Layer, Option, Result, Schema, Types } from "effect";
2import { ChildProcessSpawner } from "effect/unstable/process";
3import * as CodexClient from "effect-codex-app-server/client";
4import * as CodexSchema from "effect-codex-app-server/schema";
5import * as CodexErrors from "effect-codex-app-server/errors";
6
7import type {
8 CodexSettings,
9 ServerProvider,
10 ServerProviderState,
11 ModelCapabilities,
12 ServerProviderModel,
13 ServerProviderSkill,
14} from "@t3tools/contracts";
15import { ServerSettingsError } from "@t3tools/contracts";
16
17import { createModelCapabilities } from "@t3tools/shared/model";
18
19import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
20import { expandHomePath } from "../../pathExpansion.ts";
21import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
22import packageJson from "../../../package.json" with { type: "json" };
23
24const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
25const CODEX_PRESENTATION = {
26 displayName: "Codex",
27 showInteractionModeToggle: true,
28} as const;
29
30export interface CodexAppServerProviderSnapshot {
31 readonly account: CodexSchema.V2GetAccountResponse;
32 readonly version: string | undefined;
33 readonly models: ReadonlyArray<ServerProviderModel>;
34 readonly skills: ReadonlyArray<ServerProviderSkill>;
35}
36
37const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
38 none: "None",
39 minimal: "Minimal",
40 low: "Low",
41 medium: "Medium",
42 high: "High",
43 xhigh: "Extra High",
44};
45
46function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
47 if (!account) return undefined;
48 if (account.type === "apiKey") return "OpenAI API Key";
49
50 switch (account.planType) {
51 case "free":
52 return "ChatGPT Free Subscription";
53 case "go":
54 return "ChatGPT Go Subscription";
55 case "plus":
56 return "ChatGPT Plus Subscription";
57 case "pro":
58 return "ChatGPT Pro 20x Subscription";
59 case "prolite":
60 return "ChatGPT Pro 5x Subscription";
61 case "team":
62 return "ChatGPT Team Subscription";
63 case "self_serve_business_usage_based":
64 case "business":
65 return "ChatGPT Business Subscription";
66 case "enterprise_cbp_usage_based":
67 case "enterprise":
68 return "ChatGPT Enterprise Subscription";
69 case "edu":
70 return "ChatGPT Edu Subscription";
71 case "unknown":
72 return "ChatGPT Subscription";
73 default:
74 account.planType satisfies never;
75 return undefined;
76 }
77}
78
79function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) {
80 if (!account || account.type !== "chatgpt") return undefined;
81 return account.email;
82}
83
84function mapCodexModelCapabilities(
85 model: CodexSchema.V2ModelListResponse__Model,
86): ModelCapabilities {
87 const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
88 reasoningEffort === model.defaultReasoningEffort
89 ? {
90 id: reasoningEffort,
91 label: REASONING_EFFORT_LABELS[reasoningEffort],
92 isDefault: true,
93 }
94 : {
95 id: reasoningEffort,
96 label: REASONING_EFFORT_LABELS[reasoningEffort],
97 },
98 );
99 const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
100 const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast");
101 return createModelCapabilities({
102 optionDescriptors: [
103 ...(reasoningOptions.length > 0
104 ? [
105 {
106 id: "reasoningEffort",
107 label: "Reasoning",
108 type: "select" as const,
109 options: reasoningOptions,
110 ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
111 },
112 ]
113 : []),
114 ...(supportsFastMode
115 ? [
116 {
117 id: "fastMode",
118 label: "Fast Mode",
119 type: "boolean" as const,
120 },
121 ]
122 : []),
123 ],
124 });
125}
126
127const toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => {
128 // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash
129 return model.displayName
130 .replace(/^gpt/i, "GPT") // Handle start with 'gpt' or 'GPT'
131 .replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase());
132};
133
134function parseCodexModelListResponse(
135 response: CodexSchema.V2ModelListResponse,
136): ReadonlyArray<ServerProviderModel> {
137 return response.data.map((model) => ({
138 slug: model.model,
139 name: toDisplayName(model),
140 isCustom: false,
141 capabilities: mapCodexModelCapabilities(model),
142 }));
143}
144
145function appendCustomCodexModels(
146 models: ReadonlyArray<ServerProviderModel>,
147 customModels: ReadonlyArray<string>,
148): ReadonlyArray<ServerProviderModel> {
149 if (customModels.length === 0) {
150 return models;
151 }
152
153 const seen = new Set(models.map((model) => model.slug));
154 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
155 const customEntries: ServerProviderModel[] = [];
156 for (const rawModel of customModels) {
157 const slug = rawModel.trim();
158 if (!slug || seen.has(slug)) {
159 continue;
160 }
161 seen.add(slug);
162 customEntries.push({
163 slug,
164 name: slug,
165 isCustom: true,
166 capabilities: fallbackCapabilities,
167 });
168 }
169 return customEntries.length === 0 ? models : [...models, ...customEntries];
170}
171
172function parseCodexSkillsListResponse(
173 response: CodexSchema.V2SkillsListResponse,
174 cwd: string,
175): ReadonlyArray<ServerProviderSkill> {
176 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
177 const skills = matchingEntry
178 ? matchingEntry.skills
179 : response.data.flatMap((entry) => entry.skills);
180
181 return skills.map((skill) => {
182 const shortDescription =
183 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
184
185 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
186 name: skill.name,
187 path: skill.path,
188 enabled: skill.enabled,
189 };
190
191 if (skill.description) {
192 parsedSkill.description = skill.description;
193 }
194 if (skill.scope) {
195 parsedSkill.scope = skill.scope;
196 }
197 if (skill.interface?.displayName) {
198 parsedSkill.displayName = skill.interface.displayName;
199 }
200 if (shortDescription) {
201 parsedSkill.shortDescription = shortDescription;
202 }
203
204 return parsedSkill;
205 });
206}
207
208const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
209 client: CodexClient.CodexAppServerClientShape,
210) {
211 const models: ServerProviderModel[] = [];
212 let cursor: string | null | undefined = undefined;
213
214 do {
215 const response: CodexSchema.V2ModelListResponse = yield* client.request(
216 "model/list",
217 cursor ? { cursor } : {},
218 );
219 models.push(...parseCodexModelListResponse(response));
220 cursor = response.nextCursor;
221 } while (cursor);
222
223 return models;
224});
225
226export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
227 return {
228 clientInfo: {
229 name: "t3code_desktop",
230 title: "T3 Code Desktop",
231 version: packageJson.version,
232 },
233 capabilities: {
234 experimentalApi: true,
235 },
236 };
237}
238
239// Wrapped with `scopedSafeTeardown("codex-probe")` rather than the usual
240// `Effect.scoped` so that a defect from the `Layer.build` finalizer (e.g.
241// `ChildProcess.kill` throwing because the `codex app-server` child exited
242// early) cannot override a successful probe body. Without this guard the
243// defect bubbles past `Effect.result` in `checkCodexProviderStatus`, dies
244// `refreshOneSource`, and `providersRef` never receives the snapshot.
245const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
246 readonly binaryPath: string;
247 readonly homePath?: string;
248 readonly cwd: string;
249 readonly customModels?: ReadonlyArray<string>;
250 readonly environment?: NodeJS.ProcessEnv;
251}) {
252 // `~` is not shell-expanded when env vars are set via `child_process.spawn`,
253 // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
254 // "CODEX_HOME points to '~/.codex_work', but that path does not exist".
255 // Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.
256 const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
257 const clientContext = yield* Layer.build(
258 CodexClient.layerCommand({
259 command: input.binaryPath,
260 args: ["app-server"],
261 cwd: input.cwd,
262 env: {
263 ...(input.environment ?? process.env),
264 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
265 },
266 }),
267 );
268 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
269 Effect.provide(clientContext),
270 );
271
272 const initialize = yield* client.request("initialize", {
273 clientInfo: {
274 name: "t3code_desktop",
275 title: "T3 Code Desktop",
276 version: "0.1.0",
277 },
278 capabilities: {
279 experimentalApi: true,
280 },
281 });
282 yield* client.notify("initialized", undefined);
283
284 // Extract the version string after the first '/' in userAgent, up to the next space or the end
285 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
286 const version = versionMatch ? versionMatch[1] : undefined;
287
288 const accountResponse = yield* client.request("account/read", {});
289 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
290 return {
291 account: accountResponse,
292 version,
293 models: appendCustomCodexModels([], input.customModels ?? []),
294 skills: [],
295 } satisfies CodexAppServerProviderSnapshot;
296 }
297
298 const [skillsResponse, models] = yield* Effect.all(
299 [
300 client.request("skills/list", {
301 cwds: [input.cwd],
302 }),
303 requestAllCodexModels(client),
304 ],
305 { concurrency: "unbounded" },
306 );
307
308 return {
309 account: accountResponse,
310 version,
311 models: appendCustomCodexModels(models, input.customModels ?? []),
312 skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
313 } satisfies CodexAppServerProviderSnapshot;
314}, scopedSafeTeardown("codex-probe"));
315
316const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
317 codexSettings.customModels
318 .map((model) => model.trim())
319 .filter((model, index, models) => model.length > 0 && models.indexOf(model) === index)
320 .map((model) => ({
321 slug: model,
322 name: model,
323 isCustom: true,
324 capabilities: null,
325 }));
326
327const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProviderDraft => {
328 const checkedAt = new Date().toISOString();
329 const models = emptyCodexModelsFromSettings(codexSettings);
330
331 if (!codexSettings.enabled) {
332 return buildServerProvider({
333 presentation: CODEX_PRESENTATION,
334 enabled: false,
335 checkedAt,
336 models,
337 skills: [],
338 probe: {
339 installed: false,
340 version: null,
341 status: "warning",
342 auth: { status: "unknown" },
343 message: "Codex is disabled in T3 Code settings.",
344 },
345 });
346 }
347
348 return buildServerProvider({
349 presentation: CODEX_PRESENTATION,
350 enabled: true,
351 checkedAt,
352 models,
353 skills: [],
354 probe: {
355 installed: false,
356 version: null,
357 status: "warning",
358 auth: { status: "unknown" },
359 message: "Codex provider status has not been checked in this session yet.",
360 },
361 });
362};
363
364function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): {
365 readonly status: Exclude<ServerProviderState, "disabled">;
366 readonly auth: ServerProvider["auth"];
367 readonly message?: string;
368} {
369 const authLabel = codexAccountAuthLabel(account.account);
370 const authEmail = codexAccountEmail(account.account);
371 const auth = {
372 status: account.account ? ("authenticated" as const) : ("unknown" as const),
373 ...(account.account?.type ? { type: account.account?.type } : {}),
374 ...(authLabel ? { label: authLabel } : {}),
375 ...(authEmail ? { email: authEmail } : {}),
376 } satisfies ServerProvider["auth"];
377
378 if (account.account) {
379 return { status: "ready", auth };
380 }
381
382 if (account.requiresOpenaiAuth) {
383 return {
384 status: "error",
385 auth: { status: "unauthenticated" },
386 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
387 };
388 }
389
390 return { status: "ready", auth };
391}
392
393export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
394 codexSettings: CodexSettings,
395 probe: (input: {
396 readonly binaryPath: string;
397 readonly homePath?: string;
398 readonly cwd: string;
399 readonly customModels: ReadonlyArray<string>;
400 readonly environment?: NodeJS.ProcessEnv;
401 }) => Effect.Effect<
402 CodexAppServerProviderSnapshot,
403 CodexErrors.CodexAppServerError,
404 ChildProcessSpawner.ChildProcessSpawner
405 > = probeCodexAppServerProvider,
406 environment: NodeJS.ProcessEnv = process.env,
407): Effect.fn.Return<
408 ServerProviderDraft,
409 ServerSettingsError,
410 ChildProcessSpawner.ChildProcessSpawner
411> {
412 const checkedAt = DateTime.formatIso(yield* DateTime.now);
413 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
414
415 if (!codexSettings.enabled) {
416 return buildServerProvider({
417 presentation: CODEX_PRESENTATION,
418 enabled: false,
419 checkedAt,
420 models: emptyModels,
421 skills: [],
422 probe: {
423 installed: false,
424 version: null,
425 status: "warning",
426 auth: { status: "unknown" },
427 message: "Codex is disabled in T3 Code settings.",
428 },
429 });
430 }
431
432 const probeResult = yield* probe({
433 binaryPath: codexSettings.binaryPath,
434 homePath: codexSettings.homePath,
435 cwd: process.cwd(),
436 customModels: codexSettings.customModels,
437 environment,
438 }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
439
440 if (Result.isFailure(probeResult)) {
441 const error = probeResult.failure;
442 const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);
443 return buildServerProvider({
444 presentation: CODEX_PRESENTATION,
445 enabled: codexSettings.enabled,
446 checkedAt,
447 models: emptyModels,
448 skills: [],
449 probe: {
450 installed,
451 version: null,
452 status: "error",
453 auth: { status: "unknown" },
454 message: installed
455 ? `Codex app-server provider probe failed: ${error.message}.`
456 : "Codex CLI (`codex`) is not installed or not on PATH.",
457 },
458 });
459 }
460
461 if (Option.isNone(probeResult.success)) {
462 return buildServerProvider({
463 presentation: CODEX_PRESENTATION,
464 enabled: codexSettings.enabled,
465 checkedAt,
466 models: emptyModels,
467 skills: [],
468 probe: {
469 installed: true,
470 version: null,
471 status: "error",
472 auth: { status: "unknown" },
473 message: "Timed out while checking Codex app-server provider status.",
474 },
475 });
476 }
477
478 const snapshot = probeResult.success.value;
479 const accountStatus = accountProbeStatus(snapshot.account);
480
481 return buildServerProvider({
482 presentation: CODEX_PRESENTATION,
483 enabled: codexSettings.enabled,
484 checkedAt,
485 models: snapshot.models,
486 skills: snapshot.skills,
487 probe: {
488 installed: true,
489 version: snapshot.version ?? null,
490 status: accountStatus.status,
491 auth: accountStatus.auth,
492 ...(accountStatus.message ? { message: accountStatus.message } : {}),
493 },
494 });
495});
496
497// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of
498// the per-instance-driver refactor. `CodexDriver.create()` builds a managed
499// snapshot per instance (each with its own `CodexSettings`) and hands the
500// resulting `ServerProviderShape` back as `ProviderInstance.snapshot`.
501//
502// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are
503// re-exported for use by `CodexDriver`.
504export { makePendingCodexProvider };