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.
Files changed (184) hide show
  1. package/README.en.md +6 -5
  2. package/README.md +6 -5
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/ARCHITECTURE.md +1 -1
  5. package/docs/CHANGELOG.en.md +12 -1
  6. package/docs/CHANGELOG.md +12 -1
  7. package/docs/COMPATIBILITY.en.md +4 -0
  8. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  9. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  10. package/docs/MODEL_BILLING.en.md +123 -0
  11. package/docs/MODEL_BILLING.md +125 -0
  12. package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
  13. package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
  14. package/docs/README.en.md +5 -1
  15. package/docs/README.md +4 -0
  16. package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
  17. package/docs/RELEASE_NOTES_NEXT.md +4 -2
  18. package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
  19. package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
  20. package/docs/UPGRADE_v0.9.0.en.md +54 -0
  21. package/docs/UPGRADE_v0.9.0.md +54 -0
  22. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
  23. package/package.json +1 -1
  24. package/scripts/check-doc-links.mjs +4 -0
  25. package/scripts/check-image-tags.sh +1 -1
  26. package/scripts/check-release-consistency.test.mjs +2 -2
  27. package/scripts/install.sh +1 -1
  28. package/scripts/publish-images.sh +1 -1
  29. package/scripts/release-audit.mjs +1 -0
  30. package/scripts/sdk-runtime-test.mjs +6 -0
  31. package/scripts/verify-billing-install-upgrade.mjs +225 -0
  32. package/scripts/verify-github-repo.mjs +1 -0
  33. package/sdk/node/README.md +17 -0
  34. package/sdk/node/examples/billing.mjs +21 -0
  35. package/sdk/node/package.json +5 -1
  36. package/sdk/node/src/index.mjs +2 -0
  37. package/sdk/node/src/usage.d.mts +74 -0
  38. package/sdk/node/src/usage.mjs +62 -0
  39. package/sdk/node/tests/usage-types.mts +23 -0
  40. package/sdk/node/tests/usage.test.mjs +81 -0
  41. package/sdk/php7/README.md +19 -2
  42. package/sdk/php7/examples/billing.php +27 -0
  43. package/sdk/php7/examples/well-known.php +1 -1
  44. package/sdk/php7/src/ToolSpec.php +1 -1
  45. package/sdk/php7/src/UsageClient.php +95 -0
  46. package/sdk/php7/src/UsageClientException.php +22 -0
  47. package/sdk/php7/tests/billing-core-http.php +59 -0
  48. package/sdk/php7/tests/usage-client.php +78 -0
  49. package/sql/063_usage_model_billing.sql +153 -0
  50. package/sql/064_period_plan_allowance.sql +25 -0
  51. package/sql/README.en.md +12 -4
  52. package/sql/README.md +14 -6
  53. package/src/app/auth.ts +2 -0
  54. package/src/app/oss-edition.ts +1 -0
  55. package/src/infrastructure/config/configstore.ts +6 -0
  56. package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
  57. package/src/modules/usage/billing-contracts.ts +59 -0
  58. package/src/modules/usage/billing-decimal.test.ts +22 -0
  59. package/src/modules/usage/billing-decimal.ts +36 -0
  60. package/src/modules/usage/billing-external.ts +39 -0
  61. package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
  62. package/src/modules/usage/billing-ledger.test.ts +51 -0
  63. package/src/modules/usage/billing-ledger.ts +104 -0
  64. package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
  65. package/src/modules/usage/billing-presentation.test.ts +49 -0
  66. package/src/modules/usage/billing-presentation.ts +34 -0
  67. package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
  68. package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
  69. package/src/modules/usage/billing-repository.ts +463 -0
  70. package/src/modules/usage/contracts.ts +49 -0
  71. package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
  72. package/src/modules/usage/errors.ts +19 -0
  73. package/src/modules/usage/http.ts +85 -0
  74. package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
  75. package/src/modules/usage/identity.mysql.test.ts +120 -0
  76. package/src/modules/usage/identity.ts +303 -0
  77. package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
  78. package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
  79. package/src/modules/usage/model-gateway.ts +229 -0
  80. package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
  81. package/src/modules/usage/model-tool-provider.test.ts +37 -0
  82. package/src/modules/usage/model-tool-provider.ts +110 -0
  83. package/src/modules/usage/model-tools.test.ts +36 -0
  84. package/src/modules/usage/model-tools.ts +62 -0
  85. package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
  86. package/src/modules/usage/period.test.ts +26 -0
  87. package/src/modules/usage/period.ts +96 -0
  88. package/src/modules/usage/pricing.test.ts +178 -0
  89. package/src/modules/usage/pricing.ts +228 -0
  90. package/src/modules/usage/provider-failure.ts +37 -0
  91. package/src/modules/usage/provider-stream.test.ts +85 -0
  92. package/src/modules/usage/provider-stream.ts +77 -0
  93. package/src/modules/usage/provider.test.ts +67 -0
  94. package/src/modules/usage/provider.ts +142 -0
  95. package/src/modules/usage/repository.ts +539 -0
  96. package/src/modules/usage/service-availability.mysql.test.ts +68 -0
  97. package/src/modules/usage/service-availability.ts +13 -0
  98. package/src/modules/usage/service-delete.mysql.test.ts +87 -0
  99. package/src/modules/usage/stream-http.ts +32 -0
  100. package/src/modules/usage/test-harness.ts +108 -0
  101. package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
  102. package/src/modules/usage/usage-deletion.ts +119 -0
  103. package/src/modules/usage/validation.test.ts +18 -0
  104. package/src/modules/usage/validation.ts +33 -0
  105. package/src/routes/admin-billing-usage.ts +73 -0
  106. package/src/routes/admin-usage.ts +147 -0
  107. package/src/routes/admin.ts +4 -0
  108. package/src/routes/private.ts +8 -0
  109. package/web/connect/bailing-connect-php7.tgz +0 -0
  110. package/web/console/assets/Accounts-Bervi5JU.css +1 -0
  111. package/web/console/assets/Accounts-DnddhY6t.js +3 -0
  112. package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-VInbD7JS.js} +1 -1
  113. package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
  114. package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
  115. package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-34qUPHf0.js} +1 -1
  116. package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-BbVgkSm2.js} +1 -1
  117. package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-DgscF28e.js} +1 -1
  118. package/web/console/assets/{Channels-B9n4fbxg.js → Channels-Bp-yuk8d.js} +1 -1
  119. package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-C9Ft60TS.js} +1 -1
  120. package/web/console/assets/{Clients-CI3DBDHf.js → Clients-NPldD-DD.js} +1 -1
  121. package/web/console/assets/{Cost-JgNXQPlN.js → Cost-DZcuB-EB.js} +1 -1
  122. package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-RTT7N6zl.js} +1 -1
  123. package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-_LeK8cce.js} +1 -1
  124. package/web/console/assets/{Executors-CRbboOCZ.js → Executors-Bi7H8rIm.js} +1 -1
  125. package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
  126. package/web/console/assets/{Kb-CgLNGjRp.js → Kb-BHamz8NP.js} +2 -2
  127. package/web/console/assets/{Login-C52JmXzx.js → Login-C1rJR-6w.js} +1 -1
  128. package/web/console/assets/{Projects-CDOvHPVS.js → Projects-BRA4a48v.js} +1 -1
  129. package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
  130. package/web/console/assets/Routes-CyXV4Pba.css +1 -0
  131. package/web/console/assets/{Runs-DYNDXsqk.js → Runs-B_fa_BlD.js} +1 -1
  132. package/web/console/assets/{Setup-B91P6i1x.js → Setup-C1_d0mFy.js} +1 -1
  133. package/web/console/assets/Shell-CHEV6RGC.js +1 -0
  134. package/web/console/assets/Shell-ykb-tUfo.css +1 -0
  135. package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DlG3ojhA.js} +1 -1
  136. package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-DYo2gg6d.js} +1 -1
  137. package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-DKCoUZlq.js} +1 -1
  138. package/web/console/assets/{Targets-CuuIYeZO.js → Targets-CdkG6BPR.js} +1 -1
  139. package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DVpCt0ox.js} +1 -1
  140. package/web/console/assets/Usage-CAeDGjrb.css +1 -0
  141. package/web/console/assets/Usage-DWCpLugC.js +1 -0
  142. package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
  143. package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
  144. package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
  145. package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
  146. package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
  147. package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
  148. package/web/console/assets/index-H1kfa0Mj.js +2 -0
  149. package/web/console/assets/{request-DeGya810.js → request-DLsP1_ot.js} +1 -1
  150. package/web/console/assets/{schema-BqlqLw1R.js → schema-BLOHvAJQ.js} +1 -1
  151. package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
  152. package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
  153. package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
  154. package/web/console/index.html +3 -3
  155. package/web-admin/README.md +17 -0
  156. package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
  157. package/web-admin/src/components/UsageHelp.vue +72 -0
  158. package/web-admin/src/components/UsageServiceReferences.vue +169 -0
  159. package/web-admin/src/layout/Shell.vue +22 -5
  160. package/web-admin/src/pages/Accounts.vue +3 -3
  161. package/web-admin/src/pages/AgentTasks.vue +2 -2
  162. package/web-admin/src/pages/Routes.vue +5 -1
  163. package/web-admin/src/pages/Usage.vue +2470 -0
  164. package/web-admin/src/pages/UsageAccess.vue +1147 -0
  165. package/web-admin/src/router.ts +8 -4
  166. package/web-admin/src/styles/base.css +57 -0
  167. package/web-admin/src/table-widths.ts +16 -1
  168. package/web-admin/src/usage-deletion.ts +40 -0
  169. package/web-admin/src/usage-management.ts +13 -0
  170. package/web-admin/src/usage-presentation.test.ts +21 -0
  171. package/web-admin/src/usage-presentation.ts +107 -0
  172. package/web-admin/src/usage-price-preview.test.ts +60 -0
  173. package/web-admin/src/usage-price-preview.ts +54 -0
  174. package/web-admin/tests/token-usage.browser.mjs +773 -0
  175. package/web-admin/tests/usage-access.browser.mjs +398 -0
  176. package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
  177. package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
  178. package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
  179. package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
  180. package/web/console/assets/Routes-DkMIjMQA.css +0 -1
  181. package/web/console/assets/Routes-X9vHLpKW.js +0 -124
  182. package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
  183. package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
  184. package/web/console/assets/index-UGvfF3Xr.js +0 -2
