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,207 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createUsageTestHarness } from './test-harness';
5
+
6
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
7
+ const admin = 'synthetic-admin';
8
+ async function fixture(quota = 1_000_000, mode = 'credits') {
9
+ const h = await createUsageTestHarness();
10
+ const user = await h.seedUser({ grant: false });
11
+ const planId = randomUUID();
12
+ const config = { mode, serviceIds: [h.service.id], priceUsd: quota, multiplier: 1, ...(mode === 'periodic' ? { periodUnit: 'week', periodAllowanceUsd: quota } : {}),
13
+ duration: { unit: 'month', count: 1 } };
14
+ const plan = await h.request('/admin/api/usage/billing/plans', admin, 'POST', { id: planId, label: 'Synthetic USD plan', expected_revision: 0, config });
15
+ assert.equal(plan.status, 200, JSON.stringify(plan.body));
16
+ const grant = await h.request(`/admin/api/usage/billing/accounts/${user.accountId}/grant`, admin, 'POST', { request_key: planId, plan_id: planId, expected_revision: 0 });
17
+ assert.equal(grant.status, 200, JSON.stringify(grant.body));
18
+ const input = (id = randomUUID()) => ({ operation_id: id, messages: [{ role: 'user', content: 'Synthetic product query' }] });
19
+ return { ...h, user, planId, config, input };
20
+ }
21
+
22
+ test('Model HTTP: 300 steps without fee turns; no provider counting; one actual usage ledger', { skip: !enabled }, async () => {
23
+ const h = await fixture();
24
+ try {
25
+ const caps = await h.request('/usage/v1/capabilities', h.user.token);
26
+ assert.equal(caps.body.model_gateway.turn_required, false);
27
+ for (let i = 0; i < 300; i++) {
28
+ const result = await h.request('/usage/v1/model/requests', h.user.token, 'POST', h.input());
29
+ assert.equal(result.status, 200, JSON.stringify(result.body));
30
+ assert.equal(result.body.result_state, 'complete'); assert.equal(result.body.billing_state, 'pending');
31
+ await h.tokens.drainSettlements();
32
+ const saved = await h.request(`/usage/v1/model/requests/${result.body.operation_id}`, h.user.token);
33
+ assert.equal(saved.body.billed_usd, 25);
34
+ }
35
+ assert.equal(h.state.calls, 300); assert.equal(h.state.counts, 0);
36
+ const [tables] = await h.pool.query<any[]>("SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE()");
37
+ assert.equal(tables.length, 14); assert(!tables.some(row => /_(turns|entitlements|operations|ledger|plans)$/.test(row.TABLE_NAME ?? row.table_name) && !String(row.TABLE_NAME ?? row.table_name).includes('_billing_')));
38
+ const summary = await h.request('/usage/v1/model/summary', h.user.token);
39
+ assert.equal(summary.body.consumedUsd, 7500); assert.equal(summary.body.availableUsd, 992500);
40
+ const legacy = await h.request('/usage/v1/turns', h.user.token, 'POST', { conversation_id: 'audit', service_id: h.service.id, request_key: randomUUID() });
41
+ assert.equal(legacy.status, 404);
42
+ assert.equal(caps.body.streaming, true); assert.equal(caps.body.orchestration, 'host');
43
+ assert.equal(caps.body.presets, undefined); assert.equal(caps.body.token_gateway, undefined);
44
+ for (const path of ['/usage/v1/summary','/usage/v1/ledger','/usage/v1/model','/usage/v1/model-operations','/usage/v1/external/plans','/admin/api/usage/plans']) {
45
+ assert.equal((await h.request(path, path.startsWith('/admin') ? admin : h.user.token)).status, 404, path);
46
+ }
47
+ } finally { await h.close(); }
48
+ });
49
+
50
+ test('Model HTTP: soft final overage, duplicate ACK replay and depleted rejection', { skip: !enabled }, async () => {
51
+ const h = await fixture(20);
52
+ try {
53
+ const input = h.input();
54
+ const result = await h.request('/usage/v1/model/requests', h.user.token, 'POST', input);
55
+ assert.equal(result.status, 200); assert.equal(result.body.result_state, 'complete');
56
+ await h.tokens.drainSettlements();
57
+ const saved = await h.request(`/usage/v1/model/requests/${input.operation_id}`, h.user.token);
58
+ assert.equal(saved.body.overage_usd, 5);
59
+ const repeat = await h.request('/usage/v1/model/requests', h.user.token, 'POST', input);
60
+ assert.equal(repeat.body.operation_id, input.operation_id); assert.equal(h.state.calls, 1);
61
+ const conflict = await h.request('/usage/v1/model/requests', h.user.token, 'POST', { ...input, messages: [{ role: 'user', content: 'different' }] });
62
+ assert.equal(conflict.body.error, 'USAGE_IDEMPOTENCY_CONFLICT');
63
+ const rejected = await h.request('/usage/v1/model/requests', h.user.token, 'POST', h.input());
64
+ assert.equal(rejected.body.error, 'ALLOWANCE_INSUFFICIENT'); assert.equal(h.state.calls, 1);
65
+ const summary = await h.request('/usage/v1/model/summary', h.user.token);
66
+ assert.equal(summary.body.availableUsd, 0); assert.equal(summary.body.consumedUsd, 25);
67
+ } finally { await h.close(); }
68
+ });
69
+
70
+ test('Model HTTP: complete result without usage is deliverable, later requests remain possible', { skip: !enabled }, async () => {
71
+ const h = await fixture();
72
+ try {
73
+ h.state.mode = 'missing_usage'; const input = h.input();
74
+ const result = await h.request('/usage/v1/model/requests', h.user.token, 'POST', input);
75
+ assert.equal(result.status, 200); assert.equal(result.body.result_state, 'complete'); assert.equal(result.body.billing_state, 'pending');
76
+ assert(JSON.parse(result.body.response.body)?.choices?.[0]);
77
+ h.state.mode = 'ok'; const next = await h.request('/usage/v1/model/requests', h.user.token, 'POST', h.input());
78
+ assert.equal(next.body.result_state, 'complete'); assert.equal(h.state.calls, 2);
79
+ await h.tokens.drainSettlements();
80
+ const recovered = await h.request(`/usage/v1/model/requests/${input.operation_id}`, h.user.token);
81
+ assert.equal(recovered.body.result_state, 'complete'); assert.equal(h.state.calls, 2);
82
+ } finally { await h.close(); }
83
+ });
84
+
85
+ test('Model HTTP: streaming previews, cancellation and late results cannot replay', { skip: !enabled }, async () => {
86
+ const h = await fixture();
87
+ try {
88
+ h.state.mode = 'stream'; const input = h.input();
89
+ const response = await fetch(`${h.baseUrl}/usage/v1/model/requests/stream`, { method: 'POST', headers: { authorization: `Bearer ${h.user.token}`, 'content-type':'application/json' }, body: JSON.stringify(input) });
90
+ assert.equal(response.status, 200); const reader = response.body!.getReader();
91
+ const first = await reader.read(); assert(new TextDecoder().decode(first.value).includes('bailing.model-stream.v1'));
92
+ while (!h.state.release) await new Promise(resolve => setTimeout(resolve, 5));
93
+ const cancel = await h.request(`/usage/v1/model/requests/${input.operation_id}/cancel`, h.user.token, 'POST', {});
94
+ assert.equal(cancel.status, 200); h.state.release();
95
+ let rest = ''; for (;;) { const part = await reader.read(); if (part.done) break; rest += new TextDecoder().decode(part.value); }
96
+ await h.tokens.drainSettlements();
97
+ const recovered = await h.request(`/usage/v1/model/requests/${input.operation_id}`, h.user.token);
98
+ assert.equal(recovered.body.result_state, 'cancelled'); assert.equal(recovered.body.billing_state, 'settled');
99
+ assert.equal(h.state.calls, 1); assert(!recovered.body.response);
100
+ } finally { await h.close(); }
101
+ });
102
+
103
+ test('Model HTTP: original gateway credential follows plan models and labels with one shared allowance', { skip: !enabled }, async () => {
104
+ const h = await fixture();
105
+ try {
106
+ const second = await h.repository.putService({ id: 'second-model', label: 'Synthetic second', expectedRevision: 0, config: { ...h.service.config, model: 'synthetic-second' } });
107
+ const exchange = await h.request('/usage/v1/sessions/exchange', h.issuerToken, 'POST', { request_key: randomUUID(), tenant: 'synthetic', subject: h.user.subject, service_id: h.service.id, model_access: 'token_gateway' });
108
+ assert.equal(exchange.status, 200); const token = exchange.body.credential;
109
+ const before = (await h.request('/usage/v1/model/summary', token)).body;
110
+ const update = await h.request('/admin/api/usage/billing/plans', admin, 'POST', { id: h.planId, label: 'Synthetic USD plan', expected_revision: 1, config: { ...h.config, serviceIds: [h.service.id, second.id] } });
111
+ assert.equal(update.status, 200, JSON.stringify(update.body));
112
+ const current = (await h.request(`/admin/api/usage/billing/accounts/${h.user.accountId}/summary`, admin)).body;
113
+ assert.deepEqual(current.grant, before.grant);
114
+ assert.equal(current.availableUsd, before.availableUsd);
115
+ const denied = await h.request('/usage/v1/model/requests', h.user.token, 'POST', { ...h.input(), service_id: second.id });
116
+ assert.equal(denied.status, 403); assert.equal(h.state.calls, 0);
117
+ const models = await h.request('/usage/v1/model/models', token); assert.equal(models.body.items.length, 2);
118
+ assert.equal(models.body.selection, 'plan'); assert.equal(models.body.plan_id, h.planId);
119
+ assert.equal(models.body.items.find((m: any) => m.service_id === second.id).label, 'Synthetic second');
120
+ for (const service_id of [h.service.id, second.id]) {
121
+ const result = await h.request('/usage/v1/model/requests', token, 'POST', { ...h.input(), service_id });
122
+ assert.equal(result.status, 200, JSON.stringify(result.body)); assert.equal(result.body.service_id, service_id);
123
+ }
124
+ await h.tokens.drainSettlements();
125
+ const summary = await h.request('/usage/v1/model/summary', token); assert.equal(summary.body.consumedUsd, 50);
126
+ assert.equal(summary.body.grant.id, before.grant.id);
127
+ assert.equal(Object.hasOwn(summary.body.grant.config, 'serviceIds'), false);
128
+ const removed = await h.request('/admin/api/usage/billing/plans', admin, 'POST', { id: h.planId, label: 'Synthetic USD plan', expected_revision: 2, config: {...h.config, serviceIds:[second.id]} });
129
+ assert.equal(removed.status, 200);
130
+ const replaced = (await h.request('/usage/v1/model/models', token)).body;
131
+ assert.equal(replaced.default_service_id, second.id); assert.equal(replaced.items.length, 1);
132
+ const stale = await h.request('/usage/v1/model/requests', token, 'POST', {...h.input(), service_id:h.service.id});
133
+ assert.equal(stale.status, 403); assert.equal(stale.body.feedback.next_action, 'select_model');
134
+ assert.equal(h.state.calls, 2);
135
+ const empty = await h.request('/admin/api/usage/billing/plans', admin, 'POST', { id: h.planId, label: 'Synthetic USD plan', expected_revision: 3, config: {...h.config, serviceIds:[]} });
136
+ assert.equal(empty.status, 200);
137
+ const emptyModels = (await h.request('/usage/v1/model/models', token)).body;
138
+ assert.deepEqual(emptyModels.items, []); assert.equal(emptyModels.default_service_id, null);
139
+ const externalSummary = await h.request(`/usage/v1/external/billing/accounts/${h.user.accountId}/summary`, h.issuerToken);
140
+ assert.equal(externalSummary.status, 200); assert.equal(externalSummary.body.consumedUsd, 50);
141
+ await h.identity.revokeExternalUser(await h.identity.authenticateIssuer(h.issuerToken, 'identity:revoke'), { tenant: 'synthetic', subject: h.user.subject });
142
+ const revoked = await h.request('/usage/v1/model/requests', token, 'POST', h.input()); assert.equal(revoked.status, 401); assert.equal(h.state.calls, 2);
143
+ } finally { await h.close(); }
144
+ });
145
+
146
+
147
+ test('Token external API: account ownership, source separation and admin write permission', { skip: !enabled }, async () => {
148
+ const h = await fixture();
149
+ try {
150
+ const other = await h.seedUser({ grant: false });
151
+ const body = { request_key: randomUUID(), plan_id: h.planId, expected_revision: 0 };
152
+ const opened = await h.request(`/usage/v1/external/billing/accounts/${other.accountId}/grant`, h.issuerToken, 'POST', body);
153
+ assert.equal(opened.status, 200, JSON.stringify(opened.body));
154
+ const repeated = await h.request(`/usage/v1/external/billing/accounts/${other.accountId}/grant`, h.issuerToken, 'POST', body);
155
+ assert.equal(repeated.body.id, opened.body.id);
156
+ const sourceConflict = await h.request(`/admin/api/usage/billing/accounts/${other.accountId}/grant`, admin, 'POST', { ...body, request_key: randomUUID(), expected_revision: 1 });
157
+ assert.equal(sourceConflict.body.error, 'USAGE_SOURCE_CONFLICT');
158
+ const outsider = await h.identity.createIssuer({ id: 'other-product', label: 'Other synthetic product', permissions: ['usage:read','entitlements:write','allowance:grant'], service_ids: [h.service.id] });
159
+ const denied = await h.request(`/usage/v1/external/billing/accounts/${other.accountId}/summary`, outsider.credential!);
160
+ assert.equal(denied.status, 403); assert.equal(denied.body.error, 'USAGE_ACCOUNT_FORBIDDEN');
161
+ const readonly = await h.request('/admin/api/usage/billing/plans', 'synthetic-auditor', 'POST', { id: randomUUID(), label: 'Cannot write', expected_revision: 0, config: h.config });
162
+ assert.equal(readonly.status, 403); assert.equal(h.state.calls, 0);
163
+ } finally { await h.close(); }
164
+ });
165
+
166
+ test('native provider delivery never waits for settlement; recovery and retries bill once without dispatch', { skip: !enabled }, async () => {
167
+ const h = await fixture();
168
+ // Hold only the financial step, after durable provider evidence; no shared database is used.
169
+ const internal = h.tokens as any, settle = internal.settleRecorded.bind(h.tokens);
170
+ let release!: () => void, entered = false;
171
+ const gate = new Promise<void>(resolve => { release = resolve; });
172
+ internal.settleRecorded = async (record: unknown) => { entered = true; await gate; return settle(record); };
173
+ try {
174
+ const input = h.input();
175
+ const response = await h.request('/usage/v1/model/requests', h.user.token, 'POST', input);
176
+ assert.equal(response.body.result_state, 'complete'); assert.equal(response.body.billing_state, 'pending');
177
+ assert.equal(response.body.next_action, 'none');
178
+ assert.equal(response.body.response.schema, 'bailing.provider-response.v1');
179
+ while (!entered) await new Promise(resolve => setTimeout(resolve, 2));
180
+ const recovered = await h.request(`/usage/v1/model/requests/${input.operation_id}`, h.user.token);
181
+ assert.deepEqual(recovered.body.response, response.body.response); assert.equal(recovered.body.billing_state, 'pending');
182
+ const duplicate = await h.request('/usage/v1/model/requests', h.user.token, 'POST', input);
183
+ assert.deepEqual(duplicate.body.response, response.body.response); assert.equal(h.state.calls, 1);
184
+ release(); await h.tokens.drainSettlements();
185
+ await h.tokens.reconcilePendingUsage(); await h.tokens.reconcilePendingUsage();
186
+ const summary = await h.request('/usage/v1/model/summary', h.user.token);
187
+ assert.equal(summary.body.consumedUsd, 25); assert.equal(h.state.calls, 1);
188
+ } finally { release(); internal.settleRecorded = settle; await h.close(); }
189
+ });
190
+
191
+ test('provider error, nullable tools and semantic truncation reach local adapter as original bodies', { skip: !enabled }, async () => {
192
+ const h = await fixture();
193
+ try {
194
+ for (const mode of ['error', 'incomplete', 'stream_tools_nullable'] as const) {
195
+ h.state.mode = mode;
196
+ const response = await fetch(`${h.baseUrl}/usage/v1/model/requests/stream`, { method: 'POST',
197
+ headers: { authorization: `Bearer ${h.user.token}`, 'content-type': 'application/json' }, body: JSON.stringify(h.input()) });
198
+ const events = (await response.text()).split('\n').filter(line => line.startsWith('data: ')).map(line => JSON.parse(line.slice(6)));
199
+ const original = events.filter(event => event.type === 'provider').map(event => event.provider.data).join('');
200
+ const result = events.find(event => event.type === 'operation')!.operation;
201
+ assert.equal(result.result_state, 'complete'); assert.equal(result.response.body, original);
202
+ assert.equal(result.response.status, mode === 'error' ? 503 : 200);
203
+ assert.notEqual(result.resolution, 'USAGE_PROVIDER_RESPONSE_INVALID');
204
+ }
205
+ assert.equal(h.state.calls, 3);
206
+ } finally { await h.close(); }
207
+ });
@@ -0,0 +1,229 @@
1
+ import { ProviderFailure } from './provider-failure';
2
+ import { isModelTool, modelToolDescriptor } from './model-tools';
3
+ import { serviceAvailability } from './service-availability';
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import { createHash } from 'node:crypto';
6
+ import { readBody, send } from '../../app/http';
7
+ import { resolveLlmCredential } from '../../core/runtime/credential-resolver';
8
+ import type { AppConfig } from '../../core/config/config';
9
+ import type { CredentialStoreLike } from '../../core/runtime/credential-resolver';
10
+ import type { UsageService } from './contracts';
11
+ import { UsageError, usageAssert } from './errors';
12
+ import { authenticateUsageRequest, getUsageIdentity, usageFields, usageString, type UsageSessionContext } from './identity';
13
+ import { usageHttpError } from './http';
14
+ import { canonicalJson, executeProvider, normalizeModelRequest, providerBody, type UsageModelRequest } from './provider';
15
+ import { UsageStreamWriter } from './stream-http';
16
+ import { getBillingRepository } from './billing-repository';
17
+ import type { UsageRepository } from './repository';
18
+ import { referencePricing } from './pricing';
19
+ import { executeModelTool, modelToolBody, modelToolEndpoint } from './model-tool-provider';
20
+
21
+ export interface UsageGatewayDeps {
22
+ usage: UsageRepository | null;
23
+ cfg: Pick<AppConfig, 'llmCredentials'>;
24
+ credentials?: CredentialStoreLike | null;
25
+ isPaused?: () => boolean;
26
+ fetcher?: typeof fetch;
27
+ }
28
+
29
+ const responseCleanup = new WeakMap<UsageRepository, number>();
30
+ function scheduleResponseCleanup(repository: UsageRepository): void {
31
+ const now = Date.now();
32
+ if (now - (responseCleanup.get(repository) ?? 0) < 60_000) return;
33
+ responseCleanup.set(repository, now);
34
+ // Bounded maintenance is independent of admission and model delivery. A failed
35
+ // cleanup is retried on later traffic; expired bodies are never returned meanwhile.
36
+ const tokens = getBillingRepository(repository);
37
+ void Promise.allSettled([tokens.cleanupExpiredResponses(now), tokens.reconcilePendingUsage()]);
38
+ }
39
+
40
+ export const MODEL_GATEWAY_CAPABILITIES = {
41
+ schema: 'bailing.model-gateway.v1', supported: true, orchestration: 'host', streaming: true, provider_response: 'bailing.provider-response.v1', settlement: 'asynchronous',
42
+ model_tools: { schema: 'bailing.model-tools.v1', directory: true, execution: true, tools_path: '/usage/v1/model/tools' },
43
+ requests_path: '/usage/v1/model/requests', models_path: '/usage/v1/model/models',
44
+ summary_path: '/usage/v1/model/summary', billing_unit: 'USD', turn_required: false,
45
+ } as const;
46
+
47
+ export interface ModelInput {
48
+ operation_id: string; service_id?: string; conversation_id?: string; turn_id?: string;
49
+ messages: Record<string, unknown>[]; tools?: Record<string, unknown>[];
50
+ tool_choice?: unknown; temperature?: number; provider_options?: Record<string, unknown>;
51
+ }
52
+ export function normalizeModelGatewayRequest(value: unknown): ModelInput {
53
+ const body = usageFields(value, ['operation_id','service_id','conversation_id','turn_id','messages','tools','tool_choice','temperature','provider_options'], ['operation_id','messages']);
54
+ const operation_id = usageString(body.operation_id, 'operation_id', 191);
55
+ for (const key of ['service_id','conversation_id','turn_id'] as const) if (body[key] !== undefined) usageString(body[key], key, 191);
56
+ const { service_id, conversation_id, turn_id, ...content } = body;
57
+ normalizeModelRequest(content);
58
+ return { ...body, operation_id } as unknown as ModelInput;
59
+ }
60
+ export interface ModelToolInput { operation_id:string; service_id:string; arguments:Record<string,unknown>; conversation_id?:string;turn_id?:string }
61
+ export function normalizeModelToolRequest(value:unknown):ModelToolInput {
62
+ const b=usageFields(value,['operation_id','service_id','arguments','conversation_id','turn_id'],['operation_id','service_id','arguments']);
63
+ for(const k of ['operation_id','service_id','conversation_id','turn_id']) if(b[k]!==undefined) usageString(b[k],k,191);
64
+ usageAssert(b.arguments && typeof b.arguments==='object' && !Array.isArray(b.arguments),'USAGE_INVALID_INPUT','工具参数无效。',400);
65
+ return b as unknown as ModelToolInput;
66
+ }
67
+ function modelPayload(input: ModelInput): UsageModelRequest {
68
+ const { service_id: _service, conversation_id: _conversation, turn_id: _turn, ...content } = input;
69
+ return content;
70
+ }
71
+ /** Model membership comes from the current plan; a single-service credential remains restricted. */
72
+ export function modelAllowedServices(actor: UsageSessionContext, serviceIds: string[]): string[] {
73
+ return actor.modelAccess === 'token_gateway' ? serviceIds : serviceIds.filter(id => id === actor.serviceId);
74
+ }
75
+ export function modelDescriptor(service: UsageService, multiplier = 1) {
76
+ return { schema: 'bailing.usage-model.v1', service_id: service.id, service_revision: service.revision,
77
+ label: service.label, model: service.config.model, state: service.state, orchestration: 'host', streaming: true,
78
+ billing_rate: { multiplier },
79
+ input_formats: ['text','image_url'], model_modalities: service.config.inputModalities ?? null,
80
+ context_window_tokens: service.config.contextWindowTokens ?? null, max_input_bytes: service.config.maxInputBytes,
81
+ input_limit_scope: 'serialized_provider_request', max_messages: 1024, max_tools: 128,
82
+ max_output_tokens: service.config.maxOutputTokens, timeout_ms: service.config.timeoutMs,
83
+ provider_options: ['max_tokens','max_completion_tokens','top_p','stop','seed','presence_penalty','frequency_penalty','parallel_tool_calls','response_format','reasoning_effort','enable_thinking','thinking','verbosity'] };
84
+ }
85
+
86
+ /** One durable request, one provider dispatch; accounting never drives the local agent loop. */
87
+ export async function runModelRequest(deps: UsageGatewayDeps, actor: UsageSessionContext, input: ModelInput | ModelToolInput, stream?: UsageStreamWriter) {
88
+ usageAssert(deps.usage, 'USAGE_UNSUPPORTED', '模型网关不可用。', 503);
89
+ const repository = deps.usage, tokens = getBillingRepository(repository);
90
+ const toolRequest = 'arguments' in input;
91
+ const serviceId = input.service_id ?? actor.serviceId;
92
+ const requestHash = createHash('sha256').update(canonicalJson({ ...input, service_id: serviceId })).digest('hex');
93
+ const previous = await tokens.findRequest(actor, input.operation_id);
94
+ if (previous) {
95
+ usageAssert(previous.requestHash === requestHash, 'USAGE_IDEMPOTENCY_CONFLICT', '原请求标识已关联其他内容。');
96
+ return tokens.view(previous);
97
+ }
98
+ usageAssert(!deps.isPaused?.(), 'USAGE_SERVICE_PAUSED', '模型服务维护中;原请求结果仍可查询。', 503);
99
+ const current = await tokens.summary(actor.accountId);
100
+ usageAssert(current.grant, 'SERVICE_NOT_ENTITLED', '尚未开通套餐。', 403);
101
+ if (!modelAllowedServices(actor, current.plan?.serviceIds ?? []).includes(serviceId))
102
+ throw new UsageError('SERVICE_NOT_ENTITLED', '当前套餐已不包含所选模型,请刷新模型列表并重新选择。原请求请按原标识核对。', 403, { next_action: 'select_model' });
103
+ const service = await repository.getService(serviceId);
104
+ usageAssert(service?.state === 'active', 'USAGE_SERVICE_UNAVAILABLE', '该模型服务暂不可用。', 503);
105
+ usageAssert(isModelTool(service) === toolRequest, 'USAGE_SERVICE_PURPOSE_MISMATCH', '模型工具不能作为对话模型调用,请刷新模型目录。', 400);
106
+ const credential = await resolveLlmCredential(service.config.credential, deps.cfg, deps.credentials);
107
+ usageAssert(credential, 'USAGE_SERVICE_UNAVAILABLE', '模型连接尚未就绪。', 503);
108
+ const body = toolRequest ? modelToolBody(service.config, input.arguments) : providerBody(modelPayload(input), service.config, Boolean(stream));
109
+ if (toolRequest) modelToolEndpoint(credential.credential, service.config, body);
110
+ const priceSnapshot = await referencePricing(repository).snapshot(service.config.pricing);
111
+ let request = await tokens.admit({ actor, operationId: input.operation_id, serviceId,
112
+ conversationId: input.conversation_id ?? null, turnId: input.turn_id ?? null,
113
+ requestHash, priceSnapshot, expectedServiceRevision: service.revision, serviceConfig: service.config, model: service.config.model });
114
+ if (!request.created) return tokens.view(request);
115
+ if (deps.isPaused?.()) {
116
+ await tokens.cancel(actor, input.operation_id);
117
+ throw new UsageError('USAGE_SERVICE_PAUSED', '模型服务维护中。', 503);
118
+ }
119
+ try { request = await tokens.commitDispatch(request.id, actor); }
120
+ catch (error) {
121
+ // Lost commit ACK is never a permit to send a second provider request.
122
+ const saved = await tokens.findRequest(actor, input.operation_id).catch(() => null);
123
+ if (saved && saved.state !== 'admitted') return tokens.view(saved);
124
+ if (saved) await tokens.cancel(actor, input.operation_id);
125
+ throw error;
126
+ }
127
+ usageAssert(request.fence && request.state === 'dispatch_committed', 'USAGE_PENDING', '请核对原请求。', 503);
128
+ const complete = async () => {
129
+ try {
130
+ await stream?.emit('started');
131
+ const result = toolRequest ? await executeModelTool(credential.credential, request.serviceConfig, body, deps.fetcher) : await executeProvider(credential.credential, request.serviceConfig, body, deps.fetcher,
132
+ stream ? packet => stream.emit('provider', { provider: packet }) : undefined);
133
+ request = await tokens.recordCompletion(request.id, request.fence!, { response: result.response,
134
+ ...(result.usage ? { usage: result.usage } : {}), ...((result.rawUsage || result.usage) ? { rawUsage: { ...result.rawUsage, requestCount: 1, ...(!toolRequest ? { webSearchCount: 0 } : {}) } } : {}),
135
+ ...(result.executionId ? { executionId: result.executionId } : {}) });
136
+ } catch (error) {
137
+ const reason = error instanceof UsageError ? error.code : 'USAGE_TRANSPORT_UNCERTAIN';
138
+ try { request = error instanceof ProviderFailure
139
+ ? await tokens.recordProviderFailure(request.id, request.fence!, error)
140
+ : await tokens.markUnknown(request.id, request.fence!, reason); }
141
+ catch { throw new UsageError('USAGE_PENDING', '原请求待核对,请保留原标识,不要重新执行。', 503); }
142
+ }
143
+ return tokens.view(request);
144
+ };
145
+ if (toolRequest) {
146
+ // Return the durable dispatch record promptly. Disconnecting never regenerates an image.
147
+ void complete().then(result=>tokens.scheduleSettlement(result.operation_id,actor)).catch(()=>{});
148
+ return tokens.view(request);
149
+ }
150
+ return complete();
151
+ }
152
+
153
+ export async function handleModelGatewayApiFor(deps: UsageGatewayDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
154
+ const path = url.pathname;
155
+ if (!path.startsWith('/usage/v1/model/')) return false;
156
+ let stream: UsageStreamWriter | undefined;
157
+ try {
158
+ usageAssert(deps.usage, 'USAGE_UNSUPPORTED', '模型网关不可用。', 503);
159
+ const repository = deps.usage, tokens = getBillingRepository(repository);
160
+ usageAssert(await tokens.ready(), 'USAGE_UNSUPPORTED', '模型网关尚未就绪,请核对版本与迁移。', 503);
161
+ usageAssert(!url.search, 'USAGE_INVALID_INPUT', '此接口不接受查询参数。', 400);
162
+ const actor = await authenticateUsageRequest(getUsageIdentity(repository), req);
163
+ scheduleResponseCleanup(repository);
164
+ if (path === '/usage/v1/model/summary' && req.method === 'GET') {
165
+ const summary = await tokens.summary(actor.accountId);
166
+ const ids = modelAllowedServices(actor, summary.plan?.serviceIds ?? []);
167
+ const scopedPlan = summary.plan ? { ...summary.plan, serviceIds: ids } : null;
168
+ send(res, 200, { ...summary, plan: scopedPlan, user_id: actor.userId, service_id: actor.serviceId }); return true;
169
+ }
170
+ if (['/usage/v1/model/models','/usage/v1/model/tools'].includes(path) && req.method === 'GET') {
171
+ const summary = await tokens.summary(actor.accountId);
172
+ const active = ['active','depleted'].includes(summary.presentation.state); // Same authoritative DB clock as the allowance summary.
173
+ const ids = active ? modelAllowedServices(actor, summary.plan?.serviceIds ?? []) : [];
174
+ const services = await Promise.all(ids.map(id => repository.getService(id)));
175
+ const toolsDirectory = path.endsWith('/tools');
176
+ const selected = services.filter((service): service is UsageService => Boolean(service) && isModelTool(service!) === toolsDirectory);
177
+ const checked = await Promise.all(selected.map(async service => ({service,availability:await serviceAvailability(repository,service)})));
178
+ const available = checked.filter(item=>item.availability.state === 'ready').map(item=>item.service);
179
+ // Only plan/credential-selected targets are described, never the instance-wide service catalog.
180
+ const unavailable = checked.filter(item=>item.availability.state !== 'ready').map(({service,availability})=>({
181
+ service_id:service.id,service_revision:service.revision,label:service.label,...availability,
182
+ }));
183
+ if (toolsDirectory) {
184
+ send(res, 200, { schema: 'bailing.model-tools.v1', account_id: actor.accountId, user_id: actor.userId,
185
+ plan_id: summary.plan?.id ?? null, plan_revision: summary.plan?.revision ?? null, orchestration: 'host', execution: true,
186
+ unavailable_items: unavailable,
187
+ items: available.map(service => modelToolDescriptor(service, summary.plan?.multiplier)) }); return true;
188
+ }
189
+ send(res, 200, { schema: 'bailing.model-models.v1', account_id: actor.accountId, user_id: actor.userId,
190
+ selection: 'plan', plan_id: summary.plan?.id ?? null, plan_revision: summary.plan?.revision ?? null,
191
+ unavailable_items: unavailable,
192
+ default_service_id: available.some(service => service.id === actor.serviceId) ? actor.serviceId : available[0]?.id ?? null,
193
+ items: available.map(service => modelDescriptor(service, summary.plan?.multiplier)) }); return true;
194
+ }
195
+ if (path === '/usage/v1/model/tools/requests' && req.method === 'POST') {
196
+ const input = normalizeModelToolRequest(await readBody(req,16*1024*1024+4096));
197
+ const result = await runModelRequest(deps,actor,input);
198
+ send(res,result.result_state === 'pending' || result.result_state === 'unknown' ? 202 : 200,result); return true;
199
+ }
200
+ if (['/usage/v1/model/requests','/usage/v1/model/requests/stream'].includes(path) && req.method === 'POST') {
201
+ const input = normalizeModelGatewayRequest(await readBody(req, 16 * 1024 * 1024 + 4096));
202
+ if (path.endsWith('/stream')) stream = new UsageStreamWriter(res, input.operation_id);
203
+ const result = await runModelRequest(deps, actor, input, stream);
204
+ if (stream) { await stream.emit('operation', { operation: result }); stream.end(); }
205
+ else send(res, result.result_state === 'pending' || result.result_state === 'unknown' ? 202 : 200, result);
206
+ // Response is closed before financial aggregation; original durable evidence
207
+ // lets the existing maintenance sweep recover a failed or interrupted settlement.
208
+ tokens.scheduleSettlement(result.operation_id, actor);
209
+ return true;
210
+ }
211
+ const match = path.match(/^\/usage\/v1\/model\/requests\/([^/]+)(\/cancel)?$/);
212
+ if (match) {
213
+ const id = usageString(decodeURIComponent(match[1]!), 'operation_id', 191);
214
+ if (match[2] && req.method === 'POST') {
215
+ usageFields(await readBody(req, 1024), []);
216
+ send(res, 200, tokens.view(await tokens.cancel(actor, id))); return true;
217
+ }
218
+ if (!match[2] && req.method === 'GET') {
219
+ const request = await tokens.findRequest(actor, id);
220
+ usageAssert(request, 'USAGE_OPERATION_NOT_FOUND', '未找到原请求,未发送新的模型调用。', 404);
221
+ send(res, 200, tokens.view(request)); return true;
222
+ }
223
+ }
224
+ throw new UsageError('USAGE_NOT_FOUND', '模型接口不存在。', 404);
225
+ } catch (error) {
226
+ if (stream?.open) stream.end(); else usageHttpError(res, error);
227
+ return true;
228
+ } finally { stream?.stop(); }
229
+ }
@@ -0,0 +1,137 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { createServer } from 'node:http';
5
+ import { once } from 'node:events';
6
+ import type { AddressInfo } from 'node:net';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ import { createUsageTestHarness } from './test-harness';
9
+ import { handleModelGatewayApiFor } from './model-gateway';
10
+ import type { UsageServiceConfig } from './contracts';
11
+
12
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
13
+ async function fixture(options: {response?: () => Response | Promise<Response>} = {}) {
14
+ const h = await createUsageTestHarness();
15
+ const modelId = 'synthetic/image-model', endpointId = 'synthetic-image-provider';
16
+ const pricing = {source:'openrouter' as const,kind:'image' as const,modelId,endpointId};
17
+ const snapshot = {...pricing,currency:'USD',fetchedAt:Date.now(),lines:[
18
+ {billable:'input_image',unit:'image',costUsd:'0.01',variant:'1k'},
19
+ {billable:'output_image',unit:'image',costUsd:'0.2',variant:'1k'},
20
+ ]};
21
+ await h.pool.query('INSERT INTO bz_usage_price_snapshots(cache_key,snapshot_json,fetched_at) VALUES(?,?,?)',[
22
+ createHash('sha256').update(`image:${modelId}`).digest('hex'),JSON.stringify({fetchedAt:Date.now(),items:[{id:endpointId,pricing:snapshot}]}),Date.now(),
23
+ ]);
24
+ const config: UsageServiceConfig = {...h.service.config,purpose:'tool',model:'synthetic-image',pricing,
25
+ tool:{name:'generate_image',capability:'image_generation',description:'Generate a synthetic test image.',outputs:['image'],adapter:'aliyun-image',parameters:[
26
+ {name:'prompt',type:'string',required:true,description:'Synthetic image description'},
27
+ {name:'n',type:'number',required:false,description:'Image count'},
28
+ ]}};
29
+ const image = await h.repository.putService({id:'synthetic-image',label:'Synthetic image tool',expectedRevision:0,config});
30
+ const excluded = await h.repository.putService({id:'unselected-image',label:'Unselected synthetic tool',expectedRevision:0,config});
31
+ const pending = await h.repository.putService({id:'pending-video',label:'Declaration only',expectedRevision:0,config:{...config,pricing:undefined,tool:{...config.tool!,name:'generate_video',capability:'video_generation',outputs:['video'],adapter:'pending'}}});
32
+ const user = await h.identity.exchange(h.issuerToken,{request_key:randomUUID(),tenant:'synthetic',subject:randomUUID(),service_id:h.service.id,model_access:'token_gateway'});
33
+ const plan = await h.tokens.putPlan({id:'image-plan',label:'Synthetic shared USD allowance',expected_revision:0,config:{mode:'periodic',periodAllowanceUsd:100,priceUsd:100,multiplier:1.5,periodUnit:'week',duration:{unit:'month',count:1},serviceIds:[h.service.id,image.id,pending.id]}});
34
+ await h.tokens.grant(user.session.accountId,{request_key:randomUUID(),plan_id:plan.id,expected_revision:0});
35
+ let release!:()=>void;
36
+ const responseGate = new Promise<void>(resolve=>{release=resolve;});
37
+ const calls: Array<{url:string;body:Record<string,unknown>}> = [];
38
+ const fetcher: typeof fetch = async (input, init) => {
39
+ const url = String(input);assert.equal(url,'https://synthetic.invalid/v1/images/generations');
40
+ calls.push({url,body:JSON.parse(String(init?.body))});
41
+ await responseGate;
42
+ if (options.response) return options.response();
43
+ return new Response(JSON.stringify({id:'synthetic-provider-request',data:[{url:'https://synthetic.invalid/generated.png'}],usage:{input_image_count:0,output_image_count:1,output_image_type:'1k',output_width:1024,output_height:1024}}),{status:200,headers:{'content-type':'application/json'}});
44
+ };
45
+ const server = createServer(async(req,res)=>{
46
+ if(!await handleModelGatewayApiFor({usage:h.repository,cfg:{llmCredentials:{synthetic:{base_url:'https://synthetic.invalid/v1',api_key:'REPLACE_ME'}}},fetcher},req,res,new URL(req.url!,'http://localhost'))) {res.writeHead(404);res.end();}
47
+ }).listen(0,'127.0.0.1');await once(server,'listening');
48
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
49
+ async function request(path:string,method='GET',body?:unknown) {
50
+ const response = await fetch(base+path,{method,headers:{authorization:`Bearer ${user.credential}`,'content-type':'application/json'},...(body === undefined?{}:{body:JSON.stringify(body)})});
51
+ return {status:response.status,body:await response.json() as Record<string,any>};
52
+ }
53
+ const input = (serviceId=image.id) => ({operation_id:randomUUID(),service_id:serviceId,conversation_id:'original-conversation',turn_id:'original-turn',arguments:{prompt:'Synthetic test image',n:1}});
54
+ async function settled(operationId:string) {
55
+ for(let i=0;i<300;i++) {
56
+ const r = await request(`/usage/v1/model/requests/${operationId}`);
57
+ assert.equal(r.status,200,JSON.stringify(r.body));
58
+ if(r.body.billing_state==='settled') return r.body;
59
+ await delay(10);
60
+ }
61
+ throw new Error('Synthetic image operation did not settle');
62
+ }
63
+ return {...h,image,excluded,pending,user,calls,input,request,release,settled,
64
+ async close(){release();for(let i=0;i<300;i++){const [rows]=await h.pool.query<any[]>("SELECT COUNT(*) n FROM bz_usage_billing_requests WHERE fence IS NOT NULL AND result_hash IS NULL AND state='dispatch_committed'");if(!Number(rows[0].n))break;await delay(10);}server.close();server.closeAllConnections();await h.close();},
65
+ };
66
+ }
67
+
68
+ test('image HTTP returns pending before provider result; image-count receipt settles shared USD without invented Tokens', {skip:!enabled}, async()=>{
69
+ const h=await fixture();try{
70
+ const input=h.input(), first=await h.request('/usage/v1/model/tools/requests','POST',input);
71
+ assert.equal(first.status,202);assert.equal(first.body.result_state,'pending');assert.equal(first.body.billing_state,'pending');
72
+ assert.equal(h.calls.length,1);assert.equal(h.calls[0]!.body.model,'synthetic-image');
73
+ h.release();const done=await h.settled(input.operation_id);
74
+ assert.equal(done.result_state,'complete');assert.equal(done.usage,null);assert.equal(done.raw_usage.outputImageCount,1);
75
+ assert.equal(done.reference_cost_usd,0.2);assert.equal(done.billed_usd,0.3);assert.equal(done.response.outputs[0].type,'image');
76
+ const summary=await h.tokens.summary(h.user.session.accountId);assert.equal(summary.availableUsd,99.7);assert.equal(summary.presentation.remaining,99.7);
77
+ }finally{await h.close();}
78
+ });
79
+
80
+ test('lost image ACK and repeated original POST/GET reuse one generation and one ledger entry', {skip:!enabled},async()=>{
81
+ const h=await fixture();try{
82
+ const input=h.input();await h.request('/usage/v1/model/tools/requests','POST',input);
83
+ const retry=await h.request('/usage/v1/model/tools/requests','POST',input);assert.equal(retry.status,202);assert.equal(h.calls.length,1);
84
+ h.release();const done=await h.settled(input.operation_id);
85
+ const recovered=await h.request('/usage/v1/model/tools/requests','POST',input);assert.equal(recovered.status,200);assert.deepEqual(recovered.body,done);assert.equal(h.calls.length,1);
86
+ const changed=await h.request('/usage/v1/model/tools/requests','POST',{...input,arguments:{prompt:'Changed'}});assert.equal(changed.status,409);assert.equal(h.calls.length,1);
87
+ const [rows]=await h.pool.query<any[]>('SELECT COUNT(*) n FROM bz_usage_billing_ledger WHERE account_id=?',[h.user.session.accountId]);assert.equal(Number(rows[0].n),1);
88
+ }finally{await h.close();}
89
+ });
90
+
91
+ test('cancelled image keeps late cost evidence but never re-exposes outputs or dispatches another generation', {skip:!enabled},async()=>{
92
+ const h=await fixture();try{
93
+ const input=h.input();await h.request('/usage/v1/model/tools/requests','POST',input);
94
+ const cancelled=await h.request(`/usage/v1/model/requests/${input.operation_id}/cancel`,'POST',{});assert.equal(cancelled.status,200);assert.equal(cancelled.body.result_state,'cancelled');
95
+ h.release();const done=await h.settled(input.operation_id);assert.equal(done.result_state,'cancelled');assert.equal('response' in done,false);assert.equal(done.billed_usd,0.3);
96
+ const retry=await h.request('/usage/v1/model/tools/requests','POST',input);assert.equal(retry.body.result_state,'cancelled');assert.equal('response' in retry.body,false);assert.equal(h.calls.length,1);
97
+ }finally{await h.close();}
98
+ });
99
+
100
+ test('tool and chat directories stay separate; pending or unselected tools never reach provider', {skip:!enabled},async()=>{
101
+ const h=await fixture();try{
102
+ const models=await h.request('/usage/v1/model/models'),tools=await h.request('/usage/v1/model/tools');
103
+ assert.equal(models.status,200);assert.deepEqual(models.body.items.map((i:any)=>i.service_id),[h.service.id],JSON.stringify({models:models.body,summary:await h.tokens.summary(h.user.session.accountId),now:Date.now()}));
104
+ assert.deepEqual(tools.body.items.map((i:any)=>i.service_id),[h.image.id]);
105
+ assert.equal(tools.body.unavailable_items.find((i:any)=>i.service_id===h.pending.id).code,'MODEL_TOOL_ADAPTER_NOT_READY');
106
+ const unselected=await h.request('/usage/v1/model/tools/requests','POST',h.input(h.excluded.id));assert.equal(unselected.status,403);
107
+ const pending=await h.request('/usage/v1/model/tools/requests','POST',h.input(h.pending.id));assert.equal(pending.status,400);assert.equal(pending.body.code,'MODEL_TOOL_ADAPTER_NOT_READY');
108
+ const wrongPurpose=await h.request('/usage/v1/model/requests','POST',{operation_id:randomUUID(),service_id:h.image.id,messages:[{role:'user',content:'Synthetic'}]});assert.equal(wrongPurpose.status,400);
109
+ assert.equal(h.calls.length,0);
110
+ const [rows]=await h.pool.query<any[]>('SELECT COUNT(*) n FROM bz_usage_billing_requests');assert.equal(Number(rows[0].n),0);
111
+ }finally{await h.close();}
112
+ });
113
+
114
+ for(const status of [404,503]) test(`provider HTTP ${status} persists safe outcome; repeated original recovery never regenerates`,{skip:!enabled},async()=>{
115
+ const h=await fixture({response:()=>new Response(JSON.stringify({code:'SyntheticError',message:'DO_NOT_STORE',request_id:'synthetic-original'}),{status})});
116
+ try{
117
+ const input=h.input();await h.request('/usage/v1/model/tools/requests','POST',input);h.release();
118
+ let receipt:any;
119
+ for(let i=0;i<100;i++){receipt=(await h.request(`/usage/v1/model/requests/${input.operation_id}`)).body;if(receipt.result_state!=='pending')break;await delay(10);}
120
+ assert.equal(receipt.result_state,status===404?'failed':'unknown');assert.equal(receipt.billing_state,status===404?'settled':'pending');
121
+ assert.equal(receipt.error.http_status,status);assert.equal(receipt.error.retryable,false);assert.equal(receipt.response,undefined);
122
+ assert.equal(receipt.billed_usd,status===404?0:null);assert.equal(receipt.dispatch,status===404?'rejected':'unknown');
123
+ const replay=await h.request('/usage/v1/model/tools/requests','POST',input);assert.equal(replay.body.result_state,receipt.result_state);assert.equal(h.calls.length,1);
124
+ const [records]=await h.pool.query<any[]>('SELECT result_json FROM bz_usage_billing_requests');assert.equal(JSON.stringify(records).includes('DO_NOT_STORE'),false);
125
+ await h.tokens.reconcilePendingUsage();assert.equal(h.calls.length,1);
126
+ const summary=await h.tokens.summary(h.user.session.accountId);assert.equal(summary.availableUsd,100);
127
+ if(status===404){const cancel=await h.request(`/usage/v1/model/requests/${input.operation_id}/cancel`,'POST',{});assert.equal(cancel.body.result_state,'failed');}
128
+ }finally{await h.close();}
129
+ });
130
+
131
+ test('late rejection after cancellation closes billing without changing cancellation or exposing response',{skip:!enabled},async()=>{
132
+ const h=await fixture({response:()=>new Response('{}',{status:400})});try{
133
+ const input=h.input();await h.request('/usage/v1/model/tools/requests','POST',input);
134
+ await h.request(`/usage/v1/model/requests/${input.operation_id}/cancel`,'POST',{});h.release();
135
+ const done=await h.settled(input.operation_id);assert.equal(done.result_state,'cancelled');assert.equal(done.billed_usd,0);assert.equal(done.response,undefined);assert.equal(h.calls.length,1);
136
+ }finally{await h.close();}
137
+ });
@@ -0,0 +1,37 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { executeModelTool, modelToolBody } from './model-tool-provider';
4
+ import { ProviderFailure } from './provider-failure';
5
+ import type { UsageServiceConfig } from './contracts';
6
+ const credential={base_url:'https://synthetic.invalid/compatible-mode/v1',api_key:'sk-private-test-key'};
7
+ const config:UsageServiceConfig={credential:'synthetic',model:'synthetic-image',providerScope:'synthetic',maxInputBytes:4096,maxOutputTokens:100,timeoutMs:1000,purpose:'tool',tool:{name:'image',capability:'image_generation',description:'Synthetic',outputs:['image'],adapter:'aliyun-image-native',parameters:[{name:'prompt',type:'string',required:true,description:'Prompt'}]}};
8
+
9
+ test('native image adapter sends exactly one request on the configured origin and parses real usage',async()=>{
10
+ let calls=0;
11
+ const result=await executeModelTool(credential,config,{model:config.model,prompt:'Synthetic',size:'1024x1024',n:1},async(url,init)=>{
12
+ calls++;assert.equal(url,'https://synthetic.invalid/api/v1/services/aigc/multimodal-generation/generation');
13
+ assert.deepEqual(JSON.parse(String(init?.body)),{model:'synthetic-image',input:{messages:[{role:'user',content:[{text:'Synthetic'}]}]},parameters:{size:'1024*1024',n:1}});
14
+ return new Response(JSON.stringify({request_id:'synthetic-request',output:{choices:[{message:{content:[{text:'ignored'},{image:'https://synthetic.invalid/image.png'}]}}]},usage:{input_image_count:0,output_image_count:1,output_image_type:'qima_output_1k'}}));
15
+ });
16
+ assert.equal(calls,1);assert.equal(result.executionId,'synthetic-request');assert.equal(result.rawUsage?.outputImageCount,1);assert.equal(result.rawUsage?.outputVariant,'1k');assert.equal(result.usage,undefined);
17
+ });
18
+ test('definite provider rejection is not unknown, errors are bounded and do not retain raw body or credentials',async()=>{
19
+ for(const status of [400,401,403,404,405,413,415,422,429]){
20
+ let calls=0;
21
+ await assert.rejects(executeModelTool(credential,config,{prompt:'Synthetic'},async()=>{calls++;return new Response(JSON.stringify({request_id:'test-request',error:{code:'InvalidParameter',message:'private prompt '+credential.api_key},secret:credential.api_key}),{status});}),e=>{
22
+ assert.ok(e instanceof ProviderFailure);assert.equal(e.rejected,true);assert.equal(e.diagnostic.http_status,status);assert.equal(e.diagnostic.provider_code,'InvalidParameter');assert.equal(e.diagnostic.provider_request_id,'test-request');assert.equal(JSON.stringify(e).includes(credential.api_key),false);assert.equal(JSON.stringify(e).includes('private prompt'),false);return true;
23
+ });assert.equal(calls,1);
24
+ }
25
+ await assert.rejects(executeModelTool(credential,config,{},async()=>new Response('x'.repeat(17000),{status:404})),(e:any)=>e.rejected===true&&e.diagnostic.http_status===404);
26
+ await assert.rejects(executeModelTool(credential,config,{},async()=>new Response(JSON.stringify({code:credential.api_key,request_id:credential.api_key}),{status:400})),(e:any)=>!e.diagnostic.provider_code&&!e.diagnostic.provider_request_id);
27
+ });
28
+ test('timeouts, server errors and malformed success remain uncertain without retry or protocol fallback',async()=>{
29
+ for(const fetcher of [async()=>{throw Error('connection lost');},async()=>new Response('{}',{status:503}),async()=>new Response('{}',{status:408}),async()=>new Response('bad json')]){
30
+ let calls=0;
31
+ await assert.rejects(executeModelTool(credential,config,{},async()=>{calls++;return fetcher();}),(e:any)=>e instanceof ProviderFailure&&!e.rejected&&e.diagnostic.next_action==='inspect_original');assert.equal(calls,1);
32
+ }
33
+ });
34
+ test('native adapter shares declared parameter validation and rejects model-controlled undeclared input',()=>{
35
+ assert.throws(()=>modelToolBody(config,{prompt:'Synthetic',url:'https://other.invalid'}));
36
+ assert.deepEqual(modelToolBody(config,{prompt:'Synthetic'}),{model:config.model,prompt:'Synthetic'});
37
+ });