-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathRemoteProviderConfiguration.swift
More file actions
481 lines (413 loc) · 17.8 KB
/
RemoteProviderConfiguration.swift
File metadata and controls
481 lines (413 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//
// RemoteProviderConfiguration.swift
// osaurus
//
// Configuration model for remote OpenAI-compatible API providers.
//
import Foundation
// MARK: - Protocol Enum
/// Protocol type for remote provider connections
public enum RemoteProviderProtocol: String, Codable, Sendable, CaseIterable {
case http = "http"
case https = "https"
public var defaultPort: Int {
switch self {
case .http: return 80
case .https: return 443
}
}
}
// MARK: - Authentication Type
/// Authentication type for remote providers
public enum RemoteProviderAuthType: String, Codable, Sendable, CaseIterable {
case none = "none"
case apiKey = "apiKey"
}
// MARK: - Provider Type
/// Type of remote provider (determines API format)
public enum RemoteProviderType: String, Codable, Sendable, CaseIterable {
case openaiLegacy = "openai" // OpenAI-compatible /chat/completions (third-party servers, backward compat)
case anthropic = "anthropic" // Anthropic Messages API
case openResponses = "openResponses" // Open Responses API — used for official OpenAI and any compatible provider
case gemini = "gemini" // Google Gemini API
case osaurus = "osaurus" // Native Osaurus agent — full server-side execution via /agents/{id}/run
// Azure OpenAI uses OpenAI-compatible request/response format but requires:
// - `api-key` header instead of `Authorization: Bearer`
// - URL pattern: https://<resource>.openai.azure.com/openai/deployments/<deployment>/chat/completions?api-version=<version>
case azureOpenAI = "azureOpenAI"
public var displayName: String {
switch self {
case .openaiLegacy: return "OpenAI Compatible"
case .anthropic: return "Anthropic"
case .openResponses: return "Open Responses"
case .gemini: return "Google Gemini"
case .osaurus: return "Osaurus Agent"
case .azureOpenAI: return "Azure OpenAI"
}
}
public var chatEndpoint: String {
switch self {
case .openaiLegacy: return "/chat/completions"
case .anthropic: return "/messages"
case .openResponses: return "/responses"
case .gemini: return "/models" // Actual URL is built dynamically: /models/{model}:generateContent
case .osaurus: return "/run" // Unused — full URL built by RemoteProviderService.buildURLRequest
case .azureOpenAI: return "/chat/completions" // Unused — full URL built by RemoteProviderService.buildURLRequest
}
}
public var modelsEndpoint: String {
// Both use /models but response format differs
return "/models"
}
}
// MARK: - Remote Provider Model
/// Represents a remote API provider configuration
public struct RemoteProvider: Codable, Identifiable, Sendable, Equatable {
public let id: UUID
public var name: String
public var host: String
public var providerProtocol: RemoteProviderProtocol
public var port: Int?
public var basePath: String
public var customHeaders: [String: String]
public var authType: RemoteProviderAuthType
public var providerType: RemoteProviderType
public var enabled: Bool
public var autoConnect: Bool
public var timeout: TimeInterval
// Keys for headers that should be stored in Keychain (not persisted in config)
public var secretHeaderKeys: [String]
/// The UUID of the agent on the remote Osaurus server. Only used when providerType == .osaurus.
public var remoteAgentId: UUID?
// MARK: - Azure OpenAI specific fields
/// Azure OpenAI deployment name (replaces model in the URL path).
/// Only used when providerType == .azureOpenAI.
/// Example: "gpt-4o-deployment"
public var azureDeploymentName: String?
/// Azure OpenAI API version query parameter.
/// Only used when providerType == .azureOpenAI.
/// Defaults to "2024-02-01" if not set.
public var azureAPIVersion: String?
/// Resolved Azure API version, falling back to the stable default.
public var resolvedAzureAPIVersion: String {
azureAPIVersion ?? "2024-02-01"
}
private enum CodingKeys: String, CodingKey {
case id, name, host, providerProtocol, port, basePath
case customHeaders, authType, providerType, enabled, autoConnect, timeout
case secretHeaderKeys, remoteAgentId
case azureDeploymentName, azureAPIVersion
}
public init(
id: UUID = UUID(),
name: String,
host: String,
providerProtocol: RemoteProviderProtocol = .https,
port: Int? = nil,
basePath: String = "/v1",
customHeaders: [String: String] = [:],
authType: RemoteProviderAuthType = .none,
providerType: RemoteProviderType = .openaiLegacy,
enabled: Bool = true,
autoConnect: Bool = true,
timeout: TimeInterval = 60,
secretHeaderKeys: [String] = [],
remoteAgentId: UUID? = nil,
azureDeploymentName: String? = nil,
azureAPIVersion: String? = nil
) {
self.id = id
self.name = name
self.host = host
self.providerProtocol = providerProtocol
self.port = port
self.basePath = basePath
self.customHeaders = customHeaders
self.authType = authType
self.providerType = providerType
self.enabled = enabled
self.autoConnect = autoConnect
self.timeout = timeout
self.secretHeaderKeys = secretHeaderKeys
self.remoteAgentId = remoteAgentId
self.azureDeploymentName = azureDeploymentName
self.azureAPIVersion = azureAPIVersion
}
/// Custom decoder – uses `decodeIfPresent` for backward compatibility with older config files.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
host = try container.decode(String.self, forKey: .host)
providerProtocol =
try container.decodeIfPresent(RemoteProviderProtocol.self, forKey: .providerProtocol) ?? .https
port = try container.decodeIfPresent(Int.self, forKey: .port)
basePath = try container.decodeIfPresent(String.self, forKey: .basePath) ?? "/v1"
customHeaders = try container.decodeIfPresent([String: String].self, forKey: .customHeaders) ?? [:]
authType = try container.decodeIfPresent(RemoteProviderAuthType.self, forKey: .authType) ?? .none
providerType =
try container.decodeIfPresent(RemoteProviderType.self, forKey: .providerType) ?? .openaiLegacy
enabled = try container.decodeIfPresent(Bool.self, forKey: .enabled) ?? true
autoConnect = try container.decodeIfPresent(Bool.self, forKey: .autoConnect) ?? true
timeout = try container.decodeIfPresent(TimeInterval.self, forKey: .timeout) ?? 60
secretHeaderKeys = try container.decodeIfPresent([String].self, forKey: .secretHeaderKeys) ?? []
remoteAgentId = try container.decodeIfPresent(UUID.self, forKey: .remoteAgentId)
azureDeploymentName = try container.decodeIfPresent(String.self, forKey: .azureDeploymentName)
azureAPIVersion = try container.decodeIfPresent(String.self, forKey: .azureAPIVersion)
}
/// Get the effective port (uses protocol default if not specified)
public var effectivePort: Int {
port ?? providerProtocol.defaultPort
}
/// Build the base URL for this provider
public var baseURL: URL? {
var components = URLComponents()
components.scheme = providerProtocol.rawValue
// Parse host - it might contain a path component (e.g., "host/api")
var actualHost = host.trimmingCharacters(in: .whitespaces)
var hostPath = ""
// Check if host contains a path (indicated by a slash after the hostname)
if let slashIndex = actualHost.firstIndex(of: "/") {
hostPath = String(actualHost[slashIndex...]) // e.g., "/api"
actualHost = String(actualHost[..<slashIndex]) // e.g., "host"
}
// Check if host contains a port (e.g., "localhost:8080")
if let colonIndex = actualHost.lastIndex(of: ":"),
let portValue = Int(String(actualHost[actualHost.index(after: colonIndex)...]))
{
// Extract port from host if not already set
if port == nil {
components.port = portValue
}
actualHost = String(actualHost[..<colonIndex])
}
components.host = actualHost
// Only include port if it differs from the protocol default
if let port = port, port != providerProtocol.defaultPort {
components.port = port
}
// Combine any path from host with basePath
var normalizedPath = hostPath + basePath.trimmingCharacters(in: .whitespaces)
if !normalizedPath.hasPrefix("/") {
normalizedPath = "/" + normalizedPath
}
if normalizedPath.hasSuffix("/") {
normalizedPath = String(normalizedPath.dropLast())
}
// Normalize double slashes (e.g., "/api//v1" -> "/api/v1")
while normalizedPath.contains("//") {
normalizedPath = normalizedPath.replacingOccurrences(of: "//", with: "/")
}
components.path = normalizedPath
return components.url
}
/// Build URL for a specific endpoint
public func url(for endpoint: String) -> URL? {
guard let base = baseURL else { return nil }
let normalizedEndpoint = endpoint.hasPrefix("/") ? endpoint : "/" + endpoint
return URL(string: base.absoluteString + normalizedEndpoint)
}
/// Build the full Azure OpenAI chat completions URL for the configured deployment.
///
/// Format: `https://<resource>.openai.azure.com/openai/deployments/<deployment>/chat/completions?api-version=<version>`
///
/// - Returns: The fully constructed URL, or `nil` when `azureDeploymentName` is not set
/// or the host cannot be resolved.
public func azureChatCompletionsURL() -> URL? {
guard let deployment = azureDeploymentName, !deployment.isEmpty else { return nil }
// Build: scheme://host/openai/deployments/<deployment>/chat/completions?api-version=<version>
var components = URLComponents()
components.scheme = providerProtocol.rawValue
// Strip any path from host — Azure resource names never include a path component.
var actualHost = host.trimmingCharacters(in: .whitespaces)
if let slashIndex = actualHost.firstIndex(of: "/") {
actualHost = String(actualHost[..<slashIndex])
}
components.host = actualHost
if let port = port, port != providerProtocol.defaultPort {
components.port = port
}
components.path = "/openai/deployments/\(deployment)/chat/completions"
components.queryItems = [URLQueryItem(name: "api-version", value: resolvedAzureAPIVersion)]
return components.url
}
/// Build the Azure OpenAI models list URL.
///
/// Format: `https://<resource>.openai.azure.com/openai/models?api-version=<version>`
public func azureModelsURL() -> URL? {
var components = URLComponents()
components.scheme = providerProtocol.rawValue
var actualHost = host.trimmingCharacters(in: .whitespaces)
if let slashIndex = actualHost.firstIndex(of: "/") {
actualHost = String(actualHost[..<slashIndex])
}
components.host = actualHost
if let port = port, port != providerProtocol.defaultPort {
components.port = port
}
components.path = "/openai/models"
components.queryItems = [URLQueryItem(name: "api-version", value: resolvedAzureAPIVersion)]
return components.url
}
/// Display string for the endpoint
public var displayEndpoint: String {
// Use the baseURL to get the properly constructed endpoint
if let url = baseURL {
return url.absoluteString
}
// Fallback to manual construction
var result = "\(providerProtocol.rawValue)://\(host)"
if let port = port, port != providerProtocol.defaultPort {
result += ":\(port)"
}
result += basePath
return result
}
/// Get all headers including secret headers from Keychain
public func resolvedHeaders() -> [String: String] {
var headers = customHeaders
// Add secret headers from Keychain
for key in secretHeaderKeys {
if let value = RemoteProviderKeychain.getHeaderSecret(key: key, for: id) {
headers[key] = value
}
}
// Add API key if configured (format differs by provider type)
if authType == .apiKey, let apiKey = getAPIKey(), !apiKey.isEmpty {
switch providerType {
case .anthropic:
if headers["x-api-key"] == nil {
headers["x-api-key"] = apiKey
}
// Add required Anthropic version header if not already set
if headers["anthropic-version"] == nil {
headers["anthropic-version"] = "2023-06-01"
}
case .gemini:
if headers["x-goog-api-key"] == nil {
headers["x-goog-api-key"] = apiKey
}
case .azureOpenAI:
// Azure uses `api-key` header instead of `Authorization: Bearer`
if headers["api-key"] == nil {
headers["api-key"] = apiKey
}
case .openaiLegacy, .openResponses, .osaurus:
if headers["Authorization"] == nil {
headers["Authorization"] = "Bearer \(apiKey)"
}
}
}
return headers
}
/// Check if provider has an API key stored in Keychain
public var hasAPIKey: Bool {
RemoteProviderKeychain.hasAPIKey(for: id)
}
/// Get API key from Keychain
public func getAPIKey() -> String? {
RemoteProviderKeychain.getAPIKey(for: id)
}
}
// MARK: - Remote Provider Runtime State
/// Runtime state for a connected remote provider (not persisted)
public struct RemoteProviderState: Sendable {
public let providerId: UUID
public var isConnected: Bool
public var isConnecting: Bool
public var lastError: String?
public var discoveredModels: [String]
public var lastConnectedAt: Date?
public init(providerId: UUID) {
self.providerId = providerId
self.isConnected = false
self.isConnecting = false
self.lastError = nil
self.discoveredModels = []
self.lastConnectedAt = nil
}
public var modelCount: Int {
discoveredModels.count
}
}
// MARK: - Remote Provider Configuration
/// Collection of remote provider configurations
public struct RemoteProviderConfiguration: Codable, Sendable {
public var providers: [RemoteProvider]
public init(providers: [RemoteProvider] = []) {
self.providers = providers
}
/// Get provider by ID
public func provider(id: UUID) -> RemoteProvider? {
providers.first { $0.id == id }
}
/// Get enabled providers
public var enabledProviders: [RemoteProvider] {
providers.filter { $0.enabled }
}
/// Get providers that should auto-connect
public var autoConnectProviders: [RemoteProvider] {
providers.filter { $0.enabled && $0.autoConnect }
}
/// Add a provider
public mutating func add(_ provider: RemoteProvider) {
providers.append(provider)
}
/// Update a provider
public mutating func update(_ provider: RemoteProvider) {
if let index = providers.firstIndex(where: { $0.id == provider.id }) {
providers[index] = provider
}
}
/// Remove a provider by ID
public mutating func remove(id: UUID) {
// Clean up Keychain secrets
RemoteProviderKeychain.deleteAllSecrets(for: id)
providers.removeAll { $0.id == id }
}
/// Set enabled state for a provider
public mutating func setEnabled(_ enabled: Bool, for id: UUID) {
if let index = providers.firstIndex(where: { $0.id == id }) {
providers[index].enabled = enabled
}
}
}
// MARK: - Remote Provider Configuration Store
/// Persistence for RemoteProviderConfiguration
@MainActor
public enum RemoteProviderConfigurationStore {
public static func load() -> RemoteProviderConfiguration {
let url = configurationFileURL()
guard FileManager.default.fileExists(atPath: url.path) else {
// File doesn't exist yet – create an empty default.
let defaults = RemoteProviderConfiguration()
save(defaults)
return defaults
}
do {
return try JSONDecoder().decode(RemoteProviderConfiguration.self, from: Data(contentsOf: url))
} catch {
// Return empty in-memory config but never overwrite the existing file;
// that would permanently destroy the user's providers.
print("[Osaurus] Failed to load RemoteProviderConfiguration: \(error)")
return RemoteProviderConfiguration()
}
}
public static func save(_ configuration: RemoteProviderConfiguration) {
let url = configurationFileURL()
OsaurusPaths.ensureExistsSilent(url.deletingLastPathComponent())
do {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
try encoder.encode(configuration).write(to: url, options: [.atomic])
} catch {
print("[Osaurus] Failed to save RemoteProviderConfiguration: \(error)")
}
}
private static func configurationFileURL() -> URL {
OsaurusPaths.resolvePath(
new: OsaurusPaths.remoteProviderConfigFile(),
legacy: "RemoteProviderConfiguration.json"
)
}
}