-
Notifications
You must be signed in to change notification settings - Fork 458
feat(codex): support multiple Codex accounts across Codex homes and pi logins #1266
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jal-co
wants to merge
8
commits into
robinebers:main
Choose a base branch
from
jal-co:multi-codex
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
6a29aee
feat(codex): discover multiple Codex accounts from Codex homes and pi
jal-co 2ea5780
fix(shell-env): find the capture marker after a banner without a trai…
jal-co 40d7418
docs(codex): add multi-account screenshots
jal-co c583dcf
fix(codex): address multi-account review feedback
jal-co 328ff5d
fix(codex): address follow-up account review
jal-co 747c1a0
Merge remote-tracking branch 'origin/main' into jal/1266-review-fixes
jal-co a8f6490
fix(codex): refresh pricing for selected account
jal-co bd3ffc4
fix(codex): recalculate pricing for every account
jal-co File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
238 changes: 238 additions & 0 deletions
238
Sources/OpenUsage/Providers/Codex/CodexAccountDiscovery.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| import Foundation | ||
|
|
||
| struct CodexHomeLogin: Equatable, Sendable { | ||
| let home: String | ||
| let identity: CodexAccountIdentity | ||
| let planType: String? | ||
|
|
||
| var authPath: String { home + "/auth.json" } | ||
| } | ||
|
|
||
| struct PiCodexLogin: Equatable, Sendable { | ||
| let providerID: String | ||
| let identity: CodexAccountIdentity | ||
| let planType: String? | ||
| let label: String? | ||
| let authPath: String | ||
| } | ||
|
|
||
| struct CodexAccountDiscovery: Sendable { | ||
| var environment: EnvironmentReading | ||
| var files: TextFileAccessing | ||
| var homeDirectory: @Sendable () -> URL | ||
| var listDirectories: @Sendable (String) -> [String] | ||
|
|
||
| init( | ||
| environment: EnvironmentReading = ProcessEnvironmentReader(), | ||
| files: TextFileAccessing = LocalTextFileAccessor(), | ||
| homeDirectory: @escaping @Sendable () -> URL = { FileManager.default.homeDirectoryForCurrentUser }, | ||
| listDirectories: @escaping @Sendable (String) -> [String] = Self.listSubdirectories | ||
| ) { | ||
| self.environment = environment | ||
| self.files = files | ||
| self.homeDirectory = homeDirectory | ||
| self.listDirectories = listDirectories | ||
| } | ||
|
|
||
| static func listSubdirectories(_ path: String) -> [String] { | ||
| let urls = (try? FileManager.default.contentsOfDirectory( | ||
| at: URL(fileURLWithPath: path), | ||
| includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], | ||
| options: [.skipsHiddenFiles] | ||
| )) ?? [] | ||
| return urls.compactMap { url in | ||
| guard let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]), | ||
| values.isDirectory == true, values.isSymbolicLink != true | ||
| else { return nil } | ||
| return url.lastPathComponent | ||
| } | ||
| } | ||
|
|
||
| static func configuredHomeValues(environment: EnvironmentReading) -> [String] { | ||
| let homes = environment.value(for: "CODEX_HOME")? | ||
| .split(separator: ",") | ||
| .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } | ||
| .filter { !$0.isEmpty } ?? [] | ||
| return homes.isEmpty ? ["~/.config/codex", "~/.codex"] : homes | ||
| } | ||
|
|
||
| static func configuredHomes(environment: EnvironmentReading, homeDirectory: URL) -> [String] { | ||
| uniqueHomes(configuredHomeValues(environment: environment), homeDirectory: homeDirectory) | ||
| } | ||
|
|
||
| func candidateHomes() -> [String] { | ||
| let home = homeDirectory() | ||
| let siblingHomes = listDirectories(home.path) | ||
| .filter { $0.hasPrefix(".codex-") } | ||
| .sorted() | ||
| .map { "~/\($0)" } | ||
| + listDirectories(home.appendingPathComponent(".config").path) | ||
| .filter { $0.hasPrefix("codex-") } | ||
| .sorted() | ||
| .map { "~/.config/\($0)" } | ||
| return Self.uniqueHomes( | ||
| Self.configuredHomes(environment: environment, homeDirectory: home) + ["~/.config/codex", "~/.codex"] + siblingHomes, | ||
| homeDirectory: home | ||
| ) | ||
| } | ||
|
|
||
| func homeLogins(additionalHomes: [String] = []) -> [CodexHomeLogin] { | ||
| let homes = Self.uniqueHomes( | ||
| candidateHomes() + additionalHomes, | ||
| homeDirectory: homeDirectory() | ||
| ) | ||
| return homes.compactMap { home in | ||
| let text: String? | ||
| do { | ||
| text = try files.readTextIfPresent(home + "/auth.json") | ||
| } catch { | ||
| AppLog.warn(.config, "accounts: Codex home \(home) has an unreadable auth.json; skipping it") | ||
| return nil | ||
| } | ||
| guard let text, | ||
| let auth = CodexAuthStore.parseAuth(text), | ||
| auth.tokens?.accessToken?.nilIfEmpty != nil, | ||
| let identity = CodexAccountIdentity(auth: auth) | ||
| else { return nil } | ||
| return CodexHomeLogin( | ||
| home: home, | ||
| identity: identity, | ||
| planType: Self.planType(inTokenPayload: Self.identityPayload(auth)) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| static let piCodexProviderPrefix = "openai-codex" | ||
|
|
||
| static func isPiCodexProvider(_ providerID: String) -> Bool { | ||
| guard providerID.hasPrefix(piCodexProviderPrefix) else { return false } | ||
| let suffix = providerID.dropFirst(piCodexProviderPrefix.count) | ||
| if suffix.isEmpty { return true } | ||
| guard suffix.first == "-" else { return false } | ||
| let digits = suffix.dropFirst() | ||
| return !digits.isEmpty && digits.allSatisfy(\.isNumber) | ||
| } | ||
|
|
||
| func piAgentDirectory() -> String { | ||
| if let configDir = environment.value(for: "PI_CODING_AGENT_DIR")? | ||
| .trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty { | ||
| return Self.expandTilde(configDir, homeDirectory: homeDirectory()).trimmingTrailingSlashes | ||
| } | ||
| return homeDirectory().appendingPathComponent(".pi/agent").path | ||
| } | ||
|
|
||
| func piLogins() -> [PiCodexLogin] { | ||
| let agentDir = piAgentDirectory() | ||
| let authPath = agentDir + "/auth.json" | ||
| let object: [String: Any] | ||
| do { | ||
| guard let text = try files.readTextIfPresent(authPath) else { return [] } | ||
| guard let parsed = try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else { | ||
| AppLog.error(.config, "accounts: pi auth.json is not a JSON object; pi Codex logins skipped") | ||
| return [] | ||
| } | ||
| object = parsed | ||
| } catch { | ||
| AppLog.error(.config, "accounts: pi auth.json could not be read; pi Codex logins skipped") | ||
| return [] | ||
| } | ||
| let labels = piSubscriptionLabels(agentDir: agentDir) | ||
| return object.keys | ||
| .filter(Self.isPiCodexProvider) | ||
| .sorted { Self.piProviderIndex($0) < Self.piProviderIndex($1) } | ||
| .compactMap { providerID in | ||
| guard let auth = Self.piAuth(in: object, providerID: providerID), | ||
| let identity = CodexAccountIdentity(auth: auth), | ||
| CodexAccountIdentity.isComplete(key: identity.key) | ||
| else { return nil } | ||
| return PiCodexLogin( | ||
| providerID: providerID, | ||
| identity: identity, | ||
| planType: Self.planType(inTokenPayload: Self.identityPayload(auth)), | ||
| label: labels[providerID], | ||
| authPath: authPath | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| static func loadPiAuth(files: TextFileAccessing, path: String, providerID: String) -> CodexAuth? { | ||
| guard let text = try? files.readTextIfPresent(path), | ||
| let object = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] | ||
| else { return nil } | ||
| return piAuth(in: object, providerID: providerID) | ||
| } | ||
|
|
||
| static func piProviderIndex(_ providerID: String) -> Int { | ||
| let suffix = providerID.dropFirst(piCodexProviderPrefix.count) | ||
| guard suffix.hasPrefix("-"), let index = Int(suffix.dropFirst()) else { return 1 } | ||
| return index | ||
| } | ||
|
|
||
| static func identityPayload(_ auth: CodexAuth) -> [String: Any]? { | ||
| if let payload = auth.tokens?.idToken.flatMap(ProviderParse.jwtPayload), | ||
| DefaultAccountObserver.chatGPTAccountID(inIDTokenPayload: payload) != nil { | ||
| return payload | ||
| } | ||
| return auth.tokens?.accessToken.flatMap(ProviderParse.jwtPayload) | ||
| ?? auth.tokens?.idToken.flatMap(ProviderParse.jwtPayload) | ||
| } | ||
|
|
||
| static func email(inTokenPayload payload: [String: Any]?) -> String? { | ||
| guard let payload else { return nil } | ||
| let profile = payload["https://api.openai.com/profile"] as? [String: Any] | ||
| return ((profile?["email"] ?? payload["email"]) as? String)? | ||
| .trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty?.lowercased() | ||
| } | ||
|
|
||
| static func planType(inTokenPayload payload: [String: Any]?) -> String? { | ||
| guard let payload else { return nil } | ||
| let authClaim = payload["https://api.openai.com/auth"] as? [String: Any] | ||
| return (authClaim?["chatgpt_plan_type"] as? String)? | ||
| .trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty | ||
| } | ||
|
|
||
| private static func piAuth(in object: [String: Any], providerID: String) -> CodexAuth? { | ||
| guard let entry = object[providerID] as? [String: Any], | ||
| entry["type"] as? String == "oauth", | ||
| let accessToken = (entry["access"] as? String)?.nilIfEmpty | ||
| else { return nil } | ||
| return CodexAuth(tokens: CodexTokens( | ||
| accessToken: accessToken, | ||
| refreshToken: nil, | ||
| idToken: nil, | ||
| accountID: (entry["accountId"] as? String)?.nilIfEmpty | ||
| ), lastRefresh: nil, apiKey: nil) | ||
| } | ||
|
|
||
| private func piSubscriptionLabels(agentDir: String) -> [String: String] { | ||
| guard let text = try? files.readTextIfPresent(agentDir + "/multi-pass.json"), | ||
| let object = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any], | ||
| let subscriptions = object["subscriptions"] as? [[String: Any]] | ||
| else { return [:] } | ||
| var labels: [String: String] = [:] | ||
| for subscription in subscriptions { | ||
| guard subscription["provider"] as? String == Self.piCodexProviderPrefix, | ||
| let index = ProviderParse.number(subscription["index"]).map({ Int($0) }), | ||
| let label = (subscription["label"] as? String)? | ||
| .trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty | ||
| else { continue } | ||
| let providerID = index <= 1 ? Self.piCodexProviderPrefix : "\(Self.piCodexProviderPrefix)-\(index)" | ||
| labels[providerID] = label | ||
| } | ||
| return labels | ||
| } | ||
|
|
||
| private static func uniqueHomes(_ homes: [String], homeDirectory: URL) -> [String] { | ||
| var seen = Set<String>() | ||
| return homes.compactMap { raw in | ||
| let expanded = expandTilde(raw, homeDirectory: homeDirectory).trimmingTrailingSlashes | ||
| let standardized = URL(fileURLWithPath: expanded).standardizedFileURL.path | ||
| return seen.insert(standardized).inserted ? standardized : nil | ||
| } | ||
| } | ||
|
|
||
| private static func expandTilde(_ path: String, homeDirectory: URL) -> String { | ||
| guard path == "~" || path.hasPrefix("~/") else { return path } | ||
| return homeDirectory.path + String(path.dropFirst(1)) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.