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,54 @@
1
+ # v0.9.0 model billing: paired upgrade guide
2
+
3
+ Upgrade public Core 0.8.0 / SDK 0.6.0 / DSH 0.6.0 to Core 0.9.0 / SDK 0.7.0 / DSH 0.7.0. Verify versions, Tags and artifact digests when downloading or deploying, and retain original configuration and durable records.
4
+
5
+ ## Choose what to enable
6
+
7
+ | Need | Console and Core | Host or business backend |
8
+ | --- | --- | --- |
9
+ | Retain business tools, approvals and long tasks | Upgrade Core and retain configuration/state | Existing workflows continue without enabling model billing |
10
+ | Offer a shared model plan | Configure provider connections, reference mappings and USD plans; grant accounts access | Hosts adopt discovery, model catalogs and summaries; trusted backends provide plan-scoped identity when needed |
11
+ | Generate images from a local assistant | Configure a supported adapter and price, then include it in the plan | Adopt tool discovery, durable original requests and asynchronous lookup; using images in business data remains a separate action |
12
+ | Provision plans from the business application | Configure source ownership and permissions | Trusted backends use external billing APIs with idempotency keys; payment, currency conversion and refunds remain application responsibilities |
13
+ | Remove/restore accounts or manually reset allowance | Administrators act under the required permissions and account state | Existing summaries suffice; these management features do not independently require SDK/DSH or backend changes |
14
+
15
+ ## Backup and migration
16
+
17
+ Retain the database, instance configuration and keys, object storage, previous artifacts, and host credentials, sessions and durable records. Coordinate all Core instances and writers sharing the state database. Preserve IDs and evidence for dispatched requests; do not replace recovery with another request.
18
+
19
+ From public 0.8.0, apply all outstanding files through the official migrator (`npm run db:init` for source installations), then start the new Core. Startup does not migrate implicitly.
20
+
21
+ | Added file | Purpose |
22
+ | --- | --- |
23
+ | `063_usage_model_billing.sql` | Creates 14 model-billing tables for identity, accounts, services, USD plans, original requests, ledger and reference-price cache |
24
+ | `064_period_plan_allowance.sql` | Fills missing periodic allowances from each existing configuration/snapshot's own original allowance; empty fresh billing tables have nothing to backfill |
25
+
26
+ Migration retains existing business and real customer data. Public 0.8.0 did not include this billing module and requires no old-schema purge or table clearing. Incompatible abandoned schemas from unpublished test instances require separate maintenance; their cleanup must not become customer upgrade instructions or public migrations.
27
+
28
+ Instances that already deployed the 063 billing preview must follow the [period allowance guide](PERIOD_ALLOWANCE_UPGRADE.en.md): stop old writers, apply 064, verify original snapshots and ledger, then start the new runtime. The migrator skips recorded files; do not manually alter its ledger or replay applied SQL. Older public versions also need their outstanding preceding migrations.
29
+
30
+ ## Configuration and host integration
31
+
32
+ 1. **Model service:** configure actual credentials, URL and model identifier, with `chat` or `tool` purpose. Explicitly bind an OpenRouter reference model and endpoint; confirm that its metering maps to the actual service. The quote is not the provider's paid cost.
33
+ 2. **Plan:** use USD and one multiplier. Periodic plans require both sale price and period allowance; credit packs use only the one-time allowance. Set validity, day/week/month period and services before granting a test account.
34
+ 3. **Discovery:** inspect `model_gateway` in `GET /usage/v1/capabilities`. Use ready `items`; show configuration reasons from `unavailable_items`. Missing support stays explicit and must not trigger an automatic model switch.
35
+ 4. **Identity and persistence:** trusted backends explicitly exchange `model_access: token_gateway` when plan-wide scope is needed. Single-model `service` scope remains restricted. Persist every original `operation_id` locally and query that request after reopening. Provider credentials must not be passed to browsers or models.
36
+ 5. **Results and allowance:** handle `result_state`, `billing_state` and summary `presentation` separately. Complete results are usable; missing actual usage stays pending settlement. Display Credits or percentage from the summary, not inferred Token balances. Percentage strings may be rounded down; precise numeric values and display strings are separate fields.
37
+
38
+ Verify the actual installed and resolved SDK/DSH pairing, including packaged host dependencies. Changing a version declaration does not implement host UI, persistence or execution integration. Hosts that do not enable the gateway retain their existing business contract.
39
+
40
+ ## Acceptance after enablement
41
+
42
+ - A test account discovers its ready models and tools; unavailable entries explain their state and no provider credentials enter catalogs.
43
+ - With explicit sale price, allowance and multiplier, check one controlled request's actual usage, reference cost, billed amount and presentation. Image services without Tokens leave them absent.
44
+ - Original-ID lookup and same-content replay do not dispatch again. Known failures, unknown outcomes, cancellation and pending settlement remain distinct. Expired results do not trigger regeneration.
45
+ - Plan edits preserve original grant allowances. Archiving blocks new use and restoration does not replenish allowance. A reset retains expiration, and already-dispatched requests settle against their original pool. Check only the administrative actions being enabled.
46
+ - Verify artifacts, migration ledger and client versions while retaining approvals, original-call rules and task restrictions.
47
+
48
+ Video/voice declarations are not execution acceptance. Current image adapters do not implement provider-task recovery through a provider task ID; original-ID lookup reads the Hub's persisted result.
49
+
50
+ ## Rollback
51
+
52
+ Once new structures and snapshots exist, do not assume an older version can read or enforce them correctly. Stop new dispatches, inspect original in-flight requests and settlement, and retain ledger and rollback evidence. Restoring an older backup also requires accounting for subsequent requests and business effects. Do not roll back by dropping tables, discarding ledger entries or resending operations. Existing 0.8.0 task-enforcement markers still require compatible runtimes.
53
+
54
+ [Release notes](RELEASE_NOTES_v0.9.0.en.md) · [Complete billing contract](MODEL_BILLING.en.md) · [简体中文](UPGRADE_v0.9.0.md)
@@ -0,0 +1,54 @@
1
+ # v0.9.0 模型计费:配套升级指南
2
+
3
+ 从公开 Core 0.8.0 / SDK 0.6.0 / DSH 0.6.0 升级到 Core 0.9.0 / SDK 0.7.0 / DSH 0.7.0。下载与部署时核对版本、Tag 和制品摘要,保留原配置与持久记录。
4
+
5
+ ## 选择需要启用的能力
6
+
7
+ | 需求 | 管理端与 Core | 宿主或业务后端 |
8
+ | --- | --- | --- |
9
+ | 保持原业务工具、审批与长任务 | 升级 Core,保留原配置与状态 | 原流程继续使用,无需开启模型计费 |
10
+ | 提供统一模型套餐 | 配置模型连接、参考计价映射、USD 套餐并开通账户 | 宿主接入能力发现、模型目录与额度摘要;可信后端按需提供套餐范围身份 |
11
+ | 让本地助手生成图片 | 配置已支持的图片适配、参考价格并加入套餐 | 接入工具目录、原请求持久记录与异步查询;业务使用图片仍单独调用业务接口 |
12
+ | 自动开通业务套餐 | 配置来源所有权与权限 | 可信后端使用外部计费接口,保留幂等开通标识;支付、汇率和退款仍由业务侧处理 |
13
+ | 移除、恢复账户或手动重置额度 | 管理员按账户状态与权限操作 | 使用已有摘要;这些管理功能不单独要求 SDK/DSH 或业务后端改造 |
14
+
15
+ ## 备份与迁移
16
+
17
+ 保留数据库、实例配置和密钥、对象存储、原制品及客户端的安全凭据、会话和持久记录。升级时协调所有共用状态库的 Core 与写入方;已经派发的请求保留原 ID 和证据,不以重发替代恢复。
18
+
19
+ 从公开 0.8.0 升级,通过正式迁移器(源码安装入口为 `npm run db:init`)应用全部未执行文件,再启动新 Core。运行时启动不自动迁移。
20
+
21
+ | 新增文件 | 作用 |
22
+ | --- | --- |
23
+ | `063_usage_model_billing.sql` | 新建模型计费所需身份、账户、模型服务、USD 套餐、原请求账本及参考价格缓存,共 14 张表 |
24
+ | `064_period_plan_allowance.sql` | 为已存在且缺字段的周期配置和快照补入各自原额度;新安装的空计费表无数据回填 |
25
+
26
+ 迁移保留原业务与真实客户数据。公开 0.8.0 没有这一计费模块,无需先清退旧结构或清空表。早期未公开测试实例如有不兼容废弃结构,属于独立维护问题,不能把其清理步骤用于客户升级或混入公共迁移。
27
+
28
+ 已部署过 063 计费预览的实例,先看[周期售价与额度拆分](PERIOD_ALLOWANCE_UPGRADE.md):停止旧版本写入,再应用 064,核对原快照与账本后启动新版本。已记账文件由迁移器跳过;不手工改写账本或重跑已应用 SQL。更早公开版本还需应用缺少的前序迁移。
29
+
30
+ ## 配置与宿主接入
31
+
32
+ 1. **模型服务**:配置实际凭据、地址及型号,选择 `chat` 或 `tool` 用途。显式绑定 OpenRouter 参考模型与端点,核对价格计量与真实服务能否对应。参考报价不是供应商实付成本。
33
+ 2. **套餐**:统一 USD 与一个倍率。周期套餐同时填写售价和周期额度;额度包只填写一次性额度。确定有效期、日/周/月周期和服务集合,再为测试账户开通。
34
+ 3. **能力发现**:读取 `GET /usage/v1/capabilities` 中 `model_gateway`。宿主使用当前目录的 ready `items`,对 `unavailable_items` 显示配置原因;缺少支持时明确不可用,不自动换模型。
35
+ 4. **身份与持久化**:需要整个套餐范围时,可信后端显式交换 `model_access: token_gateway` 身份;单模型 `service` 范围仍保持。每个模型或工具请求在本地持久保存原 `operation_id`,重开后查询原请求。不要将服务端凭据传给浏览器或模型。
36
+ 5. **结果与额度**:分别处理 `result_state`、`billing_state` 与摘要的 `presentation`。结果 complete 即可使用;缺少实际计量保持待结算。Credits 与百分比使用摘要,不从 Token 数猜余额。控制台可能向下取整显示百分比,精确数值与显示字符串分别提供。
37
+
38
+ 配套 SDK/DSH 应核对实际安装与解析版本,包括打包宿主内的依赖。仅修改版本声明不会自动完成宿主 UI、持久化或工具执行接入;不启用模型网关的宿主继续遵循原业务契约。
39
+
40
+ ## 启用后的验收
41
+
42
+ - 一个测试账户能看到套餐中已就绪的模型与工具,未就绪项有可理解的原因,供应商凭据不进入目录。
43
+ - 采用明确的售价、周期额度和倍率,核对一次受控请求的实际用量、参考费用、扣费及客户展示。图片服务没有 Token 时保持为空。
44
+ - 原 ID 查询和同内容重试不会再次派发;已知失败、未知结果、取消和待结算分开展示。结果过期不触发自动重发。
45
+ - 套餐编辑不改写原开通额度。归档后阻止新使用,恢复不补发额度;重置维持原有效期,已派发请求向原池结算。只检查本次启用的管理动作。
46
+ - 验证新制品、迁移账本和客户端版本,同时保留既有审批、原调用与长任务约束。
47
+
48
+ 视频、语音声明不作为执行验收;当前图片适配不提供供应商任务 ID 的异步任务恢复,原 ID 查询读取中枢保存的结果。
49
+
50
+ ## 回退
51
+
52
+ 新结构与新快照落库后,不能假定旧版本能读取或正确约束它们。出现问题先停止新增派发,核对原在途请求及结算,保留账本与回滚材料。恢复旧备份必须同时处理备份后的请求和业务效果,不能通过删表、丢弃账本或重发原操作回退。已启用的 0.8.0 任务强制标记仍须由兼容版本执行。
53
+
54
+ [版本说明](RELEASE_NOTES_v0.9.0.md) · [完整计费契约](MODEL_BILLING.md) · [English](UPGRADE_v0.9.0.en.md)
@@ -1,5 +1,11 @@
1
1
  # 百灵中枢 · 兼容性与升级策略
