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,773 @@
1
+ import { chromium } from "playwright";
2
+ import assert from "node:assert/strict";
3
+ import { mkdir } from "node:fs/promises";
4
+ const url =
5
+ process.env.TOKEN_CONSOLE_URL || "http://127.0.0.1:4437/console/usage";
6
+ const output =
7
+ process.env.TOKEN_CONSOLE_EVIDENCE || "/tmp/bailing-token-console";
8
+ await mkdir(output, { recursive: true });
9
+ const browser = await chromium.launch({ headless: true });
10
+ const context = await browser.newContext({
11
+ viewport: { width: 1440, height: 1100 },
12
+ });
13
+ const page = await context.newPage();
14
+ page.setDefaultTimeout(10000);
15
+ let permissions = ["*"];
16
+ const errors = [],
17
+ unexpected = [],
18
+ posts = [];
19
+ page.on("pageerror", (e) => errors.push(e.message));
20
+ page.on("console", (m) => {
21
+ if (
22
+ m.type() === "warning" &&
23
+ m.text().includes("Failed to resolve component")
24
+ )
25
+ errors.push(m.text());
26
+ });
27
+ const accounts = [
28
+ {
29
+ id: "account-synthetic",
30
+ label: "合成验收账户",
31
+ kind: "personal",
32
+ state: "active",
33
+ },
34
+ ];
35
+ const services = [
36
+ {
37
+ id: "general",
38
+ label: "通用模型",
39
+ revision: 1,
40
+ state: "active",
41
+ config: {
42
+ credential: "synthetic-provider",
43
+ model: "synthetic-chat",
44
+ providerScope: "synthetic-provider",
45
+ maxInputBytes: 8388608,
46
+ maxOutputTokens: 8192,
47
+ timeoutMs: 120000,
48
+ },
49
+ },
50
+ {
51
+ id: "reasoning",
52
+ label: "推理模型",
53
+ revision: 1,
54
+ state: "active",
55
+ config: {
56
+ credential: "synthetic-provider",
57
+ model: "synthetic-reasoning",
58
+ providerScope: "synthetic-provider",
59
+ maxInputBytes: 8388608,
60
+ maxOutputTokens: 8192,
61
+ timeoutMs: 120000,
62
+ },
63
+ },
64
+ ];
65
+ let plans = [],
66
+ activeGrant = null,
67
+ dropGrantAck = true,
68
+ grantWrites = 0,
69
+ grantKey = null,
70
+ failPlanRead = false;
71
+ let projectionOverride;
72
+ const syntheticPresentation = () =>
73
+ projectionOverride !== undefined
74
+ ? projectionOverride
75
+ : !activeGrant
76
+ ? {
77
+ schema: "bailing.usage-presentation.v1",
78
+ kind: "none",
79
+ state: "unavailable",
80
+ remaining: null,
81
+ total: null,
82
+ displayValue: null,
83
+ }
84
+ : {
85
+ schema: "bailing.usage-presentation.v1",
86
+ kind:
87
+ activeGrant.config.mode === "periodic" ? "percentage" : "credits",
88
+ state: activeGrant.state === "active" ? "active" : "suspended",
89
+ remaining: activeGrant.state === "active" ? 99.9 : null,
90
+ total: 100,
91
+ displayValue: activeGrant.state === "active" ? "99" : null,
92
+ };
93
+ const summary = () => ({
94
+ presentation: syntheticPresentation(),
95
+ schema: "bailing.token-summary.v1",
96
+ accountId: accounts[0].id,
97
+ grant: activeGrant,
98
+ plan: activeGrant ? (() => { const p=plans.find(p=>p.id===activeGrant.planId); return p ? {id:p.id,label:p.label,revision:p.revision,serviceIds:p.config.serviceIds}:null; })() : null,
99
+ availableTokens: activeGrant ? 999000 : 0,
100
+ consumedTokens: 1000,
101
+ currentPeriodConsumedTokens: 1000,
102
+ overageTokens: 0,
103
+ pendingRequests: 1,
104
+ resetAt:
105
+ activeGrant?.config.mode === "periodic" ? Date.now() + 86400000 : null,
106
+ expiresAt: activeGrant ? Date.now() + 2592000000 : null,
107
+ });
108
+ await page.route("**/branding", (r) => r.fulfill({ json: {} }));
109
+ await page.route("**/health", (r) => r.fulfill({ json: { status: "ok" } }));
110
+ await page.route("**/admin/api/**", async (r) => {
111
+ const p = new URL(r.request().url()).pathname,
112
+ method = r.request().method();
113
+ if (method === "POST")
114
+ posts.push({ path: p, body: r.request().postDataJSON() });
115
+ if (p === "/admin/api/me")
116
+ return r.fulfill({
117
+ json: {
118
+ username: "synthetic-admin",
119
+ role: "admin",
120
+ via: "synthetic",
121
+ perms: permissions,
122
+ },
123
+ });
124
+ if (p === "/admin/api/status") return r.fulfill({ json: { executors: [] } });
125
+ if (p === "/admin/api/demo-dataset/status")
126
+ return r.fulfill({ json: { imported: false } });
127
+ if (p === "/admin/api/usage/services") {
128
+ if (method === "GET") return r.fulfill({ json: { items: services } });
129
+ const b = r.request().postDataJSON();
130
+ const original = services.find((item) => item.id === b.id);
131
+ assert.equal(b.expected_revision, original?.revision || 0);
132
+ const saved = {
133
+ id: b.id,
134
+ label: b.label,
135
+ state: b.state,
136
+ revision: (original?.revision || 0) + 1,
137
+ config: b.config,
138
+ };
139
+ if (original) Object.assign(original, saved);
140
+ else services.push(saved);
141
+ return r.fulfill({ json: saved });
142
+ }
143
+ if (p === "/admin/api/usage/accounts")
144
+ return r.fulfill({ json: { items: accounts, next_cursor: null } });
145
+ if (p === "/admin/api/usage/token/plans") {
146
+ if (method === "GET")
147
+ return failPlanRead
148
+ ? r.fulfill({ status: 503, json: { error: "USAGE_TOKEN_UNSUPPORTED" } })
149
+ : r.fulfill({ json: { items: plans } });
150
+ const b = r.request().postDataJSON(),
151
+ old = plans.find((x) => x.id === b.id);
152
+ assert.equal(b.expected_revision, old?.revision || 0);
153
+ const plan = {
154
+ id: b.id,
155
+ label: b.label,
156
+ state: b.state,
157
+ revision: (old?.revision || 0) + 1,
158
+ config: b.config,
159
+ };
160
+ plans = plans.filter((x) => x.id !== b.id).concat(plan);
161
+ return r.fulfill({ json: plan });
162
+ }
163
+ if (p.endsWith("/summary")) return r.fulfill({ json: summary() });
164
+ if (p.endsWith("/requests"))
165
+ return r.fulfill({
166
+ json: {
167
+ items: [
168
+ {
169
+ operation_id: "synthetic-complete",
170
+ service_id: "general",
171
+ result_state: "complete",
172
+ billing_state: "settled",
173
+ charged_tokens: 1000,
174
+ usage: { inputTokens: 800, outputTokens: 200 },
175
+ },
176
+ {
177
+ operation_id: "synthetic-pending-usage",
178
+ service_id: "reasoning",
179
+ result_state: "complete",
180
+ billing_state: "pending",
181
+ charged_tokens: null,
182
+ },
183
+ ],
184
+ next_cursor: null,
185
+ },
186
+ });
187
+ if (p.endsWith("/grant")) {
188
+ const b = r.request().postDataJSON();
189
+ if (!grantKey) {
190
+ grantKey = b.request_key;
191
+ grantWrites++;
192
+ const plan = plans.find((x) => x.id === b.plan_id);
193
+ activeGrant = {
194
+ id: "synthetic-grant",
195
+ label: plan.label,
196
+ planId: plan.id,
197
+ revision: 1,
198
+ state: "active",
199
+ sourceOwner: "hub",
200
+ startsAt: Date.now(),
201
+ config: (({serviceIds,...allowance})=>structuredClone(allowance))(plan.config),
202
+ };
203
+ }
204
+ assert.equal(b.request_key, grantKey);
205
+ assert.equal(b.expected_revision, 0);
206
+ if (dropGrantAck) {
207
+ dropGrantAck = false;
208
+ return r.abort("connectionreset");
209
+ }
210
+ return r.fulfill({ json: activeGrant });
211
+ }
212
+ if (p.endsWith("/control")) {
213
+ const b = r.request().postDataJSON();
214
+ assert.equal(b.expected_revision, activeGrant.revision);
215
+ activeGrant = {
216
+ ...activeGrant,
217
+ state: b.state,
218
+ revision: activeGrant.revision + 1,
219
+ };
220
+ return r.fulfill({ json: activeGrant });
221
+ }
222
+ unexpected.push({ p, method });
223
+ return r.fulfill({
224
+ status: 404,
225
+ json: { error: "UNEXPECTED_SYNTHETIC_ENDPOINT" },
226
+ });
227
+ });
228
+ try {
229
+ await page.goto(url);
230
+ await page.getByRole("button", { name: "新建套餐", exact: true }).click();
231
+ await page.getByLabel("套餐名称", { exact: true }).fill("联调周享套餐");
232
+ await page
233
+ .locator(".model-choices .el-checkbox")
234
+ .filter({ hasText: "通用模型" })
235
+ .click();
236
+ await page
237
+ .locator(".model-choices .el-checkbox")
238
+ .filter({ hasText: "推理模型" })
239
+ .click();
240
+ const planPreview = page.locator(".preview");
241
+ const creditsMode = page.getByRole("radio", {
242
+ name: "额度包 一次获得固定额度,在有效期内按需使用。",
243
+ exact: true,
244
+ });
245
+ const periodicMode = page.getByRole("radio", {
246
+ name: "周期套餐 订阅期间按日、周或月获得新一期额度。",
247
+ exact: true,
248
+ });
249
+ assert.match(
250
+ await planPreview.locator(".preview-amount").innerText(),
251
+ /100%/,
252
+ );
253
+ assert.doesNotMatch(await planPreview.innerText(), /Token|Credits|相当于/i);
254
+ assert.match(await planPreview.innerText(), /本期剩余额度不累积到下一期/);
255
+ await creditsMode.check();
256
+ assert.match(await planPreview.innerText(), /未用积分在套餐有效期内可用/);
257
+ assert.doesNotMatch(await planPreview.innerText(), /不累积到下一期/);
258
+ assert.match(
259
+ await planPreview.locator(".preview-amount").innerText(),
260
+ /1,000积分/,
261
+ );
262
+ await page.getByLabel("总额度", { exact: true }).fill("0.0101");
263
+ await page.getByLabel("每 1 积分对应的 Token", { exact: true }).fill("100");
264
+ await page.getByLabel("套餐名称", { exact: true }).focus();
265
+ assert.match(
266
+ await planPreview.locator(".preview-amount").innerText(),
267
+ /1.01积分/,
268
+ );
269
+ await page.getByLabel("总额度", { exact: true }).fill("0.0001");
270
+ await page.getByLabel("每 1 积分对应的 Token", { exact: true }).fill("1000");
271
+ await page.getByLabel("套餐名称", { exact: true }).focus();
272
+ assert.match(
273
+ await planPreview.locator(".preview-amount").innerText(),
274
+ /<0.01积分/,
275
+ );
276
+ await periodicMode.check();
277
+ assert.match(
278
+ await planPreview.locator(".preview-amount").innerText(),
279
+ /100%/,
280
+ );
281
+ await page.getByLabel("每期额度", { exact: true }).fill("100");
282
+ await page.getByLabel("套餐名称", { exact: true }).focus();
283
+ assert.equal(
284
+ await page.getByText("用户看到的额度单位", { exact: true }).count(),
285
+ 0,
286
+ );
287
+ assert.equal(
288
+ await page
289
+ .locator(".plan-form")
290
+ .getByText(/轮次上限|每轮最多|单轮最长/)
291
+ .count(),
292
+ 0,
293
+ );
294
+ await page.locator(".main").evaluate((el) => (el.scrollTop = 0));
295
+ await page.screenshot({
296
+ path: `${output}/token-plan-desktop.png`,
297
+ fullPage: true,
298
+ animations: "disabled",
299
+ });
300
+ await page.getByRole("button", { name: "保存套餐", exact: true }).click();
301
+ await page.getByRole("button", { name: "新建套餐", exact: true }).waitFor();
302
+ assert.equal(plans.length, 1);
303
+ assert.equal(plans[0].config.quotaTokens, 1000000);
304
+ assert.deepEqual(plans[0].config.serviceIds, ["general", "reasoning"]);
305
+ assert.equal("displayUnit" in plans[0].config, false);
306
+ assert.deepEqual(
307
+ Object.keys(plans[0].config).sort(),
308
+ [
309
+ "mode",
310
+ "serviceIds",
311
+ "quotaTokens",
312
+ "periodUnit",
313
+ "duration",
314
+ "tokensPerCredit",
315
+ ].sort(),
316
+ );
317
+ await page.getByRole("button", { name: "编辑", exact: true }).click();
318
+ await page.getByLabel("套餐名称", { exact: true }).fill("联调周享套餐修订");
319
+ await page.getByRole("button", { name: "保存套餐", exact: true }).click();
320
+ await page.getByRole("button", { name: "新建套餐", exact: true }).waitFor();
321
+ assert.equal(plans[0].revision, 2);
322
+ await page.getByRole("button", { name: "开通给账户", exact: true }).click();
323
+ await page.getByRole("dialog").locator(".el-select").first().click();
324
+ await page.getByRole("option", { name: "合成验收账户", exact: true }).click();
325
+ assert.match(await page.locator(".grant-preview").innerText(), /剩余 100 %/);
326
+ assert.doesNotMatch(
327
+ await page.locator(".grant-preview").innerText(),
328
+ /Token|Credits|相当于/i,
329
+ );
330
+ await page.getByRole("button", { name: "确认开通", exact: true }).click();
331
+ await page
332
+ .getByRole("button", { name: "核对 / 重试原请求", exact: true })
333
+ .waitFor();
334
+ await page.reload();
335
+ await page
336
+ .getByRole("button", { name: "核对 / 重试原请求", exact: true })
337
+ .click();
338
+ await page
339
+ .getByText("上一次保存需要核对", { exact: true })
340
+ .waitFor({ state: "hidden" });
341
+ assert.equal(grantWrites, 1);
342
+ assert.equal(posts.filter((x) => x.path.endsWith("/grant")).length, 2);
343
+ await page.getByRole("tab", { name: "账户用量", exact: true }).click();
344
+ await page.getByRole("button", { name: "查看用量", exact: true }).click();
345
+ await page.getByText("synthetic-complete", { exact: true }).waitFor();
346
+ const detail = page.locator(".account-detail");
347
+ const customerPreview = detail.locator(".customer-preview");
348
+ assert.equal(
349
+ await customerPreview.locator(".preview-amount").innerText(),
350
+ "99%",
351
+ );
352
+ assert.match(await customerPreview.innerText(), /1 笔用量待更新/);
353
+ assert.doesNotMatch(
354
+ await customerPreview.innerText(),
355
+ /Token|Credits|999,000|相当于/i,
356
+ );
357
+ assert.match(
358
+ await detail.locator(".operator-accounting").innerText(),
359
+ /999,000/,
360
+ );
361
+ assert.match(await detail.innerText(), /待计量/);
362
+ assert.match(await detail.innerText(), /输入 800 \/ 输出 200/);
363
+ await detail.getByRole("button", { name: "暂停新请求", exact: true }).click();
364
+ await page.getByRole("button", { name: "确认", exact: true }).click();
365
+ await detail.getByRole("button", { name: "恢复使用", exact: true }).waitFor();
366
+ assert.equal(activeGrant.state, "suspended");
367
+ assert.match(await customerPreview.innerText(), /已暂停/);
368
+ assert.equal(
369
+ await customerPreview.locator(".preview-amount").innerText(),
370
+ "—%",
371
+ );
372
+ await detail.getByRole("button", { name: "恢复使用", exact: true }).click();
373
+ await page.getByRole("button", { name: "确认", exact: true }).click();
374
+ await detail
375
+ .getByRole("button", { name: "暂停新请求", exact: true })
376
+ .waitFor();
377
+ assert.equal(activeGrant.state, "active");
378
+ await page.locator(".el-message-box__wrapper").waitFor({ state: "hidden" });
379
+ await page.locator(".el-message").last().waitFor({ state: "hidden" });
380
+ await page.screenshot({
381
+ path: `${output}/token-account-desktop.png`,
382
+ fullPage: true,
383
+ animations: "disabled",
384
+ });
385
+ const originalGrant = structuredClone(activeGrant);
386
+ const projectionCases = [
387
+ {
388
+ label: "fractional percentage",
389
+ mode: "periodic",
390
+ projection: {
391
+ kind: "percentage",
392
+ state: "active",
393
+ remaining: 0.4,
394
+ total: 100,
395
+ displayValue: "<1",
396
+ },
397
+ amount: "<1%",
398
+ state: "可用",
399
+ },
400
+ {
401
+ label: "zero percentage",
402
+ mode: "periodic",
403
+ projection: {
404
+ kind: "percentage",
405
+ state: "depleted",
406
+ remaining: 0,
407
+ total: 100,
408
+ displayValue: "0",
409
+ },
410
+ amount: "0%",
411
+ state: "额度已用完",
412
+ },
413
+ {
414
+ label: "fractional credits",
415
+ mode: "credits",
416
+ projection: {
417
+ kind: "credits",
418
+ state: "active",
419
+ remaining: 1.019,
420
+ total: 100,
421
+ displayValue: "1.01",
422
+ },
423
+ amount: "1.01积分",
424
+ state: "可用",
425
+ },
426
+ {
427
+ label: "tiny credits",
428
+ mode: "credits",
429
+ projection: {
430
+ kind: "credits",
431
+ state: "active",
432
+ remaining: 0.001,
433
+ total: 100,
434
+ displayValue: "<0.01",
435
+ },
436
+ amount: "<0.01积分",
437
+ state: "可用",
438
+ },
439
+ {
440
+ label: "zero credits",
441
+ mode: "credits",
442
+ projection: {
443
+ kind: "credits",
444
+ state: "depleted",
445
+ remaining: 0,
446
+ total: 100,
447
+ displayValue: "0",
448
+ },
449
+ amount: "0积分",
450
+ state: "额度已用完",
451
+ },
452
+ {
453
+ label: "expired",
454
+ mode: "credits",
455
+ projection: {
456
+ kind: "credits",
457
+ state: "expired",
458
+ remaining: null,
459
+ total: 100,
460
+ displayValue: null,
461
+ },
462
+ amount: "—积分",
463
+ state: "已到期",
464
+ },
465
+ {
466
+ label: "not started",
467
+ mode: "periodic",
468
+ projection: {
469
+ kind: "percentage",
470
+ state: "not_started",
471
+ remaining: null,
472
+ total: 100,
473
+ displayValue: null,
474
+ },
475
+ amount: "—%",
476
+ state: "尚未生效",
477
+ },
478
+ {
479
+ label: "suspended",
480
+ mode: "credits",
481
+ projection: {
482
+ kind: "credits",
483
+ state: "suspended",
484
+ remaining: null,
485
+ total: 100,
486
+ displayValue: null,
487
+ },
488
+ amount: "—积分",
489
+ state: "已暂停",
490
+ },
491
+ {
492
+ label: "missing projection",
493
+ mode: "periodic",
494
+ projection: null,
495
+ amount: "—",
496
+ state: "用量暂不可用",
497
+ },
498
+ {
499
+ label: "unknown projection",
500
+ mode: "periodic",
501
+ projection: {
502
+ schema: "unknown",
503
+ kind: "percentage",
504
+ state: "active",
505
+ remaining: 100,
506
+ total: 100,
507
+ displayValue: "100",
508
+ },
509
+ amount: "—",
510
+ state: "用量暂不可用",
511
+ },
512
+ {
513
+ label: "wrong mode projection",
514
+ mode: "periodic",
515
+ projection: {
516
+ kind: "credits",
517
+ state: "active",
518
+ remaining: 100,
519
+ total: 100,
520
+ displayValue: "100",
521
+ },
522
+ amount: "—",
523
+ state: "用量暂不可用",
524
+ },
525
+ ...["101", "1.25", "<0.01"].map((displayValue) => ({
526
+ label: `invalid percentage ${displayValue}`,
527
+ mode: "periodic",
528
+ projection: {
529
+ kind: "percentage",
530
+ state: "active",
531
+ remaining: 1,
532
+ total: 100,
533
+ displayValue,
534
+ },
535
+ amount: "—",
536
+ state: "用量暂不可用",
537
+ })),
538
+ {
539
+ label: "invalid credits notation",
540
+ mode: "credits",
541
+ projection: {
542
+ kind: "credits",
543
+ state: "active",
544
+ remaining: 0.1,
545
+ total: 100,
546
+ displayValue: "<1",
547
+ },
548
+ amount: "—",
549
+ state: "用量暂不可用",
550
+ },
551
+ {
552
+ label: "credits exceed total",
553
+ mode: "credits",
554
+ projection: {
555
+ kind: "credits",
556
+ state: "active",
557
+ remaining: 101,
558
+ total: 100,
559
+ displayValue: "101",
560
+ },
561
+ amount: "—",
562
+ state: "用量暂不可用",
563
+ },
564
+ {
565
+ label: "not granted",
566
+ mode: null,
567
+ projection: {
568
+ kind: "none",
569
+ state: "unavailable",
570
+ remaining: null,
571
+ total: null,
572
+ displayValue: null,
573
+ },
574
+ amount: "—",
575
+ state: "尚未开通",
576
+ },
577
+ ];
578
+ for (const scenario of projectionCases) {
579
+ activeGrant = scenario.mode
580
+ ? {
581
+ ...structuredClone(originalGrant),
582
+ config: { ...originalGrant.config, mode: scenario.mode },
583
+ }
584
+ : null;
585
+ projectionOverride =
586
+ scenario.projection === null
587
+ ? null
588
+ : { schema: "bailing.usage-presentation.v1", ...scenario.projection };
589
+ await detail.getByRole("button", { name: "刷新用量", exact: true }).click();
590
+ await customerPreview.getByText(scenario.state, { exact: true }).waitFor();
591
+ assert.equal(
592
+ await customerPreview.locator(".preview-amount").innerText(),
593
+ scenario.amount,
594
+ scenario.label,
595
+ );
596
+ assert.doesNotMatch(
597
+ await customerPreview.innerText(),
598
+ /Token|Credits|999,000|相当于/i,
599
+ scenario.label,
600
+ );
601
+ if (scenario.label === "fractional credits")
602
+ await page.screenshot({
603
+ path: `${output}/credits-account-desktop.png`,
604
+ fullPage: true,
605
+ animations: "disabled",
606
+ });
607
+ }
608
+ activeGrant = originalGrant;
609
+ projectionOverride = undefined;
610
+ await page.locator(".el-drawer__close-btn").click();
611
+ await page.getByRole("tab", { name: "套餐管理", exact: true }).click();
612
+ await page.getByRole("button", { name: "新建套餐", exact: true }).click();
613
+ await page.getByLabel("套餐名称", { exact: true }).fill("一次性额度包");
614
+ await page
615
+ .getByRole("radio", {
616
+ name: "额度包 一次获得固定额度,在有效期内按需使用。",
617
+ exact: true,
618
+ })
619
+ .check();
620
+ await page
621
+ .locator(".model-choices .el-checkbox")
622
+ .filter({ hasText: "通用模型" })
623
+ .click();
624
+ await page.locator(".preview").screenshot({
625
+ path: `${output}/credits-plan-preview.png`,
626
+ animations: "disabled",
627
+ });
628
+ await page.setViewportSize({ width: 390, height: 844 });
629
+ await page.locator(".main").evaluate((el) => (el.scrollTop = 0));
630
+ await page.screenshot({
631
+ path: `${output}/token-plan-mobile.png`,
632
+ fullPage: true,
633
+ animations: "disabled",
634
+ });
635
+ const overflow = await page.evaluate(
636
+ () => document.documentElement.scrollWidth > window.innerWidth + 1,
637
+ );
638
+ assert.equal(overflow, false, "mobile should not overflow");
639
+ await page.getByRole("button", { name: "保存套餐", exact: true }).click();
640
+ await page.getByRole("button", { name: "新建套餐", exact: true }).waitFor();
641
+ assert.equal(plans[1].config.mode, "credits");
642
+ assert.ok(!("periodUnit" in plans[1].config));
643
+ await page.setViewportSize({ width: 1440, height: 1100 });
644
+ await page.getByRole("tab", { name: "模型服务", exact: true }).click();
645
+ await page.getByRole("button", { name: "添加模型服务", exact: true }).click();
646
+ const serviceDialog = page.getByRole("dialog");
647
+ await serviceDialog
648
+ .getByLabel("显示名称", { exact: true })
649
+ .fill("附加合成模型");
650
+ await serviceDialog
651
+ .getByLabel("服务标识", { exact: true })
652
+ .fill("extra-synthetic");
653
+ await serviceDialog
654
+ .getByLabel("模型凭证名称", { exact: true })
655
+ .fill("existing-synthetic-credential");
656
+ await serviceDialog
657
+ .getByLabel("模型标识", { exact: true })
658
+ .fill("synthetic-extra");
659
+ await page.getByRole("button", { name: "保存服务", exact: true }).click();
660
+ await serviceDialog.waitFor({ state: "hidden" });
661
+ await page
662
+ .getByRole("heading", { name: "附加合成模型", exact: true })
663
+ .waitFor();
664
+ const savedService = services.find((s) => s.id === "extra-synthetic");
665
+ assert.equal(savedService.config.credential, "existing-synthetic-credential");
666
+ assert.deepEqual(
667
+ Object.keys(savedService.config).sort(),
668
+ [
669
+ "credential",
670
+ "model",
671
+ "providerScope",
672
+ "maxOutputTokens",
673
+ "maxInputBytes",
674
+ "timeoutMs",
675
+ ].sort(),
676
+ );
677
+ assert.equal("api_key" in savedService.config, false);
678
+ failPlanRead = true;
679
+ await page.reload();
680
+ await page
681
+ .getByText("用量套餐尚未就绪,请核对迁移。", { exact: false })
682
+ .waitFor();
683
+ assert.equal(
684
+ await page
685
+ .getByRole("tab", { name: "套餐管理", exact: true })
686
+ .getAttribute("class")
687
+ .then((value) => value.includes("is-disabled")),
688
+ true,
689
+ );
690
+ failPlanRead = false;
691
+ permissions = ["usage:read"];
692
+ await page.setViewportSize({ width: 1440, height: 1100 });
693
+ await page.reload();
694
+ await page.getByRole("tab", { name: "账户用量", exact: true }).waitFor();
695
+ await page.getByText("联调周享套餐修订", { exact: true }).waitFor();
696
+ assert.equal(
697
+ await page.getByRole("button", { name: "新建套餐", exact: true }).count(),
698
+ 0,
699
+ );
700
+ assert.equal(
701
+ await page.getByRole("button", { name: "开通给账户", exact: true }).count(),
702
+ 0,
703
+ );
704
+ await page.getByRole("tab", { name: "模型服务", exact: true }).click();
705
+ assert.equal(
706
+ await page
707
+ .getByRole("button", { name: "添加模型服务", exact: true })
708
+ .count(),
709
+ 0,
710
+ );
711
+ assert.equal(
712
+ await page
713
+ .getByRole("link", { name: "接入设置", exact: true })
714
+ .getAttribute("href"),
715
+ "/console/usage-access",
716
+ );
717
+ assert.deepEqual(errors, []);
718
+ assert.deepEqual(unexpected, []);
719
+ console.log(
720
+ JSON.stringify(
721
+ {
722
+ ok: true,
723
+ checks: [
724
+ "mode-controlled credits/percentage previews without Token",
725
+ "mode switch immediately updates full-period percentage",
726
+ "fractional and tiny credit previews use integer-safe floor",
727
+ "old display-unit pending payload cleared without replay",
728
+ "seventeen account projection, malformed projection and state cases",
729
+ "account preview never falls back to raw Token",
730
+ "pending usage preserves actual remaining balance",
731
+ "multi-model shared quota",
732
+ "revisioned edit",
733
+ "lost grant ACK then reload exact-key recovery",
734
+ "no duplicate allocation",
735
+ "actual usage and pending usage",
736
+ "pause/resume revision",
737
+ "allowance pack no period",
738
+ "responsive mobile",
739
+ "unsupported visible",
740
+ "existing model credential reference only",
741
+ "read-only administrator no mutation actions",
742
+ ],
743
+ requests: posts.map((x) => ({
744
+ path: x.path,
745
+ revision: x.body.expected_revision,
746
+ })),
747
+ screenshots: output,
748
+ },
749
+ null,
750
+ 2,
751
+ ),
752
+ );
753
+ } catch (e) {
754
+ console.error(
755
+ JSON.stringify(
756
+ {
757
+ posts,
758
+ errors,
759
+ unexpected,
760
+ body: await page
761
+ .locator("body")
762
+ .innerText({ timeout: 1000 })
763
+ .catch(() => "unavailable"),
764
+ },
765
+ null,
766
+ 2,
767
+ ),
768
+ );
769
+ await page.screenshot({ path: `${output}/failure.png`, fullPage: true });
770
+ throw e;
771
+ } finally {
772
+ await browser.close();
773
+ }