nuxt-backend 0.3.0 → 0.4.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 (555) hide show
  1. package/README.md +8 -1
  2. package/dist/chunks/catalog.mjs +1 -1
  3. package/dist/chunks/doctor.mjs +102 -8
  4. package/dist/chunks/email-previews.mjs +1 -1
  5. package/dist/chunks/health.mjs +2 -2
  6. package/dist/chunks/index.mjs +3 -3
  7. package/dist/chunks/install.mjs +4 -4
  8. package/dist/chunks/run.mjs +1 -1
  9. package/dist/chunks/server.mjs +6 -6
  10. package/dist/cli.mjs +285 -140
  11. package/dist/convex/catalog.d.ts +8 -0
  12. package/dist/convex/catalog.d.ts.map +1 -1
  13. package/dist/convex/catalog.js +16 -0
  14. package/dist/convex/catalog.js.map +1 -1
  15. package/dist/convex/components/backend/_generated/component.d.ts +21 -1
  16. package/dist/convex/components/backend/_generated/component.d.ts.map +1 -1
  17. package/dist/convex/components/backend/billing.d.ts +7 -0
  18. package/dist/convex/components/backend/billing.d.ts.map +1 -1
  19. package/dist/convex/components/backend/billing.js +20 -5
  20. package/dist/convex/components/backend/billing.js.map +1 -1
  21. package/dist/convex/components/backend/jobs.d.ts +69 -1
  22. package/dist/convex/components/backend/jobs.d.ts.map +1 -1
  23. package/dist/convex/components/backend/jobs.js +103 -5
  24. package/dist/convex/components/backend/jobs.js.map +1 -1
  25. package/dist/convex/components/backend/schema.d.ts +46 -18
  26. package/dist/convex/components/backend/schema.d.ts.map +1 -1
  27. package/dist/convex/components/backend/schema.js +11 -0
  28. package/dist/convex/components/backend/schema.js.map +1 -1
  29. package/dist/convex/components/backend/subscriptions.d.ts +3 -3
  30. package/dist/convex/delivery.d.ts +17 -0
  31. package/dist/convex/delivery.d.ts.map +1 -1
  32. package/dist/convex/delivery.js +26 -1
  33. package/dist/convex/delivery.js.map +1 -1
  34. package/dist/convex/emails/renewal-reminder.d.ts.map +1 -1
  35. package/dist/convex/emails/renewal-reminder.js +17 -1
  36. package/dist/convex/emails/renewal-reminder.js.map +1 -1
  37. package/dist/convex/errors.d.ts +7 -5
  38. package/dist/convex/errors.d.ts.map +1 -1
  39. package/dist/convex/errors.js +24 -9
  40. package/dist/convex/errors.js.map +1 -1
  41. package/dist/convex/events.d.ts +10 -0
  42. package/dist/convex/events.d.ts.map +1 -1
  43. package/dist/convex/events.js +7 -0
  44. package/dist/convex/events.js.map +1 -1
  45. package/dist/convex/integrations/ai/images.d.ts.map +1 -1
  46. package/dist/convex/integrations/ai/images.js +20 -7
  47. package/dist/convex/integrations/ai/images.js.map +1 -1
  48. package/dist/convex/integrations/ai/job-errors.d.ts +32 -4
  49. package/dist/convex/integrations/ai/job-errors.d.ts.map +1 -1
  50. package/dist/convex/integrations/ai/job-errors.js +55 -8
  51. package/dist/convex/integrations/ai/job-errors.js.map +1 -1
  52. package/dist/convex/integrations/ai/jobs.d.ts +128 -7
  53. package/dist/convex/integrations/ai/jobs.d.ts.map +1 -1
  54. package/dist/convex/integrations/ai/jobs.js +395 -63
  55. package/dist/convex/integrations/ai/jobs.js.map +1 -1
  56. package/dist/convex/integrations/ai/models.d.ts +1 -1
  57. package/dist/convex/integrations/ai/models.d.ts.map +1 -1
  58. package/dist/convex/integrations/ai/moderation.d.ts +9 -3
  59. package/dist/convex/integrations/ai/moderation.d.ts.map +1 -1
  60. package/dist/convex/integrations/ai/moderation.js +4 -2
  61. package/dist/convex/integrations/ai/moderation.js.map +1 -1
  62. package/dist/convex/integrations/ai.d.ts +2 -2
  63. package/dist/convex/integrations/ai.d.ts.map +1 -1
  64. package/dist/convex/integrations/ai.js +1 -1
  65. package/dist/convex/integrations/ai.js.map +1 -1
  66. package/dist/convex/integrations/billing/context.d.ts.map +1 -1
  67. package/dist/convex/integrations/billing/context.js +5 -2
  68. package/dist/convex/integrations/billing/context.js.map +1 -1
  69. package/dist/convex/integrations/billing/credits.d.ts +1 -0
  70. package/dist/convex/integrations/billing/credits.d.ts.map +1 -1
  71. package/dist/convex/integrations/billing/credits.js +4 -1
  72. package/dist/convex/integrations/billing/credits.js.map +1 -1
  73. package/dist/convex/integrations/billing/features.d.ts.map +1 -1
  74. package/dist/convex/integrations/billing/gifts.d.ts.map +1 -1
  75. package/dist/convex/integrations/billing/history.d.ts.map +1 -1
  76. package/dist/convex/integrations/billing/passes.d.ts +2 -2
  77. package/dist/convex/integrations/billing/passes.d.ts.map +1 -1
  78. package/dist/convex/integrations/billing/passes.js +3 -11
  79. package/dist/convex/integrations/billing/passes.js.map +1 -1
  80. package/dist/convex/integrations/billing/provider-failure.d.ts +17 -0
  81. package/dist/convex/integrations/billing/provider-failure.d.ts.map +1 -0
  82. package/dist/convex/integrations/billing/provider-failure.js +52 -0
  83. package/dist/convex/integrations/billing/provider-failure.js.map +1 -0
  84. package/dist/convex/integrations/billing/quotas.d.ts.map +1 -1
  85. package/dist/convex/integrations/billing/subscriptions.d.ts.map +1 -1
  86. package/dist/convex/integrations/billing/types/setup.d.ts +1 -0
  87. package/dist/convex/integrations/billing/types/setup.d.ts.map +1 -1
  88. package/dist/convex/integrations/billing/types/surface.d.ts +9 -1
  89. package/dist/convex/integrations/billing/types/surface.d.ts.map +1 -1
  90. package/dist/convex/integrations/email-sync.d.ts +24 -2
  91. package/dist/convex/integrations/email-sync.d.ts.map +1 -1
  92. package/dist/convex/integrations/email-sync.js +54 -23
  93. package/dist/convex/integrations/email-sync.js.map +1 -1
  94. package/dist/convex/integrations/inbound.d.ts +16 -7
  95. package/dist/convex/integrations/inbound.d.ts.map +1 -1
  96. package/dist/convex/integrations/inbound.js +21 -10
  97. package/dist/convex/integrations/inbound.js.map +1 -1
  98. package/dist/convex/integrations/launch.d.ts +17 -1
  99. package/dist/convex/integrations/launch.d.ts.map +1 -1
  100. package/dist/convex/integrations/launch.js +32 -3
  101. package/dist/convex/integrations/launch.js.map +1 -1
  102. package/dist/convex/integrations/referrals.d.ts +20 -0
  103. package/dist/convex/integrations/referrals.d.ts.map +1 -1
  104. package/dist/convex/integrations/referrals.js +14 -9
  105. package/dist/convex/integrations/referrals.js.map +1 -1
  106. package/dist/convex/integrations/storage.d.ts +67 -0
  107. package/dist/convex/integrations/storage.d.ts.map +1 -1
  108. package/dist/convex/integrations/storage.js +42 -1
  109. package/dist/convex/integrations/storage.js.map +1 -1
  110. package/dist/convex/label-groups/admin.d.ts +3 -0
  111. package/dist/convex/label-groups/admin.d.ts.map +1 -1
  112. package/dist/convex/label-groups/admin.js +3 -0
  113. package/dist/convex/label-groups/admin.js.map +1 -1
  114. package/dist/convex/label-groups/audit.d.ts +1 -0
  115. package/dist/convex/label-groups/audit.d.ts.map +1 -1
  116. package/dist/convex/label-groups/audit.js +1 -0
  117. package/dist/convex/label-groups/audit.js.map +1 -1
  118. package/dist/convex/label-groups/auth.d.ts +7 -0
  119. package/dist/convex/label-groups/auth.d.ts.map +1 -1
  120. package/dist/convex/label-groups/auth.js +7 -0
  121. package/dist/convex/label-groups/auth.js.map +1 -1
  122. package/dist/convex/label-groups/errors.d.ts +9 -0
  123. package/dist/convex/label-groups/errors.d.ts.map +1 -1
  124. package/dist/convex/label-groups/errors.js +12 -0
  125. package/dist/convex/label-groups/errors.js.map +1 -1
  126. package/dist/convex/label-groups/gift.d.ts +24 -0
  127. package/dist/convex/label-groups/gift.d.ts.map +1 -1
  128. package/dist/convex/label-groups/gift.js +27 -0
  129. package/dist/convex/label-groups/gift.js.map +1 -1
  130. package/dist/convex/label-groups/legal.d.ts +1 -1
  131. package/dist/convex/label-groups/pricing.d.ts +15 -0
  132. package/dist/convex/label-groups/pricing.d.ts.map +1 -1
  133. package/dist/convex/label-groups/pricing.js +20 -0
  134. package/dist/convex/label-groups/pricing.js.map +1 -1
  135. package/dist/convex/label-groups/referral.d.ts +4 -0
  136. package/dist/convex/label-groups/referral.d.ts.map +1 -1
  137. package/dist/convex/label-groups/referral.js +4 -0
  138. package/dist/convex/label-groups/referral.js.map +1 -1
  139. package/dist/convex/label-groups/settings.d.ts +34 -0
  140. package/dist/convex/label-groups/settings.d.ts.map +1 -1
  141. package/dist/convex/label-groups/settings.js +39 -0
  142. package/dist/convex/label-groups/settings.js.map +1 -1
  143. package/dist/convex/label-groups/waitlist.d.ts +5 -0
  144. package/dist/convex/label-groups/waitlist.d.ts.map +1 -1
  145. package/dist/convex/label-groups/waitlist.js +7 -2
  146. package/dist/convex/label-groups/waitlist.js.map +1 -1
  147. package/dist/convex/labels.d.ts +103 -1
  148. package/dist/convex/labels.d.ts.map +1 -1
  149. package/dist/convex/legal.d.ts +18 -1
  150. package/dist/convex/legal.d.ts.map +1 -1
  151. package/dist/convex/legal.js +17 -2
  152. package/dist/convex/legal.js.map +1 -1
  153. package/dist/convex/log.js +8 -0
  154. package/dist/convex/log.js.map +1 -1
  155. package/dist/convex/money.d.ts +10 -0
  156. package/dist/convex/money.d.ts.map +1 -0
  157. package/dist/convex/money.js +37 -0
  158. package/dist/convex/money.js.map +1 -0
  159. package/dist/convex/report-rules.d.ts +6 -0
  160. package/dist/convex/report-rules.d.ts.map +1 -1
  161. package/dist/convex/report-rules.js +15 -0
  162. package/dist/convex/report-rules.js.map +1 -1
  163. package/dist/convex/test-billing.d.ts +83 -0
  164. package/dist/convex/test-billing.d.ts.map +1 -0
  165. package/dist/convex/test-billing.js +131 -0
  166. package/dist/convex/test-billing.js.map +1 -0
  167. package/dist/convex/test-models.d.ts +14 -2
  168. package/dist/convex/test-models.d.ts.map +1 -1
  169. package/dist/convex/test-models.js +61 -4
  170. package/dist/convex/test-models.js.map +1 -1
  171. package/dist/devtools-client/index.html +1 -1
  172. package/dist/eslint.d.mts +2 -1
  173. package/dist/eslint.mjs +2 -1
  174. package/dist/module.d.ts +45 -2
  175. package/dist/module.js +2 -2
  176. package/dist/module.json +1 -1
  177. package/dist/runtime/chunk-recovery.d.ts +13 -0
  178. package/dist/runtime/chunk-recovery.js +1 -0
  179. package/dist/runtime/locales/de.json +113 -7
  180. package/dist/runtime/locales/en.json +114 -8
  181. package/dist/runtime/locales/es.json +113 -7
  182. package/dist/runtime/locales/fr.json +113 -7
  183. package/dist/runtime/locales/ru.json +113 -7
  184. package/dist/runtime/server/chunk-recovery.d.ts +49 -0
  185. package/dist/runtime/server/chunk-recovery.js +44 -0
  186. package/dist/runtime/server/csp.d.ts +7 -2
  187. package/dist/runtime/server/csp.js +2 -2
  188. package/dist/runtime/server/photo-decoder-csp.d.ts +17 -0
  189. package/dist/runtime/server/photo-decoder-csp.js +9 -0
  190. package/dist/runtime/vue/components/account/AccountDeletion.css +1 -1
  191. package/dist/runtime/vue/components/account/ActivationChecklist.css +1 -1
  192. package/dist/runtime/vue/components/account/ConsentPrompt.css +1 -1
  193. package/dist/runtime/vue/components/account/EmailUnsubscribe.css +1 -1
  194. package/dist/runtime/vue/components/account/HowDidYouHear.css +1 -1
  195. package/dist/runtime/vue/components/account/KeepAccount.css +1 -1
  196. package/dist/runtime/vue/components/account/OnboardingFlow.css +1 -1
  197. package/dist/runtime/vue/components/account/ProfileIdentity.css +1 -1
  198. package/dist/runtime/vue/components/account/ProfilePreferencesSection.css +1 -1
  199. package/dist/runtime/vue/components/account/ProfileSettings.css +1 -1
  200. package/dist/runtime/vue/components/account/SecurityAlerts.css +1 -1
  201. package/dist/runtime/vue/components/account/SecurityPasskeys.css +1 -1
  202. package/dist/runtime/vue/components/account/SecuritySessions.css +1 -1
  203. package/dist/runtime/vue/components/account/SecuritySettings.css +1 -1
  204. package/dist/runtime/vue/components/admin/AdminAccess.css +1 -1
  205. package/dist/runtime/vue/components/admin/AdminAnnouncements.css +1 -1
  206. package/dist/runtime/vue/components/admin/AdminBilling.css +1 -1
  207. package/dist/runtime/vue/components/admin/AdminChart.css +1 -1
  208. package/dist/runtime/vue/components/admin/AdminConsole.css +1 -1
  209. package/dist/runtime/vue/components/admin/AdminExperiments.css +1 -1
  210. package/dist/runtime/vue/components/admin/AdminFlags.css +1 -1
  211. package/dist/runtime/vue/components/admin/AdminQueue.css +1 -1
  212. package/dist/runtime/vue/components/admin/AdminQueueJob.vue +5 -2
  213. package/dist/runtime/vue/components/admin/AdminReferrals.css +1 -1
  214. package/dist/runtime/vue/components/admin/AdminReports.css +1 -1
  215. package/dist/runtime/vue/components/admin/AdminRevenue.css +1 -1
  216. package/dist/runtime/vue/components/admin/AdminUsers.d.vue.ts +3 -0
  217. package/dist/runtime/vue/components/admin/AdminUsers.vue.d.ts +3 -0
  218. package/dist/runtime/vue/components/admin/AdminWorkspaces.d.vue.ts +3 -0
  219. package/dist/runtime/vue/components/admin/AdminWorkspaces.vue.d.ts +3 -0
  220. package/dist/runtime/vue/components/admin/admin-access-tab.js +2 -1
  221. package/dist/runtime/vue/components/admin/admin-revenue-tab.js +4 -1
  222. package/dist/runtime/vue/components/admin/admin.css +1 -1
  223. package/dist/runtime/vue/components/auth/AuthForm.css +1 -1
  224. package/dist/runtime/vue/components/auth/AuthForm.d.vue.ts +7 -0
  225. package/dist/runtime/vue/components/auth/AuthForm.vue +1 -2
  226. package/dist/runtime/vue/components/auth/AuthForm.vue.d.ts +7 -0
  227. package/dist/runtime/vue/components/auth/AuthFormChoose.css +1 -1
  228. package/dist/runtime/vue/components/auth/AuthFormHeader.css +1 -1
  229. package/dist/runtime/vue/components/auth/AuthFormPasskeyOffer.css +1 -1
  230. package/dist/runtime/vue/components/auth/InviteRedeem.css +1 -1
  231. package/dist/runtime/vue/components/auth/InviteRedeem.vue +95 -8
  232. package/dist/runtime/vue/components/auth/ReauthenticateCode.css +1 -1
  233. package/dist/runtime/vue/components/auth/ReauthenticateDialog.css +1 -1
  234. package/dist/runtime/vue/components/auth/ReauthenticatePasskey.css +1 -1
  235. package/dist/runtime/vue/components/auth/WaitlistForm.css +1 -1
  236. package/dist/runtime/vue/components/auth/WaitlistForm.d.vue.ts +5 -0
  237. package/dist/runtime/vue/components/auth/WaitlistForm.vue +3 -5
  238. package/dist/runtime/vue/components/auth/WaitlistForm.vue.d.ts +5 -0
  239. package/dist/runtime/vue/components/auth/WaitlistPlace.css +1 -1
  240. package/dist/runtime/vue/components/auth/WaitlistShare.css +1 -1
  241. package/dist/runtime/vue/components/auth/WaitlistShare.vue +1 -7
  242. package/dist/runtime/vue/components/auth/WaitlistStatus.css +1 -1
  243. package/dist/runtime/vue/components/auth/WaitlistStatus.vue +120 -23
  244. package/dist/runtime/vue/components/auth/auth-form.d.ts +1 -1
  245. package/dist/runtime/vue/components/auth/waitlist-form.js +1 -1
  246. package/dist/runtime/vue/components/billing/BillingHistory.css +1 -1
  247. package/dist/runtime/vue/components/billing/BillingHistoryOrder.css +1 -1
  248. package/dist/runtime/vue/components/billing/CancelConfirmGroup.vue +2 -7
  249. package/dist/runtime/vue/components/billing/CancelFlow.css +1 -1
  250. package/dist/runtime/vue/components/billing/GiftForm.css +1 -0
  251. package/dist/runtime/vue/components/billing/GiftForm.d.vue.ts +105 -0
  252. package/dist/runtime/vue/components/billing/GiftForm.vue +228 -0
  253. package/dist/runtime/vue/components/billing/GiftForm.vue.d.ts +105 -0
  254. package/dist/runtime/vue/components/billing/GiftList.css +1 -1
  255. package/dist/runtime/vue/components/billing/GiftList.d.vue.ts +87 -2
  256. package/dist/runtime/vue/components/billing/GiftList.vue +7 -4
  257. package/dist/runtime/vue/components/billing/GiftList.vue.d.ts +87 -2
  258. package/dist/runtime/vue/components/billing/GiftReceived.vue +11 -3
  259. package/dist/runtime/vue/components/billing/PlanChangeConfirmGroup.d.vue.ts +7 -0
  260. package/dist/runtime/vue/components/billing/PlanChangeConfirmGroup.vue +50 -0
  261. package/dist/runtime/vue/components/billing/PlanChangeConfirmGroup.vue.d.ts +7 -0
  262. package/dist/runtime/vue/components/billing/PricingChangeConfirm.d.vue.ts +4 -0
  263. package/dist/runtime/vue/components/billing/PricingChangeConfirm.vue +17 -0
  264. package/dist/runtime/vue/components/billing/PricingChangeConfirm.vue.d.ts +4 -0
  265. package/dist/runtime/vue/components/billing/PricingPackCard.css +1 -1
  266. package/dist/runtime/vue/components/billing/PricingPlanCard.css +1 -1
  267. package/dist/runtime/vue/components/billing/PricingPlanCard.vue +15 -0
  268. package/dist/runtime/vue/components/billing/PricingTable.css +1 -1
  269. package/dist/runtime/vue/components/billing/PricingTable.d.vue.ts +24 -2
  270. package/dist/runtime/vue/components/billing/PricingTable.vue +84 -17
  271. package/dist/runtime/vue/components/billing/PricingTable.vue.d.ts +24 -2
  272. package/dist/runtime/vue/components/billing/ReferralCard.css +1 -1
  273. package/dist/runtime/vue/components/billing/ReferralCard.d.vue.ts +4 -0
  274. package/dist/runtime/vue/components/billing/ReferralCard.vue.d.ts +4 -0
  275. package/dist/runtime/vue/components/billing/ReferralLanding.css +1 -1
  276. package/dist/runtime/vue/components/billing/ReferralLanding.vue +44 -2
  277. package/dist/runtime/vue/components/billing/UpgradePrompt.css +1 -1
  278. package/dist/runtime/vue/components/billing/UsageHistory.css +1 -1
  279. package/dist/runtime/vue/components/billing/WithdrawalButton.css +1 -1
  280. package/dist/runtime/vue/components/billing/cancel-flow.js +2 -1
  281. package/dist/runtime/vue/components/billing/pricing-table.d.ts +10 -0
  282. package/dist/runtime/vue/components/billing/withdrawal-button.d.ts +3 -2
  283. package/dist/runtime/vue/components/billing/withdrawal-button.js +13 -33
  284. package/dist/runtime/vue/components/shared.css +1 -1
  285. package/dist/runtime/vue/components/shell/AccessDenied.css +1 -1
  286. package/dist/runtime/vue/components/shell/AiLabel.css +1 -1
  287. package/dist/runtime/vue/components/shell/AppShell.css +1 -1
  288. package/dist/runtime/vue/components/shell/ConfirmDialog.css +1 -1
  289. package/dist/runtime/vue/components/shell/ConnectionStatus.css +1 -1
  290. package/dist/runtime/vue/components/shell/ContactForm.css +1 -1
  291. package/dist/runtime/vue/components/shell/Gate.css +1 -1
  292. package/dist/runtime/vue/components/shell/LegalDocument.css +1 -1
  293. package/dist/runtime/vue/components/shell/NoticeAnnouncement.css +1 -1
  294. package/dist/runtime/vue/components/shell/NoticeDeletion.css +1 -1
  295. package/dist/runtime/vue/components/shell/NoticeGift.css +1 -1
  296. package/dist/runtime/vue/components/shell/NoticeImpersonation.css +1 -1
  297. package/dist/runtime/vue/components/shell/NoticeLowCredits.css +1 -1
  298. package/dist/runtime/vue/components/shell/NoticeMaintenance.css +1 -1
  299. package/dist/runtime/vue/components/shell/NoticePastDue.css +1 -1
  300. package/dist/runtime/vue/components/shell/NotificationInbox.css +1 -1
  301. package/dist/runtime/vue/components/shell/ReportAppeal.vue +16 -13
  302. package/dist/runtime/vue/components/shell/ReportNotice.css +1 -1
  303. package/dist/runtime/vue/components/shell/UploadField.css +1 -1
  304. package/dist/runtime/vue/components/shell/WorkspaceSwitcher.css +1 -1
  305. package/dist/runtime/vue/components/shell/report-form.js +1 -44
  306. package/dist/runtime/vue/components/tokens.css +1 -1
  307. package/dist/runtime/vue/components/workspaces/AuditLog.css +1 -1
  308. package/dist/runtime/vue/components/workspaces/AuditLog.d.vue.ts +1 -0
  309. package/dist/runtime/vue/components/workspaces/AuditLog.vue.d.ts +1 -0
  310. package/dist/runtime/vue/components/workspaces/WorkspaceBilling.css +1 -1
  311. package/dist/runtime/vue/components/workspaces/WorkspaceBilling.vue +29 -50
  312. package/dist/runtime/vue/components/workspaces/WorkspaceBillingPause.d.vue.ts +3 -0
  313. package/dist/runtime/vue/components/workspaces/WorkspaceBillingPause.vue +69 -0
  314. package/dist/runtime/vue/components/workspaces/WorkspaceBillingPause.vue.d.ts +3 -0
  315. package/dist/runtime/vue/components/workspaces/WorkspaceBillingSwitch.d.vue.ts +3 -0
  316. package/dist/runtime/vue/components/workspaces/WorkspaceBillingSwitch.vue +54 -0
  317. package/dist/runtime/vue/components/workspaces/WorkspaceBillingSwitch.vue.d.ts +3 -0
  318. package/dist/runtime/vue/components/workspaces/WorkspaceCredits.css +1 -1
  319. package/dist/runtime/vue/components/workspaces/WorkspaceList.css +1 -1
  320. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.d.vue.ts +38 -0
  321. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.vue +32 -1
  322. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.vue.d.ts +38 -0
  323. package/dist/runtime/vue/components/workspaces/workspace-billing.d.ts +39 -2
  324. package/dist/runtime/vue/components/workspaces/workspace-billing.js +94 -2
  325. package/dist/runtime/vue/components/workspaces/workspace-settings.d.ts +4 -0
  326. package/dist/runtime/vue/composables/billing-format.d.ts +9 -4
  327. package/dist/runtime/vue/composables/billing-format.js +17 -9
  328. package/dist/runtime/vue/composables/billing-provider.js +3 -2
  329. package/dist/runtime/vue/composables/prepare-photo.d.ts +75 -0
  330. package/dist/runtime/vue/composables/prepare-photo.js +223 -0
  331. package/dist/runtime/vue/composables/use-access.d.ts +23 -2
  332. package/dist/runtime/vue/composables/use-access.js +22 -3
  333. package/dist/runtime/vue/composables/use-billing.d.ts +76 -5
  334. package/dist/runtime/vue/composables/use-billing.js +48 -0
  335. package/dist/runtime/vue/composables/use-gift-form.d.ts +123 -0
  336. package/dist/runtime/vue/composables/use-gift-form.js +169 -0
  337. package/dist/runtime/vue/composables/use-gift-list.d.ts +44 -4
  338. package/dist/runtime/vue/composables/use-gift-list.js +11 -5
  339. package/dist/runtime/vue/composables/use-install-prompt.d.ts +71 -0
  340. package/dist/runtime/vue/composables/use-install-prompt.js +53 -0
  341. package/dist/runtime/vue/composables/use-labels.js +17 -23
  342. package/dist/runtime/vue/composables/use-login-flow.d.ts +9 -0
  343. package/dist/runtime/vue/composables/use-login-flow.js +7 -0
  344. package/dist/runtime/vue/composables/use-orders.d.ts +1 -1
  345. package/dist/runtime/vue/composables/use-pricing.d.ts +54 -5
  346. package/dist/runtime/vue/composables/use-pricing.js +37 -10
  347. package/dist/runtime/vue/composables/use-push-subscription.js +1 -7
  348. package/dist/runtime/vue/composables/use-referral-invite.d.ts +17 -2
  349. package/dist/runtime/vue/composables/use-referral-invite.js +10 -1
  350. package/dist/runtime/vue/composables/use-referrals.js +2 -1
  351. package/dist/runtime/vue/composables/use-report-appeal.d.ts +86 -0
  352. package/dist/runtime/vue/composables/use-report-appeal.js +61 -0
  353. package/dist/runtime/vue/composables/use-return-path.d.ts +5 -4
  354. package/dist/runtime/vue/composables/use-return-path.js +16 -2
  355. package/dist/runtime/vue/composables/use-waitlist.d.ts +13 -1
  356. package/dist/runtime/vue/composables/use-waitlist.js +15 -4
  357. package/dist/runtime/vue/composables/use-withdrawal.d.ts +63 -0
  358. package/dist/runtime/vue/composables/use-withdrawal.js +38 -0
  359. package/dist/runtime/vue/middleware/page-access.js +2 -2
  360. package/dist/runtime/vue/pages/gifts.vue +2 -0
  361. package/dist/runtime/vue/pages/login.vue +5 -7
  362. package/dist/runtime/vue/pages/report.vue +2 -3
  363. package/dist/runtime/vue/parts.d.ts +5 -0
  364. package/dist/runtime/vue/plugins/chunk-recovery.client.d.ts +10 -0
  365. package/dist/runtime/vue/plugins/chunk-recovery.client.js +10 -0
  366. package/dist/runtime/vue/plugins/install-banner.client.d.ts +7 -0
  367. package/dist/runtime/vue/plugins/install-banner.client.js +5 -0
  368. package/dist/runtime/vue/plugins/install-prompt.client.d.ts +7 -0
  369. package/dist/runtime/vue/plugins/install-prompt.client.js +6 -0
  370. package/dist/runtime/vue/plugins/session-ended.js +2 -3
  371. package/dist/runtime/vue/utils/active-locale.js +8 -0
  372. package/dist/runtime/vue/utils/confirm-group.d.ts +18 -0
  373. package/dist/runtime/vue/utils/confirm-group.js +17 -0
  374. package/dist/runtime/vue/utils/display-mode.d.ts +8 -0
  375. package/dist/runtime/vue/utils/display-mode.js +11 -0
  376. package/dist/runtime/vue/utils/heic-absent.d.ts +2 -0
  377. package/dist/runtime/vue/utils/heic-absent.js +3 -0
  378. package/dist/runtime/vue/utils/intl.d.ts +12 -4
  379. package/dist/runtime/vue/utils/intl.js +13 -2
  380. package/dist/runtime/vue/utils/kept-invite.js +6 -29
  381. package/dist/runtime/vue/utils/page-origin.d.ts +15 -0
  382. package/dist/runtime/vue/utils/page-origin.js +8 -0
  383. package/dist/runtime/vue/utils/page-rules.d.ts +9 -0
  384. package/dist/runtime/vue/utils/page-rules.js +3 -0
  385. package/dist/runtime/vue/utils/plan-change-confirm.d.ts +76 -0
  386. package/dist/runtime/vue/utils/plan-change-confirm.js +39 -0
  387. package/dist/runtime/vue/utils/pricing-bindings.d.ts +7 -1
  388. package/dist/runtime/vue/utils/pricing-bindings.js +21 -0
  389. package/dist/runtime/vue/utils/pricing-seo.js +4 -2
  390. package/dist/runtime/vue/utils/tab-keep.d.ts +17 -0
  391. package/dist/runtime/vue/utils/tab-keep.js +46 -0
  392. package/dist/shared/{nuxt-backend.Bq_mhlky.mjs → nuxt-backend.9IVxzzft.mjs} +55 -10
  393. package/dist/shared/{nuxt-backend.DmZI-QSO.mjs → nuxt-backend.BCjeoX0x.mjs} +2 -26
  394. package/dist/shared/{nuxt-backend.D9qXcOOI.mjs → nuxt-backend.Baxb382E.mjs} +1 -1
  395. package/dist/shared/{nuxt-backend.Lk2MQI2u.mjs → nuxt-backend.BjQoqNIu.mjs} +26 -2
  396. package/dist/shared/{nuxt-backend.G4JryO1q.mjs → nuxt-backend.CbR37s_c.mjs} +255 -49
  397. package/package.json +6 -1
  398. package/skills/nuxt-backend/references/api.md +26 -10
  399. package/skills/nuxt-backend/references/renames.json +104 -0
  400. package/skills/nuxt-backend/references/surface.json +30 -2
  401. package/skills/nuxt-backend-ai/references/api.md +2 -1
  402. package/skills/nuxt-backend-auth/references/api.md +1 -1
  403. package/skills/nuxt-backend-billing/references/api.md +2 -0
  404. package/skills/nuxt-backend-data/references/api.md +4 -1
  405. package/skills/nuxt-backend-email/SKILL.md +5 -2
  406. package/skills/nuxt-backend-email/references/api.md +1 -0
  407. package/skills/nuxt-backend-growth/references/api.md +4 -0
  408. package/skills/nuxt-backend-ship/SKILL.md +1 -1
  409. package/skills/nuxt-backend-ship/references/api.md +9 -5
  410. package/skills/nuxt-backend-ui/SKILL.md +10 -5
  411. package/skills/nuxt-backend-upgrade/SKILL.md +4 -3
  412. package/skills/nuxt-backend-upgrade/references/upgrade.md +43 -0
  413. package/src/convex/catalog.ts +17 -0
  414. package/src/convex/components/backend/_generated/component.ts +30 -2
  415. package/src/convex/components/backend/billing.ts +19 -5
  416. package/src/convex/components/backend/jobs.ts +102 -5
  417. package/src/convex/components/backend/schema.ts +11 -0
  418. package/src/convex/delivery.ts +26 -1
  419. package/src/convex/emails/renewal-reminder.ts +19 -1
  420. package/src/convex/errors.ts +23 -9
  421. package/src/convex/events.ts +7 -0
  422. package/src/convex/integrations/ai/images.ts +22 -8
  423. package/src/convex/integrations/ai/job-errors.ts +64 -9
  424. package/src/convex/integrations/ai/jobs.ts +509 -64
  425. package/src/convex/integrations/ai/models.ts +1 -1
  426. package/src/convex/integrations/ai/moderation.ts +10 -5
  427. package/src/convex/integrations/ai.ts +6 -1
  428. package/src/convex/integrations/billing/context.ts +6 -3
  429. package/src/convex/integrations/billing/credits.ts +4 -1
  430. package/src/convex/integrations/billing/passes.ts +3 -11
  431. package/src/convex/integrations/billing/provider-failure.ts +56 -0
  432. package/src/convex/integrations/billing/types/setup.ts +1 -1
  433. package/src/convex/integrations/billing/types/surface.ts +9 -2
  434. package/src/convex/integrations/email-sync.ts +74 -26
  435. package/src/convex/integrations/inbound.ts +32 -16
  436. package/src/convex/integrations/launch.ts +52 -5
  437. package/src/convex/integrations/referrals.ts +25 -7
  438. package/src/convex/integrations/storage.ts +107 -1
  439. package/src/convex/label-groups/admin.ts +3 -0
  440. package/src/convex/label-groups/audit.ts +1 -0
  441. package/src/convex/label-groups/auth.ts +7 -0
  442. package/src/convex/label-groups/errors.ts +12 -0
  443. package/src/convex/label-groups/gift.ts +27 -0
  444. package/src/convex/label-groups/pricing.ts +20 -0
  445. package/src/convex/label-groups/referral.ts +4 -0
  446. package/src/convex/label-groups/settings.ts +39 -0
  447. package/src/convex/label-groups/waitlist.ts +7 -2
  448. package/src/convex/legal.ts +23 -2
  449. package/src/convex/log.ts +8 -0
  450. package/src/convex/money.ts +40 -0
  451. package/src/convex/report-rules.ts +16 -0
  452. package/src/convex/test-billing.ts +189 -0
  453. package/src/convex/test-models.ts +59 -4
  454. package/src/convex/test.ts +95 -8
  455. package/src/runtime/vue/components/account/AccountDeletion.css +1 -1
  456. package/src/runtime/vue/components/account/ActivationChecklist.css +5 -3
  457. package/src/runtime/vue/components/account/ConsentPrompt.css +7 -5
  458. package/src/runtime/vue/components/account/EmailUnsubscribe.css +8 -4
  459. package/src/runtime/vue/components/account/HowDidYouHear.css +9 -5
  460. package/src/runtime/vue/components/account/KeepAccount.css +4 -2
  461. package/src/runtime/vue/components/account/OnboardingFlow.css +6 -4
  462. package/src/runtime/vue/components/account/ProfileIdentity.css +1 -1
  463. package/src/runtime/vue/components/account/ProfilePreferencesSection.css +4 -2
  464. package/src/runtime/vue/components/account/ProfileSettings.css +4 -2
  465. package/src/runtime/vue/components/account/SecurityAlerts.css +1 -1
  466. package/src/runtime/vue/components/account/SecurityPasskeys.css +3 -3
  467. package/src/runtime/vue/components/account/SecuritySessions.css +1 -1
  468. package/src/runtime/vue/components/account/SecuritySettings.css +1 -1
  469. package/src/runtime/vue/components/admin/AdminAccess.css +1 -1
  470. package/src/runtime/vue/components/admin/AdminAnnouncements.css +2 -2
  471. package/src/runtime/vue/components/admin/AdminBilling.css +1 -1
  472. package/src/runtime/vue/components/admin/AdminChart.css +1 -1
  473. package/src/runtime/vue/components/admin/AdminConsole.css +1 -0
  474. package/src/runtime/vue/components/admin/AdminExperiments.css +1 -1
  475. package/src/runtime/vue/components/admin/AdminFlags.css +2 -2
  476. package/src/runtime/vue/components/admin/AdminQueue.css +5 -3
  477. package/src/runtime/vue/components/admin/AdminQueueJob.vue +6 -2
  478. package/src/runtime/vue/components/admin/AdminReferrals.css +4 -2
  479. package/src/runtime/vue/components/admin/AdminReports.css +1 -1
  480. package/src/runtime/vue/components/admin/AdminRevenue.css +1 -1
  481. package/src/runtime/vue/components/admin/admin.css +3 -3
  482. package/src/runtime/vue/components/auth/AuthForm.css +7 -4
  483. package/src/runtime/vue/components/auth/AuthForm.vue +1 -2
  484. package/src/runtime/vue/components/auth/AuthFormChoose.css +2 -1
  485. package/src/runtime/vue/components/auth/AuthFormHeader.css +1 -1
  486. package/src/runtime/vue/components/auth/AuthFormPasskeyOffer.css +1 -1
  487. package/src/runtime/vue/components/auth/InviteRedeem.css +56 -2
  488. package/src/runtime/vue/components/auth/InviteRedeem.vue +110 -9
  489. package/src/runtime/vue/components/auth/ReauthenticateCode.css +1 -1
  490. package/src/runtime/vue/components/auth/ReauthenticateDialog.css +6 -3
  491. package/src/runtime/vue/components/auth/ReauthenticatePasskey.css +1 -1
  492. package/src/runtime/vue/components/auth/WaitlistForm.css +4 -2
  493. package/src/runtime/vue/components/auth/WaitlistForm.vue +5 -6
  494. package/src/runtime/vue/components/auth/WaitlistPlace.css +4 -2
  495. package/src/runtime/vue/components/auth/WaitlistShare.css +6 -4
  496. package/src/runtime/vue/components/auth/WaitlistShare.vue +2 -8
  497. package/src/runtime/vue/components/auth/WaitlistStatus.css +27 -1
  498. package/src/runtime/vue/components/auth/WaitlistStatus.vue +153 -31
  499. package/src/runtime/vue/components/billing/BillingHistory.css +2 -2
  500. package/src/runtime/vue/components/billing/BillingHistoryOrder.css +1 -1
  501. package/src/runtime/vue/components/billing/CancelConfirmGroup.vue +2 -8
  502. package/src/runtime/vue/components/billing/CancelFlow.css +6 -4
  503. package/src/runtime/vue/components/billing/GiftForm.css +89 -0
  504. package/src/runtime/vue/components/billing/GiftForm.vue +251 -0
  505. package/src/runtime/vue/components/billing/GiftList.css +5 -3
  506. package/src/runtime/vue/components/billing/GiftList.vue +21 -9
  507. package/src/runtime/vue/components/billing/GiftReceived.vue +11 -3
  508. package/src/runtime/vue/components/billing/PlanChangeConfirmGroup.vue +59 -0
  509. package/src/runtime/vue/components/billing/PricingChangeConfirm.vue +22 -0
  510. package/src/runtime/vue/components/billing/PricingPackCard.css +1 -1
  511. package/src/runtime/vue/components/billing/PricingPlanCard.css +31 -4
  512. package/src/runtime/vue/components/billing/PricingPlanCard.vue +17 -2
  513. package/src/runtime/vue/components/billing/PricingTable.css +2 -2
  514. package/src/runtime/vue/components/billing/PricingTable.vue +141 -28
  515. package/src/runtime/vue/components/billing/ReferralCard.css +6 -4
  516. package/src/runtime/vue/components/billing/ReferralLanding.css +14 -3
  517. package/src/runtime/vue/components/billing/ReferralLanding.vue +54 -3
  518. package/src/runtime/vue/components/billing/UpgradePrompt.css +6 -4
  519. package/src/runtime/vue/components/billing/UsageHistory.css +2 -2
  520. package/src/runtime/vue/components/billing/WithdrawalButton.css +5 -3
  521. package/src/runtime/vue/components/shared.css +62 -9
  522. package/src/runtime/vue/components/shell/AccessDenied.css +5 -3
  523. package/src/runtime/vue/components/shell/AiLabel.css +2 -2
  524. package/src/runtime/vue/components/shell/AppShell.css +5 -3
  525. package/src/runtime/vue/components/shell/ConfirmDialog.css +5 -3
  526. package/src/runtime/vue/components/shell/ConnectionStatus.css +1 -1
  527. package/src/runtime/vue/components/shell/ContactForm.css +4 -2
  528. package/src/runtime/vue/components/shell/Gate.css +5 -3
  529. package/src/runtime/vue/components/shell/LegalDocument.css +1 -1
  530. package/src/runtime/vue/components/shell/NoticeAnnouncement.css +1 -1
  531. package/src/runtime/vue/components/shell/NoticeDeletion.css +5 -3
  532. package/src/runtime/vue/components/shell/NoticeGift.css +1 -1
  533. package/src/runtime/vue/components/shell/NoticeImpersonation.css +1 -1
  534. package/src/runtime/vue/components/shell/NoticeLowCredits.css +6 -3
  535. package/src/runtime/vue/components/shell/NoticeMaintenance.css +1 -1
  536. package/src/runtime/vue/components/shell/NoticePastDue.css +5 -3
  537. package/src/runtime/vue/components/shell/NotificationInbox.css +6 -4
  538. package/src/runtime/vue/components/shell/ReportAppeal.vue +17 -14
  539. package/src/runtime/vue/components/shell/ReportNotice.css +1 -1
  540. package/src/runtime/vue/components/shell/UploadField.css +5 -3
  541. package/src/runtime/vue/components/shell/WorkspaceSwitcher.css +5 -3
  542. package/src/runtime/vue/components/tokens.css +30 -0
  543. package/src/runtime/vue/components/workspaces/AuditLog.css +2 -2
  544. package/src/runtime/vue/components/workspaces/WorkspaceBilling.css +75 -2
  545. package/src/runtime/vue/components/workspaces/WorkspaceBilling.vue +45 -53
  546. package/src/runtime/vue/components/workspaces/WorkspaceBillingPause.vue +79 -0
  547. package/src/runtime/vue/components/workspaces/WorkspaceBillingSwitch.vue +63 -0
  548. package/src/runtime/vue/components/workspaces/WorkspaceCredits.css +1 -0
  549. package/src/runtime/vue/components/workspaces/WorkspaceList.css +2 -2
  550. package/src/runtime/vue/components/workspaces/WorkspaceSettings.vue +47 -4
  551. package/src/runtime/vue/pages/gifts.vue +12 -7
  552. package/src/runtime/vue/pages/invite.vue +4 -2
  553. package/src/runtime/vue/pages/login.vue +8 -8
  554. package/src/runtime/vue/pages/report.vue +2 -3
  555. package/src/runtime/vue/pages/waitlist.vue +8 -5