2
2
 
3
+ ## Core 0.9.0 配套升级
4
+
5
+ Core 0.9.0 配套 SDK 0.7.0 / DSH 0.7.0,新增可选模型计费网关;本地宿主继续编排,既有业务权限、审批与原调用恢复保持。从公开 0.8.0 升级应用未执行的 063/064,保留真实数据,不需要清退测试结构。周期套餐的售价与额度独立,原开通快照和账本保留。启用模型套餐的宿主需要显式接入;只使用原业务工具的宿主不必开启计费。详见 [0.9.0 升级指南](UPGRADE_v0.9.0.md)。
6
+
7
+ > Core 0.8.0 task enrollment persists on original Agent Sessions. Do not downgrade an enrolled deployment to a version that ignores enforcement markers. See [upgrade boundaries](UPGRADE_v0.8.0.md).
8
+
3
9
  > 这份策略用于公开发布后的版本演进。目标是让绝大多数升级都能平滑完成:拉新版、执行数据库结构同步、重启 hub;已配置的路由、凭证、工具源、聊天入口不需要重配。破坏性变更必须显式说明,并提供过渡窗口。
4
10
 
5
11
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailinghub",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Open-source ACC runtime and agent control plane for existing business systems.",
@@ -137,6 +137,7 @@
137
137
  "enabled": { "type": "boolean" },
