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
@@ -0,0 +1,462 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createServer, type Server } from 'node:http';
3
+ import test from 'node:test';
4
+ import type { AppConfig } from '../core/config/config';
5
+ import type { ToolExecutionJournalEntry } from '../core/contracts/tools';
6
+ import type { AgentSession, Client, Job, Route, ToolApproval, ToolProvider } from '../core/contracts/types';
7
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
8
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
+ import type { AgentClientRunRecord } from '../infrastructure/config/config-agent-client-runtime-repository';
10
+ import {
11
+ AgentToolApiError,
12
+ invokeAgentToolFor,
13
+ listAgentToolsFor,
14
+ resumeAgentToolFor,
15
+ type AgentToolAuthContext,
16
+ } from './agent-tool-invocations';
17
+ import type { ToolProxyDeps } from './tool-proxy';
18
+
19
+ const SESSION_ID = '11111111-1111-4111-8111-111111111111';
20
+ const AGENT_RUN_ID = '22222222-2222-4222-8222-222222222222';
21
+
22
+ function invocationId(char: string): string { return char.repeat(64); }
23
+
24
+ function listen(server: Server): Promise<number> {
25
+ return new Promise((resolve, reject) => {
26
+ server.once('error', reject);
27
+ server.listen(0, '127.0.0.1', () => {
28
+ const address = server.address();
29
+ if (!address || typeof address === 'string') reject(new Error('missing address'));
30
+ else resolve(address.port);
31
+ });
32
+ });
33
+ }
34
+
35
+ function close(server: Server): Promise<void> {
36
+ return new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
37
+ }
38
+
39
+ function acc(scope: string, extra: Record<string, unknown> = {}): Record<string, unknown> {
40
+ return { 'x-agent-capability': { version: 1, enabled: true, scope, subject: { required: true }, ...extra } };
41
+ }
42
+
43
+ function spec(): string {
44
+ return JSON.stringify({
45
+ openapi: '3.0.0',
46
+ info: { title: 'Example Business', version: '1' },
47
+ paths: {
48
+ '/staff/list': {
49
+ get: {
50
+ operationId: 'staff_list', summary: '查询员工', ...acc('tenant.staff.read'),
51
+ parameters: [{ name: 'keyword', in: 'query', description: '关键字', schema: { type: 'string', maxLength: 64 } }],
52
+ },
53
+ },
54
+ '/staff/edit': {
55
+ post: {
56
+ operationId: 'staff_edit', summary: '修改员工', ...acc('tenant.staff.write', { risk: { level: 'medium' } }),
57
+ requestBody: { required: true, content: { 'application/json': { schema: {
58
+ type: 'object', required: ['id', 'name'], additionalProperties: false,
59
+ properties: { id: { type: 'integer' }, name: { type: 'string', minLength: 1, maxLength: 64 } },
60
+ } } } },
61
+ },
62
+ },
63
+ '/recharge/refund': {
64
+ post: {
65
+ operationId: 'recharge_refund', summary: '资金退款,不可撤销', ...acc('tenant.recharge.write', { risk: { level: 'medium' } }),
66
+ requestBody: { required: true, content: { 'application/json': { schema: {
67
+ type: 'object', required: ['id'], properties: { id: { type: 'integer' } },
68
+ } } } },
69
+ },
70
+ },
71
+ },
72
+ });
73
+ }
74
+
75
+ class MemoryState {
76
+ jobs = new Map<string, Job>();
77
+ byRequest = new Map<string, string>();
78
+ locks = new Map<string, string>();
79
+ audits: Array<Record<string, unknown>> = [];
80
+
81
+ async findByRequestId(requestId: string) { const id = this.byRequest.get(requestId); return id ? this.jobs.get(id) ?? null : null; }
82
+ async createJob(job: Job) { if (this.byRequest.has(job.request_id)) throw new Error('duplicate'); this.jobs.set(job.job_id, job); this.byRequest.set(job.request_id, job.job_id); }
83
+ async updateJob(jobId: string, patch: Partial<Job>) { const job = this.jobs.get(jobId); if (!job) return null; const next = { ...job, ...patch, updated_at: new Date().toISOString() }; this.jobs.set(jobId, next); return next; }
84
+ async getJob(jobId: string) { return this.jobs.get(jobId) ?? null; }
85
+ async appendAudit(entry: Record<string, unknown>) { this.audits.push(entry); }
86
+ async acquireRuntimeLock(key: string, owner: string) { if (this.locks.has(key)) return false; this.locks.set(key, owner); return true; }
87
+ async releaseRuntimeLock(key: string, owner: string) { if (this.locks.get(key) === owner) this.locks.delete(key); }
88
+ }
89
+
90
+ function route(): Route {
91
+ return {
92
+ route_key: 'tenant-agent', name: '门店助手', enabled: true, target: 'llm', target_config: {},
93
+ profile: 'general', permission: 'full', session_policy: 'new',
94
+ audience: { enabled: true, roles: ['admin'], clients: ['example-business'] },
95
+ tools: {
96
+ sources: [{ provider: 'example-business', allow: ['*'], subject_field: 'operator_uid' }],
97
+ max_calls: 5,
98
+ agent_direct: { enabled: true, write_tools: ['staff_edit'] },
99
+ },
100
+ };
101
+ }
102
+
103
+ function routeWithForcedApproval(tool = 'staff_edit'): Route {
104
+ const value = route();
105
+ value.tools = {
106
+ ...value.tools,
107
+ agent_direct: { enabled: true, write_tools: ['staff_edit'], force_approval_tools: [tool] },
108
+ };
109
+ return value;
110
+ }
111
+
112
+ function auth(): AgentToolAuthContext {
113
+ const client: Client = {
114
+ app_id: 'example-business', name: 'Example Business', token: 'hidden', agent_authorize_url: 'https://biz.example.com/agent',
115
+ allowed_routes: ['tenant-agent'], allowed_channels: [], rate_limit_per_min: 0, enabled: true,
116
+ };
117
+ const session: AgentSession = {
118
+ session_id: SESSION_ID, client_app_id: client.app_id, device_label: 'test',
119
+ principal: { id: 'u7', tenant: 't1', roles: ['admin'] }, on_behalf_of: 't1:u7',
120
+ allowed_routes: ['tenant-agent'], created_at: '2026-01-01T00:00:00.000Z',
121
+ access_expires_at: '2099-01-01T00:00:00.000Z', refresh_expires_at: '2099-02-01T00:00:00.000Z',
122
+ };
123
+ return { client, session };
124
+ }
125
+
126
+ function fixture(baseUrl: string) {
127
+ const state = new MemoryState();
128
+ let currentRoute = route();
129
+ let currentSpec = spec();
130
+ let toolRateLimited = false;
131
+ let runtimeRun: AgentClientRunRecord | null = null;
132
+ const approvals: ToolApproval[] = [];
133
+ const calls = new Map<string, ToolExecutionJournalEntry>();
134
+ const key = (jobId: string, tool: string, hash: string) => `${jobId}\0${tool}\0${hash}`;
135
+ const provider: ToolProvider = {
136
+ name: 'example-business', base_url: baseUrl, secret: 'provider-secret', enabled: true,
137
+ spec_source: 'inline', get spec_json() { return currentSpec; },
138
+ log_payload: false, timeout_ms: 10_000, rate_limit_per_min: 0,
139
+ } as ToolProvider;
140
+ const config = {
141
+ routes: { get: async () => currentRoute },
142
+ toolProviders: { get: async () => provider },
143
+ rateLimits: { consume: async () => toolRateLimited },
144
+ approvals: {
145
+ forJob: async (jobId: string) => approvals.filter((item) => item.job_id === jobId),
146
+ approvedUnusedForJob: async (jobId: string) => approvals.filter((item) => item.job_id === jobId && item.status === 'approved' && !item.used_at),
147
+ find: async (jobId: string, tool: string, hash: string, status: string, unused = false) => approvals.find((item) => item.job_id === jobId && item.tool === tool && item.args_hash === hash && item.status === status && (!unused || !item.used_at)) ?? null,
148
+ use: async (id: number) => { const item = approvals.find((row) => row.id === id); if (!item || item.status !== 'approved' || item.used_at) return false; item.used_at = new Date().toISOString(); return true; },
149
+ create: async (value: Omit<ToolApproval, 'id' | 'status' | 'created_at'>) => {
150
+ const id = approvals.length + 1;
151
+ approvals.push({ ...value, id, status: 'pending', created_at: new Date().toISOString() });
152
+ return id;
153
+ },
154
+ },
155
+ toolCalls: {
156
+ get: async (jobId: string, tool: string, hash: string) => calls.get(key(jobId, tool, hash)) ?? null,
157
+ reserve: async (jobId: string, tool: string, _scope: string, hash: string, idempotencyKey: string) => {
158
+ const k = key(jobId, tool, hash); const existing = calls.get(k);
159
+ if (existing) return { inserted: false, entry: existing };
160
+ const entry: ToolExecutionJournalEntry = { state: 'dispatching', ok: false, status: 0, text: '', idempotencyKey };
161
+ calls.set(k, entry); return { inserted: true, entry };
162
+ },
163
+ recordResponse: async (jobId: string, tool: string, hash: string, response: { ok: boolean; status: number; text: string }) => {
164
+ const k = key(jobId, tool, hash); const old = calls.get(k); if (!old) throw new Error('missing');
165
+ calls.set(k, { ...old, ...response, state: 'response_recorded' });
166
+ },
167
+ complete: async (jobId: string, tool: string, hash: string) => { const k = key(jobId, tool, hash); const old = calls.get(k); if (!old) throw new Error('missing'); calls.set(k, { ...old, state: 'completed' }); },
168
+ markUncertain: async (jobId: string, tool: string, hash: string, error: string) => { const k = key(jobId, tool, hash); const old = calls.get(k); if (old) calls.set(k, { ...old, state: 'uncertain', error }); },
169
+ markEvidenceDegraded: async (jobId: string, tool: string, hash: string, error: string) => { const k = key(jobId, tool, hash); const old = calls.get(k); if (old) calls.set(k, { ...old, state: 'evidence_degraded', error }); },
170
+ },
171
+ agentClientRuntime: { findRunForInvocation: async () => runtimeRun },
172
+ } as unknown as ConfigStoreContract;
173
+ const deps: ToolProxyDeps = {
174
+ cfg: { brand: { name: 'BailingHub' }, server: { token: 'server-token' } } as AppConfig,
175
+ configStore: config, stateStore: state as unknown as RuntimeStateStore, toolIndex: null,
176
+ now: () => new Date().toISOString(), sleep: async () => undefined,
177
+ };
178
+ return {
179
+ deps,
180
+ state,
181
+ approvals,
182
+ setRoute: (value: Route) => { currentRoute = value; },
183
+ setSpec: (value: string) => { currentSpec = value; },
184
+ setToolRateLimited: (value: boolean) => { toolRateLimited = value; },
185
+ setRuntimeRun: (value: AgentClientRunRecord | null) => { runtimeRun = value; },
186
+ };
187
+ }
188
+
189
+ function runtimeRun(overrides: Partial<AgentClientRunRecord> = {}): AgentClientRunRecord {
190
+ return {
191
+ run_id: AGENT_RUN_ID, session_id: SESSION_ID, client_app_id: 'example-business', route_key: 'tenant-agent', thread_id: 42,
192
+ client_conversation_id: 'c1', client_turn_id: 't1', user_message_id: 'm1', request_hash: 'a'.repeat(64), user_input: 'query',
193
+ context: { schema_version: 'bailing.agent-turn-context.v1' }, status: 'context_ready', completion_hash: null,
194
+ assistant_message_id: null, final_content: null, model: null, runtime: null, usage: null,
195
+ created_at: '2026-01-01T00:00:00.000Z', updated_at: '2026-01-01T00:00:00.000Z', completed_at: null,
196
+ ...overrides,
197
+ };
198
+ }
199
+
200
+ test('Agent direct: 本地投影只含只读与精确写工具,写工具默认继承 ACC 审批声明', async (t) => {
201
+ let businessCalls = 0;
202
+ const business = createServer(async (req, res) => {
203
+ businessCalls++;
204
+ assert.equal(req.headers['x-bailing-on-behalf-of'], 't1:u7');
205
+ assert.match(String(req.headers['x-bailing-signature']), /^sha256=[a-f0-9]{64}$/);
206
+ const chunks: Buffer[] = [];
207
+ for await (const chunk of req) chunks.push(chunk as Buffer);
208
+ res.writeHead(200, { 'content-type': 'application/json' });
209
+ res.end(JSON.stringify({ ok: true, path: req.url, body: Buffer.concat(chunks).toString('utf8') }));
210
+ });
211
+ const port = await listen(business);
212
+ t.after(() => close(business));
213
+ const fx = fixture(`http://127.0.0.1:${port}`);
214
+
215
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
216
+ assert.deepEqual(catalog.tools.map((item) => item.name), ['staff_edit', 'staff_list']);
217
+ assert.equal(catalog.tools.find((item) => item.name === 'staff_edit')?.approval_required, false);
218
+ assert.equal(catalog.tools.some((item) => item.name === 'recharge_refund'), false);
219
+ assert.equal(JSON.stringify(catalog).includes('provider-secret'), false);
220
+ assert.equal(JSON.stringify(catalog).includes('127.0.0.1'), false);
221
+
222
+ const read = await invokeAgentToolFor(fx.deps, auth(), {
223
+ invocation_id: invocationId('a'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
224
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_list', arguments: { keyword: 'Ada' },
225
+ });
226
+ assert.equal(read.state, 'executed');
227
+ assert.equal(read.ok, true);
228
+ assert.equal(businessCalls, 1);
229
+ assert.ok([...fx.state.jobs.values()].every((job) => job.target === 'agent-tool-v1' && job.status === 'done'));
230
+
231
+ const write = await invokeAgentToolFor(fx.deps, auth(), {
232
+ invocation_id: invocationId('b'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
233
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Ada' },
234
+ });
235
+ assert.equal(write.state, 'executed');
236
+ assert.equal(write.ok, true);
237
+ assert.equal(businessCalls, 2);
238
+ assert.equal(fx.approvals.length, 0);
239
+ });
240
+
241
+ test('Agent direct: 路由精确列出的写工具额外强制审批并可续执行', async (t) => {
242
+ let businessCalls = 0;
243
+ const business = createServer((_req, res) => {
244
+ businessCalls++;
245
+ res.writeHead(200, { 'content-type': 'application/json' });
246
+ res.end('{"ok":true}');
247
+ });
248
+ const port = await listen(business);
249
+ t.after(() => close(business));
250
+ const fx = fixture(`http://127.0.0.1:${port}`);
251
+ fx.setRoute(routeWithForcedApproval());
252
+
253
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
254
+ assert.equal(catalog.tools.find((item) => item.name === 'staff_edit')?.approval_required, true);
255
+ const pending = await invokeAgentToolFor(fx.deps, auth(), {
256
+ invocation_id: invocationId('8'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
257
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Ada' },
258
+ });
259
+ assert.equal(pending.state, 'awaiting_approval');
260
+ assert.equal(pending.approval_id, 1);
261
+ assert.equal(businessCalls, 0, '审批前不得外发写请求');
262
+ assert.equal(fx.approvals.length, 1);
263
+
264
+ fx.approvals[0]!.status = 'approved';
265
+ // 其他工具的描述变更会改变整份 catalog revision,但 staff_edit 的执行指纹未变。
266
+ fx.setSpec(spec().replace('查询员工', '查询门店员工'));
267
+ const completed = await resumeAgentToolFor(fx.deps, auth(), {
268
+ invocation_id: invocationId('8'),
269
+ });
270
+ assert.equal(completed.state, 'executed');
271
+ assert.equal(businessCalls, 1);
272
+ const again = await resumeAgentToolFor(fx.deps, auth(), {
273
+ invocation_id: invocationId('8'),
274
+ });
275
+ assert.deepEqual(again, completed);
276
+ assert.equal(businessCalls, 1, '完成后 resume 必须返回已存结果,不得重复写');
277
+ });
278
+
279
+ test('Agent direct: ACC 高风险写工具在默认继承模式下仍需要审批', async () => {
280
+ const fx = fixture('https://business.invalid');
281
+ fx.setSpec(spec().replace('"risk":{"level":"medium"}', '"risk":{"level":"high"}'));
282
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
283
+ assert.equal(catalog.tools.find((item) => item.name === 'staff_edit')?.approval_required, true);
284
+ const pending = await invokeAgentToolFor(fx.deps, auth(), {
285
+ invocation_id: invocationId('6'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
286
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Ada' },
287
+ });
288
+ assert.equal(pending.state, 'awaiting_approval');
289
+ assert.equal(fx.approvals.length, 1);
290
+ });
291
+
292
+ test('Agent direct: invocation 与 agent_run_id/参数不可变绑定', async (t) => {
293
+ let businessCalls = 0;
294
+ const business = createServer((_req, res) => {
295
+ businessCalls++;
296
+ res.writeHead(200, { 'content-type': 'application/json' });
297
+ res.end('{"ok":true}');
298
+ });
299
+ const port = await listen(business);
300
+ t.after(() => close(business));
301
+ const fx = fixture(`http://127.0.0.1:${port}`);
302
+ const authorized = auth();
303
+ const catalog = await listAgentToolsFor(fx.deps, authorized, 'tenant-agent');
304
+ const original = {
305
+ invocation_id: invocationId('d'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
306
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_list', arguments: { keyword: 'Ada' },
307
+ };
308
+ assert.equal((await invokeAgentToolFor(fx.deps, authorized, original)).state, 'executed');
309
+ await assert.rejects(
310
+ invokeAgentToolFor(fx.deps, authorized, { ...original, agent_run_id: '33333333-3333-4333-8333-333333333333' }),
311
+ (error) => error instanceof AgentToolApiError && error.code === 'invocation_conflict',
312
+ );
313
+ await assert.rejects(
314
+ invokeAgentToolFor(fx.deps, authorized, { ...original, arguments: { keyword: 'Grace' } }),
315
+ (error) => error instanceof AgentToolApiError && error.code === 'invocation_conflict',
316
+ );
317
+ authorized.session.allowed_routes = [];
318
+ await assert.rejects(
319
+ invokeAgentToolFor(fx.deps, authorized, original),
320
+ (error) => error instanceof AgentToolApiError && error.code === 'route_not_allowed',
321
+ );
322
+ assert.equal(businessCalls, 1);
323
+ });
324
+
325
+ test('Agent direct: Runtime run 重验 session/route,合法 run 把 thread 关联到 job 与审计', async (t) => {
326
+ const business = createServer((_req, res) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"ok":true}'); });
327
+ const port = await listen(business);
328
+ t.after(() => close(business));
329
+ const fx = fixture(`http://127.0.0.1:${port}`);
330
+ const authorized = auth();
331
+ const catalog = await listAgentToolsFor(fx.deps, authorized, 'tenant-agent');
332
+ const input = {
333
+ invocation_id: invocationId('7'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
334
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_list', arguments: {},
335
+ };
336
+ fx.setRuntimeRun(runtimeRun({ session_id: '99999999-9999-4999-8999-999999999999' }));
337
+ await assert.rejects(
338
+ invokeAgentToolFor(fx.deps, authorized, input),
339
+ (error) => error instanceof AgentToolApiError && error.code === 'agent_run_conflict',
340
+ );
341
+
342
+ fx.setRuntimeRun(runtimeRun());
343
+ assert.equal((await invokeAgentToolFor(fx.deps, authorized, input)).state, 'executed');
344
+ const job = [...fx.state.jobs.values()].find((candidate) => candidate.metadata?.['agent_invocation_id'] === input.invocation_id);
345
+ assert.equal(job?.thread_id, 42);
346
+ const created = fx.state.audits.find((entry) => entry['event'] === 'agent_tool_invocation_created') as any;
347
+ assert.equal(created?.detail?.agent_thread_id, 42);
348
+ });
349
+
350
+ test('Agent direct: 终态回放仍重验当前具体工具授权', async (t) => {
351
+ let businessCalls = 0;
352
+ const business = createServer((_req, res) => {
353
+ businessCalls++;
354
+ res.writeHead(200, { 'content-type': 'application/json' });
355
+ res.end('{"ok":true}');
356
+ });
357
+ const port = await listen(business);
358
+ t.after(() => close(business));
359
+ const fx = fixture(`http://127.0.0.1:${port}`);
360
+ const authorized = auth();
361
+ const catalog = await listAgentToolsFor(fx.deps, authorized, 'tenant-agent');
362
+ const original = {
363
+ invocation_id: invocationId('9'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
364
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_list', arguments: { keyword: 'Ada' },
365
+ };
366
+ assert.equal((await invokeAgentToolFor(fx.deps, authorized, original)).state, 'executed');
367
+
368
+ const narrowed = route();
369
+ narrowed.tools = {
370
+ ...narrowed.tools,
371
+ sources: [{ provider: 'example-business', allow: ['staff_edit'], subject_field: 'operator_uid' }],
372
+ };
373
+ fx.setRoute(narrowed);
374
+ await assert.rejects(
375
+ invokeAgentToolFor(fx.deps, authorized, original),
376
+ (error) => error instanceof AgentToolApiError && error.code === 'capability_changed',
377
+ );
378
+ await assert.rejects(
379
+ resumeAgentToolFor(fx.deps, authorized, { invocation_id: original.invocation_id }),
380
+ (error) => error instanceof AgentToolApiError && error.code === 'capability_changed',
381
+ );
382
+ assert.equal(businessCalls, 1, '授权撤销后不得因终态回放再次访问业务侧');
383
+ });
384
+
385
+ test('Agent direct: 当前工具执行契约变更时审批快照不执行', async () => {
386
+ const fx = fixture('https://business.invalid');
387
+ fx.setRoute(routeWithForcedApproval());
388
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
389
+ const pending = await invokeAgentToolFor(fx.deps, auth(), {
390
+ invocation_id: invocationId('e'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
391
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Ada' },
392
+ });
393
+ assert.equal(pending.state, 'awaiting_approval');
394
+ fx.approvals[0]!.status = 'approved';
395
+ fx.setSpec(spec().replace('/staff/edit', '/staff/edit-v2'));
396
+ await assert.rejects(
397
+ resumeAgentToolFor(fx.deps, auth(), {
398
+ invocation_id: invocationId('e'),
399
+ }),
400
+ (error) => error instanceof AgentToolApiError && error.code === 'capability_changed',
401
+ );
402
+ assert.equal(fx.approvals[0]!.used_at, undefined);
403
+ });
404
+
405
+ test('Agent direct: 工具限流不消费批准,同 invocation 可安全重试', async (t) => {
406
+ let businessCalls = 0;
407
+ const business = createServer((_req, res) => {
408
+ businessCalls++;
409
+ res.writeHead(200, { 'content-type': 'application/json' });
410
+ res.end('{"ok":true}');
411
+ });
412
+ const port = await listen(business);
413
+ t.after(() => close(business));
414
+ const fx = fixture(`http://127.0.0.1:${port}`);
415
+ fx.setRoute(routeWithForcedApproval());
416
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
417
+ const invocation_id = invocationId('f');
418
+ const pending = await invokeAgentToolFor(fx.deps, auth(), {
419
+ invocation_id, route: 'tenant-agent', capability_revision: catalog.capability_revision,
420
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Ada' },
421
+ });
422
+ assert.equal(pending.state, 'awaiting_approval');
423
+ fx.approvals[0]!.status = 'approved';
424
+ fx.setToolRateLimited(true);
425
+ const limited = await resumeAgentToolFor(fx.deps, auth(), {
426
+ invocation_id,
427
+ });
428
+ assert.equal(limited.state, 'rejected_before_dispatch');
429
+ assert.equal(limited.auto_retry_allowed, true);
430
+ assert.equal(limited.business_status, undefined);
431
+ assert.equal(fx.approvals[0]!.used_at, undefined);
432
+ assert.equal(businessCalls, 0);
433
+
434
+ fx.setToolRateLimited(false);
435
+ const completed = await resumeAgentToolFor(fx.deps, auth(), {
436
+ invocation_id,
437
+ });
438
+ assert.equal(completed.state, 'executed');
439
+ assert.ok(fx.approvals[0]!.used_at);
440
+ assert.equal(businessCalls, 1);
441
+ });
442
+
443
+ test('Agent direct: capability revision 变更、参数漂移和未开启路由均失败关闭', async () => {
444
+ const fx = fixture('https://business.invalid');
445
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
446
+ fx.setSpec(spec().replace('查询员工', '查询门店员工'));
447
+ await assert.rejects(
448
+ invokeAgentToolFor(fx.deps, auth(), {
449
+ invocation_id: invocationId('c'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
450
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_list', arguments: {},
451
+ }),
452
+ (error) => error instanceof AgentToolApiError && error.code === 'capability_changed',
453
+ );
454
+
455
+ const disabled = route();
456
+ disabled.tools = { ...disabled.tools, agent_direct: { enabled: false } };
457
+ fx.setRoute(disabled);
458
+ await assert.rejects(
459
+ listAgentToolsFor(fx.deps, auth(), 'tenant-agent'),
460
+ (error) => error instanceof AgentToolApiError && error.code === 'agent_direct_disabled',
461
+ );
462
+ });