bailinghub 0.4.0 → 0.5.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 (164) hide show
  1. package/.gitignore +5 -0
  2. package/README.en.md +5 -2
  3. package/README.md +6 -2
  4. package/SECURITY.md +11 -0
  5. package/docker-compose.images.yml +2 -2
  6. package/docs/AGENT_AUTH_API.en.md +191 -0
  7. package/docs/AGENT_AUTH_API.md +202 -0
  8. package/docs/AGENT_CLIENT_QUICKSTART.en.md +263 -0
  9. package/docs/AGENT_CLIENT_QUICKSTART.md +245 -0
  10. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +157 -0
  11. package/docs/AGENT_CLIENT_RUNTIME_API.md +107 -0
  12. package/docs/CHANGELOG.en.md +25 -0
  13. package/docs/CHANGELOG.md +25 -0
  14. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  15. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  16. package/docs/README.en.md +10 -2
  17. package/docs/README.md +10 -2
  18. package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
  19. package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
  20. package/docs/RELEASE_NOTES_v0.5.1.en.md +45 -0
  21. package/docs/RELEASE_NOTES_v0.5.1.md +45 -0
  22. package/package.json +3 -2
  23. package/schemas/config/client.schema.json +7 -0
  24. package/schemas/config/common.schema.json +30 -0
  25. package/schemas/config/route.schema.json +11 -0
  26. package/scripts/check-doc-links.mjs +2 -1
  27. package/scripts/check-image-tags.sh +1 -1
  28. package/scripts/check-release-consistency.test.mjs +5 -5
  29. package/scripts/e2e-console.mjs +144 -0
  30. package/scripts/export-oss.mjs +5 -12
  31. package/scripts/install.sh +1 -1
  32. package/scripts/public-content-denylist.mjs +82 -0
  33. package/scripts/public-content-denylist.test.mjs +53 -0
  34. package/scripts/publish-images.sh +1 -1
  35. package/scripts/release-audit.mjs +9 -13
  36. package/scripts/sdk-runtime-test.mjs +171 -7
  37. package/scripts/security-scan.mjs +8 -5
  38. package/scripts/validate-examples.mjs +3 -1
  39. package/scripts/verify-github-repo.mjs +8 -12
  40. package/scripts/verify-oss-export.mjs +6 -12
  41. package/sdk/php/README.md +27 -1
  42. package/sdk/php/src/AgentAuth.php +78 -0
  43. package/sdk/php/src/HubClient.php +3 -0
  44. package/sdk/php7/README.md +32 -2
  45. package/sdk/php7/src/AgentAuth.php +77 -0
  46. package/sdk/php7/src/HubClient.php +3 -0
  47. package/sql/055_agent_auth.sql +72 -0
  48. package/sql/056_agent_client_runtime.sql +60 -0
  49. package/src/adapters/channels/wecom-api.ts +1 -1
  50. package/src/app/agent-client-runtime.test.ts +221 -0
  51. package/src/app/agent-client-runtime.ts +408 -0
  52. package/src/app/agent-tool-invocations.test.ts +462 -0
  53. package/src/app/agent-tool-invocations.ts +795 -0
  54. package/src/app/agent-tool-job.test.ts +62 -0
  55. package/src/app/agent-tool-job.ts +41 -0
  56. package/src/app/auth.ts +2 -1
  57. package/src/app/kernel.ts +2 -0
  58. package/src/app/oss-edition.ts +1 -0
  59. package/src/app/runtime-context.ts +8 -0
  60. package/src/app/tool-approvals.ts +5 -1
  61. package/src/app/tool-assembly.ts +19 -1
  62. package/src/app/tool-context.ts +2 -1
  63. package/src/core/config/agent-direct-console-selection.test.ts +22 -0
  64. package/src/core/config/config-codec.ts +2 -1
  65. package/src/core/config/config-models.test.ts +10 -0
  66. package/src/core/config/config-models.ts +21 -0
  67. package/src/core/config/config-schema.test.ts +6 -0
  68. package/src/core/config/route-config.test.ts +15 -0
  69. package/src/core/config/route-config.ts +36 -0
  70. package/src/core/config/tools-config.test.ts +58 -1
  71. package/src/core/config/tools-config.ts +84 -0
  72. package/src/core/contracts/tools.ts +162 -29
  73. package/src/core/contracts/types.ts +36 -0
  74. package/src/core/runtime/agent-client-trace.test.ts +154 -0
  75. package/src/core/runtime/agent-client-trace.ts +288 -0
  76. package/src/core/runtime/launch-runtime.ts +13 -0
  77. package/src/core/runtime/trace-runtime.test.ts +18 -1
  78. package/src/core/runtime/trace-runtime.ts +28 -3
  79. package/src/core/state/state-codec.ts +2 -0
  80. package/src/infrastructure/config/config-agent-auth-repository.test.ts +183 -0
  81. package/src/infrastructure/config/config-agent-auth-repository.ts +453 -0
  82. package/src/infrastructure/config/config-agent-client-runtime-repository.test.ts +38 -0
  83. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +307 -0
  84. package/src/infrastructure/config/config-approval-ledger.test.ts +32 -0
  85. package/src/infrastructure/config/config-approval-ledger.ts +16 -0
  86. package/src/infrastructure/config/config-client-repository.ts +3 -3
  87. package/src/infrastructure/config/config-conversation-ledger.test.ts +69 -0
  88. package/src/infrastructure/config/config-conversation-ledger.ts +8 -7
  89. package/src/infrastructure/config/config-observability-ledger.test.ts +50 -0
  90. package/src/infrastructure/config/config-observability-ledger.ts +65 -10
  91. package/src/infrastructure/config/config-route-repository.ts +4 -3
  92. package/src/infrastructure/config/configstore.ts +14 -3
  93. package/src/infrastructure/state/state-mysql.ts +2 -2
  94. package/src/kernel-api/v1/contracts.ts +8 -0
  95. package/src/routes/admin-agent-clients.test.ts +120 -0
  96. package/src/routes/admin-agent-clients.ts +161 -0
  97. package/src/routes/admin-runtime.test.ts +214 -0
  98. package/src/routes/admin-runtime.ts +82 -2
  99. package/src/routes/admin.ts +3 -0
  100. package/src/routes/agent-api.test.ts +379 -0
  101. package/src/routes/agent-api.ts +251 -0
  102. package/src/routes/agent-auth.test.ts +276 -0
  103. package/src/routes/agent-auth.ts +395 -0
  104. package/src/routes/approvals.ts +4 -1
  105. package/src/routes/critical-routes.test.ts +235 -1
  106. package/src/routes/private-default.ts +2 -1
  107. package/src/routes/private.ts +16 -1
  108. package/src/routes/run.ts +79 -13
  109. package/web/connect/bailing-connect-php.tgz +0 -0
  110. package/web/connect/bailing-connect-php7.tgz +0 -0
  111. package/web/console/assets/{Accounts-DuUY2UJU.js → Accounts-r10QUjLQ.js} +1 -1
  112. package/web/console/assets/AgentClients-DsWADpzr.css +1 -0
  113. package/web/console/assets/AgentClients-UTTqbkjy.js +1 -0
  114. package/web/console/assets/{Approvals-B11mo1dy.js → Approvals-BGKkYIya.js} +1 -1
  115. package/web/console/assets/{Audit-CQwJRIJT.js → Audit-CQmjOAoO.js} +1 -1
  116. package/web/console/assets/{BrandLockup-BIF-h1pi.js → BrandLockup-BF_0pCa3.js} +1 -1
  117. package/web/console/assets/{Channels-BIploUT-.js → Channels-C4yZE67F.js} +1 -1
  118. package/web/console/assets/{ChatEntries-Cpg_WV-o.js → ChatEntries-OqsqLjU6.js} +1 -1
  119. package/web/console/assets/Clients-CNIVs7Qn.css +1 -0
  120. package/web/console/assets/Clients-Dv3sv51C.js +3 -0
  121. package/web/console/assets/{Cost-BF52tfU2.js → Cost-C_-kiH59.js} +1 -1
  122. package/web/console/assets/{Credentials-SwfmQAv6.js → Credentials-CPTEAiV6.js} +1 -1
  123. package/web/console/assets/{Diagnostics-CJfbI_8p.js → Diagnostics-O-NKFOeI.js} +1 -1
  124. package/web/console/assets/{Executors-CzlZlznA.js → Executors-GVIAiNgv.js} +1 -1
  125. package/web/console/assets/{HelpTip-CT07o3kB.js → HelpTip-i-KJhf5s.js} +1 -1
  126. package/web/console/assets/{Kb-CVX22U4k.js → Kb-BsCWkJI1.js} +2 -2
  127. package/web/console/assets/{Login-PoUVsBI-.js → Login-VFjkHNMr.js} +1 -1
  128. package/web/console/assets/{Projects-DYlbjLQy.js → Projects-Ds-sJwfy.js} +1 -1
  129. package/web/console/assets/Routes-CXGl9SMM.css +1 -0
  130. package/web/console/assets/Routes-Wwurw2UU.js +124 -0
  131. package/web/console/assets/Runs-4zDD9VOC.css +1 -0
  132. package/web/console/assets/Runs-DLPzXmSy.js +3 -0
  133. package/web/console/assets/{Setup-xiPXit_b.js → Setup-BLelw0_V.js} +1 -1
  134. package/web/console/assets/Shell-CvaeK4j_.js +1 -0
  135. package/web/console/assets/Shell-D9Uw-fsa.css +1 -0
  136. package/web/console/assets/{StorageBuckets-Bjsc3pLd.js → StorageBuckets-Dv6u47yO.js} +1 -1
  137. package/web/console/assets/{SystemSettings-CcKF2lJ9.js → SystemSettings-B9K7zaDU.js} +1 -1
  138. package/web/console/assets/{SystemStatus-Oj1xjxJn.js → SystemStatus-H-oKDo-y.js} +1 -1
  139. package/web/console/assets/{Targets-y1KllVXT.js → Targets-CCFhjPKf.js} +1 -1
  140. package/web/console/assets/{Tools-DoEP_y9x.js → Tools-D0H9xpFH.js} +1 -1
  141. package/web/console/assets/index-CuoTgf6q.js +2 -0
  142. package/web/console/assets/{index-DZEQL_yy.js → index-DyX9Bz3V.js} +1 -1
  143. package/web/console/assets/{request-CBLNpLth.js → request-F5lXa7Ro.js} +1 -1
  144. package/web/console/assets/{schema-DzwLpuOy.js → schema-DUWaWqPn.js} +1 -1
  145. package/web/console/assets/{util-SiQC2MJh.js → util-4bN2dv7B.js} +1 -1
  146. package/web/console/assets/{vendor-element-D7WRzHhy.js → vendor-element-CZoEjZr8.js} +1 -1
  147. package/web/console/assets/{vendor-mammoth-DvgsHdlx.js → vendor-mammoth-nXG51Cg7.js} +1 -1
  148. package/web/console/index.html +2 -2
  149. package/web-admin/src/agent-direct-selection.ts +21 -0
  150. package/web-admin/src/layout/Shell.vue +1 -1
  151. package/web-admin/src/pages/AgentClients.vue +254 -0
  152. package/web-admin/src/pages/Clients.vue +13 -3
  153. package/web-admin/src/pages/Routes.vue +331 -16
  154. package/web-admin/src/pages/Runs.vue +159 -38
  155. package/web-admin/src/router.ts +2 -0
  156. package/web/console/assets/Clients--D7NQJKk.css +0 -1
  157. package/web/console/assets/Clients-DS29eUi2.js +0 -3
  158. package/web/console/assets/Routes-DSEvGujN.js +0 -124
  159. package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
  160. package/web/console/assets/Runs-B-TsYZEt.js +0 -3
  161. package/web/console/assets/Runs-CUtSsPW-.css +0 -1
  162. package/web/console/assets/Shell-BVIjmoY8.css +0 -1
  163. package/web/console/assets/Shell-DNiWZOYB.js +0 -1
  164. package/web/console/assets/index-CxPIS6G7.js +0 -2
