bailinghub 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +7 -9
- package/README.md +7 -9
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.md +34 -0
- package/docs/AGENT_TASK_CONTROL.en.md +25 -0
- package/docs/AGENT_TASK_CONTROL.md +94 -0
- package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHANGELOG.en.md +22 -1
- package/docs/CHANGELOG.md +22 -1
- package/docs/COMPATIBILITY.en.md +6 -0
- package/docs/CONTRACT.en.md +2 -0
- package/docs/CONTRACT.md +2 -0
- package/docs/GENERATED_ARTIFACTS.en.md +46 -0
- package/docs/GENERATED_ARTIFACTS.md +108 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/INVOCATION_RECEIPTS.md +111 -0
- package/docs/MODEL_BILLING.en.md +123 -0
- package/docs/MODEL_BILLING.md +125 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
- package/docs/README.en.md +7 -0
- package/docs/README.md +7 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
- package/docs/RELEASE_NOTES_NEXT.md +4 -2
- package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
- package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
- package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
- package/docs/TOOL_RATE_LIMITS.md +50 -0
- package/docs/UPGRADE_v0.8.0.en.md +71 -0
- package/docs/UPGRADE_v0.8.0.md +73 -0
- package/docs/UPGRADE_v0.9.0.en.md +54 -0
- package/docs/UPGRADE_v0.9.0.md +54 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +6 -0
- package/package.json +1 -1
- package/schemas/config/route.schema.json +1 -0
- package/schemas/config/tool-provider.schema.json +2 -1
- package/scripts/check-doc-links.mjs +5 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/e2e-console.mjs +32 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +2 -0
- package/scripts/sdk-runtime-test.mjs +6 -0
- package/scripts/verify-billing-install-upgrade.mjs +225 -0
- package/scripts/verify-github-repo.mjs +2 -0
- package/sdk/node/README.md +17 -0
- package/sdk/node/examples/billing.mjs +21 -0
- package/sdk/node/package.json +5 -1
- package/sdk/node/src/index.mjs +2 -0
- package/sdk/node/src/usage.d.mts +74 -0
- package/sdk/node/src/usage.mjs +62 -0
- package/sdk/node/tests/usage-types.mts +23 -0
- package/sdk/node/tests/usage.test.mjs +81 -0
- package/sdk/php7/README.md +19 -2
- package/sdk/php7/examples/billing.php +27 -0
- package/sdk/php7/examples/well-known.php +1 -1
- package/sdk/php7/src/ToolSpec.php +1 -1
- package/sdk/php7/src/UsageClient.php +95 -0
- package/sdk/php7/src/UsageClientException.php +22 -0
- package/sdk/php7/tests/billing-core-http.php +59 -0
- package/sdk/php7/tests/usage-client.php +78 -0
- package/sql/060_agent_artifacts.sql +11 -0
- package/sql/061_tool_rate_limit_policies.sql +3 -0
- package/sql/062_agent_task_control.sql +92 -0
- package/sql/063_usage_model_billing.sql +153 -0
- package/sql/064_period_plan_allowance.sql +25 -0
- package/sql/README.en.md +12 -4
- package/sql/README.md +14 -6
- package/src/adapters/storage/object-storage.ts +15 -3
- package/src/adapters/storage/oss-signature.test.ts +40 -0
- package/src/adapters/storage/oss-signature.ts +21 -0
- package/src/app/agent-artifacts.test.ts +165 -0
- package/src/app/agent-artifacts.ts +85 -0
- package/src/app/agent-client-runtime.test.ts +76 -1
- package/src/app/agent-client-runtime.ts +13 -0
- package/src/app/agent-invocation-snapshot.ts +35 -0
- package/src/app/agent-task-control.ts +187 -0
- package/src/app/agent-task-runtime.ts +68 -0
- package/src/app/agent-tool-invocations.test.ts +329 -1
- package/src/app/agent-tool-invocations.ts +223 -10
- package/src/app/agent-tool-job.test.ts +11 -1
- package/src/app/agent-tool-job.ts +8 -1
- package/src/app/auth.ts +2 -0
- package/src/app/builtin-tools.ts +4 -0
- package/src/app/oss-edition.ts +2 -0
- package/src/app/tool-approvals.ts +4 -0
- package/src/app/tool-assembly.ts +5 -0
- package/src/core/config/artifact-config.ts +15 -0
- package/src/core/config/config-codec.ts +3 -1
- package/src/core/config/config-models.ts +11 -1
- package/src/core/config/route-config.ts +3 -2
- package/src/core/contracts/tool-rate-limits.test.ts +59 -0
- package/src/core/contracts/tool-rate-limits.ts +48 -0
- package/src/core/contracts/tools.ts +122 -43
- package/src/core/contracts/types.ts +3 -1
- package/src/core/runtime/agent-task-control.test.ts +114 -0
- package/src/core/runtime/agent-task-control.ts +227 -0
- package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
- package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
- package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
- package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
- package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
- package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
- package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
- package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
- package/src/infrastructure/config/configstore.ts +15 -1
- package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
- package/src/modules/usage/billing-contracts.ts +59 -0
- package/src/modules/usage/billing-decimal.test.ts +22 -0
- package/src/modules/usage/billing-decimal.ts +36 -0
- package/src/modules/usage/billing-external.ts +39 -0
- package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
- package/src/modules/usage/billing-ledger.test.ts +51 -0
- package/src/modules/usage/billing-ledger.ts +104 -0
- package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
- package/src/modules/usage/billing-presentation.test.ts +49 -0
- package/src/modules/usage/billing-presentation.ts +34 -0
- package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
- package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
- package/src/modules/usage/billing-repository.ts +463 -0
- package/src/modules/usage/contracts.ts +49 -0
- package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
- package/src/modules/usage/errors.ts +19 -0
- package/src/modules/usage/http.ts +85 -0
- package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
- package/src/modules/usage/identity.mysql.test.ts +120 -0
- package/src/modules/usage/identity.ts +303 -0
- package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
- package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
- package/src/modules/usage/model-gateway.ts +229 -0
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
- package/src/modules/usage/model-tool-provider.test.ts +37 -0
- package/src/modules/usage/model-tool-provider.ts +110 -0
- package/src/modules/usage/model-tools.test.ts +36 -0
- package/src/modules/usage/model-tools.ts +62 -0
- package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
- package/src/modules/usage/period.test.ts +26 -0
- package/src/modules/usage/period.ts +96 -0
- package/src/modules/usage/pricing.test.ts +178 -0
- package/src/modules/usage/pricing.ts +228 -0
- package/src/modules/usage/provider-failure.ts +37 -0
- package/src/modules/usage/provider-stream.test.ts +85 -0
- package/src/modules/usage/provider-stream.ts +77 -0
- package/src/modules/usage/provider.test.ts +67 -0
- package/src/modules/usage/provider.ts +142 -0
- package/src/modules/usage/repository.ts +539 -0
- package/src/modules/usage/service-availability.mysql.test.ts +68 -0
- package/src/modules/usage/service-availability.ts +13 -0
- package/src/modules/usage/service-delete.mysql.test.ts +87 -0
- package/src/modules/usage/stream-http.ts +32 -0
- package/src/modules/usage/test-harness.ts +108 -0
- package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
- package/src/modules/usage/usage-deletion.ts +119 -0
- package/src/modules/usage/validation.test.ts +18 -0
- package/src/modules/usage/validation.ts +33 -0
- package/src/routes/admin-agent-tasks.ts +32 -0
- package/src/routes/admin-billing-usage.ts +73 -0
- package/src/routes/admin-tool-providers.test.ts +22 -0
- package/src/routes/admin-tool-providers.ts +9 -1
- package/src/routes/admin-usage.ts +147 -0
- package/src/routes/admin.ts +7 -0
- package/src/routes/agent-api.test.ts +76 -0
- package/src/routes/agent-api.ts +42 -1
- package/src/routes/agent-artifacts.ts +29 -0
- package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
- package/src/routes/private.ts +9 -0
- package/src/routes/run.ts +2 -1
- package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/Accounts-Bervi5JU.css +1 -0
- package/web/console/assets/Accounts-DnddhY6t.js +3 -0
- package/web/console/assets/AgentClients-VInbD7JS.js +1 -0
- package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
- package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
- package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
- package/web/console/assets/{Approvals-Bs6FGbp2.js → Approvals-34qUPHf0.js} +1 -1
- package/web/console/assets/{Audit-4WWYhkFM.js → Audit-BbVgkSm2.js} +1 -1
- package/web/console/assets/{BrandLockup-D2GhCipL.js → BrandLockup-DgscF28e.js} +1 -1
- package/web/console/assets/{Channels-CmoGpiCJ.js → Channels-Bp-yuk8d.js} +1 -1
- package/web/console/assets/{ChatEntries-BFRMtwta.js → ChatEntries-C9Ft60TS.js} +1 -1
- package/web/console/assets/{Clients-DGkkSXyA.js → Clients-NPldD-DD.js} +1 -1
- package/web/console/assets/{Cost-BmGt0MfS.js → Cost-DZcuB-EB.js} +1 -1
- package/web/console/assets/{Credentials-CR-sYINT.js → Credentials-RTT7N6zl.js} +1 -1
- package/web/console/assets/{Diagnostics-DAPbKSJp.js → Diagnostics-_LeK8cce.js} +1 -1
- package/web/console/assets/{Executors-CgpiT3o8.js → Executors-Bi7H8rIm.js} +1 -1
- package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
- package/web/console/assets/{Kb-Cm9dVSQw.js → Kb-BHamz8NP.js} +2 -2
- package/web/console/assets/{Login-CyUcsTZ_.js → Login-C1rJR-6w.js} +1 -1
- package/web/console/assets/{Projects-DldFPgWg.js → Projects-BRA4a48v.js} +1 -1
- package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
- package/web/console/assets/Routes-CyXV4Pba.css +1 -0
- package/web/console/assets/{Runs-1hxgkuR4.js → Runs-B_fa_BlD.js} +1 -1
- package/web/console/assets/{Setup-DBLOnI2_.js → Setup-C1_d0mFy.js} +1 -1
- package/web/console/assets/Shell-CHEV6RGC.js +1 -0
- package/web/console/assets/Shell-ykb-tUfo.css +1 -0
- package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
- package/web/console/assets/StorageBuckets-DlG3ojhA.js +1 -0
- package/web/console/assets/{SystemSettings-cDkudo2y.js → SystemSettings-DYo2gg6d.js} +1 -1
- package/web/console/assets/{SystemStatus-DZd6s8OX.js → SystemStatus-DKCoUZlq.js} +1 -1
- package/web/console/assets/{Targets-DYNGq1NU.js → Targets-CdkG6BPR.js} +1 -1
- package/web/console/assets/Tools-DU8ei6sd.css +1 -0
- package/web/console/assets/Tools-DVpCt0ox.js +2 -0
- package/web/console/assets/Usage-CAeDGjrb.css +1 -0
- package/web/console/assets/Usage-DWCpLugC.js +1 -0
- package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
- package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
- package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
- package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
- package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
- package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
- package/web/console/assets/index-H1kfa0Mj.js +2 -0
- package/web/console/assets/{request-B7MLvOqo.js → request-DLsP1_ot.js} +1 -1
- package/web/console/assets/{schema-CMuwjYdJ.js → schema-BLOHvAJQ.js} +1 -1
- package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
- package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
- package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
- package/web/console/index.html +3 -3
- package/web-admin/README.md +17 -0
- package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
- package/web-admin/src/components/AgentSetupPanel.vue +13 -0
- package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
- package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
- package/web-admin/src/components/UsageHelp.vue +72 -0
- package/web-admin/src/components/UsageServiceReferences.vue +169 -0
- package/web-admin/src/layout/Shell.vue +23 -6
- package/web-admin/src/pages/Accounts.vue +3 -3
- package/web-admin/src/pages/AgentClients.vue +3 -1
- package/web-admin/src/pages/AgentTasks.vue +281 -0
- package/web-admin/src/pages/Routes.vue +5 -1
- package/web-admin/src/pages/StorageBuckets.vue +6 -6
- package/web-admin/src/pages/Tools.vue +53 -4
- package/web-admin/src/pages/Usage.vue +2470 -0
- package/web-admin/src/pages/UsageAccess.vue +1147 -0
- package/web-admin/src/router.ts +10 -4
- package/web-admin/src/styles/base.css +57 -0
- package/web-admin/src/table-widths.ts +16 -1
- package/web-admin/src/usage-deletion.ts +40 -0
- package/web-admin/src/usage-management.ts +13 -0
- package/web-admin/src/usage-presentation.test.ts +21 -0
- package/web-admin/src/usage-presentation.ts +107 -0
- package/web-admin/src/usage-price-preview.test.ts +60 -0
- package/web-admin/src/usage-price-preview.ts +54 -0
- package/web-admin/tests/token-usage.browser.mjs +773 -0
- package/web-admin/tests/usage-access.browser.mjs +398 -0
- package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
- package/web/console/assets/Accounts-ChL9k-XA.js +0 -3
- package/web/console/assets/AgentClients-Bs7UgVDj.js +0 -1
- package/web/console/assets/AgentClients-DkgPTEbq.css +0 -1
- package/web/console/assets/Routes-DkMIjMQA.css +0 -1
- package/web/console/assets/Routes-DubfjlBD.js +0 -124
- package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
- package/web/console/assets/Shell-gJ5Vz_E7.js +0 -1
- package/web/console/assets/StorageBuckets-DkDW16tj.js +0 -1
- package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
- package/web/console/assets/Tools-A20oaMaQ.css +0 -1
- package/web/console/assets/Tools-DpWM59vV.js +0 -2
- package/web/console/assets/index-DGqs28gI.js +0 -2
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import mysql from 'mysql2/promise';
|
|
5
|
+
import { RateLimitLedger } from './config-rate-limit-ledger';
|
|
6
|
+
import { ToolProviderRepository } from './config-tool-provider-repository';
|
|
7
|
+
import { migrateBailingHubCoreSchema } from '../schema/core-schema-migrator';
|
|
8
|
+
import type { MysqlConfig } from '../../core/config/config';
|
|
9
|
+
|
|
10
|
+
test('isolated MySQL: migration, persisted policies, 120/hour and concurrent all-gate admission', { skip: !process.env.BAILING_RATE_TEST_MYSQL_PORT }, async () => {
|
|
11
|
+
const port = Number(process.env.BAILING_RATE_TEST_MYSQL_PORT);
|
|
12
|
+
const database = `rate_test_${randomBytes(8).toString('hex')}`;
|
|
13
|
+
const admin = await mysql.createConnection({ host: '127.0.0.1', port, user: 'root' });
|
|
14
|
+
await admin.query(`CREATE DATABASE ${database}`);
|
|
15
|
+
const config = { host: '127.0.0.1', port, user: 'root', password: '', database, timezone: 'Z', connectionLimit: 8 };
|
|
16
|
+
const pool = mysql.createPool({ ...config, connectionLimit: 8 });
|
|
17
|
+
try {
|
|
18
|
+
const migration = await migrateBailingHubCoreSchema({ mysql: config as MysqlConfig, logger: { log() {}, warn() {} } });
|
|
19
|
+
assert.ok(migration.appliedFiles.includes('061_tool_rate_limit_policies.sql'));
|
|
20
|
+
assert.equal((await migrateBailingHubCoreSchema({ mysql: config as MysqlConfig, logger: { log() {}, warn() {} } })).appliedFiles.length, 0);
|
|
21
|
+
const repository = new ToolProviderRepository(() => pool);
|
|
22
|
+
await repository.upsert({ name: 'store', base_url: 'https://business.invalid', spec_source: 'inline', secret: 'synthetic', log_payload: false,
|
|
23
|
+
timeout_ms: 10000, rate_limit_per_min: 0, auto_refresh_min: 0, enabled: true,
|
|
24
|
+
tool_rate_limits: { default: { mode: 'disabled' }, overrides: { images_update: { mode: 'custom', count: 1000, window: '1h' } } } });
|
|
25
|
+
const saved = (await repository.get('store'))!;
|
|
26
|
+
await repository.upsert({ ...saved, description: 'refreshed metadata' });
|
|
27
|
+
assert.deepEqual((await repository.get('store'))!.tool_rate_limits, saved.tool_rate_limits);
|
|
28
|
+
const ledger = new RateLimitLedger(() => pool);
|
|
29
|
+
const tool = { bucket: 'tool:store:images_update', limit: 120, windowSec: 3600 };
|
|
30
|
+
for (let i = 0; i < 120; i++) assert.equal((await ledger.consumeAll([tool])).limited, false);
|
|
31
|
+
assert.equal((await ledger.consumeAll([tool])).limited, true);
|
|
32
|
+
await pool.query('UPDATE bz_rate_limits SET created_at=DATE_SUB(UTC_TIMESTAMP(), INTERVAL 61 SECOND)');
|
|
33
|
+
assert.equal((await ledger.consumeAll([tool])).limited, true);
|
|
34
|
+
await pool.query('UPDATE bz_rate_limits SET created_at=DATE_SUB(UTC_TIMESTAMP(), INTERVAL 3601 SECOND)');
|
|
35
|
+
assert.equal((await ledger.consumeAll([tool])).limited, false);
|
|
36
|
+
await ledger.clear(tool.bucket);
|
|
37
|
+
const provider = { bucket: 'provider:store', limit: 3, windowSec: 60 };
|
|
38
|
+
const gates = [{ ...tool, limit: 20 }, provider];
|
|
39
|
+
const results = await Promise.all(Array.from({ length: 12 }, () => ledger.consumeAll(gates)));
|
|
40
|
+
assert.equal(results.filter((r) => !r.limited).length, 3);
|
|
41
|
+
assert.equal(await ledger.count(tool.bucket, 3600), 3);
|
|
42
|
+
assert.equal(await ledger.count(provider.bucket, 60), 3);
|
|
43
|
+
// Saturated tool cannot consume the provider gate; a third tool still has the full provider quota.
|
|
44
|
+
await ledger.clear(provider.bucket);
|
|
45
|
+
assert.equal((await ledger.consumeAll([{ ...tool, limit: 3 }, provider])).limited, true);
|
|
46
|
+
assert.equal(await ledger.count(provider.bucket, 60), 0);
|
|
47
|
+
} finally {
|
|
48
|
+
await pool.end();
|
|
49
|
+
await admin.query(`DROP DATABASE ${database}`);
|
|
50
|
+
await admin.end();
|
|
51
|
+
}
|
|
52
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { dt, dtAt } from '../../core/config/config-codec';
|
|
3
|
+
import type { RateLimitDecision, RateLimitRequest } from '../../core/contracts/tool-rate-limits';
|
|
3
4
|
|
|
4
5
|
export class RateLimitLedger {
|
|
5
6
|
constructor(private readonly poolOf: () => any) {}
|
|
@@ -53,4 +54,51 @@ export class RateLimitLedger {
|
|
|
53
54
|
async clear(bucket: string): Promise<void> {
|
|
54
55
|
await this.pool.query('DELETE FROM bz_rate_limits WHERE bucket=?', [bucket]);
|
|
55
56
|
}
|
|
57
|
+
|
|
58
|
+
/** One connection, deterministic locks and one transaction: a rejected gate charges no other gate. */
|
|
59
|
+
async consumeAll(requests: RateLimitRequest[]): Promise<RateLimitDecision> {
|
|
60
|
+
const gates = requests.filter((gate) => gate.limit > 0);
|
|
61
|
+
if (!gates.length) return { limited: false };
|
|
62
|
+
const conn = await this.pool.getConnection();
|
|
63
|
+
const locks: string[] = [];
|
|
64
|
+
let transaction = false;
|
|
65
|
+
try {
|
|
66
|
+
for (const bucket of [...new Set(gates.map((gate) => gate.bucket))].sort()) {
|
|
67
|
+
const name = this.lockName(bucket);
|
|
68
|
+
const [rows] = await conn.query('SELECT GET_LOCK(?, 2) AS ok', [name]);
|
|
69
|
+
if (Number(rows[0]?.ok) !== 1) throw new Error('rate limit lock timeout');
|
|
70
|
+
locks.push(name);
|
|
71
|
+
}
|
|
72
|
+
await conn.beginTransaction();
|
|
73
|
+
transaction = true;
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
for (const gate of gates) {
|
|
76
|
+
const cutoff = dtAt(now - gate.windowSec * 1000);
|
|
77
|
+
const [rows] = await conn.query('SELECT COUNT(*) AS n FROM bz_rate_limits WHERE bucket=? AND created_at > ?', [gate.bucket, cutoff]);
|
|
78
|
+
const count = Number(rows[0]?.n ?? 0);
|
|
79
|
+
if (count >= gate.limit) {
|
|
80
|
+
// Offset handles a limit lowered while the original window is still occupied.
|
|
81
|
+
const [expiry] = await conn.query('SELECT created_at FROM bz_rate_limits WHERE bucket=? AND created_at > ? ORDER BY created_at, id LIMIT 1 OFFSET ?', [gate.bucket, cutoff, count - gate.limit]);
|
|
82
|
+
const raw = expiry[0]?.created_at;
|
|
83
|
+
const oldest = raw instanceof Date ? raw.getTime() : Date.parse(String(raw).replace(' ', 'T') + 'Z');
|
|
84
|
+
await conn.rollback();
|
|
85
|
+
transaction = false;
|
|
86
|
+
return { limited: true, bucket: gate.bucket, retryAfterMs: Number.isFinite(oldest) ? Math.max(1, oldest + gate.windowSec * 1000 - now) : gate.windowSec * 1000 };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
for (const gate of gates) {
|
|
90
|
+
await conn.query('DELETE FROM bz_rate_limits WHERE bucket=? AND created_at <= ?', [gate.bucket, dtAt(now - gate.windowSec * 1000)]);
|
|
91
|
+
await conn.query('INSERT INTO bz_rate_limits (bucket, created_at) VALUES (?, ?)', [gate.bucket, dtAt(now)]);
|
|
92
|
+
}
|
|
93
|
+
await conn.commit();
|
|
94
|
+
transaction = false;
|
|
95
|
+
return { limited: false };
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (transaction) await conn.rollback().catch(() => undefined);
|
|
98
|
+
throw error;
|
|
99
|
+
} finally {
|
|
100
|
+
for (const name of locks.reverse()) await conn.query('SELECT RELEASE_LOCK(?)', [name]).catch(() => undefined);
|
|
101
|
+
conn.release();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
56
104
|
}
|
|
@@ -19,12 +19,12 @@ export class StorageBucketRepository {
|
|
|
19
19
|
/** 新建/更新。编辑时 access_key / secret_key 传空 = 保留原值(列表不回显完整凭证,没法回填)。 */
|
|
20
20
|
async upsert(b: StorageBucket): Promise<void> {
|
|
21
21
|
const existing = (!b.secret_key || !b.access_key) ? await this.get(b.name) : null;
|
|
22
|
-
let sk = b.secret_key;
|
|
22
|
+
let sk = b.kind === 'local' ? 'local' : b.secret_key;
|
|
23
23
|
if (!sk) {
|
|
24
24
|
if (!existing) throw new Error('新建存储桶必须填 SecretKey');
|
|
25
25
|
sk = existing.secret_key;
|
|
26
26
|
}
|
|
27
|
-
let ak = b.access_key;
|
|
27
|
+
let ak = b.kind === 'local' ? 'local' : b.access_key;
|
|
28
28
|
if (!ak) {
|
|
29
29
|
if (!existing) throw new Error('新建存储桶必须填 SecretId / AccessKeyId');
|
|
30
30
|
ak = existing.access_key;
|
|
@@ -32,10 +32,10 @@ export class ToolProviderRepository {
|
|
|
32
32
|
? p.spec_access_policy
|
|
33
33
|
: null;
|
|
34
34
|
await this.pool.query(
|
|
35
|
-
'INSERT INTO bz_tool_providers (name,base_url,spec_source,spec_access_policy,spec_url,spec_json,spec_refreshed_at,spec_access_probe_json,authz_probe_json,secret,log_payload,timeout_ms,rate_limit_per_min,auto_refresh_min,enabled,description,embed_credential,embed_model,embed_dim,created_at,updated_at) ' +
|
|
36
|
-
'VALUES (
|
|
35
|
+
'INSERT INTO bz_tool_providers (name,base_url,spec_source,spec_access_policy,spec_url,spec_json,spec_refreshed_at,spec_access_probe_json,authz_probe_json,secret,log_payload,timeout_ms,rate_limit_per_min,auto_refresh_min,enabled,description,embed_credential,embed_model,embed_dim,created_at,updated_at,tool_rate_limits_json) ' +
|
|
36
|
+
'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' +
|
|
37
37
|
(updateExisting
|
|
38
|
-
? 'ON DUPLICATE KEY UPDATE base_url=VALUES(base_url),spec_source=VALUES(spec_source),spec_access_policy=VALUES(spec_access_policy),spec_url=VALUES(spec_url),spec_json=VALUES(spec_json),spec_refreshed_at=VALUES(spec_refreshed_at),spec_access_probe_json=VALUES(spec_access_probe_json),authz_probe_json=VALUES(authz_probe_json),secret=VALUES(secret),log_payload=VALUES(log_payload),timeout_ms=VALUES(timeout_ms),rate_limit_per_min=VALUES(rate_limit_per_min),auto_refresh_min=VALUES(auto_refresh_min),enabled=VALUES(enabled),description=VALUES(description),embed_credential=VALUES(embed_credential),embed_model=VALUES(embed_model),embed_dim=VALUES(embed_dim),updated_at=VALUES(updated_at)'
|
|
38
|
+
? 'ON DUPLICATE KEY UPDATE base_url=VALUES(base_url),spec_source=VALUES(spec_source),spec_access_policy=VALUES(spec_access_policy),spec_url=VALUES(spec_url),spec_json=VALUES(spec_json),spec_refreshed_at=VALUES(spec_refreshed_at),spec_access_probe_json=VALUES(spec_access_probe_json),authz_probe_json=VALUES(authz_probe_json),secret=VALUES(secret),log_payload=VALUES(log_payload),timeout_ms=VALUES(timeout_ms),rate_limit_per_min=VALUES(rate_limit_per_min),auto_refresh_min=VALUES(auto_refresh_min),enabled=VALUES(enabled),description=VALUES(description),embed_credential=VALUES(embed_credential),embed_model=VALUES(embed_model),embed_dim=VALUES(embed_dim),updated_at=VALUES(updated_at),tool_rate_limits_json=VALUES(tool_rate_limits_json)'
|
|
39
39
|
: ''),
|
|
40
40
|
[p.name, p.base_url, p.spec_source, specAccessPolicy, p.spec_url ?? null, p.spec_json ?? null,
|
|
41
41
|
p.spec_refreshed_at ? p.spec_refreshed_at.slice(0, 19).replace('T', ' ') : null,
|
|
@@ -43,7 +43,7 @@ export class ToolProviderRepository {
|
|
|
43
43
|
p.authz_probe ? JSON.stringify(p.authz_probe) : null,
|
|
44
44
|
p.secret, p.log_payload ? 1 : 0, p.timeout_ms, p.rate_limit_per_min, p.auto_refresh_min,
|
|
45
45
|
p.enabled ? 1 : 0, p.description ?? null,
|
|
46
|
-
p.embed_credential ?? null, p.embed_model ?? null, p.embed_dim ?? null, dt(), dt()],
|
|
46
|
+
p.embed_credential ?? null, p.embed_model ?? null, p.embed_dim ?? null, dt(), dt(), p.tool_rate_limits ? JSON.stringify(p.tool_rate_limits) : null],
|
|
47
47
|
);
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -25,8 +25,12 @@ import { MysqlKbDatasourceRepository, MysqlKnowledgeRepository } from './config-
|
|
|
25
25
|
import { InstanceBrandingRepository } from './config-instance-branding-repository';
|
|
26
26
|
import type { InstanceBrandingRepositoryContract } from './config-instance-branding-repository';
|
|
27
27
|
import { AgentAuthRepository, type AgentAuthRepositoryContract } from './config-agent-auth-repository';
|
|
28
|
+
import { AgentArtifactRepository } from './config-agent-artifact-repository';
|
|
28
29
|
import { AgentClientRuntimeRepository } from './config-agent-client-runtime-repository';
|
|
29
30
|
import { AgentConversationAuditRepository } from './config-agent-conversation-audit-repository';
|
|
31
|
+
import { AgentTaskControlRepository } from './config-agent-task-control-repository';
|
|
32
|
+
import { UsageRepository } from '../../modules/usage/repository';
|
|
33
|
+
import { getUsageIdentity } from '../../modules/usage/identity';
|
|
30
34
|
import { MysqlPoolOwner, type MysqlPoolResource } from '../mysql/pool-owner';
|
|
31
35
|
|
|
32
36
|
export type RouteRepositoryContract = Omit<Pick<RouteRepository, keyof RouteRepository>, 'compareAndSetAgentSetup'>
|
|
@@ -46,7 +50,8 @@ export type TargetRepositoryContract = Pick<TargetRepository, keyof TargetReposi
|
|
|
46
50
|
export type StorageBucketRepositoryContract = Pick<StorageBucketRepository, keyof StorageBucketRepository>;
|
|
47
51
|
export type AlertRuleRepositoryContract = Pick<AlertRuleRepository, keyof AlertRuleRepository>;
|
|
48
52
|
export type ChatConfigRepositoryContract = Pick<ChatConfigRepository, keyof ChatConfigRepository>;
|
|
49
|
-
export type RateLimitLedgerContract = Pick<RateLimitLedger, keyof RateLimitLedger
|
|
53
|
+
export type RateLimitLedgerContract = Omit<Pick<RateLimitLedger, keyof RateLimitLedger>, 'consumeAll'>
|
|
54
|
+
& Partial<Pick<RateLimitLedger, 'consumeAll'>>;
|
|
50
55
|
export type ApprovalLedgerContract =
|
|
51
56
|
Omit<Pick<ApprovalLedger, keyof ApprovalLedger>, 'forJobs'>
|
|
52
57
|
& Partial<Pick<ApprovalLedger, 'forJobs'>>;
|
|
@@ -92,11 +97,16 @@ export interface ConfigStoreContract {
|
|
|
92
97
|
readonly deliveryDlq: DeliveryDlqLedgerContract;
|
|
93
98
|
readonly observability: ObservabilityLedgerContract;
|
|
94
99
|
/** 新 Agent Auth 能力对旧宿主仓储保持可选;缺失时 HTTP 面 fail closed。 */
|
|
100
|
+
readonly agentArtifacts?: Pick<AgentArtifactRepository, keyof AgentArtifactRepository>;
|
|
95
101
|
readonly agentAuth?: AgentAuthRepositoryContract;
|
|
96
102
|
/** Agent Client Runtime v1 对旧宿主保持可选;缺失时新 API fail closed。 */
|
|
97
103
|
readonly agentClientRuntime?: AgentClientRuntimeRepositoryContract;
|
|
98
104
|
/** Optional, admin-only visible transcript ledger; never a source of Agent memory. */
|
|
99
105
|
readonly agentConversationAudit?: AgentConversationAuditRepositoryContract;
|
|
106
|
+
/** Optional for extension hosts. Managed Sessions must never fall back without this repository. */
|
|
107
|
+
readonly agentTaskControl?: Pick<AgentTaskControlRepository, keyof AgentTaskControlRepository>;
|
|
108
|
+
/** Optional usage module. Dedicated usage requests fail closed when it is absent. */
|
|
109
|
+
readonly usage?: UsageRepository;
|
|
100
110
|
init(): Promise<void>;
|
|
101
111
|
close?(): Promise<void>;
|
|
102
112
|
readonly db: Pool;
|
|
@@ -130,11 +140,15 @@ export class ConfigStore implements ConfigStoreContract {
|
|
|
130
140
|
readonly deliveryDlq = new DeliveryDlqLedger(() => this.pool);
|
|
131
141
|
readonly observability = new ObservabilityLedger(() => this.pool);
|
|
132
142
|
readonly agentAuth = new AgentAuthRepository(() => this.pool);
|
|
143
|
+
readonly agentArtifacts = new AgentArtifactRepository(() => this.pool);
|
|
133
144
|
readonly agentClientRuntime = new AgentClientRuntimeRepository(() => this.pool);
|
|
134
145
|
readonly agentConversationAudit = new AgentConversationAuditRepository(() => this.pool);
|
|
146
|
+
readonly agentTaskControl = new AgentTaskControlRepository(() => this.pool);
|
|
147
|
+
readonly usage = new UsageRepository(() => this.pool);
|
|
135
148
|
|
|
136
149
|
constructor(cfg: AppConfig['state']['mysql'], poolOwner?: MysqlPoolResource) {
|
|
137
150
|
this.poolOwner = poolOwner ?? new MysqlPoolOwner(cfg);
|
|
151
|
+
getUsageIdentity(this.usage);
|
|
138
152
|
}
|
|
139
153
|
|
|
140
154
|
async init(): Promise<void> {
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import { createUsageTestHarness } from './test-harness';
|
|
5
|
+
import { usageHash } from './repository';
|
|
6
|
+
import type { BillingPlanConfig, BillingRequest, PriceSnapshot } from './billing-contracts';
|
|
7
|
+
|
|
8
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
9
|
+
const day = 86_400_000, admin = 'synthetic-admin';
|
|
10
|
+
const price: PriceSnapshot = { source: 'openrouter', currency: 'USD', modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: 1,
|
|
11
|
+
lines: [{ billable: 'prompt', unit: 'token', costUsd: '1' }, { billable: 'completion', unit: 'token', costUsd: '1' }] };
|
|
12
|
+
async function fixture(mode: 'periodic' | 'credits' = 'periodic', sourceOwner = 'hub') {
|
|
13
|
+
const h = await createUsageTestHarness();
|
|
14
|
+
let now = Date.now(); const startsAt = now;
|
|
15
|
+
Object.defineProperty(h.tokens, 'now', { value: async () => now });
|
|
16
|
+
const user = await h.seedUser({ grant: false });
|
|
17
|
+
const config: BillingPlanConfig = { mode, priceUsd: 100, multiplier: 1, serviceIds: [h.service.id],
|
|
18
|
+
...(mode === 'periodic' ? { periodAllowanceUsd: 20, periodUnit: 'week' as const } : {}), duration: { unit: 'day', count: 30 } };
|
|
19
|
+
const plan = await h.tokens.putPlan({ id: 'synthetic-reset', label: 'Synthetic reset', expected_revision: 0, config });
|
|
20
|
+
const grant = await h.tokens.grant(user.accountId, { request_key: randomUUID(), plan_id: plan.id, expected_revision: 0, starts_at: now }, sourceOwner);
|
|
21
|
+
const path = `/admin/api/usage/billing/accounts/${user.accountId}/reset`;
|
|
22
|
+
const reset = (revision: number, key = randomUUID()) => h.request(path, admin, 'POST', { request_key: key, expected_revision: revision });
|
|
23
|
+
const admit = async () => { const operationId = randomUUID(); return h.tokens.admit({ actor: user.actor, operationId, serviceId: h.service.id,
|
|
24
|
+
conversationId: null, turnId: null, requestHash: usageHash(operationId), expectedServiceRevision: h.service.revision,
|
|
25
|
+
serviceConfig: h.service.config, model: h.service.config.model, priceSnapshot: price }); };
|
|
26
|
+
const dispatch = async () => h.tokens.commitDispatch((await admit()).id, user.actor);
|
|
27
|
+
const finish = (r: BillingRequest, cost: number) => h.tokens.complete(r.id, r.fence!, { response: { output: 'synthetic' }, usage: { inputTokens: cost, outputTokens: 0 } });
|
|
28
|
+
return { ...h, user, config, plan, grant, path, reset, dispatch, finish, startsAt, setNow: (value: number) => { now = value; } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
test('manual reset restores the original weekly allowance, moves the anchor and preserves expiry and late settlement', { skip: !enabled }, async () => {
|
|
32
|
+
const h = await fixture();
|
|
33
|
+
try {
|
|
34
|
+
const late = await h.dispatch();
|
|
35
|
+
await h.finish(await h.dispatch(), 20);
|
|
36
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).presentation.remaining, 0);
|
|
37
|
+
await h.tokens.putPlan({ id: h.plan.id, label: h.plan.label, expected_revision: 1, config: { ...h.config, priceUsd: 999, periodAllowanceUsd: 200 } });
|
|
38
|
+
h.setNow(h.startsAt + 2 * day);
|
|
39
|
+
const reset = await h.reset(1); assert.equal(reset.status, 200);
|
|
40
|
+
assert.notEqual(reset.body.id, h.grant.id);
|
|
41
|
+
assert.equal(reset.body.reset.previousGrantId, h.grant.id);
|
|
42
|
+
assert.equal(reset.body.reset.actor, 'admin-token');
|
|
43
|
+
const current = await h.tokens.summary(h.user.accountId);
|
|
44
|
+
assert.equal(current.availableUsd, 20); assert.equal(current.presentation.remaining, 100);
|
|
45
|
+
assert.equal(current.resetAt, h.startsAt + 9 * day); assert.equal(current.expiresAt, h.grant.expiresAt);
|
|
46
|
+
assert.equal(current.grant!.config.priceUsd, 100);
|
|
47
|
+
const done = await h.finish(late, 7);
|
|
48
|
+
assert.equal(done.grantId, h.grant.id);
|
|
49
|
+
assert.deepEqual(await h.finish(late, 7), done);
|
|
50
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).availableUsd, 20);
|
|
51
|
+
const [pools] = await h.pool.query<any[]>('SELECT consumed_usd FROM bz_usage_billing_periods WHERE grant_id=?', [h.grant.id]);
|
|
52
|
+
assert.equal(Number(pools[0].consumed_usd), 27);
|
|
53
|
+
assert.equal((await h.tokens.findRequest(h.user.actor, late.operationId))!.resultState, 'complete');
|
|
54
|
+
h.setNow(h.startsAt + 28 * day);
|
|
55
|
+
assert.equal((await h.reset(2)).status, 200);
|
|
56
|
+
const final = await h.tokens.summary(h.user.accountId);
|
|
57
|
+
assert.equal(final.availableUsd, 20); assert.equal(final.resetAt, null); assert.equal(final.expiresAt, h.grant.expiresAt);
|
|
58
|
+
h.setNow(h.grant.expiresAt!);
|
|
59
|
+
assert.equal((await h.reset(3)).body.error, 'SERVICE_NOT_ENTITLED');
|
|
60
|
+
} finally { await h.close(); }
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('reset retries and concurrent clicks issue one allowance; replay after spending does not refill it', { skip: !enabled }, async () => {
|
|
64
|
+
const h = await fixture();
|
|
65
|
+
try {
|
|
66
|
+
const key = randomUUID();
|
|
67
|
+
const [first, duplicate] = await Promise.all([h.reset(1, key), h.reset(1, key)]);
|
|
68
|
+
assert.equal(first.status, 200); assert.deepEqual(duplicate.body, first.body);
|
|
69
|
+
await h.finish(await h.dispatch(), 5);
|
|
70
|
+
assert.deepEqual((await h.reset(1, key)).body, first.body);
|
|
71
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).availableUsd, 15);
|
|
72
|
+
assert.equal((await h.reset(2, key)).body.error, 'USAGE_IDEMPOTENCY_CONFLICT');
|
|
73
|
+
assert.equal((await h.reset(1)).body.error, 'USAGE_REVISION_CONFLICT');
|
|
74
|
+
const results = await Promise.all([h.reset(2), h.reset(2)]);
|
|
75
|
+
assert.equal(results.filter(r => r.status === 200).length, 1);
|
|
76
|
+
assert.equal(results.filter(r => r.body.error === 'USAGE_REVISION_CONFLICT').length, 1);
|
|
77
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).availableUsd, 20);
|
|
78
|
+
const [rows] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_grants WHERE account_id=?', [h.user.accountId]);
|
|
79
|
+
assert.equal(Number(rows[0].n), 3);
|
|
80
|
+
const [receipts] = await h.pool.query<any[]>('SELECT result_json FROM bz_usage_changes WHERE JSON_EXTRACT(result_json,\'$.reset\') IS NOT NULL');
|
|
81
|
+
assert.equal(receipts.length, 2);
|
|
82
|
+
} finally { await h.close(); }
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('credits reset restores the pack without periodic renewal or extending its life', { skip: !enabled }, async () => {
|
|
86
|
+
const h = await fixture('credits');
|
|
87
|
+
try {
|
|
88
|
+
await h.finish(await h.dispatch(), 40);
|
|
89
|
+
assert.equal((await h.tokens.summary(h.user.accountId)).availableUsd, 60);
|
|
90
|
+
h.setNow(h.startsAt + day);
|
|
91
|
+
assert.equal((await h.reset(1)).status, 200);
|
|
92
|
+
const summary = await h.tokens.summary(h.user.accountId);
|
|
93
|
+
assert.equal(summary.availableUsd, 100); assert.equal(summary.presentation.kind, 'credits');
|
|
94
|
+
assert.equal(summary.resetAt, null); assert.equal(summary.expiresAt, h.grant.expiresAt);
|
|
95
|
+
} finally { await h.close(); }
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('reset enforces adjustment permission, input shape, active account and active effective grant', { skip: !enabled }, async () => {
|
|
99
|
+
const h = await fixture();
|
|
100
|
+
try {
|
|
101
|
+
const body = { request_key: randomUUID(), expected_revision: 1 };
|
|
102
|
+
assert.equal((await h.request(h.path, 'synthetic-auditor', 'POST', body)).status, 403);
|
|
103
|
+
assert.equal((await h.request(h.path, admin, 'POST', { ...body, priceUsd: 999 })).status, 400);
|
|
104
|
+
assert.equal((await h.request(h.path, admin, 'POST', { expected_revision: 1 })).status, 400);
|
|
105
|
+
h.setNow(h.startsAt - 1);
|
|
106
|
+
assert.equal((await h.reset(1)).body.error, 'SERVICE_NOT_ENTITLED');
|
|
107
|
+
h.setNow(h.startsAt);
|
|
108
|
+
await h.tokens.control(h.user.accountId, { request_key: randomUUID(), expected_revision: 1, state: 'suspended' });
|
|
109
|
+
assert.equal((await h.reset(2)).body.error, 'SERVICE_NOT_ENTITLED');
|
|
110
|
+
await h.tokens.control(h.user.accountId, { request_key: randomUUID(), expected_revision: 2, state: 'active' });
|
|
111
|
+
await h.repository.setAccountState({ accountId: h.user.accountId, expectedRevision: 1, requestId: randomUUID(), actor: admin, state: 'suspended' });
|
|
112
|
+
assert.equal((await h.reset(3)).body.error, 'USAGE_ACCOUNT_SUSPENDED');
|
|
113
|
+
const [rows] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_grants WHERE account_id=?', [h.user.accountId]);
|
|
114
|
+
assert.equal(Number(rows[0].n), 1);
|
|
115
|
+
} finally { await h.close(); }
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test('external entitlement owners retain control over their allowance', { skip: !enabled }, async () => {
|
|
119
|
+
const h = await fixture('periodic', 'issuer:synthetic-product');
|
|
120
|
+
try { assert.equal((await h.reset(1)).body.error, 'USAGE_SOURCE_CONFLICT'); }
|
|
121
|
+
finally { await h.close(); }
|
|
122
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { UsageActor, UsageServiceConfig } from './contracts';
|
|
2
|
+
|
|
3
|
+
export interface BillingAllowanceConfig {
|
|
4
|
+
mode: 'credits' | 'periodic'; priceUsd: number;
|
|
5
|
+
/** Required for periodic plans only; priceUsd remains the sale price. */
|
|
6
|
+
periodAllowanceUsd?: number;
|
|
7
|
+
periodUnit?: 'day' | 'week' | 'month';
|
|
8
|
+
duration: { unit: 'day' | 'month' | 'forever'; count: number };
|
|
9
|
+
}
|
|
10
|
+
export interface PriceLine { billable: string; unit: 'token' | 'image' | 'megapixel' | 'second' | 'request'; costUsd: string; variant?: string }
|
|
11
|
+
export interface PriceTier { minPromptTokens: number; lines: PriceLine[] }
|
|
12
|
+
export interface PriceSnapshot { source: 'openrouter'; modelId: string; endpointId: string; currency: 'USD'; fetchedAt: number; lines: PriceLine[]; tiers?: PriceTier[] }
|
|
13
|
+
export interface BillingRate { planId: string; planRevision: number; multiplier: number; price: PriceSnapshot }
|
|
14
|
+
export interface BillingPlanConfig extends BillingAllowanceConfig { serviceIds: string[]; multiplier: number }
|
|
15
|
+
export interface BillingPlan {
|
|
16
|
+
id: string; label: string; revision: number; state: 'active' | 'suspended';
|
|
17
|
+
config: BillingPlanConfig; createdAt: number; updatedAt: number;
|
|
18
|
+
}
|
|
19
|
+
export interface BillingGrant {
|
|
20
|
+
id: string; accountId: string; planId: string; planRevision: number; label: string;
|
|
21
|
+
revision: number; state: 'active' | 'suspended'; sourceOwner: string;
|
|
22
|
+
startsAt: number; expiresAt: number | null; config: BillingAllowanceConfig;
|
|
23
|
+
}
|
|
24
|
+
export interface BillingSummary {
|
|
25
|
+
schema: 'bailing.billing-summary.v1'; accountId: string; grant: BillingGrant | null;
|
|
26
|
+
plan: Pick<BillingPlan, 'id' | 'label' | 'revision'> & { serviceIds: string[]; multiplier: number } | null;
|
|
27
|
+
availableUsd: number; consumedUsd: number; currentPeriodConsumedUsd: number;
|
|
28
|
+
overageUsd: number; resetAt: number | null; expiresAt: number | null; pendingRequests: number;
|
|
29
|
+
presentation: UsagePresentation;
|
|
30
|
+
}
|
|
31
|
+
/** Customer display only. Raw Token accounting remains an independent machine contract. */
|
|
32
|
+
export interface UsagePresentation {
|
|
33
|
+
schema: 'bailing.usage-presentation.v1';
|
|
34
|
+
kind: 'credits' | 'percentage' | 'none';
|
|
35
|
+
state: 'active' | 'depleted' | 'not_started' | 'expired' | 'suspended' | 'unavailable';
|
|
36
|
+
remaining: number | null; total: number | null; displayValue: string | null;
|
|
37
|
+
}
|
|
38
|
+
export interface TokenUsage { inputTokens: number; outputTokens: number; totalTokens: number }
|
|
39
|
+
export interface BillingRequest {
|
|
40
|
+
id: string; operationId: string; accountId: string; userId: string; sessionId: string;
|
|
41
|
+
serviceId: string; conversationId: string | null; turnId: string | null; requestHash: string;
|
|
42
|
+
revision: number; state: 'admitted' | 'dispatch_committed' | 'completed' | 'unknown' | 'cancelled' | 'failed';
|
|
43
|
+
resultState: 'pending' | 'complete' | 'unknown' | 'cancelled' | 'failed'; billingState: 'pending' | 'settled';
|
|
44
|
+
serviceConfig: UsageServiceConfig; serviceRevision: number; model: string; fence: string | null;
|
|
45
|
+
grantId: string; grantRevision: number; periodStart: number; periodEnd: number | null;
|
|
46
|
+
billingRate: BillingRate;
|
|
47
|
+
grantConfig: BillingAllowanceConfig; response: Record<string, unknown> | null; resultHash: string | null; usage: TokenUsage | null;
|
|
48
|
+
rawUsage: Record<string, unknown> | null; referenceCostUsd: number | null; billedUsd: number | null; overageUsd: number | null; cancelledAt: number | null;
|
|
49
|
+
createdAt: number; updatedAt: number; created?: boolean;
|
|
50
|
+
}
|
|
51
|
+
export interface BillingAdmissionInput {
|
|
52
|
+
actor: UsageActor; operationId: string; serviceId: string; conversationId: string | null;
|
|
53
|
+
turnId: string | null; requestHash: string; expectedServiceRevision: number;
|
|
54
|
+
serviceConfig: UsageServiceConfig; model: string; priceSnapshot: PriceSnapshot;
|
|
55
|
+
}
|
|
56
|
+
export interface BillingCompletionInput {
|
|
57
|
+
response: Record<string, unknown>; usage?: { inputTokens: number; outputTokens: number };
|
|
58
|
+
rawUsage?: Record<string, unknown>; executionId?: string;
|
|
59
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { usdAmount, usdDecimal, usdMicros, USD_SCALE } from './billing-decimal';
|
|
4
|
+
import { billedUsdMicros, validateBillingPlan } from './billing-ledger';
|
|
5
|
+
|
|
6
|
+
test('USD arithmetic keeps twelve decimals and rejects silent precision loss', () => {
|
|
7
|
+
assert.equal(USD_SCALE, 1_000_000_000_000n);
|
|
8
|
+
assert.equal(usdMicros('0.000000001'), 1000n);
|
|
9
|
+
assert.equal(usdMicros(0.1) + usdMicros(0.2), 300_000_000_000n);
|
|
10
|
+
assert.equal(usdAmount(usdMicros('0.000000000001')), 1e-12);
|
|
11
|
+
assert.equal(usdDecimal(usdMicros('12.012345678912')), '12.012345678912');
|
|
12
|
+
for (const invalid of [1e-13, -1, NaN, Infinity, '1.0000000000001']) assert.throws(() => usdMicros(invalid));
|
|
13
|
+
assert.throws(() => usdAmount(usdMicros('9007199254740990.000000000001')), /exactly/);
|
|
14
|
+
});
|
|
15
|
+
test('uniform multiplier computes money without inventing generated-image tokens', () => {
|
|
16
|
+
assert.equal(usdDecimal(billedUsdMicros('0.2', 1.5)), '0.3');
|
|
17
|
+
assert.equal(usdDecimal(billedUsdMicros('0.000000000001', 0.5)), '0.000000000001');
|
|
18
|
+
assert.equal(usdDecimal(billedUsdMicros('0', 1.5)), '0');
|
|
19
|
+
const config = { mode: 'credits', serviceIds: ['a'], priceUsd: 100, multiplier: 1.5, duration: { unit: 'day', count: 1 } };
|
|
20
|
+
assert.equal(validateBillingPlan(config).multiplier, 1.5);
|
|
21
|
+
assert.throws(() => validateBillingPlan({ ...config, modelRates: {} }), /unsupported/);
|
|
22
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { UsageError, usageAssert } from './errors';
|
|
2
|
+
|
|
3
|
+
export const USD_SCALE = 1_000_000_000_000n;
|
|
4
|
+
const MAX_DECIMAL = 10n ** 30n - 1n;
|
|
5
|
+
/** Parse decimal/scientific notation without multiplying a binary floating point value. */
|
|
6
|
+
export function usdMicros(value: string | number, name = 'amount'): bigint {
|
|
7
|
+
usageAssert((typeof value === 'number' && Number.isFinite(value)) || typeof value === 'string',
|
|
8
|
+
'USAGE_INVALID_INPUT', `${name} must be a finite decimal.`, 400);
|
|
9
|
+
const match = /^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(String(value));
|
|
10
|
+
usageAssert(match, 'USAGE_INVALID_INPUT', `${name} must be a nonnegative decimal.`, 400);
|
|
11
|
+
const exponent = Number(match[3] ?? 0), fraction = match[2] ?? '';
|
|
12
|
+
usageAssert(Number.isInteger(exponent) && Math.abs(exponent) <= 30, 'USAGE_INVALID_INPUT', `${name} is outside the decimal range.`, 400);
|
|
13
|
+
const coefficient = BigInt(match[1]! + fraction), shift = 12 + exponent - fraction.length;
|
|
14
|
+
let micros: bigint;
|
|
15
|
+
if (shift >= 0) micros = coefficient * 10n ** BigInt(shift);
|
|
16
|
+
else {
|
|
17
|
+
const divisor = 10n ** BigInt(-shift);
|
|
18
|
+
usageAssert(coefficient % divisor === 0n, 'USAGE_INVALID_INPUT', `${name} allows at most twelve decimal places.`, 400);
|
|
19
|
+
micros = coefficient / divisor;
|
|
20
|
+
}
|
|
21
|
+
usageAssert(micros <= MAX_DECIMAL, 'USAGE_INVALID_INPUT', `${name} is outside the decimal range.`, 400);
|
|
22
|
+
return micros;
|
|
23
|
+
}
|
|
24
|
+
export function usdDecimal(micros: bigint): string {
|
|
25
|
+
usageAssert(micros >= 0n && micros <= MAX_DECIMAL, 'METERING_UNAVAILABLE', 'The recorded amount exceeds the accounting range.', 503);
|
|
26
|
+
const fractional = String(micros % USD_SCALE).padStart(12, '0').replace(/0+$/, '');
|
|
27
|
+
return `${micros / USD_SCALE}${fractional ? `.${fractional}` : ''}`;
|
|
28
|
+
}
|
|
29
|
+
/** Never silently round persisted decimal evidence when serializing the numeric API. */
|
|
30
|
+
export function usdAmount(micros: bigint): number {
|
|
31
|
+
const value = Number(usdDecimal(micros));
|
|
32
|
+
if (value > Number.MAX_SAFE_INTEGER || usdMicros(value) !== micros)
|
|
33
|
+
throw new UsageError('METERING_UNAVAILABLE', 'The amount cannot be represented exactly by the numeric usage interface.', 503, { reason: 'decimal_precision' });
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
export function positivePart(micros: bigint): bigint { return micros > 0n ? micros : 0n; }
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { readBody, send } from '../../app/http';
|
|
3
|
+
import { usageAssert } from './errors';
|
|
4
|
+
import { authenticateUsageIssuerRequest, getUsageIdentity, usageFields, usageKey } from './identity';
|
|
5
|
+
import { getBillingRepository } from './billing-repository';
|
|
6
|
+
import type { UsageRepository } from './repository';
|
|
7
|
+
|
|
8
|
+
/** External products can use the same plan/grant implementation with explicit source ownership. */
|
|
9
|
+
export async function handleExternalBillingUsage(repository: UsageRepository, req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
|
|
10
|
+
const match = url.pathname.match(/^\/usage\/v1\/external\/billing\/accounts\/([A-Za-z0-9_.:-]+)\/(summary|grant|control)$/);
|
|
11
|
+
const plans = url.pathname === '/usage/v1/external/billing/plans';
|
|
12
|
+
if (!match && !plans) return false;
|
|
13
|
+
const identity = getUsageIdentity(repository), tokens = getBillingRepository(repository);
|
|
14
|
+
usageAssert(await tokens.ready(), 'USAGE_UNSUPPORTED', '美元套餐尚未就绪。', 503);
|
|
15
|
+
const { issuer } = await authenticateUsageIssuerRequest(identity, req, req.method === 'GET' ? 'usage:read' : 'entitlements:write');
|
|
16
|
+
if (plans) {
|
|
17
|
+
usageAssert(req.method === 'GET', 'USAGE_INVALID_INPUT', '使用只读套餐目录。', 405);
|
|
18
|
+
send(res, 200, { items: (await tokens.listPlans()).filter(plan => plan.config.serviceIds.every(id => issuer.serviceIds.includes(id))) }); return true;
|
|
19
|
+
}
|
|
20
|
+
const [, accountId, action] = match!;
|
|
21
|
+
const summary = await tokens.summary(accountId!);
|
|
22
|
+
if (req.method === 'GET' && action === 'summary') {
|
|
23
|
+
// Account ownership must be proven even when no new billing grant exists yet.
|
|
24
|
+
await identity.requireIssuerAccount(issuer, accountId!);
|
|
25
|
+
send(res, 200, summary); return true;
|
|
26
|
+
}
|
|
27
|
+
usageAssert(req.method === 'POST' && (action === 'grant' || action === 'control'), 'USAGE_INVALID_INPUT', '不支持的套餐操作。', 405);
|
|
28
|
+
const body = await readBody(req, 8192);
|
|
29
|
+
if (action === 'grant') {
|
|
30
|
+
const fields = usageFields(body, ['request_key','plan_id','expected_revision','starts_at'], ['request_key','plan_id','expected_revision']);
|
|
31
|
+
const plan = (await tokens.listPlans()).find(p => p.id === usageKey(fields.plan_id, 'plan_id'));
|
|
32
|
+
usageAssert(plan, 'USAGE_NOT_FOUND', '套餐不存在。', 404);
|
|
33
|
+
usageAssert(plan.config.serviceIds.every(id => issuer.serviceIds.includes(id)), 'USAGE_FORBIDDEN', '此来源未获准发放该套餐。', 403);
|
|
34
|
+
}
|
|
35
|
+
await identity.requireIssuerAccount(issuer, accountId!);
|
|
36
|
+
if (action === 'grant') usageAssert(issuer.permissions.includes('allowance:grant'), 'USAGE_FORBIDDEN', '开通额度还需要 allowance:grant 权限。', 403);
|
|
37
|
+
send(res, 200, action === 'grant' ? await tokens.grant(accountId!, body, `issuer:${issuer.id}`) : await tokens.control(accountId!, body, `issuer:${issuer.id}`));
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
6
|
+
test('USD HTTP: plan-wide multiplier and original price snapshot survive a plan edit', {skip:!enabled},async()=>{
|
|
7
|
+
const h=await createUsageTestHarness();try{
|
|
8
|
+
const user=await h.seedUser({grant:false}),id=randomUUID();
|
|
9
|
+
const config={mode:'credits',priceUsd:1000,multiplier:1.5,serviceIds:[h.service.id],duration:{unit:'month',count:1}};
|
|
10
|
+
assert.equal((await h.request('/admin/api/usage/billing/plans','synthetic-admin','POST',{id,label:'Synthetic',expected_revision:0,config})).status,200);
|
|
11
|
+
assert.equal((await h.request(`/admin/api/usage/billing/accounts/${user.accountId}/grant`,'synthetic-admin','POST',{request_key:randomUUID(),plan_id:id,expected_revision:0})).status,200);
|
|
12
|
+
const models=await h.request('/usage/v1/model/models',user.token);assert.deepEqual(models.body.items[0].billing_rate,{multiplier:1.5});
|
|
13
|
+
const input={operation_id:randomUUID(),messages:[{role:'user',content:'Synthetic'}]};
|
|
14
|
+
const first=await h.request('/usage/v1/model/requests',user.token,'POST',input);assert.equal(first.status,200,JSON.stringify(first.body));
|
|
15
|
+
await h.tokens.drainSettlements();
|
|
16
|
+
assert.equal((await h.request('/admin/api/usage/billing/plans','synthetic-admin','POST',{id,label:'Synthetic',expected_revision:1,config:{...config,multiplier:2}})).status,200);
|
|
17
|
+
const replay=await h.request('/usage/v1/model/requests',user.token,'POST',input);
|
|
18
|
+
assert.equal(replay.body.reference_cost_usd,25);assert.equal(replay.body.billed_usd,37.5);assert.deepEqual(replay.body.billing_rate,first.body.billing_rate);assert.equal(h.state.calls,1);
|
|
19
|
+
const next=await h.request('/usage/v1/model/requests',user.token,'POST',{...input,operation_id:randomUUID()});await h.tokens.drainSettlements();
|
|
20
|
+
assert.equal((await h.request(`/usage/v1/model/requests/${next.body.operation_id}`,user.token)).body.billed_usd,50);
|
|
21
|
+
const summary=(await h.request('/usage/v1/model/summary',user.token)).body;assert.equal(summary.availableUsd,912.5);assert.equal(summary.consumedUsd,87.5);
|
|
22
|
+
assert.equal(summary.presentation.displayValue,'912500');
|
|
23
|
+
}finally{await h.close();}
|
|
24
|
+
});
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { billingAllowance, billingExpiry, billingPeriod, tokenUsage, validateBillingPlan } from './billing-ledger';
|
|
4
|
+
import type { BillingPlanConfig } from './billing-contracts';
|
|
5
|
+
const config: BillingPlanConfig = { mode: 'periodic', serviceIds: ['synthetic-model'], priceUsd: 1000, periodAllowanceUsd: 1000, periodUnit: 'month', duration: { unit: 'month', count: 3 }, multiplier: 1.5 };
|
|
6
|
+
test('Token plans reject turn limits and invalid units; Credits changes display only', () => {
|
|
7
|
+
assert.deepEqual(validateBillingPlan(config), config);
|
|
8
|
+
assert.throws(() => validateBillingPlan({ ...config, maxOperationsPerTurn: 8 }), /unsupported fields/);
|
|
9
|
+
assert.throws(() => validateBillingPlan({ ...config, priceUsd: 0 }), /range/);
|
|
10
|
+
assert.throws(() => validateBillingPlan({ ...config, duration: { unit: 'forever', count: 0 } }), /expiry/);
|
|
11
|
+
assert.throws(() => validateBillingPlan({ ...config, serviceIds: ['one','one'] }), /unique/);
|
|
12
|
+
assert.throws(() => validateBillingPlan({ ...config, multiplier: 0 }), /between/);
|
|
13
|
+
assert.deepEqual(tokenUsage({ inputTokens: 60, outputTokens: 40 }), { inputTokens: 60, outputTokens: 40, totalTokens: 100 });
|
|
14
|
+
assert.throws(() => tokenUsage({ inputTokens: Number.MAX_SAFE_INTEGER, outputTokens: 1 }), /range/);
|
|
15
|
+
assert.throws(() => validateBillingPlan({ ...config, displayUnit: 'credits' }), /unsupported fields/);
|
|
16
|
+
assert.throws(() => validateBillingPlan({ ...config, displayUnit: 'tokens' }), /unsupported fields/);
|
|
17
|
+
for (const field of ['quotaTokens','tokensPerCredit','modelRates']) assert.throws(() => validateBillingPlan({ ...config, [field]: 1 }), /unsupported fields/);
|
|
18
|
+
});
|
|
19
|
+
test('Calendar expiry and reset preserve grant anchor, month end, expiry and no rollover', () => {
|
|
20
|
+
const start = Date.UTC(2028, 0, 31, 12, 30, 45, 123), expiresAt = billingExpiry(start, config.duration);
|
|
21
|
+
assert.equal(expiresAt, Date.UTC(2028, 3, 30, 12, 30, 45, 123));
|
|
22
|
+
const grant = { startsAt: start, expiresAt, config };
|
|
23
|
+
assert.equal(billingPeriod(grant, Date.UTC(2028, 1, 29, 12, 30, 45, 122))!.start, start);
|
|
24
|
+
assert.deepEqual(billingPeriod(grant, Date.UTC(2028, 1, 29, 12, 30, 45, 123)), { start: Date.UTC(2028, 1, 29, 12, 30, 45, 123), end: Date.UTC(2028, 2, 31, 12, 30, 45, 123) });
|
|
25
|
+
assert.equal(billingPeriod(grant, start - 1), null);
|
|
26
|
+
assert.equal(billingPeriod(grant, expiresAt!), null);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('plan models may be empty; allowance snapshots explicitly exclude model selection', () => {
|
|
30
|
+
assert.deepEqual(validateBillingPlan({ ...config, serviceIds: [] }).serviceIds, []);
|
|
31
|
+
const { serviceIds: _models, multiplier: _multiplier, ...allowance } = config;
|
|
32
|
+
assert.deepEqual(billingAllowance(config), allowance);
|
|
33
|
+
assert.equal('serviceIds' in billingAllowance(config), false);
|
|
34
|
+
assert.notEqual(billingAllowance(config).duration, config.duration);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('periodic allowance is explicit and independent of sale price; credits have no period allowance', () => {
|
|
38
|
+
const periodic = { ...config, priceUsd: 100, periodAllowanceUsd: 20, periodUnit: 'week' as const };
|
|
39
|
+
assert.equal(validateBillingPlan(periodic).periodAllowanceUsd, 20);
|
|
40
|
+
for (const invalid of [undefined, null, 0, -1, Infinity, NaN, '20', 1_000_000_001]) {
|
|
41
|
+
assert.throws(() => validateBillingPlan({ ...periodic, periodAllowanceUsd: invalid }), /periodAllowanceUsd/);
|
|
42
|
+
}
|
|
43
|
+
assert.throws(() => validateBillingPlan({ ...periodic, periodAllowanceUsd: 0.0000000000001 }), /periodAllowanceUsd/);
|
|
44
|
+
const { periodAllowanceUsd: _allowance, periodUnit: _period, ...base } = periodic;
|
|
45
|
+
const credits = { ...base, mode: 'credits' as const };
|
|
46
|
+
assert.equal(validateBillingPlan(credits).priceUsd, 100);
|
|
47
|
+
assert.throws(() => validateBillingPlan({ ...credits, periodAllowanceUsd: 20 }), /do not accept/);
|
|
48
|
+
for (const unknown of ['periodQuotaUsd', 'maxRequests', 'maxTurns']) {
|
|
49
|
+
assert.throws(() => validateBillingPlan({ ...periodic, [unknown]: 1 }), /unsupported fields/);
|
|
50
|
+
}
|
|
51
|
+
});
|