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.
- package/README.en.md +6 -5
- package/README.md +6 -5
- package/docker-compose.images.yml +2 -2
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHANGELOG.en.md +12 -1
- package/docs/CHANGELOG.md +12 -1
- package/docs/COMPATIBILITY.en.md +4 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- 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 +5 -1
- package/docs/README.md +4 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
- package/docs/RELEASE_NOTES_NEXT.md +4 -2
- package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.0.md +45 -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 +4 -0
- package/package.json +1 -1
- package/scripts/check-doc-links.mjs +4 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +1 -0
- package/scripts/sdk-runtime-test.mjs +6 -0
- package/scripts/verify-billing-install-upgrade.mjs +225 -0
- package/scripts/verify-github-repo.mjs +1 -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/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/app/auth.ts +2 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/infrastructure/config/configstore.ts +6 -0
- 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-billing-usage.ts +73 -0
- package/src/routes/admin-usage.ts +147 -0
- package/src/routes/admin.ts +4 -0
- package/src/routes/private.ts +8 -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-Bf7sUUs_.js → AgentClients-VInbD7JS.js} +1 -1
- package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
- package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
- package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-34qUPHf0.js} +1 -1
- package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-BbVgkSm2.js} +1 -1
- package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-DgscF28e.js} +1 -1
- package/web/console/assets/{Channels-B9n4fbxg.js → Channels-Bp-yuk8d.js} +1 -1
- package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-C9Ft60TS.js} +1 -1
- package/web/console/assets/{Clients-CI3DBDHf.js → Clients-NPldD-DD.js} +1 -1
- package/web/console/assets/{Cost-JgNXQPlN.js → Cost-DZcuB-EB.js} +1 -1
- package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-RTT7N6zl.js} +1 -1
- package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-_LeK8cce.js} +1 -1
- package/web/console/assets/{Executors-CRbboOCZ.js → Executors-Bi7H8rIm.js} +1 -1
- package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
- package/web/console/assets/{Kb-CgLNGjRp.js → Kb-BHamz8NP.js} +2 -2
- package/web/console/assets/{Login-C52JmXzx.js → Login-C1rJR-6w.js} +1 -1
- package/web/console/assets/{Projects-CDOvHPVS.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-DYNDXsqk.js → Runs-B_fa_BlD.js} +1 -1
- package/web/console/assets/{Setup-B91P6i1x.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-DkuDM0oX.js → StorageBuckets-DlG3ojhA.js} +1 -1
- package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-DYo2gg6d.js} +1 -1
- package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-DKCoUZlq.js} +1 -1
- package/web/console/assets/{Targets-CuuIYeZO.js → Targets-CdkG6BPR.js} +1 -1
- package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DVpCt0ox.js} +1 -1
- 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-DeGya810.js → request-DLsP1_ot.js} +1 -1
- package/web/console/assets/{schema-BqlqLw1R.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/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 +22 -5
- package/web-admin/src/pages/Accounts.vue +3 -3
- package/web-admin/src/pages/AgentTasks.vue +2 -2
- package/web-admin/src/pages/Routes.vue +5 -1
- package/web-admin/src/pages/Usage.vue +2470 -0
- package/web-admin/src/pages/UsageAccess.vue +1147 -0
- package/web-admin/src/router.ts +8 -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-BRCR3O0P.js +0 -3
- package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
- package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
- package/web/console/assets/Routes-DkMIjMQA.css +0 -1
- package/web/console/assets/Routes-X9vHLpKW.js +0 -124
- package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
- package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
- package/web/console/assets/index-UGvfF3Xr.js +0 -2
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
import type { ProviderFailure, ProviderDiagnostic } from './provider-failure';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import type { Pool, PoolConnection, RowDataPacket } from 'mysql2/promise';
|
|
4
|
+
import type { UsageActor } from './contracts';
|
|
5
|
+
import { UsageError, usageAssert } from './errors';
|
|
6
|
+
import { assertKnownFields, integer } from './validation';
|
|
7
|
+
import { operationIdKey, usageHash, type UsageRepository } from './repository';
|
|
8
|
+
import { billingAllowanceUsd, billingAllowance, tokenBillingRate, billingExpiry, billingKey, billingPeriod, tokenUsage, validateBillingPlan, billedUsdMicros } from './billing-ledger';
|
|
9
|
+
import { positivePart, usdAmount, usdDecimal, usdMicros } from './billing-decimal';
|
|
10
|
+
import { calculateReferenceCost } from './pricing';
|
|
11
|
+
import { usagePresentation } from './billing-presentation';
|
|
12
|
+
import type { BillingAdmissionInput, BillingCompletionInput, BillingGrant, BillingPlan, BillingRequest, BillingSummary, BillingRate } from './billing-contracts';
|
|
13
|
+
|
|
14
|
+
type Row = Record<string, any>;
|
|
15
|
+
async function rows(c: Pool | PoolConnection, sql: string, params: unknown[] = []): Promise<Row[]> {
|
|
16
|
+
return (await c.query<RowDataPacket[]>(sql, params))[0];
|
|
17
|
+
}
|
|
18
|
+
function json<T>(v: unknown): T { return (typeof v === 'string' ? JSON.parse(v) : v) as T; }
|
|
19
|
+
function optionalNumber(v: unknown): number | null { return v === null || v === undefined ? null : Number(v); }
|
|
20
|
+
function plan(r: Row): BillingPlan {
|
|
21
|
+
return { id: r.id, label: r.label, revision: Number(r.revision), state: r.state, config: validateBillingPlan(json(r.config_json)), createdAt: Number(r.created_at), updatedAt: Number(r.updated_at) };
|
|
22
|
+
}
|
|
23
|
+
function grant(r: Row): BillingGrant {
|
|
24
|
+
return { id: r.id, accountId: r.account_id, planId: r.plan_id, planRevision: Number(r.plan_revision), label: r.label,
|
|
25
|
+
revision: Number(r.revision), state: r.state, sourceOwner: r.source_owner, startsAt: Number(r.starts_at), expiresAt: optionalNumber(r.expires_at), config: billingAllowance(json(r.config_json)) };
|
|
26
|
+
}
|
|
27
|
+
function request(r: Row): BillingRequest {
|
|
28
|
+
const rate = json<BillingRate>(r.billing_rate_json);
|
|
29
|
+
usageAssert(rate, 'METERING_UNAVAILABLE', 'The original price snapshot is unavailable.', 503);
|
|
30
|
+
return { id: r.id, operationId: r.operation_id, accountId: r.account_id, userId: r.user_id, sessionId: r.session_id,
|
|
31
|
+
serviceId: r.service_id, conversationId: r.conversation_id, turnId: r.turn_id, requestHash: r.request_hash,
|
|
32
|
+
revision: Number(r.revision), state: r.state, resultState: r.result_state, billingState: r.billing_state,
|
|
33
|
+
serviceConfig: json(r.service_json), serviceRevision: Number(r.service_revision), model: r.model, fence: r.fence,
|
|
34
|
+
billingRate: tokenBillingRate(rate.planId, rate.planRevision, rate.multiplier, rate.price),
|
|
35
|
+
grantId: r.grant_id, grantRevision: Number(r.grant_revision), grantConfig: billingAllowance(json(r.grant_json)),
|
|
36
|
+
periodStart: Number(r.period_start), periodEnd: optionalNumber(r.period_end), response: json(r.result_json), resultHash: r.result_hash, usage: json(r.usage_json),
|
|
37
|
+
rawUsage: json(r.raw_usage_json), referenceCostUsd: r.reference_cost_usd == null ? null : usdAmount(usdMicros(r.reference_cost_usd)),
|
|
38
|
+
billedUsd: r.billed_usd == null ? null : usdAmount(usdMicros(r.billed_usd)), overageUsd: r.overage_usd == null ? null : usdAmount(usdMicros(r.overage_usd)), cancelledAt: optionalNumber(r.cancelled_at),
|
|
39
|
+
createdAt: Number(r.created_at), updatedAt: Number(r.updated_at) };
|
|
40
|
+
}
|
|
41
|
+
function label(value: unknown): string {
|
|
42
|
+
usageAssert(typeof value === 'string' && value.trim().length > 0 && value.length <= 191 && !/[\x00-\x1f\x7f]/.test(value), 'USAGE_INVALID_INPUT', 'A short display label is required.', 400);
|
|
43
|
+
return value.trim();
|
|
44
|
+
}
|
|
45
|
+
/** Provider usage can contain extension fields; the public result exposes metering only. */
|
|
46
|
+
function publicRawUsage(raw: Record<string, unknown> | null): Record<string, unknown> | null {
|
|
47
|
+
if (!raw) return null;
|
|
48
|
+
const numbers = ['inputTokens','outputTokens','totalTokens','prompt_tokens','completion_tokens','total_tokens','input_tokens','output_tokens',
|
|
49
|
+
'cachedInputTokens','cacheWriteTokens','prompt_cache_hit_tokens','prompt_cache_miss_tokens','cache_creation_input_tokens','requestCount','webSearchCount',
|
|
50
|
+
'inputImageCount','outputImageCount','inputImageTokens','outputImageTokens','inputPixelCount','outputPixelCount','outputWidth','outputHeight','seconds'];
|
|
51
|
+
const out: Record<string, unknown> = {};
|
|
52
|
+
for (const key of numbers) if (typeof raw[key] === 'number' && Number.isFinite(raw[key]) && (raw[key] as number) >= 0) out[key] = raw[key];
|
|
53
|
+
for (const key of ['inputVariant','outputVariant']) if (typeof raw[key] === 'string' && /^[a-zA-Z0-9_.:-]{1,64}$/.test(raw[key])) out[key] = raw[key];
|
|
54
|
+
for (const key of ['prompt_tokens_details','completion_tokens_details','input_tokens_details','output_tokens_details']) {
|
|
55
|
+
const details = raw[key];
|
|
56
|
+
if (details && typeof details === 'object' && !Array.isArray(details)) {
|
|
57
|
+
const safe = Object.fromEntries(Object.entries(details).filter(([name,value]) => /^[a-z_]+tokens$/.test(name) && typeof value === 'number' && Number.isFinite(value) && value >= 0));
|
|
58
|
+
if (Object.keys(safe).length) out[key] = safe;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
const RESULT_RETENTION_MS = 7 * 86_400_000;
|
|
64
|
+
|
|
65
|
+
/** Current plan models share the account grant's original allowance and periods. */
|
|
66
|
+
export class BillingRepository {
|
|
67
|
+
constructor(readonly repository: UsageRepository) {}
|
|
68
|
+
async configurationReady(): Promise<boolean> { return this.schemaReady(); }
|
|
69
|
+
async ready(): Promise<boolean> { return this.schemaReady(); }
|
|
70
|
+
private async schemaReady(): Promise<boolean> {
|
|
71
|
+
const required: Record<string, string[]> = {
|
|
72
|
+
bz_usage_billing_plans: ['id','revision','config_json'], bz_usage_billing_grants: ['id','source_owner','revision','config_json'],
|
|
73
|
+
bz_usage_billing_heads: ['account_id','grant_id','revision'], bz_usage_billing_periods: ['grant_id','period_start','consumed_usd'],
|
|
74
|
+
bz_usage_billing_requests: ['id','request_hash','fence','billing_state','result_state','execution_key','grant_json','cancelled_at','billing_rate_json','reference_cost_usd'],
|
|
75
|
+
bz_usage_billing_ledger: ['request_id','reference_cost_usd','billed_usd','overage_usd'], bz_usage_sessions: ['model_access'],
|
|
76
|
+
bz_usage_price_snapshots: ['cache_key','snapshot_json','fetched_at'],
|
|
77
|
+
};
|
|
78
|
+
try {
|
|
79
|
+
const found = await rows(this.repository.getPool(), 'SELECT table_name,column_name,data_type,numeric_scale,is_nullable FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name IN (?)', [Object.keys(required)]);
|
|
80
|
+
const columns = new Set(found.map(r => `${r.TABLE_NAME ?? r.table_name}.${r.COLUMN_NAME ?? r.column_name}`));
|
|
81
|
+
const decimalColumns = ['bz_usage_billing_periods.allowance_usd','bz_usage_billing_periods.consumed_usd','bz_usage_billing_requests.reference_cost_usd','bz_usage_billing_ledger.reference_cost_usd','bz_usage_billing_requests.billed_usd','bz_usage_billing_requests.overage_usd','bz_usage_billing_ledger.billed_usd','bz_usage_billing_ledger.overage_usd'];
|
|
82
|
+
return Object.entries(required).every(([table, fields]) => fields.every(field => columns.has(`${table}.${field}`)))
|
|
83
|
+
&& (decimalColumns.every(column => found.some(r => `${r.TABLE_NAME ?? r.table_name}.${r.COLUMN_NAME ?? r.column_name}` === column
|
|
84
|
+
&& (r.DATA_TYPE ?? r.data_type) === 'decimal' && Number(r.NUMERIC_SCALE ?? r.numeric_scale) === 12))
|
|
85
|
+
&& ['billing_rate_json'].every(column => found.some(r => (r.TABLE_NAME ?? r.table_name) === 'bz_usage_billing_requests'
|
|
86
|
+
&& (r.COLUMN_NAME ?? r.column_name) === column && (r.IS_NULLABLE ?? r.is_nullable) === 'NO')));
|
|
87
|
+
} catch (e) {
|
|
88
|
+
if (['ER_NO_SUCH_TABLE','ER_BAD_DB_ERROR'].includes(String((e as { code?: string }).code))) return false;
|
|
89
|
+
throw new UsageError('USAGE_UNAVAILABLE', 'Billing readiness is unavailable.', 503);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
private async now(c: PoolConnection): Promise<number> {
|
|
93
|
+
return Number((await rows(c, 'SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) AS ms'))[0]!.ms);
|
|
94
|
+
}
|
|
95
|
+
private async lockAccount(c: PoolConnection, accountId: string): Promise<Row> {
|
|
96
|
+
const a = (await rows(c, 'SELECT * FROM bz_usage_accounts WHERE id=? FOR UPDATE', [billingKey(accountId, 'accountId', 64)]))[0];
|
|
97
|
+
usageAssert(a, 'USAGE_ACCOUNT_NOT_FOUND', 'Account not found.', 404);
|
|
98
|
+
usageAssert(a.state !== 'deleted', 'USAGE_RESOURCE_DELETED', '账户已删除,不能恢复或重新关联。'); return a;
|
|
99
|
+
}
|
|
100
|
+
private async currentGrant(c: Pool | PoolConnection, accountId: string, lock = false): Promise<BillingGrant | null> {
|
|
101
|
+
const r = (await rows(c, `SELECT g.* FROM bz_usage_billing_heads h JOIN bz_usage_billing_grants g ON g.id=h.grant_id WHERE h.account_id=?${lock ? ' FOR UPDATE' : ''}`, [accountId]))[0];
|
|
102
|
+
return r ? grant(r) : null;
|
|
103
|
+
}
|
|
104
|
+
private async mutate<T>(c: PoolConnection, domain: string, key: string, input: unknown, fn: () => Promise<T>): Promise<T> {
|
|
105
|
+
const changeKey = usageHash(['billing', domain, billingKey(key, 'request_key')]), hash = usageHash(input);
|
|
106
|
+
const old = (await rows(c, 'SELECT * FROM bz_usage_changes WHERE change_key=? FOR UPDATE', [changeKey]))[0];
|
|
107
|
+
if (old) { usageAssert(old.request_hash === hash, 'USAGE_IDEMPOTENCY_CONFLICT', 'This request key has different input.'); return json<T>(old.result_json); }
|
|
108
|
+
const result = await fn();
|
|
109
|
+
await c.query('INSERT INTO bz_usage_changes(change_key,request_hash,result_json,created_at) VALUES(?,?,?,?)', [changeKey, hash, JSON.stringify(result), await this.now(c)]);
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
async listPlans(): Promise<BillingPlan[]> {
|
|
113
|
+
return (await rows(this.repository.getPool(), 'SELECT * FROM bz_usage_billing_plans WHERE state<>\'deleted\' ORDER BY updated_at DESC,id LIMIT 500')).map(plan);
|
|
114
|
+
}
|
|
115
|
+
async putPlan(value: unknown): Promise<BillingPlan> {
|
|
116
|
+
assertKnownFields(value, ['id','label','expected_revision','state','config'], 'USD plan');
|
|
117
|
+
const b = value as Row, id = billingKey(b.id), title = label(b.label), revision = integer(b.expected_revision, 'expected_revision');
|
|
118
|
+
const config = validateBillingPlan(b.config);
|
|
119
|
+
usageAssert(b.state === undefined || ['active','suspended'].includes(b.state), 'USAGE_INVALID_INPUT', 'Invalid plan state.', 400);
|
|
120
|
+
return this.repository.withTransaction(async c => {
|
|
121
|
+
const old = (await rows(c, 'SELECT * FROM bz_usage_billing_plans WHERE id=? FOR UPDATE', [id]))[0];
|
|
122
|
+
usageAssert(old?.state !== 'deleted', 'USAGE_RESOURCE_DELETED', '套餐已删除,新增套餐请使用新的标识。');
|
|
123
|
+
usageAssert(Number(old?.revision ?? 0) === revision, 'USAGE_REVISION_CONFLICT', 'Plan changed; refresh before saving.');
|
|
124
|
+
for (const serviceId of [...config.serviceIds].sort()) {
|
|
125
|
+
const service = (await rows(c, "SELECT id FROM bz_usage_services WHERE id=? AND state<>'deleted' FOR SHARE", [serviceId]))[0];
|
|
126
|
+
usageAssert(service, 'USAGE_SERVICE_NOT_FOUND', 'A selected model service does not exist.', 404);
|
|
127
|
+
}
|
|
128
|
+
const now = await this.now(c);
|
|
129
|
+
const out: BillingPlan = { id, label: title, revision: revision + 1, state: b.state ?? old?.state ?? 'active', config, createdAt: Number(old?.created_at ?? now), updatedAt: now };
|
|
130
|
+
await c.query('INSERT INTO bz_usage_billing_plans(id,label,revision,state,config_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE label=VALUES(label),revision=VALUES(revision),state=VALUES(state),config_json=VALUES(config_json),updated_at=VALUES(updated_at)',
|
|
131
|
+
[id, title, out.revision, out.state, JSON.stringify(config), out.createdAt, now]);
|
|
132
|
+
return out;
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
async grant(accountId: string, value: unknown, sourceOwner = 'hub'): Promise<BillingGrant> {
|
|
136
|
+
assertKnownFields(value, ['request_key','plan_id','expected_revision','starts_at'], 'Token grant');
|
|
137
|
+
const b = value as Row, requestKey = billingKey(b.request_key), planId = billingKey(b.plan_id), expectedRevision = integer(b.expected_revision, 'expected_revision');
|
|
138
|
+
billingKey(sourceOwner, 'sourceOwner');
|
|
139
|
+
if (b.starts_at !== undefined) integer(b.starts_at, 'starts_at');
|
|
140
|
+
return this.repository.withTransaction(async c => {
|
|
141
|
+
const account = await this.lockAccount(c, accountId);
|
|
142
|
+
usageAssert(account.state === 'active', 'USAGE_ACCOUNT_SUSPENDED', 'Account is suspended.', 403);
|
|
143
|
+
if (sourceOwner.startsWith('issuer:')) {
|
|
144
|
+
const issuer = (await rows(c, 'SELECT state FROM bz_usage_issuers WHERE id=? FOR SHARE', [sourceOwner.slice(7)]))[0];
|
|
145
|
+
usageAssert(issuer?.state === 'active', 'USAGE_ISSUER_REQUIRED', '原身份来源已停用或删除,不能发放新的额度。', 401);
|
|
146
|
+
}
|
|
147
|
+
const result = await this.mutate(c, `grant:${accountId}:${sourceOwner}`, requestKey, b, async () => {
|
|
148
|
+
const old = await this.currentGrant(c, accountId, true);
|
|
149
|
+
usageAssert((old?.revision ?? 0) === expectedRevision, 'USAGE_REVISION_CONFLICT', 'Account plan changed; refresh before granting.');
|
|
150
|
+
usageAssert(!old || old.sourceOwner === sourceOwner, 'USAGE_SOURCE_CONFLICT', 'Another source owns this account plan.', 403);
|
|
151
|
+
const p = (await rows(c, 'SELECT * FROM bz_usage_billing_plans WHERE id=? FOR SHARE', [planId]))[0];
|
|
152
|
+
usageAssert(p?.state === 'active', 'SERVICE_NOT_ENTITLED', 'The selected plan is not active.', 403);
|
|
153
|
+
const planConfig = validateBillingPlan(json(p.config_json)), config = billingAllowance(planConfig), now = await this.now(c), startsAt = b.starts_at ?? now;
|
|
154
|
+
await this.requireAvailableServiceIdentities(c, planConfig.serviceIds);
|
|
155
|
+
const out: BillingGrant = { id: randomUUID(), accountId, planId, planRevision: Number(p.revision), label: p.label, revision: expectedRevision + 1, state: 'active', sourceOwner,
|
|
156
|
+
startsAt, expiresAt: billingExpiry(startsAt, config.duration), config };
|
|
157
|
+
await c.query('INSERT INTO bz_usage_billing_grants(id,account_id,plan_id,plan_revision,label,revision,state,source_owner,starts_at,expires_at,config_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
|
158
|
+
[out.id, accountId, planId, out.planRevision, out.label, out.revision, out.state, sourceOwner, startsAt, out.expiresAt, JSON.stringify(config), now, now]);
|
|
159
|
+
await c.query('INSERT INTO bz_usage_billing_heads(account_id,grant_id,revision) VALUES(?,?,?) ON DUPLICATE KEY UPDATE grant_id=VALUES(grant_id),revision=VALUES(revision)', [accountId, out.id, out.revision]);
|
|
160
|
+
return out;
|
|
161
|
+
});
|
|
162
|
+
return { ...result, config: billingAllowance(result.config) };
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/** Issue a fresh allowance window without erasing prior consumption or extending expiry. */
|
|
166
|
+
async resetAllowance(accountId: string, value: unknown, actor: string): Promise<BillingGrant> {
|
|
167
|
+
assertKnownFields(value, ['request_key','expected_revision'], 'Allowance reset');
|
|
168
|
+
const b = value as Row, requestKey = billingKey(b.request_key), expectedRevision = integer(b.expected_revision, 'expected_revision', 1);
|
|
169
|
+
label(actor);
|
|
170
|
+
return this.repository.withTransaction(async c => {
|
|
171
|
+
const account = await this.lockAccount(c, accountId);
|
|
172
|
+
usageAssert(account.state === 'active', 'USAGE_ACCOUNT_SUSPENDED', '请先启用账户。', 403);
|
|
173
|
+
return this.mutate(c, `reset:${accountId}`, requestKey, { ...b, actor }, async () => {
|
|
174
|
+
const old = await this.currentGrant(c, accountId, true), now = await this.now(c);
|
|
175
|
+
usageAssert(old, 'SERVICE_NOT_ENTITLED', '账户尚未开通套餐。', 403);
|
|
176
|
+
usageAssert(old.sourceOwner === 'hub', 'USAGE_SOURCE_CONFLICT', '此额度由业务后端维护,请在原来源调整。', 403);
|
|
177
|
+
usageAssert(old.revision === expectedRevision, 'USAGE_REVISION_CONFLICT', '账户套餐已更新,请刷新后重置。');
|
|
178
|
+
usageAssert(old.state === 'active' && billingPeriod(old, now), 'SERVICE_NOT_ENTITLED', '只能重置已经生效且未暂停、未到期的套餐。', 403);
|
|
179
|
+
usageAssert(await this.currentPlan(c, old.planId), 'SERVICE_NOT_ENTITLED', '原套餐已删除,请先开通有效套餐。', 403);
|
|
180
|
+
// The new pool is independent even for resets in the same millisecond.
|
|
181
|
+
// Original dispatched requests retain their immutable grant and period.
|
|
182
|
+
const out = { ...old, id: randomUUID(), revision: old.revision + 1, startsAt: now,
|
|
183
|
+
reset: { previousGrantId: old.id, actor, at: now } };
|
|
184
|
+
await c.query('INSERT INTO bz_usage_billing_grants(id,account_id,plan_id,plan_revision,label,revision,state,source_owner,starts_at,expires_at,config_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
|
185
|
+
[out.id, accountId, out.planId, out.planRevision, out.label, out.revision, out.state, out.sourceOwner, now, out.expiresAt, JSON.stringify(out.config), now, now]);
|
|
186
|
+
await c.query('UPDATE bz_usage_billing_heads SET grant_id=?,revision=? WHERE account_id=?', [out.id, out.revision, accountId]);
|
|
187
|
+
return out;
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
async control(accountId: string, value: unknown, sourceOwner = 'hub'): Promise<BillingGrant> {
|
|
192
|
+
assertKnownFields(value, ['request_key','expected_revision','state'], 'Token control');
|
|
193
|
+
const b = value as Row, expectedRevision = integer(b.expected_revision, 'expected_revision');
|
|
194
|
+
billingKey(sourceOwner, 'sourceOwner'); billingKey(b.request_key, 'request_key');
|
|
195
|
+
usageAssert(['active','suspended'].includes(b.state), 'USAGE_INVALID_INPUT', 'Invalid plan state.', 400);
|
|
196
|
+
return this.repository.withTransaction(async c => {
|
|
197
|
+
const account = await this.lockAccount(c, accountId);
|
|
198
|
+
usageAssert(account.state !== 'archived', 'USAGE_ACCOUNT_SUSPENDED', '账户已移除,请先恢复原账户。', 403);
|
|
199
|
+
const result = await this.mutate(c, `control:${accountId}:${sourceOwner}`, b.request_key, b, async () => {
|
|
200
|
+
const old = await this.currentGrant(c, accountId, true);
|
|
201
|
+
usageAssert(old, 'SERVICE_NOT_ENTITLED', 'No plan.', 403);
|
|
202
|
+
usageAssert(old.sourceOwner === sourceOwner, 'USAGE_SOURCE_CONFLICT', 'Another source owns this account plan.', 403);
|
|
203
|
+
usageAssert(old.revision === expectedRevision, 'USAGE_REVISION_CONFLICT', 'Account plan changed; refresh before changing state.');
|
|
204
|
+
if (b.state === 'active') usageAssert(await this.currentPlan(c, old.planId), 'SERVICE_NOT_ENTITLED', '原套餐已删除,请重新开通可用套餐。', 403);
|
|
205
|
+
await c.query('UPDATE bz_usage_billing_grants SET state=?,revision=revision+1,updated_at=? WHERE id=?', [b.state, await this.now(c), old.id]);
|
|
206
|
+
await c.query('UPDATE bz_usage_billing_heads SET revision=revision+1 WHERE account_id=?', [accountId]);
|
|
207
|
+
return { ...old, revision: old.revision + 1, state: b.state };
|
|
208
|
+
});
|
|
209
|
+
return { ...result, config: billingAllowance(result.config) };
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
private async requireAvailableServiceIdentities(c: PoolConnection, serviceIds: string[]): Promise<void> {
|
|
213
|
+
for (const id of [...serviceIds].sort()) {
|
|
214
|
+
const service = (await rows(c, "SELECT id FROM bz_usage_services WHERE id=? AND state<>'deleted' FOR SHARE", [id]))[0];
|
|
215
|
+
usageAssert(service, 'USAGE_SERVICE_NOT_FOUND', '套餐引用的模型服务已删除,请先调整套餐。', 404);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async summary(accountId: string): Promise<BillingSummary> {
|
|
219
|
+
return this.repository.withTransaction(async c => {
|
|
220
|
+
const a = await this.lockAccount(c, accountId), g = await this.currentGrant(c, accountId), now = await this.now(c);
|
|
221
|
+
integer(now, 'now');
|
|
222
|
+
const currentPlan = g ? await this.currentPlan(c, g.planId) : null;
|
|
223
|
+
const period = g ? billingPeriod(g, now) : null;
|
|
224
|
+
const aggregate = g ? (await rows(c, 'SELECT COALESCE(SUM(consumed_usd),0) AS total,COALESCE(SUM(CASE WHEN period_start=? THEN consumed_usd ELSE 0 END),0) AS current FROM bz_usage_billing_periods WHERE grant_id=?', [period?.start ?? -1, g.id]))[0]! : { total: 0, current: 0 };
|
|
225
|
+
const consumed = usdMicros(aggregate.current), quota = g ? usdMicros(billingAllowanceUsd(g.config)) : 0n, active = a.state === 'active' && g?.state === 'active' && currentPlan && period;
|
|
226
|
+
const pending = Number((await rows(c, "SELECT COUNT(*) AS n FROM bz_usage_billing_requests WHERE account_id=? AND billing_state='pending'", [accountId]))[0]!.n);
|
|
227
|
+
const available = active ? positivePart(quota - consumed) : 0n, availableUsd = usdAmount(available);
|
|
228
|
+
return { schema: 'bailing.billing-summary.v1', accountId, grant: g, plan: currentPlan, availableUsd,
|
|
229
|
+
consumedUsd: usdAmount(usdMicros(aggregate.total)), currentPeriodConsumedUsd: usdAmount(consumed), overageUsd: g && period ? usdAmount(positivePart(consumed - quota)) : 0,
|
|
230
|
+
resetAt: g?.config.mode === 'periodic' && period && period.end !== g.expiresAt ? period.end : null, expiresAt: g?.expiresAt ?? null, pendingRequests: pending,
|
|
231
|
+
presentation: usagePresentation(a.state, g, usdDecimal(available), now) };
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
private async currentPlan(c: PoolConnection, planId: string): Promise<BillingSummary['plan']> {
|
|
235
|
+
const row = (await rows(c, 'SELECT id,label,revision,config_json FROM bz_usage_billing_plans WHERE id=? AND state<>\'deleted\' FOR SHARE', [planId]))[0];
|
|
236
|
+
if (!row) return null;
|
|
237
|
+
const config = validateBillingPlan(json(row.config_json));
|
|
238
|
+
return { id: row.id, label: row.label, revision: Number(row.revision), serviceIds: config.serviceIds, multiplier: config.multiplier };
|
|
239
|
+
}
|
|
240
|
+
private async requirePlanService(c: PoolConnection, grant: BillingGrant, serviceId: string): Promise<NonNullable<BillingSummary['plan']>> {
|
|
241
|
+
const plan = await this.currentPlan(c, grant.planId);
|
|
242
|
+
if (!plan?.serviceIds.includes(serviceId)) throw new UsageError('SERVICE_NOT_ENTITLED', 'This model is not included in the current plan.', 403, { next_action: 'select_model' });
|
|
243
|
+
return plan;
|
|
244
|
+
}
|
|
245
|
+
private async scope(c: PoolConnection, actor: UsageActor, serviceId: string): Promise<void> {
|
|
246
|
+
await this.repository.validateActor(c, actor);
|
|
247
|
+
const s = (await rows(c, 'SELECT service_id,model_access FROM bz_usage_sessions WHERE id=? FOR SHARE', [actor.sessionId]))[0];
|
|
248
|
+
usageAssert(s && (s.model_access === 'token_gateway' || s.service_id === serviceId),
|
|
249
|
+
'USAGE_ACCOUNT_FORBIDDEN', 'The original usage credential does not permit this model service.', 403);
|
|
250
|
+
}
|
|
251
|
+
async findRequest(actor: UsageActor, operationId: string): Promise<BillingRequest | null> {
|
|
252
|
+
billingKey(operationId, 'operation_id');
|
|
253
|
+
const found = await this.repository.withTransaction(async c => {
|
|
254
|
+
await this.lockAccount(c, actor.accountId); await this.repository.validateActor(c, actor);
|
|
255
|
+
const r = (await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [operationIdKey(actor, operationId)]))[0];
|
|
256
|
+
if (!r) return null;
|
|
257
|
+
await this.scope(c, actor, r.service_id); return request(r);
|
|
258
|
+
});
|
|
259
|
+
// Reads and original-result recovery never wait for financial aggregation.
|
|
260
|
+
return found;
|
|
261
|
+
}
|
|
262
|
+
async listRequests(accountId: string, options: { limit?: number; cursor?: string | null } = {}) {
|
|
263
|
+
billingKey(accountId, 'accountId', 64); const limit = integer(options.limit ?? 30, 'limit', 1, 100);
|
|
264
|
+
const cursor = options.cursor ? billingKey(options.cursor, 'cursor', 64) : null;
|
|
265
|
+
const anchor = cursor ? (await rows(this.repository.getPool(), 'SELECT created_at FROM bz_usage_billing_requests WHERE account_id=? AND id=?', [accountId, cursor]))[0] : null;
|
|
266
|
+
usageAssert(!cursor || anchor, 'USAGE_INVALID_INPUT', 'Invalid request cursor for this account.', 400);
|
|
267
|
+
const page = await rows(this.repository.getPool(), `SELECT * FROM bz_usage_billing_requests WHERE account_id=?${cursor ? ' AND (created_at<? OR (created_at=? AND id<?))' : ''} ORDER BY created_at DESC,id DESC LIMIT ?`, [accountId, ...(cursor ? [anchor!.created_at, anchor!.created_at, cursor] : []), limit + 1]);
|
|
268
|
+
return { items: page.slice(0, limit).map(r => this.view(request(r))), next_cursor: page.length > limit ? String(page[limit - 1]!.id) : null };
|
|
269
|
+
}
|
|
270
|
+
async admit(i: BillingAdmissionInput): Promise<BillingRequest> {
|
|
271
|
+
billingKey(i.operationId, 'operation_id'); billingKey(i.serviceId, 'service_id');
|
|
272
|
+
if (i.conversationId !== null) billingKey(i.conversationId, 'conversation_id');
|
|
273
|
+
if (i.turnId !== null) billingKey(i.turnId, 'turn_id');
|
|
274
|
+
usageAssert(typeof i.requestHash === 'string' && /^[a-f0-9]{64}$/.test(i.requestHash), 'USAGE_INVALID_INPUT', 'Invalid request hash.', 400);
|
|
275
|
+
return this.repository.withTransaction(async c => {
|
|
276
|
+
await this.lockAccount(c, i.actor.accountId); await this.scope(c, i.actor, i.serviceId);
|
|
277
|
+
const id = operationIdKey(i.actor, i.operationId), prior = (await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=? FOR UPDATE', [id]))[0];
|
|
278
|
+
if (prior) {
|
|
279
|
+
usageAssert(prior.request_hash === i.requestHash && prior.service_id === i.serviceId && prior.conversation_id === i.conversationId && prior.turn_id === i.turnId,
|
|
280
|
+
'USAGE_IDEMPOTENCY_CONFLICT', 'The original operation ID has different input.');
|
|
281
|
+
return { ...request(prior), created: false };
|
|
282
|
+
}
|
|
283
|
+
const now = await this.now(c), g = await this.currentGrant(c, i.actor.accountId, true);
|
|
284
|
+
usageAssert(g && g.state === 'active', 'SERVICE_NOT_ENTITLED', 'No active plan.', 403);
|
|
285
|
+
const period = billingPeriod(g, now);
|
|
286
|
+
usageAssert(period, 'SUBSCRIPTION_EXPIRED', 'The plan is not currently valid.', 403);
|
|
287
|
+
const plan = await this.requirePlanService(c, g, i.serviceId);
|
|
288
|
+
const billingRate = tokenBillingRate(plan.id, plan.revision, plan.multiplier, i.priceSnapshot);
|
|
289
|
+
const service = (await rows(c, 'SELECT * FROM bz_usage_services WHERE id=? FOR SHARE', [i.serviceId]))[0];
|
|
290
|
+
usageAssert(service?.state === 'active', 'METERING_UNAVAILABLE', 'Model service is unavailable.', 503);
|
|
291
|
+
usageAssert(Number(service.revision) === i.expectedServiceRevision && usageHash(json(service.config_json)) === usageHash(i.serviceConfig)
|
|
292
|
+
&& json<{ model: string }>(service.config_json).model === i.model, 'USAGE_REVISION_CONFLICT', 'Model service changed; reload its configuration.');
|
|
293
|
+
await c.query('INSERT IGNORE INTO bz_usage_billing_periods(grant_id,period_start,period_end,allowance_usd,consumed_usd) VALUES(?,?,?,?,0)', [g.id, period.start, period.end, billingAllowanceUsd(g.config)]);
|
|
294
|
+
const pool = (await rows(c, 'SELECT * FROM bz_usage_billing_periods WHERE grant_id=? AND period_start=? FOR UPDATE', [g.id, period.start]))[0]!;
|
|
295
|
+
if (usdMicros(pool.consumed_usd) >= usdMicros(billingAllowanceUsd(g.config))) throw new UsageError(g.config.mode === 'periodic' ? 'QUOTA_WINDOW_EXHAUSTED' : 'ALLOWANCE_INSUFFICIENT', 'The allowance is exhausted. Current replies may finish; no new model request was sent.', 402, { resetAt: g.config.mode === 'periodic' ? period.end : null });
|
|
296
|
+
await c.query(`INSERT INTO bz_usage_billing_requests(id,operation_id,account_id,user_id,session_id,service_id,conversation_id,turn_id,request_hash,revision,state,result_state,billing_state,service_revision,service_json,model,grant_id,grant_revision,grant_json,billing_rate_json,period_start,period_end,created_at,updated_at)
|
|
297
|
+
VALUES(?,?,?,?,?,?,?,?,?,1,'admitted','pending','pending',?,?,?,?,?,?,?,?,?,?,?)`,
|
|
298
|
+
[id, i.operationId, i.actor.accountId, i.actor.userId, i.actor.sessionId, i.serviceId, i.conversationId, i.turnId, i.requestHash,
|
|
299
|
+
i.expectedServiceRevision, JSON.stringify(i.serviceConfig), i.model, g.id, g.revision, JSON.stringify(g.config), JSON.stringify(billingRate), period.start, period.end, now, now]);
|
|
300
|
+
return { ...request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [id]))[0]!), created: true };
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
private async locked(c: PoolConnection, id: string): Promise<Row> {
|
|
304
|
+
const hint = (await rows(c, 'SELECT account_id FROM bz_usage_billing_requests WHERE id=?', [billingKey(id)]))[0];
|
|
305
|
+
usageAssert(hint, 'USAGE_OPERATION_NOT_FOUND', 'Original model request not found.', 404);
|
|
306
|
+
await this.lockAccount(c, hint.account_id);
|
|
307
|
+
return (await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=? FOR UPDATE', [id]))[0]!;
|
|
308
|
+
}
|
|
309
|
+
async commitDispatch(id: string, actor: UsageActor): Promise<BillingRequest> {
|
|
310
|
+
return this.repository.withTransaction(async c => {
|
|
311
|
+
const r = await this.locked(c, id);
|
|
312
|
+
usageAssert(r.account_id === actor.accountId && r.user_id === actor.userId, 'USAGE_ACCOUNT_FORBIDDEN', 'Original request belongs to another user.', 403);
|
|
313
|
+
await this.scope(c, actor, r.service_id);
|
|
314
|
+
usageAssert(r.state === 'admitted', 'USAGE_PENDING', 'This original request cannot obtain another dispatch permit.');
|
|
315
|
+
const g = await this.currentGrant(c, actor.accountId, true), now = await this.now(c);
|
|
316
|
+
usageAssert(g && g.id === r.grant_id && g.revision === Number(r.grant_revision) && g.state === 'active' && billingPeriod(g, now), 'SERVICE_NOT_ENTITLED', 'The original plan has changed or is no longer active.', 403);
|
|
317
|
+
await this.requirePlanService(c, g, r.service_id);
|
|
318
|
+
const service = (await rows(c, 'SELECT * FROM bz_usage_services WHERE id=? FOR SHARE', [r.service_id]))[0];
|
|
319
|
+
usageAssert(service?.state === 'active' && Number(service.revision) === Number(r.service_revision), 'USAGE_REVISION_CONFLICT', 'The original model configuration has changed.');
|
|
320
|
+
const fence = randomUUID();
|
|
321
|
+
await c.query("UPDATE bz_usage_billing_requests SET state='dispatch_committed',fence=?,revision=revision+1,updated_at=? WHERE id=?", [fence, now, id]);
|
|
322
|
+
return request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [id]))[0]!);
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
async recordCompletion(id: string, fence: string, input: BillingCompletionInput): Promise<BillingRequest> {
|
|
326
|
+
usageAssert(input.response && typeof input.response === 'object' && !Array.isArray(input.response), 'USAGE_INVALID_INPUT', 'A complete model result is required.', 400);
|
|
327
|
+
const measured = input.usage === undefined ? null : tokenUsage(input.usage), responseHash = usageHash(input.response);
|
|
328
|
+
// Persist the usable answer before touching the financial aggregate. A later
|
|
329
|
+
// settlement outage must not turn a completed reply into an unknown model run.
|
|
330
|
+
const recorded = await this.repository.withTransaction(async c => {
|
|
331
|
+
const r = await this.locked(c, id);
|
|
332
|
+
usageAssert(r.fence && r.fence === fence, 'USAGE_FENCE_CONFLICT', 'This result does not match the original dispatch.');
|
|
333
|
+
usageAssert(['dispatch_committed','unknown','completed','cancelled'].includes(r.state), 'USAGE_OPERATION_ENDED', 'This request was not dispatched.');
|
|
334
|
+
usageAssert(!r.result_hash || r.result_hash === responseHash, 'USAGE_RECEIPT_CONFLICT', 'The original result has different evidence.');
|
|
335
|
+
usageAssert(!r.usage_json || !measured || usageHash(json(r.usage_json)) === usageHash(measured), 'USAGE_RECEIPT_CONFLICT', 'The original usage has different evidence.');
|
|
336
|
+
const executionKey = input.executionId ? usageHash([json<{ providerScope: string }>(r.service_json).providerScope, input.executionId]) : null;
|
|
337
|
+
if (executionKey) {
|
|
338
|
+
const owner = (await rows(c, 'SELECT id FROM bz_usage_billing_requests WHERE execution_key=? FOR UPDATE', [executionKey]))[0];
|
|
339
|
+
usageAssert(!owner || owner.id === id, 'USAGE_RECEIPT_CONFLICT', 'This supplier execution already belongs to another request.');
|
|
340
|
+
usageAssert(!r.execution_key || r.execution_key === executionKey, 'USAGE_RECEIPT_CONFLICT', 'Supplier execution identity changed.');
|
|
341
|
+
}
|
|
342
|
+
usageAssert(!r.raw_usage_json || !input.rawUsage || usageHash(json(r.raw_usage_json)) === usageHash(input.rawUsage), 'USAGE_RECEIPT_CONFLICT', 'The original raw usage has different evidence.');
|
|
343
|
+
if (r.billing_state === 'settled') return request(r);
|
|
344
|
+
const now = await this.now(c), cancelled = r.cancelled_at !== null;
|
|
345
|
+
await c.query('UPDATE bz_usage_billing_requests SET state=?,result_state=?,result_json=?,result_hash=?,usage_json=COALESCE(usage_json,?),raw_usage_json=COALESCE(raw_usage_json,?),execution_key=COALESCE(execution_key,?),resolution=?,revision=revision+1,updated_at=? WHERE id=?',
|
|
346
|
+
[cancelled ? 'cancelled' : 'completed', cancelled ? 'cancelled' : 'complete', JSON.stringify(input.response), responseHash,
|
|
347
|
+
measured ? JSON.stringify(measured) : null, input.rawUsage ? JSON.stringify(input.rawUsage) : null, executionKey, measured || input.rawUsage ? 'settlement_pending' : 'usage_missing', now, id]);
|
|
348
|
+
return request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [id]))[0]!);
|
|
349
|
+
});
|
|
350
|
+
return recorded;
|
|
351
|
+
}
|
|
352
|
+
/** Explicit combined operation for internal reconciliation; never awaited by model delivery. */
|
|
353
|
+
async complete(id: string, fence: string, input: BillingCompletionInput): Promise<BillingRequest> {
|
|
354
|
+
const recorded = await this.recordCompletion(id, fence, input);
|
|
355
|
+
return recorded.billingState === 'pending' && (recorded.usage || recorded.rawUsage) ? this.settleRecorded(recorded) : recorded;
|
|
356
|
+
}
|
|
357
|
+
private readonly settlements = new Map<string, Promise<void>>();
|
|
358
|
+
scheduleSettlement(operationId: string, actor: UsageActor): void {
|
|
359
|
+
const key = operationIdKey(actor, operationId);
|
|
360
|
+
if (this.settlements.has(key)) return;
|
|
361
|
+
const work = Promise.resolve().then(async () => {
|
|
362
|
+
const r = await this.findRequest(actor, operationId);
|
|
363
|
+
if (r?.billingState === 'pending' && (r.usage || r.rawUsage) && r.resultHash) await this.settleRecorded(r);
|
|
364
|
+
}).catch(() => { /* Durable pending evidence is retried by maintenance. */ })
|
|
365
|
+
.finally(() => { this.settlements.delete(key); });
|
|
366
|
+
this.settlements.set(key, work);
|
|
367
|
+
}
|
|
368
|
+
async drainSettlements(): Promise<void> { await Promise.allSettled([...this.settlements.values()]); }
|
|
369
|
+
private async settleRecorded(recorded: BillingRequest): Promise<BillingRequest> {
|
|
370
|
+
try {
|
|
371
|
+
return await this.repository.withTransaction(async c => {
|
|
372
|
+
const r = await this.locked(c, recorded.id);
|
|
373
|
+
usageAssert(r.fence === recorded.fence, 'USAGE_FENCE_CONFLICT', 'Settlement does not match the original dispatch.');
|
|
374
|
+
if (r.billing_state === 'settled' || (!r.usage_json && !r.raw_usage_json) || !r.result_hash) return request(r);
|
|
375
|
+
const measured = r.usage_json ? tokenUsage(json(r.usage_json)) : null;
|
|
376
|
+
const p = (await rows(c, 'SELECT * FROM bz_usage_billing_periods WHERE grant_id=? AND period_start=? FOR UPDATE', [r.grant_id, r.period_start]))[0];
|
|
377
|
+
usageAssert(p, 'METERING_UNAVAILABLE', 'The original allowance pool is unavailable.', 503);
|
|
378
|
+
const rate = request(r).billingRate;
|
|
379
|
+
const referenceCost = calculateReferenceCost(rate.price, { ...(json<Record<string, unknown>>(r.raw_usage_json) ?? {}), ...(measured ?? {}) });
|
|
380
|
+
if (referenceCost === null) return request(r);
|
|
381
|
+
const charged = billedUsdMicros(referenceCost, rate.multiplier);
|
|
382
|
+
const before = usdMicros(p.consumed_usd), after = before + charged, quota = usdMicros(p.allowance_usd);
|
|
383
|
+
const overage = positivePart(after - quota) - positivePart(before - quota), now = await this.now(c);
|
|
384
|
+
// The numeric API must not silently lose fractional evidence at extreme magnitudes.
|
|
385
|
+
usdAmount(charged); usdAmount(after); usdAmount(overage); usdAmount(positivePart(quota - after));
|
|
386
|
+
const chargedValue = usdDecimal(charged), afterValue = usdDecimal(after), overageValue = usdDecimal(overage);
|
|
387
|
+
await c.query('UPDATE bz_usage_billing_periods SET consumed_usd=? WHERE grant_id=? AND period_start=?', [afterValue, r.grant_id, r.period_start]);
|
|
388
|
+
await c.query('INSERT INTO bz_usage_billing_ledger(request_id,account_id,grant_id,period_start,input_tokens,output_tokens,reference_cost_usd,billed_usd,overage_usd,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',
|
|
389
|
+
[r.id, r.account_id, r.grant_id, r.period_start, measured?.inputTokens ?? null, measured?.outputTokens ?? null, referenceCost, chargedValue, overageValue, now]);
|
|
390
|
+
await c.query("UPDATE bz_usage_billing_requests SET billing_state='settled',reference_cost_usd=?,billed_usd=?,overage_usd=?,resolution='actual_usage',revision=revision+1,updated_at=? WHERE id=?", [referenceCost, chargedValue, overageValue, now, r.id]);
|
|
391
|
+
return request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [r.id]))[0]!);
|
|
392
|
+
});
|
|
393
|
+
} catch (e) {
|
|
394
|
+
if (e instanceof UsageError && e.status < 500) throw e;
|
|
395
|
+
// Durable evidence remains available for the original request to reconcile.
|
|
396
|
+
return recorded;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
async cleanupExpiredResponses(now = Date.now()): Promise<void> {
|
|
400
|
+
integer(now, 'now');
|
|
401
|
+
await this.repository.getPool().query('UPDATE bz_usage_billing_requests SET result_json=NULL WHERE created_at<? AND result_json IS NOT NULL AND result_hash IS NOT NULL LIMIT 500', [now - RESULT_RETENTION_MS]);
|
|
402
|
+
}
|
|
403
|
+
async reconcilePendingUsage(): Promise<void> {
|
|
404
|
+
// Only previously saved supplier evidence may settle in maintenance. This
|
|
405
|
+
// path has no credentials/provider transport and cannot create model work.
|
|
406
|
+
const pending = await rows(this.repository.getPool(), "SELECT * FROM bz_usage_billing_requests WHERE billing_state='pending' AND (usage_json IS NOT NULL OR raw_usage_json IS NOT NULL) AND result_hash IS NOT NULL AND fence IS NOT NULL ORDER BY updated_at,id LIMIT 50");
|
|
407
|
+
for (const row of pending) await this.settleRecorded(request(row));
|
|
408
|
+
}
|
|
409
|
+
/** Persist a terminal rejection independently of settlement; never dispatch again. */
|
|
410
|
+
async recordProviderFailure(id: string, fence: string, failure: ProviderFailure): Promise<BillingRequest> {
|
|
411
|
+
return this.repository.withTransaction(async c => {
|
|
412
|
+
const r = await this.locked(c, id);
|
|
413
|
+
usageAssert(r.fence && r.fence === fence, 'USAGE_FENCE_CONFLICT', 'Failure does not match original dispatch.');
|
|
414
|
+
if (r.billing_state === 'settled' || r.result_state === 'complete' || r.result_state === 'failed') return request(r);
|
|
415
|
+
const cancelled = r.cancelled_at !== null, rejected = failure.rejected;
|
|
416
|
+
await c.query('UPDATE bz_usage_billing_requests SET state=?,result_state=?,billing_state=?,result_json=?,reference_cost_usd=?,billed_usd=?,overage_usd=?,resolution=?,revision=revision+1,updated_at=? WHERE id=?',
|
|
417
|
+
[cancelled ? 'cancelled' : rejected ? 'failed' : 'unknown', cancelled ? 'cancelled' : rejected ? 'failed' : 'unknown',
|
|
418
|
+
rejected ? 'settled' : 'pending', JSON.stringify({schema:'bailing.provider-failure.v1',error:failure.diagnostic}),
|
|
419
|
+
rejected ? 0 : null, rejected ? 0 : null, rejected ? 0 : null, failure.code, await this.now(c), id]);
|
|
420
|
+
return request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [id]))[0]!);
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
async markUnknown(id: string, fence: string, reason: string): Promise<BillingRequest> {
|
|
424
|
+
billingKey(reason, 'reason', 64);
|
|
425
|
+
return this.repository.withTransaction(async c => {
|
|
426
|
+
const r = await this.locked(c, id);
|
|
427
|
+
usageAssert(r.fence && r.fence === fence, 'USAGE_FENCE_CONFLICT', 'The uncertainty report does not match original dispatch.');
|
|
428
|
+
if (r.billing_state === 'settled' || r.result_state === 'complete' || r.result_state === 'cancelled' || r.result_state === 'failed') return request(r);
|
|
429
|
+
await c.query("UPDATE bz_usage_billing_requests SET state='unknown',result_state='unknown',resolution=?,revision=revision+1,updated_at=? WHERE id=?", [reason, await this.now(c), id]);
|
|
430
|
+
return request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [id]))[0]!);
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
async cancel(actor: UsageActor, operationId: string): Promise<BillingRequest> {
|
|
434
|
+
billingKey(operationId, 'operation_id');
|
|
435
|
+
return this.repository.withTransaction(async c => {
|
|
436
|
+
const r = await this.locked(c, operationIdKey(actor, operationId)); await this.scope(c, actor, r.service_id);
|
|
437
|
+
if (r.cancelled_at !== null || r.result_state === 'complete') return request(r);
|
|
438
|
+
if (r.result_state === 'failed') return request(r);
|
|
439
|
+
const now = await this.now(c), sent = r.fence !== null;
|
|
440
|
+
await c.query("UPDATE bz_usage_billing_requests SET state='cancelled',result_state='cancelled',billing_state=?,reference_cost_usd=?,billed_usd=?,overage_usd=?,cancelled_at=?,resolution=?,revision=revision+1,updated_at=? WHERE id=?",
|
|
441
|
+
[sent ? 'pending' : 'settled', sent ? null : 0, sent ? null : 0, sent ? null : 0, now, sent ? 'cancel_requested' : 'cancelled_before_dispatch', now, r.id]);
|
|
442
|
+
return request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [r.id]))[0]!);
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
/** Recovery metadata is durable. Response content is returned for seven days only. */
|
|
446
|
+
view(r: BillingRequest, now = Date.now()) {
|
|
447
|
+
const responseExpired = r.resultHash !== null && now - r.createdAt > RESULT_RETENTION_MS;
|
|
448
|
+
const diagnostic = r.response?.schema === 'bailing.provider-failure.v1' ? r.response.error as ProviderDiagnostic : undefined;
|
|
449
|
+
return { schema: 'bailing.model-operation.v1' as const, operation_id: r.operationId, account_id: r.accountId, user_id: r.userId,
|
|
450
|
+
service_id: r.serviceId, conversation_id: r.conversationId, turn_id: r.turnId, state: r.state, result_state: r.resultState,
|
|
451
|
+
billing_state: r.billingState, billing_rate: r.billingRate, dispatch: r.resultState === 'failed' ? 'rejected' as const : r.fence === null ? 'not_dispatched' as const : r.resultHash !== null ? 'completed' as const : 'unknown' as const,
|
|
452
|
+
...(diagnostic ? {error:diagnostic} : {}),
|
|
453
|
+
next_action: r.resultState === 'failed' ? 'contact_operator' as const : r.resultState === 'unknown' || r.resultState === 'pending' ? 'inspect_original' as const : 'none' as const,
|
|
454
|
+
revision: r.revision, ...(r.resultState === 'complete' && r.response && !responseExpired ? { response: r.response } : {}),
|
|
455
|
+
...(responseExpired ? { response_expired: true } : {}), usage: r.usage, raw_usage: publicRawUsage(r.rawUsage), reference_cost_usd: r.referenceCostUsd, billed_usd: r.billedUsd, overage_usd: r.overageUsd };
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
const repositories = new WeakMap<UsageRepository, BillingRepository>();
|
|
459
|
+
export function getBillingRepository(repository: UsageRepository): BillingRepository {
|
|
460
|
+
let value = repositories.get(repository);
|
|
461
|
+
if (!value) { value = new BillingRepository(repository); repositories.set(repository, value); }
|
|
462
|
+
return value;
|
|
463
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { PricingBinding } from './pricing';
|
|
2
|
+
import type { ModelToolConfig } from './model-tools';
|
|
3
|
+
import type { PoolConnection } from "mysql2/promise";
|
|
4
|
+
export interface UsageActor {
|
|
5
|
+
userId: string;
|
|
6
|
+
accountId: string;
|
|
7
|
+
sessionId: string;
|
|
8
|
+
serviceId?: string;
|
|
9
|
+
modelAccess?: "service" | "token_gateway";
|
|
10
|
+
}
|
|
11
|
+
export type UsageActorValidator = (connection: PoolConnection, actor: UsageActor) => Promise<void>;
|
|
12
|
+
export interface UsageAccount {
|
|
13
|
+
id: string;
|
|
14
|
+
kind: "personal" | "organization";
|
|
15
|
+
label: string;
|
|
16
|
+
state: "active" | "suspended" | "archived";
|
|
17
|
+
revision: number;
|
|
18
|
+
createdAt: number;
|
|
19
|
+
updatedAt: number;
|
|
20
|
+
}
|
|
21
|
+
export interface UsageServiceConfig {
|
|
22
|
+
purpose?: "chat" | "tool";
|
|
23
|
+
pricing?: PricingBinding;
|
|
24
|
+
tool?: ModelToolConfig;
|
|
25
|
+
credential: string;
|
|
26
|
+
model: string;
|
|
27
|
+
providerScope: string;
|
|
28
|
+
maxInputBytes: number;
|
|
29
|
+
maxOutputTokens: number;
|
|
30
|
+
timeoutMs: number;
|
|
31
|
+
/** Operator-verified model metadata; absence means unknown, never a guessed context window. */
|
|
32
|
+
contextWindowTokens?: number;
|
|
33
|
+
inputModalities?: ('text' | 'image')[];
|
|
34
|
+
}
|
|
35
|
+
export interface UsageService {
|
|
36
|
+
id: string;
|
|
37
|
+
label: string;
|
|
38
|
+
state: "active" | "suspended";
|
|
39
|
+
revision: number;
|
|
40
|
+
config: UsageServiceConfig;
|
|
41
|
+
}
|
|
42
|
+
export interface CreateUsageAccountInput {
|
|
43
|
+
requestId: string;
|
|
44
|
+
sourceOwner: string;
|
|
45
|
+
sourceId: string;
|
|
46
|
+
kind: "personal" | "organization";
|
|
47
|
+
label: string;
|
|
48
|
+
userId: string;
|
|
49
|
+
}
|