bailinghub 0.3.1 → 0.3.2

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 (81) hide show
  1. package/.env.example +3 -0
  2. package/README.en.md +1 -1
  3. package/README.md +1 -0
  4. package/THIRD_PARTY_NOTICES.md +1 -1
  5. package/demo/business/server.mjs +107 -59
  6. package/docker-compose.images.yml +2 -2
  7. package/docs/CHANGELOG.en.md +12 -0
  8. package/docs/CHANGELOG.md +12 -0
  9. package/docs/DEMO.en.md +25 -0
  10. package/docs/DEMO.md +25 -0
  11. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  12. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  13. package/docs/README.en.md +2 -0
  14. package/docs/README.md +2 -0
  15. package/docs/RELEASE_NOTES_v0.3.2.en.md +57 -0
  16. package/docs/RELEASE_NOTES_v0.3.2.md +57 -0
  17. package/package.json +4 -1
  18. package/scripts/check-doc-links.mjs +1 -0
  19. package/scripts/check-image-tags.sh +1 -1
  20. package/scripts/check-package-artifact.mjs +2 -1
  21. package/scripts/check-release-consistency.mjs +57 -23
  22. package/scripts/check-release-consistency.test.mjs +63 -3
  23. package/scripts/install.sh +1 -1
  24. package/scripts/publish-images.sh +1 -1
  25. package/scripts/release-audit.mjs +1 -1
  26. package/scripts/seed-demo.ts +24 -99
  27. package/scripts/validate-examples.mjs +6 -4
  28. package/scripts/verify-github-repo.mjs +1 -1
  29. package/sql/054_demo_dataset_state.sql +12 -0
  30. package/src/app/kernel.ts +3 -0
  31. package/src/core/config/config.test.ts +69 -0
  32. package/src/core/config/config.ts +54 -0
  33. package/src/infrastructure/config/config-chat-repository.ts +12 -1
  34. package/src/infrastructure/config/config-client-repository.ts +21 -2
  35. package/src/infrastructure/config/config-route-repository.ts +12 -1
  36. package/src/infrastructure/config/config-target-repository.ts +12 -1
  37. package/src/infrastructure/config/config-tool-provider-repository.ts +12 -1
  38. package/src/routes/admin-default.ts +2 -0
  39. package/src/routes/admin-demo-dataset.test.ts +93 -0
  40. package/src/routes/admin-demo-dataset.ts +83 -0
  41. package/src/routes/admin-host.test.ts +10 -1
  42. package/src/routes/admin.ts +14 -0
  43. package/src/services/demo-business-profile.test.ts +230 -0
  44. package/src/services/demo-dataset.test.ts +369 -0
  45. package/src/services/demo-dataset.ts +872 -0
  46. package/web/console/assets/{Accounts-Dwzm4D_V.js → Accounts-08VltF2i.js} +1 -1
  47. package/web/console/assets/{Approvals-BxhuI0ku.js → Approvals-CqgmsMau.js} +1 -1
  48. package/web/console/assets/{Audit-dFAbGynl.js → Audit-bPlpSQt3.js} +1 -1
  49. package/web/console/assets/{BrandLockup-BtZyvkM5.js → BrandLockup-DhX07g3G.js} +1 -1
  50. package/web/console/assets/{Channels-Dqg4-_yr.js → Channels-BZe0pLgx.js} +1 -1
  51. package/web/console/assets/{ChatEntries-CEGZ3NnJ.js → ChatEntries-Ca0lcGqn.js} +1 -1
  52. package/web/console/assets/{Clients-C0QD1x7g.js → Clients-BVVZfX3r.js} +1 -1
  53. package/web/console/assets/{Cost-BAJqLhpK.js → Cost-DANcjr_p.js} +1 -1
  54. package/web/console/assets/{Credentials-D_GDRgWi.js → Credentials-D_8tP2Xa.js} +1 -1
  55. package/web/console/assets/{Diagnostics-BWYnDxRj.js → Diagnostics-Bw1WImFe.js} +1 -1
  56. package/web/console/assets/{Executors-Cmryk4Vk.js → Executors-fuieN2Sl.js} +1 -1
  57. package/web/console/assets/{Kb-BSXQE0Fa.js → Kb-BaMi_7xf.js} +1 -1
  58. package/web/console/assets/{Login-BnBPqC8Z.js → Login-Cmz2ppY8.js} +1 -1
  59. package/web/console/assets/{Projects-CNHx4L_7.js → Projects-D6xIgFB3.js} +1 -1
  60. package/web/console/assets/{Routes-u5cEAEXQ.js → Routes-B90i3ZNa.js} +1 -1
  61. package/web/console/assets/{Runs-BeFUR77_.js → Runs-9qpwotOj.js} +1 -1
  62. package/web/console/assets/Setup-BIjCiA2i.js +1 -0
  63. package/web/console/assets/Setup-BuyKFofL.css +1 -0
  64. package/web/console/assets/Shell-BVIjmoY8.css +1 -0
  65. package/web/console/assets/Shell-Dm6eFcl1.js +1 -0
  66. package/web/console/assets/{StorageBuckets-DMXRJxUA.js → StorageBuckets-DY8WuJlM.js} +1 -1
  67. package/web/console/assets/{SystemSettings-B72F-loY.js → SystemSettings-O_NMPzq_.js} +1 -1
  68. package/web/console/assets/{SystemStatus-hOj_TPYE.js → SystemStatus-Cok3S7S3.js} +1 -1
  69. package/web/console/assets/{Targets-UVVf7twC.js → Targets-YWBoxqvy.js} +1 -1
  70. package/web/console/assets/{Tools-ihkr9R9x.js → Tools-BgXDw7Mg.js} +1 -1
  71. package/web/console/assets/{index-DxvruykG.js → index-S_J0I0Zh.js} +2 -2
  72. package/web/console/assets/{request-BisL2T9B.js → request-FM608Kfz.js} +1 -1
  73. package/web/console/assets/{schema-CzpUpoLk.js → schema-DWnFqTkB.js} +1 -1
  74. package/web/console/index.html +1 -1
  75. package/web-admin/package-lock.json +3 -3
  76. package/web-admin/src/layout/Shell.vue +5 -4
  77. package/web-admin/src/pages/Setup.vue +12 -9
  78. package/web/console/assets/Setup-BjZfrmfN.js +0 -1
  79. package/web/console/assets/Setup-QjlHZKdB.css +0 -1
  80. package/web/console/assets/Shell-CbGNTN91.css +0 -1
  81. package/web/console/assets/Shell-EJuYf3OO.js +0 -1
