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

CodexProvider.ts

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