bailinghub 0.5.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.
Files changed (82) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -0
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +25 -9
  5. package/docs/AGENT_AUTH_API.md +17 -5
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +65 -14
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +51 -12
  8. package/docs/CHANGELOG.en.md +12 -0
  9. package/docs/CHANGELOG.md +12 -0
  10. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  11. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  12. package/docs/README.en.md +2 -0
  13. package/docs/README.md +2 -0
  14. package/docs/RELEASE_NOTES_v0.5.1.en.md +45 -0
  15. package/docs/RELEASE_NOTES_v0.5.1.md +45 -0
  16. package/package.json +1 -1
  17. package/scripts/check-doc-links.mjs +1 -0
  18. package/scripts/check-image-tags.sh +1 -1
  19. package/scripts/check-release-consistency.test.mjs +5 -5
  20. package/scripts/install.sh +1 -1
  21. package/scripts/publish-images.sh +1 -1
  22. package/scripts/release-audit.mjs +1 -0
  23. package/scripts/verify-github-repo.mjs +1 -0
  24. package/src/app/oss-edition.ts +1 -0
  25. package/src/core/config/agent-direct-console-selection.test.ts +22 -0
  26. package/src/infrastructure/config/config-agent-auth-repository.test.ts +36 -0
  27. package/src/infrastructure/config/config-agent-auth-repository.ts +97 -0
  28. package/src/infrastructure/config/config-agent-client-runtime-repository.test.ts +38 -0
  29. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +54 -0
  30. package/src/routes/admin-agent-clients.test.ts +120 -0
  31. package/src/routes/admin-agent-clients.ts +161 -0
  32. package/src/routes/admin.ts +3 -0
  33. package/web/console/assets/{Accounts-D4RRm5D1.js → Accounts-r10QUjLQ.js} +1 -1
  34. package/web/console/assets/AgentClients-DsWADpzr.css +1 -0
  35. package/web/console/assets/AgentClients-UTTqbkjy.js +1 -0
  36. package/web/console/assets/{Approvals-CsTTKb8o.js → Approvals-BGKkYIya.js} +1 -1
  37. package/web/console/assets/{Audit-BzvZ7JZw.js → Audit-CQmjOAoO.js} +1 -1
  38. package/web/console/assets/{BrandLockup-CYcA93wh.js → BrandLockup-BF_0pCa3.js} +1 -1
  39. package/web/console/assets/{Channels-DRQZggqM.js → Channels-C4yZE67F.js} +1 -1
  40. package/web/console/assets/{ChatEntries-BUB7BWKU.js → ChatEntries-OqsqLjU6.js} +1 -1
  41. package/web/console/assets/Clients-CNIVs7Qn.css +1 -0
  42. package/web/console/assets/Clients-Dv3sv51C.js +3 -0
  43. package/web/console/assets/{Cost-BZgFf1yM.js → Cost-C_-kiH59.js} +1 -1
  44. package/web/console/assets/{Credentials-BTe2Q07j.js → Credentials-CPTEAiV6.js} +1 -1
  45. package/web/console/assets/{Diagnostics-WL-buYli.js → Diagnostics-O-NKFOeI.js} +1 -1
  46. package/web/console/assets/{Executors-CGZ-7Xmp.js → Executors-GVIAiNgv.js} +1 -1
  47. package/web/console/assets/{HelpTip-CT07o3kB.js → HelpTip-i-KJhf5s.js} +1 -1
  48. package/web/console/assets/{Kb-VVw8oGsT.js → Kb-BsCWkJI1.js} +2 -2
  49. package/web/console/assets/{Login-rwvmBBPl.js → Login-VFjkHNMr.js} +1 -1
  50. package/web/console/assets/{Projects-CexaCEY1.js → Projects-Ds-sJwfy.js} +1 -1
  51. package/web/console/assets/Routes-CXGl9SMM.css +1 -0
  52. package/web/console/assets/Routes-Wwurw2UU.js +124 -0
  53. package/web/console/assets/{Runs-BzFNPTwD.js → Runs-DLPzXmSy.js} +1 -1
  54. package/web/console/assets/{Setup-Djh5yadQ.js → Setup-BLelw0_V.js} +1 -1
  55. package/web/console/assets/Shell-CvaeK4j_.js +1 -0
  56. package/web/console/assets/Shell-D9Uw-fsa.css +1 -0
  57. package/web/console/assets/{StorageBuckets-CQBR41W1.js → StorageBuckets-Dv6u47yO.js} +1 -1
  58. package/web/console/assets/{SystemSettings-DgnopekD.js → SystemSettings-B9K7zaDU.js} +1 -1
  59. package/web/console/assets/{SystemStatus-Bj8-kPt2.js → SystemStatus-H-oKDo-y.js} +1 -1
  60. package/web/console/assets/{Targets-BAfCt_nH.js → Targets-CCFhjPKf.js} +1 -1
  61. package/web/console/assets/{Tools-xjd0NZdE.js → Tools-D0H9xpFH.js} +1 -1
  62. package/web/console/assets/index-CuoTgf6q.js +2 -0
  63. package/web/console/assets/{index-DZEQL_yy.js → index-DyX9Bz3V.js} +1 -1
  64. package/web/console/assets/{request-DkNPOweH.js → request-F5lXa7Ro.js} +1 -1
  65. package/web/console/assets/{schema-CgPWAu1_.js → schema-DUWaWqPn.js} +1 -1
  66. package/web/console/assets/{util-SiQC2MJh.js → util-4bN2dv7B.js} +1 -1
  67. package/web/console/assets/{vendor-element-D7WRzHhy.js → vendor-element-CZoEjZr8.js} +1 -1
  68. package/web/console/assets/{vendor-mammoth-DvgsHdlx.js → vendor-mammoth-nXG51Cg7.js} +1 -1
  69. package/web/console/index.html +2 -2
  70. package/web-admin/src/agent-direct-selection.ts +21 -0
  71. package/web-admin/src/layout/Shell.vue +1 -1
  72. package/web-admin/src/pages/AgentClients.vue +254 -0
  73. package/web-admin/src/pages/Clients.vue +4 -2
  74. package/web-admin/src/pages/Routes.vue +54 -5
  75. package/web-admin/src/router.ts +2 -0
  76. package/web/console/assets/Clients-CQ_MonGL.css +0 -1
  77. package/web/console/assets/Clients-HhCyrxfz.js +0 -3
  78. package/web/console/assets/Routes-B9ZHbQAp.js +0 -124
  79. package/web/console/assets/Routes-BbkFpi6Y.css +0 -1
  80. package/web/console/assets/Shell-BVIjmoY8.css +0 -1
  81. package/web/console/assets/Shell-kn763smL.js +0 -1
  82. package/web/console/assets/index-DfJA7iJS.js +0 -2
