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,221 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomUUID } from 'node:crypto';
3
+ import test from 'node:test';
4
+ import { getBillingRepository } from './billing-repository';
5
+ import { usageHash } from './repository';
6
+ import { createUsageTestHarness } from './test-harness';
7
+ import type { UsageActor, UsageService } from './contracts';
8
+ import type { PriceSnapshot, BillingPlanConfig } from './billing-contracts';
9
+
10
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
11
+ const response = { choices: [{ message: { role: 'assistant', content: 'Synthetic result' } }] };
12
+ const admin = 'synthetic-admin';
13
+ async function fixture(mode: BillingPlanConfig['mode'] = 'credits') {
14
+ const h = await createUsageTestHarness(), tokens = getBillingRepository(h.repository);
15
+ const user = await h.identity.exchange(h.issuerToken, { request_key: randomUUID(), tenant: 'synthetic', subject: randomUUID(),
16
+ service_id: h.service.id, model_access: 'token_gateway' });
17
+ const config: BillingPlanConfig = { mode, serviceIds: [h.service.id], priceUsd: 1000, multiplier: 1,
18
+ duration: { unit: 'month', count: 2 }, ...(mode === 'periodic' ? { periodUnit: 'week', periodAllowanceUsd: 1000 } : {}) };
19
+ const plan = await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic allowance', expected_revision: 0, config });
20
+ const grantBody = { request_key: randomUUID(), plan_id: plan.id, expected_revision: 0 };
21
+ const original = await tokens.grant(user.session.accountId, grantBody);
22
+ const model = (id: string) => h.repository.putService({ id, label: `Synthetic ${id}`, expectedRevision: 0, config: { ...h.service.config, model: `model-${id}` } });
23
+ const edit = (config: BillingPlanConfig, expected_revision: number, state: 'active' | 'suspended' = 'active') =>
24
+ tokens.putPlan({ id: plan.id, label: plan.label, expected_revision, state, config });
25
+ const priceSnapshot: PriceSnapshot = { source:'openrouter',modelId:'synthetic/model',endpointId:'synthetic-endpoint',currency:'USD',fetchedAt:Date.now(),lines:[{billable:'prompt',unit:'token',costUsd:'1'},{billable:'completion',unit:'token',costUsd:'1'}] };
26
+ const admit = (service: UsageService = h.service, actor: UsageActor = user.session, operationId: string = randomUUID()) =>
27
+ tokens.admit({ actor, operationId, serviceId: service.id, conversationId: 'synthetic-conversation', turnId: 'synthetic-turn',
28
+ requestHash: usageHash(operationId), expectedServiceRevision: service.revision, serviceConfig: service.config, model: service.config.model, priceSnapshot });
29
+ const remove = (service: UsageService = h.service) => h.repository.deleteService({ id: service.id, expectedRevision: service.revision, requestId: randomUUID(), actor: admin });
30
+ const finish = async (service: UsageService = h.service) => {
31
+ const r = await admit(service), dispatched = await tokens.commitDispatch(r.id, user.session);
32
+ return tokens.complete(r.id, dispatched.fence!, { response, usage: { inputTokens: 20, outputTokens: 5 } });
33
+ };
34
+ return { ...h, tokens, user, config, plan, grantBody, original, model, edit, admit, remove, finish };
35
+ }
36
+
37
+ for (const mode of ['credits', 'periodic'] as const) test(`dynamic ${mode} plan: add B through same credential, share balance, keep original allowance and dates`, { skip: !enabled }, async () => {
38
+ const h = await fixture(mode);
39
+ try {
40
+ const b = await h.model('new-model');
41
+ await assert.rejects(h.admit(b), { code: 'SERVICE_NOT_ENTITLED', details: { next_action: 'select_model' } });
42
+ await h.finish();
43
+ const before = await h.tokens.summary(h.user.session.accountId);
44
+ const edited = await h.edit({ ...h.config, serviceIds: [h.service.id, b.id], priceUsd: 9000,
45
+ duration: { unit: 'month', count: 9 }, ...(mode === 'periodic' ? { periodUnit: 'day' } : {}) }, 1);
46
+ const current = await h.tokens.summary(h.user.session.accountId);
47
+ assert.deepEqual(current.grant, h.original); assert.deepEqual(current.grant, before.grant);
48
+ assert.equal(current.resetAt, before.resetAt); assert.equal(current.expiresAt, before.expiresAt);
49
+ assert.equal(current.availableUsd, 975);
50
+ assert.deepEqual(current.plan, { id: h.plan.id, label: h.plan.label, revision: edited.revision, serviceIds: [h.service.id, b.id], multiplier: 1 });
51
+ const sent = await h.finish(b);
52
+ assert.equal('serviceIds' in sent.grantConfig, false); assert.equal('serviceIds' in current.grant!.config, false);
53
+ const summary = await h.tokens.summary(h.user.session.accountId);
54
+ assert.equal(summary.availableUsd, 950); assert.equal(summary.consumedUsd, 50);
55
+ assert.equal(summary.grant!.revision, h.original.revision); assert.equal(summary.resetAt, before.resetAt);
56
+ const [issuer] = await h.pool.query<any[]>('SELECT service_ids_json FROM bz_usage_issuers WHERE id=?', ['synthetic-product']);
57
+ assert.deepEqual(issuer[0].service_ids_json, [h.service.id]);
58
+ const [raw] = await h.pool.query<any[]>('SELECT config_json FROM bz_usage_billing_grants WHERE id=?', [h.original.id]);
59
+ assert.equal('serviceIds' in raw[0].config_json, false);
60
+ } finally { await h.close(); }
61
+ });
62
+
63
+ test('dynamic plan: paused plan only prevents new grants; empty and missing directories never use a grant snapshot', { skip: !enabled }, async () => {
64
+ const h = await fixture();
65
+ try {
66
+ await h.edit(h.config, 1, 'suspended');
67
+ await h.finish();
68
+ const second = await h.seedUser({ grant: false });
69
+ await assert.rejects(h.tokens.grant(second.accountId, { request_key: randomUUID(), plan_id: h.plan.id, expected_revision: 0 }), { code: 'SERVICE_NOT_ENTITLED' });
70
+ const admitted = await h.admit();
71
+ await h.edit({ ...h.config, serviceIds: [] }, 2, 'suspended');
72
+ await assert.rejects(h.tokens.commitDispatch(admitted.id, h.user.session), { code: 'SERVICE_NOT_ENTITLED' });
73
+ await assert.rejects(h.admit(), { code: 'SERVICE_NOT_ENTITLED' });
74
+ assert.deepEqual((await h.tokens.summary(h.user.session.accountId)).plan!.serviceIds, []);
75
+ await h.pool.query('DELETE FROM bz_usage_billing_plans WHERE id=?', [h.plan.id]);
76
+ assert.equal((await h.tokens.summary(h.user.session.accountId)).plan, null);
77
+ await assert.rejects(h.admit(), { code: 'SERVICE_NOT_ENTITLED' });
78
+ assert.deepEqual((await h.tokens.summary(h.user.session.accountId)).grant, h.original);
79
+ } finally { await h.close(); }
80
+ });
81
+
82
+ test('service delete removes all plan selections atomically, keeps grant/periods and previews impact with exact totals', { skip: !enabled }, async () => {
83
+ const h = await fixture();
84
+ try {
85
+ const b = await h.model('second-model');
86
+ await h.edit({ ...h.config, serviceIds: [h.service.id, b.id] }, 1);
87
+ await h.tokens.putPlan({ id: 'paused-plan', label: 'Paused template', expected_revision: 0, state: 'suspended', config: h.config });
88
+ await h.finish();
89
+ const before = await h.tokens.summary(h.user.session.accountId);
90
+ const [periodsBefore] = await h.pool.query<any[]>('SELECT * FROM bz_usage_billing_periods');
91
+ const [grantBefore] = await h.pool.query<any[]>('SELECT * FROM bz_usage_billing_grants WHERE id=?', [h.original.id]);
92
+ const preview = await h.repository.serviceReferences(h.service.id);
93
+ assert.equal(preview.deletable, true); assert.equal(preview.plans.total, 2); assert.equal(preview.accounts.total, 1); assert.equal(preview.requests.total, 1);
94
+ assert.deepEqual(preview.accounts.items[0]!.serviceIds, [h.service.id, b.id]);
95
+ assert(!JSON.stringify(preview).includes('serviceConfig')); assert(!JSON.stringify(preview).includes('requestHash'));
96
+ const receipt = await h.remove();
97
+ assert.equal(receipt.affected_plan_count, 2); assert.equal(receipt.affected_account_count, 1); assert.equal(receipt.affected_request_count, 1);
98
+ const plans = await h.tokens.listPlans();
99
+ assert.deepEqual(plans.find(p => p.id === h.plan.id)!.config.serviceIds, [b.id]);
100
+ assert.equal(plans.find(p => p.id === h.plan.id)!.revision, 3);
101
+ assert.deepEqual(plans.find(p => p.id === 'paused-plan')!.config.serviceIds, []);
102
+ assert.equal(plans.find(p => p.id === 'paused-plan')!.revision, 2);
103
+ const [periodsAfter] = await h.pool.query<any[]>('SELECT * FROM bz_usage_billing_periods');
104
+ const [grantAfter] = await h.pool.query<any[]>('SELECT * FROM bz_usage_billing_grants WHERE id=?', [h.original.id]);
105
+ assert.deepEqual(periodsAfter, periodsBefore); assert.deepEqual(grantAfter, grantBefore);
106
+ assert.equal((await h.tokens.summary(h.user.session.accountId)).availableUsd, before.availableUsd);
107
+ await h.finish(b); await h.remove(b);
108
+ const after = await h.tokens.summary(h.user.session.accountId);
109
+ assert.deepEqual(after.plan!.serviceIds, []); assert.equal(after.availableUsd, 950); assert.deepEqual(after.grant, h.original);
110
+ await assert.rejects(h.repository.putService({ ...h.service, expectedRevision: 2 }), { code: 'USAGE_SERVICE_DELETED' });
111
+ } finally { await h.close(); }
112
+ });
113
+
114
+ test('service delete fences unissued work but preserves dispatched/unknown/cancelled evidence and late settlement', { skip: !enabled }, async () => {
115
+ const h = await fixture();
116
+ try {
117
+ const unsent = await h.admit(), a = await h.admit(), b = await h.admit(), completed = await h.admit();
118
+ const pa = await h.tokens.commitDispatch(a.id, h.user.session), pb = await h.tokens.commitDispatch(b.id, h.user.session);
119
+ const pc = await h.tokens.commitDispatch(completed.id, h.user.session);
120
+ await h.tokens.markUnknown(a.id, pa.fence!, 'synthetic_confirmation_lost');
121
+ await h.tokens.cancel(h.user.session, b.operationId);
122
+ await h.tokens.complete(completed.id, pc.fence!, { response });
123
+ const receipt = await h.remove(); assert.equal(receipt.affected_request_count, 4);
124
+ await assert.rejects(h.tokens.commitDispatch(unsent.id, h.user.session), { code: 'SERVICE_NOT_ENTITLED' });
125
+ const restored = await h.tokens.findRequest(h.user.session, a.operationId); assert.equal(restored?.state, 'unknown');
126
+ await h.tokens.complete(a.id, pa.fence!, { response, usage: { inputTokens: 20, outputTokens: 5 } });
127
+ await h.tokens.complete(b.id, pb.fence!, { response: { tool_calls: [{ id: 'never-execute' }] }, usage: { inputTokens: 10, outputTokens: 5 } });
128
+ const late = await h.tokens.findRequest(h.user.session, b.operationId);
129
+ assert.equal(late?.state, 'cancelled'); assert.equal('response' in h.tokens.view(late!), false);
130
+ const complete = await h.tokens.complete(completed.id, pc.fence!, { response, usage: { inputTokens: 5, outputTokens: 5 } });
131
+ assert.equal(complete.billingState, 'settled'); assert.equal((await h.tokens.summary(h.user.session.accountId)).consumedUsd, 50);
132
+ await h.tokens.findRequest(h.user.session, completed.operationId);
133
+ assert.equal((await h.tokens.summary(h.user.session.accountId)).consumedUsd, 50);
134
+ assert.equal((await h.tokens.cancel(h.user.session, unsent.operationId)).billedUsd, 0);
135
+ const other = await h.seedUser({ grant: false });
136
+ assert.equal(await h.tokens.findRequest(other.actor, a.operationId), null);
137
+ await assert.rejects(h.tokens.cancel(other.actor, a.operationId), { code: 'USAGE_OPERATION_NOT_FOUND' });
138
+ } finally { await h.close(); }
139
+ });
140
+
141
+ test('grant snapshots and idempotent receipts never override current plan model selections', { skip: !enabled }, async () => {
142
+ const h = await fixture();
143
+ try {
144
+ const r = await h.admit();
145
+ await h.pool.query("UPDATE bz_usage_billing_grants SET config_json=JSON_SET(config_json,'$.serviceIds',JSON_ARRAY('unselected')) WHERE id=?", [h.original.id]);
146
+ await h.pool.query("UPDATE bz_usage_billing_requests SET grant_json=JSON_SET(grant_json,'$.serviceIds',JSON_ARRAY('unselected')) WHERE id=?", [r.id]);
147
+ await h.pool.query("UPDATE bz_usage_changes SET result_json=JSON_SET(result_json,'$.config.serviceIds',JSON_ARRAY('unselected')) WHERE JSON_UNQUOTE(JSON_EXTRACT(result_json,'$.id'))=?", [h.original.id]);
148
+ const summary = await h.tokens.summary(h.user.session.accountId);
149
+ assert.deepEqual(summary.grant, h.original); assert.deepEqual(summary.plan!.serviceIds, [h.service.id]);
150
+ assert.equal('serviceIds' in (await h.tokens.findRequest(h.user.session, r.operationId))!.grantConfig, false);
151
+ assert.deepEqual(await h.tokens.grant(h.user.session.accountId, h.grantBody), h.original);
152
+ const controlBody = { request_key: randomUUID(), expected_revision: 1, state: 'suspended' };
153
+ const suspended = await h.tokens.control(h.user.session.accountId, controlBody);
154
+ await h.pool.query("UPDATE bz_usage_changes SET result_json=JSON_SET(result_json,'$.config.serviceIds',JSON_ARRAY('unselected')) WHERE JSON_UNQUOTE(JSON_EXTRACT(result_json,'$.id'))=?", [h.original.id]);
155
+ assert.deepEqual(await h.tokens.control(h.user.session.accountId, controlBody), suspended);
156
+ } finally { await h.close(); }
157
+ });
158
+
159
+ test('dynamic plan permissions: single-service credential remains bounded; discarded account-model endpoint is gone', { skip: !enabled }, async () => {
160
+ const h = await fixture();
161
+ try {
162
+ const b = await h.model('selected-b'); await h.edit({ ...h.config, serviceIds: [h.service.id, b.id] }, 1);
163
+ const single = await h.identity.exchange(h.issuerToken, { request_key: randomUUID(), tenant: 'synthetic', subject: randomUUID(), service_id: h.service.id, model_access: 'service' });
164
+ await h.tokens.grant(single.session.accountId, { request_key: randomUUID(), plan_id: h.plan.id, expected_revision: 0 });
165
+ await assert.rejects(h.admit(b, single.session), { code: 'USAGE_ACCOUNT_FORBIDDEN' });
166
+ assert.equal((await h.request(`/admin/api/usage/services/${h.service.id}/references`, 'synthetic-auditor')).status, 403);
167
+ assert.equal((await h.request(`/admin/api/usage/services/${h.service.id}/references`, admin)).status, 200);
168
+ assert.equal((await h.request(`/admin/api/usage/billing/accounts/${h.user.session.accountId}/models`, admin, 'POST', {})).status, 404);
169
+ assert.equal((await h.request('/admin/api/usage/billing/plans', 'synthetic-auditor', 'POST', { id: h.plan.id, label: h.plan.label, expected_revision: 2, config: h.config })).status, 403);
170
+ await h.pool.query("UPDATE bz_usage_members SET state='revoked' WHERE account_id=? AND user_id=?", [h.user.session.accountId, h.user.session.userId]);
171
+ await assert.rejects(h.admit(b), { code: 'USAGE_ACCOUNT_FORBIDDEN' });
172
+ } finally { await h.close(); }
173
+ });
174
+
175
+ test('concurrent model deletion and plan creation/edits leave no selectable deleted identity; deletion permits original completion', { skip: !enabled }, async () => {
176
+ const h = await fixture();
177
+ try {
178
+ for (let i = 0; i < 5; i++) {
179
+ const service = await h.model(`race-${i}`);
180
+ const results = await Promise.allSettled([
181
+ h.tokens.putPlan({ id: `race-plan-${i}`, label: 'Concurrent template', expected_revision: 0, config: { ...h.config, serviceIds: [service.id] } }),
182
+ h.remove(service),
183
+ ]);
184
+ assert.equal(results[1]!.status, 'fulfilled', JSON.stringify(results));
185
+ if (results[0]!.status === 'rejected') assert.equal(results[0]!.reason.code, 'USAGE_SERVICE_NOT_FOUND');
186
+ const p = (await h.tokens.listPlans()).find(p => p.id === `race-plan-${i}`);
187
+ if (p) assert.deepEqual(p.config.serviceIds, []);
188
+ assert.equal(await h.repository.getService(service.id), null);
189
+ }
190
+ const r = await h.admit(), p = await h.tokens.commitDispatch(r.id, h.user.session);
191
+ const results = await Promise.allSettled([
192
+ h.edit({ ...h.config, priceUsd: 3000 }, 1),
193
+ h.remove(),
194
+ h.tokens.complete(r.id, p.fence!, { response, usage: { inputTokens: 20, outputTokens: 5 } }),
195
+ ]);
196
+ assert.equal(results[1]!.status, 'fulfilled', JSON.stringify(results)); assert.equal(results[2]!.status, 'fulfilled', JSON.stringify(results));
197
+ if (results[0]!.status === 'rejected') assert(['USAGE_SERVICE_NOT_FOUND','USAGE_REVISION_CONFLICT'].includes(results[0]!.reason.code));
198
+ const summary = await h.tokens.summary(h.user.session.accountId);
199
+ assert.deepEqual(summary.plan!.serviceIds, []); assert.deepEqual(summary.grant, h.original); assert.equal(summary.availableUsd, 975);
200
+ } finally { await h.close(); }
201
+ });
202
+
203
+ test('one plan multiplier applies to all models while original requests retain their accepted USD price snapshot', { skip: !enabled }, async () => {
204
+ const h = await fixture();
205
+ try {
206
+ const second = await h.model('shared-multiplier');
207
+ await h.edit({ ...h.config, serviceIds:[h.service.id, second.id], multiplier:1.5 }, 1);
208
+ const original = await h.admit();
209
+ await h.edit({ ...h.config, serviceIds:[h.service.id, second.id], multiplier:2 }, 2);
210
+ const sent = await h.tokens.commitDispatch(original.id, h.user.session);
211
+ const completed = await h.tokens.complete(original.id, sent.fence!, {response, usage:{inputTokens:20,outputTokens:5}});
212
+ assert.equal(completed.referenceCostUsd,25);
213
+ assert.equal(completed.billedUsd,37.5);
214
+ assert.equal(completed.billingRate.multiplier,1.5);
215
+ const next = await h.finish(second);
216
+ assert.equal(next.referenceCostUsd,25);
217
+ assert.equal(next.billedUsd,50);
218
+ assert.equal(next.billingRate.multiplier,2);
219
+ assert.equal((await h.tokens.summary(h.user.session.accountId)).availableUsd,912.5);
220
+ } finally {await h.close();}
221
+ });
@@ -0,0 +1,19 @@
1
+ export class UsageError extends Error {
2
+ constructor(
3
+ public readonly code: string,
4
+ message: string,
5
+ public readonly status = 409,
6
+ public readonly details?: Record<string, unknown>,
7
+ ) {
8
+ super(message);
9
+ this.name = "UsageError";
10
+ }
11
+ }
12
+ export function usageAssert(
13
+ condition: unknown,
14
+ code: string,
15
+ message: string,
16
+ status = 409,
17
+ ): asserts condition {
18
+ if (!condition) throw new UsageError(code, message, status);
19
+ }
@@ -0,0 +1,85 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { PayloadTooLargeError, readBody, send } from '../../app/http';
3
+ import { UsageError, usageAssert } from './errors';
4
+ import { authenticateUsageIssuerRequest, authenticateUsageRequest, getUsageIdentity, usageFields, usageKey } from './identity';
5
+ import type { UsageRepository } from './repository';
6
+
7
+ export interface UsageApiDeps { usage: UsageRepository | null | undefined }
8
+ export const USAGE_CAPABILITIES = { schema: 'bailing.usage.v1', supported: true, modes: ['credits', 'periodic'],
9
+ streaming: true, orchestration: 'host', business_authorization_unchanged: true } as const;
10
+
11
+ export function usageHttpError(res: ServerResponse, error: unknown, context: { dispatch?: 'not_dispatched' | 'unknown'; next_action?: string; operation_id?: string } = {}): void {
12
+ const known = error instanceof UsageError, invalid = error instanceof PayloadTooLargeError || error instanceof SyntaxError;
13
+ const code = known ? error.code : invalid ? 'USAGE_INVALID_INPUT' : 'USAGE_UNAVAILABLE';
14
+ const dispatch = context.dispatch ?? (known && !['USAGE_PENDING','RECONCILIATION_REQUIRED'].includes(code) || invalid ? 'not_dispatched' : 'unknown');
15
+ const resetAt = known ? error.details?.resetAt ?? error.details?.reset_at : undefined;
16
+ const actions: Record<string, string> = {
17
+ USAGE_UPGRADE_REQUIRED: 'upgrade_required', USAGE_IDENTITY_REQUIRED: 'reauthenticate', USAGE_IDENTITY_EXPIRED: 'reauthenticate', USAGE_ISSUER_REQUIRED: 'contact_operator',
18
+ USAGE_ACCOUNT_FORBIDDEN: 'contact_operator', USAGE_ACCOUNT_SUSPENDED: 'contact_operator', SERVICE_NOT_ENTITLED: 'contact_operator', SUBSCRIPTION_EXPIRED: 'contact_operator',
19
+ ALLOWANCE_INSUFFICIENT: 'contact_operator', QUOTA_WINDOW_EXHAUSTED: Number.isSafeInteger(resetAt) ? 'wait_for_reset' : 'contact_operator',
20
+ METERING_UNAVAILABLE: 'retry_original', USAGE_UNAVAILABLE: 'retry_original', USAGE_UNSUPPORTED: 'upgrade_required',
21
+ USAGE_OPERATION_ENDED: 'inspect_original',
22
+ USAGE_PRICE_NOT_CONFIGURED: 'contact_operator', USAGE_PRICE_UNAVAILABLE: 'contact_operator', USAGE_PRICE_UNSUPPORTED: 'contact_operator',
23
+ MODEL_TOOL_ADAPTER_NOT_READY: 'contact_operator',
24
+ };
25
+ const next_action = dispatch === 'unknown' ? 'inspect_original' : context.next_action
26
+ ?? (known && error.details?.next_action === 'select_model' ? 'select_model' : actions[code] ?? 'resolve_error');
27
+ const message = known ? error.message : invalid ? '请求格式不正确或超过大小限制。' : '用量服务暂时不可用,请保留原请求重试。';
28
+ const feedback = { schema: 'bailing.usage-feedback.v1', origin: 'hub_usage', code, dispatch, next_action, retryable: dispatch === 'not_dispatched' && next_action === 'retry_original',
29
+ ...(known && error.details?.input_limit ? { input_limit: error.details.input_limit } : {}),
30
+ ...(Number.isSafeInteger(resetAt) ? { resetAt, reset_at: resetAt } : {}), ...(context.operation_id ? { operation_id: context.operation_id } : {}) };
31
+ send(res, known ? error.status : error instanceof PayloadTooLargeError ? 413 : invalid ? 400 : 503,
32
+ { ...feedback, schema: 'bailing.usage-error.v1', error: code, message, feedback,
33
+ ...(known && code === 'USAGE_RESOURCE_IN_USE' && Array.isArray(error.details?.blockers) ? { blockers: error.details.blockers } : {}) });
34
+ }
35
+ export function usagePage(query: URLSearchParams, allow: readonly string[] = []): { limit: number; cursor: string | null } {
36
+ const fields = ['limit', 'cursor', ...allow];
37
+ for (const key of query.keys()) usageAssert(fields.includes(key) && query.getAll(key).length === 1, 'USAGE_INVALID_INPUT', '查询字段不正确。', 400);
38
+ const rawLimit = query.get('limit') ?? '30';
39
+ usageAssert(/^\d+$/.test(rawLimit), 'USAGE_INVALID_INPUT', '分页大小不正确。', 400);
40
+ const limit = Number(rawLimit); usageAssert(limit >= 1 && limit <= 100, 'USAGE_INVALID_INPUT', '分页大小必须为 1–100。', 400);
41
+ const cursor = query.get('cursor');
42
+ if (cursor !== null) usageAssert(/^[A-Za-z0-9_-]{1,1024}$/.test(cursor), 'USAGE_INVALID_INPUT', '分页游标不正确。', 400);
43
+ return { limit, cursor };
44
+ }
45
+ export function usageRevision(value: unknown): number {
46
+ usageAssert(Number.isSafeInteger(value) && Number(value) >= 0, 'USAGE_INVALID_INPUT', '需要非负整数修订。', 400); return Number(value);
47
+ }
48
+ export function usageRequestKey(body: Record<string, unknown>): string { return usageKey(body.request_key, 'request_key'); }
49
+
50
+ /** Public usage surface intentionally never authenticates admin/client/Agent credentials. */
51
+ export async function handleUsageApiFor(deps: UsageApiDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
52
+ const path = url.pathname, method = req.method ?? 'GET';
53
+ if (!path.startsWith('/usage/v1/') || path.startsWith('/usage/v1/model/')) return false;
54
+ try {
55
+ if (path === '/usage/v1/capabilities' && method === 'GET') {
56
+ const { getBillingRepository } = await import('./billing-repository');
57
+ const { MODEL_GATEWAY_CAPABILITIES } = await import('./model-gateway');
58
+ const ready = Boolean(deps.usage && await getUsageIdentity(deps.usage).ready() && await getBillingRepository(deps.usage).ready());
59
+ send(res, 200, { ...USAGE_CAPABILITIES, supported: ready, model_gateway: { ...MODEL_GATEWAY_CAPABILITIES, supported: ready } }); return true;
60
+ }
61
+ usageAssert(deps.usage, 'USAGE_UNSUPPORTED', '此实例未配置用量模块。', 503);
62
+ const repository = deps.usage, identity = getUsageIdentity(repository);
63
+ usageAssert(await identity.ready(), 'USAGE_UNSUPPORTED', '用量模块尚未就绪,请核对版本与迁移。', 503);
64
+ if (path === '/usage/v1/sessions/exchange' && method === 'POST') {
65
+ const { token } = await authenticateUsageIssuerRequest(identity, req, 'identity:exchange');
66
+ send(res, 200, await identity.exchange(token, await readBody(req, 8192))); return true;
67
+ }
68
+ if (path === '/usage/v1/external/users/revoke' && method === 'POST') {
69
+ const { issuer } = await authenticateUsageIssuerRequest(identity, req, 'identity:revoke');
70
+ await identity.revokeExternalUser(issuer, await readBody(req, 4096)); send(res, 200, { revoked: true }); return true;
71
+ }
72
+ if (path.startsWith('/usage/v1/external/billing/')) {
73
+ const { handleExternalBillingUsage } = await import('./billing-external');
74
+ if (await handleExternalBillingUsage(repository, req, res, url)) return true;
75
+ }
76
+ if (path === '/usage/v1/session' && method === 'GET') {
77
+ const actor = await authenticateUsageRequest(identity, req);
78
+ send(res, 200, { schema: 'bailing.usage-session.v1', session: actor });
79
+ } else if (path === '/usage/v1/sessions/revoke' && method === 'POST') {
80
+ const actor = await authenticateUsageRequest(identity, req);
81
+ usageFields(await readBody(req, 1024), []); await identity.revokeSession(actor); send(res, 200, { revoked: true });
82
+ } else send(res, 404, { error: 'not_found' });
83
+ } catch (error) { usageHttpError(res, error); }
84
+ return true;
85
+ }
@@ -0,0 +1,286 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createServer } from 'node:http';
5
+ import { once } from 'node:events';
6
+ import type { AddressInfo } from 'node:net';
7
+ import { createUsageTestHarness } from './test-harness';
8
+ import { UsageRepository, usageHash } from './repository';
9
+ import type { PriceSnapshot } from './billing-contracts';
10
+ import { getBillingRepository } from './billing-repository';
11
+ import { handleUsageApiFor } from './http';
12
+
13
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
14
+ type Harness = Awaited<ReturnType<typeof createUsageTestHarness>>;
15
+ function deferred() {
16
+ let resolve!: () => void;
17
+ const promise = new Promise<void>(r => { resolve = r; });
18
+ return { promise, resolve };
19
+ }
20
+ /** Pause one real SQL boundary; all HTTP, transactions and locking still use MySQL. */
21
+ function sqlGate(h: Harness, matches: (sql: string, args: any[]) => boolean, after = false, fail = false) {
22
+ const entered = deferred(), release = deferred();
23
+ const original = h.pool.getConnection.bind(h.pool);
24
+ let armed = true;
25
+ const errors: string[] = [];
26
+ h.pool.getConnection = (async () => {
27
+ const connection = await original();
28
+ return new Proxy(connection, { get(target, key) {
29
+ const value = Reflect.get(target, key);
30
+ if (key !== 'query' && key !== 'execute') return typeof value === 'function' ? value.bind(target) : value;
31
+ return async (...args: any[]) => {
32
+ try {
33
+ const selected = armed && matches(String(args[0]), args[1] ?? []);
34
+ if (selected) {
35
+ armed = false;
36
+ if (after) {
37
+ const result = await value.apply(target, args); entered.resolve(); await release.promise;
38
+ if (fail) throw new Error('synthetic_cleanup_unavailable');
39
+ return result;
40
+ }
41
+ entered.resolve(); await release.promise;
42
+ if (fail) throw new Error('synthetic_cleanup_unavailable');
43
+ }
44
+ return await value.apply(target, args);
45
+ } catch (error) { errors.push(String((error as { code?: string }).code ?? error)); throw error; }
46
+ };
47
+ } });
48
+ }) as typeof h.pool.getConnection;
49
+ return { errors, entered: entered.promise, release: release.resolve, restore() { release.resolve(); h.pool.getConnection = original; } };
50
+ }
51
+ const identityInsert = (state: string) => (sql: string, args: any[]) => sql.startsWith('INSERT INTO bz_usage_users') && args[5] === state;
52
+ const sessionCleanup = (sql: string) => sql.startsWith("UPDATE bz_usage_sessions SET state='revoked' WHERE user_id=");
53
+ function input(h: Harness, subject = randomUUID(), extra: Record<string, unknown> = {}) {
54
+ return { request_key: randomUUID(), tenant: 'synthetic', subject, generation: 'original', service_id: h.service.id, ...extra };
55
+ }
56
+ const exact = (body: ReturnType<typeof input>) => ({ tenant: body.tenant, subject: body.subject, generation: body.generation });
57
+ const exchange = (h: Harness, body: ReturnType<typeof input>, token = h.issuerToken) => h.request('/usage/v1/sessions/exchange', token, 'POST', body);
58
+ const revoke = (h: Harness, body: ReturnType<typeof input>, token = h.issuerToken) => h.request('/usage/v1/external/users/revoke', token, 'POST', exact(body));
59
+ async function stored(h: Harness, body: ReturnType<typeof input>) {
60
+ const [rows] = await h.pool.query<any[]>('SELECT id,state FROM bz_usage_users WHERE issuer_id=? AND tenant_key=? AND subject_key=? AND generation_key=?', ['synthetic-product', body.tenant, body.subject, body.generation]);
61
+ return rows[0];
62
+ }
63
+ async function noActiveSessions(h: Harness, userId: string) {
64
+ const [rows] = await h.pool.query<any[]>("SELECT COUNT(*) AS n FROM bz_usage_sessions WHERE user_id=? AND state='active'", [userId]);
65
+ assert.equal(Number(rows[0].n), 0);
66
+ }
67
+
68
+ test('usage revocation: durable exact-generation fence and account-first concurrency through real HTTP/MySQL', { skip: !enabled, timeout: 120_000 }, async t => {
69
+ const h = await createUsageTestHarness();
70
+ try {
71
+ await t.test('unknown identity revocation persists without creating an account, allowance or credential', async () => {
72
+ const body = input(h);
73
+ assert.deepEqual((await revoke(h, body)).body, { revoked: true });
74
+ const tombstone = await stored(h, body); assert.equal(tombstone.state, 'suspended');
75
+ assert.equal((await revoke(h, body)).status, 200); assert.equal((await stored(h, body)).id, tombstone.id);
76
+ for (const retry of [body, { ...body, request_key: randomUUID() }]) {
77
+ const result = await exchange(h, retry); assert.equal(result.status, 403); assert.equal(result.body.code, 'USAGE_ACCOUNT_SUSPENDED');
78
+ }
79
+ const [counts] = await h.pool.query<any[]>('SELECT (SELECT COUNT(*) FROM bz_usage_accounts) AS accounts,(SELECT COUNT(*) FROM bz_usage_sessions) AS sessions,(SELECT COUNT(*) FROM bz_usage_billing_plans) AS plans,(SELECT COUNT(*) FROM bz_usage_billing_grants) AS grants');
80
+ assert.deepEqual(Object.values(counts[0]).map(Number), [0, 0, 0, 0]);
81
+ });
82
+ await t.test('first exchange delayed before identity persistence cannot revive a revocation that already acknowledged', async () => {
83
+ const body = input(h), gate = sqlGate(h, identityInsert('active'));
84
+ try {
85
+ const pending = exchange(h, body); await gate.entered;
86
+ assert.equal((await revoke(h, body)).status, 200);
87
+ gate.release(); const late = await pending;
88
+ assert.equal(late.status, 403); assert.equal(late.body.code, 'USAGE_ACCOUNT_SUSPENDED');
89
+ const user = await stored(h, body); assert.equal(user.state, 'suspended'); await noActiveSessions(h, user.id);
90
+ } finally { gate.restore(); }
91
+ });
92
+ await t.test('revocation between identity creation and first account transaction prevents account creation', async () => {
93
+ const body = input(h), gate = sqlGate(h, sql => sql === 'SELECT id,state FROM bz_usage_users WHERE id=? FOR UPDATE');
94
+ try {
95
+ const pending = exchange(h, body); await gate.entered;
96
+ const initial = await stored(h, body); assert.equal(initial.state, 'active');
97
+ assert.equal((await revoke(h, body)).status, 200);
98
+ gate.release(); assert.equal((await pending).status, 403);
99
+ const [members] = await h.pool.query<any[]>('SELECT account_id FROM bz_usage_members WHERE user_id=?', [initial.id]);
100
+ assert.equal(members.length, 0); await noActiveSessions(h, initial.id);
101
+ } finally { gate.restore(); }
102
+ });
103
+ await t.test('exchange committing first is revoked with original account and session records retained', async () => {
104
+ const body = input(h), gate = sqlGate(h, sql => sql.startsWith('INSERT INTO bz_usage_sessions'), true);
105
+ try {
106
+ const pendingExchange = exchange(h, body); await gate.entered;
107
+ const pendingRevoke = revoke(h, body);
108
+ gate.release(); const [issued, revoked] = await Promise.all([pendingExchange, pendingRevoke]);
109
+ assert.equal(issued.status, 200); assert.equal(revoked.status, 200);
110
+ assert.equal((await h.request('/usage/v1/session', issued.body.credential)).status, 401);
111
+ assert.equal((await exchange(h, body)).status, 401);
112
+ assert.equal((await exchange(h, { ...body, request_key: randomUUID() })).status, 403);
113
+ const [records] = await h.pool.query<any[]>('SELECT s.id,s.account_id,s.state,a.id AS retained_account FROM bz_usage_sessions s JOIN bz_usage_accounts a ON a.id=s.account_id WHERE s.id=?', [issued.body.session.sessionId]);
114
+ assert.equal(records[0].id, issued.body.session.sessionId); assert.equal(records[0].state, 'revoked'); assert.equal(records[0].retained_account, issued.body.session.accountId);
115
+ } finally { gate.restore(); }
116
+ });
117
+ await t.test('committed tombstone blocks exchange, authentication and model dispatch before session cleanup completes', async () => {
118
+ const user = await h.seedUser(), body = input(h, user.subject, { generation: '' });
119
+ const gate = sqlGate(h, sql => sql.startsWith('SELECT account_id FROM bz_usage_members WHERE user_id=? ORDER BY account_id'));
120
+ try {
121
+ const pending = revoke(h, body); await gate.entered;
122
+ assert.equal((await stored(h, body)).state, 'suspended');
123
+ const [sessions] = await h.pool.query<any[]>('SELECT state FROM bz_usage_sessions WHERE id=?', [user.actor.sessionId]); assert.equal(sessions[0].state, 'active');
124
+ assert.equal((await h.request('/usage/v1/session', user.token)).body.code, 'USAGE_ACCOUNT_SUSPENDED');
125
+ assert.equal((await exchange(h, body)).status, 403);
126
+ const calls = h.state.calls;
127
+ const denied = await h.request('/usage/v1/model/requests', user.token, 'POST', { operation_id: randomUUID(), messages: [{ role: 'user', content: 'Synthetic fenced request.' }] });
128
+ assert.equal(denied.status, 403); assert.equal(denied.body.code, 'USAGE_ACCOUNT_SUSPENDED'); assert.equal(h.state.calls, calls);
129
+ gate.release(); assert.equal((await pending).status, 200);
130
+ } finally { gate.restore(); }
131
+ });
132
+ await t.test('session cleanup failure is reported, but the durable fence survives and exact retry finishes cleanup', async () => {
133
+ const user = await h.seedUser(), body = input(h, user.subject, { generation: '' }), gate = sqlGate(h, sessionCleanup, false, true);
134
+ try {
135
+ const pending = revoke(h, body); await gate.entered; gate.release();
136
+ const failed = await pending; assert.equal(failed.status, 503); assert.equal(failed.body.code, 'USAGE_UNAVAILABLE');
137
+ } finally { gate.restore(); }
138
+ assert.equal((await stored(h, body)).state, 'suspended');
139
+ assert.equal((await h.request('/usage/v1/session', user.token)).body.code, 'USAGE_ACCOUNT_SUSPENDED');
140
+ assert.equal((await exchange(h, body)).status, 403);
141
+ const [before] = await h.pool.query<any[]>('SELECT * FROM bz_usage_billing_ledger WHERE account_id=? ORDER BY id', [user.accountId]);
142
+ assert.equal((await revoke(h, body)).status, 200); assert.equal((await h.request('/usage/v1/session', user.token)).status, 401);
143
+ const [after] = await h.pool.query<any[]>('SELECT * FROM bz_usage_billing_ledger WHERE account_id=? ORDER BY id', [user.accountId]); assert.deepEqual(after, before);
144
+ });
145
+ await t.test('fresh HTTP runtime sees tombstone; issuer, tenant and generation stay isolated', async () => {
146
+ const body = input(h); assert.equal((await revoke(h, body)).status, 200);
147
+ const repository = new UsageRepository(() => h.pool);
148
+ const server = createServer(async (req, res) => { await handleUsageApiFor({ usage: repository }, req, res, new URL(req.url!, 'http://localhost')); }).listen(0, '127.0.0.1');
149
+ await once(server, 'listening');
150
+ try {
151
+ const result = await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}/usage/v1/sessions/exchange`, { method: 'POST', headers: { authorization: `Bearer ${h.issuerToken}`, 'content-type': 'application/json' }, body: JSON.stringify(body) });
152
+ assert.equal(result.status, 403); assert.equal((await result.json() as any).code, 'USAGE_ACCOUNT_SUSPENDED');
153
+ } finally { server.close(); server.closeAllConnections(); }
154
+ const otherIssuer = await h.identity.createIssuer({ id: `issuer-${randomUUID()}`, label: 'Other synthetic product', permissions: ['identity:exchange'], service_ids: [h.service.id] });
155
+ const others = [await exchange(h, { ...body, request_key: randomUUID(), tenant: 'other' }), await exchange(h, { ...body, request_key: randomUUID(), generation: 'reassigned' }), await exchange(h, body, otherIssuer.credential!)];
156
+ for (const result of others) assert.equal(result.status, 200, JSON.stringify(result.body));
157
+ assert.equal(new Set(others.map(result => result.body.session.userId)).size, 3);
158
+ assert.equal((await stored(h, body)).state, 'suspended');
159
+ });
160
+ await t.test('shared-account authentication and exchange use account-first locks without a deadlock retry', async () => {
161
+ const user = await h.seedUser(), key = randomUUID();
162
+ const organization = await h.repository.createAccount({ requestId: key, sourceId: key, sourceOwner: 'synthetic-admin', kind: 'organization', label: 'Synthetic shared account', userId: user.actor.userId });
163
+ await h.pool.query('UPDATE bz_usage_issuers SET account_ids_json=? WHERE id=?', [JSON.stringify([organization.id]), 'synthetic-product']);
164
+ const body = input(h, user.subject, { generation: '', account_id: organization.id });
165
+ const initial = await exchange(h, body); assert.equal(initial.status, 200);
166
+ const authGate = sqlGate(h, sql => sql.includes('FROM bz_usage_sessions s JOIN bz_usage_users u'));
167
+ let accountGate: ReturnType<typeof sqlGate> | undefined;
168
+ try {
169
+ const authenticating = h.request('/usage/v1/session', initial.body.credential); await authGate.entered;
170
+ accountGate = sqlGate(h, (sql, args) => sql === 'SELECT id FROM bz_usage_accounts WHERE id=? FOR UPDATE' && args[0] === organization.id);
171
+ const exchanging = exchange(h, { ...body, request_key: randomUUID() }); await accountGate.entered;
172
+ accountGate.release(); authGate.release();
173
+ const [authenticated, exchanged] = await Promise.all([authenticating, exchanging]);
174
+ assert.equal(authenticated.status, 200); assert.equal(exchanged.status, 200, JSON.stringify(exchanged.body));
175
+ assert.equal(exchanged.body.session.accountId, organization.id); assert.equal(exchanged.body.session.userId, user.actor.userId);
176
+ assert.deepEqual([...authGate.errors, ...accountGate.errors], []);
177
+ } finally { accountGate?.restore(); authGate.restore(); }
178
+ assert.equal((await revoke(h, body)).status, 200);
179
+ assert.equal((await h.request('/usage/v1/session', user.token)).status, 401);
180
+ assert.equal((await h.request('/usage/v1/session', initial.body.credential)).status, 401);
181
+ });
182
+ await t.test('revocation refuses an un-dispatched request and retains original dispatched billing evidence', async () => {
183
+ const user = await h.seedUser(), body = input(h, user.subject, { generation: '' }), tokens = getBillingRepository(h.repository);
184
+ const priceSnapshot: PriceSnapshot = {source:'openrouter',modelId:'synthetic/model',endpointId:'synthetic-endpoint',currency:'USD',fetchedAt:Date.now(),lines:[{billable:'prompt',unit:'token',costUsd:'1'},{billable:'completion',unit:'token',costUsd:'1'}]};
185
+ const admit = () => tokens.admit({ priceSnapshot, actor: user.actor, serviceId: h.service.id, conversationId: 'original-operation', turnId: null,
186
+ operationId: randomUUID(), requestHash: usageHash(randomUUID()), model: h.service.config.model,
187
+ serviceConfig: h.service.config, expectedServiceRevision: h.service.revision });
188
+ const first = await admit(), dispatched = await tokens.commitDispatch(first.id, user.actor);
189
+ await tokens.markUnknown(first.id, dispatched.fence!, 'synthetic_response_lost');
190
+ const second = await admit();
191
+ assert.equal((await revoke(h, body)).status, 200);
192
+ await assert.rejects(tokens.commitDispatch(second.id, user.actor), (error: any) => ['USAGE_IDENTITY_EXPIRED', 'USAGE_ACCOUNT_SUSPENDED'].includes(error.code));
193
+ const [before] = await h.pool.query<any[]>('SELECT id,state,fence,request_hash,account_id,user_id,session_id FROM bz_usage_billing_requests WHERE id=?', [first.id]);
194
+ assert.equal(before[0].state, 'unknown'); assert.equal(before[0].fence, dispatched.fence);
195
+ const receipt = { response: { text: 'Synthetic original result' }, usage: { inputTokens: 20, outputTokens: 5 } };
196
+ const settled = await tokens.complete(first.id, dispatched.fence!, receipt); assert.equal(settled.billedUsd, 25);
197
+ assert.equal((await tokens.complete(first.id, dispatched.fence!, receipt)).billedUsd, 25);
198
+ const [after] = await h.pool.query<any[]>('SELECT id,state,fence,request_hash,account_id,user_id,session_id FROM bz_usage_billing_requests WHERE id=?', [first.id]);
199
+ assert.deepEqual({ ...after[0], state: 'unknown' }, before[0]);
200
+ const [charges] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger WHERE account_id=?', [user.accountId]);
201
+ assert.equal(Number(charges[0].n), 1);
202
+ });
203
+ await t.test('simultaneous first exchanges serialize on one real identity and return one original personal account', async () => {
204
+ const body = input(h), gate = sqlGate(h, sql => sql.includes('ON DUPLICATE KEY UPDATE change_key=change_key'), true);
205
+ let followerGate: ReturnType<typeof sqlGate> | undefined;
206
+ try {
207
+ const first = exchange(h, body); await gate.entered;
208
+ followerGate = sqlGate(h, identityInsert('active'));
209
+ const follower = exchange(h, { ...body, request_key: randomUUID() }); await followerGate.entered;
210
+ followerGate.release(); gate.release();
211
+ const [a, b] = await Promise.all([first, follower]);
212
+ assert.equal(a.status, 200); assert.equal(b.status, 200);
213
+ assert.equal(a.body.session.userId, b.body.session.userId); assert.equal(a.body.session.accountId, b.body.session.accountId);
214
+ assert.deepEqual((await exchange(h, body)).body, a.body);
215
+ const [members] = await h.pool.query<any[]>('SELECT account_id FROM bz_usage_members WHERE user_id=?', [a.body.session.userId]);
216
+ assert.equal(members.length, 1); assert.deepEqual([...gate.errors, ...followerGate.errors], []);
217
+ } finally { followerGate?.restore(); gate.restore(); }
218
+ });
219
+ await t.test('different first identities reserve independent account keys without gap-lock deadlocks', async () => {
220
+ const capture = sqlGate(h, () => false);
221
+ try {
222
+ const bodies = Array.from({ length: 24 }, () => input(h));
223
+ const results = await Promise.all(bodies.map(body => exchange(h, body)));
224
+ for (const result of results) assert.equal(result.status, 200, JSON.stringify(result.body));
225
+ assert.equal(new Set(results.map(result => result.body.session.userId)).size, 24);
226
+ assert.equal(new Set(results.map(result => result.body.session.accountId)).size, 24);
227
+ assert.deepEqual(capture.errors, []);
228
+ } finally { capture.restore(); }
229
+ });
230
+ await t.test('failed account creation rolls back its placeholder; the original key can retry and rejects changed input', async () => {
231
+ const user = await h.seedUser(), body = { request_key: randomUUID(), source_id: randomUUID(), kind: 'organization', label: 'Synthetic rollback account', user_id: user.actor.userId };
232
+ const key = usageHash(['account:hub', body.request_key]);
233
+ const [before] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_accounts');
234
+ const gate = sqlGate(h, sql => sql.startsWith('INSERT INTO bz_usage_members'), true, true);
235
+ try {
236
+ const pending = h.request('/admin/api/usage/accounts', 'synthetic-admin', 'POST', body); await gate.entered; gate.release();
237
+ assert.equal((await pending).status, 503);
238
+ } finally { gate.restore(); }
239
+ const [changes] = await h.pool.query<any[]>('SELECT change_key FROM bz_usage_changes WHERE change_key=?', [key]); assert.equal(changes.length, 0);
240
+ const [after] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_accounts'); assert.deepEqual(after, before);
241
+ const created = await h.request('/admin/api/usage/accounts', 'synthetic-admin', 'POST', body); assert.equal(created.status, 200);
242
+ assert.deepEqual((await h.request('/admin/api/usage/accounts', 'synthetic-admin', 'POST', body)).body, created.body);
243
+ assert.equal((await h.request('/admin/api/usage/accounts', 'synthetic-admin', 'POST', { ...body, label: 'Changed input' })).body.code, 'USAGE_IDEMPOTENCY_CONFLICT');
244
+ const [saved] = await h.pool.query<any[]>("SELECT JSON_TYPE(result_json) AS kind FROM bz_usage_changes WHERE change_key=?", [key]); assert.equal(saved[0].kind, 'OBJECT');
245
+ });
246
+ await t.test('identity persistence never holds the source while waiting for an existing user lock', async () => {
247
+ const body = input(h); assert.equal((await exchange(h, body)).status, 200);
248
+ const user = await stored(h, body), held = await h.pool.getConnection();
249
+ const gate = sqlGate(h, identityInsert('suspended'));
250
+ let pending: ReturnType<typeof revoke> | undefined;
251
+ try {
252
+ await held.query('SET SESSION innodb_lock_wait_timeout=1');
253
+ await held.beginTransaction();
254
+ await held.query('SELECT id FROM bz_usage_users WHERE id=? FOR UPDATE', [user.id]);
255
+ pending = revoke(h, body); await gate.entered;
256
+ // The exchange/dispatch path already owns this user before checking its
257
+ // source. A concurrent identity upsert must not hold the inverse lock.
258
+ await held.query('SELECT id FROM bz_usage_issuers WHERE id=? FOR UPDATE', ['synthetic-product']);
259
+ await held.commit(); gate.release();
260
+ assert.equal((await pending).status, 200);
261
+ assert.deepEqual(gate.errors, []);
262
+ assert.equal((await stored(h, body)).state, 'suspended');
263
+ await noActiveSessions(h, user.id);
264
+ } finally {
265
+ await held.rollback(); gate.release();
266
+ if (pending) await pending;
267
+ await held.query('SET SESSION innodb_lock_wait_timeout=50'); held.release(); gate.restore();
268
+ }
269
+ });
270
+ await t.test('competing first exchanges and revocations converge without a live credential or false success', async () => {
271
+ const capture = sqlGate(h, () => false);
272
+ try {
273
+ for (let round = 0; round < 50; round++) {
274
+ const body = input(h), outcomes = await Promise.all(Array.from({ length: 6 }, (_, i) => i % 3 === round % 3 ? revoke(h, body) : exchange(h, { ...body, request_key: i % 2 ? body.request_key : randomUUID() })));
275
+ for (const result of outcomes) assert.ok([200, 401, 403].includes(result.status), JSON.stringify(result.body));
276
+ assert.equal((await revoke(h, body)).status, 200);
277
+ const user = await stored(h, body); assert.equal(user.state, 'suspended'); await noActiveSessions(h, user.id);
278
+ for (const result of outcomes) if (result.body.credential) assert.equal((await h.request('/usage/v1/session', result.body.credential)).status, 401);
279
+ }
280
+ assert.equal(capture.errors.filter(code => code === 'ER_LOCK_DEADLOCK').length, 0);
281
+ const [pending] = await h.pool.query<any[]>("SELECT COUNT(*) AS n FROM bz_usage_changes WHERE JSON_TYPE(result_json)='NULL'"); assert.equal(Number(pending[0].n), 0);
282
+ } finally { capture.restore(); }
283
+ });
284
+ assert.equal(h.state.calls, 0, 'identity tests never invoke a model');
285
+ } finally { await h.close(); }
286
+ });