@@ -44,10 +44,11 @@ import { setupAudit } from '../audit.js'
44
44
  import type { CostReport, SpendReservation } from '../billing.js'
45
45
  import { BILLING_ACCESS, BILLING_METERS, BILLING_TO } from '../billing/context.js'
46
46
  import { requireCreditAmount } from '../billing/credits.js'
47
+ import { providerFailurePasses, providerRefusesForGood } from '../billing/provider-failure.js'
47
48
  import type { Ai, AiModel, MeteredModel } from './config.js'
48
49
  import { AI_CONTEXTS } from './context.js'
49
50
  import { usageOf } from './costs.js'
50
- import { catalogPayload, classifyStepError, failurePayload, isPassing, modelOutcomeOf } from './job-errors.js'
51
+ import { catalogPayload, classifyStepError, EMPTY_ATTEMPTS, failurePayload, isPassing, modelOutcomeOf } from './job-errors.js'
51
52
  import type { ModerationInput, ModerationSubject } from './moderation.js'
52
53
  import { type AiImageModel, meteredImageModel } from './images.js'
53
54
  import { settledAmount } from './metering.js'
@@ -76,8 +77,17 @@ const HOLD_MS = 7 * 24 * 60 * 60 * 1000
76
77
  /** How many times a failed job's refund is tried before it waits for an administrator: about four hours of tries. */
