-
Notifications
You must be signed in to change notification settings - Fork 322
feat: Add OpenRouter provider for credit-based usage tracking #298
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
chountalas
wants to merge
2
commits into
steipete:main
Choose a base branch
from
chountalas:feature/openrouter-provider
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 all commits
Commits
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
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
56 changes: 56 additions & 0 deletions
56
Sources/CodexBar/Providers/OpenRouter/OpenRouterProviderImplementation.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,56 @@ | ||
| import AppKit | ||
| import CodexBarCore | ||
| import CodexBarMacroSupport | ||
| import Foundation | ||
| import SwiftUI | ||
|
|
||
| @ProviderImplementationRegistration | ||
| struct OpenRouterProviderImplementation: ProviderImplementation { | ||
| let id: UsageProvider = .openrouter | ||
|
|
||
| @MainActor | ||
| func presentation(context _: ProviderPresentationContext) -> ProviderPresentation { | ||
| ProviderPresentation { _ in "api" } | ||
| } | ||
|
|
||
| @MainActor | ||
| func observeSettings(_ settings: SettingsStore) { | ||
| _ = settings.openRouterAPIToken | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsSnapshot(context: ProviderSettingsSnapshotContext) -> ProviderSettingsSnapshotContribution? { | ||
| _ = context | ||
| return nil | ||
| } | ||
|
|
||
| @MainActor | ||
| func isAvailable(context: ProviderAvailabilityContext) -> Bool { | ||
| if OpenRouterSettingsReader.apiToken(environment: context.environment) != nil { | ||
| return true | ||
| } | ||
| context.settings.ensureOpenRouterAPITokenLoaded() | ||
| return !context.settings.openRouterAPIToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsPickers(context _: ProviderSettingsContext) -> [ProviderSettingsPickerDescriptor] { | ||
| [] | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsFields(context: ProviderSettingsContext) -> [ProviderSettingsFieldDescriptor] { | ||
| [ | ||
| ProviderSettingsFieldDescriptor( | ||
| id: "openrouter-api-key", | ||
| title: "API key", | ||
| subtitle: "Stored in ~/.codexbar/config.json. Get your key from openrouter.ai/settings/keys.", | ||
| kind: .secure, | ||
| placeholder: "sk-or-v1-...", | ||
| binding: context.stringBinding(\.openRouterAPIToken), | ||
| actions: [], | ||
| isVisible: nil, | ||
| onActivate: { context.settings.ensureOpenRouterAPITokenLoaded() }), | ||
| ] | ||
| } | ||
| } |
16 changes: 16 additions & 0 deletions
16
Sources/CodexBar/Providers/OpenRouter/OpenRouterSettingsStore.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,16 @@ | ||
| import CodexBarCore | ||
| import Foundation | ||
|
|
||
| extension SettingsStore { | ||
| var openRouterAPIToken: String { | ||
| get { self.configSnapshot.providerConfig(for: .openrouter)?.sanitizedAPIKey ?? "" } | ||
| set { | ||
| self.updateProviderConfig(provider: .openrouter) { entry in | ||
| entry.apiKey = self.normalizedConfigValue(newValue) | ||
| } | ||
| self.logSecretUpdate(provider: .openrouter, field: "apiKey", value: newValue) | ||
| } | ||
| } | ||
|
|
||
| func ensureOpenRouterAPITokenLoaded() {} | ||
| } |
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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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
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
83 changes: 83 additions & 0 deletions
83
Sources/CodexBarCore/Providers/OpenRouter/OpenRouterProviderDescriptor.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,83 @@ | ||
| import CodexBarMacroSupport | ||
| import Foundation | ||
|
|
||
| @ProviderDescriptorRegistration | ||
| @ProviderDescriptorDefinition | ||
| public enum OpenRouterProviderDescriptor { | ||
| static func makeDescriptor() -> ProviderDescriptor { | ||
| ProviderDescriptor( | ||
| id: .openrouter, | ||
| metadata: ProviderMetadata( | ||
| id: .openrouter, | ||
| displayName: "OpenRouter", | ||
| sessionLabel: "Credits", | ||
| weeklyLabel: "Usage", | ||
| opusLabel: nil, | ||
| supportsOpus: false, | ||
| supportsCredits: true, | ||
| creditsHint: "Credit balance from OpenRouter API", | ||
| toggleTitle: "Show OpenRouter usage", | ||
| cliName: "openrouter", | ||
| defaultEnabled: false, | ||
| isPrimaryProvider: false, | ||
| usesAccountFallback: false, | ||
| dashboardURL: "https://openrouter.ai/settings/credits", | ||
| statusPageURL: nil, | ||
| statusLinkURL: "https://status.openrouter.ai"), | ||
| branding: ProviderBranding( | ||
| iconStyle: .openrouter, | ||
| iconResourceName: "ProviderIcon-openrouter", | ||
| color: ProviderColor(red: 111 / 255, green: 66 / 255, blue: 193 / 255)), | ||
| tokenCost: ProviderTokenCostConfig( | ||
| supportsTokenCost: false, | ||
| noDataMessage: { "OpenRouter cost summary is not yet supported." }), | ||
| fetchPlan: ProviderFetchPlan( | ||
| sourceModes: [.auto, .api], | ||
| pipeline: ProviderFetchPipeline(resolveStrategies: { _ in [OpenRouterAPIFetchStrategy()] })), | ||
| cli: ProviderCLIConfig( | ||
| name: "openrouter", | ||
| aliases: ["or"], | ||
| versionDetector: nil)) | ||
| } | ||
| } | ||
|
|
||
| struct OpenRouterAPIFetchStrategy: ProviderFetchStrategy { | ||
| let id: String = "openrouter.api" | ||
| let kind: ProviderFetchKind = .apiToken | ||
|
|
||
| func isAvailable(_ context: ProviderFetchContext) async -> Bool { | ||
| Self.resolveToken(environment: context.env) != nil | ||
| } | ||
|
|
||
| func fetch(_ context: ProviderFetchContext) async throws -> ProviderFetchResult { | ||
| guard let apiKey = Self.resolveToken(environment: context.env) else { | ||
| throw OpenRouterSettingsError.missingToken | ||
| } | ||
| let usage = try await OpenRouterUsageFetcher.fetchUsage( | ||
| apiKey: apiKey, | ||
| environment: context.env) | ||
| return self.makeResult( | ||
| usage: usage.toUsageSnapshot(), | ||
| sourceLabel: "api") | ||
| } | ||
|
|
||
| func shouldFallback(on _: Error, context _: ProviderFetchContext) -> Bool { | ||
| false | ||
| } | ||
|
|
||
| private static func resolveToken(environment: [String: String]) -> String? { | ||
| ProviderTokenResolver.openRouterToken(environment: environment) | ||
| } | ||
| } | ||
|
|
||
| /// Errors related to OpenRouter settings | ||
| public enum OpenRouterSettingsError: LocalizedError, Sendable { | ||
| case missingToken | ||
|
|
||
| public var errorDescription: String? { | ||
| switch self { | ||
| case .missingToken: | ||
| "OpenRouter API token not configured. Set OPENROUTER_API_KEY environment variable or configure in Settings." | ||
| } | ||
| } | ||
| } | ||
38 changes: 38 additions & 0 deletions
38
Sources/CodexBarCore/Providers/OpenRouter/OpenRouterSettingsReader.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,38 @@ | ||
| import Foundation | ||
|
|
||
| /// Reads OpenRouter settings from environment variables | ||
| public enum OpenRouterSettingsReader { | ||
| /// Environment variable key for OpenRouter API token | ||
| public static let envKey = "OPENROUTER_API_KEY" | ||
|
|
||
| /// Returns the API token from environment if present and non-empty | ||
| public static func apiToken(environment: [String: String] = ProcessInfo.processInfo.environment) -> String? { | ||
| cleaned(environment[envKey]) | ||
| } | ||
|
|
||
| /// Returns the API URL, defaulting to production endpoint | ||
| public static func apiURL(environment: [String: String] = ProcessInfo.processInfo.environment) -> URL { | ||
| if let override = environment["OPENROUTER_API_URL"], | ||
| let url = URL(string: cleaned(override) ?? "") | ||
| { | ||
| return url | ||
| } | ||
| return URL(string: "https://openrouter.ai/api/v1")! | ||
| } | ||
|
|
||
| static func cleaned(_ raw: String?) -> String? { | ||
| guard var value = raw?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { | ||
| return nil | ||
| } | ||
|
|
||
| if (value.hasPrefix("\"") && value.hasSuffix("\"")) || | ||
| (value.hasPrefix("'") && value.hasSuffix("'")) | ||
| { | ||
| value.removeFirst() | ||
| value.removeLast() | ||
| } | ||
|
|
||
| value = value.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| return value.isEmpty ? nil : value | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This strategy only resolves the token from
context.envviaProviderTokenResolver.openRouterToken, which readsOPENROUTER_API_KEY. The UI stores the key in config.json (OpenRouterSettingsStore), butProviderConfigEnvironment.applyAPIKeyOverridedoesn’t map.openrouter, so the saved key never reachescontext.env. As a result, users who configure the API key in Settings (and don’t export the env var) will see the provider marked available but every fetch fails withmissingToken.Useful? React with 👍 / 👎.