From 1e0c334ec0e16f4881654325ce458b40ccee03c6 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:16:49 -0600 Subject: [PATCH 1/5] Add OpenCode Go reader, declarative endpoint plugins, and UI/perf review fixes (Refs OPS-1122) - OpenCode Go: documented usage endpoint via the CLI's local auth file - Endpoint plugins: validated JSON descriptors in the Plugins folder, generic bounded reader, SSRF gate, Settings toggles without recompiling - Alibaba/MiMo/Qwen verified against #554/#555 (already on main), docs updated - UI: sentenceGap, accent-ink shortcut, logo fallback from reader list, PiP keyboard/VoiceOver access, larger tertiary labels, keyboard splitter, popup no longer auto-expires for VoiceOver/Reduce Motion, right-click hint - Perf: snapshot-write chain predecessor deadline surfaces a stuck write instead of stalling silently; v2 publisher retries transient 502/503/504 --- Sources/CodeCaps/AppDelegate.swift | 2 +- Sources/CodeCaps/BrandMark.swift | 7 +- Sources/CodeCaps/ConsoleViews.swift | 14 +- Sources/CodeCaps/ExhaustionPopupView.swift | 7 + Sources/CodeCaps/GlanceViews.swift | 6 +- Sources/CodeCaps/MonitorModel.swift | 37 ++- Sources/CodeCaps/PipWidget.swift | 17 +- Sources/CodeCaps/RunawayAlertsView.swift | 6 +- Sources/CodeCaps/SettingsViews.swift | 24 +- Sources/CodeCaps/UsageHistoryViews.swift | 2 +- .../QuotaCore/EndpointPluginDescriptor.swift | 252 ++++++++++++++++++ Sources/QuotaCore/EndpointPluginLoader.swift | 60 +++++ .../GenericEndpointQuotaReader.swift | 131 +++++++++ .../QuotaCore/LocalQuotaReaderRegistry.swift | 11 +- Sources/QuotaCore/OpenCodeGoQuotaReader.swift | 170 ++++++++++++ Sources/QuotaCore/QuotaModels.swift | 1 + Sources/QuotaCore/QuotaPublisher.swift | 31 +++ .../SnapshotWriteDrainTests.swift | 8 + .../QuotaCoreTests/EndpointPluginTests.swift | 120 +++++++++ .../OpenCodeGoQuotaReaderTests.swift | 82 ++++++ .../QuotaCoreTests/QuotaPublisherTests.swift | 44 +++ docs/ENDPOINT-PLUGINS.md | 73 +++++ docs/TOKEN-PLAN-SOURCES.md | 20 ++ 23 files changed, 1095 insertions(+), 30 deletions(-) create mode 100644 Sources/QuotaCore/EndpointPluginDescriptor.swift create mode 100644 Sources/QuotaCore/EndpointPluginLoader.swift create mode 100644 Sources/QuotaCore/GenericEndpointQuotaReader.swift create mode 100644 Sources/QuotaCore/OpenCodeGoQuotaReader.swift create mode 100644 Tests/QuotaCoreTests/EndpointPluginTests.swift create mode 100644 Tests/QuotaCoreTests/OpenCodeGoQuotaReaderTests.swift create mode 100644 docs/ENDPOINT-PLUGINS.md diff --git a/Sources/CodeCaps/AppDelegate.swift b/Sources/CodeCaps/AppDelegate.swift index 99f298b2..a10ce215 100644 --- a/Sources/CodeCaps/AppDelegate.swift +++ b/Sources/CodeCaps/AppDelegate.swift @@ -537,7 +537,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe button.title = " \(title)" } - button.toolTip = "CodeCaps · \(detail)" + button.toolTip = "CodeCaps · \(detail) — right-click for commands" button.setAccessibilityLabel("CodeCaps, \(detail)") } diff --git a/Sources/CodeCaps/BrandMark.swift b/Sources/CodeCaps/BrandMark.swift index 6463ebb7..99d91668 100644 --- a/Sources/CodeCaps/BrandMark.swift +++ b/Sources/CodeCaps/BrandMark.swift @@ -9,10 +9,9 @@ import SwiftUI /// show the real mark instead of a stand-in. /// /// The menu bar keeps the owner's own black template icon, which is what that -/// artwork is for and where it belongs. The PiP widget header and the Glance -/// popover header keep that same black template on purpose, so the template -/// mark still appears in the menu bar and in those two headers, and nowhere -/// else. +/// artwork is for and where it belongs. The Glance popover header shows the +/// colour mark on its light ground (see `GlanceBrandMark`), so the template +/// mark itself appears only in the menu bar. public enum BrandMarkImage { /// The mark, loaded once. The asset is a required, bundled resource: /// `BrandAssetTests` fails the test suite, and so CI, if the bundle ever diff --git a/Sources/CodeCaps/ConsoleViews.swift b/Sources/CodeCaps/ConsoleViews.swift index 19bbddeb..74771d89 100644 --- a/Sources/CodeCaps/ConsoleViews.swift +++ b/Sources/CodeCaps/ConsoleViews.swift @@ -337,7 +337,7 @@ struct ConsoleView: View { .accessibilityHidden(true) } if let unavailable = state.unavailableAlert { - Text("Alert source unavailable: \(unavailable.providerKey)\(unavailable.windowId.map { " · \($0)" } ?? ""). Check Sources & Fleet for this provider.") + Text("Alert source unavailable: \(unavailable.providerKey)\(unavailable.windowId.map { " · \($0)" } ?? "") + "\(sentenceGap)Check Sources & Fleet for this provider.") .font(.callout) .foregroundStyle(Theme.warning) .padding(.horizontal, Metrics.pagePadding) @@ -448,6 +448,10 @@ private struct ConsoleSidebarSplitter: View { @State private var isHovering = false @State private var dragStart: CGFloat? + private func persistWidth() { + UserDefaults.standard.set(Double(width), forKey: "consoleSidebarWidth") + } + var body: some View { ZStack { Rectangle() @@ -488,6 +492,14 @@ private struct ConsoleSidebarSplitter: View { // owner picked, so the grabber glowed system blue next to an accent // that was doing everything else in the sidebar. .background(isHovering ? Theme.accent.opacity(0.15) : Color.clear) + // The drag is pointer-only, so the same resize is offered to the + // keyboard: focus the splitter and use the arrow keys. + .focusable() + .onKeyPress(.leftArrow) { width = max(Metrics.sidebarWidthMin, width - 8); persistWidth(); return .handled } + .onKeyPress(.rightArrow) { width = min(Metrics.sidebarWidthMax, width + 8); persistWidth(); return .handled } + .accessibilityLabel("Sidebar width") + .accessibilityValue("\(Int(width)) points") + .accessibilityHint("Use the left and right arrow keys to resize the sidebar") } } diff --git a/Sources/CodeCaps/ExhaustionPopupView.swift b/Sources/CodeCaps/ExhaustionPopupView.swift index 245837be..e500dbac 100644 --- a/Sources/CodeCaps/ExhaustionPopupView.swift +++ b/Sources/CodeCaps/ExhaustionPopupView.swift @@ -141,6 +141,13 @@ final class ExhaustionPopupController { private func scheduleExpiry(for id: UUID) { expireTask?.cancel() + // A warning that vanishes on a timer can disappear before a + // VoiceOver or Reduce Motion user has read it; for them it stays + // until dismissed. + if NSWorkspace.shared.isVoiceOverEnabled || NSWorkspace.shared.accessibilityDisplayShouldReduceMotion { + expireTask = nil + return + } expireTask = Task { @MainActor [weak self] in try? await Task.sleep(nanoseconds: UInt64(Self.autoExpire * 1_000_000_000)) guard !Task.isCancelled, let self, self.shownId == id else { return } diff --git a/Sources/CodeCaps/GlanceViews.swift b/Sources/CodeCaps/GlanceViews.swift index 5829fa07..59f53478 100644 --- a/Sources/CodeCaps/GlanceViews.swift +++ b/Sources/CodeCaps/GlanceViews.swift @@ -384,7 +384,7 @@ struct GlancePopover: View { Text("Open CodeCaps") Text("⌘1") .font(.caption2.weight(.medium)) - .foregroundStyle(colorScheme == .dark ? Color.black.opacity(0.55) : Color.white.opacity(0.75)) + .foregroundStyle(Theme.onAccent.opacity(0.75)) } } .buttonStyle(GlanceFooterProminentButtonStyle(model: model)) @@ -1943,10 +1943,10 @@ struct GlanceMeterColumns: View { } else if let gap, !gap.isEmpty { Text(gap) .font(.caption2) - .foregroundStyle(Theme.ink.opacity(0.62)) + .foregroundStyle(.secondary) .multilineTextAlignment(.leading) .lineLimit(3) - .minimumScaleFactor(0.7) + .minimumScaleFactor(0.85) .frame(width: Metrics.glanceMeterWidth, alignment: .leading) .accessibilityLabel(gap) } else { diff --git a/Sources/CodeCaps/MonitorModel.swift b/Sources/CodeCaps/MonitorModel.swift index ad31511f..b2a1208e 100644 --- a/Sources/CodeCaps/MonitorModel.swift +++ b/Sources/CodeCaps/MonitorModel.swift @@ -1351,7 +1351,13 @@ final class MonitorModel: ObservableObject { } func setOptionalQuotaReaderEnabled(_ enabled: Bool, readerID: String) { - guard LocalQuotaReaderRegistry.builtIn.optionalRegistrations.contains(where: { $0.id == readerID }), + // Consult a freshly configured registry, not the launch-time + // `builtIn` snapshot, so a plugin file dropped into the Plugins + // folder can be toggled without relaunching the app. Building the + // registry only creates factory closures; none is invoked here. + let live = LocalQuotaReaderRegistry.configured( + zCodeCredentialProvider: { nil }, mimoCredentialProvider: { nil }) + guard live.optionalRegistrations.contains(where: { $0.id == readerID }), optionalQuotaReaderPreferences.isEnabled(readerID) != enabled else { return } var preferences = optionalQuotaReaderPreferences preferences.setEnabled(enabled, for: readerID) @@ -1359,10 +1365,15 @@ final class MonitorModel: ObservableObject { preferences.save(to: defaults) invalidateRefresh() if !enabled, let providerResult { + // Built-in optional readers use their provider key as their id; + // a plugin's id is `plugin:` while its windows carry its + // own provider key, so resolve the key before purging. + let providerKey = live.optionalRegistrations + .first { $0.id == readerID }?.configurationMetadata["providerKey"] ?? readerID self.providerResult = LocalQuotaResult( - windows: providerResult.windows.filter { $0.canonicalProviderKey != readerID }, - issues: providerResult.issues.filter { $0.key != readerID }, - consentNeeded: providerResult.consentNeeded.subtracting([readerID])) + windows: providerResult.windows.filter { $0.canonicalProviderKey != providerKey }, + issues: providerResult.issues.filter { $0.key != providerKey }, + consentNeeded: providerResult.consentNeeded.subtracting([providerKey])) rebuildLocalState(recordSamples: false) } if providerChecksEnabled || serverEnabled { refreshProviderChecks() } @@ -3374,6 +3385,11 @@ final class MonitorModel: ObservableObject { }) } + /// How long one snapshot write waits for its predecessor before giving + /// up. The write itself is a bounded file replace; only a stuck disk + /// can hold a link this long. + static let snapshotWritePredecessorTimeout: Duration = .seconds(10) + /// Runs `work` on a background executor after every previously enqueued /// write, then reports success back on the main actor. func enqueueSnapshotWrite(_ work: @escaping @Sendable () throws -> Void, @@ -3381,7 +3397,18 @@ final class MonitorModel: ObservableObject { guard !snapshotWritesClosedForTermination else { return } let previous = snapshotWriteChain snapshotWriteChain = Task.detached(priority: .utility) { - await previous?.value + // A predecessor stuck on a disk write must not stall every later + // handoff and widget write indefinitely while the stale file + // still looks current. Wait with a deadline: on timeout this + // link reports failure (which surfaces as the handoff/widget + // error) and completes, so the chain behind it moves again. The + // skipped write is superseded by the next refresh's snapshot. + let predecessorFinished = await SnapshotWriteDrain.wait( + for: previous, timeout: Self.snapshotWritePredecessorTimeout) + guard predecessorFinished else { + await completion(false) + return + } let succeeded: Bool do { try work(); succeeded = true } catch { succeeded = false } await completion(succeeded) diff --git a/Sources/CodeCaps/PipWidget.swift b/Sources/CodeCaps/PipWidget.swift index 2f28b44f..12824e4c 100644 --- a/Sources/CodeCaps/PipWidget.swift +++ b/Sources/CodeCaps/PipWidget.swift @@ -960,11 +960,12 @@ struct PipWidgetView: View { // MARK: Header /// Close, or Back when a platform detail is open. It floats over the - /// rows' top-right corner and appears only on hover, so it never occupies - /// permanent space above the numbers. + /// rows' top-right corner and appears on hover, so it never occupies + /// permanent space above the numbers. VoiceOver users get it + /// permanently: hover is not a discovery path they can use. @ViewBuilder private var floatingControl: some View { - if isHovering { + if isHovering || NSWorkspace.shared.isVoiceOverEnabled { if detailRow == nil { HStack(spacing: 5) { settingsButton @@ -1099,7 +1100,7 @@ struct PipWidgetView: View { // Say so, rather than letting a pinned row look absent. It // sits under the scroll view so it never scrolls away itself. Text("\(targetRows.count - max(1, visible)) more pinned — scroll") - .font(.system(size: 9, weight: .medium)) + .font(.system(size: 10, weight: .medium)) .foregroundStyle(background.countdownInk) .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, PipMetrics.padding) @@ -1233,6 +1234,10 @@ struct PipWidgetView: View { .frame(maxWidth: .infinity, alignment: .leading) .contentShape(Rectangle()) .onTapGesture { detailRowId = row.id } + // Keyboard activation for the same action the tap performs, so the + // row is reachable and operable without a pointer. + .focusable() + .onKeyPress(.return) { detailRowId = row.id; return .handled } .help(row.title) .accessibilityLabel("\(row.title) — open details") .accessibilityAddTraits(.isButton) @@ -1277,7 +1282,7 @@ struct PipWidgetView: View { Spacer(minLength: 0) if row.section.expected, row.section.windows.isEmpty { Text("No readings published") - .font(.system(size: 9, weight: .semibold)) + .font(.system(size: 10, weight: .semibold)) .foregroundStyle(Theme.warning) .lineLimit(1) } @@ -1335,7 +1340,7 @@ struct PipWidgetView: View { return HStack(spacing: PipMetrics.meterSpacing) { Text(cadenceCaption) - .font(.system(size: 9, weight: .bold)) + .font(.system(size: 10, weight: .bold)) .foregroundStyle(background.countdownInk) .frame(width: PipMetrics.cadenceWidth, alignment: .leading) diff --git a/Sources/CodeCaps/RunawayAlertsView.swift b/Sources/CodeCaps/RunawayAlertsView.swift index b0f98b7d..03faadfb 100644 --- a/Sources/CodeCaps/RunawayAlertsView.swift +++ b/Sources/CodeCaps/RunawayAlertsView.swift @@ -24,11 +24,11 @@ struct RunawayAlertsPage: View { private var calibrationDescription: String { if summary.days >= 7.0 { - return "Fully calibrated. Evaluates current burn against your 7-day rolling average and worst peak hour." + return "Fully calibrated." + sentenceGap + "Evaluates current burn against your 7-day rolling average and worst peak hour." } else if summary.days >= 0.2 { - return "Calibrated for peak alerts. Collecting additional readings to calibrate your full 7-day average baseline." + return "Calibrated for peak alerts." + sentenceGap + "Collecting additional readings to calibrate your full 7-day average baseline." } else { - return "Collecting baseline history. CodeCaps records usage samples every refresh to establish your normal burn pattern." + return "Collecting baseline history." + sentenceGap + "CodeCaps records usage samples every refresh to establish your normal burn pattern." } } diff --git a/Sources/CodeCaps/SettingsViews.swift b/Sources/CodeCaps/SettingsViews.swift index 7466927a..7801bd34 100644 --- a/Sources/CodeCaps/SettingsViews.swift +++ b/Sources/CodeCaps/SettingsViews.swift @@ -480,7 +480,7 @@ struct SettingsSourcesFleetPage: View { } } .disabled(!model.localEnabled || !model.sessionFileChecksEnabled) - ForEach(ReaderStatus.all, id: \.providerKey) { reader in + ForEach(ReaderStatus.current, id: \.providerKey) { reader in readerRow(reader) if reader.optionalReaderID == "zcode" { ZAIQuotaSettingsView(controller: model.zAIQuotaSetup) } if reader.optionalReaderID == "mimo-token-plan" { MiMoQuotaSettings(model: model) } @@ -690,8 +690,8 @@ struct SettingsSourcesFleetPage: View { .frame(maxWidth: .infinity, alignment: .leading) Text("#\(index + 1)") - .font(.system(.caption2, design: .monospaced).weight(.medium)) - .foregroundStyle(.tertiary) + .font(.system(.caption, design: .monospaced).weight(.medium)) + .foregroundStyle(.secondary) .frame(width: 24, alignment: .trailing) Button { @@ -1023,7 +1023,18 @@ struct ReaderStatus { ReaderStatus(providerKey: "alibaba-token-plan", label: "Alibaba Token Plan", source: "Bailian CLI console sign-in", optionalReaderID: "alibaba-token-plan"), ReaderStatus(providerKey: "alibaba-coding-plan", label: "Alibaba Coding Plan (Qwen Code)", source: "Bailian CLI console sign-in", optionalReaderID: "alibaba-coding-plan"), ReaderStatus(providerKey: "mimo-token-plan", label: "Xiaomi MiMo Token Plan", source: "MiMo Token Plan key", optionalReaderID: "mimo-token-plan"), + ReaderStatus(providerKey: "opencode-go", label: "OpenCode Go", source: "OpenCode CLI sign-in", optionalReaderID: "opencode-go"), ] + + /// Built-in rows plus one row per declarative endpoint plugin found in + /// the Plugins folder, so a plugin subscription can be toggled in + /// Settings without a CodeCaps update. + static var current: [ReaderStatus] { + all + EndpointPluginLoader.load().map { descriptor in + ReaderStatus(providerKey: descriptor.providerKey, label: descriptor.displayName, + source: "Endpoint plugin", optionalReaderID: descriptor.id) + } + } } // MARK: - Appearance @@ -1125,7 +1136,9 @@ struct SettingsLogoStylePage: View { private var orderedKeys: [String] { if model.displaySections.isEmpty { - return ["claude", "cursor", "codex", "gemini", "antigravity", "grok", "grok-bot", "minimax"] + // Derive the pre-read fallback from the reader list so a new + // provider cannot be silently missing from this page. + return ReaderStatus.current.map(\.providerKey) } let live = Set(model.displaySections.map(\.id)) let stored = model.platformOrder.filter(live.contains) @@ -1143,6 +1156,9 @@ struct SettingsLogoStylePage: View { if let match = model.displaySections.first(where: { $0.id == rowId }) { return match.title } + if let reader = ReaderStatus.current.first(where: { $0.providerKey == rowId }) { + return reader.label + } switch rowId { case "claude", "anthropic": return "Claude Code" case "cursor": return "Cursor" diff --git a/Sources/CodeCaps/UsageHistoryViews.swift b/Sources/CodeCaps/UsageHistoryViews.swift index 80c12c37..224e96de 100644 --- a/Sources/CodeCaps/UsageHistoryViews.swift +++ b/Sources/CodeCaps/UsageHistoryViews.swift @@ -377,7 +377,7 @@ struct UsageHistoryView: View { + "Diamonds mark scheduled resets; green squares mark mid-cycle vendor resets; amber squares mark likely plan changes; amber dashed lines mark runaway alerts.") .font(.system(size: 11)).foregroundStyle(.secondary) Text("Burn stats are based on % of quota over time, unless absolute token data is available for the platform — in which case the detector prefers the absolute figures.") - .font(.system(size: 10)).foregroundStyle(.tertiary) + .font(.system(size: 11)).foregroundStyle(.secondary) .frame(maxWidth: .infinity, alignment: .trailing) .multilineTextAlignment(.trailing) } diff --git a/Sources/QuotaCore/EndpointPluginDescriptor.swift b/Sources/QuotaCore/EndpointPluginDescriptor.swift new file mode 100644 index 00000000..39e12768 --- /dev/null +++ b/Sources/QuotaCore/EndpointPluginDescriptor.swift @@ -0,0 +1,252 @@ +import Foundation + +/// A declarative, data-only description of an extra subscription quota +/// endpoint. Plugins are JSON files, never code: there is no script, shell, +/// dynamic library, or expression evaluation anywhere in this path, so adding +/// a subscription cannot execute anything the owner did not already run. +/// +/// A descriptor names one GET endpoint and, for each quota window, the JSON +/// paths of the numbers CodeCaps should show. Secrets are never in the file: +/// authentication is either absent or the *name* of an environment variable +/// whose value is sent as a Bearer token and never logged. +public struct EndpointPluginDescriptor: Codable, Equatable, Sendable { + public struct Auth: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { + case none + case bearerEnv + } + + public var type: Kind + /// Environment variable holding the Bearer token (`bearerEnv` only). + public var env: String? + + public init(type: Kind, env: String? = nil) { + self.type = type + self.env = env + } + } + + public struct Window: Codable, Equatable, Sendable { + /// Suffix appended to the provider key to form the window id. + public var idSuffix: String + public var label: String + /// Cadence name shown by the app, e.g. `5h`, `weekly`, `monthly`. + public var window: String? + /// JSON path of a 0-100 *remaining* percentage. + public var remainingPercentPath: String? + /// JSON path of a 0-100 *used* percentage (the complement is shown). + public var usedPercentPath: String? + public var absoluteRemainingPath: String? + public var absoluteLimitPath: String? + public var quotaUnit: String? + /// JSON path of an ISO-8601 reset stamp or an epoch seconds/ms number. + public var resetAtPath: String? + public var planNamePath: String? + + public init(idSuffix: String, label: String, window: String? = nil, + remainingPercentPath: String? = nil, usedPercentPath: String? = nil, + absoluteRemainingPath: String? = nil, absoluteLimitPath: String? = nil, + quotaUnit: String? = nil, resetAtPath: String? = nil, planNamePath: String? = nil) { + self.idSuffix = idSuffix + self.label = label + self.window = window + self.remainingPercentPath = remainingPercentPath + self.usedPercentPath = usedPercentPath + self.absoluteRemainingPath = absoluteRemainingPath + self.absoluteLimitPath = absoluteLimitPath + self.quotaUnit = quotaUnit + self.resetAtPath = resetAtPath + self.planNamePath = planNamePath + } + } + + /// Registration id, always `plugin:` so it can never shadow a + /// built-in reader in Settings, ranking, or source toggles. + public var id: String + public var displayName: String + /// Quota provider key the windows are filed under, e.g. `acme-plan`. + public var providerKey: String + /// GET endpoint. HTTPS only, except loopback HTTP with `allowLoopback`. + public var endpoint: String + public var allowLoopback: Bool? + public var auth: Auth + public var windows: [Window] + + public init(id: String, displayName: String, providerKey: String, endpoint: String, + allowLoopback: Bool? = nil, auth: Auth, windows: [Window]) { + self.id = id + self.displayName = displayName + self.providerKey = providerKey + self.endpoint = endpoint + self.allowLoopback = allowLoopback + self.auth = auth + self.windows = windows + } + + /// Provider keys a plugin may not claim, so a descriptor can never + /// impersonate a built-in subscription row. + static let reservedProviderKeys: Set = [ + "anthropic", "openai", "google-antigravity", "cursor", "github-copilot", + "xai", "grok", "grok-bot", "minimax", "muse-assist", "muse-code", + "kimi", "zcode", "alibaba-token-plan", "alibaba-coding-plan", + "mimo-token-plan", "opencode-go", + ] + + /// Why a descriptor was refused. The text is shown nowhere with the file + /// contents; it exists for tests and for a one-line Settings note. + public enum ValidationError: Error, Equatable, Sendable { + case badID, badProviderKey, reservedProviderKey, badEndpoint, badAuth, badWindows, badPath(String) + } + + public func validated() throws -> EndpointPluginDescriptor { + guard Self.isSlug(id, prefix: "plugin:") else { throw ValidationError.badID } + guard Self.isSlug(providerKey, prefix: "") else { throw ValidationError.badProviderKey } + guard !Self.reservedProviderKeys.contains(providerKey) else { throw ValidationError.reservedProviderKey } + guard (1...200).contains(displayName.count), !displayName.contains("\n") else { throw ValidationError.badID } + guard let url = Self.validatedEndpoint(endpoint, allowLoopback: allowLoopback ?? false) else { + throw ValidationError.badEndpoint + } + _ = url + switch auth.type { + case .none: + if auth.env != nil { throw ValidationError.badAuth } + case .bearerEnv: + guard let env = auth.env, + env.range(of: "^[A-Za-z_][A-Za-z0-9_]{0,127}$", options: .regularExpression) != nil + else { throw ValidationError.badAuth } + } + guard (1...10).contains(windows.count) else { throw ValidationError.badWindows } + var suffixes = Set() + for window in windows { + guard Self.isSlug(window.idSuffix, prefix: ""), suffixes.insert(window.idSuffix).inserted, + (1...80).contains(window.label.count), + (window.remainingPercentPath == nil) != (window.usedPercentPath == nil) + || (window.absoluteRemainingPath != nil && window.absoluteLimitPath != nil) + else { throw ValidationError.badWindows } + for path in [window.remainingPercentPath, window.usedPercentPath, window.absoluteRemainingPath, + window.absoluteLimitPath, window.resetAtPath, window.planNamePath].compactMap({ $0 }) { + guard EndpointJSONPath.isValid(path) else { throw ValidationError.badPath(path) } + } + } + return self + } + + public var endpointURL: URL? { + Self.validatedEndpoint(endpoint, allowLoopback: allowLoopback ?? false) + } + + static func isSlug(_ value: String, prefix: String) -> Bool { + guard value.hasPrefix(prefix) else { return false } + let slug = value.dropFirst(prefix.count) + guard (1...63).contains(slug.count), + let first = slug.unicodeScalars.first, + (97...122).contains(first.value) || (48...57).contains(first.value) else { return false } + return slug.unicodeScalars.allSatisfy { + (97...122).contains($0.value) || (48...57).contains($0.value) || $0.value == 45 + } && !slug.hasSuffix("-") && !slug.contains("--") + } + + /// The plugin SSRF gate, deliberately stricter than the user-endpoint + /// gate in `QuotaClient`: no userinfo, query, or fragment; HTTPS only + /// (loopback HTTP needs the explicit opt-in); and a literal host may + /// never be a private, loopback, link-local, or metadata address. A + /// hostname that *resolves* to such an address is refused by + /// `BoundedHTTPFetch`'s no-redirect rule only at connect time, so DNS + /// rebinding remains a documented residual risk of declarative plugins: + /// a descriptor is trusted configuration the owner placed on disk, in + /// the same trust class as the push/pull endpoint in Settings. + static func validatedEndpoint(_ raw: String, allowLoopback: Bool) -> URL? { + guard let components = URLComponents(string: raw), + let rawHost = components.host?.lowercased(), !rawHost.isEmpty, + components.user == nil, components.password == nil, + components.query == nil, components.fragment == nil, + components.port == nil || components.port == 443 || allowLoopback else { return nil } + // An IPv6 literal may still carry its brackets depending on the + // URL parser; compare the bare address either way. + let host = rawHost.hasPrefix("[") && rawHost.hasSuffix("]") + ? String(rawHost.dropFirst().dropLast()) : rawHost + let loopback = host == "localhost" || host == "127.0.0.1" || host == "::1" + if components.scheme == "http" { + guard allowLoopback, loopback else { return nil } + } else { + guard components.scheme == "https" else { return nil } + } + if loopback { return allowLoopback ? components.url : nil } + if isPrivateLiteralIP(host) { return nil } + return components.url + } + + static func isPrivateLiteralIP(_ host: String) -> Bool { + let ipv4 = host.split(separator: ".").map { Int($0) } + if ipv4.count == 4, ipv4.allSatisfy({ $0 != nil }) { + let octets = ipv4.map { $0! } + guard octets.allSatisfy({ (0...255).contains($0) }) else { return false } + switch octets[0] { + case 0, 10, 127: return true + case 100: return (64...127).contains(octets[1]) + case 169: return octets[1] == 254 + case 172: return (16...31).contains(octets[1]) + case 192: return octets[1] == 168 || (octets[1] == 0 && octets[2] == 0) + case 198: return octets[1] == 18 || octets[1] == 19 + case 224...255: return true + default: return false + } + } + let lower = host.lowercased() + if lower == "::1" || lower.hasPrefix("fe8") || lower.hasPrefix("fe9") + || lower.hasPrefix("fea") || lower.hasPrefix("feb") + || lower.hasPrefix("fc") || lower.hasPrefix("fd") || lower.hasPrefix("ff") { + return true + } + return false + } +} + +/// A restricted JSON path: dot-separated keys with optional `[index]` +/// steps, e.g. `usage.rolling.percent` or `items[0].remaining`. There is +/// no wildcard, filter, or expression syntax, by design. +public enum EndpointJSONPath { + public static func isValid(_ path: String) -> Bool { + guard (1...200).contains(path.count), !path.hasPrefix("."), !path.hasSuffix("."), + !path.contains(".."), !path.contains(" ") else { return false } + return path.split(separator: ".", omittingEmptySubsequences: false).allSatisfy { segment in + !segment.isEmpty && segment.range(of: "^[A-Za-z0-9_-]+(\\[[0-9]{1,4}\\])*$", options: .regularExpression) != nil + } + } + + public static func resolve(_ root: Any, path: String) -> Any? { + var current: Any = root + for segment in path.split(separator: ".", omittingEmptySubsequences: false) { + let parts = segment.split(separator: "[", omittingEmptySubsequences: false) + guard let key = parts.first, !key.isEmpty, + let dict = current as? [String: Any], let next = dict[String(key)] else { return nil } + current = next + for indexPart in parts.dropFirst() { + guard indexPart.hasSuffix("]"), let index = Int(indexPart.dropLast()), + let array = current as? [Any], array.indices.contains(index) else { return nil } + current = array[index] + } + } + return current + } + + public static func number(_ root: Any, path: String?) -> Double? { + guard let path, let value = resolve(root, path: path) else { return nil } + if let text = value as? String { + let trimmed = text.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty, trimmed.utf8.count <= 32, + trimmed.allSatisfy({ $0.isASCII && ($0.isNumber || $0 == "." || $0 == "-") }), + let parsed = Double(trimmed), parsed.isFinite else { return nil } + return parsed + } + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), + number.doubleValue.isFinite else { return nil } + return number.doubleValue + } + + public static func string(_ root: Any, path: String?) -> String? { + guard let path, let value = resolve(root, path: path) as? String, + !value.isEmpty, value.utf8.count <= 160 else { return nil } + return value + } +} diff --git a/Sources/QuotaCore/EndpointPluginLoader.swift b/Sources/QuotaCore/EndpointPluginLoader.swift new file mode 100644 index 00000000..abdbb39c --- /dev/null +++ b/Sources/QuotaCore/EndpointPluginLoader.swift @@ -0,0 +1,60 @@ +import Foundation + +/// Loads declarative endpoint plugins from +/// `~/Library/Application Support/CodeCaps/Plugins/*.json`. +/// +/// Loading is fail-closed and quiet: an unreadable, oversize, malformed, or +/// invalid file is skipped (never half-applied), a duplicate or reserved id +/// loses to the first valid file in filename order, and no file content — +/// which could quote a secret by mistake — is ever logged or surfaced. The +/// absence of the directory is the normal case and simply means no plugins. +public enum EndpointPluginLoader { + public static let maxFiles = 20 + public static let maxFileBytes = 65_536 + + public static var defaultDirectory: URL { + FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/Application Support/CodeCaps/Plugins", isDirectory: true) + } + + public static func load(directory: URL = defaultDirectory) -> [EndpointPluginDescriptor] { + let manager = FileManager.default + guard let entries = try? manager.contentsOfDirectory( + at: directory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) else { return [] } + let files = entries + .filter { $0.pathExtension.lowercased() == "json" && !$0.hasDirectoryPath } + .sorted { $0.lastPathComponent < $1.lastPathComponent } + .prefix(maxFiles) + var seenIDs = Set() + var seenProviderKeys = Set() + var descriptors: [EndpointPluginDescriptor] = [] + for file in files { + guard let data = try? Data(contentsOf: file, options: .mappedIfSafe), + data.count <= maxFileBytes, + let descriptor = try? JSONDecoder().decode(EndpointPluginDescriptor.self, from: data), + let valid = try? descriptor.validated(), + seenIDs.insert(valid.id).inserted, + seenProviderKeys.insert(valid.providerKey).inserted else { continue } + descriptors.append(valid) + } + return descriptors + } + + /// Registrations for the local reader registry. Every plugin is an + /// optional reader: it defaults to enabled like the other optional + /// readers, its factory is never invoked while disabled, and its id + /// (`plugin:`) keeps it clear of every built-in toggle. + public static func registrations( + descriptors: [EndpointPluginDescriptor], + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> [LocalQuotaReaderRegistration] { + descriptors.map { descriptor in + LocalQuotaReaderRegistration( + id: descriptor.id, label: descriptor.displayName, + configurationMetadata: ["providerKey": descriptor.providerKey], isOptional: true + ) { + GenericEndpointQuotaReader(descriptor: descriptor, environment: environment) + } + } + } +} diff --git a/Sources/QuotaCore/GenericEndpointQuotaReader.swift b/Sources/QuotaCore/GenericEndpointQuotaReader.swift new file mode 100644 index 00000000..065c2831 --- /dev/null +++ b/Sources/QuotaCore/GenericEndpointQuotaReader.swift @@ -0,0 +1,131 @@ +import Foundation + +/// The one reader behind every declarative endpoint plugin. It speaks the +/// same contract as the built-in readers — returns a `LocalQuotaResult`, +/// never throws to the caller, never logs a credential — over the shared +/// bounded transport (ephemeral session, no cookies, no redirects, byte and +/// time caps), so plugin windows flow through snapshot export, ranking, +/// and Settings toggles exactly like a built-in provider's. +public struct GenericEndpointQuotaReader: LocalQuotaReading, Sendable { + private let descriptor: EndpointPluginDescriptor + private let now: @Sendable () -> Date + private let fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + private let token: @Sendable () -> String? + + private static let maxResponseBytes = 262_144 + private static let timeout: TimeInterval = 15 + + public init( + descriptor: EndpointPluginDescriptor, + environment: [String: String] = ProcessInfo.processInfo.environment, + now: @escaping @Sendable () -> Date = { Date() }, + fetch: (@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse))? = nil + ) { + self.descriptor = descriptor + self.now = now + switch descriptor.auth.type { + case .none: + self.token = { nil } + case .bearerEnv: + let name = descriptor.auth.env ?? "" + self.token = { environment[name].flatMap { $0.isEmpty ? nil : $0 } } + } + self.fetch = fetch ?? Self.makeFetcher() + } + + public func read() async -> LocalQuotaResult { + let id = descriptor.providerKey + do { + guard let url = descriptor.endpointURL else { + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) plugin endpoint is not a permitted address."]) + } + var request = URLRequest(url: url) + request.httpMethod = "GET" + request.cachePolicy = .reloadIgnoringLocalCacheData + request.timeoutInterval = Self.timeout + request.setValue("application/json", forHTTPHeaderField: "Accept") + if descriptor.auth.type == .bearerEnv { + guard let token = token() else { + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) plugin needs its configured sign-in key."]) + } + request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + } + let (data, response) = try await fetch(request) + if response.statusCode == 401 || response.statusCode == 403 { + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) rejected the configured sign-in."]) + } + guard (200..<300).contains(response.statusCode) else { + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) quota service is unavailable."]) + } + guard data.count <= Self.maxResponseBytes, + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) returned no readable quota."]) + } + let windows = Self.parse(root, descriptor: descriptor, observedAt: now()) + if windows.isEmpty { + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) returned no readable quota."]) + } + return LocalQuotaResult(windows: windows) + } catch is CancellationError { + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) quota refresh was cancelled."]) + } catch { + if Task.isCancelled { + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) quota refresh was cancelled."]) + } + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) quota service could not be reached."]) + } + } + + static func parse(_ root: [String: Any], descriptor: EndpointPluginDescriptor, observedAt: Date) -> [QuotaWindow] { + let observed = ISO8601DateFormatter().string(from: observedAt) + return descriptor.windows.compactMap { spec in + let absoluteRemaining = EndpointJSONPath.number(root, path: spec.absoluteRemainingPath) + let absoluteLimit = EndpointJSONPath.number(root, path: spec.absoluteLimitPath) + let remaining: Double? + if let percent = EndpointJSONPath.number(root, path: spec.remainingPercentPath) { + remaining = percent + } else if let used = EndpointJSONPath.number(root, path: spec.usedPercentPath) { + remaining = 100 - used + } else if let absoluteRemaining, let absoluteLimit, absoluteLimit > 0 { + remaining = absoluteRemaining / absoluteLimit * 100 + } else { + remaining = nil + } + guard let remaining, remaining.isFinite else { return nil } + let bounded = min(100, max(0, remaining)) + return QuotaWindow( + id: descriptor.providerKey + ":" + spec.idSuffix, + provider: descriptor.providerKey, providerKey: descriptor.providerKey, + providerLabel: descriptor.displayName, label: spec.label, + remainingPercent: bounded, + absoluteRemaining: absoluteRemaining, absoluteLimit: absoluteLimit, + quotaUnit: spec.quotaUnit, + planName: EndpointJSONPath.string(root, path: spec.planNamePath), + isExhausted: bounded == 0, resetAt: resetTimestamp(root, path: spec.resetAtPath), + window: spec.window, status: .derived(remainingPercent: bounded), + occurredAt: observed, source: descriptor.id) + } + } + + /// A reset stamp may be ISO-8601 text or an epoch number; numbers at or + /// above 10^12 are milliseconds, anything smaller is seconds. + private static func resetTimestamp(_ root: [String: Any], path: String?) -> String? { + guard let path else { return nil } + if let text = EndpointJSONPath.string(root, path: path) { + let iso = ISO8601DateFormatter() + if iso.date(from: text) != nil { return text } + iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + if iso.date(from: text) != nil { return text } + return nil + } + guard let epoch = EndpointJSONPath.number(root, path: path), epoch > 0, epoch < 10_000_000_000_000 else { return nil } + let date = Date(timeIntervalSince1970: epoch >= 1_000_000_000_000 ? epoch / 1000 : epoch) + return ISO8601DateFormatter().string(from: date) + } + + static func makeFetcher() -> @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) { + return { request in + try await BoundedHTTPFetch.data(for: request, timeout: Self.timeout, maxBytes: Self.maxResponseBytes) + } + } +} diff --git a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift index a2ad0883..40c2820d 100644 --- a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift +++ b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift @@ -94,7 +94,8 @@ public struct LocalQuotaReaderRegistry: Sendable { public static func configured( zCodeCredentialProvider: @escaping @Sendable () async -> ZCodeQuotaCredential?, - mimoCredentialProvider: @escaping @Sendable () async -> MiMoTokenPlanCredential? + mimoCredentialProvider: @escaping @Sendable () async -> MiMoTokenPlanCredential?, + pluginDescriptors: [EndpointPluginDescriptor] = EndpointPluginLoader.load() ) -> LocalQuotaReaderRegistry { LocalQuotaReaderRegistry(registrations: [ LocalQuotaReaderRegistration(id: "local-primary", label: "Built-In Provider Sessions", @@ -128,6 +129,12 @@ public struct LocalQuotaReaderRegistry: Sendable { LocalQuotaReaderRegistration(id: "mimo-token-plan", label: "Xiaomi MiMo Token Plan", isOptional: true) { MiMoTokenPlanReader(credential: mimoCredentialProvider) }, - ]) + LocalQuotaReaderRegistration(id: "opencode-go", label: "OpenCode Go", configurationMetadata: ["providerKey": "opencode-go"], isOptional: true) { + OpenCodeGoQuotaReader() + }, + // Declarative endpoint plugins come last: a built-in reader for + // the same plan always wins, and a plugin's provider key is + // validated clear of every built-in key before it can register. + ] + EndpointPluginLoader.registrations(descriptors: pluginDescriptors)) } } diff --git a/Sources/QuotaCore/OpenCodeGoQuotaReader.swift b/Sources/QuotaCore/OpenCodeGoQuotaReader.swift new file mode 100644 index 00000000..2407726f --- /dev/null +++ b/Sources/QuotaCore/OpenCodeGoQuotaReader.swift @@ -0,0 +1,170 @@ +import Foundation + +/// Reads OpenCode Go's subscription quota from OpenCode's documented usage +/// endpoint (`GET https://opencode.ai/inference/go/v1/usage`) using the Go +/// key the OpenCode CLI already saved in its local auth file. +/// +/// The key is read read-only from `~/.local/share/opencode/auth.json` +/// (`$XDG_DATA_HOME/opencode/auth.json` when set), never persisted, logged, +/// or refreshed by this reader. A missing auth file or a missing Go entry +/// means the product is simply absent, the same way a missing `gh` binary is +/// not a Copilot error. `opencode stats` and the local database are +/// consumption estimates, not remaining quota, and are never read here. +public struct OpenCodeGoQuotaReader: Sendable { + public static let providerKey = "opencode-go" + public static let usageURL = URL(string: "https://opencode.ai/inference/go/v1/usage")! + + private let now: @Sendable () -> Date + private let credential: @Sendable () -> String? + private let fetch: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + + private static let maxResponseBytes = 262_144 + private static let maxCredentialBytes = 1_048_576 + private static let timeout: TimeInterval = 15 + + public init( + homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser, + environment: [String: String] = ProcessInfo.processInfo.environment, + now: @escaping @Sendable () -> Date = { Date() }, + accessToken: (@Sendable () -> String?)? = nil, + fetch: (@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse))? = nil + ) { + self.now = now + if let accessToken { + self.credential = accessToken + } else { + let home = homeDirectory.standardizedFileURL + self.credential = { Self.readGoKey(home: home, environment: environment) } + } + self.fetch = fetch ?? Self.makeFetcher() + } + + public func read() async -> LocalQuotaResult { + let id = Self.providerKey + do { + guard let key = credential(), !key.isEmpty else { + // No local OpenCode Go sign-in: the product is absent. + return LocalQuotaResult() + } + var request = URLRequest(url: Self.usageURL) + request.httpMethod = "GET" + request.cachePolicy = .reloadIgnoringLocalCacheData + request.timeoutInterval = Self.timeout + request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") + request.setValue("application/json", forHTTPHeaderField: "Accept") + let (data, response) = try await fetch(request) + if response.statusCode == 401 { + return LocalQuotaResult(issues: [id: "OpenCode Go rejected the saved key; sign in again in OpenCode."]) + } + if response.statusCode == 403 { + return LocalQuotaResult(issues: [id: "OpenCode Go reports no active Go subscription for this key."]) + } + guard (200..<300).contains(response.statusCode) else { + return LocalQuotaResult(issues: [id: "OpenCode Go quota service is unavailable."]) + } + guard data.count <= Self.maxResponseBytes, + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { + return LocalQuotaResult(issues: [id: "OpenCode Go returned no readable quota."]) + } + let windows = Self.parse(root, observedAt: now()) + if windows.isEmpty { + return LocalQuotaResult(issues: [id: "OpenCode Go returned no readable quota."]) + } + return LocalQuotaResult(windows: windows) + } catch is CancellationError { + return LocalQuotaResult(issues: [id: "OpenCode Go quota refresh was cancelled."]) + } catch { + if Task.isCancelled { return LocalQuotaResult(issues: [id: "OpenCode Go quota refresh was cancelled."]) } + return LocalQuotaResult(issues: [id: "OpenCode Go quota service could not be reached."]) + } + } + + /// Parses `usage.{rolling,weekly,monthly}.{status,percent,resetsAt}`. + /// `percent` is the share already used, so the remaining share CodeCaps + /// displays is its complement. The same shape at the top level (without + /// the `usage` wrapper) is accepted so a documented-shape change in one + /// place does not silently drop every window. + static func parse(_ root: [String: Any], observedAt: Date) -> [QuotaWindow] { + let usage = (root["usage"] as? [String: Any]) ?? root + let observed = ISO8601DateFormatter().string(from: observedAt) + let kinds: [(key: String, label: String, window: String)] = [ + ("rolling", "5 hours", "5h"), + ("weekly", "Weekly", "weekly"), + ("monthly", "Monthly", "monthly"), + ] + return kinds.compactMap { kind in + guard let entry = usage[kind.key] as? [String: Any], + let used = number(entry["percent"]), (0...100).contains(used) else { return nil } + let remaining = 100 - used + let statusText = (entry["status"] as? String)?.lowercased() + let exhausted = remaining == 0 || statusText == "rate-limited" || statusText == "rate_limited" + return QuotaWindow( + id: "opencode-go:" + kind.key, provider: Self.providerKey, providerKey: Self.providerKey, + providerLabel: "OpenCode Go", label: kind.label, remainingPercent: remaining, + isExhausted: exhausted, resetAt: resetTimestamp(entry), + window: kind.window, status: .derived(remainingPercent: remaining), + occurredAt: observed, source: "opencode-go-api") + } + } + + /// The Go entry of the CLI's auth file. Entry field names are read + /// tolerantly (`key`, then `apiKey`, then `access_token`) because the + /// file is the CLI's private store; anything else is treated as absent + /// rather than guessed at. The raw string is extracted directly, never + /// through a display-length-capped helper. + internal static func readGoKey( + home: URL, environment: [String: String] = ProcessInfo.processInfo.environment + ) -> String? { + let dataHome = environment["XDG_DATA_HOME"].flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0) } + ?? home.appendingPathComponent(".local/share") + let url = dataHome.appendingPathComponent("opencode/auth.json") + guard let data = try? Data(contentsOf: url, options: .mappedIfSafe), + data.count <= maxCredentialBytes, + let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } + for entryKey in ["opencode-go", "opencode_go", "opencodeGo"] { + guard let entry = root[entryKey] as? [String: Any] else { continue } + // An OAuth entry carries no reusable API key for this endpoint. + if let type = entry["type"] as? String, type.lowercased() == "oauth" { continue } + for field in ["key", "apiKey", "api_key", "access_token", "accessToken"] { + if let key = entry[field] as? String, validKey(key) { return key } + } + } + return nil + } + + static func validKey(_ key: String) -> Bool { + !key.isEmpty && key.utf8.count <= 8_192 && !key.contains("\r") && !key.contains("\n") + } + + private static func resetTimestamp(_ entry: [String: Any]) -> String? { + for field in ["resetsAt", "resetAt", "resets_at", "reset_at"] { + guard let text = entry[field] as? String, text.utf8.count <= 64 else { continue } + let iso = ISO8601DateFormatter() + if iso.date(from: text) != nil { return text } + iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + if iso.date(from: text) != nil { return text } + } + return nil + } + + private static func number(_ value: Any?) -> Double? { + if let text = value as? String { + let trimmed = text.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty, trimmed.utf8.count <= 32, + trimmed.allSatisfy({ $0.isASCII && ($0.isNumber || $0 == ".") }), + let parsed = Double(trimmed), parsed.isFinite else { return nil } + return parsed + } + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), + number.doubleValue.isFinite else { return nil } + return number.doubleValue + } + + static func makeFetcher() -> @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) { + return { request in + let (data, response) = try await BoundedHTTPFetch.data( + for: request, timeout: Self.timeout, maxBytes: Self.maxResponseBytes) + return (data, response) + } + } +} diff --git a/Sources/QuotaCore/QuotaModels.swift b/Sources/QuotaCore/QuotaModels.swift index fae9140a..671723dd 100644 --- a/Sources/QuotaCore/QuotaModels.swift +++ b/Sources/QuotaCore/QuotaModels.swift @@ -1142,6 +1142,7 @@ enum QuotaProviders { "alibaba-token-plan": "Alibaba Token Plan", "alibaba-coding-plan": "Alibaba Coding Plan", "mimo-token-plan": "Xiaomi MiMo Token Plan", + "opencode-go": "OpenCode Go", ] static func canonicalKey(provider: String, providerKey: String?, via: String?) -> String { diff --git a/Sources/QuotaCore/QuotaPublisher.swift b/Sources/QuotaCore/QuotaPublisher.swift index 1c0261cb..80aeacea 100644 --- a/Sources/QuotaCore/QuotaPublisher.swift +++ b/Sources/QuotaCore/QuotaPublisher.swift @@ -102,12 +102,43 @@ public actor QuotaPublisher { session.invalidateAndCancel() } + /// Publishes, retrying a transient gateway answer twice for the v2 + /// format. V2 event ids are derived from the reading itself, so a + /// retry is counted as a duplicate by the ingest, never as a second + /// reading. The generic webhook has no such guarantee and is sent once. public func publish( windows: [QuotaWindow], to endpoint: URL, token: String? = nil, format: QuotaSyncFormat = .usageMonitorV2, machineName: String? = nil + ) async throws -> QuotaPublishResult { + let maxAttempts = format == .usageMonitorV2 ? 3 : 1 + var attempt = 0 + while true { + do { + return try await publishOnce( + windows: windows, to: endpoint, token: token, format: format, machineName: machineName) + } catch let error as QuotaPublisherError { + attempt += 1 + let retryable: Bool + switch error { + case .httpStatus(let status, _): retryable = [502, 503, 504].contains(status) + case .timedOut: retryable = true + default: retryable = false + } + guard retryable, attempt < maxAttempts else { throw error } + try await Task.sleep(nanoseconds: UInt64(attempt) * 500_000_000) + } + } + } + + private func publishOnce( + windows: [QuotaWindow], + to endpoint: URL, + token: String? = nil, + format: QuotaSyncFormat = .usageMonitorV2, + machineName: String? = nil ) async throws -> QuotaPublishResult { guard QuotaClient.isAllowedEndpoint(endpoint) else { throw QuotaPublisherError.invalidEndpoint diff --git a/Tests/CodeCapsTests/SnapshotWriteDrainTests.swift b/Tests/CodeCapsTests/SnapshotWriteDrainTests.swift index eace59db..8a6e9848 100644 --- a/Tests/CodeCapsTests/SnapshotWriteDrainTests.swift +++ b/Tests/CodeCapsTests/SnapshotWriteDrainTests.swift @@ -152,6 +152,14 @@ final class SnapshotTerminationIntegrationTests: XCTestCase { XCTAssertFalse(model.contains("sem.wait(")) } + func testSnapshotWriteChainBoundsPredecessorWaitAndReportsFailure() throws { + let model = try source("MonitorModel.swift") + XCTAssertTrue(model.contains("static let snapshotWritePredecessorTimeout: Duration = .seconds(10)")) + XCTAssertTrue(model.contains("for: previous, timeout: Self.snapshotWritePredecessorTimeout")) + XCTAssertFalse(model.contains("await previous?.value"), + "an unbounded predecessor wait stalls every later snapshot write behind one stuck disk write") + } + func testDisableQueuesRemovalAndWidgetUsesCompletionTimeOrder() throws { let model = try source("MonitorModel.swift") let disable = try XCTUnwrap(model.range(of: "func setLocalEnabled(")) diff --git a/Tests/QuotaCoreTests/EndpointPluginTests.swift b/Tests/QuotaCoreTests/EndpointPluginTests.swift new file mode 100644 index 00000000..999dd715 --- /dev/null +++ b/Tests/QuotaCoreTests/EndpointPluginTests.swift @@ -0,0 +1,120 @@ +import Foundation +import XCTest +@testable import QuotaCore + +final class EndpointPluginTests: XCTestCase { + private func descriptor( + id: String = "plugin:acme", providerKey: String = "acme-plan", + endpoint: String = "https://api.example.com/usage", + auth: EndpointPluginDescriptor.Auth = .init(type: .none) + ) -> EndpointPluginDescriptor { + EndpointPluginDescriptor( + id: id, displayName: "Acme Plan", providerKey: providerKey, endpoint: endpoint, + auth: auth, + windows: [.init(idSuffix: "monthly", label: "Monthly", window: "monthly", + usedPercentPath: "usage.monthly.percent", + resetAtPath: "usage.monthly.resetsAt")]) + } + + func testValidDescriptorPasses() throws { + XCTAssertNoThrow(try descriptor().validated()) + } + + func testReservedAndMalformedDescriptorsAreRefused() { + XCTAssertThrowsError(try descriptor(providerKey: "kimi").validated()) + XCTAssertThrowsError(try descriptor(id: "acme").validated()) + XCTAssertThrowsError(try descriptor(providerKey: "Acme Plan").validated()) + XCTAssertThrowsError(try descriptor(auth: .init(type: .bearerEnv, env: "1BAD-NAME")).validated()) + XCTAssertThrowsError(try descriptor(auth: .init(type: .none, env: "SECRET")).validated()) + } + + func testEndpointSSRFMatrix() { + let refused = [ + "http://api.example.com/usage", + "https://user:pass@api.example.com/usage", + "https://api.example.com/usage?token=x", + "https://169.254.169.254/latest/meta-data", + "https://10.0.0.5/usage", + "https://172.16.0.5/usage", + "https://192.168.1.5/usage", + "https://[::1]/usage", + "ftp://api.example.com/usage", + ] + for endpoint in refused { + XCTAssertThrowsError(try descriptor(endpoint: endpoint).validated(), endpoint) + } + XCTAssertNoThrow(try descriptor(endpoint: "https://8.8.8.8/usage").validated()) + } + + func testLoopbackNeedsExplicitOptIn() throws { + XCTAssertThrowsError(try descriptor(endpoint: "http://127.0.0.1:8080/usage").validated()) + var loopback = descriptor(endpoint: "http://127.0.0.1:8080/usage") + loopback.allowLoopback = true + XCTAssertNoThrow(try loopback.validated()) + } + + func testJSONPathGrammar() { + XCTAssertTrue(EndpointJSONPath.isValid("usage.monthly.percent")) + XCTAssertTrue(EndpointJSONPath.isValid("items[0].remaining")) + XCTAssertFalse(EndpointJSONPath.isValid("usage..percent")) + XCTAssertFalse(EndpointJSONPath.isValid("usage.*.percent")) + XCTAssertFalse(EndpointJSONPath.isValid("a b")) + let root: [String: Any] = ["items": [["remaining": 42]]] + XCTAssertEqual(EndpointJSONPath.number(root, path: "items[0].remaining"), 42) + } + + func testGenericReaderMapsUsedPercentAndReset() async { + let reader = GenericEndpointQuotaReader( + descriptor: descriptor(), + environment: [:], + now: { Date(timeIntervalSince1970: 0) }, + fetch: { _ in + let response = HTTPURLResponse( + url: URL(string: "https://api.example.com/usage")!, + statusCode: 200, httpVersion: nil, headerFields: nil)! + return (Data(#"{"usage":{"monthly":{"percent":25,"resetsAt":"2026-12-01T00:00:00Z"}}}"#.utf8), response) + }) + let result = await reader.read() + XCTAssertTrue(result.issues.isEmpty) + XCTAssertEqual(result.windows.count, 1) + XCTAssertEqual(result.windows.first?.providerKey, "acme-plan") + XCTAssertEqual(result.windows.first?.remainingPercent, 75) + XCTAssertEqual(result.windows.first?.resetAt, "2026-12-01T00:00:00Z") + XCTAssertEqual(result.windows.first?.source, "plugin:acme") + } + + func testGenericReaderMissingEnvKeyReportsSignIn() async { + let reader = GenericEndpointQuotaReader( + descriptor: descriptor(auth: .init(type: .bearerEnv, env: "ACME_MISSING_KEY")), + environment: [:], + fetch: { _ in XCTFail("fetch must not run without the configured key"); throw URLError(.badURL) }) + let result = await reader.read() + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["acme-plan"], "Acme Plan plugin needs its configured sign-in key.") + } + + func testLoaderSkipsInvalidAndDuplicateFiles() throws { + let dir = FileManager.default.temporaryDirectory + .appendingPathComponent("endpoint-plugin-tests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + let encoder = JSONEncoder() + try encoder.encode(descriptor()).write(to: dir.appendingPathComponent("a.json")) + try encoder.encode(descriptor()).write(to: dir.appendingPathComponent("b.json")) + try Data(#"{"id":"plugin:broken"}"#.utf8).write(to: dir.appendingPathComponent("c.json")) + try Data("not json".utf8).write(to: dir.appendingPathComponent("d.json")) + let loaded = EndpointPluginLoader.load(directory: dir) + XCTAssertEqual(loaded.map(\.id), ["plugin:acme"]) + } + + func testDisabledPluginFactoryIsNeverInvoked() async { + let descriptor = try! descriptor().validated() + let registry = LocalQuotaReaderRegistry( + registrations: EndpointPluginLoader.registrations(descriptors: [descriptor], environment: [:])) + var preferences = QuotaReaderPreferences() + preferences.setEnabled(false, for: "plugin:acme") + let result = await registry.read(preferences: preferences) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertTrue(result.issues.isEmpty) + } +} diff --git a/Tests/QuotaCoreTests/OpenCodeGoQuotaReaderTests.swift b/Tests/QuotaCoreTests/OpenCodeGoQuotaReaderTests.swift new file mode 100644 index 00000000..f24e0c2c --- /dev/null +++ b/Tests/QuotaCoreTests/OpenCodeGoQuotaReaderTests.swift @@ -0,0 +1,82 @@ +import Foundation +import XCTest +@testable import QuotaCore + +final class OpenCodeGoQuotaReaderTests: XCTestCase { + private func read( + _ json: String, status: Int = 200, token: String? = "go-key" + ) async -> LocalQuotaResult { + await OpenCodeGoQuotaReader( + now: { Date(timeIntervalSince1970: 0) }, + accessToken: { token }, + fetch: { _ in + let response = HTTPURLResponse( + url: OpenCodeGoQuotaReader.usageURL, + statusCode: status, httpVersion: nil, headerFields: nil + )! + return (Data(json.utf8), response) + } + ).read() + } + + func testUsagePercentsAreInvertedToRemaining() async { + let result = await read(#"{"usage":{"rolling":{"status":"ok","percent":25,"resetsAt":"2026-11-25T10:00:00Z"},"weekly":{"status":"ok","percent":50,"resetsAt":"2026-11-30T00:00:00Z"},"monthly":{"status":"ok","percent":90,"resetsAt":"2026-12-25T00:00:00Z"}}}"#) + XCTAssertTrue(result.issues.isEmpty) + XCTAssertEqual(result.windows.map(\.label), ["5 hours", "Weekly", "Monthly"]) + XCTAssertEqual(result.windows.map(\.remainingPercent), [75, 50, 10]) + XCTAssertEqual(result.windows.map(\.window), ["5h", "weekly", "monthly"]) + XCTAssertEqual(result.windows.first?.providerKey, "opencode-go") + XCTAssertEqual(result.windows.first?.providerLabel, "OpenCode Go") + XCTAssertEqual(result.windows.first?.resetAt, "2026-11-25T10:00:00Z") + XCTAssertEqual(result.windows.last?.status, .nearCap) + } + + func testRateLimitedWindowIsExhausted() async { + let result = await read(#"{"usage":{"rolling":{"status":"rate-limited","percent":100,"resetsAt":"2026-11-25T10:00:00Z"}}}"#) + XCTAssertEqual(result.windows.count, 1) + XCTAssertEqual(result.windows.first?.remainingPercent, 0) + XCTAssertTrue(result.windows.first?.isExhausted == true) + XCTAssertEqual(result.windows.first?.status, .exhausted) + } + + func testNoLocalKeyIsAbsentWithoutIssue() async { + let result = await read("{}", token: nil) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertTrue(result.issues.isEmpty) + } + + func testRejectedKeyAndMissingSubscriptionWording() async { + let rejected = await read("{}", status: 401) + XCTAssertEqual(rejected.issues["opencode-go"], "OpenCode Go rejected the saved key; sign in again in OpenCode.") + let unsubscribed = await read("{}", status: 403) + XCTAssertEqual(unsubscribed.issues["opencode-go"], "OpenCode Go reports no active Go subscription for this key.") + } + + func testUnparseablePayloadReportsNoReadableQuota() async { + let result = await read(#"{"usage":{"rolling":{"status":"ok"}}}"#) + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["opencode-go"], "OpenCode Go returned no readable quota.") + } + + func testAuthFileGoKeyExtraction() throws { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("opencode-go-tests-\(UUID().uuidString)") + let authDir = home.appendingPathComponent(".local/share/opencode") + try FileManager.default.createDirectory(at: authDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + let auth = #"{"anthropic":{"type":"oauth"},"opencode-go":{"type":"api","key":"go-secret"}}"# + try Data(auth.utf8).write(to: authDir.appendingPathComponent("auth.json")) + XCTAssertEqual(OpenCodeGoQuotaReader.readGoKey(home: home, environment: [:]), "go-secret") + } + + func testAuthFileOAuthOnlyEntryIsAbsent() throws { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("opencode-go-tests-\(UUID().uuidString)") + let authDir = home.appendingPathComponent(".local/share/opencode") + try FileManager.default.createDirectory(at: authDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + try Data(#"{"opencode-go":{"type":"oauth","access":"x"}}"#.utf8) + .write(to: authDir.appendingPathComponent("auth.json")) + XCTAssertNil(OpenCodeGoQuotaReader.readGoKey(home: home, environment: [:])) + } +} diff --git a/Tests/QuotaCoreTests/QuotaPublisherTests.swift b/Tests/QuotaCoreTests/QuotaPublisherTests.swift index 6194f3c9..f0e6b436 100644 --- a/Tests/QuotaCoreTests/QuotaPublisherTests.swift +++ b/Tests/QuotaCoreTests/QuotaPublisherTests.swift @@ -26,6 +26,13 @@ private final class MockSyncProtocol: URLProtocol, @unchecked Sendable { override func stopLoading() {} } +private final class AttemptCounter: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func next() -> Int { lock.lock(); defer { lock.unlock() }; count += 1; return count } + var value: Int { lock.lock(); defer { lock.unlock() }; return count } +} + final class QuotaPublisherTests: XCTestCase { override func tearDown() { MockSyncProtocol.requestHandler = nil @@ -294,6 +301,43 @@ final class QuotaPublisherTests: XCTestCase { XCTAssertEqual(result.message, "Synced 2 quotas (2 persisted, 0 duplicates, 0 pruned).") } + func testPublishRetriesTransientGatewayStatusForV2() async throws { + let responseData = try JSONSerialization.data(withJSONObject: acknowledgment()) + let counter = AttemptCounter() + MockSyncProtocol.requestHandler = { request in + let status = counter.next() < 3 ? 503 : 200 + let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: ["Content-Type": "application/json"])! + return (response, status == 200 ? responseData : Data()) + } + let publisher = QuotaPublisher(urlProtocolClasses: [MockSyncProtocol.self]) + let result = try await publisher.publish( + windows: makeSampleWindows(), + to: URL(string: "https://usage.example.com/api/ingest/usage")!, token: "test-ingest-token") + XCTAssertEqual(counter.value, 3) + XCTAssertEqual(result.statusCode, 200) + } + + func testPublishDoesNotRetryGenericWebhook() async { + let counter = AttemptCounter() + MockSyncProtocol.requestHandler = { request in + _ = counter.next() + let response = HTTPURLResponse(url: request.url!, statusCode: 503, httpVersion: nil, headerFields: nil)! + return (response, Data()) + } + let publisher = QuotaPublisher(urlProtocolClasses: [MockSyncProtocol.self]) + do { + _ = try await publisher.publish( + windows: makeSampleWindows(), + to: URL(string: "https://usage.example.com/hook")!, format: .genericWebhook) + XCTFail("a 503 must surface") + } catch let error as QuotaPublisherError { + guard case .httpStatus(503, _) = error else { return XCTFail("unexpected error: \(error)") } + } catch { + XCTFail("unexpected error: \(error)") + } + XCTAssertEqual(counter.value, 1) + } + func testPublishRejectsMalformedSuccessfulResponses() async { for body in ["", "private-server-detail", "{", "[]", "null", "{}"] { await assertInvalidAcknowledgment(Data(body.utf8), message: "invalid v2 acknowledgment") diff --git a/docs/ENDPOINT-PLUGINS.md b/docs/ENDPOINT-PLUGINS.md new file mode 100644 index 00000000..4d000aff --- /dev/null +++ b/docs/ENDPOINT-PLUGINS.md @@ -0,0 +1,73 @@ +# Endpoint Plugins: Add A Subscription Without A CodeCaps Update + +CodeCaps can monitor an extra AI subscription plan from a declarative +endpoint plugin: a small JSON file that names one quota endpoint and the +JSON paths of the numbers to show. Plugins are data, never code — no +script, shell, dynamic library, or expression is ever run — so a plugin +cannot execute anything, and a bad file is skipped rather than half-applied. + +## Install + +Save one JSON file per plan in +`~/Library/Application Support/CodeCaps/Plugins/` (create the folder first), +then toggle the new row in **Settings → Sources & Fleet**. Removing the +file removes the plan at the next refresh. + +## Example + +```json +{ + "id": "plugin:acme", + "displayName": "Acme Plan", + "providerKey": "acme-plan", + "endpoint": "https://api.example.com/usage", + "auth": { "type": "bearerEnv", "env": "ACME_API_KEY" }, + "windows": [ + { + "idSuffix": "monthly", + "label": "Monthly", + "window": "monthly", + "usedPercentPath": "usage.monthly.percent", + "resetAtPath": "usage.monthly.resetsAt" + } + ] +} +``` + +With `ACME_API_KEY` in CodeCaps' environment, the plugin sends it as a +Bearer token, reads `usage.monthly.percent` as the used percentage, and +shows the remaining percentage resetting at `usage.monthly.resetsAt`. + +## Fields + +| Field | Meaning | +|---|---| +| `id` | `plugin:`; unique, and never a built-in reader's id | +| `displayName` | Row label in Settings and quota cards | +| `providerKey` | Lowercase slug the windows are filed under; built-in provider keys are reserved and refused | +| `endpoint` | One GET endpoint; HTTPS only (loopback HTTP needs `"allowLoopback": true`), no query, fragment, or credentials in the URL | +| `auth` | `{ "type": "none" }` or `{ "type": "bearerEnv", "env": "VAR_NAME" }`; the token value never lives in the file and is never logged | +| `windows` | 1–10 windows; each needs a remaining-percent path, a used-percent path, or an absolute remaining/limit path pair | + +Window paths use a restricted dot/index grammar (`usage.monthly.percent`, +`items[0].remaining`). A reset path may be ISO-8601 text or an epoch +seconds/milliseconds number. Absolute paths (`absoluteRemainingPath`, +`absoluteLimitPath`, `quotaUnit`) show real balances where the endpoint +reports them. + +## Safety Rules + +Endpoints on private, loopback, link-local, or cloud-metadata literal +addresses are refused, redirects are refused, responses are capped, and +every plugin is an optional reader that can be switched off in Settings. +A descriptor is trusted configuration you place on disk — the same trust +class as the push/pull endpoint in Settings — so only install files whose +endpoint you recognise. Anything this format cannot express (OAuth +refresh, request signing, POST bodies) belongs in a built-in reader, not +in a plugin. + +## Built-In Equivalents + +OpenCode Go, Alibaba Token Plan and Coding Plan (the Qwen Code plans), and +Xiaomi MiMo Token Plan (the MiMo Code plan) are built in; see +`docs/TOKEN-PLAN-SOURCES.md`. They do not need plugin files. diff --git a/docs/TOKEN-PLAN-SOURCES.md b/docs/TOKEN-PLAN-SOURCES.md index acecafc6..8a157853 100644 --- a/docs/TOKEN-PLAN-SOURCES.md +++ b/docs/TOKEN-PLAN-SOURCES.md @@ -38,6 +38,26 @@ performs inference. Team and pay-as-you-go keys are not supported. The poll preserves Xiaomi’s reported credit balance and exact billing-cycle end rather than assuming it is monthly. Do not paste the key into a support report. +MiMo Code is a client of this same plan: signing MiMo Code in with an +individual Token Plan key and saving that key above monitors the one shared +allowance. Local `mimo stats` output is consumption history, not remaining +quota, and is never shown as a quota meter. + +## OpenCode Go + +Enable **OpenCode Go** in **Settings → Sources & Fleet** after signing in +with `opencode auth login`. CodeCaps reads the Go key read-only from the +OpenCode CLI's local auth file and checks OpenCode's documented usage +endpoint for the rolling five-hour, weekly, and monthly windows. Local +`opencode stats` output is a consumption estimate, not remaining quota, +and is never shown as a quota meter. + +## Other Plans + +Any other subscription whose provider publishes a quota endpoint can be +added without a CodeCaps update as a declarative endpoint plugin; see +`docs/ENDPOINT-PLUGINS.md`. + Use these with signed-in test subscriptions to verify the Mac settings and quota meters. The fixtures do not prove any specific account or region is eligible. The iPhone companion still uses synced snapshots, not these local collectors. From 8aba0d4882facd147fd3fe6655fb9c37533f61de Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:18:22 -0600 Subject: [PATCH 2/5] Avoid reloading plugin descriptors per logo-style row (Refs OPS-1122) --- Sources/CodeCaps/SettingsViews.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/CodeCaps/SettingsViews.swift b/Sources/CodeCaps/SettingsViews.swift index 7801bd34..020ade8d 100644 --- a/Sources/CodeCaps/SettingsViews.swift +++ b/Sources/CodeCaps/SettingsViews.swift @@ -1156,7 +1156,9 @@ struct SettingsLogoStylePage: View { if let match = model.displaySections.first(where: { $0.id == rowId }) { return match.title } - if let reader = ReaderStatus.current.first(where: { $0.providerKey == rowId }) { + // Built-in rows only here: this label is resolved per row, and the + // plugin-inclusive list reads the Plugins folder from disk. + if let reader = ReaderStatus.all.first(where: { $0.providerKey == rowId }) { return reader.label } switch rowId { From 3d8c4ea334feb34d8001146e480bd671df4526b3 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:29:23 -0600 Subject: [PATCH 3/5] Declare OpenCode Go reader conformance (Refs OPS-1122) --- Sources/QuotaCore/LocalQuotaReaderRegistry.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift index 40c2820d..0d4b0514 100644 --- a/Sources/QuotaCore/LocalQuotaReaderRegistry.swift +++ b/Sources/QuotaCore/LocalQuotaReaderRegistry.swift @@ -12,6 +12,7 @@ extension GrokBotQuotaReader: LocalQuotaReading {} extension GbuQuotaReader: LocalQuotaReading {} extension KimiQuotaReader: LocalQuotaReading {} extension ZCodeQuotaReader: LocalQuotaReading {} +extension OpenCodeGoQuotaReader: LocalQuotaReading {} /// A registered reader and the non-secret configuration metadata used to /// describe it in the app. The factory keeps credential reads inside the From 943f35ea5c931b03556063386c6a2609de802e89 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:43:12 -0600 Subject: [PATCH 4/5] Fix banner string syntax (Refs OPS-1122) --- Sources/CodeCaps/ConsoleViews.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/CodeCaps/ConsoleViews.swift b/Sources/CodeCaps/ConsoleViews.swift index 74771d89..217fe8d5 100644 --- a/Sources/CodeCaps/ConsoleViews.swift +++ b/Sources/CodeCaps/ConsoleViews.swift @@ -337,7 +337,7 @@ struct ConsoleView: View { .accessibilityHidden(true) } if let unavailable = state.unavailableAlert { - Text("Alert source unavailable: \(unavailable.providerKey)\(unavailable.windowId.map { " · \($0)" } ?? "") + "\(sentenceGap)Check Sources & Fleet for this provider.") + Text("Alert source unavailable: \(unavailable.providerKey)\(unavailable.windowId.map { " · \($0)" } ?? "").\(sentenceGap)Check Sources & Fleet for this provider.") .font(.callout) .foregroundStyle(Theme.warning) .padding(.horizontal, Metrics.pagePadding) From 8d1a7af5330aef94f6eb06bb0a94f7a1c3309ed9 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:46:34 -0600 Subject: [PATCH 5/5] Address Kody findings on endpoint plugins (Refs OPS-1122) - Restrict bearerEnv to CODECAPS_PLUGIN_-prefixed variables and name the missing variable in the plugin issue - Refuse non-canonical IP literals (hex/octal/bare-integer/leading-zero) and scope the loopback port exception to loopback hosts only - Reject descriptors with both percent paths; dedicated badDisplayName error - Reject out-of-range percentages instead of clamping them - Cache plugin loads for Settings rows and reader toggles --- Sources/CodeCaps/MonitorModel.swift | 3 +- Sources/CodeCaps/SettingsViews.swift | 2 +- .../QuotaCore/EndpointPluginDescriptor.swift | 46 ++++++++++++++--- Sources/QuotaCore/EndpointPluginLoader.swift | 21 ++++++++ .../GenericEndpointQuotaReader.swift | 16 ++++-- .../QuotaCoreTests/EndpointPluginTests.swift | 50 ++++++++++++++++++- docs/ENDPOINT-PLUGINS.md | 6 +-- 7 files changed, 125 insertions(+), 19 deletions(-) diff --git a/Sources/CodeCaps/MonitorModel.swift b/Sources/CodeCaps/MonitorModel.swift index b2a1208e..b72eda82 100644 --- a/Sources/CodeCaps/MonitorModel.swift +++ b/Sources/CodeCaps/MonitorModel.swift @@ -1356,7 +1356,8 @@ final class MonitorModel: ObservableObject { // folder can be toggled without relaunching the app. Building the // registry only creates factory closures; none is invoked here. let live = LocalQuotaReaderRegistry.configured( - zCodeCredentialProvider: { nil }, mimoCredentialProvider: { nil }) + zCodeCredentialProvider: { nil }, mimoCredentialProvider: { nil }, + pluginDescriptors: EndpointPluginLoader.loadCached()) guard live.optionalRegistrations.contains(where: { $0.id == readerID }), optionalQuotaReaderPreferences.isEnabled(readerID) != enabled else { return } var preferences = optionalQuotaReaderPreferences diff --git a/Sources/CodeCaps/SettingsViews.swift b/Sources/CodeCaps/SettingsViews.swift index 020ade8d..344831e3 100644 --- a/Sources/CodeCaps/SettingsViews.swift +++ b/Sources/CodeCaps/SettingsViews.swift @@ -1030,7 +1030,7 @@ struct ReaderStatus { /// the Plugins folder, so a plugin subscription can be toggled in /// Settings without a CodeCaps update. static var current: [ReaderStatus] { - all + EndpointPluginLoader.load().map { descriptor in + all + EndpointPluginLoader.loadCached().map { descriptor in ReaderStatus(providerKey: descriptor.providerKey, label: descriptor.displayName, source: "Endpoint plugin", optionalReaderID: descriptor.id) } diff --git a/Sources/QuotaCore/EndpointPluginDescriptor.swift b/Sources/QuotaCore/EndpointPluginDescriptor.swift index 39e12768..d238af26 100644 --- a/Sources/QuotaCore/EndpointPluginDescriptor.swift +++ b/Sources/QuotaCore/EndpointPluginDescriptor.swift @@ -95,14 +95,21 @@ public struct EndpointPluginDescriptor: Codable, Equatable, Sendable { /// Why a descriptor was refused. The text is shown nowhere with the file /// contents; it exists for tests and for a one-line Settings note. public enum ValidationError: Error, Equatable, Sendable { - case badID, badProviderKey, reservedProviderKey, badEndpoint, badAuth, badWindows, badPath(String) + case badID, badDisplayName, badProviderKey, reservedProviderKey, badEndpoint, badAuth, badWindows, badPath(String) + } + + /// The only environment variables a plugin may send: a plugin file can + /// name a purpose-made variable, never a general-purpose secret that + /// happens to be in the app's environment. + public static func isPluginEnvName(_ name: String) -> Bool { + name.range(of: "^CODECAPS_PLUGIN_[A-Z0-9_]{1,100}$", options: .regularExpression) != nil } public func validated() throws -> EndpointPluginDescriptor { guard Self.isSlug(id, prefix: "plugin:") else { throw ValidationError.badID } guard Self.isSlug(providerKey, prefix: "") else { throw ValidationError.badProviderKey } guard !Self.reservedProviderKeys.contains(providerKey) else { throw ValidationError.reservedProviderKey } - guard (1...200).contains(displayName.count), !displayName.contains("\n") else { throw ValidationError.badID } + guard (1...200).contains(displayName.count), !displayName.contains("\n") else { throw ValidationError.badDisplayName } guard let url = Self.validatedEndpoint(endpoint, allowLoopback: allowLoopback ?? false) else { throw ValidationError.badEndpoint } @@ -111,16 +118,17 @@ public struct EndpointPluginDescriptor: Codable, Equatable, Sendable { case .none: if auth.env != nil { throw ValidationError.badAuth } case .bearerEnv: - guard let env = auth.env, - env.range(of: "^[A-Za-z_][A-Za-z0-9_]{0,127}$", options: .regularExpression) != nil + guard let env = auth.env, Self.isPluginEnvName(env) else { throw ValidationError.badAuth } } guard (1...10).contains(windows.count) else { throw ValidationError.badWindows } var suffixes = Set() for window in windows { + let percentPaths = [window.remainingPercentPath, window.usedPercentPath].compactMap { $0 }.count guard Self.isSlug(window.idSuffix, prefix: ""), suffixes.insert(window.idSuffix).inserted, (1...80).contains(window.label.count), - (window.remainingPercentPath == nil) != (window.usedPercentPath == nil) + percentPaths <= 1, + percentPaths == 1 || (window.absoluteRemainingPath != nil && window.absoluteLimitPath != nil) else { throw ValidationError.badWindows } for path in [window.remainingPercentPath, window.usedPercentPath, window.absoluteRemainingPath, @@ -159,23 +167,45 @@ public struct EndpointPluginDescriptor: Codable, Equatable, Sendable { guard let components = URLComponents(string: raw), let rawHost = components.host?.lowercased(), !rawHost.isEmpty, components.user == nil, components.password == nil, - components.query == nil, components.fragment == nil, - components.port == nil || components.port == 443 || allowLoopback else { return nil } + components.query == nil, components.fragment == nil else { return nil } // An IPv6 literal may still carry its brackets depending on the // URL parser; compare the bare address either way. let host = rawHost.hasPrefix("[") && rawHost.hasSuffix("]") ? String(rawHost.dropFirst().dropLast()) : rawHost let loopback = host == "localhost" || host == "127.0.0.1" || host == "::1" + // The port relaxation belongs to loopback only; an external host + // keeps the default-or-443 rule even when the opt-in is set. + if let port = components.port, port != 443 { + guard allowLoopback, loopback else { return nil } + } if components.scheme == "http" { guard allowLoopback, loopback else { return nil } } else { guard components.scheme == "https" else { return nil } } if loopback { return allowLoopback ? components.url : nil } - if isPrivateLiteralIP(host) { return nil } + if isPrivateLiteralIP(host) || isNonCanonicalIPLiteral(host) { return nil } return components.url } + /// A host written like an IP address but not as a strict decimal + /// dotted quad — hex (`0x7f.0.0.1`), octal (`0177.0.0.1`), a bare + /// integer (`2130706433`), or a leading-zero octet — can be resolved + /// by the network stack as the private address it disguises, so it is + /// refused outright rather than classified as a public hostname. + static func isNonCanonicalIPLiteral(_ host: String) -> Bool { + let segments = host.split(separator: ".", omittingEmptySubsequences: false) + let numericLike = segments.allSatisfy { segment in + !segment.isEmpty && segment.range(of: "^(0[xX][0-9a-fA-F]+|[0-9]+)$", options: .regularExpression) != nil + } + guard numericLike, segments.contains(where: { Int($0) != nil || $0.lowercased().hasPrefix("0x") }) else { return false } + guard segments.count == 4 else { return true } + return segments.contains { segment in + guard let value = Int(segment), String(value) == segment, (0...255).contains(value) else { return true } + return false + } + } + static func isPrivateLiteralIP(_ host: String) -> Bool { let ipv4 = host.split(separator: ".").map { Int($0) } if ipv4.count == 4, ipv4.allSatisfy({ $0 != nil }) { diff --git a/Sources/QuotaCore/EndpointPluginLoader.swift b/Sources/QuotaCore/EndpointPluginLoader.swift index abdbb39c..e6f51f8b 100644 --- a/Sources/QuotaCore/EndpointPluginLoader.swift +++ b/Sources/QuotaCore/EndpointPluginLoader.swift @@ -17,6 +17,27 @@ public enum EndpointPluginLoader { .appendingPathComponent("Library/Application Support/CodeCaps/Plugins", isDirectory: true) } + private final class Cache: @unchecked Sendable { + let lock = NSLock() + var descriptors: [EndpointPluginDescriptor] = [] + var loadedAt: Date = .distantPast + } + + private static let cache = Cache() + + /// A short-lived cache of the default folder for main-thread callers + /// (Settings rows, reader toggles) that cannot rescan the disk on every + /// access. The refresh path keeps using `load()` directly, so a new + /// plugin file is picked up within one refresh regardless. + public static func loadCached(ttl: TimeInterval = 60) -> [EndpointPluginDescriptor] { + cache.lock.lock() + defer { cache.lock.unlock() } + if Date().timeIntervalSince(cache.loadedAt) <= ttl { return cache.descriptors } + cache.descriptors = load() + cache.loadedAt = Date() + return cache.descriptors + } + public static func load(directory: URL = defaultDirectory) -> [EndpointPluginDescriptor] { let manager = FileManager.default guard let entries = try? manager.contentsOfDirectory( diff --git a/Sources/QuotaCore/GenericEndpointQuotaReader.swift b/Sources/QuotaCore/GenericEndpointQuotaReader.swift index 065c2831..13d4dab6 100644 --- a/Sources/QuotaCore/GenericEndpointQuotaReader.swift +++ b/Sources/QuotaCore/GenericEndpointQuotaReader.swift @@ -28,7 +28,13 @@ public struct GenericEndpointQuotaReader: LocalQuotaReading, Sendable { self.token = { nil } case .bearerEnv: let name = descriptor.auth.env ?? "" - self.token = { environment[name].flatMap { $0.isEmpty ? nil : $0 } } + // Defence in depth behind descriptor validation: only a + // purpose-made plugin variable is ever read, whatever a + // hand-built descriptor claims. + self.token = { + guard EndpointPluginDescriptor.isPluginEnvName(name) else { return nil } + return environment[name].flatMap { $0.isEmpty ? nil : $0 } + } } self.fetch = fetch ?? Self.makeFetcher() } @@ -46,7 +52,7 @@ public struct GenericEndpointQuotaReader: LocalQuotaReading, Sendable { request.setValue("application/json", forHTTPHeaderField: "Accept") if descriptor.auth.type == .bearerEnv { guard let token = token() else { - return LocalQuotaResult(issues: [id: "\(descriptor.displayName) plugin needs its configured sign-in key."]) + return LocalQuotaResult(issues: [id: "\(descriptor.displayName) plugin needs the \(descriptor.auth.env ?? "configured") environment variable set."]) } request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } @@ -91,8 +97,10 @@ public struct GenericEndpointQuotaReader: LocalQuotaReading, Sendable { } else { remaining = nil } - guard let remaining, remaining.isFinite else { return nil } - let bounded = min(100, max(0, remaining)) + // An out-of-range percentage is a broken endpoint answer, not + // a full or empty quota; drop the window as unreadable. + guard let remaining, remaining.isFinite, (0...100).contains(remaining) else { return nil } + let bounded = remaining return QuotaWindow( id: descriptor.providerKey + ":" + spec.idSuffix, provider: descriptor.providerKey, providerKey: descriptor.providerKey, diff --git a/Tests/QuotaCoreTests/EndpointPluginTests.swift b/Tests/QuotaCoreTests/EndpointPluginTests.swift index 999dd715..95ad5dbf 100644 --- a/Tests/QuotaCoreTests/EndpointPluginTests.swift +++ b/Tests/QuotaCoreTests/EndpointPluginTests.swift @@ -38,6 +38,10 @@ final class EndpointPluginTests: XCTestCase { "https://172.16.0.5/usage", "https://192.168.1.5/usage", "https://[::1]/usage", + "https://0x7f.0.0.1/usage", + "https://0177.0.0.1/usage", + "https://2130706433/usage", + "https://08.8.8.8/usage", "ftp://api.example.com/usage", ] for endpoint in refused { @@ -46,6 +50,33 @@ final class EndpointPluginTests: XCTestCase { XCTAssertNoThrow(try descriptor(endpoint: "https://8.8.8.8/usage").validated()) } + func testExternalHostKeepsDefaultPortEvenWithLoopbackOptIn() throws { + var external = descriptor(endpoint: "https://8.8.8.8:8080/usage") + external.allowLoopback = true + XCTAssertThrowsError(try external.validated()) + } + + func testBothPercentPathsAreRefusedEvenWithAbsolutes() { + var both = descriptor() + both.windows[0].remainingPercentPath = "usage.monthly.remaining" + both.windows[0].absoluteRemainingPath = "usage.monthly.left" + both.windows[0].absoluteLimitPath = "usage.monthly.total" + XCTAssertThrowsError(try both.validated()) + } + + func testBadDisplayNameHasItsOwnError() { + var bad = descriptor() + bad.displayName = "" + XCTAssertThrowsError(try bad.validated()) { error in + XCTAssertEqual(error as? EndpointPluginDescriptor.ValidationError, .badDisplayName) + } + } + + func testNonPluginEnvNameIsRefused() { + XCTAssertThrowsError(try descriptor(auth: .init(type: .bearerEnv, env: "AWS_SECRET_ACCESS_KEY")).validated()) + XCTAssertNoThrow(try descriptor(auth: .init(type: .bearerEnv, env: "CODECAPS_PLUGIN_ACME_API_KEY")).validated()) + } + func testLoopbackNeedsExplicitOptIn() throws { XCTAssertThrowsError(try descriptor(endpoint: "http://127.0.0.1:8080/usage").validated()) var loopback = descriptor(endpoint: "http://127.0.0.1:8080/usage") @@ -83,14 +114,29 @@ final class EndpointPluginTests: XCTestCase { XCTAssertEqual(result.windows.first?.source, "plugin:acme") } + func testGenericReaderDropsOutOfRangePercent() async { + let reader = GenericEndpointQuotaReader( + descriptor: descriptor(), environment: [:], + now: { Date(timeIntervalSince1970: 0) }, + fetch: { _ in + let response = HTTPURLResponse( + url: URL(string: "https://api.example.com/usage")!, + statusCode: 200, httpVersion: nil, headerFields: nil)! + return (Data(#"{"usage":{"monthly":{"percent":140}}}"#.utf8), response) + }) + let result = await reader.read() + XCTAssertTrue(result.windows.isEmpty) + XCTAssertEqual(result.issues["acme-plan"], "Acme Plan returned no readable quota.") + } + func testGenericReaderMissingEnvKeyReportsSignIn() async { let reader = GenericEndpointQuotaReader( - descriptor: descriptor(auth: .init(type: .bearerEnv, env: "ACME_MISSING_KEY")), + descriptor: descriptor(auth: .init(type: .bearerEnv, env: "CODECAPS_PLUGIN_ACME_KEY")), environment: [:], fetch: { _ in XCTFail("fetch must not run without the configured key"); throw URLError(.badURL) }) let result = await reader.read() XCTAssertTrue(result.windows.isEmpty) - XCTAssertEqual(result.issues["acme-plan"], "Acme Plan plugin needs its configured sign-in key.") + XCTAssertEqual(result.issues["acme-plan"], "Acme Plan plugin needs the CODECAPS_PLUGIN_ACME_KEY environment variable set.") } func testLoaderSkipsInvalidAndDuplicateFiles() throws { diff --git a/docs/ENDPOINT-PLUGINS.md b/docs/ENDPOINT-PLUGINS.md index 4d000aff..d684c852 100644 --- a/docs/ENDPOINT-PLUGINS.md +++ b/docs/ENDPOINT-PLUGINS.md @@ -21,7 +21,7 @@ file removes the plan at the next refresh. "displayName": "Acme Plan", "providerKey": "acme-plan", "endpoint": "https://api.example.com/usage", - "auth": { "type": "bearerEnv", "env": "ACME_API_KEY" }, + "auth": { "type": "bearerEnv", "env": "CODECAPS_PLUGIN_ACME_API_KEY" }, "windows": [ { "idSuffix": "monthly", @@ -34,7 +34,7 @@ file removes the plan at the next refresh. } ``` -With `ACME_API_KEY` in CodeCaps' environment, the plugin sends it as a +With `CODECAPS_PLUGIN_ACME_API_KEY` in CodeCaps' environment, the plugin sends it as a Bearer token, reads `usage.monthly.percent` as the used percentage, and shows the remaining percentage resetting at `usage.monthly.resetsAt`. @@ -46,7 +46,7 @@ shows the remaining percentage resetting at `usage.monthly.resetsAt`. | `displayName` | Row label in Settings and quota cards | | `providerKey` | Lowercase slug the windows are filed under; built-in provider keys are reserved and refused | | `endpoint` | One GET endpoint; HTTPS only (loopback HTTP needs `"allowLoopback": true`), no query, fragment, or credentials in the URL | -| `auth` | `{ "type": "none" }` or `{ "type": "bearerEnv", "env": "VAR_NAME" }`; the token value never lives in the file and is never logged | +| `auth` | `{ "type": "none" }` or `{ "type": "bearerEnv", "env": "CODECAPS_PLUGIN_VAR_NAME" }` (only `CODECAPS_PLUGIN_`-prefixed variables may be named, so a plugin can never send a general-purpose secret); the token value never lives in the file and is never logged | | `windows` | 1–10 windows; each needs a remaining-percent path, a used-percent path, or an absolute remaining/limit path pair | Window paths use a restricted dot/index grammar (`usage.monthly.percent`,