77
78
  const REFUND_ATTEMPTS = 8
78
79
 
79
- /** The wait before a refund's next try: a minute, doubling, at most two hours. */
80
- const refundBackoff = (attempt: number): number => Math.min(2 ** attempt * 60_000, 2 * 60 * 60 * 1000)
80
+ /** How many times an owed charge is tried, the first in the job itself, before it is given up: about two hours of tries. */
81
+ const OWED_ATTEMPTS = 8
82
+
83
+ /** The wait before a refund's or an owed charge's next try: a minute, doubling, at most two hours. */
84
+ const billBackoff = (attempt: number): number => Math.min(2 ** attempt * 60_000, 2 * 60 * 60 * 1000)
85
+
86
+ /** How many times a hold or a charge waits for a balance or a customer billing has not synced yet before the job fails: about five minutes of waits. */
87
+ const BILL_WAITS = 6
88
+
89
+ /** The wait before such a hold or charge is tried again: five seconds, doubling. */
90
+ const billWait = (attempt: number): number => 5000 * 2 ** attempt
81
91
 
82
92
  /** How many times the claim at sign-up looks for the new account's workspace: about a minute of tries. */
83
93
  const CLAIM_ATTEMPTS = 7
@@ -150,6 +160,14 @@ export const vJobEnd = {
150
160
  charged: v.number(),
151
161
  /** Put in line `{ free: true }`: it held, charged and counted nothing. */
152
162
  free: v.boolean(),
163
+ /**
164
+ * The credits its charge still owes, for a kind charged by output whose
165
+ * `job.charge` the provider refused for now: the job is `done` (or
166
+ * canceled without a refund), its result stands, its hold stays taken and
167
+ * the queue tries the charge again in the background. `onOwedCharge`
168
+ * hears how that ends. Absent when nothing is owed.
169
+ */
170
+ owed: v.optional(v.number()),
153
171
  }
