bailinghub 0.7.0 → 0.8.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 -9
- package/README.md +6 -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/CHANGELOG.en.md +11 -1
- package/docs/CHANGELOG.md +11 -1
- package/docs/COMPATIBILITY.en.md +2 -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/README.en.md +3 -0
- package/docs/README.md +3 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +2 -2
- package/docs/RELEASE_NOTES_NEXT.md +2 -2
- package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
- package/docs/RELEASE_NOTES_v0.8.0.md +62 -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//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -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 +1 -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 +1 -0
- package/scripts/verify-github-repo.mjs +1 -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/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/builtin-tools.ts +4 -0
- package/src/app/oss-edition.ts +1 -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 +9 -1
- package/src/routes/admin-agent-tasks.ts +32 -0
- package/src/routes/admin-tool-providers.test.ts +22 -0
- package/src/routes/admin-tool-providers.ts +9 -1
- package/src/routes/admin.ts +3 -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 +1 -0
- package/src/routes/run.ts +2 -1
- package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
- package/web/console/assets/{Accounts-ChL9k-XA.js → Accounts-BRCR3O0P.js} +1 -1
- package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
- package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
- package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
- package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
- package/web/console/assets/{Approvals-Bs6FGbp2.js → Approvals-BIbZvInm.js} +1 -1
- package/web/console/assets/{Audit-4WWYhkFM.js → Audit-KyPSmBdZ.js} +1 -1
- package/web/console/assets/{BrandLockup-D2GhCipL.js → BrandLockup-Sv5DU2G6.js} +1 -1
- package/web/console/assets/{Channels-CmoGpiCJ.js → Channels-B9n4fbxg.js} +1 -1
- package/web/console/assets/{ChatEntries-BFRMtwta.js → ChatEntries-xsOCUXi_.js} +1 -1
- package/web/console/assets/{Clients-DGkkSXyA.js → Clients-CI3DBDHf.js} +1 -1
- package/web/console/assets/{Cost-BmGt0MfS.js → Cost-JgNXQPlN.js} +1 -1
- package/web/console/assets/{Credentials-CR-sYINT.js → Credentials-B5UUUdt0.js} +1 -1
- package/web/console/assets/{Diagnostics-DAPbKSJp.js → Diagnostics-BMGciWQb.js} +1 -1
- package/web/console/assets/{Executors-CgpiT3o8.js → Executors-CRbboOCZ.js} +1 -1
- package/web/console/assets/{Kb-Cm9dVSQw.js → Kb-CgLNGjRp.js} +1 -1
- package/web/console/assets/{Login-CyUcsTZ_.js → Login-C52JmXzx.js} +1 -1
- package/web/console/assets/{Projects-DldFPgWg.js → Projects-CDOvHPVS.js} +1 -1
- package/web/console/assets/{Routes-DubfjlBD.js → Routes-X9vHLpKW.js} +1 -1
- package/web/console/assets/{Runs-1hxgkuR4.js → Runs-DYNDXsqk.js} +1 -1
- package/web/console/assets/{Setup-DBLOnI2_.js → Setup-B91P6i1x.js} +1 -1
- package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
- package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
- package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
- package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
- package/web/console/assets/{SystemSettings-cDkudo2y.js → SystemSettings-B7Mqj3k1.js} +1 -1
- package/web/console/assets/{SystemStatus-DZd6s8OX.js → SystemStatus-Db93b6dc.js} +1 -1
- package/web/console/assets/{Targets-DYNGq1NU.js → Targets-CuuIYeZO.js} +1 -1
- package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
- package/web/console/assets/Tools-DU8ei6sd.css +1 -0
- package/web/console/assets/index-UGvfF3Xr.js +2 -0
- package/web/console/assets/{request-B7MLvOqo.js → request-DeGya810.js} +1 -1
- package/web/console/assets/{schema-CMuwjYdJ.js → schema-BqlqLw1R.js} +1 -1
- package/web/console/index.html +1 -1
- 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/layout/Shell.vue +1 -1
- package/web-admin/src/pages/AgentClients.vue +3 -1
- package/web-admin/src/pages/AgentTasks.vue +281 -0
- package/web-admin/src/pages/StorageBuckets.vue +6 -6
- package/web-admin/src/pages/Tools.vue +53 -4
- package/web-admin/src/router.ts +2 -0
- package/web/console/assets/AgentClients-Bs7UgVDj.js +0 -1
- package/web/console/assets/AgentClients-DkgPTEbq.css +0 -1
- package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
- package/web/console/assets/Shell-gJ5Vz_E7.js +0 -1
- package/web/console/assets/StorageBuckets-DkDW16tj.js +0 -1
- package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
- package/web/console/assets/Tools-A20oaMaQ.css +0 -1
- package/web/console/assets/Tools-DpWM59vV.js +0 -2
- package/web/console/assets/index-DGqs28gI.js +0 -2
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import mysql from 'mysql2/promise';
|
|
5
|
+
import { RateLimitLedger } from './config-rate-limit-ledger';
|
|
6
|
+
import { ToolProviderRepository } from './config-tool-provider-repository';
|
|
7
|
+
import { migrateBailingHubCoreSchema } from '../schema/core-schema-migrator';
|
|
8
|
+
import type { MysqlConfig } from '../../core/config/config';
|
|
9
|
+
|
|
10
|
+
test('isolated MySQL: migration, persisted policies, 120/hour and concurrent all-gate admission', { skip: !process.env.BAILING_RATE_TEST_MYSQL_PORT }, async () => {
|
|
11
|
+
const port = Number(process.env.BAILING_RATE_TEST_MYSQL_PORT);
|
|
12
|
+
const database = `rate_test_${randomBytes(8).toString('hex')}`;
|
|
13
|
+
const admin = await mysql.createConnection({ host: '127.0.0.1', port, user: 'root' });
|
|
14
|
+
await admin.query(`CREATE DATABASE ${database}`);
|
|
15
|
+
const config = { host: '127.0.0.1', port, user: 'root', password: '', database, timezone: 'Z', connectionLimit: 8 };
|
|
16
|
+
const pool = mysql.createPool({ ...config, connectionLimit: 8 });
|
|
17
|
+
try {
|
|
18
|
+
const migration = await migrateBailingHubCoreSchema({ mysql: config as MysqlConfig, logger: { log() {}, warn() {} } });
|
|
19
|
+
assert.ok(migration.appliedFiles.includes('061_tool_rate_limit_policies.sql'));
|
|
20
|
+
assert.equal((await migrateBailingHubCoreSchema({ mysql: config as MysqlConfig, logger: { log() {}, warn() {} } })).appliedFiles.length, 0);
|
|
21
|
+
const repository = new ToolProviderRepository(() => pool);
|
|
22
|
+
await repository.upsert({ name: 'store', base_url: 'https://business.invalid', spec_source: 'inline', secret: 'synthetic', log_payload: false,
|
|
23
|
+
timeout_ms: 10000, rate_limit_per_min: 0, auto_refresh_min: 0, enabled: true,
|
|
24
|
+
tool_rate_limits: { default: { mode: 'disabled' }, overrides: { images_update: { mode: 'custom', count: 1000, window: '1h' } } } });
|
|
25
|
+
const saved = (await repository.get('store'))!;
|
|
26
|
+
await repository.upsert({ ...saved, description: 'refreshed metadata' });
|
|
27
|
+
assert.deepEqual((await repository.get('store'))!.tool_rate_limits, saved.tool_rate_limits);
|
|
28
|
+
const ledger = new RateLimitLedger(() => pool);
|
|
29
|
+
const tool = { bucket: 'tool:store:images_update', limit: 120, windowSec: 3600 };
|
|
30
|
+
for (let i = 0; i < 120; i++) assert.equal((await ledger.consumeAll([tool])).limited, false);
|
|
31
|
+
assert.equal((await ledger.consumeAll([tool])).limited, true);
|
|
32
|
+
await pool.query('UPDATE bz_rate_limits SET created_at=DATE_SUB(UTC_TIMESTAMP(), INTERVAL 61 SECOND)');
|
|
33
|
+
assert.equal((await ledger.consumeAll([tool])).limited, true);
|
|
34
|
+
await pool.query('UPDATE bz_rate_limits SET created_at=DATE_SUB(UTC_TIMESTAMP(), INTERVAL 3601 SECOND)');
|
|
35
|
+
assert.equal((await ledger.consumeAll([tool])).limited, false);
|
|
36
|
+
await ledger.clear(tool.bucket);
|
|
37
|
+
const provider = { bucket: 'provider:store', limit: 3, windowSec: 60 };
|
|
38
|
+
const gates = [{ ...tool, limit: 20 }, provider];
|
|
39
|
+
const results = await Promise.all(Array.from({ length: 12 }, () => ledger.consumeAll(gates)));
|
|
40
|
+
assert.equal(results.filter((r) => !r.limited).length, 3);
|
|
41
|
+
assert.equal(await ledger.count(tool.bucket, 3600), 3);
|
|
42
|
+
assert.equal(await ledger.count(provider.bucket, 60), 3);
|
|
43
|
+
// Saturated tool cannot consume the provider gate; a third tool still has the full provider quota.
|
|
44
|
+
await ledger.clear(provider.bucket);
|
|
45
|
+
assert.equal((await ledger.consumeAll([{ ...tool, limit: 3 }, provider])).limited, true);
|
|
46
|
+
assert.equal(await ledger.count(provider.bucket, 60), 0);
|
|
47
|
+
} finally {
|
|
48
|
+
await pool.end();
|
|
49
|
+
await admin.query(`DROP DATABASE ${database}`);
|
|
50
|
+
await admin.end();
|
|
51
|
+
}
|
|
52
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { dt, dtAt } from '../../core/config/config-codec';
|
|
3
|
+
import type { RateLimitDecision, RateLimitRequest } from '../../core/contracts/tool-rate-limits';
|
|
3
4
|
|
|
4
5
|
export class RateLimitLedger {
|
|
5
6
|
constructor(private readonly poolOf: () => any) {}
|
|
@@ -53,4 +54,51 @@ export class RateLimitLedger {
|
|
|
53
54
|
async clear(bucket: string): Promise<void> {
|
|
54
55
|
await this.pool.query('DELETE FROM bz_rate_limits WHERE bucket=?', [bucket]);
|
|
55
56
|
}
|
|
57
|
+
|
|
58
|
+
/** One connection, deterministic locks and one transaction: a rejected gate charges no other gate. */
|
|
59
|
+
async consumeAll(requests: RateLimitRequest[]): Promise<RateLimitDecision> {
|
|
60
|
+
const gates = requests.filter((gate) => gate.limit > 0);
|
|
61
|
+
if (!gates.length) return { limited: false };
|
|
62
|
+
const conn = await this.pool.getConnection();
|
|
63
|
+
const locks: string[] = [];
|
|
64
|
+
let transaction = false;
|
|
65
|
+
try {
|
|
66
|
+
for (const bucket of [...new Set(gates.map((gate) => gate.bucket))].sort()) {
|
|
67
|
+
const name = this.lockName(bucket);
|
|
68
|
+
const [rows] = await conn.query('SELECT GET_LOCK(?, 2) AS ok', [name]);
|
|
69
|
+
if (Number(rows[0]?.ok) !== 1) throw new Error('rate limit lock timeout');
|
|
70
|
+
locks.push(name);
|
|
71
|
+
}
|
|
72
|
+
await conn.beginTransaction();
|
|
73
|
+
transaction = true;
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
for (const gate of gates) {
|
|
76
|
+
const cutoff = dtAt(now - gate.windowSec * 1000);
|
|
77
|
+
const [rows] = await conn.query('SELECT COUNT(*) AS n FROM bz_rate_limits WHERE bucket=? AND created_at > ?', [gate.bucket, cutoff]);
|
|
78
|
+
const count = Number(rows[0]?.n ?? 0);
|
|
79
|
+
if (count >= gate.limit) {
|
|
80
|
+
// Offset handles a limit lowered while the original window is still occupied.
|
|
81
|
+
const [expiry] = await conn.query('SELECT created_at FROM bz_rate_limits WHERE bucket=? AND created_at > ? ORDER BY created_at, id LIMIT 1 OFFSET ?', [gate.bucket, cutoff, count - gate.limit]);
|
|
82
|
+
const raw = expiry[0]?.created_at;
|
|
83
|
+
const oldest = raw instanceof Date ? raw.getTime() : Date.parse(String(raw).replace(' ', 'T') + 'Z');
|
|
84
|
+
await conn.rollback();
|
|
85
|
+
transaction = false;
|
|
86
|
+
return { limited: true, bucket: gate.bucket, retryAfterMs: Number.isFinite(oldest) ? Math.max(1, oldest + gate.windowSec * 1000 - now) : gate.windowSec * 1000 };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
for (const gate of gates) {
|
|
90
|
+
await conn.query('DELETE FROM bz_rate_limits WHERE bucket=? AND created_at <= ?', [gate.bucket, dtAt(now - gate.windowSec * 1000)]);
|
|
91
|
+
await conn.query('INSERT INTO bz_rate_limits (bucket, created_at) VALUES (?, ?)', [gate.bucket, dtAt(now)]);
|
|
92
|
+
}
|
|
93
|
+
await conn.commit();
|
|
94
|
+
transaction = false;
|
|
95
|
+
return { limited: false };
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (transaction) await conn.rollback().catch(() => undefined);
|
|
98
|
+
throw error;
|
|
99
|
+
} finally {
|
|
100
|
+
for (const name of locks.reverse()) await conn.query('SELECT RELEASE_LOCK(?)', [name]).catch(() => undefined);
|
|
101
|
+
conn.release();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
56
104
|
}
|
|
@@ -19,12 +19,12 @@ export class StorageBucketRepository {
|
|
|
19
19
|
/** 新建/更新。编辑时 access_key / secret_key 传空 = 保留原值(列表不回显完整凭证,没法回填)。 */
|
|
20
20
|
async upsert(b: StorageBucket): Promise<void> {
|
|
21
21
|
const existing = (!b.secret_key || !b.access_key) ? await this.get(b.name) : null;
|
|
22
|
-
let sk = b.secret_key;
|
|
22
|
+
let sk = b.kind === 'local' ? 'local' : b.secret_key;
|
|
23
23
|
if (!sk) {
|
|
24
24
|
if (!existing) throw new Error('新建存储桶必须填 SecretKey');
|
|
25
25
|
sk = existing.secret_key;
|
|
26
26
|
}
|
|
27
|
-
let ak = b.access_key;
|
|
27
|
+
let ak = b.kind === 'local' ? 'local' : b.access_key;
|
|
28
28
|
if (!ak) {
|
|
29
29
|
if (!existing) throw new Error('新建存储桶必须填 SecretId / AccessKeyId');
|
|
30
30
|
ak = existing.access_key;
|
|
@@ -32,10 +32,10 @@ export class ToolProviderRepository {
|
|
|
32
32
|
? p.spec_access_policy
|
|
33
33
|
: null;
|
|
34
34
|
await this.pool.query(
|
|
35
|
-
'INSERT INTO bz_tool_providers (name,base_url,spec_source,spec_access_policy,spec_url,spec_json,spec_refreshed_at,spec_access_probe_json,authz_probe_json,secret,log_payload,timeout_ms,rate_limit_per_min,auto_refresh_min,enabled,description,embed_credential,embed_model,embed_dim,created_at,updated_at) ' +
|
|
36
|
-
'VALUES (
|
|
35
|
+
'INSERT INTO bz_tool_providers (name,base_url,spec_source,spec_access_policy,spec_url,spec_json,spec_refreshed_at,spec_access_probe_json,authz_probe_json,secret,log_payload,timeout_ms,rate_limit_per_min,auto_refresh_min,enabled,description,embed_credential,embed_model,embed_dim,created_at,updated_at,tool_rate_limits_json) ' +
|
|
36
|
+
'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' +
|
|
37
37
|
(updateExisting
|
|
38
|
-
? 'ON DUPLICATE KEY UPDATE base_url=VALUES(base_url),spec_source=VALUES(spec_source),spec_access_policy=VALUES(spec_access_policy),spec_url=VALUES(spec_url),spec_json=VALUES(spec_json),spec_refreshed_at=VALUES(spec_refreshed_at),spec_access_probe_json=VALUES(spec_access_probe_json),authz_probe_json=VALUES(authz_probe_json),secret=VALUES(secret),log_payload=VALUES(log_payload),timeout_ms=VALUES(timeout_ms),rate_limit_per_min=VALUES(rate_limit_per_min),auto_refresh_min=VALUES(auto_refresh_min),enabled=VALUES(enabled),description=VALUES(description),embed_credential=VALUES(embed_credential),embed_model=VALUES(embed_model),embed_dim=VALUES(embed_dim),updated_at=VALUES(updated_at)'
|
|
38
|
+
? 'ON DUPLICATE KEY UPDATE base_url=VALUES(base_url),spec_source=VALUES(spec_source),spec_access_policy=VALUES(spec_access_policy),spec_url=VALUES(spec_url),spec_json=VALUES(spec_json),spec_refreshed_at=VALUES(spec_refreshed_at),spec_access_probe_json=VALUES(spec_access_probe_json),authz_probe_json=VALUES(authz_probe_json),secret=VALUES(secret),log_payload=VALUES(log_payload),timeout_ms=VALUES(timeout_ms),rate_limit_per_min=VALUES(rate_limit_per_min),auto_refresh_min=VALUES(auto_refresh_min),enabled=VALUES(enabled),description=VALUES(description),embed_credential=VALUES(embed_credential),embed_model=VALUES(embed_model),embed_dim=VALUES(embed_dim),updated_at=VALUES(updated_at),tool_rate_limits_json=VALUES(tool_rate_limits_json)'
|
|
39
39
|
: ''),
|
|
40
40
|
[p.name, p.base_url, p.spec_source, specAccessPolicy, p.spec_url ?? null, p.spec_json ?? null,
|
|
41
41
|
p.spec_refreshed_at ? p.spec_refreshed_at.slice(0, 19).replace('T', ' ') : null,
|
|
@@ -43,7 +43,7 @@ export class ToolProviderRepository {
|
|
|
43
43
|
p.authz_probe ? JSON.stringify(p.authz_probe) : null,
|
|
44
44
|
p.secret, p.log_payload ? 1 : 0, p.timeout_ms, p.rate_limit_per_min, p.auto_refresh_min,
|
|
45
45
|
p.enabled ? 1 : 0, p.description ?? null,
|
|
46
|
-
p.embed_credential ?? null, p.embed_model ?? null, p.embed_dim ?? null, dt(), dt()],
|
|
46
|
+
p.embed_credential ?? null, p.embed_model ?? null, p.embed_dim ?? null, dt(), dt(), p.tool_rate_limits ? JSON.stringify(p.tool_rate_limits) : null],
|
|
47
47
|
);
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -25,8 +25,10 @@ import { MysqlKbDatasourceRepository, MysqlKnowledgeRepository } from './config-
|
|
|
25
25
|
import { InstanceBrandingRepository } from './config-instance-branding-repository';
|
|
26
26
|
import type { InstanceBrandingRepositoryContract } from './config-instance-branding-repository';
|
|
27
27
|
import { AgentAuthRepository, type AgentAuthRepositoryContract } from './config-agent-auth-repository';
|
|
28
|
+
import { AgentArtifactRepository } from './config-agent-artifact-repository';
|
|
28
29
|
import { AgentClientRuntimeRepository } from './config-agent-client-runtime-repository';
|
|
29
30
|
import { AgentConversationAuditRepository } from './config-agent-conversation-audit-repository';
|
|
31
|
+
import { AgentTaskControlRepository } from './config-agent-task-control-repository';
|
|
30
32
|
import { MysqlPoolOwner, type MysqlPoolResource } from '../mysql/pool-owner';
|
|
31
33
|
|
|
32
34
|
export type RouteRepositoryContract = Omit<Pick<RouteRepository, keyof RouteRepository>, 'compareAndSetAgentSetup'>
|
|
@@ -46,7 +48,8 @@ export type TargetRepositoryContract = Pick<TargetRepository, keyof TargetReposi
|
|
|
46
48
|
export type StorageBucketRepositoryContract = Pick<StorageBucketRepository, keyof StorageBucketRepository>;
|
|
47
49
|
export type AlertRuleRepositoryContract = Pick<AlertRuleRepository, keyof AlertRuleRepository>;
|
|
48
50
|
export type ChatConfigRepositoryContract = Pick<ChatConfigRepository, keyof ChatConfigRepository>;
|
|
49
|
-
export type RateLimitLedgerContract = Pick<RateLimitLedger, keyof RateLimitLedger
|
|
51
|
+
export type RateLimitLedgerContract = Omit<Pick<RateLimitLedger, keyof RateLimitLedger>, 'consumeAll'>
|
|
52
|
+
& Partial<Pick<RateLimitLedger, 'consumeAll'>>;
|
|
50
53
|
export type ApprovalLedgerContract =
|
|
51
54
|
Omit<Pick<ApprovalLedger, keyof ApprovalLedger>, 'forJobs'>
|
|
52
55
|
& Partial<Pick<ApprovalLedger, 'forJobs'>>;
|
|
@@ -92,11 +95,14 @@ export interface ConfigStoreContract {
|
|
|
92
95
|
readonly deliveryDlq: DeliveryDlqLedgerContract;
|
|
93
96
|
readonly observability: ObservabilityLedgerContract;
|
|
94
97
|
/** 新 Agent Auth 能力对旧宿主仓储保持可选;缺失时 HTTP 面 fail closed。 */
|
|
98
|
+
readonly agentArtifacts?: Pick<AgentArtifactRepository, keyof AgentArtifactRepository>;
|
|
95
99
|
readonly agentAuth?: AgentAuthRepositoryContract;
|
|
96
100
|
/** Agent Client Runtime v1 对旧宿主保持可选;缺失时新 API fail closed。 */
|
|
97
101
|
readonly agentClientRuntime?: AgentClientRuntimeRepositoryContract;
|
|
98
102
|
/** Optional, admin-only visible transcript ledger; never a source of Agent memory. */
|
|
99
103
|
readonly agentConversationAudit?: AgentConversationAuditRepositoryContract;
|
|
104
|
+
/** Optional for extension hosts. Managed Sessions must never fall back without this repository. */
|
|
105
|
+
readonly agentTaskControl?: Pick<AgentTaskControlRepository, keyof AgentTaskControlRepository>;
|
|
100
106
|
init(): Promise<void>;
|
|
101
107
|
close?(): Promise<void>;
|
|
102
108
|
readonly db: Pool;
|
|
@@ -130,8 +136,10 @@ export class ConfigStore implements ConfigStoreContract {
|
|
|
130
136
|
readonly deliveryDlq = new DeliveryDlqLedger(() => this.pool);
|
|
131
137
|
readonly observability = new ObservabilityLedger(() => this.pool);
|
|
132
138
|
readonly agentAuth = new AgentAuthRepository(() => this.pool);
|
|
139
|
+
readonly agentArtifacts = new AgentArtifactRepository(() => this.pool);
|
|
133
140
|
readonly agentClientRuntime = new AgentClientRuntimeRepository(() => this.pool);
|
|
134
141
|
readonly agentConversationAudit = new AgentConversationAuditRepository(() => this.pool);
|
|
142
|
+
readonly agentTaskControl = new AgentTaskControlRepository(() => this.pool);
|
|
135
143
|
|
|
136
144
|
constructor(cfg: AppConfig['state']['mysql'], poolOwner?: MysqlPoolResource) {
|
|
137
145
|
this.poolOwner = poolOwner ?? new MysqlPoolOwner(cfg);
|
|
@@ -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
|
+
}
|
|
@@ -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
|
|
package/src/routes/admin.ts
CHANGED
|
@@ -21,6 +21,7 @@ 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';
|
|
24
25
|
import { handleAdminDemoDatasetApiFor, type DemoDatasetServiceContract } from './admin-demo-dataset';
|
|
25
26
|
import { refreshTargets, type TargetRegistry } from '../core/targets/registry';
|
|
26
27
|
import type { AppConfig } from '../core/config/config';
|
|
@@ -109,6 +110,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
109
110
|
[/^\/admin\/api\/config-schemas/, 'audit:read', 'audit:read'],
|
|
110
111
|
[/^\/admin\/api\/cost/, 'runs:read', 'runs:read'], // 成本可观测=运行面只读
|
|
111
112
|
[/^\/admin\/api\/agent-clients/, 'clients:read', 'clients:write'],
|
|
113
|
+
[/^\/admin\/api\/agent-tasks/, 'clients:read', 'clients:write'],
|
|
112
114
|
[/^\/admin\/api\/clients/, 'clients:read', 'clients:write'],
|
|
113
115
|
[/^\/admin\/api\/credentials/, 'credentials:read', 'credentials:write'],
|
|
114
116
|
[/^\/admin\/api\/storage-buckets/, 'storage:read', 'storage:write'], // 含桶凭证,默认仅 admin(*)可管
|
|
@@ -198,6 +200,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
198
200
|
engineRuntime: deps.engineRuntime,
|
|
199
201
|
}, method, path, req, res, principal)) return true;
|
|
200
202
|
if (await handleAdminAgentClientsApiFor({ configStore, stateStore: deps.stateStore, now: deps.now }, method, path, req, res, principal)) return true;
|
|
203
|
+
if (await handleAdminAgentTasksApiFor(configStore, method, path, req, res, principal)) return true;
|
|
201
204
|
if (await handleAdminBrandingApiFor({ brandingProvider: deps.brandingProvider }, method, path, req, res)) return true;
|
|
202
205
|
if (await handleAdminAccessApiFor({ configStore, stateStore: deps.stateStore, now: deps.now }, method, path, req, res, principal)) return true;
|
|
203
206
|
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;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
2
3
|
import { Readable } from 'node:stream';
|
|
3
4
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
5
|
import test from 'node:test';
|
|
@@ -191,6 +192,74 @@ test('Agent Tool API: pause 在读取请求与工具治理链前拦截 invoke/re
|
|
|
191
192
|
assert.equal(resume.json()['error'], 'hub_paused');
|
|
192
193
|
});
|
|
193
194
|
|
|
195
|
+
test('Agent receipt HTTP: authenticated capability negotiation and inspection work during global pause', async () => {
|
|
196
|
+
const fx = runtimeHttpFixture();
|
|
197
|
+
const headers = { authorization: `Bearer ${fx.token}` };
|
|
198
|
+
const session = (await fx.deps.configStore.agentAuth!.getSessionByAccessHash(tokenHash(fx.token)))!;
|
|
199
|
+
const invocationId = 'a'.repeat(64);
|
|
200
|
+
const runId = '22222222-2222-4222-8222-222222222222';
|
|
201
|
+
const requestId = `agent-tool:${createHash('sha256').update(`bailing.agent-tool.v1\0${session.session_id}\0${invocationId}`).digest('hex')}`;
|
|
202
|
+
const job: Job = {
|
|
203
|
+
job_id: '33333333-3333-4333-8333-333333333333', request_id: requestId, target: 'agent-tool-v1',
|
|
204
|
+
status: 'done', profile: 'general', project: '', source: `agent-tool:${session.client_app_id}`,
|
|
205
|
+
client_app_id: session.client_app_id, agent_session_id: session.session_id, session_id: runId,
|
|
206
|
+
on_behalf_of: session.on_behalf_of, input_preview: 'Synthetic invocation',
|
|
207
|
+
metadata: {
|
|
208
|
+
agent_tool_job_marker: 'bailing.agent-tool-job.v1', agent_tool_call_v1: true,
|
|
209
|
+
agent_invocation_id: invocationId, agent_run_id: runId, agent_route: 'allowed', agent_tool: 'staff_list',
|
|
210
|
+
agent_args_hash: 'b'.repeat(64), agent_capability_revision: 'c'.repeat(64), agent_execution_fingerprint: 'd'.repeat(64),
|
|
211
|
+
agent_dispatch_attempted: true, principal: session.principal,
|
|
212
|
+
},
|
|
213
|
+
dispatch: { route_key: 'allowed' },
|
|
214
|
+
result: {
|
|
215
|
+
schema_version: 'bailing.agent-tool-invocation.v1', invocation_id: invocationId, route: 'allowed', tool: 'staff_list',
|
|
216
|
+
state: 'executed', ok: true, auto_retry_allowed: false, text: 'Synthetic result', business_status: 200,
|
|
217
|
+
},
|
|
218
|
+
created_at: '2026-01-01T00:00:00.000Z', updated_at: '2026-01-01T00:00:00.000Z',
|
|
219
|
+
};
|
|
220
|
+
const before = JSON.stringify(job);
|
|
221
|
+
let stateReads = 0;
|
|
222
|
+
fx.deps.stateStore.findByRequestId = async (id: string) => { stateReads++; return id === requestId ? job : null; };
|
|
223
|
+
fx.deps.configStore.toolCalls.get = async () => null;
|
|
224
|
+
fx.deps.configStore.approvals.forJob = async () => [];
|
|
225
|
+
const denied = async () => { throw new Error('unexpected_inspection_mutation'); };
|
|
226
|
+
fx.deps.stateStore.createJob = denied;
|
|
227
|
+
fx.deps.stateStore.updateJob = denied;
|
|
228
|
+
fx.deps.stateStore.acquireRuntimeLock = denied;
|
|
229
|
+
fx.deps.stateStore.appendAudit = denied;
|
|
230
|
+
fx.deps.isPaused = () => true;
|
|
231
|
+
const capabilityUrl = new URL('https://hub.example.com/agent-api/v1/tool-invocations/inspection-capabilities');
|
|
232
|
+
const receiptUrl = new URL(`https://hub.example.com/agent-api/v1/tool-invocations/${invocationId}/receipt`);
|
|
233
|
+
const capabilities = new FakeResponse();
|
|
234
|
+
await handleAgentApiHttpFor(fx.deps, request('GET', headers), capabilities as unknown as ServerResponse, capabilityUrl);
|
|
235
|
+
assert.deepEqual(capabilities.json(), {
|
|
236
|
+
schema_version: 'bailing.agent-invocation-inspection-capabilities.v1',
|
|
237
|
+
receipt_schema: 'bailing.agent-invocation-receipt.v1', read_only: true,
|
|
238
|
+
});
|
|
239
|
+
assert.equal(stateReads, 0);
|
|
240
|
+
const response = new FakeResponse();
|
|
241
|
+
await handleAgentApiHttpFor(fx.deps, request('GET', headers), response as unknown as ServerResponse, receiptUrl);
|
|
242
|
+
assert.equal(response.statusCode, 200);
|
|
243
|
+
assert.equal(response.headers['cache-control'], 'no-store');
|
|
244
|
+
assert.equal(response.json()['read_only'], true);
|
|
245
|
+
assert.equal(response.json()['business_operation_performed'], false);
|
|
246
|
+
assert.equal((response.json()['result'] as Record<string, unknown>)['text'], 'Synthetic result');
|
|
247
|
+
assert.equal(stateReads, 1);
|
|
248
|
+
assert.equal(JSON.stringify(job), before);
|
|
249
|
+
|
|
250
|
+
for (const url of [capabilityUrl, receiptUrl]) {
|
|
251
|
+
const anonymous = new FakeResponse();
|
|
252
|
+
await handleAgentApiHttpFor(fx.deps, request('GET'), anonymous as unknown as ServerResponse, url);
|
|
253
|
+
assert.equal(anonymous.statusCode, 401);
|
|
254
|
+
const changed = new URL(url);
|
|
255
|
+
changed.searchParams.set('route', 'another-target');
|
|
256
|
+
const parameters = new FakeResponse();
|
|
257
|
+
await handleAgentApiHttpFor(fx.deps, request('GET', headers), parameters as unknown as ServerResponse, changed);
|
|
258
|
+
assert.equal(parameters.statusCode, 400);
|
|
259
|
+
}
|
|
260
|
+
assert.equal(stateReads, 1, 'rejected inspection envelopes must not read invocation records');
|
|
261
|
+
});
|
|
262
|
+
|
|
194
263
|
function runtimeHttpFixture() {
|
|
195
264
|
const token = `bha_${'r'.repeat(43)}`;
|
|
196
265
|
const client: Client = {
|
|
@@ -264,6 +333,8 @@ function runtimeHttpFixture() {
|
|
|
264
333
|
toolProviders: { get: async () => provider },
|
|
265
334
|
conversations: { getThreadMemory: async () => ({ summary: null, summary_upto_id: 0 }), recentMessagesAfter: async () => [] },
|
|
266
335
|
agentClientRuntime: runtimeRepo,
|
|
336
|
+
toolCalls: { get: async () => null },
|
|
337
|
+
approvals: { forJob: async () => [] },
|
|
267
338
|
} as unknown as ConfigStoreContract;
|
|
268
339
|
const stateStore = { appendAudit: async () => undefined } as unknown as RuntimeStateStore;
|
|
269
340
|
const toolProxyDeps: ToolProxyDeps = {
|
|
@@ -376,4 +447,9 @@ test('Agent Runtime HTTP: 客户端文本与 renderers 非法时 400,空搜索
|
|
|
376
447
|
await handleAgentApiHttpFor(fx.deps, request('POST', headers, { run_id: 'a23e4567-e89b-42d3-a456-426614174000' }), search as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/capabilities/search'));
|
|
377
448
|
assert.equal(search.statusCode, 200, JSON.stringify(search.json()));
|
|
378
449
|
assert.equal(search.json()['query'], '查询员工');
|
|
450
|
+
assert.deepEqual(search.json()['discovery'], {
|
|
451
|
+
mode: 'ranked_candidates', scope: 'current_authorization', returned_count: 1, authorized_total: 1,
|
|
452
|
+
matched_total: null, matched_total_exact: false, limit: 1, truncated: false, has_more: false,
|
|
453
|
+
truncation_scope: 'authorized_catalog', pagination: 'unsupported',
|
|
454
|
+
}, 'HTTP serialization must preserve discovery semantics for SDK and host consumers');
|
|
379
455
|
});
|
package/src/routes/agent-api.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { handleAgentArtifacts } from './agent-artifacts';
|
|
1
2
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
3
|
import { PayloadTooLargeError, readBody, send } from '../app/http';
|
|
3
4
|
import type { Principal } from '../app/auth';
|
|
4
5
|
import type { ToolProxyDeps } from '../app/tool-proxy';
|
|
5
6
|
import {
|
|
6
7
|
AgentToolApiError,
|
|
8
|
+
agentInvocationInspectionCapabilities,
|
|
9
|
+
inspectAgentToolInvocationFor,
|
|
7
10
|
invokeAgentToolFor,
|
|
8
11
|
listAgentToolsFor,
|
|
9
12
|
resumeAgentToolFor,
|
|
@@ -15,6 +18,8 @@ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
|
15
18
|
import { authenticateAgentAccess } from './agent-auth';
|
|
16
19
|
import { handleAgentConversationAuditFor } from './agent-conversation-audit';
|
|
17
20
|
import { getAgentSystemInfoFor } from '../app/agent-system-info';
|
|
21
|
+
import { agentTaskCapabilitiesFor, inspectAgentTaskFor, assertAgentLegacyTaskAllowedFor, taskErrorStatus, publicAgentTaskError } from '../app/agent-task-control';
|
|
22
|
+
import { AgentTaskControlError } from '../core/runtime/agent-task-control';
|
|
18
23
|
import type { KbService } from '../services/kb';
|
|
19
24
|
import {
|
|
20
25
|
completeAgentRunFor,
|
|
@@ -33,6 +38,7 @@ export interface AgentApiHttpDeps {
|
|
|
33
38
|
/** 未注入时仅关闭新的无模型直调面,保持旧宿主的 Agent Auth / run 兼容。 */
|
|
34
39
|
toolProxyDeps?: ToolProxyDeps;
|
|
35
40
|
kbService?: KbService | null;
|
|
41
|
+
artifactRoot?: string;
|
|
36
42
|
}
|
|
37
43
|
|
|
38
44
|
// 64000 个 UTF-16 code units 在 JSON 中最坏可被转义为约 384 KB;512 KiB 还可容纳
|
|
@@ -55,6 +61,11 @@ function declaredFields(body: Record<string, unknown>, allowedFields: string[],
|
|
|
55
61
|
}
|
|
56
62
|
|
|
57
63
|
function sendAgentToolError(res: ServerResponse, error: unknown): void {
|
|
64
|
+
if (error instanceof AgentTaskControlError) {
|
|
65
|
+
const visible = publicAgentTaskError(error);
|
|
66
|
+
send(res, taskErrorStatus(visible), { error: visible.code, message: visible.message });
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
58
69
|
if (error instanceof AgentToolApiError) {
|
|
59
70
|
send(res, error.statusCode, { error: error.code, message: error.message });
|
|
60
71
|
return;
|
|
@@ -93,6 +104,19 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
93
104
|
if (!auth) { send(res, 401, { error: 'unauthorized' }); return true; }
|
|
94
105
|
const principal: Principal = { kind: 'agent', session: auth.session, client: auth.client };
|
|
95
106
|
const method = req.method ?? 'GET';
|
|
107
|
+
if (method === 'GET' && path === '/agent-api/v1/task-control/capabilities') {
|
|
108
|
+
try { send(res, 200, await agentTaskCapabilitiesFor(deps.configStore, auth, Boolean(deps.toolProxyDeps))); }
|
|
109
|
+
catch { send(res, 503, { error: 'TASK_UNAVAILABLE', message: 'Task control could not be verified.' }); }
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
const taskMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/tasks\/([0-9a-f-]{36})$/i) : null;
|
|
113
|
+
if (taskMatch) {
|
|
114
|
+
try { send(res, 200, await inspectAgentTaskFor(deps.configStore, auth, taskMatch[1]!,
|
|
115
|
+
url.searchParams.get('workspace') ?? '', url.searchParams.get('client_conversation_id') ?? '')); }
|
|
116
|
+
catch (error) { sendAgentToolError(res, error); }
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
if (await handleAgentArtifacts({ configStore: deps.configStore, root: deps.artifactRoot, isPaused: deps.isPaused }, auth, req, res, path)) return true;
|
|
96
120
|
if (await handleAgentConversationAuditFor(deps.configStore, auth, req, res, path)) return true;
|
|
97
121
|
const systemInfoMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/system-info$/) : null;
|
|
98
122
|
if (systemInfoMatch) {
|
|
@@ -125,7 +149,7 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
125
149
|
if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
|
|
126
150
|
const body = await readAgentToolBody(req, res, AGENT_RUNTIME_JSON_BODY_MAX_BYTES);
|
|
127
151
|
if (!body) return true;
|
|
128
|
-
if (!declaredFields(body, ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input', 'page_context', 'renderers'], ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input'])
|
|
152
|
+
if (!declaredFields(body, ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input', 'page_context', 'renderers', 'task_binding'], ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input'])
|
|
129
153
|
|| typeof body['client_conversation_id'] !== 'string'
|
|
130
154
|
|| typeof body['client_turn_id'] !== 'string'
|
|
131
155
|
|| typeof body['user_message_id'] !== 'string'
|
|
@@ -140,6 +164,7 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
140
164
|
user_message_id: body['user_message_id'], user_input: body['user_input'],
|
|
141
165
|
...(record(body['page_context']) ? { page_context: record(body['page_context'])! } : {}),
|
|
142
166
|
...(Array.isArray(body['renderers']) ? { renderers: body['renderers'] as string[] } : {}),
|
|
167
|
+
...(Object.hasOwn(body, 'task_binding') ? { task_binding: body['task_binding'] } : {}),
|
|
143
168
|
}));
|
|
144
169
|
} catch (error) { sendAgentToolError(res, error); }
|
|
145
170
|
return true;
|
|
@@ -199,6 +224,20 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
199
224
|
catch (error) { sendAgentToolError(res, error); }
|
|
200
225
|
return true;
|
|
201
226
|
}
|
|
227
|
+
if (method === 'GET' && path === '/agent-api/v1/tool-invocations/inspection-capabilities') {
|
|
228
|
+
if (!deps.toolProxyDeps || !deps.configStore) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
|
|
229
|
+
if (url.search) { send(res, 400, { error: 'invalid_request', message: 'Invocation inspection does not accept query parameters.' }); return true; }
|
|
230
|
+
send(res, 200, agentInvocationInspectionCapabilities());
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
const receiptMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/tool-invocations\/([a-f0-9]{64})\/receipt$/) : null;
|
|
234
|
+
if (receiptMatch) {
|
|
235
|
+
if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
|
|
236
|
+
if (url.search) { send(res, 400, { error: 'invalid_request', message: 'Invocation inspection does not accept query parameters.' }); return true; }
|
|
237
|
+
try { send(res, 200, await inspectAgentToolInvocationFor(deps.toolProxyDeps, auth, { invocation_id: receiptMatch[1]! })); }
|
|
238
|
+
catch (error) { sendAgentToolError(res, error); }
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
202
241
|
if (method === 'POST' && path === '/agent-api/v1/tool-invocations') {
|
|
203
242
|
if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
|
|
204
243
|
if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
|
|
@@ -243,6 +282,8 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
243
282
|
return true;
|
|
244
283
|
}
|
|
245
284
|
if (method === 'POST' && path === '/agent-api/v1/run') {
|
|
285
|
+
try { await assertAgentLegacyTaskAllowedFor(deps.configStore, auth.session.session_id); }
|
|
286
|
+
catch (error) { sendAgentToolError(res, error); return true; }
|
|
246
287
|
await deps.handleRun(req, res, principal);
|
|
247
288
|
return true;
|
|
248
289
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { send } from '../app/http';
|
|
3
|
+
import { AgentToolApiError, type AgentToolAuthContext } from '../app/agent-tool-invocations';
|
|
4
|
+
import { ARTIFACT_MAX_BYTES } from '../core/config/artifact-config';
|
|
5
|
+
import { artifactError, artifactMetadata, readAgentArtifact, uploadAgentArtifact, type ArtifactDeps } from '../app/agent-artifacts';
|
|
6
|
+
|
|
7
|
+
export async function handleAgentArtifacts(deps: ArtifactDeps & { isPaused: () => boolean }, auth: AgentToolAuthContext, req: IncomingMessage, res: ServerResponse, path: string): Promise<boolean> {
|
|
8
|
+
const m = path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/artifacts\/([a-f0-9]{64})$/);
|
|
9
|
+
if (!m) return false;
|
|
10
|
+
try {
|
|
11
|
+
if (req.method === 'GET') send(res, 200, await readAgentArtifact(deps, auth, m[1]!, m[2]!));
|
|
12
|
+
else if (req.method === 'POST') {
|
|
13
|
+
if (deps.isPaused()) artifactError(503, 'hub_paused');
|
|
14
|
+
const raw = req.headers['x-bailing-artifact'];
|
|
15
|
+
if (typeof raw !== 'string' || raw.length > 4096 || !/^[a-zA-Z0-9_-]+$/.test(raw)) artifactError(400, 'artifact_invalid_request');
|
|
16
|
+
let value: unknown;
|
|
17
|
+
try { value = JSON.parse(Buffer.from(raw as string, 'base64url').toString('utf8')); } catch { artifactError(400, 'artifact_invalid_request'); }
|
|
18
|
+
const metadata = artifactMetadata(value);
|
|
19
|
+
if (req.headers['content-type'] !== metadata.mime || (req.headers['content-length'] !== undefined && Number(req.headers['content-length']) !== metadata.bytes)) artifactError(400, 'artifact_content_mismatch');
|
|
20
|
+
const chunks: Buffer[] = []; let size = 0;
|
|
21
|
+
for await (const chunk of req) { const data = Buffer.from(chunk); size += data.length; if (size > Math.min(metadata.bytes, ARTIFACT_MAX_BYTES)) artifactError(413, 'artifact_too_large'); chunks.push(data); }
|
|
22
|
+
send(res, 200, await uploadAgentArtifact(deps, auth, m[1]!, m[2]!, metadata, Buffer.concat(chunks)));
|
|
23
|
+
} else send(res, 405, { error: 'method_not_allowed' });
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (error instanceof AgentToolApiError) send(res, error.statusCode, { error: error.code });
|
|
26
|
+
else send(res, 503, { error: 'artifact_storage_unavailable' });
|
|
27
|
+
}
|
|
28
|
+
return true;
|
|
29
|
+
}
|