|
| 1 | +import { readFile } from 'node:fs/promises'; |
| 2 | +import path from 'node:path'; |
| 3 | +import process from 'node:process'; |
| 4 | +import { Result } from '@praha/byethrow'; |
| 5 | +import { CODEX_HOME_ENV, DEFAULT_CODEX_DIR } from './_consts.ts'; |
| 6 | +import { logger } from './logger.ts'; |
| 7 | + |
| 8 | +export type CodexSpeed = 'standard' | 'fast'; |
| 9 | +export type CodexSpeedOption = 'auto' | CodexSpeed; |
| 10 | + |
| 11 | +type ParsedConfig = { |
| 12 | + profile?: string; |
| 13 | + serviceTier?: string; |
| 14 | + profiles: Map<string, { serviceTier?: string }>; |
| 15 | +}; |
| 16 | + |
| 17 | +function codexHome(): string { |
| 18 | + const value = process.env[CODEX_HOME_ENV]?.trim(); |
| 19 | + return value == null || value === '' ? DEFAULT_CODEX_DIR : path.resolve(value); |
| 20 | +} |
| 21 | + |
| 22 | +export function codexConfigPath(): string { |
| 23 | + return path.join(codexHome(), 'config.toml'); |
| 24 | +} |
| 25 | + |
| 26 | +function parseStringValue(value: string): string | undefined { |
| 27 | + const trimmed = value.trim(); |
| 28 | + const quoted = /^"([^"]*)"|'([^']*)'/.exec(trimmed); |
| 29 | + if (quoted != null) { |
| 30 | + return quoted[1] ?? quoted[2]; |
| 31 | + } |
| 32 | + |
| 33 | + const bare = /^([^\s#]+)/.exec(trimmed); |
| 34 | + return bare?.[1]; |
| 35 | +} |
| 36 | + |
| 37 | +function profileNameFromSection(section: string): string | undefined { |
| 38 | + const match = /^profiles\.(?:"([^"]+)"|'([^']+)'|([\w-]+))$/.exec(section); |
| 39 | + return match?.[1] ?? match?.[2] ?? match?.[3]; |
| 40 | +} |
| 41 | + |
| 42 | +export function parseCodexConfig(content: string): ParsedConfig { |
| 43 | + const parsed: ParsedConfig = { profiles: new Map() }; |
| 44 | + let section = ''; |
| 45 | + |
| 46 | + for (const rawLine of content.split(/\r?\n/)) { |
| 47 | + const line = rawLine.trim(); |
| 48 | + if (line === '' || line.startsWith('#')) { |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + const sectionMatch = /^\[([^\]]+)\]$/.exec(line); |
| 53 | + if (sectionMatch != null) { |
| 54 | + section = sectionMatch[1]!.trim(); |
| 55 | + continue; |
| 56 | + } |
| 57 | + |
| 58 | + const assignmentIndex = line.indexOf('='); |
| 59 | + if (assignmentIndex === -1) { |
| 60 | + continue; |
| 61 | + } |
| 62 | + |
| 63 | + const key = line.slice(0, assignmentIndex).trim(); |
| 64 | + if (!/^[\w-]+$/.test(key)) { |
| 65 | + continue; |
| 66 | + } |
| 67 | + |
| 68 | + const value = parseStringValue(line.slice(assignmentIndex + 1)); |
| 69 | + if (value == null) { |
| 70 | + continue; |
| 71 | + } |
| 72 | + |
| 73 | + if (section === '') { |
| 74 | + if (key === 'profile') { |
| 75 | + parsed.profile = value; |
| 76 | + } else if (key === 'service_tier') { |
| 77 | + parsed.serviceTier = value; |
| 78 | + } |
| 79 | + continue; |
| 80 | + } |
| 81 | + |
| 82 | + if (key !== 'service_tier') { |
| 83 | + continue; |
| 84 | + } |
| 85 | + |
| 86 | + const profileName = profileNameFromSection(section); |
| 87 | + if (profileName == null) { |
| 88 | + continue; |
| 89 | + } |
| 90 | + |
| 91 | + const profile = parsed.profiles.get(profileName) ?? {}; |
| 92 | + profile.serviceTier = value; |
| 93 | + parsed.profiles.set(profileName, profile); |
| 94 | + } |
| 95 | + |
| 96 | + return parsed; |
| 97 | +} |
| 98 | + |
| 99 | +function isFastServiceTier(serviceTier: string | undefined): boolean { |
| 100 | + const normalized = serviceTier?.trim().toLowerCase(); |
| 101 | + return normalized === 'fast' || normalized === 'priority'; |
| 102 | +} |
| 103 | + |
| 104 | +export function speedFromCodexConfig(content: string): CodexSpeed { |
| 105 | + const parsed = parseCodexConfig(content); |
| 106 | + const profileServiceTier = |
| 107 | + parsed.profile == null ? undefined : parsed.profiles.get(parsed.profile)?.serviceTier; |
| 108 | + return isFastServiceTier(profileServiceTier ?? parsed.serviceTier) ? 'fast' : 'standard'; |
| 109 | +} |
| 110 | + |
| 111 | +export function normalizeSpeedOption(value: unknown): CodexSpeedOption { |
| 112 | + if (value == null || value === '') { |
| 113 | + return 'auto'; |
| 114 | + } |
| 115 | + if (value === 'auto' || value === 'standard' || value === 'fast') { |
| 116 | + return value; |
| 117 | + } |
| 118 | + throw new Error('Invalid --speed value. Use auto, standard, or fast.'); |
| 119 | +} |
| 120 | + |
| 121 | +export async function resolveCodexSpeed(option: CodexSpeedOption): Promise<CodexSpeed> { |
| 122 | + if (option !== 'auto') { |
| 123 | + return option; |
| 124 | + } |
| 125 | + |
| 126 | + const configPath = codexConfigPath(); |
| 127 | + const configResult = await Result.try({ |
| 128 | + try: readFile(configPath, 'utf8'), |
| 129 | + catch: (error) => error, |
| 130 | + }); |
| 131 | + |
| 132 | + if (Result.isFailure(configResult)) { |
| 133 | + logger.debug('Codex config not found or unreadable; using standard pricing', { |
| 134 | + configPath, |
| 135 | + error: configResult.error, |
| 136 | + }); |
| 137 | + return 'standard'; |
| 138 | + } |
| 139 | + |
| 140 | + return speedFromCodexConfig(configResult.value); |
| 141 | +} |
| 142 | + |
| 143 | +if (import.meta.vitest != null) { |
| 144 | + describe('Codex config speed resolution', () => { |
| 145 | + it('detects top-level priority service tier as fast', () => { |
| 146 | + expect(speedFromCodexConfig('service_tier = "priority"')).toBe('fast'); |
| 147 | + }); |
| 148 | + |
| 149 | + it('detects legacy top-level fast service tier as fast', () => { |
| 150 | + expect(speedFromCodexConfig('service_tier = "fast"')).toBe('fast'); |
| 151 | + }); |
| 152 | + |
| 153 | + it('uses the active profile service tier over the top-level service tier', () => { |
| 154 | + const content = [ |
| 155 | + 'profile = "work"', |
| 156 | + 'service_tier = "priority"', |
| 157 | + '', |
| 158 | + '[profiles.work]', |
| 159 | + 'service_tier = "flex"', |
| 160 | + ].join('\n'); |
| 161 | + |
| 162 | + expect(speedFromCodexConfig(content)).toBe('standard'); |
| 163 | + }); |
| 164 | + |
| 165 | + it('defaults to standard when no fast tier is configured', () => { |
| 166 | + expect(speedFromCodexConfig('model = "gpt-5.3-codex"')).toBe('standard'); |
| 167 | + }); |
| 168 | + |
| 169 | + it('validates CLI speed options', () => { |
| 170 | + expect(normalizeSpeedOption(undefined)).toBe('auto'); |
| 171 | + expect(normalizeSpeedOption('fast')).toBe('fast'); |
| 172 | + expect(() => normalizeSpeedOption('slow')).toThrow('Invalid --speed value'); |
| 173 | + }); |
| 174 | + }); |
| 175 | +} |
0 commit comments