Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexProvider.ts

519 lines15.2 KB

1import {
2 DateTime,
3 Duration,
4 Effect,
5 Equal,
6 Layer,
7 Option,
8 Result,
9 Schema,
10 Stream,
11 Types,
12} from "effect";
13import { ChildProcessSpawner } from "effect/unstable/process";
14import * as CodexClient from "effect-codex-app-server/client";
15import * as CodexSchema from "effect-codex-app-server/schema";
16import * as CodexErrors from "effect-codex-app-server/errors";
17​
18import type {
19 CodexSettings,
20 ServerProvider,
21 ServerProviderState,
22 ModelCapabilities,
23 ServerProviderModel,
24 ServerProviderSkill,
25} from "@t3tools/contracts";
26import { ServerSettingsError } from "@t3tools/contracts";
27​
28import { createModelCapabilities } from "@t3tools/shared/model";
29​
30import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
31import { buildServerProvider } from "../providerSnapshot.ts";
32import { CodexProvider } from "../Services/CodexProvider.ts";
33import { expandHomePath } from "../../pathExpansion.ts";
34import { ServerSettingsService } from "../../serverSettings.ts";
35import packageJson from "../../../package.json" with { type: "json" };
36​
37const PROVIDER = "codex" as const;
38const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
39const CODEX_PRESENTATION = {
40 displayName: "Codex",
41 showInteractionModeToggle: true,
42} as const;
43​
44export interface CodexAppServerProviderSnapshot {
45 readonly account: CodexSchema.V2GetAccountResponse;
46 readonly version: string | undefined;
47 readonly models: ReadonlyArray<ServerProviderModel>;
48 readonly skills: ReadonlyArray<ServerProviderSkill>;
50​
51const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
52 none: "None",
53 minimal: "Minimal",
54 low: "Low",
55 medium: "Medium",
56 high: "High",
57 xhigh: "Extra High",
58};
59​
60function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
61 if (!account) return undefined;
62 if (account.type === "apiKey") return "OpenAI API Key";
63​
64 switch (account.planType) {
65 case "free":
66 return "ChatGPT Free Subscription";
67 case "go":
68 return "ChatGPT Go Subscription";
69 case "plus":
70 return "ChatGPT Plus Subscription";
71 case "pro":
72 return "ChatGPT Pro 20x Subscription";
73 case "prolite":
74 return "ChatGPT Pro 5x Subscription";
75 case "team":
76 return "ChatGPT Team Subscription";
77 case "self_serve_business_usage_based":
78 case "business":
79 return "ChatGPT Business Subscription";
80 case "enterprise_cbp_usage_based":
81 case "enterprise":
82 return "ChatGPT Enterprise Subscription";
83 case "edu":
84 return "ChatGPT Edu Subscription";
85 case "unknown":
86 return "ChatGPT Subscription";
87 default:
88 account.planType satisfies never;
89 return undefined;
90 }
92​
93function mapCodexModelCapabilities(
94 model: CodexSchema.V2ModelListResponse__Model,
95): ModelCapabilities {
96 const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
97 reasoningEffort === model.defaultReasoningEffort
98 ? {
99 id: reasoningEffort,
100 label: REASONING_EFFORT_LABELS[reasoningEffort],
101 isDefault: true,
102 }
103 : {
104 id: reasoningEffort,
105 label: REASONING_EFFORT_LABELS[reasoningEffort],
106 },
107 );
108 const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
109 const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast");
110 return createModelCapabilities({
111 optionDescriptors: [
112 ...(reasoningOptions.length > 0
113 ? [
114 {
115 id: "reasoningEffort",
116 label: "Reasoning",
117 type: "select" as const,
118 options: reasoningOptions,
119 ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
120 },
121 ]
122 : []),
123 ...(supportsFastMode
124 ? [
125 {
126 id: "fastMode",
127 label: "Fast Mode",
128 type: "boolean" as const,
129 },
130 ]
131 : []),
132 ],
133 });
135​
136const toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => {
137 // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash
138 return model.displayName
139 .replace(/^gpt/i, "GPT") // Handle start with 'gpt' or 'GPT'
140 .replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase());
141};
142​
143function parseCodexModelListResponse(
144 response: CodexSchema.V2ModelListResponse,
145): ReadonlyArray<ServerProviderModel> {
146 return response.data.map((model) => ({
147 slug: model.model,
148 name: toDisplayName(model),
149 isCustom: false,
150 capabilities: mapCodexModelCapabilities(model),
151 }));
153​
154function appendCustomCodexModels(
155 models: ReadonlyArray<ServerProviderModel>,
156 customModels: ReadonlyArray<string>,
157): ReadonlyArray<ServerProviderModel> {
158 if (customModels.length === 0) {
159 return models;
160 }
161​
162 const seen = new Set(models.map((model) => model.slug));
163 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
164 const customEntries: ServerProviderModel[] = [];
165 for (const rawModel of customModels) {
166 const slug = rawModel.trim();
167 if (!slug || seen.has(slug)) {
168 continue;
169 }
170 seen.add(slug);
171 customEntries.push({
172 slug,
173 name: slug,
174 isCustom: true,
175 capabilities: fallbackCapabilities,
176 });
177 }
178 return customEntries.length === 0 ? models : [...models, ...customEntries];
180​
181function parseCodexSkillsListResponse(
182 response: CodexSchema.V2SkillsListResponse,
183 cwd: string,
184): ReadonlyArray<ServerProviderSkill> {
185 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
186 const skills = matchingEntry
187 ? matchingEntry.skills
188 : response.data.flatMap((entry) => entry.skills);
189​
190 return skills.map((skill) => {
191 const shortDescription =
192 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
193​
194 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
195 name: skill.name,
196 path: skill.path,
197 enabled: skill.enabled,
198 };
199​
200 if (skill.description) {
201 parsedSkill.description = skill.description;
202 }
203 if (skill.scope) {
204 parsedSkill.scope = skill.scope;
205 }
206 if (skill.interface?.displayName) {
207 parsedSkill.displayName = skill.interface.displayName;
208 }
209 if (shortDescription) {
210 parsedSkill.shortDescription = shortDescription;
211 }
212​
213 return parsedSkill;
214 });
216​
217const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
218 client: CodexClient.CodexAppServerClientShape,
219) {
220 const models: ServerProviderModel[] = [];
221 let cursor: string | null | undefined = undefined;
222​
223 do {
224 const response: CodexSchema.V2ModelListResponse = yield* client.request(
225 "model/list",
226 cursor ? { cursor } : {},
227 );
228 models.push(...parseCodexModelListResponse(response));
229 cursor = response.nextCursor;
230 } while (cursor);
231​
232 return models;
233});
234​
235export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
236 return {
237 clientInfo: {
238 name: "t3code_desktop",
239 title: "T3 Code Desktop",
240 version: packageJson.version,
241 },
242 capabilities: {
243 experimentalApi: true,
244 },
245 };
247​
248const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
249 readonly binaryPath: string;
250 readonly homePath?: string;
251 readonly cwd: string;
252 readonly customModels?: ReadonlyArray<string>;
253}) {
254 const clientContext = yield* Layer.build(
255 CodexClient.layerCommand({
256 command: input.binaryPath,
257 args: ["app-server"],
258 cwd: input.cwd,
259 ...(input.homePath ? { env: { CODEX_HOME: expandHomePath(input.homePath) } } : {}),
260 }),
261 );
262 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
263 Effect.provide(clientContext),
264 );
265​
266 const initialize = yield* client.request("initialize", {
267 clientInfo: {
268 name: "t3code_desktop",
269 title: "T3 Code Desktop",
270 version: "0.1.0",
271 },
272 capabilities: {
273 experimentalApi: true,
274 },
275 });
276 yield* client.notify("initialized", undefined);
277​
278 // Extract the version string after the first '/' in userAgent, up to the next space or the end
279 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
280 const version = versionMatch ? versionMatch[1] : undefined;
281​
282 const accountResponse = yield* client.request("account/read", {});
283 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
284 return {
285 account: accountResponse,
286 version,
287 models: appendCustomCodexModels([], input.customModels ?? []),
288 skills: [],
289 } satisfies CodexAppServerProviderSnapshot;
290 }
291​
292 const [skillsResponse, models] = yield* Effect.all(
293 [
294 client.request("skills/list", {
295 cwds: [input.cwd],
296 }),
297 requestAllCodexModels(client),
298 ],
299 { concurrency: "unbounded" },
300 );
301​
302 return {
303 account: accountResponse,
304 version,
305 models: appendCustomCodexModels(models, input.customModels ?? []),
306 skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
307 } satisfies CodexAppServerProviderSnapshot;
308}, Effect.scoped);
309​
310const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
311 codexSettings.customModels
312 .map((model) => model.trim())
313 .filter((model, index, models) => model.length > 0 && models.indexOf(model) === index)
314 .map((model) => ({
315 slug: model,
316 name: model,
317 isCustom: true,
318 capabilities: null,
319 }));
320​
321const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
322 const checkedAt = new Date().toISOString();
323 const models = emptyCodexModelsFromSettings(codexSettings);
324​
325 if (!codexSettings.enabled) {
326 return buildServerProvider({
327 provider: PROVIDER,
328 presentation: CODEX_PRESENTATION,
329 enabled: false,
330 checkedAt,
331 models,
332 skills: [],
333 probe: {
334 installed: false,
335 version: null,
336 status: "warning",
337 auth: { status: "unknown" },
338 message: "Codex is disabled in T3 Code settings.",
339 },
340 });
341 }
342​
343 return buildServerProvider({
344 provider: PROVIDER,
345 presentation: CODEX_PRESENTATION,
346 enabled: true,
347 checkedAt,
348 models,
349 skills: [],
350 probe: {
351 installed: false,
352 version: null,
353 status: "warning",
354 auth: { status: "unknown" },
355 message: "Codex provider status has not been checked in this session yet.",
356 },
357 });
358};
359​
360function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): {
361 readonly status: Exclude<ServerProviderState, "disabled">;
362 readonly auth: ServerProvider["auth"];
363 readonly message?: string;
364} {
365 const authLabel = codexAccountAuthLabel(account.account);
366 const auth = {
367 status: account.account ? ("authenticated" as const) : ("unknown" as const),
368 ...(account.account?.type ? { type: account.account?.type } : {}),
369 ...(authLabel ? { label: authLabel } : {}),
370 } satisfies ServerProvider["auth"];
371​
372 if (account.account) {
373 return { status: "ready", auth };
374 }
375​
376 if (account.requiresOpenaiAuth) {
377 return {
378 status: "error",
379 auth: { status: "unauthenticated" },
380 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
381 };
382 }
383​
384 return { status: "ready", auth };
386​
387export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
388 probe: (input: {
389 readonly binaryPath: string;
390 readonly homePath?: string;
391 readonly cwd: string;
392 readonly customModels: ReadonlyArray<string>;
393 }) => Effect.Effect<
394 CodexAppServerProviderSnapshot,
395 CodexErrors.CodexAppServerError,
396 ChildProcessSpawner.ChildProcessSpawner
397 > = probeCodexAppServerProvider,
398): Effect.fn.Return<
399 ServerProvider,
400 ServerSettingsError,
401 ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner
402> {
403 const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
404 Effect.flatMap((service) => service.getSettings),
405 Effect.map((settings) => settings.providers.codex),
406 );
407 const checkedAt = DateTime.formatIso(yield* DateTime.now);
408 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
409​
410 if (!codexSettings.enabled) {
411 return buildServerProvider({
412 provider: PROVIDER,
413 presentation: CODEX_PRESENTATION,
414 enabled: false,
415 checkedAt,
416 models: emptyModels,
417 skills: [],
418 probe: {
419 installed: false,
420 version: null,
421 status: "warning",
422 auth: { status: "unknown" },
423 message: "Codex is disabled in T3 Code settings.",
424 },
425 });
426 }
427​
428 const probeResult = yield* probe({
429 binaryPath: codexSettings.binaryPath,
430 homePath: codexSettings.homePath,
431 cwd: process.cwd(),
432 customModels: codexSettings.customModels,
433 }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
434​
435 if (Result.isFailure(probeResult)) {
436 const error = probeResult.failure;
437 const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);
438 return buildServerProvider({
439 provider: PROVIDER,
440 presentation: CODEX_PRESENTATION,
441 enabled: codexSettings.enabled,
442 checkedAt,
443 models: emptyModels,
444 skills: [],
445 probe: {
446 installed,
447 version: null,
448 status: "error",
449 auth: { status: "unknown" },
450 message: installed
451 ? `Codex app-server provider probe failed: ${error.message}.`
452 : "Codex CLI (`codex`) is not installed or not on PATH.",
453 },
454 });
455 }
456​
457 if (Option.isNone(probeResult.success)) {
458 return buildServerProvider({
459 provider: PROVIDER,
460 presentation: CODEX_PRESENTATION,
461 enabled: codexSettings.enabled,
462 checkedAt,
463 models: emptyModels,
464 skills: [],
465 probe: {
466 installed: true,
467 version: null,
468 status: "error",
469 auth: { status: "unknown" },
470 message: "Timed out while checking Codex app-server provider status.",
471 },
472 });
473 }
474​
475 const snapshot = probeResult.success.value;
476 const accountStatus = accountProbeStatus(snapshot.account);
477​
478 return buildServerProvider({
479 provider: PROVIDER,
480 presentation: CODEX_PRESENTATION,
481 enabled: codexSettings.enabled,
482 checkedAt,
483 models: snapshot.models,
484 skills: snapshot.skills,
485 probe: {
486 installed: true,
487 version: snapshot.version ?? null,
488 status: accountStatus.status,
489 auth: accountStatus.auth,
490 ...(accountStatus.message ? { message: accountStatus.message } : {}),
491 },
492 });
493});
494​
495export const CodexProviderLive = Layer.effect(
496 CodexProvider,
497 Effect.gen(function* () {
498 const serverSettings = yield* ServerSettingsService;
499 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
500 const checkProvider = checkCodexProviderStatus().pipe(
501 Effect.provideService(ServerSettingsService, serverSettings),
502 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
503 );
504​
505 return yield* makeManagedServerProvider<CodexSettings>({
506 getSettings: serverSettings.getSettings.pipe(
507 Effect.map((settings) => settings.providers.codex),
508 Effect.orDie,
509 ),
510 streamSettings: serverSettings.streamChanges.pipe(
511 Stream.map((settings) => settings.providers.codex),
512 ),
513 haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
514 initialSnapshot: makePendingCodexProvider,
515 checkProvider,
516 refreshInterval: Duration.minutes(5),
517 });
518 }),
519);