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

CodexProvider.ts

517 lines15.6 KB

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