@@ -0,0 +1,230 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
3
+ import { once } from 'node:events';
4
+ import { createServer } from 'node:net';
5
+ import { fileURLToPath } from 'node:url';
6
+ import test from 'node:test';
7
+ import { signToolCall } from '../core/contracts/tools';
8
+ import { demoToolSpec } from './demo-dataset';
9
+
10
+ const serverPath = fileURLToPath(new URL('../../demo/business/server.mjs', import.meta.url));
11
+ const strongSecret = '4f7b2c91a8d03e65b49c27e018f3d6aa';
12
+
13
+ async function unusedPort(): Promise<number> {
14
+ const reservation = createServer();
15
+ await new Promise<void>((resolve, reject) => {
16
+ reservation.once('error', reject);
17
+ reservation.listen(0, '127.0.0.1', resolve);
18
+ });
19
+ const address = reservation.address();
20
+ assert.ok(address && typeof address === 'object');
21
+ const port = address.port;
22
+ await new Promise<void>((resolve, reject) => reservation.close((error) => error ? reject(error) : resolve()));
23
+ return port;
24
+ }
25
+
26
+ async function waitUntilReady(child: ChildProcess, baseUrl: string, stderr: () => string): Promise<void> {
27
+ for (let attempt = 0; attempt < 100; attempt++) {
28
+ if (child.exitCode !== null) throw new Error(`demo business 提前退出 (${child.exitCode}): ${stderr()}`);
29
+ try {
30
+ const response = await fetch(`${baseUrl}/health`);
31
+ if (response.ok) return;
32
+ } catch {
33
+ // 子进程刚启动时连接拒绝属于正常竞态,短暂重试。
34
+ }
35
+ await new Promise((resolve) => setTimeout(resolve, 20));
36
+ }
37
+ throw new Error(`demo business 启动超时: ${stderr()}`);
38
+ }
39
+
40
+ async function stop(child: ChildProcess): Promise<void> {
41
+ if (child.exitCode !== null) return;
42
+ const exited = once(child, 'exit');
43
+ child.kill('SIGTERM');
44
+ await exited;
45
+ }
46
+
47
+ function signedHeaders(
48
+ method: string,
49
+ pathWithQuery: string,
50
+ body: string,
51
+ subject = 'demo-user-001',
52
+ jobId = 'contract-test',
53
+ signingSecret = strongSecret,
54
+ ): Record<string, string> {
55
+ const timestamp = Math.floor(Date.now() / 1000);
56
+ return {
57
+ 'content-type': 'application/json',
58
+ 'x-bailing-timestamp': String(timestamp),
59
+ 'x-bailing-signature': signToolCall(signingSecret, timestamp, method, pathWithQuery, body, subject, jobId),
60
+ 'x-bailing-on-behalf-of': subject,
61
+ 'x-bailing-job-id': jobId,
62
+ };
63
+ }
64
+
65
+ test('demo business stateless-readonly: 只暴露签名只读工具,不暴露或积累可变状态', { timeout: 10_000 }, async () => {
66
+ const port = await unusedPort();
67
+ let stderr = '';
68
+ const child = spawn(process.execPath, [serverPath], {
69
+ env: {
70
+ ...process.env,
71
+ DEMO_HOST: '127.0.0.1',
72
+ DEMO_PORT: String(port),
73
+ DEMO_PROFILE: 'stateless-readonly',
74
+ DEMO_TOOL_SECRET: strongSecret,
75
+ // 即使这两项是无效值,只读 profile 也不应触达 Hub 或 client token 路径。
76
+ DEMO_HUB_URL: 'http://127.0.0.1:1',
77
+ DEMO_CLIENT_TOKEN: 'must-not-be-used',
78
+ },
79
+ stdio: ['ignore', 'pipe', 'pipe'],
80
+ });
81
+ child.stderr.setEncoding('utf8');
82
+ child.stderr.on('data', (chunk: string) => { stderr += chunk; });
83
+ const baseUrl = `http://127.0.0.1:${port}`;
84
+
85
+ try {
86
+ await waitUntilReady(child, baseUrl, () => stderr);
87
+
88
+ const healthResponse = await fetch(`${baseUrl}/health`);
89
+ assert.equal(healthResponse.status, 200);
90
+ assert.deepEqual(await healthResponse.json(), { ok: true, app: 'demo-business', profile: 'stateless-readonly' });
91
+
92
+ const rootResponse = await fetch(`${baseUrl}/`);
93
+ assert.equal(rootResponse.status, 200);
94
+ const root = await rootResponse.text();
95
+ assert.doesNotMatch(root, new RegExp('批准|拒绝|authorization: Bearer|/console/'));
96
+
97
+ const specResponse = await fetch(`${baseUrl}/.well-known/bailing/tools.json`);
98
+ assert.equal(specResponse.status, 200);
99
+ const spec = await specResponse.json();
100
+ assert.deepEqual(spec, demoToolSpec('stateless-readonly'));
101
+ assert.deepEqual(Object.keys((spec as { paths: object }).paths).sort(), ['/failure-demo', '/orders']);
102
+
103
+ const probeBody = JSON.stringify({ subject: 'demo-user-001' });
104
+ const probePath = '/.well-known/bailing/authz-probe';
105
+ const probeResponse = await fetch(`${baseUrl}${probePath}`, {
106
+ method: 'POST',
107
+ headers: signedHeaders('POST', probePath, probeBody, 'demo-user-001', 'probe-test'),
108
+ body: probeBody,
109
+ });
110
+ assert.equal(probeResponse.status, 200);
111
+ assert.deepEqual(await probeResponse.json(), { authorized: true, subject: 'demo-user-001' });
112
+
113
+ const orderPath = '/orders?order_no=SO-1001';
114
+ const orderResponse = await fetch(`${baseUrl}${orderPath}`, {
115
+ headers: signedHeaders('GET', orderPath, ''),
116
+ });
117
+ assert.equal(orderResponse.status, 200);
118
+ const orderResult = await orderResponse.json() as { subject: string; orders: Array<{ order_no: string }> };
119
+ assert.equal(orderResult.subject, 'demo-user-001');
120
+ assert.deepEqual(orderResult.orders.map((order) => order.order_no), ['SO-1001']);
121
+
122
+ const failurePath = '/failure-demo';
123
+ const failureResponse = await fetch(`${baseUrl}${failurePath}`, {
124
+ headers: signedHeaders('GET', failurePath, ''),
125
+ });
126
+ assert.equal(failureResponse.status, 500);
127
+
128
+ const mutableRequests: Array<[string, RequestInit]> = [
129
+ ['/api/state', {}],
130
+ ['/tickets', { method: 'POST', body: '{}' }],
131
+ ['/refunds', { method: 'POST', body: '{}' }],
132
+ ['/approvals', { method: 'POST', body: '{}' }],
133
+ ['/api/approvals/1/decision', { method: 'POST', body: 'decision=approved' }],
134
+ ];
135
+ for (const [path, init] of mutableRequests) {
136
+ const response = await fetch(`${baseUrl}${path}`, init);
137
+ assert.equal(response.status, 404, `${path} 在 stateless-readonly 下必须隐藏`);
138
+ }
139
+ } finally {
140
+ await stop(child);
141
+ }
142
+ });
143
+
144
+ test('demo business 默认 profile 保持 full-local 工单与状态演示能力', { timeout: 10_000 }, async () => {
145
+ const port = await unusedPort();
146
+ let stderr = '';
147
+ const env = { ...process.env };
148
+ delete env.DEMO_PROFILE;
149
+ delete env.DEMO_TOOL_SECRET;
150
+ const child = spawn(process.execPath, [serverPath], {
151
+ env: {
152
+ ...env,
153
+ DEMO_HOST: '127.0.0.1',
154
+ DEMO_PORT: String(port),
155
+ },
156
+ stdio: ['ignore', 'pipe', 'pipe'],
157
+ });
158
+ child.stderr.setEncoding('utf8');
159
+ child.stderr.on('data', (chunk: string) => { stderr += chunk; });
160
+ const baseUrl = `http://127.0.0.1:${port}`;
161
+
162
+ try {
163
+ await waitUntilReady(child, baseUrl, () => stderr);
164
+ const healthResponse = await fetch(`${baseUrl}/health`);
165
+ assert.deepEqual(await healthResponse.json(), { ok: true, app: 'demo-business', profile: 'full-local' });
166
+
167
+ const specResponse = await fetch(`${baseUrl}/.well-known/bailing/tools.json`);
168
+ assert.deepEqual(await specResponse.json(), demoToolSpec('full-local'));
169
+
170
+ const ticketPath = '/tickets';
171
+ const ticketBody = JSON.stringify({ order_no: 'SO-1001', title: '需要人工跟进', message: '本地完整 demo 回归' });
172
+ const ticketResponse = await fetch(`${baseUrl}${ticketPath}`, {
173
+ method: 'POST',
174
+ headers: signedHeaders('POST', ticketPath, ticketBody, 'demo-user-001', 'full-local-test', 'demo-tool-secret-change-me'),
175
+ body: ticketBody,
176
+ });
177
+ assert.equal(ticketResponse.status, 200);
178
+
179
+ const stateResponse = await fetch(`${baseUrl}/api/state`);
180
+ assert.equal(stateResponse.status, 200);
181
+ const state = await stateResponse.json() as { tickets: Array<{ order_no: string }> };
182
+ assert.deepEqual(state.tickets.map((ticket) => ticket.order_no), ['SO-1001']);
183
+ } finally {
184
+ await stop(child);
185
+ }
186
+ });
187
+
188
+ test('demo business stateless-readonly: 弱密钥和占位符启动时 fail-fast', () => {
189
+ const weakSecrets = [
190
+ 'short-secret',
191
+ ' ',
192
+ 'demo-tool-secret-change-me',
193
+ 'test-secret-that-is-long-enough',
194
+ 'example-secret-that-is-long-enough',
195
+ 'change-this-secret-right-now',
196
+ 'replace-this-secret-right-now',
197
+ 'REPLACE_WITH_32_BYTE_INDEPENDENT_DEMO_TOOL_SECRET',
198
+ ];
199
+ for (const weakSecret of weakSecrets) {
200
+ const result = spawnSync(process.execPath, [serverPath], {
201
+ env: {
202
+ ...process.env,
203
+ DEMO_HOST: '127.0.0.1',
204
+ DEMO_PORT: '0',
205
+ DEMO_PROFILE: 'stateless-readonly',
206
+ DEMO_TOOL_SECRET: weakSecret,
207
+ },
208
+ encoding: 'utf8',
209
+ timeout: 2_000,
210
+ });
211
+ assert.notEqual(result.status, 0, `弱密钥 ${weakSecret} 不应启动成功`);
212
+ assert.match(result.stderr, /DEMO_TOOL_SECRET 不安全/);
213
+ }
214
+ });
215
+
216
+ test('demo business stateless-readonly: 拒绝绑定非回环地址', () => {
217
+ const result = spawnSync(process.execPath, [serverPath], {
218
+ env: {
219
+ ...process.env,
220
+ DEMO_HOST: '0.0.0.0',
221
+ DEMO_PORT: '0',
222
+ DEMO_PROFILE: 'stateless-readonly',
223
+ DEMO_TOOL_SECRET: strongSecret,
224
+ },
225
+ encoding: 'utf8',
226
+ timeout: 2_000,
227
+ });
228
+ assert.notEqual(result.status, 0);
229
+ assert.match(result.stderr, /DEMO_HOST 必须是本机回环地址/);
230
+ });
@@ -0,0 +1,369 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import {
4
+ DEMO_CHAT_ENTRY,
5
+ DemoDatasetConflictError,
6
+ DemoDatasetService,
7
+ demoToolSpec,
8
+ parseDemoDatasetManifest,
9
+ } from './demo-dataset';
10
+
11
+ const hash = 'a'.repeat(64);
12
+
13
+ class FakeDemoDatabase {
14
+ readonly events: string[] = [];
15
+ readonly targets = new Map<string, Record<string, unknown>>([
16
+ ['llm', { name: 'llm', kind: 'inhub', stateless: 1, needs_project: 0, timeout_ms: 120000, enabled: 1, description: 'built-in' }],
17
+ ]);
18
+ readonly providers = new Map<string, Record<string, unknown>>();
19
+ readonly routes = new Map<string, Record<string, unknown>>();
20
+ readonly clients = new Map<string, Record<string, unknown>>();
21
+ readonly chatEntries = new Map<string, Record<string, unknown>>();
22
+ readonly sessions: Array<Record<string, unknown>> = [];
23
+ readonly threads: Array<Record<string, unknown>> = [];
24
+ readonly jobs: Array<Record<string, unknown>> = [];
25
+ readonly toolApprovals: Array<Record<string, unknown>> = [];
26
+ readonly jobRatings: Array<Record<string, unknown>> = [];
27
+ readonly toolEmbeddings: Array<Record<string, unknown>> = [];
28
+ readonly pageContexts: Array<Record<string, unknown>> = [];
29
+ readonly channels: Array<Record<string, unknown>> = [];
30
+ readonly executorTokens: Array<Record<string, unknown>> = [];
31
+ auditRows = 0;
32
+ marker: Record<string, unknown> | null = null;
33
+
34
+ readonly connection = {
35
+ query: async (sql: string, params: unknown[] = []) => this.query(sql, params),
36
+ beginTransaction: async () => { this.events.push('BEGIN'); },
37
+ commit: async () => { this.events.push('COMMIT'); },
38
+ rollback: async () => { this.events.push('ROLLBACK'); },
39
+ release: () => { this.events.push('RELEASE'); },
40
+ };
41
+
42
+ readonly store = { db: { getConnection: async () => this.connection, query: async (sql: string, params: unknown[] = []) => this.query(sql, params) } };
43
+
44
+ private rows<T extends Record<string, unknown>>(values: Iterable<T>): T[] {
45
+ return [...values].map((value) => ({ ...value }));
46
+ }
47
+
48
+ private duplicate(): never {
49
+ throw Object.assign(new Error('duplicate'), { code: 'ER_DUP_ENTRY', errno: 1062 });
50
+ }
51
+
52
+ private put(
53
+ map: Map<string, Record<string, unknown>>,
54
+ key: string,
55
+ row: Record<string, unknown>,
56
+ sql: string,
57
+ ): void {
58
+ if (map.has(key) && !sql.includes('ON DUPLICATE KEY UPDATE')) this.duplicate();
59
+ map.set(key, row);
60
+ }
61
+
62
+ private async query(sql: string, params: unknown[]): Promise<[any[], Record<string, never>]> {
63
+ const normalized = sql.replace(/\s+/g, ' ').trim();
64
+ this.events.push(normalized);
65
+ const result = (rows: any[] = []): [any[], Record<string, never>] => [rows, {}];
66
+
67
+ if (normalized.startsWith('SELECT GET_LOCK')) return result([{ acquired: 1 }]);
68
+ if (normalized.startsWith('SELECT RELEASE_LOCK')) return result([{ released: 1 }]);
69
+ if (normalized === 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE') return result();
70
+ if (normalized.includes('(SELECT COUNT(*) FROM bz_routes) AS routes')) {
71
+ return result([{
72
+ routes: this.routes.size,
73
+ clients: this.clients.size,
74
+ tool_providers: this.providers.size,
75
+ targets: this.targets.size,
76
+ channels: this.channels.length,
77
+ chat_entries: this.chatEntries.size,
78
+ jobs: this.jobs.length,
79
+ approvals: 0,
80
+ auxiliary: this.executorTokens.length,
81
+ custom_targets: [...this.targets.keys()].filter((name) => name !== 'llm').length,
82
+ }]);
83
+ }
84
+ if (normalized.startsWith('SELECT version,manifest_json,imported_at,updated_at FROM bz_demo_datasets')) {
85
+ return result(this.marker ? [{ ...this.marker }] : []);
86
+ }
87
+
88
+ if (normalized === 'SELECT name FROM bz_targets WHERE name=? FOR UPDATE') return result(this.targets.has(String(params[0])) ? [{ name: params[0] }] : []);
89
+ if (normalized === 'SELECT name FROM bz_tool_providers WHERE name=? FOR UPDATE') return result(this.providers.has(String(params[0])) ? [{ name: params[0] }] : []);
90
+ if (normalized === 'SELECT route_key FROM bz_routes WHERE route_key=? FOR UPDATE') return result(this.routes.has(String(params[0])) ? [{ route_key: params[0] }] : []);
91
+ if (normalized === 'SELECT app_id FROM bz_clients WHERE app_id=? FOR UPDATE') return result(this.clients.has(String(params[0])) ? [{ app_id: params[0] }] : []);
92
+ if (normalized === 'SELECT entry_key FROM bz_chat_entries WHERE entry_key=? FOR UPDATE') return result(this.chatEntries.has(String(params[0])) ? [{ entry_key: params[0] }] : []);
93
+ if (normalized.startsWith('SELECT id FROM bz_sessions WHERE route_key=')) return result(this.sessions.filter((row) => row['route_key'] === params[0]).slice(0, 1));
94
+ if (normalized.startsWith('SELECT thread_id FROM bz_threads WHERE route_key=')) return result(this.threads.filter((row) => row['route_key'] === params[0]).slice(0, 1));
95
+ if (normalized.startsWith('SELECT job_id FROM bz_jobs WHERE target=? OR client_app_id=?')) {
96
+ return result(this.jobs.filter((row) => row['target'] === params[0]
97
+ || row['client_app_id'] === params[1]
98
+ || (row['dispatch'] as Record<string, unknown> | undefined)?.['route_key'] === params[2]).slice(0, 1));
99
+ }
100
+ if (normalized.startsWith('SELECT id FROM bz_tool_approvals WHERE provider=')) {
101
+ return result(this.toolApprovals.filter((row) => row['provider'] === params[0]).slice(0, 1));
102
+ }
103
+ if (normalized.startsWith('SELECT job_id FROM bz_job_ratings WHERE entry_key=')) {
104
+ return result(this.jobRatings.filter((row) => row['entry_key'] === params[0]).slice(0, 1));
105
+ }
106
+ if (normalized.startsWith('SELECT id FROM bz_tool_embeddings WHERE provider=')) {
107
+ return result(this.toolEmbeddings.filter((row) => row['provider'] === params[0]).slice(0, 1));
108
+ }
109
+
110
+ if (normalized === 'SELECT * FROM bz_targets ORDER BY name') return result(this.rows(this.targets.values()));
111
+ if (normalized.startsWith('SELECT * FROM bz_tool_providers WHERE name=')) return result(this.providers.has(String(params[0])) ? [{ ...this.providers.get(String(params[0]))! }] : []);
112
+ if (normalized.startsWith('SELECT * FROM bz_routes WHERE route_key=')) return result(this.routes.has(String(params[0])) ? [{ ...this.routes.get(String(params[0]))! }] : []);
113
+ if (normalized.startsWith('SELECT * FROM bz_clients WHERE app_id=')) return result(this.clients.has(String(params[0])) ? [{ ...this.clients.get(String(params[0]))! }] : []);
114
+ if (normalized.startsWith('SELECT * FROM bz_chat_entries WHERE entry_key=')) return result(this.chatEntries.has(String(params[0])) ? [{ ...this.chatEntries.get(String(params[0]))! }] : []);
115
+
116
+ if (normalized.startsWith('INSERT INTO bz_targets ')) {
117
+ this.put(this.targets, String(params[0]), {
118
+ name: params[0], kind: params[1], stateless: params[2], needs_project: params[3], timeout_ms: params[4],
119
+ enabled: params[5], description: params[6], created_at: params[7], updated_at: params[8],
120
+ }, normalized);
121
+ return result();
122
+ }
123
+ if (normalized.startsWith('INSERT INTO bz_tool_providers ')) {
124
+ this.put(this.providers, String(params[0]), {
125
+ name: params[0], base_url: params[1], spec_source: params[2], spec_access_policy: params[3], spec_url: params[4],
126
+ spec_json: params[5], spec_refreshed_at: params[6], spec_access_probe_json: params[7], authz_probe_json: params[8],
127
+ secret: params[9], log_payload: params[10], timeout_ms: params[11], rate_limit_per_min: params[12],
128
+ auto_refresh_min: params[13], enabled: params[14], description: params[15], embed_credential: params[16],
129
+ embed_model: params[17], embed_dim: params[18], created_at: params[19], updated_at: params[20],
130
+ }, normalized);
131
+ return result();
132
+ }
133
+ if (normalized.startsWith('INSERT INTO bz_routes ')) {
134
+ const columns = ['route_key', 'name', 'enabled', 'target', 'target_config', 'project', 'profile', 'permission', 'session_policy',
135
+ 'session_fixed_id', 'session_key_field', 'default_callback_url', 'delivery', 'knowledge', 'retry', 'tools', 'audience', 'memory',
136
+ 'budget', 'description', 'created_at', 'updated_at'];
137
+ this.put(this.routes, String(params[0]), Object.fromEntries(columns.map((column, index) => [column, params[index]])), normalized);
138
+ return result();
139
+ }
140
+ if (normalized.startsWith('INSERT INTO bz_clients ')) {
141
+ const columns = ['app_id', 'name', 'token', 'allowed_routes', 'allowed_channels', 'rate_limit_per_min', 'budget', 'enabled', 'description', 'created_at', 'updated_at'];
142
+ this.put(this.clients, String(params[0]), Object.fromEntries(columns.map((column, index) => [column, params[index]])), normalized);
143
+ return result();
144
+ }
145
+ if (normalized.startsWith('INSERT INTO bz_chat_entries ')) {
146
+ const columns = ['entry_key', 'name', 'route_key', 'enabled', 'allowed_origins', 'rate_limit_per_min', 'ticket_client', 'bucket',
147
+ 'title', 'greeting', 'color', 'appearance', 'description', 'created_at', 'updated_at'];
148
+ this.put(this.chatEntries, String(params[0]), Object.fromEntries(columns.map((column, index) => [column, params[index]])), normalized);
149
+ return result();
150
+ }
151
+ if (normalized.startsWith('UPDATE bz_clients SET token=')) {
152
+ const client = this.clients.get(String(params[2]));
153
+ if (client) { client['token'] = params[0]; client['updated_at'] = params[1]; }
154
+ return result();
155
+ }
156
+ if (normalized.startsWith('INSERT INTO bz_demo_datasets ')) {
157
+ if (this.marker) this.duplicate();
158
+ this.marker = { dataset_key: params[0], version: params[1], manifest_json: params[2], imported_at: params[3], updated_at: params[4] };
159
+ return result();
160
+ }
161
+ if (normalized.startsWith('UPDATE bz_demo_datasets SET version=')) {
162
+ assert.ok(this.marker);
163
+ this.marker = { ...this.marker!, version: params[0], manifest_json: params[1], updated_at: params[2] };
164
+ return result();
165
+ }
166
+
167
+ if (normalized === 'SELECT route_key,target,tools,audience FROM bz_routes FOR UPDATE') return result(this.rows(this.routes.values()));
168
+ if (normalized === 'SELECT entry_key,route_key,ticket_client FROM bz_chat_entries FOR UPDATE') return result(this.rows(this.chatEntries.values()));
169
+ if (normalized === 'SELECT id,entry_key FROM bz_page_contexts FOR UPDATE') return result(this.rows(this.pageContexts));
170
+ if (normalized === 'SELECT name,route_key FROM bz_channels FOR UPDATE') return result(this.rows(this.channels));
171
+ if (normalized === 'SELECT app_id,allowed_routes FROM bz_clients FOR UPDATE') return result(this.rows(this.clients.values()));
172
+ if (normalized === 'SELECT name,allowed_targets FROM bz_executor_tokens FOR UPDATE') return result(this.rows(this.executorTokens));
173
+
174
+ if (normalized.startsWith('DELETE FROM bz_chat_entries WHERE entry_key=')) { this.chatEntries.delete(String(params[0])); return result(); }
175
+ if (normalized.startsWith('DELETE FROM bz_clients WHERE app_id=')) { this.clients.delete(String(params[0])); return result(); }
176
+ if (normalized.startsWith('DELETE FROM bz_routes WHERE route_key=')) { this.routes.delete(String(params[0])); return result(); }
177
+ if (normalized.startsWith('DELETE FROM bz_tool_providers WHERE name=')) { this.providers.delete(String(params[0])); return result(); }
178
+ if (normalized.startsWith('DELETE FROM bz_targets WHERE name=')) { this.targets.delete(String(params[0])); return result(); }
179
+ if (normalized.startsWith('DELETE FROM bz_demo_datasets WHERE dataset_key=')) { this.marker = null; return result(); }
180
+
181
+ throw new Error(`FakeDemoDatabase 未覆盖 SQL: ${normalized}`);
182
+ }
183
+ }
184
+
185
+ test('demo dataset manifest: MySQL JSON 重排键后仍按结构验证', () => {
186
+ const reordered = JSON.stringify({
187
+ resources: {
188
+ chat_entries: [],
189
+ clients: [{ fingerprint: hash, key: 'demo-app' }],
190
+ routes: [{ fingerprint: hash, key: 'demo_support' }],
191
+ tool_providers: [{ fingerprint: hash, key: 'demo-business' }],
192
+ targets: [{ fingerprint: hash, key: 'demo-agent' }],
193
+ },
194
+ profile: 'stateless-readonly',
195
+ schema: 'bailinghub.demo-dataset.v1',
196
+ });
197
+ assert.equal(parseDemoDatasetManifest(reordered).profile, 'stateless-readonly');
198
+ });
199
+
200
+ test('demo dataset contract: hosted profile 不声明写工具或公开聊天入口', () => {
201
+ const spec = demoToolSpec('stateless-readonly') as { paths: Record<string, unknown> };
202
+ assert.deepEqual(Object.keys(spec.paths).sort(), ['/failure-demo', '/orders']);
203
+ assert.match(DEMO_CHAT_ENTRY, /^pub_[A-Za-z0-9_-]{8,64}$/);
204
+ assert.throws(() => parseDemoDatasetManifest({
205
+ schema: 'bailinghub.demo-dataset.v1',
206
+ profile: 'stateless-readonly',
207
+ resources: {
208
+ targets: [{ key: 'demo-agent', fingerprint: hash }],
209
+ tool_providers: [{ key: 'demo-business', fingerprint: hash }],
210
+ routes: [{ key: 'demo_support', fingerprint: hash }],
211
+ clients: [{ key: 'demo-app', fingerprint: hash }],
212
+ chat_entries: [{ key: DEMO_CHAT_ENTRY, fingerprint: hash }],
213
+ },
214
+ }), /chat_entries/);
215
+ });
216
+
217
+ test('demo dataset import: SERIALIZABLE 在交易前设置且首导 duplicate fail-closed', async () => {
218
+ const events: string[] = [];
219
+ const connection = {
220
+ async query(sql: string): Promise<[any[], any]> {
221
+ events.push(sql);
222
+ if (sql.startsWith('SELECT GET_LOCK')) return [[{ acquired: 1 }], []];
223
+ if (sql.startsWith('SELECT RELEASE_LOCK')) return [[{ released: 1 }], []];
224
+ if (sql.startsWith('INSERT INTO bz_targets')) {
225
+ assert.doesNotMatch(sql, /ON DUPLICATE KEY UPDATE/);
226
+ throw Object.assign(new Error('duplicate'), { code: 'ER_DUP_ENTRY', errno: 1062 });
227
+ }
228
+ return [[], []];
229
+ },
230
+ async beginTransaction(): Promise<void> { events.push('BEGIN'); },
231
+ async commit(): Promise<void> { events.push('COMMIT'); },
232
+ async rollback(): Promise<void> { events.push('ROLLBACK'); },
233
+ release(): void { events.push('RELEASE'); },
234
+ };
235
+ const service = new DemoDatasetService({
236
+ db: { getConnection: async () => connection },
237
+ } as any, {
238
+ businessBaseUrl: 'http://127.0.0.1:19080',
239
+ toolSecret: 'strong-independent-demo-secret',
240
+ profile: 'stateless-readonly',
241
+ });
242
+
243
+ await assert.rejects(
244
+ () => service.import(),
245
+ (error: unknown) => error instanceof DemoDatasetConflictError && /Core 已回滚/.test(error.message),
246
+ );
247
+ assert.ok(events.indexOf('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE') < events.indexOf('BEGIN'));
248
+ assert.ok(events.includes('ROLLBACK'));
249
+ assert.ok(events.includes('RELEASE'));
250
+ });
251
+
252
+ test('demo dataset lifecycle: stateless import/status/refresh/clear 不伪造或清理运行账本', async () => {
253
+ const db = new FakeDemoDatabase();
254
+ let tick = 0;
255
+ const service = new DemoDatasetService(db.store as any, {
256
+ businessBaseUrl: 'http://127.0.0.1:19080',
257
+ toolSecret: '4f7b2c91a8d03e65b49c27e018f3d6aa',
258
+ profile: 'stateless-readonly',
259
+ }, () => `2026-08-08T10:00:0${tick++}.000Z`);
260
+
261
+ assert.deepEqual(await service.status(), {
262
+ available: true,
263
+ imported: false,
264
+ empty: true,
265
+ counts: { routes: 0, clients: 0, tool_providers: 0, targets: 1, channels: 0, chat_entries: 0, jobs: 0, approvals: 0 },
266
+ });
267
+ const imported = await service.import();
268
+ assert.equal(imported.imported, true);
269
+ assert.equal(db.chatEntries.size, 0);
270
+ assert.deepEqual(imported.created.sort(), [
271
+ 'client:demo-app', 'route:demo_support', 'target:demo-agent', 'tool-provider:demo-business',
272
+ ]);
273
+ const importedAt = imported.imported_at;
274
+
275
+ const refreshed = await service.import();
276
+ assert.equal(refreshed.imported_at, importedAt);
277
+ assert.equal(db.marker?.['version'], 1);
278
+
279
+ db.jobs.push({ job_id: 'job-1', dispatch: { route_key: 'demo_support' } });
280
+ db.auditRows = 3;
281
+ const cleared = await service.clear();
282
+ assert.equal(cleared.imported, false);
283
+ assert.equal(cleared.counts.jobs, 1);
284
+ assert.equal(db.jobs.length, 1);
285
+ assert.equal(db.auditRows, 3);
286
+ assert.equal(db.targets.has('demo-agent'), false);
287
+ assert.equal(db.targets.has('llm'), true);
288
+ assert.equal(db.events.some((sql) => /^DELETE FROM bz_(jobs|audit|messages)/.test(sql)), false);
289
+ });
290
+
291
+ test('demo dataset ownership: 指纹漂移后拒绝覆盖与删除', async () => {
292
+ const db = new FakeDemoDatabase();
293
+ const service = new DemoDatasetService(db.store as any, {
294
+ businessBaseUrl: 'http://127.0.0.1:19080',
295
+ toolSecret: '4f7b2c91a8d03e65b49c27e018f3d6aa',
296
+ profile: 'stateless-readonly',
297
+ });
298
+ await service.import();
299
+ db.routes.get('demo_support')!['name'] = '用户重建的同名路由';
300
+
301
+ await assert.rejects(() => service.import(), (error: unknown) =>
302
+ error instanceof DemoDatasetConflictError && error.conflicts.includes('route:demo_support'));
303
+ assert.equal(db.routes.get('demo_support')?.['name'], '用户重建的同名路由');
304
+ await assert.rejects(() => service.clear(), (error: unknown) =>
305
+ error instanceof DemoDatasetConflictError && error.conflicts.includes('route:demo_support'));
306
+ assert.equal(db.routes.has('demo_support'), true);
307
+ assert.ok(db.marker);
308
+ });
309
+
310
+ test('demo dataset references: 首导不意外接通 dangling chat,清理不破坏外部引用', async () => {
311
+ const dangling = new FakeDemoDatabase();
312
+ dangling.chatEntries.set('pub_existing_entry', {
313
+ entry_key: 'pub_existing_entry', name: 'existing', route_key: 'demo_support', enabled: 1,
314
+ allowed_origins: '[]', rate_limit_per_min: 20, ticket_client: null,
315
+ });
316
+ const firstImport = new DemoDatasetService(dangling.store as any, {
317
+ businessBaseUrl: 'http://127.0.0.1:19080',
318
+ toolSecret: '4f7b2c91a8d03e65b49c27e018f3d6aa',
319
+ profile: 'stateless-readonly',
320
+ });
321
+ await assert.rejects(() => firstImport.import(), (error: unknown) =>
322
+ error instanceof DemoDatasetConflictError && error.conflicts.includes('chat-entry:pub_existing_entry->route:demo_support'));
323
+ assert.equal(dangling.routes.has('demo_support'), false);
324
+
325
+ const db = new FakeDemoDatabase();
326
+ const service = new DemoDatasetService(db.store as any, {
327
+ businessBaseUrl: 'http://127.0.0.1:19080',
328
+ toolSecret: '4f7b2c91a8d03e65b49c27e018f3d6aa',
329
+ profile: 'stateless-readonly',
330
+ });
331
+ await service.import();
332
+ db.routes.set('user-route', {
333
+ route_key: 'user-route', name: 'user', enabled: 1, target: 'demo-agent', target_config: '{}', profile: 'readonly',
334
+ session_policy: 'new', tools: null, audience: null,
335
+ });
336
+ await assert.rejects(() => service.import(), (error: unknown) =>
337
+ error instanceof DemoDatasetConflictError && error.conflicts.includes('route:user-route->target:demo-agent'));
338
+ await assert.rejects(() => service.clear(), (error: unknown) =>
339
+ error instanceof DemoDatasetConflictError && error.conflicts.includes('route:user-route->target:demo-agent'));
340
+ assert.equal(db.routes.has('demo_support'), true);
341
+ });
342
+
343
+ test('演示数据首导:保留的运行账本不能重新认领固定 demo 身份', async () => {
344
+ const db = new FakeDemoDatabase();
345
+ db.jobs.push({ job_id: 'legacy-job', target: 'demo-agent', client_app_id: null, dispatch: {} });
346
+ const service = new DemoDatasetService(db.store as any, {
347
+ businessBaseUrl: 'http://127.0.0.1:19080',
348
+ toolSecret: '4f7b2c91a8d03e65b49c27e018f3d6aa',
349
+ profile: 'stateless-readonly',
350
+ });
351
+
352
+ await assert.rejects(() => service.import(), (error: unknown) =>
353
+ error instanceof DemoDatasetConflictError && error.conflicts.includes('job-demo-identity'));
354
+ assert.equal(db.routes.has('demo_support'), false);
355
+ });
356
+
357
+ test('demo dataset profile: full-local 仅导入默认停用的合法 chat entry', async () => {
358
+ const db = new FakeDemoDatabase();
359
+ const service = new DemoDatasetService(db.store as any, {
360
+ businessBaseUrl: 'http://127.0.0.1:19080',
361
+ toolSecret: 'demo-tool-secret-change-me',
362
+ profile: 'full-local',
363
+ clientToken: 'bailing-demo-client-token',
364
+ });
365
+ const imported = await service.import();
366
+ assert.ok(imported.created.includes(`chat-entry:${DEMO_CHAT_ENTRY}`));
367
+ assert.equal(db.chatEntries.get(DEMO_CHAT_ENTRY)?.['enabled'], 0);
368
+ assert.equal(db.chatEntries.get(DEMO_CHAT_ENTRY)?.['route_key'], 'demo_support');
369
+ });