bailinghub 0.8.0 → 0.9.1

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 (209) hide show
  1. package/.dockerignore +6 -0
  2. package/.npmignore +6 -0
  3. package/CONTRIBUTING.md +4 -0
  4. package/GOVERNANCE.md +9 -0
  5. package/README.en.md +8 -6
  6. package/README.md +8 -6
  7. package/SECURITY.md +8 -2
  8. package/THIRD_PARTY_NOTICES.md +17 -17
  9. package/docker-compose.images.yml +2 -2
  10. package/docs/ARCHITECTURE.md +1 -1
  11. package/docs/CHANGELOG.en.md +22 -1
  12. package/docs/CHANGELOG.md +22 -1
  13. package/docs/COMPATIBILITY.en.md +8 -0
  14. package/docs/IMPLEMENTATION_STATUS.en.md +73 -0
  15. package/docs/IMPLEMENTATION_STATUS.md +73 -0
  16. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  17. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  18. package/docs/KERNEL_HOST_API.en.md +18 -0
  19. package/docs/KERNEL_HOST_API.md +18 -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 +8 -1
  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.9.0.en.md +45 -0
  29. package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
  30. package/docs/RELEASE_NOTES_v0.9.1.en.md +38 -0
  31. package/docs/RELEASE_NOTES_v0.9.1.md +38 -0
  32. package/docs/UPGRADE_v0.9.0.en.md +54 -0
  33. package/docs/UPGRADE_v0.9.0.md +54 -0
  34. package/docs/UPGRADE_v0.9.1.en.md +39 -0
  35. package/docs/UPGRADE_v0.9.1.md +39 -0
  36. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +8 -0
  37. package/package.json +5 -4
  38. package/scripts/check-doc-links.mjs +6 -0
  39. package/scripts/check-image-tags.sh +1 -1
  40. package/scripts/check-release-consistency.test.mjs +2 -2
  41. package/scripts/dependency-audit.mjs +134 -0
  42. package/scripts/dependency-audit.test.mjs +125 -0
  43. package/scripts/install.sh +1 -1
  44. package/scripts/osps-results.py +114 -0
  45. package/scripts/publish-images.sh +1 -1
  46. package/scripts/release-audit.mjs +2 -0
  47. package/scripts/sdk-runtime-test.mjs +6 -0
  48. package/scripts/verify-billing-install-upgrade.mjs +225 -0
  49. package/scripts/verify-github-repo.mjs +2 -0
  50. package/sdk/node/README.md +17 -0
  51. package/sdk/node/examples/billing.mjs +21 -0
  52. package/sdk/node/package.json +5 -1
  53. package/sdk/node/src/index.mjs +2 -0
  54. package/sdk/node/src/usage.d.mts +74 -0
  55. package/sdk/node/src/usage.mjs +62 -0
  56. package/sdk/node/tests/usage-types.mts +23 -0
  57. package/sdk/node/tests/usage.test.mjs +81 -0
  58. package/sdk/php7/README.md +19 -2
  59. package/sdk/php7/examples/billing.php +27 -0
  60. package/sdk/php7/examples/well-known.php +1 -1
  61. package/sdk/php7/src/ToolSpec.php +1 -1
  62. package/sdk/php7/src/UsageClient.php +95 -0
  63. package/sdk/php7/src/UsageClientException.php +22 -0
  64. package/sdk/php7/tests/billing-core-http.php +59 -0
  65. package/sdk/php7/tests/usage-client.php +78 -0
  66. package/security/dependency-audit-exceptions.json +192 -0
  67. package/sql/063_usage_model_billing.sql +153 -0
  68. package/sql/064_period_plan_allowance.sql +25 -0
  69. package/sql/README.en.md +12 -4
  70. package/sql/README.md +14 -6
  71. package/src/app/auth.ts +2 -0
  72. package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
  73. package/src/app/kernel.ts +10 -0
  74. package/src/app/oss-edition.ts +1 -0
  75. package/src/infrastructure/config/configstore.ts +6 -0
  76. package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
  77. package/src/modules/usage/background-work.test.ts +144 -0
  78. package/src/modules/usage/background-work.ts +50 -0
  79. package/src/modules/usage/billing-contracts.ts +59 -0
  80. package/src/modules/usage/billing-decimal.test.ts +22 -0
  81. package/src/modules/usage/billing-decimal.ts +36 -0
  82. package/src/modules/usage/billing-external.ts +39 -0
  83. package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
  84. package/src/modules/usage/billing-ledger.test.ts +51 -0
  85. package/src/modules/usage/billing-ledger.ts +104 -0
  86. package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
  87. package/src/modules/usage/billing-presentation.test.ts +49 -0
  88. package/src/modules/usage/billing-presentation.ts +34 -0
  89. package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
  90. package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
  91. package/src/modules/usage/billing-repository.ts +465 -0
  92. package/src/modules/usage/contracts.ts +49 -0
  93. package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
  94. package/src/modules/usage/errors.ts +19 -0
  95. package/src/modules/usage/http.ts +85 -0
  96. package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
  97. package/src/modules/usage/identity.mysql.test.ts +120 -0
  98. package/src/modules/usage/identity.ts +303 -0
  99. package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
  100. package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
  101. package/src/modules/usage/model-gateway.ts +236 -0
  102. package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
  103. package/src/modules/usage/model-tool-provider.test.ts +37 -0
  104. package/src/modules/usage/model-tool-provider.ts +110 -0
  105. package/src/modules/usage/model-tools.test.ts +36 -0
  106. package/src/modules/usage/model-tools.ts +62 -0
  107. package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
  108. package/src/modules/usage/period.test.ts +26 -0
  109. package/src/modules/usage/period.ts +96 -0
  110. package/src/modules/usage/pricing.test.ts +178 -0
  111. package/src/modules/usage/pricing.ts +229 -0
  112. package/src/modules/usage/provider-failure.ts +37 -0
  113. package/src/modules/usage/provider-stream.test.ts +85 -0
  114. package/src/modules/usage/provider-stream.ts +77 -0
  115. package/src/modules/usage/provider.test.ts +67 -0
  116. package/src/modules/usage/provider.ts +142 -0
  117. package/src/modules/usage/repository.ts +541 -0
  118. package/src/modules/usage/service-availability.mysql.test.ts +68 -0
  119. package/src/modules/usage/service-availability.ts +13 -0
  120. package/src/modules/usage/service-delete.mysql.test.ts +87 -0
  121. package/src/modules/usage/stream-http.ts +32 -0
  122. package/src/modules/usage/test-harness.ts +109 -0
  123. package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
  124. package/src/modules/usage/usage-deletion.ts +119 -0
  125. package/src/modules/usage/validation.test.ts +18 -0
  126. package/src/modules/usage/validation.ts +33 -0
  127. package/src/routes/admin-billing-usage.ts +73 -0
  128. package/src/routes/admin-usage.ts +147 -0
  129. package/src/routes/admin.ts +4 -0
  130. package/src/routes/private.ts +8 -0
  131. package/web/connect/bailing-connect-php7.tgz +0 -0
  132. package/web/console/assets/Accounts-Bervi5JU.css +1 -0
  133. package/web/console/assets/Accounts-DKhw_QLr.js +3 -0
  134. package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-CM4_5HaA.js} +1 -1
  135. package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
  136. package/web/console/assets/AgentTasks-CkQgZTU5.js +2 -0
  137. package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-B9O9TkbO.js} +1 -1
  138. package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-2vDC1SPu.js} +1 -1
  139. package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-BgASiRSE.js} +1 -1
  140. package/web/console/assets/{Channels-B9n4fbxg.js → Channels-A-GvkNBt.js} +1 -1
  141. package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-BLxymI67.js} +1 -1
  142. package/web/console/assets/{Clients-CI3DBDHf.js → Clients-DeNlmvS6.js} +1 -1
  143. package/web/console/assets/{Cost-JgNXQPlN.js → Cost-CBq_L4Kz.js} +1 -1
  144. package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-DmtbctNj.js} +1 -1
  145. package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-BbcRDiA-.js} +1 -1
  146. package/web/console/assets/{Executors-CRbboOCZ.js → Executors-gGgmQrDt.js} +1 -1
  147. package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-Dtdt2tKR.js} +1 -1
  148. package/web/console/assets/{Kb-CgLNGjRp.js → Kb-lgY6OXUz.js} +2 -2
  149. package/web/console/assets/{Login-C52JmXzx.js → Login-DA6BASZd.js} +1 -1
  150. package/web/console/assets/{Projects-CDOvHPVS.js → Projects-DEbmB_sT.js} +1 -1
  151. package/web/console/assets/Routes-CyXV4Pba.css +1 -0
  152. package/web/console/assets/Routes-qS6LLoyS.js +124 -0
  153. package/web/console/assets/{Runs-DYNDXsqk.js → Runs-DG-VLRSc.js} +1 -1
  154. package/web/console/assets/{Setup-B91P6i1x.js → Setup-DEpVF5uw.js} +1 -1
  155. package/web/console/assets/Shell-DgoPgK1E.js +1 -0
  156. package/web/console/assets/Shell-ykb-tUfo.css +1 -0
  157. package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DJtNN769.js} +1 -1
  158. package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-0DEUgeTR.js} +1 -1
  159. package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-CR1phiPE.js} +1 -1
  160. package/web/console/assets/{Targets-CuuIYeZO.js → Targets-D65l-IMB.js} +1 -1
  161. package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DqtrINrN.js} +1 -1
  162. package/web/console/assets/Usage-B5njXNjx.js +1 -0
  163. package/web/console/assets/Usage-CAeDGjrb.css +1 -0
  164. package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
  165. package/web/console/assets/UsageAccess-ChnB4pjb.js +1 -0
  166. package/web/console/assets/UsageHelp-BBKIvbQ5.js +1 -0
  167. package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
  168. package/web/console/assets/{index-QnmD7N7F.js → index-65JiiUr4.js} +1 -1
  169. package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
  170. package/web/console/assets/index-sLKrJd_p.js +2 -0
  171. package/web/console/assets/{request-DeGya810.js → request-BpaimqEb.js} +1 -1
  172. package/web/console/assets/{schema-BqlqLw1R.js → schema-D0Z4kFCZ.js} +1 -1
  173. package/web/console/assets/{util-4bN2dv7B.js → util-DZYfJ5Zo.js} +1 -1
  174. package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-8cVcdt5T.js} +2 -2
  175. package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-CnDA23N0.js} +1 -1
  176. package/web/console/assets/vendor-vue-Co7x2FW6.js +29 -0
  177. package/web/console/index.html +4 -4
  178. package/web-admin/README.md +17 -0
  179. package/web-admin/package-lock.json +83 -85
  180. package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
  181. package/web-admin/src/components/UsageHelp.vue +72 -0
  182. package/web-admin/src/components/UsageServiceReferences.vue +169 -0
  183. package/web-admin/src/layout/Shell.vue +22 -5
  184. package/web-admin/src/pages/Accounts.vue +3 -3
  185. package/web-admin/src/pages/AgentTasks.vue +2 -2
  186. package/web-admin/src/pages/Routes.vue +5 -1
  187. package/web-admin/src/pages/Usage.vue +2470 -0
  188. package/web-admin/src/pages/UsageAccess.vue +1147 -0
  189. package/web-admin/src/router.ts +8 -4
  190. package/web-admin/src/styles/base.css +57 -0
  191. package/web-admin/src/table-widths.ts +16 -1
  192. package/web-admin/src/usage-deletion.ts +40 -0
  193. package/web-admin/src/usage-management.ts +13 -0
  194. package/web-admin/src/usage-presentation.test.ts +21 -0
  195. package/web-admin/src/usage-presentation.ts +107 -0
  196. package/web-admin/src/usage-price-preview.test.ts +60 -0
  197. package/web-admin/src/usage-price-preview.ts +54 -0
  198. package/web-admin/tests/token-usage.browser.mjs +773 -0
  199. package/web-admin/tests/usage-access.browser.mjs +398 -0
  200. package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
  201. package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
  202. package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
  203. package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
  204. package/web/console/assets/Routes-DkMIjMQA.css +0 -1
  205. package/web/console/assets/Routes-X9vHLpKW.js +0 -124
  206. package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
  207. package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
  208. package/web/console/assets/index-UGvfF3Xr.js +0 -2
  209. package/web/console/assets/vendor-vue-B2uhHUfE.js +0 -29
