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,119 @@
|
|
|
1
|
+
import type { PoolConnection, RowDataPacket } from 'mysql2/promise';
|
|
2
|
+
import { UsageError, usageAssert } from './errors';
|
|
3
|
+
import { usageHash, type UsageRepository } from './repository';
|
|
4
|
+
import { billingKey } from './billing-ledger';
|
|
5
|
+
import { integer } from './validation';
|
|
6
|
+
|
|
7
|
+
export type UsageResourceKind = 'plan' | 'issuer' | 'account';
|
|
8
|
+
export interface UsageDeletionBlocker { code: string; message: string; count: number }
|
|
9
|
+
export interface UsageDeletionPreview {
|
|
10
|
+
kind: UsageResourceKind; id: string; label: string; revision: number; can_delete: boolean;
|
|
11
|
+
blockers: UsageDeletionBlocker[]; effect: string;
|
|
12
|
+
}
|
|
13
|
+
const tables = { plan: 'bz_usage_billing_plans', issuer: 'bz_usage_issuers', account: 'bz_usage_accounts' } as const;
|
|
14
|
+
async function rows(c: PoolConnection, sql: string, parameters: unknown[] = []): Promise<RowDataPacket[]> {
|
|
15
|
+
return (await c.query<RowDataPacket[]>(sql, parameters))[0];
|
|
16
|
+
}
|
|
17
|
+
/** Each writer takes the same resource lock before adding a reference. */
|
|
18
|
+
async function blockers(c: PoolConnection, kind: UsageResourceKind, id: string, resource: RowDataPacket): Promise<UsageDeletionBlocker[]> {
|
|
19
|
+
const found: UsageDeletionBlocker[] = [];
|
|
20
|
+
const count = async (code: string, message: string, sql: string, params: unknown[] = [id]) => {
|
|
21
|
+
const total = Number((await rows(c, sql, params))[0]!.n);
|
|
22
|
+
if (total > 0) found.push({ code, message, count: total });
|
|
23
|
+
};
|
|
24
|
+
if (kind === 'plan') {
|
|
25
|
+
// Only the account's current grant can require the live plan. Replaced grants
|
|
26
|
+
// keep immutable terms for history and settlement; they must not pin the catalog.
|
|
27
|
+
// Future active grants still own the plan. Suspended grants/accounts do not;
|
|
28
|
+
// deleting the catalog does not restore it when an identity is re-enabled.
|
|
29
|
+
await count('PLAN_CURRENT_ACCOUNTS', '仍有启用账户持有有效或待生效的套餐,请先更换或停用其套餐,或等待到期。',
|
|
30
|
+
`SELECT COUNT(*) AS n FROM bz_usage_billing_heads h
|
|
31
|
+
JOIN bz_usage_billing_grants g ON g.id=h.grant_id AND g.account_id=h.account_id
|
|
32
|
+
JOIN bz_usage_accounts a ON a.id=h.account_id
|
|
33
|
+
WHERE g.plan_id=? AND a.state='active' AND g.state='active' AND (g.expires_at IS NULL OR g.expires_at>CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED))`);
|
|
34
|
+
} else if (kind === 'issuer') {
|
|
35
|
+
await count('ISSUER_USER_HISTORY', '身份来源已接入使用身份,需保留关联;可停用来源。', 'SELECT COUNT(*) AS n FROM bz_usage_users WHERE issuer_id=?');
|
|
36
|
+
await count('ISSUER_SESSION_HISTORY', '身份来源已有使用凭证记录,不能删除历史。', 'SELECT COUNT(*) AS n FROM bz_usage_sessions WHERE issuer_id=?');
|
|
37
|
+
await count('ISSUER_GRANT_HISTORY', '身份来源已有发放额度记录,不能删除历史。', 'SELECT COUNT(*) AS n FROM bz_usage_billing_grants WHERE source_owner=?', [`issuer:${id}`]);
|
|
38
|
+
} else {
|
|
39
|
+
if (resource.state !== 'suspended') found.push({ code: 'ACCOUNT_ACTIVE', message: '请先停用账户,再从列表移除;停用会阻止新的模型请求。', count: 1 });
|
|
40
|
+
// A head without its grant is incomplete storage, not evidence that deletion is safe.
|
|
41
|
+
await count('ACCOUNT_ALLOWANCE_REFERENCE', '账户仍有关联额度记录,请先核对记录完整性。',
|
|
42
|
+
'SELECT COUNT(*) AS n FROM bz_usage_billing_heads h LEFT JOIN bz_usage_billing_grants g ON g.id=h.grant_id WHERE h.account_id=? AND g.id IS NULL');
|
|
43
|
+
}
|
|
44
|
+
return found;
|
|
45
|
+
}
|
|
46
|
+
function effect(kind: UsageResourceKind): string {
|
|
47
|
+
return kind === 'plan' ? '从套餐列表移除,保留历史开通、账本和原请求;原标识不能再次使用。'
|
|
48
|
+
: kind === 'issuer' ? '从身份来源列表移除,原来源凭据失效;原标识不能再次使用。'
|
|
49
|
+
: '从默认列表移除并撤销现有使用凭证;保留原身份、成员、套餐和用量历史。管理员可从“已移除”恢复原账户,恢复后仍为停用状态,不重发额度。';
|
|
50
|
+
}
|
|
51
|
+
export class UsageDeletionRepository {
|
|
52
|
+
constructor(readonly repository: UsageRepository) {}
|
|
53
|
+
async preview(kind: UsageResourceKind, id: string): Promise<UsageDeletionPreview> {
|
|
54
|
+
billingKey(id, 'id', kind === 'plan' ? 191 : 64);
|
|
55
|
+
return this.repository.withTransaction(async c => {
|
|
56
|
+
const current = (await rows(c, `SELECT * FROM ${tables[kind]} WHERE id=? FOR SHARE`, [id]))[0];
|
|
57
|
+
usageAssert(current && !['deleted', 'archived'].includes(current.state), 'USAGE_RESOURCE_NOT_FOUND', '资源不存在或已删除。', 404);
|
|
58
|
+
const blocking = await blockers(c, kind, id, current);
|
|
59
|
+
return { kind, id, label: String(current.label ?? id), revision: Number(current.revision), can_delete: !blocking.length, blockers: blocking, effect: effect(kind) };
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/** Restore the original account only. Never reissue allowance or revive sessions. */
|
|
63
|
+
async restoreAccount(input: { id: string; requestKey: string; expectedRevision: number; actor: string }) {
|
|
64
|
+
const { id, requestKey, expectedRevision, actor } = input;
|
|
65
|
+
billingKey(id, 'id', 64); billingKey(requestKey, 'request_key'); integer(expectedRevision, 'expected_revision', 1);
|
|
66
|
+
usageAssert(typeof actor === 'string' && actor.length > 0 && actor.length <= 191, 'USAGE_INVALID_INPUT', '恢复需要管理身份。', 400);
|
|
67
|
+
return this.repository.withTransaction(async c => {
|
|
68
|
+
const changeKey = usageHash(['usage-account-restore', id, requestKey]), hash = usageHash(input);
|
|
69
|
+
const now = Number((await rows(c, 'SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) AS ms'))[0]!.ms);
|
|
70
|
+
await c.query("INSERT INTO bz_usage_changes(change_key,request_hash,result_json,created_at) VALUES(?,?,'null',?) ON DUPLICATE KEY UPDATE change_key=change_key", [changeKey, hash, now]);
|
|
71
|
+
const change = (await rows(c, 'SELECT request_hash,result_json FROM bz_usage_changes WHERE change_key=? FOR UPDATE', [changeKey]))[0]!;
|
|
72
|
+
usageAssert(change.request_hash === hash, 'USAGE_IDEMPOTENCY_CONFLICT', '同一恢复请求关联了不同内容。');
|
|
73
|
+
const saved = typeof change.result_json === 'string' ? JSON.parse(change.result_json) : change.result_json;
|
|
74
|
+
if (saved !== null) return saved as { id: string; state: 'suspended'; revision: number };
|
|
75
|
+
const current = (await rows(c, 'SELECT * FROM bz_usage_accounts WHERE id=? FOR UPDATE', [id]))[0];
|
|
76
|
+
usageAssert(current, 'USAGE_RESOURCE_NOT_FOUND', '账户不存在。', 404);
|
|
77
|
+
usageAssert(current.state !== 'deleted', 'USAGE_RESOURCE_DELETED', '原删除标记不能恢复。');
|
|
78
|
+
usageAssert(Number(current.revision) === expectedRevision, 'USAGE_REVISION_CONFLICT', '账户已更新,请刷新后恢复。');
|
|
79
|
+
usageAssert(current.state === 'archived', 'USAGE_INVALID_INPUT', '只有已移除账户需要恢复。', 400);
|
|
80
|
+
await c.query("UPDATE bz_usage_accounts SET state='suspended',revision=revision+1,updated_at=? WHERE id=?", [now, id]);
|
|
81
|
+
const receipt = { id, state: 'suspended' as const, revision: expectedRevision + 1 };
|
|
82
|
+
await c.query('UPDATE bz_usage_changes SET result_json=? WHERE change_key=?', [JSON.stringify(receipt), changeKey]);
|
|
83
|
+
return receipt;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async remove(input: { kind: UsageResourceKind; id: string; requestKey: string; expectedRevision: number; actor: string }) {
|
|
87
|
+
const { kind, id, requestKey, expectedRevision, actor } = input;
|
|
88
|
+
billingKey(id, 'id', kind === 'plan' ? 191 : 64); billingKey(requestKey, 'request_key'); integer(expectedRevision, 'expected_revision', 1);
|
|
89
|
+
usageAssert(typeof actor === 'string' && actor.length > 0 && actor.length <= 191, 'USAGE_INVALID_INPUT', '删除操作需要管理身份。', 400);
|
|
90
|
+
return this.repository.withTransaction(async c => {
|
|
91
|
+
const changeKey = usageHash(['usage-resource-delete', kind, id, requestKey]), hash = usageHash(input);
|
|
92
|
+
const now = Number((await rows(c, 'SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) AS ms'))[0]!.ms);
|
|
93
|
+
await c.query("INSERT INTO bz_usage_changes(change_key,request_hash,result_json,created_at) VALUES(?,?,'null',?) ON DUPLICATE KEY UPDATE change_key=change_key", [changeKey, hash, now]);
|
|
94
|
+
const change = (await rows(c, 'SELECT request_hash,result_json FROM bz_usage_changes WHERE change_key=? FOR UPDATE', [changeKey]))[0]!;
|
|
95
|
+
usageAssert(change.request_hash === hash, 'USAGE_IDEMPOTENCY_CONFLICT', '同一删除请求关联了不同内容。');
|
|
96
|
+
const saved = typeof change.result_json === 'string' ? JSON.parse(change.result_json) : change.result_json;
|
|
97
|
+
if (saved !== null) return saved as { id: string; deleted: true; revision: number; kind: UsageResourceKind; deletedAt: number };
|
|
98
|
+
const current = (await rows(c, `SELECT * FROM ${tables[kind]} WHERE id=? FOR UPDATE`, [id]))[0];
|
|
99
|
+
usageAssert(current, 'USAGE_RESOURCE_NOT_FOUND', '资源不存在。', 404);
|
|
100
|
+
usageAssert(!['deleted', 'archived'].includes(current.state), 'USAGE_RESOURCE_DELETED', '资源已删除,原标识不能再次使用。');
|
|
101
|
+
usageAssert(Number(current.revision) === expectedRevision, 'USAGE_REVISION_CONFLICT', '资源已更新,请刷新预览后再删除。');
|
|
102
|
+
const blocking = await blockers(c, kind, id, current);
|
|
103
|
+
if (blocking.length) throw new UsageError('USAGE_RESOURCE_IN_USE', '资源已有使用记录或关联,不能删除。请查看具体原因。', 409, { blockers: blocking });
|
|
104
|
+
await c.query(`UPDATE ${tables[kind]} SET state=?,revision=revision+1,updated_at=? WHERE id=?`, [kind === 'account' ? 'archived' : 'deleted', now, id]);
|
|
105
|
+
if (kind === 'account') await c.query("UPDATE bz_usage_sessions SET state='revoked' WHERE account_id=? AND state='active'", [id]);
|
|
106
|
+
const receipt = { id, deleted: true as const, revision: expectedRevision + 1, kind, deletedAt: now };
|
|
107
|
+
await c.query('UPDATE bz_usage_changes SET result_json=? WHERE change_key=?', [JSON.stringify(receipt), changeKey]);
|
|
108
|
+
return receipt;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
export function getUsageDeletionRepository(repository: UsageRepository): UsageDeletionRepository { return new UsageDeletionRepository(repository); }
|
|
113
|
+
|
|
114
|
+
export function usageDeletionId(segment: string, kind: UsageResourceKind): string {
|
|
115
|
+
let decoded: string;
|
|
116
|
+
try { decoded = decodeURIComponent(segment); }
|
|
117
|
+
catch { throw new UsageError('USAGE_INVALID_INPUT', '资源标识格式不正确。', 400); }
|
|
118
|
+
return billingKey(decoded, 'id', kind === 'plan' ? 191 : 64);
|
|
119
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { assertKnownFields, integer } from './validation';
|
|
4
|
+
|
|
5
|
+
test('shared validation accepts exact integers and rejects ambiguous quantities', () => {
|
|
6
|
+
assert.equal(integer(0, 'count'), 0);
|
|
7
|
+
assert.equal(integer(10, 'count', 1, 10), 10);
|
|
8
|
+
for (const value of ['10', -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) {
|
|
9
|
+
assert.throws(() => integer(value, 'count'), { code: 'USAGE_INVALID_INPUT' });
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test('shared field validation rejects unknown configuration and non-object input', () => {
|
|
14
|
+
assertKnownFields({ label: 'Synthetic' }, ['label'], 'sample');
|
|
15
|
+
for (const value of [null, [], 'text', { label: 'Synthetic', hiddenSetting: true }]) {
|
|
16
|
+
assert.throws(() => assertKnownFields(value, ['label'], 'sample'), { code: 'USAGE_INVALID_INPUT' });
|
|
17
|
+
}
|
|
18
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { usageAssert } from "./errors";
|
|
2
|
+
export function integer(
|
|
3
|
+
value: unknown,
|
|
4
|
+
name: string,
|
|
5
|
+
min = 0,
|
|
6
|
+
max = Number.MAX_SAFE_INTEGER,
|
|
7
|
+
): number {
|
|
8
|
+
usageAssert(
|
|
9
|
+
Number.isSafeInteger(value) && Number(value) >= min && Number(value) <= max,
|
|
10
|
+
"USAGE_INVALID_INPUT",
|
|
11
|
+
`${name} is outside the supported integer range.`,
|
|
12
|
+
400,
|
|
13
|
+
);
|
|
14
|
+
return Number(value);
|
|
15
|
+
}
|
|
16
|
+
export function assertKnownFields(
|
|
17
|
+
value: unknown,
|
|
18
|
+
allowed: readonly string[],
|
|
19
|
+
name: string,
|
|
20
|
+
): void {
|
|
21
|
+
usageAssert(
|
|
22
|
+
value !== null && typeof value === "object" && !Array.isArray(value),
|
|
23
|
+
"USAGE_INVALID_INPUT",
|
|
24
|
+
`${name} must be an object.`,
|
|
25
|
+
400,
|
|
26
|
+
);
|
|
27
|
+
usageAssert(
|
|
28
|
+
Object.keys(value).every((k) => allowed.includes(k)),
|
|
29
|
+
"USAGE_INVALID_INPUT",
|
|
30
|
+
`${name} contains unsupported fields.`,
|
|
31
|
+
400,
|
|
32
|
+
);
|
|
33
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { can, type Principal } from '../app/auth';
|
|
3
|
+
import { readBody, PayloadTooLargeError, send } from '../app/http';
|
|
4
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
5
|
+
import { AgentTaskControlError } from '../core/runtime/agent-task-control';
|
|
6
|
+
import { createAdminAgentTaskFor, listAdminAgentTasksFor, getAdminAgentTaskFor, controlAdminAgentTaskFor, taskErrorStatus } from '../app/agent-task-control';
|
|
7
|
+
|
|
8
|
+
/** Authenticated operator surface. There is deliberately no Agent-bearer create/control API. */
|
|
9
|
+
export async function handleAdminAgentTasksApiFor(
|
|
10
|
+
config: ConfigStoreContract, method: string, path: string, req: IncomingMessage, res: ServerResponse, principal: Principal,
|
|
11
|
+
): Promise<boolean> {
|
|
12
|
+
if (path !== '/admin/api/agent-tasks' && !path.startsWith('/admin/api/agent-tasks/')) return false;
|
|
13
|
+
if (principal.kind !== 'admin' || !can(principal, method === 'GET' ? 'clients:read' : 'clients:write')) {
|
|
14
|
+
send(res, 403, { error: 'forbidden', message: '当前身份无任务控制权限。' }); return true;
|
|
15
|
+
}
|
|
16
|
+
const query = new URL(req.url ?? path, 'http://bailing.local').searchParams;
|
|
17
|
+
const match = path.match(/^\/admin\/api\/agent-tasks\/([0-9a-f-]+)(\/control)?$/i);
|
|
18
|
+
try {
|
|
19
|
+
const actor = principal.username ?? 'admin-token';
|
|
20
|
+
if (path === '/admin/api/agent-tasks' && method === 'GET') send(res, 200, await listAdminAgentTasksFor(config, query));
|
|
21
|
+
else if (path === '/admin/api/agent-tasks' && method === 'POST') send(res, 200, await createAdminAgentTaskFor(config, actor, await readBody(req, 64 * 1024)));
|
|
22
|
+
else if (match && !match[2] && method === 'GET') send(res, 200, await getAdminAgentTaskFor(config, match[1]!, query));
|
|
23
|
+
else if (match?.[2] === '/control' && method === 'POST') send(res, 200, await controlAdminAgentTaskFor(config, actor, match[1]!, await readBody(req, 4096)));
|
|
24
|
+
else send(res, 404, { error: 'not_found' });
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (error instanceof AgentTaskControlError) send(res, taskErrorStatus(error), { error: error.code, message: error.message });
|
|
27
|
+
else if (error instanceof PayloadTooLargeError) send(res, 413, { error: 'TASK_INVALID_INPUT', message: '请求过大。' });
|
|
28
|
+
else if (error instanceof SyntaxError) send(res, 400, { error: 'TASK_INVALID_INPUT', message: '请求必须是有效 JSON。' });
|
|
29
|
+
else send(res, 503, { error: 'TASK_UNAVAILABLE', message: '任务记录暂时不可用,请使用原请求重试。' });
|
|
30
|
+
}
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { can, type Principal } from '../app/auth';
|
|
3
|
+
import { readBody, send } from '../app/http';
|
|
4
|
+
import { usageAssert } from '../modules/usage/errors';
|
|
5
|
+
import { usagePage, usageRequestKey, usageRevision } from '../modules/usage/http';
|
|
6
|
+
import { usageFields } from '../modules/usage/identity';
|
|
7
|
+
import { getUsageDeletionRepository, usageDeletionId } from '../modules/usage/usage-deletion';
|
|
8
|
+
import { getBillingRepository } from '../modules/usage/billing-repository';
|
|
9
|
+
import type { UsageRepository } from '../modules/usage/repository';
|
|
10
|
+
import { serviceAvailability } from '../modules/usage/service-availability';
|
|
11
|
+
import { validateBillingPlan, billingKey } from '../modules/usage/billing-ledger';
|
|
12
|
+
|
|
13
|
+
/** Caller has already verified Console identity and usage read/write permissions. */
|
|
14
|
+
export async function handleAdminBillingUsage(repository: UsageRepository, method: string, path: string,
|
|
15
|
+
req: IncomingMessage, res: ServerResponse, principal: Principal): Promise<boolean> {
|
|
16
|
+
if (!path.startsWith('/admin/api/usage/billing/')) return false;
|
|
17
|
+
usageAssert(principal.kind === 'admin', 'USAGE_FORBIDDEN', '需要后台管理身份。', 403);
|
|
18
|
+
const tokens = getBillingRepository(repository);
|
|
19
|
+
usageAssert(await tokens.configurationReady(), 'USAGE_UNSUPPORTED', '套餐配置尚未就绪,请核对迁移。', 503);
|
|
20
|
+
const billingReady = await tokens.ready();
|
|
21
|
+
if (method !== 'GET') usageAssert(billingReady, 'USAGE_BILLING_UNSUPPORTED', '美元计费尚未就绪,请核对迁移。', 503);
|
|
22
|
+
const query = new URL(req.url ?? path, 'http://local').searchParams;
|
|
23
|
+
if (path === '/admin/api/usage/billing/plans') {
|
|
24
|
+
if (method === 'GET') send(res, 200, { items: await tokens.listPlans(), billing_ready: billingReady, period_allowance_supported: true });
|
|
25
|
+
else if (method === 'POST') {
|
|
26
|
+
const body = usageFields(await readBody(req, 32 * 1024), ['id','label','expected_revision','state','config'], ['id','label','expected_revision','config']);
|
|
27
|
+
const config = validateBillingPlan(body.config), id = billingKey(body.id);
|
|
28
|
+
const [rows] = await repository.getPool().query<any[]>('SELECT config_json FROM bz_usage_billing_plans WHERE id=?', [id]);
|
|
29
|
+
const raw = rows[0]?.config_json;
|
|
30
|
+
const original = raw ? validateBillingPlan(typeof raw === 'string' ? JSON.parse(raw) : raw).serviceIds : [];
|
|
31
|
+
// Existing selections may become unavailable later. Let the operator keep
|
|
32
|
+
// or remove them while preventing a newly selected unusable service.
|
|
33
|
+
for (const serviceId of config.serviceIds.filter(value => !original.includes(value))) {
|
|
34
|
+
const service = await repository.getService(serviceId);
|
|
35
|
+
usageAssert(service, 'USAGE_SERVICE_NOT_FOUND', '所选模型服务不存在。', 404);
|
|
36
|
+
const ready = await serviceAvailability(repository, service);
|
|
37
|
+
usageAssert(ready.state === 'ready', ready.code ?? 'USAGE_SERVICE_UNAVAILABLE', ready.message ?? '请先完成模型服务配置。', 409);
|
|
38
|
+
}
|
|
39
|
+
send(res, 200, await tokens.putPlan(body));
|
|
40
|
+
}
|
|
41
|
+
else send(res, 405, { error: 'method_not_allowed' });
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
const deletion = path.match(/^\/admin\/api\/usage\/billing\/plans\/([^/]+)(\/deletion-preview)?$/);
|
|
45
|
+
if (deletion && ((!deletion[2] && method === 'DELETE') || (deletion[2] && method === 'GET'))) {
|
|
46
|
+
const id = usageDeletionId(deletion[1]!, 'plan'), resources = getUsageDeletionRepository(repository);
|
|
47
|
+
if (deletion[2]) send(res, 200, await resources.preview('plan', id));
|
|
48
|
+
else {
|
|
49
|
+
const body = usageFields(await readBody(req, 4096), ['request_key','expected_revision'], ['request_key','expected_revision']);
|
|
50
|
+
send(res, 200, await resources.remove({ kind: 'plan', id, requestKey: usageRequestKey(body), expectedRevision: usageRevision(body.expected_revision), actor: principal.username ?? 'admin-billing' }));
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
const account = path.match(/^\/admin\/api\/usage\/billing\/accounts\/([A-Za-z0-9_.:-]+)\/(summary|grant|control|reset|requests)$/);
|
|
55
|
+
if (!account) { send(res, 404, { error: 'not_found' }); return true; }
|
|
56
|
+
const [, id, action] = account;
|
|
57
|
+
if (method === 'GET' && action === 'summary') send(res, 200, await tokens.summary(id!));
|
|
58
|
+
else if (method === 'GET' && action === 'requests') {
|
|
59
|
+
usageAssert(billingReady, 'USAGE_BILLING_UNSUPPORTED', '原请求计量需要配套更新计费内核与迁移后查看。', 503);
|
|
60
|
+
const { limit, cursor } = usagePage(query);
|
|
61
|
+
const page = await tokens.listRequests(id!, { limit, cursor });
|
|
62
|
+
send(res, 200, page);
|
|
63
|
+
} else if (method === 'POST' && action === 'grant') {
|
|
64
|
+
usageAssert(can(principal, 'usage:adjust'), 'USAGE_FORBIDDEN', '开通美元额度需要额度调整权限。', 403);
|
|
65
|
+
send(res, 200, await tokens.grant(id!, await readBody(req, 8192), 'hub'));
|
|
66
|
+
} else if (method === 'POST' && action === 'reset') {
|
|
67
|
+
usageAssert(can(principal, 'usage:adjust'), 'USAGE_FORBIDDEN', '重置额度需要额度调整权限。', 403);
|
|
68
|
+
const body = usageFields(await readBody(req, 4096), ['request_key','expected_revision'], ['request_key','expected_revision']);
|
|
69
|
+
send(res, 200, await tokens.resetAllowance(id!, body, principal.username ?? 'admin-token'));
|
|
70
|
+
} else if (method === 'POST' && action === 'control') send(res, 200, await tokens.control(id!, await readBody(req, 4096), 'hub'));
|
|
71
|
+
else send(res, 405, { error: 'method_not_allowed' });
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
@@ -64,6 +64,28 @@ function deps(old: ToolProvider, upserts: ToolProvider[]) {
|
|
|
64
64
|
};
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
test('admin policy edits persist without changing the business declaration or legacy access intent', async () => {
|
|
68
|
+
const old = historicalProvider();
|
|
69
|
+
const upserts: ToolProvider[] = [];
|
|
70
|
+
const policy = { default: { mode: 'disabled' }, overrides: { images_update: { mode: 'custom', count: 1000, window: '1h' } } };
|
|
71
|
+
const payload = { name: old.name, base_url: old.base_url, spec_source: old.spec_source, spec_url: old.spec_url, rate_limit_per_min: 0, tool_rate_limits: policy };
|
|
72
|
+
const res = new FakeResponse();
|
|
73
|
+
await handleAdminToolProviderApiFor(deps(old, upserts), 'POST', '/admin/api/tool-providers', request(payload), res as unknown as ServerResponse, { kind: 'admin', via: 'token' });
|
|
74
|
+
assert.equal(res.statusCode, 200);
|
|
75
|
+
assert.deepEqual(upserts[0]!.tool_rate_limits, policy);
|
|
76
|
+
assert.equal(upserts[0]!.rate_limit_per_min, 0);
|
|
77
|
+
assert.equal(upserts[0]!.spec_access_policy, 'legacy_unverified');
|
|
78
|
+
assert.equal(upserts[0]!.secret, old.secret);
|
|
79
|
+
const after = new FakeResponse();
|
|
80
|
+
const { tool_rate_limits: _omitted, ...unchanged } = payload;
|
|
81
|
+
await handleAdminToolProviderApiFor(deps(upserts[0]!, upserts), 'POST', '/admin/api/tool-providers', request(unchanged), after as unknown as ServerResponse, { kind: 'admin', via: 'token' });
|
|
82
|
+
assert.deepEqual(upserts[1]!.tool_rate_limits, policy);
|
|
83
|
+
const invalid = new FakeResponse();
|
|
84
|
+
await handleAdminToolProviderApiFor(deps(upserts[1]!, upserts), 'POST', '/admin/api/tool-providers', request({ ...payload, tool_rate_limits: { default: { mode: 'custom', count: 0, window: '1h' } } }), invalid as unknown as ServerResponse, { kind: 'admin', via: 'token' });
|
|
85
|
+
assert.equal(invalid.statusCode, 400);
|
|
86
|
+
assert.equal(upserts.length, 2);
|
|
87
|
+
});
|
|
88
|
+
|
|
67
89
|
test('admin tool-provider route: 直接 API 不能绕过历史 URL 源的策略确认', async () => {
|
|
68
90
|
const upserts: ToolProvider[] = [];
|
|
69
91
|
const old = historicalProvider();
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { effectiveToolRateLimit } from '../core/contracts/tool-rate-limits';
|
|
1
2
|
// 后台工具源 API:业务系统 OpenAPI/ToolDefinition 的注册、对账、索引和调试入口。
|
|
2
3
|
// 这里是“AI 调业务工具”这条核心卖点的控制台边界,不放在通用 admin 分发器里。
|
|
3
4
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
@@ -48,6 +49,13 @@ export async function handleAdminToolProviderApiFor(
|
|
|
48
49
|
if (!prepared.ok) { send(res, 400, { error: prepared.error }); return true; }
|
|
49
50
|
const prov = prepared.value;
|
|
50
51
|
await configStore.toolProviders.upsert(prov);
|
|
52
|
+
if (old?.rate_limit_per_min !== prov.rate_limit_per_min || JSON.stringify(old?.tool_rate_limits) !== JSON.stringify(prov.tool_rate_limits)) {
|
|
53
|
+
await deps.stateStore.appendAudit({ ts: deps.now(), job_id: '-', request_id: 'config', event: 'tool_rate_limit_policy_updated',
|
|
54
|
+
detail: { provider: prov.name, by: principal.kind === 'admin' ? principal.username ?? 'token' : 'client',
|
|
55
|
+
before: { total_per_min: old?.rate_limit_per_min ?? null, tools: old?.tool_rate_limits ?? null },
|
|
56
|
+
after: { total_per_min: prov.rate_limit_per_min, tools: prov.tool_rate_limits ?? null }, scope: 'tool_provider_shared' },
|
|
57
|
+
}).catch(() => undefined);
|
|
58
|
+
}
|
|
51
59
|
// 注册期 authorize 探针(只读、不阻断;得 suspect = 疑似只验签未授权,控制台据 authz_probe 标红)
|
|
52
60
|
const authz_probe = await probeAuthorizeFor(configStore, deps.stateStore, prov, deps.cfg, deps.now, deps.sleep).catch(() => undefined);
|
|
53
61
|
// 配齐了 embedding 坐标系且有 spec → 顺手建/增量重建工具检索索引(失败不阻塞保存,控制台用 index_result 提示)
|
|
@@ -172,7 +180,7 @@ export async function handleAdminToolProviderApiFor(
|
|
|
172
180
|
if (!p.spec_json) { send(res, 200, { tools: [], diagnostics: [], skipped: [], warnings: [], note: '尚无 spec(粘贴或刷新)' }); return true; }
|
|
173
181
|
const { tools, diagnostics } = compileOpenApiTools(p.spec_json);
|
|
174
182
|
// 全量字段:工具清单是注解的"对账面"——业务侧标了什么、中枢派生成了什么,必须全部可见可核对
|
|
175
|
-
send(res, 200, { tools: tools.map((t) => ({ name: t.name, source: t.source, schema_version: t.schemaVersion, method: t.method, path: t.path, scope: t.scope, risk: t.risk, confirm_required: t.confirmRequired, confirm_when: t.confirmWhen ?? [], requires_subject: t.requiresSubject, sensitive: t.sensitive, readonly: t.readonly, idempotent: t.idempotent, timeout_ms: t.timeoutMs, rate_limit_per_min: t.rateLimitPerMin, confirm_prompt: t.confirmPrompt, context: t.context, extensions: t.extensions, parameters: t.inputSchema, param_in: t.paramIn, description: t.description })), diagnostics, skipped: skippedDiagnostics(diagnostics), warnings: warningDiagnostics(diagnostics) });
|
|
183
|
+
send(res, 200, { tools: tools.map((t) => ({ name: t.name, source: t.source, schema_version: t.schemaVersion, method: t.method, path: t.path, scope: t.scope, risk: t.risk, confirm_required: t.confirmRequired, confirm_when: t.confirmWhen ?? [], requires_subject: t.requiresSubject, sensitive: t.sensitive, readonly: t.readonly, idempotent: t.idempotent, timeout_ms: t.timeoutMs, rate_limit_per_min: t.rateLimitPerMin, rate_limit: t.rateLimit ?? null, effective_rate_limit: effectiveToolRateLimit(t, p.tool_rate_limits), confirm_prompt: t.confirmPrompt, context: t.context, extensions: t.extensions, parameters: t.inputSchema, param_in: t.paramIn, description: t.description })), diagnostics, skipped: skippedDiagnostics(diagnostics), warnings: warningDiagnostics(diagnostics) });
|
|
176
184
|
return true;
|
|
177
185
|
}
|
|
178
186
|
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { referencePricing } from '../modules/usage/pricing';
|
|
2
|
+
import { serviceAvailability } from '../modules/usage/service-availability';
|
|
3
|
+
import { validateModelToolConfig } from '../modules/usage/model-tools';
|
|
4
|
+
import { getUsageDeletionRepository, usageDeletionId, type UsageResourceKind } from '../modules/usage/usage-deletion';
|
|
5
|
+
import { getBillingRepository } from '../modules/usage/billing-repository';
|
|
6
|
+
import { handleAdminBillingUsage } from './admin-billing-usage';
|
|
7
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
8
|
+
import { can, type Principal } from '../app/auth';
|
|
9
|
+
import { readBody, send } from '../app/http';
|
|
10
|
+
import type { UsageServiceConfig } from '../modules/usage/contracts';
|
|
11
|
+
import { usageAssert } from '../modules/usage/errors';
|
|
12
|
+
import { getUsageIdentity, usageFields, usageKey, usageString } from '../modules/usage/identity';
|
|
13
|
+
import { USAGE_CAPABILITIES, usageHttpError, usagePage, usageRequestKey, usageRevision } from '../modules/usage/http';
|
|
14
|
+
import type { UsageRepository } from '../modules/usage/repository';
|
|
15
|
+
|
|
16
|
+
/** Console uses domain services too; ordinary usage credentials never gain admin permissions. */
|
|
17
|
+
export async function handleAdminUsageApiFor(repository: UsageRepository | null | undefined, method: string, path: string,
|
|
18
|
+
req: IncomingMessage, res: ServerResponse, principal: Principal): Promise<boolean> {
|
|
19
|
+
if (path !== '/admin/api/usage' && !path.startsWith('/admin/api/usage/')) return false;
|
|
20
|
+
try {
|
|
21
|
+
usageAssert(principal.kind === 'admin' && can(principal, method === 'GET' ? 'usage:read' : 'usage:write'), 'USAGE_FORBIDDEN', '当前账号没有用户与用量管理权限。', 403);
|
|
22
|
+
if (path === '/admin/api/usage' && method === 'GET') { send(res, 200, { ...USAGE_CAPABILITIES, supported: Boolean(repository && await getUsageIdentity(repository).ready() && await getBillingRepository(repository).ready()) }); return true; }
|
|
23
|
+
usageAssert(repository, 'USAGE_UNSUPPORTED', '此实例尚未配置用量模块。', 503);
|
|
24
|
+
const identity = getUsageIdentity(repository), url = new URL(req.url ?? path, 'http://bailing.local');
|
|
25
|
+
usageAssert(await identity.ready(), 'USAGE_UNSUPPORTED', '用量模块尚未就绪,请核对版本与迁移。', 503);
|
|
26
|
+
if (await handleAdminBillingUsage(repository, method, path, req, res, principal)) return true;
|
|
27
|
+
const query = url.searchParams;
|
|
28
|
+
if (path.startsWith('/admin/api/usage/pricing/')) {
|
|
29
|
+
usageAssert(can(principal, 'usage:issuers'), 'USAGE_FORBIDDEN', '参考价格设置需要模型服务管理权限。', 403);
|
|
30
|
+
const prices = referencePricing(repository);
|
|
31
|
+
if (method === 'GET' && ['/admin/api/usage/pricing/models','/admin/api/usage/pricing/endpoints'].includes(path)) {
|
|
32
|
+
const kind = query.get('kind'); usageAssert(kind === 'chat' || kind === 'image', 'USAGE_INVALID_INPUT', '参考目录类型无效。', 400);
|
|
33
|
+
const model = query.get('model_id') ?? undefined;
|
|
34
|
+
if (path.endsWith('/endpoints')) usageAssert(model, 'USAGE_INVALID_INPUT', '请选择参考模型。', 400);
|
|
35
|
+
send(res,200,await prices.catalog(kind, path.endsWith('/endpoints') ? model : undefined)); return true;
|
|
36
|
+
}
|
|
37
|
+
if (method === 'POST' && path.endsWith('/sync')) {
|
|
38
|
+
const b = usageFields(await readBody(req,2048), ['kind','model_id'], ['kind','model_id']);
|
|
39
|
+
usageAssert(b.kind === 'chat' || b.kind === 'image', 'USAGE_INVALID_INPUT', '参考目录类型无效。', 400);
|
|
40
|
+
send(res,200,await prices.catalog(b.kind, usageString(b.model_id,'model_id',191),true)); return true;
|
|
41
|
+
}
|
|
42
|
+
send(res,404,{error:'not_found'}); return true;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const deletion = path.match(/^\/admin\/api\/usage\/(issuers|accounts)\/([^/]+)(\/deletion-preview)?$/);
|
|
46
|
+
if (deletion && ((!deletion[3] && method === 'DELETE') || (deletion[3] && method === 'GET'))) {
|
|
47
|
+
const kind: UsageResourceKind = deletion[1] === 'issuers' ? 'issuer' : 'account';
|
|
48
|
+
if (kind === 'issuer') usageAssert(can(principal, 'usage:issuers'), 'USAGE_FORBIDDEN', '身份来源删除与关联预览需要身份来源管理权限。', 403);
|
|
49
|
+
const id = usageDeletionId(deletion[2]!, kind), resources = getUsageDeletionRepository(repository);
|
|
50
|
+
if (deletion[3]) send(res, 200, await resources.preview(kind, id));
|
|
51
|
+
else {
|
|
52
|
+
const body = usageFields(await readBody(req, 4096), ['request_key','expected_revision'], ['request_key','expected_revision']);
|
|
53
|
+
send(res, 200, await resources.remove({ kind, id, requestKey: usageRequestKey(body), expectedRevision: usageRevision(body.expected_revision), actor: principal.username ?? 'admin-token' }));
|
|
54
|
+
}
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
if (path === '/admin/api/usage/issuers') {
|
|
58
|
+
usageAssert(can(principal, 'usage:issuers'), 'USAGE_FORBIDDEN', '需要身份来源管理权限。', 403);
|
|
59
|
+
if (method === 'GET') send(res, 200, { items: await identity.listIssuers() });
|
|
60
|
+
else if (method === 'POST') send(res, 200, await identity.createIssuer(await readBody(req, 16 * 1024)));
|
|
61
|
+
else send(res, 405, { error: 'method_not_allowed' });
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
const issuer = path.match(/^\/admin\/api\/usage\/issuers\/([A-Za-z0-9_.:-]+)\/control$/);
|
|
65
|
+
if (issuer && method === 'POST') {
|
|
66
|
+
usageAssert(can(principal, 'usage:issuers'), 'USAGE_FORBIDDEN', '需要身份来源管理权限。', 403);
|
|
67
|
+
const body = usageFields(await readBody(req, 4096), ['expected_revision', 'state', 'rotate'], ['expected_revision', 'state']);
|
|
68
|
+
usageAssert(body.state === 'active' || body.state === 'suspended', 'USAGE_INVALID_INPUT', '状态不正确。', 400);
|
|
69
|
+
usageAssert(body.rotate === undefined || typeof body.rotate === 'boolean', 'USAGE_INVALID_INPUT', '轮换参数不正确。', 400);
|
|
70
|
+
send(res, 200, await identity.controlIssuer(issuer[1]!, usageRevision(body.expected_revision), body.state, body.rotate === true)); return true;
|
|
71
|
+
}
|
|
72
|
+
if (path === '/admin/api/usage/services') {
|
|
73
|
+
if (method === 'GET') send(res, 200, { items: await Promise.all((await repository.listServices()).map(async service => {
|
|
74
|
+
const [availability, quote] = await Promise.all([
|
|
75
|
+
serviceAvailability(repository, service), referencePricing(repository).inspect(service.config.pricing),
|
|
76
|
+
]);
|
|
77
|
+
// Public reference prices are safe for usage readers. Editing bindings still requires usage:issuers.
|
|
78
|
+
return {...service, availability, reference_price: quote.price ?? null};
|
|
79
|
+
})) });
|
|
80
|
+
else if (method === 'POST') {
|
|
81
|
+
usageAssert(can(principal, 'usage:issuers'), 'USAGE_FORBIDDEN', '模型服务配置需要身份与服务管理权限。', 403);
|
|
82
|
+
const body = usageFields(await readBody(req, 16 * 1024), ['id', 'label', 'expected_revision', 'state', 'config'], ['id', 'label', 'expected_revision', 'config']);
|
|
83
|
+
usageAssert(body.state === undefined || body.state === 'active' || body.state === 'suspended', 'USAGE_INVALID_INPUT', '状态不正确。', 400);
|
|
84
|
+
const config = body.config as UsageServiceConfig;
|
|
85
|
+
usageAssert(config && typeof config === 'object', 'USAGE_INVALID_INPUT', '模型服务配置无效。', 400);
|
|
86
|
+
validateModelToolConfig(config);
|
|
87
|
+
const existing = await repository.getService(usageKey(body.id, 'id'));
|
|
88
|
+
if ((body.state ?? existing?.state ?? 'active') === 'active' && config.tool?.adapter !== 'pending')
|
|
89
|
+
await referencePricing(repository).snapshot(config.pricing);
|
|
90
|
+
send(res, 200, await repository.putService({ id: usageKey(body.id, 'id'), label: usageString(body.label, 'label'), expectedRevision: usageRevision(body.expected_revision), state: body.state as 'active' | 'suspended' | undefined, config: body.config as UsageServiceConfig }));
|
|
91
|
+
} else send(res, 405, { error: 'method_not_allowed' });
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
const service = path.match(/^\/admin\/api\/usage\/services\/([^/]+)(\/references)?$/);
|
|
95
|
+
if (service && ((!service[2] && method === 'DELETE') || (service[2] && method === 'GET'))) {
|
|
96
|
+
usageAssert(can(principal, 'usage:issuers'), 'USAGE_FORBIDDEN', '查看模型占用或删除服务需要身份与服务管理权限。', 403);
|
|
97
|
+
let id: string;
|
|
98
|
+
try { id = decodeURIComponent(service[1]!); }
|
|
99
|
+
catch { usageAssert(false, 'USAGE_INVALID_INPUT', '模型服务标识格式不正确。', 400); }
|
|
100
|
+
if (service[2]) { send(res, 200, await repository.serviceReferences(usageKey(id, 'id'))); return true; }
|
|
101
|
+
const body = usageFields(await readBody(req, 4096), ['expected_revision', 'request_key'], ['expected_revision', 'request_key']);
|
|
102
|
+
send(res, 200, await repository.deleteService({ id: usageKey(id, 'id'),
|
|
103
|
+
expectedRevision: usageRevision(body.expected_revision), requestId: usageRequestKey(body), actor: principal.username ?? 'admin-token' }));
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
if (path === '/admin/api/usage/accounts') {
|
|
107
|
+
if (method === 'GET') {
|
|
108
|
+
const view = query.get('view') ?? 'current';
|
|
109
|
+
usageAssert(['current', 'archived'].includes(view), 'USAGE_INVALID_INPUT', '账户视图不正确。', 400);
|
|
110
|
+
const page = usagePage(query, ['view']); const result = await repository.listAccounts({ limit: page.limit, before: page.cursor ?? undefined, archived: view === 'archived' });
|
|
111
|
+
send(res, 200, { items: result.items, next_cursor: result.nextCursor });
|
|
112
|
+
} else if (method === 'POST') {
|
|
113
|
+
const body = usageFields(await readBody(req, 8192), ['request_key', 'source_id', 'kind', 'label', 'user_id'], ['request_key', 'source_id', 'kind', 'label', 'user_id']);
|
|
114
|
+
usageAssert(body.kind === 'personal' || body.kind === 'organization', 'USAGE_INVALID_INPUT', '请选择个人或组织账户。', 400);
|
|
115
|
+
await identity.requireUsageUser(usageKey(body.user_id, 'user_id'));
|
|
116
|
+
send(res, 200, await repository.createAccount({ requestId: usageRequestKey(body), sourceOwner: 'hub', sourceId: usageKey(body.source_id, 'source_id'), kind: body.kind, label: usageString(body.label, 'label'), userId: usageKey(body.user_id, 'user_id') }));
|
|
117
|
+
} else send(res, 405, { error: 'method_not_allowed' });
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
const restore = path.match(/^\/admin\/api\/usage\/accounts\/([A-Za-z0-9_.:-]+)\/restore$/);
|
|
121
|
+
if (restore && method === 'POST') {
|
|
122
|
+
const body = usageFields(await readBody(req, 4096), ['request_key','expected_revision'], ['request_key','expected_revision']);
|
|
123
|
+
send(res, 200, await getUsageDeletionRepository(repository).restoreAccount({ id: restore[1]!, requestKey: usageRequestKey(body), expectedRevision: usageRevision(body.expected_revision), actor: principal.username ?? 'admin-token' })); return true;
|
|
124
|
+
}
|
|
125
|
+
const member = path.match(/^\/admin\/api\/usage\/accounts\/([A-Za-z0-9_.:-]+)\/members\/([A-Za-z0-9_.:-]+)$/);
|
|
126
|
+
if (member && method === 'PUT') {
|
|
127
|
+
const body = usageFields(await readBody(req, 4096), ['request_key', 'state', 'expected_revision'], ['request_key', 'state', 'expected_revision']);
|
|
128
|
+
usageAssert(body.state === 'active' || body.state === 'revoked', 'USAGE_INVALID_INPUT', '成员状态不正确。', 400);
|
|
129
|
+
if (body.state === 'active') await identity.requireUsageUser(member[2]!);
|
|
130
|
+
send(res, 200, await repository.setMembership({ requestId: usageRequestKey(body), accountId: member[1]!, userId: member[2]!, state: body.state, expectedRevision: usageRevision(body.expected_revision), actor: principal.username ?? 'admin-token' })); return true;
|
|
131
|
+
}
|
|
132
|
+
const account = path.match(/^\/admin\/api\/usage\/accounts\/([A-Za-z0-9_.:-]+)(\/control)?$/);
|
|
133
|
+
if (account && method === 'GET' && !account[2]) {
|
|
134
|
+
const saved = await repository.getAccount(account[1]!, true);
|
|
135
|
+
usageAssert(saved, 'USAGE_RESOURCE_NOT_FOUND', '账户不存在或已删除。', 404);
|
|
136
|
+
const [members] = await repository.getPool().query('SELECT user_id AS userId,state,revision FROM bz_usage_members WHERE account_id=? ORDER BY user_id LIMIT 500', [account[1]!]);
|
|
137
|
+
send(res, 200, { account: saved, members }); return true;
|
|
138
|
+
}
|
|
139
|
+
if (account?.[2] && method === 'POST') {
|
|
140
|
+
const body = usageFields(await readBody(req, 4096), ['request_key','expected_revision','state'], ['request_key','expected_revision','state']);
|
|
141
|
+
usageAssert(body.state === 'active' || body.state === 'suspended', 'USAGE_INVALID_INPUT', '状态不正确。', 400);
|
|
142
|
+
send(res, 200, await repository.setAccountState({ requestId: usageRequestKey(body), accountId: account[1]!, expectedRevision: usageRevision(body.expected_revision), state: body.state, actor: principal.username ?? 'admin-token' })); return true;
|
|
143
|
+
}
|
|
144
|
+
send(res, 404, { error: 'not_found' });
|
|
145
|
+
} catch (error) { usageHttpError(res, error); }
|
|
146
|
+
return true;
|
|
147
|
+
}
|
package/src/routes/admin.ts
CHANGED
|
@@ -21,6 +21,8 @@ import { handleAdminConversationAuditFor } from './admin-conversation-audit';
|
|
|
21
21
|
import { handleAdminToolProviderApiFor } from './admin-tool-providers';
|
|
22
22
|
import { handleAdminBrandingApiFor } from './admin-branding';
|
|
23
23
|
import { handleAdminAgentClientsApiFor } from './admin-agent-clients';
|
|
24
|
+
import { handleAdminAgentTasksApiFor } from './admin-agent-tasks';
|
|
25
|
+
import { handleAdminUsageApiFor } from './admin-usage';
|
|
24
26
|
import { handleAdminDemoDatasetApiFor, type DemoDatasetServiceContract } from './admin-demo-dataset';
|
|
25
27
|
import { refreshTargets, type TargetRegistry } from '../core/targets/registry';
|
|
26
28
|
import type { AppConfig } from '../core/config/config';
|
|
@@ -92,6 +94,9 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
92
94
|
send(res, 200, deps.capabilities);
|
|
93
95
|
return true;
|
|
94
96
|
}
|
|
97
|
+
if (path === '/admin/api/usage' || path.startsWith('/admin/api/usage/')) {
|
|
98
|
+
return handleAdminUsageApiFor(configStore.usage ?? null, method, path, req, res, principal);
|
|
99
|
+
}
|
|
95
100
|
if (deps.demoDataset && await handleAdminDemoDatasetApiFor(
|
|
96
101
|
{ demoDataset: deps.demoDataset, refreshTargets: deps.refreshTargets },
|
|
97
102
|
method, path, req, res, principal,
|
|
@@ -109,6 +114,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
109
114
|
[/^\/admin\/api\/config-schemas/, 'audit:read', 'audit:read'],
|
|
110
115
|
[/^\/admin\/api\/cost/, 'runs:read', 'runs:read'], // 成本可观测=运行面只读
|
|
111
116
|
[/^\/admin\/api\/agent-clients/, 'clients:read', 'clients:write'],
|
|
117
|
+
[/^\/admin\/api\/agent-tasks/, 'clients:read', 'clients:write'],
|
|
112
118
|
[/^\/admin\/api\/clients/, 'clients:read', 'clients:write'],
|
|
113
119
|
[/^\/admin\/api\/credentials/, 'credentials:read', 'credentials:write'],
|
|
114
120
|
[/^\/admin\/api\/storage-buckets/, 'storage:read', 'storage:write'], // 含桶凭证,默认仅 admin(*)可管
|
|
@@ -198,6 +204,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
198
204
|
engineRuntime: deps.engineRuntime,
|
|
199
205
|
}, method, path, req, res, principal)) return true;
|
|
200
206
|
if (await handleAdminAgentClientsApiFor({ configStore, stateStore: deps.stateStore, now: deps.now }, method, path, req, res, principal)) return true;
|
|
207
|
+
if (await handleAdminAgentTasksApiFor(configStore, method, path, req, res, principal)) return true;
|
|
201
208
|
if (await handleAdminBrandingApiFor({ brandingProvider: deps.brandingProvider }, method, path, req, res)) return true;
|
|
202
209
|
if (await handleAdminAccessApiFor({ configStore, stateStore: deps.stateStore, now: deps.now }, method, path, req, res, principal)) return true;
|
|
203
210
|
if (await handleAdminToolProviderApiFor({ cfg: deps.cfg, configStore, stateStore: deps.stateStore, toolIndex: deps.toolIndex, now: deps.now, sleep: deps.sleep }, method, path, req, res, principal)) return true;
|