bailinghub 0.3.4 → 0.5.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/.gitignore +5 -0
- package/README.en.md +6 -1
- package/README.md +6 -0
- package/SECURITY.md +11 -0
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +175 -0
- package/docs/AGENT_AUTH_API.md +190 -0
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +212 -0
- package/docs/AGENT_CLIENT_QUICKSTART.md +206 -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 +59 -1
- package/docs/CHANGELOG.md +27 -1
- package/docs/COMPATIBILITY.en.md +25 -0
- package/docs/CONTRACT.en.md +79 -8
- package/docs/CONTRACT.md +36 -6
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/QUICKSTART.en.md +6 -0
- package/docs/QUICKSTART.md +1 -1
- package/docs/README.en.md +8 -0
- package/docs/README.md +8 -0
- package/docs/RELEASE_NOTES_v0.4.0.en.md +39 -0
- package/docs/RELEASE_NOTES_v0.4.0.md +39 -0
- package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
- package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
- package/docs/STREAMING.en.md +32 -0
- package/docs/STREAMING.md +8 -2
- package/docs/WIDGET_RENDERERS.en.md +123 -6
- package/docs/WIDGET_RENDERERS.md +75 -6
- package/docs/user-guide/console-map.en.md +1 -2
- package/docs/user-guide/console-map.md +2 -2
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +9 -0
- package/package.json +3 -2
- package/schemas/config/chat-entry.schema.json +2 -1
- 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 +1 -0
- 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 +8 -12
- 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 +7 -11
- package/scripts/verify-oss-export.mjs +6 -12
- package/scripts/widget-renderer-test.mjs +244 -16
- 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/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/config-codec.ts +2 -1
- package/src/core/config/config-models.test.ts +28 -1
- package/src/core/config/config-models.ts +46 -3
- package/src/core/config/config-schema.test.ts +8 -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 +38 -1
- package/src/core/platform/chat-form.test.ts +147 -0
- package/src/core/platform/chat-form.ts +402 -0
- package/src/core/platform/version.ts +1 -1
- 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/execution-runtime.test.ts +61 -0
- package/src/core/runtime/execution-runtime.ts +17 -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 +147 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +356 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +253 -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-runtime.test.ts +214 -0
- package/src/routes/admin-runtime.ts +82 -2
- 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/chat.test.ts +319 -7
- package/src/routes/chat.ts +166 -21
- 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-CAwrtBiS.js → Accounts-D4RRm5D1.js} +1 -1
- package/web/console/assets/{Approvals-C2BZ86T3.js → Approvals-CsTTKb8o.js} +1 -1
- package/web/console/assets/{Audit-B-E4Y_Up.js → Audit-BzvZ7JZw.js} +1 -1
- package/web/console/assets/{BrandLockup-C18u8Lx5.js → BrandLockup-CYcA93wh.js} +1 -1
- package/web/console/assets/{Channels-DTy8ylH-.js → Channels-DRQZggqM.js} +1 -1
- package/web/console/assets/ChatEntries-BUB7BWKU.js +7 -0
- package/web/console/assets/ChatEntries-DsYtcXN6.css +1 -0
- package/web/console/assets/Clients-CQ_MonGL.css +1 -0
- package/web/console/assets/Clients-HhCyrxfz.js +3 -0
- package/web/console/assets/{Cost-2SSYs1AT.js → Cost-BZgFf1yM.js} +1 -1
- package/web/console/assets/{Credentials-B79LtxCE.js → Credentials-BTe2Q07j.js} +1 -1
- package/web/console/assets/{Diagnostics-BakcRYvb.js → Diagnostics-WL-buYli.js} +1 -1
- package/web/console/assets/{Executors-BXoyo28u.js → Executors-CGZ-7Xmp.js} +1 -1
- package/web/console/assets/{Kb-ISbzquab.js → Kb-VVw8oGsT.js} +1 -1
- package/web/console/assets/{Login-Dlu6Wgcf.js → Login-rwvmBBPl.js} +1 -1
- package/web/console/assets/{Projects-DFzmtnqg.js → Projects-CexaCEY1.js} +1 -1
- package/web/console/assets/Routes-B9ZHbQAp.js +124 -0
- package/web/console/assets/Routes-BbkFpi6Y.css +1 -0
- package/web/console/assets/Runs-4zDD9VOC.css +1 -0
- package/web/console/assets/Runs-BzFNPTwD.js +3 -0
- package/web/console/assets/{Setup-CrBAV-b9.js → Setup-Djh5yadQ.js} +1 -1
- package/web/console/assets/{Shell-B1a8DvXQ.js → Shell-kn763smL.js} +1 -1
- package/web/console/assets/{StorageBuckets-BRfL_eHb.js → StorageBuckets-CQBR41W1.js} +1 -1
- package/web/console/assets/{SystemSettings-CyirVLbq.js → SystemSettings-DgnopekD.js} +1 -1
- package/web/console/assets/{SystemStatus-DZ_OR7sk.js → SystemStatus-Bj8-kPt2.js} +1 -1
- package/web/console/assets/{Targets-CtIMa66c.js → Targets-BAfCt_nH.js} +1 -1
- package/web/console/assets/{Tools-BfDZHt01.js → Tools-xjd0NZdE.js} +1 -1
- package/web/console/assets/{index-DBiByFiO.js → index-DfJA7iJS.js} +2 -2
- package/web/console/assets/{request-DY2cxQqZ.js → request-DkNPOweH.js} +1 -1
- package/web/console/assets/{schema-6mCQ7rR5.js → schema-CgPWAu1_.js} +1 -1
- package/web/console/index.html +1 -1
- package/web/widget/widget.js +493 -14
- package/web-admin/src/pages/ChatEntries.vue +18 -6
- package/web-admin/src/pages/Clients.vue +11 -3
- package/web-admin/src/pages/Routes.vue +282 -16
- package/web-admin/src/pages/Runs.vue +159 -38
- package/web/console/assets/ChatEntries-9xbRiQov.css +0 -1
- package/web/console/assets/ChatEntries-DvD-4IeE.js +0 -7
- package/web/console/assets/Clients--D7NQJKk.css +0 -1
- package/web/console/assets/Clients-DWs9JFr0.js +0 -3
- package/web/console/assets/Routes-B-hm9HGY.js +0 -124
- package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
- package/web/console/assets/Runs-CUtSsPW-.css +0 -1
- package/web/console/assets/Runs-hMRu1im3.js +0 -3
|
@@ -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,
|
|
@@ -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
|
|
|
@@ -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 白名单不能为空', () => {
|
|
@@ -177,7 +187,7 @@ test('prepareChatEntryConfig: 生成入口、校验引用并收紧外观', async
|
|
|
177
187
|
const ok = await prepareChatEntryConfig({
|
|
178
188
|
name: ' 官网客服 ',
|
|
179
189
|
route_key: ' chat.main ',
|
|
180
|
-
allowed_origins: [' https://
|
|
190
|
+
allowed_origins: [' https://EXAMPLE.com:443/ ', 'https://example.com', ''],
|
|
181
191
|
ticket_client: 'app-main',
|
|
182
192
|
bucket: 'chat-cos',
|
|
183
193
|
rate_limit_per_min: 9999,
|
|
@@ -185,6 +195,7 @@ test('prepareChatEntryConfig: 生成入口、校验引用并收紧外观', async
|
|
|
185
195
|
greeting: 'G'.repeat(300),
|
|
186
196
|
color: '#12abef',
|
|
187
197
|
appearance: {
|
|
198
|
+
default_open: true,
|
|
188
199
|
width: 9999,
|
|
189
200
|
height: 100,
|
|
190
201
|
title_align: 'left',
|
|
@@ -212,6 +223,7 @@ test('prepareChatEntryConfig: 生成入口、校验引用并收紧外观', async
|
|
|
212
223
|
assert.equal(ok.value.title?.length, 64);
|
|
213
224
|
assert.equal(ok.value.greeting?.length, 255);
|
|
214
225
|
assert.deepEqual(ok.value.appearance, {
|
|
226
|
+
default_open: true,
|
|
215
227
|
width: 720,
|
|
216
228
|
height: 360,
|
|
217
229
|
title_align: 'left',
|
|
@@ -233,6 +245,21 @@ test('prepareChatEntryConfig: 生成入口、校验引用并收紧外观', async
|
|
|
233
245
|
});
|
|
234
246
|
assert.equal(missingRoute.ok, false);
|
|
235
247
|
assert.match(missingRoute.ok ? '' : missingRoute.error, /路由 missing 不存在/);
|
|
248
|
+
|
|
249
|
+
const originDeps = {
|
|
250
|
+
routeExists: async () => true,
|
|
251
|
+
entryExists: async () => false,
|
|
252
|
+
clientExists: async () => true,
|
|
253
|
+
bucketExists: async () => true,
|
|
254
|
+
};
|
|
255
|
+
const missingOrigins = await prepareChatEntryConfig({ name: 'x', route_key: 'chat.main' }, originDeps);
|
|
256
|
+
assert.equal(missingOrigins.ok, false);
|
|
257
|
+
assert.match(missingOrigins.ok ? '' : missingOrigins.error, /allowed_origins 必须是数组/);
|
|
258
|
+
for (const invalidOrigin of ['example.com', 'ftp://example.com', 'https://example.com/path', 'https://example.com///', 'https://example.com?', 'https://example.com#', 'https://example.com?q=1', 'https://user@example.com', `https://${'a'.repeat(250)}.com`]) {
|
|
259
|
+
const invalid = await prepareChatEntryConfig({ name: 'x', route_key: 'chat.main', allowed_origins: [invalidOrigin] }, originDeps);
|
|
260
|
+
assert.equal(invalid.ok, false, invalidOrigin);
|
|
261
|
+
assert.match(invalid.ok ? '' : invalid.error, /Origin/);
|
|
262
|
+
}
|
|
236
263
|
});
|
|
237
264
|
|
|
238
265
|
test('preparePageContextConfig: 页面上下文只接受寻址字段,不开放 kb_tag 写入', async () => {
|
|
@@ -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),
|
|
@@ -215,9 +236,31 @@ function safeHttpUrl(v: unknown): string | undefined {
|
|
|
215
236
|
return /^https?:\/\/.{3,}/.test(s) ? s.slice(0, 255) : undefined;
|
|
216
237
|
}
|
|
217
238
|
|
|
239
|
+
function allowedOrigins(v: unknown): PrepareResult<string[]> {
|
|
240
|
+
if (!Array.isArray(v)) return fail('allowed_origins 必须是数组(不限站点时请传空数组 [])');
|
|
241
|
+
const origins = new Set<string>();
|
|
242
|
+
for (const raw of v) {
|
|
243
|
+
const candidate = String(raw).trim();
|
|
244
|
+
if (!candidate) continue;
|
|
245
|
+
if (candidate.length > 255) return fail('Origin 长度不能超过 255 个字符');
|
|
246
|
+
let url: URL;
|
|
247
|
+
try { url = new URL(candidate); }
|
|
248
|
+
catch { return fail(`Origin 格式无效:${candidate}(请填 scheme://host[:port])`); }
|
|
249
|
+
if (candidate.includes('?') || candidate.includes('#')
|
|
250
|
+
|| (url.protocol !== 'http:' && url.protocol !== 'https:')
|
|
251
|
+
|| url.username || url.password || url.search || url.hash
|
|
252
|
+
|| url.pathname !== '/' || url.origin === 'null') {
|
|
253
|
+
return fail(`Origin 只能填 scheme://host[:port],不能带路径、参数、用户信息或片段:${candidate}`);
|
|
254
|
+
}
|
|
255
|
+
origins.add(url.origin);
|
|
256
|
+
}
|
|
257
|
+
return { ok: true, value: [...origins] };
|
|
258
|
+
}
|
|
259
|
+
|
|
218
260
|
function chatAppearance(v: unknown): ChatEntry['appearance'] | undefined {
|
|
219
261
|
const apIn = object(v);
|
|
220
262
|
const appearance: ChatEntry['appearance'] = {};
|
|
263
|
+
if (apIn.default_open === true) appearance.default_open = true;
|
|
221
264
|
const width = clampNum(apIn.width, 280, 720); if (width !== undefined) appearance.width = width;
|
|
222
265
|
const height = clampNum(apIn.height, 360, 900); if (height !== undefined) appearance.height = height;
|
|
223
266
|
if (apIn.title_align === 'left' || apIn.title_align === 'center') appearance.title_align = apIn.title_align;
|
|
@@ -253,6 +296,8 @@ export async function prepareChatEntryConfig(
|
|
|
253
296
|
if (ticketClient && !(await deps.clientExists(ticketClient))) return fail(`票据签发方 ${ticketClient} 不是已登记的接入方`);
|
|
254
297
|
const bucketName = str(input.bucket);
|
|
255
298
|
if (bucketName && !(await deps.bucketExists(bucketName))) return fail(`存储桶 ${bucketName} 未登记(先在「对象存储」建)`);
|
|
299
|
+
const origins = allowedOrigins(input.allowed_origins);
|
|
300
|
+
if (!origins.ok) return origins;
|
|
256
301
|
|
|
257
302
|
return {
|
|
258
303
|
ok: true,
|
|
@@ -261,9 +306,7 @@ export async function prepareChatEntryConfig(
|
|
|
261
306
|
name,
|
|
262
307
|
route_key: routeKey,
|
|
263
308
|
enabled: input.enabled !== false,
|
|
264
|
-
allowed_origins:
|
|
265
|
-
? input.allowed_origins.map((x) => String(x).trim().replace(/\/+$/, '')).filter(Boolean)
|
|
266
|
-
: [],
|
|
309
|
+
allowed_origins: origins.value,
|
|
267
310
|
rate_limit_per_min: Math.min(Math.max(Number(input.rate_limit_per_min ?? 20) || 20, 1), 600),
|
|
268
311
|
ticket_client: ticketClient || undefined,
|
|
269
312
|
bucket: bucketName || undefined,
|
|
@@ -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: 接入方、渠道、存储桶和工具源契约对齐', () => {
|
|
@@ -142,9 +148,11 @@ test('Config JSON Schemas: 接入方、渠道、存储桶和工具源契约对
|
|
|
142
148
|
assert.equal(alertRule.properties.cooldown_min.maximum, 1440);
|
|
143
149
|
|
|
144
150
|
assert.deepEqual(chatEntry.required, ['name', 'route_key', 'allowed_origins', 'rate_limit_per_min', 'enabled']);
|
|
151
|
+
assert.equal(chatEntry.properties.allowed_origins.items.pattern, '^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@]+/?$');
|
|
145
152
|
assert.equal(chatEntry.properties.rate_limit_per_min.maximum, 600);
|
|
146
153
|
assert.deepEqual(chatEntry.properties.appearance.properties.title_align.enum, ['center', 'left']);
|
|
147
154
|
assert.deepEqual(chatEntry.properties.appearance.properties.position.enum, ['right', 'left']);
|
|
155
|
+
assert.equal(chatEntry.properties.appearance.properties.default_open.default, false);
|
|
148
156
|
assert.equal(chatEntry.properties.appearance.properties.ai_notice.type, 'boolean');
|
|
149
157
|
|
|
150
158
|
assert.deepEqual(pageContext.required, ['entry_key', 'url_pattern', 'enabled']);
|
|
@@ -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
|
+
});
|