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