@@ -6,13 +6,29 @@ import { send } from '../app/http';
6
6
  import { redactValue, redactionSummary } from '../core/runtime/redaction-runtime';
7
7
  import { renderDebugReport } from '../core/runtime/debug-report';
8
8
  import { buildJobTrace } from '../core/runtime/trace-runtime';
9
+ import { buildAgentClientTrace } from '../core/runtime/agent-client-trace';
9
10
  import type { RuntimeStateStore } from '../core/state/state-contracts';
10
11
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
12
+ import type { AgentClientRunRecord } from '../infrastructure/config/config-agent-client-runtime-repository';
11
13
  import type { Principal } from '../app/auth';
12
14
  import type { ChannelMessage, ChannelSendResult } from '../app/channels';
15
+ import { isAgentToolInvocationJob } from '../app/agent-tool-job';
13
16
 
14
17
  export type AdminChannelSender = (channelName: string, recipient: string, message: string | ChannelMessage) => Promise<ChannelSendResult>;
15
18
 
19
+ function isToolJobForAgentRun(job: any, run: AgentClientRunRecord): boolean {
20
+ const metadata = job?.metadata ?? {};
21
+ return isAgentToolInvocationJob(job)
22
+ && Number(job.thread_id) === run.thread_id
23
+ && job.session_id === run.run_id
24
+ && job.client_app_id === run.client_app_id
25
+ && job.agent_session_id === run.session_id
26
+ && metadata['agent_run_id'] === run.run_id
27
+ && Number(metadata['agent_thread_id']) === run.thread_id
28
+ && metadata['agent_route'] === run.route_key
29
+ && job.dispatch?.route_key === run.route_key;
30
+ }
31
+
16
32
  function textPreview(v: unknown, limit = 2000): string | null {
17
33
  if (v == null) return null;
18
34
  const s = typeof v === 'string' ? v : JSON.stringify(v);
@@ -326,7 +342,7 @@ export async function handleAdminRuntimeApiFor(
326
342
  return true;
327
343
  }
328
344
 
329
- // 会话视图(调度台「会话」Tab):列线索 / 取单会话全量(消息总账+对齐的 job_id,执行轨迹复用 /runs/:job 接口懒拉)
345
+ // 会话视图(调度台「会话」Tab):旧中枢轮次按 job_id,Agent Client 轮次按 agent_run_id 懒加载轨迹。
330
346
  if (path === '/admin/api/threads' && method === 'GET') {
331
347
  const q = new URL(req.url ?? '/', 'http://x').searchParams;
332
348
  send(res, 200, await configStore.conversations.listRecentThreads(Number(q.get('limit')) || 80, Number(q.get('offset')) || 0));
@@ -340,6 +356,66 @@ export async function handleAdminRuntimeApiFor(
340
356
  return true;
341
357
  }
342
358
 
359
+ // Agent Client 一轮轨迹:本地负责规划,中枢只聚合安全的运行边界、ACC 工具治理、审批与结果。
360
+ // 使用 thread + run 双键防止串线;工具 Job 还要通过服务端 marker 和身份/路由不变量复核。
361
+ const mAgentRunTrace = path.match(/^\/admin\/api\/threads\/(\d+)\/agent-runs\/([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\/trace$/i);
362
+ if (mAgentRunTrace && method === 'GET') {
363
+ const threadId = Number(mAgentRunTrace[1]);
364
+ const runId = mAgentRunTrace[2]!;
365
+ const runtimeRepo = configStore.agentClientRuntime;
366
+ const candidateLookup = configStore.observability.agentToolJobCandidatesForRun;
367
+ if (!runtimeRepo || !candidateLookup) {
368
+ send(res, 503, { error: '智能体客户端执行轨迹在当前配置仓储中不可用' });
369
+ return true;
370
+ }
371
+ const run = await runtimeRepo.findRunForInvocation(runId);
372
+ if (!run || run.thread_id !== threadId) {
373
+ send(res, 404, { error: '智能体客户端运行不存在' });
374
+ return true;
375
+ }
376
+ const [runAudit, candidates] = await Promise.all([
377
+ configStore.observability.auditForJob(runId),
378
+ configStore.observability.agentToolJobCandidatesForRun!(runId, threadId),
379
+ ]);
380
+ const jobs = candidates.jobs
381
+ .filter((job) => isToolJobForAgentRun(job, run))
382
+ .sort((a, b) => a.created_at.localeCompare(b.created_at) || a.job_id.localeCompare(b.job_id));
383
+ const jobIds = jobs.map((job) => job.job_id);
384
+ const auditPromise = configStore.observability.auditsForJobs
385
+ ? configStore.observability.auditsForJobs(jobIds)
386
+ : Promise.all(jobIds.map((jobId) => configStore.observability.auditForJob(jobId)))
387
+ .then((rows) => Object.fromEntries(jobIds.map((jobId, index) => [jobId, rows[index] ?? []])));
388
+ const approvalPromise = configStore.approvals.forJobs
389
+ ? configStore.approvals.forJobs(jobIds)
390
+ : Promise.all(jobIds.map((jobId) => configStore.approvals.forJob(jobId)))
391
+ .then((rows) => Object.fromEntries(jobIds.map((jobId, index) => [jobId, rows[index] ?? []])));
392
+ const [auditByJob, approvalsByJob] = await Promise.all([auditPromise, approvalPromise]);
393
+ const tools = jobs.map((job) => ({
394
+ job,
395
+ audit: auditByJob[job.job_id] ?? [],
396
+ approvals: approvalsByJob[job.job_id] ?? [],
397
+ }));
398
+ send(res, 200, buildAgentClientTrace({
399
+ run: {
400
+ run_id: run.run_id,
401
+ thread_id: run.thread_id,
402
+ client_app_id: run.client_app_id,
403
+ route_key: run.route_key,
404
+ status: run.status,
405
+ model: run.model,
406
+ runtime: run.runtime,
407
+ usage: run.usage,
408
+ created_at: run.created_at,
409
+ updated_at: run.updated_at,
410
+ completed_at: run.completed_at,
411
+ },
412
+ runAudit,
413
+ tools,
414
+ candidatesTruncated: candidates.truncated,
415
+ }));
416
+ return true;
417
+ }
418
+
343
419
  // 任务详情 / 审计时间线 / 重跑
344
420
  const mRun = path.match(/^\/admin\/api\/runs\/([0-9a-f-]{36})(\/audit|\/rerun|\/trace)?$/);
345
421
  if (mRun) {
@@ -362,6 +438,10 @@ export async function handleAdminRuntimeApiFor(
362
438
  return true;
363
439
  }
364
440
  if (method === 'POST' && mRun[2] === '/rerun') {
441
+ if (isAgentToolInvocationJob(job)) {
442
+ send(res, 409, { error: 'Agent 直调记录不能进入中枢模型重跑;请由原本地 Agent 用 invocation_id 续执行' });
443
+ return true;
444
+ }
365
445
  if (job.status === 'queued' || job.status === 'running' || job.status === 'dispatched') {
366
446
  send(res, 400, { error: `任务在途(${job.status}),无需重跑` });
367
447
  return true;
@@ -399,7 +479,7 @@ export async function handleAdminRuntimeApiFor(
399
479
  let rerun = false;
400
480
  if (action === 'approve') {
401
481
  const job = await stateStore.getJob(appr.job_id);
402
- if (job && (job.status === 'done' || job.status === 'error' || job.status === 'rejected')) {
482
+ if (job && !isAgentToolInvocationJob(job) && (job.status === 'done' || job.status === 'error' || job.status === 'rejected')) {
403
483
  await deps.engineRuntime.requeueForRerun(job, by, `approval_${id}`);
404
484
  rerun = true;
405
485
  }
@@ -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 { handleAdminAgentClientsApiFor } from './admin-agent-clients';
22
23
  import { handleAdminDemoDatasetApiFor, type DemoDatasetServiceContract } from './admin-demo-dataset';
23
24
  import { refreshTargets, type TargetRegistry } from '../core/targets/registry';
24
25
  import type { AppConfig } from '../core/config/config';
@@ -105,6 +106,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
105
106
  [/^\/admin\/api\/dispatch-status/, 'runs:read', 'runs:read'],
106
107
  [/^\/admin\/api\/config-schemas/, 'audit:read', 'audit:read'],
107
108
  [/^\/admin\/api\/cost/, 'runs:read', 'runs:read'], // 成本可观测=运行面只读
109
+ [/^\/admin\/api\/agent-clients/, 'clients:read', 'clients:write'],
108
110
  [/^\/admin\/api\/clients/, 'clients:read', 'clients:write'],
109
111
  [/^\/admin\/api\/credentials/, 'credentials:read', 'credentials:write'],
110
112
  [/^\/admin\/api\/storage-buckets/, 'storage:read', 'storage:write'], // 含桶凭证,默认仅 admin(*)可管
@@ -192,6 +194,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
192
194
  channelSend: deps.channelSend,
193
195
  engineRuntime: deps.engineRuntime,
194
196
  }, method, path, req, res, principal)) return true;
197
+ if (await handleAdminAgentClientsApiFor({ configStore, stateStore: deps.stateStore, now: deps.now }, method, path, req, res, principal)) return true;
195
198
  if (await handleAdminBrandingApiFor({ brandingProvider: deps.brandingProvider }, method, path, req, res)) return true;
196
199
  if (await handleAdminAccessApiFor({ configStore, stateStore: deps.stateStore, now: deps.now }, method, path, req, res, principal)) return true;
197
200
  if (await handleAdminToolProviderApiFor({ cfg: deps.cfg, configStore, stateStore: deps.stateStore, toolIndex: deps.toolIndex, now: deps.now, sleep: deps.sleep }, method, path, req, res, principal)) return true;
@@ -0,0 +1,379 @@
1
+ import assert from 'node:assert/strict';
2
+ import { Readable } from 'node:stream';
3
+ import type { IncomingMessage, ServerResponse } from 'node:http';
4
+ import test from 'node:test';
5
+ import type { AgentSession, Client, Job, Route, ToolProvider } from '../core/contracts/types';
6
+ import type { AppConfig } from '../core/config/config';
7
+ import type { AgentClientRunRecord } from '../infrastructure/config/config-agent-client-runtime-repository';
8
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
10
+ import { tokenHash } from './agent-auth';
11
+ import { handleAgentApiHttpFor } from './agent-api';
12
+ import type { ToolProxyDeps } from '../app/tool-proxy';
13
+
14
+ class FakeResponse {
15
+ statusCode = 0;
16
+ headers: Record<string, string | number | string[]> = {};
17
+ body = Buffer.alloc(0);
18
+ setHeader(name: string, value: string | number | string[]): void { this.headers[name.toLowerCase()] = value; }
19
+ writeHead(code: number, headers?: Record<string, string | number | string[]>): void {
20
+ this.statusCode = code;
21
+ for (const [name, value] of Object.entries(headers ?? {})) this.headers[name.toLowerCase()] = value;
22
+ }
23
+ end(value?: string | Buffer): void { this.body = value ? Buffer.from(value) : Buffer.alloc(0); }
24
+ json(): Record<string, unknown> { return JSON.parse(this.body.toString('utf8')) as Record<string, unknown>; }
25
+ }
26
+
27
+ function request(method: string, headers: Record<string, string> = {}, body?: unknown): IncomingMessage {
28
+ const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]) as unknown as IncomingMessage;
29
+ req.method = method;
30
+ req.headers = headers;
31
+ return req;
32
+ }
33
+
34
+ test('Agent API job reads are isolated to the originating Agent Session', async () => {
35
+ const token = `bha_${'a'.repeat(43)}`;
36
+ const client: Client = {
37
+ app_id: 'example-business', name: 'Example Business', token: 'client-token',
38
+ agent_authorize_url: 'https://tenant.example.com/agent-authorize',
39
+ allowed_routes: ['orders'], allowed_channels: [], rate_limit_per_min: 0, enabled: true,
40
+ };
41
+ const session: AgentSession = {
42
+ session_id: '123e4567-e89b-42d3-a456-426614174000',
43
+ client_app_id: client.app_id,
44
+ device_label: 'Mac mini',
45
+ principal: { id: 'user-7', roles: [] },
46
+ on_behalf_of: 'tenant-2:user-7',
47
+ allowed_routes: ['orders'],
48
+ created_at: '2026-01-01T00:00:00.000Z',
49
+ access_expires_at: '2099-01-01T00:00:00.000Z',
50
+ refresh_expires_at: '2099-01-30T00:00:00.000Z',
51
+ };
52
+ const ownJob: Job = {
53
+ job_id: '223e4567-e89b-42d3-a456-426614174000', request_id: 'request-1', status: 'done',
54
+ profile: 'general', project: '', source: 'agent:example-business', client_app_id: client.app_id,
55
+ agent_session_id: session.session_id, on_behalf_of: session.on_behalf_of,
56
+ input_preview: 'hello', metadata: {}, created_at: '2026-01-01T00:00:00.000Z', updated_at: '2026-01-01T00:00:01.000Z',
57
+ };
58
+ const otherJob = { ...ownJob, job_id: '323e4567-e89b-42d3-a456-426614174000', agent_session_id: '423e4567-e89b-42d3-a456-426614174000' };
59
+ const configStore = {
60
+ agentAuth: { getSessionByAccessHash: async (hash: string) => hash === tokenHash(token) ? session : null },
61
+ clients: { get: async () => client },
62
+ } as unknown as ConfigStoreContract;
63
+ const stateStore = {
64
+ getJob: async (id: string) => id === ownJob.job_id ? ownJob : id === otherJob.job_id ? otherJob : null,
65
+ } as unknown as RuntimeStateStore;
66
+ const deps = {
67
+ configStore,
68
+ stateStore,
69
+ isPaused: () => false,
70
+ handleRun: async () => { throw new Error('run not expected'); },
71
+ };
72
+
73
+ const queryRes = new FakeResponse();
74
+ await handleAgentApiHttpFor(deps, request('GET'), queryRes as unknown as ServerResponse, new URL(`https://hub.example.com/agent-api/v1/jobs/${ownJob.job_id}?token=${token}`));
75
+ assert.equal(queryRes.statusCode, 401);
76
+
77
+ const ownRes = new FakeResponse();
78
+ await handleAgentApiHttpFor(deps, request('GET', { authorization: `Bearer ${token}` }), ownRes as unknown as ServerResponse, new URL(`https://hub.example.com/agent-api/v1/jobs/${ownJob.job_id}`));
79
+ assert.equal(ownRes.statusCode, 200);
80
+ assert.equal(ownRes.json()['job_id'], ownJob.job_id);
81
+
82
+ const otherRes = new FakeResponse();
83
+ await handleAgentApiHttpFor(deps, request('GET', { authorization: `Bearer ${token}` }), otherRes as unknown as ServerResponse, new URL(`https://hub.example.com/agent-api/v1/jobs/${otherJob.job_id}`));
84
+ assert.equal(otherRes.statusCode, 404);
85
+ });
86
+
87
+ test('Agent Tool API: envelope 严格拒绝非对象 arguments 与字段漂移', async () => {
88
+ const token = `bha_${'b'.repeat(43)}`;
89
+ const client: Client = {
90
+ app_id: 'example-business', name: 'Example Business', token: 'client-token',
91
+ agent_authorize_url: 'https://tenant.example.com/agent-authorize',
92
+ allowed_routes: ['orders'], allowed_channels: [], rate_limit_per_min: 0, enabled: true,
93
+ };
94
+ const session: AgentSession = {
95
+ session_id: '523e4567-e89b-42d3-a456-426614174000', client_app_id: client.app_id, device_label: 'Mac mini',
96
+ principal: { id: 'user-7', roles: [] }, on_behalf_of: 'tenant-2:user-7', allowed_routes: ['orders'],
97
+ created_at: '2026-01-01T00:00:00.000Z', access_expires_at: '2099-01-01T00:00:00.000Z', refresh_expires_at: '2099-01-30T00:00:00.000Z',
98
+ };
99
+ const deps = {
100
+ configStore: {
101
+ agentAuth: { getSessionByAccessHash: async (hash: string) => hash === tokenHash(token) ? session : null },
102
+ clients: { get: async () => client },
103
+ } as unknown as ConfigStoreContract,
104
+ stateStore: {} as RuntimeStateStore,
105
+ isPaused: () => false,
106
+ handleRun: async () => { throw new Error('run not expected'); },
107
+ toolProxyDeps: {} as ToolProxyDeps,
108
+ };
109
+ const base = {
110
+ invocation_id: 'a'.repeat(64),
111
+ route: 'orders',
112
+ capability_revision: 'b'.repeat(64),
113
+ agent_run_id: '623e4567-e89b-42d3-a456-426614174000',
114
+ tool: 'order_list',
115
+ arguments: {},
116
+ };
117
+ const headers = { authorization: `Bearer ${token}` };
118
+
119
+ for (const invalidBody of [[], null, 'x', 7]) {
120
+ const res = new FakeResponse();
121
+ await handleAgentApiHttpFor(deps, request('POST', headers, invalidBody), res as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
122
+ assert.equal(res.statusCode, 400);
123
+ assert.equal(res.json()['error'], 'invalid_request');
124
+ }
125
+
126
+ for (const invalid of [[], null, 'x', 7]) {
127
+ const res = new FakeResponse();
128
+ await handleAgentApiHttpFor(deps, request('POST', headers, { ...base, arguments: invalid }), res as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
129
+ assert.equal(res.statusCode, 400);
130
+ assert.equal(res.json()['error'], 'invalid_request');
131
+ }
132
+
133
+ const missing = new FakeResponse();
134
+ const { tool: _tool, ...withoutTool } = base;
135
+ await handleAgentApiHttpFor(deps, request('POST', headers, withoutTool), missing as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
136
+ assert.equal(missing.statusCode, 400);
137
+
138
+ const extra = new FakeResponse();
139
+ await handleAgentApiHttpFor(deps, request('POST', headers, { ...base, future: true }), extra as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
140
+ assert.equal(extra.statusCode, 400);
141
+
142
+ const oversized = new FakeResponse();
143
+ await handleAgentApiHttpFor(deps, request('POST', headers, { ...base, future: 'x'.repeat(20_000) }), oversized as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
144
+ assert.equal(oversized.statusCode, 413);
145
+ assert.equal(oversized.json()['error'], 'arguments_too_large');
146
+
147
+ for (const invalidBody of [[], null, 'x', 7]) {
148
+ const res = new FakeResponse();
149
+ await handleAgentApiHttpFor(deps, request('POST', headers, invalidBody), res as unknown as ServerResponse, new URL(`https://hub.example.com/agent-api/v1/tool-invocations/${'a'.repeat(64)}/resume`));
150
+ assert.equal(res.statusCode, 400);
151
+ assert.equal(res.json()['error'], 'invalid_request');
152
+ }
153
+ });
154
+
155
+ test('Agent Tool API: pause 在读取请求与工具治理链前拦截 invoke/resume', async () => {
156
+ const token = `bha_${'c'.repeat(43)}`;
157
+ const client: Client = {
158
+ app_id: 'example-business', name: 'Example Business', token: 'client-token',
159
+ agent_authorize_url: 'https://tenant.example.com/agent-authorize',
160
+ allowed_routes: ['orders'], allowed_channels: [], rate_limit_per_min: 0, enabled: true,
161
+ };
162
+ const session: AgentSession = {
163
+ session_id: '723e4567-e89b-42d3-a456-426614174000', client_app_id: client.app_id, device_label: 'Mac mini',
164
+ principal: { id: 'user-7', roles: [] }, on_behalf_of: 'tenant-2:user-7', allowed_routes: ['orders'],
165
+ created_at: '2026-01-01T00:00:00.000Z', access_expires_at: '2099-01-01T00:00:00.000Z', refresh_expires_at: '2099-01-30T00:00:00.000Z',
166
+ };
167
+ const deps = {
168
+ configStore: {
169
+ agentAuth: { getSessionByAccessHash: async (hash: string) => hash === tokenHash(token) ? session : null },
170
+ clients: { get: async () => client },
171
+ } as unknown as ConfigStoreContract,
172
+ stateStore: {} as RuntimeStateStore,
173
+ isPaused: () => true,
174
+ handleRun: async () => { throw new Error('run not expected'); },
175
+ toolProxyDeps: {} as ToolProxyDeps,
176
+ };
177
+ const headers = { authorization: `Bearer ${token}` };
178
+ const invoke = new FakeResponse();
179
+ await handleAgentApiHttpFor(deps, request('POST', headers, {
180
+ invocation_id: 'd'.repeat(64), route: 'orders', capability_revision: 'e'.repeat(64),
181
+ agent_run_id: '823e4567-e89b-42d3-a456-426614174000', tool: 'order_list', arguments: {},
182
+ }), invoke as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
183
+ assert.equal(invoke.statusCode, 503);
184
+ assert.equal(invoke.json()['status'], 'paused');
185
+ assert.equal(invoke.json()['error'], 'hub_paused');
186
+
187
+ const resume = new FakeResponse();
188
+ await handleAgentApiHttpFor(deps, request('POST', headers, {}), resume as unknown as ServerResponse, new URL(`https://hub.example.com/agent-api/v1/tool-invocations/${'d'.repeat(64)}/resume`));
189
+ assert.equal(resume.statusCode, 503);
190
+ assert.equal(resume.json()['status'], 'paused');
191
+ assert.equal(resume.json()['error'], 'hub_paused');
192
+ });
193
+
194
+ function runtimeHttpFixture() {
195
+ const token = `bha_${'r'.repeat(43)}`;
196
+ const client: Client = {
197
+ app_id: 'example-business', name: 'Example Business', token: 'client-token',
198
+ agent_authorize_url: 'https://tenant.example.com/agent-authorize',
199
+ allowed_routes: ['allowed', 'audience-denied', 'agent-off', 'session-denied'], allowed_channels: [], rate_limit_per_min: 0, enabled: true,
200
+ };
201
+ const session: AgentSession = {
202
+ session_id: '923e4567-e89b-42d3-a456-426614174000', client_app_id: client.app_id, device_label: 'Mac mini',
203
+ principal: { id: 'user-7', roles: ['admin'] }, on_behalf_of: 'tenant-2:user-7',
204
+ allowed_routes: ['allowed', 'audience-denied', 'agent-off', 'client-denied'],
205
+ created_at: '2026-01-01T00:00:00.000Z', access_expires_at: '2099-01-01T00:00:00.000Z', refresh_expires_at: '2099-01-30T00:00:00.000Z',
206
+ };
207
+ const baseRoute = (route_key: string): Route => ({
208
+ route_key, name: route_key, enabled: true, target: 'llm', target_config: { credential: 'hidden', system_prompt: 'safe system' },
209
+ profile: 'general', permission: 'full', session_policy: 'new', agent_client: { enabled: true, active_tool_limit: 1 },
210
+ audience: { enabled: true, roles: ['admin'], clients: ['example-business'] },
211
+ tools: { sources: [{ provider: 'business', allow: ['*'] }], agent_direct: { enabled: true } },
212
+ });
213
+ const routes = [
214
+ baseRoute('allowed'),
215
+ { ...baseRoute('audience-denied'), audience: { enabled: true, roles: ['owner'] } },
216
+ { ...baseRoute('agent-off'), agent_client: { enabled: false } },
217
+ baseRoute('session-denied'),
218
+ baseRoute('client-denied'),
219
+ ];
220
+ const provider: ToolProvider = {
221
+ name: 'business', base_url: 'https://business.invalid', secret: 'secret', spec_source: 'inline', enabled: true,
222
+ log_payload: false, timeout_ms: 1000, rate_limit_per_min: 0, auto_refresh_min: 0,
223
+ spec_json: JSON.stringify({ openapi: '3.0.0', info: { title: 'test', version: '1' }, paths: {
224
+ '/staff': { get: { operationId: 'staff_list', summary: '查询员工', 'x-agent-capability': { version: 1, enabled: true, scope: 'staff.read', subject: { required: true } } } },
225
+ } }),
226
+ };
227
+ let run: AgentClientRunRecord | null = null;
228
+ let completeCalls = 0;
229
+ const runtimeRepo = {
230
+ resolveConversation: async () => 9,
231
+ reserveRun: async (input: any) => {
232
+ if (!run) run = {
233
+ run_id: 'a23e4567-e89b-42d3-a456-426614174000', ...input, context: null, status: 'preparing',
234
+ completion_hash: null, assistant_message_id: null, final_content: null, model: null, runtime: null, usage: null,
235
+ created_at: '2026-01-01T00:00:00.000Z', updated_at: '2026-01-01T00:00:00.000Z', completed_at: null,
236
+ } as AgentClientRunRecord;
237
+ return { run, created: !run.context };
238
+ },
239
+ finalizeTurn: async (input: any) => { run = { ...run!, context: input.context, status: 'context_ready' }; return run; },
240
+ getRun: async () => run,
241
+ findRunForInvocation: async () => run,
242
+ completeRun: async (input: any) => {
243
+ completeCalls++;
244
+ if (!run?.context) throw new Error('turn context is not ready');
245
+ if (run.completion_hash) return { run, created: false };
246
+ run = {
247
+ ...run,
248
+ completion_hash: input.completion_hash,
249
+ assistant_message_id: input.assistant_message_id,
250
+ final_content: input.assistant_output,
251
+ status: input.status,
252
+ model: input.model ?? null,
253
+ runtime: input.runtime ?? null,
254
+ usage: input.usage ?? null,
255
+ completed_at: '2026-01-01T00:01:00.000Z',
256
+ };
257
+ return { run, created: true };
258
+ },
259
+ };
260
+ const configStore = {
261
+ agentAuth: { getSessionByAccessHash: async (value: string) => value === tokenHash(token) ? session : null },
262
+ clients: { get: async () => client },
263
+ routes: { list: async () => routes, get: async (key: string) => routes.find((route) => route.route_key === key) ?? null },
264
+ toolProviders: { get: async () => provider },
265
+ conversations: { getThreadMemory: async () => ({ summary: null, summary_upto_id: 0 }), recentMessagesAfter: async () => [] },
266
+ agentClientRuntime: runtimeRepo,
267
+ } as unknown as ConfigStoreContract;
268
+ const stateStore = { appendAudit: async () => undefined } as unknown as RuntimeStateStore;
269
+ const toolProxyDeps: ToolProxyDeps = {
270
+ cfg: {} as AppConfig, configStore, stateStore, toolIndex: null, now: () => '2026-01-01T00:00:00.000Z', sleep: async () => undefined,
271
+ };
272
+ return {
273
+ token,
274
+ deps: { configStore, stateStore, isPaused: () => false, handleRun: async () => undefined, toolProxyDeps, kbService: null },
275
+ completeCalls: () => completeCalls,
276
+ };
277
+ }
278
+
279
+ test('Agent Runtime HTTP: workspace 只列授权交集,turn 可省 page_context/renderers 且拒绝未知字段', async () => {
280
+ const fx = runtimeHttpFixture();
281
+ const headers = { authorization: `Bearer ${fx.token}` };
282
+ const workspaces = new FakeResponse();
283
+ await handleAgentApiHttpFor(fx.deps, request('GET', headers), workspaces as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces'));
284
+ assert.equal(workspaces.statusCode, 200);
285
+ assert.deepEqual((workspaces.json()['workspaces'] as Array<{ route: string }>).map((item) => item.route), ['allowed']);
286
+
287
+ const turn = new FakeResponse();
288
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, {
289
+ client_conversation_id: 'c1', client_turn_id: 't1', user_message_id: 'm1', user_input: '查询员工',
290
+ }), turn as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/turns'));
291
+ assert.equal(turn.statusCode, 200, JSON.stringify(turn.json()));
292
+ assert.equal(turn.json()['schema_version'], 'bailing.agent-turn-context.v1');
293
+
294
+ const unknown = new FakeResponse();
295
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, {
296
+ client_conversation_id: 'c2', client_turn_id: 't2', user_message_id: 'm2', user_input: '查询员工', future: true,
297
+ }), unknown as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/turns'));
298
+ assert.equal(unknown.statusCode, 400);
299
+ assert.equal(unknown.json()['error'], 'invalid_request');
300
+ });
301
+
302
+ test('Agent Runtime HTTP: complete 拒绝 hidden reasoning 且不触达 repository', async () => {
303
+ const fx = runtimeHttpFixture();
304
+ const res = new FakeResponse();
305
+ await handleAgentApiHttpFor(fx.deps, request('POST', { authorization: `Bearer ${fx.token}` }, {
306
+ assistant_message_id: 'a1', status: 'completed', content: 'done', hidden_reasoning: 'secret chain of thought',
307
+ }), res as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/runs/a23e4567-e89b-42d3-a456-426614174000/complete'));
308
+ assert.equal(res.statusCode, 400);
309
+ assert.equal(fx.completeCalls(), 0);
310
+ });
311
+
312
+ test('Agent Runtime HTTP: 64000 个中文字符可穿过字节上限完成 turn 与 complete', async () => {
313
+ const fx = runtimeHttpFixture();
314
+ const headers = { authorization: `Bearer ${fx.token}` };
315
+ const boundaryText = '中'.repeat(64_000);
316
+ const turnBody = {
317
+ client_conversation_id: 'c-boundary', client_turn_id: 't-boundary', user_message_id: 'm-boundary', user_input: boundaryText,
318
+ page_context: { title: '中文边界' }, renderers: ['markdown'],
319
+ };
320
+ assert.ok(Buffer.byteLength(JSON.stringify(turnBody), 'utf8') > 96 * 1024);
321
+ const turn = new FakeResponse();
322
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, turnBody), turn as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/turns'));
323
+ assert.equal(turn.statusCode, 200, JSON.stringify(turn.json()));
324
+
325
+ const completionBody = { assistant_message_id: 'a-boundary', status: 'completed', content: boundaryText };
326
+ assert.ok(Buffer.byteLength(JSON.stringify(completionBody), 'utf8') > 80 * 1024);
327
+ const complete = new FakeResponse();
328
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, completionBody), complete as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/runs/a23e4567-e89b-42d3-a456-426614174000/complete'));
329
+ assert.equal(complete.statusCode, 200, JSON.stringify(complete.json()));
330
+ assert.equal(fx.completeCalls(), 1);
331
+ });
332
+
333
+ test('Agent Runtime HTTP: 客户端文本与 renderers 非法时 400,空搜索仅可通过 run 回退', async () => {
334
+ const fx = runtimeHttpFixture();
335
+ const headers = { authorization: `Bearer ${fx.token}` };
336
+ const turnBase = { client_conversation_id: 'c1', client_turn_id: 't1', user_message_id: 'm1', user_input: '查询员工' };
337
+ const invalidTurns = [
338
+ { ...turnBase, user_input: '中'.repeat(64_001) },
339
+ { ...turnBase, user_input: '查询\u0000员工' },
340
+ { ...turnBase, renderers: Array.from({ length: 21 }, (_, index) => `renderer.${index}`) },
341
+ { ...turnBase, renderers: ['markdown', 'markdown'] },
342
+ { ...turnBase, renderers: ['invalid renderer'] },
343
+ ];
344
+ for (const body of invalidTurns) {
345
+ const res = new FakeResponse();
346
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, body), res as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/turns'));
347
+ assert.equal(res.statusCode, 400, JSON.stringify(res.json()));
348
+ }
349
+
350
+ const completionBase = { assistant_message_id: 'a1', status: 'completed', content: 'done' };
351
+ const invalidCompletions = [
352
+ { ...completionBase, content: '中'.repeat(64_001) },
353
+ { ...completionBase, content: 'done\u0001' },
354
+ { ...completionBase, model: 'm'.repeat(192) },
355
+ { ...completionBase, model: 'model\u007f' },
356
+ { ...completionBase, runtime: 'r'.repeat(192) },
357
+ { ...completionBase, runtime: 'runtime\u0002' },
358
+ ];
359
+ for (const body of invalidCompletions) {
360
+ const res = new FakeResponse();
361
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, body), res as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/runs/a23e4567-e89b-42d3-a456-426614174000/complete'));
362
+ assert.equal(res.statusCode, 400, JSON.stringify(res.json()));
363
+ }
364
+ assert.equal(fx.completeCalls(), 0);
365
+
366
+ for (const body of [{}, { query: ' \n\t ' }]) {
367
+ const res = new FakeResponse();
368
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, body), res as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/capabilities/search'));
369
+ assert.equal(res.statusCode, 400, JSON.stringify(res.json()));
370
+ }
371
+
372
+ const turn = new FakeResponse();
373
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, turnBase), turn as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/turns'));
374
+ assert.equal(turn.statusCode, 200, JSON.stringify(turn.json()));
375
+ const search = new FakeResponse();
376
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, { run_id: 'a23e4567-e89b-42d3-a456-426614174000' }), search as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/capabilities/search'));
377
+ assert.equal(search.statusCode, 200, JSON.stringify(search.json()));
378
+ assert.equal(search.json()['query'], '查询员工');
379
+ });