@lastbrain/module-ai 2.0.26 → 2.0.30

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 (365) hide show
  1. package/README.md +52 -1
  2. package/dist/ai.build.config.d.ts.map +1 -1
  3. package/dist/ai.build.config.js +508 -9
  4. package/dist/api/admin/ai-provider-models/[id].d.ts +18 -0
  5. package/dist/api/admin/ai-provider-models/[id].d.ts.map +1 -0
  6. package/dist/api/admin/ai-provider-models/[id].js +58 -0
  7. package/dist/api/admin/ai-provider-models.d.ts +20 -0
  8. package/dist/api/admin/ai-provider-models.d.ts.map +1 -0
  9. package/dist/api/admin/ai-provider-models.js +26 -0
  10. package/dist/api/admin/ai-providers/[key].d.ts +18 -0
  11. package/dist/api/admin/ai-providers/[key].d.ts.map +1 -0
  12. package/dist/api/admin/ai-providers/[key].js +55 -0
  13. package/dist/api/admin/ai-providers.d.ts +20 -0
  14. package/dist/api/admin/ai-providers.d.ts.map +1 -0
  15. package/dist/api/admin/ai-providers.js +26 -0
  16. package/dist/api/admin/billing-analytics.d.ts +43 -0
  17. package/dist/api/admin/billing-analytics.d.ts.map +1 -0
  18. package/dist/api/admin/billing-analytics.js +144 -0
  19. package/dist/api/admin/global-ai-settings.d.ts +14 -0
  20. package/dist/api/admin/global-ai-settings.d.ts.map +1 -0
  21. package/dist/api/admin/global-ai-settings.js +63 -0
  22. package/dist/api/admin/token-packs/[id].d.ts.map +1 -1
  23. package/dist/api/admin/token-packs/[id].js +3 -2
  24. package/dist/api/admin/token-packs.d.ts.map +1 -1
  25. package/dist/api/admin/token-packs.js +3 -2
  26. package/dist/api/admin/user-monthly-details.d.ts +49 -0
  27. package/dist/api/admin/user-monthly-details.d.ts.map +1 -0
  28. package/dist/api/admin/user-monthly-details.js +140 -0
  29. package/dist/api/admin/user-quota.d.ts +21 -0
  30. package/dist/api/admin/user-quota.d.ts.map +1 -0
  31. package/dist/api/admin/user-quota.js +59 -0
  32. package/dist/api/admin/user-token/[id].d.ts.map +1 -1
  33. package/dist/api/admin/user-token/[id].js +2 -1
  34. package/dist/api/admin/user-token.d.ts +5 -2
  35. package/dist/api/admin/user-token.d.ts.map +1 -1
  36. package/dist/api/admin/user-token.js +91 -17
  37. package/dist/api/admin/user-usage-by-model.d.ts +22 -0
  38. package/dist/api/admin/user-usage-by-model.d.ts.map +1 -0
  39. package/dist/api/admin/user-usage-by-model.js +78 -0
  40. package/dist/api/admin/user-wallet-analytics.d.ts +15 -0
  41. package/dist/api/admin/user-wallet-analytics.d.ts.map +1 -0
  42. package/dist/api/admin/user-wallet-analytics.js +67 -0
  43. package/dist/api/admin/wallet-repair/route.d.ts +30 -0
  44. package/dist/api/admin/wallet-repair/route.d.ts.map +1 -0
  45. package/dist/api/admin/wallet-repair/route.js +63 -0
  46. package/dist/api/auth/ai-model-settings.d.ts +21 -0
  47. package/dist/api/auth/ai-model-settings.d.ts.map +1 -0
  48. package/dist/api/auth/ai-model-settings.js +86 -0
  49. package/dist/api/auth/ai-settings.d.ts +17 -0
  50. package/dist/api/auth/ai-settings.d.ts.map +1 -0
  51. package/dist/api/auth/ai-settings.js +87 -0
  52. package/dist/api/auth/api-keys/[id].d.ts +17 -0
  53. package/dist/api/auth/api-keys/[id].d.ts.map +1 -0
  54. package/dist/api/auth/api-keys/[id].js +66 -0
  55. package/dist/api/auth/api-keys.d.ts +19 -0
  56. package/dist/api/auth/api-keys.d.ts.map +1 -0
  57. package/dist/api/auth/api-keys.js +94 -0
  58. package/dist/api/auth/create-checkout.d.ts +1 -1
  59. package/dist/api/auth/create-checkout.d.ts.map +1 -1
  60. package/dist/api/auth/create-checkout.js +8 -6
  61. package/dist/api/auth/generate-image.d.ts +2 -2
  62. package/dist/api/auth/generate-image.d.ts.map +1 -1
  63. package/dist/api/auth/generate-image.js +404 -104
  64. package/dist/api/auth/generate-text.d.ts +3 -2
  65. package/dist/api/auth/generate-text.d.ts.map +1 -1
  66. package/dist/api/auth/generate-text.js +130 -58
  67. package/dist/api/auth/process-ocr.d.ts +9 -0
  68. package/dist/api/auth/process-ocr.d.ts.map +1 -0
  69. package/dist/api/auth/process-ocr.js +43 -0
  70. package/dist/api/auth/prompts/stats.d.ts +14 -0
  71. package/dist/api/auth/prompts/stats.d.ts.map +1 -0
  72. package/dist/api/auth/prompts/stats.js +46 -0
  73. package/dist/api/auth/prompts.d.ts +26 -0
  74. package/dist/api/auth/prompts.d.ts.map +1 -0
  75. package/dist/api/auth/prompts.js +175 -0
  76. package/dist/api/auth/token-balance.d.ts +26 -0
  77. package/dist/api/auth/token-balance.d.ts.map +1 -0
  78. package/dist/api/auth/token-balance.js +47 -0
  79. package/dist/api/auth/token-checkout.d.ts.map +1 -1
  80. package/dist/api/auth/token-checkout.js +22 -4
  81. package/dist/api/auth/token-packs.d.ts.map +1 -1
  82. package/dist/api/auth/token-packs.js +2 -1
  83. package/dist/api/auth/usage-by-model.d.ts +25 -0
  84. package/dist/api/auth/usage-by-model.d.ts.map +1 -0
  85. package/dist/api/auth/usage-by-model.js +95 -0
  86. package/dist/api/auth/usage.d.ts +26 -0
  87. package/dist/api/auth/usage.d.ts.map +1 -0
  88. package/dist/api/auth/usage.js +127 -0
  89. package/dist/api/auth/user-tokens.d.ts.map +1 -1
  90. package/dist/api/auth/user-tokens.js +36 -2
  91. package/dist/api/auth/wallet/route.d.ts +17 -0
  92. package/dist/api/auth/wallet/route.d.ts.map +1 -0
  93. package/dist/api/auth/wallet/route.js +68 -0
  94. package/dist/api/auth/wallet.d.ts +16 -0
  95. package/dist/api/auth/wallet.d.ts.map +1 -0
  96. package/dist/api/auth/wallet.js +71 -0
  97. package/dist/api/public/gateway-models.d.ts +25 -0
  98. package/dist/api/public/gateway-models.d.ts.map +1 -0
  99. package/dist/api/public/gateway-models.js +49 -0
  100. package/dist/api/public/pricing-summary.d.ts +46 -0
  101. package/dist/api/public/pricing-summary.d.ts.map +1 -0
  102. package/dist/api/public/pricing-summary.js +70 -0
  103. package/dist/api/public/prompts/[id]/stats.d.ts +15 -0
  104. package/dist/api/public/prompts/[id]/stats.d.ts.map +1 -0
  105. package/dist/api/public/prompts/[id]/stats.js +37 -0
  106. package/dist/api/public/prompts/[id]/view.d.ts +15 -0
  107. package/dist/api/public/prompts/[id]/view.d.ts.map +1 -0
  108. package/dist/api/public/prompts/[id]/view.js +41 -0
  109. package/dist/api/public/prompts/slug/[slug].d.ts +15 -0
  110. package/dist/api/public/prompts/slug/[slug].d.ts.map +1 -0
  111. package/dist/api/public/prompts/slug/[slug].js +40 -0
  112. package/dist/api/public/prompts/user/[username].d.ts +17 -0
  113. package/dist/api/public/prompts/user/[username].d.ts.map +1 -0
  114. package/dist/api/public/prompts/user/[username].js +51 -0
  115. package/dist/api/public/prompts.d.ts +15 -0
  116. package/dist/api/public/prompts.d.ts.map +1 -0
  117. package/dist/api/public/prompts.js +45 -0
  118. package/dist/api/public/token-packs.d.ts +11 -0
  119. package/dist/api/public/token-packs.d.ts.map +1 -0
  120. package/dist/api/public/token-packs.js +25 -0
  121. package/dist/api/public/token-pricing.d.ts +44 -0
  122. package/dist/api/public/token-pricing.d.ts.map +1 -0
  123. package/dist/api/public/token-pricing.js +168 -0
  124. package/dist/api/public/v1/_lib/artifacts.d.ts +52 -0
  125. package/dist/api/public/v1/_lib/artifacts.d.ts.map +1 -0
  126. package/dist/api/public/v1/_lib/artifacts.js +217 -0
  127. package/dist/api/public/v1/_lib/auth.d.ts +43 -0
  128. package/dist/api/public/v1/_lib/auth.d.ts.map +1 -0
  129. package/dist/api/public/v1/_lib/auth.js +108 -0
  130. package/dist/api/public/v1/_lib/errors.d.ts +17 -0
  131. package/dist/api/public/v1/_lib/errors.d.ts.map +1 -0
  132. package/dist/api/public/v1/_lib/errors.js +16 -0
  133. package/dist/api/public/v1/_lib/log.d.ts +29 -0
  134. package/dist/api/public/v1/_lib/log.d.ts.map +1 -0
  135. package/dist/api/public/v1/_lib/log.js +68 -0
  136. package/dist/api/public/v1/_lib/quota.d.ts +24 -0
  137. package/dist/api/public/v1/_lib/quota.d.ts.map +1 -0
  138. package/dist/api/public/v1/_lib/quota.js +118 -0
  139. package/dist/api/public/v1/_lib/router.d.ts +54 -0
  140. package/dist/api/public/v1/_lib/router.d.ts.map +1 -0
  141. package/dist/api/public/v1/_lib/router.js +119 -0
  142. package/dist/api/public/v1/connect.d.ts +20 -0
  143. package/dist/api/public/v1/connect.d.ts.map +1 -0
  144. package/dist/api/public/v1/connect.js +119 -0
  145. package/dist/api/public/v1/doc.d.ts +239 -0
  146. package/dist/api/public/v1/doc.d.ts.map +1 -0
  147. package/dist/api/public/v1/doc.js +253 -0
  148. package/dist/api/public/v1/history/[id].d.ts +92 -0
  149. package/dist/api/public/v1/history/[id].d.ts.map +1 -0
  150. package/dist/api/public/v1/history/[id].js +176 -0
  151. package/dist/api/public/v1/history.d.ts +30 -0
  152. package/dist/api/public/v1/history.d.ts.map +1 -0
  153. package/dist/api/public/v1/history.js +142 -0
  154. package/dist/api/public/v1/image-ai.d.ts +24 -0
  155. package/dist/api/public/v1/image-ai.d.ts.map +1 -0
  156. package/dist/api/public/v1/image-ai.js +233 -0
  157. package/dist/api/public/v1/prompts.d.ts +19 -0
  158. package/dist/api/public/v1/prompts.d.ts.map +1 -0
  159. package/dist/api/public/v1/prompts.js +107 -0
  160. package/dist/api/public/v1/provider.d.ts +16 -0
  161. package/dist/api/public/v1/provider.d.ts.map +1 -0
  162. package/dist/api/public/v1/provider.js +130 -0
  163. package/dist/api/public/v1/purchase.d.ts +11 -0
  164. package/dist/api/public/v1/purchase.d.ts.map +1 -0
  165. package/dist/api/public/v1/purchase.js +18 -0
  166. package/dist/api/public/v1/status.d.ts +35 -0
  167. package/dist/api/public/v1/status.d.ts.map +1 -0
  168. package/dist/api/public/v1/status.js +163 -0
  169. package/dist/api/public/v1/text-ai.d.ts +26 -0
  170. package/dist/api/public/v1/text-ai.d.ts.map +1 -0
  171. package/dist/api/public/v1/text-ai.js +239 -0
  172. package/dist/api/public/webhook.d.ts.map +1 -1
  173. package/dist/api/public/webhook.js +50 -39
  174. package/dist/api/track-usage.d.ts +12 -0
  175. package/dist/api/track-usage.d.ts.map +1 -0
  176. package/dist/api/track-usage.js +37 -0
  177. package/dist/components/Doc.d.ts.map +1 -1
  178. package/dist/components/Doc.js +1 -1
  179. package/dist/components/DocUsageCustom.js +6 -6
  180. package/dist/components/admin/UserTokenTab.d.ts.map +1 -1
  181. package/dist/components/admin/UserTokenTab.js +170 -23
  182. package/dist/components/auth/AuthDashboardAi.d.ts +2 -0
  183. package/dist/components/auth/AuthDashboardAi.d.ts.map +1 -0
  184. package/dist/components/auth/AuthDashboardAi.js +53 -0
  185. package/dist/docs/REFACTORING_BILLING_GUIDE.d.ts +277 -0
  186. package/dist/docs/REFACTORING_BILLING_GUIDE.d.ts.map +1 -0
  187. package/dist/docs/REFACTORING_BILLING_GUIDE.js +276 -0
  188. package/dist/index.d.ts +15 -1
  189. package/dist/index.d.ts.map +1 -1
  190. package/dist/index.js +18 -1
  191. package/dist/scripts/migrate-tokens-to-wallet.d.ts +13 -0
  192. package/dist/scripts/migrate-tokens-to-wallet.d.ts.map +1 -0
  193. package/dist/scripts/migrate-tokens-to-wallet.js +165 -0
  194. package/dist/server/__tests__/billing.test.d.ts +5 -0
  195. package/dist/server/__tests__/billing.test.d.ts.map +1 -0
  196. package/dist/server/__tests__/billing.test.js +223 -0
  197. package/dist/server/ai-client.d.ts +59 -0
  198. package/dist/server/ai-client.d.ts.map +1 -0
  199. package/dist/server/ai-client.js +111 -0
  200. package/dist/server/ai-generation-service.d.ts +66 -0
  201. package/dist/server/ai-generation-service.d.ts.map +1 -0
  202. package/dist/server/ai-generation-service.js +274 -0
  203. package/dist/server/billing.d.ts +200 -0
  204. package/dist/server/billing.d.ts.map +1 -0
  205. package/dist/server/billing.js +488 -0
  206. package/dist/server/gateway-service.d.ts +13 -0
  207. package/dist/server/gateway-service.d.ts.map +1 -0
  208. package/dist/server/gateway-service.js +161 -0
  209. package/dist/server/global-settings.d.ts +16 -0
  210. package/dist/server/global-settings.d.ts.map +1 -0
  211. package/dist/server/global-settings.js +42 -0
  212. package/dist/server/model-filter.d.ts +25 -0
  213. package/dist/server/model-filter.d.ts.map +1 -0
  214. package/dist/server/model-filter.js +240 -0
  215. package/dist/server/ocr.d.ts +39 -0
  216. package/dist/server/ocr.d.ts.map +1 -0
  217. package/dist/server/ocr.js +280 -0
  218. package/dist/server/openai-client.d.ts +19 -0
  219. package/dist/server/openai-client.d.ts.map +1 -0
  220. package/dist/server/openai-client.js +26 -0
  221. package/dist/server/pricing-config.d.ts +18 -0
  222. package/dist/server/pricing-config.d.ts.map +1 -0
  223. package/dist/server/pricing-config.js +94 -0
  224. package/dist/server/pricing-validator.d.ts +41 -0
  225. package/dist/server/pricing-validator.d.ts.map +1 -0
  226. package/dist/server/pricing-validator.js +113 -0
  227. package/dist/server/pricing.d.ts +121 -0
  228. package/dist/server/pricing.d.ts.map +1 -0
  229. package/dist/server/pricing.js +225 -0
  230. package/dist/server/quota.d.ts +66 -0
  231. package/dist/server/quota.d.ts.map +1 -0
  232. package/dist/server/quota.js +538 -0
  233. package/dist/server/wallet-repair.d.ts +32 -0
  234. package/dist/server/wallet-repair.d.ts.map +1 -0
  235. package/dist/server/wallet-repair.js +189 -0
  236. package/dist/server.d.ts +13 -1
  237. package/dist/server.d.ts.map +1 -1
  238. package/dist/server.js +87 -16
  239. package/dist/sitemap/handlers/prompts.d.ts +6 -0
  240. package/dist/sitemap/handlers/prompts.d.ts.map +1 -0
  241. package/dist/sitemap/handlers/prompts.js +72 -0
  242. package/dist/sitemap/handlers/users.d.ts +6 -0
  243. package/dist/sitemap/handlers/users.d.ts.map +1 -0
  244. package/dist/sitemap/handlers/users.js +80 -0
  245. package/dist/sitemap/manifest.d.ts +8 -0
  246. package/dist/sitemap/manifest.d.ts.map +1 -0
  247. package/dist/sitemap/manifest.js +27 -0
  248. package/dist/types/gateway.d.ts +40 -0
  249. package/dist/types/gateway.d.ts.map +1 -0
  250. package/dist/types/gateway.js +4 -0
  251. package/dist/types/quota.d.ts +74 -0
  252. package/dist/types/quota.d.ts.map +1 -0
  253. package/dist/types/quota.js +11 -0
  254. package/dist/utils/date.d.ts +7 -0
  255. package/dist/utils/date.d.ts.map +1 -0
  256. package/dist/utils/date.js +17 -0
  257. package/dist/web/admin/AdminTokenPacksPage.js +1 -1
  258. package/dist/web/admin/BillingAnalyticsPage.d.ts +2 -0
  259. package/dist/web/admin/BillingAnalyticsPage.d.ts.map +1 -0
  260. package/dist/web/admin/BillingAnalyticsPage.js +141 -0
  261. package/dist/web/admin/GlobalAISettingsPage.d.ts +2 -0
  262. package/dist/web/admin/GlobalAISettingsPage.d.ts.map +1 -0
  263. package/dist/web/admin/GlobalAISettingsPage.js +93 -0
  264. package/dist/web/admin/UserTokenPage.d.ts.map +1 -1
  265. package/dist/web/admin/UserTokenPage.js +20 -7
  266. package/dist/web/auth/AISettingsPage.d.ts +2 -0
  267. package/dist/web/auth/AISettingsPage.d.ts.map +1 -0
  268. package/dist/web/auth/AISettingsPage.js +258 -0
  269. package/dist/web/auth/APIKeysPage.d.ts +2 -0
  270. package/dist/web/auth/APIKeysPage.d.ts.map +1 -0
  271. package/dist/web/auth/APIKeysPage.js +154 -0
  272. package/dist/web/auth/HistoryPage.d.ts +2 -0
  273. package/dist/web/auth/HistoryPage.d.ts.map +1 -0
  274. package/dist/web/auth/HistoryPage.js +279 -0
  275. package/dist/web/auth/PromptsPage.d.ts +5 -0
  276. package/dist/web/auth/PromptsPage.d.ts.map +1 -0
  277. package/dist/web/auth/PromptsPage.js +137 -0
  278. package/dist/web/auth/TokenPage.d.ts.map +1 -1
  279. package/dist/web/auth/TokenPage.js +88 -31
  280. package/dist/web/auth/UsageAndTokensPage.d.ts +2 -0
  281. package/dist/web/auth/UsageAndTokensPage.d.ts.map +1 -0
  282. package/dist/web/auth/UsageAndTokensPage.js +157 -0
  283. package/dist/web/auth/UsagePage.d.ts +2 -0
  284. package/dist/web/auth/UsagePage.d.ts.map +1 -0
  285. package/dist/web/auth/UsagePage.js +62 -0
  286. package/dist/web/auth/components/ApiKeyFilterSelect.d.ts +13 -0
  287. package/dist/web/auth/components/ApiKeyFilterSelect.d.ts.map +1 -0
  288. package/dist/web/auth/components/ApiKeyFilterSelect.js +16 -0
  289. package/dist/web/auth/components/ModelUsageTable.d.ts +19 -0
  290. package/dist/web/auth/components/ModelUsageTable.d.ts.map +1 -0
  291. package/dist/web/auth/components/ModelUsageTable.js +37 -0
  292. package/dist/web/auth/components/PurchaseButton.d.ts +7 -0
  293. package/dist/web/auth/components/PurchaseButton.d.ts.map +1 -0
  294. package/dist/web/auth/components/PurchaseButton.js +13 -0
  295. package/dist/web/auth/components/TokenHistoryCard.d.ts +20 -0
  296. package/dist/web/auth/components/TokenHistoryCard.d.ts.map +1 -0
  297. package/dist/web/auth/components/TokenHistoryCard.js +76 -0
  298. package/dist/web/auth/components/TokenKpiGrid.d.ts +24 -0
  299. package/dist/web/auth/components/TokenKpiGrid.d.ts.map +1 -0
  300. package/dist/web/auth/components/TokenKpiGrid.js +38 -0
  301. package/dist/web/auth/components/UsageByDayChart.d.ts +11 -0
  302. package/dist/web/auth/components/UsageByDayChart.d.ts.map +1 -0
  303. package/dist/web/auth/components/UsageByDayChart.js +32 -0
  304. package/dist/web/auth/components/UsageByModelBarChart.d.ts +12 -0
  305. package/dist/web/auth/components/UsageByModelBarChart.d.ts.map +1 -0
  306. package/dist/web/auth/components/UsageByModelBarChart.js +32 -0
  307. package/dist/web/auth/components/WalletStatusCard.d.ts +9 -0
  308. package/dist/web/auth/components/WalletStatusCard.d.ts.map +1 -0
  309. package/dist/web/auth/components/WalletStatusCard.js +50 -0
  310. package/dist/web/components/ImageGenerative.d.ts +3 -1
  311. package/dist/web/components/ImageGenerative.d.ts.map +1 -1
  312. package/dist/web/components/ImageGenerative.js +139 -52
  313. package/dist/web/components/TextareaGenerative.d.ts +3 -1
  314. package/dist/web/components/TextareaGenerative.d.ts.map +1 -1
  315. package/dist/web/components/TextareaGenerative.js +10 -5
  316. package/dist/web/public/PromptDetailPage.d.ts +25 -0
  317. package/dist/web/public/PromptDetailPage.d.ts.map +1 -0
  318. package/dist/web/public/PromptDetailPage.js +71 -0
  319. package/dist/web/public/PromptDetailPageServer.d.ts +15 -0
  320. package/dist/web/public/PromptDetailPageServer.d.ts.map +1 -0
  321. package/dist/web/public/PromptDetailPageServer.js +68 -0
  322. package/dist/web/public/PublicPromptsPage.d.ts +5 -0
  323. package/dist/web/public/PublicPromptsPage.d.ts.map +1 -0
  324. package/dist/web/public/PublicPromptsPage.js +110 -0
  325. package/dist/web/public/PurchaseTokensPage.d.ts +2 -0
  326. package/dist/web/public/PurchaseTokensPage.d.ts.map +1 -0
  327. package/dist/web/public/PurchaseTokensPage.js +98 -0
  328. package/dist/web/public/UserAvatar.d.ts +13 -0
  329. package/dist/web/public/UserAvatar.d.ts.map +1 -0
  330. package/dist/web/public/UserAvatar.js +13 -0
  331. package/dist/web/public/UserDetailPageServer.d.ts +15 -0
  332. package/dist/web/public/UserDetailPageServer.d.ts.map +1 -0
  333. package/dist/web/public/UserDetailPageServer.js +31 -0
  334. package/dist/web/public/UserPromptsPage.d.ts +9 -0
  335. package/dist/web/public/UserPromptsPage.d.ts.map +1 -0
  336. package/dist/web/public/UserPromptsPage.js +112 -0
  337. package/dist/web/public/UserPromptsPageServer.d.ts +15 -0
  338. package/dist/web/public/UserPromptsPageServer.d.ts.map +1 -0
  339. package/dist/web/public/UserPromptsPageServer.js +31 -0
  340. package/package.json +18 -9
  341. package/supabase/migrations/20251125000000_ai_tokens.sql +7 -0
  342. package/supabase/migrations/20260123100002_user_token_quota_monthly copy.sql +173 -0
  343. package/supabase/migrations/20260128100003_update_and_add_table.sql +368 -0
  344. package/supabase/migrations/20260128120000_seed_providers_models.sql +78 -0
  345. package/supabase/migrations/20260128131405_add_api_key_id_to_ledgers.sql +41 -0
  346. package/supabase/migrations/20260128140000_ai_artifacts_storage.sql +99 -0
  347. package/supabase/migrations/20260128140002_ai_user_settings.sql +57 -0
  348. package/supabase/migrations/20260128150000_drop_ai_user_settings.sql +21 -0
  349. package/supabase/migrations/20260128160000_wallet_billing_system.sql +192 -0
  350. package/supabase/migrations/20260128160001_wallet_rpc_functions.sql +165 -0
  351. package/supabase/migrations/20260128170000_add_pack_coef_to_token_packs.sql +30 -0
  352. package/supabase/migrations/20260129120000_wallet_view_rpc.sql +41 -0
  353. package/supabase/migrations/20260129220003_update_pack_margins.sql +31 -0
  354. package/supabase/migrations/20260129330004_ai_user_prompts.sql +151 -0
  355. package/supabase/migrations/20260129330005_ai_prompts_ip_tracking.sql +92 -0
  356. package/supabase/migrations/20260129330006_ai_prompts_slug.sql +64 -0
  357. package/supabase/migrations/20260129330007_ai_prompts_view_slug.sql +26 -0
  358. package/supabase/migrations/20260129440000_ai_prompts_view_username.sql +33 -0
  359. package/supabase/migrations/20260129450000_ai_prompts_add_lang.sql +40 -0
  360. package/supabase/migrations/20260131000000_extract_model_prompt_in_ledger.sql +92 -0
  361. package/supabase/migrations/20260131140000_fix_duplicate_purchases.sql +64 -0
  362. package/supabase/migrations/20260201120000_module-ai_default_models.sql +63 -0
  363. package/supabase/migrations/20260201130000_module-ai_remove_provider_tables.sql +17 -0
  364. package/supabase/migrations-down/20251217120000_user_token_quota_monthly.sql +34 -0
  365. package/supabase/migrations-down/20260128131405_add_api_key_id_to_ledgers.sql +25 -0
