bailinghub 0.7.0 → 0.9.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 (263) hide show
  1. package/README.en.md +7 -9
  2. package/README.md +7 -9
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
  5. package/docs/AGENT_CLIENT_RUNTIME_API.md +34 -0
  6. package/docs/AGENT_TASK_CONTROL.en.md +25 -0
  7. package/docs/AGENT_TASK_CONTROL.md +94 -0
  8. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
  9. package/docs/ARCHITECTURE.md +1 -1
  10. package/docs/CHANGELOG.en.md +22 -1
  11. package/docs/CHANGELOG.md +22 -1
  12. package/docs/COMPATIBILITY.en.md +6 -0
  13. package/docs/CONTRACT.en.md +2 -0
  14. package/docs/CONTRACT.md +2 -0
  15. package/docs/GENERATED_ARTIFACTS.en.md +46 -0
  16. package/docs/GENERATED_ARTIFACTS.md +108 -0
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/INVOCATION_RECEIPTS.md +111 -0
  20. package/docs/MODEL_BILLING.en.md +123 -0
  21. package/docs/MODEL_BILLING.md +125 -0
  22. package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
  23. package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
  24. package/docs/README.en.md +7 -0
  25. package/docs/README.md +7 -0
  26. package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
  27. package/docs/RELEASE_NOTES_NEXT.md +4 -2
  28. package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
  29. package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
  30. package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
  31. package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
  32. package/docs/TOOL_RATE_LIMITS.md +50 -0
  33. package/docs/UPGRADE_v0.8.0.en.md +71 -0
  34. package/docs/UPGRADE_v0.8.0.md +73 -0
  35. package/docs/UPGRADE_v0.9.0.en.md +54 -0
  36. package/docs/UPGRADE_v0.9.0.md +54 -0
  37. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +6 -0
  38. package/package.json +1 -1
  39. package/schemas/config/route.schema.json +1 -0
  40. package/schemas/config/tool-provider.schema.json +2 -1
  41. package/scripts/check-doc-links.mjs +5 -0
  42. package/scripts/check-image-tags.sh +1 -1
  43. package/scripts/check-release-consistency.test.mjs +2 -2
  44. package/scripts/e2e-console.mjs +32 -2
  45. package/scripts/install.sh +1 -1
  46. package/scripts/publish-images.sh +1 -1
  47. package/scripts/release-audit.mjs +2 -0
  48. package/scripts/sdk-runtime-test.mjs +6 -0
  49. package/scripts/verify-billing-install-upgrade.mjs +225 -0
  50. package/scripts/verify-github-repo.mjs +2 -0
  51. package/sdk/node/README.md +17 -0
  52. package/sdk/node/examples/billing.mjs +21 -0
  53. package/sdk/node/package.json +5 -1
  54. package/sdk/node/src/index.mjs +2 -0
  55. package/sdk/node/src/usage.d.mts +74 -0
  56. package/sdk/node/src/usage.mjs +62 -0
  57. package/sdk/node/tests/usage-types.mts +23 -0
  58. package/sdk/node/tests/usage.test.mjs +81 -0
  59. package/sdk/php7/README.md +19 -2
  60. package/sdk/php7/examples/billing.php +27 -0
  61. package/sdk/php7/examples/well-known.php +1 -1
  62. package/sdk/php7/src/ToolSpec.php +1 -1
  63. package/sdk/php7/src/UsageClient.php +95 -0
  64. package/sdk/php7/src/UsageClientException.php +22 -0
  65. package/sdk/php7/tests/billing-core-http.php +59 -0
  66. package/sdk/php7/tests/usage-client.php +78 -0
  67. package/sql/060_agent_artifacts.sql +11 -0
  68. package/sql/061_tool_rate_limit_policies.sql +3 -0
  69. package/sql/062_agent_task_control.sql +92 -0
  70. package/sql/063_usage_model_billing.sql +153 -0
  71. package/sql/064_period_plan_allowance.sql +25 -0
  72. package/sql/README.en.md +12 -4
  73. package/sql/README.md +14 -6
  74. package/src/adapters/storage/object-storage.ts +15 -3
  75. package/src/adapters/storage/oss-signature.test.ts +40 -0
  76. package/src/adapters/storage/oss-signature.ts +21 -0
  77. package/src/app/agent-artifacts.test.ts +165 -0
  78. package/src/app/agent-artifacts.ts +85 -0
  79. package/src/app/agent-client-runtime.test.ts +76 -1
  80. package/src/app/agent-client-runtime.ts +13 -0
  81. package/src/app/agent-invocation-snapshot.ts +35 -0
  82. package/src/app/agent-task-control.ts +187 -0
  83. package/src/app/agent-task-runtime.ts +68 -0
  84. package/src/app/agent-tool-invocations.test.ts +329 -1
  85. package/src/app/agent-tool-invocations.ts +223 -10
  86. package/src/app/agent-tool-job.test.ts +11 -1
  87. package/src/app/agent-tool-job.ts +8 -1
  88. package/src/app/auth.ts +2 -0
  89. package/src/app/builtin-tools.ts +4 -0
  90. package/src/app/oss-edition.ts +2 -0
  91. package/src/app/tool-approvals.ts +4 -0
  92. package/src/app/tool-assembly.ts +5 -0
  93. package/src/core/config/artifact-config.ts +15 -0
  94. package/src/core/config/config-codec.ts +3 -1
  95. package/src/core/config/config-models.ts +11 -1
  96. package/src/core/config/route-config.ts +3 -2
  97. package/src/core/contracts/tool-rate-limits.test.ts +59 -0
  98. package/src/core/contracts/tool-rate-limits.ts +48 -0
  99. package/src/core/contracts/tools.ts +122 -43
  100. package/src/core/contracts/types.ts +3 -1
  101. package/src/core/runtime/agent-task-control.test.ts +114 -0
  102. package/src/core/runtime/agent-task-control.ts +227 -0
  103. package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
  104. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
  105. package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
  106. package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
  107. package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
  108. package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
  109. package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
  110. package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
  111. package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
  112. package/src/infrastructure/config/configstore.ts +15 -1
  113. package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
  114. package/src/modules/usage/billing-contracts.ts +59 -0
  115. package/src/modules/usage/billing-decimal.test.ts +22 -0
  116. package/src/modules/usage/billing-decimal.ts +36 -0
  117. package/src/modules/usage/billing-external.ts +39 -0
  118. package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
  119. package/src/modules/usage/billing-ledger.test.ts +51 -0
  120. package/src/modules/usage/billing-ledger.ts +104 -0
  121. package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
  122. package/src/modules/usage/billing-presentation.test.ts +49 -0
  123. package/src/modules/usage/billing-presentation.ts +34 -0
  124. package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
  125. package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
  126. package/src/modules/usage/billing-repository.ts +463 -0
  127. package/src/modules/usage/contracts.ts +49 -0
  128. package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
  129. package/src/modules/usage/errors.ts +19 -0
  130. package/src/modules/usage/http.ts +85 -0
  131. package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
  132. package/src/modules/usage/identity.mysql.test.ts +120 -0
  133. package/src/modules/usage/identity.ts +303 -0
  134. package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
  135. package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
  136. package/src/modules/usage/model-gateway.ts +229 -0
  137. package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
  138. package/src/modules/usage/model-tool-provider.test.ts +37 -0
  139. package/src/modules/usage/model-tool-provider.ts +110 -0
  140. package/src/modules/usage/model-tools.test.ts +36 -0
  141. package/src/modules/usage/model-tools.ts +62 -0
  142. package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
  143. package/src/modules/usage/period.test.ts +26 -0
  144. package/src/modules/usage/period.ts +96 -0
  145. package/src/modules/usage/pricing.test.ts +178 -0
  146. package/src/modules/usage/pricing.ts +228 -0
  147. package/src/modules/usage/provider-failure.ts +37 -0
  148. package/src/modules/usage/provider-stream.test.ts +85 -0
  149. package/src/modules/usage/provider-stream.ts +77 -0
  150. package/src/modules/usage/provider.test.ts +67 -0
  151. package/src/modules/usage/provider.ts +142 -0
  152. package/src/modules/usage/repository.ts +539 -0
  153. package/src/modules/usage/service-availability.mysql.test.ts +68 -0
  154. package/src/modules/usage/service-availability.ts +13 -0
  155. package/src/modules/usage/service-delete.mysql.test.ts +87 -0
  156. package/src/modules/usage/stream-http.ts +32 -0
  157. package/src/modules/usage/test-harness.ts +108 -0
  158. package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
  159. package/src/modules/usage/usage-deletion.ts +119 -0
  160. package/src/modules/usage/validation.test.ts +18 -0
  161. package/src/modules/usage/validation.ts +33 -0
  162. package/src/routes/admin-agent-tasks.ts +32 -0
  163. package/src/routes/admin-billing-usage.ts +73 -0
  164. package/src/routes/admin-tool-providers.test.ts +22 -0
  165. package/src/routes/admin-tool-providers.ts +9 -1
  166. package/src/routes/admin-usage.ts +147 -0
  167. package/src/routes/admin.ts +7 -0
  168. package/src/routes/agent-api.test.ts +76 -0
  169. package/src/routes/agent-api.ts +42 -1
  170. package/src/routes/agent-artifacts.ts +29 -0
  171. package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
  172. package/src/routes/private.ts +9 -0
  173. package/src/routes/run.ts +2 -1
  174. package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
  175. package/web/connect/bailing-connect-php7.tgz +0 -0
  176. package/web/console/assets/Accounts-Bervi5JU.css +1 -0
  177. package/web/console/assets/Accounts-DnddhY6t.js +3 -0
  178. package/web/console/assets/AgentClients-VInbD7JS.js +1 -0
  179. package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
  180. package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
  181. package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
  182. package/web/console/assets/{Approvals-Bs6FGbp2.js → Approvals-34qUPHf0.js} +1 -1
  183. package/web/console/assets/{Audit-4WWYhkFM.js → Audit-BbVgkSm2.js} +1 -1
  184. package/web/console/assets/{BrandLockup-D2GhCipL.js → BrandLockup-DgscF28e.js} +1 -1
  185. package/web/console/assets/{Channels-CmoGpiCJ.js → Channels-Bp-yuk8d.js} +1 -1
  186. package/web/console/assets/{ChatEntries-BFRMtwta.js → ChatEntries-C9Ft60TS.js} +1 -1
  187. package/web/console/assets/{Clients-DGkkSXyA.js → Clients-NPldD-DD.js} +1 -1
  188. package/web/console/assets/{Cost-BmGt0MfS.js → Cost-DZcuB-EB.js} +1 -1
  189. package/web/console/assets/{Credentials-CR-sYINT.js → Credentials-RTT7N6zl.js} +1 -1
  190. package/web/console/assets/{Diagnostics-DAPbKSJp.js → Diagnostics-_LeK8cce.js} +1 -1
  191. package/web/console/assets/{Executors-CgpiT3o8.js → Executors-Bi7H8rIm.js} +1 -1
  192. package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
  193. package/web/console/assets/{Kb-Cm9dVSQw.js → Kb-BHamz8NP.js} +2 -2
  194. package/web/console/assets/{Login-CyUcsTZ_.js → Login-C1rJR-6w.js} +1 -1
  195. package/web/console/assets/{Projects-DldFPgWg.js → Projects-BRA4a48v.js} +1 -1
  196. package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
  197. package/web/console/assets/Routes-CyXV4Pba.css +1 -0
  198. package/web/console/assets/{Runs-1hxgkuR4.js → Runs-B_fa_BlD.js} +1 -1
  199. package/web/console/assets/{Setup-DBLOnI2_.js → Setup-C1_d0mFy.js} +1 -1
  200. package/web/console/assets/Shell-CHEV6RGC.js +1 -0
  201. package/web/console/assets/Shell-ykb-tUfo.css +1 -0
  202. package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
  203. package/web/console/assets/StorageBuckets-DlG3ojhA.js +1 -0
  204. package/web/console/assets/{SystemSettings-cDkudo2y.js → SystemSettings-DYo2gg6d.js} +1 -1
  205. package/web/console/assets/{SystemStatus-DZd6s8OX.js → SystemStatus-DKCoUZlq.js} +1 -1
  206. package/web/console/assets/{Targets-DYNGq1NU.js → Targets-CdkG6BPR.js} +1 -1
  207. package/web/console/assets/Tools-DU8ei6sd.css +1 -0
  208. package/web/console/assets/Tools-DVpCt0ox.js +2 -0
  209. package/web/console/assets/Usage-CAeDGjrb.css +1 -0
  210. package/web/console/assets/Usage-DWCpLugC.js +1 -0
  211. package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
  212. package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
  213. package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
  214. package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
  215. package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
  216. package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
  217. package/web/console/assets/index-H1kfa0Mj.js +2 -0
  218. package/web/console/assets/{request-B7MLvOqo.js → request-DLsP1_ot.js} +1 -1
  219. package/web/console/assets/{schema-CMuwjYdJ.js → schema-BLOHvAJQ.js} +1 -1
  220. package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
  221. package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
  222. package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
  223. package/web/console/index.html +3 -3
  224. package/web-admin/README.md +17 -0
  225. package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
  226. package/web-admin/src/components/AgentSetupPanel.vue +13 -0
  227. package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
  228. package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
  229. package/web-admin/src/components/UsageHelp.vue +72 -0
  230. package/web-admin/src/components/UsageServiceReferences.vue +169 -0
  231. package/web-admin/src/layout/Shell.vue +23 -6
  232. package/web-admin/src/pages/Accounts.vue +3 -3
  233. package/web-admin/src/pages/AgentClients.vue +3 -1
  234. package/web-admin/src/pages/AgentTasks.vue +281 -0
  235. package/web-admin/src/pages/Routes.vue +5 -1
  236. package/web-admin/src/pages/StorageBuckets.vue +6 -6
  237. package/web-admin/src/pages/Tools.vue +53 -4
  238. package/web-admin/src/pages/Usage.vue +2470 -0
  239. package/web-admin/src/pages/UsageAccess.vue +1147 -0
  240. package/web-admin/src/router.ts +10 -4
  241. package/web-admin/src/styles/base.css +57 -0
  242. package/web-admin/src/table-widths.ts +16 -1
  243. package/web-admin/src/usage-deletion.ts +40 -0
  244. package/web-admin/src/usage-management.ts +13 -0
  245. package/web-admin/src/usage-presentation.test.ts +21 -0
  246. package/web-admin/src/usage-presentation.ts +107 -0
  247. package/web-admin/src/usage-price-preview.test.ts +60 -0
  248. package/web-admin/src/usage-price-preview.ts +54 -0
  249. package/web-admin/tests/token-usage.browser.mjs +773 -0
  250. package/web-admin/tests/usage-access.browser.mjs +398 -0
  251. package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
  252. package/web/console/assets/Accounts-ChL9k-XA.js +0 -3
  253. package/web/console/assets/AgentClients-Bs7UgVDj.js +0 -1
  254. package/web/console/assets/AgentClients-DkgPTEbq.css +0 -1
  255. package/web/console/assets/Routes-DkMIjMQA.css +0 -1
  256. package/web/console/assets/Routes-DubfjlBD.js +0 -124
  257. package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
  258. package/web/console/assets/Shell-gJ5Vz_E7.js +0 -1
  259. package/web/console/assets/StorageBuckets-DkDW16tj.js +0 -1
  260. package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
  261. package/web/console/assets/Tools-A20oaMaQ.css +0 -1
  262. package/web/console/assets/Tools-DpWM59vV.js +0 -2
  263. package/web/console/assets/index-DGqs28gI.js +0 -2