138
138
  "instructions": { "type": "string", "maxLength": 20000 },
139
139
  "active_tool_limit": { "type": "integer", "minimum": 1, "maximum": 12 },
140
+ "artifact_upload": {"type": "object", "additionalProperties": false, "required": ["enabled"], "properties": {"enabled": {"type": "boolean"}, "bucket": {"type": "string", "pattern": "^[a-zA-Z0-9_-]{1,64}$"}, "max_bytes": {"type": "integer", "minimum": 1, "maximum": 6291456}, "allowed_mimes": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"enum": ["image/png", "image/jpeg", "image/webp"]}}}, "allOf": [{"if": {"properties": {"enabled": {"const": true}}}, "then": {"required": ["bucket"]}}]},
140
141
  "system_info": {
141
142
  "type": "object",
142
143
  "title": "业务系统说明",
@@ -43,7 +43,8 @@
43
43
  "secret": { "type": "string", "minLength": 1, "title": "签名密钥", "description": "中枢与业务工具源共享的 HMAC 密钥,用于工具调用、spec 拉取与授权探针验签。" },
44
44
  "log_payload": { "type": "boolean", "title": "审计粒度", "description": "控制工具调用参数在审计中记录全量值还是只记录键名;敏感工具仍强制脱敏。" },
45
45
  "timeout_ms": { "type": "integer", "minimum": 1000, "maximum": 60000, "title": "单次调用超时", "description": "中枢等待单个工具接口响应的最长毫秒数。" },
46
- "rate_limit_per_min": { "type": "integer", "minimum": 0, "title": "总闸限流", "description": "该工具源所有工具共享的每分钟调用上限,0 表示不限。" },
46
+ "rate_limit_per_min": { "type": "integer", "minimum": 0, "maximum": 1000000, "title": "工具源总限额", "description": "该工具源的所有工具、用户、授权和会话共用每分钟调度额度;0 只关闭总闸,单工具策略仍独立生效。" },
47
+ "tool_rate_limits": {"type": "object", "additionalProperties": false, "title": "中枢单工具限额策略", "description": "指定工具覆盖优先于默认策略;默认继承业务声明,支持自定义或关闭中枢限额。每个工具按工具源共享计数。", "properties": {"default": {"oneOf": [{"type": "object", "additionalProperties": false, "required": ["mode"], "properties": {"mode": {"enum": ["inherit", "disabled"]}}}, {"type": "object", "additionalProperties": false, "required": ["mode", "count", "window"], "properties": {"mode": {"const": "custom"}, "count": {"type": "integer", "minimum": 1, "maximum": 1000000}, "window": {"enum": ["1s", "1m", "1h", "1d"]}}}]}, "overrides": {"type": "object", "maxProperties": 1000, "propertyNames": {"pattern": "^[A-Za-z_][A-Za-z0-9_]{0,63}$"}, "additionalProperties": {"oneOf": [{"type": "object", "additionalProperties": false, "required": ["mode"], "properties": {"mode": {"enum": ["inherit", "disabled"]}}}, {"type": "object", "additionalProperties": false, "required": ["mode", "count", "window"], "properties": {"mode": {"const": "custom"}, "count": {"type": "integer", "minimum": 1, "maximum": 1000000}, "window": {"enum": ["1s", "1m", "1h", "1d"]}}}]}}}},
47
48
  "auto_refresh_min": { "type": "integer", "minimum": 0, "maximum": 1440, "title": "自动刷新", "description": "URL 模式下按分钟自动拉取新 spec;0 表示关闭。" },
48
49
  "enabled": { "type": "boolean", "title": "启用", "description": "关闭后该工具源不会再向路由提供业务工具。" },
49
50
  "description": { "type": "string", "title": "说明", "description": "给后台维护者看的备注,不参与运行期决策。" },
@@ -103,6 +103,11 @@ const englishCompanions = {
103
103
  'docs/RELEASE_NOTES_v0.3.4.md': 'docs/RELEASE_NOTES_v0.3.4.en.md',
104
104
  'docs/RELEASE_NOTES_v0.5.0.md': 'docs/RELEASE_NOTES_v0.5.0.en.md',
105
105
  'docs/RELEASE_NOTES_v0.5.1.md': 'docs/RELEASE_NOTES_v0.5.1.en.md',
106
+ 'docs/RELEASE_NOTES_v0.8.0.md': 'docs/RELEASE_NOTES_v0.8.0.en.md',
107
+ 'docs/RELEASE_NOTES_v0.9.0.md': 'docs/RELEASE_NOTES_v0.9.0.en.md',
108
+ 'docs/UPGRADE_v0.9.0.md': 'docs/UPGRADE_v0.9.0.en.md',
109
+ 'docs/MODEL_BILLING.md': 'docs/MODEL_BILLING.en.md',
110
+ 'docs/PERIOD_ALLOWANCE_UPGRADE.md': 'docs/PERIOD_ALLOWANCE_UPGRADE.en.md',
106
111
  'docs/RELEASE_NOTES_v0.7.0.md': 'docs/RELEASE_NOTES_v0.7.0.en.md',
107
112
  'docs/RELEASE_NOTES_v0.6.1.md': 'docs/RELEASE_NOTES_v0.6.1.en.md',
108
113
  'docs/RELEASE_NOTES_v0.6.0.md': 'docs/RELEASE_NOTES_v0.6.0.en.md',
@@ -9,7 +9,7 @@ REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_REGISTRY}"
9
9
  NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_NAMESPACE}"
