@sriinnu/runic 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (584) hide show
  1. package/.swiftformat +50 -0
  2. package/.swiftlint.yml +160 -0
  3. package/CHANGELOG.md +307 -0
  4. package/CONTRIBUTING.md +456 -0
  5. package/Icon.icns +0 -0
  6. package/Icon.icon/Assets/runic.png +0 -0
  7. package/Icon.icon/icon.json +36 -0
  8. package/LICENSE +21 -0
  9. package/Package.resolved +51 -0
  10. package/Package.swift +136 -0
  11. package/Packages/Helix/LICENSE +21 -0
  12. package/Packages/Helix/Package.swift +29 -0
  13. package/Packages/Helix/README.md +976 -0
  14. package/Packages/Helix/Sources/Helix/Binding.swift +111 -0
  15. package/Packages/Helix/Sources/Helix/CommandParser.swift +160 -0
  16. package/Packages/Helix/Sources/Helix/CommandSignature.swift +117 -0
  17. package/Packages/Helix/Sources/Helix/ExpressibleFromArgument.swift +72 -0
  18. package/Packages/Helix/Sources/Helix/HelpGenerator.swift +175 -0
  19. package/Packages/Helix/Sources/Helix/NameSpecification.swift +98 -0
  20. package/Packages/Helix/Sources/Helix/ParsableCommand.swift +204 -0
  21. package/Packages/Helix/Sources/Helix/Platform/DarwinPlatformContext.swift +44 -0
  22. package/Packages/Helix/Sources/Helix/Platform/LinuxPlatformContext.swift +34 -0
  23. package/Packages/Helix/Sources/Helix/Platform/PlatformContext+Default.swift +91 -0
  24. package/Packages/Helix/Sources/Helix/Platform/PlatformContext.swift +94 -0
  25. package/Packages/Helix/Sources/Helix/Platform/PlatformPath.swift +167 -0
  26. package/Packages/Helix/Sources/Helix/Platform/Stdio.swift +99 -0
  27. package/Packages/Helix/Sources/Helix/Platform/WebPlatformContext.swift +146 -0
  28. package/Packages/Helix/Sources/Helix/Platform/WindowsPlatformContext.swift +97 -0
  29. package/Packages/Helix/Sources/Helix/Program.swift +204 -0
  30. package/Packages/Helix/Sources/Helix/PropertyWrappers.swift +367 -0
  31. package/Packages/Silo/LICENSE +21 -0
  32. package/Packages/Silo/Package.swift +34 -0
  33. package/Packages/Silo/README.md +466 -0
  34. package/Packages/Silo/Sources/Silo/BinaryCookiesReader.swift +169 -0
  35. package/Packages/Silo/Sources/Silo/BrowserCookieAnalytics.swift +365 -0
  36. package/Packages/Silo/Sources/Silo/BrowserCookieBackends.swift +594 -0
  37. package/Packages/Silo/Sources/Silo/BrowserCookieClient.swift +326 -0
  38. package/Packages/Silo/Sources/Silo/BrowserCookieExport.swift +154 -0
  39. package/Packages/Silo/Sources/Silo/BrowserCookieImport.swift +119 -0
  40. package/Packages/Silo/Sources/Silo/BrowserCookieMockStore.swift +121 -0
  41. package/Packages/Silo/Sources/Silo/BrowserCookieModels.swift +391 -0
  42. package/Packages/Silo/Sources/Silo/ChromiumCookieReader.swift +240 -0
  43. package/Packages/Silo/Sources/Silo/CryptoSupport.swift +86 -0
  44. package/Packages/Silo/Sources/Silo/FirefoxCookieReader.swift +172 -0
  45. package/Packages/Silo/Sources/Silo/LinuxChromiumCookieReader.swift +172 -0
  46. package/Packages/Silo/Sources/Silo/LinuxSecretService.swift +105 -0
  47. package/Packages/Silo/Sources/Silo/MacOSChromiumCookieReader.swift +191 -0
  48. package/Packages/Silo/Sources/Silo/SQLiteSnapshot.swift +41 -0
  49. package/Packages/Silo/Sources/Silo/WindowsChromiumCookieReader.swift +110 -0
  50. package/README.md +109 -0
  51. package/RuniciOS/App/RuniciOSApp.swift +105 -0
  52. package/RuniciOS/Core/iOSUsageStore.swift +192 -0
  53. package/RuniciOS/Views/ProviderDetailView.swift +312 -0
  54. package/RuniciOS/Views/ProviderListView.swift +228 -0
  55. package/RuniciOS/Widgets/LargeWidget.swift +367 -0
  56. package/RuniciOS/Widgets/LiveActivity.swift +342 -0
  57. package/RuniciOS/Widgets/LockScreenWidget.swift +273 -0
  58. package/RuniciOS/Widgets/MediumWidget.swift +370 -0
  59. package/RuniciOS/Widgets/RunicWidget.swift +274 -0
  60. package/RuniciOS/Widgets/SmallWidget.swift +281 -0
  61. package/RuniciOS/Widgets/WidgetModels.swift +285 -0
  62. package/RuniciOS/Widgets/WidgetTimeline.swift +270 -0
  63. package/Scripts/CREATION-SUMMARY.md +367 -0
  64. package/Scripts/DIRECTORY-STRUCTURE.md +358 -0
  65. package/Scripts/GETTING-STARTED-CHECKLIST.md +364 -0
  66. package/Scripts/INDEX.md +365 -0
  67. package/Scripts/QUICK-REFERENCE.md +164 -0
  68. package/Scripts/README-SCRIPTS.md +926 -0
  69. package/Scripts/build-android.sh +526 -0
  70. package/Scripts/build-ios.sh +529 -0
  71. package/Scripts/build-macos.sh +603 -0
  72. package/Scripts/build-windows.sh +504 -0
  73. package/Scripts/build_icon.sh +49 -0
  74. package/Scripts/changelog-to-html.sh +89 -0
  75. package/Scripts/check-release-assets.sh +10 -0
  76. package/Scripts/ci-config.yml +474 -0
  77. package/Scripts/compile_and_run.sh +219 -0
  78. package/Scripts/compile_and_run_adhoc.sh +4 -0
  79. package/Scripts/docs-list.mjs +119 -0
  80. package/Scripts/make_appcast.sh +58 -0
  81. package/Scripts/package_app.sh +409 -0
  82. package/Scripts/release-lib.sh +214 -0
  83. package/Scripts/release.sh +76 -0
  84. package/Scripts/setup-all.sh +387 -0
  85. package/Scripts/setup-ios.sh +404 -0
  86. package/Scripts/setup-react-native.sh +523 -0
  87. package/Scripts/sign-and-notarize.sh +122 -0
  88. package/Scripts/test_live_update.sh +38 -0
  89. package/Scripts/validate_changelog.sh +23 -0
  90. package/Scripts/verify_appcast.sh +92 -0
  91. package/Sources/Runic/About.swift +93 -0
  92. package/Sources/Runic/AppNotifications.swift +115 -0
  93. package/Sources/Runic/Controllers/StatusItemController+Actions.swift +657 -0
  94. package/Sources/Runic/Controllers/StatusItemController+Animation.swift +518 -0
  95. package/Sources/Runic/Controllers/StatusItemController+ChartSubmenus.swift +810 -0
  96. package/Sources/Runic/Controllers/StatusItemController+CustomProviders.swift +87 -0
  97. package/Sources/Runic/Controllers/StatusItemController+Menu.swift +1379 -0
  98. package/Sources/Runic/Controllers/StatusItemController+MenuCards.swift +337 -0
  99. package/Sources/Runic/Controllers/StatusItemController+MenuHelpers.swift +395 -0
  100. package/Sources/Runic/Controllers/StatusItemController.swift +360 -0
  101. package/Sources/Runic/Core/BudgetNotificationManager.swift +80 -0
  102. package/Sources/Runic/Core/Login/ClaudeLoginRunner.swift +103 -0
  103. package/Sources/Runic/Core/Login/CodexLoginRunner.swift +154 -0
  104. package/Sources/Runic/Core/Login/CursorLoginRunner.swift +206 -0
  105. package/Sources/Runic/Core/Login/GeminiLoginRunner.swift +95 -0
  106. package/Sources/Runic/Core/Rendering/IconRenderer.swift +1216 -0
  107. package/Sources/Runic/Core/Rendering/IconView.swift +120 -0
  108. package/Sources/Runic/Core/Rendering/ProviderBrandIcon.swift +71 -0
  109. package/Sources/Runic/Core/RunicAnimation.swift +53 -0
  110. package/Sources/Runic/Core/RunicColors.swift +73 -0
  111. package/Sources/Runic/Core/RunicCornerRadius.swift +15 -0
  112. package/Sources/Runic/Core/RunicSpacing.swift +68 -0
  113. package/Sources/Runic/Core/Stores/AuggieTokenStore.swift +143 -0
  114. package/Sources/Runic/Core/Stores/AzureOpenAITokenStore.swift +143 -0
  115. package/Sources/Runic/Core/Stores/CerebrasTokenStore.swift +143 -0
  116. package/Sources/Runic/Core/Stores/CohereTokenStore.swift +143 -0
  117. package/Sources/Runic/Core/Stores/CopilotTokenStore.swift +143 -0
  118. package/Sources/Runic/Core/Stores/CustomProviderStore.swift +158 -0
  119. package/Sources/Runic/Core/Stores/DeepSeekTokenStore.swift +143 -0
  120. package/Sources/Runic/Core/Stores/FireworksTokenStore.swift +143 -0
  121. package/Sources/Runic/Core/Stores/GroqTokenStore.swift +143 -0
  122. package/Sources/Runic/Core/Stores/KimiTokenStore.swift +143 -0
  123. package/Sources/Runic/Core/Stores/MiniMaxCookieHeaderStore.swift +143 -0
  124. package/Sources/Runic/Core/Stores/MiniMaxGroupIDStore.swift +143 -0
  125. package/Sources/Runic/Core/Stores/MiniMaxTokenStore.swift +143 -0
  126. package/Sources/Runic/Core/Stores/MistralTokenStore.swift +143 -0
  127. package/Sources/Runic/Core/Stores/OpenRouterTokenStore.swift +143 -0
  128. package/Sources/Runic/Core/Stores/PerplexityTokenStore.swift +143 -0
  129. package/Sources/Runic/Core/Stores/ProviderToggleStore.swift +30 -0
  130. package/Sources/Runic/Core/Stores/QwenTokenStore.swift +143 -0
  131. package/Sources/Runic/Core/Stores/SambaNovaTokenStore.swift +143 -0
  132. package/Sources/Runic/Core/Stores/SettingsStore.swift +1702 -0
  133. package/Sources/Runic/Core/Stores/TogetherTokenStore.swift +143 -0
  134. package/Sources/Runic/Core/Stores/UsageStore+Accessors.swift +20 -0
  135. package/Sources/Runic/Core/Stores/UsageStore+Status.swift +189 -0
  136. package/Sources/Runic/Core/Stores/UsageStore+TokenCost.swift +33 -0
  137. package/Sources/Runic/Core/Stores/UsageStore+WidgetSnapshot.swift +67 -0
  138. package/Sources/Runic/Core/Stores/UsageStore.swift +3564 -0
  139. package/Sources/Runic/Core/Stores/XAITokenStore.swift +143 -0
  140. package/Sources/Runic/Core/Stores/ZaiTokenStore.swift +143 -0
  141. package/Sources/Runic/Core/UsageExporter.swift +193 -0
  142. package/Sources/Runic/Date+RelativeDescription.swift +21 -0
  143. package/Sources/Runic/HiddenWindowView.swift +32 -0
  144. package/Sources/Runic/InstallOrigin.swift +9 -0
  145. package/Sources/Runic/KeyboardShortcuts+Names.swift +6 -0
  146. package/Sources/Runic/MouseLocationReader.swift +65 -0
  147. package/Sources/Runic/Notifications+Runic.swift +6 -0
  148. package/Sources/Runic/OpenAICreditsPurchaseWindowController.swift +503 -0
  149. package/Sources/Runic/ProviderRegistry.swift +100 -0
  150. package/Sources/Runic/ProviderSwitcherButtons.swift +267 -0
  151. package/Sources/Runic/Providers/Antigravity/AntigravityLoginFlow.swift +11 -0
  152. package/Sources/Runic/Providers/Antigravity/AntigravityProviderImplementation.swift +14 -0
  153. package/Sources/Runic/Providers/Auggie/AuggieProviderImplementation.swift +24 -0
  154. package/Sources/Runic/Providers/Azure/AzureProviderImplementation.swift +52 -0
  155. package/Sources/Runic/Providers/Bedrock/BedrockProviderImplementation.swift +42 -0
  156. package/Sources/Runic/Providers/Cerebras/CerebrasProviderImplementation.swift +24 -0
  157. package/Sources/Runic/Providers/Claude/ClaudeLoginFlow.swift +26 -0
  158. package/Sources/Runic/Providers/Claude/ClaudeProviderImplementation.swift +14 -0
  159. package/Sources/Runic/Providers/Codex/CodexLoginFlow.swift +18 -0
  160. package/Sources/Runic/Providers/Codex/CodexProviderImplementation.swift +15 -0
  161. package/Sources/Runic/Providers/Cohere/CohereProviderImplementation.swift +24 -0
  162. package/Sources/Runic/Providers/Copilot/CopilotLoginFlow.swift +193 -0
  163. package/Sources/Runic/Providers/Copilot/CopilotProviderImplementation.swift +110 -0
  164. package/Sources/Runic/Providers/Cursor/CursorLoginFlow.swift +28 -0
  165. package/Sources/Runic/Providers/Cursor/CursorProviderImplementation.swift +15 -0
  166. package/Sources/Runic/Providers/DeepSeek/DeepSeekProviderImplementation.swift +24 -0
  167. package/Sources/Runic/Providers/Factory/FactoryLoginFlow.swift +12 -0
  168. package/Sources/Runic/Providers/Factory/FactoryProviderImplementation.swift +15 -0
  169. package/Sources/Runic/Providers/Fireworks/FireworksProviderImplementation.swift +24 -0
  170. package/Sources/Runic/Providers/Gemini/GeminiLoginFlow.swift +20 -0
  171. package/Sources/Runic/Providers/Gemini/GeminiProviderImplementation.swift +15 -0
  172. package/Sources/Runic/Providers/Groq/GroqProviderImplementation.swift +24 -0
  173. package/Sources/Runic/Providers/Kimi/KimiProviderImplementation.swift +24 -0
  174. package/Sources/Runic/Providers/MiniMax/MiniMaxProviderImplementation.swift +32 -0
  175. package/Sources/Runic/Providers/Mistral/MistralProviderImplementation.swift +24 -0
  176. package/Sources/Runic/Providers/OpenRouter/OpenRouterProviderImplementation.swift +24 -0
  177. package/Sources/Runic/Providers/Perplexity/PerplexityProviderImplementation.swift +24 -0
  178. package/Sources/Runic/Providers/SambaNova/SambaNovaProviderImplementation.swift +24 -0
  179. package/Sources/Runic/Providers/Shared/ProviderCatalog.swift +15 -0
  180. package/Sources/Runic/Providers/Shared/ProviderImplementation.swift +48 -0
  181. package/Sources/Runic/Providers/Shared/ProviderImplementationRegistry.swift +66 -0
  182. package/Sources/Runic/Providers/Shared/ProviderLoginFlow.swift +12 -0
  183. package/Sources/Runic/Providers/Shared/ProviderSettingsDescriptors.swift +99 -0
  184. package/Sources/Runic/Providers/Shared/SystemSettingsLinks.swift +18 -0
  185. package/Sources/Runic/Providers/Together/TogetherProviderImplementation.swift +24 -0
  186. package/Sources/Runic/Providers/XAI/XAIProviderImplementation.swift +24 -0
  187. package/Sources/Runic/Providers/Zai/ZaiProviderImplementation.swift +24 -0
  188. package/Sources/Runic/Resources/ProviderIcon-antigravity.svg +2 -0
  189. package/Sources/Runic/Resources/ProviderIcon-auggie.svg +3 -0
  190. package/Sources/Runic/Resources/ProviderIcon-azure.svg +5 -0
  191. package/Sources/Runic/Resources/ProviderIcon-bedrock.svg +7 -0
  192. package/Sources/Runic/Resources/ProviderIcon-cerebras.svg +3 -0
  193. package/Sources/Runic/Resources/ProviderIcon-claude.svg +1 -0
  194. package/Sources/Runic/Resources/ProviderIcon-codex.svg +1 -0
  195. package/Sources/Runic/Resources/ProviderIcon-cohere.svg +3 -0
  196. package/Sources/Runic/Resources/ProviderIcon-copilot.svg +1 -0
  197. package/Sources/Runic/Resources/ProviderIcon-cursor.svg +3 -0
  198. package/Sources/Runic/Resources/ProviderIcon-deepseek.svg +4 -0
  199. package/Sources/Runic/Resources/ProviderIcon-factory.svg +3 -0
  200. package/Sources/Runic/Resources/ProviderIcon-fireworks.svg +3 -0
  201. package/Sources/Runic/Resources/ProviderIcon-gemini.svg +1 -0
  202. package/Sources/Runic/Resources/ProviderIcon-groq.svg +1 -0
  203. package/Sources/Runic/Resources/ProviderIcon-kimi.svg +4 -0
  204. package/Sources/Runic/Resources/ProviderIcon-minimax.svg +1 -0
  205. package/Sources/Runic/Resources/ProviderIcon-mistral.svg +5 -0
  206. package/Sources/Runic/Resources/ProviderIcon-openrouter.svg +7 -0
  207. package/Sources/Runic/Resources/ProviderIcon-perplexity.svg +4 -0
  208. package/Sources/Runic/Resources/ProviderIcon-qwen.svg +9 -0
  209. package/Sources/Runic/Resources/ProviderIcon-sambanova.svg +4 -0
  210. package/Sources/Runic/Resources/ProviderIcon-together.svg +5 -0
  211. package/Sources/Runic/Resources/ProviderIcon-vertexai.svg +17 -0
  212. package/Sources/Runic/Resources/ProviderIcon-xai.svg +3 -0
  213. package/Sources/Runic/Resources/ProviderIcon-zai.svg +5 -0
  214. package/Sources/Runic/Resources/RunicMenubarIcon.svg +7 -0
  215. package/Sources/Runic/RunicApp.swift +357 -0
  216. package/Sources/Runic/SessionQuotaNotifications.swift +58 -0
  217. package/Sources/Runic/UsagePaceText.swift +52 -0
  218. package/Sources/Runic/UsageProgressBar.swift +224 -0
  219. package/Sources/Runic/Utilities/DisplayLink.swift +96 -0
  220. package/Sources/Runic/Utilities/LoadingPattern.swift +60 -0
  221. package/Sources/Runic/Utilities/PerformanceConstants.swift +85 -0
  222. package/Sources/Runic/Views/Menu/AlertsMenuView.swift +256 -0
  223. package/Sources/Runic/Views/Menu/ChartPanelStyle.swift +22 -0
  224. package/Sources/Runic/Views/Menu/CostComparativeChartMenuView.swift +275 -0
  225. package/Sources/Runic/Views/Menu/CostHistoryChartMenuView.swift +377 -0
  226. package/Sources/Runic/Views/Menu/CreditsHistoryChartMenuView.swift +312 -0
  227. package/Sources/Runic/Views/Menu/EfficiencyMetricsMenuView.swift +312 -0
  228. package/Sources/Runic/Views/Menu/HeroStatCardsMenuView.swift +228 -0
  229. package/Sources/Runic/Views/Menu/HourlyActivityChartMenuView.swift +228 -0
  230. package/Sources/Runic/Views/Menu/InlineUsageChartView.swift +162 -0
  231. package/Sources/Runic/Views/Menu/MenuCardEntranceModifier.swift +64 -0
  232. package/Sources/Runic/Views/Menu/MenuCardSidebarView.swift +268 -0
  233. package/Sources/Runic/Views/Menu/MenuCardSkeletonView.swift +104 -0
  234. package/Sources/Runic/Views/Menu/MenuCardView.swift +1900 -0
  235. package/Sources/Runic/Views/Menu/MenuContent.swift +150 -0
  236. package/Sources/Runic/Views/Menu/MenuDescriptor.swift +369 -0
  237. package/Sources/Runic/Views/Menu/MenuHighlightStyle.swift +42 -0
  238. package/Sources/Runic/Views/Menu/ModelBreakdownMenuView.swift +235 -0
  239. package/Sources/Runic/Views/Menu/OverviewMenuView.swift +141 -0
  240. package/Sources/Runic/Views/Menu/ProjectBreakdownMenuView.swift +209 -0
  241. package/Sources/Runic/Views/Menu/ProjectBudgetMenuView.swift +220 -0
  242. package/Sources/Runic/Views/Menu/ProviderTabBarView.swift +88 -0
  243. package/Sources/Runic/Views/Menu/SubscriptionUtilizationChartMenuView.swift +201 -0
  244. package/Sources/Runic/Views/Menu/UsageBreakdownChartMenuView.swift +398 -0
  245. package/Sources/Runic/Views/Menu/UsageHeatmapMenuView.swift +232 -0
  246. package/Sources/Runic/Views/Menu/UsageTimelineChartMenuView.swift +417 -0
  247. package/Sources/Runic/Views/Menu/UsageWindowComparisonChartMenuView.swift +190 -0
  248. package/Sources/Runic/Views/Menu/WeeklyActivityChartMenuView.swift +132 -0
  249. package/Sources/Runic/Views/Performance/PerformanceDashboardView.swift +618 -0
  250. package/Sources/Runic/Views/Preferences/LiquidComponents.swift +305 -0
  251. package/Sources/Runic/Views/Preferences/PreferencesAboutPane.swift +271 -0
  252. package/Sources/Runic/Views/Preferences/PreferencesAdvancedPane.swift +268 -0
  253. package/Sources/Runic/Views/Preferences/PreferencesAlertsPane.swift +422 -0
  254. package/Sources/Runic/Views/Preferences/PreferencesAnalyticsPane.swift +641 -0
  255. package/Sources/Runic/Views/Preferences/PreferencesBudgetsPane.swift +344 -0
  256. package/Sources/Runic/Views/Preferences/PreferencesComponents.swift +230 -0
  257. package/Sources/Runic/Views/Preferences/PreferencesCustomProvidersPane.swift +322 -0
  258. package/Sources/Runic/Views/Preferences/PreferencesDebugPane.swift +469 -0
  259. package/Sources/Runic/Views/Preferences/PreferencesGeneralPane.swift +231 -0
  260. package/Sources/Runic/Views/Preferences/PreferencesHelpPane.swift +50 -0
  261. package/Sources/Runic/Views/Preferences/PreferencesIntegrationsPane.swift +497 -0
  262. package/Sources/Runic/Views/Preferences/PreferencesPerformancePane.swift +288 -0
  263. package/Sources/Runic/Views/Preferences/PreferencesProvidersPane.swift +3435 -0
  264. package/Sources/Runic/Views/Preferences/PreferencesSelection.swift +25 -0
  265. package/Sources/Runic/Views/Preferences/PreferencesSyncPane.swift +59 -0
  266. package/Sources/Runic/Views/Preferences/PreferencesView.swift +206 -0
  267. package/Sources/Runic/Views/Rating/QualityRatingView.swift +238 -0
  268. package/Sources/Runic/Views/Team/TeamDashboardView.swift +371 -0
  269. package/Sources/Runic/Views/Team/TeamInviteSheet.swift +175 -0
  270. package/Sources/Runic/Views/Team/TeamManagementView.swift +761 -0
  271. package/Sources/Runic/Views/Team/TeamMemberRow.swift +181 -0
  272. package/Sources/RunicCLI/CLIEntry.swift +942 -0
  273. package/Sources/RunicCLI/CLIRenderer.swift +87 -0
  274. package/Sources/RunicCLI/Commands/EnhancedUsageCommand.swift +588 -0
  275. package/Sources/RunicCLI/Commands/ModelsCommand.swift +362 -0
  276. package/Sources/RunicCLI/Commands/ProjectsCommand.swift +439 -0
  277. package/Sources/RunicCLI/Commands/ResetCommand.swift +429 -0
  278. package/Sources/RunicCLI/Commands/UsageLedgerSourceFactory.swift +168 -0
  279. package/Sources/RunicClaudeWatchdog/main.swift +122 -0
  280. package/Sources/RunicClaudeWebProbe/main.swift +62 -0
  281. package/Sources/RunicCore/AlertRuleStore.swift +187 -0
  282. package/Sources/RunicCore/BrowserCookieImportOrder.swift +25 -0
  283. package/Sources/RunicCore/CopilotUsageModels.swift +84 -0
  284. package/Sources/RunicCore/CostUsageFetcher.swift +119 -0
  285. package/Sources/RunicCore/CostUsageModels.swift +479 -0
  286. package/Sources/RunicCore/CreditsModels.swift +50 -0
  287. package/Sources/RunicCore/CustomProviders/CustomProviderModels.swift +269 -0
  288. package/Sources/RunicCore/CustomProviders/GenericProviderFetcher.swift +622 -0
  289. package/Sources/RunicCore/CustomProviders/ProviderTemplates.swift +500 -0
  290. package/Sources/RunicCore/Host/PTY/TTYCommandRunner.swift +679 -0
  291. package/Sources/RunicCore/Host/Process/SubprocessRunner.swift +135 -0
  292. package/Sources/RunicCore/Integrations/GitHubIntegration.swift +173 -0
  293. package/Sources/RunicCore/Logging/JSONStderrLogHandler.swift +79 -0
  294. package/Sources/RunicCore/Logging/OSLogLogHandler.swift +86 -0
  295. package/Sources/RunicCore/Logging/RunicLog.swift +123 -0
  296. package/Sources/RunicCore/Models/EnhancedUsageModels.swift +371 -0
  297. package/Sources/RunicCore/OpenAIDashboardModels.swift +210 -0
  298. package/Sources/RunicCore/OpenAIWeb/OpenAIDashboardBrowserCookieImporter.swift +676 -0
  299. package/Sources/RunicCore/OpenAIWeb/OpenAIDashboardFetcher.swift +492 -0
  300. package/Sources/RunicCore/OpenAIWeb/OpenAIDashboardNavigationDelegate.swift +51 -0
  301. package/Sources/RunicCore/OpenAIWeb/OpenAIDashboardParser.swift +483 -0
  302. package/Sources/RunicCore/OpenAIWeb/OpenAIDashboardScrapeScript.swift +558 -0
  303. package/Sources/RunicCore/OpenAIWeb/OpenAIDashboardWebViewCache.swift +204 -0
  304. package/Sources/RunicCore/OpenAIWeb/OpenAIDashboardWebsiteDataStore.swift +78 -0
  305. package/Sources/RunicCore/PathEnvironment.swift +482 -0
  306. package/Sources/RunicCore/Performance/PerformanceModels.swift +371 -0
  307. package/Sources/RunicCore/Performance/PerformanceStorageImpl.swift +409 -0
  308. package/Sources/RunicCore/Policy/UsagePolicyEngine.swift +178 -0
  309. package/Sources/RunicCore/ProjectBudgetStore.swift +99 -0
  310. package/Sources/RunicCore/ProviderCostSnapshot.swift +29 -0
  311. package/Sources/RunicCore/Providers/Antigravity/AntigravityProviderDescriptor.swift +66 -0
  312. package/Sources/RunicCore/Providers/Antigravity/AntigravityStatusProbe.swift +685 -0
  313. package/Sources/RunicCore/Providers/Auggie/AuggieProviderDescriptor.swift +83 -0
  314. package/Sources/RunicCore/Providers/Auggie/AuggieUsageFetcher.swift +142 -0
  315. package/Sources/RunicCore/Providers/Azure/AzureProviderDescriptor.swift +141 -0
  316. package/Sources/RunicCore/Providers/Azure/AzureUsageFetcher.swift +186 -0
  317. package/Sources/RunicCore/Providers/Bedrock/BedrockProviderDescriptor.swift +126 -0
  318. package/Sources/RunicCore/Providers/Bedrock/BedrockUsageFetcher.swift +168 -0
  319. package/Sources/RunicCore/Providers/Cerebras/CerebrasProviderDescriptor.swift +84 -0
  320. package/Sources/RunicCore/Providers/Cerebras/CerebrasUsageFetcher.swift +75 -0
  321. package/Sources/RunicCore/Providers/Claude/ClaudeCLISession.swift +332 -0
  322. package/Sources/RunicCore/Providers/Claude/ClaudeOAuth/ClaudeOAuthCredentials.swift +180 -0
  323. package/Sources/RunicCore/Providers/Claude/ClaudeOAuth/ClaudeOAuthUsageFetcher.swift +137 -0
  324. package/Sources/RunicCore/Providers/Claude/ClaudeProviderDescriptor.swift +207 -0
  325. package/Sources/RunicCore/Providers/Claude/ClaudeStatusProbe.swift +654 -0
  326. package/Sources/RunicCore/Providers/Claude/ClaudeUsageDataSource.swift +28 -0
  327. package/Sources/RunicCore/Providers/Claude/ClaudeUsageFetcher.swift +480 -0
  328. package/Sources/RunicCore/Providers/Claude/ClaudeWeb/ClaudeWebAPIFetcher.swift +780 -0
  329. package/Sources/RunicCore/Providers/Codex/CodexOAuth/CodexOAuthCredentials.swift +146 -0
  330. package/Sources/RunicCore/Providers/Codex/CodexOAuth/CodexOAuthUsageFetcher.swift +269 -0
  331. package/Sources/RunicCore/Providers/Codex/CodexOAuth/CodexTokenRefresher.swift +100 -0
  332. package/Sources/RunicCore/Providers/Codex/CodexProviderDescriptor.swift +243 -0
  333. package/Sources/RunicCore/Providers/Codex/CodexStatusProbe.swift +125 -0
  334. package/Sources/RunicCore/Providers/Codex/CodexUsageDataSource.swift +24 -0
  335. package/Sources/RunicCore/Providers/Codex/CodexWebDashboardStrategy.swift +181 -0
  336. package/Sources/RunicCore/Providers/Cohere/CohereProviderDescriptor.swift +83 -0
  337. package/Sources/RunicCore/Providers/Cohere/CohereUsageFetcher.swift +85 -0
  338. package/Sources/RunicCore/Providers/Copilot/CopilotDeviceFlow.swift +123 -0
  339. package/Sources/RunicCore/Providers/Copilot/CopilotGitHubCLITokenReader.swift +114 -0
  340. package/Sources/RunicCore/Providers/Copilot/CopilotProviderDescriptor.swift +100 -0
  341. package/Sources/RunicCore/Providers/Copilot/CopilotUsageFetcher.swift +291 -0
  342. package/Sources/RunicCore/Providers/Copilot/CopilotVSCodeTokenReader.swift +386 -0
  343. package/Sources/RunicCore/Providers/Cursor/CursorProviderDescriptor.swift +65 -0
  344. package/Sources/RunicCore/Providers/Cursor/CursorStatusProbe.swift +594 -0
  345. package/Sources/RunicCore/Providers/DeepSeek/DeepSeekProviderDescriptor.swift +85 -0
  346. package/Sources/RunicCore/Providers/DeepSeek/DeepSeekUsageFetcher.swift +108 -0
  347. package/Sources/RunicCore/Providers/Factory/FactoryLocalStorageImporter.swift +398 -0
  348. package/Sources/RunicCore/Providers/Factory/FactoryProviderDescriptor.swift +65 -0
  349. package/Sources/RunicCore/Providers/Factory/FactoryStatusProbe.swift +1275 -0
  350. package/Sources/RunicCore/Providers/Fireworks/FireworksProviderDescriptor.swift +84 -0
  351. package/Sources/RunicCore/Providers/Fireworks/FireworksUsageFetcher.swift +75 -0
  352. package/Sources/RunicCore/Providers/Gemini/GeminiProviderDescriptor.swift +65 -0
  353. package/Sources/RunicCore/Providers/Gemini/GeminiStatusProbe.swift +835 -0
  354. package/Sources/RunicCore/Providers/Groq/GroqProviderDescriptor.swift +83 -0
  355. package/Sources/RunicCore/Providers/Groq/GroqUsageFetcher.swift +71 -0
  356. package/Sources/RunicCore/Providers/Kimi/KimiProviderDescriptor.swift +83 -0
  357. package/Sources/RunicCore/Providers/Kimi/KimiUsageFetcher.swift +77 -0
  358. package/Sources/RunicCore/Providers/MiniMax/MiniMaxProviderDescriptor.swift +92 -0
  359. package/Sources/RunicCore/Providers/MiniMax/MiniMaxSettingsReader.swift +54 -0
  360. package/Sources/RunicCore/Providers/MiniMax/MiniMaxUsageFetcher.swift +171 -0
  361. package/Sources/RunicCore/Providers/MiniMax/MiniMaxWebUsageFetcher.swift +911 -0
  362. package/Sources/RunicCore/Providers/Mistral/MistralProviderDescriptor.swift +84 -0
  363. package/Sources/RunicCore/Providers/Mistral/MistralUsageFetcher.swift +75 -0
  364. package/Sources/RunicCore/Providers/OpenRouter/OpenRouterProviderDescriptor.swift +87 -0
  365. package/Sources/RunicCore/Providers/OpenRouter/OpenRouterUsageFetcher.swift +207 -0
  366. package/Sources/RunicCore/Providers/Perplexity/PerplexityProviderDescriptor.swift +84 -0
  367. package/Sources/RunicCore/Providers/Perplexity/PerplexityUsageFetcher.swift +75 -0
  368. package/Sources/RunicCore/Providers/ProviderBranding.swift +25 -0
  369. package/Sources/RunicCore/Providers/ProviderCLIConfig.swift +17 -0
  370. package/Sources/RunicCore/Providers/ProviderDescriptor.swift +129 -0
  371. package/Sources/RunicCore/Providers/ProviderFetchPlan.swift +263 -0
  372. package/Sources/RunicCore/Providers/ProviderSettingsSnapshot.swift +98 -0
  373. package/Sources/RunicCore/Providers/ProviderTokenResolver.swift +501 -0
  374. package/Sources/RunicCore/Providers/ProviderVersionDetector.swift +68 -0
  375. package/Sources/RunicCore/Providers/Providers.swift +184 -0
  376. package/Sources/RunicCore/Providers/Qwen/QwenProviderDescriptor.swift +84 -0
  377. package/Sources/RunicCore/Providers/Qwen/QwenSettingsReader.swift +30 -0
  378. package/Sources/RunicCore/Providers/Qwen/QwenUsageStats.swift +317 -0
  379. package/Sources/RunicCore/Providers/SambaNova/SambaNovaProviderDescriptor.swift +84 -0
  380. package/Sources/RunicCore/Providers/SambaNova/SambaNovaUsageFetcher.swift +75 -0
  381. package/Sources/RunicCore/Providers/Together/TogetherProviderDescriptor.swift +83 -0
  382. package/Sources/RunicCore/Providers/Together/TogetherUsageFetcher.swift +75 -0
  383. package/Sources/RunicCore/Providers/VertexAI/VertexAIProviderDescriptor.swift +123 -0
  384. package/Sources/RunicCore/Providers/VertexAI/VertexAISettingsReader.swift +48 -0
  385. package/Sources/RunicCore/Providers/VertexAI/VertexAIUsageFetcher.swift +144 -0
  386. package/Sources/RunicCore/Providers/XAI/XAIProviderDescriptor.swift +83 -0
  387. package/Sources/RunicCore/Providers/XAI/XAIUsageFetcher.swift +75 -0
  388. package/Sources/RunicCore/Providers/Zai/ZaiProviderDescriptor.swift +72 -0
  389. package/Sources/RunicCore/Providers/Zai/ZaiSettingsReader.swift +41 -0
  390. package/Sources/RunicCore/Providers/Zai/ZaiUsageStats.swift +724 -0
  391. package/Sources/RunicCore/Sync/BackgroundSyncManager.swift +385 -0
  392. package/Sources/RunicCore/Sync/SyncConflictResolver.swift +310 -0
  393. package/Sources/RunicCore/Sync/SyncProtocol.swift +288 -0
  394. package/Sources/RunicCore/Sync/SyncRecord.swift +405 -0
  395. package/Sources/RunicCore/Sync/SyncUsageExample.swift +294 -0
  396. package/Sources/RunicCore/Sync/TeamSyncRecords.swift +775 -0
  397. package/Sources/RunicCore/Sync/iCloudSyncEngine.swift +333 -0
  398. package/Sources/RunicCore/Team/TeamModels.swift +583 -0
  399. package/Sources/RunicCore/Team/TeamShowbackExporter.swift +495 -0
  400. package/Sources/RunicCore/Team/TeamStore.swift +792 -0
  401. package/Sources/RunicCore/TextParsing.swift +55 -0
  402. package/Sources/RunicCore/UsageFetcher.swift +694 -0
  403. package/Sources/RunicCore/UsageFormatter.swift +410 -0
  404. package/Sources/RunicCore/UsageLedger/ClaudeUsageLogSource.swift +329 -0
  405. package/Sources/RunicCore/UsageLedger/CodexUsageLogSource.swift +448 -0
  406. package/Sources/RunicCore/UsageLedger/OTelGenAILedgerAdapter.swift +550 -0
  407. package/Sources/RunicCore/UsageLedger/UsageLedger.swift +29 -0
  408. package/Sources/RunicCore/UsageLedger/UsageLedgerAggregator.swift +660 -0
  409. package/Sources/RunicCore/UsageLedger/UsageLedgerInsightsAdvisor.swift +209 -0
  410. package/Sources/RunicCore/UsageLedger/UsageLedgerModels.swift +417 -0
  411. package/Sources/RunicCore/UsageLedger/UsageLedgerProjectIdentity.swift +245 -0
  412. package/Sources/RunicCore/UsagePace.swift +81 -0
  413. package/Sources/RunicCore/Vendored/CostUsage/CostUsageCache.swift +73 -0
  414. package/Sources/RunicCore/Vendored/CostUsage/CostUsageJsonl.swift +74 -0
  415. package/Sources/RunicCore/Vendored/CostUsage/CostUsagePricing.swift +208 -0
  416. package/Sources/RunicCore/Vendored/CostUsage/CostUsageScanner+Claude.swift +455 -0
  417. package/Sources/RunicCore/Vendored/CostUsage/CostUsageScanner+Timestamp.swift +132 -0
  418. package/Sources/RunicCore/Vendored/CostUsage/CostUsageScanner.swift +589 -0
  419. package/Sources/RunicCore/WidgetSnapshot.swift +183 -0
  420. package/Sources/RunicMacroSupport/ProviderRegistrationMacros.swift +14 -0
  421. package/Sources/RunicMacros/ProviderRegistrationMacros.swift +216 -0
  422. package/Sources/RunicWidget/RunicWidgetBundle.swift +79 -0
  423. package/Sources/RunicWidget/RunicWidgetProvider.swift +283 -0
  424. package/Sources/RunicWidget/RunicWidgetViews.swift +680 -0
  425. package/Tests/RunicTests/AntigravityStatusProbeTests.swift +50 -0
  426. package/Tests/RunicTests/AppDelegateTests.swift +43 -0
  427. package/Tests/RunicTests/BrowserCookieOrderLabelTests.swift +22 -0
  428. package/Tests/RunicTests/CLIArgumentParsingTests.swift +70 -0
  429. package/Tests/RunicTests/CLICostTests.swift +65 -0
  430. package/Tests/RunicTests/CLIProviderSelectionTests.swift +22 -0
  431. package/Tests/RunicTests/CLISnapshotTests.swift +72 -0
  432. package/Tests/RunicTests/CLIWebFallbackTests.swift +58 -0
  433. package/Tests/RunicTests/ClaudeOAuthTests.swift +164 -0
  434. package/Tests/RunicTests/ClaudeResilienceTests.swift +30 -0
  435. package/Tests/RunicTests/ClaudeUsageTests.swift +370 -0
  436. package/Tests/RunicTests/CodexOAuthTests.swift +122 -0
  437. package/Tests/RunicTests/CodexUsageLogSourceTests.swift +82 -0
  438. package/Tests/RunicTests/CopilotTokenResolverTests.swift +75 -0
  439. package/Tests/RunicTests/CopilotVSCodeTokenReaderTests.swift +75 -0
  440. package/Tests/RunicTests/CostUsageDecodingTests.swift +394 -0
  441. package/Tests/RunicTests/CostUsagePricingTests.swift +50 -0
  442. package/Tests/RunicTests/CostUsageScannerTests.swift +700 -0
  443. package/Tests/RunicTests/CursorStatusProbeTests.swift +323 -0
  444. package/Tests/RunicTests/FactoryStatusProbeTests.swift +69 -0
  445. package/Tests/RunicTests/GeminiAPITestHelpers.swift +94 -0
  446. package/Tests/RunicTests/GeminiLoginAlertTests.swift +28 -0
  447. package/Tests/RunicTests/GeminiStatusProbeAPITests.swift +283 -0
  448. package/Tests/RunicTests/GeminiStatusProbePlanTests.swift +279 -0
  449. package/Tests/RunicTests/GeminiStatusProbeTests.swift +233 -0
  450. package/Tests/RunicTests/GeminiTestEnvironment.swift +87 -0
  451. package/Tests/RunicTests/GoogleWorkspaceStatusTests.swift +73 -0
  452. package/Tests/RunicTests/InstallOriginTests.swift +18 -0
  453. package/Tests/RunicTests/KeyboardShortcutsBundleTests.swift +9 -0
  454. package/Tests/RunicTests/LiveAccountTests.swift +24 -0
  455. package/Tests/RunicTests/LoadingPatternTests.swift +35 -0
  456. package/Tests/RunicTests/MenuCardModelTests.swift +545 -0
  457. package/Tests/RunicTests/MiniMaxCookieHeaderStoreTestSupport.swift +8 -0
  458. package/Tests/RunicTests/MiniMaxGroupIDStoreTestSupport.swift +8 -0
  459. package/Tests/RunicTests/MiniMaxParsingTests.swift +68 -0
  460. package/Tests/RunicTests/MiniMaxTokenStoreTestSupport.swift +8 -0
  461. package/Tests/RunicTests/OTelGenAILedgerAdapterTests.swift +112 -0
  462. package/Tests/RunicTests/OpenAIDashboardBrowserCookieImporterTests.swift +17 -0
  463. package/Tests/RunicTests/OpenAIDashboardFetcherCreditsWaitTests.swift +75 -0
  464. package/Tests/RunicTests/OpenAIDashboardOffscreenHostTests.swift +27 -0
  465. package/Tests/RunicTests/OpenAIDashboardParserTests.swift +134 -0
  466. package/Tests/RunicTests/OpenAIWebAccountSwitchTests.swift +53 -0
  467. package/Tests/RunicTests/OpenRouterTokenStoreTestSupport.swift +92 -0
  468. package/Tests/RunicTests/PathBuilderTests.swift +237 -0
  469. package/Tests/RunicTests/ProviderFetchPipelineTests.swift +160 -0
  470. package/Tests/RunicTests/ProviderIconResourcesTests.swift +38 -0
  471. package/Tests/RunicTests/ProviderMetadataStatusLinkTests.swift +16 -0
  472. package/Tests/RunicTests/ProviderRegistryTests.swift +29 -0
  473. package/Tests/RunicTests/ProviderSettingsDescriptorTests.swift +202 -0
  474. package/Tests/RunicTests/ProviderToggleStoreTests.swift +51 -0
  475. package/Tests/RunicTests/RunicTests.swift +120 -0
  476. package/Tests/RunicTests/SessionQuotaNotificationLogicTests.swift +36 -0
  477. package/Tests/RunicTests/SettingsStoreTests.swift +161 -0
  478. package/Tests/RunicTests/StatusItemAnimationTests.swift +49 -0
  479. package/Tests/RunicTests/StatusMenuTests.swift +434 -0
  480. package/Tests/RunicTests/StatusProbeTests.swift +377 -0
  481. package/Tests/RunicTests/SubprocessRunnerTests.swift +20 -0
  482. package/Tests/RunicTests/SubscriptionDetectionTests.swift +65 -0
  483. package/Tests/RunicTests/TTYCommandRunnerTests.swift +148 -0
  484. package/Tests/RunicTests/TTYIntegrationTests.swift +41 -0
  485. package/Tests/RunicTests/TeamShowbackExporterTests.swift +159 -0
  486. package/Tests/RunicTests/TextParsingTests.swift +12 -0
  487. package/Tests/RunicTests/UsageFormatterTests.swift +112 -0
  488. package/Tests/RunicTests/UsageLedgerAnomalyDetectionTests.swift +172 -0
  489. package/Tests/RunicTests/UsageLedgerForecastTests.swift +213 -0
  490. package/Tests/RunicTests/UsageLedgerInsightsAdvisorTests.swift +83 -0
  491. package/Tests/RunicTests/UsageLedgerProjectNameTests.swift +170 -0
  492. package/Tests/RunicTests/UsagePaceTests.swift +77 -0
  493. package/Tests/RunicTests/UsagePaceTextTests.swift +109 -0
  494. package/Tests/RunicTests/UsagePolicyEngineTests.swift +91 -0
  495. package/Tests/RunicTests/WidgetSnapshotTests.swift +45 -0
  496. package/Tests/RunicTests/ZaiProviderTests.swift +61 -0
  497. package/Tests/RunicTests/ZaiTokenStoreTestSupport.swift +6 -0
  498. package/TestsLinux/PlatformGatingTests.swift +46 -0
  499. package/appcast.xml +105 -0
  500. package/assets/logo-concept-stack.svg +24 -0
  501. package/assets/logo-minimal-bars.svg +15 -0
  502. package/assets/logo.svg +20 -0
  503. package/assets/logo2.svg +43 -0
  504. package/bin/docs-list +5 -0
  505. package/bin/install-runic-cli.sh +32 -0
  506. package/build-and-run.sh +369 -0
  507. package/docs/.nojekyll +1 -0
  508. package/docs/CNAME +1 -0
  509. package/docs/antigravity.md +75 -0
  510. package/docs/architecture.md +32 -0
  511. package/docs/claude.md +93 -0
  512. package/docs/cli-commands/integration_guide.md +371 -0
  513. package/docs/cli-commands/quick_reference.md +362 -0
  514. package/docs/cli-commands/readme.md +361 -0
  515. package/docs/cli.md +156 -0
  516. package/docs/cloudkit_sync_guide.md +495 -0
  517. package/docs/codebase_review.md +288 -0
  518. package/docs/codex-oauth.md +635 -0
  519. package/docs/codex.md +104 -0
  520. package/docs/codexbar.png +0 -0
  521. package/docs/copilot.md +44 -0
  522. package/docs/cursor.md +46 -0
  523. package/docs/design/designcomparisonchart.md +510 -0
  524. package/docs/design/implementationguide.md +792 -0
  525. package/docs/design/menubaricondesignconcepts.md +796 -0
  526. package/docs/design/mockups/hybridiconconcept.svg +62 -0
  527. package/docs/design/mockups/infinityiconconcept.svg +41 -0
  528. package/docs/design/mockups/infinityiconstates.svg +129 -0
  529. package/docs/design/mockups/wavelogorefined.svg +48 -0
  530. package/docs/design/quick_summary.md +426 -0
  531. package/docs/design/readme.md +478 -0
  532. package/docs/design/sizespecifications.md +575 -0
  533. package/docs/design-system.md +836 -0
  534. package/docs/factory.md +103 -0
  535. package/docs/gemini.md +73 -0
  536. package/docs/icon.md +37 -0
  537. package/docs/icon.png +0 -0
  538. package/docs/index.html +175 -0
  539. package/docs/keychain_fix.md +274 -0
  540. package/docs/minimax.md +71 -0
  541. package/docs/packaging.md +25 -0
  542. package/docs/progress-bar-improvements.md +240 -0
  543. package/docs/progress-bar-quick-reference.md +283 -0
  544. package/docs/progress-bar-technical-details.md +432 -0
  545. package/docs/progress-bar-visual-test.swift +375 -0
  546. package/docs/provider.md +202 -0
  547. package/docs/providers.md +86 -0
  548. package/docs/refactor/macros.md +35 -0
  549. package/docs/refresh-loop.md +22 -0
  550. package/docs/releasing-homebrew.md +35 -0
  551. package/docs/releasing.md +121 -0
  552. package/docs/research/concrete_todo_2026-02-22.md +47 -0
  553. package/docs/research/core-feature-research.md +248 -0
  554. package/docs/research/feature_uiux_roadmap_2026-02-22.md +202 -0
  555. package/docs/research/parity_matrix.md +49 -0
  556. package/docs/research/provider_expansion_candidates_2026-02-22.md +80 -0
  557. package/docs/research/provider_model_token_project_matrix_2026-02-23.md +46 -0
  558. package/docs/research/release_gate_checklist.md +57 -0
  559. package/docs/site.css +505 -0
  560. package/docs/sparkle.md +28 -0
  561. package/docs/status.md +28 -0
  562. package/docs/sync/implementation.md +393 -0
  563. package/docs/sync/readme.md +317 -0
  564. package/docs/sync_files_summary.md +391 -0
  565. package/docs/sync_quick_reference.md +225 -0
  566. package/docs/todo.md +11 -0
  567. package/docs/ui.md +29 -0
  568. package/docs/web-integration.md +9 -0
  569. package/docs/widgets.md +85 -0
  570. package/docs/workflows/error-handling-improvements.md +434 -0
  571. package/docs/workflows/folder_structure.md +299 -0
  572. package/docs/workflows/loading_states.md +446 -0
  573. package/docs/workflows/loading_states_examples.md +565 -0
  574. package/docs/workflows/loading_states_flow.md +430 -0
  575. package/docs/workflows/performance_optimizations.md +457 -0
  576. package/docs/workflows/phase1-cli-testing-report.md +313 -0
  577. package/docs/workflows/quick_reference.md +228 -0
  578. package/docs/workflows/readme.md +59 -0
  579. package/docs/workflows/recent_improvements.md +275 -0
  580. package/docs/workflows/sync_enablement_summary.md +400 -0
  581. package/docs/zai.md +43 -0
  582. package/package.json +36 -0
  583. package/runic.png +0 -0
  584. package/version.env +2 -0
