bailinghub 0.6.1 → 0.7.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.
Files changed (145) hide show
  1. package/README.en.md +9 -5
  2. package/README.md +8 -5
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.md +4 -1
  9. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  10. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  11. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  12. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  13. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  14. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  15. package/docs/CHANGELOG.en.md +14 -1
  16. package/docs/CHANGELOG.md +14 -1
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  20. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  21. package/docs/README.en.md +6 -0
  22. package/docs/README.md +6 -0
  23. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  24. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  25. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  26. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  27. package/docs/SDK.en.md +31 -0
  28. package/docs/user-guide/conversations.en.md +4 -2
  29. package/docs/user-guide/conversations.md +4 -2
  30. package/package.json +1 -1
  31. package/schemas/config/route.schema.json +15 -2
  32. package/scripts/check-doc-links.mjs +1 -0
  33. package/scripts/check-image-tags.sh +1 -1
  34. package/scripts/check-release-consistency.test.mjs +2 -2
  35. package/scripts/install.sh +1 -1
  36. package/scripts/publish-images.sh +1 -1
  37. package/scripts/release-audit.mjs +1 -0
  38. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  39. package/scripts/sdk-runtime-test.mjs +5 -2
  40. package/scripts/verify-github-repo.mjs +1 -0
  41. package/sdk/php/README.md +29 -0
  42. package/sdk/php/src/AgentAuth.php +100 -4
  43. package/sdk/php/src/HubClient.php +2 -1
  44. package/sdk/php7/README.md +31 -0
  45. package/sdk/php7/src/AgentAuth.php +99 -4
  46. package/sdk/php7/src/HubClient.php +2 -1
  47. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  48. package/sql/059_agent_subject_display.sql +5 -0
  49. package/sql/README.en.md +15 -0
  50. package/sql/README.md +25 -0
  51. package/src/app/agent-conversation-audit.ts +20 -0
  52. package/src/app/agent-system-info.ts +41 -0
  53. package/src/app/agent-tool-invocations.ts +16 -4
  54. package/src/core/config/agent-setup.ts +37 -0
  55. package/src/core/config/client-agent-setup.ts +25 -0
  56. package/src/core/config/config-schema.test.ts +11 -0
  57. package/src/core/config/route-config.test.ts +28 -0
  58. package/src/core/config/route-config.ts +43 -4
  59. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  60. package/src/core/contracts/agent-subject-display.ts +36 -0
  61. package/src/core/contracts/types.ts +15 -0
  62. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  63. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  64. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  65. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  66. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  67. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  68. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  69. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  70. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  71. package/src/infrastructure/config/config-client-repository.ts +21 -0
  72. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  73. package/src/infrastructure/config/config-route-repository.ts +24 -0
  74. package/src/infrastructure/config/configstore.ts +7 -3
  75. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  76. package/src/routes/admin-access.ts +37 -0
  77. package/src/routes/admin-agent-clients.ts +11 -0
  78. package/src/routes/admin-agent-setup.test.ts +130 -0
  79. package/src/routes/admin-agent-setup.ts +68 -0
  80. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  81. package/src/routes/admin-dispatch-config.ts +2 -0
  82. package/src/routes/agent-api.ts +7 -0
  83. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  84. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  85. package/src/routes/agent-auth.test.ts +1 -1
  86. package/src/routes/agent-auth.ts +206 -16
  87. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  88. package/src/routes/agent-conversation-audit.ts +8 -2
  89. package/src/routes/agent-subject-display-http.test.ts +145 -0
  90. package/src/routes/agent-system-info.test.ts +132 -0
  91. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  92. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  93. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  94. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  95. package/web/connect/bailing-connect-php.tgz +0 -0
  96. package/web/connect/bailing-connect-php7.tgz +0 -0
  97. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-ChL9k-XA.js} +1 -1
  98. package/web/console/assets/AgentClients-Bs7UgVDj.js +1 -0
  99. package/web/console/assets/AgentClients-DkgPTEbq.css +1 -0
  100. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-Bs6FGbp2.js} +1 -1
  101. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-4WWYhkFM.js} +1 -1
  102. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-D2GhCipL.js} +1 -1
  103. package/web/console/assets/{Channels-CApxH2TB.js → Channels-CmoGpiCJ.js} +1 -1
  104. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-BFRMtwta.js} +1 -1
  105. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  106. package/web/console/assets/Clients-DGkkSXyA.js +3 -0
  107. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-BmGt0MfS.js} +1 -1
  108. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-CR-sYINT.js} +1 -1
  109. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-DAPbKSJp.js} +1 -1
  110. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CgpiT3o8.js} +1 -1
  111. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-Cm9dVSQw.js} +1 -1
  112. package/web/console/assets/{Login-DiTjPWmN.js → Login-CyUcsTZ_.js} +1 -1
  113. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-DldFPgWg.js} +1 -1
  114. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  115. package/web/console/assets/Routes-DubfjlBD.js +124 -0
  116. package/web/console/assets/Runs-1hxgkuR4.js +3 -0
  117. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  118. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-DBLOnI2_.js} +1 -1
  119. package/web/console/assets/{Shell-BEqpONiy.js → Shell-gJ5Vz_E7.js} +1 -1
  120. package/web/console/assets/{StorageBuckets-CkORbYXY.js → StorageBuckets-DkDW16tj.js} +1 -1
  121. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-cDkudo2y.js} +1 -1
  122. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-DZd6s8OX.js} +1 -1
  123. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-DYNGq1NU.js} +1 -1
  124. package/web/console/assets/{Tools-CIHInlHL.js → Tools-DpWM59vV.js} +1 -1
  125. package/web/console/assets/{index-BkLbd7Cc.js → index-DGqs28gI.js} +2 -2
  126. package/web/console/assets/{request-r7GHVJzw.js → request-B7MLvOqo.js} +1 -1
  127. package/web/console/assets/{schema-BVn_hB7M.js → schema-CMuwjYdJ.js} +1 -1
  128. package/web/console/index.html +1 -1
  129. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  130. package/web-admin/src/components/AgentSetupPanel.vue +262 -0
  131. package/web-admin/src/components/ClientConversations.vue +21 -4
  132. package/web-admin/src/components/conversation-audit.ts +20 -0
  133. package/web-admin/src/pages/AgentClients.vue +97 -23
  134. package/web-admin/src/pages/Clients.vue +4 -1
  135. package/web-admin/src/pages/Routes.vue +10 -1
  136. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  137. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  138. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  139. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  140. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  141. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  142. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  143. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  144. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  145. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