10
10
  PACKAGE_VERSION="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' package.json | head -1)"
11
11
  TAG="${BAILING_IMAGE_TAG:-$PACKAGE_VERSION}"
12
- [ -n "$TAG" ] || TAG="0.7.0"
12
+ [ -n "$TAG" ] || TAG="0.9.0"
13
13
  MYSQL_TAG="${BAILING_MYSQL_IMAGE_TAG:-8.4}"
14
14
  MYSQL_IMAGE="${BAILING_MYSQL_IMAGE:-$REGISTRY/$NAMESPACE/bailing-mysql:$MYSQL_TAG}"
15
15
  PLATFORM="${BAILING_IMAGE_PLATFORM:-linux/amd64}"
@@ -38,8 +38,8 @@ function updateJson(root, relativePath, update) {
38
38
  test('current release surface is internally consistent', () => {
39
39
  const result = checkReleaseConsistency({ root: repoRoot });
40
40
  assert.deepEqual(result.findings, []);
41
- assert.equal(result.version, '0.7.0');
42
- assert.equal(result.stableVersion, '0.7.0');
41
+ assert.equal(result.version, '0.9.0');
42
+ assert.equal(result.stableVersion, '0.9.0');
43
43
  assert.equal(result.publishTag, 'latest');
44
44
  });
45
45
 
@@ -57,6 +57,7 @@ const fixtures = {
57
57
  },
58
58
  authz_probe: { status: 'pass' },
59
59
  auto_refresh_min: 60,
60
+ rate_limit_per_min: 120, timeout_ms: 10000, log_payload: false,
60
61
  }],
61
62
  clients: [{ app_id: 'demo-app', name: 'Demo 业务系统', token: '****oken', allowed_routes: ['demo_support'], allowed_channels: [], rate_limit_per_min: 60, enabled: true }],
62
63
  routes: [{ route_key: 'demo_support', name: 'Demo 售后助手', target: 'demo-agent', enabled: true, tools: { sources: [{ provider: 'demo-business', allow: ['demo.*'] }], max_calls: 5 } }],
@@ -292,7 +293,15 @@ async function mockApi(context) {
292
293
  }
293
294
  if (url.pathname === '/admin/api/credentials') return route.fulfill({ json: fixtures.credentials });
294
295
  if (url.pathname === '/admin/api/targets') return route.fulfill({ json: fixtures.targets });
295
- if (url.pathname === '/admin/api/tool-providers') return route.fulfill({ json: fixtures.providers });
296
+ if (url.pathname === '/admin/api/tool-providers') {
297
+ if (route.request().method() === 'POST') {
298
+ const payload = route.request().postDataJSON();
299
+ Object.assign(fixtures.providers[0], payload);
300
+ return route.fulfill({ json: { ok: true } });
301
+ }
302
+ return route.fulfill({ json: fixtures.providers });
303
+ }
304
+ if (/^\/admin\/api\/tool-providers\/[^/]+\/tools$/.test(url.pathname)) return route.fulfill({ json: { tools: [{ name: 'list_demo_orders', scope: 'demo.order.read' }] } });
296
305
  if (url.pathname === '/admin/api/clients') return route.fulfill({ json: fixtures.clients });
297
306
  if (url.pathname === '/admin/api/routes') return route.fulfill({ json: fixtures.routes });
298
307
  if (url.pathname === '/admin/api/runs') return route.fulfill({ json: fixtures.runs });
@@ -401,7 +410,28 @@ try {
401
410
  if (!await signedPolicy.isChecked()) throw new Error('采用实测结果后应选择签名保护');
402
411
  await page.getByRole('button', { name: '取消' }).click();
403
412
 
404
- await page.getByRole('menuitem', { name: '任务' }).click();
413
+ await page.getByRole('button', { name: '编辑' }).first().click();
414
+ await page.getByRole('tab', { name: '治理', exact: true }).click();
415
+ await expectVisible(page, '工具源总限额');
416
+ await expectVisible(page, '用户、授权和会话共用');
417
+ const defaultPolicy = page.locator('.limit-editor').first();
418
+ await defaultPolicy.locator('.el-select__wrapper').first().click();
419
+ await page.getByRole('option', { name: '自定义中枢限额', exact: true }).click();
420
+ await defaultPolicy.getByRole('spinbutton').fill('1000');
421
+ await page.getByRole('button', { name: '添加工具覆盖', exact: true }).click();
422
+ await page.getByText('选择或输入工具名', { exact: true }).click();
423
+ await page.getByRole('option', { name: 'list_demo_orders', exact: true }).last().click();
424
+ await page.getByRole('button', { name: '保存', exact: true }).click();
425
+ await expectVisible(page, '已保存');
426
+ if (fixtures.providers[0].tool_rate_limits.default.count !== 1000 || fixtures.providers[0].tool_rate_limits.default.window !== '1h') throw new Error('custom hour policy not saved');
427
+ if (fixtures.providers[0].tool_rate_limits.overrides.list_demo_orders.mode !== 'inherit') throw new Error('per-tool override not saved');
428
+ await page.getByRole('button', { name: '编辑' }).first().click();
429
+ await page.getByRole('tab', { name: '治理', exact: true }).click();
430
+ if (await page.locator('.limit-editor').first().getByRole('spinbutton').inputValue() !== '1000') throw new Error('saved policy did not restore');
431
+ if (process.env.BAILING_RATE_SCREENSHOT) await page.screenshot({ path: process.env.BAILING_RATE_SCREENSHOT, fullPage: true });
432
+ await page.getByRole('button', { name: '取消', exact: true }).click();
433
+
434
+ await page.getByRole('menuitem', { name: '任务', exact: true }).click();
405
435
  const auditRadio = page.getByRole('radio', { name: '客户端完整对话', exact: true });
406
436
  if (!await auditRadio.isChecked()) throw new Error('任务会话页应默认展示客户端完整对话');
407
437
  const auditList = page.locator('aside[aria-label="客户端对话列表"]');
@@ -275,7 +275,7 @@ write_env() {
275
275
  TOOL_SECRET="${DEMO_TOOL_SECRET:-$(secret)}"
276
276
  CLIENT_TOKEN="${DEMO_CLIENT_TOKEN:-$(secret)}"
277
277
  IMAGE_TAG="${BAILING_IMAGE_TAG:-$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$APP_DIR/package.json" | head -1)}"
