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

CodexProvider.ts

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