@@ -0,0 +1,104 @@
1
+ import { usageAssert } from './errors';
2
+ import { assertKnownFields, integer } from './validation';
3
+ import { periodBounds } from './period';
4
+ import { usdMicros, USD_SCALE } from './billing-decimal';
5
+ import type { BillingAllowanceConfig, BillingRate, BillingGrant, PriceSnapshot, BillingPlanConfig, TokenUsage } from './billing-contracts';
6
+
7
+ export function billingKey(value: unknown, name = 'id', max = 191): string {
8
+ usageAssert(typeof value === 'string' && value.length > 0 && value.length <= max && /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/.test(value),
9
+ 'USAGE_INVALID_INPUT', `Invalid ${name}.`, 400);
10
+ return value;
11
+ }
12
+ export function validateBillingPlan(value: unknown): BillingPlanConfig {
13
+ assertKnownFields(value, ['mode','serviceIds','priceUsd','periodAllowanceUsd','multiplier','periodUnit','duration'], 'USD plan');
14
+ const c = value as BillingPlanConfig;
15
+ usageAssert(Array.isArray(c.serviceIds) && c.serviceIds.length <= 64, 'USAGE_INVALID_INPUT', 'Model services must be an explicit list.', 400);
16
+ c.serviceIds.forEach(id => billingKey(id, 'serviceId'));
17
+ usageAssert(new Set(c.serviceIds).size === c.serviceIds.length, 'USAGE_INVALID_INPUT', 'Model services must be unique.', 400);
18
+ return { ...billingAllowance(c), serviceIds: [...c.serviceIds], multiplier: validateMultiplier(c.multiplier) };
19
+ }
20
+ /** Project immutable allowance terms; model selection belongs only to the current plan. */
21
+ export function billingAllowance(value: BillingAllowanceConfig): BillingAllowanceConfig {
22
+ const c = value;
23
+ usageAssert(['credits','periodic'].includes(c.mode), 'USAGE_INVALID_INPUT', 'Choose an allowance pack or a periodic plan.', 400);
24
+ usageAssert(typeof c.priceUsd === 'number' && c.priceUsd > 0 && c.priceUsd <= 1_000_000_000, 'USAGE_INVALID_INPUT', 'priceUsd must be positive and within range.', 400);
25
+ usdMicros(c.priceUsd, 'priceUsd');
26
+ if (c.mode === 'periodic') {
27
+ usageAssert(typeof c.periodAllowanceUsd === 'number' && c.periodAllowanceUsd > 0 && c.periodAllowanceUsd <= 1_000_000_000,
28
+ 'USAGE_INVALID_INPUT', 'periodAllowanceUsd must be positive and within range for periodic plans.', 400);
29
+ usdMicros(c.periodAllowanceUsd, 'periodAllowanceUsd');
30
+ } else usageAssert(c.periodAllowanceUsd === undefined, 'USAGE_INVALID_INPUT', 'Credits plans do not accept periodAllowanceUsd.', 400);
31
+ usageAssert(c.mode === 'periodic' ? ['day','week','month'].includes(c.periodUnit ?? '') : c.periodUnit === undefined,
32
+ 'USAGE_INVALID_INPUT', 'Periodic plans require one reset schedule; allowance packs have no reset.', 400);
33
+ assertKnownFields(c.duration, ['unit','count'], 'duration');
34
+ usageAssert(['day','month','forever'].includes(c.duration.unit), 'USAGE_INVALID_INPUT', 'Unsupported duration.', 400);
35
+ usageAssert(c.duration.unit !== 'forever' || c.mode === 'credits', 'USAGE_INVALID_INPUT', 'Periodic subscriptions need an expiry.', 400);
36
+ integer(c.duration.count, 'duration.count', c.duration.unit === 'forever' ? 0 : 1, 1200);
37
+ return { mode: c.mode, priceUsd: c.priceUsd, duration: structuredClone(c.duration),
38
+ ...(c.mode === 'periodic' ? { periodAllowanceUsd: c.periodAllowanceUsd } : {}),
39
+ ...(c.periodUnit === undefined ? {} : { periodUnit: c.periodUnit }) };
40
+ }
41
+ /** Effective allowance from explicit terms; never infer periodic allowance from sale price. */
42
+ export function billingAllowanceUsd(config: BillingAllowanceConfig): number {
43
+ const terms = billingAllowance(config);
44
+ return terms.mode === 'periodic' ? terms.periodAllowanceUsd! : terms.priceUsd;
45
+ }
46
+ /** Calendar months retain the original UTC day, clamping only in shorter months. */
47
+ export function billingExpiry(startsAt: number, duration: BillingAllowanceConfig['duration']): number | null {
48
+ integer(startsAt, 'startsAt', 0, 8_000_000_000_000_000);
49
+ if (duration.unit === 'forever') return null;
50
+ if (duration.unit === 'day') return integer(startsAt + duration.count * 86_400_000, 'expiresAt');
51
+ const start = new Date(startsAt), out = new Date(startsAt);
52
+ out.setUTCDate(1); out.setUTCMonth(out.getUTCMonth() + duration.count);
53
+ out.setUTCDate(Math.min(start.getUTCDate(), new Date(Date.UTC(out.getUTCFullYear(), out.getUTCMonth() + 1, 0)).getUTCDate()));
54
+ return integer(out.getTime(), 'expiresAt');
55
+ }
56
+ export function billingPeriod(grant: Pick<BillingGrant, 'startsAt' | 'expiresAt' | 'config'>, now: number): { start: number; end: number | null } | null {
57
+ if (now < grant.startsAt || (grant.expiresAt !== null && now >= grant.expiresAt)) return null;
58
+ if (grant.config.mode === 'credits') return { start: grant.startsAt, end: grant.expiresAt };
59
+ const p = periodBounds({ unit: grant.config.periodUnit!, anchor: grant.startsAt, timezone: 'UTC' }, now)!;
60
+ return { start: p.start, end: Math.min(p.end, grant.expiresAt ?? p.end) };
61
+ }
62
+ export function tokenUsage(value: { inputTokens: number; outputTokens: number }): TokenUsage {
63
+ const inputTokens = integer(value.inputTokens, 'inputTokens'), outputTokens = integer(value.outputTokens, 'outputTokens');
64
+ return { inputTokens, outputTokens, totalTokens: integer(inputTokens + outputTokens, 'totalTokens') };
65
+ }
66
+
67
+ export function validateMultiplier(value: unknown): number {
68
+ usageAssert(typeof value === 'number' && value >= 0.000001 && value <= 1000,
69
+ 'USAGE_INVALID_INPUT', 'multiplier must be between 0.000001 and 1000.', 400);
70
+ usdMicros(value, 'multiplier'); return value;
71
+ }
72
+ export function tokenBillingRate(planId: string, planRevision: number, multiplier: number, price: PriceSnapshot): BillingRate {
73
+ billingKey(planId, 'planId'); integer(planRevision, 'planRevision', 1);
74
+ usageAssert(price?.source === 'openrouter' && price.currency === 'USD' && typeof price.modelId === 'string' && price.modelId.length > 0
75
+ && typeof price.endpointId === 'string' && price.endpointId.length > 0 && Array.isArray(price.lines) && price.lines.length > 0,
76
+ 'METERING_UNAVAILABLE', 'A verified reference price snapshot is required.', 503);
77
+ integer(price.fetchedAt, 'fetchedAt');
78
+ const lineSets = [price.lines];
79
+ if (price.tiers !== undefined) {
80
+ usageAssert(Array.isArray(price.tiers) && price.tiers.length <= 64, 'METERING_UNAVAILABLE', 'Invalid reference price tiers.', 503);
81
+ const seen = new Set<number>();
82
+ for (const tier of price.tiers) {
83
+ usageAssert(Number.isSafeInteger(tier.minPromptTokens) && tier.minPromptTokens > 0 && !seen.has(tier.minPromptTokens),
84
+ 'METERING_UNAVAILABLE', 'Reference price thresholds must be unique positive token counts.', 503);
85
+ seen.add(tier.minPromptTokens); lineSets.push(tier.lines);
86
+ }
87
+ }
88
+ for (const lines of lineSets) {
89
+ usageAssert(Array.isArray(lines) && lines.length > 0 && lines.length <= 64, 'METERING_UNAVAILABLE', 'Invalid reference price lines.', 503);
90
+ for (const line of lines) {
91
+ const validUnit = ['prompt','completion','input_cache_read','input_cache_write'].includes(line.billable) ? line.unit === 'token'
92
+ : ['input_image','output_image','input_reference'].includes(line.billable) ? ['token','image','megapixel'].includes(line.unit)
93
+ : ['request','web_search'].includes(line.billable) && line.unit === 'request';
94
+ usageAssert(validUnit, 'METERING_UNAVAILABLE', 'Invalid reference price line.', 503);
95
+ usdMicros(line.costUsd, 'costUsd');
96
+ }
97
+ }
98
+ return { planId, planRevision, multiplier: validateMultiplier(multiplier), price: structuredClone(price) };
99
+ }
100
+ /** Round a positive sub-unit charge up, never silently turn it into free usage. */
101
+ export function billedUsdMicros(referenceCostUsd: string, multiplier: number): bigint {
102
+ const product = usdMicros(referenceCostUsd) * usdMicros(validateMultiplier(multiplier));
103
+ return (product + USD_SCALE - 1n) / USD_SCALE;
104
+ }
@@ -0,0 +1,95 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createUsageTestHarness } from './test-harness';
5
+ import { getBillingRepository } from './billing-repository';
6
+ import { billingAllowance } from './billing-ledger';
7
+ import { billingPeriod } from './billing-ledger';
8
+ import type { BillingPlanConfig } from './billing-contracts';
9
+
10
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
11
+ test('customer allowance presentation uses persisted authority and all summary APIs agree', { skip: !enabled }, async t => {
12
+ const h = await createUsageTestHarness(), tokens = getBillingRepository(h.repository);
13
+ const config: BillingPlanConfig = { mode: 'credits', serviceIds: [h.service.id], priceUsd: 10_000, multiplier: 1, duration: { unit: 'month', count: 1 } };
14
+ const dbNow = async () => Number((await h.pool.query<any[]>('SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) AS ms'))[0][0].ms);
15
+ async function open(c = config, startsAt?: number) {
16
+ const user = await h.seedUser({ grant: false }), id = randomUUID();
17
+ await tokens.putPlan({ id, label: 'Synthetic allowance', expected_revision: 0, config: c });
18
+ const grant = await tokens.grant(user.accountId, { request_key: id, plan_id: id, expected_revision: 0, ...(startsAt === undefined ? {} : { starts_at: startsAt }) });
19
+ return { ...user, grant, planId: id };
20
+ }
21
+ async function allSummaries(user: { accountId: string; token: string }) {
22
+ const results = await Promise.all([
23
+ h.request('/usage/v1/model/summary', user.token),
24
+ h.request(`/admin/api/usage/billing/accounts/${user.accountId}/summary`, 'synthetic-admin'),
25
+ h.request(`/usage/v1/external/billing/accounts/${user.accountId}/summary`, h.issuerToken),
26
+ ]);
27
+ results.forEach(r => assert.equal(r.status, 200, JSON.stringify(r.body)));
28
+ assert.deepEqual(results[0]!.body.presentation, results[1]!.body.presentation);
29
+ assert.deepEqual(results[0]!.body.presentation, results[2]!.body.presentation);
30
+ return results[0]!.body;
31
+ }
32
+ try {
33
+ await t.test('no grant is unavailable, identity stays usable, removed display selector is rejected', async () => {
34
+ const user = await h.seedUser({ grant: false }), summary = await allSummaries(user);
35
+ assert.deepEqual(summary.presentation, { schema: 'bailing.usage-presentation.v1', kind: 'none', state: 'unavailable', remaining: null, total: null, displayValue: null });
36
+ const bad = await h.request('/admin/api/usage/billing/plans', 'synthetic-admin', 'POST', { id: randomUUID(), label: 'Unsupported selector', expected_revision: 0, config: { ...config, displayUnit: 'tokens' } });
37
+ assert.equal(bad.status, 400); assert.equal(h.state.calls, 0);
38
+ });
39
+ await t.test('credits reflect actual usage; pending billing does not erase balance; reads never debit or regrant', async () => {
40
+ const user = await open(), operation = randomUUID();
41
+ const result = await h.request('/usage/v1/model/requests', user.token, 'POST', { operation_id: operation, messages: [{ role: 'user', content: 'Synthetic' }] });
42
+ assert.equal(result.body.billing_state, 'pending');
43
+ await h.tokens.drainSettlements();
44
+ const saved = await h.request(`/usage/v1/model/requests/${operation}`, user.token);
45
+ assert.equal(saved.body.billed_usd, 25);
46
+ let summary = await allSummaries(user);
47
+ assert.deepEqual(summary.presentation, { schema: 'bailing.usage-presentation.v1', kind: 'credits', state: 'active', remaining: 9_975_000, total: 10_000_000, displayValue: '9975000' });
48
+ h.state.mode = 'missing_usage';
49
+ const pending = await h.request('/usage/v1/model/requests', user.token, 'POST', { operation_id: randomUUID(), messages: [{ role: 'user', content: 'Synthetic pending' }] });
50
+ assert.equal(pending.body.result_state, 'complete'); assert.equal(pending.body.billing_state, 'pending'); h.state.mode = 'ok';
51
+ summary = await allSummaries(user); assert.equal(summary.pendingRequests, 1); assert.equal(summary.presentation.displayValue, '9975000');
52
+ for (let i = 0; i < 3; i++) await allSummaries(user);
53
+ const [rows] = await h.pool.query<any[]>('SELECT (SELECT COUNT(*) FROM bz_usage_billing_grants WHERE account_id=?) AS grants,(SELECT COUNT(*) FROM bz_usage_billing_ledger WHERE account_id=?) AS ledger', [user.accountId,user.accountId]);
54
+ assert.equal(Number(rows[0].grants), 1); assert.equal(Number(rows[0].ledger), 1);
55
+ assert.equal(summary.grant.id, user.grant.id); assert.equal(summary.grant.revision, 1);
56
+ });
57
+ await t.test('template mode and conversion edits do not change an existing grant or its presentation', async () => {
58
+ const user = await open();
59
+ await tokens.putPlan({ id: user.planId, label: 'Periodic template', expected_revision: 1, config: { ...config, mode: 'periodic', periodAllowanceUsd: 123, periodUnit: 'week', multiplier: 7, priceUsd: 123 } });
60
+ const summary = await allSummaries(user);
61
+ assert.equal(summary.presentation.kind, 'credits'); assert.equal(summary.presentation.total, 10_000_000);
62
+ assert.equal(summary.grant.id, user.grant.id); assert.equal(summary.grant.planRevision, 1); assert.equal(summary.grant.revision, 1);
63
+ assert.deepEqual(summary.grant.config, billingAllowance(config));
64
+ });
65
+ await t.test('periodic projection uses current period only and clamps overage to depleted zero', async () => {
66
+ const now = await dbNow(), startsAt = now - 86_400_000 - 1000;
67
+ const user = await open({ ...config, mode: 'periodic', periodAllowanceUsd: 1000, periodUnit: 'day', priceUsd: 1000 }, startsAt);
68
+ const period = billingPeriod(user.grant, now)!;
69
+ await h.pool.execute('INSERT INTO bz_usage_billing_periods (grant_id,period_start,period_end,allowance_usd,consumed_usd) VALUES (?,?,?,?,?),(?,?,?,?,?)',
70
+ [user.grant.id,startsAt,startsAt + 86_400_000,1000,1000,user.grant.id,period.start,period.end,1000,875]);
71
+ let summary = await allSummaries(user);
72
+ assert.equal(summary.consumedUsd, 1875); assert.equal(summary.currentPeriodConsumedUsd, 875);
73
+ assert.deepEqual(summary.presentation, { schema: 'bailing.usage-presentation.v1', kind: 'percentage', state: 'active', remaining: 12.5, total: 100, displayValue: '12' });
74
+ await h.pool.execute('UPDATE bz_usage_billing_periods SET consumed_usd=1005 WHERE grant_id=? AND period_start=?', [user.grant.id,period.start]);
75
+ summary = await allSummaries(user); assert.equal(summary.presentation.state, 'depleted'); assert.equal(summary.presentation.remaining, 0); assert.equal(summary.presentation.displayValue, '0');
76
+ assert.equal(summary.overageUsd, 5);
77
+ });
78
+ await t.test('future, expired and suspended state comes from persisted grant and account with DB time', async () => {
79
+ const future = await open(config, await dbNow() + 60_000);
80
+ assert.equal((await allSummaries(future)).presentation.state, 'not_started');
81
+ const user = await open();
82
+ await h.pool.execute('UPDATE bz_usage_billing_grants SET expires_at=? WHERE id=?', [await dbNow() - 1,user.grant.id]);
83
+ let summary = await allSummaries(user); assert.equal(summary.presentation.state, 'expired'); assert.equal(summary.presentation.remaining, null); assert.equal(summary.presentation.displayValue, null);
84
+ await h.pool.execute("UPDATE bz_usage_billing_grants SET state='suspended' WHERE id=?", [user.grant.id]);
85
+ summary = await allSummaries(user); assert.equal(summary.presentation.state, 'suspended'); assert.equal(summary.presentation.remaining, null);
86
+ const account = await open();
87
+ await h.pool.execute("UPDATE bz_usage_accounts SET state='suspended' WHERE id=?", [account.accountId]);
88
+ assert.equal((await h.request('/usage/v1/model/summary', account.token)).status, 403);
89
+ const admin = await h.request(`/admin/api/usage/billing/accounts/${account.accountId}/summary`, 'synthetic-admin');
90
+ const external = await h.request(`/usage/v1/external/billing/accounts/${account.accountId}/summary`, h.issuerToken);
91
+ assert.equal(admin.body.presentation.state, 'suspended'); assert.equal(admin.body.presentation.remaining, null); assert.deepEqual(external.body.presentation, admin.body.presentation);
92
+ assert.equal((await h.request('/usage/v1/model/summary?now=0', future.token)).status, 400);
93
+ });
94
+ } finally { await h.close(); }
95
+ });
@@ -0,0 +1,49 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { usagePresentation } from './billing-presentation';
4
+ import type { BillingGrant } from './billing-contracts';
5
+
6
+ const grant: BillingGrant = { id: 'synthetic', accountId: 'synthetic', planId: 'synthetic', planRevision: 1, revision: 1,
7
+ label: 'Synthetic', state: 'active', sourceOwner: 'hub', startsAt: 1000, expiresAt: 3000,
8
+ config: { mode: 'credits', priceUsd: 1000, duration: { unit: 'day', count: 1 } } };
9
+
10
+ test('credits are a fixed display projection of USD and small positive balances are not zero', () => {
11
+ for (const [available, expected] of [[0.00029,'0.29'],[0.0011,'1.1'],[0.000001,'<0.01'],[0.000019,'0.01'],[1,'1000'],[0,'0']] as const) {
12
+ const view = usagePresentation('active', grant, available, 2000);
13
+ assert.equal(view.kind, 'credits'); assert.equal(view.displayValue, expected);
14
+ assert.equal(view.remaining, available * 1000); assert.equal(view.total, 1_000_000);
15
+ assert.equal(view.state, available ? 'active' : 'depleted');
16
+ }
17
+ });
18
+
19
+ test('periodic projection describes remaining percentage, clamps the range and distinguishes sub-one-percent', () => {
20
+ const periodic = { ...grant, config: { ...grant.config, mode: 'periodic' as const, periodAllowanceUsd: 1000, periodUnit: 'day' as const } };
21
+ for (const [available, expected] of [[1000,'100'],[125,'12'],[10,'1'],[1,'<1'],[0,'0'],[-25,'0'],[1500,'100']] as const) {
22
+ const view = usagePresentation('active', periodic, available, 2000);
23
+ assert.equal(view.kind, 'percentage'); assert.equal(view.total, 100); assert.equal(view.displayValue, expected);
24
+ assert.equal(view.remaining, Math.min(100, Math.max(0, available) / 1000 * 100));
25
+ }
26
+ });
27
+
28
+ test('no allowance and nonusable states never fabricate a zero remaining allowance', () => {
29
+ assert.deepEqual(usagePresentation('active', null, 0, 2000), {
30
+ schema: 'bailing.usage-presentation.v1', kind: 'none', state: 'unavailable', remaining: null, total: null, displayValue: null,
31
+ });
32
+ for (const [accountState, g, now, state] of [
33
+ ['active', grant, 999, 'not_started'], ['active', grant, 3000, 'expired'],
34
+ ['suspended', grant, 2000, 'suspended'], ['active', { ...grant, state: 'suspended' as const }, 2000, 'suspended'],
35
+ ['suspended', grant, 4000, 'suspended'],
36
+ ] as const) {
37
+ const view = usagePresentation(accountState, g, 1000, now);
38
+ assert.equal(view.state, state); assert.equal(view.remaining, null); assert.equal(view.displayValue, null); assert.equal(view.total, 1_000_000);
39
+ }
40
+ assert.equal(usagePresentation('active', grant, 1000, 1000).state, 'active');
41
+ assert.equal(usagePresentation('active', { ...grant, expiresAt: null }, 1000, 4000).state, 'active');
42
+ });
43
+
44
+ test('periodic percentage divides by period allowance instead of sale price', () => {
45
+ const periodic: BillingGrant = { ...grant, config: { ...grant.config, mode: 'periodic', periodUnit: 'week', priceUsd: 100, periodAllowanceUsd: 20 } };
46
+ assert.equal(usagePresentation('active', periodic, 10, 2000).remaining, 50);
47
+ assert.equal(usagePresentation('active', periodic, 10, 2000).displayValue, '50');
48
+ assert.equal(usagePresentation('active', periodic, 20, 2000).remaining, 100);
49
+ });
@@ -0,0 +1,34 @@
1
+ import { billingAllowanceUsd } from './billing-ledger';
2
+ import { USD_SCALE, usdMicros } from './billing-decimal';
3
+ import type { BillingGrant, UsagePresentation } from './billing-contracts';
4
+
5
+ /** Inputs are the original grant, locked account state and DB time used by summary. */
6
+ export function usagePresentation(accountState: string, grant: BillingGrant | null, availableUsd: number | string, now: number): UsagePresentation {
7
+ const empty: UsagePresentation = { schema: 'bailing.usage-presentation.v1', kind: 'none', state: 'unavailable', remaining: null, total: null, displayValue: null };
8
+ if (!grant) return empty;
9
+ const { config } = grant;
10
+ const kind = config.mode === 'credits' ? 'credits' : 'percentage';
11
+ const total = kind === 'credits' ? config.priceUsd * 1000 : 100;
12
+ const unavailable = (state: UsagePresentation['state']): UsagePresentation => ({ ...empty, kind, state, total });
13
+ if (accountState !== 'active' || grant.state !== 'active') return unavailable('suspended');
14
+ if (grant.expiresAt !== null && now >= grant.expiresAt) return unavailable('expired');
15
+ if (now < grant.startsAt) return unavailable('not_started');
16
+ const available = Math.max(0, Number(availableUsd));
17
+ const micros = available > 0 ? usdMicros(availableUsd) : 0n;
18
+ const state = available > 0 ? 'active' : 'depleted';
19
+ if (kind === 'credits') {
20
+ // Decimal micro-units preserve fractional charges without binary floor errors.
21
+ const hundredths = micros * 100_000n / USD_SCALE;
22
+ const fraction = String(hundredths % 100n).padStart(2, '0').replace(/0+$/, '');
23
+ const displayValue = available > 0 && hundredths === 0n ? '<0.01'
24
+ : `${hundredths / 100n}${fraction ? `.${fraction}` : ''}`;
25
+ return { ...empty, kind, state, total, remaining: available * 1000, displayValue };
26
+ }
27
+ const allowance = billingAllowanceUsd(config);
28
+ const bounded = Math.min(available, allowance);
29
+ const quotaMicros = usdMicros(allowance);
30
+ const boundedMicros = micros < quotaMicros ? micros : quotaMicros;
31
+ const wholePercent = boundedMicros * 100n / quotaMicros;
32
+ return { ...empty, kind, state, total, remaining: Math.min(100, bounded / allowance * 100),
33
+ displayValue: bounded > 0 && wholePercent === 0n ? '<1' : String(wholePercent) };
34
+ }
@@ -0,0 +1,88 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomUUID } from 'node:crypto';
3
+ import test from 'node:test';
4
+ import { usageHash } from './repository';
5
+ import { createUsageTestHarness } from './test-harness';
6
+ import type { PriceSnapshot, BillingPlanConfig, BillingRequest } from './billing-contracts';
7
+
8
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
9
+ const response = { output: 'Synthetic complete result' };
10
+ const price: PriceSnapshot = { source: 'openrouter', currency: 'USD', modelId: 'synthetic-model', endpointId: 'synthetic-endpoint', fetchedAt: 1,
11
+ lines: [{ billable: 'prompt', unit: 'token', costUsd: '0.1' }, { billable: 'completion', unit: 'token', costUsd: '0.25' }] };
12
+ async function fixture(mode: BillingPlanConfig['mode'] = 'credits', priceUsd = 100) {
13
+ const h = await createUsageTestHarness(), tokens = h.tokens;
14
+ const user = await h.identity.exchange(h.issuerToken, { request_key: randomUUID(), tenant: 'synthetic', subject: randomUUID(), service_id: h.service.id, model_access: 'token_gateway' });
15
+ const config: BillingPlanConfig = { mode, serviceIds: [h.service.id], priceUsd, multiplier: 1.5, duration: { unit: 'month', count: 1 }, ...(mode === 'periodic' ? { periodUnit: 'week', periodAllowanceUsd: priceUsd } : {}) };
16
+ const plan = await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic USD plan', expected_revision: 0, config });
17
+ const grant = await tokens.grant(user.session.accountId, { request_key: randomUUID(), plan_id: plan.id, expected_revision: 0 });
18
+ const edit = (next: BillingPlanConfig, expected_revision: number) => tokens.putPlan({ id: plan.id, label: plan.label, expected_revision, config: next });
19
+ const admit = (snapshot = price, operationId: string = randomUUID()) => tokens.admit({ actor: user.session, operationId, serviceId: h.service.id,
20
+ conversationId: null, turnId: null, requestHash: usageHash(operationId), expectedServiceRevision: h.service.revision, serviceConfig: h.service.config, model: h.service.config.model, priceSnapshot: snapshot });
21
+ const dispatch = async (snapshot = price) => tokens.commitDispatch((await admit(snapshot)).id, user.session);
22
+ const finish = (request: BillingRequest, inputTokens = 3, outputTokens = 2) => tokens.complete(request.id, request.fence!, { response, usage: { inputTokens, outputTokens } });
23
+ return { ...h, tokens, user, config, plan, grant, edit, admit, dispatch, finish };
24
+ }
25
+ for (const mode of ['credits', 'periodic'] as const) test(`USD ${mode}: immutable allowance, uniform multiplier and tiny charges`, { skip: !enabled }, async () => {
26
+ const h = await fixture(mode);
27
+ try {
28
+ const first = await h.finish(await h.dispatch());
29
+ assert.equal(first.referenceCostUsd, 0.8); assert.equal(first.billedUsd, 1.2);
30
+ assert.deepEqual(first.usage, { inputTokens: 3, outputTokens: 2, totalTokens: 5 });
31
+ assert.equal(first.billingRate.multiplier, 1.5);
32
+ await h.edit({ ...h.config, priceUsd: 9999, multiplier: 2 }, 1);
33
+ const tiny = { ...price, lines: [{ billable: 'prompt', unit: 'token' as const, costUsd: '0.000000001' }, { billable: 'completion', unit: 'token' as const, costUsd: '0.000000002' }] };
34
+ for (let i = 0; i < 10; i++) assert.equal((await h.finish(await h.dispatch(tiny), 1, 1)).billedUsd, 0.000000006);
35
+ const summary = await h.tokens.summary(h.user.session.accountId);
36
+ assert.equal(summary.consumedUsd, 1.20000006); assert.equal(summary.availableUsd, 98.79999994);
37
+ assert.deepEqual(summary.grant, h.grant); assert.equal('multiplier' in summary.grant!.config, false);
38
+ assert.equal(summary.plan!.multiplier, 2);
39
+ assert.equal(summary.presentation.displayValue, mode === 'credits' ? '98799.99' : '98');
40
+ const [ledger] = await h.pool.query<any[]>('SELECT SUM(billed_usd) AS charged,SUM(input_tokens+output_tokens) AS actual FROM bz_usage_billing_ledger WHERE grant_id=?', [h.grant.id]);
41
+ assert.equal(ledger[0].charged, '1.200000060000'); assert.equal(Number(ledger[0].actual), 25);
42
+ } finally { await h.close(); }
43
+ });
44
+ test('original price and multiplier survive edits, ACK loss and repeat completion exactly once', { skip: !enabled }, async () => {
45
+ const h = await fixture();
46
+ try {
47
+ const admitted = await h.admit();
48
+ await h.edit({ ...h.config, multiplier: 3 }, 1);
49
+ const dispatched = await h.tokens.commitDispatch(admitted.id, h.user.session);
50
+ const complete = await h.finish(dispatched); assert.equal(complete.billedUsd, 1.2);
51
+ assert.deepEqual(h.tokens.view(complete).billing_rate, admitted.billingRate);
52
+ assert.deepEqual((await h.admit({ ...price, lines: [{ billable: 'prompt', unit: 'token', costUsd: '999' }] }, admitted.operationId)).billingRate, admitted.billingRate);
53
+ await h.finish(dispatched); await h.finish(dispatched);
54
+ assert.equal((await h.tokens.summary(h.user.session.accountId)).consumedUsd, 1.2);
55
+ const [count] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger'); assert.equal(count[0].n, 1);
56
+ await assert.rejects(h.tokens.complete(dispatched.id, dispatched.fence!, { response, usage: { inputTokens: 3, outputTokens: 3 } }), { code: 'USAGE_RECEIPT_CONFLICT' });
57
+ } finally { await h.close(); }
58
+ });
59
+ test('concurrent work may slightly overrun USD allowance; subsequent work stops and missing usage stays pending', { skip: !enabled }, async () => {
60
+ const h = await fixture('credits', 2);
61
+ try {
62
+ const a = await h.dispatch(), b = await h.dispatch();
63
+ const noUsage = await h.tokens.complete(a.id, a.fence!, { response });
64
+ assert.equal(noUsage.resultState, 'complete'); assert.equal(noUsage.billedUsd, null);
65
+ assert.equal((await h.tokens.summary(h.user.session.accountId)).consumedUsd, 0);
66
+ await Promise.all([h.finish(a), h.finish(b)]);
67
+ const summary = await h.tokens.summary(h.user.session.accountId);
68
+ assert.equal(summary.consumedUsd, 2.4); assert.equal(summary.overageUsd, 0.4); assert.equal(summary.availableUsd, 0);
69
+ await assert.rejects(h.admit(), { code: 'ALLOWANCE_INSUFFICIENT' });
70
+ } finally { await h.close(); }
71
+ });
72
+ test('image accounting uses server counts, leaves tokens null, rejects changed evidence and does not trust a supplied cost', { skip: !enabled }, async () => {
73
+ const h = await fixture();
74
+ try {
75
+ const image: PriceSnapshot = { ...price, lines: [{ billable: 'output_image', unit: 'image', costUsd: '0.03', variant: '1k' }] };
76
+ const r = await h.dispatch(image);
77
+ const missing = await h.tokens.complete(r.id, r.fence!, { response });
78
+ assert.equal(missing.billingState, 'pending'); assert.equal(missing.billedUsd, null);
79
+ const rawUsage = { outputImageCount: 2, outputVariant: '1k', cost: 99999, providerExtension: 'synthetic-private-metadata' };
80
+ const done = await h.tokens.complete(r.id, r.fence!, { response, rawUsage });
81
+ assert.deepEqual(h.tokens.view(done).raw_usage, { outputImageCount: 2, outputVariant: '1k' });
82
+ assert.equal(done.usage, null); assert.equal(done.referenceCostUsd, 0.06); assert.equal(done.billedUsd, 0.09);
83
+ const again = await h.tokens.complete(r.id, r.fence!, { response, rawUsage }); assert.equal(again.billedUsd, 0.09);
84
+ await assert.rejects(h.tokens.complete(r.id, r.fence!, { response, rawUsage: { ...rawUsage, outputImageCount: 3 } }), { code: 'USAGE_RECEIPT_CONFLICT' });
85
+ const [ledger] = await h.pool.query<any[]>('SELECT input_tokens,output_tokens,billed_usd FROM bz_usage_billing_ledger');
86
+ assert.equal(ledger[0].input_tokens, null); assert.equal(ledger[0].output_tokens, null);
87
+ } finally { await h.close(); }
88
+ });
@@ -0,0 +1,181 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { createPool, type RowDataPacket } from 'mysql2/promise';
6
+ import { UsageRepository, usageHash } from './repository';
7
+ import { getUsageIdentity } from './identity';
8
+ import { getBillingRepository } from './billing-repository';
9
+ import type { BillingPlanConfig } from './billing-contracts';
10
+ import type { UsageActor, UsageService } from './contracts';
11
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
12
+ test('USD repository: shared allowance, soft overage, original settlement, lifetime and scope', { skip: !enabled }, async t => {
13
+ const db = `token_repository_${randomUUID().replaceAll('-', '')}`;
14
+ const settings = { host: '127.0.0.1', port: 16307, user: 'root', password: '', multipleStatements: true, connectionLimit: 12 };
15
+ const admin = createPool(settings); await admin.query(`CREATE DATABASE \`${db}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
16
+ const pool = createPool({ ...settings, database: db }), repo = new UsageRepository(() => pool), identity = getUsageIdentity(repo), tokens = getBillingRepository(repo);
17
+ try {
18
+ assert.equal(await tokens.ready(), false);
19
+ const migration = await readFile(new URL('../../../sql/063_usage_model_billing.sql', import.meta.url), 'utf8');
20
+ await pool.query(migration); await pool.query(migration); assert.equal(await tokens.ready(), true);
21
+ await t.test('fresh idempotent migration installs exactly the identity and USD schema', async () => {
22
+ const [tables] = await pool.query<RowDataPacket[]>('SELECT TABLE_NAME AS name FROM information_schema.tables WHERE table_schema=DATABASE()');
23
+ const expected = ['accounts','members','changes','services','issuers','users','sessions',
24
+ 'billing_plans','billing_grants','billing_heads','billing_periods','billing_requests','billing_ledger','price_snapshots'].map(name => `bz_usage_${name}`);
25
+ assert.deepEqual(tables.map(row => row.name).sort(), expected.sort());
26
+ const [columns] = await pool.query<RowDataPacket[]>("SELECT COLUMN_DEFAULT AS defaultValue,IS_NULLABLE AS nullable FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='bz_usage_sessions' AND column_name='model_access'");
27
+ assert.equal(columns.length, 1); assert.equal(columns[0]!.defaultValue, 'service'); assert.equal(columns[0]!.nullable, 'NO');
28
+ assert.equal(await identity.ready(), true);
29
+ });
30
+ const services: UsageService[] = [];
31
+ for (const id of ['alpha','beta','outside']) services.push(await repo.putService({ id, label: `Synthetic ${id}`, expectedRevision: 0,
32
+ config: { credential: 'synthetic', model: `model-${id}`, providerScope: `synthetic-${id}`, maxInputBytes: 100000, maxOutputTokens: 1000, timeoutMs: 3000 } }));
33
+ const issuer = await identity.createIssuer({ id: 'synthetic-issuer', label: 'Synthetic issuer', permissions: ['identity:exchange','identity:revoke','usage:read'], service_ids: ['alpha','beta'] });
34
+ const config: BillingPlanConfig = { mode: 'credits', serviceIds: ['alpha','beta'], priceUsd: 100, duration: { unit: 'day', count: 30 }, multiplier: 1 };
35
+ const plan = await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic allowance', expected_revision: 0, config });
36
+ async function user(modelAccess: 'service' | 'token_gateway' = 'token_gateway', planId = plan.id, startsAt?: number) {
37
+ const out = await identity.exchange(issuer.credential!, { request_key: randomUUID(), tenant: 'synthetic', subject: randomUUID(), service_id: 'alpha', ...(modelAccess === 'token_gateway' ? { model_access: modelAccess } : {}) });
38
+ const grant = await tokens.grant(out.session.accountId, { request_key: randomUUID(), plan_id: planId, expected_revision: 0, ...(startsAt === undefined ? {} : { starts_at: startsAt }) });
39
+ return { actor: out.session, grant };
40
+ }
41
+ async function admit(actor: UsageActor, serviceId = 'alpha', operationId: string = randomUUID()) {
42
+ const svc = services.find(s => s.id === serviceId)!;
43
+ return tokens.admit({ actor, operationId, serviceId, conversationId: null, turnId: null, requestHash: usageHash([operationId, serviceId]), expectedServiceRevision: svc.revision, serviceConfig: svc.config, model: svc.config.model, priceSnapshot: { source: 'openrouter', currency: 'USD', modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: Date.now(), lines: [{ billable: 'prompt', unit: 'token', costUsd: '1' }, { billable: 'completion', unit: 'token', costUsd: '1' }] } });
44
+ }
45
+ const response = { choices: [{ message: { role: 'assistant', content: 'Synthetic result' } }] };
46
+ await t.test('multiple models share Token pool; finish admitted response and block next; replay exact evidence', async () => {
47
+ const { actor } = await user();
48
+ const a = await admit(actor), b = await admit(actor, 'beta');
49
+ const [pa,pb] = await Promise.all([tokens.commitDispatch(a.id, actor), tokens.commitDispatch(b.id, actor)]);
50
+ await assert.rejects(tokens.commitDispatch(a.id, actor), { code: 'USAGE_PENDING' });
51
+ await tokens.complete(a.id, pa.fence!, { response, usage: { inputTokens: 20, outputTokens: 40 } });
52
+ const receipt = { response, usage: { inputTokens: 30, outputTokens: 40 }, executionId: 'synthetic-unique' };
53
+ const settled = await tokens.complete(b.id, pb.fence!, receipt);
54
+ assert.equal(settled.billedUsd, 70); assert.equal(settled.overageUsd, 30);
55
+ assert.equal((await tokens.complete(b.id, pb.fence!, receipt)).revision, settled.revision);
56
+ const summary = await tokens.summary(actor.accountId);
57
+ assert.equal(summary.availableUsd, 0); assert.equal(summary.consumedUsd, 130); assert.equal(summary.overageUsd, 30);
58
+ await assert.rejects(admit(actor), { code: 'ALLOWANCE_INSUFFICIENT' });
59
+ const duplicate = await admit(actor, 'beta', b.operationId); assert.equal(duplicate.created, false);
60
+ await assert.rejects(tokens.complete(b.id, pb.fence!, { response, usage: { inputTokens: 1, outputTokens: 1 } }), { code: 'USAGE_RECEIPT_CONFLICT' });
61
+ await assert.rejects(tokens.complete(b.id, pb.fence!, { ...receipt, executionId: 'different-execution' }), { code: 'USAGE_RECEIPT_CONFLICT' });
62
+ const view = tokens.view(settled); assert.equal('serviceConfig' in view, false); assert.equal('fence' in view, false); assert.deepEqual(view.response, response);
63
+ assert.equal('response' in tokens.view(settled, settled.createdAt + 8 * 86_400_000), false);
64
+ });
65
+ await t.test('result complete without usage remains usable; delayed usage settles once, unknown never redispatches', async () => {
66
+ const { actor } = await user(), a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
67
+ const completed = await tokens.complete(a.id, p.fence!, { response });
68
+ assert.equal(completed.resultState, 'complete'); assert.equal(completed.billingState, 'pending');
69
+ assert.deepEqual(tokens.view(completed).response, response); assert.equal((await tokens.summary(actor.accountId)).pendingRequests, 1);
70
+ const finished = await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 12, outputTokens: 3 } });
71
+ assert.equal(finished.billingState, 'settled');
72
+ const b = await admit(actor), q = await tokens.commitDispatch(b.id, actor);
73
+ await tokens.markUnknown(b.id, q.fence!, 'connection_lost');
74
+ assert.equal((await tokens.findRequest(actor, b.operationId))!.resultState, 'unknown');
75
+ assert.equal((await admit(actor, 'alpha', b.operationId)).created, false);
76
+ await assert.rejects(tokens.commitDispatch(b.id, actor), { code: 'USAGE_PENDING' });
77
+ await tokens.complete(b.id, q.fence!, { response, usage: { inputTokens: 4, outputTokens: 1 } });
78
+ assert.equal((await tokens.summary(actor.accountId)).consumedUsd, 20);
79
+ });
80
+ await t.test('plan CAS and grant snapshots preserve old requests and late settlement across replacement', async () => {
81
+ const { actor, grant } = await user(), a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
82
+ const edited = await tokens.putPlan({ id: plan.id, label: 'Edited template', expected_revision: plan.revision, config: { ...config, priceUsd: 300 } });
83
+ assert.equal((await tokens.summary(actor.accountId)).grant!.config.priceUsd, 100);
84
+ await assert.rejects(tokens.putPlan({ id: plan.id, label: 'Stale', expected_revision: 1, config }), { code: 'USAGE_REVISION_CONFLICT' });
85
+ const requestKey = randomUUID(), body = { request_key: requestKey, plan_id: edited.id, expected_revision: grant.revision };
86
+ const replacement = await tokens.grant(actor.accountId, body);
87
+ assert.equal((await tokens.grant(actor.accountId, body)).id, replacement.id);
88
+ await assert.rejects(tokens.grant(actor.accountId, { ...body, plan_id: 'other' }), { code: 'USAGE_IDEMPOTENCY_CONFLICT' });
89
+ await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 20, outputTokens: 10 } });
90
+ assert.equal((await tokens.summary(actor.accountId)).availableUsd, 300);
91
+ const [old] = await pool.query<RowDataPacket[]>('SELECT consumed_usd FROM bz_usage_billing_periods WHERE grant_id=?', [grant.id]);
92
+ assert.equal(Number(old[0]!.consumed_usd), 30);
93
+ await assert.rejects(tokens.control(actor.accountId, { request_key: randomUUID(), expected_revision: replacement.revision, state: 'suspended' }, 'external'), { code: 'USAGE_SOURCE_CONFLICT' });
94
+ const before = await admit(actor);
95
+ await tokens.control(actor.accountId, { request_key: randomUUID(), expected_revision: replacement.revision, state: 'suspended' });
96
+ await assert.rejects(tokens.commitDispatch(before.id, actor), { code: 'SERVICE_NOT_ENTITLED' });
97
+ assert.equal((await tokens.findRequest(actor, a.operationId))!.billedUsd, 30);
98
+ });
99
+ await t.test('settlement storage failure preserves usable reply and original-request reconciliation', async () => {
100
+ const { actor } = await user(), a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
101
+ const transact = repo.withTransaction.bind(repo); let calls = 0;
102
+ repo.withTransaction = async fn => { calls++; if (calls === 2) throw new Error('synthetic_settlement_storage_unavailable'); return transact(fn); };
103
+ let pending;
104
+ try { pending = await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 20, outputTokens: 10 } }); }
105
+ finally { repo.withTransaction = transact; }
106
+ assert.equal(calls, 2); assert.equal(pending.billingState, 'pending'); assert.equal(pending.resultState, 'complete'); assert.deepEqual(tokens.view(pending).response, response);
107
+ const [before] = await pool.query<RowDataPacket[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger WHERE request_id=?', [a.id]); assert.equal(Number(before[0]!.n), 0);
108
+ await tokens.reconcilePendingUsage();
109
+ const [reconciled] = await pool.query<RowDataPacket[]>('SELECT billing_state FROM bz_usage_billing_requests WHERE id=?', [a.id]); assert.equal(reconciled[0]!.billing_state, 'settled');
110
+ const restored = await tokens.findRequest(actor, a.operationId); assert.equal(restored!.billingState, 'settled'); assert.equal(restored!.billedUsd, 30);
111
+ await tokens.findRequest(actor, a.operationId);
112
+ const [after] = await pool.query<RowDataPacket[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger WHERE request_id=?', [a.id]); assert.equal(Number(after[0]!.n), 1);
113
+ });
114
+ await t.test('cancel before dispatch costs zero; late canceled completion settles but cannot return executable tools', async () => {
115
+ const { actor } = await user(), a = await admit(actor);
116
+ assert.equal((await tokens.cancel(actor, a.operationId)).billedUsd, 0);
117
+ await assert.rejects(tokens.commitDispatch(a.id, actor), { code: 'USAGE_PENDING' });
118
+ const b = await admit(actor), p = await tokens.commitDispatch(b.id, actor);
119
+ await tokens.cancel(actor, b.operationId);
120
+ const late = await tokens.complete(b.id, p.fence!, { response: { tool_calls: [{ id: 'never-execute' }] }, usage: { inputTokens: 8, outputTokens: 2 } });
121
+ assert.equal(late.state, 'cancelled'); assert.equal(late.billingState, 'settled'); assert.equal('response' in tokens.view(late), false);
122
+ assert.equal((await tokens.summary(actor.accountId)).consumedUsd, 10);
123
+ });
124
+ await t.test('service/issuer scope, member revocation and template service changes are checked again at dispatch', async () => {
125
+ const old = await user('service'); await assert.rejects(admit(old.actor, 'beta'), { code: 'USAGE_ACCOUNT_FORBIDDEN' });
126
+ const { actor } = await user(); await assert.rejects(admit(actor, 'outside'), { code: 'SERVICE_NOT_ENTITLED' });
127
+ const a = await admit(actor);
128
+ await pool.query("UPDATE bz_usage_members SET state='revoked' WHERE account_id=? AND user_id=?", [actor.accountId, actor.userId]);
129
+ await assert.rejects(tokens.commitDispatch(a.id, actor), { code: 'USAGE_ACCOUNT_FORBIDDEN' });
130
+ const fresh = await user(), b = await admit(fresh.actor);
131
+ await pool.query("UPDATE bz_usage_services SET state='suspended',revision=revision+1 WHERE id='alpha'");
132
+ await assert.rejects(tokens.commitDispatch(b.id, fresh.actor), { code: 'USAGE_REVISION_CONFLICT' });
133
+ await pool.query("UPDATE bz_usage_services SET state='active',revision=1 WHERE id='alpha'");
134
+ });
135
+ await t.test('late usage belongs to original anchored period; current period is fresh, expiry stops admission', async () => {
136
+ await tokens.putPlan({ id: 'daily', label: 'Synthetic daily', expected_revision: 0, config: { ...config, mode: 'periodic', periodAllowanceUsd: 100, periodUnit: 'day', duration: { unit: 'day', count: 3 } } });
137
+ const dbNow = async () => Number((await pool.query<RowDataPacket[]>('SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) AS ms'))[0][0]!.ms);
138
+ const { actor, grant } = await user('token_gateway', 'daily', await dbNow() - 86_400_000 + 1200);
139
+ const a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
140
+ await new Promise(resolve => setTimeout(resolve, 1250));
141
+ await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 110, outputTokens: 20 } });
142
+ const summary = await tokens.summary(actor.accountId);
143
+ assert.equal(summary.currentPeriodConsumedUsd, 0); assert.equal(summary.availableUsd, 100); assert.equal(summary.consumedUsd, 130);
144
+ const b = await admit(actor); assert.notEqual(b.periodStart, a.periodStart);
145
+ await pool.query('UPDATE bz_usage_billing_grants SET expires_at=? WHERE id=?', [await dbNow() - 1, grant.id]);
146
+ const expired = await tokens.summary(actor.accountId);
147
+ assert.equal(expired.availableUsd, 0); assert.equal(expired.presentation.state, 'expired'); assert.equal(expired.presentation.remaining, null);
148
+ });
149
+ await t.test('same optional coordinates support more than 256 model requests without a turn record', async () => {
150
+ const { actor } = await user();
151
+ for (let index = 0; index < 260; index++) {
152
+ const a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
153
+ await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 0, outputTokens: 0 } });
154
+ }
155
+ assert.equal((await tokens.summary(actor.accountId)).consumedUsd, 0);
156
+ const page = await tokens.listRequests(actor.accountId, { limit: 25 }); assert.equal(page.items.length, 25); assert.ok(page.next_cursor);
157
+ const next = await tokens.listRequests(actor.accountId, { limit: 25, cursor: page.next_cursor });
158
+ assert.equal(new Set([...page.items,...next.items].map(x => x.operation_id)).size, 50);
159
+ const [tables] = await pool.query<RowDataPacket[]>('SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE()');
160
+ assert.equal(tables.length, 14, 'Only identity/account/model and USD accounting tables are installed.');
161
+ });
162
+ await t.test('supplier execution cannot settle two requests; expired reply body is purged without losing audit identity', async () => {
163
+ const { actor } = await user(), a = await admit(actor), b = await admit(actor);
164
+ const pa = await tokens.commitDispatch(a.id, actor), pb = await tokens.commitDispatch(b.id, actor);
165
+ const receipt = { response, usage: { inputTokens: 5, outputTokens: 5 }, executionId: 'unique-supplier-receipt' };
166
+ await tokens.complete(a.id, pa.fence!, receipt);
167
+ await assert.rejects(tokens.complete(b.id, pb.fence!, receipt), { code: 'USAGE_RECEIPT_CONFLICT' });
168
+ const oldTime = Date.now() - 8 * 86_400_000;
169
+ await pool.query('UPDATE bz_usage_billing_requests SET created_at=? WHERE id=?', [oldTime, a.id]);
170
+ await tokens.cleanupExpiredResponses();
171
+ const restored = (await tokens.findRequest(actor, a.operationId))!;
172
+ assert.equal(restored.response, null); assert.equal(restored.billedUsd, 10); assert.ok(restored.resultHash);
173
+ const publicView = tokens.view(restored); assert.equal(publicView.response_expired, true); assert.equal(publicView.dispatch, 'completed');
174
+ assert.equal('response' in publicView, false); assert.equal('resultHash' in publicView, false);
175
+ const other = await user(); assert.equal(await tokens.findRequest(other.actor, a.operationId), null);
176
+ await assert.rejects(tokens.listRequests(other.actor.accountId, { cursor: a.id }), { code: 'USAGE_INVALID_INPUT' });
177
+ });
178
+ } finally {
179
+ await pool.end(); await admin.query(`DROP DATABASE \`${db}\``); await admin.end();
180
+ }
181
+ });