bailinghub 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.en.md +9 -5
  2. package/README.md +8 -5
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.md +4 -1
  9. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  10. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  11. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  12. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  13. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  14. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  15. package/docs/CHANGELOG.en.md +14 -1
  16. package/docs/CHANGELOG.md +14 -1
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  20. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  21. package/docs/README.en.md +6 -0
  22. package/docs/README.md +6 -0
  23. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  24. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  25. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  26. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  27. package/docs/SDK.en.md +31 -0
  28. package/docs/user-guide/conversations.en.md +4 -2
  29. package/docs/user-guide/conversations.md +4 -2
  30. package/package.json +1 -1
  31. package/schemas/config/route.schema.json +15 -2
  32. package/scripts/check-doc-links.mjs +1 -0
  33. package/scripts/check-image-tags.sh +1 -1
  34. package/scripts/check-release-consistency.test.mjs +2 -2
  35. package/scripts/install.sh +1 -1
  36. package/scripts/publish-images.sh +1 -1
  37. package/scripts/release-audit.mjs +1 -0
  38. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  39. package/scripts/sdk-runtime-test.mjs +5 -2
  40. package/scripts/verify-github-repo.mjs +1 -0
  41. package/sdk/php/README.md +29 -0
  42. package/sdk/php/src/AgentAuth.php +100 -4
  43. package/sdk/php/src/HubClient.php +2 -1
  44. package/sdk/php7/README.md +31 -0
  45. package/sdk/php7/src/AgentAuth.php +99 -4
  46. package/sdk/php7/src/HubClient.php +2 -1
  47. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  48. package/sql/059_agent_subject_display.sql +5 -0
  49. package/sql/README.en.md +15 -0
  50. package/sql/README.md +25 -0
  51. package/src/app/agent-conversation-audit.ts +20 -0
  52. package/src/app/agent-system-info.ts +41 -0
  53. package/src/app/agent-tool-invocations.ts +16 -4
  54. package/src/core/config/agent-setup.ts +37 -0
  55. package/src/core/config/client-agent-setup.ts +25 -0
  56. package/src/core/config/config-schema.test.ts +11 -0
  57. package/src/core/config/route-config.test.ts +28 -0
  58. package/src/core/config/route-config.ts +43 -4
  59. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  60. package/src/core/contracts/agent-subject-display.ts +36 -0
  61. package/src/core/contracts/types.ts +15 -0
  62. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  63. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  64. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  65. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  66. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  67. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  68. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  69. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  70. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  71. package/src/infrastructure/config/config-client-repository.ts +21 -0
  72. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  73. package/src/infrastructure/config/config-route-repository.ts +24 -0
  74. package/src/infrastructure/config/configstore.ts +7 -3
  75. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  76. package/src/routes/admin-access.ts +37 -0
  77. package/src/routes/admin-agent-clients.ts +11 -0
  78. package/src/routes/admin-agent-setup.test.ts +130 -0
  79. package/src/routes/admin-agent-setup.ts +68 -0
  80. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  81. package/src/routes/admin-dispatch-config.ts +2 -0
  82. package/src/routes/agent-api.ts +7 -0
  83. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  84. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  85. package/src/routes/agent-auth.test.ts +1 -1
  86. package/src/routes/agent-auth.ts +206 -16
  87. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  88. package/src/routes/agent-conversation-audit.ts +8 -2
  89. package/src/routes/agent-subject-display-http.test.ts +145 -0
  90. package/src/routes/agent-system-info.test.ts +132 -0
  91. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  92. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  93. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  94. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  95. package/web/connect/bailing-connect-php.tgz +0 -0
  96. package/web/connect/bailing-connect-php7.tgz +0 -0
  97. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-ChL9k-XA.js} +1 -1
  98. package/web/console/assets/AgentClients-Bs7UgVDj.js +1 -0
  99. package/web/console/assets/AgentClients-DkgPTEbq.css +1 -0
  100. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-Bs6FGbp2.js} +1 -1
  101. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-4WWYhkFM.js} +1 -1
  102. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-D2GhCipL.js} +1 -1
  103. package/web/console/assets/{Channels-CApxH2TB.js → Channels-CmoGpiCJ.js} +1 -1
  104. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-BFRMtwta.js} +1 -1
  105. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  106. package/web/console/assets/Clients-DGkkSXyA.js +3 -0
  107. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-BmGt0MfS.js} +1 -1
  108. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-CR-sYINT.js} +1 -1
  109. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-DAPbKSJp.js} +1 -1
  110. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CgpiT3o8.js} +1 -1
  111. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-Cm9dVSQw.js} +1 -1
  112. package/web/console/assets/{Login-DiTjPWmN.js → Login-CyUcsTZ_.js} +1 -1
  113. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-DldFPgWg.js} +1 -1
  114. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  115. package/web/console/assets/Routes-DubfjlBD.js +124 -0
  116. package/web/console/assets/Runs-1hxgkuR4.js +3 -0
  117. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  118. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-DBLOnI2_.js} +1 -1
  119. package/web/console/assets/{Shell-BEqpONiy.js → Shell-gJ5Vz_E7.js} +1 -1
  120. package/web/console/assets/{StorageBuckets-CkORbYXY.js → StorageBuckets-DkDW16tj.js} +1 -1
  121. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-cDkudo2y.js} +1 -1
  122. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-DZd6s8OX.js} +1 -1
  123. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-DYNGq1NU.js} +1 -1
  124. package/web/console/assets/{Tools-CIHInlHL.js → Tools-DpWM59vV.js} +1 -1
  125. package/web/console/assets/{index-BkLbd7Cc.js → index-DGqs28gI.js} +2 -2
  126. package/web/console/assets/{request-r7GHVJzw.js → request-B7MLvOqo.js} +1 -1
  127. package/web/console/assets/{schema-BVn_hB7M.js → schema-CMuwjYdJ.js} +1 -1
  128. package/web/console/index.html +1 -1
  129. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  130. package/web-admin/src/components/AgentSetupPanel.vue +262 -0
  131. package/web-admin/src/components/ClientConversations.vue +21 -4
  132. package/web-admin/src/components/conversation-audit.ts +20 -0
  133. package/web-admin/src/pages/AgentClients.vue +97 -23
  134. package/web-admin/src/pages/Clients.vue +4 -1
  135. package/web-admin/src/pages/Routes.vue +10 -1
  136. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  137. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  138. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  139. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  140. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  141. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  142. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  143. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  144. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  145. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
