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";
65
66function reasoningEffortLabel(reasoningEffort: string): string {
67 return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
68}
69
70function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
71 if (!account) return undefined;
72 if (account.type === "apiKey") return "OpenAI API Key";
73 if (account.type === "amazonBedrock") return "Amazon Bedrock";
74 if (account.type !== "chatgpt") return undefined;
75
76 switch (account.planType) {
77 case "free":
78 return "ChatGPT Free Subscription";
79 case "go":
80 return "ChatGPT Go Subscription";
81 case "plus":
82 return "ChatGPT Plus Subscription";
83 case "pro":
84 return "ChatGPT Pro 20x Subscription";
85 case "prolite":
86 return "ChatGPT Pro 5x Subscription";
87 case "team":
88 return "ChatGPT Team Subscription";
89 case "self_serve_business_prolite":
90 case "self_serve_business_usage_based":
91 case "business":
92 return "ChatGPT Business Subscription";
93 case "ent26":
94 case "enterprise_cbp_automation":
95 case "enterprise_cbp_usage_based":
96 case "enterprise":
97 return "ChatGPT Enterprise Subscription";
98 case "edu":
99 case "edu_plus":
100 case "edu_pro":
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 capabilities: mapCodexModelCapabilities(model),
199 }));
200}
201
202/**
203 * Prefer our own default-model ranking when one of the preferred slugs is in
204 * the live catalog; otherwise keep whatever Codex itself flagged as default.
205 */
206export function applyPreferredCodexDefaultModel(
207 models: ReadonlyArray<ServerProviderModel>,
208): ReadonlyArray<ServerProviderModel> {
209 const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
210 models.some((model) => model.slug === slug && !model.isCustom),
211 );
212 if (!preferredSlug) {
213 return models;
214 }
215 return models.map((model) => {
216 if (model.slug === preferredSlug) {
217 return model.isDefault ? model : { ...model, isDefault: true };
218 }
219 if (!model.isDefault) {
220 return model;
221 }
222 const { isDefault: _isDefault, ...rest } = model;
223 return rest;
224 });
225}
226
227function appendCustomCodexModels(
228 models: ReadonlyArray<ServerProviderModel>,
229 customModels: ReadonlyArray<string>,
230): ReadonlyArray<ServerProviderModel> {
231 if (customModels.length === 0) {
232 return models;
233 }
234
235 const seen = new Set(models.map((model) => model.slug));
236 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
237 const customEntries: ServerProviderModel[] = [];
238 for (const rawModel of customModels) {
239 const slug = rawModel.trim();
240 if (!slug || seen.has(slug)) {
241 continue;
242 }
243 seen.add(slug);
244 customEntries.push({
245 slug,
246 name: slug,
247 isCustom: true,
248 capabilities: fallbackCapabilities,
249 });
250 }
251 return customEntries.length === 0 ? models : [...models, ...customEntries];
252}
253
254function parseCodexSkillsListResponse(
255 response: CodexSchema.V2SkillsListResponse,
256 cwd: string,
257): ReadonlyArray<ServerProviderSkill> {
258 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
259 const skills = matchingEntry
260 ? matchingEntry.skills
261 : response.data.flatMap((entry) => entry.skills);
262
263 return skills.map((skill) => {
264 const shortDescription =
265 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
266
267 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
268 name: skill.name,
269 path: skill.path,
270 enabled: skill.enabled,
271 };
272
273 if (skill.description) {
274 parsedSkill.description = skill.description;
275 }
276 if (skill.scope) {
277 parsedSkill.scope = skill.scope;
278 }
279 if (skill.interface?.displayName) {
280 parsedSkill.displayName = skill.interface.displayName;
281 }
282 if (shortDescription) {
283 parsedSkill.shortDescription = shortDescription;
284 }
285
286 return parsedSkill;
287 });
288}
289
290const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
291 client: CodexClient.CodexAppServerClient["Service"],
292) {
293 const models: ServerProviderModel[] = [];
294 let cursor: string | null | undefined = undefined;
295
296 do {
297 const response: CodexSchema.V2ModelListResponse = yield* client.request(
298 "model/list",
299 cursor ? { cursor } : {},
300 );
301 models.push(...parseCodexModelListResponse(response));
302 cursor = response.nextCursor;
303 } while (cursor);
304
305 return models;
306});
307
308export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
309 return {
310 clientInfo: {
311 name: "t3code_desktop",
312 title: "T3 Code Desktop",
313 version: packageJson.version,
314 },
315 capabilities: {
316 experimentalApi: true,
317 },
318 };
319}
320
321const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
322 readonly binaryPath: string;
323 readonly homePath?: string;
324 readonly launchArgs?: string;
325 readonly cwd: string;
326 readonly customModels?: ReadonlyArray<string>;
327 readonly environment?: NodeJS.ProcessEnv;
328}) {
329 // `~` is not shell-expanded when env vars are set via `child_process.spawn`,
330 // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
331 // "CODEX_HOME points to '~/.codex_work', but that path does not exist".
332 // Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.
333 const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
334 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
335 const environment = {
336 ...input.environment,
337 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
338 };
339 const spawnCommand = yield* resolveSpawnCommand(
340 input.binaryPath,
341 codexAppServerArgs(input.launchArgs),
342 {
343 env: environment,
344 extendEnv: true,
345 },
346 );
347 const child = yield* spawner
348 .spawn(
349 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
350 cwd: input.cwd,
351 env: environment,
352 extendEnv: true,
353 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
354 shell: spawnCommand.shell,
355 }),
356 )
357 .pipe(
358 Effect.mapError(
359 (cause) =>
360 new CodexErrors.CodexAppServerSpawnError({
361 command: `${input.binaryPath} app-server`,
362 cause,
363 }),
364 ),
365 );
366 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
367 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
368 Effect.provide(clientContext),
369 );
370
371 const initialize = yield* client.request("initialize", {
372 clientInfo: {
373 name: "t3code_desktop",
374 title: "T3 Code Desktop",
375 version: "0.1.0",
376 },
377 capabilities: {
378 experimentalApi: true,
379 },
380 });
381 yield* client.notify("initialized", undefined);
382
383 // Extract the version string after the first '/' in userAgent, up to the next space or the end
384 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
385 const version = versionMatch ? versionMatch[1] : undefined;
386
387 const accountResponse = yield* client.request("account/read", {});
388 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
389 return {
390 account: accountResponse,
391 version,
392 models: appendCustomCodexModels([], input.customModels ?? []),
393 skills: [],
394 } satisfies CodexAppServerProviderSnapshot;
395 }
396
397 const [skillsResponse, models] = yield* Effect.all(
398 [
399 client.request("skills/list", {
400 cwds: [input.cwd],
401 }),
402 requestAllCodexModels(client),
403 ],
404 { concurrency: "unbounded" },
405 );
406
407 return {
408 account: accountResponse,
409 version,
410 models: applyPreferredCodexDefaultModel(
411 appendCustomCodexModels(models, input.customModels ?? []),
412 ),
413 skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
414 } satisfies CodexAppServerProviderSnapshot;
415});
416
417export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
418 readonly binaryPath: string;
419 readonly homePath?: string;
420 readonly launchArgs?: string;
421 readonly cwd: string;
422 readonly environment?: NodeJS.ProcessEnv;
423}) {
424 const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
425 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
426 const environment = {
427 ...input.environment,
428 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
429 };
430 const spawnCommand = yield* resolveSpawnCommand(
431 input.binaryPath,
432 codexAppServerArgs(input.launchArgs),
433 { env: environment, extendEnv: true },
434 );
435 const child = yield* spawner
436 .spawn(
437 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
438 cwd: input.cwd,
439 env: environment,
440 extendEnv: true,
441 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
442 shell: spawnCommand.shell,
443 }),
444 )
445 .pipe(
446 Effect.mapError(
447 (cause) =>
448 new CodexErrors.CodexAppServerSpawnError({
449 command: `${input.binaryPath} app-server`,
450 cause,
451 }),
452 ),
453 );
454 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
455 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
456 Effect.provide(clientContext),
457 );
458 yield* client.request("initialize", buildCodexInitializeParams());
459 yield* client.notify("initialized", undefined);
460 const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
461 return parseCodexSkillsListResponse(skillsResponse, input.cwd);
462});
463
464const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => {
465 const models = new Set<string>();
466 for (const model of codexSettings.customModels) {
467 const trimmed = model.trim();
468 if (trimmed.length > 0) {
469 models.add(trimmed);
470 }
471 }
472 return Array.from(models, (model) => ({
473 slug: model,
474 name: model,
475 isCustom: true,
476 capabilities: null,
477 }));
478};
479
480const makePendingCodexProvider = (
481 codexSettings: CodexSettings,
482): Effect.Effect<ServerProviderDraft> =>
483 Effect.gen(function* () {
484 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
485 const models = emptyCodexModelsFromSettings(codexSettings);
486
487 if (!codexSettings.enabled) {
488 return buildServerProvider({
489 presentation: CODEX_PRESENTATION,
490 enabled: false,
491 checkedAt,
492 models,
493 skills: [],
494 probe: {
495 installed: false,
496 version: null,
497 status: "warning",
498 auth: { status: "unknown" },
499 message: "Codex is disabled in T3 Code settings.",
500 },
501 });
502 }
503
504 return buildServerProvider({
505 presentation: CODEX_PRESENTATION,
506 enabled: true,
507 checkedAt,
508 models,
509 skills: [],
510 probe: {
511 installed: false,
512 version: null,
513 status: "warning",
514 auth: { status: "unknown" },
515 message: "Codex provider status has not been checked in this session yet.",
516 },
517 });
518 });
519
520function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): {
521 readonly status: Exclude<ServerProviderState, "disabled">;
522 readonly auth: ServerProvider["auth"];
523 readonly message?: string;
524} {
525 const authLabel = codexAccountAuthLabel(account.account);
526 const authEmail = codexAccountEmail(account.account);
527 const auth = {
528 status: account.account ? ("authenticated" as const) : ("unknown" as const),
529 ...(account.account?.type ? { type: account.account?.type } : {}),
530 ...(authLabel ? { label: authLabel } : {}),
531 ...(authEmail ? { email: authEmail } : {}),
532 } satisfies ServerProvider["auth"];
533
534 if (account.account) {
535 return { status: "ready", auth };
536 }
537
538 if (account.requiresOpenaiAuth) {
539 return {
540 status: "error",
541 auth: { status: "unauthenticated" },
542 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
543 };
544 }
545
546 return { status: "ready", auth };
547}
548
549export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
550 codexSettings: CodexSettings,
551 probe: (input: {
552 readonly binaryPath: string;
553 readonly homePath?: string;
554 readonly launchArgs?: string;
555 readonly cwd: string;
556 readonly customModels: ReadonlyArray<string>;
557 readonly environment?: NodeJS.ProcessEnv;
558 }) => Effect.Effect<
559 CodexAppServerProviderSnapshot,
560 CodexErrors.CodexAppServerError,
561 ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
562 > = probeCodexAppServerProvider,
563 environment?: NodeJS.ProcessEnv,
564): Effect.fn.Return<
565 ServerProviderDraft,
566 ServerSettingsError,
567 ChildProcessSpawner.ChildProcessSpawner
568> {
569 const resolvedEnvironment = environment ?? process.env;
570 const checkedAt = DateTime.formatIso(yield* DateTime.now);
571 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
572
573 if (!codexSettings.enabled) {
574 return buildServerProvider({
575 presentation: CODEX_PRESENTATION,
576 enabled: false,
577 checkedAt,
578 models: emptyModels,
579 skills: [],
580 probe: {
581 installed: false,
582 version: null,
583 status: "warning",
584 auth: { status: "unknown" },
585 message: "Codex is disabled in T3 Code settings.",
586 },
587 });
588 }
589
590 const probeResult = yield* probe({
591 binaryPath: codexSettings.binaryPath,
592 homePath: codexSettings.homePath,
593 launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
594 cwd: process.cwd(),
595 customModels: codexSettings.customModels,
596 environment: resolvedEnvironment,
597 }).pipe(
598 Effect.scoped,
599 Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),
600 Effect.result,
601 );
602
603 if (Result.isFailure(probeResult)) {
604 const error = probeResult.failure;
605 const installed = !isCodexAppServerSpawnError(error);
606 return buildServerProvider({
607 presentation: CODEX_PRESENTATION,
608 enabled: codexSettings.enabled,
609 checkedAt,
610 models: emptyModels,
611 skills: [],
612 probe: {
613 installed,
614 version: null,
615 status: "error",
616 auth: { status: "unknown" },
617 message: installed
618 ? `Codex app-server provider probe failed: ${error.message}.`
619 : "Codex CLI (`codex`) was not found on PATH.",
620 },
621 });
622 }
623
624 if (Option.isNone(probeResult.success)) {
625 return buildServerProvider({
626 presentation: CODEX_PRESENTATION,
627 enabled: codexSettings.enabled,
628 checkedAt,
629 models: emptyModels,
630 skills: [],
631 probe: {
632 installed: true,
633 version: null,
634 status: "error",
635 auth: { status: "unknown" },
636 message: "Timed out while checking Codex app-server provider status.",
637 },
638 });
639 }
640
641 const snapshot = probeResult.success.value;
642 const accountStatus = accountProbeStatus(snapshot.account);
643
644 return buildServerProvider({
645 presentation: CODEX_PRESENTATION,
646 enabled: codexSettings.enabled,
647 checkedAt,
648 models: snapshot.models,
649 skills: snapshot.skills,
650 slashCommands: [
651 {
652 name: "feedback",
653 description: "Send this thread and Codex logs to OpenAI",
654 input: { hint: "Describe the issue (optional)" },
655 },
656 ],
657 probe: {
658 installed: true,
659 version: snapshot.version ?? null,
660 status: accountStatus.status,
661 auth: accountStatus.auth,
662 ...(accountStatus.message ? { message: accountStatus.message } : {}),
663 },
664 });
665});
666
667// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of
668// the per-instance-driver refactor. `CodexDriver.create()` builds a managed
669// snapshot per instance (each with its own `CodexSettings`) and hands the
670// resulting `ServerProviderShape` back as `ProviderInstance.snapshot`.
671//
672// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are
673// re-exported for use by `CodexDriver`.
674export { makePendingCodexProvider };