bailinghub 0.6.0 → 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 (149) hide show
  1. package/README.en.md +11 -7
  2. package/README.md +10 -7
  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 +25 -2
  16. package/docs/CHANGELOG.md +24 -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 +8 -0
  22. package/docs/README.md +8 -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.6.0.en.md +4 -2
  26. package/docs/RELEASE_NOTES_v0.6.0.md +2 -0
  27. package/docs/RELEASE_NOTES_v0.6.1.en.md +53 -0
  28. package/docs/RELEASE_NOTES_v0.6.1.md +53 -0
  29. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  30. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  31. package/docs/SDK.en.md +31 -0
  32. package/docs/user-guide/conversations.en.md +4 -2
  33. package/docs/user-guide/conversations.md +4 -2
  34. package/package.json +1 -1
  35. package/schemas/config/route.schema.json +15 -2
  36. package/scripts/check-doc-links.mjs +2 -0
  37. package/scripts/check-image-tags.sh +1 -1
  38. package/scripts/check-release-consistency.test.mjs +2 -2
  39. package/scripts/install.sh +1 -1
  40. package/scripts/publish-images.sh +1 -1
  41. package/scripts/release-audit.mjs +2 -0
  42. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  43. package/scripts/sdk-runtime-test.mjs +5 -2
  44. package/scripts/verify-github-repo.mjs +2 -0
  45. package/sdk/php/README.md +29 -0
  46. package/sdk/php/src/AgentAuth.php +100 -4
  47. package/sdk/php/src/HubClient.php +2 -1
  48. package/sdk/php7/README.md +31 -0
  49. package/sdk/php7/src/AgentAuth.php +99 -4
  50. package/sdk/php7/src/HubClient.php +2 -1
  51. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  52. package/sql/059_agent_subject_display.sql +5 -0
  53. package/sql/README.en.md +15 -0
  54. package/sql/README.md +25 -0
  55. package/src/app/agent-conversation-audit.ts +20 -0
  56. package/src/app/agent-system-info.ts +41 -0
  57. package/src/app/agent-tool-invocations.ts +16 -4
  58. package/src/core/config/agent-setup.ts +37 -0
  59. package/src/core/config/client-agent-setup.ts +25 -0
  60. package/src/core/config/config-schema.test.ts +11 -0
  61. package/src/core/config/route-config.test.ts +28 -0
  62. package/src/core/config/route-config.ts +43 -4
  63. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  64. package/src/core/contracts/agent-subject-display.ts +36 -0
  65. package/src/core/contracts/types.ts +15 -0
  66. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  67. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  68. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  69. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  70. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  71. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  72. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  73. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  74. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  75. package/src/infrastructure/config/config-client-repository.ts +21 -0
  76. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  77. package/src/infrastructure/config/config-route-repository.ts +24 -0
  78. package/src/infrastructure/config/configstore.ts +7 -3
  79. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  80. package/src/routes/admin-access.ts +37 -0
  81. package/src/routes/admin-agent-clients.ts +11 -0
  82. package/src/routes/admin-agent-setup.test.ts +130 -0
  83. package/src/routes/admin-agent-setup.ts +68 -0
  84. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  85. package/src/routes/admin-dispatch-config.ts +2 -0
  86. package/src/routes/agent-api.ts +7 -0
  87. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  88. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  89. package/src/routes/agent-auth.test.ts +1 -1
  90. package/src/routes/agent-auth.ts +206 -16
  91. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  92. package/src/routes/agent-conversation-audit.ts +8 -2
  93. package/src/routes/agent-subject-display-http.test.ts +145 -0
  94. package/src/routes/agent-system-info.test.ts +132 -0
  95. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  96. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  97. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  98. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  99. package/web/connect/bailing-connect-php.tgz +0 -0
  100. package/web/connect/bailing-connect-php7.tgz +0 -0
  101. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-ChL9k-XA.js} +1 -1
  102. package/web/console/assets/AgentClients-Bs7UgVDj.js +1 -0
  103. package/web/console/assets/AgentClients-DkgPTEbq.css +1 -0
  104. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-Bs6FGbp2.js} +1 -1
  105. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-4WWYhkFM.js} +1 -1
  106. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-D2GhCipL.js} +1 -1
  107. package/web/console/assets/{Channels-CApxH2TB.js → Channels-CmoGpiCJ.js} +1 -1
  108. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-BFRMtwta.js} +1 -1
  109. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  110. package/web/console/assets/Clients-DGkkSXyA.js +3 -0
  111. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-BmGt0MfS.js} +1 -1
  112. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-CR-sYINT.js} +1 -1
  113. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-DAPbKSJp.js} +1 -1
  114. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CgpiT3o8.js} +1 -1
  115. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-Cm9dVSQw.js} +1 -1
  116. package/web/console/assets/{Login-DiTjPWmN.js → Login-CyUcsTZ_.js} +1 -1
  117. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-DldFPgWg.js} +1 -1
  118. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  119. package/web/console/assets/Routes-DubfjlBD.js +124 -0
  120. package/web/console/assets/Runs-1hxgkuR4.js +3 -0
  121. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  122. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-DBLOnI2_.js} +1 -1
  123. package/web/console/assets/{Shell-BEqpONiy.js → Shell-gJ5Vz_E7.js} +1 -1
  124. package/web/console/assets/{StorageBuckets-CkORbYXY.js → StorageBuckets-DkDW16tj.js} +1 -1
  125. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-cDkudo2y.js} +1 -1
  126. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-DZd6s8OX.js} +1 -1
  127. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-DYNGq1NU.js} +1 -1
  128. package/web/console/assets/{Tools-CIHInlHL.js → Tools-DpWM59vV.js} +1 -1
  129. package/web/console/assets/{index-BkLbd7Cc.js → index-DGqs28gI.js} +2 -2
  130. package/web/console/assets/{request-r7GHVJzw.js → request-B7MLvOqo.js} +1 -1
  131. package/web/console/assets/{schema-BVn_hB7M.js → schema-CMuwjYdJ.js} +1 -1
  132. package/web/console/index.html +1 -1
  133. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  134. package/web-admin/src/components/AgentSetupPanel.vue +262 -0
  135. package/web-admin/src/components/ClientConversations.vue +21 -4
  136. package/web-admin/src/components/conversation-audit.ts +20 -0
  137. package/web-admin/src/pages/AgentClients.vue +97 -23
  138. package/web-admin/src/pages/Clients.vue +4 -1
  139. package/web-admin/src/pages/Routes.vue +10 -1
  140. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  141. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  142. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  143. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  144. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  145. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  146. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  147. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  148. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  149. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