@@ -0,0 +1,107 @@
1
+ /**
2
+ * GET /api/public/v1/prompts
3
+ * Get user's prompts via Bearer token authentication
4
+ */
5
+ import { NextResponse } from "next/server";
6
+ import { randomUUID } from "crypto";
7
+ import { logger } from "@lastbrain/core";
8
+ import { getSupabaseServiceClient } from "@lastbrain/core/server";
9
+ import { validateApiKey } from "./_lib/auth";
10
+ import { createErrorResponse } from "./_lib/errors";
11
+ import { logApiCall, updateApiKeyLastUsed } from "./_lib/log";
12
+ export async function GET(request) {
13
+ const startTime = Date.now();
14
+ const requestId = randomUUID();
15
+ let apiKeyId = null;
16
+ let ownerId = null;
17
+ let statusCode = 200;
18
+ let errorCode = null;
19
+ try {
20
+ const authHeader = request.headers.get("Authorization");
21
+ // 1. Validate API key
22
+ const authResult = await validateApiKey(authHeader);
23
+ if (!authResult.success || !authResult.apiKey) {
24
+ const { response, status } = createErrorResponse(authResult.errorCode, authResult.error || "Authentication failed", requestId, undefined, 401);
25
+ statusCode = status;
26
+ errorCode = authResult.errorCode || null;
27
+ return NextResponse.json(response, { status });
28
+ }
29
+ const apiKey = authResult.apiKey;
30
+ apiKeyId = apiKey.id;
31
+ ownerId = apiKey.owner_id;
32
+ // 2. Get query parameters
33
+ const { searchParams } = new URL(request.url);
34
+ const type = searchParams.get("type"); // 'text' or 'image'
35
+ const favorite = searchParams.get("favorite") === "true";
36
+ const publicOnly = searchParams.get("public") === "true";
37
+ // 3. Get prompts
38
+ const supabase = await getSupabaseServiceClient();
39
+ let query = supabase
40
+ .from("user_prompt")
41
+ .select("id, title, content, type, tags, is_public, favorite, created_at")
42
+ .eq("owner_id", ownerId)
43
+ .order("favorite", { ascending: false })
44
+ .order("created_at", { ascending: false });
45
+ if (type) {
46
+ query = query.eq("type", type);
47
+ }
48
+ if (favorite) {
49
+ query = query.eq("favorite", true);
50
+ }
51
+ if (publicOnly) {
52
+ query = query.eq("is_public", true);
53
+ }
54
+ const { data: prompts, error } = await query;
55
+ if (error) {
56
+ logger.error("[prompts] Error fetching prompts:", error);
57
+ statusCode = 500;
58
+ errorCode = "DATABASE_ERROR";
59
+ const { response, status } = createErrorResponse("INTERNAL_ERROR", "Failed to fetch prompts", requestId, undefined, 500);
60
+ return NextResponse.json(response, { status });
61
+ }
62
+ // 4. Update API key last used
63
+ await updateApiKeyLastUsed(apiKey);
64
+ // 5. Log API call
65
+ await logApiCall({
66
+ apiKeyId,
67
+ ownerId,
68
+ endpoint: "prompts",
69
+ provider: null,
70
+ model: null,
71
+ tokensIn: null,
72
+ tokensOut: null,
73
+ tokensTotal: null,
74
+ latencyMs: Date.now() - startTime,
75
+ statusCode,
76
+ errorCode,
77
+ requestId,
78
+ });
79
+ return NextResponse.json({
80
+ request_id: requestId,
81
+ prompts,
82
+ });
83
+ }
84
+ catch (error) {
85
+ logger.error("[prompts] Unexpected error:", error);
86
+ statusCode = 500;
87
+ errorCode = "INTERNAL_ERROR";
88
+ if (apiKeyId && ownerId) {
89
+ await logApiCall({
90
+ apiKeyId,
91
+ ownerId,
92
+ endpoint: "prompts",
93
+ provider: null,
94
+ model: null,
95
+ tokensIn: null,
96
+ tokensOut: null,
97
+ tokensTotal: null,
98
+ latencyMs: Date.now() - startTime,
99
+ statusCode,
100
+ errorCode,
101
+ requestId,
102
+ });
103
+ }
104
+ const { response, status } = createErrorResponse("INTERNAL_ERROR", error.message || "Internal server error", requestId, undefined, 500);
105
+ return NextResponse.json(response, { status });
106
+ }
107
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * GET /api/public/v1/provider
3
+ * List available AI providers and models from Vercel AI Gateway
4
+ */
5
+ import { NextRequest, NextResponse } from "next/server";
6
+ export declare function GET(request: NextRequest): Promise<NextResponse<import("./_lib/errors").ApiError> | NextResponse<{
7
+ request_id: `${string}-${string}-${string}-${string}-${string}`;
8
+ providers: import("../../../types/gateway").GatewayProvider[];
9
+ stale: boolean | undefined;
10
+ cached_at: string | undefined;
11
+ user_settings: {
12
+ enabled_models: any;
13
+ enabled_providers: null;
14
+ };
15
+ }>>;
16
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../../src/api/public/v1/provider.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AASxD,wBAAsB,GAAG,CAAC,OAAO,EAAE,WAAW;;;;;;;;;IAwJ7C"}
@@ -0,0 +1,130 @@
1
+ /**
2
+ * GET /api/public/v1/provider
3
+ * List available AI providers and models from Vercel AI Gateway
4
+ */
5
+ import { NextResponse } from "next/server";
6
+ import { randomUUID } from "crypto";
7
+ import { logger } from "@lastbrain/core";
8
+ import { validateApiKey } from "./_lib/auth";
9
+ import { createErrorResponse } from "./_lib/errors";
10
+ import { logApiCall, updateApiKeyLastUsed } from "./_lib/log";
11
+ import { fetchGatewayModels } from "../../../server/gateway-service";
12
+ import { getSupabaseServiceClient } from "@lastbrain/core/server";
13
+ export async function GET(request) {
14
+ const startTime = Date.now();
15
+ const requestId = randomUUID();
16
+ let apiKeyId = null;
17
+ let ownerId = null;
18
+ let statusCode = 200;
19
+ let errorCode = null;
20
+ try {
21
+ const authHeader = request.headers.get("Authorization");
22
+ console.log("🚀 ~ GET ~ authHeader:", authHeader);
23
+ // 1. Validate API key
24
+ const authResult = await validateApiKey(authHeader);
25
+ if (!authResult.success || !authResult.apiKey) {
26
+ const { response, status } = createErrorResponse(authResult.errorCode, authResult.error || "Authentication failed", requestId, undefined, 401);
27
+ statusCode = status;
28
+ errorCode = authResult.errorCode || null;
29
+ return NextResponse.json(response, { status });
30
+ }
31
+ const apiKey = authResult.apiKey;
32
+ apiKeyId = apiKey.id;
33
+ ownerId = apiKey.owner_id;
34
+ // 2. Get query parameters
35
+ const searchParams = request.nextUrl.searchParams;
36
+ const kindFilter = searchParams.get("kind"); // "text" or "image"
37
+ const includeDisabled = searchParams.get("include_disabled") === "true";
38
+ // 3. Fetch models from Vercel AI Gateway
39
+ const gatewayResponse = await fetchGatewayModels();
40
+ // 4. Get user's enabled models settings
41
+ const supabase = await getSupabaseServiceClient();
42
+ const { data: settings } = await supabase
43
+ .from("user_ai_settings")
44
+ .select("allowed_models")
45
+ .eq("owner_id", ownerId)
46
+ .single();
47
+ console.log("🚀 ~ GET ~ settings:", settings);
48
+ const enabledModels = settings?.allowed_models || [];
49
+ const enabledProviders = null; // No provider filter in user_ai_settings
50
+ // 5. Filter models based on user settings (unless include_disabled=true)
51
+ let filteredProviders = gatewayResponse.providers;
52
+ // Only filter if allowed_models is explicitly set and include_disabled is false
53
+ if (!includeDisabled && enabledModels.length > 0) {
54
+ filteredProviders = gatewayResponse.providers
55
+ .map((provider) => {
56
+ // Filter models by allowed_models
57
+ const filteredModels = provider.models.filter((model) => enabledModels.includes(model.id));
58
+ if (filteredModels.length === 0) {
59
+ return null;
60
+ }
61
+ return {
62
+ ...provider,
63
+ models: filteredModels,
64
+ };
65
+ })
66
+ .filter((p) => p !== null);
67
+ console.log("🚀 ~ GET ~ filteredProviders count:", filteredProviders.length, "total models:", filteredProviders.reduce((sum, p) => sum + p.models.length, 0));
68
+ }
69
+ // 6. Apply kind filter if specified
70
+ if (kindFilter) {
71
+ filteredProviders = filteredProviders
72
+ .map((provider) => ({
73
+ ...provider,
74
+ models: provider.models.filter((m) => m.type === kindFilter),
75
+ }))
76
+ .filter((p) => p.models.length > 0);
77
+ }
78
+ // 7. Update API key last used
79
+ await updateApiKeyLastUsed(apiKey);
80
+ // 8. Log API call
81
+ await logApiCall({
82
+ apiKeyId,
83
+ ownerId,
84
+ endpoint: "provider",
85
+ provider: null,
86
+ model: null,
87
+ tokensIn: null,
88
+ tokensOut: null,
89
+ tokensTotal: null,
90
+ latencyMs: Date.now() - startTime,
91
+ statusCode,
92
+ errorCode,
93
+ requestId,
94
+ });
95
+ return NextResponse.json({
96
+ request_id: requestId,
97
+ providers: filteredProviders,
98
+ stale: gatewayResponse.stale,
99
+ cached_at: gatewayResponse.cached_at,
100
+ user_settings: {
101
+ enabled_models: enabledModels,
102
+ enabled_providers: enabledProviders,
103
+ },
104
+ });
105
+ }
106
+ catch (error) {
107
+ logger.error("[provider] Error:", error);
108
+ statusCode = 500;
109
+ errorCode = "INTERNAL_ERROR";
110
+ // Log failed API call
111
+ if (apiKeyId && ownerId) {
112
+ await logApiCall({
113
+ apiKeyId,
114
+ ownerId,
115
+ endpoint: "provider",
116
+ provider: null,
117
+ model: null,
118
+ tokensIn: null,
119
+ tokensOut: null,
120
+ tokensTotal: null,
121
+ latencyMs: Date.now() - startTime,
122
+ statusCode,
123
+ errorCode,
124
+ requestId,
125
+ });
126
+ }
127
+ const { response, status } = createErrorResponse("INTERNAL_ERROR", error.message, requestId);
128
+ return NextResponse.json(response, { status });
129
+ }
130
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * GET /api/public/v1/purchase
3
+ * Get URL to purchase tokens
4
+ */
5
+ import { NextRequest, NextResponse } from "next/server";
6
+ export declare function GET(request: NextRequest): Promise<NextResponse<{
7
+ request_id: `${string}-${string}-${string}-${string}-${string}`;
8
+ purchase_url: string;
9
+ message: string;
10
+ }>>;
11
+ //# sourceMappingURL=purchase.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"purchase.d.ts","sourceRoot":"","sources":["../../../../src/api/public/v1/purchase.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAGxD,wBAAsB,GAAG,CAAC,OAAO,EAAE,WAAW;;;;IAc7C"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * GET /api/public/v1/purchase
3
+ * Get URL to purchase tokens
4
+ */
5
+ import { NextResponse } from "next/server";
6
+ import { randomUUID } from "crypto";
7
+ export async function GET(request) {
8
+ const requestId = randomUUID();
9
+ // Get purchase URL from environment or use default
10
+ const purchaseUrl = process.env.TOKEN_PURCHASE_URL ||
11
+ process.env.NEXT_PUBLIC_APP_URL + "/auth/module-ai/tokens" ||
12
+ "/auth/module-ai/tokens";
13
+ return NextResponse.json({
14
+ request_id: requestId,
15
+ purchase_url: purchaseUrl,
16
+ message: "Visit this URL to purchase tokens for your account",
17
+ });
18
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * GET /api/public/v1/status
3
+ * Get user status, balance, and quota information
4
+ */
5
+ import { NextRequest, NextResponse } from "next/server";
6
+ export declare function GET(request: NextRequest): Promise<NextResponse<import("./_lib/errors").ApiError> | NextResponse<{
7
+ request_id: `${string}-${string}-${string}-${string}-${string}`;
8
+ api_key: {
9
+ id: string;
10
+ name: string;
11
+ prefix: string;
12
+ env: string;
13
+ scopes: string[];
14
+ rate_limit_rpm: number;
15
+ daily_token_limit: bigint | null;
16
+ created_at: string;
17
+ };
18
+ balance: {
19
+ purchased: any;
20
+ quota: any;
21
+ total: any;
22
+ };
23
+ quota: any;
24
+ settings: {
25
+ mode: any;
26
+ max_tokens_per_call: any;
27
+ };
28
+ storage: {
29
+ db_mb: number;
30
+ files_mb: number;
31
+ total_mb: number;
32
+ allocated_mb: number;
33
+ };
34
+ }>>;
35
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../../../../src/api/public/v1/status.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAQxD,wBAAsB,GAAG,CAAC,OAAO,EAAE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA6L7C"}
@@ -0,0 +1,163 @@
1
+ /**
2
+ * GET /api/public/v1/status
3
+ * Get user status, balance, and quota information
4
+ */
5
+ import { NextResponse } from "next/server";
6
+ import { randomUUID } from "crypto";
7
+ import { logger, getStorageUsage } from "@lastbrain/core";
8
+ import { getSupabaseServiceClient } from "@lastbrain/core/server";
9
+ import { validateApiKey } from "./_lib/auth";
10
+ import { createErrorResponse } from "./_lib/errors";
11
+ import { logApiCall, updateApiKeyLastUsed } from "./_lib/log";
12
+ export async function GET(request) {
13
+ const startTime = Date.now();
14
+ const requestId = randomUUID();
15
+ let apiKeyId = null;
16
+ let ownerId = null;
17
+ let statusCode = 200;
18
+ let errorCode = null;
19
+ try {
20
+ const authHeader = request.headers.get("Authorization");
21
+ // 1. Validate API key
22
+ const authResult = await validateApiKey(authHeader);
23
+ if (!authResult.success || !authResult.apiKey) {
24
+ const { response, status } = createErrorResponse(authResult.errorCode, authResult.error || "Authentication failed", requestId, undefined, 401);
25
+ statusCode = status;
26
+ errorCode = authResult.errorCode || null;
27
+ return NextResponse.json(response, { status });
28
+ }
29
+ const apiKey = authResult.apiKey;
30
+ apiKeyId = apiKey.id;
31
+ ownerId = apiKey.owner_id;
32
+ // 2. Get token balance (purchased)
33
+ const supabase = await getSupabaseServiceClient();
34
+ const { data: balanceData } = await supabase
35
+ .from("user_token_balance_v")
36
+ .select("balance")
37
+ .eq("owner_id", ownerId)
38
+ .single();
39
+ const purchasedBalance = balanceData?.balance || 0;
40
+ // 3. Get quota balance (monthly included)
41
+ const { data: quotaData } = await supabase
42
+ .from("user_token_quota_monthly")
43
+ .select("plan, effective_included_tokens, used_included_tokens, period_start, period_end")
44
+ .eq("owner_id", ownerId)
45
+ .single();
46
+ let quotaInfo = {
47
+ plan: "free",
48
+ effective_quota: 0,
49
+ used_quota: 0,
50
+ remaining_quota: 0,
51
+ period_start: null,
52
+ period_end: null,
53
+ is_active: false,
54
+ };
55
+ if (quotaData) {
56
+ const now = new Date();
57
+ const periodStart = quotaData.period_start
58
+ ? new Date(quotaData.period_start)
59
+ : null;
60
+ const periodEnd = quotaData.period_end
61
+ ? new Date(quotaData.period_end)
62
+ : null;
63
+ const isActive = periodStart && periodEnd && now >= periodStart && now <= periodEnd;
64
+ quotaInfo = {
65
+ plan: quotaData.plan,
66
+ effective_quota: quotaData.effective_included_tokens,
67
+ used_quota: quotaData.used_included_tokens || 0,
68
+ remaining_quota: isActive
69
+ ? Math.max(0, quotaData.effective_included_tokens -
70
+ (quotaData.used_included_tokens || 0))
71
+ : 0,
72
+ period_start: quotaData.period_start,
73
+ period_end: quotaData.period_end,
74
+ is_active: isActive,
75
+ };
76
+ }
77
+ // 4. Get user AI settings
78
+ const { data: settings } = await supabase
79
+ .from("user_ai_settings")
80
+ .select("mode, max_tokens_per_call")
81
+ .eq("owner_id", ownerId)
82
+ .single();
83
+ const settingsInfo = {
84
+ mode: settings?.mode || "auto",
85
+ max_tokens_per_call: settings?.max_tokens_per_call || null,
86
+ };
87
+ // 5. Get storage info
88
+ const storageData = await getStorageUsage(supabase, ownerId);
89
+ const storageInfo = {
90
+ db_mb: 0, // getStorageUsage ne fait pas cette distinction
91
+ files_mb: storageData.usedBytes / (1024 * 1024),
92
+ total_mb: storageData.usedBytes / (1024 * 1024),
93
+ allocated_mb: storageData.allocatedBytes / (1024 * 1024),
94
+ };
95
+ // 6. API key info
96
+ const apiKeyInfo = {
97
+ id: apiKey.id,
98
+ name: apiKey.name,
99
+ prefix: apiKey.prefix,
100
+ env: apiKey.env,
101
+ scopes: apiKey.scopes,
102
+ rate_limit_rpm: apiKey.rate_limit_rpm,
103
+ daily_token_limit: apiKey.daily_token_limit,
104
+ created_at: apiKey.created_at,
105
+ };
106
+ // 7. Log API call
107
+ const latencyMs = Date.now() - startTime;
108
+ await logApiCall({
109
+ apiKeyId,
110
+ ownerId,
111
+ endpoint: "status",
112
+ provider: null,
113
+ model: null,
114
+ tokensIn: null,
115
+ tokensOut: null,
116
+ tokensTotal: null,
117
+ latencyMs,
118
+ statusCode,
119
+ errorCode: null,
120
+ requestId,
121
+ });
122
+ // 8. Update API key last used
123
+ await updateApiKeyLastUsed(apiKey);
124
+ // 9. Return response
125
+ return NextResponse.json({
126
+ request_id: requestId,
127
+ api_key: apiKeyInfo,
128
+ balance: {
129
+ purchased: purchasedBalance,
130
+ quota: quotaInfo.remaining_quota,
131
+ total: purchasedBalance + quotaInfo.remaining_quota,
132
+ },
133
+ quota: quotaInfo,
134
+ settings: settingsInfo,
135
+ storage: storageInfo,
136
+ });
137
+ }
138
+ catch (error) {
139
+ logger.error("[status] Unexpected error", error);
140
+ statusCode = 500;
141
+ errorCode = "INTERNAL_ERROR";
142
+ // Log error even in catch
143
+ if (apiKeyId && ownerId) {
144
+ const latencyMs = Date.now() - startTime;
145
+ await logApiCall({
146
+ apiKeyId,
147
+ ownerId,
148
+ endpoint: "status",
149
+ provider: null,
150
+ model: null,
151
+ tokensIn: null,
152
+ tokensOut: null,
153
+ tokensTotal: null,
154
+ latencyMs,
155
+ statusCode,
156
+ errorCode,
157
+ requestId,
158
+ });
159
+ }
160
+ const { response, status } = createErrorResponse("INTERNAL_ERROR", error.message || "Internal server error", requestId, undefined, 500);
161
+ return NextResponse.json(response, { status });
162
+ }
163
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * POST /api/public/v1/text-ai
3
+ * Generate text using AI
4
+ */
5
+ import { NextRequest, NextResponse } from "next/server";
6
+ export declare function POST(request: NextRequest): Promise<NextResponse<import("./_lib/errors").ApiError> | NextResponse<{
7
+ request_id: `${string}-${string}-${string}-${string}-${string}`;
8
+ text: string | undefined;
9
+ model: string | undefined;
10
+ provider: string | undefined;
11
+ tokens: {
12
+ input: number | undefined;
13
+ output: number | undefined;
14
+ total: number;
15
+ };
16
+ balance: {
17
+ remaining_quota: number;
18
+ remaining_purchased: any;
19
+ total: any;
20
+ };
21
+ artifact: {
22
+ id: string | undefined;
23
+ stored: boolean;
24
+ } | undefined;
25
+ }>>;
26
+ //# sourceMappingURL=text-ai.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text-ai.d.ts","sourceRoot":"","sources":["../../../../src/api/public/v1/text-ai.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAyBxD,wBAAsB,IAAI,CAAC,OAAO,EAAE,WAAW;;;;;;;;;;;;;;;;;;;IA6S9C"}