bailinghub 0.8.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.
- package/README.en.md +6 -5
- package/README.md +6 -5
- package/docker-compose.images.yml +2 -2
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHANGELOG.en.md +12 -1
- package/docs/CHANGELOG.md +12 -1
- package/docs/COMPATIBILITY.en.md +4 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/MODEL_BILLING.en.md +123 -0
- package/docs/MODEL_BILLING.md +125 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
- package/docs/README.en.md +5 -1
- package/docs/README.md +4 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
- package/docs/RELEASE_NOTES_NEXT.md +4 -2
- package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
- package/docs/UPGRADE_v0.9.0.en.md +54 -0
- package/docs/UPGRADE_v0.9.0.md +54 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
- package/package.json +1 -1
- package/scripts/check-doc-links.mjs +4 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +1 -0
- package/scripts/sdk-runtime-test.mjs +6 -0
- package/scripts/verify-billing-install-upgrade.mjs +225 -0
- package/scripts/verify-github-repo.mjs +1 -0
- package/sdk/node/README.md +17 -0
- package/sdk/node/examples/billing.mjs +21 -0
- package/sdk/node/package.json +5 -1
- package/sdk/node/src/index.mjs +2 -0
- package/sdk/node/src/usage.d.mts +74 -0
- package/sdk/node/src/usage.mjs +62 -0
- package/sdk/node/tests/usage-types.mts +23 -0
- package/sdk/node/tests/usage.test.mjs +81 -0
- package/sdk/php7/README.md +19 -2
- package/sdk/php7/examples/billing.php +27 -0
- package/sdk/php7/examples/well-known.php +1 -1
- package/sdk/php7/src/ToolSpec.php +1 -1
- package/sdk/php7/src/UsageClient.php +95 -0
- package/sdk/php7/src/UsageClientException.php +22 -0
- package/sdk/php7/tests/billing-core-http.php +59 -0
- package/sdk/php7/tests/usage-client.php +78 -0
- package/sql/063_usage_model_billing.sql +153 -0
- package/sql/064_period_plan_allowance.sql +25 -0
- package/sql/README.en.md +12 -4
- package/sql/README.md +14 -6
- package/src/app/auth.ts +2 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/infrastructure/config/configstore.ts +6 -0
- package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
- package/src/modules/usage/billing-contracts.ts +59 -0
- package/src/modules/usage/billing-decimal.test.ts +22 -0
- package/src/modules/usage/billing-decimal.ts +36 -0
- package/src/modules/usage/billing-external.ts +39 -0
- package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
- package/src/modules/usage/billing-ledger.test.ts +51 -0
- package/src/modules/usage/billing-ledger.ts +104 -0
- package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
- package/src/modules/usage/billing-presentation.test.ts +49 -0
- package/src/modules/usage/billing-presentation.ts +34 -0
- package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
- package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
- package/src/modules/usage/billing-repository.ts +463 -0
- package/src/modules/usage/contracts.ts +49 -0
- package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
- package/src/modules/usage/errors.ts +19 -0
- package/src/modules/usage/http.ts +85 -0
- package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
- package/src/modules/usage/identity.mysql.test.ts +120 -0
- package/src/modules/usage/identity.ts +303 -0
- package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
- package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
- package/src/modules/usage/model-gateway.ts +229 -0
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
- package/src/modules/usage/model-tool-provider.test.ts +37 -0
- package/src/modules/usage/model-tool-provider.ts +110 -0
- package/src/modules/usage/model-tools.test.ts +36 -0
- package/src/modules/usage/model-tools.ts +62 -0
- package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
- package/src/modules/usage/period.test.ts +26 -0
- package/src/modules/usage/period.ts +96 -0
- package/src/modules/usage/pricing.test.ts +178 -0
- package/src/modules/usage/pricing.ts +228 -0
- package/src/modules/usage/provider-failure.ts +37 -0
- package/src/modules/usage/provider-stream.test.ts +85 -0
- package/src/modules/usage/provider-stream.ts +77 -0
- package/src/modules/usage/provider.test.ts +67 -0
- package/src/modules/usage/provider.ts +142 -0
- package/src/modules/usage/repository.ts +539 -0
- package/src/modules/usage/service-availability.mysql.test.ts +68 -0
- package/src/modules/usage/service-availability.ts +13 -0
- package/src/modules/usage/service-delete.mysql.test.ts +87 -0
- package/src/modules/usage/stream-http.ts +32 -0
- package/src/modules/usage/test-harness.ts +108 -0
- package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
- package/src/modules/usage/usage-deletion.ts +119 -0
- package/src/modules/usage/validation.test.ts +18 -0
- package/src/modules/usage/validation.ts +33 -0
- package/src/routes/admin-billing-usage.ts +73 -0
- package/src/routes/admin-usage.ts +147 -0
- package/src/routes/admin.ts +4 -0
- package/src/routes/private.ts +8 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/Accounts-Bervi5JU.css +1 -0
- package/web/console/assets/Accounts-DnddhY6t.js +3 -0
- package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-VInbD7JS.js} +1 -1
- package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
- package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
- package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-34qUPHf0.js} +1 -1
- package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-BbVgkSm2.js} +1 -1
- package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-DgscF28e.js} +1 -1
- package/web/console/assets/{Channels-B9n4fbxg.js → Channels-Bp-yuk8d.js} +1 -1
- package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-C9Ft60TS.js} +1 -1
- package/web/console/assets/{Clients-CI3DBDHf.js → Clients-NPldD-DD.js} +1 -1
- package/web/console/assets/{Cost-JgNXQPlN.js → Cost-DZcuB-EB.js} +1 -1
- package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-RTT7N6zl.js} +1 -1
- package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-_LeK8cce.js} +1 -1
- package/web/console/assets/{Executors-CRbboOCZ.js → Executors-Bi7H8rIm.js} +1 -1
- package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
- package/web/console/assets/{Kb-CgLNGjRp.js → Kb-BHamz8NP.js} +2 -2
- package/web/console/assets/{Login-C52JmXzx.js → Login-C1rJR-6w.js} +1 -1
- package/web/console/assets/{Projects-CDOvHPVS.js → Projects-BRA4a48v.js} +1 -1
- package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
- package/web/console/assets/Routes-CyXV4Pba.css +1 -0
- package/web/console/assets/{Runs-DYNDXsqk.js → Runs-B_fa_BlD.js} +1 -1
- package/web/console/assets/{Setup-B91P6i1x.js → Setup-C1_d0mFy.js} +1 -1
- package/web/console/assets/Shell-CHEV6RGC.js +1 -0
- package/web/console/assets/Shell-ykb-tUfo.css +1 -0
- package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DlG3ojhA.js} +1 -1
- package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-DYo2gg6d.js} +1 -1
- package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-DKCoUZlq.js} +1 -1
- package/web/console/assets/{Targets-CuuIYeZO.js → Targets-CdkG6BPR.js} +1 -1
- package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DVpCt0ox.js} +1 -1
- package/web/console/assets/Usage-CAeDGjrb.css +1 -0
- package/web/console/assets/Usage-DWCpLugC.js +1 -0
- package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
- package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
- package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
- package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
- package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
- package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
- package/web/console/assets/index-H1kfa0Mj.js +2 -0
- package/web/console/assets/{request-DeGya810.js → request-DLsP1_ot.js} +1 -1
- package/web/console/assets/{schema-BqlqLw1R.js → schema-BLOHvAJQ.js} +1 -1
- package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
- package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
- package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
- package/web/console/index.html +3 -3
- package/web-admin/README.md +17 -0
- package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
- package/web-admin/src/components/UsageHelp.vue +72 -0
- package/web-admin/src/components/UsageServiceReferences.vue +169 -0
- package/web-admin/src/layout/Shell.vue +22 -5
- package/web-admin/src/pages/Accounts.vue +3 -3
- package/web-admin/src/pages/AgentTasks.vue +2 -2
- package/web-admin/src/pages/Routes.vue +5 -1
- package/web-admin/src/pages/Usage.vue +2470 -0
- package/web-admin/src/pages/UsageAccess.vue +1147 -0
- package/web-admin/src/router.ts +8 -4
- package/web-admin/src/styles/base.css +57 -0
- package/web-admin/src/table-widths.ts +16 -1
- package/web-admin/src/usage-deletion.ts +40 -0
- package/web-admin/src/usage-management.ts +13 -0
- package/web-admin/src/usage-presentation.test.ts +21 -0
- package/web-admin/src/usage-presentation.ts +107 -0
- package/web-admin/src/usage-price-preview.test.ts +60 -0
- package/web-admin/src/usage-price-preview.ts +54 -0
- package/web-admin/tests/token-usage.browser.mjs +773 -0
- package/web-admin/tests/usage-access.browser.mjs +398 -0
- package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
- package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
- package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
- package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
- package/web/console/assets/Routes-DkMIjMQA.css +0 -1
- package/web/console/assets/Routes-X9vHLpKW.js +0 -124
- package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
- package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
- package/web/console/assets/index-UGvfF3Xr.js +0 -2
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Current release: Core 0.9.0
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Core 0.9.0 introduces an optional model billing gateway, shared USD plans, periodic allowances and text-to-image tools. Release pairing: SDK 0.7.0 / DSH 0.7.0.
|
|
4
|
+
|
|
5
|
+
[Core 0.9.0 release notes](RELEASE_NOTES_v0.9.0.en.md) · [Upgrade guide](UPGRADE_v0.9.0.en.md) · [Billing contract](MODEL_BILLING.en.md) · [简体中文](RELEASE_NOTES_NEXT.md)
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 当前版本:Core 0.9.0
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Core 0.9.0 提供可选模型计费网关、统一 USD 套餐、周期额度与文生图工具。配套为 SDK 0.7.0 / DSH 0.7.0。
|
|
4
|
+
|
|
5
|
+
[Core 0.9.0 版本说明](RELEASE_NOTES_v0.9.0.md) · [升级指南](UPGRADE_v0.9.0.md) · [计费契约](MODEL_BILLING.md) · [English](RELEASE_NOTES_NEXT.en.md)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# BailingHub v0.9.0: model services and shared plan allowances
|
|
2
|
+
|
|
3
|
+
Release pairing: **Core 0.9.0 / MCP and Agent Client SDK 0.7.0 / DSH 0.7.0**. These notes describe changes and upgrade impact relative to public Core 0.8.0.
|
|
4
|
+
|
|
5
|
+
An enterprise assistant may select a conversation model, generate a campaign image and then call an authorized business API. Administrators can now give those models and generation tools a shared allowance. The local host continues to orchestrate the conversation and task; the Hub records original requests, actual usage and settlement. Existing business permissions and approvals still apply.
|
|
6
|
+
|
|
7
|
+
## An optional lightweight model billing gateway
|
|
8
|
+
|
|
9
|
+
Enable model billing when needed. Administrators configure a provider connection, actual model identifier, reference pricing model and endpoint, then grant a plan to a personal or shared organization account. Conversation models and model tools have separate discovery catalogs. Charges are not based on user turns or task steps.
|
|
10
|
+
|
|
11
|
+
The actual model identifier can differ from the reference catalog identifier; operators explicitly verify that mapping. OpenRouter supplies reference prices, **not the actual provider's paid price or invoice**. Each request retains its price and plan-multiplier snapshot, so later price changes do not recalculate history. Unready services stay out of callable catalog entries; hosts can show the reason and direct users to their administrator.
|
|
12
|
+
|
|
13
|
+
## One plan, one USD allowance
|
|
14
|
+
|
|
15
|
+
Every model and tool in a plan shares its USD allowance and a single multiplier. For example, an Enterprise Assistant monthly plan may sell for 300 USD and provide 100 USD per month at a 1.5 multiplier. A request with a 0.20 USD reference cost deducts 0.30 USD, leaving an actual allowance ratio of 99.70%.
|
|
16
|
+
|
|
17
|
+
- **Periodic plans** separate sale price `priceUsd` from per-period allowance `periodAllowanceUsd`. Daily, weekly or monthly resets restore that allowance; customers see a remaining percentage whose denominator is the allowance.
|
|
18
|
+
- **Credit packs** use `priceUsd` as the one-time USD allowance. Customers see Credits at a fixed 1000 Credits per USD, with no separate credit ledger.
|
|
19
|
+
- Validity and reset periods are independent. A final partial period still provides the full allowance; expiration stops new requests and unused allowance does not roll over. Template price edits do not reset existing grant terms; the current service set and unified multiplier are read from the plan.
|
|
20
|
+
- The business application owns payment, currency conversion, refunds and product pricing. Raw Token counts remain usage evidence, not plan limits or percentage denominators.
|
|
21
|
+
|
|
22
|
+
## Text-to-image tools and asynchronous settlement
|
|
23
|
+
|
|
24
|
+
Model tools declare their name, purpose, parameters and output; hosts choose and invoke them. Initial executable adapters support text-to-image through Aliyun's OpenAI Images-compatible API, native DashScope and OpenRouter Images. Video, voice and custom capabilities may be declared, but remain explicitly uncallable without an execution adapter. A saved declaration does not imply generation support.
|
|
25
|
+
|
|
26
|
+
Image requests persist dispatch evidence and finish asynchronously. Hosts query the original `operation_id`. A completed result can be used while billing awaits actual metering; missing reliable usage never becomes an invented fee or Token count. Positive balances admit requests; late concurrent settlements can create an overage, and depleted balances block new requests.
|
|
27
|
+
|
|
28
|
+
Connection loss, missing responses and unknown outcomes retain the original ID rather than creating another generation. Confirmed rejection and unknown results are distinct. Late usage after cancellation remains accountable and does not revive a finished turn. Hosts can reuse the existing attachment space for image URLs/Base64 when needed; generation does not automatically modify business data.
|
|
29
|
+
|
|
30
|
+
## Everyday administration
|
|
31
|
+
|
|
32
|
+
- Removing a plan preserves its identity, grants, allowance pools, requests and ledger. A plan still used by an effective grant requires its use relationship to be resolved first. Suspending a template only stops new grants.
|
|
33
|
+
- Disabled personal and shared accounts can be archived. Restoration returns the original account to disabled state; revoked credentials and members are not restored and allowance is not replenished.
|
|
34
|
+
- Authorized administrators can reset an active account's effective Hub-managed plan. Periodic plans regain their original period allowance with a new period anchor; credit packs regain their original Credits. Expiration is unchanged and original in-flight requests settle against their original pool.
|
|
35
|
+
- Console examples use generic business-assistant and enterprise-service descriptions suitable for different business systems.
|
|
36
|
+
|
|
37
|
+
## Upgrade impact and acceptance
|
|
38
|
+
|
|
39
|
+
From public Core 0.8.0, use the official migrator to apply `063_usage_model_billing.sql` and `064_period_plan_allowance.sql`, retaining existing data and the migration ledger. **Normal public-version upgrades require no real-data or test-data purge.** Instances that already deployed a billing preview separately follow the [period allowance guide](PERIOD_ALLOWANCE_UPGRADE.en.md) for original snapshots.
|
|
40
|
+
|
|
41
|
+
Hosts opt into model catalogs, tools, summaries and persistent original-request records. Business backends adopt provisioning or plan-scoped identity APIs only when needed. Existing business-tool deployments need not enable model billing. Identity, permissions, session scope, approvals, task controls and business-call archives remain independent.
|
|
42
|
+
|
|
43
|
+
Verify enabled service configuration, customer allowance display, actual usage, original-ID recovery and administration against the final matched artifacts. Automated checks do not establish provider, client or production acceptance.
|
|
44
|
+
|
|
45
|
+
[Paired upgrade guide](UPGRADE_v0.9.0.en.md) · [Model billing contract](MODEL_BILLING.en.md) · [简体中文](RELEASE_NOTES_v0.9.0.md)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# 百灵中枢 v0.9.0:模型服务与统一套餐额度
|
|
2
|
+
|
|
3
|
+
版本:**Core 0.9.0 / MCP 与 Agent Client SDK 0.7.0 / DSH 0.7.0**。本页说明相对公开 Core 0.8.0 的变化与升级影响。
|
|
4
|
+
|
|
5
|
+
企业业务助手需要在对话中选择模型、生成活动图片,再调用已获授权的业务接口。管理员现在可以为这些模型与生成工具配置一份共享额度;本地宿主继续负责对话和任务编排,中枢记录原请求、计量及结算,原业务权限与审批继续生效。
|
|
6
|
+
|
|
7
|
+
## 可选的微型模型计费网关
|
|
8
|
+
|
|
9
|
+
模型计费按需启用。管理员配置模型连接、实际调用型号、参考计价模型与端点,再创建套餐并开通给个人或组织共享账户。对话模型与模型工具进入独立目录,宿主按能力发现接入;中枢不按用户轮次或任务步数收费。
|
|
10
|
+
|
|
11
|
+
实际调用型号可以与参考目录中的型号不同,管理员需要显式核对映射。参考价格来自 OpenRouter,**不代表实际模型供应商的实付价格或账单**。每个请求保留参考价格和套餐倍率快照,后续调价不重算历史请求。配置未就绪的服务不会进入可调用目录,宿主可读取原因并提示联系管理员。
|
|
12
|
+
|
|
13
|
+
## 一个套餐、一份 USD 额度
|
|
14
|
+
|
|
15
|
+
套餐统一使用 USD 计量,同一套餐内所有模型与工具共用额度与一个倍率。例如“企业服务助手”月套餐售价 300 USD,每月额度 100 USD,倍率 1.5;一次请求参考费用 0.20 USD,结算扣除 0.30 USD,实际剩余额度占比为 99.70%。
|
|
16
|
+
|
|
17
|
+
- **周期套餐**:售价 `priceUsd` 与每周期额度 `periodAllowanceUsd` 分开设置。按日、周或月恢复额度,客户显示剩余百分比;分母是周期额度。
|
|
18
|
+
- **额度包**:`priceUsd` 提供一次性 USD 额度,客户显示 Credits(积分),固定 1 USD = 1000 Credits。没有独立积分账本。
|
|
19
|
+
- 有效期与重置周期分开,最后不足一个完整周期仍提供完整额度,到期停止新请求,未用额度不结转。模板改价不会重置已开通账户的原额度条款;当前模型集合和统一倍率按套餐读取。
|
|
20
|
+
- 支付、汇率、退款及商品定价由业务侧处理。原始 Token 是用量记录,不是套餐上限或百分比分母。
|
|
21
|
+
|
|
22
|
+
## 文生图与异步结算
|
|
23
|
+
|
|
24
|
+
模型工具声明名称、用途、参数及输出,宿主负责选择并调用。首批可执行适配为阿里云 OpenAI Images 兼容接口、DashScope 原生接口和 OpenRouter Images 接口的文生图。视频、语音与自定义能力可以保存声明;没有执行适配时明确不可调用,不表示已支持生成。
|
|
25
|
+
|
|
26
|
+
图片请求保存派发记录后异步完成,宿主用原 `operation_id` 查询结果。结果完成即可使用,计费可能仍在等待实际计量;缺少可信计量不猜测费用或伪造 Token。余额为正时允许新请求,并发晚结算可能产生超额,余额耗尽后阻止新请求。
|
|
27
|
+
|
|
28
|
+
断网、回包丢失或结果未知时保持原 ID,不另建生成请求。明确拒绝与结果未知分开展示;取消后的晚到结果仍可记录用量,不恢复已结束轮次。图片 URL/Base64 可由宿主按需写入已有附件空间,生成成功不会自动修改业务数据。
|
|
29
|
+
|
|
30
|
+
## 后台日常管理
|
|
31
|
+
|
|
32
|
+
- 套餐移除保留原 ID、历史开通、额度池、请求及账本;仍被有效开通使用的套餐需要先处理使用关系。停用模板只停止新开通。
|
|
33
|
+
- 个人账户和组织共享账户停用后可移除归档;恢复回原账户的停用状态,旧凭证与被撤销成员不恢复,额度不补发。
|
|
34
|
+
- 有权限的管理员可为启用账户手动重置中枢维护的有效套餐:周期套餐恢复到原周期额度并重新起算周期,额度包恢复原始积分。到期时间不延长;原在途请求仍向原额度池结算。
|
|
35
|
+
- 控制台的接入示例使用通用业务助手和企业服务描述,便于各类业务系统复用。
|
|
36
|
+
|
|
37
|
+
## 升级影响与验收
|
|
38
|
+
|
|
39
|
+
从公开 Core 0.8.0 升级时,通过正式迁移器应用新增的 `063_usage_model_billing.sql` 和 `064_period_plan_allowance.sql`,保留原数据和迁移账本。**正常公开版升级不要求清退真实数据或旧测试数据。** 已部署过计费预览的实例另按[周期额度说明](PERIOD_ALLOWANCE_UPGRADE.md)核对原快照。
|
|
40
|
+
|
|
41
|
+
客户端宿主按需接入模型目录、工具、摘要与原请求持久记录;业务后端仅在需要开通套餐或提供套餐范围身份时接入对应接口。只使用既有业务工具的部署无需开启模型计费。原身份、权限、会话范围、审批、长任务控制与业务调用归档保持独立。
|
|
42
|
+
|
|
43
|
+
验收应覆盖所启用的服务配置、额度展示、实际计量、原 ID 查询及管理操作,并核对最终制品与配套版本。自动化通过不等于供应商、客户端或生产环境的实际验收。
|
|
44
|
+
|
|
45
|
+
[配套升级指南](UPGRADE_v0.9.0.md) · [模型服务与套餐计费](MODEL_BILLING.md) · [English](RELEASE_NOTES_v0.9.0.en.md)
|
|
@@ -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,9 @@
|
|
|
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
|
+
|
|
3
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).
|
|
4
8
|
|
|
5
9
|
> 这份策略用于公开发布后的版本演进。目标是让绝大多数升级都能平滑完成:拉新版、执行数据库结构同步、重启 hub;已配置的路由、凭证、工具源、聊天入口不需要重配。破坏性变更必须显式说明,并提供过渡窗口。
|
package/package.json
CHANGED
|
@@ -104,6 +104,10 @@ const englishCompanions = {
|
|
|
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
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',
|
|
107
111
|
'docs/RELEASE_NOTES_v0.7.0.md': 'docs/RELEASE_NOTES_v0.7.0.en.md',
|
|
108
112
|
'docs/RELEASE_NOTES_v0.6.1.md': 'docs/RELEASE_NOTES_v0.6.1.en.md',
|
|
109
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.
|
|
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.
|
|
42
|
-
assert.equal(result.stableVersion, '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
|
|
package/scripts/install.sh
CHANGED
|
@@ -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.
|
|
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.
|
|
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}"
|
|
@@ -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
|
+
}
|
|
@@ -131,6 +131,7 @@ const requiredFiles = [
|
|
|
131
131
|
'docs/RELEASE_NOTES_v0.5.1.md',
|
|
132
132
|
'docs/RELEASE_NOTES_v0.7.0.md',
|
|
133
133
|
'docs/RELEASE_NOTES_v0.8.0.md',
|
|
134
|
+
'docs/RELEASE_NOTES_v0.9.0.md',
|
|
134
135
|
'docs/RELEASE_NOTES_v0.6.1.md',
|
|
135
136
|
'docs/RELEASE_NOTES_v0.6.0.md',
|
|
136
137
|
'docs/CHANGELOG.md',
|
package/sdk/node/README.md
CHANGED
|
@@ -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
|
+
}
|