278
- [ -n "$IMAGE_TAG" ] || IMAGE_TAG="0.7.0"
278
+ [ -n "$IMAGE_TAG" ] || IMAGE_TAG="0.9.0"
279
279
  IMAGE_REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_IMAGE_REGISTRY}"
280
280
  IMAGE_NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_IMAGE_NAMESPACE}"
281
281
  cat > "$ENV_FILE" <<EOF
@@ -9,7 +9,7 @@ REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_REGISTRY}"
9
9
  NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_NAMESPACE}"
10
10
  PACKAGE_VERSION="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' package.json | head -1)"
11
11
  TAG="${BAILING_IMAGE_TAG:-$PACKAGE_VERSION}"
12
- [ -n "$TAG" ] || TAG="0.7.0"
12
+ [ -n "$TAG" ] || TAG="0.9.0"
13
13
  NODE_IMAGE="${BAILING_NODE_IMAGE:-node:22-bookworm-slim}"
14
14
  PLATFORM="${BAILING_IMAGE_PLATFORM:-linux/amd64}"
15
15
  PUSH="${BAILING_PUSH_IMAGES:-0}"
@@ -38,6 +38,8 @@ const requiredRepoFiles = [
38
38
  'docs/RELEASE_NOTES_v0.5.0.md',
39
39
  'docs/RELEASE_NOTES_v0.5.1.md',
40
40
  'docs/RELEASE_NOTES_v0.7.0.md',
41
+ 'docs/RELEASE_NOTES_v0.8.0.md',
42
+ 'docs/RELEASE_NOTES_v0.9.0.md',
41
43
  'docs/RELEASE_NOTES_v0.6.1.md',
42
44
  'docs/RELEASE_NOTES_v0.6.0.md',
43
45
  'docs/CHANGELOG.md',
@@ -57,6 +57,12 @@ async function closeServer(server) {
57
57
  }
58
58
 
59
59
  console.log('— SDK runtime helpers');
60
+ const nodeUsage = run(process.execPath, ['--test', 'sdk/node/tests/usage.test.mjs']);
61
+ ok('Node billing issuer transport boundaries', nodeUsage.status === 0, nodeUsage.stderr || nodeUsage.stdout);
62
+ const phpUsage = run(process.env.BAILING_SDK_PHP7_BINARY || 'php', ['sdk/php7/tests/usage-client.php']);
63
+ ok('PHP7 billing issuer transport boundaries', phpUsage.status === 0, phpUsage.stderr || phpUsage.stdout);
64
+ const billingTypes = run(process.execPath, ['node_modules/typescript/bin/tsc', '--noEmit', '--strict', '--skipLibCheck', '--module', 'NodeNext', '--target', 'ES2022', '--types', 'node', 'sdk/node/tests/usage-types.mts']);
65
+ ok('Node billing public package types match the documented methods', billingTypes.status === 0, billingTypes.stderr || billingTypes.stdout);
60
66
  ok('Node signTicket deterministic vector', signTicket('secret', 'tenant:user', { expiresAt: 2_000_000_000 }) === expectedTicket);
61
67
 
62
68
  const ts = Math.floor(Date.now() / 1000);
@@ -0,0 +1,225 @@
1
+ // Local-only synthetic release acceptance. Never loads application configuration.
2
+ // Run: node --import tsx scripts/verify-billing-install-upgrade.mjs
3
+ // Requires an isolated MySQL at 127.0.0.1:16307 (root, empty password).
4
+ import assert from 'node:assert/strict';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
8
+ import { tmpdir } from 'node:os';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { createConnection, createPool } from 'mysql2/promise';
12
+ import { migrateBailingHubCoreSchema } from '../src/infrastructure/schema/core-schema-migrator.ts';
13
+ import { UsageRepository } from '../src/modules/usage/repository.ts';
14
+ import { getUsageIdentity } from '../src/modules/usage/identity.ts';
15
+ import { getBillingRepository } from '../src/modules/usage/billing-repository.ts';
16
+
17
+ const root = fileURLToPath(new URL('../', import.meta.url));
18
+ const mysql = Object.freeze({ host: '127.0.0.1', port: 16307, user: 'root', password: '',
19
+ connectionLimit: 2, connectTimeout: 5_000, dateStrings: true,
20
+ supportBigNumbers: true, bigNumberStrings: true });
21
+ const expectedAdditions = ['063_usage_model_billing.sql', '064_period_plan_allowance.sql'];
22
+ const git = (...args) => execFileSync('git', args, { cwd: root, maxBuffer: 8 * 1024 * 1024 });
23
+ const digest = data => createHash('sha256').update(data).digest('hex');
24
+ const quote = identifier => { assert.match(identifier, /^[a-zA-Z0-9_]+$/); return `\`${identifier}\``; };
25
+ const canonical = value => {
26
+ if (Array.isArray(value)) return value.map(canonical);
27
+ if (value && typeof value === 'object') return Object.fromEntries(
28
+ Object.keys(value).sort().map(key => [key, canonical(value[key])]),
29
+ );
30
+ return value;
31
+ };
32
+
33
+ async function manifest(directory) {
34
+ const names = (await readdir(directory)).filter(name => name.endsWith('.sql')).sort();
35
+ return Promise.all(names.map(async filename => ({ filename,
36
+ checksum_sha256: digest(await readFile(join(directory, filename))) })));
37
+ }
38
+
39
+ async function stageBaseline(baselineRoot, revision) {
40
+ // Extract only the local public tag's SQL and official migrator dependencies.
41
+ const names = git('ls-tree', '-r', '--name-only', revision, 'sql', 'src/infrastructure/schema')
42
+ .toString().trim().split('\n').filter(name => name.endsWith('.sql')
43
+ || name.endsWith('.ts') && !name.endsWith('.test.ts'));
44
+ for (const name of names) {
45
+ const destination = join(baselineRoot, name);
46
+ await mkdir(dirname(destination), { recursive: true });
47
+ await writeFile(destination, git('show', `${revision}:${name}`));
48
+ }
49
+ await writeFile(join(baselineRoot, 'package.json'), '{"type":"module"}\n');
50
+ return import(pathToFileURL(join(baselineRoot, 'src/infrastructure/schema/core-schema-migrator.ts')).href);
51
+ }
52
+
53
+ async function tables(connection) {
54
+ const [rows] = await connection.query('SHOW FULL TABLES WHERE Table_type = ?', ['BASE TABLE']);
55
+ return rows.map(row => Object.values(row)[0]).sort();
56
+ }
57
+
58
+ async function snapshot(connection, names) {
59
+ const result = {};
60
+ for (const table of names) {
61
+ const [rows] = await connection.query(`SELECT * FROM ${quote(table)}`);
62
+ const [ddl] = await connection.query(`SHOW CREATE TABLE ${quote(table)}`);
63
+ const serialized = rows.map(row => JSON.stringify(canonical(row))).sort();
64
+ result[table] = { rowCount: rows.length, rowsSha256: digest(JSON.stringify(serialized)),
65
+ schemaSha256: digest(ddl[0]['Create Table']) };
66
+ }
67
+ return result;
68
+ }
69
+
70
+ async function verifyLedger(connection, expected) {
71
+ const [rows] = await connection.query(
72
+ 'SELECT filename, checksum_sha256 FROM bz_schema_migrations ORDER BY filename',
73
+ );
74
+ assert.deepEqual(rows.map(row => ({ ...row })), expected);
75
+ }
76
+
77
+ async function seedLegacyRecords(connection) {
78
+ const date = '2026-01-02 03:04:05', expires = '2036-01-02 03:04:05';
79
+ const session = randomUUID(), job = randomUUID(), authorization = randomUUID();
80
+ const client = 'synthetic-upgrade-client', route = 'synthetic-upgrade-route';
81
+ const principal = JSON.stringify({ tenant: 'synthetic', id: 'upgrade-user' });
82
+ const routes = JSON.stringify([route]);
83
+ const fixtures = [
84
+ ['bz_clients', { app_id: client, name: 'Synthetic existing integration', token: '0'.repeat(32),
85
+ allowed_routes: routes, created_at: date, updated_at: date }],
86
+ ['bz_routes', { route_key: route, name: 'Synthetic existing route', created_at: date, updated_at: date }],
87
+ ['bz_agent_sessions', { session_id: session, client_app_id: client, device_label: 'Synthetic device',
88
+ principal_json: principal, on_behalf_of: 'upgrade-user', allowed_routes: routes,
89
+ access_token_hash: '1'.repeat(64), access_expires_at: expires, refresh_expires_at: expires,
90
+ created_at: date, updated_at: date, subject_display: JSON.stringify({ name: 'Synthetic person' }) }],
91
+ ['bz_agent_authorizations', { authorization_id: authorization, client_app_id: client,
92
+ redirect_uri: 'http://127.0.0.1:1/synthetic-callback', state_value: 'synthetic-state',
93
+ requested_routes: routes, device_label: 'Synthetic device', code_challenge: 'x'.repeat(43),
94
+ status: 'consumed', principal_json: principal, on_behalf_of: 'upgrade-user', allowed_routes: routes,
95
+ session_id: session, created_at: date, expires_at: expires, consumed_at: date }],
96
+ ['bz_agent_refresh_tokens', { token_hash: '2'.repeat(64), session_id: session,
97
+ status: 'used', created_at: date, expires_at: expires, used_at: date }],
98
+ ['bz_jobs', { job_id: job, request_id: 'synthetic-original-request', profile: 'readonly',
99
+ status: 'done', client_app_id: client, agent_session_id: session, on_behalf_of: 'upgrade-user',
100
+ result: JSON.stringify({ text: 'Original synthetic result' }), created_at: date, updated_at: date }],
101
+ ['bz_audit', { ts: date, job_id: job, request_id: 'synthetic-original-request', event: 'finished',
102
+ detail: JSON.stringify({ preserved: true, fixture: 'upgrade' }) }],
103
+ ['bz_approvals', { job_id: job, action: JSON.stringify({ synthetic: true }), status: 'approved',
104
+ decided_by: 'synthetic-reviewer', created_at: date, decided_at: date }],
105
+ ];
106
+ for (const [table, record] of fixtures) await connection.query('INSERT INTO ?? SET ?', [table, record]);
107
+ return fixtures.map(([table]) => table);
108
+ }
109
+
110
+ async function verifyOptionalBilling(connection, database) {
111
+ const usageTables = (await tables(connection)).filter(table => table.startsWith('bz_usage_'));
112
+ assert.equal(usageTables.length, 14);
113
+ const before = await snapshot(connection, usageTables);
114
+ for (const [table, value] of Object.entries(before)) assert.equal(value.rowCount, 0, `${table} must be empty`);
115
+ const pool = createPool({ ...mysql, database });
116
+ try {
117
+ const repository = new UsageRepository(() => pool);
118
+ assert.equal(await getUsageIdentity(repository).ready(), true);
119
+ assert.equal(await getBillingRepository(repository).ready(), true);
120
+ assert.deepEqual(await getBillingRepository(repository).listPlans(), []);
121
+ } finally { await pool.end(); }
122
+ assert.deepEqual(await snapshot(connection, usageTables), before,
123
+ 'Readiness and listing must not create identities, plans, grants, requests or charges');
124
+ return { tables: usageTables.length, allEmpty: true, schemaReady: true, autoProvisioned: false };
125
+ }
126
+
127
+ function assertNoReplay(result, expectedFiles) {
128
+ assert.deepEqual(result.appliedFiles, []);
129
+ assert.deepEqual(result.skippedFiles, expectedFiles);
130
+ assert.deepEqual(result.checksumBackfilledFiles, []);
131
+ assert.equal(result.executedStatements, 0);
132
+ assert.equal(result.toleratedStatements, 0);
133
+ }
134
+
135
+ const baselineRoot = await mkdtemp(join(tmpdir(), 'bailing-billing-upgrade-'));
136
+ let admin;
137
+ const createdDatabases = new Set();
138
+ async function isolatedDatabase(label, callback) {
139
+ const database = `billing_install_${label}_${randomUUID().replaceAll('-', '')}`;
140
+ assert.match(database, /^billing_install_(fresh|upgrade)_[a-f0-9]{32}$/);
141
+ await admin.query(`CREATE DATABASE ${quote(database)} CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
142
+ createdDatabases.add(database);
143
+ let connection;
144
+ try {
145
+ connection = await createConnection({ ...mysql, database });
146
+ return await callback(connection, database);
147
+ } finally {
148
+ if (connection) await connection.end();
149
+ await admin.query(`DROP DATABASE ${quote(database)}`);
150
+ createdDatabases.delete(database);
151
+ }
152
+ }
153
+
154
+ try {
155
+ const baselineRevision = git('rev-parse', 'v0.8.0^{commit}').toString().trim();
156
+ const candidateHead = git('rev-parse', 'HEAD').toString().trim();
157
+ const { migrateBailingHubCoreSchema: migrateBaseline } = await stageBaseline(baselineRoot, baselineRevision);
158
+ const baselineManifest = await manifest(join(baselineRoot, 'sql'));
159
+ const currentManifest = await manifest(join(root, 'sql'));
160
+ const baselineNames = baselineManifest.map(file => file.filename);
161
+ const currentNames = currentManifest.map(file => file.filename);
162
+ assert.deepEqual(currentNames.filter(name => !baselineNames.includes(name)), expectedAdditions);
163
+ for (const oldFile of baselineManifest) assert.deepEqual(
164
+ currentManifest.find(file => file.filename === oldFile.filename), oldFile,
165
+ `Published migration ${oldFile.filename} must remain byte-identical`,
166
+ );
167
+ admin = await createConnection(mysql);
168
+ const [[server]] = await admin.query('SELECT VERSION() AS version');
169
+ const fresh = await isolatedDatabase('fresh', async (connection, database) => {
170
+ const input = { mysql: { ...mysql, database }, connection };
171
+ assert.deepEqual(await tables(connection), []);
172
+ const install = await migrateBailingHubCoreSchema(input);
173
+ assert.deepEqual(install.appliedFiles, currentNames);
174
+ assert.deepEqual(install.skippedFiles, []);
175
+ await verifyLedger(connection, currentManifest);
176
+ const billing = await verifyOptionalBilling(connection, database);
177
+ const before = await snapshot(connection, await tables(connection));
178
+ const rerun = await migrateBailingHubCoreSchema(input);
179
+ assertNoReplay(rerun, currentNames);
180
+ assert.deepEqual(await snapshot(connection, await tables(connection)), before);
181
+ return { migrations: install.appliedFiles.length, executedStatements: install.executedStatements,
182
+ toleratedStatements: install.toleratedStatements, tables: Object.keys(before).length,
183
+ rerunExecutedStatements: rerun.executedStatements, billing };
184
+ });
185
+ const upgrade = await isolatedDatabase('upgrade', async (connection, database) => {
186
+ const input = { mysql: { ...mysql, database }, connection };
187
+ const initial = await migrateBaseline(input);
188
+ assert.deepEqual(initial.appliedFiles, baselineNames);
189
+ await verifyLedger(connection, baselineManifest);
190
+ assert.equal((await tables(connection)).some(table => table.startsWith('bz_usage_')), false);
191
+ const seededTables = await seedLegacyRecords(connection);
192
+ const legacyTables = (await tables(connection)).filter(table => table !== 'bz_schema_migrations');
193
+ const before = await snapshot(connection, legacyTables);
194
+ const [oldLedger] = await connection.query('SELECT * FROM bz_schema_migrations ORDER BY filename');
195
+ const migrated = await migrateBailingHubCoreSchema(input);
196
+ assert.deepEqual(migrated.appliedFiles, expectedAdditions);
197
+ assert.deepEqual(migrated.skippedFiles, baselineNames);
198
+ assert.deepEqual(migrated.checksumBackfilledFiles, []);
199
+ await verifyLedger(connection, currentManifest);
200
+ const [newLedger] = await connection.query('SELECT * FROM bz_schema_migrations ORDER BY filename');
201
+ assert.deepEqual(newLedger.filter(row => baselineNames.includes(row.filename)), oldLedger);
202
+ assert.deepEqual(await snapshot(connection, legacyTables), before,
203
+ 'Every original table schema and row must be preserved');
204
+ const billing = await verifyOptionalBilling(connection, database);
205
+ const complete = await snapshot(connection, await tables(connection));
206
+ const rerun = await migrateBailingHubCoreSchema(input);
207
+ assertNoReplay(rerun, currentNames);
208
+ assert.deepEqual(await snapshot(connection, await tables(connection)), complete);
209
+ return { baselineMigrations: initial.appliedFiles.length, appliedMigrations: migrated.appliedFiles,
210
+ executedStatements: migrated.executedStatements, preservedTables: legacyTables.length,
211
+ preservedRows: Object.values(before).reduce((total, value) => total + value.rowCount, 0),
212
+ seededTables, originalLedgerPreserved: true, oldSchemaAndDataPreserved: true,
213
+ rerunExecutedStatements: rerun.executedStatements, billing };
214
+ });
215
+ console.log(JSON.stringify({ status: 'passed', baselineRevision, candidateHead, mysqlVersion: server.version,
216
+ publishedSqlUnchanged: true, baselineSqlManifestSha256: digest(JSON.stringify(baselineManifest)),
217
+ currentSqlManifestSha256: digest(JSON.stringify(currentManifest)), fresh, upgrade,
218
+ syntheticDatabasesRemoved: createdDatabases.size === 0 }, null, 2));
219
+ } finally {
220
+ if (admin) {
221
+ for (const database of createdDatabases) await admin.query(`DROP DATABASE ${quote(database)}`);
222
+ await admin.end();
223
+ }
224
+ await rm(baselineRoot, { recursive: true, force: true });
225
+ }
@@ -130,6 +130,8 @@ const requiredFiles = [
130
130
  'docs/RELEASE_NOTES_v0.5.0.md',
131
131
  'docs/RELEASE_NOTES_v0.5.1.md',
132
132
  'docs/RELEASE_NOTES_v0.7.0.md',
133
+ 'docs/RELEASE_NOTES_v0.8.0.md',
134
+ 'docs/RELEASE_NOTES_v0.9.0.md',
133
135
  'docs/RELEASE_NOTES_v0.6.1.md',
134
136
  'docs/RELEASE_NOTES_v0.6.0.md',
135
137
  'docs/CHANGELOG.md',
@@ -105,3 +105,20 @@ const job = await hub.run({
105
105
  const result = await hub.getJob(job.job_id);
106
106
  await hub.send({ requestId: `notice_${orderId}`, channel: 'team-im', to: 'user_001', text: '任务已完成' });
107
107
  ```
108
+
109
+ ## 可选模型套餐与登录
110
+
111
+ `UsageIssuerClient` 使用独立的服务端 Usage issuer 凭据,提供 `exchangeSession`、`revokeUser`、`listBillingPlans`、`getBillingSummary`、`grantBillingPlan` 和 `controlBillingPlan`。不要复用业务 Client Token,也不要把 issuer 凭据或管理方法交给浏览器或模型。
112
+
113
+ 业务后端根据已验证登录提交 `request_key/tenant/subject/generation/service_id` 换取短期模型凭证。`model_access: "service"` 限定所选模型;显式 `"token_gateway"` 可在身份来源及套餐允许的模型交集中选择,不扩大业务权限。只将短期凭证和固定身份交给对应使用人。登录不依赖套餐摘要成功;未开通套餐通过摘要的 `grant=null` 表达。
114
+
115
+ `grantBillingPlan(accountId, input)` 的 input 包含原 `request_key`、`plan_id`、`expected_revision`。`controlBillingPlan(accountId, input)` 使用原请求键、当前修订和 `state: active|suspended`。`getBillingSummary(accountId)` 读取当前账户美元余额、实际费用与周期状态,不执行模型。向用户展示时只使用摘要 `presentation`:额度包显示积分,周期套餐显示剩余百分比;美元字段用于计费核账;原始 Token 用量保留在模型请求明细中。售价、收款和合同由业务系统负责。
116
+
117
+ 套餐管理统一使用 `/usage/v1/external/billing/`。套餐目录返回 `config.priceUsd`、周期套餐必填的 `config.periodAllowanceUsd`、`periodUnit`、`duration`、`serviceIds` 和 `multiplier`。周期套餐售价与每周期额度是两个独立字段;账户摘要使用 `bailing.billing-summary.v1`,美元余额为 `availableUsd`,已消费为 `consumedUsd`,客户展示使用 `presentation`。
118
+
119
+ 管理写入不会自动重试。回包丢失时沿原键、原参数核对,不能换新键重复发放。异常只包含脱敏错误码、`outcome`、`requestKey` 和安全反馈。`revokeUser` 按原 tenant/subject/generation 幂等停用,不需要 request_key。
120
+
121
+ 完整契约见 [模型服务与套餐计费](../../docs/MODEL_BILLING.md)。安装业务 SDK 本身不接管本地模型流量;客户端接入模型请求/流式入口后才会计量。
122
+
123
+
124
+ 示例将准备和发送分开:先调用 `prepareBillingPlan` 并持久化 `grantInput`,再调用 `applyBillingPlan`;回包不确定时沿用已保存的输入,不能重新计算修订。服务端开通示例见 [examples/billing.mjs](examples/billing.mjs)。TypeScript 可通过 `import { UsageIssuerClient, type BillingSummary } from "@bailinghub/connect/usage"` 获取完整的套餐与身份类型。
@@ -0,0 +1,21 @@
1
+ import { UsageIssuerClient } from '../src/usage.mjs';
2
+
3
+ /** Invoke after authenticating a user in your own backend. No network call occurs on import. */
4
+ export async function prepareBillingPlan({ baseUrl, issuerToken, identity, loginRequestKey, serviceId, planId, orderRequestKey }) {
5
+ const issuer = new UsageIssuerClient({ baseUrl, issuerToken });
6
+ const login = await issuer.exchangeSession({
7
+ ...identity, request_key: loginRequestKey, service_id: serviceId, model_access: 'token_gateway',
8
+ });
9
+ const accountId = login.session.accountId;
10
+ const summary = await issuer.getBillingSummary(accountId);
11
+ // Persist this exact body with your order before calling grantBillingPlan.
12
+ const grantInput = { request_key: orderRequestKey, plan_id: planId, expected_revision: summary.grant?.revision ?? 0 };
13
+ return { credential: login.credential, session: login.session, accountId, grantInput };
14
+ }
15
+
16
+ /** Submit the saved input, including its original revision. Do not prepare it again on retry. */
17
+ export async function applyBillingPlan({ baseUrl, issuerToken, accountId, grantInput }) {
18
+ const issuer = new UsageIssuerClient({ baseUrl, issuerToken });
19
+ await issuer.grantBillingPlan(accountId, grantInput);
20
+ return (await issuer.getBillingSummary(accountId)).presentation;
21
+ }
@@ -5,7 +5,11 @@
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
7
7
  "exports": {
8
- ".": "./src/index.mjs"
8
+ ".": "./src/index.mjs",
9
+ "./usage": {
10
+ "types": "./src/usage.d.mts",
11
+ "default": "./src/usage.mjs"
12
+ }
9
13
  },
10
14
  "files": [
11
15
  "src",
@@ -248,3 +248,5 @@ export class HubClient {
248
248
  }
249
249
  }
250
250
  }
251
+
252
+ export { UsageIssuerClient, UsageIssuerError } from './usage.mjs';