154
172
 
155
173
  /** A job's end as `onJobEnd` receives it ({@link vJobEnd}). */
@@ -163,6 +181,7 @@ export type JobEnd = {
163
181
  endedAt: number
164
182
  charged: number
165
183
  free: boolean
184
+ owed?: number
166
185
  }
167
186
 
168
187
  /**
@@ -171,6 +190,48 @@ export type JobEnd = {
171
190
  */
172
191
  export type OnJobEnd = FunctionReference<'mutation' | 'action', 'internal', JobEnd>
173
192
 
193
+ /**
194
+ * How an owed charge ended, as `onOwedCharge` receives it: use these as
195
+ * your function's `args` (`internalMutation({ args: vOwedCharge, handler })`).
196
+ */
197
+ export const vOwedCharge = {
198
+ /** The job's id, as `jobs.enqueue` returned it. */
199
+ jobId: v.string(),
200
+ /** Its `jobs.define` export, as `module:name`. */
201
+ kind: v.string(),
202
+ /** The args it was put in line with. */
203
+ args: v.any(),
204
+ /** Which run of the job charged it, as `vJobEnd` counts them. */
205
+ retries: v.number(),
206
+ /**
207
+ * `charged`: the provider took the charge at last, under the same
208
+ * idempotency key, so it is billed once. `given_up`: every try failed,
209
+ * or the provider refused it in a way no try changes (a revoked access
210
+ * token), so it was given up at once; the hold went back and the job
211
+ * stays uncharged, for an administrator's retry from the Queue tab
212
+ * (`retryJob`).
213
+ */
214
+ status: v.union(v.literal('charged'), v.literal('given_up')),
215
+ /** The credits it owed: what `job.charge` charged. */
216
+ credits: v.number(),
217
+ /** When it ended, in ms since the epoch. */
218
+ at: v.number(),
219
+ }
220
+
221
+ /** An owed charge's end as `onOwedCharge` receives it ({@link vOwedCharge}). */
222
+ export type OwedCharge = {
223
+ jobId: string
224
+ kind: string
225
+ args: unknown
226
+ retries: number
227
+ status: 'charged' | 'given_up'
228
+ credits: number
229
+ at: number
230
+ }
231
+
232
+ /** Your internal mutation, or action, that hears how an owed charge ended: taking `vOwedCharge` as its args. */
233
+ export type OnOwedCharge = FunctionReference<'mutation' | 'action', 'internal', OwedCharge>
234
+
174
235
  /** Where a model's limit starts, and the range it adapts within, in calls a minute. */