@@ -199,6 +199,96 @@ test('Core Schema Migrator: 同名列结构冲突时不容忍、不记账', asyn
199
199
  assert.equal(connection.ledger.has('003_executor.sql'), false);
200
200
  });
201
201
 
202
+ test('Core Schema Migrator: 058 upgrades a 057 ledger additively and is idempotent for private Hosts', async () => {
203
+ const connection = new FakeMigrationConnection();
204
+ seedLedgerWithCurrentChecksums(connection);
205
+ connection.ledger.delete('058_agent_conversation_member_bindings.sql');
206
+ const original057 = connection.ledger.get('057_agent_conversation_audit.sql');
207
+ const result = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
208
+ assert.deepEqual(result.appliedFiles, ['058_agent_conversation_member_bindings.sql']);
209
+ assert.equal(connection.migrationStatements.length, 4);
210
+ for (const sql of connection.migrationStatements) {
211
+ assert.match(sql, /^ALTER TABLE `bz_agent_conversation_(audits|members)` ADD COLUMN /);
212
+ assert.match(sql, / DEFAULT /);
213
+ assert.doesNotMatch(sql, /\b(?:UPDATE|DELETE|DROP|MODIFY|RENAME)\b/i);
214
+ }
215
+ assert.equal(connection.ledger.get('057_agent_conversation_audit.sql'), original057);
216
+ const rerun = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
217
+ assert.deepEqual(rerun.appliedFiles, []);
218
+ assert.equal(connection.migrationStatements.length, 4);
219
+ assert.equal(connection.ends, 0, 'the private Host retains ownership of its injected connection');
220
+ });
221
+
222
+ test('Core Schema Migrator: a partial 058 replay verifies actual column definitions before recording success', async () => {
223
+ const migration = '058_agent_conversation_member_bindings.sql';
224
+ for (const conflicting of [false, true]) {
225
+ const connection = new FakeMigrationConnection();
226
+ seedLedgerWithCurrentChecksums(connection);
227
+ connection.ledger.delete(migration);
228
+ connection.statementFaults = [
229
+ { pattern: /ADD COLUMN `membership_version`/, errno: 1060 },
230
+ { pattern: /ADD COLUMN `client_app_id`/, errno: 1060 },
231
+ ];
232
+ connection.fullColumns.set('bz_agent_conversation_audits', [
233
+ { Field: 'membership_version', Type: 'tinyint unsigned', Null: 'NO', Default: '1' },
234
+ ]);
235
+ connection.fullColumns.set('bz_agent_conversation_members', [
236
+ { Field: 'client_app_id', Type: conflicting ? 'varchar(32)' : 'varchar(64)', Null: 'YES', Default: null },
237
+ ]);
238
+ if (conflicting) {
239
+ await assert.rejects(migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection }), /058_agent_conversation_member_bindings\.sql 执行失败/);
240
+ assert.equal(connection.ledger.has(migration), false);
241
+ } else {
242
+ const result = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
243
+ assert.deepEqual(result.appliedFiles, [migration]);
244
+ assert.equal(result.toleratedStatements, 2);
245
+ }
246
+ }
247
+ });
248
+
249
+ test('Core Schema Migrator: 059 adds only nullable display columns, preserves the ledger and skips replay', async () => {
250
+ const connection = new FakeMigrationConnection();
251
+ seedLedgerWithCurrentChecksums(connection);
252
+ const migration = '059_agent_subject_display.sql';
253
+ connection.ledger.delete(migration);
254
+ const prior = new Map(connection.ledger);
255
+ const result = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
256
+ assert.deepEqual(result.appliedFiles, [migration]);
257
+ assert.equal(connection.migrationStatements.length, 2);
258
+ for (const sql of connection.migrationStatements) {
259
+ assert.match(sql, /^ALTER TABLE `bz_agent_(authorizations|sessions)` ADD COLUMN `subject_display` JSON DEFAULT NULL/);
260
+ assert.doesNotMatch(sql, /\b(?:UPDATE|DELETE|DROP|MODIFY|RENAME)\b/i);
261
+ }
262
+ for (const [name, checksum] of prior) assert.equal(connection.ledger.get(name), checksum);
263
+ const rerun = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
264
+ assert.deepEqual(rerun.appliedFiles, []);
265
+ assert.equal(connection.migrationStatements.length, 2);
266
+ });
267
+
268
+ test('Core Schema Migrator: partial 059 replay verifies JSON type, nullability and default', async () => {
269
+ const migration = '059_agent_subject_display.sql';
270
+ for (const shape of [
271
+ { Type: 'json', Null: 'YES', Default: null },
272
+ { Type: 'text', Null: 'YES', Default: null },
273
+ { Type: 'json', Null: 'NO', Default: null },
274
+ { Type: 'json', Null: 'YES', Default: '{}' },
275
+ ]) {
276
+ const connection = new FakeMigrationConnection();
277
+ seedLedgerWithCurrentChecksums(connection);
278
+ connection.ledger.delete(migration);
279
+ connection.statementFaults = [{ pattern: /ADD COLUMN `subject_display`/, errno: 1060 }];
280
+ connection.fullColumns.set('bz_agent_authorizations', [{ Field: 'subject_display', ...shape }]);
281
+ if (shape.Type === 'json' && shape.Null === 'YES' && shape.Default === null) {
282
+ const result = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
283
+ assert.deepEqual(result.appliedFiles, [migration]);
284
+ assert.equal(result.toleratedStatements, 1);
285
+ } else {
286
+ await assert.rejects(migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection }), /059_agent_subject_display\.sql 执行失败/);
287
+ assert.equal(connection.ledger.has(migration), false);
288
+ }
289
+ }
290
+ });
291
+
202
292
  test('Core Schema Migrator: 兼容文件名旧账本,补录摘要但绝不重放已记账 SQL', async () => {
203
293
  const connection = new FakeMigrationConnection();
204
294
  const official = officialMigrations();
@@ -7,6 +7,7 @@ import type { Client, ExecutorToken } from '../core/contracts/types';
7
7
  import type { RuntimeStateStore } from '../core/state/state-contracts';
8
8
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
9
  import { maskKey } from './admin-format';
10
+ import { clientAgentSetupView } from '../core/config/client-agent-setup';
10
11
 
11
12
  export interface AdminAccessApiDeps {
12
13
  configStore: ConfigStoreContract | null;
@@ -57,6 +58,42 @@ export async function handleAdminAccessApiFor(
57
58
  return true;
58
59
  }
59
60
 
61
+ const setupMatch = path.match(/^\/admin\/api\/clients\/([a-z0-9][a-z0-9_-]{1,63})\/agent-setup$/);
62
+ if (setupMatch && (method === 'GET' || method === 'PUT')) {
63
+ if (!can(principal, method === 'GET' ? 'clients:read' : 'clients:write')) {
64
+ send(res, 403, { error: 'forbidden' }); return true;
65
+ }
66
+ const current = await configStore.clients.get(setupMatch[1]!);
67
+ if (!current) { send(res, 404, { error: 'client_not_found' }); return true; }
68
+ if (method === 'GET') { send(res, 200, clientAgentSetupView(current)); return true; }
69
+ if (!configStore.clients.updateAgentSetup) { send(res, 503, { error: 'agent_setup_unsupported' }); return true; }
70
+ let raw: unknown;
71
+ try { raw = await readBody(req, 32 * 1024); }
72
+ catch { send(res, 400, { error: 'invalid_agent_setup' }); return true; }
73
+ const body = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : null;
74
+ if (!body || Object.keys(body).length !== 4 || Object.keys(body).some((key) => !['expected_revision', 'enabled', 'agent_authorize_url', 'allowed_routes'].includes(key))
75
+ || typeof body['expected_revision'] !== 'string' || !/^[a-f0-9]{64}$/.test(body['expected_revision'])
76
+ || typeof body['enabled'] !== 'boolean'
77
+ || !(body['agent_authorize_url'] === null || typeof body['agent_authorize_url'] === 'string')
78
+ || !Array.isArray(body['allowed_routes']) || body['allowed_routes'].length > 256
79
+ || !body['allowed_routes'].every((value) => typeof value === 'string' && /^(?:\*|[a-z0-9][a-z0-9_-]{1,63})$/.test(value))) {
80
+ send(res, 400, { error: 'invalid_agent_setup' }); return true;
81
+ }
82
+ const prepared = prepareClientConfig({ ...current,
83
+ enabled: body['enabled'], agent_authorize_url: body['agent_authorize_url'] as string | undefined,
84
+ allowed_routes: body['allowed_routes'] as string[],
85
+ });
86
+ if (!prepared.ok) { send(res, 400, { error: prepared.error }); return true; }
87
+ const result = await configStore.clients.updateAgentSetup(current.app_id, body['expected_revision'], {
88
+ enabled: prepared.value.enabled, agent_authorize_url: prepared.value.agent_authorize_url || null,
89
+ allowed_routes: prepared.value.allowed_routes,
90
+ });
91
+ if (result !== 'updated') { send(res, result === 'conflict' ? 409 : 404, { error: result === 'conflict' ? 'agent_setup_conflict' : 'client_not_found' }); return true; }
92
+ const saved = await configStore.clients.get(current.app_id);
93
+ if (!saved) { send(res, 404, { error: 'client_not_found' }); return true; }
94
+ send(res, 200, clientAgentSetupView(saved)); return true;
95
+ }
96
+
60
97
  if (path === '/admin/api/clients') {
61
98
  // token 即调用方凭证,与工具源 secret / 凭证 api_key 同等对待:列表只给掩码,完整值走显式 reveal(见下)
62
99
  if (method === 'GET') {
@@ -108,6 +108,17 @@ export async function handleAdminAgentClientsApiFor(
108
108
  name: route.name,
109
109
  description: route.description ?? '',
110
110
  })),
111
+ setup_workspaces: routes.map((route) => {
112
+ const direct = route.tools?.['agent_direct'] as Record<string, unknown> | undefined;
113
+ return {
114
+ route: route.route_key, name: route.name, enabled: route.enabled,
115
+ runtime_enabled: Boolean(routeAgentClientConfig(route)),
116
+ direct_enabled: direct?.['enabled'] === true,
117
+ system_info_configured: Boolean(route.agent_client?.system_info),
118
+ source_count: Array.isArray(route.tools?.sources) ? route.tools.sources.length : 0,
119
+ write_tool_count: Array.isArray(direct?.['write_tools']) ? direct['write_tools'].length : 0,
120
+ permission: route.permission || null,
121
+ }; }),
111
122
  summary: {
112
123
  applications: applications.length,
113
124
  agent_auth_enabled: applications.filter((item) => item.agent_auth_enabled).length,
@@ -0,0 +1,130 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { Readable } from 'node:stream';
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { Route } from '../core/contracts/types';
6
+ import { agentSetupRevision } from '../core/config/agent-setup';
7
+ import type { AgentSetupUpdate } from '../core/config/agent-setup';
8
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
+ import { TargetRegistry } from '../core/targets/registry';
10
+ import { handleAdminAgentSetupFor } from './admin-agent-setup';
11
+ import { handleAdminApiFor, type AdminApiDeps } from './admin';
12
+
13
+ class Response {
14
+ statusCode = 0;
15
+ body = '';
16
+ writeHead(code: number) { this.statusCode = code; }
17
+ setHeader() {}
18
+ end(value = '') { this.body = String(value); }
19
+ json() { return JSON.parse(this.body); }
20
+ }
21
+
22
+ function request(body?: unknown): IncomingMessage {
23
+ const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]) as unknown as IncomingMessage;
24
+ req.headers = {};
25
+ return req;
26
+ }
27
+
28
+ function fixture() {
29
+ let route: Route = {
30
+ route_key: 'helpdesk', name: 'Helpdesk', enabled: true, target: 'notify', target_config: { private_setting: 'do-not-return' },
31
+ profile: 'general', permission: 'readonly', session_policy: 'fixed', session_fixed_id: 'preserve-session',
32
+ memory: { recent_messages: 10 }, budget: { hard_tokens: 1000 }, audience: { roles: ['staff'] },
33
+ tools: { sources: [{ provider: 'helpdesk', allow: ['ticket.read'], subject_field: 'operator_id' }],
34
+ max_calls: 4, approval: { type: 'manual' }, custom_extension: { preserve: true }, agent_direct: { enabled: false } },
35
+ agent_client: { enabled: false, instructions: 'Keep existing instructions.', active_tool_limit: 3 },
36
+ };
37
+ let writes = 0;
38
+ let race = false;
39
+ const routes = {
40
+ get: async () => route,
41
+ compareAndSetAgentSetup: async (_key: string, revision: string, update: AgentSetupUpdate) => {
42
+ if (race) route = { ...route, description: 'concurrent change' };
43
+ if (revision !== agentSetupRevision(route)) return { status: 'conflict' as const };
44
+ route = { ...route, ...update }; writes++;
45
+ return { status: 'updated' as const, route };
46
+ },
47
+ upsert: async () => { throw new Error('Full route upsert is forbidden'); },
48
+ };
49
+ const targetRegistry = new TargetRegistry();
50
+ targetRegistry.setTargets([{ name: 'notify', kind: 'inhub', stateless: true, needs_project: false, timeout_ms: 1000, enabled: true }]);
51
+ const deps = { configStore: { routes, toolProviders: { get: async (name: string) => name === 'helpdesk' ? {} : null } } as unknown as ConfigStoreContract,
52
+ defaultProfile: 'general', refreshTargets: async () => {}, targetRegistry };
53
+ const body = () => ({ expected_revision: agentSetupRevision(route), agent_client: {
54
+ ...route.agent_client, enabled: true, system_info: { name: 'Helpdesk', summary: 'Support ticket operations.', domains: [], boundaries: [] },
55
+ }, tool_sources: route.tools!.sources, agent_direct: { enabled: true, write_tools: ['ticket_update'] } });
56
+ async function call(method = 'GET', payload?: unknown) {
57
+ const res = new Response();
58
+ await handleAdminAgentSetupFor(deps, method, '/admin/api/routes/helpdesk/agent-setup', request(payload), res as unknown as ServerResponse);
59
+ return res;
60
+ }
61
+ return { deps, routes, body, call, route: () => route, writes: () => writes, race: () => { race = true; } };
62
+ }
63
+
64
+ test('route Agent setup exposes only its editing surface and preserves all other configuration', async () => {
65
+ const f = fixture();
66
+ const before = structuredClone(f.route());
67
+ const read = await f.call();
68
+ assert.equal(read.statusCode, 200);
69
+ assert.deepEqual(Object.keys(read.json()).sort(), ['agent_client', 'agent_direct', 'enabled', 'name', 'permission', 'revision', 'route_key', 'tool_sources']);
70
+ assert.equal(read.json().permission, 'readonly');
71
+ assert.doesNotMatch(read.body, /do-not-return|preserve-session|custom_extension|hard_tokens/);
72
+ const saved = await f.call('PUT', f.body());
73
+ assert.equal(saved.statusCode, 200, saved.body);
74
+ assert.equal(f.writes(), 1);
75
+ const after = f.route();
76
+ assert.deepEqual({ ...after, agent_client: before.agent_client, tools: before.tools }, before);
77
+ assert.deepEqual({ ...after.tools, sources: before.tools!.sources, agent_direct: before.tools!.agent_direct }, before.tools);
78
+ assert.equal(after.agent_client!.instructions, before.agent_client!.instructions);
79
+ assert.notEqual(saved.json().revision, read.json().revision);
80
+ });
81
+
82
+ test('route Agent setup rejects stale/concurrent writes, undeclared fields and unsafe direct tools', async () => {
83
+ for (const kind of ['stale', 'race', 'extra', 'nested', 'wildcard', 'unknown-provider'] as const) {
84
+ const f = fixture();
85
+ const payload: any = f.body();
86
+ if (kind === 'stale') payload.expected_revision = '0'.repeat(64);
87
+ if (kind === 'race') f.race();
88
+ if (kind === 'extra') payload.target_config = {};
89
+ if (kind === 'nested') payload.agent_client.unrecognized = true;
90
+ if (kind === 'wildcard') payload.agent_direct.write_tools = ['*'];
91
+ if (kind === 'unknown-provider') payload.tool_sources = [{ provider: 'unknown', allow: ['*'] }];
92
+ const res = await f.call('PUT', payload);
93
+ assert.equal(res.statusCode, kind === 'stale' || kind === 'race' ? 409 : 400, kind);
94
+ assert.equal(f.writes(), 0);
95
+ }
96
+ });
97
+
98
+ test('route Agent setup supports deliberate clearing and reports old Host save support explicitly', async () => {
99
+ const f = fixture();
100
+ const res = await f.call('PUT', { expected_revision: agentSetupRevision(f.route()), agent_client: null, tool_sources: [], agent_direct: null });
101
+ assert.equal(res.statusCode, 200);
102
+ assert.equal(res.json().agent_client, null);
103
+ assert.equal(res.json().agent_direct, null);
104
+ assert.deepEqual(res.json().tool_sources, []);
105
+ assert.equal(f.route().tools!.max_calls, 4);
106
+ delete (f.routes as Partial<typeof f.routes>).compareAndSetAgentSetup;
107
+ const unsupported = await f.call('PUT', f.body());
108
+ assert.equal(unsupported.statusCode, 503);
109
+ assert.equal(unsupported.json().error, 'agent_setup_unsupported');
110
+ });
111
+
112
+ test('route Agent setup remains behind routes permissions rather than clients permissions', async () => {
113
+ const f = fixture();
114
+ const deps = { ...f.deps, cfg: { defaultProfile: 'general' } } as unknown as AdminApiDeps;
115
+ for (const permissions of [['clients:write'], ['routes:read']]) {
116
+ const response = new Response();
117
+ await handleAdminApiFor(deps, 'PUT', '/admin/api/routes/helpdesk/agent-setup', request(f.body()), response as unknown as ServerResponse,
118
+ { kind: 'admin', via: 'session', permissions });
119
+ assert.equal(response.statusCode, 403);
120
+ }
121
+ assert.equal(f.writes(), 0);
122
+ const read = new Response();
123
+ await handleAdminApiFor(deps, 'GET', '/admin/api/routes/helpdesk/agent-setup', request(), read as unknown as ServerResponse,
124
+ { kind: 'admin', via: 'session', permissions: ['routes:read'] });
125
+ assert.equal(read.statusCode, 200);
126
+ const write = new Response();
127
+ await handleAdminApiFor(deps, 'PUT', '/admin/api/routes/helpdesk/agent-setup', request(f.body()), write as unknown as ServerResponse,
128
+ { kind: 'admin', via: 'session', permissions: ['routes:write'] });
129
+ assert.equal(write.statusCode, 200);
130
+ });
@@ -0,0 +1,68 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { readBody, send } from '../app/http';
3
+ import { agentSetupRevision, agentSetupView } from '../core/config/agent-setup';
4
+ import { prepareRouteConfig } from '../core/config/route-config';
5
+ import type { Route } from '../core/contracts/types';
6
+ import { defaultTargetRegistry } from '../core/targets/registry';
7
+ import type { AdminDispatchConfigApiDeps } from './admin-dispatch-config';
8
+
9
+ function record(value: unknown): Record<string, unknown> | null {
10
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
11
+ }
12
+
13
+ /** Called only after the parent admin routes:read/routes:write gate. */
14
+ export async function handleAdminAgentSetupFor(
15
+ deps: AdminDispatchConfigApiDeps,
16
+ method: string,
17
+ path: string,
18
+ req: IncomingMessage,
19
+ res: ServerResponse,
20
+ ): Promise<boolean> {
21
+ const match = path.match(/^\/admin\/api\/routes\/([^/]+)\/agent-setup$/);
22
+ if (!match || !deps.configStore) return false;
23
+ const store = deps.configStore;
24
+ let key: string;
25
+ try { key = decodeURIComponent(match[1]!); }
26
+ catch { send(res, 400, { error: 'invalid_request' }); return true; }
27
+ if (!/^[a-z0-9][a-z0-9_.:-]{0,127}$/i.test(key)) { send(res, 400, { error: 'invalid_request' }); return true; }
28
+ if (method !== 'GET' && method !== 'PUT') { send(res, 405, { error: 'method_not_allowed' }); return true; }
29
+ const current = await store.routes.get(key);
30
+ if (!current) { send(res, 404, { error: 'route_not_found' }); return true; }
31
+ if (method === 'GET') { send(res, 200, agentSetupView(current)); return true; }
32
+ if (typeof store.routes.compareAndSetAgentSetup !== 'function') {
33
+ send(res, 503, { error: 'agent_setup_unsupported' }); return true;
34
+ }
35
+ let body: Record<string, unknown> | null;
36
+ try { body = record(await readBody(req, 256 * 1024)); }
37
+ catch { send(res, 400, { error: 'invalid_request' }); return true; }
38
+ const fields = ['expected_revision', 'agent_client', 'tool_sources', 'agent_direct'];
39
+ if (!body || Object.keys(body).length !== fields.length || Object.keys(body).some((name) => !fields.includes(name))
40
+ || typeof body.expected_revision !== 'string' || !/^[a-f0-9]{64}$/.test(body.expected_revision)
41
+ || (body.agent_client !== null && !record(body.agent_client)) || !Array.isArray(body.tool_sources)
42
+ || (body.agent_direct !== null && !record(body.agent_direct))) {
43
+ send(res, 400, { error: 'invalid_request' }); return true;
44
+ }
45
+ if (agentSetupRevision(current) !== body.expected_revision) { send(res, 409, { error: 'agent_setup_conflict' }); return true; }
46
+ const tools = { ...current.tools };
47
+ if (body.tool_sources.length) tools.sources = body.tool_sources;
48
+ else delete tools.sources;
49
+ if (body.agent_direct !== null) tools.agent_direct = body.agent_direct;
50
+ else delete tools.agent_direct;
51
+ const registry = deps.targetRegistry ?? defaultTargetRegistry;
52
+ const prepared = await prepareRouteConfig({
53
+ ...current,
54
+ agent_client: (body.agent_client ?? undefined) as Route['agent_client'],
55
+ tools,
56
+ }, {
57
+ targetExists: (name) => registry.isKnown(name), targetNeedsProject: (name) => registry.needsProject(name),
58
+ toolProviderExists: async (name) => !!(await store.toolProviders.get(name)),
59
+ }, { defaultProfile: deps.defaultProfile });
60
+ if (!prepared.ok) { send(res, 400, { error: prepared.error }); return true; }
61
+ const result = await store.routes.compareAndSetAgentSetup(key, body.expected_revision, {
62
+ agent_client: prepared.route.agent_client, tools: prepared.route.tools,
63
+ });
64
+ if (result.status === 'conflict') { send(res, 409, { error: 'agent_setup_conflict' }); return true; }
65
+ if (result.status === 'not_found') { send(res, 404, { error: 'route_not_found' }); return true; }
66
+ send(res, 200, agentSetupView(result.route));
67
+ return true;
68
+ }
@@ -0,0 +1,93 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { Readable } from 'node:stream';
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { Principal } from '../app/auth';
6
+ import { handleAdminAccessApiFor } from './admin-access';
7
+ import { ClientRepository } from '../infrastructure/config/config-client-repository';
8
+ import { clientAgentSetupRevision } from '../core/config/client-agent-setup';
9
+ import { rowClient } from '../core/config/config-codec';
10
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
11
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
12
+
13
+ class Response {
14
+ statusCode = 0; body = '';
15
+ writeHead(value: number) { this.statusCode = value; }
16
+ setHeader() {}
17
+ end(value = '') { this.body = String(value); }
18
+ json() { return JSON.parse(this.body); }
19
+ }
20
+ const admin: Principal = { kind: 'admin', via: 'session', username: 'maintainer', role: 'admin' };
21
+ function fixture() {
22
+ const row: Record<string, any> = { app_id: 'helpdesk', name: 'Helpdesk', enabled: 1, token: 'synthetic-preserved-token', agent_authorize_url: 'https://example.test/authorize',
23
+ allowed_routes: '["helpdesk"]', allowed_channels: '["alerts"]', rate_limit_per_min: 37, budget: '{"hard_tokens":1200}', description: 'private administrator note' };
24
+ const sql: string[] = []; let rollbacks = 0; let commits = 0; let released = 0;
25
+ const connection = {
26
+ beginTransaction: async () => {}, rollback: async () => { rollbacks++; }, commit: async () => { commits++; }, release: () => { released++; },
27
+ query: async (query: string, params: any[]) => {
28
+ sql.push(query);
29
+ if (query.startsWith('SELECT')) return [[{ ...row }]];
30
+ assert.match(query, /^UPDATE bz_clients SET enabled=\?,agent_authorize_url=\?,allowed_routes=\?,updated_at=\? WHERE app_id=\?$/);
31
+ Object.assign(row, { enabled: params[0], agent_authorize_url: params[1], allowed_routes: params[2], updated_at: params[3] });
32
+ return [{ affectedRows: 1 }];
33
+ },
34
+ };
35
+ const pool = { getConnection: async () => connection, query: async () => [[{ ...row }]] };
36
+ const clients = new ClientRepository(() => pool);
37
+ const deps = { configStore: { clients } as unknown as ConfigStoreContract, stateStore: {} as RuntimeStateStore, now: () => '2026-01-01T00:00:00Z' };
38
+ const body = () => ({ expected_revision: clientAgentSetupRevision(rowClient(row)), enabled: false, agent_authorize_url: 'https://example.test/new-authorize', allowed_routes: ['helpdesk', 'inventory'] });
39
+ async function call(method = 'GET', value?: unknown, principal = admin) {
40
+ const req = Readable.from(value === undefined ? [] : [Buffer.from(JSON.stringify(value))]) as unknown as IncomingMessage;
41
+ req.headers = {}; const res = new Response();
42
+ await handleAdminAccessApiFor(deps, method, '/admin/api/clients/helpdesk/agent-setup', req, res as unknown as ServerResponse, principal);
43
+ return res;
44
+ }
45
+ return { row, sql, clients, body, call, counts: () => ({ rollbacks, commits, released }) };
46
+ }
47
+
48
+ test('client setup GET and PUT never expose credentials; narrow SQL preserves unrelated configuration', async () => {
49
+ const f = fixture(); const before = structuredClone(f.row);
50
+ const read = await f.call(); assert.equal(read.statusCode, 200);
51
+ assert.deepEqual(Object.keys(read.json()).sort(), ['agent_authorize_url', 'allowed_routes', 'app_id', 'enabled', 'name', 'revision']);
52
+ const saved = await f.call('PUT', f.body()); assert.equal(saved.statusCode, 200, saved.body);
53
+ for (const output of [read.body, saved.body]) assert.doesNotMatch(output, /synthetic-preserved-token|private administrator note|hard_tokens/);
54
+ for (const key of ['token', 'allowed_channels', 'rate_limit_per_min', 'budget', 'description', 'name']) assert.equal(f.row[key], before[key]);
55
+ assert.equal(f.row.enabled, 0); assert.deepEqual(JSON.parse(f.row.allowed_routes), ['helpdesk', 'inventory']);
56
+ assert.notEqual(saved.json().revision, read.json().revision);
57
+ assert.deepEqual(f.counts(), { rollbacks: 0, commits: 1, released: 1 });
58
+ });
59
+
60
+ test('stale client setup rejects under the row lock and does not overwrite concurrent settings', async () => {
61
+ const f = fixture(); const body = f.body(); f.row.agent_authorize_url = 'https://example.test/concurrent';
62
+ const res = await f.call('PUT', body); assert.equal(res.statusCode, 409);
63
+ assert.equal(res.json().error, 'agent_setup_conflict'); assert.equal(f.row.enabled, 1);
64
+ assert.equal(f.sql.filter((s) => s.startsWith('UPDATE')).length, 0);
65
+ assert.deepEqual(f.counts(), { rollbacks: 1, commits: 0, released: 1 });
66
+ });
67
+
68
+ test('client setup rejects missing write permission and forbids token rotation or extra fields', async () => {
69
+ const f = fixture();
70
+ const viewer = { ...admin, permissions: ['clients:read'] } as Principal;
71
+ assert.equal((await f.call('GET', undefined, viewer)).statusCode, 200);
72
+ assert.equal((await f.call('PUT', f.body(), viewer)).statusCode, 403);
73
+ for (const extra of [{ rotate_token: true }, { token: 'anything' }, { app_id: 'other-client' }, { allowed_channels: ['*'] }]) {
74
+ assert.equal((await f.call('PUT', { ...f.body(), ...extra })).statusCode, 400);
75
+ }
76
+ assert.equal(f.counts().commits, 0);
77
+ });
78
+
79
+ test('client setup validates authorization URL and allowed routes without fallback to all routes', async () => {
80
+ const f = fixture();
81
+ for (const bad of [{ agent_authorize_url: 'http://example.test/auth' }, { agent_authorize_url: 'https://user:pass@example.test/auth' }, { allowed_routes: [] }, { allowed_routes: [null] }, { allowed_routes: ['bad/route'] }]) {
82
+ assert.equal((await f.call('PUT', { ...f.body(), ...bad })).statusCode, 400);
83
+ }
84
+ assert.equal(f.counts().commits, 0);
85
+ assert.equal((await f.call('PUT', { ...f.body(), agent_authorize_url: null })).statusCode, 200);
86
+ assert.equal(f.row.agent_authorize_url, null);
87
+ });
88
+
89
+ test('old Host without the optional client update method returns explicit unsupported', async () => {
90
+ const f = fixture(); (f.clients as any).updateAgentSetup = undefined;
91
+ const res = await f.call('PUT', f.body()); assert.equal(res.statusCode, 503); assert.equal(res.json().error, 'agent_setup_unsupported');
92
+ assert.equal((await f.call()).statusCode, 200); assert.equal(f.counts().commits, 0);
93
+ });
@@ -9,6 +9,7 @@ import { resolvePrincipal } from '../core/runtime/identity-runtime';
9
9
  import { previewAutoRoute } from '../core/runtime/routing-runtime';
10
10
  import type { AppConfig } from '../core/config/config';
11
11
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
12
+ import { handleAdminAgentSetupFor } from './admin-agent-setup';
12
13
 
13
14
  export interface AdminDispatchConfigApiDeps {
14
15
  configStore: ConfigStoreContract | null;
@@ -27,6 +28,7 @@ export async function handleAdminDispatchConfigApiFor(
27
28
  if (!deps.configStore) return false;
28
29
  const configStore = deps.configStore;
29
30
  const targetRegistry = deps.targetRegistry ?? defaultTargetRegistry;
31
+ if (await handleAdminAgentSetupFor(deps, method, path, req, res)) return true;
30
32
 
31
33
  if (path === '/admin/api/projects') {
32
34
  if (method === 'GET') { send(res, 200, await configStore.projects.list()); return true; }
@@ -14,6 +14,7 @@ import type { RuntimeStateStore } from '../core/state/state-contracts';
14
14
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
15
15
  import { authenticateAgentAccess } from './agent-auth';
16
16
  import { handleAgentConversationAuditFor } from './agent-conversation-audit';
17
+ import { getAgentSystemInfoFor } from '../app/agent-system-info';
17
18
  import type { KbService } from '../services/kb';
18
19
  import {
19
20
  completeAgentRunFor,
@@ -93,6 +94,12 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
93
94
  const principal: Principal = { kind: 'agent', session: auth.session, client: auth.client };
94
95
  const method = req.method ?? 'GET';
95
96
  if (await handleAgentConversationAuditFor(deps.configStore, auth, req, res, path)) return true;
97
+ const systemInfoMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/system-info$/) : null;
98
+ if (systemInfoMatch) {
99
+ try { send(res, 200, await getAgentSystemInfoFor(deps.configStore, auth, systemInfoMatch[1]!)); }
100
+ catch (error) { sendAgentToolError(res, error); }
101
+ return true;
102
+ }
96
103
  const runtimeDeps = (): AgentClientRuntimeDeps | null => deps.toolProxyDeps
97
104
  ? { toolProxyDeps: deps.toolProxyDeps, kbService: deps.kbService ?? null, stateStore: deps.stateStore }
98
105
  : null;