@@ -0,0 +1,45 @@
1
+ # BailingHub v0.5.1:智能体客户端管理中心与批量写操作配置
2
+
3
+ `v0.5.1` 是 `v0.5.0` Agent Client v1 的兼容性管理增量。它让部署者能在 BailingHub 控制台集中查看客户端应用、已授权设备与 Agent Session、运行统计和工作区,并为路由批量选择当前工具源声明的可写操作。身份、审批、幂等、业务调用与最终授权仍沿用既有治理链路。
4
+
5
+ ## 主要变化
6
+
7
+ - **独立管理中心**:控制台新增“智能体客户端”菜单,复用既有 Client App、触发路由、Agent Auth 与 Agent Client Runtime 账本,不新增第二套客户端或执行器资源。
8
+ - **应用与工作区概览**:展示客户端启停状态、是否配置统一业务授权入口、允许路由、最近使用时间,以及启用 Agent Client 的工作区。
9
+ - **会话列表与撤销**:支持按客户端和 active、expired、revoked 状态查看 Agent Session,并由具备客户端写权限的管理员逐个撤销。撤销操作进入审计记录。
10
+ - **运行统计**:按时间窗口聚合运行数、会话数、完成/失败、工具调用、Token 与审批状态。失败率按 Core 已记录的 Agent Run 计算。
11
+ - **批量写操作选择**:路由编辑页可选择或清除当前工具源中全部可写 operationId,避免逐项配置大量能力。保存结果仍是精确 operationId 白名单,不支持 `*`。
12
+ - **统一业务授权入口**:文档明确每个 Client App 只配置一个账号与租户中立的 `agent_authorize_url`。用户打开该入口后,由业务页面基于当前登录态完成换号、租户选择、批准或拒绝;业务后端负责派生可信身份。
13
+
14
+ ## 安全与责任边界
15
+
16
+ - 管理 API 只向已有 Core 管理员权限开放。会话投影不选择或返回 access token hash、refresh token、授权码、提示词、工具参数和业务结果。
17
+ - 批量选择只减少控制台重复操作,不改变能力声明。未由工具源声明、未进入路由精确白名单或不在 Agent Session 允许范围内的操作仍不可见。
18
+ - 是否需要审批继续继承业务侧 ACC 与 Core 风险规则;`force_approval_tools` 只能额外收紧,不能通过批量选择放宽。
19
+ - 业务系统仍须在每次工具调用时验签并检查当前用户、租户、角色和权限;BailingHub 管理员不能替代业务最终授权。
20
+ - `connectionName` 是宿主本机的连接实例选择器,不是可信身份、业务 URL、账号或租户声明。
21
+
22
+ ## 兼容性与升级
23
+
24
+ - 没有新增或修改 SQL migration;沿用 `v0.5.0` 已发布的 Agent Auth 与 Agent Client Runtime 表。
25
+ - Agent Client Runtime、Client API、Kernel API、业务侧 PHP SDK、Widget、Executor Protocol、工具签名和审批协议保持兼容。
26
+ - 新管理中心依赖 MySQL Agent Auth 与 Runtime 账本。没有这些账本的部署不会获得虚构的会话或统计数据。
27
+ - 不使用 Agent Client 的部署无需新增配置,既有 `/run`、聊天入口和执行器路径不变。
28
+
29
+ ## 验证
30
+
31
+ 发布候选应完成:
32
+
33
+ ```bash
34
+ npm run release:check
35
+ ```
36
+
37
+ 重点覆盖 Core 类型检查与 612 项单测、管理 API 权限与脱敏投影、会话撤销、批量 operationId 选择、控制台构建和 E2E、Client API 生态消费者、全部 SDK 契约、Docker Demo、OSS 边界、安全扫描、依赖审计、版本一致性和 npm 制品检查。发布前还必须确认公开差异与制品不包含私有域名、凭据、本机路径或环境专属信息。
38
+
39
+ ## 相关文档
40
+
41
+ - [Agent Client v1 接入指南](AGENT_CLIENT_QUICKSTART.md)
42
+ - [Agent Auth v1](AGENT_AUTH_API.md)
43
+ - [Agent Client Runtime v1](AGENT_CLIENT_RUNTIME_API.md)
44
+ - [兼容性与升级](兼容性与升级.md)
45
+ - [English release notes](RELEASE_NOTES_v0.5.1.en.md)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailinghub",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Open-source ACC runtime and agent control plane for existing business systems.",
@@ -102,6 +102,7 @@ const englishCompanions = {
102
102
  'docs/RELEASE_NOTES_v0.3.3.md': 'docs/RELEASE_NOTES_v0.3.3.en.md',
103
103
  'docs/RELEASE_NOTES_v0.3.4.md': 'docs/RELEASE_NOTES_v0.3.4.en.md',
104
104
  'docs/RELEASE_NOTES_v0.5.0.md': 'docs/RELEASE_NOTES_v0.5.0.en.md',
105
+ 'docs/RELEASE_NOTES_v0.5.1.md': 'docs/RELEASE_NOTES_v0.5.1.en.md',
105
106
  'docs/TOOLS_DESIGN.md': 'docs/TOOLS_DESIGN.en.md',
106
107
  'docs/TOOLS_MODEL.md': 'docs/TOOLS_MODEL.en.md',
107
108
  'docs/AI友好工具设计指南.md': 'docs/AI_FRIENDLY_TOOLS.en.md',
@@ -9,7 +9,7 @@ REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_REGISTRY}"
9
9
  NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_NAMESPACE}"
