|
| 1 | +import Foundation |
| 2 | + |
| 3 | +// MARK: - CodexConfigManager |
| 4 | + |
| 5 | +/// Manages Codex CLI config.toml to toggle between proxy and direct modes. |
| 6 | +public struct CodexConfigManager { |
| 7 | + |
| 8 | + public enum Mode: String, CustomStringConvertible { |
| 9 | + case proxy = "proxy" |
| 10 | + case direct = "direct" |
| 11 | + public var description: String { rawValue } |
| 12 | + } |
| 13 | + |
| 14 | + public enum ConfigError: Error, LocalizedError { |
| 15 | + case configNotFound(String) |
| 16 | + case readFailed(String) |
| 17 | + case writeFailed(String) |
| 18 | + |
| 19 | + public var errorDescription: String? { |
| 20 | + switch self { |
| 21 | + case .configNotFound(let p): return "Codex config not found: \(p)" |
| 22 | + case .readFailed(let m): return "Failed to read config: \(m)" |
| 23 | + case .writeFailed(let m): return "Failed to write config: \(m)" |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + private let configPath: String |
| 29 | + private static let providerKey = "rate_watcher" |
| 30 | + |
| 31 | + // MARK: Init |
| 32 | + |
| 33 | + public init(configPath: String? = nil) { |
| 34 | + if let p = configPath { |
| 35 | + self.configPath = p |
| 36 | + } else { |
| 37 | + let home = FileManager.default.homeDirectoryForCurrentUser.path |
| 38 | + self.configPath = "\(home)/.codex/config.toml" |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // MARK: Public – read |
| 43 | + |
| 44 | + /// The resolved config file path. |
| 45 | + public var path: String { configPath } |
| 46 | + |
| 47 | + /// Detect current mode by scanning for an active `model_provider = "rate_watcher"`. |
| 48 | + public func currentMode() -> Mode { |
| 49 | + guard let content = try? String(contentsOfFile: configPath, encoding: .utf8) else { |
| 50 | + return .direct |
| 51 | + } |
| 52 | + return Self.detectMode(in: content) |
| 53 | + } |
| 54 | + |
| 55 | + // MARK: Public – write |
| 56 | + |
| 57 | + /// Switch Codex to proxy mode (route through rate-watcher proxy). |
| 58 | + @discardableResult |
| 59 | + public func switchTo(proxy port: UInt16 = 19876) throws -> String { |
| 60 | + let content = try readConfig() |
| 61 | + try backup(content) |
| 62 | + var lines = content.components(separatedBy: "\n") |
| 63 | + |
| 64 | + // 1. Comment out every active model_provider line that isn't ours |
| 65 | + for i in 0..<lines.count { |
| 66 | + let t = lines[i].trimmingCharacters(in: .whitespaces) |
| 67 | + guard !t.hasPrefix("#"), t.hasPrefix("model_provider"), t.contains("=") else { continue } |
| 68 | + if !t.contains(Self.providerKey) { |
| 69 | + lines[i] = "# \(lines[i])" |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + // 2. Ensure our provider line is present and uncommented |
| 74 | + if let idx = indexOfLine(containing: Self.providerKey, withPrefix: "model_provider", in: lines) { |
| 75 | + lines[idx] = "model_provider = \"\(Self.providerKey)\"" |
| 76 | + } else { |
| 77 | + let insertAt = insertionPointForProvider(in: lines) |
| 78 | + lines.insert("model_provider = \"\(Self.providerKey)\"", at: insertAt) |
| 79 | + } |
| 80 | + |
| 81 | + // 3. Ensure [model_providers.rate_watcher] section exists |
| 82 | + let joined = lines.joined(separator: "\n") |
| 83 | + if !joined.contains("[model_providers.\(Self.providerKey)]") { |
| 84 | + let section = [ |
| 85 | + "", |
| 86 | + "[model_providers.\(Self.providerKey)]", |
| 87 | + "name = \"Rate Watcher Proxy\"", |
| 88 | + "base_url = \"http://localhost:\(port)\"", |
| 89 | + "wire_api = \"responses\"", |
| 90 | + ] |
| 91 | + let at = insertionPointForSection(in: lines) |
| 92 | + lines.insert(contentsOf: section, at: at) |
| 93 | + } else { |
| 94 | + // Update port in existing section |
| 95 | + updatePort(port, in: &lines) |
| 96 | + } |
| 97 | + |
| 98 | + try writeConfig(lines.joined(separator: "\n")) |
| 99 | + return configPath |
| 100 | + } |
| 101 | + |
| 102 | + /// Switch back to direct / account mode. |
| 103 | + @discardableResult |
| 104 | + public func switchToDirect() throws -> String { |
| 105 | + let content = try readConfig() |
| 106 | + try backup(content) |
| 107 | + var lines = content.components(separatedBy: "\n") |
| 108 | + |
| 109 | + for i in 0..<lines.count { |
| 110 | + let t = lines[i].trimmingCharacters(in: .whitespaces) |
| 111 | + if !t.hasPrefix("#"), t.contains("model_provider"), t.contains(Self.providerKey) { |
| 112 | + lines[i] = "# \(lines[i])" |
| 113 | + break |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + try writeConfig(lines.joined(separator: "\n")) |
| 118 | + return configPath |
| 119 | + } |
| 120 | + |
| 121 | + // MARK: Internal helpers (visible to tests) |
| 122 | + |
| 123 | + static func detectMode(in content: String) -> Mode { |
| 124 | + for line in content.components(separatedBy: "\n") { |
| 125 | + let t = line.trimmingCharacters(in: .whitespaces) |
| 126 | + if !t.hasPrefix("#"), t.hasPrefix("model_provider"), t.contains(providerKey) { |
| 127 | + return .proxy |
| 128 | + } |
| 129 | + } |
| 130 | + return .direct |
| 131 | + } |
| 132 | + |
| 133 | + // MARK: Private |
| 134 | + |
| 135 | + private func readConfig() throws -> String { |
| 136 | + guard FileManager.default.fileExists(atPath: configPath) else { |
| 137 | + throw ConfigError.configNotFound(configPath) |
| 138 | + } |
| 139 | + do { return try String(contentsOfFile: configPath, encoding: .utf8) } |
| 140 | + catch { throw ConfigError.readFailed(error.localizedDescription) } |
| 141 | + } |
| 142 | + |
| 143 | + private func writeConfig(_ content: String) throws { |
| 144 | + do { try content.write(toFile: configPath, atomically: true, encoding: .utf8) } |
| 145 | + catch { throw ConfigError.writeFailed(error.localizedDescription) } |
| 146 | + } |
| 147 | + |
| 148 | + private func backup(_ content: String) throws { |
| 149 | + let fmt = DateFormatter() |
| 150 | + fmt.dateFormat = "yyyy-MM-dd'T'HH-mm-ss" |
| 151 | + try content.write( |
| 152 | + toFile: configPath + ".rw-backup.\(fmt.string(from: Date()))", |
| 153 | + atomically: true, encoding: .utf8 |
| 154 | + ) |
| 155 | + } |
| 156 | + |
| 157 | + /// Find an existing line that contains `keyword` and starts with `prefix`. |
| 158 | + private func indexOfLine(containing keyword: String, withPrefix prefix: String, in lines: [String]) -> Int? { |
| 159 | + for i in 0..<lines.count { |
| 160 | + let t = lines[i].trimmingCharacters(in: .whitespaces) |
| 161 | + .replacingOccurrences(of: "# ", with: "") |
| 162 | + .replacingOccurrences(of: "#", with: "") |
| 163 | + if t.hasPrefix(prefix), t.contains(keyword) { return i } |
| 164 | + } |
| 165 | + return nil |
| 166 | + } |
| 167 | + |
| 168 | + /// Best line to insert `model_provider = ...` (right after the `model = ...` line). |
| 169 | + private func insertionPointForProvider(in lines: [String]) -> Int { |
| 170 | + for i in 0..<lines.count { |
| 171 | + let t = lines[i].trimmingCharacters(in: .whitespaces) |
| 172 | + if !t.hasPrefix("#"), t.hasPrefix("model "), t.contains("=") { return i + 1 } |
| 173 | + } |
| 174 | + return min(1, lines.count) |
| 175 | + } |
| 176 | + |
| 177 | + /// Best line to insert the `[model_providers.rate_watcher]` section. |
| 178 | + private func insertionPointForSection(in lines: [String]) -> Int { |
| 179 | + var lastProviderEnd = -1 |
| 180 | + for i in 0..<lines.count { |
| 181 | + if lines[i].hasPrefix("[model_providers.") { |
| 182 | + var j = i + 1 |
| 183 | + while j < lines.count, !lines[j].hasPrefix("[") { j += 1 } |
| 184 | + lastProviderEnd = j |
| 185 | + } |
| 186 | + } |
| 187 | + if lastProviderEnd > 0 { return lastProviderEnd } |
| 188 | + |
| 189 | + // Fallback: insert before first non-model top-level section |
| 190 | + for i in 0..<lines.count { |
| 191 | + let l = lines[i] |
| 192 | + if l.hasPrefix("[projects.") || l.hasPrefix("[notice") || l.hasPrefix("[memories") |
| 193 | + || l.hasPrefix("[mcp_servers") || l.hasPrefix("[sandbox") || l.hasPrefix("[features") |
| 194 | + { |
| 195 | + return i |
| 196 | + } |
| 197 | + } |
| 198 | + return lines.count |
| 199 | + } |
| 200 | + |
| 201 | + /// Update `base_url` inside the `[model_providers.rate_watcher]` section. |
| 202 | + private func updatePort(_ port: UInt16, in lines: inout [String]) { |
| 203 | + var inSection = false |
| 204 | + for i in 0..<lines.count { |
| 205 | + if lines[i].contains("[model_providers.\(Self.providerKey)]") { |
| 206 | + inSection = true; continue |
| 207 | + } |
| 208 | + if inSection, lines[i].hasPrefix("[") { break } |
| 209 | + if inSection, lines[i].contains("base_url") { |
| 210 | + lines[i] = "base_url = \"http://localhost:\(port)\"" |
| 211 | + break |
| 212 | + } |
| 213 | + } |
| 214 | + } |
| 215 | +} |
0 commit comments