bailinghub 0.6.1 → 0.8.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 (229) hide show
  1. package/README.en.md +8 -7
  2. package/README.md +7 -7
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
  9. package/docs/AGENT_CLIENT_RUNTIME_API.md +38 -1
  10. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  11. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  12. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  13. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  14. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  15. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  16. package/docs/AGENT_TASK_CONTROL.en.md +25 -0
  17. package/docs/AGENT_TASK_CONTROL.md +94 -0
  18. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
  19. package/docs/CHANGELOG.en.md +24 -1
  20. package/docs/CHANGELOG.md +24 -1
  21. package/docs/COMPATIBILITY.en.md +2 -0
  22. package/docs/CONTRACT.en.md +2 -0
  23. package/docs/CONTRACT.md +2 -0
  24. package/docs/GENERATED_ARTIFACTS.en.md +46 -0
  25. package/docs/GENERATED_ARTIFACTS.md +108 -0
  26. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  27. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  28. package/docs/INVOCATION_RECEIPTS.md +111 -0
  29. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  30. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  31. package/docs/README.en.md +9 -0
  32. package/docs/README.md +9 -0
  33. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  34. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  35. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  36. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  37. package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
  38. package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
  39. package/docs/SDK.en.md +31 -0
  40. package/docs/TOOL_RATE_LIMITS.md +50 -0
  41. package/docs/UPGRADE_v0.8.0.en.md +71 -0
  42. package/docs/UPGRADE_v0.8.0.md +73 -0
  43. package/docs/user-guide/conversations.en.md +4 -2
  44. package/docs/user-guide/conversations.md +4 -2
  45. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
  46. package/package.json +1 -1
  47. package/schemas/config/route.schema.json +16 -2
  48. package/schemas/config/tool-provider.schema.json +2 -1
  49. package/scripts/check-doc-links.mjs +2 -0
  50. package/scripts/check-image-tags.sh +1 -1
  51. package/scripts/check-release-consistency.test.mjs +2 -2
  52. package/scripts/e2e-console.mjs +32 -2
  53. package/scripts/install.sh +1 -1
  54. package/scripts/publish-images.sh +1 -1
  55. package/scripts/release-audit.mjs +2 -0
  56. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  57. package/scripts/sdk-runtime-test.mjs +5 -2
  58. package/scripts/verify-github-repo.mjs +2 -0
  59. package/sdk/php/README.md +29 -0
  60. package/sdk/php/src/AgentAuth.php +100 -4
  61. package/sdk/php/src/HubClient.php +2 -1
  62. package/sdk/php7/README.md +31 -0
  63. package/sdk/php7/src/AgentAuth.php +99 -4
  64. package/sdk/php7/src/HubClient.php +2 -1
  65. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  66. package/sql/059_agent_subject_display.sql +5 -0
  67. package/sql/060_agent_artifacts.sql +11 -0
  68. package/sql/061_tool_rate_limit_policies.sql +3 -0
  69. package/sql/062_agent_task_control.sql +92 -0
  70. package/sql/README.en.md +15 -0
  71. package/sql/README.md +25 -0
  72. package/src/adapters/storage/object-storage.ts +15 -3
  73. package/src/adapters/storage/oss-signature.test.ts +40 -0
  74. package/src/adapters/storage/oss-signature.ts +21 -0
  75. package/src/app/agent-artifacts.test.ts +165 -0
  76. package/src/app/agent-artifacts.ts +85 -0
  77. package/src/app/agent-client-runtime.test.ts +76 -1
  78. package/src/app/agent-client-runtime.ts +13 -0
  79. package/src/app/agent-conversation-audit.ts +20 -0
  80. package/src/app/agent-invocation-snapshot.ts +35 -0
  81. package/src/app/agent-system-info.ts +41 -0
  82. package/src/app/agent-task-control.ts +187 -0
  83. package/src/app/agent-task-runtime.ts +68 -0
  84. package/src/app/agent-tool-invocations.test.ts +329 -1
  85. package/src/app/agent-tool-invocations.ts +239 -14
  86. package/src/app/agent-tool-job.test.ts +11 -1
  87. package/src/app/agent-tool-job.ts +8 -1
  88. package/src/app/builtin-tools.ts +4 -0
  89. package/src/app/oss-edition.ts +1 -0
  90. package/src/app/tool-approvals.ts +4 -0
  91. package/src/app/tool-assembly.ts +5 -0
  92. package/src/core/config/agent-setup.ts +37 -0
  93. package/src/core/config/artifact-config.ts +15 -0
  94. package/src/core/config/client-agent-setup.ts +25 -0
  95. package/src/core/config/config-codec.ts +3 -1
  96. package/src/core/config/config-models.ts +11 -1
  97. package/src/core/config/config-schema.test.ts +11 -0
  98. package/src/core/config/route-config.test.ts +28 -0
  99. package/src/core/config/route-config.ts +44 -4
  100. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  101. package/src/core/contracts/agent-subject-display.ts +36 -0
  102. package/src/core/contracts/tool-rate-limits.test.ts +59 -0
  103. package/src/core/contracts/tool-rate-limits.ts +48 -0
  104. package/src/core/contracts/tools.ts +122 -43
  105. package/src/core/contracts/types.ts +18 -1
  106. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  107. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  108. package/src/core/runtime/agent-task-control.test.ts +114 -0
  109. package/src/core/runtime/agent-task-control.ts +227 -0
  110. package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
  111. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  112. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  113. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  114. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  115. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
  116. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  117. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  118. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  119. package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
  120. package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
  121. package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
  122. package/src/infrastructure/config/config-client-repository.ts +21 -0
  123. package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
  124. package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
  125. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  126. package/src/infrastructure/config/config-route-repository.ts +24 -0
  127. package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
  128. package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
  129. package/src/infrastructure/config/configstore.ts +16 -4
  130. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  131. package/src/routes/admin-access.ts +37 -0
  132. package/src/routes/admin-agent-clients.ts +11 -0
  133. package/src/routes/admin-agent-setup.test.ts +130 -0
  134. package/src/routes/admin-agent-setup.ts +68 -0
  135. package/src/routes/admin-agent-tasks.ts +32 -0
  136. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  137. package/src/routes/admin-dispatch-config.ts +2 -0
  138. package/src/routes/admin-tool-providers.test.ts +22 -0
  139. package/src/routes/admin-tool-providers.ts +9 -1
  140. package/src/routes/admin.ts +3 -0
  141. package/src/routes/agent-api.test.ts +76 -0
  142. package/src/routes/agent-api.ts +49 -1
  143. package/src/routes/agent-artifacts.ts +29 -0
  144. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  145. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  146. package/src/routes/agent-auth.test.ts +1 -1
  147. package/src/routes/agent-auth.ts +206 -16
  148. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  149. package/src/routes/agent-conversation-audit.ts +8 -2
  150. package/src/routes/agent-subject-display-http.test.ts +145 -0
  151. package/src/routes/agent-system-info.test.ts +132 -0
  152. package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
  153. package/src/routes/private.ts +1 -0
  154. package/src/routes/run.ts +2 -1
  155. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  156. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  157. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  158. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  159. package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
  160. package/web/connect/bailing-connect-php.tgz +0 -0
  161. package/web/connect/bailing-connect-php7.tgz +0 -0
  162. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-BRCR3O0P.js} +1 -1
  163. package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
  164. package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
  165. package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
  166. package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
  167. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-BIbZvInm.js} +1 -1
  168. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-KyPSmBdZ.js} +1 -1
  169. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-Sv5DU2G6.js} +1 -1
  170. package/web/console/assets/{Channels-CApxH2TB.js → Channels-B9n4fbxg.js} +1 -1
  171. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-xsOCUXi_.js} +1 -1
  172. package/web/console/assets/Clients-CI3DBDHf.js +3 -0
  173. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  174. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-JgNXQPlN.js} +1 -1
  175. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-B5UUUdt0.js} +1 -1
  176. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-BMGciWQb.js} +1 -1
  177. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CRbboOCZ.js} +1 -1
  178. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-CgLNGjRp.js} +1 -1
  179. package/web/console/assets/{Login-DiTjPWmN.js → Login-C52JmXzx.js} +1 -1
  180. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-CDOvHPVS.js} +1 -1
  181. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  182. package/web/console/assets/Routes-X9vHLpKW.js +124 -0
  183. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  184. package/web/console/assets/Runs-DYNDXsqk.js +3 -0
  185. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-B91P6i1x.js} +1 -1
  186. package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
  187. package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
  188. package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
  189. package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
  190. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-B7Mqj3k1.js} +1 -1
  191. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-Db93b6dc.js} +1 -1
  192. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-CuuIYeZO.js} +1 -1
  193. package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
  194. package/web/console/assets/Tools-DU8ei6sd.css +1 -0
  195. package/web/console/assets/index-UGvfF3Xr.js +2 -0
  196. package/web/console/assets/{request-r7GHVJzw.js → request-DeGya810.js} +1 -1
  197. package/web/console/assets/{schema-BVn_hB7M.js → schema-BqlqLw1R.js} +1 -1
  198. package/web/console/index.html +1 -1
  199. package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
  200. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  201. package/web-admin/src/components/AgentSetupPanel.vue +275 -0
  202. package/web-admin/src/components/ClientConversations.vue +21 -4
  203. package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
  204. package/web-admin/src/components/conversation-audit.ts +20 -0
  205. package/web-admin/src/layout/Shell.vue +1 -1
  206. package/web-admin/src/pages/AgentClients.vue +99 -23
  207. package/web-admin/src/pages/AgentTasks.vue +281 -0
  208. package/web-admin/src/pages/Clients.vue +4 -1
  209. package/web-admin/src/pages/Routes.vue +10 -1
  210. package/web-admin/src/pages/StorageBuckets.vue +6 -6
  211. package/web-admin/src/pages/Tools.vue +53 -4
  212. package/web-admin/src/router.ts +2 -0
  213. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  214. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  215. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  216. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  217. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  218. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  219. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  220. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  221. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  222. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
  223. package/web/console/assets/Shell-BEqpONiy.js +0 -1
  224. package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
  225. package/web/console/assets/StorageBuckets-CkORbYXY.js +0 -1
  226. package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
  227. package/web/console/assets/Tools-A20oaMaQ.css +0 -1
  228. package/web/console/assets/Tools-CIHInlHL.js +0 -2
  229. package/web/console/assets/index-BkLbd7Cc.js +0 -2