10
10
  PACKAGE_VERSION="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' package.json | head -1)"
11
11
  TAG="${BAILING_IMAGE_TAG:-$PACKAGE_VERSION}"
12
- [ -n "$TAG" ] || TAG="0.5.0"
12
+ [ -n "$TAG" ] || TAG="0.5.1"
13
13
  MYSQL_TAG="${BAILING_MYSQL_IMAGE_TAG:-8.4}"
14
14
  MYSQL_IMAGE="${BAILING_MYSQL_IMAGE:-$REGISTRY/$NAMESPACE/bailing-mysql:$MYSQL_TAG}"
15
15
  PLATFORM="${BAILING_IMAGE_PLATFORM:-linux/amd64}"
@@ -38,8 +38,8 @@ function updateJson(root, relativePath, update) {
38
38
  test('current release surface is internally consistent', () => {
39
39
  const result = checkReleaseConsistency({ root: repoRoot });
40
40
  assert.deepEqual(result.findings, []);
41
- assert.equal(result.version, '0.5.0');
42
- assert.equal(result.stableVersion, '0.5.0');
41
+ assert.equal(result.version, '0.5.1');
42
+ assert.equal(result.stableVersion, '0.5.1');
43
43
  assert.equal(result.publishTag, 'latest');
44
44
  });
45
45
 
@@ -51,13 +51,13 @@ for (const [label, tag] of [
51
51
  const root = createFixture();
52
52
  try {
53
53
  updateJson(root, 'package.json', (pkg) => {
54
- pkg.version = '0.5.0-rc.1';
54
+ pkg.version = '0.5.1-rc.1';
55
55
  if (tag === undefined) delete pkg.publishConfig;
56
56
  else pkg.publishConfig = { tag };
57
57
  });
58
58
  updateJson(root, 'package-lock.json', (lock) => {
59
- lock.version = '0.5.0-rc.1';
60
- lock.packages[''].version = '0.5.0-rc.1';
59
+ lock.version = '0.5.1-rc.1';
60
+ lock.packages[''].version = '0.5.1-rc.1';
61
61
  });
62
62
 
63
63
  const result = checkReleaseConsistency({ root });
@@ -275,7 +275,7 @@ write_env() {
275
275
  TOOL_SECRET="${DEMO_TOOL_SECRET:-$(secret)}"
276
276
  CLIENT_TOKEN="${DEMO_CLIENT_TOKEN:-$(secret)}"
277
277
  IMAGE_TAG="${BAILING_IMAGE_TAG:-$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$APP_DIR/package.json" | head -1)}"
278
- [ -n "$IMAGE_TAG" ] || IMAGE_TAG="0.5.0"
278
+ [ -n "$IMAGE_TAG" ] || IMAGE_TAG="0.5.1"
279
279
  IMAGE_REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_IMAGE_REGISTRY}"
280
280
  IMAGE_NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_IMAGE_NAMESPACE}"
281
281
  cat > "$ENV_FILE" <<EOF
@@ -9,7 +9,7 @@ REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_REGISTRY}"
9
9
  NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_NAMESPACE}"