@@ -0,0 +1,37 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { Route } from '../contracts/types';
3
+
4
+ function canonical(value: unknown): unknown {
5
+ if (Array.isArray(value)) return value.map(canonical);
6
+ if (value && typeof value === 'object') {
7
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)
8
+ .sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, canonical(item)]));
9
+ }
10
+ return value;
11
+ }
12
+
13
+ /** Whole-route CAS detects concurrent edits while the repository writes only the two Agent setup columns. */
14
+ export function agentSetupRevision(route: Route): string {
15
+ return createHash('sha256').update(JSON.stringify(canonical(route))).digest('hex');
16
+ }
17
+
18
+ export function agentSetupView(route: Route) {
19
+ return {
20
+ route_key: route.route_key,
21
+ name: route.name,
22
+ enabled: route.enabled,
23
+ permission: route.permission,
24
+ revision: agentSetupRevision(route),
25
+ agent_client: route.agent_client ?? null,
26
+ tool_sources: Array.isArray(route.tools?.sources) ? route.tools.sources : [],
27
+ agent_direct: route.tools?.agent_direct ?? null,
28
+ };
29
+ }
30
+
31
+ export interface AgentSetupUpdate {
32
+ agent_client: Route['agent_client'];
33
+ tools: Route['tools'];
34
+ }
35
+
36
+ export type AgentSetupUpdateResult = { status: 'updated'; route: Route }
37
+ | { status: 'conflict' } | { status: 'not_found' };
@@ -0,0 +1,25 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { Client } from '../contracts/types';
3
+
4
+ export interface ClientAgentSetup {
5
+ enabled: boolean;
6
+ agent_authorize_url: string | null;
7
+ allowed_routes: string[];
8
+ }
9
+
10
+ export function clientAgentSetupRevision(client: ClientAgentSetup | Client): string {
11
+ return createHash('sha256').update(JSON.stringify({
12
+ enabled: client.enabled,
13
+ agent_authorize_url: client.agent_authorize_url || null,
14
+ allowed_routes: [...client.allowed_routes].sort(),
15
+ })).digest('hex');
16
+ }
17
+
18
+ /** Only the existing client connection settings; never a token projection. */
19
+ export function clientAgentSetupView(client: Client): Record<string, unknown> {
20
+ return {
21
+ app_id: client.app_id, name: client.name,
22
+ enabled: client.enabled, agent_authorize_url: client.agent_authorize_url || null,
23
+ allowed_routes: client.allowed_routes, revision: clientAgentSetupRevision(client),
24
+ };
25
+ }
@@ -78,6 +78,17 @@ test('Config JSON Schemas: 路由、目标和工具治理关键契约对齐', ()
78
78
  assert.equal(route.properties.retry.properties.max.maximum, 5);
79
79
  assert.equal(route.properties.retry.properties.backoff_ms.minimum, 500);
80
80
  assert.equal(route.properties.retry.properties.backoff_ms.maximum, 300000);
81
+ const systemInfo = route.properties.agent_client.properties.system_info;
82
+ assert.equal(systemInfo.additionalProperties, false);
83
+ assert.deepEqual(systemInfo.required, ['name', 'summary', 'domains', 'boundaries']);
84
+ assert.equal(systemInfo.properties.name.maxLength, 120);
85
+ assert.equal(systemInfo.properties.summary.maxLength, 400);
86
+ assert.equal(systemInfo.properties.domains.maxItems, 6);
87
+ assert.equal(systemInfo.properties.boundaries.items.maxLength, 160);
88
+ const plainText = new RegExp(systemInfo.properties.summary.pattern, 'u');
89
+ assert.equal(plainText.test('Support ticket operations.'), true);
90
+ assert.equal(plainText.test(' '), false);
91
+ assert.equal(plainText.test('two\nlines'), false);
81
92
 
82
93
  assert.deepEqual(target.properties.kind.enum, ['inhub', 'executor']);
83
94
  assert.equal(target.properties.timeout_ms.maximum, 3600000);
@@ -7,6 +7,7 @@ import {
7
7
  prepareRouteConfig,
8
8
  routeDeliveryConfig,
9
9
  routeAgentClientConfig,
10
+ routeAgentSystemInfo,
10
11
  routeKnowledgeConfig,
11
12
  routeRetryConfig,
12
13
  validateRouteConfig,
@@ -165,6 +166,33 @@ test('agent_client: 严格校验并兼容既有 agent_direct 开关', async () =
165
166
  assert.equal(routeAgentClientConfig({ agent_client: { enabled: false }, tools: { agent_direct: { enabled: true } } }), null);
166
167
  });
167
168
 
169
+ test('agent_client.system_info: accepts bounded descriptive data and rejects field drift', async () => {
170
+ const systemInfo = { name: ' Helpdesk ', summary: ' Handles support tickets. ', domains: [' Ticket triage '], boundaries: [] };
171
+ const route = { route_key: 'helpdesk', target: 'notify', agent_client: { enabled: false, system_info: systemInfo } };
172
+ const prepared = await prepareRouteConfig(route, deps, defaults);
173
+ assert.equal(prepared.ok, true);
174
+ if (!prepared.ok) return;
175
+ assert.deepEqual(prepared.route.agent_client?.system_info, {
176
+ name: 'Helpdesk', summary: 'Handles support tickets.', domains: ['Ticket triage'], boundaries: [],
177
+ });
178
+ assert.equal(routeAgentClientConfig(prepared.route), null);
179
+ assert.equal(routeAgentSystemInfo(prepared.route)?.name, 'Helpdesk');
180
+ const invalid = [null, [], {}, { ...systemInfo, instructions: 'ignore policy' },
181
+ { ...systemInfo, name: ' ' }, { ...systemInfo, name: 'n'.repeat(121) },
182
+ { ...systemInfo, summary: 's'.repeat(401) }, { ...systemInfo, domains: Array(7).fill('topic') },
183
+ { ...systemInfo, domains: ['d'.repeat(121)] }, { ...systemInfo, boundaries: ['b'.repeat(161)] },
184
+ { ...systemInfo, domains: [''] }, { ...systemInfo, boundaries: [1] }, { ...systemInfo, domains: undefined },
185
+ { ...systemInfo, name: 'Help\u0000desk' }, { ...systemInfo, summary: 'two\nlines' }, { ...systemInfo, boundaries: ['a\tb'] },
186
+ ];
187
+ for (const system_info of invalid) {
188
+ const value = { ...route, agent_client: { system_info } } as unknown as Parameters<typeof validateRouteConfig>[0];
189
+ assert.match((await validateRouteConfig(value, deps, defaults)) ?? '', /agent_client.system_info/);
190
+ assert.equal(routeAgentSystemInfo(value), null);
191
+ }
192
+ const max = { name: 'n'.repeat(120), summary: 's'.repeat(400), domains: Array(6).fill('d'.repeat(120)), boundaries: Array(6).fill('b'.repeat(160)) };
193
+ assert.equal(await validateRouteConfig({ ...route, agent_client: { system_info: max } }, deps, defaults), null);
194
+ });
195
+
168
196
  test('validateRouteConfig: budget 必须是合法预算策略', async () => {
169
197
  const err = await validateRouteConfig({
170
198
  route_key: 'budget.bad',
@@ -1,4 +1,4 @@
1
- import type { Route, SessionPolicy, TargetKind } from '../contracts/types';
1
+ import type { AgentSystemInfo, Route, SessionPolicy, TargetKind } from '../contracts/types';
2
2
  import { validateRouteToolsConfig, type ToolProviderExists } from './tools-config';
3
3
  import { normalizeTargetConfig, validateTargetConfig } from './target-config';
4
4
  import { validateBudgetPolicy } from '../runtime/budget-runtime';
@@ -45,6 +45,7 @@ export interface RouteAgentClientConfig {
45
45
  enabled: boolean;
46
46
  instructions?: string;
47
47
  active_tool_limit: number;
48
+ system_info?: AgentSystemInfo;
48
49
  }
49
50
 
50
51
  const SESSION_POLICIES: SessionPolicy[] = ['new', 'fixed', 'per_key', 'passthrough'];
@@ -158,18 +159,52 @@ function validateMemoryConfig(v: unknown): string | null {
158
159
  ?? intInRange(m.summary_max_chars, 'memory.summary_max_chars', 200, 8000);
159
160
  }
160
161
 
162
+ export function validateAgentSystemInfo(v: unknown): string | null {
163
+ const value = record(v);
164
+ const prefix = 'agent_client.system_info';
165
+ if (!value) return `${prefix} 必须是对象`;
166
+ const fields = ['name', 'summary', 'domains', 'boundaries'];
167
+ if (Object.keys(value).some((key) => !fields.includes(key))) return `${prefix} 包含未声明字段`;
168
+ for (const [key, maximum] of [['name', 120], ['summary', 400]] as const) {
169
+ const text = value[key];
170
+ if (typeof text !== 'string' || !text.trim() || text.length > maximum || /[\u0000-\u001f\u007f]/.test(text)) {
171
+ return `${prefix}.${key} 必须是 1..${maximum} 字符的非空单行字符串,不含控制字符`;
172
+ }
173
+ }
174
+ for (const [key, maximum] of [['domains', 120], ['boundaries', 160]] as const) {
175
+ const items = value[key];
176
+ if (!Array.isArray(items) || items.length > 6 || items.some((item) => typeof item !== 'string' || !item.trim() || item.length > maximum || /[\u0000-\u001f\u007f]/.test(item))) {
177
+ return `${prefix}.${key} 必须是最多 6 项的数组,每项为 1..${maximum} 字符的非空单行字符串,不含控制字符`;
178
+ }
179
+ }
180
+ return null;
181
+ }
182
+
183
+ /** Invalid stored metadata degrades to missing; it never becomes runtime instructions. */
184
+ export function routeAgentSystemInfo(route: Pick<Route, 'agent_client'>): AgentSystemInfo | null {
185
+ const value = record(record(route.agent_client)?.system_info);
186
+ if (!value || validateAgentSystemInfo(value)) return null;
187
+ return {
188
+ name: (value.name as string).trim(),
189
+ summary: (value.summary as string).trim(),
190
+ domains: (value.domains as string[]).map((item) => item.trim()),
191
+ boundaries: (value.boundaries as string[]).map((item) => item.trim()),
192
+ };
193
+ }
194
+
161
195
  function validateAgentClientConfig(v: unknown): string | null {
162
196
  if (v === undefined || v === null) return null;
163
197
  const cfg = record(v);
164
198
  if (!cfg) return 'agent_client 必须是对象';
165
- const known = new Set(['enabled', 'instructions', 'active_tool_limit']);
199
+ const known = new Set(['enabled', 'instructions', 'active_tool_limit', 'system_info']);
166
200
  const unknown = Object.keys(cfg).filter((key) => !known.has(key));
167
201
  if (unknown.length) return `agent_client 包含未声明字段: ${unknown.join(',')}`;
168
202
  if (cfg.enabled !== undefined && typeof cfg.enabled !== 'boolean') return 'agent_client.enabled 必须是布尔值';
169
203
  if (cfg.instructions !== undefined && (typeof cfg.instructions !== 'string' || cfg.instructions.length > 20_000)) {
170
204
  return 'agent_client.instructions 必须是最长 20000 字符的字符串';
171
205
  }
172
- return intInRange(cfg.active_tool_limit, 'agent_client.active_tool_limit', 1, 12);
206
+ return (cfg.system_info === undefined ? null : validateAgentSystemInfo(cfg.system_info))
207
+ ?? intInRange(cfg.active_tool_limit, 'agent_client.active_tool_limit', 1, 12);
173
208
  }
174
209
 
175
210
  export async function validateRouteConfig(input: Partial<Route>, deps: RouteConfigDeps, defaults: RouteConfigDefaults): Promise<string | null> {
@@ -205,6 +240,8 @@ export function normalizeRouteConfig(input: Partial<Route>, defaults: RouteConfi
205
240
  const targetConfig = normalizeTargetConfig(target, input.target_config);
206
241
  const sessionPolicy = (cleanString(input.session_policy) ?? 'new') as SessionPolicy;
207
242
  const tools = nonEmptyRecord(input.tools);
243
+ const agentClient = nonEmptyRecord(input.agent_client);
244
+ const systemInfo = routeAgentSystemInfo(input);
208
245
  return {
209
246
  route_key: routeKey,
210
247
  name: cleanString(input.name) ?? routeKey,
@@ -224,7 +261,7 @@ export function normalizeRouteConfig(input: Partial<Route>, defaults: RouteConfi
224
261
  tools,
225
262
  audience: normalizeAudiencePolicy(input.audience),
226
263
  memory: nonEmptyRecord(input.memory),
227
- agent_client: nonEmptyRecord(input.agent_client) as Route['agent_client'],
264
+ agent_client: agentClient ? { ...agentClient, ...(systemInfo ? { system_info: systemInfo } : {}) } as Route['agent_client'] : undefined,
228
265
  budget: nonEmptyRecord(input.budget),
229
266
  description: input.description,
230
267
  };
@@ -237,10 +274,12 @@ export function routeAgentClientConfig(route: Pick<Route, 'agent_client' | 'tool
237
274
  const enabled = raw?.enabled === false ? false : raw?.enabled === true || direct?.enabled === true;
238
275
  if (!enabled) return null;
239
276
  const instructions = typeof raw?.instructions === 'string' ? raw.instructions.trim().slice(0, 20_000) : '';
277
+ const systemInfo = routeAgentSystemInfo(route);
240
278
  return {
241
279
  enabled: true,
242
280
  ...(instructions ? { instructions } : {}),
243
281
  active_tool_limit: intValue(raw?.active_tool_limit, 8, 1, 12),
282
+ ...(systemInfo ? { system_info: systemInfo } : {}),
244
283
  };
245
284
  }
246
285
 
@@ -0,0 +1,19 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { agentSubjectDisplayView, readAgentSubjectDisplay, validateAgentSubjectDisplay } from './agent-subject-display';
4
+
5
+ test('subject display is bounded presentation, with explicit missing and no identity inference', () => {
6
+ assert.deepEqual(validateAgentSubjectDisplay({ name: ' Workspace North ' }), { ok: true, value: { name: 'Workspace North' } });
7
+ assert.deepEqual(agentSubjectDisplayView(undefined), { subject_display: null, subject_display_status: 'missing' });
8
+ assert.deepEqual(agentSubjectDisplayView({ name: 'Company A' }), { subject_display: { name: 'Company A' }, subject_display_status: 'provided' });
9
+ assert.deepEqual(readAgentSubjectDisplay('{"name":"Account A"}'), { name: 'Account A' });
10
+ assert.equal(validateAgentSubjectDisplay({ name: '😀'.repeat(60) }).ok, true);
11
+ assert.equal(validateAgentSubjectDisplay({ name: '😀'.repeat(61) }).ok, false);
12
+ for (const invalid of [{ name: '' }, { name: ' ' }, { name: 7 }, { tenant: 'Account A' }, { name: 'A', secret: 'redacted' },
13
+ { name: 'A', id: 'identity' }, ['Account A'], 'Account A', { name: 'A'.repeat(121) },
14
+ ...['\n', '\t', '\u0000', '\u007f', '\u0085', '\u009f', '\u2028', '\u2029', '\ud800', '\udc00'].map((c) => ({ name: c + 'A' }))]) {
15
+ assert.equal(validateAgentSubjectDisplay(invalid).ok, false);
16
+ assert.deepEqual(agentSubjectDisplayView(invalid), { subject_display: null, subject_display_status: 'missing' });
17
+ }
18
+ assert.equal(readAgentSubjectDisplay('{invalid'), null);
19
+ });
@@ -0,0 +1,36 @@
1
+ import type { AgentSubjectDisplay } from './types';
2
+
3
+ export type SubjectDisplayValidation =
4
+ | { ok: true; value: AgentSubjectDisplay | null }
5
+ | { ok: false };
6
+
7
+ /** A bounded presentation label, treated as data rather than identity or instructions. */
8
+ export function validateAgentSubjectDisplay(value: unknown): SubjectDisplayValidation {
9
+ if (value === null || value === undefined) return { ok: true, value: null };
10
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false };
11
+ const record = value as Record<string, unknown>;
12
+ if (Object.keys(record).length !== 1 || typeof record.name !== 'string') return { ok: false };
13
+ const name = record.name.trim();
14
+ // Check controls before trimming so a tab/newline is not silently accepted.
15
+ if (!name || name.length > 120 || /[\u0000-\u001f\u007f-\u009f\u2028\u2029\ud800-\udfff]/u.test(record.name)) return { ok: false };
16
+ return { ok: true, value: { name } };
17
+ }
18
+
19
+ /** Old/malformed presentation data must not break an otherwise valid authorization. */
20
+ export function readAgentSubjectDisplay(value: unknown): AgentSubjectDisplay | null {
21
+ let decoded = value;
22
+ if (typeof value === 'string') {
23
+ try { decoded = JSON.parse(value) as unknown; }
24
+ catch { return null; }
25
+ }
26
+ const checked = validateAgentSubjectDisplay(decoded);
27
+ return checked.ok ? checked.value : null;
28
+ }
29
+
30
+ export function agentSubjectDisplayView(value: unknown): {
31
+ subject_display: AgentSubjectDisplay | null;
32
+ subject_display_status: 'provided' | 'missing';
33
+ } {
34
+ const display = readAgentSubjectDisplay(value);
35
+ return { subject_display: display, subject_display_status: display ? 'provided' : 'missing' };
36
+ }
@@ -137,6 +137,11 @@ export interface Client {
137
137
  last_used_at?: string;
138
138
  }
139
139
 
140
+ /** Business-supplied presentation only; never a principal, routing or deduplication key. */
141
+ export interface AgentSubjectDisplay {
142
+ name: string;
143
+ }
144
+
140
145
  /** 业务后端在 Agent 授权时提交的可信业务主体。 */
141
146
  export interface AgentBusinessPrincipal {
142
147
  id: string;
@@ -154,6 +159,7 @@ export interface AgentSession {
154
159
  session_id: string;
155
160
  client_app_id: string;
156
161
  device_label: string;
162
+ subject_display?: AgentSubjectDisplay | null;
157
163
  principal: AgentBusinessPrincipal;
158
164
  on_behalf_of: string;
159
165
  allowed_routes: string[];
@@ -255,6 +261,14 @@ export interface ExecutorCapabilities {
255
261
  labels?: string[]; // 部署方自定义标签(可选,便于人识别这台机器的角色)
256
262
  }
257
263
 
264
+ /** 受控产品定位。仅作为描述数据,不授予能力,也不作为模型系统指令。 */
265
+ export interface AgentSystemInfo {
266
+ name: string;
267
+ summary: string;
268
+ domains: string[];
269
+ boundaries: string[];
270
+ }
271
+
258
272
  /** 触发路由:某业务场景 → 发给哪个 target / 哪个项目 / 哪个会话策略 / 哪个能力档 */
259
273
  export interface Route {
260
274
  route_key: string;
@@ -286,6 +300,7 @@ export interface Route {
286
300
  enabled?: boolean;
287
301
  instructions?: string;
288
302
  active_tool_limit?: number;
303
+ system_info?: AgentSystemInfo;
289
304
  };
290
305
  budget?: Record<string, unknown>; // 成本预算闸:{window/window_hours, hard_cost_usd?, hard_tokens?, ...}
291
306
  description?: string;
@@ -1,6 +1,6 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import test from 'node:test';
3
- import { ConversationAuditError, parseCreateConversationAudit, parseConversationAuditEvents } from './agent-conversation-audit';
3
+ import { ConversationAuditError, parseCreateConversationAudit, parseCreateCrossBindingConversationAudit, parseConversationAuditEvents } from './agent-conversation-audit';
4
4
  import { conversationAuditFixture, AUDIT_SESSION_A } from '../../test-support/agent-conversation-audit-fixture';
5
5
 
6
6
  test('visible text preserves original characters and refuses undeclared reasoning or identity fields', () => {
@@ -36,3 +36,21 @@ test('event batches enforce continuity, unique ids and explicit byte or total-ev
36
36
  Array.from({ length: 5 }, (_, index) => ({ ...event, event_id: `large-${index}`, sequence: index + 1, content: 'a'.repeat(64_000) })),
37
37
  ]) assert.throws(() => parseConversationAuditEvents({ events: batch }), (error: unknown) => error instanceof ConversationAuditError && error.code === 'conversation_audit_limit' && error.statusCode === 413);
38
38
  });
39
+
40
+ test('cross-binding membership is explicit, canonical and cannot reuse one Session for two routes', () => {
41
+ const fx = conversationAuditFixture({ crossBinding: true });
42
+ const input = fx.crossInput();
43
+ assert.deepEqual(parseCreateCrossBindingConversationAudit({ ...input, members: [...input.members].reverse() }), input);
44
+ for (const patch of [
45
+ { schema: 'bailing.agent-conversation-audit-create.v1' },
46
+ { route: 'orders' }, { hub_url: 'https://other-hub.example.com' },
47
+ { member_session_ids: [AUDIT_SESSION_A] }, { members: [] },
48
+ { members: [input.members[0], { ...input.members[0], route: 'inventory' }] },
49
+ { members: [{ ...input.members[0], client_app_id: 'WRONG_CASE' }] },
50
+ { members: [{ ...input.members[0], route: 'auto' }] },
51
+ { members: [{ ...input.members[0], label: 'x'.repeat(129) }] },
52
+ { members: [{ ...input.members[0], access_token: 'never permitted' }] },
53
+ ]) assert.throws(() => parseCreateCrossBindingConversationAudit({ ...input, ...patch }),
54
+ (error: unknown) => error instanceof ConversationAuditError && error.statusCode === 400);
55
+ assert.throws(() => parseCreateConversationAudit(input), 'old v1 must never infer a wider membership');
56
+ });
@@ -6,6 +6,9 @@ import { audienceAllows } from './identity-runtime';
6
6
 
7
7
  export const CONVERSATION_AUDIT_SCHEMA = 'bailing.agent-conversation-audit.v1';
8
8
  export const CONVERSATION_AUDIT_ACK_SCHEMA = 'bailing.agent-conversation-audit-ack.v1';
9
+ export const CONVERSATION_AUDIT_CREATE_V2_SCHEMA = 'bailing.agent-conversation-audit-create.v2';
10
+ export const CONVERSATION_AUDIT_CAPABILITIES_SCHEMA = 'bailing.agent-conversation-audit-capabilities.v1';
11
+ export const CONVERSATION_AUDIT_MEMBER_BINDINGS = 'session-client-route.v1';
9
12
  export const CONVERSATION_AUDIT_MAX_EVENTS = 20_000;
10
13
  export const CONVERSATION_AUDIT_MAX_BYTES = 16 * 1024 * 1024;
11
14
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -24,6 +27,7 @@ export function auditError(code = 'conversation_audit_conflict', status = 409):
24
27
  ? 'The conversation audit is unavailable for this identity.'
25
28
  : status === 403 ? 'The frozen conversation authorization is no longer valid.'
26
29
  : status === 413 ? 'The conversation audit limit was exceeded; no events were truncated or saved.'
30
+ : status === 503 ? 'The conversation audit capability is unavailable.'
27
31
  : 'The conversation audit request conflicts with its frozen membership or event history.');
28
32
  }
29
33
 
@@ -85,6 +89,41 @@ export function parseCreateConversationAudit(value: unknown): CreateConversation
85
89
  };
86
90
  }
87
91
 
92
+ export interface ConversationAuditMemberBindingInput {
93
+ session_id: string;
94
+ client_app_id: string;
95
+ route: string;
96
+ label?: string;
97
+ }
98
+
99
+ export interface CreateCrossBindingConversationAuditInput {
100
+ schema: typeof CONVERSATION_AUDIT_CREATE_V2_SCHEMA;
101
+ client_archive_id: string;
102
+ client_conversation_id: string;
103
+ members: ConversationAuditMemberBindingInput[];
104
+ }
105
+
106
+ /** Explicit opt-in: v1 callers never acquire cross-client or cross-route scope. */
107
+ export function parseCreateCrossBindingConversationAudit(value: unknown): CreateCrossBindingConversationAuditInput {
108
+ fields(value, ['schema', 'client_archive_id', 'client_conversation_id', 'members']);
109
+ if (value.schema !== CONVERSATION_AUDIT_CREATE_V2_SCHEMA || !Array.isArray(value.members) ||
110
+ value.members.length < 1 || value.members.length > 64) invalid();
111
+ const members = value.members.map((raw): ConversationAuditMemberBindingInput => {
112
+ fields(raw, ['session_id', 'client_app_id', 'route'], ['label']);
113
+ if (typeof raw.client_app_id !== 'string' || !/^[a-z0-9][a-z0-9_-]{1,63}$/.test(raw.client_app_id) ||
114
+ typeof raw.route !== 'string' || !/^[a-z0-9][a-z0-9_-]{1,63}$/.test(raw.route) || raw.route === 'auto') invalid();
115
+ return {
116
+ session_id: auditUuid(raw.session_id), client_app_id: raw.client_app_id, route: raw.route,
117
+ ...(raw.label !== undefined ? { label: text(raw.label, 128) } : {}),
118
+ };
119
+ }).sort((a, b) => a.session_id.localeCompare(b.session_id));
120
+ // One session cannot identify two targets, even if both routes are permitted.
121
+ if (new Set(members.map((member) => member.session_id)).size !== members.length) invalid();
122
+ return { schema: CONVERSATION_AUDIT_CREATE_V2_SCHEMA,
123
+ client_archive_id: auditUuid(value.client_archive_id),
124
+ client_conversation_id: identifier(value.client_conversation_id), members };
125
+ }
126
+
88
127
  export type ConversationAuditEventKind = 'turn_start' | 'user_message' | 'assistant_message' | 'run_link' | 'turn_end';
89
128
  export type ConversationAuditTurnStatus = 'running' | 'completed' | 'failed' | 'cancelled';
90
129
  export interface ConversationAuditEventInput {
@@ -0,0 +1,120 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import type { Pool } from 'mysql2/promise';
4
+ import { AgentAuthRepository } from './config-agent-auth-repository';
5
+ import { evaluateBusinessSessionQuery } from '../../test-support/agent-auth-business-query-fixture';
6
+
7
+ type Row = Record<string, any>;
8
+ const APP = 'example-business';
9
+ const OTHER_APP = 'other-business';
10
+ const sessionId = (n: number) => `123e4567-e89b-42d3-a456-${String(n).padStart(12, '0')}`;
11
+ const authorizationId = (n: number) => `223e4567-e89b-42d3-a456-${String(n).padStart(12, '0')}`;
12
+ function session(n: number, overrides: Row = {}): Row {
13
+ return {
14
+ session_id: sessionId(n), client_app_id: APP, device_label: 'Synthetic device',
15
+ principal_json: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'], audience: 'internal', channel: 'browser', private_secret: 'DO_NOT_RETURN_PRINCIPAL_SECRET' },
16
+ on_behalf_of: 'tenant-2:user-7', allowed_routes: ['orders'],
17
+ access_token_hash: 'DO_NOT_RETURN_ACCESS_HASH', refresh_token: 'DO_NOT_RETURN_REFRESH_TOKEN',
18
+ access_expires_at: '2000-01-01 00:00:00', refresh_expires_at: '2099-01-30 00:00:00',
19
+ created_at: '2026-09-09 08:00:00', updated_at: '2026-09-09 08:00:00', last_seen_at: null, revoked_at: null,
20
+ ...overrides,
21
+ };
22
+ }
23
+
24
+ /** In-memory evaluator for the narrow generated SELECT surface, not a live DB. */
25
+ function queryFixture(seed: Row[], authorizations: Row[] = []) {
26
+ const sessions = structuredClone(seed);
27
+ const queries: Array<{ sql: string; params: unknown[] }> = [];
28
+ const pool = { async query(sql: string, params: unknown[] = []) {
29
+ queries.push({ sql, params });
30
+ return evaluateBusinessSessionQuery(sessions, authorizations, sql, params);
31
+ } } as unknown as Pool;
32
+ return { repo: new AgentAuthRepository(() => pool), sessions, queries };
33
+ }
34
+
35
+ test('business Session detail is App-scoped and returns a principal field whitelist without token material', async () => {
36
+ const fx = queryFixture([session(1), session(2, { client_app_id: OTHER_APP })], [
37
+ { authorization_id: authorizationId(1), session_id: sessionId(1), client_app_id: APP, status: 'consumed' },
38
+ ]);
39
+ const detail = (await fx.repo.getBusinessSession(APP, sessionId(1)))!;
40
+ assert.equal(detail.authorization_id, authorizationId(1));
41
+ assert.equal(detail.state, 'active', 'access expiry alone does not end the absolute refresh lifetime');
42
+ assert.deepEqual(detail.principal, { id: 'user-7', tenant: 'tenant-2', roles: ['manager'], audience: 'internal', channel: 'browser' });
43
+ assert.doesNotMatch(JSON.stringify(detail), /DO_NOT_RETURN|private_secret|token_hash|refresh_token|cursor_created_at/);
44
+ assert.equal(await fx.repo.getBusinessSession(APP, sessionId(2)), null);
45
+ assert.equal(await fx.repo.getBusinessSession(OTHER_APP, sessionId(1)), null);
46
+ await assert.rejects(fx.repo.getBusinessSession('', sessionId(1)), /authenticated Client App/);
47
+ });
48
+
49
+ test('business Session selectors combine exact authorization, subject and principal/tenant filters with AND', async () => {
50
+ const fx = queryFixture([
51
+ session(1), session(2, { on_behalf_of: 'tenant-2:User-7' }),
52
+ session(3, { principal_json: { id: 'User-7', tenant: 'tenant-2', roles: [] } }),
53
+ session(4, { principal_json: { id: 'user-7', tenant: 'tenant-3', roles: [] } }),
54
+ session(5, { client_app_id: OTHER_APP }),
55
+ ], [1, 2, 3, 4, 5].map((n) => ({ authorization_id: authorizationId(n), session_id: sessionId(n), client_app_id: n === 5 ? OTHER_APP : APP, status: 'consumed' })));
56
+ const input = { clientAppId: APP, authorizationId: authorizationId(1), onBehalfOf: 'tenant-2:user-7', principalId: 'user-7', tenant: 'tenant-2', state: 'active' as const, limit: 20 };
57
+ assert.deepEqual((await fx.repo.listBusinessSessions(input)).list.map((row) => row.session_id), [sessionId(1)]);
58
+ assert.deepEqual((await fx.repo.listBusinessSessions({ ...input, tenant: 'tenant-3' })).list, []);
59
+ assert.deepEqual((await fx.repo.listBusinessSessions({ ...input, authorizationId: authorizationId(5) })).list, []);
60
+ assert.deepEqual((await fx.repo.listBusinessSessions({ clientAppId: APP, onBehalfOf: 'tenant-2:User-7', limit: 20 })).list.map((row) => row.session_id), [sessionId(2)]);
61
+ assert.match(fx.queries[0]!.sql, /matched\.client_app_id=s\.client_app_id/);
62
+ assert.match(fx.queries[0]!.sql, /BINARY s\.on_behalf_of=BINARY \?/);
63
+ assert.doesNotMatch(JSON.stringify((await fx.repo.listBusinessSessions({ clientAppId: APP, limit: 20 })).list), /DO_NOT_RETURN|private_secret/);
64
+ });
65
+
66
+ test('tenant absence is explicit and Session status distinguishes expiry, revocation and refreshable access', async () => {
67
+ const fx = queryFixture([
68
+ session(1, { principal_json: { id: 'user-7', roles: [] } }),
69
+ session(2, { principal_json: { id: 'user-7', tenant: '', roles: [] } }),
70
+ session(3, { principal_json: { id: 'user-7', tenant: null, roles: [] } }),
71
+ session(4), session(5, { refresh_expires_at: '2000-01-01 00:00:00' }),
72
+ session(6, { revoked_at: '2026-09-09 08:00:00' }),
73
+ ]);
74
+ assert.deepEqual((await fx.repo.listBusinessSessions({ clientAppId: APP, tenant: '', limit: 20 })).list.map((row) => row.session_id), [3, 2, 1].map(sessionId));
75
+ assert.equal((await fx.repo.listBusinessSessions({ clientAppId: APP, limit: 20 })).list.length, 6);
76
+ assert.deepEqual((await fx.repo.listBusinessSessions({ clientAppId: APP, state: 'expired', limit: 20 })).list.map((row) => row.state), ['expired']);
77
+ assert.deepEqual((await fx.repo.listBusinessSessions({ clientAppId: APP, state: 'revoked', limit: 20 })).list.map((row) => row.state), ['revoked']);
78
+ assert.equal((await fx.repo.listBusinessSessions({ clientAppId: APP, state: 'active', limit: 20 })).list.length, 4);
79
+ });
80
+
81
+ test('keyset pages preserve identical timestamps and remain stable when earlier active Sessions are revoked', async () => {
82
+ const fx = queryFixture([session(1), session(2), session(3), session(4)]);
83
+ const input = { clientAppId: APP, state: 'active' as const, limit: 2 };
84
+ const first = await fx.repo.listBusinessSessions(input);
85
+ assert.deepEqual(first.list.map((row) => row.session_id), [4, 3].map(sessionId));
86
+ assert.deepEqual(first.nextCursor, { createdAt: '2026-09-09T08:00:00.000Z', sessionId: sessionId(3) });
87
+ for (const row of fx.sessions.filter((item) => [sessionId(3), sessionId(4)].includes(item.session_id))) row.revoked_at = '2026-09-09 09:00:00';
88
+ const second = await fx.repo.listBusinessSessions({ ...input, cursor: first.nextCursor });
89
+ assert.deepEqual(second.list.map((row) => row.session_id), [2, 1].map(sessionId));
90
+ assert.equal(second.nextCursor, undefined);
91
+ assert.equal(fx.queries[0]!.params.at(-1), 3, 'the repository fetches limit+1');
92
+ await fx.repo.listBusinessSessions({ clientAppId: APP, limit: 999 });
93
+ assert.equal(fx.queries.at(-1)!.params.at(-1), 101);
94
+ });
95
+
96
+ test('duplicate or cross-App authorization links do not duplicate Session rows or invent an unambiguous mapping', async () => {
97
+ const fx = queryFixture([session(1), session(2)], [
98
+ { authorization_id: authorizationId(1), session_id: sessionId(1), client_app_id: APP, status: 'consumed' },
99
+ { authorization_id: authorizationId(2), session_id: sessionId(1), client_app_id: APP, status: 'consumed' },
100
+ { authorization_id: authorizationId(3), session_id: sessionId(2), client_app_id: OTHER_APP, status: 'consumed' },
101
+ ]);
102
+ const page = await fx.repo.listBusinessSessions({ clientAppId: APP, limit: 20 });
103
+ assert.equal(page.list.length, 2);
104
+ assert.ok(page.list.every((row) => !Object.hasOwn(row, 'authorization_id')));
105
+ assert.equal((await fx.repo.listBusinessSessions({ clientAppId: APP, authorizationId: authorizationId(1), limit: 20 })).list.length, 1);
106
+ assert.equal((await fx.repo.listBusinessSessions({ clientAppId: APP, authorizationId: authorizationId(3), limit: 20 })).list.length, 0);
107
+ assert.match(fx.queries[0]!.sql, /CASE WHEN COUNT\(\*\)=1 THEN MIN\(a\.authorization_id\) ELSE NULL END/);
108
+ });
109
+
110
+ test('authorization projections include consumed Session mapping while code/token hashes remain internal', async () => {
111
+ const row = {
112
+ authorization_id: authorizationId(1), client_app_id: APP, redirect_uri: 'http://127.0.0.1:43123/callback', state_value: 'synthetic-state',
113
+ requested_routes: ['orders'], device_label: 'Synthetic device', code_challenge: 'c'.repeat(43),
114
+ status: 'consumed', session_id: sessionId(1), created_at: '2026-09-09 08:00:00', expires_at: '2026-09-09 08:10:00', code_hash: 'DO_NOT_RETURN_CODE_HASH',
115
+ };
116
+ const pool = { query: async () => [[row], []] } as unknown as Pool;
117
+ const result = await new AgentAuthRepository(() => pool).getAuthorization(authorizationId(1));
118
+ assert.equal(result?.session_id, sessionId(1));
119
+ assert.doesNotMatch(JSON.stringify(result), /DO_NOT_RETURN|code_hash/);
120
+ });