bailinghub 0.3.4 → 0.5.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 (169) hide show
  1. package/.gitignore +5 -0
  2. package/README.en.md +6 -1
  3. package/README.md +6 -0
  4. package/SECURITY.md +11 -0
  5. package/docker-compose.images.yml +2 -2
  6. package/docs/AGENT_AUTH_API.en.md +175 -0
  7. package/docs/AGENT_AUTH_API.md +190 -0
  8. package/docs/AGENT_CLIENT_QUICKSTART.en.md +212 -0
  9. package/docs/AGENT_CLIENT_QUICKSTART.md +206 -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 +59 -1
  13. package/docs/CHANGELOG.md +27 -1
  14. package/docs/COMPATIBILITY.en.md +25 -0
  15. package/docs/CONTRACT.en.md +79 -8
  16. package/docs/CONTRACT.md +36 -6
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/QUICKSTART.en.md +6 -0
  20. package/docs/QUICKSTART.md +1 -1
  21. package/docs/README.en.md +8 -0
  22. package/docs/README.md +8 -0
  23. package/docs/RELEASE_NOTES_v0.4.0.en.md +39 -0
  24. package/docs/RELEASE_NOTES_v0.4.0.md +39 -0
  25. package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
  26. package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
  27. package/docs/STREAMING.en.md +32 -0
  28. package/docs/STREAMING.md +8 -2
  29. package/docs/WIDGET_RENDERERS.en.md +123 -6
  30. package/docs/WIDGET_RENDERERS.md +75 -6
  31. package/docs/user-guide/console-map.en.md +1 -2
  32. package/docs/user-guide/console-map.md +2 -2
  33. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +9 -0
  34. package/package.json +3 -2
  35. package/schemas/config/chat-entry.schema.json +2 -1
  36. package/schemas/config/client.schema.json +7 -0
  37. package/schemas/config/common.schema.json +30 -0
  38. package/schemas/config/route.schema.json +11 -0
  39. package/scripts/check-doc-links.mjs +1 -0
  40. package/scripts/check-image-tags.sh +1 -1
  41. package/scripts/check-release-consistency.test.mjs +5 -5
  42. package/scripts/e2e-console.mjs +144 -0
  43. package/scripts/export-oss.mjs +5 -12
  44. package/scripts/install.sh +1 -1
  45. package/scripts/public-content-denylist.mjs +82 -0
  46. package/scripts/public-content-denylist.test.mjs +53 -0
  47. package/scripts/publish-images.sh +1 -1
  48. package/scripts/release-audit.mjs +8 -12
  49. package/scripts/sdk-runtime-test.mjs +171 -7
  50. package/scripts/security-scan.mjs +8 -5
  51. package/scripts/validate-examples.mjs +3 -1
  52. package/scripts/verify-github-repo.mjs +7 -11
  53. package/scripts/verify-oss-export.mjs +6 -12
  54. package/scripts/widget-renderer-test.mjs +244 -16
  55. package/sdk/php/README.md +27 -1
  56. package/sdk/php/src/AgentAuth.php +78 -0
  57. package/sdk/php/src/HubClient.php +3 -0
  58. package/sdk/php7/README.md +32 -2
  59. package/sdk/php7/src/AgentAuth.php +77 -0
  60. package/sdk/php7/src/HubClient.php +3 -0
  61. package/sql/055_agent_auth.sql +72 -0
  62. package/sql/056_agent_client_runtime.sql +60 -0
  63. package/src/adapters/channels/wecom-api.ts +1 -1
  64. package/src/app/agent-client-runtime.test.ts +221 -0
  65. package/src/app/agent-client-runtime.ts +408 -0
  66. package/src/app/agent-tool-invocations.test.ts +462 -0
  67. package/src/app/agent-tool-invocations.ts +795 -0
  68. package/src/app/agent-tool-job.test.ts +62 -0
  69. package/src/app/agent-tool-job.ts +41 -0
  70. package/src/app/auth.ts +2 -1
  71. package/src/app/kernel.ts +2 -0
  72. package/src/app/runtime-context.ts +8 -0
  73. package/src/app/tool-approvals.ts +5 -1
  74. package/src/app/tool-assembly.ts +19 -1
  75. package/src/app/tool-context.ts +2 -1
  76. package/src/core/config/config-codec.ts +2 -1
  77. package/src/core/config/config-models.test.ts +28 -1
  78. package/src/core/config/config-models.ts +46 -3
  79. package/src/core/config/config-schema.test.ts +8 -0
  80. package/src/core/config/route-config.test.ts +15 -0
  81. package/src/core/config/route-config.ts +36 -0
  82. package/src/core/config/tools-config.test.ts +58 -1
  83. package/src/core/config/tools-config.ts +84 -0
  84. package/src/core/contracts/tools.ts +162 -29
  85. package/src/core/contracts/types.ts +38 -1
  86. package/src/core/platform/chat-form.test.ts +147 -0
  87. package/src/core/platform/chat-form.ts +402 -0
  88. package/src/core/platform/version.ts +1 -1
  89. package/src/core/runtime/agent-client-trace.test.ts +154 -0
  90. package/src/core/runtime/agent-client-trace.ts +288 -0
  91. package/src/core/runtime/execution-runtime.test.ts +61 -0
  92. package/src/core/runtime/execution-runtime.ts +17 -0
  93. package/src/core/runtime/launch-runtime.ts +13 -0
  94. package/src/core/runtime/trace-runtime.test.ts +18 -1
  95. package/src/core/runtime/trace-runtime.ts +28 -3
  96. package/src/core/state/state-codec.ts +2 -0
  97. package/src/infrastructure/config/config-agent-auth-repository.test.ts +147 -0
  98. package/src/infrastructure/config/config-agent-auth-repository.ts +356 -0
  99. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +253 -0
  100. package/src/infrastructure/config/config-approval-ledger.test.ts +32 -0
  101. package/src/infrastructure/config/config-approval-ledger.ts +16 -0
  102. package/src/infrastructure/config/config-client-repository.ts +3 -3
  103. package/src/infrastructure/config/config-conversation-ledger.test.ts +69 -0
  104. package/src/infrastructure/config/config-conversation-ledger.ts +8 -7
  105. package/src/infrastructure/config/config-observability-ledger.test.ts +50 -0
  106. package/src/infrastructure/config/config-observability-ledger.ts +65 -10
  107. package/src/infrastructure/config/config-route-repository.ts +4 -3
  108. package/src/infrastructure/config/configstore.ts +14 -3
  109. package/src/infrastructure/state/state-mysql.ts +2 -2
  110. package/src/kernel-api/v1/contracts.ts +8 -0
  111. package/src/routes/admin-runtime.test.ts +214 -0
  112. package/src/routes/admin-runtime.ts +82 -2
  113. package/src/routes/agent-api.test.ts +379 -0
  114. package/src/routes/agent-api.ts +251 -0
  115. package/src/routes/agent-auth.test.ts +276 -0
  116. package/src/routes/agent-auth.ts +395 -0
  117. package/src/routes/approvals.ts +4 -1
  118. package/src/routes/chat.test.ts +319 -7
  119. package/src/routes/chat.ts +166 -21
  120. package/src/routes/critical-routes.test.ts +235 -1
  121. package/src/routes/private-default.ts +2 -1
  122. package/src/routes/private.ts +16 -1
  123. package/src/routes/run.ts +79 -13
  124. package/web/connect/bailing-connect-php.tgz +0 -0
  125. package/web/connect/bailing-connect-php7.tgz +0 -0
  126. package/web/console/assets/{Accounts-CAwrtBiS.js → Accounts-D4RRm5D1.js} +1 -1
  127. package/web/console/assets/{Approvals-C2BZ86T3.js → Approvals-CsTTKb8o.js} +1 -1
  128. package/web/console/assets/{Audit-B-E4Y_Up.js → Audit-BzvZ7JZw.js} +1 -1
  129. package/web/console/assets/{BrandLockup-C18u8Lx5.js → BrandLockup-CYcA93wh.js} +1 -1
  130. package/web/console/assets/{Channels-DTy8ylH-.js → Channels-DRQZggqM.js} +1 -1
  131. package/web/console/assets/ChatEntries-BUB7BWKU.js +7 -0
  132. package/web/console/assets/ChatEntries-DsYtcXN6.css +1 -0
  133. package/web/console/assets/Clients-CQ_MonGL.css +1 -0
  134. package/web/console/assets/Clients-HhCyrxfz.js +3 -0
  135. package/web/console/assets/{Cost-2SSYs1AT.js → Cost-BZgFf1yM.js} +1 -1
  136. package/web/console/assets/{Credentials-B79LtxCE.js → Credentials-BTe2Q07j.js} +1 -1
  137. package/web/console/assets/{Diagnostics-BakcRYvb.js → Diagnostics-WL-buYli.js} +1 -1
  138. package/web/console/assets/{Executors-BXoyo28u.js → Executors-CGZ-7Xmp.js} +1 -1
  139. package/web/console/assets/{Kb-ISbzquab.js → Kb-VVw8oGsT.js} +1 -1
  140. package/web/console/assets/{Login-Dlu6Wgcf.js → Login-rwvmBBPl.js} +1 -1
  141. package/web/console/assets/{Projects-DFzmtnqg.js → Projects-CexaCEY1.js} +1 -1
  142. package/web/console/assets/Routes-B9ZHbQAp.js +124 -0
  143. package/web/console/assets/Routes-BbkFpi6Y.css +1 -0
  144. package/web/console/assets/Runs-4zDD9VOC.css +1 -0
  145. package/web/console/assets/Runs-BzFNPTwD.js +3 -0
  146. package/web/console/assets/{Setup-CrBAV-b9.js → Setup-Djh5yadQ.js} +1 -1
  147. package/web/console/assets/{Shell-B1a8DvXQ.js → Shell-kn763smL.js} +1 -1
  148. package/web/console/assets/{StorageBuckets-BRfL_eHb.js → StorageBuckets-CQBR41W1.js} +1 -1
  149. package/web/console/assets/{SystemSettings-CyirVLbq.js → SystemSettings-DgnopekD.js} +1 -1
  150. package/web/console/assets/{SystemStatus-DZ_OR7sk.js → SystemStatus-Bj8-kPt2.js} +1 -1
  151. package/web/console/assets/{Targets-CtIMa66c.js → Targets-BAfCt_nH.js} +1 -1
  152. package/web/console/assets/{Tools-BfDZHt01.js → Tools-xjd0NZdE.js} +1 -1
  153. package/web/console/assets/{index-DBiByFiO.js → index-DfJA7iJS.js} +2 -2
  154. package/web/console/assets/{request-DY2cxQqZ.js → request-DkNPOweH.js} +1 -1
  155. package/web/console/assets/{schema-6mCQ7rR5.js → schema-CgPWAu1_.js} +1 -1
  156. package/web/console/index.html +1 -1
  157. package/web/widget/widget.js +493 -14
  158. package/web-admin/src/pages/ChatEntries.vue +18 -6
  159. package/web-admin/src/pages/Clients.vue +11 -3
  160. package/web-admin/src/pages/Routes.vue +282 -16
  161. package/web-admin/src/pages/Runs.vue +159 -38
  162. package/web/console/assets/ChatEntries-9xbRiQov.css +0 -1
  163. package/web/console/assets/ChatEntries-DvD-4IeE.js +0 -7
  164. package/web/console/assets/Clients--D7NQJKk.css +0 -1
  165. package/web/console/assets/Clients-DWs9JFr0.js +0 -3
  166. package/web/console/assets/Routes-B-hm9HGY.js +0 -124
  167. package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
  168. package/web/console/assets/Runs-CUtSsPW-.css +0 -1
  169. package/web/console/assets/Runs-hMRu1im3.js +0 -3
