bailinghub 0.3.0 → 0.3.2-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/.env.example +3 -0
  2. package/README.en.md +2 -2
  3. package/README.md +2 -1
  4. package/THIRD_PARTY_NOTICES.md +14 -14
  5. package/demo/business/server.mjs +107 -59
  6. package/docker-compose.images.yml +2 -2
  7. package/docs/CHANGELOG.en.md +10 -0
  8. package/docs/CHANGELOG.md +10 -0
  9. package/docs/DEMO.md +25 -0
  10. package/docs/INDEPENDENT_VALIDATION.en.md +4 -3
  11. package/docs/INDEPENDENT_VALIDATION.md +4 -3
  12. package/docs/README.en.md +2 -0
  13. package/docs/README.md +2 -0
  14. package/docs/RELEASE_NOTES_v0.3.1.en.md +44 -0
  15. package/docs/RELEASE_NOTES_v0.3.1.md +44 -0
  16. package/package.json +5 -2
  17. package/scripts/check-doc-links.mjs +1 -0
  18. package/scripts/check-image-tags.sh +1 -1
  19. package/scripts/check-package-artifact.mjs +2 -1
  20. package/scripts/check-release-consistency.mjs +57 -23
  21. package/scripts/check-release-consistency.test.mjs +58 -3
  22. package/scripts/install.sh +1 -1
  23. package/scripts/publish-images.sh +1 -1
  24. package/scripts/release-audit.mjs +1 -0
  25. package/scripts/seed-demo.ts +24 -99
  26. package/scripts/validate-examples.mjs +6 -4
  27. package/scripts/verify-github-repo.mjs +2 -1
  28. package/sql/054_demo_dataset_state.sql +12 -0
  29. package/src/adapters/llm/file.ts +2 -2
  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
@@ -29,6 +29,10 @@ const ENV_KEYS = [
29
29
  'BAILING_TOOL_QUERY_EMBEDDING_TIMEOUT_MS',
30
30
  'BAILING_BOOTSTRAP_ADMIN_USERNAME',
31
31
  'BAILING_BOOTSTRAP_ADMIN_PASSWORD',
32
+ 'DEMO_BUSINESS_URL',
33
+ 'DEMO_TOOL_SECRET',
34
+ 'DEMO_PROFILE',
35
+ 'DEMO_CLIENT_TOKEN',
32
36
  ];
33
37
 
34
38
  function withTempConfig(config: Record<string, unknown>, env: Record<string, string | undefined>, fn: () => void): void {
@@ -251,6 +255,71 @@ test('loadConfig: 工具检索运行保护拒绝非整数与越界超时', () =>
251
255
  });
252
256
  });
253
257
 