@@ -0,0 +1,724 @@
1
+ import Foundation
2
+ #if canImport(FoundationNetworking)
3
+ import FoundationNetworking
4
+ #endif
5
+
6
+ // MARK: - Enums
7
+
8
+ /// Z.ai usage limit types from the API
9
+ public enum ZaiLimitType: String, Sendable {
10
+ case timeLimit = "TIME_LIMIT"
11
+ case tokensLimit = "TOKENS_LIMIT"
12
+ }
13
+
14
+ /// Z.ai usage limit unit types
15
+ public enum ZaiLimitUnit: Int, Sendable {
16
+ case unknown = 0
17
+ case days = 1
18
+ case hours = 3
19
+ case minutes = 5
20
+ }
21
+
22
+ // MARK: - Quota limit models
23
+
24
+ /// A single limit entry from the z.ai API
25
+ public struct ZaiLimitEntry: Sendable {
26
+ public let type: ZaiLimitType
27
+ public let unit: ZaiLimitUnit
28
+ public let number: Int
29
+ public let usage: Int
30
+ public let currentValue: Int
31
+ public let remaining: Int
32
+ public let percentage: Double
33
+ public let usageDetails: [ZaiUsageDetail]
34
+ public let nextResetTime: Date?
35
+
36
+ public init(
37
+ type: ZaiLimitType,
38
+ unit: ZaiLimitUnit,
39
+ number: Int,
40
+ usage: Int,
41
+ currentValue: Int,
42
+ remaining: Int,
43
+ percentage: Double,
44
+ usageDetails: [ZaiUsageDetail],
45
+ nextResetTime: Date?)
46
+ {
47
+ self.type = type
48
+ self.unit = unit
49
+ self.number = number
50
+ self.usage = usage
51
+ self.currentValue = currentValue
52
+ self.remaining = remaining
53
+ self.percentage = percentage
54
+ self.usageDetails = usageDetails
55
+ self.nextResetTime = nextResetTime
56
+ }
57
+ }
58
+
59
+ extension ZaiLimitEntry {
60
+ public var usedPercent: Double {
61
+ if let computed = self.computedUsedPercent {
62
+ return computed
63
+ }
64
+ return self.percentage
65
+ }
66
+
67
+ public var windowMinutes: Int? {
68
+ guard self.number > 0 else { return nil }
69
+ switch self.unit {
70
+ case .minutes:
71
+ return self.number
72
+ case .hours:
73
+ return self.number * 60
74
+ case .days:
75
+ return self.number * 24 * 60
76
+ case .unknown:
77
+ return nil
78
+ }
79
+ }
80
+
81
+ public var windowDescription: String? {
82
+ guard self.number > 0 else { return nil }
83
+ let unitLabel: String? = switch self.unit {
84
+ case .minutes: "minute"
85
+ case .hours: "hour"
86
+ case .days: "day"
87
+ case .unknown: nil
88
+ }
89
+ guard let unitLabel else { return nil }
90
+ let suffix = self.number == 1 ? unitLabel : "\(unitLabel)s"
91
+ return "\(self.number) \(suffix)"
92
+ }
93
+
94
+ public var windowLabel: String? {
95
+ guard let description = self.windowDescription else { return nil }
96
+ return "\(description) window"
97
+ }
98
+
99
+ private var computedUsedPercent: Double? {
100
+ guard self.usage > 0 else { return nil }
101
+ let limit = max(0, self.usage)
102
+ guard limit > 0 else { return nil }
103
+
104
+ let usedFromRemaining = limit - self.remaining
105
+ let used = max(0, min(limit, max(usedFromRemaining, self.currentValue)))
106
+ let percent = (Double(used) / Double(limit)) * 100
107
+ return min(100, max(0, percent))
108
+ }
109
+ }
110
+
111
+ /// Usage detail for MCP tools
112
+ public struct ZaiUsageDetail: Sendable, Codable {
113
+ public let modelCode: String
114
+ public let usage: Int
115
+
116
+ public init(modelCode: String, usage: Int) {
117
+ self.modelCode = modelCode
118
+ self.usage = usage
119
+ }
120
+ }
121
+
122
+ // MARK: - Model usage (24h breakdown)
123
+
124
+ /// Per-model usage entry from the model-usage endpoint.
125
+ public struct ZaiModelUsageEntry: Sendable {
126
+ public let modelCode: String
127
+ public let tokens: Int
128
+ public let prompts: Int
129
+ public let estimatedCostUSD: Double?
130
+
131
+ public init(modelCode: String, tokens: Int, prompts: Int, estimatedCostUSD: Double?) {
132
+ self.modelCode = modelCode
133
+ self.tokens = tokens
134
+ self.prompts = prompts
135
+ self.estimatedCostUSD = estimatedCostUSD
136
+ }
137
+ }
138
+
139
+ /// Aggregated model usage from the 24h rolling window.
140
+ public struct ZaiModelUsageSummary: Sendable {
141
+ public let entries: [ZaiModelUsageEntry]
142
+ public let totalTokens: Int
143
+ public let totalPrompts: Int
144
+ public let totalEstimatedCostUSD: Double
145
+ public let windowStart: Date
146
+ public let windowEnd: Date
147
+
148
+ public init(
149
+ entries: [ZaiModelUsageEntry],
150
+ totalTokens: Int,
151
+ totalPrompts: Int,
152
+ totalEstimatedCostUSD: Double,
153
+ windowStart: Date,
154
+ windowEnd: Date)
155
+ {
156
+ self.entries = entries
157
+ self.totalTokens = totalTokens
158
+ self.totalPrompts = totalPrompts
159
+ self.totalEstimatedCostUSD = totalEstimatedCostUSD
160
+ self.windowStart = windowStart
161
+ self.windowEnd = windowEnd
162
+ }
163
+ }
164
+
165
+ // MARK: - Tool usage (24h breakdown)
166
+
167
+ /// Per-tool MCP usage entry from the tool-usage endpoint.
168
+ public struct ZaiToolUsageEntry: Sendable {
169
+ public let toolName: String
170
+ public let count: Int
171
+
172
+ public init(toolName: String, count: Int) {
173
+ self.toolName = toolName
174
+ self.count = count
175
+ }
176
+ }
177
+
178
+ /// Aggregated tool usage from the 24h rolling window.
179
+ public struct ZaiToolUsageSummary: Sendable {
180
+ public let entries: [ZaiToolUsageEntry]
181
+ public let totalCalls: Int
182
+
183
+ public init(entries: [ZaiToolUsageEntry], totalCalls: Int) {
184
+ self.entries = entries
185
+ self.totalCalls = totalCalls
186
+ }
187
+ }
188
+
189
+ // MARK: - Pricing table
190
+
191
+ /// Static pricing lookup for z.ai models (USD per 1M tokens).
192
+ public enum ZaiModelPricing {
193
+ public struct Tier: Sendable {
194
+ public let inputPerMillion: Double
195
+ public let outputPerMillion: Double
196
+ public let contextWindow: Int
197
+ }
198
+
199
+ private static let tiers: [String: Tier] = [
200
+ "glm-4.7-flash": Tier(inputPerMillion: 0.06, outputPerMillion: 0.40, contextWindow: 203_000),
201
+ "glm-4.7-flash-thinking": Tier(inputPerMillion: 0.06, outputPerMillion: 0.40, contextWindow: 203_000),
202
+ "glm-4-32b": Tier(inputPerMillion: 0.10, outputPerMillion: 0.10, contextWindow: 128_000),
203
+ "glm-4.5-air": Tier(inputPerMillion: 0.13, outputPerMillion: 0.85, contextWindow: 131_000),
204
+ "glm-4.6v": Tier(inputPerMillion: 0.30, outputPerMillion: 0.90, contextWindow: 131_000),
205
+ "glm-4.6v-thinking": Tier(inputPerMillion: 0.30, outputPerMillion: 0.90, contextWindow: 131_000),
206
+ "glm-4.7": Tier(inputPerMillion: 0.38, outputPerMillion: 1.75, contextWindow: 203_000),
207
+ "glm-4.7-thinking": Tier(inputPerMillion: 0.38, outputPerMillion: 1.75, contextWindow: 203_000),
208
+ "glm-4.6": Tier(inputPerMillion: 0.39, outputPerMillion: 1.74, contextWindow: 205_000),
209
+ "glm-4.6-thinking": Tier(inputPerMillion: 0.39, outputPerMillion: 1.74, contextWindow: 205_000),
210
+ "glm-4.5v": Tier(inputPerMillion: 0.60, outputPerMillion: 1.80, contextWindow: 66_000),
211
+ "glm-4.5v-thinking": Tier(inputPerMillion: 0.60, outputPerMillion: 1.80, contextWindow: 66_000),
212
+ "glm-4.5": Tier(inputPerMillion: 0.60, outputPerMillion: 2.20, contextWindow: 131_000),
213
+ "glm-4.5-thinking": Tier(inputPerMillion: 0.60, outputPerMillion: 2.20, contextWindow: 131_000),
214
+ "glm-5": Tier(inputPerMillion: 0.72, outputPerMillion: 2.30, contextWindow: 203_000),
215
+ "glm-5-thinking": Tier(inputPerMillion: 0.72, outputPerMillion: 2.30, contextWindow: 203_000),
216
+ ]
217
+
218
+ /// Returns pricing tier for a model code, case-insensitive with fuzzy matching.
219
+ public static func tier(for modelCode: String) -> Tier? {
220
+ let key = modelCode.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
221
+ if let exact = self.tiers[key] { return exact }
222
+ return self.tiers.first { key.contains($0.key) || $0.key.contains(key) }?.value
223
+ }
224
+
225
+ /// Estimates cost assuming a 60/40 input/output token split (typical for coding).
226
+ public static func estimateCost(tokens: Int, modelCode: String) -> Double? {
227
+ guard let tier = self.tier(for: modelCode), tokens > 0 else { return nil }
228
+ let inputTokens = Double(tokens) * 0.6
229
+ let outputTokens = Double(tokens) * 0.4
230
+ let inputCost = (inputTokens / 1_000_000) * tier.inputPerMillion
231
+ let outputCost = (outputTokens / 1_000_000) * tier.outputPerMillion
232
+ return inputCost + outputCost
233
+ }
234
+ }
235
+
236
+ // MARK: - Complete snapshot
237
+
238
+ /// Complete z.ai usage response including all 3 endpoints.
239
+ public struct ZaiUsageSnapshot: Sendable {
240
+ public let tokenLimit: ZaiLimitEntry?
241
+ public let timeLimit: ZaiLimitEntry?
242
+ public let planName: String?
243
+ public let modelUsage: ZaiModelUsageSummary?
244
+ public let toolUsage: ZaiToolUsageSummary?
245
+ public let updatedAt: Date
246
+
247
+ public init(
248
+ tokenLimit: ZaiLimitEntry?,
249
+ timeLimit: ZaiLimitEntry?,
250
+ planName: String?,
251
+ modelUsage: ZaiModelUsageSummary? = nil,
252
+ toolUsage: ZaiToolUsageSummary? = nil,
253
+ updatedAt: Date)
254
+ {
255
+ self.tokenLimit = tokenLimit
256
+ self.timeLimit = timeLimit
257
+ self.planName = planName
258
+ self.modelUsage = modelUsage
259
+ self.toolUsage = toolUsage
260
+ self.updatedAt = updatedAt
261
+ }
262
+
263
+ public var isValid: Bool {
264
+ self.tokenLimit != nil || self.timeLimit != nil
265
+ }
266
+ }
267
+
268
+ extension ZaiUsageSnapshot {
269
+ public func toUsageSnapshot() -> UsageSnapshot {
270
+ let primaryLimit = self.tokenLimit ?? self.timeLimit
271
+ let secondaryLimit = (self.tokenLimit != nil && self.timeLimit != nil) ? self.timeLimit : nil
272
+
273
+ let primary = primaryLimit.map { Self.rateWindow(for: $0) } ?? RateWindow(
274
+ usedPercent: 0,
275
+ windowMinutes: nil,
276
+ resetsAt: nil,
277
+ resetDescription: nil)
278
+ let secondary = secondaryLimit.map { Self.rateWindow(for: $0) }
279
+
280
+ let planName = self.planName?.trimmingCharacters(in: .whitespacesAndNewlines)
281
+ let loginMethod = (planName?.isEmpty ?? true) ? nil : planName
282
+ let identity = ProviderIdentitySnapshot(
283
+ providerID: .zai,
284
+ accountEmail: nil,
285
+ accountOrganization: nil,
286
+ loginMethod: loginMethod)
287
+ return UsageSnapshot(
288
+ primary: primary,
289
+ secondary: secondary,
290
+ tertiary: nil,
291
+ providerCost: nil,
292
+ zaiUsage: self,
293
+ updatedAt: self.updatedAt,
294
+ identity: identity)
295
+ }
296
+
297
+ private static func rateWindow(for limit: ZaiLimitEntry) -> RateWindow {
298
+ RateWindow(
299
+ usedPercent: limit.usedPercent,
300
+ windowMinutes: limit.type == .tokensLimit ? limit.windowMinutes : nil,
301
+ resetsAt: limit.nextResetTime,
302
+ resetDescription: self.resetDescription(for: limit))
303
+ }
304
+
305
+ private static func resetDescription(for limit: ZaiLimitEntry) -> String? {
306
+ if let label = limit.windowLabel {
307
+ return label
308
+ }
309
+ if limit.type == .timeLimit {
310
+ return "Monthly"
311
+ }
312
+ return nil
313
+ }
314
+ }
315
+
316
+ // MARK: - Private API response models
317
+
318
+ private struct ZaiQuotaLimitResponse: Decodable {
319
+ let code: Int?
320
+ let msg: String?
321
+ let data: ZaiQuotaLimitData?
322
+ let success: Bool?
323
+
324
+ var isSuccess: Bool { (self.success ?? (self.code == 200)) && (self.code ?? 200) == 200 }
325
+
326
+ var errorMessage: String {
327
+ self.msg ?? self.message ?? "Unknown API error (code: \(self.code ?? -1))"
328
+ }
329
+
330
+ // Some responses use "message" instead of "msg".
331
+ private let message: String?
332
+
333
+ private enum CodingKeys: String, CodingKey {
334
+ case code, msg, data, success, message
335
+ }
336
+ }
337
+
338
+ private struct ZaiQuotaLimitData: Decodable {
339
+ let limits: [ZaiLimitRaw]
340
+ let planName: String?
341
+
342
+ init(from decoder: Decoder) throws {
343
+ let container = try decoder.container(keyedBy: CodingKeys.self)
344
+ self.limits = try container.decode([ZaiLimitRaw].self, forKey: .limits)
345
+ let rawPlan = try [
346
+ container.decodeIfPresent(String.self, forKey: .planName),
347
+ container.decodeIfPresent(String.self, forKey: .plan),
348
+ container.decodeIfPresent(String.self, forKey: .planType),
349
+ container.decodeIfPresent(String.self, forKey: .packageName),
350
+ container.decodeIfPresent(String.self, forKey: .level),
351
+ ].compactMap(\.self).first
352
+ let trimmed = rawPlan?.trimmingCharacters(in: .whitespacesAndNewlines)
353
+ self.planName = (trimmed?.isEmpty ?? true) ? nil : trimmed
354
+ }
355
+
356
+ private enum CodingKeys: String, CodingKey {
357
+ case limits
358
+ case planName
359
+ case plan
360
+ case planType = "plan_type"
361
+ case packageName
362
+ case level
363
+ }
364
+ }
365
+
366
+ private struct ZaiLimitRaw: Codable {
367
+ let type: String
368
+ let unit: Int?
369
+ let number: Int?
370
+ let usage: Int?
371
+ let currentValue: Int?
372
+ let remaining: Int?
373
+ let percentage: Int?
374
+ let usageDetails: [ZaiUsageDetail]?
375
+ let nextResetTime: Int?
376
+
377
+ func toLimitEntry() -> ZaiLimitEntry? {
378
+ guard let limitType = ZaiLimitType(rawValue: type) else { return nil }
379
+ let limitUnit = ZaiLimitUnit(rawValue: unit ?? 0) ?? .unknown
380
+ let resolvedUsage = self.usage ?? 0
381
+ let resolvedCurrent = self.currentValue ?? 0
382
+ let resolvedRemaining = self.remaining ?? max(0, resolvedUsage - resolvedCurrent)
383
+ let nextReset = self.nextResetTime.map { Date(timeIntervalSince1970: TimeInterval($0) / 1000) }
384
+ return ZaiLimitEntry(
385
+ type: limitType,
386
+ unit: limitUnit,
387
+ number: self.number ?? 0,
388
+ usage: resolvedUsage,
389
+ currentValue: resolvedCurrent,
390
+ remaining: resolvedRemaining,
391
+ percentage: Double(self.percentage ?? 0),
392
+ usageDetails: self.usageDetails ?? [],
393
+ nextResetTime: nextReset)
394
+ }
395
+ }
396
+
397
+ /// Flexible model-usage API response (best-effort decoding).
398
+ private struct ZaiModelUsageResponse: Decodable {
399
+ let code: Int?
400
+ let success: Bool?
401
+ let data: ZaiModelUsageData?
402
+
403
+ struct ZaiModelUsageData: Decodable {
404
+ let models: [ZaiModelUsageRaw]?
405
+ let totalTokens: Int?
406
+ let totalPrompts: Int?
407
+ let total_tokens: Int?
408
+ let total_prompts: Int?
409
+
410
+ var resolvedTotalTokens: Int? { self.totalTokens ?? self.total_tokens }
411
+ var resolvedTotalPrompts: Int? { self.totalPrompts ?? self.total_prompts }
412
+ }
413
+
414
+ struct ZaiModelUsageRaw: Decodable {
415
+ let modelCode: String?
416
+ let model_code: String?
417
+ let model: String?
418
+ let tokens: Int?
419
+ let usage: Int?
420
+ let prompts: Int?
421
+ let calls: Int?
422
+
423
+ var resolvedModelCode: String? { self.modelCode ?? self.model_code ?? self.model }
424
+ var resolvedTokens: Int { self.tokens ?? self.usage ?? 0 }
425
+ var resolvedPrompts: Int { self.prompts ?? self.calls ?? 0 }
426
+ }
427
+ }
428
+
429
+ /// Flexible tool-usage API response (best-effort decoding).
430
+ private struct ZaiToolUsageResponse: Decodable {
431
+ let code: Int?
432
+ let success: Bool?
433
+ let data: ZaiToolUsageData?
434
+
435
+ struct ZaiToolUsageData: Decodable {
436
+ let tools: [ZaiToolUsageRaw]?
437
+
438
+ init(from decoder: Decoder) throws {
439
+ let container = try decoder.container(keyedBy: DynamicKey.self)
440
+ var toolEntries: [ZaiToolUsageRaw] = []
441
+ if let tools = try? container.decodeIfPresent([ZaiToolUsageRaw].self, forKey: DynamicKey(stringValue: "tools")!) {
442
+ toolEntries = tools
443
+ } else {
444
+ // Fallback: try top-level keys as tool names with int values
445
+ for key in container.allKeys {
446
+ if let count = try? container.decode(Int.self, forKey: key) {
447
+ toolEntries.append(ZaiToolUsageRaw(tool: key.stringValue, name: nil, count: count, usage: nil))
448
+ }
449
+ }
450
+ }
451
+ self.tools = toolEntries.isEmpty ? nil : toolEntries
452
+ }
453
+ }
454
+
455
+ struct ZaiToolUsageRaw: Decodable {
456
+ let tool: String?
457
+ let name: String?
458
+ let count: Int?
459
+ let usage: Int?
460
+
461
+ var resolvedName: String? { self.tool ?? self.name }
462
+ var resolvedCount: Int { self.count ?? self.usage ?? 0 }
463
+ }
464
+
465
+ struct DynamicKey: CodingKey {
466
+ var stringValue: String
467
+ var intValue: Int?
468
+ init?(stringValue: String) { self.stringValue = stringValue }
469
+ init?(intValue: Int) { self.stringValue = "\(intValue)"; self.intValue = intValue }
470
+ }
471
+ }
472
+
473
+ // MARK: - Fetcher
474
+
475
+ /// Fetches usage stats from the z.ai API (all 3 endpoints).
476
+ public struct ZaiUsageFetcher: Sendable {
477
+ private static let log = RunicLog.logger("zai-usage")
478
+
479
+ private static let baseURL = "https://api.z.ai/api/monitor/usage"
480
+ private static let quotaAPIURL = "\(baseURL)/quota/limit"
481
+ private static let modelUsageAPIURL = "\(baseURL)/model-usage"
482
+ private static let toolUsageAPIURL = "\(baseURL)/tool-usage"
483
+
484
+ /// Fetches all available usage data from z.ai in parallel.
485
+ public static func fetchUsage(apiKey: String) async throws -> ZaiUsageSnapshot {
486
+ guard !apiKey.isEmpty else {
487
+ throw ZaiUsageError.invalidCredentials
488
+ }
489
+
490
+ // Fetch quota (required) and model/tool usage (best-effort) concurrently.
491
+ async let quotaTask = self.fetchQuota(apiKey: apiKey)
492
+ async let modelTask = self.fetchModelUsageBestEffort(apiKey: apiKey)
493
+ async let toolTask = self.fetchToolUsageBestEffort(apiKey: apiKey)
494
+
495
+ let (tokenLimit, timeLimit, planName) = try await quotaTask
496
+ let modelUsage = await modelTask
497
+ let toolUsage = await toolTask
498
+
499
+ return ZaiUsageSnapshot(
500
+ tokenLimit: tokenLimit,
501
+ timeLimit: timeLimit,
502
+ planName: planName,
503
+ modelUsage: modelUsage,
504
+ toolUsage: toolUsage,
505
+ updatedAt: Date())
506
+ }
507
+
508
+ // MARK: - Quota endpoint (required)
509
+
510
+ private static func fetchQuota(apiKey: String) async throws -> (ZaiLimitEntry?, ZaiLimitEntry?, String?) {
511
+ let request = try self.makeRequest(url: quotaAPIURL, apiKey: apiKey)
512
+ let (data, response) = try await URLSession.shared.data(for: request)
513
+
514
+ guard let httpResponse = response as? HTTPURLResponse else {
515
+ throw ZaiUsageError.networkError("Invalid response")
516
+ }
517
+ guard httpResponse.statusCode == 200 else {
518
+ let errorMessage = String(data: data, encoding: .utf8) ?? "Unknown error"
519
+ Self.log.error("z.ai quota API returned \(httpResponse.statusCode): \(errorMessage)")
520
+ throw ZaiUsageError.apiError("HTTP \(httpResponse.statusCode): \(errorMessage)")
521
+ }
522
+
523
+ if let jsonString = String(data: data, encoding: .utf8) {
524
+ Self.log.debug("z.ai quota response: \(jsonString)")
525
+ }
526
+
527
+ let apiResponse: ZaiQuotaLimitResponse
528
+ do {
529
+ apiResponse = try JSONDecoder().decode(ZaiQuotaLimitResponse.self, from: data)
530
+ } catch {
531
+ let body = String(data: data, encoding: .utf8) ?? "<binary>"
532
+ Self.log.error("z.ai quota parse failed: \(error) — body: \(body)")
533
+ throw ZaiUsageError.parseFailed(error.localizedDescription)
534
+ }
535
+ guard apiResponse.isSuccess else {
536
+ throw ZaiUsageError.apiError(apiResponse.errorMessage)
537
+ }
538
+ guard let quotaData = apiResponse.data else {
539
+ throw ZaiUsageError.apiError("API returned success but no data")
540
+ }
541
+
542
+ var tokenLimit: ZaiLimitEntry?
543
+ var timeLimit: ZaiLimitEntry?
544
+ for limit in quotaData.limits {
545
+ if let entry = limit.toLimitEntry() {
546
+ switch entry.type {
547
+ case .tokensLimit: tokenLimit = entry
548
+ case .timeLimit: timeLimit = entry
549
+ }
550
+ }
551
+ }
552
+ return (tokenLimit, timeLimit, quotaData.planName)
553
+ }
554
+
555
+ // MARK: - Model usage endpoint (best-effort)
556
+
557
+ private static func fetchModelUsageBestEffort(apiKey: String) async -> ZaiModelUsageSummary? {
558
+ do {
559
+ return try await self.fetchModelUsage(apiKey: apiKey)
560
+ } catch {
561
+ Self.log.info("z.ai model-usage endpoint unavailable: \(error.localizedDescription)")
562
+ return nil
563
+ }
564
+ }
565
+
566
+ private static func fetchModelUsage(apiKey: String) async throws -> ZaiModelUsageSummary {
567
+ let (startTime, endTime) = self.rolling24hWindow()
568
+ let urlString = "\(modelUsageAPIURL)?startTime=\(startTime)&endTime=\(endTime)"
569
+ let request = try self.makeRequest(url: urlString, apiKey: apiKey)
570
+ let (data, response) = try await URLSession.shared.data(for: request)
571
+
572
+ guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
573
+ throw ZaiUsageError.apiError("model-usage endpoint returned non-200")
574
+ }
575
+
576
+ if let jsonString = String(data: data, encoding: .utf8) {
577
+ Self.log.debug("z.ai model-usage response: \(jsonString)")
578
+ }
579
+
580
+ let raw = try JSONDecoder().decode(ZaiModelUsageResponse.self, from: data)
581
+ let models = raw.data?.models ?? []
582
+
583
+ var entries: [ZaiModelUsageEntry] = []
584
+ var totalTokens = 0
585
+ var totalPrompts = 0
586
+ var totalCost = 0.0
587
+
588
+ for model in models {
589
+ guard let code = model.resolvedModelCode else { continue }
590
+ let tokens = model.resolvedTokens
591
+ let prompts = model.resolvedPrompts
592
+ let cost = ZaiModelPricing.estimateCost(tokens: tokens, modelCode: code)
593
+ entries.append(ZaiModelUsageEntry(
594
+ modelCode: code,
595
+ tokens: tokens,
596
+ prompts: prompts,
597
+ estimatedCostUSD: cost))
598
+ totalTokens += tokens
599
+ totalPrompts += prompts
600
+ totalCost += cost ?? 0
601
+ }
602
+
603
+ // If the API returned totals, prefer those.
604
+ let resolvedTotalTokens = raw.data?.resolvedTotalTokens ?? totalTokens
605
+ let resolvedTotalPrompts = raw.data?.resolvedTotalPrompts ?? totalPrompts
606
+
607
+ let (startDate, endDate) = self.rolling24hDates()
608
+ return ZaiModelUsageSummary(
609
+ entries: entries.sorted { $0.tokens > $1.tokens },
610
+ totalTokens: resolvedTotalTokens,
611
+ totalPrompts: resolvedTotalPrompts,
612
+ totalEstimatedCostUSD: totalCost,
613
+ windowStart: startDate,
614
+ windowEnd: endDate)
615
+ }
616
+
617
+ // MARK: - Tool usage endpoint (best-effort)
618
+
619
+ private static func fetchToolUsageBestEffort(apiKey: String) async -> ZaiToolUsageSummary? {
620
+ do {
621
+ return try await self.fetchToolUsage(apiKey: apiKey)
622
+ } catch {
623
+ Self.log.info("z.ai tool-usage endpoint unavailable: \(error.localizedDescription)")
624
+ return nil
625
+ }
626
+ }
627
+
628
+ private static func fetchToolUsage(apiKey: String) async throws -> ZaiToolUsageSummary {
629
+ let (startTime, endTime) = self.rolling24hWindow()
630
+ let urlString = "\(toolUsageAPIURL)?startTime=\(startTime)&endTime=\(endTime)"
631
+ let request = try self.makeRequest(url: urlString, apiKey: apiKey)
632
+ let (data, response) = try await URLSession.shared.data(for: request)
633
+
634
+ guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
635
+ throw ZaiUsageError.apiError("tool-usage endpoint returned non-200")
636
+ }
637
+
638
+ if let jsonString = String(data: data, encoding: .utf8) {
639
+ Self.log.debug("z.ai tool-usage response: \(jsonString)")
640
+ }
641
+
642
+ let raw = try JSONDecoder().decode(ZaiToolUsageResponse.self, from: data)
643
+ let tools = raw.data?.tools ?? []
644
+
645
+ var entries: [ZaiToolUsageEntry] = []
646
+ var total = 0
647
+ for tool in tools {
648
+ guard let name = tool.resolvedName else { continue }
649
+ let count = tool.resolvedCount
650
+ entries.append(ZaiToolUsageEntry(toolName: name, count: count))
651
+ total += count
652
+ }
653
+
654
+ return ZaiToolUsageSummary(
655
+ entries: entries.sorted { $0.count > $1.count },
656
+ totalCalls: total)
657
+ }
658
+
659
+ // MARK: - Helpers
660
+
661
+ private static func makeRequest(url: String, apiKey: String) throws -> URLRequest {
662
+ guard let requestURL = URL(string: url) else {
663
+ throw ZaiUsageError.networkError("Invalid URL: \(url)")
664
+ }
665
+ var request = URLRequest(url: requestURL)
666
+ request.httpMethod = "GET"
667
+ // z.ai expects "Bearer <token>" — add prefix if the user didn't include it.
668
+ let authValue: String
669
+ if apiKey.lowercased().hasPrefix("bearer ") {
670
+ authValue = "Bearer \(apiKey.dropFirst(7).trimmingCharacters(in: .whitespaces))"
671
+ } else {
672
+ authValue = "Bearer \(apiKey)"
673
+ }
674
+ request.setValue(authValue, forHTTPHeaderField: "Authorization")
675
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
676
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
677
+ request.setValue("en-US,en", forHTTPHeaderField: "Accept-Language")
678
+ request.timeoutInterval = 15
679
+ return request
680
+ }
681
+
682
+ /// Returns (startTime, endTime) as millisecond timestamps for a 24h rolling window.
683
+ private static func rolling24hWindow() -> (Int64, Int64) {
684
+ let now = Date()
685
+ let calendar = Calendar.current
686
+ let startOfCurrentHour = calendar.dateInterval(of: .hour, for: now)!.start
687
+ let yesterday = calendar.date(byAdding: .day, value: -1, to: startOfCurrentHour)!
688
+ let endOfCurrentHour = calendar.date(byAdding: .second, value: 3599, to: startOfCurrentHour)!
689
+
690
+ let startMs = Int64(yesterday.timeIntervalSince1970 * 1000)
691
+ let endMs = Int64(endOfCurrentHour.timeIntervalSince1970 * 1000)
692
+ return (startMs, endMs)
693
+ }
694
+
695
+ private static func rolling24hDates() -> (Date, Date) {
696
+ let now = Date()
697
+ let calendar = Calendar.current
698
+ let startOfCurrentHour = calendar.dateInterval(of: .hour, for: now)!.start
699
+ let yesterday = calendar.date(byAdding: .day, value: -1, to: startOfCurrentHour)!
700
+ return (yesterday, now)
701
+ }
702
+ }
703
+
704
+ // MARK: - Errors
705
+
706
+ public enum ZaiUsageError: LocalizedError, Sendable {
707
+ case invalidCredentials
708
+ case networkError(String)
709
+ case apiError(String)
710
+ case parseFailed(String)
711
+
712
+ public var errorDescription: String? {
713
+ switch self {
714
+ case .invalidCredentials:
715
+ "Invalid z.ai API credentials"
716
+ case let .networkError(message):
717
+ "z.ai network error: \(message)"
718
+ case let .apiError(message):
719
+ "z.ai API error: \(message)"
720
+ case let .parseFailed(message):
721
+ "Failed to parse z.ai response: \(message)"
722
+ }
723
+ }
724
+ }