-
Notifications
You must be signed in to change notification settings - Fork 743
feat: add Mistral AI as a new provider #607
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
welcoMattic
wants to merge
2
commits into
steipete:main
Choose a base branch
from
welcoMattic:main
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.
+1,040
−9
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
106 changes: 106 additions & 0 deletions
106
Sources/CodexBar/Providers/Mistral/MistralProviderImplementation.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,106 @@ | ||
| import AppKit | ||
| import CodexBarCore | ||
| import CodexBarMacroSupport | ||
| import Foundation | ||
| import SwiftUI | ||
|
|
||
| @ProviderImplementationRegistration | ||
| struct MistralProviderImplementation: ProviderImplementation { | ||
| let id: UsageProvider = .mistral | ||
|
|
||
| @MainActor | ||
| func presentation(context _: ProviderPresentationContext) -> ProviderPresentation { | ||
| ProviderPresentation { _ in "web" } | ||
| } | ||
|
|
||
| @MainActor | ||
| func observeSettings(_ settings: SettingsStore) { | ||
| _ = settings.mistralCookieSource | ||
| _ = settings.mistralCookieHeader | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsSnapshot(context: ProviderSettingsSnapshotContext) -> ProviderSettingsSnapshotContribution? { | ||
| .mistral(context.settings.mistralSettingsSnapshot(tokenOverride: context.tokenOverride)) | ||
| } | ||
|
|
||
| @MainActor | ||
| func tokenAccountsVisibility(context: ProviderSettingsContext, support: TokenAccountSupport) -> Bool { | ||
| guard support.requiresManualCookieSource else { return true } | ||
| if !context.settings.tokenAccounts(for: context.provider).isEmpty { return true } | ||
| return context.settings.mistralCookieSource == .manual | ||
| } | ||
|
|
||
| @MainActor | ||
| func applyTokenAccountCookieSource(settings: SettingsStore) { | ||
| if settings.mistralCookieSource != .manual { | ||
| settings.mistralCookieSource = .manual | ||
| } | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsPickers(context: ProviderSettingsContext) -> [ProviderSettingsPickerDescriptor] { | ||
| let cookieBinding = Binding( | ||
| get: { context.settings.mistralCookieSource.rawValue }, | ||
| set: { raw in | ||
| context.settings.mistralCookieSource = ProviderCookieSource(rawValue: raw) ?? .auto | ||
| }) | ||
| let cookieOptions = ProviderCookieSourceUI.options( | ||
| allowsOff: false, | ||
| keychainDisabled: context.settings.debugDisableKeychainAccess) | ||
|
|
||
| let cookieSubtitle: () -> String? = { | ||
| ProviderCookieSourceUI.subtitle( | ||
| source: context.settings.mistralCookieSource, | ||
| keychainDisabled: context.settings.debugDisableKeychainAccess, | ||
| auto: "Automatic imports browser cookies from admin.mistral.ai.", | ||
| manual: "Paste a Cookie header captured from the billing page.", | ||
| off: "Mistral cookies are disabled.") | ||
| } | ||
|
|
||
| return [ | ||
| ProviderSettingsPickerDescriptor( | ||
| id: "mistral-cookie-source", | ||
| title: "Cookie source", | ||
| subtitle: "Automatic imports browser cookies from admin.mistral.ai.", | ||
| dynamicSubtitle: cookieSubtitle, | ||
| binding: cookieBinding, | ||
| options: cookieOptions, | ||
| isVisible: nil, | ||
| onChange: nil, | ||
| trailingText: { | ||
| guard let entry = CookieHeaderCache.load(provider: .mistral) else { return nil } | ||
| let when = entry.storedAt.relativeDescription() | ||
| return "Cached: \(entry.sourceLabel) • \(when)" | ||
| }), | ||
| ] | ||
| } | ||
|
|
||
| @MainActor | ||
| func settingsFields(context: ProviderSettingsContext) -> [ProviderSettingsFieldDescriptor] { | ||
| [ | ||
| ProviderSettingsFieldDescriptor( | ||
| id: "mistral-cookie-header", | ||
| title: "Cookie header", | ||
| subtitle: "Paste the Cookie header from a request to admin.mistral.ai. " | ||
| + "Must contain an ory_session_* cookie.", | ||
| kind: .secure, | ||
| placeholder: "ory_session_…=…; csrftoken=…", | ||
| binding: context.stringBinding(\.mistralCookieHeader), | ||
| actions: [ | ||
| ProviderSettingsActionDescriptor( | ||
| id: "mistral-open-console", | ||
| title: "Open Mistral Admin", | ||
| style: .link, | ||
| isVisible: nil, | ||
| perform: { | ||
| if let url = URL(string: "https://admin.mistral.ai/organization/usage") { | ||
| NSWorkspace.shared.open(url) | ||
| } | ||
| }), | ||
| ], | ||
| isVisible: { context.settings.mistralCookieSource == .manual }, | ||
| onActivate: nil), | ||
| ] | ||
| } | ||
| } |
64 changes: 64 additions & 0 deletions
64
Sources/CodexBar/Providers/Mistral/MistralSettingsStore.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,64 @@ | ||
| import CodexBarCore | ||
| import Foundation | ||
|
|
||
| extension SettingsStore { | ||
| var mistralCookieHeader: String { | ||
| get { self.configSnapshot.providerConfig(for: .mistral)?.sanitizedCookieHeader ?? "" } | ||
| set { | ||
| self.updateProviderConfig(provider: .mistral) { entry in | ||
| entry.cookieHeader = self.normalizedConfigValue(newValue) | ||
| } | ||
| self.logSecretUpdate(provider: .mistral, field: "cookieHeader", value: newValue) | ||
| } | ||
| } | ||
|
|
||
| var mistralCookieSource: ProviderCookieSource { | ||
| get { self.resolvedCookieSource(provider: .mistral, fallback: .auto) } | ||
| set { | ||
| self.updateProviderConfig(provider: .mistral) { entry in | ||
| entry.cookieSource = newValue | ||
| } | ||
| self.logProviderModeChange(provider: .mistral, field: "cookieSource", value: newValue.rawValue) | ||
| } | ||
| } | ||
|
|
||
| func ensureMistralCookieLoaded() {} | ||
| } | ||
|
|
||
| extension SettingsStore { | ||
| func mistralSettingsSnapshot(tokenOverride: TokenAccountOverride?) -> ProviderSettingsSnapshot | ||
| .MistralProviderSettings | ||
| { | ||
| ProviderSettingsSnapshot.MistralProviderSettings( | ||
| cookieSource: self.mistralSnapshotCookieSource(tokenOverride: tokenOverride), | ||
| manualCookieHeader: self.mistralSnapshotCookieHeader(tokenOverride: tokenOverride)) | ||
| } | ||
|
|
||
| private func mistralSnapshotCookieHeader(tokenOverride: TokenAccountOverride?) -> String { | ||
| let fallback = self.mistralCookieHeader | ||
| guard let support = TokenAccountSupportCatalog.support(for: .mistral), | ||
| case .cookieHeader = support.injection | ||
| else { | ||
| return fallback | ||
| } | ||
| guard let account = ProviderTokenAccountSelection.selectedAccount( | ||
| provider: .mistral, | ||
| settings: self, | ||
| override: tokenOverride) | ||
| else { | ||
| return fallback | ||
| } | ||
| return TokenAccountSupportCatalog.normalizedCookieHeader(account.token, support: support) | ||
| } | ||
|
|
||
| private func mistralSnapshotCookieSource(tokenOverride: TokenAccountOverride?) -> ProviderCookieSource { | ||
| let fallback = self.mistralCookieSource | ||
| guard let support = TokenAccountSupportCatalog.support(for: .mistral), | ||
| support.requiresManualCookieSource | ||
| else { | ||
| return fallback | ||
| } | ||
| if self.tokenAccounts(for: .mistral).isEmpty { return fallback } | ||
| return .manual | ||
| } | ||
| } | ||
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
101 changes: 101 additions & 0 deletions
101
Sources/CodexBarCore/Providers/Mistral/MistralCookieImporter.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,101 @@ | ||
| import Foundation | ||
|
|
||
| #if os(macOS) | ||
| import SweetCookieKit | ||
|
|
||
| private let mistralCookieImportOrder: BrowserCookieImportOrder = | ||
| ProviderDefaults.metadata[.mistral]?.browserCookieOrder ?? Browser.defaultImportOrder | ||
|
|
||
| public enum MistralCookieImporter { | ||
| private static let cookieClient = BrowserCookieClient() | ||
| private static let cookieDomains = ["mistral.ai", "admin.mistral.ai", "auth.mistral.ai"] | ||
|
|
||
| public struct SessionInfo: Sendable { | ||
| public let cookies: [HTTPCookie] | ||
| public let sourceLabel: String | ||
|
|
||
| public init(cookies: [HTTPCookie], sourceLabel: String) { | ||
| self.cookies = cookies | ||
| self.sourceLabel = sourceLabel | ||
| } | ||
|
|
||
| public var cookieHeader: String { | ||
| self.cookies.map { "\($0.name)=\($0.value)" }.joined(separator: "; ") | ||
| } | ||
|
|
||
| /// Extracts the CSRF token from the `csrftoken` cookie for the `X-CSRFTOKEN` header. | ||
| public var csrfToken: String? { | ||
| self.cookies.first { $0.name == "csrftoken" }?.value | ||
| } | ||
| } | ||
|
|
||
| /// Returns `true` if any cookie name starts with `ory_session_` (the Ory Kratos session cookie). | ||
| private static func hasSessionCookie(_ cookies: [HTTPCookie]) -> Bool { | ||
| cookies.contains { $0.name.hasPrefix("ory_session_") } | ||
| } | ||
|
|
||
| public static func importSession( | ||
| browserDetection: BrowserDetection, | ||
| preferredBrowsers: [Browser] = [.chrome], | ||
| logger: ((String) -> Void)? = nil) throws -> SessionInfo | ||
| { | ||
| let log: (String) -> Void = { msg in logger?("[mistral-cookie] \(msg)") } | ||
| let installedBrowsers = preferredBrowsers.isEmpty | ||
| ? mistralCookieImportOrder.cookieImportCandidates(using: browserDetection) | ||
| : preferredBrowsers.cookieImportCandidates(using: browserDetection) | ||
|
|
||
| for browserSource in installedBrowsers { | ||
| do { | ||
| let query = BrowserCookieQuery(domains: self.cookieDomains) | ||
| let sources = try Self.cookieClient.records( | ||
| matching: query, | ||
| in: browserSource, | ||
| logger: log) | ||
| for source in sources where !source.records.isEmpty { | ||
| let httpCookies = BrowserCookieClient.makeHTTPCookies(source.records, origin: query.origin) | ||
| if !httpCookies.isEmpty { | ||
| guard Self.hasSessionCookie(httpCookies) else { | ||
| log("Skipping \(source.label) cookies: missing ory_session_* cookie") | ||
| continue | ||
| } | ||
| log("Found \(httpCookies.count) Mistral cookies in \(source.label)") | ||
| return SessionInfo(cookies: httpCookies, sourceLabel: source.label) | ||
| } | ||
| } | ||
| } catch { | ||
| BrowserCookieAccessGate.recordIfNeeded(error) | ||
| log("\(browserSource.displayName) cookie import failed: \(error.localizedDescription)") | ||
| } | ||
| } | ||
|
|
||
| throw MistralCookieImportError.noCookies | ||
| } | ||
|
|
||
| public static func hasSession( | ||
| browserDetection: BrowserDetection, | ||
| preferredBrowsers: [Browser] = [.chrome], | ||
| logger: ((String) -> Void)? = nil) -> Bool | ||
| { | ||
| do { | ||
| _ = try self.importSession( | ||
| browserDetection: browserDetection, | ||
| preferredBrowsers: preferredBrowsers, | ||
| logger: logger) | ||
| return true | ||
| } catch { | ||
| return false | ||
| } | ||
| } | ||
| } | ||
|
|
||
| enum MistralCookieImportError: LocalizedError { | ||
| case noCookies | ||
|
|
||
| var errorDescription: String? { | ||
| switch self { | ||
| case .noCookies: | ||
| "No Mistral session cookies found in browsers." | ||
| } | ||
| } | ||
| } | ||
| #endif |
35 changes: 35 additions & 0 deletions
35
Sources/CodexBarCore/Providers/Mistral/MistralErrors.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,35 @@ | ||
| import Foundation | ||
|
|
||
| public enum MistralUsageError: LocalizedError, Sendable { | ||
| case missingCookie | ||
| case invalidCredentials | ||
| case apiError(String) | ||
| case parseFailed(String) | ||
|
|
||
| public var errorDescription: String? { | ||
| switch self { | ||
| case .missingCookie: | ||
| "No Mistral session cookies found in browsers." | ||
| case .invalidCredentials: | ||
| "Mistral session expired or invalid (HTTP 401/403)." | ||
| case let .apiError(detail): | ||
| "Mistral API error: \(detail)" | ||
| case let .parseFailed(detail): | ||
| "Failed to parse Mistral billing response: \(detail)" | ||
| } | ||
| } | ||
| } | ||
|
|
||
| enum MistralSettingsError: LocalizedError { | ||
| case missingCookie | ||
| case invalidCookie | ||
|
|
||
| var errorDescription: String? { | ||
| switch self { | ||
| case .missingCookie: | ||
| "No Mistral session cookies found in browsers." | ||
| case .invalidCookie: | ||
| "Mistral cookie header is invalid or missing ory_session cookie." | ||
| } | ||
| } | ||
| } |
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.