258
+ test('loadConfig: 演示数据边界由环境注入且规范化 URL', () => {
259
+ const config = { server: { host: '127.0.0.1', token: '' }, state: { backend: 'jsonl' } };
260
+ withTempConfig(config, {
261
+ DEMO_BUSINESS_URL: 'http://127.0.0.1:19080/',
262
+ DEMO_TOOL_SECRET: 'a-strong-demo-secret-for-trial',
263
+ DEMO_PROFILE: 'stateless-readonly',
264
+ }, () => {
265
+ assert.deepEqual(loadConfig().demoDataset, {
266
+ businessBaseUrl: 'http://127.0.0.1:19080',
267
+ toolSecret: 'a-strong-demo-secret-for-trial',
268
+ profile: 'stateless-readonly',
269
+ });
270
+ });
271
+ });
272
+
273
+ test('loadConfig: 无状态只读演示拒绝缺失、非 HTTP 和弱密钥', () => {
274
+ const config = { server: { host: '127.0.0.1', token: '' }, state: { backend: 'jsonl' } };
275
+ withTempConfig(config, { DEMO_BUSINESS_URL: 'http://127.0.0.1:19080' }, () => {
276
+ assert.throws(() => loadConfig(), /DEMO_BUSINESS_URL 与 DEMO_TOOL_SECRET 必须同时配置/);
277
+ });
278
+ withTempConfig(config, {
279
+ DEMO_BUSINESS_URL: 'file:///tmp/demo',
280
+ DEMO_TOOL_SECRET: 'a-strong-demo-secret-for-trial',
281
+ DEMO_PROFILE: 'stateless-readonly',
282
+ }, () => {
283
+ assert.throws(() => loadConfig(), /http\(s\) URL/);
284
+ });
285
+ withTempConfig(config, {
286
+ DEMO_BUSINESS_URL: 'http://127.0.0.1:19080',
287
+ DEMO_TOOL_SECRET: 'demo-tool-secret-change-me',
288
+ DEMO_PROFILE: 'stateless-readonly',
289
+ }, () => {
290
+ assert.throws(() => loadConfig(), /至少 24 位/);
291
+ });
292
+ withTempConfig(config, {
293
+ DEMO_BUSINESS_URL: 'http://127.0.0.1:19080',
294
+ DEMO_TOOL_SECRET: 'REPLACE_WITH_32_BYTE_INDEPENDENT_DEMO_TOOL_SECRET',
295
+ DEMO_PROFILE: 'stateless-readonly',
296
+ }, () => {
297
+ assert.throws(() => loadConfig(), /至少 24 位/);
298
+ });
299
+ withTempConfig(config, {
300
+ DEMO_BUSINESS_URL: 'http://127.0.0.1:19080',
301
+ DEMO_TOOL_SECRET: ' a-strong-demo-secret-for-trial ',
302
+ DEMO_PROFILE: 'stateless-readonly',
303
+ }, () => {
304
+ assert.throws(() => loadConfig(), /至少 24 位/);
305
+ });
306
+ });
307
+
308
+ test('loadConfig: full-local Docker demo 保留显式的本地兼容默认', () => {
309
+ const config = { server: { host: '127.0.0.1', token: '' }, state: { backend: 'jsonl' } };
310
+ withTempConfig(config, {
311
+ DEMO_BUSINESS_URL: 'http://demo-business:19080',
312
+ DEMO_TOOL_SECRET: 'demo-tool-secret-change-me',
313
+ }, () => {
314
+ assert.deepEqual(loadConfig().demoDataset, {
315
+ businessBaseUrl: 'http://demo-business:19080',
316
+ toolSecret: 'demo-tool-secret-change-me',
317
+ profile: 'full-local',
318
+ clientToken: 'bailing-demo-client-token',
319
+ });
320
+ });
321
+ });
322
+
254
323
  test('loadConfig: 首次管理员变量必须成对配置且不回显密码', () => {
255
324
  const password = 'bootstrap-secret-123';
256
325
  withTempConfig({
@@ -37,6 +37,20 @@ export interface ToolRetrievalConfig {
37
37
  embeddingTimeoutMs: number;
38
38
  }
39
39
 
40
+ export type DemoDatasetProfile = 'full-local' | 'stateless-readonly';
41
+
42
+ /**
43
+ * Core 内置演示数据只保存中枢自己的配置。演示业务系统仍是独立 HTTP 边界;
44
+ * Host 可为多个隔离 Kernel 注入同一个无状态、只读的 loopback 演示服务。
45
+ */
46
+ export interface DemoDatasetConfig {
47
+ businessBaseUrl: string;
48
+ toolSecret: string;
49
+ profile: DemoDatasetProfile;
50
+ /** full-local Docker demo 的业务侧审批回调凭据;无状态只读模式不使用。 */
51
+ clientToken?: string;
52
+ }
53
+
40
54
  export const DEFAULT_TOOL_RETRIEVAL_CONFIG: Readonly<ToolRetrievalConfig> = Object.freeze({
41
55
  indexLoadTimeoutMs: 5000,
42
56
  embeddingTimeoutMs: 15_000,
@@ -85,6 +99,8 @@ export interface AppConfig {
85
99
  metrics: MetricsConfig;
86
100
  /** loadConfig 始终补齐;保留 optional 让旧版扩展注入的 AppConfig 继续兼容。 */
87
101
  toolRetrieval?: ToolRetrievalConfig;
102
+ /** 未配置时后台仍可读取 status,但 available=false 且不允许导入。 */
103
+ demoDataset?: DemoDatasetConfig | null;
88
104
  bootstrapAdmin: BootstrapAdminConfig | null;
89
105
  concurrency: number;
90
106
  killSwitchFile: string;
@@ -180,6 +196,43 @@ function bootstrapAdminFromEnv(env: NodeJS.ProcessEnv): BootstrapAdminConfig | n
180
196
  return { username, password };
181
197
  }
182
198
 
199
+ function demoDatasetFromEnv(env: NodeJS.ProcessEnv): DemoDatasetConfig | null {
200
+ const rawUrl = String(env['DEMO_BUSINESS_URL'] ?? '').trim();
201
+ const toolSecret = String(env['DEMO_TOOL_SECRET'] ?? '');
202
+ if (!rawUrl && !toolSecret) return null;
203
+ if (!rawUrl || !toolSecret) {
204
+ throw new Error('DEMO_BUSINESS_URL 与 DEMO_TOOL_SECRET 必须同时配置');
205
+ }
206
+
207
+ let parsed: URL;
208
+ try { parsed = new URL(rawUrl); }
209
+ catch { throw new Error('DEMO_BUSINESS_URL 必须是合法的 http(s) URL'); }
210
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash) {
211
+ throw new Error('DEMO_BUSINESS_URL 必须是不含账号、查询参数或片段的 http(s) URL');
212
+ }
213
+ const profileRaw = String(env['DEMO_PROFILE'] ?? 'full-local').trim();
214
+ if (profileRaw !== 'full-local' && profileRaw !== 'stateless-readonly') {
215
+ throw new Error('DEMO_PROFILE 仅支持 full-local 或 stateless-readonly');
216
+ }
217
+ const profile: DemoDatasetProfile = profileRaw;
218
+ if (profile === 'stateless-readonly') {
219
+ const weak = toolSecret.length < 24
220
+ || toolSecret !== toolSecret.trim()
221
+ || toolSecret === 'demo-tool-secret-change-me'
222
+ || /^(?:replace|change|demo|test|example|sample)(?:[_-]|$)/i.test(toolSecret);
223
+ if (weak) throw new Error('stateless-readonly 演示服务必须配置至少 24 位的非占位 DEMO_TOOL_SECRET');
224
+ }
225
+
226
+ const businessBaseUrl = parsed.toString().replace(/\/+$/, '');
227
+ const clientToken = String(env['DEMO_CLIENT_TOKEN'] ?? '').trim();
228
+ return {
229
+ businessBaseUrl,
230
+ toolSecret,
231
+ profile,
232
+ ...(profile === 'full-local' ? { clientToken: clientToken || 'bailing-demo-client-token' } : {}),
233
+ };
234
+ }
235
+
183
236
  /**
184
237
  * Standalone 模式从当前部署目录读取 config.json;Kernel Host 模式只读已安装
185
238
  * Core 制品内的安全默认。这样宿主 cwd 不会被误当成 Core 制品根或配置根。
@@ -240,6 +293,7 @@ export function loadConfig(options: LoadConfigOptions = {}): AppConfig {
240
293
  indexLoadTimeoutMs: boundedIntegerEnv('BAILING_TOOL_INDEX_LOAD_TIMEOUT_MS', DEFAULT_TOOL_RETRIEVAL_CONFIG.indexLoadTimeoutMs, 100, 60_000),
241
294
  embeddingTimeoutMs: boundedIntegerEnv('BAILING_TOOL_QUERY_EMBEDDING_TIMEOUT_MS', DEFAULT_TOOL_RETRIEVAL_CONFIG.embeddingTimeoutMs, 250, 120_000),
242
295
  },
296
+ demoDataset: demoDatasetFromEnv(env),
243
297
  bootstrapAdmin: bootstrapAdminFromEnv(env),
244
298
  concurrency: Number(raw['concurrency'] ?? 2),
245
299
  killSwitchFile: resolve(root, raw['killSwitchFile'] ?? '.paused'),
@@ -18,9 +18,20 @@ export class ChatConfigRepository {
18
18
  }
19
19
 
20
20
  async upsert(e: ChatEntry): Promise<void> {
21
+ await this.writeEntry(e, true);
22
+ }
23
+
24
+ /** Insert-only variant for ownership-sensitive bootstrap flows. */
25
+ async create(e: ChatEntry): Promise<void> {
26
+ await this.writeEntry(e, false);
27
+ }
28
+
29
+ private async writeEntry(e: ChatEntry, updateExisting: boolean): Promise<void> {
21
30
  await this.pool.query(
22
31
  'INSERT INTO bz_chat_entries (entry_key,name,route_key,enabled,allowed_origins,rate_limit_per_min,ticket_client,bucket,title,greeting,color,appearance,description,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' +
23
- 'ON DUPLICATE KEY UPDATE name=VALUES(name),route_key=VALUES(route_key),enabled=VALUES(enabled),allowed_origins=VALUES(allowed_origins),rate_limit_per_min=VALUES(rate_limit_per_min),ticket_client=VALUES(ticket_client),bucket=VALUES(bucket),title=VALUES(title),greeting=VALUES(greeting),color=VALUES(color),appearance=VALUES(appearance),description=VALUES(description),updated_at=VALUES(updated_at)',
32
+ (updateExisting
33
+ ? 'ON DUPLICATE KEY UPDATE name=VALUES(name),route_key=VALUES(route_key),enabled=VALUES(enabled),allowed_origins=VALUES(allowed_origins),rate_limit_per_min=VALUES(rate_limit_per_min),ticket_client=VALUES(ticket_client),bucket=VALUES(bucket),title=VALUES(title),greeting=VALUES(greeting),color=VALUES(color),appearance=VALUES(appearance),description=VALUES(description),updated_at=VALUES(updated_at)'
34
+ : ''),
24
35
  [e.entry_key, e.name, e.route_key, e.enabled ? 1 : 0, JSON.stringify(e.allowed_origins ?? []),
25
36
  e.rate_limit_per_min, e.ticket_client ?? null, e.bucket ?? null, e.title ?? null, e.greeting ?? null, e.color ?? null,
26
37
  e.appearance && Object.keys(e.appearance).length ? JSON.stringify(e.appearance) : null, e.description ?? null, dt(), dt()],
@@ -26,14 +26,33 @@ export class ClientRepository {
26
26
  async upsert(c: Omit<Client, 'token'>, rotateToken = false): Promise<string> {
27
27
  const existing = await this.get(c.app_id);
28
28
  const token = !existing || rotateToken ? randomBytes(16).toString('hex') : existing.token;
29
+ await this.write(c, token, true);
30
+ return token;
31
+ }
32
+
33
+ /** Insert-only variant for ownership-sensitive bootstrap flows. */
34
+ async create(c: Omit<Client, 'token'>, explicitToken?: string): Promise<string> {
35
+ const token = explicitToken ?? randomBytes(16).toString('hex');
36
+ if (token.length < 16) throw new Error('client token 至少 16 位');
37
+ await this.write(c, token, false);
38
+ return token;
39
+ }
40
+
41
+ private async write(c: Omit<Client, 'token'>, token: string, updateExisting: boolean): Promise<void> {
29
42
  await this.pool.query(
30
43
  'INSERT INTO bz_clients (app_id,name,token,allowed_routes,allowed_channels,rate_limit_per_min,budget,enabled,description,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?) ' +
31
- 'ON DUPLICATE KEY UPDATE name=VALUES(name),token=VALUES(token),allowed_routes=VALUES(allowed_routes),allowed_channels=VALUES(allowed_channels),rate_limit_per_min=VALUES(rate_limit_per_min),budget=VALUES(budget),enabled=VALUES(enabled),description=VALUES(description),updated_at=VALUES(updated_at)',
44
+ (updateExisting
45
+ ? 'ON DUPLICATE KEY UPDATE name=VALUES(name),token=VALUES(token),allowed_routes=VALUES(allowed_routes),allowed_channels=VALUES(allowed_channels),rate_limit_per_min=VALUES(rate_limit_per_min),budget=VALUES(budget),enabled=VALUES(enabled),description=VALUES(description),updated_at=VALUES(updated_at)'
46
+ : ''),
32
47
  [c.app_id, c.name, token, JSON.stringify(c.allowed_routes ?? []), JSON.stringify(c.allowed_channels ?? []), c.rate_limit_per_min ?? 60,
33
48
  c.budget && Object.keys(c.budget).length ? JSON.stringify(c.budget) : null,
34
49
  c.enabled ? 1 : 0, c.description ?? null, dt(), dt()],
35
50
  );
36
- return token;
51
+ }
52
+
53
+ async replaceToken(appId: string, token: string): Promise<void> {
54
+ if (token.length < 16) throw new Error('client token 至少 16 位');
55
+ await this.pool.query('UPDATE bz_clients SET token=?,updated_at=? WHERE app_id=?', [token, dt(), appId]);
37
56
  }
38
57
 
39
58
  async delete(appId: string): Promise<void> {
@@ -17,10 +17,21 @@ export class RouteRepository {
17
17
  }
18
18
 
19
19
  async upsert(r: Route): Promise<void> {
20
+ await this.write(r, true);
21
+ }
22
+
23
+ /** Insert-only variant for ownership-sensitive bootstrap flows. */
24
+ async create(r: Route): Promise<void> {
25
+ await this.write(r, false);
26
+ }
27
+
28
+ private async write(r: Route, updateExisting: boolean): Promise<void> {
20
29
  await this.pool.query(
21
30
  'INSERT INTO bz_routes (route_key,name,enabled,target,target_config,project,profile,permission,session_policy,session_fixed_id,session_key_field,default_callback_url,delivery,knowledge,retry,tools,audience,memory,budget,description,created_at,updated_at) ' +
22
31
  'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' +
23
- 'ON DUPLICATE KEY UPDATE name=VALUES(name),enabled=VALUES(enabled),target=VALUES(target),target_config=VALUES(target_config),project=VALUES(project),profile=VALUES(profile),permission=VALUES(permission),session_policy=VALUES(session_policy),session_fixed_id=VALUES(session_fixed_id),session_key_field=VALUES(session_key_field),default_callback_url=VALUES(default_callback_url),delivery=VALUES(delivery),knowledge=VALUES(knowledge),retry=VALUES(retry),tools=VALUES(tools),audience=VALUES(audience),memory=VALUES(memory),budget=VALUES(budget),description=VALUES(description),updated_at=VALUES(updated_at)',
32
+ (updateExisting
33
+ ? 'ON DUPLICATE KEY UPDATE name=VALUES(name),enabled=VALUES(enabled),target=VALUES(target),target_config=VALUES(target_config),project=VALUES(project),profile=VALUES(profile),permission=VALUES(permission),session_policy=VALUES(session_policy),session_fixed_id=VALUES(session_fixed_id),session_key_field=VALUES(session_key_field),default_callback_url=VALUES(default_callback_url),delivery=VALUES(delivery),knowledge=VALUES(knowledge),retry=VALUES(retry),tools=VALUES(tools),audience=VALUES(audience),memory=VALUES(memory),budget=VALUES(budget),description=VALUES(description),updated_at=VALUES(updated_at)'
34
+ : ''),
24
35
  [r.route_key, r.name, r.enabled ? 1 : 0, r.target, r.target_config ? JSON.stringify(r.target_config) : null,
25
36
  r.project ?? null, r.profile, r.permission ?? null, r.session_policy,
26
37
  r.session_fixed_id ?? null, r.session_key_field ?? null, r.default_callback_url ?? null,
@@ -12,9 +12,20 @@ export class TargetRepository {
12
12
  }
13
13
 
14
14
  async upsert(t: TargetDef): Promise<void> {
15
+ await this.write(t, true);
16
+ }
17
+
18
+ /** Insert-only variant for ownership-sensitive bootstrap flows. */
19
+ async create(t: TargetDef): Promise<void> {
20
+ await this.write(t, false);
21
+ }
22
+
23
+ private async write(t: TargetDef, updateExisting: boolean): Promise<void> {
15
24
  await this.pool.query(
16
25
  'INSERT INTO bz_targets (name,kind,stateless,needs_project,timeout_ms,enabled,description,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?) ' +
17
- 'ON DUPLICATE KEY UPDATE kind=VALUES(kind),stateless=VALUES(stateless),needs_project=VALUES(needs_project),timeout_ms=VALUES(timeout_ms),enabled=VALUES(enabled),description=VALUES(description),updated_at=VALUES(updated_at)',
26
+ (updateExisting
27
+ ? 'ON DUPLICATE KEY UPDATE kind=VALUES(kind),stateless=VALUES(stateless),needs_project=VALUES(needs_project),timeout_ms=VALUES(timeout_ms),enabled=VALUES(enabled),description=VALUES(description),updated_at=VALUES(updated_at)'
28
+ : ''),
18
29
  [t.name, t.kind, t.stateless ? 1 : 0, t.needs_project ? 1 : 0, t.timeout_ms ?? 0, t.enabled ? 1 : 0, t.description ?? null, dt(), dt()],
19
30
  );
20
31
  }
@@ -17,6 +17,15 @@ export class ToolProviderRepository {
17
17
  }
18
18
 
19
19
  async upsert(p: ToolProvider): Promise<void> {
20
+ await this.write(p, true);
21
+ }
22
+
23
+ /** Insert-only variant for ownership-sensitive bootstrap flows. */
24
+ async create(p: ToolProvider): Promise<void> {
25
+ await this.write(p, false);
26
+ }
27
+
28
+ private async write(p: ToolProvider, updateExisting: boolean): Promise<void> {
20
29
  // legacy_unverified 只是读取历史空值时的兼容映射;数据库不持久化该 sentinel。
21
30
  const specAccessPolicy = p.spec_source === 'url'
22
31
  && (p.spec_access_policy === 'signed_required' || p.spec_access_policy === 'public_allowed')
@@ -25,7 +34,9 @@ export class ToolProviderRepository {
25
34
  await this.pool.query(
26
35
  'INSERT INTO bz_tool_providers (name,base_url,spec_source,spec_access_policy,spec_url,spec_json,spec_refreshed_at,spec_access_probe_json,authz_probe_json,secret,log_payload,timeout_ms,rate_limit_per_min,auto_refresh_min,enabled,description,embed_credential,embed_model,embed_dim,created_at,updated_at) ' +
27
36
  'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ' +
28
- 'ON DUPLICATE KEY UPDATE base_url=VALUES(base_url),spec_source=VALUES(spec_source),spec_access_policy=VALUES(spec_access_policy),spec_url=VALUES(spec_url),spec_json=VALUES(spec_json),spec_refreshed_at=VALUES(spec_refreshed_at),spec_access_probe_json=VALUES(spec_access_probe_json),authz_probe_json=VALUES(authz_probe_json),secret=VALUES(secret),log_payload=VALUES(log_payload),timeout_ms=VALUES(timeout_ms),rate_limit_per_min=VALUES(rate_limit_per_min),auto_refresh_min=VALUES(auto_refresh_min),enabled=VALUES(enabled),description=VALUES(description),embed_credential=VALUES(embed_credential),embed_model=VALUES(embed_model),embed_dim=VALUES(embed_dim),updated_at=VALUES(updated_at)',
37
+ (updateExisting
38
+ ? 'ON DUPLICATE KEY UPDATE base_url=VALUES(base_url),spec_source=VALUES(spec_source),spec_access_policy=VALUES(spec_access_policy),spec_url=VALUES(spec_url),spec_json=VALUES(spec_json),spec_refreshed_at=VALUES(spec_refreshed_at),spec_access_probe_json=VALUES(spec_access_probe_json),authz_probe_json=VALUES(authz_probe_json),secret=VALUES(secret),log_payload=VALUES(log_payload),timeout_ms=VALUES(timeout_ms),rate_limit_per_min=VALUES(rate_limit_per_min),auto_refresh_min=VALUES(auto_refresh_min),enabled=VALUES(enabled),description=VALUES(description),embed_credential=VALUES(embed_credential),embed_model=VALUES(embed_model),embed_dim=VALUES(embed_dim),updated_at=VALUES(updated_at)'
39
+ : ''),
29
40
  [p.name, p.base_url, p.spec_source, specAccessPolicy, p.spec_url ?? null, p.spec_json ?? null,
30
41
  p.spec_refreshed_at ? p.spec_refreshed_at.slice(0, 19).replace('T', ' ') : null,
31
42
  p.spec_access_probe ? JSON.stringify(p.spec_access_probe) : null,
@@ -8,6 +8,7 @@ import { cfg, cfgStore, edition, isPaused, kbService, kbSync, queue, store, targ
8
8
  import type { Principal } from '../app/auth';
9
9
  import { refreshTargets } from '../core/targets/registry';
10
10
  import { handleAdminApiFor, type AdminApiDeps } from './admin';
11
+ import { DemoDatasetService } from '../services/demo-dataset';
11
12
 
12
13
  export function defaultAdminApiDeps(): AdminApiDeps {
13
14
  return {
@@ -27,6 +28,7 @@ export function defaultAdminApiDeps(): AdminApiDeps {
27
28
  engineRuntime: { requeueForRerun },
28
29
  refreshTargets,
29
30
  targetRegistry,
31
+ demoDataset: cfgStore ? new DemoDatasetService(cfgStore, cfg.demoDataset) : null,
30
32
  };
31
33
  }
32
34
 
@@ -0,0 +1,93 @@
1
+ import assert from 'node:assert/strict';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import test from 'node:test';
4
+ import type { Principal } from '../app/auth';
5
+ import {
6
+ DemoDatasetConflictError,
7
+ type DemoDatasetClearResult,
8
+ type DemoDatasetImportResult,
9
+ type DemoDatasetStatus,
10
+ } from '../services/demo-dataset';
11
+ import { handleAdminDemoDatasetApiFor, type DemoDatasetServiceContract } from './admin-demo-dataset';
12
+
13
+ const emptyStatus: DemoDatasetStatus = {
14
+ available: true,
15
+ imported: false,
16
+ empty: true,
17
+ counts: { routes: 0, clients: 0, tool_providers: 0, targets: 1, channels: 0, chat_entries: 0, jobs: 0, approvals: 0 },
18
+ };
19
+
20
+ function principal(permissions: string[]): Principal {
21
+ return { kind: 'admin', via: 'session', username: 'operator', permissions };
22
+ }
23
+
24
+ function response(): { res: ServerResponse; status(): number; json(): Record<string, unknown> } {
25
+ let status = 0;
26
+ let body = '';
27
+ const headers = new Map<string, unknown>();
28
+ return {
29
+ res: {
30
+ writeHead(code: number) { status = code; },
31
+ setHeader(name: string, value: unknown) { headers.set(name.toLowerCase(), value); },
32
+ end(chunk?: string) { body += chunk ?? ''; },
33
+ } as unknown as ServerResponse,
34
+ status: () => status,
35
+ json: () => JSON.parse(body) as Record<string, unknown>,
36
+ };
37
+ }
38
+
39
+ function service(overrides: Partial<DemoDatasetServiceContract> = {}): DemoDatasetServiceContract {
40
+ return {
41
+ status: async () => emptyStatus,
42
+ import: async () => ({ ok: true, ...emptyStatus, imported: true, created: [] } as DemoDatasetImportResult),
43
+ clear: async () => ({ ok: true, ...emptyStatus, removed: [] } as DemoDatasetClearResult),
44
+ ...overrides,
45
+ };
46
+ }
47
+
48
+ test('demo dataset admin API: status 与写入分别使用审计权限和四类聚合写权限', async () => {
49
+ const statusOut = response();
50
+ await handleAdminDemoDatasetApiFor(
51
+ { demoDataset: service(), refreshTargets: async () => undefined },
52
+ 'GET', '/admin/api/demo-dataset/status', {} as IncomingMessage, statusOut.res,
53
+ principal(['audit:read']),
54
+ );
55
+ assert.equal(statusOut.status(), 200);
56
+
57
+ for (const missing of ['targets:write', 'tools:write', 'routes:write', 'clients:write']) {
58
+ const out = response();
59
+ const permissions = ['targets:write', 'tools:write', 'routes:write', 'clients:write'].filter((item) => item !== missing);
60
+ await handleAdminDemoDatasetApiFor(
61
+ { demoDataset: service(), refreshTargets: async () => undefined },
62
+ 'POST', '/admin/api/demo-dataset/import', {} as IncomingMessage, out.res,
63
+ principal(permissions),
64
+ );
65
+ assert.equal(out.status(), 403, `missing ${missing}`);
66
+ }
67
+ });
68
+
69
+ test('demo dataset admin API: import 成功后刷新 target registry', async () => {
70
+ let refreshed = 0;
71
+ const out = response();
72
+ await handleAdminDemoDatasetApiFor(
73
+ { demoDataset: service(), refreshTargets: async () => { refreshed += 1; } },
74
+ 'POST', '/admin/api/demo-dataset/import', {} as IncomingMessage, out.res,
75
+ principal(['targets:write', 'tools:write', 'routes:write', 'clients:write']),
76
+ );
77
+ assert.equal(out.status(), 200);
78
+ assert.equal(refreshed, 1);
79
+ });
80
+
81
+ test('demo dataset admin API: ownership 冲突显式返回 409', async () => {
82
+ const out = response();
83
+ await handleAdminDemoDatasetApiFor(
84
+ {
85
+ demoDataset: service({ import: async () => { throw new DemoDatasetConflictError('同名冲突', ['route:demo_support']); } }),
86
+ refreshTargets: async () => undefined,
87
+ },
88
+ 'POST', '/admin/api/demo-dataset/import', {} as IncomingMessage, out.res,
89
+ principal(['*']),
90
+ );
91
+ assert.equal(out.status(), 409);
92
+ assert.deepEqual(out.json()['conflicts'], ['route:demo_support']);
93
+ });
@@ -0,0 +1,83 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { can, type Principal } from '../app/auth';
3
+ import { send } from '../app/http';
4
+ import {
5
+ DemoDatasetConflictError,
6
+ DemoDatasetUnavailableError,
7
+ type DemoDatasetClearResult,
8
+ type DemoDatasetImportResult,
9
+ type DemoDatasetStatus,
10
+ } from '../services/demo-dataset';
11
+
12
+ export interface DemoDatasetServiceContract {
13
+ status(): Promise<DemoDatasetStatus>;
14
+ import(): Promise<DemoDatasetImportResult>;
15
+ clear(): Promise<DemoDatasetClearResult>;
16
+ }
17
+
18
+ export interface AdminDemoDatasetApiDeps {
19
+ demoDataset: DemoDatasetServiceContract;
20
+ refreshTargets(): Promise<void>;
21
+ }
22
+
23
+ const WRITE_PERMISSIONS = ['targets:write', 'tools:write', 'routes:write', 'clients:write'] as const;
24
+
25
+ function canWriteDemoDataset(principal: Principal): boolean {
26
+ return WRITE_PERMISSIONS.every((permission) => can(principal, permission));
27
+ }
28
+
29
+ export async function handleAdminDemoDatasetApiFor(
30
+ deps: AdminDemoDatasetApiDeps,
31
+ method: string,
32
+ path: string,
33
+ _req: IncomingMessage,
34
+ res: ServerResponse,
35
+ principal: Principal,
36
+ ): Promise<boolean> {
37
+ if (!(path === '/admin/api/demo-dataset'
38
+ || path === '/admin/api/demo-dataset/status'
39
+ || path === '/admin/api/demo-dataset/import')) return false;
40
+
41
+ const statusRequest = path === '/admin/api/demo-dataset/status' && method === 'GET';
42
+ const importRequest = path === '/admin/api/demo-dataset/import' && method === 'POST';
43
+ const clearRequest = path === '/admin/api/demo-dataset' && method === 'DELETE';
44
+ if (!statusRequest && !importRequest && !clearRequest) {
45
+ res.setHeader('allow', path.endsWith('/status') ? 'GET' : path.endsWith('/import') ? 'POST' : 'DELETE');
46
+ send(res, 405, { error: 'method not allowed' });
47
+ return true;
48
+ }
49
+
50
+ if (statusRequest
51
+ ? !(can(principal, 'audit:read') || canWriteDemoDataset(principal))
52
+ : !canWriteDemoDataset(principal)) {
53
+ send(res, 403, { error: '当前角色无演示数据管理权限' });
54
+ return true;
55
+ }
56
+
57
+ try {
58
+ if (statusRequest) {
59
+ send(res, 200, await deps.demoDataset.status());
60
+ return true;
61
+ }
62
+ if (importRequest) {
63
+ const result = await deps.demoDataset.import();
64
+ await deps.refreshTargets();
65
+ send(res, 200, result);
66
+ return true;
67
+ }
68
+ const result = await deps.demoDataset.clear();
69
+ await deps.refreshTargets();
70
+ send(res, 200, result);
71
+ return true;
72
+ } catch (error) {
73
+ if (error instanceof DemoDatasetConflictError) {
74
+ send(res, 409, { error: error.message, conflicts: error.conflicts });
75
+ return true;
76
+ }
77
+ if (error instanceof DemoDatasetUnavailableError) {
78
+ send(res, 503, { error: error.message });
79
+ return true;
80
+ }
81
+ throw error;
82
+ }
83
+ }
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
2
2
  import type { IncomingMessage, ServerResponse } from 'node:http';
3
3
  import test from 'node:test';
4
4
  import type { Principal } from '../app/auth';
5
- import { adminSmokeHub, handleAdminApiFor, type AdminApiDeps } from './admin';
5
+ import { adminSmokeHub, adminSmokeRunInput, handleAdminApiFor, type AdminApiDeps } from './admin';
6
6
 
7
7
  function response() {
8
8
  let status = 0;
@@ -35,6 +35,15 @@ test('admin smoke loopback includes the trusted Kernel mount prefix', () => {
35
35
  );
36
36
  });
37
37
 
38
+ test('admin smoke uses a read-only request for the stateless demo profile', () => {
39
+ assert.match(adminSmokeRunInput({ demoDataset: {
40
+ businessBaseUrl: 'http://127.0.0.1:19080',
41
+ toolSecret: 'not-returned',
42
+ profile: 'stateless-readonly',
43
+ } }) ?? '', /只查询订单 SO-1001/);
44
+ assert.equal(adminSmokeRunInput({ demoDataset: null }), undefined);
45
+ });
46
+
38
47
  test('host identity cannot reach dead Core-local password or account APIs', async () => {
39
48
  for (const [method, path] of [
40
49
  ['POST', '/admin/api/password'],
@@ -19,6 +19,7 @@ import { handleAdminKbApiFor } from './admin-kb';
19
19
  import { handleAdminRuntimeApiFor } from './admin-runtime';
20
20
  import { handleAdminToolProviderApiFor } from './admin-tool-providers';
21
21
  import { handleAdminBrandingApiFor } from './admin-branding';
22
+ import { handleAdminDemoDatasetApiFor, type DemoDatasetServiceContract } from './admin-demo-dataset';
22
23
  import { refreshTargets, type TargetRegistry } from '../core/targets/registry';
23
24
  import type { AppConfig } from '../core/config/config';
24
25
  import type { RuntimeStateStore } from '../core/state/state-contracts';
@@ -52,12 +53,20 @@ export interface AdminApiDeps {
52
53
  httpMountPath?: string;
53
54
  /** False when a Host identity provider owns human accounts and passwords. */
54
55
  localAdminManagement?: boolean;
56
+ /** Core-native demo dataset service; only available with the MySQL config store. */
57
+ demoDataset: DemoDatasetServiceContract | null;
55
58
  }
56
59
 
57
60
  export function adminSmokeHub(cfg: Pick<AppConfig, 'server'>, httpMountPath?: string): string {
58
61
  return `http://127.0.0.1:${cfg.server.port}${normalizeHttpMountPath(httpMountPath)}`;
59
62
  }
60
63
 
64
+ export function adminSmokeRunInput(cfg: Pick<AppConfig, 'demoDataset'>): string | undefined {
65
+ return cfg.demoDataset?.profile === 'stateless-readonly'
66
+ ? 'smoke test: 只查询订单 SO-1001 并返回订单状态'
67
+ : undefined;
68
+ }
69
+
61
70
  // ---- web 配置后台 API(管理项目/路由/接入方,查看任务)----
62
71
  export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path: string, req: IncomingMessage, res: ServerResponse, principal: Principal): Promise<boolean> {
63
72
  if (deps.localAdminManagement === false && (path === '/admin/api/password' || /^\/admin\/api\/admins(?:\/|$)/.test(path))) {
@@ -81,6 +90,10 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
81
90
  send(res, 200, deps.capabilities);
82
91
  return true;
83
92
  }
93
+ if (deps.demoDataset && await handleAdminDemoDatasetApiFor(
94
+ { demoDataset: deps.demoDataset, refreshTargets: deps.refreshTargets },
95
+ method, path, req, res, principal,
96
+ )) return true;
84
97
  // 权限闸门:板块:动作 不在角色权限集内一律 403
85
98
  const deny = (): true => { send(res, 403, { error: '当前角色无此权限' }); return true; };
86
99
  const PERM_RULES: Array<[RegExp, string, string]> = [ // [路径, GET 所需权限, 写操作所需权限]
@@ -155,6 +168,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
155
168
  tenantId,
156
169
  runRoute: demo?.route,
157
170
  runToken: demo?.token,
171
+ runInput: adminSmokeRunInput(deps.cfg),
158
172
  waitMs: 20_000,
159
173
  }));
160
174
  return true;