The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,192 lines 41.7 KB
Raw
1 import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe";
2 import { pipe } from "effect/Function";
3 import * as DateTime from "effect/DateTime";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as Equal from "effect/Equal";
7 import * as Exit from "effect/Exit";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as Path from "effect/Path";
12 import * as RcMap from "effect/RcMap";
13 import * as Result from "effect/Result";
14 import * as Schema from "effect/Schema";
15 import * as Schedule from "effect/Schedule";
16 import * as Scope from "effect/Scope";
17 import * as Types from "effect/Types";
18 import * as ChildProcess from "effect/process/ChildProcess";
19 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
20 import * as CodexClient from "effect-codex-app-server/client";
21 import * as CodexSchema from "effect-codex-app-server/schema";
22 import * as CodexErrors from "effect-codex-app-server/errors";
23
24 import type {
25 CodexSettings,
26 CustomModelSetting,
27 ServerProvider,
28 ServerProviderState,
29 ModelCapabilities,
30 ProviderOptionDescriptor,
31 ServerProviderModel,
32 ServerProviderSkill,
33 } from "@t3tools/contracts";
34 import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
35
36 import {
37 codexModelFamily,
38 createModelCapabilities,
39 formatCodexModelName,
40 } from "@t3tools/shared/model";
41 import { resolveSpawnCommand } from "@t3tools/shared/shell";
42 import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
43 import {
44 buildServerProvider,
45 COMPACT_SLASH_COMMAND,
46 DEFAULT_TIMEOUT_MS,
47 providerModelsFromSettings,
48 providerProbeEnvironment,
49 spawnAndCollect,
50 type ServerProviderDraft,
51 } from "@t3tools/provider-core/server/snapshotProbe";
52 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
53 import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
54 import {
55 codexRateLimitsFailureMessage,
56 codexRateLimitsToLimits,
57 type CodexRateLimitSnapshot,
58 type CodexResetCreditsSummary,
59 } from "./codexUsageLimits.ts";
60 import * as HostProcess from "@t3tools/shared/HostProcess";
61 import packageJson from "../../package.json" with { type: "json" };
62 const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
63
64 type CodexRateLimitsProbe =
65 | {
66 readonly snapshot: CodexRateLimitSnapshot;
67 readonly rateLimitsByLimitId?:
68 | Readonly<Record<string, CodexRateLimitSnapshot>>
69 | null
70 | undefined;
71 readonly resetCredits: CodexResetCreditsSummary | null | undefined;
72 readonly accountId?: string | null | undefined;
73 }
74 | { readonly failure: string };
75
76 const CodexRoutingConfig = Schema.Struct({
77 model_provider: Schema.optionalKey(Schema.NullOr(Schema.String)),
78 openai_base_url: Schema.optionalKey(Schema.NullOr(Schema.String)),
79 model_providers: Schema.optionalKey(
80 Schema.Record(
81 Schema.String,
82 Schema.Struct({ base_url: Schema.optionalKey(Schema.NullOr(Schema.String)) }),
83 ),
84 ),
85 });
86 const decodeCodexRoutingConfig = Schema.decodeUnknownOption(CodexRoutingConfig);
87
88 const CodexCyberAccessConfig = Schema.Struct({
89 daybreak: Schema.optionalKey(Schema.NullOr(Schema.Boolean)),
90 features: Schema.optionalKey(
91 Schema.NullOr(
92 Schema.Struct({
93 api_key_cyber_access_programs: Schema.optionalKey(Schema.NullOr(Schema.Boolean)),
94 }),
95 ),
96 ),
97 });
98 const decodeCodexCyberAccessConfig = Schema.decodeUnknownOption(CodexCyberAccessConfig);
99
100 // Null is Codex's auth-dependent OpenAI default; undefined is a route that cannot be read.
101 function codexRouteBaseUrl(config: unknown): string | null | undefined {
102 const decoded = decodeCodexRoutingConfig(config);
103 if (Option.isNone(decoded)) return undefined;
104 const routing = decoded.value;
105 const providerId = routing.model_provider ?? "openai";
106 if (providerId === "openai") return routing.openai_base_url || null;
107 const provider = routing.model_providers?.[providerId];
108 return provider ? (provider.base_url ?? null) : undefined;
109 }
110
111 function routesToNativeOpenai(config: unknown): boolean {
112 const baseUrl = codexRouteBaseUrl(config);
113 if (baseUrl === undefined) return false;
114 if (baseUrl === null) return true;
115 if (!URL.canParse(baseUrl)) return false;
116 const url = new URL(baseUrl);
117 return (
118 url.protocol === "https:" &&
119 (url.hostname === "api.openai.com" || url.hostname === "chatgpt.com")
120 );
121 }
122
123 /** The origin of the custom endpoint Codex sends model requests to, if it uses one. */
124 export function codexCustomEndpoint(config: unknown): string | undefined {
125 const baseUrl = codexRouteBaseUrl(config);
126 const url = baseUrl ? URL.parse(baseUrl) : null;
127 return url && /^https?:$/.test(url.protocol) && !routesToNativeOpenai(config)
128 ? url.origin
129 : undefined;
130 }
131
132 // A stored login does not mean this provider's traffic spends that login's quota.
133 export const codexRoutesSpendNativeQuota = (
134 account: CodexSchema.V2GetAccountResponse,
135 config: unknown,
136 ): boolean =>
137 account.requiresOpenaiAuth && account.account?.type !== "apiKey" && routesToNativeOpenai(config);
138
139 const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
140 const CODEX_CATALOG_REFRESH_TIMEOUT_MS = 3_000;
141 const CODEX_CONFIG_PROBE_TIMEOUT_MS = 3_000;
142 const CODEX_CATALOG_REFRESH_POLL = "100 millis" as const;
143 const CODEX_CLIENT_NAME = "T3 Code";
144 // Handshake plus account/models/skills requests can exceed the shared 10s probe budget.
145 const CODEX_AUTH_PROBE_TIMEOUT_MS = 20_000;
146 const CODEX_DISCOVERY_MARGIN_MS = 250;
147 // `codex-cli 0.159.0`, `codex-cli 0.160.0-alpha.1` or the npm CLI's bare `0.1.4161006`.
148 // Keep a prerelease suffix so compatibility stays unknown for it, as it does for `initialize`.
149 const CODEX_CLI_VERSION_PATTERN = /(?:^|\s)v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?=\s|$)/u;
150
151 const CODEX_PRESENTATION = {
152 displayName: "Codex",
153 showInteractionModeToggle: true,
154 reportsContextWindow: true,
155 } as const;
156
157 export interface CodexAppServerProviderSnapshot {
158 readonly account: CodexSchema.V2GetAccountResponse;
159 readonly endpoint?: string | undefined;
160 readonly nativeUsage?: boolean;
161 readonly rateLimits?: CodexRateLimitsProbe;
162 readonly version: string | undefined;
163 readonly models: ReadonlyArray<ServerProviderModel> | undefined;
164 readonly serviceTier?: string | undefined;
165 /** Undefined when `config/read` failed, so T3 cannot know Codex's default program. */
166 readonly daybreakEnabled?: boolean | undefined;
167 readonly cyberAccessProgramsUnavailable?: boolean | undefined;
168 readonly skills: ReadonlyArray<ServerProviderSkill>;
169 }
170
171 const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
172 none: "None",
173 minimal: "Minimal",
174 low: "Low",
175 medium: "Medium",
176 high: "High",
177 xhigh: "Extra High",
178 max: "Max",
179 ultra: "Ultra",
180 };
181
182 const DEFAULT_SERVICE_TIER_ID = "default";
183
184 const SERVICE_TIER_DESCRIPTIONS: Readonly<Record<string, string>> = {
185 ultrafast: "Even faster, more expensive",
186 };
187
188 const CYBER_ACCESS_PROGRAM_LABELS: Readonly<Record<string, string>> = {
189 standard: "Standard",
190 daybreakBlue: "Daybreak Blue",
191 daybreakRed: "Daybreak Red",
192 };
193
194 function reasoningEffortLabel(reasoningEffort: string): string {
195 return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
196 }
197
198 function codexAccountAuthLabel(
199 account: CodexSchema.V2GetAccountResponse["account"],
200 usagePlanType: string | null | undefined,
201 ) {
202 if (!account) return undefined;
203 if (account.type === "apiKey") return "OpenAI API Key";
204 if (account.type === "amazonBedrock") return "Amazon Bedrock";
205 if (account.type !== "chatgpt") return undefined;
206 // account/read takes the plan from the cached login token; the usage read asks the backend.
207 const usageLabel = usagePlanType === "unknown" ? undefined : codexPlanLabel(usagePlanType);
208 return usageLabel ?? codexPlanLabel(account.planType);
209 }
210
211 export function codexPlanLabel(planType: string | null | undefined): string | undefined {
212 switch (planType) {
213 case "free":
214 return "ChatGPT Free Subscription";
215 case "go":
216 return "ChatGPT Go Subscription";
217 case "plus":
218 return "ChatGPT Plus Subscription";
219 case "pro":
220 return "ChatGPT Pro 200 Subscription";
221 case "prolite":
222 return "ChatGPT Pro 100 Subscription";
223 case "promax":
224 return "ChatGPT Pro 500 Subscription";
225 case "self_serve_business_prolite":
226 return "ChatGPT Business Premium Subscription";
227 case "team":
228 case "self_serve_business_usage_based":
229 case "business":
230 return "ChatGPT Business Subscription";
231 case "ent26":
232 case "enterprise_cbp_automation":
233 case "enterprise_cbp_usage_based":
234 case "enterprise":
235 return "ChatGPT Enterprise Subscription";
236 case "edu":
237 case "edu_plus":
238 case "edu_pro":
239 return "ChatGPT Edu Subscription";
240 case "unknown":
241 return "ChatGPT Subscription";
242 default:
243 return undefined;
244 }
245 }
246
247 function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) {
248 if (!account || account.type !== "chatgpt") return undefined;
249 return account.email;
250 }
251
252 export function codexDefaultReasoningEffortOverride(model: string): "medium" | undefined {
253 return codexModelFamily(model) === "gpt-6-astra" ? "medium" : undefined;
254 }
255
256 export function mapCodexModelCapabilities(
257 model: CodexSchema.V2ModelListResponse__Model,
258 ): ModelCapabilities {
259 const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
260 reasoningEffort ===
261 (codexDefaultReasoningEffortOverride(model.model) ?? model.defaultReasoningEffort)
262 ? {
263 id: reasoningEffort,
264 label: reasoningEffortLabel(reasoningEffort),
265 isDefault: true,
266 }
267 : {
268 id: reasoningEffort,
269 label: reasoningEffortLabel(reasoningEffort),
270 },
271 );
272 const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
273 const serviceTiers =
274 model.serviceTiers && model.serviceTiers.length > 0
275 ? model.serviceTiers
276 : (model.additionalSpeedTiers ?? []).map((id) => ({
277 id,
278 name: id === "fast" ? "Fast" : id,
279 description: "",
280 }));
281 const catalogDefaultServiceTier = serviceTiers.some(
282 (tier) => tier.id === model.defaultServiceTier,
283 )
284 ? model.defaultServiceTier
285 : null;
286 const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
287 const optionDescriptors: ProviderOptionDescriptor[] = [];
288
289 if (reasoningOptions.length > 0) {
290 optionDescriptors.push({
291 id: "reasoningEffort",
292 label: "Reasoning",
293 type: "select",
294 options: reasoningOptions,
295 ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
296 });
297 }
298 if (serviceTiers.length > 0) {
299 optionDescriptors.push({
300 id: "serviceTier",
301 label: "Service Tier",
302 type: "select",
303 options: [
304 {
305 id: DEFAULT_SERVICE_TIER_ID,
306 label: "Standard",
307 ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
308 },
309 ...serviceTiers.map((tier) => {
310 const description = SERVICE_TIER_DESCRIPTIONS[tier.id] ?? tier.description;
311 return {
312 id: tier.id,
313 label: tier.name,
314 ...(description ? { description } : {}),
315 ...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
316 };
317 }),
318 ],
319 currentValue: defaultServiceTier,
320 });
321 }
322 const cyberAccessPrograms = model.availableAccessPrograms?.cyber ?? [];
323 if (cyberAccessPrograms.length > 0) {
324 const hasStandard = cyberAccessPrograms.includes("standard");
325 const defaultProgram = hasStandard ? "standard" : cyberAccessPrograms[0];
326 optionDescriptors.push({
327 id: "cyberAccessProgram",
328 label: "Cyber Access",
329 type: "select",
330 // Standard stays selectable as an opt-out; Codex rejects it visibly when the login cannot use it.
331 options: (hasStandard ? cyberAccessPrograms : ["standard", ...cyberAccessPrograms]).map(
332 (program) => ({
333 id: program,
334 label: CYBER_ACCESS_PROGRAM_LABELS[program] ?? program,
335 ...(program === defaultProgram ? { isDefault: true } : {}),
336 }),
337 ),
338 ...(defaultProgram === undefined ? {} : { currentValue: defaultProgram }),
339 });
340 }
341
342 return createModelCapabilities({
343 optionDescriptors,
344 });
345 }
346
347 function parseCodexModelListResponse(
348 response: CodexSchema.V2ModelListResponse,
349 ): ReadonlyArray<ServerProviderModel> {
350 return response.data.map((model) => ({
351 slug: model.model,
352 name: formatCodexModelName(model.displayName),
353 isCustom: false,
354 ...(model.isDefault ? { isDefault: true } : {}),
355 capabilities: mapCodexModelCapabilities(model),
356 }));
357 }
358
359 export function applyPreferredCodexDefaultModel(
360 models: ReadonlyArray<ServerProviderModel>,
361 ): ReadonlyArray<ServerProviderModel> {
362 const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.flatMap((slug) =>
363 models.filter((model) => !model.isCustom && codexModelFamily(model.slug) === slug),
364 )[0]?.slug;
365 if (!preferredSlug) {
366 return models;
367 }
368 return models.map((model) => {
369 if (model.slug === preferredSlug) {
370 return model.isDefault ? model : { ...model, isDefault: true };
371 }
372 if (!model.isDefault) {
373 return model;
374 }
375 const { isDefault: _isDefault, ...rest } = model;
376 return rest;
377 });
378 }
379
380 function mapCodexOptionDescriptors(
381 models: ReadonlyArray<ServerProviderModel>,
382 update: (
383 descriptors: ReadonlyArray<ProviderOptionDescriptor>,
384 model: ServerProviderModel,
385 ) => ReadonlyArray<ProviderOptionDescriptor>,
386 ): ReadonlyArray<ServerProviderModel> {
387 return models.map((model) => {
388 if (!model.capabilities?.optionDescriptors) return model;
389 return {
390 ...model,
391 capabilities: {
392 ...model.capabilities,
393 optionDescriptors: update(model.capabilities.optionDescriptors, model),
394 },
395 };
396 });
397 }
398
399 function withConfiguredSelectDefault(
400 models: ReadonlyArray<ServerProviderModel>,
401 descriptorId: string,
402 pick: (options: ReadonlyArray<{ readonly id: string }>) => string | undefined,
403 ): ReadonlyArray<ServerProviderModel> {
404 return mapCodexOptionDescriptors(models, (descriptors) =>
405 descriptors.map((descriptor) => {
406 if (descriptor.id !== descriptorId || descriptor.type !== "select") return descriptor;
407 const value = pick(descriptor.options);
408 if (!value) return descriptor;
409 return {
410 ...descriptor,
411 currentValue: value,
412 options: descriptor.options.map(({ isDefault: _isDefault, ...option }) =>
413 option.id === value ? { ...option, isDefault: true } : option,
414 ),
415 };
416 }),
417 );
418 }
419
420 function applyConfiguredCodexServiceTier(
421 models: ReadonlyArray<ServerProviderModel>,
422 serviceTier: string | undefined,
423 ): ReadonlyArray<ServerProviderModel> {
424 if (!serviceTier) return models;
425 return withConfiguredSelectDefault(
426 models,
427 "serviceTier",
428 (options) =>
429 options.find(
430 (option) =>
431 option.id === serviceTier || (serviceTier === "fast" && option.id === "priority"),
432 )?.id,
433 );
434 }
435
436 /** Mirrors Codex: `daybreak = true` prefers a Daybreak program, Blue before Red. */
437 function applyConfiguredCodexCyberAccess(
438 models: ReadonlyArray<ServerProviderModel>,
439 snapshot: Pick<
440 CodexAppServerProviderSnapshot,
441 "daybreakEnabled" | "cyberAccessProgramsUnavailable"
442 >,
443 ): ReadonlyArray<ServerProviderModel> {
444 // Without a descriptor no turn sends a program; without a default only an explicit choice goes.
445 const offered = mapCodexOptionDescriptors(models, (descriptors, model) =>
446 descriptors.flatMap((descriptor): ReadonlyArray<ProviderOptionDescriptor> => {
447 if (descriptor.id !== "cyberAccessProgram" || descriptor.type !== "select") {
448 return [descriptor];
449 }
450 if (model.isCustom || snapshot.cyberAccessProgramsUnavailable === true) return [];
451 if (snapshot.daybreakEnabled !== undefined) return [descriptor];
452 const { currentValue: _currentValue, ...withoutDefault } = descriptor;
453 return [
454 {
455 ...withoutDefault,
456 options: descriptor.options.map(({ isDefault: _isDefault, ...option }) => option),
457 },
458 ];
459 }),
460 );
461 if (snapshot.daybreakEnabled !== true) return offered;
462 return withConfiguredSelectDefault(offered, "cyberAccessProgram", (options) =>
463 ["daybreakBlue", "daybreakRed"].find((program) =>
464 options.some((option) => option.id === program),
465 ),
466 );
467 }
468
469 /**
470 * Codex has no static default capability set, so a bare custom slug borrows
471 * the first built-in's descriptors; an entry with its own capabilities keeps
472 * them.
473 */
474 function appendCustomCodexModels(
475 models: ReadonlyArray<ServerProviderModel>,
476 customModels: ReadonlyArray<CustomModelSetting>,
477 ): ReadonlyArray<ServerProviderModel> {
478 const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
479 return providerModelsFromSettings(models, customModels, fallbackCapabilities);
480 }
481
482 function parseCodexSkillsListResponse(
483 response: CodexSchema.V2SkillsListResponse,
484 cwd: string,
485 ): ReadonlyArray<ServerProviderSkill> {
486 const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
487 const skills = matchingEntry
488 ? matchingEntry.skills
489 : response.data.flatMap((entry) => entry.skills);
490
491 return skills.map((skill) => {
492 const shortDescription =
493 skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
494
495 const parsedSkill: Types.Mutable<ServerProviderSkill> = {
496 name: skill.name,
497 path: skill.path,
498 enabled: skill.enabled,
499 };
500
501 if (skill.description) {
502 parsedSkill.description = skill.description;
503 }
504 if (skill.scope) {
505 parsedSkill.scope = skill.scope;
506 }
507 if (skill.interface?.displayName) {
508 parsedSkill.displayName = skill.interface.displayName;
509 }
510 if (shortDescription) {
511 parsedSkill.shortDescription = shortDescription;
512 }
513
514 return parsedSkill;
515 });
516 }
517
518 const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* (
519 client: CodexClient.CodexAppServerClient["Service"],
520 ) {
521 const models: ServerProviderModel[] = [];
522 let cursor: string | null | undefined = undefined;
523
524 do {
525 const response: CodexSchema.V2ModelListResponse = yield* client.request(
526 "model/list",
527 cursor ? { cursor } : {},
528 );
529 models.push(...parseCodexModelListResponse(response));
530 cursor = response.nextCursor;
531 } while (cursor);
532
533 return models;
534 });
535
536 const decodeCodexModelsCacheStamp = Schema.decodeUnknownOption(
537 Schema.fromJsonString(Schema.Struct({ fetched_at: Schema.String })),
538 );
539
540 const readCodexModelsCacheFetchedAt = Effect.fn("readCodexModelsCacheFetchedAt")(function* (
541 codexHome: string,
542 ) {
543 const fileSystem = yield* FileSystem.FileSystem;
544 const path = yield* Path.Path;
545 const text = yield* fileSystem
546 .readFileString(path.join(codexHome, "models_cache.json"))
547 .pipe(Effect.option);
548 return Option.flatMap(text, decodeCodexModelsCacheStamp).pipe(
549 Option.flatMap((stamp) => DateTime.make(stamp.fetched_at)),
550 Option.match({ onNone: () => Number.NaN, onSome: DateTime.toEpochMillis }),
551 );
552 });
553
554 const withCodexDiscoveryDeadline = Effect.fnUntraced(function* <A, E, R>(
555 effect: Effect.Effect<A, E, R>,
556 deadlineMs: number,
557 timeoutMs = Infinity,
558 ) {
559 const remainingMs = Math.min(timeoutMs, deadlineMs - DateTime.toEpochMillis(yield* DateTime.now));
560 if (remainingMs <= 0) return undefined;
561 return yield* effect.pipe(
562 Effect.timeoutOption(Duration.millis(remainingMs)),
563 Effect.map(Option.getOrUndefined),
564 );
565 });
566
567 /**
568 * Every Codex client on the machine shares that file, and the backend tailors
569 * the catalog to each client's originator: the plain CLI does not get Sol
570 * Ultrafast. App-server refreshes the catalog online at startup, so wait until
571 * a write newer than this process's spawn lands, then list again.
572 */
573 const requestCodexChatGptModels = Effect.fn("requestCodexChatGptModels")(function* (input: {
574 readonly client: CodexClient.CodexAppServerClient["Service"];
575 readonly codexHome: string;
576 readonly spawnedAtMs: number;
577 readonly deadlineMs: number;
578 }) {
579 const models = yield* withCodexDiscoveryDeadline(
580 requestAllCodexModels(input.client),
581 input.deadlineMs,
582 );
583 if (models === undefined) return undefined;
584 const refreshed = yield* withCodexDiscoveryDeadline(
585 readCodexModelsCacheFetchedAt(input.codexHome).pipe(
586 Effect.repeat({
587 schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL),
588 until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs,
589 }),
590 ),
591 input.deadlineMs,
592 CODEX_CATALOG_REFRESH_TIMEOUT_MS,
593 );
594 if (refreshed === undefined) {
595 yield* Effect.logWarning(
596 "Codex did not refresh its model catalog in time; using the cached catalog.",
597 );
598 return models;
599 }
600 return (
601 (yield* withCodexDiscoveryDeadline(requestAllCodexModels(input.client), input.deadlineMs)) ??
602 models
603 );
604 });
605
606 /** Set originator at spawn; the pre-initialize refresh otherwise overwrites shared cache with plain-CLI models. */
607 export const codexAppServerEnvironment = (
608 environment: NodeJS.ProcessEnv | undefined,
609 ): NodeJS.ProcessEnv => ({
610 CODEX_INTERNAL_ORIGINATOR_OVERRIDE: CODEX_CLIENT_NAME,
611 ...environment,
612 });
613
614 export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
615 return {
616 clientInfo: {
617 name: CODEX_CLIENT_NAME,
618 title: CODEX_CLIENT_NAME,
619 version: packageJson.version,
620 },
621 capabilities: {
622 experimentalApi: true,
623 },
624 };
625 }
626
627 const codexProcessEnvironment = Effect.fn("codexProcessEnvironment")(function* (input: {
628 readonly homePath?: string | undefined;
629 readonly environment?: NodeJS.ProcessEnv | undefined;
630 }) {
631 // Expand CODEX_HOME explicitly: spawn passes a literal ~ that Codex rejects.
632 const resolvedHomePath = input.homePath
633 ? expandHomePath(input.homePath, yield* HostProcess.HomeDirectory)
634 : undefined;
635 return {
636 ...codexAppServerEnvironment(input.environment),
637 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
638 };
639 });
640
641 export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(function* (input: {
642 readonly binaryPath: string;
643 readonly homePath?: string | undefined;
644 readonly launchArgs?: string | undefined;
645 readonly cwd: string;
646 readonly environment?: NodeJS.ProcessEnv | undefined;
647 }) {
648 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
649 const environment = yield* codexProcessEnvironment(input);
650 const spawnCommand = yield* resolveSpawnCommand(
651 input.binaryPath,
652 codexAppServerArgs(input.launchArgs),
653 { env: environment, extendEnv: true },
654 );
655 const child = yield* spawner
656 .spawn(
657 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
658 cwd: input.cwd,
659 env: environment,
660 extendEnv: true,
661 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
662 shell: spawnCommand.shell,
663 }),
664 )
665 .pipe(
666 Effect.mapError(
667 (cause) =>
668 new CodexErrors.CodexAppServerSpawnError({
669 command: `${input.binaryPath} app-server`,
670 cause,
671 }),
672 ),
673 );
674 const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
675 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
676 Effect.provide(clientContext),
677 );
678 const initialize = yield* client.request("initialize", buildCodexInitializeParams());
679 yield* client.notify("initialized", undefined);
680 return { client, initialize, pid: child.pid };
681 });
682
683 // Codex runs git (ssh for ssh URLs) for plugin marketplaces at launch and exits without waiting
684 // for it, so stopping a short probe mid-fetch strands ssh in an SSH-agent request.
685 const CODEX_STARTUP_WORK_GRACE = Duration.minutes(1);
686
687 const codexProcessGroupIsBusy = Effect.fn("codexProcessGroupIsBusy")(
688 function* (pid: number) {
689 const { stdout } = yield* spawnAndCollect(
690 "pgrep",
691 ChildProcess.make("pgrep", ["-g", `${pid}`]),
692 );
693 return stdout.split("\n").some((line) => line.trim() !== "" && Number(line) !== pid);
694 },
695 Effect.orElseSucceed(() => false),
696 );
697
698 const stopCodexAfterStartupWork = (pid: number, processScope: Scope.Closeable) =>
699 codexProcessGroupIsBusy(pid).pipe(
700 Effect.repeat({ schedule: Schedule.spaced("500 millis"), while: (busy) => busy }),
701 Effect.timeoutOption(CODEX_STARTUP_WORK_GRACE),
702 Effect.ensuring(Scope.close(processScope, Exit.void)),
703 );
704
705 // Usage is an enrichment: a failure or a slow answer degrades to "no usage this
706 // probe" rather than costing the account and models.
707 const readCodexRateLimits = (
708 client: CodexClient.CodexAppServerClient["Service"],
709 deadlineMs: number,
710 ) =>
711 withCodexDiscoveryDeadline(client.request("account/rateLimits/read", null), deadlineMs).pipe(
712 Effect.map((response): CodexRateLimitsProbe =>
713 response
714 ? {
715 snapshot: response.rateLimits,
716 rateLimitsByLimitId: response.rateLimitsByLimitId,
717 resetCredits: response.rateLimitResetCredits,
718 accountId: response.accountId,
719 }
720 : { failure: "Codex did not answer the usage request." },
721 ),
722 Effect.catch((error) =>
723 Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(
724 Effect.as<CodexRateLimitsProbe>({ failure: codexRateLimitsFailureMessage(error) }),
725 ),
726 ),
727 );
728
729 const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
730 readonly probeTimeoutMs: number;
731 readonly binaryPath: string;
732 readonly homePath?: string;
733 readonly launchArgs?: string;
734 readonly cwd: string;
735 readonly environment?: NodeJS.ProcessEnv;
736 readonly skipNativeUsage?: boolean;
737 }) {
738 const spawnedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
739 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
740 const processScope = yield* Scope.make();
741 let pid: number | undefined;
742 // Returning the snapshot must not wait for Codex's own startup work.
743 yield* Effect.addFinalizer(() =>
744 pid === undefined
745 ? Scope.close(processScope, Exit.void)
746 : stopCodexAfterStartupWork(pid, processScope).pipe(
747 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
748 Effect.forkDetach,
749 Effect.asVoid,
750 ),
751 );
752 const opened = yield* withCodexAppServerClient(input).pipe(Scope.provide(processScope));
753 pid = opened.pid;
754 const { client, initialize } = opened;
755
756 const versionMatch = initialize.userAgent.match(/\/([^\s]+)/);
757 const version = versionMatch ? versionMatch[1] : undefined;
758
759 const accountResponse = yield* client.request("account/read", {});
760 if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {
761 return {
762 account: accountResponse,
763 version,
764 models: [],
765 skills: [],
766 } satisfies CodexAppServerProviderSnapshot;
767 }
768
769 // Optional discovery must finish before the outer timeout can discard the account result.
770 const deadlineMs = spawnedAtMs + input.probeTimeoutMs - CODEX_DISCOVERY_MARGIN_MS;
771 const [skillsResponse, models, { config, nativeUsage, rateLimits }] = yield* Effect.all(
772 [
773 withCodexDiscoveryDeadline(client.request("skills/list", { cwds: [input.cwd] }), deadlineMs),
774 accountResponse.account?.type === "chatgpt"
775 ? requestCodexChatGptModels({
776 client,
777 codexHome: initialize.codexHome,
778 spawnedAtMs,
779 deadlineMs,
780 })
781 : withCodexDiscoveryDeadline(requestAllCodexModels(client), deadlineMs),
782 // The shared catalog must exclude config from the server's launch project.
783 withCodexDiscoveryDeadline(
784 client.request("config/read", { includeLayers: false }),
785 deadlineMs,
786 CODEX_CONFIG_PROBE_TIMEOUT_MS,
787 ).pipe(
788 Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined))),
789 Effect.flatMap((config) => {
790 // Only a confirmed native route may probe or publish the login's quota.
791 const nativeUsage =
792 !input.skipNativeUsage &&
793 config !== undefined &&
794 codexRoutesSpendNativeQuota(accountResponse, config.config);
795 const readUsage: Effect.Effect<CodexRateLimitsProbe | undefined> = nativeUsage
796 ? readCodexRateLimits(client, deadlineMs)
797 : Effect.undefined;
798 return readUsage.pipe(
799 Effect.map((rateLimits) => ({
800 config: config?.config,
801 nativeUsage,
802 rateLimits,
803 })),
804 );
805 }),
806 ),
807 ],
808 { concurrency: "unbounded" },
809 );
810
811 const cyberAccess = Option.getOrUndefined(decodeCodexCyberAccessConfig(config));
812 return {
813 account: accountResponse,
814 endpoint: config ? codexCustomEndpoint(config) : undefined,
815 nativeUsage,
816 ...(rateLimits ? { rateLimits } : {}),
817 version,
818 models,
819 serviceTier: config?.service_tier ?? undefined,
820 daybreakEnabled: config === undefined ? undefined : cyberAccess?.daybreak === true,
821 // An unread config cannot rule out an API key with the programs turned off.
822 cyberAccessProgramsUnavailable:
823 accountResponse.account?.type === "apiKey" &&
824 (config === undefined || cyberAccess?.features?.api_key_cyber_access_programs === false),
825 skills: skillsResponse ? parseCodexSkillsListResponse(skillsResponse, input.cwd) : [],
826 } satisfies CodexAppServerProviderSnapshot;
827 });
828
829 // Old CLIs can exit before initialize reports the version needed for compatibility advice.
830 const probeCodexCliVersion = Effect.fn("probeCodexCliVersion")(
831 function* (input: {
832 readonly binaryPath: string;
833 readonly homePath?: string | undefined;
834 readonly cwd: string;
835 readonly environment?: NodeJS.ProcessEnv | undefined;
836 }) {
837 const environment = yield* codexProcessEnvironment(input);
838 const spawnCommand = yield* resolveSpawnCommand(input.binaryPath, ["--version"], {
839 env: environment,
840 extendEnv: true,
841 });
842 const result = yield* spawnAndCollect(
843 input.binaryPath,
844 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
845 cwd: input.cwd,
846 env: environment,
847 extendEnv: true,
848 forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
849 shell: spawnCommand.shell,
850 }),
851 );
852 if (result.code !== 0) return null;
853 return CODEX_CLI_VERSION_PATTERN.exec(result.stdout)?.[1] ?? null;
854 },
855 (effect, input) =>
856 effect.pipe(
857 Effect.timeoutOption(
858 resolveProviderProbeTimeoutMs("codex", DEFAULT_TIMEOUT_MS, input.environment),
859 ),
860 ),
861 Effect.map(Option.getOrNull),
862 Effect.catch((cause) =>
863 Effect.logDebug("Codex --version fallback failed.", { cause }).pipe(Effect.as(null)),
864 ),
865 );
866
867 export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(function* (input: {
868 readonly binaryPath: string;
869 readonly homePath?: string;
870 readonly launchArgs?: string;
871 readonly cwd: string;
872 readonly environment?: NodeJS.ProcessEnv;
873 }) {
874 const { client } = yield* withCodexAppServerClient({
875 ...input,
876 environment: providerProbeEnvironment(input.environment ?? process.env),
877 });
878 const skillsResponse = yield* client.request("skills/list", { cwds: [input.cwd] });
879 return parseCodexSkillsListResponse(skillsResponse, input.cwd);
880 });
881
882 // Long enough for a burst of workspace switches; short because the helper holds the user's
883 // binary open, and Windows refuses to overwrite or delete a running executable.
884 const CODEX_SKILLS_HELPER_IDLE_TTL = "30 seconds";
885
886 /** Reuses one app-server per launch identity; each read passes its cwd and rescans from disk. */
887 export const makeCodexSkillsProbe = Effect.fn("makeCodexSkillsProbe")(function* () {
888 const helpers = yield* RcMap.make({
889 lookup: (launch: {
890 readonly binaryPath: string;
891 readonly homePath?: string;
892 readonly launchArgs?: string;
893 readonly environment: NodeJS.ProcessEnv;
894 }) =>
895 withCodexAppServerClient({ ...launch, cwd: process.cwd() }).pipe(
896 Effect.map(({ client }) => client),
897 ),
898 idleTimeToLive: CODEX_SKILLS_HELPER_IDLE_TTL,
899 });
900 return Effect.fn("CodexSkillsProbe.probe")(function* (input: {
901 readonly binaryPath: string;
902 readonly homePath?: string;
903 readonly launchArgs?: string;
904 readonly cwd: string;
905 readonly environment?: NodeJS.ProcessEnv;
906 }) {
907 const { cwd, ...rest } = input;
908 const launch = {
909 ...rest,
910 environment: providerProbeEnvironment(rest.environment ?? process.env),
911 };
912 // Retire helpers for a previous binary, home, credentials, or launch options.
913 const stale = Array.from(yield* RcMap.keys(helpers)).filter(
914 (key) => !Equal.equals(key, launch),
915 );
916 yield* Effect.forEach(stale, (key) => RcMap.invalidate(helpers, key), { discard: true });
917 const skillsResponse = yield* RcMap.get(helpers, launch).pipe(
918 Effect.flatMap((client) => client.request("skills/list", { cwds: [cwd], forceReload: true })),
919 Effect.scoped,
920 // RcMap keeps a failed spawn, and a dead helper keeps failing; drop it so the retry respawns.
921 Effect.onError(() => RcMap.invalidate(helpers, launch)),
922 Effect.retry({ times: 1 }),
923 );
924 return parseCodexSkillsListResponse(skillsResponse, cwd);
925 });
926 });
927
928 const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
929 appendCustomCodexModels([], codexSettings.customModels);
930
931 const makePendingCodexProvider = Effect.fn("CodexProvider.makePendingCodexProvider")(function* (
932 codexSettings: CodexSettings,
933 ): Effect.fn.Return<ServerProviderDraft> {
934 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
935 const models = emptyCodexModelsFromSettings(codexSettings);
936
937 if (!codexSettings.enabled) {
938 return buildServerProvider({
939 presentation: CODEX_PRESENTATION,
940 enabled: false,
941 checkedAt,
942 models,
943 skills: [],
944 probe: {
945 installed: false,
946 version: null,
947 status: "warning",
948 auth: { status: "unknown" },
949 message: "Codex is disabled in T3 Code settings.",
950 },
951 });
952 }
953
954 return buildServerProvider({
955 presentation: CODEX_PRESENTATION,
956 enabled: true,
957 checkedAt,
958 models,
959 skills: [],
960 probe: {
961 installed: false,
962 version: null,
963 status: "warning",
964 auth: { status: "unknown" },
965 message: "Codex provider status has not been checked in this session yet.",
966 },
967 });
968 });
969
970 const quotePath = Schema.encodeSync(Schema.fromJsonString(Schema.String));
971
972 function accountProbeStatus(
973 { account, rateLimits }: CodexAppServerProviderSnapshot,
974 codexHome: string | undefined,
975 ): {
976 readonly status: Exclude<ServerProviderState, "disabled">;
977 readonly auth: ServerProvider["auth"];
978 readonly message?: string;
979 } {
980 const authLabel = codexAccountAuthLabel(
981 account.account,
982 rateLimits && "snapshot" in rateLimits ? rateLimits.snapshot.planType : undefined,
983 );
984 const authEmail = codexAccountEmail(account.account);
985 const workspaceId =
986 rateLimits && "accountId" in rateLimits ? rateLimits.accountId?.trim() : undefined;
987 const auth = {
988 status: account.account ? ("authenticated" as const) : ("unknown" as const),
989 ...(account.account?.type ? { type: account.account?.type } : {}),
990 ...(authLabel ? { label: authLabel } : {}),
991 ...(authEmail ? { email: authEmail } : {}),
992 ...(workspaceId ? { workspaceId } : {}),
993 } satisfies ServerProvider["auth"];
994
995 if (account.account) {
996 return { status: "ready", auth };
997 }
998
999 if (account.requiresOpenaiAuth) {
1000 return {
1001 status: "error",
1002 auth: { status: "unauthenticated" },
1003 message: codexHome
1004 ? `Codex CLI is not authenticated. Run \`codex login\` with CODEX_HOME set to ${quotePath(codexHome)} and try again.`
1005 : "Codex CLI is not authenticated. Run `codex login` and try again.",
1006 };
1007 }
1008
1009 return { status: "ready", auth };
1010 }
1011
1012 export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
1013 codexSettings: CodexSettings,
1014 probe: (input: {
1015 readonly probeTimeoutMs: number;
1016 readonly binaryPath: string;
1017 readonly homePath?: string;
1018 readonly launchArgs?: string;
1019 readonly cwd: string;
1020 readonly environment?: NodeJS.ProcessEnv;
1021 readonly skipNativeUsage?: boolean;
1022 }) => Effect.Effect<
1023 CodexAppServerProviderSnapshot,
1024 CodexErrors.CodexAppServerError,
1025 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope
1026 > = probeCodexAppServerProvider,
1027 environment?: NodeJS.ProcessEnv,
1028 managedAuth?: ServerProvider["auth"],
1029 ): Effect.fn.Return<
1030 ServerProviderDraft,
1031 ServerSettingsError,
1032 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
1033 > {
1034 const resolvedEnvironment = providerProbeEnvironment(environment ?? process.env);
1035 const checkedAt = DateTime.formatIso(yield* DateTime.now);
1036 const emptyModels = emptyCodexModelsFromSettings(codexSettings);
1037
1038 if (!codexSettings.enabled) {
1039 return buildServerProvider({
1040 presentation: CODEX_PRESENTATION,
1041 enabled: false,
1042 checkedAt,
1043 models: emptyModels,
1044 skills: [],
1045 probe: {
1046 installed: false,
1047 version: null,
1048 status: "warning",
1049 auth: { status: "unknown" },
1050 message: "Codex is disabled in T3 Code settings.",
1051 },
1052 });
1053 }
1054
1055 const probeTimeoutMs = resolveProviderProbeTimeoutMs(
1056 "codex",
1057 CODEX_AUTH_PROBE_TIMEOUT_MS,
1058 resolvedEnvironment,
1059 );
1060 const probeResult = yield* probe({
1061 probeTimeoutMs,
1062 binaryPath: codexSettings.binaryPath,
1063 homePath: codexSettings.homePath,
1064 launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
1065 cwd: process.cwd(),
1066 environment: resolvedEnvironment,
1067 ...(managedAuth ? { skipNativeUsage: true } : {}),
1068 }).pipe(
1069 // Process teardown can outlast the work budget without discarding a completed snapshot.
1070 Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
1071 Effect.scoped,
1072 Effect.result,
1073 );
1074
1075 if (Result.isFailure(probeResult)) {
1076 const error = probeResult.failure;
1077 const installed = !isCodexAppServerSpawnError(error);
1078 const version = installed
1079 ? yield* probeCodexCliVersion({
1080 binaryPath: codexSettings.binaryPath,
1081 homePath: codexSettings.homePath,
1082 cwd: process.cwd(),
1083 environment: resolvedEnvironment,
1084 })
1085 : null;
1086 return buildServerProvider({
1087 presentation: CODEX_PRESENTATION,
1088 enabled: codexSettings.enabled,
1089 checkedAt,
1090 models: emptyModels,
1091 skills: [],
1092 probe: {
1093 installed,
1094 version,
1095 status: "error",
1096 auth: { status: "unknown" },
1097 message: installed
1098 ? `Codex app-server provider probe failed: ${error.message}.`
1099 : `Could not start Codex CLI (\`${codexSettings.binaryPath}\`). Check Settings → Providers → Codex → Binary path on the server.` +
1100 (codexSettings.binaryPath === "codex"
1101 ? " Installing ChatGPT or Codex desktop may not add codex to PATH."
1102 : " Make sure the configured executable exists and can be run."),
1103 },
1104 });
1105 }
1106
1107 if (Option.isNone(probeResult.success)) {
1108 return buildServerProvider({
1109 presentation: CODEX_PRESENTATION,
1110 enabled: codexSettings.enabled,
1111 checkedAt,
1112 models: emptyModels,
1113 skills: [],
1114 probe: {
1115 installed: true,
1116 version: null,
1117 status: "error",
1118 auth: { status: "unknown" },
1119 message: "Timed out while checking Codex app-server provider status.",
1120 },
1121 });
1122 }
1123
1124 const snapshot = probeResult.success.value;
1125 const accountStatus = managedAuth
1126 ? { status: "ready" as const, auth: managedAuth, message: undefined }
1127 : accountProbeStatus(
1128 snapshot,
1129 codexSettings.homePath
1130 ? expandHomePath(codexSettings.homePath, yield* HostProcess.HomeDirectory)
1131 : undefined,
1132 );
1133 // Sign-in guidance still applies when Codex itself says it needs an OpenAI login.
1134 const usageLimits =
1135 !snapshot.nativeUsage && !accountStatus.message
1136 ? makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" })
1137 : snapshot.rateLimits === undefined || "failure" in snapshot.rateLimits
1138 ? makeUnavailableUsageLimits({
1139 checkedAt,
1140 reason: "probeFailed",
1141 ...(accountStatus.message ? { message: accountStatus.message } : {}),
1142 ...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}),
1143 })
1144 : codexRateLimitsToLimits({
1145 snapshot: snapshot.rateLimits.snapshot,
1146 rateLimitsByLimitId: snapshot.rateLimits.rateLimitsByLimitId,
1147 resetCredits: snapshot.rateLimits.resetCredits,
1148 checkedAt,
1149 });
1150
1151 return buildServerProvider({
1152 presentation: CODEX_PRESENTATION,
1153 enabled: codexSettings.enabled,
1154 checkedAt,
1155 models: pipe(
1156 appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels),
1157 applyPreferredCodexDefaultModel,
1158 (models) => applyConfiguredCodexServiceTier(models, snapshot.serviceTier),
1159 (models) => applyConfiguredCodexCyberAccess(models, snapshot),
1160 ),
1161 skills: snapshot.skills,
1162 slashCommands: [
1163 COMPACT_SLASH_COMMAND,
1164 {
1165 name: "goal",
1166 description: "Set a goal Codex keeps working toward until it is done",
1167 input: { hint: "Objective, or pause, resume, clear" },
1168 },
1169 {
1170 name: "feedback",
1171 description: "Send this thread and Codex logs to OpenAI",
1172 input: { hint: "Describe the issue (optional)" },
1173 },
1174 ],
1175 probe: {
1176 installed: true,
1177 version: snapshot.version ?? null,
1178 status: snapshot.models === undefined ? "warning" : accountStatus.status,
1179 auth: snapshot.endpoint
1180 ? { ...accountStatus.auth, endpoint: snapshot.endpoint }
1181 : accountStatus.auth,
1182 ...(accountStatus.message
1183 ? { message: accountStatus.message }
1184 : snapshot.models === undefined
1185 ? { message: "Codex did not return its model catalog in time." }
1186 : {}),
1187 ...(managedAuth ? {} : { usageLimits }),
1188 },
1189 });
1190 });
1191
1192 export { makePendingCodexProvider };