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