bailinghub 0.4.0 → 0.5.1
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/.gitignore +5 -0
- package/README.en.md +5 -2
- package/README.md +6 -2
- package/SECURITY.md +11 -0
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +191 -0
- package/docs/AGENT_AUTH_API.md +202 -0
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +263 -0
- package/docs/AGENT_CLIENT_QUICKSTART.md +245 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.en.md +157 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.md +107 -0
- package/docs/CHANGELOG.en.md +25 -0
- package/docs/CHANGELOG.md +25 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/README.en.md +10 -2
- package/docs/README.md +10 -2
- package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
- package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
- package/docs/RELEASE_NOTES_v0.5.1.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.5.1.md +45 -0
- package/package.json +3 -2
- package/schemas/config/client.schema.json +7 -0
- package/schemas/config/common.schema.json +30 -0
- package/schemas/config/route.schema.json +11 -0
- package/scripts/check-doc-links.mjs +2 -1
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +5 -5
- package/scripts/e2e-console.mjs +144 -0
- package/scripts/export-oss.mjs +5 -12
- package/scripts/install.sh +1 -1
- package/scripts/public-content-denylist.mjs +82 -0
- package/scripts/public-content-denylist.test.mjs +53 -0
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +9 -13
- package/scripts/sdk-runtime-test.mjs +171 -7
- package/scripts/security-scan.mjs +8 -5
- package/scripts/validate-examples.mjs +3 -1
- package/scripts/verify-github-repo.mjs +8 -12
- package/scripts/verify-oss-export.mjs +6 -12
- package/sdk/php/README.md +27 -1
- package/sdk/php/src/AgentAuth.php +78 -0
- package/sdk/php/src/HubClient.php +3 -0
- package/sdk/php7/README.md +32 -2
- package/sdk/php7/src/AgentAuth.php +77 -0
- package/sdk/php7/src/HubClient.php +3 -0
- package/sql/055_agent_auth.sql +72 -0
- package/sql/056_agent_client_runtime.sql +60 -0
- package/src/adapters/channels/wecom-api.ts +1 -1
- package/src/app/agent-client-runtime.test.ts +221 -0
- package/src/app/agent-client-runtime.ts +408 -0
- package/src/app/agent-tool-invocations.test.ts +462 -0
- package/src/app/agent-tool-invocations.ts +795 -0
- package/src/app/agent-tool-job.test.ts +62 -0
- package/src/app/agent-tool-job.ts +41 -0
- package/src/app/auth.ts +2 -1
- package/src/app/kernel.ts +2 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/app/runtime-context.ts +8 -0
- package/src/app/tool-approvals.ts +5 -1
- package/src/app/tool-assembly.ts +19 -1
- package/src/app/tool-context.ts +2 -1
- package/src/core/config/agent-direct-console-selection.test.ts +22 -0
- package/src/core/config/config-codec.ts +2 -1
- package/src/core/config/config-models.test.ts +10 -0
- package/src/core/config/config-models.ts +21 -0
- package/src/core/config/config-schema.test.ts +6 -0
- package/src/core/config/route-config.test.ts +15 -0
- package/src/core/config/route-config.ts +36 -0
- package/src/core/config/tools-config.test.ts +58 -1
- package/src/core/config/tools-config.ts +84 -0
- package/src/core/contracts/tools.ts +162 -29
- package/src/core/contracts/types.ts +36 -0
- package/src/core/runtime/agent-client-trace.test.ts +154 -0
- package/src/core/runtime/agent-client-trace.ts +288 -0
- package/src/core/runtime/launch-runtime.ts +13 -0
- package/src/core/runtime/trace-runtime.test.ts +18 -1
- package/src/core/runtime/trace-runtime.ts +28 -3
- package/src/core/state/state-codec.ts +2 -0
- package/src/infrastructure/config/config-agent-auth-repository.test.ts +183 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +453 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.test.ts +38 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +307 -0
- package/src/infrastructure/config/config-approval-ledger.test.ts +32 -0
- package/src/infrastructure/config/config-approval-ledger.ts +16 -0
- package/src/infrastructure/config/config-client-repository.ts +3 -3
- package/src/infrastructure/config/config-conversation-ledger.test.ts +69 -0
- package/src/infrastructure/config/config-conversation-ledger.ts +8 -7
- package/src/infrastructure/config/config-observability-ledger.test.ts +50 -0
- package/src/infrastructure/config/config-observability-ledger.ts +65 -10
- package/src/infrastructure/config/config-route-repository.ts +4 -3
- package/src/infrastructure/config/configstore.ts +14 -3
- package/src/infrastructure/state/state-mysql.ts +2 -2
- package/src/kernel-api/v1/contracts.ts +8 -0
- package/src/routes/admin-agent-clients.test.ts +120 -0
- package/src/routes/admin-agent-clients.ts +161 -0
- package/src/routes/admin-runtime.test.ts +214 -0
- package/src/routes/admin-runtime.ts +82 -2
- package/src/routes/admin.ts +3 -0
- package/src/routes/agent-api.test.ts +379 -0
- package/src/routes/agent-api.ts +251 -0
- package/src/routes/agent-auth.test.ts +276 -0
- package/src/routes/agent-auth.ts +395 -0
- package/src/routes/approvals.ts +4 -1
- package/src/routes/critical-routes.test.ts +235 -1
- package/src/routes/private-default.ts +2 -1
- package/src/routes/private.ts +16 -1
- package/src/routes/run.ts +79 -13
- package/web/connect/bailing-connect-php.tgz +0 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/{Accounts-DuUY2UJU.js → Accounts-r10QUjLQ.js} +1 -1
- package/web/console/assets/AgentClients-DsWADpzr.css +1 -0
- package/web/console/assets/AgentClients-UTTqbkjy.js +1 -0
- package/web/console/assets/{Approvals-B11mo1dy.js → Approvals-BGKkYIya.js} +1 -1
- package/web/console/assets/{Audit-CQwJRIJT.js → Audit-CQmjOAoO.js} +1 -1
- package/web/console/assets/{BrandLockup-BIF-h1pi.js → BrandLockup-BF_0pCa3.js} +1 -1
- package/web/console/assets/{Channels-BIploUT-.js → Channels-C4yZE67F.js} +1 -1
- package/web/console/assets/{ChatEntries-Cpg_WV-o.js → ChatEntries-OqsqLjU6.js} +1 -1
- package/web/console/assets/Clients-CNIVs7Qn.css +1 -0
- package/web/console/assets/Clients-Dv3sv51C.js +3 -0
- package/web/console/assets/{Cost-BF52tfU2.js → Cost-C_-kiH59.js} +1 -1
- package/web/console/assets/{Credentials-SwfmQAv6.js → Credentials-CPTEAiV6.js} +1 -1
- package/web/console/assets/{Diagnostics-CJfbI_8p.js → Diagnostics-O-NKFOeI.js} +1 -1
- package/web/console/assets/{Executors-CzlZlznA.js → Executors-GVIAiNgv.js} +1 -1
- package/web/console/assets/{HelpTip-CT07o3kB.js → HelpTip-i-KJhf5s.js} +1 -1
- package/web/console/assets/{Kb-CVX22U4k.js → Kb-BsCWkJI1.js} +2 -2
- package/web/console/assets/{Login-PoUVsBI-.js → Login-VFjkHNMr.js} +1 -1
- package/web/console/assets/{Projects-DYlbjLQy.js → Projects-Ds-sJwfy.js} +1 -1
- package/web/console/assets/Routes-CXGl9SMM.css +1 -0
- package/web/console/assets/Routes-Wwurw2UU.js +124 -0
- package/web/console/assets/Runs-4zDD9VOC.css +1 -0
- package/web/console/assets/Runs-DLPzXmSy.js +3 -0
- package/web/console/assets/{Setup-xiPXit_b.js → Setup-BLelw0_V.js} +1 -1
- package/web/console/assets/Shell-CvaeK4j_.js +1 -0
- package/web/console/assets/Shell-D9Uw-fsa.css +1 -0
- package/web/console/assets/{StorageBuckets-Bjsc3pLd.js → StorageBuckets-Dv6u47yO.js} +1 -1
- package/web/console/assets/{SystemSettings-CcKF2lJ9.js → SystemSettings-B9K7zaDU.js} +1 -1
- package/web/console/assets/{SystemStatus-Oj1xjxJn.js → SystemStatus-H-oKDo-y.js} +1 -1
- package/web/console/assets/{Targets-y1KllVXT.js → Targets-CCFhjPKf.js} +1 -1
- package/web/console/assets/{Tools-DoEP_y9x.js → Tools-D0H9xpFH.js} +1 -1
- package/web/console/assets/index-CuoTgf6q.js +2 -0
- package/web/console/assets/{index-DZEQL_yy.js → index-DyX9Bz3V.js} +1 -1
- package/web/console/assets/{request-CBLNpLth.js → request-F5lXa7Ro.js} +1 -1
- package/web/console/assets/{schema-DzwLpuOy.js → schema-DUWaWqPn.js} +1 -1
- package/web/console/assets/{util-SiQC2MJh.js → util-4bN2dv7B.js} +1 -1
- package/web/console/assets/{vendor-element-D7WRzHhy.js → vendor-element-CZoEjZr8.js} +1 -1
- package/web/console/assets/{vendor-mammoth-DvgsHdlx.js → vendor-mammoth-nXG51Cg7.js} +1 -1
- package/web/console/index.html +2 -2
- package/web-admin/src/agent-direct-selection.ts +21 -0
- package/web-admin/src/layout/Shell.vue +1 -1
- package/web-admin/src/pages/AgentClients.vue +254 -0
- package/web-admin/src/pages/Clients.vue +13 -3
- package/web-admin/src/pages/Routes.vue +331 -16
- package/web-admin/src/pages/Runs.vue +159 -38
- package/web-admin/src/router.ts +2 -0
- package/web/console/assets/Clients--D7NQJKk.css +0 -1
- package/web/console/assets/Clients-DS29eUi2.js +0 -3
- package/web/console/assets/Routes-DSEvGujN.js +0 -124
- package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
- package/web/console/assets/Runs-B-TsYZEt.js +0 -3
- package/web/console/assets/Runs-CUtSsPW-.css +0 -1
- package/web/console/assets/Shell-BVIjmoY8.css +0 -1
- package/web/console/assets/Shell-DNiWZOYB.js +0 -1
- package/web/console/assets/index-CxPIS6G7.js +0 -2
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import type { Job } from '../core/contracts/types';
|
|
4
|
+
import { AGENT_TOOL_JOB_MARKER, isAgentToolInvocationJob } from './agent-tool-job';
|
|
5
|
+
|
|
6
|
+
function directJob(): Job {
|
|
7
|
+
const route = 'tenant-agent';
|
|
8
|
+
const runId = '22222222-2222-4222-8222-222222222222';
|
|
9
|
+
return {
|
|
10
|
+
job_id: '11111111-1111-4111-8111-111111111111',
|
|
11
|
+
request_id: `agent-tool:${'a'.repeat(64)}`,
|
|
12
|
+
status: 'done',
|
|
13
|
+
target: 'agent-tool-v1',
|
|
14
|
+
profile: 'general',
|
|
15
|
+
project: '',
|
|
16
|
+
source: 'agent-tool:example-business',
|
|
17
|
+
client_app_id: 'example-business',
|
|
18
|
+
agent_session_id: '33333333-3333-4333-8333-333333333333',
|
|
19
|
+
on_behalf_of: 'tenant-1:user-7',
|
|
20
|
+
session_id: runId,
|
|
21
|
+
input_preview: 'Agent tool staff_edit',
|
|
22
|
+
dispatch: { route_key: route, route_name: '门店助手', tools: {} },
|
|
23
|
+
metadata: {
|
|
24
|
+
agent_tool_job_marker: AGENT_TOOL_JOB_MARKER,
|
|
25
|
+
agent_tool_call_v1: true,
|
|
26
|
+
agent_invocation_id: 'b'.repeat(64),
|
|
27
|
+
agent_run_id: runId,
|
|
28
|
+
agent_route: route,
|
|
29
|
+
agent_tool: 'staff_edit',
|
|
30
|
+
agent_args_hash: 'c'.repeat(64),
|
|
31
|
+
agent_capability_revision: 'd'.repeat(64),
|
|
32
|
+
agent_execution_fingerprint: 'e'.repeat(64),
|
|
33
|
+
},
|
|
34
|
+
created_at: '2026-01-01T00:00:00.000Z',
|
|
35
|
+
updated_at: '2026-01-01T00:00:00.000Z',
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
test('Agent direct synthetic job: 必须同时命中服务端 target/source/session 与完整指纹', () => {
|
|
40
|
+
assert.equal(isAgentToolInvocationJob(directJob()), true);
|
|
41
|
+
|
|
42
|
+
const spoofedRun = directJob();
|
|
43
|
+
spoofedRun.target = 'llm';
|
|
44
|
+
spoofedRun.source = 'agent:example-business';
|
|
45
|
+
assert.equal(isAgentToolInvocationJob(spoofedRun), false, '/run metadata 不能单独伪造 direct job');
|
|
46
|
+
|
|
47
|
+
const wrongRequest = directJob();
|
|
48
|
+
wrongRequest.request_id = 'ordinary-run-request';
|
|
49
|
+
assert.equal(isAgentToolInvocationJob(wrongRequest), false);
|
|
50
|
+
|
|
51
|
+
const missingFingerprint = directJob();
|
|
52
|
+
delete missingFingerprint.metadata!['agent_execution_fingerprint'];
|
|
53
|
+
assert.equal(isAgentToolInvocationJob(missingFingerprint), false);
|
|
54
|
+
|
|
55
|
+
const mismatchedRun = directJob();
|
|
56
|
+
mismatchedRun.session_id = '44444444-4444-4444-8444-444444444444';
|
|
57
|
+
assert.equal(isAgentToolInvocationJob(mismatchedRun), false);
|
|
58
|
+
|
|
59
|
+
const mismatchedRoute = directJob();
|
|
60
|
+
mismatchedRoute.dispatch!.route_key = 'other-route';
|
|
61
|
+
assert.equal(isAgentToolInvocationJob(mismatchedRoute), false);
|
|
62
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Job } from '../core/contracts/types';
|
|
2
|
+
|
|
3
|
+
export const AGENT_TOOL_JOB_TARGET = 'agent-tool-v1';
|
|
4
|
+
export const AGENT_TOOL_JOB_SOURCE_PREFIX = 'agent-tool:';
|
|
5
|
+
export const AGENT_TOOL_JOB_MARKER = 'bailing.agent-tool-job.v1';
|
|
6
|
+
|
|
7
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
8
|
+
const HEX_64_RE = /^[a-f0-9]{64}$/;
|
|
9
|
+
const REQUEST_ID_RE = /^agent-tool:[a-f0-9]{64}$/;
|
|
10
|
+
const ROUTE_RE = /^[a-z0-9][a-z0-9_-]{1,63}$/;
|
|
11
|
+
const TOOL_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Agent 直调 synthetic job 的唯一判定入口。metadata 只是其中一部分;
|
|
15
|
+
* target/source/client/session 均由服务端生成,普通 /run 无法仅靠伪造 metadata
|
|
16
|
+
* 改变审批续执行或重跑语义。
|
|
17
|
+
*/
|
|
18
|
+
export function isAgentToolInvocationJob(job: Job | null | undefined): boolean {
|
|
19
|
+
if (!job) return false;
|
|
20
|
+
const metadata = job.metadata ?? {};
|
|
21
|
+
const clientAppId = String(job.client_app_id ?? '');
|
|
22
|
+
const agentSessionId = String(job.agent_session_id ?? '');
|
|
23
|
+
const agentRunId = String(metadata['agent_run_id'] ?? '');
|
|
24
|
+
return job.target === AGENT_TOOL_JOB_TARGET
|
|
25
|
+
&& REQUEST_ID_RE.test(job.request_id)
|
|
26
|
+
&& !!clientAppId
|
|
27
|
+
&& job.source === `${AGENT_TOOL_JOB_SOURCE_PREFIX}${clientAppId}`
|
|
28
|
+
&& UUID_RE.test(agentSessionId)
|
|
29
|
+
&& !!job.on_behalf_of
|
|
30
|
+
&& metadata['agent_tool_job_marker'] === AGENT_TOOL_JOB_MARKER
|
|
31
|
+
&& metadata['agent_tool_call_v1'] === true
|
|
32
|
+
&& HEX_64_RE.test(String(metadata['agent_invocation_id'] ?? ''))
|
|
33
|
+
&& UUID_RE.test(agentRunId)
|
|
34
|
+
&& job.session_id === agentRunId
|
|
35
|
+
&& ROUTE_RE.test(String(metadata['agent_route'] ?? ''))
|
|
36
|
+
&& job.dispatch?.route_key === metadata['agent_route']
|
|
37
|
+
&& TOOL_RE.test(String(metadata['agent_tool'] ?? ''))
|
|
38
|
+
&& HEX_64_RE.test(String(metadata['agent_args_hash'] ?? ''))
|
|
39
|
+
&& HEX_64_RE.test(String(metadata['agent_capability_revision'] ?? ''))
|
|
40
|
+
&& HEX_64_RE.test(String(metadata['agent_execution_fingerprint'] ?? ''));
|
|
41
|
+
}
|
package/src/app/auth.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
5
|
import { ipOf, readBody, send } from './http';
|
|
6
6
|
import { verifyPassword } from '../core/platform/password';
|
|
7
|
-
import type { Client, ExecutorToken } from '../core/contracts/types';
|
|
7
|
+
import type { AgentSession, Client, ExecutorToken } from '../core/contracts/types';
|
|
8
8
|
import type { AppConfig } from '../core/config/config';
|
|
9
9
|
import { allowsUnauthenticatedLocalDevelopment } from '../core/platform/server-token';
|
|
10
10
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
@@ -19,6 +19,7 @@ export type Principal =
|
|
|
19
19
|
permissions?: string[];
|
|
20
20
|
}
|
|
21
21
|
| { kind: 'client'; client: Client }
|
|
22
|
+
| { kind: 'agent'; session: AgentSession; client: Client }
|
|
22
23
|
| { kind: 'executor'; token: ExecutorToken };
|
|
23
24
|
|
|
24
25
|
export interface AuthRuntimeDeps {
|
package/src/app/kernel.ts
CHANGED
|
@@ -82,6 +82,7 @@ function kernelLaunchRequestV1(spec: LaunchSpec): KernelLaunchRequestV1 {
|
|
|
82
82
|
threadScope: spec.threadScope,
|
|
83
83
|
principalId: spec.principalId,
|
|
84
84
|
channel: spec.channel,
|
|
85
|
+
...(spec.agentAttribution ? { agentAttribution: Object.freeze({ ...spec.agentAttribution }) } : {}),
|
|
85
86
|
});
|
|
86
87
|
}
|
|
87
88
|
|
|
@@ -308,6 +309,7 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
308
309
|
cfg,
|
|
309
310
|
configStore: composition.cfgStore,
|
|
310
311
|
stateStore: composition.store,
|
|
312
|
+
isPaused,
|
|
311
313
|
kbService: composition.kbService,
|
|
312
314
|
toolIndex: composition.toolIndex,
|
|
313
315
|
identityProvider: input.identityProvider,
|
package/src/app/oss-edition.ts
CHANGED
|
@@ -22,6 +22,14 @@ export function actorForPrincipal(principal: Principal | null | undefined): Runt
|
|
|
22
22
|
displayName: principal.client.name,
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
+
if (principal.kind === 'agent') {
|
|
26
|
+
return {
|
|
27
|
+
kind: 'agent',
|
|
28
|
+
id: principal.session.principal.id,
|
|
29
|
+
roles: principal.session.principal.roles,
|
|
30
|
+
displayName: principal.session.principal.id,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
25
33
|
return {
|
|
26
34
|
kind: 'executor',
|
|
27
35
|
id: principal.token.name,
|
|
@@ -8,6 +8,7 @@ import { subjectOf } from './tool-context';
|
|
|
8
8
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
9
9
|
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
10
10
|
import type { AppConfig } from '../core/config/config';
|
|
11
|
+
import { isAgentToolInvocationJob } from './agent-tool-job';
|
|
11
12
|
|
|
12
13
|
/** 重跑时的"已批准调用清单"提示:审批车道 B 的另一半。 */
|
|
13
14
|
export async function approvedNoteForJobFor(config: ConfigStoreContract | null, jobId: string): Promise<string | undefined> {
|
|
@@ -36,6 +37,7 @@ export function approvalDepsForStores(
|
|
|
36
37
|
if (!config) return undefined;
|
|
37
38
|
const cs = config;
|
|
38
39
|
return {
|
|
40
|
+
continuationMode: isAgentToolInvocationJob(job) ? 'resume' : 'rerun',
|
|
39
41
|
async consumeApproved(tool, hash) {
|
|
40
42
|
const a = await cs.approvals.find(job.job_id, tool, hash, 'approved', true);
|
|
41
43
|
if (!a) return null;
|
|
@@ -126,7 +128,9 @@ async function notifyApprovalFor(
|
|
|
126
128
|
`任务:${job.dispatch?.route_name || job.request_id}(job ${job.job_id})`,
|
|
127
129
|
`工具:${snap.tool}(scope ${snap.scope},风险 ${snap.risk})`,
|
|
128
130
|
`参数:${snap.args_json}`,
|
|
129
|
-
|
|
131
|
+
isAgentToolInvocationJob(job)
|
|
132
|
+
? '请到控制台「工具审批」页处理;批准后由原本地 Agent 用 invocation_id 续执行,中枢不启动模型重跑。'
|
|
133
|
+
: '请到控制台「工具审批」页处理;批准后任务将自动重跑完成该操作。',
|
|
130
134
|
'', `—— ${appConfig.brand.name}`,
|
|
131
135
|
].join('\n');
|
|
132
136
|
const ap = approvalConfig(toolsCfg)
|
package/src/app/tool-assembly.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { TOOL_INLINE_MAX, type ToolRuntime, buildToolRuntime, composeToolRuntimes } from '../core/contracts/tools';
|
|
2
2
|
import type { Job, Route } from '../core/contracts/types';
|
|
3
3
|
import { approvedNoteForJobFor, approvalDepsForStores } from './tool-approvals';
|
|
4
|
-
import { conversationAddrOf, embedConfigOf, maxCallsOf, resolveAllowedToolsFor, retrievalOptsOf } from './tool-context';
|
|
4
|
+
import { conversationAddrOf, embedConfigOf, maxCallsOf, resolveAllowedToolsFor, retrievalOptsOf, type AllowedToolContext } from './tool-context';
|
|
5
5
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
6
6
|
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
7
7
|
import type { ToolIndexService } from '../services/tools-index';
|
|
@@ -25,6 +25,24 @@ export async function assembleToolRuntimeFor(
|
|
|
25
25
|
): Promise<ToolRuntime | 'subject_locked' | undefined> {
|
|
26
26
|
const r = await resolveAllowedToolsFor(config, job, route);
|
|
27
27
|
if (!r) return undefined;
|
|
28
|
+
return assembleResolvedToolRuntimeFor(config, state, index, job, r, appConfig, nowFn, sleepFn, targetRegistry);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 已解析工具面 → 受治理运行时。Agent 直调会先按独立 direct policy 裁剪并对
|
|
33
|
+
* 写工具提级审批,再从这个入口组装;避免调用时重新组装出一份不同的清单。
|
|
34
|
+
*/
|
|
35
|
+
export async function assembleResolvedToolRuntimeFor(
|
|
36
|
+
config: ConfigStoreContract | null,
|
|
37
|
+
state: RuntimeStateStore,
|
|
38
|
+
index: ToolIndexService | null,
|
|
39
|
+
job: Job,
|
|
40
|
+
r: AllowedToolContext,
|
|
41
|
+
appConfig: AppConfig,
|
|
42
|
+
nowFn: () => string,
|
|
43
|
+
sleepFn: (ms: number) => Promise<void>,
|
|
44
|
+
targetRegistry: TargetRegistry = defaultTargetRegistry,
|
|
45
|
+
): Promise<ToolRuntime | 'subject_locked' | undefined> {
|
|
28
46
|
if (!r.allowed.length) return 'subject_locked';
|
|
29
47
|
const maxCalls = maxCallsOf(r.toolsCfg);
|
|
30
48
|
const retrievalMode = r.allowed.length > TOOL_INLINE_MAX;
|
package/src/app/tool-context.ts
CHANGED
|
@@ -23,9 +23,10 @@ export interface AllowedToolContext {
|
|
|
23
23
|
|
|
24
24
|
/** 主体取数:显式 subject_field 优先,取不到时回落中枢标准字段 visitor_uid,再取不到由渠道派生。 */
|
|
25
25
|
export function subjectOf(job: Job, sourceCfg: ToolSourceConfig): string {
|
|
26
|
+
if (job.on_behalf_of) return job.on_behalf_of;
|
|
26
27
|
const f = String(sourceCfg.subject_field ?? '');
|
|
27
28
|
const meta = (job.metadata ?? {}) as Record<string, unknown>;
|
|
28
|
-
const explicit = String((f ? meta[f] ?? meta['visitor_uid'] : meta['visitor_uid']) ?? '');
|
|
29
|
+
const explicit = String((f ? meta[f] ?? meta['on_behalf_of'] ?? meta['visitor_uid'] : meta['on_behalf_of'] ?? meta['visitor_uid']) ?? '');
|
|
29
30
|
return explicit || channelSubject(job);
|
|
30
31
|
}
|
|
31
32
|
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import {
|
|
4
|
+
includesAllCurrentOperationIds,
|
|
5
|
+
mergeExactOperationIds,
|
|
6
|
+
} from '../../../web-admin/src/agent-direct-selection';
|
|
7
|
+
|
|
8
|
+
test('本地 Agent 全选当前写操作会保留手填项,并写入精确 operationId 快照', () => {
|
|
9
|
+
assert.deepEqual(
|
|
10
|
+
mergeExactOperationIds(
|
|
11
|
+
['manual_write', 'staff_edit'],
|
|
12
|
+
['staff_edit', 'item_add', '*', 'bad-operation'],
|
|
13
|
+
),
|
|
14
|
+
['manual_write', 'staff_edit', 'item_add'],
|
|
15
|
+
);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('本地 Agent 全选状态只比较当前工具目录,不把未来能力视为已授权', () => {
|
|
19
|
+
assert.equal(includesAllCurrentOperationIds(['staff_edit', 'item_add'], ['staff_edit', 'item_add']), true);
|
|
20
|
+
assert.equal(includesAllCurrentOperationIds(['staff_edit'], ['staff_edit', 'item_add']), false);
|
|
21
|
+
assert.equal(includesAllCurrentOperationIds([], []), false);
|
|
22
|
+
});
|
|
@@ -42,6 +42,7 @@ export function rowClient(r: any): Client {
|
|
|
42
42
|
const budget = r.budget ? (typeof r.budget === 'string' ? JSON.parse(r.budget) : r.budget) : undefined;
|
|
43
43
|
return {
|
|
44
44
|
app_id: r.app_id, name: r.name, token: r.token,
|
|
45
|
+
agent_authorize_url: r.agent_authorize_url ?? undefined,
|
|
45
46
|
allowed_routes: ar ? (typeof ar === 'string' ? JSON.parse(ar) : ar) : [],
|
|
46
47
|
allowed_channels: ac ? (typeof ac === 'string' ? JSON.parse(ac) : ac) : [],
|
|
47
48
|
rate_limit_per_min: Number(r.rate_limit_per_min ?? 60),
|
|
@@ -75,7 +76,7 @@ export function rowRoute(r: any): Route {
|
|
|
75
76
|
project: r.project ?? undefined, profile: r.profile, permission: r.permission ?? undefined,
|
|
76
77
|
session_policy: r.session_policy, session_fixed_id: r.session_fixed_id ?? undefined,
|
|
77
78
|
session_key_field: r.session_key_field ?? undefined, default_callback_url: r.default_callback_url ?? undefined,
|
|
78
|
-
delivery: j(r.delivery), knowledge: j(r.knowledge), retry: j(r.retry), tools: j(r.tools), audience: j(r.audience), memory: j(r.memory), budget: j(r.budget),
|
|
79
|
+
delivery: j(r.delivery), knowledge: j(r.knowledge), retry: j(r.retry), tools: j(r.tools), audience: j(r.audience), memory: j(r.memory), agent_client: j(r.agent_client), budget: j(r.budget),
|
|
79
80
|
description: r.description ?? undefined,
|
|
80
81
|
};
|
|
81
82
|
}
|
|
@@ -45,6 +45,16 @@ test('prepareClientConfig: 规范化接入方并校验预算', () => {
|
|
|
45
45
|
const badBudget = prepareClientConfig({ app_id: 'app-main', name: 'x', allowed_routes: ['*'], budget: { hard_tokens: 1.2 } });
|
|
46
46
|
assert.equal(badBudget.ok, false);
|
|
47
47
|
assert.match(badBudget.ok ? '' : badBudget.error, /client\.budget\.hard_tokens/);
|
|
48
|
+
|
|
49
|
+
const agent = prepareClientConfig({ app_id: 'app-main', name: 'x', allowed_routes: ['orders'], agent_authorize_url: 'https://business.example.com/agent-authorize' });
|
|
50
|
+
assert.equal(agent.ok, true);
|
|
51
|
+
if (agent.ok) assert.equal(agent.value.agent_authorize_url, 'https://business.example.com/agent-authorize');
|
|
52
|
+
for (const invalidUrl of ['http://business.example.com/agent-authorize', 'http://localhost:8080/agent-authorize', 'http://127.0.0.1/agent-authorize', 'http://2130706433:8080/agent-authorize', 'http://0x7f000001:8080/agent-authorize']) {
|
|
53
|
+
const invalid = prepareClientConfig({ app_id: 'app-main', name: 'x', allowed_routes: ['orders'], agent_authorize_url: invalidUrl });
|
|
54
|
+
assert.equal(invalid.ok, false, invalidUrl);
|
|
55
|
+
}
|
|
56
|
+
const localAgent = prepareClientConfig({ app_id: 'app-main', name: 'x', allowed_routes: ['orders'], agent_authorize_url: 'http://127.0.0.1:8080/agent-authorize' });
|
|
57
|
+
assert.equal(localAgent.ok, true);
|
|
48
58
|
});
|
|
49
59
|
|
|
50
60
|
test('prepareExecutorTokenConfig: target 白名单不能为空', () => {
|
|
@@ -29,6 +29,13 @@ function object(v: unknown): Record<string, unknown> {
|
|
|
29
29
|
return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : {};
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
function hasStrictLoopbackHttpAuthority(value: string): boolean {
|
|
33
|
+
const match = /^http:\/\/(?:127\.0\.0\.1|\[::1\]):([0-9]{1,5})(?:[/?#]|$)/i.exec(value);
|
|
34
|
+
if (!match) return false;
|
|
35
|
+
const port = Number(match[1]);
|
|
36
|
+
return Number.isInteger(port) && port >= 1 && port <= 65535;
|
|
37
|
+
}
|
|
38
|
+
|
|
32
39
|
function resourceName(v: unknown, label: string): PrepareResult<string> {
|
|
33
40
|
const name = str(v);
|
|
34
41
|
if (!RESOURCE_NAME_RE.test(name)) return fail(`${label} 仅限小写字母/数字/中划线/下划线,且长度 2..64`);
|
|
@@ -45,11 +52,25 @@ export function prepareClientConfig(input: Partial<Client> & { rotate_token?: bo
|
|
|
45
52
|
const budgetErr = validateBudgetPolicy(input.budget, 'client.budget');
|
|
46
53
|
if (budgetErr) return fail(budgetErr);
|
|
47
54
|
const budget = object(input.budget);
|
|
55
|
+
const agentAuthorizeUrl = optionalStr(input.agent_authorize_url);
|
|
56
|
+
if (agentAuthorizeUrl) {
|
|
57
|
+
try {
|
|
58
|
+
const parsed = new URL(agentAuthorizeUrl);
|
|
59
|
+
const hostname = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
60
|
+
const loopbackDev = hasStrictLoopbackHttpAuthority(agentAuthorizeUrl) && (hostname === '127.0.0.1' || hostname === '::1');
|
|
61
|
+
if ((parsed.protocol !== 'https:' && !loopbackDev) || parsed.username || parsed.password || parsed.hash || agentAuthorizeUrl.length > 2048) {
|
|
62
|
+
return fail('agent_authorize_url 只允许 HTTPS;本机开发可使用带显式端口的 127.0.0.1/::1 HTTP URL');
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
return fail('agent_authorize_url 必须是有效的 HTTP(S) URL');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
48
68
|
return {
|
|
49
69
|
ok: true,
|
|
50
70
|
value: {
|
|
51
71
|
app_id: appId,
|
|
52
72
|
name,
|
|
73
|
+
...(agentAuthorizeUrl ? { agent_authorize_url: agentAuthorizeUrl } : {}),
|
|
53
74
|
allowed_routes: allowedRoutes,
|
|
54
75
|
allowed_channels: stringList(input.allowed_channels),
|
|
55
76
|
rate_limit_per_min: Math.max(Number(input.rate_limit_per_min ?? 60) || 0, 0),
|
|
@@ -100,6 +100,12 @@ test('Config JSON Schemas: 路由、目标和工具治理关键契约对齐', ()
|
|
|
100
100
|
assert.equal(common.$defs.routeToolsConfig.properties.max_calls.maximum, 50);
|
|
101
101
|
assert.deepEqual(common.$defs.routeToolsConfig.properties.builtin.properties.send_message.required, ['channels']);
|
|
102
102
|
assert.deepEqual(common.$defs.routeToolsConfig.properties.approval.required, ['type']);
|
|
103
|
+
assert.deepEqual(common.$defs.routeToolsConfig.properties.agent_direct.required, ['enabled']);
|
|
104
|
+
assert.equal(common.$defs.routeToolsConfig.properties.agent_direct.additionalProperties, false);
|
|
105
|
+
assert.deepEqual(common.$defs.routeToolsConfig.properties.agent_direct.not.required, ['force_approval_tools', 'unattended_write_tools']);
|
|
106
|
+
assert.equal(common.$defs.routeToolsConfig.properties.agent_direct.properties.write_tools.items.pattern, '^[A-Za-z_][A-Za-z0-9_]{0,63}$');
|
|
107
|
+
assert.equal(common.$defs.routeToolsConfig.properties.agent_direct.properties.force_approval_tools.items.pattern, '^[A-Za-z_][A-Za-z0-9_]{0,63}$');
|
|
108
|
+
assert.equal(common.$defs.routeToolsConfig.properties.agent_direct.properties.unattended_write_tools.deprecated, true);
|
|
103
109
|
});
|
|
104
110
|
|
|
105
111
|
test('Config JSON Schemas: 接入方、渠道、存储桶和工具源契约对齐', () => {
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
normalizeRouteConfig,
|
|
7
7
|
prepareRouteConfig,
|
|
8
8
|
routeDeliveryConfig,
|
|
9
|
+
routeAgentClientConfig,
|
|
9
10
|
routeKnowledgeConfig,
|
|
10
11
|
routeRetryConfig,
|
|
11
12
|
validateRouteConfig,
|
|
@@ -150,6 +151,20 @@ test('validateRouteConfig: retry 与 memory 范围错误会提前拒绝', async
|
|
|
150
151
|
assert.equal(err2, 'memory.recent_messages 必须是 1..50 的整数');
|
|
151
152
|
});
|
|
152
153
|
|
|
154
|
+
test('agent_client: 严格校验并兼容既有 agent_direct 开关', async () => {
|
|
155
|
+
const err = await validateRouteConfig({
|
|
156
|
+
route_key: 'agent.bad', target: 'notify', agent_client: { enabled: true, active_tool_limit: 13 },
|
|
157
|
+
}, deps, defaults);
|
|
158
|
+
assert.equal(err, 'agent_client.active_tool_limit 必须是 1..12 的整数');
|
|
159
|
+
assert.deepEqual(routeAgentClientConfig({ tools: { agent_direct: { enabled: true } } }), {
|
|
160
|
+
enabled: true, active_tool_limit: 8,
|
|
161
|
+
});
|
|
162
|
+
assert.deepEqual(routeAgentClientConfig({ agent_client: { instructions: 'local' }, tools: { agent_direct: { enabled: true } } }), {
|
|
163
|
+
enabled: true, instructions: 'local', active_tool_limit: 8,
|
|
164
|
+
});
|
|
165
|
+
assert.equal(routeAgentClientConfig({ agent_client: { enabled: false }, tools: { agent_direct: { enabled: true } } }), null);
|
|
166
|
+
});
|
|
167
|
+
|
|
153
168
|
test('validateRouteConfig: budget 必须是合法预算策略', async () => {
|
|
154
169
|
const err = await validateRouteConfig({
|
|
155
170
|
route_key: 'budget.bad',
|
|
@@ -41,6 +41,12 @@ export interface RouteRetryConfig {
|
|
|
41
41
|
backoff_ms: number;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
export interface RouteAgentClientConfig {
|
|
45
|
+
enabled: boolean;
|
|
46
|
+
instructions?: string;
|
|
47
|
+
active_tool_limit: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
44
50
|
const SESSION_POLICIES: SessionPolicy[] = ['new', 'fixed', 'per_key', 'passthrough'];
|
|
45
51
|
const KNOWLEDGE_INJECT_MODES = ['chunk', 'doc'];
|
|
46
52
|
|
|
@@ -152,6 +158,20 @@ function validateMemoryConfig(v: unknown): string | null {
|
|
|
152
158
|
?? intInRange(m.summary_max_chars, 'memory.summary_max_chars', 200, 8000);
|
|
153
159
|
}
|
|
154
160
|
|
|
161
|
+
function validateAgentClientConfig(v: unknown): string | null {
|
|
162
|
+
if (v === undefined || v === null) return null;
|
|
163
|
+
const cfg = record(v);
|
|
164
|
+
if (!cfg) return 'agent_client 必须是对象';
|
|
165
|
+
const known = new Set(['enabled', 'instructions', 'active_tool_limit']);
|
|
166
|
+
const unknown = Object.keys(cfg).filter((key) => !known.has(key));
|
|
167
|
+
if (unknown.length) return `agent_client 包含未声明字段: ${unknown.join(',')}`;
|
|
168
|
+
if (cfg.enabled !== undefined && typeof cfg.enabled !== 'boolean') return 'agent_client.enabled 必须是布尔值';
|
|
169
|
+
if (cfg.instructions !== undefined && (typeof cfg.instructions !== 'string' || cfg.instructions.length > 20_000)) {
|
|
170
|
+
return 'agent_client.instructions 必须是最长 20000 字符的字符串';
|
|
171
|
+
}
|
|
172
|
+
return intInRange(cfg.active_tool_limit, 'agent_client.active_tool_limit', 1, 12);
|
|
173
|
+
}
|
|
174
|
+
|
|
155
175
|
export async function validateRouteConfig(input: Partial<Route>, deps: RouteConfigDeps, defaults: RouteConfigDefaults): Promise<string | null> {
|
|
156
176
|
const routeKey = cleanString(input.route_key);
|
|
157
177
|
if (!routeKey) return 'route_key 必填';
|
|
@@ -173,6 +193,7 @@ export async function validateRouteConfig(input: Partial<Route>, deps: RouteConf
|
|
|
173
193
|
?? validateKnowledgeConfig(input.knowledge)
|
|
174
194
|
?? validateRetryConfig(input.retry)
|
|
175
195
|
?? validateMemoryConfig(input.memory)
|
|
196
|
+
?? validateAgentClientConfig(input.agent_client)
|
|
176
197
|
?? validateAudiencePolicy(input.audience)
|
|
177
198
|
?? validateBudgetPolicy(input.budget)
|
|
178
199
|
?? await validateRouteToolsConfig(input.tools, deps.toolProviderExists);
|
|
@@ -203,11 +224,26 @@ export function normalizeRouteConfig(input: Partial<Route>, defaults: RouteConfi
|
|
|
203
224
|
tools,
|
|
204
225
|
audience: normalizeAudiencePolicy(input.audience),
|
|
205
226
|
memory: nonEmptyRecord(input.memory),
|
|
227
|
+
agent_client: nonEmptyRecord(input.agent_client) as Route['agent_client'],
|
|
206
228
|
budget: nonEmptyRecord(input.budget),
|
|
207
229
|
description: input.description,
|
|
208
230
|
};
|
|
209
231
|
}
|
|
210
232
|
|
|
233
|
+
/** 缺省配置兼容既有 tools.agent_direct.enabled;显式 enabled=false 始终关闭。 */
|
|
234
|
+
export function routeAgentClientConfig(route: Pick<Route, 'agent_client' | 'tools'>): RouteAgentClientConfig | null {
|
|
235
|
+
const raw = record(route.agent_client);
|
|
236
|
+
const direct = record(record(route.tools)?.agent_direct);
|
|
237
|
+
const enabled = raw?.enabled === false ? false : raw?.enabled === true || direct?.enabled === true;
|
|
238
|
+
if (!enabled) return null;
|
|
239
|
+
const instructions = typeof raw?.instructions === 'string' ? raw.instructions.trim().slice(0, 20_000) : '';
|
|
240
|
+
return {
|
|
241
|
+
enabled: true,
|
|
242
|
+
...(instructions ? { instructions } : {}),
|
|
243
|
+
active_tool_limit: intValue(raw?.active_tool_limit, 8, 1, 12),
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
211
247
|
export function routeDeliveryConfig(v: unknown): RouteDeliveryConfig | null {
|
|
212
248
|
const d = record(v);
|
|
213
249
|
const type = cleanString(d?.type);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// 顶层扁平字段不是公共契约,必须显式拒绝。
|
|
3
3
|
import { test } from 'node:test';
|
|
4
4
|
import assert from 'node:assert/strict';
|
|
5
|
-
import { approvalConfig, maxToolCalls, routeToolsConfig, sendMessageConfig, toolSourceConfigs, validateRouteToolsConfig } from './tools-config';
|
|
5
|
+
import { agentDirectToolsConfig, approvalConfig, maxToolCalls, routeToolsConfig, sendMessageConfig, toolSourceConfigs, validateRouteToolsConfig } from './tools-config';
|
|
6
6
|
|
|
7
7
|
test('toolSourceConfigs: 读取 tools.sources,清洗 provider / allow 并去重 scope', () => {
|
|
8
8
|
const cfg = {
|
|
@@ -122,3 +122,60 @@ test('validateRouteToolsConfig: 业务 webhook 审批必须配置 url', async ()
|
|
|
122
122
|
|
|
123
123
|
assert.equal(err, 'tools.approval.type=business_webhook 时 url 必填');
|
|
124
124
|
});
|
|
125
|
+
|
|
126
|
+
test('agentDirectToolsConfig: 写工具默认继承 ACC,新字段只精确追加审批', () => {
|
|
127
|
+
assert.equal(agentDirectToolsConfig({}), null);
|
|
128
|
+
assert.equal(agentDirectToolsConfig({ agent_direct: { enabled: false } }), null);
|
|
129
|
+
assert.deepEqual(agentDirectToolsConfig({
|
|
130
|
+
agent_direct: {
|
|
131
|
+
enabled: true,
|
|
132
|
+
write_tools: ['staff_edit', 'staff_edit'],
|
|
133
|
+
force_approval_tools: ['staff_edit', 'staff_edit'],
|
|
134
|
+
},
|
|
135
|
+
}), {
|
|
136
|
+
enabled: true,
|
|
137
|
+
write_tools: ['staff_edit'],
|
|
138
|
+
force_approval_tools: ['staff_edit'],
|
|
139
|
+
});
|
|
140
|
+
assert.deepEqual(agentDirectToolsConfig({
|
|
141
|
+
agent_direct: { enabled: true, write_tools: ['staff_edit'] },
|
|
142
|
+
}), {
|
|
143
|
+
enabled: true,
|
|
144
|
+
write_tools: ['staff_edit'],
|
|
145
|
+
force_approval_tools: [],
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test('agentDirectToolsConfig: 旧 unattended 白名单兼容转换为显式强制审批集', () => {
|
|
150
|
+
assert.deepEqual(agentDirectToolsConfig({
|
|
151
|
+
agent_direct: {
|
|
152
|
+
enabled: true,
|
|
153
|
+
write_tools: ['staff_edit', 'ticket_draft'],
|
|
154
|
+
unattended_write_tools: ['ticket_draft'],
|
|
155
|
+
},
|
|
156
|
+
}), {
|
|
157
|
+
enabled: true,
|
|
158
|
+
write_tools: ['staff_edit', 'ticket_draft'],
|
|
159
|
+
force_approval_tools: ['staff_edit'],
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test('validateRouteToolsConfig: Agent 直调审批覆盖只允许精确 operationId 且必须是写工具子集', async () => {
|
|
164
|
+
assert.equal(await validateRouteToolsConfig({ agent_direct: { enabled: true } }), null);
|
|
165
|
+
assert.match(await validateRouteToolsConfig({ agent_direct: { enabled: true, write_tools: ['*'] } }) ?? '', /不允许通配符/);
|
|
166
|
+
assert.match(await validateRouteToolsConfig({
|
|
167
|
+
agent_direct: { enabled: true, write_tools: ['staff_edit'], force_approval_tools: ['staff_delete'] },
|
|
168
|
+
}) ?? '', /force_approval_tools 必须是 write_tools 的子集/);
|
|
169
|
+
assert.match(await validateRouteToolsConfig({
|
|
170
|
+
agent_direct: { enabled: true, write_tools: ['staff_edit'], unattended_write_tools: ['staff_delete'] },
|
|
171
|
+
}) ?? '', /write_tools 的子集/);
|
|
172
|
+
assert.match(await validateRouteToolsConfig({
|
|
173
|
+
agent_direct: {
|
|
174
|
+
enabled: true,
|
|
175
|
+
write_tools: ['staff_edit'],
|
|
176
|
+
force_approval_tools: ['staff_edit'],
|
|
177
|
+
unattended_write_tools: ['staff_edit'],
|
|
178
|
+
},
|
|
179
|
+
}) ?? '', /不可同时配置/);
|
|
180
|
+
assert.match(await validateRouteToolsConfig({ agent_direct: { enabled: true, future: true } }) ?? '', /未声明字段/);
|
|
181
|
+
});
|
|
@@ -18,6 +18,30 @@ export interface ToolApprovalConfig {
|
|
|
18
18
|
[key: string]: unknown;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* 本地 Agent 直调工具面是独立的明示授权,不从 route.permission 或 scope allow
|
|
23
|
+
* 推导。只读工具在 enabled=true 时可见;写工具必须按 operationId 精确列出。
|
|
24
|
+
* 已暴露写工具默认继承 ACC 风险/审批声明;只有再次精确列入
|
|
25
|
+
* force_approval_tools 才由路由额外强制审批。不接受通配符。
|
|
26
|
+
*
|
|
27
|
+
* unattended_write_tools 仅用于兼容私有候选的旧配置:存在该字段且没有新字段时,
|
|
28
|
+
* 仍按“其余 write_tools 强制审批”的旧语义解析;保存配置时应迁移为
|
|
29
|
+
* force_approval_tools,未配置任何审批覆盖即表示继承 ACC。
|
|
30
|
+
*/
|
|
31
|
+
export interface AgentDirectToolsConfig {
|
|
32
|
+
enabled: boolean;
|
|
33
|
+
write_tools?: string[];
|
|
34
|
+
force_approval_tools?: string[];
|
|
35
|
+
/** @deprecated 使用 force_approval_tools 明示额外强制审批。 */
|
|
36
|
+
unattended_write_tools?: string[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ResolvedAgentDirectToolsConfig {
|
|
40
|
+
enabled: true;
|
|
41
|
+
write_tools: string[];
|
|
42
|
+
force_approval_tools: string[];
|
|
43
|
+
}
|
|
44
|
+
|
|
21
45
|
export interface RouteToolsConfig {
|
|
22
46
|
sources?: ToolSourceConfig[];
|
|
23
47
|
max_calls?: number;
|
|
@@ -26,6 +50,7 @@ export interface RouteToolsConfig {
|
|
|
26
50
|
[key: string]: unknown;
|
|
27
51
|
};
|
|
28
52
|
approval?: ToolApprovalConfig;
|
|
53
|
+
agent_direct?: AgentDirectToolsConfig;
|
|
29
54
|
[key: string]: unknown;
|
|
30
55
|
}
|
|
31
56
|
|
|
@@ -71,6 +96,29 @@ export function approvalConfig(v: unknown): ToolApprovalConfig | null {
|
|
|
71
96
|
return type ? { ...ap, type } as ToolApprovalConfig : null;
|
|
72
97
|
}
|
|
73
98
|
|
|
99
|
+
export function agentDirectToolsConfig(v: unknown): ResolvedAgentDirectToolsConfig | null {
|
|
100
|
+
const cfg = routeToolsConfig(v);
|
|
101
|
+
const direct = record(cfg?.agent_direct);
|
|
102
|
+
if (!direct || direct.enabled !== true) return null;
|
|
103
|
+
const names = (value: unknown): string[] => Array.isArray(value)
|
|
104
|
+
? [...new Set(value.map((item) => String(item).trim()).filter(Boolean))]
|
|
105
|
+
: [];
|
|
106
|
+
const writeTools = names(direct.write_tools);
|
|
107
|
+
const hasForceApprovalTools = Object.prototype.hasOwnProperty.call(direct, 'force_approval_tools');
|
|
108
|
+
const hasLegacyUnattendedTools = Object.prototype.hasOwnProperty.call(direct, 'unattended_write_tools');
|
|
109
|
+
const legacyUnattendedTools = new Set(names(direct.unattended_write_tools));
|
|
110
|
+
const forceApprovalTools = hasForceApprovalTools
|
|
111
|
+
? names(direct.force_approval_tools)
|
|
112
|
+
: hasLegacyUnattendedTools
|
|
113
|
+
? writeTools.filter((name) => !legacyUnattendedTools.has(name))
|
|
114
|
+
: [];
|
|
115
|
+
return {
|
|
116
|
+
enabled: true,
|
|
117
|
+
write_tools: writeTools,
|
|
118
|
+
force_approval_tools: forceApprovalTools,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
74
122
|
export async function validateRouteToolsConfig(v: unknown, toolProviderExists?: ToolProviderExists): Promise<string | null> {
|
|
75
123
|
const toolsCfg = routeToolsConfig(v);
|
|
76
124
|
if (!toolsCfg || !Object.keys(toolsCfg).length) return null;
|
|
@@ -122,5 +170,41 @@ export async function validateRouteToolsConfig(v: unknown, toolProviderExists?:
|
|
|
122
170
|
}
|
|
123
171
|
}
|
|
124
172
|
|
|
173
|
+
|
|
174
|
+
if (toolsCfg.agent_direct !== undefined) {
|
|
175
|
+
const direct = record(toolsCfg.agent_direct);
|
|
176
|
+
if (!direct) return 'tools.agent_direct 必须是对象';
|
|
177
|
+
const known = new Set(['enabled', 'write_tools', 'force_approval_tools', 'unattended_write_tools']);
|
|
178
|
+
const unknown = Object.keys(direct).filter((key) => !known.has(key));
|
|
179
|
+
if (unknown.length) return `tools.agent_direct 包含未声明字段: ${unknown.join(',')}`;
|
|
180
|
+
if (typeof direct.enabled !== 'boolean') return 'tools.agent_direct.enabled 必须是布尔值';
|
|
181
|
+
const operationId = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
182
|
+
const parseNames = (field: 'write_tools' | 'force_approval_tools' | 'unattended_write_tools'): string[] | string => {
|
|
183
|
+
const raw = direct[field];
|
|
184
|
+
if (raw === undefined) return [];
|
|
185
|
+
if (!Array.isArray(raw)) return `tools.agent_direct.${field} 必须是 operationId 数组`;
|
|
186
|
+
const values = raw.map((item) => typeof item === 'string' ? item.trim() : '');
|
|
187
|
+
if (!values.length || values.some((item) => !operationId.test(item))) {
|
|
188
|
+
return `tools.agent_direct.${field} 只允许非空的精确 operationId,不允许通配符`;
|
|
189
|
+
}
|
|
190
|
+
if (new Set(values).size !== values.length) return `tools.agent_direct.${field} 不允许重复值`;
|
|
191
|
+
return values;
|
|
192
|
+
};
|
|
193
|
+
const writes = parseNames('write_tools');
|
|
194
|
+
if (typeof writes === 'string') return writes;
|
|
195
|
+
const forced = parseNames('force_approval_tools');
|
|
196
|
+
if (typeof forced === 'string') return forced;
|
|
197
|
+
const unattended = parseNames('unattended_write_tools');
|
|
198
|
+
if (typeof unattended === 'string') return unattended;
|
|
199
|
+
if (direct.force_approval_tools !== undefined && direct.unattended_write_tools !== undefined) {
|
|
200
|
+
return 'tools.agent_direct.force_approval_tools 与已弃用的 unattended_write_tools 不可同时配置';
|
|
201
|
+
}
|
|
202
|
+
const allowedWrites = new Set(writes);
|
|
203
|
+
const forcedOutside = forced.filter((name) => !allowedWrites.has(name));
|
|
204
|
+
if (forcedOutside.length) return `tools.agent_direct.force_approval_tools 必须是 write_tools 的子集: ${forcedOutside.join(',')}`;
|
|
205
|
+
const unattendedOutside = unattended.filter((name) => !allowedWrites.has(name));
|
|
206
|
+
if (unattendedOutside.length) return `tools.agent_direct.unattended_write_tools 必须是 write_tools 的子集: ${unattendedOutside.join(',')}`;
|
|
207
|
+
}
|
|
208
|
+
|
|
125
209
|
return null;
|
|
126
210
|
}
|