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