@@ -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;
@@ -0,0 +1,177 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createServer } from 'node:http';
3
+ import type { AddressInfo } from 'node:net';
4
+ import test, { type TestContext } from 'node:test';
5
+ import type { Pool } from 'mysql2/promise';
6
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
+ import { AgentAuthRepository } from '../infrastructure/config/config-agent-auth-repository';
8
+ import { evaluateBusinessSessionQuery } from '../test-support/agent-auth-business-query-fixture';
9
+ import { LedgerFixture, REDIRECT } from '../test-support/agent-auth-lifecycle-fixture';
10
+ import { handleAgentAuthHttpFor, pkceChallenge } from './agent-auth';
11
+
12
+ // Real loopback HTTP, route parsing/authorization and repository SQL. Only the
13
+ // SQL engine, client registry and rate counter are synthetic; no MySQL or business
14
+ // server is contacted. Transaction/lock semantics have separate repository tests.
15
+ const CLIENTS = [
16
+ { app_id: 'example-business', name: 'Example', enabled: true, token: 'synthetic-client-token-a', allowed_routes: ['orders'], agent_authorize_url: 'https://example.test/authorize' },
17
+ { app_id: 'other-business', name: 'Other', enabled: true, token: 'synthetic-client-token-b', allowed_routes: ['inventory'], agent_authorize_url: 'https://other.example.test/authorize' },
18
+ ] as const;
19
+ type SyntheticClient = typeof CLIENTS[number];
20
+ const A = CLIENTS[0];
21
+ const B = CLIENTS[1];
22
+ const verifier = 'synthetic-pkce-verifier-'.padEnd(64, 'v');
23
+ const principal = { id: 'operator', tenant: 'tenant-A', roles: ['manager'] };
24
+
25
+ /** Match the production mysql2 pool's timezone:'Z' DATETIME result decoding. */
26
+ function driverRows(result: any[]): any[] {
27
+ if (!Array.isArray(result[0])) return result;
28
+ return [result[0].map((row: Record<string, unknown>) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key,
29
+ key.endsWith('_at') && typeof value === 'string' && /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)
30
+ ? new Date(`${value.replace(' ', 'T')}Z`) : value,
31
+ ]))), ...result.slice(1)];
32
+ }
33
+
34
+ async function fixture(t: TestContext) {
35
+ const ledger = new LedgerFixture();
36
+ for (const table of Object.values(ledger.rows)) table.clear();
37
+ const originalQuery = ledger.pool.query.bind(ledger.pool) as (sql: string, params: unknown[]) => Promise<any[]>;
38
+ const pool = {
39
+ async getConnection() {
40
+ const connection = await ledger.pool.getConnection();
41
+ return {
42
+ beginTransaction: connection.beginTransaction.bind(connection), commit: connection.commit.bind(connection),
43
+ rollback: connection.rollback.bind(connection), release: connection.release.bind(connection),
44
+ async query(sql: string, params: unknown[] = []) { return driverRows(await connection.query(sql, params)); },
45
+ };
46
+ },
47
+ async query(sql: string, params: unknown[] = []) {
48
+ if (sql.includes('FROM bz_agent_sessions s WHERE')) {
49
+ return driverRows(evaluateBusinessSessionQuery([...ledger.rows.session.values()], [...ledger.rows.authorization.values()], sql, params));
50
+ }
51
+ return driverRows(await originalQuery(sql, params));
52
+ },
53
+ } as unknown as Pool;
54
+ const repository = new AgentAuthRepository(() => pool);
55
+ const store = {
56
+ agentAuth: repository,
57
+ clients: {
58
+ async get(id: string) { return CLIENTS.find((client) => client.app_id === id) ?? null; },
59
+ async getByToken(token: string) { return CLIENTS.find((client) => client.token === token) ?? null; },
60
+ },
61
+ rateLimits: { async consume() { return false; } },
62
+ } as unknown as ConfigStoreContract;
63
+ const failures: unknown[] = [];
64
+ const server = createServer(async (req, res) => {
65
+ try {
66
+ if (!await handleAgentAuthHttpFor({ configStore: store }, req, res, new URL(req.url!, 'http://127.0.0.1'))) {
67
+ res.writeHead(404); res.end();
68
+ }
69
+ } catch (error) { failures.push(error); res.writeHead(500); res.end('{"error":"fixture_failure"}'); }
70
+ });
71
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
72
+ t.after(async () => {
73
+ await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
74
+ assert.deepEqual(failures, [], 'unexpected SQL or route exceptions must fail the integration');
75
+ });
76
+ const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
77
+ async function call(path: string, method = 'GET', body?: unknown, token?: string) {
78
+ const response = await fetch(`${origin}/agent-auth/v1${path}`, {
79
+ method, headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
80
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
81
+ });
82
+ assert.equal(response.headers.get('cache-control'), 'no-store');
83
+ if (path === '/token') assert.equal(response.headers.get('pragma'), 'no-cache');
84
+ return { status: response.status, body: await response.json() as any };
85
+ }
86
+ async function approve(client: SyntheticClient = A) {
87
+ const created = await call('/authorizations', 'POST', {
88
+ client_app_id: client.app_id, redirect_uri: REDIRECT, state: 'synthetic-state', requested_routes: client.allowed_routes,
89
+ device_label: 'Synthetic device', code_challenge: pkceChallenge(verifier), code_challenge_method: 'S256',
90
+ });
91
+ assert.equal(created.status, 201);
92
+ const id: string = created.body.authorization_id;
93
+ assert.equal(new URL(created.body.authorization_url).searchParams.get('authorization_id'), id);
94
+ const context = await call(`/authorizations/${id}`, 'GET', undefined, client.token);
95
+ assert.equal(context.status, 200); assert.equal(context.body.status, 'pending');
96
+ const approved = await call(`/authorizations/${id}/approve`, 'POST', { principal, on_behalf_of: 'tenant-A:operator', allowed_routes: client.allowed_routes }, client.token);
97
+ assert.equal(approved.status, 200);
98
+ const redirect = new URL(approved.body.redirect_uri);
99
+ assert.equal(redirect.searchParams.get('state'), 'synthetic-state');
100
+ const code = redirect.searchParams.get('code'); assert.ok(code);
101
+ return { id, client, code };
102
+ }
103
+ async function exchange(authorization: Awaited<ReturnType<typeof approve>>) {
104
+ return call('/token', 'POST', { grant_type: 'authorization_code', client_app_id: authorization.client.app_id,
105
+ code: authorization.code, redirect_uri: REDIRECT, code_verifier: verifier });
106
+ }
107
+ return { ledger, call, approve, exchange };
108
+ }
109
+
110
+ test('HTTP and real repository: approved authorization links to a scoped session; atomic revoke rejects access and refresh', async (t) => {
111
+ const f = await fixture(t);
112
+ const authorization = await f.approve();
113
+ const token = await f.exchange(authorization); assert.equal(token.status, 200);
114
+ const sessionId = token.body.session_id;
115
+ assert.equal(f.ledger.rows.authorization.get(authorization.id)?.session_id, sessionId);
116
+ const context = await f.call(`/authorizations/${authorization.id}`, 'GET', undefined, A.token);
117
+ assert.equal(context.status, 200); assert.equal(context.body.status, 'consumed');
118
+ assert.deepEqual(Object.keys(context.body.session).sort(), ['expires_at', 'session_id', 'state', 'subject_display', 'subject_display_status']);
119
+ assert.equal(context.body.session.session_id, sessionId); assert.equal(context.body.session.state, 'active');
120
+ assert.doesNotMatch(JSON.stringify(context.body), /code_hash|code_challenge|redirect_uri|access_token|refresh_token|principal/);
121
+
122
+ const filters = new URLSearchParams({ authorization_id: authorization.id, on_behalf_of: 'tenant-A:operator', principal_id: 'operator', tenant: 'tenant-A', state: 'active' });
123
+ const listed = await f.call(`/sessions?${filters}`, 'GET', undefined, A.token);
124
+ assert.equal(listed.status, 200); assert.equal(listed.body.list.length, 1);
125
+ assert.equal(listed.body.list[0].session_id, sessionId); assert.equal(listed.body.list[0].authorization_id, authorization.id);
126
+ assert.deepEqual(listed.body.list[0].principal, principal); assert.equal(listed.body.next_cursor, null);
127
+ assert.doesNotMatch(JSON.stringify(listed.body), /token_hash|access_token|refresh_token|code_challenge|code_hash/);
128
+ filters.set('tenant', 'tenant-B');
129
+ assert.deepEqual((await f.call(`/sessions?${filters}`, 'GET', undefined, A.token)).body.list, []);
130
+ assert.equal((await f.call('/session', 'GET', undefined, token.body.access_token)).status, 200);
131
+
132
+ const revoked = await f.call(`/authorizations/${authorization.id}/revoke`, 'POST', {}, A.token);
133
+ assert.equal(revoked.status, 200);
134
+ assert.deepEqual(revoked.body, { authorization_id: authorization.id, revoked: true, session_id: sessionId });
135
+ const after = await f.call(`/authorizations/${authorization.id}`, 'GET', undefined, A.token);
136
+ assert.equal(after.body.status, 'consumed'); assert.equal(after.body.session.state, 'revoked'); assert.ok(after.body.session.revoked_at);
137
+ assert.equal((await f.call('/session', 'GET', undefined, token.body.access_token)).status, 401);
138
+ const refreshed = await f.call('/token', 'POST', { grant_type: 'refresh_token', client_app_id: A.app_id, refresh_token: token.body.refresh_token });
139
+ assert.deepEqual(refreshed, { status: 400, body: { error: 'invalid_grant' } });
140
+ assert.deepEqual(await f.call(`/authorizations/${authorization.id}/revoke`, 'POST', {}, A.token), revoked);
141
+ assert.equal(f.ledger.rows.session.size, 1); assert.equal(f.ledger.rows.token.size, 1);
142
+ assert.ok(f.ledger.rows.session.get(sessionId)?.revoked_at);
143
+ assert.ok([...f.ledger.rows.token.values()].every((row) => row.status === 'revoked'));
144
+ });
145
+
146
+ test('HTTP and real repository: revocation after approval but before exchange prevents session issuance', async (t) => {
147
+ const f = await fixture(t); const authorization = await f.approve();
148
+ const revoked = await f.call(`/authorizations/${authorization.id}/revoke`, 'POST', {}, A.token);
149
+ assert.deepEqual(revoked, { status: 200, body: { authorization_id: authorization.id, revoked: true } });
150
+ const stored = f.ledger.rows.authorization.get(authorization.id)!;
151
+ assert.equal(stored.status, 'revoked'); assert.equal(stored.code_hash, null); assert.equal(stored.code_expires_at, null);
152
+ assert.deepEqual(await f.exchange(authorization), { status: 400, body: { error: 'invalid_grant' } });
153
+ assert.equal(f.ledger.rows.session.size, 0); assert.equal(f.ledger.rows.token.size, 0);
154
+ const context = await f.call(`/authorizations/${authorization.id}`, 'GET', undefined, A.token);
155
+ assert.equal(context.body.status, 'revoked'); assert.equal('session' in context.body, false);
156
+ assert.deepEqual(await f.call(`/authorizations/${authorization.id}/revoke`, 'POST', {}, A.token), revoked);
157
+ });
158
+
159
+ test('HTTP and real repository: another Client App cannot query or revoke an authorization or its session', async (t) => {
160
+ const f = await fixture(t);
161
+ const authorizationA = await f.approve(A); const tokenA = await f.exchange(authorizationA); assert.equal(tokenA.status, 200);
162
+ const authorizationB = await f.approve(B); const tokenB = await f.exchange(authorizationB); assert.equal(tokenB.status, 200);
163
+ const unknown = { status: 404, body: { error: 'not_found' } };
164
+ assert.deepEqual(await f.call(`/authorizations/${authorizationA.id}`, 'GET', undefined, B.token), unknown);
165
+ assert.deepEqual(await f.call(`/authorizations/${authorizationA.id}/revoke`, 'POST', {}, B.token), unknown);
166
+ assert.deepEqual(await f.call(`/sessions/${tokenA.body.session_id}/revoke`, 'POST', {}, B.token), unknown);
167
+ const hidden = await f.call(`/sessions?authorization_id=${authorizationA.id}`, 'GET', undefined, B.token);
168
+ assert.deepEqual(hidden, { status: 200, body: { list: [], next_cursor: null } });
169
+ for (const [client, token] of [[A, tokenA], [B, tokenB]] as const) {
170
+ const list = await f.call('/sessions?tenant=tenant-A', 'GET', undefined, client.token);
171
+ assert.equal(list.status, 200); assert.equal(list.body.list.length, 1);
172
+ assert.equal(list.body.list[0].client_app_id, client.app_id); assert.equal(list.body.list[0].session_id, token.body.session_id);
173
+ assert.equal((await f.call('/session', 'GET', undefined, token.body.access_token)).status, 200);
174
+ }
175
+ assert.ok([...f.ledger.rows.session.values()].every((row) => row.revoked_at === null));
176
+ assert.ok([...f.ledger.rows.token.values()].every((row) => row.status === 'active'));
177
+ });