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