@@ -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
+ });
@@ -0,0 +1,251 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { PayloadTooLargeError, readBody, send } from '../app/http';
3
+ import type { Principal } from '../app/auth';
4
+ import type { ToolProxyDeps } from '../app/tool-proxy';
5
+ import {
6
+ AgentToolApiError,
7
+ invokeAgentToolFor,
8
+ listAgentToolsFor,
9
+ resumeAgentToolFor,
10
+ type InvokeAgentToolInput,
11
+ type ResumeAgentToolInput,
12
+ } from '../app/agent-tool-invocations';
13
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
14
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
15
+ import { authenticateAgentAccess } from './agent-auth';
16
+ import type { KbService } from '../services/kb';
17
+ import {
18
+ completeAgentRunFor,
19
+ getAgentWorkspaceBootstrapFor,
20
+ listAgentWorkspacesFor,
21
+ prepareAgentTurnFor,
22
+ searchAgentCapabilitiesFor,
23
+ type AgentClientRuntimeDeps,
24
+ } from '../app/agent-client-runtime';
25
+
26
+ export interface AgentApiHttpDeps {
27
+ configStore: ConfigStoreContract | null;
28
+ stateStore: RuntimeStateStore;
29
+ isPaused: () => boolean;
30
+ handleRun(req: IncomingMessage, res: ServerResponse, principal: Principal): Promise<void>;
31
+ /** 未注入时仅关闭新的无模型直调面,保持旧宿主的 Agent Auth / run 兼容。 */
32
+ toolProxyDeps?: ToolProxyDeps;
33
+ kbService?: KbService | null;
34
+ }
35
+
36
+ // 64000 个 UTF-16 code units 在 JSON 中最坏可被转义为约 384 KB;512 KiB 还可容纳
37
+ // Turn 的 16 KiB page_context、renderer/标识字段与固定 envelope,同时保留预解析内存上限。
38
+ const AGENT_RUNTIME_JSON_BODY_MAX_BYTES = 512 * 1024;
39
+
40
+ function record(value: unknown): Record<string, unknown> | null {
41
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
42
+ }
43
+
44
+ function exactFields(body: Record<string, unknown>, expected: string[]): boolean {
45
+ const allowed = new Set(expected);
46
+ const fields = Object.keys(body);
47
+ return fields.length === expected.length && fields.every((key) => allowed.has(key));
48
+ }
49
+
50
+ function declaredFields(body: Record<string, unknown>, allowedFields: string[], requiredFields: string[] = []): boolean {
51
+ const allowed = new Set(allowedFields);
52
+ return Object.keys(body).every((key) => allowed.has(key)) && requiredFields.every((key) => Object.prototype.hasOwnProperty.call(body, key));
53
+ }
54
+
55
+ function sendAgentToolError(res: ServerResponse, error: unknown): void {
56
+ if (error instanceof AgentToolApiError) {
57
+ send(res, error.statusCode, { error: error.code, message: error.message });
58
+ return;
59
+ }
60
+ send(res, 500, { error: 'agent_tool_internal_error', message: 'The governed Agent tool operation failed.' });
61
+ }
62
+
63
+ async function readAgentToolBody(
64
+ req: IncomingMessage,
65
+ res: ServerResponse,
66
+ maxBytes: number,
67
+ ): Promise<Record<string, unknown> | null> {
68
+ try {
69
+ const body = record(await readBody(req, maxBytes));
70
+ if (!body) {
71
+ send(res, 400, { error: 'invalid_request', message: 'The request body must be a JSON object.' });
72
+ return null;
73
+ }
74
+ return body;
75
+ } catch (error) {
76
+ if (error instanceof PayloadTooLargeError) {
77
+ send(res, 413, { error: 'arguments_too_large', message: `The Agent tool request exceeds ${maxBytes} bytes.` });
78
+ } else {
79
+ send(res, 400, { error: 'invalid_request', message: 'The request body must be valid JSON.' });
80
+ }
81
+ return null;
82
+ }
83
+ }
84
+
85
+ /** Dedicated local-Agent API. Agent bearer tokens are never admitted to the legacy /run surface. */
86
+ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
87
+ const path = url.pathname;
88
+ if (!path.startsWith('/agent-api/')) return false;
89
+ res.setHeader('cache-control', 'no-store');
90
+ const auth = await authenticateAgentAccess(deps, req, url);
91
+ if (!auth) { send(res, 401, { error: 'unauthorized' }); return true; }
92
+ const principal: Principal = { kind: 'agent', session: auth.session, client: auth.client };
93
+ const method = req.method ?? 'GET';
94
+ const runtimeDeps = (): AgentClientRuntimeDeps | null => deps.toolProxyDeps
95
+ ? { toolProxyDeps: deps.toolProxyDeps, kbService: deps.kbService ?? null, stateStore: deps.stateStore }
96
+ : null;
97
+ if (method === 'GET' && path === '/agent-api/v1/workspaces') {
98
+ const runtime = runtimeDeps();
99
+ if (!runtime) { send(res, 503, { error: 'agent_runtime_unavailable' }); return true; }
100
+ try { send(res, 200, await listAgentWorkspacesFor(runtime, auth)); }
101
+ catch (error) { sendAgentToolError(res, error); }
102
+ return true;
103
+ }
104
+ const bootstrapMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/bootstrap$/) : null;
105
+ if (bootstrapMatch) {
106
+ const runtime = runtimeDeps();
107
+ if (!runtime) { send(res, 503, { error: 'agent_runtime_unavailable' }); return true; }
108
+ try { send(res, 200, await getAgentWorkspaceBootstrapFor(runtime, auth, bootstrapMatch[1]!)); }
109
+ catch (error) { sendAgentToolError(res, error); }
110
+ return true;
111
+ }
112
+ const turnMatch = method === 'POST' ? path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/turns$/) : null;
113
+ if (turnMatch) {
114
+ const runtime = runtimeDeps();
115
+ if (!runtime) { send(res, 503, { error: 'agent_runtime_unavailable' }); return true; }
116
+ if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
117
+ const body = await readAgentToolBody(req, res, AGENT_RUNTIME_JSON_BODY_MAX_BYTES);
118
+ if (!body) return true;
119
+ if (!declaredFields(body, ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input', 'page_context', 'renderers'], ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input'])
120
+ || typeof body['client_conversation_id'] !== 'string'
121
+ || typeof body['client_turn_id'] !== 'string'
122
+ || typeof body['user_message_id'] !== 'string'
123
+ || typeof body['user_input'] !== 'string'
124
+ || (body['page_context'] !== undefined && !record(body['page_context']))
125
+ || (body['renderers'] !== undefined && (!Array.isArray(body['renderers']) || !body['renderers'].every((value) => typeof value === 'string')))) {
126
+ send(res, 400, { error: 'invalid_request', message: 'The Agent turn contains missing or undeclared fields.' }); return true;
127
+ }
128
+ try {
129
+ send(res, 200, await prepareAgentTurnFor(runtime, auth, turnMatch[1]!, {
130
+ client_conversation_id: body['client_conversation_id'], client_turn_id: body['client_turn_id'],
131
+ user_message_id: body['user_message_id'], user_input: body['user_input'],
132
+ ...(record(body['page_context']) ? { page_context: record(body['page_context'])! } : {}),
133
+ ...(Array.isArray(body['renderers']) ? { renderers: body['renderers'] as string[] } : {}),
134
+ }));
135
+ } catch (error) { sendAgentToolError(res, error); }
136
+ return true;
137
+ }
138
+ const searchMatch = method === 'POST' ? path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/capabilities\/search$/) : null;
139
+ if (searchMatch) {
140
+ const runtime = runtimeDeps();
141
+ if (!runtime) { send(res, 503, { error: 'agent_runtime_unavailable' }); return true; }
142
+ const body = await readAgentToolBody(req, res, 8 * 1024);
143
+ if (!body) return true;
144
+ if (!declaredFields(body, ['query', 'limit', 'run_id'])
145
+ || (body['query'] !== undefined && typeof body['query'] !== 'string')
146
+ || (body['limit'] !== undefined && (!Number.isInteger(body['limit']) || Number(body['limit']) < 1 || Number(body['limit']) > 12))
147
+ || (body['run_id'] !== undefined && typeof body['run_id'] !== 'string')) {
148
+ send(res, 400, { error: 'invalid_request', message: 'The capability search contains undeclared or invalid fields.' }); return true;
149
+ }
150
+ try {
151
+ send(res, 200, await searchAgentCapabilitiesFor(runtime, auth, searchMatch[1]!, {
152
+ ...(typeof body['query'] === 'string' ? { query: body['query'] } : {}),
153
+ ...(typeof body['limit'] === 'number' ? { limit: body['limit'] } : {}),
154
+ ...(typeof body['run_id'] === 'string' ? { run_id: body['run_id'] } : {}),
155
+ }));
156
+ } catch (error) { sendAgentToolError(res, error); }
157
+ return true;
158
+ }
159
+ const completeMatch = method === 'POST' ? path.match(/^\/agent-api\/v1\/runs\/([0-9a-f-]{36})\/complete$/i) : null;
160
+ if (completeMatch) {
161
+ const runtime = runtimeDeps();
162
+ if (!runtime) { send(res, 503, { error: 'agent_runtime_unavailable' }); return true; }
163
+ const body = await readAgentToolBody(req, res, AGENT_RUNTIME_JSON_BODY_MAX_BYTES);
164
+ if (!body) return true;
165
+ if (!declaredFields(body, ['assistant_message_id', 'status', 'content', 'model', 'runtime', 'usage'], ['assistant_message_id', 'status', 'content'])
166
+ || typeof body['assistant_message_id'] !== 'string'
167
+ || typeof body['status'] !== 'string'
168
+ || typeof body['content'] !== 'string'
169
+ || (body['model'] !== undefined && typeof body['model'] !== 'string')
170
+ || (body['runtime'] !== undefined && typeof body['runtime'] !== 'string')
171
+ || (body['usage'] !== undefined && !record(body['usage']))) {
172
+ send(res, 400, { error: 'invalid_request', message: 'The run completion contains missing or undeclared fields.' }); return true;
173
+ }
174
+ try {
175
+ send(res, 200, await completeAgentRunFor(runtime, auth, completeMatch[1]!, {
176
+ assistant_message_id: body['assistant_message_id'],
177
+ status: body['status'] as 'completed' | 'failed' | 'cancelled',
178
+ content: body['content'],
179
+ ...(typeof body['model'] === 'string' ? { model: body['model'] } : {}),
180
+ ...(typeof body['runtime'] === 'string' ? { runtime: body['runtime'] } : {}),
181
+ ...(record(body['usage']) ? { usage: record(body['usage'])! } : {}),
182
+ }));
183
+ } catch (error) { sendAgentToolError(res, error); }
184
+ return true;
185
+ }
186
+ if (method === 'GET' && path === '/agent-api/v1/tools') {
187
+ if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
188
+ const route = String(url.searchParams.get('route') ?? '');
189
+ try { send(res, 200, await listAgentToolsFor(deps.toolProxyDeps, auth, route)); }
190
+ catch (error) { sendAgentToolError(res, error); }
191
+ return true;
192
+ }
193
+ if (method === 'POST' && path === '/agent-api/v1/tool-invocations') {
194
+ if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
195
+ if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
196
+ const body = await readAgentToolBody(req, res, 16 * 1024);
197
+ if (!body) return true;
198
+ if (!body
199
+ || !exactFields(body, ['invocation_id', 'route', 'capability_revision', 'agent_run_id', 'tool', 'arguments'])
200
+ || typeof body['invocation_id'] !== 'string'
201
+ || typeof body['route'] !== 'string'
202
+ || typeof body['capability_revision'] !== 'string'
203
+ || typeof body['agent_run_id'] !== 'string'
204
+ || typeof body['tool'] !== 'string'
205
+ || !record(body['arguments'])) {
206
+ send(res, 400, { error: 'invalid_request', message: 'The Agent tool invocation contains undeclared fields.' }); return true;
207
+ }
208
+ const input: InvokeAgentToolInput = {
209
+ invocation_id: body['invocation_id'],
210
+ route: body['route'],
211
+ capability_revision: body['capability_revision'],
212
+ agent_run_id: body['agent_run_id'],
213
+ tool: body['tool'],
214
+ arguments: record(body['arguments'])!,
215
+ };
216
+ try { send(res, 200, await invokeAgentToolFor(deps.toolProxyDeps, auth, input)); }
217
+ catch (error) { sendAgentToolError(res, error); }
218
+ return true;
219
+ }
220
+ const resumeMatch = method === 'POST' ? path.match(/^\/agent-api\/v1\/tool-invocations\/([a-f0-9]{64})\/resume$/) : null;
221
+ if (resumeMatch) {
222
+ if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
223
+ if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
224
+ const body = await readAgentToolBody(req, res, 1024);
225
+ if (!body) return true;
226
+ if (!body || !exactFields(body, [])) {
227
+ send(res, 400, { error: 'invalid_request', message: 'The Agent tool resume request contains undeclared fields.' }); return true;
228
+ }
229
+ const input: ResumeAgentToolInput = {
230
+ invocation_id: resumeMatch[1]!,
231
+ };
232
+ try { send(res, 200, await resumeAgentToolFor(deps.toolProxyDeps, auth, input)); }
233
+ catch (error) { sendAgentToolError(res, error); }
234
+ return true;
235
+ }
236
+ if (method === 'POST' && path === '/agent-api/v1/run') {
237
+ await deps.handleRun(req, res, principal);
238
+ return true;
239
+ }
240
+ const jobMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/jobs\/([0-9a-f-]{36})$/i) : null;
241
+ if (jobMatch) {
242
+ const job = await deps.stateStore.getJob(jobMatch[1]!);
243
+ if (!job || job.agent_session_id !== auth.session.session_id) {
244
+ send(res, 404, { error: 'not_found' }); return true;
245
+ }
246
+ send(res, 200, job);
247
+ return true;
248
+ }
249
+ send(res, 404, { error: 'not_found' });
250
+ return true;
251
+ }