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,72 @@
|
|
|
1
|
+
-- 055: 本地 Agent 基于业务系统网页授权的可撤销持久会话。
|
|
2
|
+
-- 只建身份与授权账本;不包含套餐、付费、权益或用量语义。
|
|
3
|
+
|
|
4
|
+
ALTER TABLE `bz_clients`
|
|
5
|
+
ADD COLUMN `agent_authorize_url` VARCHAR(2048) DEFAULT NULL COMMENT '业务侧 Agent 网页授权入口' AFTER `token`;
|
|
6
|
+
|
|
7
|
+
ALTER TABLE `bz_jobs`
|
|
8
|
+
ADD COLUMN `agent_session_id` CHAR(36) DEFAULT NULL COMMENT '受信本地 Agent 会话归属' AFTER `client_app_id`;
|
|
9
|
+
|
|
10
|
+
ALTER TABLE `bz_jobs`
|
|
11
|
+
ADD COLUMN `on_behalf_of` VARCHAR(191) DEFAULT NULL COMMENT '业务侧批准的操作主体' AFTER `agent_session_id`;
|
|
12
|
+
|
|
13
|
+
ALTER TABLE `bz_jobs`
|
|
14
|
+
ADD KEY `idx_agent_session` (`agent_session_id`, `created_at`);
|
|
15
|
+
|
|
16
|
+
CREATE TABLE IF NOT EXISTS `bz_agent_authorizations` (
|
|
17
|
+
`authorization_id` CHAR(36) NOT NULL,
|
|
18
|
+
`client_app_id` VARCHAR(64) NOT NULL,
|
|
19
|
+
`redirect_uri` VARCHAR(2048) NOT NULL COMMENT '创建时锁定的 loopback redirect',
|
|
20
|
+
`state_value` VARCHAR(512) NOT NULL,
|
|
21
|
+
`requested_routes` JSON NOT NULL,
|
|
22
|
+
`device_label` VARCHAR(128) NOT NULL,
|
|
23
|
+
`code_challenge` CHAR(43) NOT NULL COMMENT 'PKCE S256 base64url digest',
|
|
24
|
+
`status` VARCHAR(16) NOT NULL DEFAULT 'pending',
|
|
25
|
+
`principal_json` JSON DEFAULT NULL,
|
|
26
|
+
`on_behalf_of` VARCHAR(191) DEFAULT NULL,
|
|
27
|
+
`allowed_routes` JSON DEFAULT NULL,
|
|
28
|
+
`code_hash` CHAR(64) DEFAULT NULL COMMENT '一次性 authorization code SHA-256',
|
|
29
|
+
`code_expires_at` DATETIME DEFAULT NULL COMMENT '批准后的短时兑换截止时间',
|
|
30
|
+
`session_id` CHAR(36) DEFAULT NULL,
|
|
31
|
+
`created_at` DATETIME NOT NULL,
|
|
32
|
+
`expires_at` DATETIME NOT NULL,
|
|
33
|
+
`approved_at` DATETIME DEFAULT NULL,
|
|
34
|
+
`consumed_at` DATETIME DEFAULT NULL,
|
|
35
|
+
PRIMARY KEY (`authorization_id`),
|
|
36
|
+
UNIQUE KEY `uk_agent_auth_code_hash` (`code_hash`),
|
|
37
|
+
KEY `idx_agent_auth_client` (`client_app_id`, `created_at`),
|
|
38
|
+
KEY `idx_agent_auth_expires` (`status`, `expires_at`)
|
|
39
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='本地 Agent 一次性网页授权请求';
|
|
40
|
+
|
|
41
|
+
CREATE TABLE IF NOT EXISTS `bz_agent_sessions` (
|
|
42
|
+
`session_id` CHAR(36) NOT NULL,
|
|
43
|
+
`client_app_id` VARCHAR(64) NOT NULL,
|
|
44
|
+
`device_label` VARCHAR(128) NOT NULL,
|
|
45
|
+
`principal_json` JSON NOT NULL,
|
|
46
|
+
`on_behalf_of` VARCHAR(191) NOT NULL,
|
|
47
|
+
`allowed_routes` JSON NOT NULL,
|
|
48
|
+
`access_token_hash` CHAR(64) NOT NULL COMMENT '当前 access token SHA-256',
|
|
49
|
+
`access_expires_at` DATETIME NOT NULL,
|
|
50
|
+
`refresh_expires_at` DATETIME NOT NULL,
|
|
51
|
+
`created_at` DATETIME NOT NULL,
|
|
52
|
+
`updated_at` DATETIME NOT NULL,
|
|
53
|
+
`last_seen_at` DATETIME DEFAULT NULL,
|
|
54
|
+
`revoked_at` DATETIME DEFAULT NULL,
|
|
55
|
+
PRIMARY KEY (`session_id`),
|
|
56
|
+
UNIQUE KEY `uk_agent_access_hash` (`access_token_hash`),
|
|
57
|
+
KEY `idx_agent_session_client` (`client_app_id`, `created_at`),
|
|
58
|
+
KEY `idx_agent_session_refresh_exp` (`refresh_expires_at`),
|
|
59
|
+
KEY `idx_agent_session_revoked` (`revoked_at`)
|
|
60
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='可撤销本地 Agent 会话';
|
|
61
|
+
|
|
62
|
+
CREATE TABLE IF NOT EXISTS `bz_agent_refresh_tokens` (
|
|
63
|
+
`token_hash` CHAR(64) NOT NULL COMMENT 'refresh token SHA-256',
|
|
64
|
+
`session_id` CHAR(36) NOT NULL,
|
|
65
|
+
`status` VARCHAR(16) NOT NULL DEFAULT 'active' COMMENT 'active|used|replayed|revoked',
|
|
66
|
+
`created_at` DATETIME NOT NULL,
|
|
67
|
+
`expires_at` DATETIME NOT NULL,
|
|
68
|
+
`used_at` DATETIME DEFAULT NULL,
|
|
69
|
+
PRIMARY KEY (`token_hash`),
|
|
70
|
+
KEY `idx_agent_refresh_session` (`session_id`, `created_at`),
|
|
71
|
+
KEY `idx_agent_refresh_expires` (`status`, `expires_at`)
|
|
72
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Agent refresh token 轮换与重放检测账本';
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
-- 056: Agent Client Runtime v1 私有候选。
|
|
2
|
+
-- 本迁移只增加本地编排的配置、会话映射、运行幂等和可见消息关联;不改变旧 /run 编排语义。
|
|
3
|
+
|
|
4
|
+
ALTER TABLE `bz_routes`
|
|
5
|
+
ADD COLUMN `agent_client` JSON DEFAULT NULL COMMENT '本地 Agent Runtime 覆盖配置' AFTER `memory`;
|
|
6
|
+
|
|
7
|
+
ALTER TABLE `bz_messages`
|
|
8
|
+
ADD COLUMN `agent_run_id` CHAR(36) DEFAULT NULL COMMENT '本地 Agent Runtime run 关联' AFTER `job_id`;
|
|
9
|
+
|
|
10
|
+
ALTER TABLE `bz_messages`
|
|
11
|
+
ADD COLUMN `external_message_id` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '客户端可见消息幂等键' AFTER `agent_run_id`;
|
|
12
|
+
|
|
13
|
+
ALTER TABLE `bz_messages`
|
|
14
|
+
ADD UNIQUE KEY `uk_agent_run_direction` (`agent_run_id`, `direction`);
|
|
15
|
+
|
|
16
|
+
ALTER TABLE `bz_messages`
|
|
17
|
+
ADD KEY `idx_external_message` (`external_message_id`);
|
|
18
|
+
|
|
19
|
+
CREATE TABLE IF NOT EXISTS `bz_agent_client_conversations` (
|
|
20
|
+
`session_id` CHAR(36) NOT NULL,
|
|
21
|
+
`client_app_id` VARCHAR(64) NOT NULL,
|
|
22
|
+
`route_key` VARCHAR(64) NOT NULL,
|
|
23
|
+
`client_conversation_id` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
|
|
24
|
+
`thread_id` BIGINT UNSIGNED NOT NULL,
|
|
25
|
+
`created_at` DATETIME NOT NULL,
|
|
26
|
+
`last_active_at` DATETIME NOT NULL,
|
|
27
|
+
PRIMARY KEY (`session_id`, `route_key`, `client_conversation_id`),
|
|
28
|
+
KEY `idx_agent_conversation_thread` (`thread_id`),
|
|
29
|
+
KEY `idx_agent_conversation_client` (`client_app_id`, `last_active_at`)
|
|
30
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='本地 Agent 会话到 Hub thread 的隔离映射';
|
|
31
|
+
|
|
32
|
+
CREATE TABLE IF NOT EXISTS `bz_agent_client_runs` (
|
|
33
|
+
`run_id` CHAR(36) NOT NULL,
|
|
34
|
+
`session_id` CHAR(36) NOT NULL,
|
|
35
|
+
`client_app_id` VARCHAR(64) NOT NULL,
|
|
36
|
+
`route_key` VARCHAR(64) NOT NULL,
|
|
37
|
+
`thread_id` BIGINT UNSIGNED NOT NULL,
|
|
38
|
+
`client_conversation_id` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
|
|
39
|
+
`client_turn_id` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
|
|
40
|
+
`user_message_id` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
|
|
41
|
+
`request_hash` CHAR(64) NOT NULL,
|
|
42
|
+
`user_input` MEDIUMTEXT NOT NULL,
|
|
43
|
+
`context_json` JSON DEFAULT NULL,
|
|
44
|
+
`status` VARCHAR(24) NOT NULL DEFAULT 'preparing',
|
|
45
|
+
`completion_hash` CHAR(64) DEFAULT NULL,
|
|
46
|
+
`assistant_message_id` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
|
|
47
|
+
`final_content` MEDIUMTEXT DEFAULT NULL,
|
|
48
|
+
`model` VARCHAR(191) DEFAULT NULL,
|
|
49
|
+
`runtime` VARCHAR(191) DEFAULT NULL,
|
|
50
|
+
`usage_json` JSON DEFAULT NULL,
|
|
51
|
+
`created_at` DATETIME NOT NULL,
|
|
52
|
+
`updated_at` DATETIME NOT NULL,
|
|
53
|
+
`completed_at` DATETIME DEFAULT NULL,
|
|
54
|
+
PRIMARY KEY (`run_id`),
|
|
55
|
+
UNIQUE KEY `uk_agent_turn` (`session_id`, `route_key`, `client_conversation_id`, `client_turn_id`),
|
|
56
|
+
UNIQUE KEY `uk_agent_user_message` (`session_id`, `route_key`, `user_message_id`),
|
|
57
|
+
UNIQUE KEY `uk_agent_assistant_message` (`session_id`, `route_key`, `assistant_message_id`),
|
|
58
|
+
KEY `idx_agent_run_thread` (`thread_id`, `created_at`),
|
|
59
|
+
KEY `idx_agent_run_client` (`client_app_id`, `created_at`)
|
|
60
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='本地 Agent Runtime 运行与幂等快照';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 企业微信主动发消息(qyapi):corpid+secret 换 access_token(缓存)→ message/send 推文本给成员。
|
|
2
2
|
// 用于"异步主动推":llm/执行器回答超过企微回调 5s 被动窗口时,任务完成后由中枢主动把回复推回用户。
|
|
3
|
-
// ⚠ 调用来源 IP 必须在该应用的「企业可信IP」名单里,否则报 60020
|
|
3
|
+
// ⚠ 调用来源 IP 必须在该应用的「企业可信IP」名单里,否则报 60020;请将实际部署环境的出口 IP 加入名单。
|
|
4
4
|
// 用全局 fetch(Node ≥18),无第三方依赖。
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
6
6
|
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import type { AppConfig } from '../core/config/config';
|
|
4
|
+
import type { AgentSession, Client, Route, ToolProvider } from '../core/contracts/types';
|
|
5
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
6
|
+
import type { AgentClientRunRecord } from '../infrastructure/config/config-agent-client-runtime-repository';
|
|
7
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
8
|
+
import type { ToolProxyDeps } from './tool-proxy';
|
|
9
|
+
import { AgentToolApiError, listAgentToolsFor } from './agent-tool-invocations';
|
|
10
|
+
import { completeAgentRunFor, getAgentWorkspaceBootstrapFor, prepareAgentTurnFor, searchAgentCapabilitiesFor, type AgentClientRuntimeDeps } from './agent-client-runtime';
|
|
11
|
+
|
|
12
|
+
const SESSION_ID = '11111111-1111-4111-8111-111111111111';
|
|
13
|
+
const RUN_ID = '22222222-2222-4222-8222-222222222222';
|
|
14
|
+
|
|
15
|
+
function spec(): string {
|
|
16
|
+
const acc = (scope: string) => ({ 'x-agent-capability': { version: 1, enabled: true, scope, subject: { required: true } } });
|
|
17
|
+
return JSON.stringify({ openapi: '3.0.0', info: { title: 'test', version: '1' }, paths: {
|
|
18
|
+
'/staff': { get: { operationId: 'staff_list', summary: '查询员工', ...acc('tenant.staff.read') } },
|
|
19
|
+
'/orders': { get: { operationId: 'order_list', summary: '查询订单', ...acc('tenant.order.read') } },
|
|
20
|
+
} });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function route(): Route {
|
|
24
|
+
return {
|
|
25
|
+
route_key: 'tenant-agent', name: '门店助手', description: '本地业务助手', enabled: true,
|
|
26
|
+
target: 'llm', target_config: { credential: 'never-return-this', model: 'never-return-model', system_prompt: '只按业务规则回答' },
|
|
27
|
+
profile: 'general', permission: 'full', session_policy: 'new',
|
|
28
|
+
agent_client: { enabled: true, instructions: '先确认再执行', active_tool_limit: 2 },
|
|
29
|
+
audience: { enabled: true, clients: ['example-business'], roles: ['admin'] },
|
|
30
|
+
memory: { recent_messages: 5 },
|
|
31
|
+
tools: { sources: [{ provider: 'business', allow: ['*'] }], max_calls: 4, agent_direct: { enabled: true } },
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function auth(): { client: Client; session: AgentSession } {
|
|
36
|
+
return {
|
|
37
|
+
client: { app_id: 'example-business', name: 'Example Business', token: 'hidden', allowed_routes: ['tenant-agent'], allowed_channels: [], rate_limit_per_min: 0, enabled: true },
|
|
38
|
+
session: {
|
|
39
|
+
session_id: SESSION_ID, client_app_id: 'example-business', device_label: 'test', principal: { id: 'u1', roles: ['admin'] },
|
|
40
|
+
on_behalf_of: 'tenant:u1', allowed_routes: ['tenant-agent'], created_at: '2026-01-01T00:00:00.000Z',
|
|
41
|
+
access_expires_at: '2099-01-01T00:00:00.000Z', refresh_expires_at: '2099-02-01T00:00:00.000Z',
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function fixture() {
|
|
47
|
+
let currentRoute = route();
|
|
48
|
+
let userWrites = 0;
|
|
49
|
+
let assistantWrites = 0;
|
|
50
|
+
let run: AgentClientRunRecord | null = null;
|
|
51
|
+
const provider: ToolProvider = {
|
|
52
|
+
name: 'business', base_url: 'https://secret-business.example.com', secret: 'provider-secret', spec_source: 'inline', spec_json: spec(),
|
|
53
|
+
enabled: true, log_payload: false, timeout_ms: 1000, rate_limit_per_min: 0, auto_refresh_min: 0,
|
|
54
|
+
};
|
|
55
|
+
const repo = {
|
|
56
|
+
resolveConversation: async () => 7,
|
|
57
|
+
reserveRun: async (input: any) => {
|
|
58
|
+
if (!run) {
|
|
59
|
+
run = {
|
|
60
|
+
run_id: RUN_ID, ...input, context: null, status: 'preparing', completion_hash: null, assistant_message_id: null,
|
|
61
|
+
final_content: null, model: null, runtime: null, usage: null,
|
|
62
|
+
created_at: '2026-01-01T00:00:00.000Z', updated_at: '2026-01-01T00:00:00.000Z', completed_at: null,
|
|
63
|
+
} as AgentClientRunRecord;
|
|
64
|
+
return { run, created: true };
|
|
65
|
+
}
|
|
66
|
+
if (run.request_hash !== input.request_hash) throw new Error('unexpected conflict');
|
|
67
|
+
return { run, created: false };
|
|
68
|
+
},
|
|
69
|
+
finalizeTurn: async (input: any) => {
|
|
70
|
+
if (!run) throw new Error('missing run');
|
|
71
|
+
if (!run.context) { userWrites++; run = { ...run, context: input.context, status: 'context_ready' }; }
|
|
72
|
+
return run;
|
|
73
|
+
},
|
|
74
|
+
getRun: async () => run,
|
|
75
|
+
findRunForInvocation: async () => run,
|
|
76
|
+
completeRun: async (input: any) => {
|
|
77
|
+
if (!run) throw new Error('missing run');
|
|
78
|
+
if (run.completion_hash) {
|
|
79
|
+
if (run.completion_hash !== input.completion_hash) {
|
|
80
|
+
const { AgentClientRuntimeConflictError } = await import('../infrastructure/config/config-agent-client-runtime-repository');
|
|
81
|
+
throw new AgentClientRuntimeConflictError('immutable');
|
|
82
|
+
}
|
|
83
|
+
return { run, created: false };
|
|
84
|
+
}
|
|
85
|
+
assistantWrites++;
|
|
86
|
+
run = { ...run, completion_hash: input.completion_hash, assistant_message_id: input.assistant_message_id, final_content: input.assistant_output, status: input.status, completed_at: '2026-01-01T00:01:00.000Z' };
|
|
87
|
+
return { run, created: true };
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
const config = {
|
|
91
|
+
routes: { get: async () => currentRoute, list: async () => [currentRoute] },
|
|
92
|
+
toolProviders: { get: async () => provider },
|
|
93
|
+
conversations: {
|
|
94
|
+
getThreadMemory: async () => ({ summary: '之前讨论员工', summary_upto_id: 2 }),
|
|
95
|
+
recentMessagesAfter: async () => [{ direction: 'out', channel: 'hub', content: '上一条回复', created_at: '2026-01-01T00:00:00.000Z' }],
|
|
96
|
+
},
|
|
97
|
+
agentClientRuntime: repo,
|
|
98
|
+
} as unknown as ConfigStoreContract;
|
|
99
|
+
const stateStore = { appendAudit: async () => undefined } as unknown as RuntimeStateStore;
|
|
100
|
+
const toolProxyDeps: ToolProxyDeps = {
|
|
101
|
+
cfg: { toolRetrieval: {} } as AppConfig, configStore: config, stateStore, toolIndex: null,
|
|
102
|
+
now: () => '2026-01-01T00:00:00.000Z', sleep: async () => undefined,
|
|
103
|
+
};
|
|
104
|
+
const deps: AgentClientRuntimeDeps = { toolProxyDeps, kbService: null, stateStore };
|
|
105
|
+
return { deps, repo, setRoute: (value: Route) => { currentRoute = value; }, counts: () => ({ userWrites, assistantWrites }) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
test('Agent Runtime bootstrap 只返回安全字段并声明本地规划治理边界', async () => {
|
|
109
|
+
const fx = fixture();
|
|
110
|
+
const bootstrap = await getAgentWorkspaceBootstrapFor(fx.deps, auth(), 'tenant-agent');
|
|
111
|
+
assert.equal(bootstrap['schema_version'], 'bailing.agent-runtime-profile.v1');
|
|
112
|
+
const encoded = JSON.stringify(bootstrap);
|
|
113
|
+
assert.match(encoded, /只按业务规则回答/);
|
|
114
|
+
assert.match(encoded, /先确认再执行/);
|
|
115
|
+
assert.doesNotMatch(encoded, /never-return-this|never-return-model|provider-secret|secret-business/);
|
|
116
|
+
const profile = bootstrap['profile'] as Record<string, any>;
|
|
117
|
+
assert.equal(profile.governance.planner, 'local_agent');
|
|
118
|
+
assert.equal(profile.governance.hidden_reasoning_sync, false);
|
|
119
|
+
assert.equal(profile.governance.max_tool_calls, 4);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test('Agent Runtime turn 先装配旧记忆、主动工具封顶且幂等写一条 user message', async () => {
|
|
123
|
+
const fx = fixture();
|
|
124
|
+
const input = { client_conversation_id: 'c1', client_turn_id: 't1', user_message_id: 'm1', user_input: '查询员工 Ada' };
|
|
125
|
+
const first = await prepareAgentTurnFor(fx.deps, auth(), 'tenant-agent', input);
|
|
126
|
+
const replay = await prepareAgentTurnFor(fx.deps, auth(), 'tenant-agent', input);
|
|
127
|
+
assert.deepEqual(replay, first);
|
|
128
|
+
assert.equal(fx.counts().userWrites, 1);
|
|
129
|
+
assert.equal((first['active_tools'] as unknown[]).length, 2);
|
|
130
|
+
const context = first['context'] as Record<string, any>;
|
|
131
|
+
assert.equal(context.memory.recent.length, 1);
|
|
132
|
+
assert.equal(context.governance.authorization, 'server_revalidated');
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('Agent Runtime turn 对超长、控制字符和非法 renderers 严格失败而不静默改写', async () => {
|
|
136
|
+
const fx = fixture();
|
|
137
|
+
const base = { client_conversation_id: 'c1', client_turn_id: 't1', user_message_id: 'm1', user_input: '查询员工' };
|
|
138
|
+
const badRequest = (error: unknown) => error instanceof AgentToolApiError && error.statusCode === 400;
|
|
139
|
+
|
|
140
|
+
for (const user_input of ['x'.repeat(64_001), '查询\u0000员工']) {
|
|
141
|
+
await assert.rejects(prepareAgentTurnFor(fx.deps, auth(), 'tenant-agent', { ...base, user_input }), badRequest);
|
|
142
|
+
}
|
|
143
|
+
const invalidRenderers = [
|
|
144
|
+
Array.from({ length: 21 }, (_, index) => `renderer.${index}`),
|
|
145
|
+
['markdown', 'markdown'],
|
|
146
|
+
['markdown', 'invalid renderer'],
|
|
147
|
+
];
|
|
148
|
+
for (const renderers of invalidRenderers) {
|
|
149
|
+
await assert.rejects(prepareAgentTurnFor(fx.deps, auth(), 'tenant-agent', { ...base, renderers }), badRequest);
|
|
150
|
+
}
|
|
151
|
+
assert.deepEqual(fx.counts(), { userWrites: 0, assistantWrites: 0 });
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test('Agent Runtime complete 冻结 assistant_message_id/content/status/usage 并幂等回放', async () => {
|
|
155
|
+
const fx = fixture();
|
|
156
|
+
await prepareAgentTurnFor(fx.deps, auth(), 'tenant-agent', { client_conversation_id: 'c1', client_turn_id: 't1', user_message_id: 'm1', user_input: '查询员工' });
|
|
157
|
+
const completion = { assistant_message_id: 'a1', status: 'completed' as const, content: '已完成', usage: { total_tokens: 9 } };
|
|
158
|
+
assert.equal((await completeAgentRunFor(fx.deps, auth(), RUN_ID, completion))['idempotent_replay'], false);
|
|
159
|
+
assert.equal((await completeAgentRunFor(fx.deps, auth(), RUN_ID, completion))['idempotent_replay'], true);
|
|
160
|
+
assert.equal(fx.counts().assistantWrites, 1);
|
|
161
|
+
await assert.rejects(
|
|
162
|
+
completeAgentRunFor(fx.deps, auth(), RUN_ID, { ...completion, assistant_message_id: 'a2' }),
|
|
163
|
+
(error) => error instanceof AgentToolApiError && error.statusCode === 409,
|
|
164
|
+
);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test('Agent Runtime complete 对超长和控制字符正文、模型、运行时严格返回 400', async () => {
|
|
168
|
+
const fx = fixture();
|
|
169
|
+
const base = { assistant_message_id: 'a1', status: 'completed' as const, content: '已完成' };
|
|
170
|
+
const invalid = [
|
|
171
|
+
{ ...base, content: 'x'.repeat(64_001) },
|
|
172
|
+
{ ...base, content: '完成\u0001' },
|
|
173
|
+
{ ...base, model: 'm'.repeat(192) },
|
|
174
|
+
{ ...base, model: 'model\u007f' },
|
|
175
|
+
{ ...base, runtime: 'r'.repeat(192) },
|
|
176
|
+
{ ...base, runtime: 'runtime\u0002' },
|
|
177
|
+
];
|
|
178
|
+
for (const completion of invalid) {
|
|
179
|
+
await assert.rejects(
|
|
180
|
+
completeAgentRunFor(fx.deps, auth(), RUN_ID, completion),
|
|
181
|
+
(error) => error instanceof AgentToolApiError && error.statusCode === 400,
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
assert.equal(fx.counts().assistantWrites, 0);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test('agent_client.enabled=false 只关闭新 Runtime,旧 Agent tools catalog 仍兼容', async () => {
|
|
188
|
+
const fx = fixture();
|
|
189
|
+
fx.setRoute({ ...route(), agent_client: { enabled: false } });
|
|
190
|
+
await assert.rejects(
|
|
191
|
+
getAgentWorkspaceBootstrapFor(fx.deps, auth(), 'tenant-agent'),
|
|
192
|
+
(error) => error instanceof AgentToolApiError && error.code === 'agent_client_disabled',
|
|
193
|
+
);
|
|
194
|
+
assert.equal((await listAgentToolsFor(fx.deps.toolProxyDeps, auth(), 'tenant-agent')).tools.length, 2);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test('capability search 在 embedding 不可用时整体确定性 lexical 回退', async () => {
|
|
198
|
+
const fx = fixture();
|
|
199
|
+
fx.deps.toolProxyDeps.toolIndex = { retrieve: async () => { throw new Error('embedding down'); } } as any;
|
|
200
|
+
const first = await searchAgentCapabilitiesFor(fx.deps, auth(), 'tenant-agent', { query: '员工', limit: 2 });
|
|
201
|
+
const second = await searchAgentCapabilitiesFor(fx.deps, auth(), 'tenant-agent', { query: '员工', limit: 2 });
|
|
202
|
+
assert.equal(first['schema_version'], 'bailing.agent-capability-search.v1');
|
|
203
|
+
assert.deepEqual(first, second);
|
|
204
|
+
assert.equal((first['tools'] as Array<{ name: string }>)[0]?.name, 'staff_list');
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
test('capability search 空 query 必须绑定合法 run,且可回退到该 run 的 user_input', async () => {
|
|
208
|
+
const fx = fixture();
|
|
209
|
+
for (const input of [{}, { query: ' \n\t ' }]) {
|
|
210
|
+
await assert.rejects(
|
|
211
|
+
searchAgentCapabilitiesFor(fx.deps, auth(), 'tenant-agent', input),
|
|
212
|
+
(error) => error instanceof AgentToolApiError && error.statusCode === 400,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
await prepareAgentTurnFor(fx.deps, auth(), 'tenant-agent', {
|
|
216
|
+
client_conversation_id: 'c1', client_turn_id: 't1', user_message_id: 'm1', user_input: '查询员工 Ada',
|
|
217
|
+
});
|
|
218
|
+
const fallback = await searchAgentCapabilitiesFor(fx.deps, auth(), 'tenant-agent', { run_id: RUN_ID });
|
|
219
|
+
assert.equal(fallback['query'], '查询员工 Ada');
|
|
220
|
+
assert.equal((fallback['tools'] as Array<{ name: string }>)[0]?.name, 'staff_list');
|
|
221
|
+
});
|