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