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