@@ -7,7 +7,7 @@ export const SETUP_PAGE = { path: 'setup', perm: 'audit:read', title: '上手向
7
7
 
8
8
  // 页面与所需权限(菜单渲染同源于此;后端接口另有二次拦截)。
9
9
  // 数组顺序 = 菜单显示顺序,也是常规默认落地优先级(进 `/` 落到第一个有权限的页 → 任务)。
10
- // 分组按「日常使用频率 + 概念角色」切:任务(运行入口) → 场景配置 → 入口(谁/从哪触发) → 能力(引用的积木) → 基础资源(低频公共配置) → 运行治理 → 系统(平台管理)。
10
+ // 任务是唯一独立工作入口;其余按配置、接入、能力、运行、运营、资源与系统职责分组。
11
11
  // 上手向导是首次接入与低频自检入口,不常驻左侧主导航;路由保留,入口收敛到默认落地与右上角菜单。
12
12
  export const PAGES = [
13
13
  // ① 任务 —— 稳定运行后的默认工作台
@@ -30,9 +30,11 @@ export const PAGES = [
30
30
  { path: 'projects', perm: 'projects:read', title: '项目目录', group: '基础资源' },
31
31
  // ⑥ 运行治理 —— 非默认运行配置与治理观察
32
32
  { path: 'executors', perm: 'runs:read', title: '执行器', group: '运行' },
33
- { path: 'cost', perm: 'runs:read', title: '成本观测', group: '运行' },
34
33
  { path: 'approvals', perm: 'runs:read', title: '审批意图', group: '运行' },
35
- // ⑦ 系统 —— 平台管理(低频)
34
+ // ⑦ 运营管理 —— 跨接入入口的账户、套餐与成本,不隶属于智能体客户端
35
+ { path: 'usage', perm: 'usage:read', title: '用户与用量', group: '运营管理' },
36
+ { path: 'cost', perm: 'runs:read', title: '成本观测', group: '运营管理' },
37
+ // ⑧ 系统 —— 平台管理(低频)
36
38
  { path: 'settings', perm: 'admins:manage', title: '实例外观', group: '系统管理' },
37
39
  { path: 'system', perm: 'audit:read', title: '系统状态', group: '系统管理' },
38
40
  { path: 'diagnostics', perm: 'audit:read', title: '系统体检', group: '系统管理' },
@@ -51,6 +53,8 @@ export const router = createRouter({
51
53
  { path: 'setup', component: () => import('./pages/Setup.vue'), meta: { perm: SETUP_PAGE.perm, title: SETUP_PAGE.title } },
52
54
  { path: 'kb', component: () => import('./pages/Kb.vue'), meta: { perm: 'kb:read', title: '知识库' } },
53
55
  { path: 'runs', component: () => import('./pages/Runs.vue'), meta: { perm: 'runs:read', title: '任务' } },
56
+ { path: 'usage', component: () => import('./pages/Usage.vue'), meta: { perm: 'usage:read', title: '用户与用量' } },
57
+ { path: 'usage-access', component: () => import('./pages/UsageAccess.vue'), meta: { perm: 'usage:read', title: '用量接入设置' } },
54
58
  { path: 'executors', component: () => import('./pages/Executors.vue'), meta: { perm: 'runs:read', title: '执行器' } },
55
59
  { path: 'cost', component: () => import('./pages/Cost.vue'), meta: { perm: 'runs:read', title: '成本观测' } },
56
60
  { path: 'routes', component: () => import('./pages/Routes.vue'), meta: { perm: 'routes:read', title: '触发路由' } },
@@ -112,7 +116,7 @@ router.beforeEach(async (to) => {
112
116
  if (!first) { await s.logout(); return { path: '/login', query: to.query }; } // 零权限账号(不应出现)
113
117
  return '/' + first.path;
114
118
  }
115
- const page = PAGES.find((candidate) => `/${candidate.path}` === to.path);
119
+ const page = PAGES.find((candidate) => `/${candidate.path}` === to.path || (candidate.path === 'usage' && to.path === '/usage-access'));
116
120
  if (page && !s.hasModule(page.path)) return '/';
117
121
  if (to.meta['perm'] && !s.can(to.meta['perm'] as string)) return '/';
118
122
  return true;
@@ -132,6 +132,63 @@ body *::after {
132
132
  width: 2px;
133
133
  }
134
134
  .el-card { --el-card-padding: 24px; } /* 默认 20px */
135
+
136
+ /* 页面页签与上下文操作共用一行;内容跨满容器,避免另占工具栏。 */
137
+ .console-page-tabs {
138
+ display: grid;
139
+ grid-template-columns: minmax(0, 1fr) auto;
140
+ column-gap: 16px;
141
+ min-width: 0;
142
+ }
143
+ .console-page-tabs::before {
144
+ content: '';
145
+ grid-column: 1 / -1;
146
+ grid-row: 1;
147
+ align-self: end;
148
+ height: 1px;
149
+ background: var(--el-border-color-light);
150
+ }
151
+ .console-page-tabs > .el-tabs { display: contents; }
152
+ .console-page-tabs > .el-tabs > .el-tabs__header {
153
+ grid-column: 1;
154
+ grid-row: 1;
155
+ min-width: 0;
156
+ margin: 0;
157
+ }
158
+ .console-page-tabs > .el-tabs > .el-tabs__header .el-tabs__nav-wrap {
159
+ margin-bottom: 0;
160
+ }
161
+ .console-page-tabs > .el-tabs > .el-tabs__header .el-tabs__nav-wrap::after {
162
+ content: none;
163
+ }
164
+ .console-page-tabs > .el-tabs > .el-tabs__content {
165
+ grid-column: 1 / -1;
166
+ grid-row: 2;
167
+ min-width: 0;
168
+ padding-top: 20px;
169
+ }
170
+ .console-page-tabs-actions {
171
+ grid-column: 2;
172
+ grid-row: 1;
173
+ display: flex;
174
+ align-items: center;
175
+ justify-content: flex-end;
176
+ gap: 8px;
177
+ min-width: 0;
178
+ padding-bottom: 2px;
179
+ }
180
+ .console-page-tabs-actions .el-button + .el-button { margin-left: 0; }
181
+ @media (max-width: 760px) {
182
+ .console-page-tabs { grid-template-columns: minmax(0, 1fr); }
183
+ .console-page-tabs-actions {
184
+ grid-column: 1;
185
+ grid-row: 2;
186
+ flex-wrap: wrap;
187
+ padding-top: 12px;
188
+ }
189
+ .console-page-tabs-actions:empty { display: none; }
190
+ .console-page-tabs > .el-tabs > .el-tabs__content { grid-row: 3; }
191
+ }
135
192
  .el-form--label-top .el-form-item { margin-bottom: 22px; } /* 抽屉表单项间距,默认 18px */
136
193
  /* 本版 EP 对 label-top 没有 label 高度覆盖:small 的 height:24px 锁死,
137
194
  * 长说明 label(如路由页)折行即撑破盒子叠到输入框上。放开高度 + 留 label→输入间隙。 */
@@ -255,7 +255,9 @@ function columnMinWidth(column: any, index: number, defaults?: Record<string, De
255
255
 
256
256
  function isActionColumn(column: any): boolean {
257
257
  const type = String(column.type || '');
258
- return !column.label && !column.property && !column.columnKey && !column.rawColumnKey && !['expand', 'selection', 'index'].includes(type);
258
+ if (['expand', 'selection', 'index'].includes(type)) return false;
259
+ if (column.columnKey === 'actions' || column.rawColumnKey === 'actions') return true;
260
+ return (!column.label || column.label === '操作') && !column.property && !column.columnKey && !column.rawColumnKey;
259
261
  }
260
262
 
261
263
  function actionColumn(instance: TableInstanceLike): any | null {
@@ -387,6 +389,19 @@ function normalizeTableWidths(instance: TableInstanceLike, router: Router): bool
387
389
  if (tableWidth <= 16) return false;
388
390
  const defaults = DEFAULT_COLUMN_WIDTHS[tableKey(instance, router)];
389
391
  let changed = false;
392
+ // Fixed operation columns must also fit the container. An oversized saved
393
+ // width cannot be repaired by shrinking only the non-fixed columns.
394
+ const columns = columnsOf(instance);
395
+ const action = actionColumn(instance);
396
+ if (action) {
397
+ const reserved = columns.filter((column) => column !== action).reduce((sum, column) =>
398
+ sum + (canForceShrinkColumn(column) ? Math.min(columnWidth(column), HARD_MIN_WIDTH) : columnWidth(column)), 0);
399
+ const maxActionWidth = Math.max(HARD_MIN_WIDTH, tableWidth - reserved);
400
+ if (columnWidth(action) > maxActionWidth) {
401
+ setColumnWidth(action, maxActionWidth);
402
+ changed = true;
403
+ }
404
+ }
390
405
  if (shrinkColumnsForOverflow(instance, tableWidth, defaults)) changed = true;
391
406
  if (stretchColumnForSlack(instance, tableWidth, defaults)) changed = true;
392
407
  const overflow = actualScrollOverflow(instance);
@@ -0,0 +1,40 @@
1
+ import { ref } from 'vue';
2
+ import { api } from './request';
3
+
4
+ export interface UsageDeletionReport {
5
+ kind: 'plan' | 'issuer' | 'account';
6
+ id: string;
7
+ label: string;
8
+ revision: number;
9
+ can_delete: boolean;
10
+ blockers: Array<{ code: string; message: string; count: number }>;
11
+ effect: string;
12
+ }
13
+ export function useUsageDeletion(describe: (error: unknown) => string) {
14
+ const open = ref(false), loading = ref(false), error = ref('');
15
+ const path = ref(''), label = ref('');
16
+ const report = ref<UsageDeletionReport | null>(null);
17
+ let sequence = 0;
18
+ async function refresh() {
19
+ const current = ++sequence;
20
+ const target = path.value;
21
+ loading.value = true;
22
+ error.value = '';
23
+ report.value = null;
24
+ try {
25
+ const result = await api<UsageDeletionReport>(`${target}/deletion-preview`);
26
+ if (current === sequence) report.value = result;
27
+ } catch (e) {
28
+ if (current === sequence) error.value = describe(e);
29
+ } finally {
30
+ if (current === sequence) loading.value = false;
31
+ }
32
+ }
33
+ async function show(target: string, name: string) {
34
+ path.value = target;
35
+ label.value = name;
36
+ open.value = true;
37
+ await refresh();
38
+ }
39
+ return { open, loading, error, path, label, report, refresh, show };
40
+ }
@@ -0,0 +1,13 @@
1
+ export interface ServiceReferenceAccount {
2
+ id: string; label: string; kind: 'personal' | 'organization'; state: 'active' | 'suspended';
3
+ grantId: string; grantLabel: string; sourceOwner: string; serviceIds: string[]; revision: number;
4
+ }
5
+ export interface ServiceReferenceRequest {
6
+ accountId: string; accountLabel: string; operationId: string; state: string; resultState: string;
7
+ }
8
+ export interface ServiceReferenceReport {
9
+ service: { id: string; label: string; revision: number }; deletable: boolean;
10
+ plans: { total: number; truncated: boolean; items: Array<{id: string; label: string}> };
11
+ accounts: { total: number; truncated: boolean; items: ServiceReferenceAccount[] };
12
+ requests: { total: number; truncated: boolean; items: ServiceReferenceRequest[] };
13
+ }
@@ -0,0 +1,21 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { previewPresentation, readPresentation } from './usage-presentation';
4
+
5
+ test('USD allowance preview uses fixed credits or percentage, never supplier token usage', () => {
6
+ const credits = previewPresentation({mode:'credits',priceUsd:100});
7
+ assert.equal(credits.kind,'credits'); assert.equal(credits.remaining,100000); assert.equal(credits.displayValue,'100000');
8
+ const periodic = previewPresentation({mode:'periodic',priceUsd:100,periodAllowanceUsd:20});
9
+ assert.equal(periodic.kind,'percentage'); assert.equal(periodic.remaining,100);
10
+ assert.equal(previewPresentation({mode:'credits',priceUsd:Number.NaN}).state,'unavailable');
11
+ });
12
+ test('account presentation requires authoritative projection, never derives balance from raw token or USD fields', () => {
13
+ assert.equal(readPresentation({availableUsd:10, inputTokens:1000},'credits').state,'unavailable');
14
+ const presentation = {schema:'bailing.usage-presentation.v1',kind:'percentage',state:'active',remaining:99.7,total:100,displayValue:'99'};
15
+ assert.equal(readPresentation(presentation,'periodic').remaining,99.7);
16
+ assert.equal(readPresentation(presentation,'credits').state,'unavailable');
17
+ });
18
+
19
+ test('period preview requires its own allowance, never the sale price', () => {
20
+ assert.equal(previewPresentation({mode:'periodic',priceUsd:100}).state,'unavailable');
21
+ });
@@ -0,0 +1,107 @@
1
+ export interface UsagePresentation {
2
+ schema: "bailing.usage-presentation.v1";
3
+ kind: "credits" | "percentage" | "none";
4
+ state:
5
+ | "active"
6
+ | "depleted"
7
+ | "not_started"
8
+ | "expired"
9
+ | "suspended"
10
+ | "unavailable";
11
+ remaining: number | null;
12
+ total: number | null;
13
+ displayValue: string | null;
14
+ }
15
+
16
+ const unavailable = (): UsagePresentation => ({
17
+ schema: "bailing.usage-presentation.v1",
18
+ kind: "none",
19
+ state: "unavailable",
20
+ remaining: null,
21
+ total: null,
22
+ displayValue: null,
23
+ });
24
+
25
+ // A missing or incompatible projection must never fall back to accounting data.
26
+ export function readPresentation(
27
+ value: unknown,
28
+ mode?: "credits" | "periodic",
29
+ ): UsagePresentation {
30
+ if (!value || typeof value !== "object") return unavailable();
31
+ const p = value as UsagePresentation;
32
+ const expected =
33
+ mode === "credits"
34
+ ? "credits"
35
+ : mode === "periodic"
36
+ ? "percentage"
37
+ : "none";
38
+ if (
39
+ p.schema !== "bailing.usage-presentation.v1" ||
40
+ p.kind !== expected ||
41
+ ![
42
+ "active",
43
+ "depleted",
44
+ "not_started",
45
+ "expired",
46
+ "suspended",
47
+ "unavailable",
48
+ ].includes(p.state)
49
+ )
50
+ return unavailable();
51
+ if (p.state !== "active" && p.state !== "depleted") {
52
+ return { ...p, remaining: null, displayValue: null };
53
+ }
54
+ if (
55
+ p.kind === "none" ||
56
+ typeof p.remaining !== "number" ||
57
+ !Number.isFinite(p.remaining) ||
58
+ p.remaining < 0 ||
59
+ typeof p.total !== "number" ||
60
+ !Number.isFinite(p.total) ||
61
+ p.total <= 0 ||
62
+ typeof p.displayValue !== "string" ||
63
+ p.remaining > p.total ||
64
+ (p.kind === "percentage" &&
65
+ (p.total !== 100 ||
66
+ !/^(?:100|[1-9]?\d|<1)$/.test(p.displayValue) ||
67
+ (p.displayValue === "<1" && p.remaining >= 1))) ||
68
+ (p.kind === "credits" &&
69
+ (!/^(?:\d+(?:\.\d{1,2})?|<0\.01)$/.test(p.displayValue) ||
70
+ (p.displayValue === "<0.01" && p.remaining >= 0.01))) ||
71
+ (p.state === "active" &&
72
+ (p.remaining <= 0 || Number(p.displayValue) === 0)) ||
73
+ (p.state === "depleted" && (p.remaining !== 0 || p.displayValue !== "0"))
74
+ )
75
+ return unavailable();
76
+ return p;
77
+ }
78
+
79
+ // Template previews start at a full allowance. This is never used for account balances.
80
+ export function previewPresentation(config: {mode:'credits'|'periodic';priceUsd:number;periodAllowanceUsd?:number}): UsagePresentation {
81
+ if (!Number.isFinite(config.priceUsd) || config.priceUsd <= 0) return unavailable();
82
+ if (config.mode === 'periodic' && (typeof config.periodAllowanceUsd !== 'number' || !Number.isFinite(config.periodAllowanceUsd) || config.periodAllowanceUsd <= 0)) return unavailable();
83
+ const amount = config.mode === 'periodic' ? 100 : config.priceUsd * 1000;
84
+ const displayValue = amount < 0.01 ? '<0.01' : String(Math.floor(amount * 100) / 100);
85
+ return {schema:'bailing.usage-presentation.v1',kind:config.mode === 'periodic' ? 'percentage':'credits',state:'active',remaining:amount,total:amount,displayValue};
86
+ }
87
+
88
+ export function presentationAmount(p: UsagePresentation): string {
89
+ if (p.displayValue === null) return "—";
90
+ if (p.displayValue.startsWith("<")) return p.displayValue;
91
+ const [whole, fraction] = p.displayValue.split(".");
92
+ return (
93
+ whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",") +
94
+ (fraction ? "." + fraction : "")
95
+ );
96
+ }
97
+ export const presentationUnit = (p: UsagePresentation) =>
98
+ p.kind === "percentage" ? "%" : p.kind === "credits" ? "积分" : "";
99
+ export const presentationState = (p: UsagePresentation) =>
100
+ ({
101
+ active: "可用",
102
+ depleted: "额度已用完",
103
+ not_started: "尚未生效",
104
+ expired: "已到期",
105
+ suspended: "已暂停",
106
+ unavailable: "用量暂不可用",
107
+ })[p.state];
@@ -0,0 +1,60 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { effectiveBillingModel, estimateModelAllowance, type ReferenceQuote } from './usage-price-preview';
4
+
5
+ const chat: ReferenceQuote = { source: 'openrouter', currency: 'USD', modelId: 'provider/model', endpointId: 'provider', fetchedAt: 1,
6
+ lines: [{billable:'prompt',unit:'token',costUsd:'0.000001'}, {billable:'completion',unit:'token',costUsd:'0.000003'}] };
7
+ const image: ReferenceQuote = {...chat, lines:[{billable:'output_image',unit:'image',variant:'1k',costUsd:'0.03'}, {billable:'output_image',unit:'image',variant:'2k',costUsd:'0.06'}]};
8
+
9
+ test('optional pricing override matches the exact selected identifier without alias guesses', () => {
10
+ assert.equal(effectiveBillingModel('provider/custom-alias', 'other/exact-version'), 'other/exact-version');
11
+ assert.equal(effectiveBillingModel(' provider/model ', ' '), 'provider/model');
12
+ });
13
+ test('whole allowance is independently estimated with plan multiplier and stated input/output mix', () => {
14
+ const first = estimateModelAllowance(chat, 10, 2, 'chat')[0];
15
+ assert.equal(first.estimate, '约 333.33 万 Token');
16
+ assert.match(first.prices, /输入 \$1 .*输出 \$3/);
17
+ assert.match(first.assumption, /3∶1/);
18
+ assert.equal(estimateModelAllowance(chat, 20, 2, 'chat')[0].estimate, '约 666.66 万 Token');
19
+ assert.equal(estimateModelAllowance(chat, 10, 1, 'chat')[0].estimate, '约 666.66 万 Token');
20
+ // No selected-model count is supplied: adding another choice never divides either estimate.
21
+ assert.deepEqual(estimateModelAllowance(chat, 10, 2, 'chat')[0], first);
22
+ });
23
+ test('per-image estimates floor counts for each resolution and show multiplied unit cost', () => {
24
+ const result = estimateModelAllowance(image, 10, 1.5, 'image');
25
+ assert.equal(result[0].estimate, '约 222 张');
26
+ assert.equal(result[1].estimate, '约 111 张');
27
+ assert.equal(result[1].label, '2K');
28
+ assert.match(result[0].prices, /倍率后 \$0.045/);
29
+ });
30
+ test('price tiers remain separate scenarios; base-price estimate is not passed off as all-tier rate', () => {
31
+ const quote = {...chat, tiers:[{minPromptTokens:100000,lines:chat.lines.map(l=>({...l,costUsd:String(Number(l.costUsd)*2)}))}]};
32
+ const result=estimateModelAllowance(quote,10,2,'chat');
33
+ assert.equal(result.length,2); assert.match(result[0].label,/0–99,999/); assert.match(result[1].label,/100,000\+/);
34
+ assert.equal(result[1].estimate,'约 166.66 万 Token');
35
+ });
36
+ test('unknown, invalid and free rates never become invented free or unlimited allowance', () => {
37
+ assert.deepEqual(estimateModelAllowance(undefined,10,1,'chat'),[]);
38
+ assert.deepEqual(estimateModelAllowance({...chat,lines:[{...chat.lines[0],costUsd:'NaN'}]},10,1,'chat'),[]);
39
+ assert.match(estimateModelAllowance({...chat,lines:chat.lines.map(l=>({...l,costUsd:'0'}))},10,1,'chat')[0].estimate,/暂不估算/);
40
+ assert.match(estimateModelAllowance(chat,10,0,'chat')[0].estimate,/有效价格和倍率/);
41
+ });
42
+ test('additional request fees do not produce an overstated token estimate', () => {
43
+ assert.match(estimateModelAllowance({...chat,lines:[...chat.lines,{billable:'request',unit:'request',costUsd:'0.01'}]},10,1,'chat')[0].estimate,/额外按次/);
44
+ });
45
+ test('pixel and image-token prices retain their actual units instead of guessing image counts', () => {
46
+ for(const unit of ['megapixel','token']) {
47
+ const result=estimateModelAllowance({...image,lines:[{billable:'output_image',unit,costUsd:'0.01'}]},10,1,'image')[0];
48
+ assert.doesNotMatch(result.estimate,/张/);assert.match(result.assumption,/张数取决于/);
49
+ }
50
+ });
51
+
52
+ import { planEstimateBudget } from './usage-price-preview';
53
+ test('weekly estimates use the full weekly allowance per model, not sale price', () => {
54
+ const budget = planEstimateBudget({mode:'periodic',priceUsd:100,periodAllowanceUsd:20});
55
+ assert.equal(budget,20);
56
+ assert.equal(estimateModelAllowance(chat,budget!,2,'chat')[0].estimate,'约 666.66 万 Token');
57
+ assert.equal(estimateModelAllowance(image,budget!,1.5,'image')[0].estimate,'约 444 张');
58
+ assert.equal(planEstimateBudget({mode:'periodic',priceUsd:100}),null);
59
+ assert.equal(planEstimateBudget({mode:'credits',priceUsd:100}),100);
60
+ });
@@ -0,0 +1,54 @@
1
+ /** Console estimates only. Never use these numbers to admit or settle a request. */
2
+ export interface PriceLine { billable: string; unit: string; costUsd: string; variant?: string }
3
+ export interface ReferenceQuote {
4
+ source: 'openrouter'; modelId: string; endpointId: string; currency: 'USD'; fetchedAt: number;
5
+ lines: PriceLine[]; tiers?: Array<{ minPromptTokens: number; lines: PriceLine[] }>;
6
+ }
7
+ export interface PriceEstimate { label: string; prices: string; estimate: string; assumption: string }
8
+ export const effectiveBillingModel = (model: string, override: string) => override.trim() || model.trim();
9
+ const money = (value: number) => new Intl.NumberFormat('en-US', { maximumSignificantDigits: 6 }).format(value);
10
+ const quantity = (value: number) => value >= 10000
11
+ ? `${new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 2 }).format(Math.floor(value / 100) / 100)} 万`
12
+ : new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 0 }).format(Math.floor(value));
13
+ const price = (line: PriceLine) => Number(line.costUsd);
14
+ const valid = (lines: PriceLine[]) => lines.length > 0 && lines.every(l => l.costUsd.trim() !== '' && Number.isFinite(price(l)) && price(l) >= 0);
15
+
16
+ export function estimateModelAllowance(quote: ReferenceQuote | null | undefined, budget: number, multiplier: number, kind: 'chat' | 'image'): PriceEstimate[] {
17
+ if (!quote || quote.source !== 'openrouter' || quote.currency !== 'USD' || !valid(quote.lines)) return [];
18
+ const usable = Number.isFinite(budget) && budget > 0 && Number.isFinite(multiplier) && multiplier > 0;
19
+ const units = (cost: number, unit: string, floor = false) => !usable ? '请填写有效价格和倍率'
20
+ : cost === 0 ? '参考单价为 0,暂不估算可用量'
21
+ : `约 ${floor ? Math.floor(budget / multiplier / cost).toLocaleString('zh-CN') : quantity(budget / multiplier / cost)} ${unit}`;
22
+ if (kind === 'chat') {
23
+ const tiers = quote.tiers ?? [];
24
+ const scenarios = [{ minPromptTokens: 0, lines: quote.lines }, ...tiers].sort((a, b) => a.minPromptTokens - b.minPromptTokens);
25
+ return scenarios.map((scenario, index) => {
26
+ const { lines } = scenario;
27
+ const inputs = lines.filter(l => l.billable === 'prompt' && l.unit === 'token');
28
+ const outputs = lines.filter(l => l.billable === 'completion' && l.unit === 'token');
29
+ const label = scenarios.length === 1 ? '对话' : `单次输入 ${scenario.minPromptTokens.toLocaleString('zh-CN')}${scenarios[index + 1] ? `–${(scenarios[index + 1].minPromptTokens - 1).toLocaleString('zh-CN')}` : '+'} Token`;
30
+ if (!valid(lines) || inputs.length !== 1 || outputs.length !== 1) return { label, prices: '报价不完整', estimate: '暂无法估算', assumption: '' };
31
+ const prices = `输入 $${money(price(inputs[0]) * 1e6)} / 百万 Token · 输出 $${money(price(outputs[0]) * 1e6)} / 百万 Token`;
32
+ const extra = lines.some(l => !['prompt', 'completion', 'input_cache_read', 'input_cache_write'].includes(l.billable) && price(l) > 0);
33
+ return { label, prices,
34
+ estimate: extra ? '含额外按次费用,暂不换算 Token' : units(price(inputs[0]) * .75 + price(outputs[0]) * .25, 'Token'),
35
+ assumption: '输入∶输出 = 3∶1,未命中缓存;全部额度仅用于此模型' };
36
+ });
37
+ }
38
+ const outputs = quote.lines.filter(l => l.billable === 'output_image');
39
+ return outputs.map(line => {
40
+ const sameVariant = outputs.filter(l => l.variant === line.variant);
41
+ const unit = line.unit === 'image' ? '张' : line.unit === 'megapixel' ? '百万像素' : line.unit === 'token' ? '图像 Token' : '';
42
+ const extra = quote.lines.some(l => !['output_image', 'input_image', 'input_reference'].includes(l.billable) && price(l) > 0);
43
+ return { label: line.variant ? line.variant.toUpperCase() : '图片',
44
+ prices: unit ? `$${money(price(line))} / ${unit} · 倍率后 $${money(price(line) * multiplier)} / ${unit}` : '计量单位尚不支持',
45
+ estimate: !unit || extra || sameVariant.length !== 1 ? '暂无法估算' : units(price(line), unit, line.unit === 'image'),
46
+ assumption: `纯文生图,不含参考图;全部额度仅用于此模型${line.unit !== 'image' ? ',张数取决于每张实际用量' : ''}` };
47
+ });
48
+ }
49
+
50
+ // Sale price is not a periodic allowance; missing period configuration stays unknown.
51
+ export function planEstimateBudget(config: {mode: 'credits'|'periodic';priceUsd:number;periodAllowanceUsd?:number}): number | null {
52
+ const budget = config.mode === 'periodic' ? config.periodAllowanceUsd : config.priceUsd;
53
+ return typeof budget === 'number' && Number.isFinite(budget) && budget > 0 ? budget : null;
54
+ }