@@ -0,0 +1,178 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { calculateReferenceCost, ReferencePricing, validatePricingBinding } from './pricing';
4
+ import { UsageRepository } from './repository';
5
+ import type { Pool } from 'mysql2/promise';
6
+ import type { PriceLine, PriceSnapshot } from './billing-contracts';
7
+
8
+ const snapshot = (lines: PriceLine[]): PriceSnapshot => ({ source: 'openrouter', currency: 'USD', modelId: 'synthetic/model', endpointId: 'synthetic-provider', fetchedAt: 1, lines });
9
+ const chat = snapshot([{ billable: 'prompt', unit: 'token', costUsd: '0.000001' }, { billable: 'completion', unit: 'token', costUsd: '0.000004' }]);
10
+
11
+ test('reference USD uses measured input and output; supplier cost is never trusted', () => {
12
+ assert.equal(calculateReferenceCost(chat, { inputTokens: 100, outputTokens: 20, cost: 99999, costUsd: 99999, referenceCostUsd: 99999 }), '0.00018');
13
+ assert.equal(calculateReferenceCost(chat, { prompt_tokens: 100, completion_tokens: 20 }), '0.00018');
14
+ assert.equal(calculateReferenceCost(chat, { input_tokens: 100, output_tokens: 20 }), '0.00018');
15
+ assert.equal(calculateReferenceCost(chat, { cost: 0 }), null);
16
+ });
17
+ test('tiny USD prices retain twelve decimals rather than truncating to free usage', () => {
18
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'completion', unit: 'token', costUsd: '0.000000000001' }]), { outputTokens: 7 }), '0.000000000007');
19
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'output_image', unit: 'megapixel', costUsd: '0.000000000001' }]), { outputImageCount: 1, outputPixelCount: 1 }), '0.000000000001');
20
+ });
21
+ test('explicit free prices and measured zero counts are supported; absent usage remains unknown', () => {
22
+ const free = snapshot([{ billable: 'prompt', unit: 'token', costUsd: '0' }, { billable: 'completion', unit: 'token', costUsd: '0' }]);
23
+ assert.equal(calculateReferenceCost(free, { inputTokens: 100, outputTokens: 20 }), '0');
24
+ assert.equal(calculateReferenceCost(free, {}), null);
25
+ assert.equal(calculateReferenceCost(chat, { inputTokens: 0, outputTokens: 0 }), '0');
26
+ assert.equal(calculateReferenceCost(snapshot([]), { inputTokens: 0, outputTokens: 0 }), null);
27
+ });
28
+ test('cache hits are subtracted from full-price prompt only when separately priced', () => {
29
+ const cached = snapshot([...chat.lines, { billable: 'input_cache_read', unit: 'token', costUsd: '0.0000001' }, { billable: 'input_cache_write', unit: 'token', costUsd: '0.000002' }]);
30
+ assert.equal(calculateReferenceCost(cached, { inputTokens: 100, outputTokens: 20, cachedInputTokens: 40, cacheWriteTokens: 10 }), '0.000154');
31
+ assert.equal(calculateReferenceCost(chat, { inputTokens: 100, outputTokens: 20, cachedInputTokens: 40 }), '0.00018');
32
+ assert.equal(calculateReferenceCost(cached, { inputTokens: 20, outputTokens: 10, cachedInputTokens: 40, cacheWriteTokens: 0 }), null);
33
+ assert.equal(calculateReferenceCost(cached, { inputTokens: 100, outputTokens: 20 }), null, 'Missing separately priced cache counts are unknown, not zero.');
34
+ assert.equal(calculateReferenceCost(cached, { inputTokens: 100, outputTokens: 20, input_tokens_details: { cached_tokens: 40 }, cacheWriteTokens: 10 }), '0.000154');
35
+ });
36
+ test('image billing requires explicit matching variant; no resolution, name or count guessing', () => {
37
+ const price = snapshot([{ billable: 'input_image', unit: 'image', costUsd: '0.003' },
38
+ { billable: 'output_image', unit: 'image', costUsd: '0.03', variant: '1k' },
39
+ { billable: 'output_image', unit: 'image', costUsd: '0.05', variant: '2k' }]);
40
+ assert.equal(calculateReferenceCost(price, { inputImageCount: 0, outputImageCount: 2, outputVariant: '1k' }), '0.06');
41
+ assert.equal(calculateReferenceCost(price, { inputImageCount: 1, outputImageCount: 2, outputVariant: '2k' }), '0.103');
42
+ assert.equal(calculateReferenceCost(price, { outputImageCount: 1, outputVariant: '1k' }), null);
43
+ assert.equal(calculateReferenceCost(price, { inputImageCount: 0, outputImageCount: 1, outputWidth: 1024, outputHeight: 1024 }), null);
44
+ assert.equal(calculateReferenceCost(price, { inputImageCount: 0, outputImageCount: 1, outputVariant: '4k' }), null);
45
+ const ambiguous = snapshot([...price.lines, { billable: 'output_image', unit: 'image', costUsd: '0.01' }]);
46
+ assert.equal(calculateReferenceCost(ambiguous, { inputImageCount: 0, outputImageCount: 1, outputVariant: '1k' }), null);
47
+ });
48
+ test('image tokens and total measured pixel counts have distinct units', () => {
49
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'output_image', unit: 'token', costUsd: '0.000001' }]), { outputImageCount: 1, outputImageTokens: 1200 }), '0.0012');
50
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'output_image', unit: 'token', costUsd: '0.000001' }]), { outputImageCount: 1 }), null);
51
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'output_image', unit: 'megapixel', costUsd: '0.01' }]), { outputImageCount: 2, outputPixelCount: 2_500_000 }), '0.025');
52
+ });
53
+ test('unsupported or malformed metering never produces a fabricated charge, including zero-count cases', () => {
54
+ for (const raw of [{inputTokens: -1,outputTokens: 0}, {inputTokens: 1.1,outputTokens: 0}, {inputTokens: NaN,outputTokens: 0}, {inputTokens: '1',outputTokens: 0}]) assert.equal(calculateReferenceCost(chat, raw), null);
55
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'unknown_metric', unit: 'token', costUsd: '1' }]), { inputTokens: 1 }), null);
56
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'prompt', unit: 'image', costUsd: '1' }]), { inputTokens: 1 }), null);
57
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'prompt', unit: 'token', costUsd: '-1' }]), { inputTokens: 0 }), null);
58
+ assert.equal(calculateReferenceCost(snapshot([{ billable: 'prompt', unit: 'second', costUsd: '1' }]), { inputTokens: 0 }), null);
59
+ });
60
+ test('request fees require a measured request count and are added once', () => {
61
+ const price = snapshot([...chat.lines, { billable: 'request', unit: 'request', costUsd: '0.01' }]);
62
+ assert.equal(calculateReferenceCost(price, { inputTokens: 100, outputTokens: 20, requestCount: 1 }), '0.01018');
63
+ assert.equal(calculateReferenceCost(price, { inputTokens: 100, outputTokens: 20 }), null);
64
+ });
65
+
66
+ /** Synthetic persistence and transport only: no real endpoint, account or provider key. */
67
+ function cacheFixture() {
68
+ const saved = new Map<string, any>();
69
+ const pool = { async query(sql: string, parameters: any[]) {
70
+ if (sql.startsWith('SELECT snapshot_json')) { const v = saved.get(parameters[0]); return [v ? [{ snapshot_json: structuredClone(v) }] : []]; }
71
+ if (sql.startsWith('INSERT INTO bz_usage_price_snapshots')) { saved.set(parameters[0], JSON.parse(parameters[1])); return [{}]; }
72
+ throw new Error('Unexpected synthetic query');
73
+ } } as unknown as Pool;
74
+ let calls = 0, status = 200;
75
+ let value: unknown = { data: { endpoints: [{ tag: 'synthetic-provider', provider_name: 'Synthetic', pricing: { prompt: '0.000001', completion: '0.000004' } }] } };
76
+ const fetcher = (async (url: string | URL | Request, options?: RequestInit) => {
77
+ calls++; assert.equal(options?.redirect, 'error'); assert(String(url).startsWith('https://openrouter.ai/api/v1/'));
78
+ return new Response(JSON.stringify(value), { status, headers: {'content-type': 'application/json'} });
79
+ }) as typeof fetch;
80
+ const repository = new UsageRepository(() => pool), pricing = new ReferencePricing(repository, fetcher);
81
+ return { pricing, saved, calls: () => calls, set(v: unknown, s = 200) { value = v; status = s; } };
82
+ }
83
+ const binding = {source:'openrouter' as const,kind:'chat' as const,modelId:'synthetic/model',endpointId:'synthetic-provider'};
84
+ test('binding is explicit and rejects arbitrary remote URLs and path traversal', () => {
85
+ validatePricingBinding(binding);
86
+ for (const value of [{...binding,modelId:'../secret'}, {...binding,source:'custom'}, {...binding,endpointId:''}, {...binding,url:'https://invalid.example'}]) assert.throws(() => validatePricingBinding(value));
87
+ });
88
+ test('reference snapshot requires synchronized selected endpoint and never adds a fetch before admission', async () => {
89
+ const h = cacheFixture();
90
+ await assert.rejects(h.pricing.snapshot(binding), { code:'USAGE_PRICE_UNAVAILABLE' }); assert.equal(h.calls(), 0);
91
+ await h.pricing.catalog('chat', binding.modelId); assert.equal(h.calls(), 1);
92
+ const original = await h.pricing.snapshot(binding); assert.equal(h.calls(), 1); assert.equal(original.lines[0]!.costUsd, '0.000001');
93
+ original.lines[0]!.costUsd = '999'; assert.equal((await h.pricing.snapshot(binding)).lines[0]!.costUsd, '0.000001');
94
+ await assert.rejects(h.pricing.snapshot({...binding,endpointId:'other-provider'}), {code:'USAGE_PRICE_UNAVAILABLE'});
95
+ await h.pricing.catalog('chat',binding.modelId); assert.equal(h.calls(),1);
96
+ });
97
+ test('catalog outage keeps the last verified price; first-time outage never invents zero price', async () => {
98
+ const h=cacheFixture(); await h.pricing.catalog('chat',binding.modelId);
99
+ h.set({error:'synthetic'},503);
100
+ const stale=await h.pricing.catalog('chat',binding.modelId,true); assert.equal(stale.stale,true);
101
+ assert.equal((await h.pricing.snapshot(binding)).lines[0]!.costUsd,'0.000001');
102
+ const first=cacheFixture(); first.set({},503);
103
+ await assert.rejects(first.pricing.catalog('chat',binding.modelId), {code:'USAGE_PRICE_UNAVAILABLE'});
104
+ });
105
+ test('ambiguous endpoint and unknown priced dimensions cannot silently select another quote', async () => {
106
+ const h=cacheFixture(); await h.pricing.catalog('chat',binding.modelId);
107
+ assert.equal((await h.pricing.snapshot(binding)).lines[0]!.costUsd,'0.000001');
108
+ h.set({data:{endpoints:[{tag:'synthetic-provider',pricing:{prompt:'0.1',completion:'0.2',unknown_dimension:'1'}}]}});
109
+ const result=await h.pricing.catalog('chat',binding.modelId,true); assert.equal(result.items[0].unavailable,true);
110
+ await assert.rejects(h.pricing.snapshot(binding),{code:'USAGE_PRICE_UNSUPPORTED'});
111
+ h.set({data:{endpoints:[{tag:'synthetic-provider',pricing:{prompt:'0.1',completion:'0.2'}},{tag:'synthetic-provider',pricing:{prompt:'0.5',completion:'0.2'}}]}});
112
+ assert.equal((await h.pricing.catalog('chat',binding.modelId,true)).items.length,0);
113
+ });
114
+
115
+ test('tier selects the highest measured prompt threshold inclusively, not incremental bands or uncached tokens', () => {
116
+ const tiered: PriceSnapshot = { ...chat, tiers: [
117
+ { minPromptTokens: 500000, lines: [{billable:'prompt',unit:'token',costUsd:'0.000004'},{billable:'completion',unit:'token',costUsd:'0.000016'}] },
118
+ { minPromptTokens: 272000, lines: [{billable:'prompt',unit:'token',costUsd:'0.000002'},{billable:'completion',unit:'token',costUsd:'0.000008'}] },
119
+ ] };
120
+ assert.equal(calculateReferenceCost(tiered,{inputTokens:271999,outputTokens:10}),'0.272039');
121
+ assert.equal(calculateReferenceCost(tiered,{inputTokens:272000,outputTokens:10}),'0.54408');
122
+ assert.equal(calculateReferenceCost(tiered,{inputTokens:500000,outputTokens:10}),'2.00016');
123
+ assert.equal(calculateReferenceCost(tiered,{outputTokens:10}),null);
124
+ const cached: PriceSnapshot = { ...chat, tiers:[{minPromptTokens:272000,lines:[
125
+ {billable:'prompt',unit:'token',costUsd:'0.000002'}, {billable:'completion',unit:'token',costUsd:'0.000008'},
126
+ {billable:'input_cache_read',unit:'token',costUsd:'0.0000002'}, {billable:'input_cache_write',unit:'token',costUsd:'0.000004'},
127
+ ]}] };
128
+ assert.equal(calculateReferenceCost(cached,{inputTokens:300000,outputTokens:10,cachedInputTokens:200000,cacheWriteTokens:0}),'0.24008');
129
+ assert.equal(calculateReferenceCost(cached,{inputTokens:300000,outputTokens:10,cachedInputTokens:200000}),null);
130
+ assert.equal(calculateReferenceCost({...tiered,tiers:[tiered.tiers![0]!,tiered.tiers![0]!]}, {inputTokens:1,outputTokens:0}),null);
131
+ });
132
+
133
+ test('web search is a separately measured request fee: missing is unknown, explicit zero is no fee', () => {
134
+ const price=snapshot([...chat.lines,{billable:'web_search',unit:'request',costUsd:'0.01'}]);
135
+ assert.equal(calculateReferenceCost(price,{inputTokens:100,outputTokens:20}),null);
136
+ assert.equal(calculateReferenceCost(price,{inputTokens:100,outputTokens:20,webSearchCount:0}),'0.00018');
137
+ assert.equal(calculateReferenceCost(price,{inputTokens:100,outputTokens:20,webSearchCount:2}),'0.02018');
138
+ assert.equal(calculateReferenceCost(price,{inputTokens:100,outputTokens:20,webSearchCount:'0'}),null);
139
+ });
140
+
141
+ test('catalog normalizes tier overrides into frozen complete quotes retaining base request fees', async () => {
142
+ const h=cacheFixture();
143
+ h.set({data:{endpoints:[{tag:'synthetic-provider',pricing:{prompt:'0.000001',completion:'0.000004',input_cache_read:'0.0000001',input_cache_write:'0.000002',web_search:'0.01',
144
+ overrides:[{min_prompt_tokens:272000,prompt:'0.000002',completion:'0.000008',input_cache_read:'0.0000002',input_cache_write:'0.000004'}]}}]}});
145
+ const catalog=await h.pricing.catalog('chat',binding.modelId); assert.equal(catalog.items[0].unavailable,undefined);
146
+ const price=await h.pricing.snapshot(binding);
147
+ assert.equal(price.tiers?.[0]?.minPromptTokens,272000); assert.equal(price.tiers?.[0]?.lines.length,5);
148
+ assert.equal(price.tiers?.[0]?.lines.find(line=>line.billable==='web_search')?.costUsd,'0.01');
149
+ assert.equal(calculateReferenceCost(price,{inputTokens:300000,outputTokens:10,cachedInputTokens:200000,cacheWriteTokens:0,webSearchCount:0}),'0.24008');
150
+ assert.equal(calculateReferenceCost(price,{inputTokens:300000,outputTokens:10,cachedInputTokens:200000,cacheWriteTokens:0}),null);
151
+ h.set({data:{endpoints:[{tag:'synthetic-provider',pricing:{prompt:'1',completion:'1',overrides:[{min_prompt_tokens:1,min_output_tokens:1,prompt:'2'}]}}]}});
152
+ const bad=await h.pricing.catalog('chat',binding.modelId,true); assert.equal(bad.items[0].unavailable,true);
153
+ await assert.rejects(h.pricing.snapshot(binding),{code:'USAGE_PRICE_UNSUPPORTED'});
154
+ });
155
+
156
+ test('admission snapshot rejects invalid tier thresholds and invalid future-tier units before any dispatch', async () => {
157
+ const { tokenBillingRate } = await import('./billing-ledger');
158
+ const price: PriceSnapshot = {...chat,tiers:[{minPromptTokens:272000,lines:chat.lines}]};
159
+ assert.deepEqual(tokenBillingRate('synthetic-plan',1,1.5,price).price,price);
160
+ assert.throws(()=>tokenBillingRate('synthetic-plan',1,1.5,{...price,tiers:[price.tiers![0]!,price.tiers![0]!]}), /unique/);
161
+ assert.throws(()=>tokenBillingRate('synthetic-plan',1,1.5,{...price,tiers:[{minPromptTokens:0,lines:chat.lines}]}), /positive/);
162
+ assert.throws(()=>tokenBillingRate('synthetic-plan',1,1.5,{...price,tiers:[{minPromptTokens:1,lines:[{billable:'prompt',unit:'image',costUsd:'1'}]}]}), /Invalid/);
163
+ });
164
+
165
+
166
+ test('readiness distinguishes unbound, unsynchronized, unsupported and ready without provider traffic', async () => {
167
+ const h = cacheFixture();
168
+ assert.equal((await h.pricing.inspect(undefined)).availability.code, 'USAGE_PRICE_NOT_CONFIGURED');
169
+ assert.equal((await h.pricing.inspect(binding)).availability.code, 'USAGE_PRICE_UNAVAILABLE');
170
+ assert.equal(h.calls(), 0);
171
+ await h.pricing.catalog('chat', binding.modelId);
172
+ assert.deepEqual((await h.pricing.inspect(binding)).availability, {state:'ready',code:null,message:null});
173
+ assert.equal(h.calls(), 1);
174
+ h.set({data:{endpoints:[{tag:binding.endpointId,pricing:{prompt:'1',completion:'2',unsupported_meter:'3'}}]}});
175
+ await h.pricing.catalog('chat', binding.modelId, true);
176
+ assert.equal((await h.pricing.inspect(binding)).availability.code, 'USAGE_PRICE_UNSUPPORTED');
177
+ assert.equal(h.calls(), 2);
178
+ });
@@ -0,0 +1,229 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { RowDataPacket } from 'mysql2/promise';
3
+ import { UsageError, usageAssert } from './errors';
4
+ import { assertKnownFields } from './validation';
5
+ import { usdMicros, usdDecimal } from './billing-decimal';
6
+ import type { PriceLine, PriceSnapshot, PriceTier } from './billing-contracts';
7
+ import type { UsageRepository } from './repository';
8
+
9
+ export interface PricingBinding { source: 'openrouter'; kind: 'chat' | 'image'; modelId: string; endpointId: string }
10
+ export interface PriceAvailability {
11
+ state: 'ready' | 'unavailable'; code: string | null; message: string | null;
12
+ }
13
+ export function validatePricingBinding(value: unknown): asserts value is PricingBinding {
14
+ assertKnownFields(value, ['source','kind','modelId','endpointId'], 'pricing');
15
+ const p = value as PricingBinding;
16
+ usageAssert(p?.source === 'openrouter' && ['chat','image'].includes(p.kind)
17
+ && typeof p.modelId === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,190}$/.test(p.modelId)
18
+ && !p.modelId.includes('..') && typeof p.endpointId === 'string' && p.endpointId.length > 0 && p.endpointId.length <= 191,
19
+ 'USAGE_INVALID_INPUT', '请选择明确的参考模型和价格端点。', 400);
20
+ }
21
+ const finiteCount = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
22
+ function numericPrice(value: unknown): string {
23
+ usageAssert(typeof value === 'string' || typeof value === 'number', 'USAGE_PRICE_UNAVAILABLE', '参考价格缺少有效单价。', 503);
24
+ return usdDecimal(usdMicros(value));
25
+ }
26
+ function imageLines(value: unknown): PriceLine[] {
27
+ usageAssert(Array.isArray(value) && value.length > 0 && value.length <= 64, 'USAGE_PRICE_UNAVAILABLE', '参考价格缺少计费项。', 503);
28
+ return value.map(line => {
29
+ usageAssert(line && ['input_image','output_image','input_reference'].includes(line.billable)
30
+ && ['image','megapixel','token'].includes(line.unit) && (line.variant === undefined || typeof line.variant === 'string'),
31
+ 'USAGE_PRICE_UNSUPPORTED', '此价格规则尚无计量映射,不能按免费处理。', 503);
32
+ return { billable: line.billable, unit: line.unit, costUsd: numericPrice(line.cost_usd), ...(line.variant ? { variant: line.variant.toLowerCase() } : {}) };
33
+ });
34
+ }
35
+ function chatLines(p: Record<string, unknown>): PriceLine[] {
36
+ const fields = ['prompt','completion','input_cache_read','input_cache_write'];
37
+ usageAssert(p && p.prompt !== undefined && p.completion !== undefined, 'USAGE_PRICE_UNAVAILABLE', '缺少输入或输出参考单价。', 503);
38
+ for (const [key, value] of Object.entries(p)) {
39
+ if (![...fields,'discount','request','web_search'].includes(key) && Number(value) !== 0)
40
+ throw new UsageError('USAGE_PRICE_UNSUPPORTED', `参考价格包含尚未适配的计费项:${key}`, 503);
41
+ }
42
+ return [...fields.filter(k => p[k] !== undefined).map(k => ({ billable: k, unit: 'token' as const, costUsd: numericPrice(p[k]) })),
43
+ ...['request','web_search'].filter(k => p[k] !== undefined && Number(p[k]) !== 0).map(k => ({ billable: k, unit: 'request' as const, costUsd: numericPrice(p[k]) }))];
44
+ }
45
+ /** Persist complete tier quotes so later catalog changes cannot reinterpret a request. */
46
+ function chatPricing(value: Record<string, unknown>): Pick<PriceSnapshot, 'lines' | 'tiers'> {
47
+ usageAssert(value && typeof value === 'object' && !Array.isArray(value), 'USAGE_PRICE_UNAVAILABLE', '缺少参考价格。', 503);
48
+ const { overrides, ...base } = value;
49
+ const lines = chatLines(base);
50
+ if (overrides === undefined) return { lines };
51
+ usageAssert(Array.isArray(overrides) && overrides.length <= 64, 'USAGE_PRICE_UNSUPPORTED', '阶梯报价格式不支持。', 503);
52
+ const seen = new Set<number>();
53
+ const tiers: PriceTier[] = overrides.map(override => {
54
+ usageAssert(override && typeof override === 'object' && !Array.isArray(override), 'USAGE_PRICE_UNSUPPORTED', '阶梯报价格式不支持。', 503);
55
+ const { min_prompt_tokens, ...rates } = override;
56
+ usageAssert(finiteCount(min_prompt_tokens) && min_prompt_tokens > 0 && !seen.has(min_prompt_tokens), 'USAGE_PRICE_UNSUPPORTED', '阶梯报价门槛必须明确且唯一。', 503);
57
+ usageAssert(Object.keys(rates).every(key => ['prompt','completion','input_cache_read','input_cache_write','request','web_search','discount'].includes(key)),
58
+ 'USAGE_PRICE_UNSUPPORTED', '阶梯报价含未适配的条件或收费项。', 503);
59
+ seen.add(min_prompt_tokens);
60
+ return { minPromptTokens: min_prompt_tokens, lines: chatLines({ ...base, ...rates }) };
61
+ }).sort((a,b) => a.minPromptTokens - b.minPromptTokens);
62
+ return { lines, ...(tiers.length ? { tiers } : {}) };
63
+ }
64
+
65
+ /** Reference pricing is independent of the actual provider bill. Unknown usage never means zero. */
66
+ export function calculateReferenceCost(snapshot: PriceSnapshot, raw: Record<string, unknown>): string | null {
67
+ try {
68
+ if (!snapshot.lines.length) return null;
69
+ let selectedLines = snapshot.lines;
70
+ if (snapshot.tiers !== undefined) {
71
+ if (!Array.isArray(snapshot.tiers) || snapshot.tiers.length > 64) return null;
72
+ const input = raw.inputTokens ?? raw.prompt_tokens ?? raw.input_tokens;
73
+ if (!finiteCount(input)) return null;
74
+ let selectedThreshold = -1;
75
+ const seen = new Set<number>();
76
+ for (const tier of snapshot.tiers) {
77
+ if (!finiteCount(tier.minPromptTokens) || tier.minPromptTokens <= 0 || seen.has(tier.minPromptTokens)
78
+ || !Array.isArray(tier.lines) || !tier.lines.length) return null;
79
+ seen.add(tier.minPromptTokens);
80
+ if (input >= tier.minPromptTokens && tier.minPromptTokens > selectedThreshold) {
81
+ selectedLines = tier.lines; selectedThreshold = tier.minPromptTokens;
82
+ }
83
+ }
84
+ }
85
+ let total = 0n;
86
+ const groups = new Map<string, PriceLine[]>();
87
+ const tokenMetrics = new Set(['prompt','completion','input_cache_read','input_cache_write']);
88
+ const imageMetrics = new Set(['input_image','output_image','input_reference']);
89
+ for (const line of selectedLines) {
90
+ // Validate even when the measured count is zero. Unknown dimensions and
91
+ // corrupt quotes must never silently become a valid free-price record.
92
+ const validUnit = tokenMetrics.has(line.billable) ? line.unit === 'token'
93
+ : imageMetrics.has(line.billable) ? ['image','megapixel','token'].includes(line.unit)
94
+ : ['request','web_search'].includes(line.billable) && line.unit === 'request';
95
+ if (!validUnit) return null;
96
+ usdMicros(line.costUsd);
97
+ const group = groups.get(line.billable) ?? []; group.push(line); groups.set(line.billable, group);
98
+ }
99
+ const cache = (raw.prompt_tokens_details ?? raw.input_tokens_details) as Record<string,unknown> | undefined;
100
+ const cached = groups.has('input_cache_read') ? raw.cachedInputTokens ?? cache?.cached_tokens ?? raw.prompt_cache_hit_tokens : 0;
101
+ const written = groups.has('input_cache_write') ? raw.cacheWriteTokens ?? raw.cache_creation_input_tokens : 0;
102
+ // The reference quote distinguishes these counts, so missing evidence
103
+ // cannot be treated as zero or billed at the undiscounted prompt price.
104
+ if (!finiteCount(cached) || !finiteCount(written)) return null;
105
+ for (const [billable, lines] of groups) {
106
+ let count: unknown, variant: unknown;
107
+ const input = raw.inputTokens ?? raw.prompt_tokens ?? raw.input_tokens;
108
+ const output = raw.outputTokens ?? raw.completion_tokens ?? raw.output_tokens;
109
+ switch (billable) {
110
+ case 'prompt': {
111
+ if (!finiteCount(input)) return null;
112
+ count = input - (groups.has('input_cache_read') ? cached : 0) - (groups.has('input_cache_write') ? written : 0); break;
113
+ }
114
+ case 'completion': count = output; break;
115
+ case 'input_cache_read': count = cached; break;
116
+ case 'input_cache_write': count = written; break;
117
+ case 'request': count = raw.requestCount; break;
118
+ case 'web_search': count = raw.webSearchCount; break;
119
+ case 'input_image': case 'input_reference': count = raw.inputImageCount; variant = raw.inputVariant; break;
120
+ case 'output_image': count = raw.outputImageCount; variant = raw.outputVariant; break;
121
+ default: return null;
122
+ }
123
+ if (!finiteCount(count)) return null;
124
+ if (count === 0) continue;
125
+ const matching = lines.filter(l => !l.variant || l.variant === variant);
126
+ if (matching.length !== 1) return null;
127
+ const line = matching[0]!;
128
+ if ((billable.endsWith('image') || billable === 'input_reference') && line.unit === 'token') {
129
+ const tokens = billable === 'output_image' ? raw.outputImageTokens : raw.inputImageTokens;
130
+ if (!finiteCount(tokens)) return null; count = tokens;
131
+ }
132
+ if (!finiteCount(count)) return null;
133
+ let multiplier = BigInt(count), divisor = 1n;
134
+ if (line.unit === 'megapixel') {
135
+ const pixels = billable === 'output_image' ? raw.outputPixelCount : raw.inputPixelCount;
136
+ if (!finiteCount(pixels)) return null;
137
+ multiplier = BigInt(pixels); divisor = 1_000_000n;
138
+ }
139
+ total += (usdMicros(line.costUsd) * multiplier + divisor - 1n) / divisor;
140
+ }
141
+ return usdDecimal(total);
142
+ } catch { return null; }
143
+ }
144
+
145
+ const TTL = 6 * 60 * 60 * 1000;
146
+ const MAX_RESPONSE = 8 * 1024 * 1024;
147
+ type Catalog = { items: any[]; fetchedAt: number; stale?: boolean };
148
+ export class ReferencePricing {
149
+ private flights = new Map<string, Promise<Catalog>>();
150
+ constructor(private repository: UsageRepository, private fetcher: typeof fetch = fetch) {}
151
+ private async get(key: string): Promise<Catalog | null> {
152
+ const [rows] = await this.repository.getPool().query<RowDataPacket[]>('SELECT snapshot_json FROM bz_usage_price_snapshots WHERE cache_key=?', [key]);
153
+ if (!rows[0]) return null;
154
+ return typeof rows[0].snapshot_json === 'string' ? JSON.parse(rows[0].snapshot_json) : rows[0].snapshot_json;
155
+ }
156
+ private async save(key: string, data: Catalog) {
157
+ await this.repository.getPool().query('INSERT INTO bz_usage_price_snapshots(cache_key,snapshot_json,fetched_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE snapshot_json=VALUES(snapshot_json),fetched_at=VALUES(fetched_at)', [key, JSON.stringify(data),data.fetchedAt]);
158
+ }
159
+ private key(kind: string, model?: string) { return createHash('sha256').update(`${kind}:${model ?? 'catalog'}`).digest('hex'); }
160
+ private async fetchJson(path: string): Promise<any> {
161
+ const response = await this.fetcher(`https://openrouter.ai/api/v1/${path}`, { redirect:'error', signal:AbortSignal.timeout(10000), headers:{accept:'application/json'} });
162
+ usageAssert(response.ok, 'USAGE_PRICE_UNAVAILABLE', '参考价格目录暂不可用。', 503);
163
+ let bytes = 0; const chunks: Uint8Array[] = [];
164
+ if (!response.body) throw new UsageError('USAGE_PRICE_UNAVAILABLE','参考目录返回空内容。',503);
165
+ for await (const chunk of response.body) { bytes += chunk.length; if (bytes > MAX_RESPONSE) { await response.body.cancel().catch(()=>{}); throw new UsageError('USAGE_PRICE_UNAVAILABLE','参考目录响应过大。',503); } chunks.push(chunk); }
166
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
167
+ }
168
+ private async refresh(kind: 'chat'|'image', modelId?: string): Promise<Catalog> {
169
+ const key = this.key(kind,modelId), pending = this.flights.get(key); if (pending) return pending;
170
+ const job = this.repository.backgroundWork.startMaintenance('reference-price-refresh', async () => {
171
+ const prefix = kind === 'image' ? 'images/models' : 'models';
172
+ const encoded = modelId?.split('/').map(encodeURIComponent).join('/');
173
+ const value = await this.fetchJson(modelId ? `${prefix}/${encoded}/endpoints` : prefix);
174
+ const fetchedAt = Date.now(); let items: any[];
175
+ if (!modelId) {
176
+ usageAssert(Array.isArray(value.data), 'USAGE_PRICE_UNAVAILABLE','参考模型目录格式异常。',503);
177
+ items = value.data.filter((x:any) => typeof x.id === 'string' && (kind === 'image' || x.architecture?.output_modalities?.includes('text'))).map((x:any)=>({id:x.id,label:x.name||x.id,kind}));
178
+ } else {
179
+ const endpoints = kind === 'image' ? value.endpoints : value.data?.endpoints;
180
+ usageAssert(Array.isArray(endpoints), 'USAGE_PRICE_UNAVAILABLE','参考端点目录格式异常。',503);
181
+ items = endpoints.map((x:any) => {
182
+ const id = kind === 'image' ? x.provider_tag ?? x.provider_slug : x.tag;
183
+ if (typeof id !== 'string' || !id) return null;
184
+ try { const quote = kind === 'image' ? { lines: imageLines(x.pricing) } : chatPricing(x.pricing);
185
+ return {id,label:x.provider_name||id,pricing:{source:'openrouter',modelId,endpointId:id,currency:'USD',fetchedAt,...quote} satisfies PriceSnapshot};
186
+ } catch { return {id,label:x.provider_name||id,unavailable:true,reason:'USAGE_PRICE_UNSUPPORTED'}; }
187
+ }).filter(Boolean);
188
+ // A duplicate endpoint ID cannot silently pick a different price record.
189
+ items = items.filter((x:any) => items.filter((y:any)=>y.id===x.id).length===1);
190
+ }
191
+ const result = {items,fetchedAt}; await this.save(key,result); return result;
192
+ });
193
+ usageAssert(job, 'USAGE_PRICE_UNAVAILABLE', '参考价格同步已停止,请稍后重试。', 503);
194
+ this.flights.set(key,job); try {return await job;} finally {this.flights.delete(key);}
195
+ }
196
+ async catalog(kind:'chat'|'image', modelId?: string, force=false): Promise<Catalog> {
197
+ if (modelId) validatePricingBinding({source:'openrouter',kind,modelId,endpointId:'lookup'});
198
+ const cached=await this.get(this.key(kind,modelId));
199
+ if (cached && !force) {
200
+ const stale = Date.now()-cached.fetchedAt > TTL;
201
+ if (stale) void this.refresh(kind,modelId).catch(()=>{});
202
+ return {...cached,stale};
203
+ }
204
+ try {return {...await this.refresh(kind,modelId),stale:false};}
205
+ catch(error){if(cached)return {...cached,stale:true};throw error;}
206
+ }
207
+ /** Same cached quote check for the console, discovery and dispatch. No paid call or catalog round-trip. */
208
+ async inspect(binding: PricingBinding | undefined): Promise<{ availability: PriceAvailability; price?: PriceSnapshot }> {
209
+ const unavailable = (code: string, message: string) => ({ availability: {state: 'unavailable' as const, code, message} });
210
+ if (!binding) return unavailable('USAGE_PRICE_NOT_CONFIGURED', '尚未绑定参考模型和价格端点,请配置参考价格。');
211
+ try { validatePricingBinding(binding); }
212
+ catch { return unavailable('USAGE_PRICE_NOT_CONFIGURED', '参考价格绑定无效,请重新配置。'); }
213
+ const cached = await this.get(this.key(binding.kind,binding.modelId));
214
+ const endpoint = cached?.items.find(x=>x.id===binding.endpointId);
215
+ if (!cached) return unavailable('USAGE_PRICE_UNAVAILABLE', '参考价格尚未同步,请在模型服务中同步价格。');
216
+ if (!endpoint) return unavailable('USAGE_PRICE_UNAVAILABLE', '参考端点已不在目录中,请重新选择端点并同步价格。');
217
+ if (endpoint.unavailable) return unavailable('USAGE_PRICE_UNSUPPORTED', '参考端点的计量规则暂不支持,请选择受支持的参考端点。');
218
+ if (!endpoint.pricing) return unavailable('USAGE_PRICE_UNAVAILABLE', '参考端点缺少有效报价,请同步价格或重新配置。');
219
+ if (Date.now()-cached!.fetchedAt > TTL) void this.refresh(binding.kind,binding.modelId).catch(()=>{});
220
+ return {availability:{state:'ready',code:null,message:null},price:structuredClone(endpoint.pricing)};
221
+ }
222
+ async snapshot(binding: PricingBinding | undefined): Promise<PriceSnapshot> {
223
+ const result = await this.inspect(binding);
224
+ usageAssert(result.price, result.availability.code ?? 'USAGE_PRICE_UNAVAILABLE',result.availability.message ?? '参考价格暂不可用。',503);
225
+ return result.price;
226
+ }
227
+ }
228
+ const instances=new WeakMap<UsageRepository,ReferencePricing>();
229
+ export function referencePricing(repository:UsageRepository) {let p=instances.get(repository);if(!p){p=new ReferencePricing(repository);instances.set(repository,p);}return p;}
@@ -0,0 +1,37 @@
1
+ import { UsageError } from './errors';
2
+
3
+ /** Safe diagnostics only: never retain provider messages, bodies, URLs or credentials. */
4
+ export interface ProviderDiagnostic {
5
+ code: 'USAGE_PROVIDER_REJECTED' | 'USAGE_PROVIDER_ERROR' | 'USAGE_TRANSPORT_UNCERTAIN' | 'USAGE_PROVIDER_INVALID';
6
+ message: string;
7
+ http_status?: number;
8
+ provider_code?: string;
9
+ provider_request_id?: string;
10
+ retryable: false;
11
+ next_action: 'contact_operator' | 'inspect_original';
12
+ }
13
+ export class ProviderFailure extends UsageError {
14
+ constructor(readonly rejected: boolean, readonly diagnostic: ProviderDiagnostic) {
15
+ super(diagnostic.code, diagnostic.message, 502);
16
+ }
17
+ }
18
+ export function safeProviderIdentifier(value: unknown, secrets: string[] = []): string | undefined {
19
+ if (typeof value !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(value)
20
+ || /^(?:sk-|bearer|eyJ)/i.test(value) || secrets.some(s => s && value.includes(s))) return undefined;
21
+ return value;
22
+ }
23
+ export function httpProviderFailure(status: number, value: unknown, requestId: unknown, secrets: string[] = []): ProviderFailure {
24
+ const record = value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
25
+ const nested = record.error && typeof record.error === 'object' ? record.error as Record<string, unknown> : record;
26
+ const provider_code = safeProviderIdentifier(nested.code, secrets);
27
+ const provider_request_id = safeProviderIdentifier(requestId ?? record.request_id, secrets);
28
+ // These HTTP responses reject the request. Timeouts, conflicts and server
29
+ // errors do not prove that generation did not execute and must not be replayed.
30
+ const rejected = [400,401,403,404,405,413,415,422,429].includes(status);
31
+ return new ProviderFailure(rejected, {
32
+ code: rejected ? 'USAGE_PROVIDER_REJECTED' : 'USAGE_PROVIDER_ERROR',
33
+ message: rejected ? '生成服务拒绝了本次请求,请检查模型接口、权限和参数。' : '生成服务返回异常,原请求结果尚无法确认。',
34
+ http_status: status, ...(provider_code ? {provider_code} : {}), ...(provider_request_id ? {provider_request_id} : {}),
35
+ retryable: false, next_action: rejected ? 'contact_operator' : 'inspect_original',
36
+ });
37
+ }
@@ -0,0 +1,85 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { readProviderExchange } from './provider-stream';
4
+ import { normalizeModelRequest, providerBody } from './provider';
5
+ import type { UsageServiceConfig } from './contracts';
6
+
7
+ const config: UsageServiceConfig = { credential: 'synthetic', model: 'synthetic', providerScope: 'synthetic',
8
+ maxInputBytes: 1048576, maxOutputTokens: 2048, timeoutMs: 60000 };
9
+ const request = { operation_id: 'op', messages: [{ role: 'user', content: 'synthetic' }] };
10
+ const event = (data: unknown) => `data: ${JSON.stringify(data)}\r\n\r\n`;
11
+ const stream = (body: string) => new Response(body, { headers: { 'content-type': 'text/event-stream' } });
12
+
13
+ test('transport forwards every provider field and UTF8 fragment before completion', async () => {
14
+ let source!: ReadableStreamDefaultController<Uint8Array>;
15
+ const response = new Response(new ReadableStream({ start(c) { source = c; } }), { headers: { 'content-type': 'text/event-stream' } });
16
+ const packets: Record<string, unknown>[] = []; let first!: () => void;
17
+ const preview = new Promise<void>(resolve => { first = resolve; });
18
+ const result = readProviderExchange(response, async packet => { packets.push(packet); first(); });
19
+ const head = event({ id: 'synthetic', choices: [{ index: 0, delta: { content: '你好', reasoning: { extension: true }, tool_calls: null }, finish_reason: 'provider_specific' }], extension: { a: 1 } });
20
+ for (const byte of new TextEncoder().encode(head)) source.enqueue(Uint8Array.of(byte));
21
+ await preview;
22
+ const tail = event({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 2 } }) + 'data: [DONE]\r\n\r\n';
23
+ source.enqueue(new TextEncoder().encode(tail)); source.close();
24
+ const completed = await result;
25
+ assert.equal(packets.map(packet => packet.data).join(''), head + tail);
26
+ assert.equal(completed.response.body, head + tail);
27
+ assert.deepEqual(completed.usage, { inputTokens: 10, outputTokens: 2 });
28
+ });
29
+
30
+ test('provider semantics are preserved for local parsing, never rejected by the meter', async () => {
31
+ const bodies = [
32
+ event({ choices: [{ delta: { content: '', tool_calls: [] }, finish_reason: 'content_filter' }] }),
33
+ event({ id: 'first', choices: [] }) + event({ id: 'second', choices: [] }),
34
+ event({ choices: [{ index: 4, delta: { tool_calls: [{ index: 9, type: 'extension', function: { arguments: {} } }] }, finish_reason: 'custom' }] }),
35
+ 'data: malformed-json\n\n',
36
+ 'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n',
37
+ ];
38
+ for (const body of bodies) {
39
+ const result = await readProviderExchange(stream(body));
40
+ assert.equal(result.response.body, body);
41
+ assert.equal(result.usage, undefined);
42
+ }
43
+ });
44
+
45
+ test('JSON and HTTP error responses keep native body/status; metering is independent', async () => {
46
+ for (const status of [200, 400, 401, 404, 429, 503]) {
47
+ const body = JSON.stringify({ unknown: 'extension', choices: [], error: { type: 'synthetic_error' }, usage: { total_tokens: 123 } });
48
+ const result = await readProviderExchange(new Response(body, { status }));
49
+ assert.equal(result.response.body, body); assert.equal(result.response.status, status);
50
+ assert.equal(result.usage, undefined);
51
+ }
52
+ const text = '{"choices":[],"usage":{"prompt_tokens":5,"completion_tokens":2,"total_tokens":7}}';
53
+ assert.deepEqual((await readProviderExchange(new Response(text))).usage, { inputTokens: 5, outputTokens: 2 });
54
+ });
55
+
56
+ test('conflicting usage or execution identity cannot fabricate financial evidence', async () => {
57
+ const body = event({ id: 'one', usage: { prompt_tokens: 1, completion_tokens: 2 } })
58
+ + event({ id: 'two', usage: { prompt_tokens: 1, completion_tokens: 2 } });
59
+ const result = await readProviderExchange(stream(body));
60
+ assert.equal(result.response.body, body); assert.equal(result.executionId, null); assert.equal(result.usage, undefined);
61
+ });
62
+
63
+ test('actual transport loss and byte bound remain errors without exposing response content', async () => {
64
+ const broken = new Response(new ReadableStream({ start(c) { c.error(new Error('synthetic transport loss')); } }));
65
+ await assert.rejects(readProviderExchange(broken), /synthetic transport loss/);
66
+ await assert.rejects(readProviderExchange(new Response('x'.repeat(4 * 1024 * 1024 + 1))), { code: 'USAGE_PROVIDER_RESPONSE_TOO_LARGE' });
67
+ const signal = AbortSignal.abort();
68
+ await assert.rejects(readProviderExchange(stream(event({ choices: [] })), undefined, signal));
69
+ });
70
+
71
+ test('large legitimate context and model options are preserved, exceeding the service limit reports exact counts', () => {
72
+ const input = normalizeModelRequest({ ...request, messages: [{ role: 'user', content: 'x'.repeat(300000) }],
73
+ provider_options: { top_p: 0.5, response_format: { type: 'json_object' }, max_tokens: 1000 } });
74
+ const body = providerBody(input, config, true);
75
+ assert.equal(body.stream, true); assert.equal(body.top_p, 0.5); assert.equal(body.max_tokens, 1000);
76
+ assert.deepEqual(body.messages, input.messages);
77
+ assert.throws(() => providerBody(input, { ...config, maxInputBytes: 262144 }, true), (error: any) => {
78
+ assert.equal(error.code, 'USAGE_INPUT_LIMIT');
79
+ assert.equal(error.details.input_limit.actual, Buffer.byteLength(JSON.stringify(body)));
80
+ assert.equal(error.details.input_limit.allowed, 262144); assert.equal(error.details.input_limit.message_count, 1); return true;
81
+ });
82
+ for (const provider_options of [{ model: 'other' }, { api_key: 'not-allowed' }, { stream: false }, { messages: [] }])
83
+ assert.throws(() => normalizeModelRequest({ ...request, provider_options }));
84
+ assert.throws(() => providerBody({ ...request, provider_options: { max_tokens: 9000 } }, config), { code: 'USAGE_OUTPUT_LIMIT' });
85
+ });
@@ -0,0 +1,77 @@
1
+ import { UsageError } from './errors';
2
+ import { object, verifiedUsage, type JsonObject, type ProviderResult } from './provider';
3
+
4
+ const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
5
+ export type ProviderEnvelope = {
6
+ schema: 'bailing.provider-response.v1'; format: 'sse' | 'json'; status: number;
7
+ content_type: 'text/event-stream' | 'application/json'; body: string;
8
+ };
9
+
10
+ /** A passive meter. Parsing failures never alter or suppress provider output. */
11
+ class ProviderMeter {
12
+ private buffer = '';
13
+ private data: string[] = [];
14
+ private id: string | null = null;
15
+ private changedId = false;
16
+ private usage?: ProviderResult['usage'];
17
+ private rawUsage?: JsonObject;
18
+ constructor(private readonly sse: boolean) {}
19
+ private observe(text: string) {
20
+ let value: unknown;
21
+ try { value = JSON.parse(text); } catch { return; }
22
+ if (!object(value)) return;
23
+ if (typeof value.id === 'string' && value.id.length > 0 && value.id.length <= 256) {
24
+ if (this.id !== null && this.id !== value.id) this.changedId = true;
25
+ this.id ??= value.id;
26
+ }
27
+ if (value.usage != null) {
28
+ this.usage = verifiedUsage(value.usage);
29
+ this.rawUsage = this.usage && object(value.usage) ? value.usage : undefined;
30
+ }
31
+ }
32
+ push(text: string) {
33
+ this.buffer += text;
34
+ if (!this.sse) return;
35
+ // SSE permits CRLF, LF and CR. Leave a trailing CR until the next chunk.
36
+ let match: RegExpExecArray | null;
37
+ while ((match = /\r\n|\n|\r(?!$)/.exec(this.buffer))) {
38
+ const line = this.buffer.slice(0, match.index);
39
+ this.buffer = this.buffer.slice(match.index + match[0].length);
40
+ if (!line) { this.observe(this.data.join('\n')); this.data = []; }
41
+ else if (line.startsWith('data:')) this.data.push(line.slice(5).replace(/^ /, ''));
42
+ }
43
+ }
44
+ finish(): Omit<ProviderResult, 'response'> {
45
+ if (!this.sse) this.observe(this.buffer);
46
+ // Conflicting supplier identities cannot be used for financial evidence.
47
+ // The untouched body still goes to the local adapter.
48
+ return this.changedId ? { executionId: null } : { executionId: this.id,
49
+ ...(this.usage ? { usage: this.usage, rawUsage: this.rawUsage } : {}) };
50
+ }
51
+ }
52
+
53
+ /** Forward the provider body without interpreting choices, tools or finish reasons. */
54
+ export async function readProviderExchange(response: Response, onProvider?: (packet: JsonObject) => Promise<void>, signal?: AbortSignal): Promise<ProviderResult> {
55
+ const sse = (response.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream');
56
+ const header: Omit<ProviderEnvelope, 'body'> = { schema: 'bailing.provider-response.v1',
57
+ format: sse ? 'sse' : 'json', status: response.status, content_type: sse ? 'text/event-stream' : 'application/json' };
58
+ const meter = new ProviderMeter(sse), decoder = new TextDecoder();
59
+ let body = '', bytes = 0;
60
+ const reader = response.body?.getReader();
61
+ try {
62
+ if (reader) for (;;) {
63
+ signal?.throwIfAborted();
64
+ const next = await reader.read();
65
+ const text = next.done ? decoder.decode() : decoder.decode(next.value, { stream: true });
66
+ if (!next.done) bytes += next.value.byteLength;
67
+ if (bytes > MAX_RESPONSE_BYTES) throw new UsageError('USAGE_PROVIDER_RESPONSE_TOO_LARGE', 'The provider response exceeded the transport byte limit.', 502);
68
+ body += text;
69
+ // Delivery runs before metering, which only observes the same text locally.
70
+ if (text) await onProvider?.({ ...header, data: text });
71
+ meter.push(text);
72
+ if (next.done) break;
73
+ }
74
+ signal?.throwIfAborted();
75
+ return { response: { ...header, body }, ...meter.finish() };
76
+ } finally { await reader?.cancel().catch(() => {}); }
77
+ }