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

CodexProvider.ts

505 lines15.6 KB

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