175
236
  export interface JobModelLimit {
176
237
  perMinute: number
@@ -220,6 +281,25 @@ export interface DefineJobQueueOptions {
220
281
  * - Idempotency: an administrator's retry runs a failed job again, and it ends again: compare `retries` with the run you last recorded, and let a later run's end win
221
282
  */
222
283
  onJobEnd?: OnJobEnd
284
+ /**
285
+ * Hear how a charge the queue owed ended: a kind charged by output whose
286
+ * `job.charge` the provider refused for a passing reason ends `done`
287
+ * with `owed` on its `onJobEnd`, and the queue tries the charge again
288
+ * in the background. This hears it `charged` once it lands, or
289
+ * `given_up` after its last try, or at once when the provider refuses it
290
+ * in a way no try changes (a revoked access token), with the job's id,
291
+ * kind, args, run and the credits it owed. Your internal mutation or action, by its
292
+ * reference, taking `vOwedCharge`: settle what your rows say about the
293
+ * charge. Never move credits here.
294
+ *
295
+ * @guarantee
296
+ * - Runs: as its own function, scheduled by the transaction that recorded how the charge ended, once it commits
297
+ * - Delivery: once per owed charge that ends, `charged` or `given_up`; an administrator's retry of a given-up charge owes it again, and it ends again
298
+ * - Order: after `onJobEnd` was scheduled for the run that owed it, unless the charge landed or was given up while the job still ran, when it may run first; owed charges of different jobs end in no set order
299
+ * - When it throws: the failure is the hook's own, in the deployment's logs; the charge's outcome stands
300
+ * - Idempotency: a retried charge that lands after it gave up is heard `charged` after `given_up`: let the later one win
301
+ */
302
+ onOwedCharge?: OnOwedCharge
223
303
  }
224
304
 
225
305
  /** How far a job got, as `job.progress` reports it. */
@@ -229,6 +309,21 @@ export interface JobProgress {
229
309
  label?: string
230
310
  }
231
311
 
312
+ /** What `job.charge` takes beside the credits. */
313
+ export interface JobChargeOptions {
314
+ /**
315
+ * More of your own string metadata for the usage event, such as the id
316
+ * of what the job made (`{ stripId }`): merged with the queue's
317
+ * `userId` and `job`, which win over keys of the same name. Within the
318
+ * billing provider's limits on a usage event: at most 47 keys (it takes
319
+ * 50, and the queue adds `userId`, `job` and the meter's amount), each of
320
+ * 1 to 40 ASCII characters, not starting with `_` (the provider's own
321
+ * keys, such as `_cost` and `_llm`) or `$`, and values of at most 500
322
+ * characters. `job.charge` throws a `TypeError` past them.
323
+ */
324
+ metadata?: Record<string, string>
325
+ }
326
+
232
327
  /** What a job's handler gets: its id, and the durable calls it orders. */
233
328
  export interface JobContext {
234
329
  /** The job's id. */
@@ -247,8 +342,19 @@ export interface JobContext {
247
342
  * hold goes back unbilled. Once: a later call changes nothing. A job that
248
343
  * fails after it is refunded what it was charged. Throws in a kind that
249
344
  * charges at start; does nothing in a job put in line `{ free: true }`.
345
+ *
346
+ * A balance short of the credits fails the job. A refusal that may pass
347
+ * (the provider down or rate limiting, no billing customer yet) leaves
348
+ * the charge owed: the job runs on and ends `done`, its hold stays
349
+ * taken, and the queue tries the charge again in the background
350
+ * (`onOwedCharge`). A billing provider that refuses the charge itself,
351
+ * such as a revoked access token, gives it up at once: the job runs on
352
+ * and ends `done` uncharged, its hold back, `onOwedCharge` hears
353
+ * `given_up`, and `ai.job_charge_refused` is logged. `metadata` goes on the usage event
354
+ * beside the queue's own, within the provider's limits
355
+ * ({@link JobChargeOptions.metadata}): past them, `job.charge` throws.
250
356
  */
251
- charge: (credits: number) => Promise<void>
357
+ charge: (credits: number, options?: JobChargeOptions) => Promise<void>
252
358
  }
253
359
 
254
360
  /**
@@ -318,8 +424,23 @@ export interface JobStepContext extends ImageStoreContext {
318
424
  * step, under the model's limit), and the step's `signal`.
319
425
  */
320
426
  callSettings: { maxRetries: 0, abortSignal: AbortSignal }
321
- /** The job it runs for, and which attempt this is. */
322
- job: { id: string, attempt: number }
427
+ /**
428
+ * The job it runs for, which attempt this is, and who it is for: its
429
+ * `owner`, the billing entity that pays (a workspace, an account under
430
+ * `billTo: 'user'`, `guest:<visitor>` or `app`), and `userId`, the
431
+ * account that started it, when somebody signed in did. `ai.moderate`
432
+ * and `ai.requireSafe` called in the step name them on a flag unless
433
+ * told otherwise.
434
+ */
435
+ job: StepJob
436
+ }
437
+
438
+ /** The job a step runs for, as `ctx.job` names it. */
439
+ export interface StepJob {
440
+ id: string
441
+ attempt: number
442
+ owner: string
443
+ userId?: string
323
444
  }
324
445
 
325
446
  /** The image model `ctx.image()` returns: an AI SDK image model. */
@@ -374,6 +495,20 @@ export interface JobView {
374
495
  charged: number
375
496
  /** Put in line `{ free: true }`: it holds, charges and counts nothing. */
376
497
  free: boolean
498
+ /**
499
+ * A charge it still owes, for a kind charged by output whose
500
+ * `job.charge` the provider refused: the credits, and whether the queue
501
+ * gave up trying (`givenUp`, after its last try or at once for a refusal
502
+ * no try changes) or still tries. `charged` reads
503
+ * `0` until it lands. Absent when nothing is owed.
504
+ */
505
+ owed?: JobOwed
506
+ }
507
+
508
+ /** A charge a job still owes ({@link JobView.owed}). */
509
+ export interface JobOwed {
510
+ credits: number
511
+ givenUp: boolean
377
512
  }
378
513
 
379
514
  /** A job as `jobs.get` reads it for your own functions: `getJob`'s view, with who owns it and its args. */
@@ -407,6 +542,8 @@ export interface AdminJobView {
407
542
  cost: number
408
543
  /** What `job.charge` charged, for a kind charged by output. */
409
544
  price?: number
545
+ /** A charge it still owes ({@link JobView.owed}): an administrator's retry tries a given-up one again. */
546
+ owed?: JobOwed
410
547
  joinedAt: number
411
548
  startedAt?: number
412
549
  endedAt?: number
@@ -436,7 +573,7 @@ export interface JobQueueApi {
436
573
  /** Internal: the pick, the stall sweep, a job's progress and each job's end. */
437
574
  runQueue: RegisteredMutation<'internal', Record<string, unknown>, Promise<null>>
438
575
  /** Internal: a job's charge, refund and cost report. */
439
- billJob: RegisteredAction<'internal', { op: 'charge' | 'hold' | 'refund' | 'report' | 'moderate', jobId: string, attempt?: number, amount?: number, input?: ModerationInput & Pick<ModerationSubject, 'subject' | 'stage'> }, Promise<null | { blocked: Record<string, unknown> }>>
576
+ billJob: RegisteredAction<'internal', { op: 'charge' | 'hold' | 'refund' | 'owed' | 'report' | 'moderate', jobId: string, attempt?: number, amount?: number, metadata?: Record<string, string>, input?: ModerationInput & Pick<ModerationSubject, 'subject' | 'stage'> }, Promise<null | { blocked: Record<string, unknown> } | { wait: number }>>
440
577
  }
441
578
 
442
579
  /** What `jobs.enqueue` takes beside the kind and its args. */
@@ -513,6 +650,9 @@ type JobRow = {
513
650
  price?: number
514
651
  refundOwed?: 'pending' | 'given_up'
515
652
  refundAt?: number
653
+ chargeOwed?: 'pending' | 'given_up'
654
+ chargeAt?: number
655
+ chargeMetadata?: Record<string, string>
516
656
  workflowId?: string
517
657
  attempts: number
518
658
  retries: number
@@ -635,12 +775,31 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
635
775
  const schedulePick = (ctx: { scheduler: Ctx['scheduler'] }) => ctx.scheduler.runAfter(0, RUN_QUEUE, { op: 'pick' })
636
776
  const scheduleRefund = (ctx: { scheduler: Ctx['scheduler'] }, jobId: string, attempt = 0, delay = 0) =>
637
777
  ctx.scheduler.runAfter(delay, BILL_JOB, { op: 'refund', jobId, ...(attempt > 0 ? { attempt } : {}) })
778
+ const scheduleOwed = (ctx: { scheduler: Ctx['scheduler'] }, jobId: string, attempt: number, delay: number) =>
779
+ ctx.scheduler.runAfter(delay, BILL_JOB, { op: 'owed', jobId, attempt })
638
780
 
639
781
  // ── Kinds and steps ─────────────────────────────────────────────────────
640
782
 
641
783
  /** How a charge's step is tried: three times, two seconds apart and doubling. */
642
784
  const BILL_RETRY = { maxAttempts: 3, initialBackoffMs: 2000, base: 2 }
643
785
 
786
+ /**
787
+ * Run a billing step of the job's workflow: one that waits for billing
788
+ * to sync (`{ wait }`) sleeps and is run again, its try counted; one
789
+ * that refuses the job (`{ blocked }`) fails it with that refusal.
790
+ */
791
+ const billStep = async (step: WorkflowCtx, args: { op: 'charge' | 'hold' | 'moderate', jobId: string, amount?: number, metadata?: Record<string, string>, input?: unknown }): Promise<void> => {
792
+ for (let attempt = 0; ; attempt++) {
793
+ const billed = await step.runAction(BILL_JOB, { ...args, ...(attempt > 0 ? { attempt } : {}) }, { retry: BILL_RETRY }) as BillOutcome | null
794
+ if (billed && 'wait' in billed) {
795
+ await step.sleep(billed.wait)
796
+ continue
797
+ }
798
+ if (billed?.blocked) throw new Error(`${CATALOG_MARK}${JSON.stringify(billed.blocked)}`)
799
+ return
800
+ }
801
+ }
802
+
644
803
  const jobContext = (step: WorkflowCtx, jobId: string, mode: 'start' | 'output'): JobContext => ({
645
804
  id: jobId,
646
805
  run: (async (stepRef: FunctionReference<'action', 'internal'>, args: Record<string, unknown>) => {
@@ -665,11 +824,11 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
665
824
  progress: async (progress) => {
666
825
  await step.runMutation(RUN_QUEUE, { op: 'progress', jobId, progress }, { inline: true })
667
826
  },
668
- charge: async (credits) => {
827
+ charge: async (credits, chargeOptions = {}) => {
669
828
  if (mode !== 'output') throw new TypeError('[nuxt-backend] job.charge: this kind charges its whole `cost` as it starts. Define it with `charge: \'output\'` to charge what the job made.')
670
829
  requireCreditAmount(credits, 'job.charge: `credits`', { orZero: true })
671
- const billed = await step.runAction(BILL_JOB, { op: 'charge', jobId, amount: credits }, { retry: BILL_RETRY }) as Shortfall | null
672
- if (billed?.blocked) throw new Error(`${CATALOG_MARK}${JSON.stringify(billed.blocked)}`)
830
+ const metadata = chargeOptions.metadata === undefined ? undefined : checkedMetadata(chargeOptions.metadata)
831
+ await billStep(step, defined({ op: 'charge' as const, jobId, amount: credits, metadata }))
673
832
  },
674
833
  })
675
834
 
@@ -702,18 +861,12 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
702
861
  const kind = workflow.define({
703
862
  args: { jobId: v.string(), args: v.any() },
704
863
  handler: async (step, { jobId, args }): Promise<unknown> => {
705
- if (definition.moderate) {
706
- // The safety check first: a flagged job is never charged, and its hold goes back as it ends.
707
- const checked = await step.runAction(BILL_JOB, { op: 'moderate', jobId, input: definition.moderate(args as never) }, { retry: BILL_RETRY }) as { blocked: Record<string, unknown> } | null
708
- if (checked?.blocked) throw new Error(`${CATALOG_MARK}${JSON.stringify(checked.blocked)}`)
709
- }
864
+ // The safety check first: a flagged job is never charged, and its hold goes back as it ends.
865
+ if (definition.moderate) await billStep(step, { op: 'moderate', jobId, input: definition.moderate(args as never) })
710
866
  // A kind charged at start pays its whole cost now; one charged by
711
867
  // output takes its hold again (a balance read for the first time, a
712
868
  // hold past its week) and pays at `job.charge`.
713
- if (definition.meter !== false) {
714
- const billed = await step.runAction(BILL_JOB, { op: mode === 'output' ? 'hold' : 'charge', jobId }, { retry: BILL_RETRY }) as Shortfall | null
715
- if (billed?.blocked) throw new Error(`${CATALOG_MARK}${JSON.stringify(billed.blocked)}`)
716
- }
869
+ if (definition.meter !== false) await billStep(step, { op: mode === 'output' ? 'hold' : 'charge', jobId })
717
870
  try {
718
871
  return await definition.handler(jobContext(step, jobId, mode), args as never)
719
872
  }
@@ -771,8 +924,9 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
771
924
  await ctx.runMutation(queue.touch, defined({ jobId, until: lease(), lastError: text, usage: usageOf(calls), spendLimitUsd: aiConfig.spendLimit?.usdPerDay }))
772
925
  const outcome = modelOutcomeOf(failed)
773
926
  if (modelId && outcome) await ctx.runMutation(queue.recordModel, { model: modelId, outcome, ...defaultsOf(modelId) })
774
- if (isPassing(failed) && attempt.attempt < STEP_ATTEMPTS) {
775
- const wait = retryDelay(attempt.attempt, failed.retryAfter, `${jobId}:${modelId ?? ''}`)
927
+ // An empty image answer is tried once more at most: each try bills the prompt again.
928
+ if (isPassing(failed) && attempt.attempt < (failed.kind === 'empty' ? EMPTY_ATTEMPTS : STEP_ATTEMPTS)) {
929
+ const wait = retryDelay(attempt.attempt, failed.kind === 'empty' ? undefined : failed.retryAfter, `${jobId}:${modelId ?? ''}`)
776
930
  await ctx.runMutation(queue.touch, { jobId, until: lease() + wait })
777
931
  return { retry: wait }
778
932
  }
@@ -797,7 +951,8 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
797
951
  // A turn from the model's bucket first: none free, and the step waits without counting an attempt.
798
952
  const waiting = await takeTurn(ctx, jobId, modelId)
799
953
  if (waiting) return waiting
800
- await ctx.runMutation(queue.touch, { jobId, until: lease(), attempt: true })
954
+ const whose = await ctx.runMutation(queue.touch, { jobId, until: lease(), attempt: true })
955
+ const job: StepJob = defined({ id: jobId, attempt, owner: whose?.owner ?? APP_OWNER, userId: whose?.userId })
801
956
  const calls: ModelCall[] = []
802
957
  // The step's deadline: every model call gets it, and a timeout is tried again like a provider's.
803
958
  const deadline = new AbortController()
@@ -818,7 +973,7 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
818
973
  let value: unknown
819
974
  try {
820
975
  const storeImage = imageStore(ctx, aiConfig.provenance, provenanceRows, { jobId, calls, model: modelId })
821
- value = await definition.handler(Object.assign(ctx, { model: pick, image, signal: deadline.signal, callSettings, job: { id: jobId, attempt }, storeImage }) as never, args as never)
976
+ value = await definition.handler(Object.assign(ctx, { model: pick, image, signal: deadline.signal, callSettings, job, storeImage }) as never, args as never)
822
977
  }
823
978
  catch (error) {
824
979
  return await failedAttempt(ctx, { jobId, attempt, modelId }, error, calls)
@@ -1015,20 +1170,31 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1015
1170
  return { jobId }
1016
1171
  }
1017
1172
 
1018
- /** A charge or a hold no retry changes: short of credits, or no credits at all once the balance was read. */
1019
- type Shortfall = { blocked: Record<string, unknown> }
1173
+ /**
1174
+ * What a billing step of the workflow answers: nothing (it went
1175
+ * through), a refusal that fails the job (`blocked`), or a wait for
1176
+ * billing to sync before it is tried again.
1177
+ */
1178
+ type BillOutcome = { blocked: Record<string, unknown> } | { wait: number }
1179
+
1180
+ /** A refusal no retry changes: the balance is short of the credits. */
1181
+ const isShortfall = (error: unknown): boolean => getBackendError(error)?.code === 'insufficient_credits'
1182
+
1183
+ /** A refusal that waits: billing has not synced the balance (`not_synced`) or the customer (`no_customer`) yet. */
1184
+ const isUnsynced = (error: unknown): boolean => getBackendError(error)?.code === 'not_ready'
1185
+
1186
+ /** Whether a hold's or a charge's refusal is waited out ({@link billingRefused}): billing not synced yet, with waits left. */
1187
+ const waitsForBilling = (error: unknown, attempt: number): boolean => isUnsynced(error) && attempt < BILL_WAITS
1020
1188
 
1021
1189
  /**
1022
- * A refusal that fails the job at once, as `insufficient_credits`: the
1023
- * balance is short, or, read afresh, holds no credit meter (`not_ready`).
1024
- * Anything else is tried again.
1190
+ * A refusal a charge by output waits out as an owed charge: billing not
1191
+ * synced yet, or a provider failure that may pass (no answer, a `408`,
1192
+ * `429` or `5xx`). A provider that refuses the request itself, such as a
1193
+ * revoked access token (`401`), would refuse every try
1194
+ * (`providerRefusesForGood`): that charge is given up at once, the job
1195
+ * still `done`; charged at start, the job fails, its hold back.
1025
1196
  */
1026
- const shortfallOf = (error: unknown, job: JobRow): Record<string, unknown> | undefined => {
1027
- const refusal = getBackendError(error)
1028
- if (refusal?.code === 'insufficient_credits') return payloadOf(error)
1029
- if (refusal?.code === 'not_ready') return defined({ code: 'insufficient_credits', meter: job.meter, balance: 0, need: job.cost })
1030
- return undefined
1031
- }
1197
+ const isPassingRefusal = (error: unknown): boolean => isUnsynced(error) || providerFailurePasses(error)
1032
1198
 
1033
1199
  /** A hold to let go by its id: one an earlier try took and never noted is still let go, and none is a no-op. */
1034
1200
  const released = (hold: SpendReservation): SpendReservation => ({ ...hold, reserved: true })
@@ -1037,6 +1203,10 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1037
1203
  const holdData = (hold: SpendReservation) => defined({ externalId: hold.externalId, reserved: hold.reserved, value: hold.value, meter: hold.meter, meterId: hold.meterId })
1038
1204
  const reservationOf = (job: JobRow): SpendReservation | undefined => job.hold && { ...job.hold, entityId: job.owner }
1039
1205
 
1206
+ /** The usage event's metadata for a job's charge: the app's own, then the queue's, which win. */
1207
+ const chargeTags = (job: JobRow, metadata: Record<string, string> | undefined): Record<string, string> =>
1208
+ defined({ ...metadata, userId: job.userId, job: job.kind }) as Record<string, string>
1209
+
1040
1210
  // ── The queue's own functions ───────────────────────────────────────────
1041
1211
 
1042
1212
  /**
@@ -1048,7 +1218,7 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1048
1218
  const onJobEnd = options.onJobEnd
1049
1219
  if (!onJobEnd || (job.status !== 'done' && job.status !== 'failed' && job.status !== 'canceled')) return
1050
1220
  try {
1051
- await ctx.scheduler.runAfter(0, onJobEnd as FunctionReference<'mutation', 'internal'>, defined({ jobId: job._id, kind: job.kind, status: job.status, error: job.status === 'failed' ? job.error : undefined, args: job.args, retries: job.retries, endedAt: job.endedAt ?? Date.now(), charged: chargedOf(job), free: job.free === true }))
1221
+ await ctx.scheduler.runAfter(0, onJobEnd as FunctionReference<'mutation', 'internal'>, defined({ jobId: job._id, kind: job.kind, status: job.status, error: job.status === 'failed' ? job.error : undefined, args: job.args, retries: job.retries, endedAt: job.endedAt ?? Date.now(), charged: chargedOf(job), free: job.free === true, owed: job.chargeOwed === 'pending' ? job.price : undefined }))
1052
1222
  }
1053
1223
  catch (error) {
1054
1224
  logBackend('error', 'ai.job_end_unannounced', `Job ${job._id} ended ${job.status}, but onJobEnd could not be scheduled.`, error)
@@ -1056,10 +1226,10 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1056
1226
  }
1057
1227
 
1058
1228
  /** After a job ended: its hold let go, its credits refunded, its cost reported, as its end asks, and the app told. */
1059
- const afterEnd = async (ctx: Ctx, job: JobRow): Promise<void> => {
1229
+ const afterEnd = async (ctx: Ctx, job: JobRow & { owedDropped?: boolean }): Promise<void> => {
1060
1230
  const hold = reservationOf(job)
1061
- // A charge on its way settles the hold, or lets it go, itself.
1062
- if (hold && !job.charged && job.charging === undefined) await billing.releaseSpend(ctx as never, released(hold))
1231
+ // A charge on its way settles the hold, or lets it go, itself; an owed charge the end dropped lets it go here.
1232
+ if (hold && !job.charged && (job.charging === undefined || job.owedDropped)) await billing.releaseSpend(ctx as never, released(hold))
1063
1233
  if (job.refundOwed === 'pending') await scheduleRefund(ctx, job._id)
1064
1234
  if (job.status !== 'canceled' && job.usage && job.startedAt !== undefined) await ctx.scheduler.runAfter(0, BILL_JOB, { op: 'report', jobId: job._id })
1065
1235
  await announceEnd(ctx, job)
@@ -1131,14 +1301,88 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1131
1301
  }
1132
1302
  }
1133
1303
 
1304
+ /** Tell the app how an owed charge ended, in the transaction that recorded it. */
1305
+ const announceCharge = async (ctx: Ctx, job: JobRow, status: OwedCharge['status']): Promise<void> => {
1306
+ const onOwedCharge = options.onOwedCharge
1307
+ if (!onOwedCharge) return
1308
+ try {
1309
+ await ctx.scheduler.runAfter(0, onOwedCharge as FunctionReference<'mutation', 'internal'>, { jobId: job._id, kind: job.kind, args: job.args, retries: job.retries, status, credits: job.price ?? 0, at: Date.now() })
1310
+ }
1311
+ catch (error) {
1312
+ logBackend('error', 'ai.job_charge_unannounced', `Job ${job._id}'s owed charge ended ${status}, but onOwedCharge could not be scheduled.`, error)
1313
+ }
1314
+ }
1315
+
1316
+ /**
1317
+ * An owed charge's step, in one transaction with what it schedules: owed
1318
+ * (`owe`), its first try a minute on; refused in a way no try changes
1319
+ * (`refused`), given up at once; tried and failed (`retry`), the next one
1320
+ * due; given up, its hold back; or charged at last, refunded at once when
1321
+ * the job ended needing its credits back. Each end is heard.
1322
+ */
1323
+ type OwedStep = { jobId: string, outcome: 'owe' | 'refused' | 'retry' | 'given_up' | 'charged', attempt?: number, price?: number, metadata?: Record<string, string> }
1324
+
1325
+ /** Let a job's hold go, when it holds one and was never charged. */
1326
+ const releaseHold = async (ctx: Ctx, job: JobRow): Promise<void> => {
1327
+ const hold = reservationOf(job)
1328
+ if (hold && !job.charged) await billing.releaseSpend(ctx as never, released(hold))
1329
+ }
1330
+
1331
+ /** An owed charge's next try: the first a minute on (`owe`), or the next one after a failed try (`retry`). */
1332
+ const owedTry = async (ctx: Ctx, job: JobRow, step: OwedStep): Promise<void> => {
1333
+ const first = step.outcome === 'owe'
1334
+ const attempt = first ? 1 : step.attempt ?? 1
1335
+ const delay = billBackoff(attempt - 1)
1336
+ const at = Date.now() + delay
1337
+ const owed = first
1338
+ ? await ctx.runMutation(queue.oweCharge, defined({ jobId: job._id, price: step.price ?? 0, at, metadata: step.metadata }))
1339
+ : await ctx.runMutation(queue.chargeTried, { jobId: job._id, outcome: 'retry', at })
1340
+ // A job that ended meanwhile owes nothing: the hold taken for it goes back.
1341
+ if (owed) await scheduleOwed(ctx, job._id, attempt, delay)
1342
+ else await releaseHold(ctx, job)
1343
+ }
1344
+
1345
+ /**
1346
+ * A job's charge the provider refused in a way no try changes, for a kind
1347
+ * charged by output: owed and given up at once, with no try in the
1348
+ * background, its hold back, and heard `given_up`, for an administrator's
1349
+ * retry once the cause is fixed. A job that ended meanwhile owes nothing,
1350
+ * and its hold goes back all the same.
1351
+ */
1352
+ const refusedForGood = async (ctx: Ctx, job: JobRow, step: OwedStep): Promise<void> => {
1353
+ const owed = await ctx.runMutation(queue.oweCharge, defined({ jobId: job._id, price: step.price ?? 0, at: Date.now(), metadata: step.metadata, givenUp: true }))
1354
+ await releaseHold(ctx, job)
1355
+ if (owed) await announceCharge(ctx, { ...job, price: step.price }, 'given_up')
1356
+ }
1357
+
1358
+ const recordOwed = async (ctx: Ctx, step: OwedStep): Promise<void> => {
1359
+ const { jobId, outcome } = step
1360
+ const job = await ctx.runQuery(queue.get, { jobId }) as JobRow | null
1361
+ if (!job) return
1362
+ if (outcome === 'owe' || outcome === 'retry') return await owedTry(ctx, job, step)
1363
+ if (outcome === 'refused') return await refusedForGood(ctx, job, step)
1364
+ if (outcome === 'given_up') {
1365
+ if (!await ctx.runMutation(queue.chargeTried, { jobId, outcome: 'given_up' })) return
1366
+ await releaseHold(ctx, job)
1367
+ return await announceCharge(ctx, job, 'given_up')
1368
+ }
1369
+ const { refund } = await ctx.runMutation(queue.mark, { jobId, charged: true as const, price: job.price })
1370
+ if (refund) await scheduleRefund(ctx, jobId)
1371
+ if (job.chargeOwed !== undefined) await announceCharge(ctx, job, 'charged')
1372
+ }
1373
+
1134
1374
  const runQueue = internalMutationGeneric({
1135
1375
  args: {
1136
- op: v.optional(v.union(v.literal('pick'), v.literal('progress'), v.literal('claim'))),
1376
+ op: v.optional(v.union(v.literal('pick'), v.literal('progress'), v.literal('claim'), v.literal('owed'))),
1137
1377
  jobId: v.optional(v.string()),
1138
1378
  // A claim at sign-up: the account, and how many times it looked for its workspace.
1139
1379
  userId: v.optional(v.string()),
1140
1380
  attempt: v.optional(v.number()),
1141
1381
  progress: v.optional(v.object({ done: v.number(), total: v.number(), label: v.optional(v.string()) })),
1382
+ // An owed charge's step: how its try went, what it owes, and the usage event's metadata.
1383
+ outcome: v.optional(v.union(v.literal('owe'), v.literal('refused'), v.literal('retry'), v.literal('given_up'), v.literal('charged'))),
1384
+ price: v.optional(v.number()),
1385
+ metadata: v.optional(v.record(v.string(), v.string())),
1142
1386
  // A workflow's end (the Workflow component's onComplete).
1143
1387
  workflowId: v.optional(v.string()),
1144
1388
  result: v.optional(v.any()),
@@ -1158,6 +1402,10 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1158
1402
  if (args.userId) await claimGuests(ctx, args.userId, args.attempt ?? 0)
1159
1403
  return null
1160
1404
  }
1405
+ if (args.op === 'owed') {
1406
+ if (args.jobId && args.outcome) await recordOwed(ctx, defined({ jobId: args.jobId, outcome: args.outcome, attempt: args.attempt, price: args.price, metadata: args.metadata }))
1407
+ return null
1408
+ }
1161
1409
  const jobId = (args.context as { jobId?: string } | undefined)?.jobId
1162
1410
  if (jobId && args.result) await endJob(ctx, jobId, args.result as WorkflowResult)
1163
1411
  // A workflow's end runs inside the Workflow component's own call: the next pick, which starts workflows, runs on its own.
@@ -1168,10 +1416,19 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1168
1416
 
1169
1417
  /**
1170
1418
  * Why a hold or a charge was refused, recorded on the job: a shortfall
1171
- * fails the job at once; anything else is thrown, and tried again.
1419
+ * fails the job at once; billing not synced yet (a balance never read, a
1420
+ * customer not made yet) waits and is tried again, up to
1421
+ * {@link BILL_WAITS} times, then fails the job with its refusal; anything
1422
+ * else is thrown, and tried again.
1172
1423
  */
1173
- const billingRefused = async (ctx: ActionCtx, job: JobRow, error: unknown): Promise<Shortfall> => {
1174
- const short = shortfallOf(error, job)
1424
+ const billingRefused = async (ctx: ActionCtx, job: JobRow, error: unknown, attempt: number): Promise<BillOutcome> => {
1425
+ if (waitsForBilling(error, attempt)) {
1426
+ const wait = billWait(attempt)
1427
+ await ctx.runMutation(queue.touch, { jobId: job._id, until: lease() + wait, lastError: errorText(error) })
1428
+ logBackend('warn', 'ai.job_billing_wait', `Job ${job._id}: billing is not synced for its owner yet; trying again in ${wait / 1000}s.`, error)
1429
+ return { wait }
1430
+ }
1431
+ const short = isShortfall(error) || isUnsynced(error) ? payloadOf(error) : undefined
1175
1432
  await ctx.runMutation(queue.recordError, { jobId: job._id, error: short ?? (getBackendError(error) ? payloadOf(error) : failure('provider_refused')), lastError: errorText(error) })
1176
1433
  if (short) return { blocked: short }
1177
1434
  throw error
@@ -1185,17 +1442,70 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1185
1442
  return undefined
1186
1443
  }
1187
1444
 
1445
+ /**
1446
+ * Keep an owed charge's credits held under the job's hold id while the
1447
+ * charge is owed. A settle the provider refused kept them
1448
+ * (`keepReservation`), what it would charge and no more, so this is a
1449
+ * no-op while that hold stands, and no other spend ever finds them free.
1450
+ * A hold that is gone all the same (past its week, or dropped by a
1451
+ * provider sync after a refund) is taken again past the balance, as the
1452
+ * provider bills what the job made all the same. A balance that cannot be
1453
+ * read keeps nothing held; the charge is tried anyway.
1454
+ */
1455
+ const holdOwed = async (ctx: ActionCtx, job: JobRow, hold: SpendReservation, price: number): Promise<void> => {
1456
+ try {
1457
+ await billing.reserveCredits(ctx as never, { userId: job.owner, meter: hold.meter, meterId: hold.meterId, value: price, externalId: hold.externalId, hold: HOLD_MS, allowOverage: true })
1458
+ }
1459
+ catch (error) {
1460
+ logBackend('warn', 'ai.job_charge_unheld', `Job ${job._id}: its owed charge's credits could not be held again; the charge is still tried.`, error)
1461
+ }
1462
+ }
1463
+
1464
+ /**
1465
+ * Owe a job's charge, for a kind charged by output whose `job.charge` the
1466
+ * provider refused for a passing reason: its credits kept held, and the
1467
+ * charge tried in the background from a minute on. The job runs on.
1468
+ */
1469
+ const oweCharge = async (ctx: ActionCtx, job: JobRow, hold: SpendReservation, price: number, metadata: Record<string, string> | undefined, error: unknown): Promise<undefined> => {
1470
+ await holdOwed(ctx, job, hold, price)
1471
+ await ctx.runMutation(queue.touch, { jobId: job._id, until: lease(), lastError: errorText(error) })
1472
+ await ctx.runMutation(RUN_QUEUE, defined({ op: 'owed' as const, jobId: job._id, outcome: 'owe' as const, price, metadata }))
1473
+ logBackend('warn', 'ai.job_charge_owed', `Job ${job._id}: the billing provider refused its charge of ${price} credits for now. The job runs on, and its charge is tried again in the background.`, error)
1474
+ return undefined
1475
+ }
1476
+
1477
+ /**
1478
+ * Give a job's charge up at once, for a kind charged by output whose
1479
+ * `job.charge` the provider refused in a way no try changes (a revoked
1480
+ * access token, a product or meter it does not have): the job runs on and
1481
+ * keeps what it made, the charge is owed given up with no try in the
1482
+ * background, its hold goes back, and the error is logged for the
1483
+ * operator. An administrator's retry tries it once the cause is fixed.
1484
+ */
1485
+ const giveUpCharge = async (ctx: ActionCtx, job: JobRow, price: number, metadata: Record<string, string> | undefined, error: unknown): Promise<undefined> => {
1486
+ await ctx.runMutation(queue.touch, { jobId: job._id, until: lease(), lastError: errorText(error) })
1487
+ await ctx.runMutation(RUN_QUEUE, defined({ op: 'owed' as const, jobId: job._id, outcome: 'refused' as const, price, metadata }))
1488
+ logBackend('error', 'ai.job_charge_refused', `Job ${job._id}: the billing provider refused its charge of ${price} credits in a way no retry changes. The job keeps its result uncharged, and its hold went back. Fix what the error names, then retry the charge from the Queue tab.`, error)
1489
+ return undefined
1490
+ }
1491
+
1188
1492
  /**
1189
1493
  * Charge a job's held credits, as its workflow's first step: only while
1190
1494
  * the job still runs and nobody canceled it. The hold is taken again under
1191
1495
  * the same id first, a no-op while it stands: after an attempt whose
1192
1496
  * ingest failed let it go, or a wait past its week let it lapse, the
1193
1497
  * credits are taken again, or the job fails short of them, so the
1194
- * provider never bills what the cached balance still shows.
1498
+ * provider never bills what the cached balance still shows. Charged by
1499
+ * output (`amount`), a refusal that may pass ({@link isPassingRefusal})
1500
+ * leaves the charge owed instead of failing a job that made what it
1501
+ * charges for. Charged at start, billing not synced yet is waited out
1502
+ * with the hold still taken, so the try after the wait never finds its
1503
+ * credits spent elsewhere.
1195
1504
  */
1196
- const charge = async (ctx: ActionCtx, job: JobRow, amount?: number): Promise<Shortfall | undefined> => {
1505
+ const charge = async (ctx: ActionCtx, job: JobRow, amount?: number, metadata?: Record<string, string>, attempt = 0): Promise<BillOutcome | undefined> => {
1197
1506
  const hold = reservationOf(job)
1198
- if (job.charged || !hold) return
1507
+ // An owed charge is the job's one charge: a later `job.charge` changes nothing.
1508
+ if (job.charged || !hold || job.chargeOwed !== undefined) return
1199
1509
  const claim = await ctx.runMutation(queue.claimCharge, { jobId: job._id })
1200
1510
  if (claim === 'charged') return
1201
1511
  if (claim === 'ended') throw new Error(`[nuxt-backend] Job ${job._id} ended before its charge: nothing was billed.`)
@@ -1207,24 +1517,80 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1207
1517
  // A hold that lapsed is taken again for what the job charges, not its whole cost.
1208
1518
  held = await billing.reserveCredits(ctx as never, { userId: job.owner, meter: hold.meter, meterId: hold.meterId, value: price ?? job.cost, externalId: hold.externalId, hold: HOLD_MS })
1209
1519
  // The job's hold id is the event's idempotency key: a charge run again never bills twice.
1210
- await billing.settleSpend(ctx as never, held, defined({ finalAmount: price, metadata: defined({ userId: job.userId, job: job.kind }) as Record<string, string> }))
1520
+ // A refused settle keeps what it charges held: below, an owed charge keeps it, and any other refusal lets it go.
1521
+ await billing.settleSpend(ctx as never, held, defined({ finalAmount: price, metadata: chargeTags(job, metadata), keepReservation: true }))
1211
1522
  }
1212
1523
  catch (error) {
1213
- await billing.releaseSpend(ctx as never, released(held ?? hold))
1214
- return await billingRefused(ctx, job, error)
1524
+ return await chargeRefused(ctx, job, held ?? hold, { price, metadata, attempt }, error)
1215
1525
  }
1216
1526
  // A job that ended while its charge was on its way gets it back at once.
1217
1527
  const { refund: owed } = await ctx.runMutation(queue.mark, defined({ jobId: job._id, charged: true as const, price }))
1218
1528
  if (owed) await scheduleRefund(ctx, job._id)
1219
1529
  }
1220
1530
 
1531
+ /**
1532
+ * A refused charge. Charged by output: owed for a refusal that may pass,
1533
+ * given up at once for one the provider repeats on every try
1534
+ * ({@link giveUpCharge}), the job `done` either way. Otherwise: waited out
1535
+ * with the hold the refused settle kept, for billing not synced yet, so
1536
+ * no other spend takes its credits meanwhile; else its hold let go and the
1537
+ * refusal recorded, the job failed ({@link billingRefused}).
1538
+ */
1539
+ const chargeRefused = async (ctx: ActionCtx, job: JobRow, hold: SpendReservation, tried: { price?: number, metadata?: Record<string, string>, attempt: number }, error: unknown): Promise<BillOutcome | undefined> => {
1540
+ const { price, metadata, attempt } = tried
1541
+ if (price !== undefined && isPassingRefusal(error)) return await oweCharge(ctx, job, hold, price, metadata, error)
1542
+ if (price !== undefined && providerRefusesForGood(error)) return await giveUpCharge(ctx, job, price, metadata, error)
1543
+ const kept = waitsForBilling(error, attempt) && await ctx.runMutation(queue.chargeWaits, { jobId: job._id })
1544
+ if (!kept) await billing.releaseSpend(ctx as never, released(hold))
1545
+ return await billingRefused(ctx, job, error, attempt)
1546
+ }
1547
+
1548
+ /**
1549
+ * Give an owed charge up, its hold back, after its last try, or after a
1550
+ * try the provider refused in a way no later try changes: logged as such,
1551
+ * so the operator sees which.
1552
+ */
1553
+ const giveUpOwed = async (ctx: ActionCtx, job: JobRow, price: number, tries: number, error: unknown): Promise<void> => {
1554
+ await ctx.runMutation(RUN_QUEUE, { op: 'owed', jobId: job._id, outcome: 'given_up' })
1555
+ if (providerRefusesForGood(error)) logBackend('error', 'ai.job_charge_refused', `Job ${job._id}: the billing provider refused its owed charge of ${price} credits in a way no retry changes, so it was given up at once: the job stays uncharged, and its hold went back. Fix what the error names, then retry the charge from the Queue tab.`, error)
1556
+ else logBackend('error', 'ai.job_charge_given_up', `Job ${job._id}'s owed charge of ${price} credits failed ${tries} times: the job stays uncharged, and its hold went back. Retry it from the Queue tab to charge it.`, error)
1557
+ }
1558
+
1559
+ /**
1560
+ * Try an owed charge again, in the background: under the job's hold id,
1561
+ * so the provider bills it once however many tries reach it. One that
1562
+ * fails is tried again a minute later, doubling, up to
1563
+ * {@link OWED_ATTEMPTS} tries in all; after that, or at once for a refusal
1564
+ * the provider repeats on every try, it is given up, its hold goes back,
1565
+ * and the job stays uncharged for an administrator's retry.
1566
+ * `onOwedCharge` hears either end.
1567
+ */
1568
+ const settleOwed = async (ctx: ActionCtx, job: JobRow, attempt: number): Promise<void> => {
1569
+ const hold = reservationOf(job)
1570
+ if (job.chargeOwed !== 'pending' || job.charged || !hold || job.price === undefined) return
1571
+ const price = job.price
1572
+ try {
1573
+ // Settled from the job's hold, which a refused try keeps; a hold that is gone is taken from the balance as the charge lands.
1574
+ await billing.settleSpend(ctx as never, released({ ...hold, value: price }), { finalAmount: price, metadata: chargeTags(job, job.chargeMetadata), keepReservation: true })
1575
+ }
1576
+ catch (error) {
1577
+ const next = attempt + 1
1578
+ if (next >= OWED_ATTEMPTS || providerRefusesForGood(error)) return await giveUpOwed(ctx, job, price, next, error)
1579
+ await holdOwed(ctx, job, hold, price)
1580
+ await ctx.runMutation(RUN_QUEUE, { op: 'owed', jobId: job._id, outcome: 'retry', attempt: next })
1581
+ logBackend('warn', 'ai.job_charge_retry', `Job ${job._id}'s owed charge failed; trying again in ${billBackoff(attempt) / 1000}s.`, error)
1582
+ return
1583
+ }
1584
+ await ctx.runMutation(RUN_QUEUE, { op: 'owed', jobId: job._id, outcome: 'charged' })
1585
+ }
1586
+
1221
1587
  /**
1222
1588
  * Take a job's hold again as it starts, for a kind charged by output: a
1223
1589
  * no-op while it stands; a balance read for the first time, or a hold past
1224
1590
  * its week, is taken now, or the job fails short of credits before any
1225
1591
  * model is called. A hold taken for a job that ended meanwhile goes back.
1226
1592
  */
1227
- const takeHold = async (ctx: ActionCtx, job: JobRow): Promise<Shortfall | undefined> => {
1593
+ const takeHold = async (ctx: ActionCtx, job: JobRow, attempt = 0): Promise<BillOutcome | undefined> => {
1228
1594
  const hold = reservationOf(job)
1229
1595
  if (job.charged || !hold) return
1230
1596
  // A job that ended meanwhile: a hold an earlier try took and never noted goes back by its id.
@@ -1237,7 +1603,7 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1237
1603
  held = await billing.reserveCredits(ctx as never, { userId: job.owner, meter: hold.meter, meterId: hold.meterId, value: job.cost, externalId: hold.externalId, hold: HOLD_MS })
1238
1604
  }
1239
1605
  catch (error) {
1240
- return await billingRefused(ctx, job, error)
1606
+ return await billingRefused(ctx, job, error, attempt)
1241
1607
  }
1242
1608
  if (hold.reserved) return
1243
1609
  const live = await ctx.runMutation(queue.holdTaken, { jobId: job._id, hold: holdData(held) })
@@ -1265,7 +1631,7 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1265
1631
  logBackend('error', 'ai.job_refund_failed', `Job ${job._id}'s refund failed ${REFUND_ATTEMPTS} times: its credits are still owed. Retry the job to run it on the charge it paid.`, error)
1266
1632
  return
1267
1633
  }
1268
- const delay = refundBackoff(attempt)
1634
+ const delay = billBackoff(attempt)
1269
1635
  await ctx.runMutation(queue.refundTried, { jobId: job._id, outcome: 'retry', at: Date.now() + delay })
1270
1636
  await scheduleRefund(ctx, job._id, next, delay)
1271
1637
  logBackend('warn', 'ai.job_refund_retry', `Job ${job._id}'s refund failed; trying again in ${delay / 1000}s.`, error)
@@ -1309,21 +1675,24 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1309
1675
 
1310
1676
  const billJob = internalActionGeneric({
1311
1677
  args: {
1312
- op: v.union(v.literal('charge'), v.literal('hold'), v.literal('refund'), v.literal('report'), v.literal('moderate')),
1678
+ op: v.union(v.literal('charge'), v.literal('hold'), v.literal('refund'), v.literal('owed'), v.literal('report'), v.literal('moderate')),
1313
1679
  jobId: v.string(),
1314
1680
  attempt: v.optional(v.number()),
1315
1681
  /** What `job.charge` charges, for a kind charged by output. */
1316
1682
  amount: v.optional(v.number()),
1683
+ /** The app's own metadata for the usage event (`job.charge(n, { metadata })`). */
1684
+ metadata: v.optional(v.record(v.string(), v.string())),
1317
1685
  input: v.optional(v.object({ text: v.optional(v.string()), images: v.optional(v.array(v.string())), subject: v.optional(v.string()), stage: v.optional(v.string()) })),
1318
1686
  },
1319
- returns: v.union(v.null(), v.object({ blocked: v.any() })),
1320
- handler: async (ctx, { op, jobId, attempt, amount, input }): Promise<null | { blocked: Record<string, unknown> }> => {
1687
+ returns: v.union(v.null(), v.object({ blocked: v.any() }), v.object({ wait: v.number() })),
1688
+ handler: async (ctx, { op, jobId, attempt, amount, metadata, input }): Promise<null | BillOutcome> => {
1321
1689
  if (op === 'moderate') return await moderateJob(ctx, jobId, input)
1322
1690
  const job = await ctx.runQuery(queue.get, { jobId }) as JobRow | null
1323
1691
  if (!job) return null
1324
- if (op === 'charge') return await charge(ctx, job, amount) ?? null
1325
- if (op === 'hold') return await takeHold(ctx, job) ?? null
1692
+ if (op === 'charge') return await charge(ctx, job, amount, metadata, attempt) ?? null
1693
+ if (op === 'hold') return await takeHold(ctx, job, attempt) ?? null
1326
1694
  if (op === 'refund') await refund(ctx, job, attempt)
1695
+ else if (op === 'owed') await settleOwed(ctx, job, attempt ?? 1)
1327
1696
  else await reportJobCost(ctx, job)
1328
1697
  return null
1329
1698
  },
@@ -1483,26 +1852,55 @@ export function defineJobQueue(components: JobQueueComponents, options: DefineJo
1483
1852
  },
1484
1853
  })
1485
1854
 
1855
+ /**
1856
+ * An administrator's retry of a job whose charge gave up, done, still
1857
+ * running or canceled without a refund: the charge is owed again, its
1858
+ * credits held again, and it is tried at once; the job's result stands.
1859
+ * One already owed again (a second click) is left to its tries. `false`
1860
+ * for any other job, a failed one included: its retry runs it again.
1861
+ */
1862
+ const retryOwedCharge = async (ctx: Ctx, job: JobRow | null, actor: string): Promise<boolean> => {
1863
+ if (job?.chargeOwed === undefined || job.charged || job.status === 'failed' || (job.status === 'canceled' && job.cancel?.refund === true)) return false
1864
+ if (job.chargeOwed === 'pending') return true
1865
+ const hold = reservationOf(job)
1866
+ const price = job.price ?? 0
1867
+ if (hold && await ctx.runMutation(queue.oweCharge, { jobId: job._id, price, at: Date.now(), again: true })) {
1868
+ await billing.reserveCredits(ctx as never, { userId: job.owner, meter: hold.meter, meterId: hold.meterId, value: price, externalId: hold.externalId, hold: HOLD_MS, allowOverage: true, allowRefresh: false }).catch(() => undefined)
1869
+ await scheduleOwed(ctx, job._id, 1, 0)
1870
+ await billing.recordEvent(ctx as never, job.owner, { type: 'job.charge_retried', actor, data: { kind: job.kind, credits: price } } as never)
1871
+ }
1872
+ return true
1873
+ }
1874
+
1875
+ /**
1876
+ * A job charged by output never runs on its old charge: what it made then
1877
+ * is no price for the rerun. Its charge goes back first, then the rerun
1878
+ * takes a fresh hold: this retry gives the charge back, and the next one,
1879
+ * once it lands, runs the job again. `false` when nothing is to give back.
1880
+ */
1881
+ const refundBeforeRetry = async (ctx: Ctx, job: JobRow): Promise<boolean> => {
1882
+ if (!(job.price !== undefined && job.charged && !job.refunded && job.price > 0)) return false
1883
+ if (await ctx.runMutation(queue.oweRefund, { jobId: job._id })) await scheduleRefund(ctx, job._id)
1884
+ logBackend('info', 'ai.job_refund_retry', `Job ${job._id} was charged by output and never refunded: its refund is tried again first. Retry it once the refund lands.`)
1885
+ return true
1886
+ }
1887
+
1486
1888
  const retryJob = mutationGeneric({
1487
1889
  args: { jobId: v.string() },
1488
1890
  returns: v.null(),
1489
1891
  handler: async (ctx, { jobId }) => {
1490
1892
  const actor = await requireAdministrator(ctx, 'retryJob')
1491
1893
  const job = await ctx.runQuery(queue.get, { jobId }) as JobRow | null
1894
+ if (await retryOwedCharge(ctx, job, actor)) return null
1492
1895
  if (!job?.deadLetter || job.status !== 'failed') throw backendError('invalid_input', { field: 'jobId', reason: 'not_dead_letter' }, '[nuxt-backend] retryJob: only a failed job in the dead letters goes back in line.')
1493
1896
  if (refundInFlight(job)) throw backendError('invalid_input', { field: 'jobId', reason: 'refund_pending' }, '[nuxt-backend] retryJob: this job\'s refund is still on its way. Retry it once the refund lands.')
1494
1897
  if (chargeInFlight(job)) throw backendError('invalid_input', { field: 'jobId', reason: 'charge_pending' }, '[nuxt-backend] retryJob: this job\'s charge may still land. Retry it in a few minutes.')
1898
+ // A job charged by output gets its old charge back before it runs again:
1899
+ // this retry only gives it back, so it counts nothing in the budget.
1900
+ if (await refundBeforeRetry(ctx, job)) return null
1495
1901
  // An administrator's retry counts in the owner's window now, and is never refused for it.
1496
1902
  // A guest job counts in none, also once claimed: the app pays for it.
1497
1903
  const budget = job.visitor === undefined ? await countBudget(ctx, job.owner, job.cost, true) : { budgetCounted: 0 }
1498
- // A job charged by output never runs on its old charge: what it made then is no price for the rerun.
1499
- // Its charge goes back first, then the rerun takes a fresh hold.
1500
- // This retry gives the charge back; the next one, once it lands, runs the job again.
1501
- if (job.price !== undefined && job.charged && !job.refunded && job.price > 0) {
1502
- if (await ctx.runMutation(queue.oweRefund, { jobId })) await scheduleRefund(ctx, jobId)
1503
- logBackend('info', 'ai.job_refund_retry', `Job ${jobId} was charged by output and never refunded: its refund is tried again first. Retry it once the refund lands.`)
1504
- return null
1505
- }
1506
1904
  // A charge at start that was never refunded carries over: the new run neither holds nor charges again.
1507
1905
  const carry = job.charged && !job.refunded && job.price === undefined
1508
1906
  const hold = carry ? undefined : await holdCredits(ctx, job.owner, job.meter ?? false, job.cost)
@@ -1572,9 +1970,55 @@ function jobViewOf(job: JobRow, standing: { waitingOn: string, position: number
1572
1970
  canCancel,
1573
1971
  charged: chargedOf(job),
1574
1972
  free: job.free === true,
1973
+ owed: owedOf(job),
1575
1974
  })
1576
1975
  }
1577
1976
 
1977
+ /** A charge a job still owes, for a kind charged by output: its credits, and whether its tries gave up. */
1978
+ function owedOf(job: JobRow): JobOwed | undefined {
1979
+ return job.chargeOwed === undefined || job.charged ? undefined : { credits: job.price ?? 0, givenUp: job.chargeOwed === 'given_up' }
1980
+ }
1981
+
1982
+ /** The billing provider's limits on a usage event's metadata: 50 keys, each of 40 characters at most, and string values of 500. */
1983
+ const EVENT_METADATA = { keys: 50, keyLength: 40, valueLength: 500 }
1984
+
1985
+ /** The keys the queue adds to every charge's metadata: `userId`, `job` and the meter's amount. */
1986
+ const QUEUE_METADATA_KEYS = 3
1987
+
1988
+ /**
1989
+ * A metadata key both a usage event and the job's billing step take: 1 to
1990
+ * 40 printable ASCII characters, the first neither `_` (the provider's own
1991
+ * keys) nor `$`.
1992
+ */
1993
+ const METADATA_KEY = /^[\x20-\x23\x25-\x5E\x60-\x7E][\x20-\x7E]{0,39}$/
1994
+
1995
+ /**
1996
+ * `job.charge`'s metadata, checked against what a usage event takes: an
1997
+ * object of string values, within the billing provider's limits. Past them
1998
+ * the provider would refuse the charge on every try, so it throws here,
1999
+ * where the job's code called it.
2000
+ */
2001
+ function checkedMetadata(metadata: Record<string, string>): Record<string, string> {
2002
+ if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata) || Object.values(metadata).some(value => typeof value !== 'string')) {
2003
+ throw new TypeError('[nuxt-backend] job.charge: `metadata` is an object of string values, such as `{ stripId }`.')
2004
+ }
2005
+ const keys = Object.keys(metadata)
2006
+ const most = EVENT_METADATA.keys - QUEUE_METADATA_KEYS
2007
+ if (keys.length > most) {
2008
+ throw new TypeError(`[nuxt-backend] job.charge: \`metadata\` has ${keys.length} keys, over the ${most} of your own a usage event takes: the billing provider takes ${EVENT_METADATA.keys}, and the queue adds \`userId\`, \`job\` and the meter's amount.`)
2009
+ }
2010
+ for (const key of keys) {
2011
+ if (!METADATA_KEY.test(key)) {
2012
+ throw new TypeError(`[nuxt-backend] job.charge: \`metadata\` key ${JSON.stringify(key)} is no key a usage event takes: 1 to ${EVENT_METADATA.keyLength} ASCII characters, not starting with \`_\` (the billing provider's own keys, such as \`_cost\` and \`_llm\`) or \`$\`.`)
2013
+ }
2014
+ const length = [...metadata[key]!].length
2015
+ if (length > EVENT_METADATA.valueLength) {
2016
+ throw new TypeError(`[nuxt-backend] job.charge: \`metadata.${key}\` is ${length} characters, over the ${EVENT_METADATA.valueLength} a usage event takes.`)
2017
+ }
2018
+ }
2019
+ return { ...metadata }
2020
+ }
2021
+
1578
2022
  /** The credits a job was charged: its `cost`, or what `job.charge` charged; `0` before a charge. */
1579
2023
  function chargedOf(job: JobRow): number {
1580
2024
  return job.charged ? job.price ?? job.cost : 0
@@ -1594,6 +2038,7 @@ function adminViewOf(job: JobRow): AdminJobView {
1594
2038
  retries: job.retries,
1595
2039
  cost: job.cost,
1596
2040
  price: job.price,
2041
+ owed: owedOf(job),
1597
2042
  joinedAt: job.joinedAt,
1598
2043
  startedAt: job.startedAt,
1599
2044
  endedAt: job.endedAt,