@@ -1,3 +1,4 @@
1
+ import { normalizeToolRateLimitPolicies } from '../contracts/tool-rate-limits';
1
2
  import type { PageRule } from '../platform/pagecontext';
2
3
  import type { AlertRule, Channel, ChatEntry, Client, Credential, ExecutorToken, ProjectReg, Route, StorageBucket, TargetDef, ToolApproval, ToolProvider, TraceSeverity, TraceStage } from '../contracts/types';
3
4
 
@@ -155,6 +156,7 @@ export function rowToolProvider(r: any): ToolProvider {
155
156
  : undefined;
156
157
  return {
157
158
  name: r.name, base_url: r.base_url,
159
+ tool_rate_limits: r.tool_rate_limits_json ? normalizeToolRateLimitPolicies(parseOptionalJson(r.tool_rate_limits_json)) : undefined,
158
160
  spec_source: specSource,
159
161
  spec_access_policy: specAccessPolicy,
160
162
  spec_url: r.spec_url ?? undefined, spec_json: r.spec_json ?? undefined,
@@ -189,7 +191,7 @@ export function rowCredential(r: any): Credential {
189
191
 
190
192
  export function rowStorageBucket(r: any): StorageBucket {
191
193
  return {
192
- name: r.name, kind: (r.kind === 'oss' ? 'oss' : r.kind === 's3' ? 's3' : 'cos'),
194
+ name: r.name, kind: (r.kind === 'local' ? 'local' : r.kind === 'oss' ? 'oss' : r.kind === 's3' ? 's3' : 'cos'),
193
195
  region: r.region ?? '', bucket: r.bucket, endpoint: r.endpoint ?? undefined,
194
196
  access_key: r.access_key, secret_key: r.secret_key,
195
197
  public_base_url: r.public_base_url ?? '', path_prefix: r.path_prefix ?? 'bailing/chat',
@@ -1,3 +1,4 @@
1
+ import { normalizeToolRateLimitPolicies } from '../contracts/tool-rate-limits';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { validateBudgetPolicy } from '../runtime/budget-runtime';
3
4
  import type { PageRule } from '../platform/pagecontext';
@@ -147,6 +148,7 @@ export function prepareStorageBucketConfig(input: Partial<StorageBucket>): Prepa
147
148
  const publicBaseUrl = str(input.public_base_url).replace(/\/+$/, '');
148
149
  if (kind !== 'local' && !publicBaseUrl) return fail('公开访问域名 public_base_url 必填(拼最终媒体 URL 用)');
149
150
  const region = str(input.region);
151
+ if (kind === 'oss' && !region) return fail('OSS 必须填地域 region(如 cn-shanghai)');
150
152
  if (kind === 'cos' && !region) return fail('COS 必须填地域 region(如 ap-shanghai)');
151
153
  return {
152
154
  ok: true,
@@ -372,6 +374,13 @@ export function prepareToolProviderConfig(
372
374
  : requestedSpecAccessPolicy
373
375
  ? requestedSpecAccessPolicy as ToolProvider['spec_access_policy']
374
376
  : old?.spec_source === 'url' ? oldSpecAccessPolicy : 'signed_required';
377
+ let toolRateLimits = old?.tool_rate_limits;
378
+ if (input.tool_rate_limits !== undefined) {
379
+ try { toolRateLimits = normalizeToolRateLimitPolicies(input.tool_rate_limits); }
380
+ catch (error) { return fail((error as Error).message); }
381
+ }
382
+ const providerLimit = Number(input.rate_limit_per_min ?? old?.rate_limit_per_min ?? 120);
383
+ if (!Number.isSafeInteger(providerLimit) || providerLimit < 0 || providerLimit > 1_000_000) return fail('工具源总限额需为 0–1000000 的整数,0=关闭');
375
384
  const autoRefreshMin = Math.min(Math.max(Number(input.auto_refresh_min ?? old?.auto_refresh_min ?? 0) || 0, 0), 1440);
376
385
  const enabled = input.enabled !== false;
377
386
 
@@ -423,7 +432,8 @@ export function prepareToolProviderConfig(
423
432
  secret,
424
433
  log_payload: input.log_payload !== false,
425
434
  timeout_ms: Math.min(Math.max(Number(input.timeout_ms ?? old?.timeout_ms ?? 10000) || 10000, 1000), 60000),
426
- rate_limit_per_min: Math.max(Number(input.rate_limit_per_min ?? old?.rate_limit_per_min ?? 120) || 0, 0),
435
+ rate_limit_per_min: providerLimit,
436
+ tool_rate_limits: toolRateLimits,
427
437
  auto_refresh_min: autoRefreshMin,
428
438
  enabled,
429
439
  description: optionalStr(input.description),
@@ -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,5 @@
1
- import type { Route, SessionPolicy, TargetKind } from '../contracts/types';
1
+ import { validateArtifactConfig } from './artifact-config';
2
+ import type { AgentSystemInfo, Route, SessionPolicy, TargetKind } from '../contracts/types';
2
3
  import { validateRouteToolsConfig, type ToolProviderExists } from './tools-config';
3
4
  import { normalizeTargetConfig, validateTargetConfig } from './target-config';
4
5
  import { validateBudgetPolicy } from '../runtime/budget-runtime';
@@ -45,6 +46,7 @@ export interface RouteAgentClientConfig {
45
46
  enabled: boolean;
46
47
  instructions?: string;
47
48
  active_tool_limit: number;
49
+ system_info?: AgentSystemInfo;
48
50
  }
49
51
 
50
52
  const SESSION_POLICIES: SessionPolicy[] = ['new', 'fixed', 'per_key', 'passthrough'];
@@ -158,18 +160,52 @@ function validateMemoryConfig(v: unknown): string | null {
158
160
  ?? intInRange(m.summary_max_chars, 'memory.summary_max_chars', 200, 8000);
159
161
  }
160
162
 
163
+ export function validateAgentSystemInfo(v: unknown): string | null {
164
+ const value = record(v);
165
+ const prefix = 'agent_client.system_info';
166
+ if (!value) return `${prefix} 必须是对象`;
167
+ const fields = ['name', 'summary', 'domains', 'boundaries'];
168
+ if (Object.keys(value).some((key) => !fields.includes(key))) return `${prefix} 包含未声明字段`;
169
+ for (const [key, maximum] of [['name', 120], ['summary', 400]] as const) {
170
+ const text = value[key];
171
+ if (typeof text !== 'string' || !text.trim() || text.length > maximum || /[\u0000-\u001f\u007f]/.test(text)) {
172
+ return `${prefix}.${key} 必须是 1..${maximum} 字符的非空单行字符串,不含控制字符`;
173
+ }
174
+ }
175
+ for (const [key, maximum] of [['domains', 120], ['boundaries', 160]] as const) {
176
+ const items = value[key];
177
+ if (!Array.isArray(items) || items.length > 6 || items.some((item) => typeof item !== 'string' || !item.trim() || item.length > maximum || /[\u0000-\u001f\u007f]/.test(item))) {
178
+ return `${prefix}.${key} 必须是最多 6 项的数组,每项为 1..${maximum} 字符的非空单行字符串,不含控制字符`;
179
+ }
180
+ }
181
+ return null;
182
+ }
183
+
184
+ /** Invalid stored metadata degrades to missing; it never becomes runtime instructions. */
185
+ export function routeAgentSystemInfo(route: Pick<Route, 'agent_client'>): AgentSystemInfo | null {
186
+ const value = record(record(route.agent_client)?.system_info);
187
+ if (!value || validateAgentSystemInfo(value)) return null;
188
+ return {
189
+ name: (value.name as string).trim(),
190
+ summary: (value.summary as string).trim(),
191
+ domains: (value.domains as string[]).map((item) => item.trim()),
192
+ boundaries: (value.boundaries as string[]).map((item) => item.trim()),
193
+ };
194
+ }
195
+
161
196
  function validateAgentClientConfig(v: unknown): string | null {
162
197
  if (v === undefined || v === null) return null;
163
198
  const cfg = record(v);
164
199
  if (!cfg) return 'agent_client 必须是对象';
165
- const known = new Set(['enabled', 'instructions', 'active_tool_limit']);
200
+ const known = new Set(['enabled', 'instructions', 'active_tool_limit', 'system_info', 'artifact_upload']);
166
201
  const unknown = Object.keys(cfg).filter((key) => !known.has(key));
167
202
  if (unknown.length) return `agent_client 包含未声明字段: ${unknown.join(',')}`;
168
203
  if (cfg.enabled !== undefined && typeof cfg.enabled !== 'boolean') return 'agent_client.enabled 必须是布尔值';
169
204
  if (cfg.instructions !== undefined && (typeof cfg.instructions !== 'string' || cfg.instructions.length > 20_000)) {
170
205
  return 'agent_client.instructions 必须是最长 20000 字符的字符串';
171
206
  }
172
- return intInRange(cfg.active_tool_limit, 'agent_client.active_tool_limit', 1, 12);
207
+ return validateArtifactConfig(cfg.artifact_upload) ?? (cfg.system_info === undefined ? null : validateAgentSystemInfo(cfg.system_info))
208
+ ?? intInRange(cfg.active_tool_limit, 'agent_client.active_tool_limit', 1, 12);
173
209
  }
174
210
 
175
211
  export async function validateRouteConfig(input: Partial<Route>, deps: RouteConfigDeps, defaults: RouteConfigDefaults): Promise<string | null> {
@@ -205,6 +241,8 @@ export function normalizeRouteConfig(input: Partial<Route>, defaults: RouteConfi
205
241
  const targetConfig = normalizeTargetConfig(target, input.target_config);
206
242
  const sessionPolicy = (cleanString(input.session_policy) ?? 'new') as SessionPolicy;
207
243
  const tools = nonEmptyRecord(input.tools);
244
+ const agentClient = nonEmptyRecord(input.agent_client);
245
+ const systemInfo = routeAgentSystemInfo(input);
208
246
  return {
209
247
  route_key: routeKey,
210
248
  name: cleanString(input.name) ?? routeKey,
@@ -224,7 +262,7 @@ export function normalizeRouteConfig(input: Partial<Route>, defaults: RouteConfi
224
262
  tools,
225
263
  audience: normalizeAudiencePolicy(input.audience),
226
264
  memory: nonEmptyRecord(input.memory),
227
- agent_client: nonEmptyRecord(input.agent_client) as Route['agent_client'],
265
+ agent_client: agentClient ? { ...agentClient, ...(systemInfo ? { system_info: systemInfo } : {}) } as Route['agent_client'] : undefined,
228
266
  budget: nonEmptyRecord(input.budget),
229
267
  description: input.description,
230
268
  };
@@ -237,10 +275,12 @@ export function routeAgentClientConfig(route: Pick<Route, 'agent_client' | 'tool
237
275
  const enabled = raw?.enabled === false ? false : raw?.enabled === true || direct?.enabled === true;
238
276
  if (!enabled) return null;
239
277
  const instructions = typeof raw?.instructions === 'string' ? raw.instructions.trim().slice(0, 20_000) : '';
278
+ const systemInfo = routeAgentSystemInfo(route);
240
279
  return {
241
280
  enabled: true,
242
281
  ...(instructions ? { instructions } : {}),
243
282
  active_tool_limit: intValue(raw?.active_tool_limit, 8, 1, 12),
283
+ ...(systemInfo ? { system_info: systemInfo } : {}),
244
284
  };
245
285
  }
246
286
 
@@ -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
+ }
@@ -0,0 +1,59 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { effectiveToolRateLimit, normalizeToolRateLimitPolicies } from './tool-rate-limits';
4
+ import { LocalSlidingWindowRateLimiter } from './tools';
5
+
6
+ test('120/hour permits a burst and remains occupied after one minute; windows expire exactly', () => {
7
+ let now = 0;
8
+ const limiter = new LocalSlidingWindowRateLimiter(() => now);
9
+ for (let n = 0; n < 120; n++) assert.equal(limiter.consume('tool:store:images', 120, 3600), false);
10
+ assert.equal(limiter.consume('tool:store:images', 120, 3600), true);
11
+ now = 60_001;
12
+ assert.equal(limiter.consume('tool:store:images', 120, 3600), true);
13
+ // A second user's different session still hits the same provider/tool bucket; a different provider does not.
14
+ assert.equal(limiter.consume('tool:another:images', 120, 3600), false);
15
+ now = 3_600_000;
16
+ assert.equal(limiter.consume('tool:store:images', 120, 3600), false);
17
+ });
18
+
19
+ test('all supported windows and disabled limits retain their original units', () => {
20
+ for (const windowSec of [1, 60, 3600, 86400]) {
21
+ let now = 0;
22
+ const limiter = new LocalSlidingWindowRateLimiter(() => now);
23
+ assert.equal(limiter.consume('tool', 2, windowSec), false);
24
+ assert.equal(limiter.consume('tool', 2, windowSec), false);
25
+ now = windowSec * 1000 - 1;
26
+ assert.deepEqual(limiter.consumeAll([{ bucket: 'tool', limit: 2, windowSec }]), { limited: true, bucket: 'tool', retryAfterMs: 1 });
27
+ now++;
28
+ assert.equal(limiter.consume('tool', 2, windowSec), false);
29
+ assert.equal(limiter.consume('tool', 0, windowSec), false);
30
+ }
31
+ });
32
+
33
+ test('rejecting either gate never burns quota in the other gate', () => {
34
+ for (const blocked of ['tool', 'provider']) {
35
+ const limiter = new LocalSlidingWindowRateLimiter(() => 0);
36
+ limiter.consume(blocked, 1);
37
+ const other = blocked === 'tool' ? 'provider' : 'tool';
38
+ for (let n = 0; n < 5; n++) assert.equal(limiter.consumeAll([
39
+ { bucket: 'tool', limit: 1, windowSec: 60 }, { bucket: 'provider', limit: 1, windowSec: 60 },
40
+ ]).limited, true);
41
+ assert.equal(limiter.consume(other, 1), false);
42
+ }
43
+ });
44
+
45
+ test('default, per-tool overrides and inheritance preserve raw declaration without changing it', () => {
46
+ const tool = { name: 'images_update', rateLimit: { count: 120, window: '1h' as const }, rateLimitPerMin: 2 };
47
+ const original = structuredClone(tool);
48
+ assert.equal(effectiveToolRateLimit(tool).window_sec, 3600);
49
+ const policies = normalizeToolRateLimitPolicies({ default: { mode: 'disabled' }, overrides: { images_update: { mode: 'inherit' } } });
50
+ assert.equal(effectiveToolRateLimit(tool, policies).count, 120);
51
+ assert.equal(effectiveToolRateLimit({ ...tool, name: 'another' }, policies).enabled, false);
52
+ policies.overrides.images_update = { mode: 'custom', count: 1000, window: '1m' };
53
+ assert.equal(effectiveToolRateLimit(tool, policies).count, 1000);
54
+ assert.deepEqual(tool, original);
55
+ for (const count of [0, -1, 1.5, '120', Infinity, 1000001]) {
56
+ assert.throws(() => normalizeToolRateLimitPolicies({ default: { mode: 'custom', count, window: '1h' } }));
57
+ }
58
+ assert.throws(() => normalizeToolRateLimitPolicies({ default: { mode: 'disabled', count: 120 } }));
59
+ });
@@ -0,0 +1,48 @@
1
+ import type { ToolDefinition, ToolRateLimitWindow } from './tool-definition';
2
+
3
+ export type ToolRateLimitPolicy = { mode: 'inherit' | 'disabled' } | { mode: 'custom'; count: number; window: ToolRateLimitWindow };
4
+ export interface ToolRateLimitPolicies {
5
+ default: ToolRateLimitPolicy;
6
+ overrides: Record<string, ToolRateLimitPolicy>;
7
+ }
8
+ export interface RateLimitRequest { bucket: string; limit: number; windowSec: number }
9
+ export interface RateLimitDecision { limited: boolean; bucket?: string; retryAfterMs?: number }
10
+ export const RATE_WINDOW_SECONDS = { '1s': 1, '1m': 60, '1h': 3600, '1d': 86400 } as const;
11
+
12
+ /** Omitted configuration preserves the published business declaration. Never rewrite the spec. */
13
+ export function normalizeToolRateLimitPolicies(raw: unknown): ToolRateLimitPolicies {
14
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('tool_rate_limits 必须是对象');
15
+ const value = raw as Record<string, unknown>;
16
+ if (Object.keys(value).some((key) => !['default', 'overrides'].includes(key))) throw new Error('tool_rate_limits 包含未知字段');
17
+ const policy = (v: unknown): ToolRateLimitPolicy => {
18
+ if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('单工具限额策略必须是对象');
19
+ const p = v as Record<string, unknown>;
20
+ if (p.mode === 'inherit' || p.mode === 'disabled') {
21
+ if (Object.keys(p).some((key) => key !== 'mode')) throw new Error('继承或关闭策略不应包含自定义限额');
22
+ return { mode: p.mode };
23
+ }
24
+ if (p.mode !== 'custom' || !Number.isSafeInteger(p.count) || Number(p.count) < 1 || Number(p.count) > 1_000_000
25
+ || typeof p.window !== 'string' || !Object.hasOwn(RATE_WINDOW_SECONDS, p.window)
26
+ || Object.keys(p).some((key) => !['mode', 'count', 'window'].includes(key))) {
27
+ throw new Error('自定义限额需为 1–1000000 的整数,窗口为 1s/1m/1h/1d');
28
+ }
29
+ return { mode: 'custom', count: Number(p.count), window: p.window as ToolRateLimitWindow };
30
+ };
31
+ const overrides = value.overrides ?? {};
32
+ if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides) || Object.keys(overrides).length > 1000) throw new Error('单工具覆盖最多 1000 项');
33
+ const entries = Object.entries(overrides).map(([name, v]) => {
34
+ if (!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name)) throw new Error('单工具覆盖需使用有效的工具名');
35
+ return [name, policy(v)] as const;
36
+ });
37
+ return { default: policy(value.default ?? { mode: 'inherit' }), overrides: Object.fromEntries(entries) };
38
+ }
39
+
40
+ export function effectiveToolRateLimit(tool: Pick<ToolDefinition, 'name' | 'rateLimit' | 'rateLimitPerMin'>, policies?: ToolRateLimitPolicies) {
41
+ const override = policies?.overrides && Object.hasOwn(policies.overrides, tool.name) ? policies.overrides[tool.name] : undefined;
42
+ const policy = override ?? policies?.default ?? { mode: 'inherit' };
43
+ const source = policy.mode === 'inherit' ? 'declaration' : override ? 'tool_override' : 'provider_default';
44
+ const limit = policy.mode === 'disabled' ? null : policy.mode === 'custom' ? policy
45
+ : tool.rateLimit ?? (tool.rateLimitPerMin > 0 ? { count: tool.rateLimitPerMin, window: '1m' as const } : null);
46
+ return { enabled: !!limit && limit.count > 0, count: limit?.count ?? 0, window: limit?.window ?? null,
47
+ window_sec: limit ? RATE_WINDOW_SECONDS[limit.window] : 0, source, scope: 'tool_provider_shared' as const };
48
+ }