10
10
  PACKAGE_VERSION="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' package.json | head -1)"
11
11
  TAG="${BAILING_IMAGE_TAG:-$PACKAGE_VERSION}"
12
- [ -n "$TAG" ] || TAG="0.5.0"
12
+ [ -n "$TAG" ] || TAG="0.5.1"
13
13
  NODE_IMAGE="${BAILING_NODE_IMAGE:-node:22-bookworm-slim}"
14
14
  PLATFORM="${BAILING_IMAGE_PLATFORM:-linux/amd64}"
15
15
  PUSH="${BAILING_PUSH_IMAGES:-0}"
@@ -36,6 +36,7 @@ const requiredRepoFiles = [
36
36
  'docs/RELEASE_NOTES_v0.3.3.md',
37
37
  'docs/RELEASE_NOTES_v0.3.4.md',
38
38
  'docs/RELEASE_NOTES_v0.5.0.md',
39
+ 'docs/RELEASE_NOTES_v0.5.1.md',
39
40
  'docs/CHANGELOG.md',
40
41
  'docs/CLIENT_API.md',
41
42
  'config.example.json',
@@ -128,6 +128,7 @@ const requiredFiles = [
128
128
  'docs/RELEASE_NOTES_v0.3.3.md',
129
129
  'docs/RELEASE_NOTES_v0.3.4.md',
130
130
  'docs/RELEASE_NOTES_v0.5.0.md',
131
+ 'docs/RELEASE_NOTES_v0.5.1.md',
131
132
  'docs/CHANGELOG.md',
132
133
  ];
133
134
  for (const file of requiredFiles) requireFile(file);
@@ -83,6 +83,7 @@ export function createOssEdition(cfg: AppConfig, options: {
83
83
  modules: [
84
84
  'routes',
85
85
  'clients',
86
+ 'agent-clients',
86
87
  'chat',
87
88
  'channels',
88
89
  'targets',
@@ -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
+ });
@@ -145,3 +145,39 @@ test('AgentAuthRepository rejects an approved authorization after its short code
145
145
  assert.deepEqual(result, { ok: false, reason: 'invalid_grant' });
146
146
  assert.equal(insertedSession, false);
147
147
  });
148
+
149
+ test('AgentAuthRepository admin session projection filters state and never returns token hashes', async () => {
150
+ const queries: Array<{ sql: string; params: unknown[] }> = [];
151
+ const row = sessionRow({
152
+ access_expires_at: '2026-08-27 01:00:00',
153
+ refresh_expires_at: '2026-09-27 00:00:00',
154
+ created_at: '2026-08-27 00:00:00',
155
+ updated_at: '2026-08-27 00:10:00',
156
+ last_seen_at: '2026-08-27 00:10:00',
157
+ });
158
+ const pool = {
159
+ async query(sql: string, params: unknown[] = []) {
160
+ queries.push({ sql, params });
161
+ if (sql.startsWith('SELECT COUNT(*) AS total,')) {
162
+ return [[{ total: 3, active: 1, expired: 1, revoked: 1 }], []];
163
+ }
164
+ if (sql.startsWith('SELECT COUNT(*) AS total')) return [[{ total: 1 }], []];
165
+ if (sql.startsWith('SELECT session_id,client_app_id')) return [[row], []];
166
+ throw new Error(`unexpected query: ${sql}`);
167
+ },
168
+ } as unknown as Pool;
169
+ const repo = new AgentAuthRepository(() => pool);
170
+ const now = new Date('2026-08-27T00:30:00.000Z');
171
+ const result = await repo.listSessionsForAdmin({
172
+ clientAppId: 'example-business', state: 'active', limit: 25, offset: 5, now,
173
+ });
174
+ assert.equal(result.total, 1);
175
+ assert.equal(result.list[0]?.state, 'active');
176
+ assert.equal(result.list[0]?.last_seen_at, new Date('2026-08-27 00:10:00').toISOString());
177
+ assert.equal(Object.hasOwn(result.list[0]!, 'access_token_hash'), false);
178
+ assert.match(queries[0]!.sql, /client_app_id=\? AND revoked_at IS NULL AND refresh_expires_at>\?/);
179
+ assert.deepEqual(queries[1]!.params.slice(-2), [25, 5]);
180
+
181
+ const summary = await repo.sessionSummaryForAdmin(now);
182
+ assert.deepEqual(summary, { total: 3, active: 1, expired: 1, revoked: 1 });
183
+ });
@@ -33,6 +33,25 @@ export type RefreshRotationResult =
33
33
  | { ok: true; session: AgentSession }
34
34
  | { ok: false; reason: 'invalid_grant' | 'replayed' };
35
35
 
36
+ export type AgentSessionAdminState = 'active' | 'expired' | 'revoked';
37
+
38
+ export interface AgentSessionAdminRecord extends AgentSession {
39
+ last_seen_at?: string;
40
+ state: AgentSessionAdminState;
41
+ }
42
+
43
+ export interface AgentSessionAdminList {
44
+ list: AgentSessionAdminRecord[];
45
+ total: number;
46
+ }
47
+
48
+ export interface AgentSessionAdminSummary {
49
+ total: number;
50
+ active: number;
51
+ expired: number;
52
+ revoked: number;
53
+ }
54
+
36
55
  function jsonObject<T extends object>(value: unknown): T {
37
56
  if (value && typeof value === 'object' && !Array.isArray(value)) return value as T;
38
57
  if (typeof value === 'string') {
@@ -88,6 +107,19 @@ function sessionRow(row: any): AgentSession {
88
107
  };
89
108
  }
90
109
 
110
+ function sessionAdminState(row: any, now: Date): AgentSessionAdminState {
111
+ if (row.revoked_at) return 'revoked';
112
+ return new Date(row.refresh_expires_at).getTime() <= now.getTime() ? 'expired' : 'active';
113
+ }
114
+
115
+ function sessionAdminRow(row: any, now: Date): AgentSessionAdminRecord {
116
+ return {
117
+ ...sessionRow(row),
118
+ ...(row.last_seen_at ? { last_seen_at: iso(row.last_seen_at) } : {}),
119
+ state: sessionAdminState(row, now),
120
+ };
121
+ }
122
+
91
123
  async function rollback(connection: PoolConnection): Promise<void> {
92
124
  await connection.rollback().catch(() => undefined);
93
125
  }
@@ -244,6 +276,71 @@ export class AgentAuthRepository {
244
276
  return sessionRow(row);
245
277
  }
246
278
 
279
+ /** Admin-only projection. Token hashes and refresh-token rows never leave the repository. */
280
+ async listSessionsForAdmin(input: {
281
+ clientAppId?: string;
282
+ state?: AgentSessionAdminState | 'all';
283
+ limit?: number;
284
+ offset?: number;
285
+ now?: Date;
286
+ } = {}): Promise<AgentSessionAdminList> {
287
+ const now = input.now ?? new Date();
288
+ const limit = Math.min(Math.max(Math.round(Number(input.limit) || 50), 1), 200);
289
+ const offset = Math.max(Math.round(Number(input.offset) || 0), 0);
290
+ const where: string[] = [];
291
+ const params: unknown[] = [];
292
+ if (input.clientAppId) {
293
+ where.push('client_app_id=?');
294
+ params.push(input.clientAppId);
295
+ }
296
+ if (input.state === 'active') {
297
+ where.push('revoked_at IS NULL AND refresh_expires_at>?');
298
+ params.push(dtIso(now.toISOString()));
299
+ } else if (input.state === 'expired') {
300
+ where.push('revoked_at IS NULL AND refresh_expires_at<=?');
301
+ params.push(dtIso(now.toISOString()));
302
+ } else if (input.state === 'revoked') {
303
+ where.push('revoked_at IS NOT NULL');
304
+ }
305
+ const predicate = where.length ? ` WHERE ${where.join(' AND ')}` : '';
306
+ const [countRows] = await this.pool.query(`SELECT COUNT(*) AS total FROM bz_agent_sessions${predicate}`, params);
307
+ const [rows] = await this.pool.query(
308
+ `SELECT session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_expires_at,refresh_expires_at,created_at,updated_at,last_seen_at,revoked_at FROM bz_agent_sessions${predicate} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
309
+ [...params, limit, offset],
310
+ );
311
+ return {
312
+ list: (rows as any[]).map((row) => sessionAdminRow(row, now)),
313
+ total: Number((countRows as any[])[0]?.total ?? 0),
314
+ };
315
+ }
316
+
317
+ async getSessionForAdmin(sessionId: string, now = new Date()): Promise<AgentSessionAdminRecord | null> {
318
+ const [rows] = await this.pool.query(
319
+ 'SELECT session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_expires_at,refresh_expires_at,created_at,updated_at,last_seen_at,revoked_at FROM bz_agent_sessions WHERE session_id=? LIMIT 1',
320
+ [sessionId],
321
+ );
322
+ return (rows as any[])[0] ? sessionAdminRow((rows as any[])[0], now) : null;
323
+ }
324
+
325
+ async sessionSummaryForAdmin(now = new Date()): Promise<AgentSessionAdminSummary> {
326
+ const stamp = dtIso(now.toISOString());
327
+ const [rows] = await this.pool.query(
328
+ 'SELECT COUNT(*) AS total,' +
329
+ ' SUM(CASE WHEN revoked_at IS NULL AND refresh_expires_at>? THEN 1 ELSE 0 END) AS active,' +
330
+ ' SUM(CASE WHEN revoked_at IS NULL AND refresh_expires_at<=? THEN 1 ELSE 0 END) AS expired,' +
331
+ ' SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END) AS revoked' +
332
+ ' FROM bz_agent_sessions',
333
+ [stamp, stamp],
334
+ );
335
+ const row = (rows as any[])[0] ?? {};
336
+ return {
337
+ total: Number(row.total ?? 0),
338
+ active: Number(row.active ?? 0),
339
+ expired: Number(row.expired ?? 0),
340
+ revoked: Number(row.revoked ?? 0),
341
+ };
342
+ }
343
+
247
344
  async rotateRefreshToken(input: {
248
345
  refreshTokenHash: string;
249
346
  clientAppId: string;
@@ -0,0 +1,38 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { AgentClientRuntimeRepository } from './config-agent-client-runtime-repository';
4
+
5
+ test('AgentClientRuntimeRepository admin stats return aggregates only and parameterize client scope', async () => {
6
+ const queries: Array<{ sql: string; params: unknown[] }> = [];
7
+ const pool = {
8
+ async query(sql: string, params: unknown[] = []) {
9
+ queries.push({ sql, params });
10
+ if (sql.includes('FROM bz_agent_client_runs')) {
11
+ return [[{
12
+ client_app_id: 'example-business', runs: 4, conversations: 2,
13
+ completed: 3, failed: 1, tool_calls: 7, total_tokens: 2400,
14
+ }], []];
15
+ }
16
+ if (sql.includes('FROM bz_tool_approvals')) {
17
+ return [[
18
+ { client_app_id: 'example-business', status: 'approved', total: 2 },
19
+ { client_app_id: 'example-business', status: 'denied', total: 1 },
20
+ ], []];
21
+ }
22
+ throw new Error(`unexpected query: ${sql}`);
23
+ },
24
+ };
25
+ const repo = new AgentClientRuntimeRepository(() => pool);
26
+ const result = await repo.statsForAdmin({
27
+ since: '2026-08-20 00:00:00', clientAppId: 'example-business',
28
+ });
29
+ assert.deepEqual(result, [{
30
+ client_app_id: 'example-business', runs: 4, conversations: 2,
31
+ completed: 3, failed: 1, tool_calls: 7, total_tokens: 2400,
32
+ approvals: { approved: 2, denied: 1 },
33
+ }]);
34
+ assert.equal(queries.length, 2);
35
+ assert.deepEqual(queries[0]!.params, ['2026-08-20 00:00:00', 'example-business']);
36
+ assert.deepEqual(queries[1]!.params, ['2026-08-20 00:00:00', 'example-business']);
37
+ assert.doesNotMatch(queries[0]!.sql, /user_input|final_content|context_json/);
38
+ });
@@ -37,6 +37,17 @@ export interface ReserveAgentClientRunInput {
37
37
  user_input: string;
38
38
  }
39
39
 
40
+ export interface AgentClientAdminStats {
41
+ client_app_id: string;
42
+ runs: number;
43
+ conversations: number;
44
+ completed: number;
45
+ failed: number;
46
+ tool_calls: number;
47
+ total_tokens: number;
48
+ approvals: Record<string, number>;
49
+ }
50
+
40
51
  export class AgentClientRuntimeConflictError extends Error {
41
52
  override readonly name = 'AgentClientRuntimeConflictError';
42
53
  }
@@ -169,6 +180,49 @@ export class AgentClientRuntimeRepository {
169
180
  return rows[0] ? runRow(rows[0]) : null;
170
181
  }
171
182
 
183
+ /** Safe aggregate for the Agent Client admin center. No prompts, tool arguments, or results are returned. */
184
+ async statsForAdmin(input: { since: string; clientAppId?: string }): Promise<AgentClientAdminStats[]> {
185
+ const where = input.clientAppId ? 'created_at>=? AND client_app_id=?' : 'created_at>=?';
186
+ const params = input.clientAppId ? [input.since, input.clientAppId] : [input.since];
187
+ const [runRows] = await this.pool.query(
188
+ 'SELECT client_app_id,COUNT(*) AS runs,' +
189
+ ' COUNT(DISTINCT CONCAT_WS(\'|\',session_id,route_key,client_conversation_id)) AS conversations,' +
190
+ ' SUM(CASE WHEN status=\'completed\' THEN 1 ELSE 0 END) AS completed,' +
191
+ ' SUM(CASE WHEN status IN (\'failed\',\'cancelled\') THEN 1 ELSE 0 END) AS failed,' +
192
+ ' SUM(COALESCE(CAST(JSON_UNQUOTE(JSON_EXTRACT(usage_json,\'$.tool_calls\')) AS UNSIGNED),0)) AS tool_calls,' +
193
+ ' SUM(COALESCE(CAST(JSON_UNQUOTE(JSON_EXTRACT(usage_json,\'$.total_tokens\')) AS UNSIGNED),0)) AS total_tokens' +
194
+ ` FROM bz_agent_client_runs WHERE ${where} GROUP BY client_app_id ORDER BY client_app_id`,
195
+ params,
196
+ );
197
+ const approvalWhere = input.clientAppId
198
+ ? 'j.created_at>=? AND j.agent_session_id IS NOT NULL AND j.client_app_id=?'
199
+ : 'j.created_at>=? AND j.agent_session_id IS NOT NULL';
200
+ const [approvalRows] = await this.pool.query(
201
+ 'SELECT j.client_app_id,a.status,COUNT(*) AS total FROM bz_tool_approvals a' +
202
+ ` JOIN bz_jobs j ON j.job_id=a.job_id WHERE ${approvalWhere}` +
203
+ ' GROUP BY j.client_app_id,a.status ORDER BY j.client_app_id,a.status',
204
+ params,
205
+ );
206
+ const approvals = new Map<string, Record<string, number>>();
207
+ for (const row of approvalRows as any[]) {
208
+ const clientAppId = String(row.client_app_id);
209
+ const status = String(row.status);
210
+ const current = approvals.get(clientAppId) ?? {};
211
+ current[status] = Number(row.total ?? 0);
212
+ approvals.set(clientAppId, current);
213
+ }
214
+ return (runRows as any[]).map((row) => ({
215
+ client_app_id: String(row.client_app_id),
216
+ runs: Number(row.runs ?? 0),
217
+ conversations: Number(row.conversations ?? 0),
218
+ completed: Number(row.completed ?? 0),
219
+ failed: Number(row.failed ?? 0),
220
+ tool_calls: Number(row.tool_calls ?? 0),
221
+ total_tokens: Number(row.total_tokens ?? 0),
222
+ approvals: approvals.get(String(row.client_app_id)) ?? {},
223
+ }));
224
+ }
225
+
172
226
  async finalizeTurn(input: {
173
227
  run_id: string;
174
228
  session_id: string;
@@ -0,0 +1,120 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import type { IncomingMessage, ServerResponse } from 'node:http';
4
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
5
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
6
+ import { handleAdminAgentClientsApiFor } from './admin-agent-clients';
7
+
8
+ class FakeResponse {
9
+ statusCode = 0;
10
+ body = Buffer.alloc(0);
11
+ headers: Record<string, string | number | string[]> = {};
12
+ setHeader(name: string, value: string | number | string[]): void { this.headers[name.toLowerCase()] = value; }
13
+ writeHead(code: number, headers?: Record<string, string | number | string[]>): void {
14
+ this.statusCode = code;
15
+ Object.assign(this.headers, headers ?? {});
16
+ }
17
+ end(value?: string | Buffer): void { this.body = value ? Buffer.from(value) : Buffer.alloc(0); }
18
+ json(): any { return JSON.parse(this.body.toString('utf8')); }
19
+ }
20
+
21
+ const SESSION_ID = '123e4567-e89b-42d3-a456-426614174000';
22
+
23
+ function fakeDeps() {
24
+ let revoked = false;
25
+ const audits: any[] = [];
26
+ const session = {
27
+ session_id: SESSION_ID,
28
+ client_app_id: 'example-business',
29
+ device_label: 'Development workstation',
30
+ principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
31
+ on_behalf_of: 'tenant-2:user-7',
32
+ allowed_routes: ['orders'],
33
+ created_at: '2026-08-27T00:00:00.000Z',
34
+ access_expires_at: '2026-08-27T01:00:00.000Z',
35
+ refresh_expires_at: '2026-09-27T00:00:00.000Z',
36
+ last_seen_at: '2026-08-27T00:10:00.000Z',
37
+ state: 'active' as const,
38
+ };
39
+ const configStore = {
40
+ clients: {
41
+ list: async () => [{
42
+ app_id: 'example-business', name: 'Example business', token: 'PRIVATE_CLIENT_TOKEN', enabled: true,
43
+ allowed_routes: ['orders'], allowed_channels: [], rate_limit_per_min: 60,
44
+ agent_authorize_url: 'https://business.example.com/agent-authorize',
45
+ }],
46
+ },
47
+ routes: {
48
+ list: async () => [
49
+ { route_key: 'orders', name: 'Order assistant', enabled: true, tools: {}, agent_client: { enabled: true } },
50
+ { route_key: 'legacy', name: 'Legacy route', enabled: true, tools: {} },
51
+ ],
52
+ },
53
+ agentAuth: {
54
+ sessionSummaryForAdmin: async () => ({ total: 1, active: 1, expired: 0, revoked: 0 }),
55
+ listSessionsForAdmin: async () => ({ list: [session], total: 1 }),
56
+ getSessionForAdmin: async (id: string) => id === SESSION_ID ? session : null,
57
+ revokeSessionForClient: async () => { revoked = true; return true; },
58
+ },
59
+ agentClientRuntime: {
60
+ statsForAdmin: async () => [{
61
+ client_app_id: 'example-business', runs: 3, conversations: 2, completed: 2, failed: 1,
62
+ tool_calls: 5, total_tokens: 1200, approvals: { approved: 1 },
63
+ }],
64
+ },
65
+ } as unknown as ConfigStoreContract;
66
+ const stateStore = {
67
+ appendAudit: async (entry: any) => { audits.push(entry); },
68
+ } as unknown as RuntimeStateStore;
69
+ return {
70
+ deps: { configStore, stateStore, now: () => '2026-08-27T00:30:00.000Z' },
71
+ audits,
72
+ wasRevoked: () => revoked,
73
+ };
74
+ }
75
+
76
+ test('智能体客户端 overview 聚合既有资源且不暴露接入方 token', async () => {
77
+ const fx = fakeDeps();
78
+ const res = new FakeResponse();
79
+ const req = { url: '/admin/api/agent-clients/overview?days=7' } as IncomingMessage;
80
+ const handled = await handleAdminAgentClientsApiFor(
81
+ fx.deps,
82
+ 'GET',
83
+ '/admin/api/agent-clients/overview',
84
+ req,
85
+ res as unknown as ServerResponse,
86
+ { kind: 'admin', via: 'session', username: 'admin', role: 'admin' },
87
+ );
88
+ assert.equal(handled, true);
89
+ assert.equal(res.statusCode, 200);
90
+ const payload = res.json();
91
+ assert.equal(payload.days, 7);
92
+ assert.equal(payload.applications[0].stats.runs, 3);
93
+ assert.deepEqual(payload.workspaces.map((item: any) => item.route), ['orders']);
94
+ assert.equal(payload.summary.sessions.active, 1);
95
+ assert.equal(payload.summary.failure_rate, 1 / 3);
96
+ assert.equal(JSON.stringify(payload).includes('PRIVATE_CLIENT_TOKEN'), false);
97
+ assert.equal(Object.hasOwn(payload.applications[0], 'token'), false);
98
+ });
99
+
100
+ test('管理员撤销 Agent Session 幂等调用受 Client 归属约束并写审计', async () => {
101
+ const fx = fakeDeps();
102
+ const res = new FakeResponse();
103
+ await handleAdminAgentClientsApiFor(
104
+ fx.deps,
105
+ 'POST',
106
+ `/admin/api/agent-clients/sessions/${SESSION_ID}/revoke`,
107
+ { url: `/admin/api/agent-clients/sessions/${SESSION_ID}/revoke` } as IncomingMessage,
108
+ res as unknown as ServerResponse,
109
+ { kind: 'admin', via: 'session', username: 'operator', role: 'admin' },
110
+ );
111
+ assert.equal(res.statusCode, 200);
112
+ assert.equal(fx.wasRevoked(), true);
113
+ assert.equal(fx.audits.length, 1);
114
+ assert.equal(fx.audits[0].event, 'agent_session_admin_revoked');
115
+ assert.deepEqual(fx.audits[0].detail, {
116
+ session_id: SESSION_ID,
117
+ client_app_id: 'example-business',
118
+ by: 'operator',
119
+ });
120
+ });