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
@@ -0,0 +1,228 @@
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 = (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
+ this.flights.set(key,job); try {return await job;} finally {this.flights.delete(key);}
194
+ }
195
+ async catalog(kind:'chat'|'image', modelId?: string, force=false): Promise<Catalog> {
196
+ if (modelId) validatePricingBinding({source:'openrouter',kind,modelId,endpointId:'lookup'});
197
+ const cached=await this.get(this.key(kind,modelId));
198
+ if (cached && !force) {
199
+ const stale = Date.now()-cached.fetchedAt > TTL;
200
+ if (stale) void this.refresh(kind,modelId).catch(()=>{});
201
+ return {...cached,stale};
202
+ }
203
+ try {return {...await this.refresh(kind,modelId),stale:false};}
204
+ catch(error){if(cached)return {...cached,stale:true};throw error;}
205
+ }
206
+ /** Same cached quote check for the console, discovery and dispatch. No paid call or catalog round-trip. */
207
+ async inspect(binding: PricingBinding | undefined): Promise<{ availability: PriceAvailability; price?: PriceSnapshot }> {
208
+ const unavailable = (code: string, message: string) => ({ availability: {state: 'unavailable' as const, code, message} });
209
+ if (!binding) return unavailable('USAGE_PRICE_NOT_CONFIGURED', '尚未绑定参考模型和价格端点,请配置参考价格。');
210
+ try { validatePricingBinding(binding); }
211
+ catch { return unavailable('USAGE_PRICE_NOT_CONFIGURED', '参考价格绑定无效,请重新配置。'); }
212
+ const cached = await this.get(this.key(binding.kind,binding.modelId));
213
+ const endpoint = cached?.items.find(x=>x.id===binding.endpointId);
214
+ if (!cached) return unavailable('USAGE_PRICE_UNAVAILABLE', '参考价格尚未同步,请在模型服务中同步价格。');
215
+ if (!endpoint) return unavailable('USAGE_PRICE_UNAVAILABLE', '参考端点已不在目录中,请重新选择端点并同步价格。');
216
+ if (endpoint.unavailable) return unavailable('USAGE_PRICE_UNSUPPORTED', '参考端点的计量规则暂不支持,请选择受支持的参考端点。');
217
+ if (!endpoint.pricing) return unavailable('USAGE_PRICE_UNAVAILABLE', '参考端点缺少有效报价,请同步价格或重新配置。');
218
+ if (Date.now()-cached!.fetchedAt > TTL) void this.refresh(binding.kind,binding.modelId).catch(()=>{});
219
+ return {availability:{state:'ready',code:null,message:null},price:structuredClone(endpoint.pricing)};
220
+ }
221
+ async snapshot(binding: PricingBinding | undefined): Promise<PriceSnapshot> {
222
+ const result = await this.inspect(binding);
223
+ usageAssert(result.price, result.availability.code ?? 'USAGE_PRICE_UNAVAILABLE',result.availability.message ?? '参考价格暂不可用。',503);
224
+ return result.price;
225
+ }
226
+ }
227
+ const instances=new WeakMap<UsageRepository,ReferencePricing>();
228
+ 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
+ }
@@ -0,0 +1,67 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createServer } from 'node:http';
4
+ import { once } from 'node:events';
5
+ import type { AddressInfo } from 'node:net';
6
+ import { executeProvider, canonicalJson, normalizeModelRequest, providerBody, verifiedUsage } from './provider';
7
+ import type { UsageServiceConfig } from './contracts';
8
+
9
+ const config: UsageServiceConfig = {
10
+ credential: 'synthetic', model: 'synthetic-text', providerScope: 'test-provider', maxInputBytes: 16384,
11
+ maxOutputTokens: 100, timeoutMs: 1000,
12
+
13
+ };
14
+ const input = { operation_id: 'operation-1', messages: [{ role: 'user', content: 'Show product availability.' }] };
15
+
16
+ test('gateway preserves supported content parts without accepting caller-selected model or credentials', () => {
17
+ for (const field of ['model', 'base_url', 'api_key', 'usage', 'account_id', 'stream', 'max_tokens']) {
18
+ assert.throws(() => normalizeModelRequest({ ...input, [field]: 'untrusted' }), /not supported/);
19
+ }
20
+ const image = [{ role: 'user', content: [{ type: 'image_url', image_url: { url: 'https://example.invalid/image' } }] }];
21
+ assert.deepEqual(normalizeModelRequest({ ...input, messages: image }).messages, image);
22
+ assert.throws(() => normalizeModelRequest({ ...input, messages: [{ role: 'user', content: [{ type: 'image_url', image_url: { url: 'file:///private/image' } }] }] }), /Only text/);
23
+ assert.throws(() => normalizeModelRequest({ ...input, tools: [{ type: 'web_search' }] }), /function/);
24
+ const normalized = normalizeModelRequest(input);
25
+ assert.equal(providerBody(normalized, config).max_tokens, 100);
26
+ assert.throws(() => providerBody(normalized, { ...config, maxInputBytes: 2 }), { code: 'USAGE_INPUT_LIMIT' });
27
+ });
28
+
29
+ test('original operation hash ignores object key order but preserves every message and tool parameter', () => {
30
+ const first = normalizeModelRequest(input);
31
+ const second = normalizeModelRequest({ messages: [{ content: 'Show product availability.', role: 'user' }], operation_id: 'operation-1' });
32
+ assert.equal(canonicalJson(first), canonicalJson(second));
33
+ assert.notEqual(canonicalJson(first), canonicalJson({ ...first, messages: [{ role: 'user', content: 'Update product availability.' }] }));
34
+ });
35
+
36
+ test('usage preserves unknown and does not add cached or reasoning subsets twice', () => {
37
+ assert.equal(verifiedUsage(undefined), undefined);
38
+ assert.equal(verifiedUsage({ total_tokens: 0 }), undefined);
39
+ assert.equal(verifiedUsage({ prompt_tokens: -1, completion_tokens: 2 }), undefined);
40
+ assert.equal(verifiedUsage({ prompt_tokens: 5, completion_tokens: 2, total_tokens: 9 }), undefined);
41
+ assert.deepEqual(verifiedUsage({ prompt_tokens: 5, completion_tokens: 2, total_tokens: 7, prompt_tokens_details: { cached_tokens: 4 }, completion_tokens_details: { reasoning_tokens: 1 } }), { inputTokens: 5, outputTokens: 2 });
42
+ });
43
+
44
+ test('real HTTP provider receives only the service output bound, no automatic retry', async () => {
45
+ let modelCalls = 0; const bodies: Record<string, unknown>[] = [];
46
+ const server = createServer(async (req, res) => {
47
+ const chunks = []; for await (const chunk of req) chunks.push(chunk);
48
+ bodies.push(JSON.parse(Buffer.concat(chunks).toString()));
49
+ res.setHeader('content-type', 'application/json');
50
+ if (req.url === '/v1/count-input') { res.end(JSON.stringify({ input_tokens: 20 })); return; }
51
+ modelCalls++; res.writeHead(503); res.end(JSON.stringify({ message: 'synthetic transport failure' }));
52
+ }).listen(0, '127.0.0.1'); await once(server, 'listening');
53
+ try {
54
+ const credential = { base_url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`, api_key: 'synthetic-test-only' };
55
+ const body = providerBody(normalizeModelRequest(input), config);
56
+ const result = await executeProvider(credential, config, body);
57
+ assert.equal(result.response.status, 503);
58
+ assert.deepEqual(JSON.parse(result.response.body as string), { message: 'synthetic transport failure' });
59
+ assert.equal(result.usage, undefined);
60
+ assert.equal(modelCalls, 1);
61
+ assert.equal(bodies[0]?.max_tokens, 100);
62
+ assert.equal(bodies[0]?.model, 'synthetic-text');
63
+ assert.equal(bodies[0]?.account_id, undefined);
64
+ assert.equal(modelCalls, 1, 'absolute-origin tokenizer paths must not become /v1/v1/count-input');
65
+ assert.equal(modelCalls, 1);
66
+ } finally { server.close(); await once(server, 'close'); }
67
+ });