bailinghub 0.4.0 → 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 (141) hide show
  1. package/.gitignore +5 -0
  2. package/README.en.md +5 -2
  3. package/README.md +5 -2
  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 +13 -0
  13. package/docs/CHANGELOG.md +13 -0
  14. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  15. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  16. package/docs/README.en.md +8 -2
  17. package/docs/README.md +8 -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/package.json +3 -2
  21. package/schemas/config/client.schema.json +7 -0
  22. package/schemas/config/common.schema.json +30 -0
  23. package/schemas/config/route.schema.json +11 -0
  24. package/scripts/check-doc-links.mjs +1 -1
  25. package/scripts/check-image-tags.sh +1 -1
  26. package/scripts/check-release-consistency.test.mjs +5 -5
  27. package/scripts/e2e-console.mjs +144 -0
  28. package/scripts/export-oss.mjs +5 -12
  29. package/scripts/install.sh +1 -1
  30. package/scripts/public-content-denylist.mjs +82 -0
  31. package/scripts/public-content-denylist.test.mjs +53 -0
  32. package/scripts/publish-images.sh +1 -1
  33. package/scripts/release-audit.mjs +8 -13
  34. package/scripts/sdk-runtime-test.mjs +171 -7
  35. package/scripts/security-scan.mjs +8 -5
  36. package/scripts/validate-examples.mjs +3 -1
  37. package/scripts/verify-github-repo.mjs +7 -12
  38. package/scripts/verify-oss-export.mjs +6 -12
  39. package/sdk/php/README.md +27 -1
  40. package/sdk/php/src/AgentAuth.php +78 -0
  41. package/sdk/php/src/HubClient.php +3 -0
  42. package/sdk/php7/README.md +32 -2
  43. package/sdk/php7/src/AgentAuth.php +77 -0
  44. package/sdk/php7/src/HubClient.php +3 -0
  45. package/sql/055_agent_auth.sql +72 -0
  46. package/sql/056_agent_client_runtime.sql +60 -0
  47. package/src/adapters/channels/wecom-api.ts +1 -1
  48. package/src/app/agent-client-runtime.test.ts +221 -0
  49. package/src/app/agent-client-runtime.ts +408 -0
  50. package/src/app/agent-tool-invocations.test.ts +462 -0
  51. package/src/app/agent-tool-invocations.ts +795 -0
  52. package/src/app/agent-tool-job.test.ts +62 -0
  53. package/src/app/agent-tool-job.ts +41 -0
  54. package/src/app/auth.ts +2 -1
  55. package/src/app/kernel.ts +2 -0
  56. package/src/app/runtime-context.ts +8 -0
  57. package/src/app/tool-approvals.ts +5 -1
  58. package/src/app/tool-assembly.ts +19 -1
  59. package/src/app/tool-context.ts +2 -1
  60. package/src/core/config/config-codec.ts +2 -1
  61. package/src/core/config/config-models.test.ts +10 -0
  62. package/src/core/config/config-models.ts +21 -0
  63. package/src/core/config/config-schema.test.ts +6 -0
  64. package/src/core/config/route-config.test.ts +15 -0
  65. package/src/core/config/route-config.ts +36 -0
  66. package/src/core/config/tools-config.test.ts +58 -1
  67. package/src/core/config/tools-config.ts +84 -0
  68. package/src/core/contracts/tools.ts +162 -29
  69. package/src/core/contracts/types.ts +36 -0
  70. package/src/core/runtime/agent-client-trace.test.ts +154 -0
  71. package/src/core/runtime/agent-client-trace.ts +288 -0
  72. package/src/core/runtime/launch-runtime.ts +13 -0
  73. package/src/core/runtime/trace-runtime.test.ts +18 -1
  74. package/src/core/runtime/trace-runtime.ts +28 -3
  75. package/src/core/state/state-codec.ts +2 -0
  76. package/src/infrastructure/config/config-agent-auth-repository.test.ts +147 -0
  77. package/src/infrastructure/config/config-agent-auth-repository.ts +356 -0
  78. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +253 -0
  79. package/src/infrastructure/config/config-approval-ledger.test.ts +32 -0
  80. package/src/infrastructure/config/config-approval-ledger.ts +16 -0
  81. package/src/infrastructure/config/config-client-repository.ts +3 -3
  82. package/src/infrastructure/config/config-conversation-ledger.test.ts +69 -0
  83. package/src/infrastructure/config/config-conversation-ledger.ts +8 -7
  84. package/src/infrastructure/config/config-observability-ledger.test.ts +50 -0
  85. package/src/infrastructure/config/config-observability-ledger.ts +65 -10
  86. package/src/infrastructure/config/config-route-repository.ts +4 -3
  87. package/src/infrastructure/config/configstore.ts +14 -3
  88. package/src/infrastructure/state/state-mysql.ts +2 -2
  89. package/src/kernel-api/v1/contracts.ts +8 -0
  90. package/src/routes/admin-runtime.test.ts +214 -0
  91. package/src/routes/admin-runtime.ts +82 -2
  92. package/src/routes/agent-api.test.ts +379 -0
  93. package/src/routes/agent-api.ts +251 -0
  94. package/src/routes/agent-auth.test.ts +276 -0
  95. package/src/routes/agent-auth.ts +395 -0
  96. package/src/routes/approvals.ts +4 -1
  97. package/src/routes/critical-routes.test.ts +235 -1
  98. package/src/routes/private-default.ts +2 -1
  99. package/src/routes/private.ts +16 -1
  100. package/src/routes/run.ts +79 -13
  101. package/web/connect/bailing-connect-php.tgz +0 -0
  102. package/web/connect/bailing-connect-php7.tgz +0 -0
  103. package/web/console/assets/{Accounts-DuUY2UJU.js → Accounts-D4RRm5D1.js} +1 -1
  104. package/web/console/assets/{Approvals-B11mo1dy.js → Approvals-CsTTKb8o.js} +1 -1
  105. package/web/console/assets/{Audit-CQwJRIJT.js → Audit-BzvZ7JZw.js} +1 -1
  106. package/web/console/assets/{BrandLockup-BIF-h1pi.js → BrandLockup-CYcA93wh.js} +1 -1
  107. package/web/console/assets/{Channels-BIploUT-.js → Channels-DRQZggqM.js} +1 -1
  108. package/web/console/assets/{ChatEntries-Cpg_WV-o.js → ChatEntries-BUB7BWKU.js} +1 -1
  109. package/web/console/assets/Clients-CQ_MonGL.css +1 -0
  110. package/web/console/assets/Clients-HhCyrxfz.js +3 -0
  111. package/web/console/assets/{Cost-BF52tfU2.js → Cost-BZgFf1yM.js} +1 -1
  112. package/web/console/assets/{Credentials-SwfmQAv6.js → Credentials-BTe2Q07j.js} +1 -1
  113. package/web/console/assets/{Diagnostics-CJfbI_8p.js → Diagnostics-WL-buYli.js} +1 -1
  114. package/web/console/assets/{Executors-CzlZlznA.js → Executors-CGZ-7Xmp.js} +1 -1
  115. package/web/console/assets/{Kb-CVX22U4k.js → Kb-VVw8oGsT.js} +1 -1
  116. package/web/console/assets/{Login-PoUVsBI-.js → Login-rwvmBBPl.js} +1 -1
  117. package/web/console/assets/{Projects-DYlbjLQy.js → Projects-CexaCEY1.js} +1 -1
  118. package/web/console/assets/Routes-B9ZHbQAp.js +124 -0
  119. package/web/console/assets/Routes-BbkFpi6Y.css +1 -0
  120. package/web/console/assets/Runs-4zDD9VOC.css +1 -0
  121. package/web/console/assets/Runs-BzFNPTwD.js +3 -0
  122. package/web/console/assets/{Setup-xiPXit_b.js → Setup-Djh5yadQ.js} +1 -1
  123. package/web/console/assets/{Shell-DNiWZOYB.js → Shell-kn763smL.js} +1 -1
  124. package/web/console/assets/{StorageBuckets-Bjsc3pLd.js → StorageBuckets-CQBR41W1.js} +1 -1
  125. package/web/console/assets/{SystemSettings-CcKF2lJ9.js → SystemSettings-DgnopekD.js} +1 -1
  126. package/web/console/assets/{SystemStatus-Oj1xjxJn.js → SystemStatus-Bj8-kPt2.js} +1 -1
  127. package/web/console/assets/{Targets-y1KllVXT.js → Targets-BAfCt_nH.js} +1 -1
  128. package/web/console/assets/{Tools-DoEP_y9x.js → Tools-xjd0NZdE.js} +1 -1
  129. package/web/console/assets/{index-CxPIS6G7.js → index-DfJA7iJS.js} +2 -2
  130. package/web/console/assets/{request-CBLNpLth.js → request-DkNPOweH.js} +1 -1
  131. package/web/console/assets/{schema-DzwLpuOy.js → schema-CgPWAu1_.js} +1 -1
  132. package/web/console/index.html +1 -1
  133. package/web-admin/src/pages/Clients.vue +11 -3
  134. package/web-admin/src/pages/Routes.vue +282 -16
  135. package/web-admin/src/pages/Runs.vue +159 -38
  136. package/web/console/assets/Clients--D7NQJKk.css +0 -1
  137. package/web/console/assets/Clients-DS29eUi2.js +0 -3
  138. package/web/console/assets/Routes-DSEvGujN.js +0 -124
  139. package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
  140. package/web/console/assets/Runs-B-TsYZEt.js +0 -3
  141. package/web/console/assets/Runs-CUtSsPW-.css +0 -1
@@ -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
+ }
@@ -0,0 +1,276 @@
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 } from '../core/contracts/types';
6
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
+ import type { AgentAuthorization } from '../infrastructure/config/config-agent-auth-repository';
8
+ import { handleAgentAuthHttpFor, isLoopbackRedirectUri, pkceChallenge, tokenHash } from './agent-auth';
9
+
10
+ class FakeResponse {
11
+ statusCode = 0;
12
+ headers: Record<string, string | number | string[]> = {};
13
+ body = Buffer.alloc(0);
14
+
15
+ setHeader(name: string, value: string | number | string[]): void { this.headers[name.toLowerCase()] = value; }
16
+ writeHead(code: number, headers?: Record<string, string | number | string[]>): void {
17
+ this.statusCode = code;
18
+ for (const [name, value] of Object.entries(headers ?? {})) this.headers[name.toLowerCase()] = value;
19
+ }
20
+ end(value?: string | Buffer): void { this.body = value ? Buffer.from(value) : Buffer.alloc(0); }
21
+ json(): Record<string, any> { return JSON.parse(this.body.toString('utf8')) as Record<string, any>; }
22
+ }
23
+
24
+ function request(method: string, body?: Record<string, unknown>, headers: Record<string, string> = {}): IncomingMessage {
25
+ const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))];
26
+ const req = Readable.from(chunks) as unknown as IncomingMessage;
27
+ req.method = method;
28
+ req.headers = headers;
29
+ Object.defineProperty(req, 'socket', { value: { remoteAddress: '127.0.0.9' } });
30
+ return req;
31
+ }
32
+
33
+ async function call(store: ConfigStoreContract, method: string, path: string, body?: Record<string, unknown>, headers: Record<string, string> = {}): Promise<FakeResponse> {
34
+ const res = new FakeResponse();
35
+ const handled = await handleAgentAuthHttpFor(
36
+ { configStore: store },
37
+ request(method, body, headers),
38
+ res as unknown as ServerResponse,
39
+ new URL(path, 'https://hub.example.com'),
40
+ );
41
+ assert.equal(handled, true);
42
+ return res;
43
+ }
44
+
45
+ test('Agent Auth loopback redirect only accepts explicit-port IP literals', () => {
46
+ assert.equal(isLoopbackRedirectUri('http://127.0.0.1:43123/callback'), true);
47
+ assert.equal(isLoopbackRedirectUri('http://[::1]:43123/callback'), true);
48
+ assert.equal(isLoopbackRedirectUri('http://localhost:43123/callback'), false);
49
+ assert.equal(isLoopbackRedirectUri('http://2130706433:43123/callback'), false);
50
+ assert.equal(isLoopbackRedirectUri('http://0x7f000001:43123/callback'), false);
51
+ assert.equal(isLoopbackRedirectUri('http://127.0.0.1/callback'), false);
52
+ assert.equal(isLoopbackRedirectUri('https://127.0.0.1:43123/callback'), false);
53
+ assert.equal(isLoopbackRedirectUri('http://user@127.0.0.1:43123/callback'), false);
54
+ assert.equal(isLoopbackRedirectUri('http://127.0.0.1:43123/callback#fragment'), false);
55
+ });
56
+
57
+ test('Agent Auth v1: context is redacted, PKCE binds client/redirect, query tokens fail, and business can revoke', async () => {
58
+ const client: Client = {
59
+ app_id: 'example-business',
60
+ name: 'Example Business',
61
+ token: 'business-client-token-0001',
62
+ agent_authorize_url: 'https://tenant.example.com/agent-authorize?from=hub',
63
+ allowed_routes: ['orders'],
64
+ allowed_channels: [],
65
+ rate_limit_per_min: 0,
66
+ enabled: true,
67
+ };
68
+ const otherClient: Client = { ...client, app_id: 'other-client', name: 'Other', token: 'other-client-token-000001' };
69
+ let authorization: AgentAuthorization | null = null;
70
+ let approvedCodeHash = '';
71
+ let accessHash = '';
72
+ let refreshHash = '';
73
+ let session: AgentSession | null = null;
74
+ let revoked = false;
75
+ let rateLimited = false;
76
+
77
+ const agentAuth = {
78
+ async createAuthorization(input: any) {
79
+ authorization = {
80
+ authorization_id: input.authorizationId,
81
+ client_app_id: input.clientAppId,
82
+ redirect_uri: input.redirectUri,
83
+ state: input.state,
84
+ requested_routes: input.requestedRoutes,
85
+ device_label: input.deviceLabel,
86
+ code_challenge: input.codeChallenge,
87
+ status: 'pending',
88
+ created_at: new Date().toISOString(),
89
+ expires_at: input.expiresAt,
90
+ };
91
+ },
92
+ async getAuthorization(id: string) { return authorization?.authorization_id === id ? authorization : null; },
93
+ async approveAuthorization(input: any) {
94
+ if (!authorization || authorization.authorization_id !== input.authorizationId || authorization.status !== 'pending') return { ok: false, reason: 'invalid_state' };
95
+ approvedCodeHash = input.codeHash;
96
+ authorization = {
97
+ ...authorization,
98
+ status: 'approved',
99
+ principal: input.principal,
100
+ on_behalf_of: input.onBehalfOf,
101
+ allowed_routes: input.allowedRoutes,
102
+ code_expires_at: input.codeExpiresAt,
103
+ };
104
+ return { ok: true, authorization };
105
+ },
106
+ async denyAuthorization() { return { ok: false, reason: 'invalid_state' }; },
107
+ async exchangeAuthorizationCode(input: any) {
108
+ if (!authorization || authorization.status !== 'approved' || input.codeHash !== approvedCodeHash ||
109
+ input.clientAppId !== authorization.client_app_id || input.redirectUri !== authorization.redirect_uri ||
110
+ input.codeChallenge !== authorization.code_challenge) return { ok: false, reason: 'invalid_grant' };
111
+ accessHash = input.accessTokenHash;
112
+ refreshHash = input.refreshTokenHash;
113
+ session = {
114
+ session_id: input.sessionId,
115
+ client_app_id: authorization.client_app_id,
116
+ device_label: authorization.device_label,
117
+ principal: authorization.principal!,
118
+ on_behalf_of: authorization.on_behalf_of!,
119
+ allowed_routes: authorization.allowed_routes!,
120
+ created_at: new Date().toISOString(),
121
+ access_expires_at: input.accessExpiresAt,
122
+ refresh_expires_at: input.refreshExpiresAt,
123
+ };
124
+ authorization = { ...authorization, status: 'consumed' };
125
+ return { ok: true, session };
126
+ },
127
+ async rotateRefreshToken() { return { ok: false, reason: 'invalid_grant' }; },
128
+ async getSessionByAccessHash(hash: string) { return !revoked && hash === accessHash ? session : null; },
129
+ async revokeByAccessHash(hash: string) { if (hash === accessHash) revoked = true; return hash === accessHash; },
130
+ async revokeByRefreshHash(_app: string, hash: string) { if (hash === refreshHash) revoked = true; return hash === refreshHash; },
131
+ async revokeSessionForClient(appId: string, sessionId: string) {
132
+ if (session?.client_app_id === appId && session.session_id === sessionId) { revoked = true; return true; }
133
+ return false;
134
+ },
135
+ };
136
+ const store = {
137
+ agentAuth,
138
+ clients: {
139
+ get: async (appId: string) => appId === client.app_id ? client : appId === otherClient.app_id ? otherClient : null,
140
+ getByToken: async (token: string) => token === client.token ? client : token === otherClient.token ? otherClient : null,
141
+ },
142
+ rateLimits: { consume: async () => rateLimited },
143
+ } as unknown as ConfigStoreContract;
144
+
145
+ const verifier = 'v'.repeat(43);
146
+ const redirectUri = 'http://127.0.0.1:43123/callback?local=1';
147
+ const created = await call(store, 'POST', '/agent-auth/v1/authorizations', {
148
+ client_app_id: client.app_id,
149
+ redirect_uri: redirectUri,
150
+ state: 'state-12345678',
151
+ requested_routes: ['orders'],
152
+ device_label: 'Mac mini',
153
+ code_challenge: pkceChallenge(verifier),
154
+ code_challenge_method: 'S256',
155
+ });
156
+ assert.equal(created.statusCode, 201);
157
+ assert.equal(created.json().expires_in, 600);
158
+ const authorizationId = String(created.json().authorization_id);
159
+ const authorizeUrl = new URL(String(created.json().authorization_url));
160
+ assert.equal(authorizeUrl.origin, 'https://tenant.example.com');
161
+ assert.equal(authorizeUrl.searchParams.get('from'), 'hub');
162
+ assert.equal(authorizeUrl.searchParams.get('authorization_id'), authorizationId);
163
+
164
+ const autoRoute = await call(store, 'POST', '/agent-auth/v1/authorizations', {
165
+ client_app_id: client.app_id,
166
+ redirect_uri: 'http://127.0.0.1:43124/callback',
167
+ state: 'state-87654321',
168
+ requested_routes: ['auto'],
169
+ device_label: 'Mac mini',
170
+ code_challenge: pkceChallenge(verifier),
171
+ code_challenge_method: 'S256',
172
+ });
173
+ assert.equal(autoRoute.statusCode, 400);
174
+ const wildcardRoute = await call(store, 'POST', '/agent-auth/v1/authorizations', {
175
+ client_app_id: client.app_id,
176
+ redirect_uri: 'http://127.0.0.1:43126/callback',
177
+ state: 'state-66778899',
178
+ requested_routes: ['*'],
179
+ device_label: 'Mac mini',
180
+ code_challenge: pkceChallenge(verifier),
181
+ code_challenge_method: 'S256',
182
+ });
183
+ assert.equal(wildcardRoute.statusCode, 400);
184
+
185
+ rateLimited = true;
186
+ const throttled = await call(store, 'POST', '/agent-auth/v1/authorizations', {
187
+ client_app_id: client.app_id,
188
+ redirect_uri: 'http://127.0.0.1:43125/callback',
189
+ state: 'state-11223344',
190
+ requested_routes: ['orders'],
191
+ device_label: 'Mac mini',
192
+ code_challenge: pkceChallenge(verifier),
193
+ code_challenge_method: 'S256',
194
+ });
195
+ assert.equal(throttled.statusCode, 429);
196
+ rateLimited = false;
197
+
198
+ const queryToken = await call(store, 'GET', `/agent-auth/v1/authorizations/${authorizationId}?token=${encodeURIComponent(client.token)}`);
199
+ assert.equal(queryToken.statusCode, 401);
200
+ const context = await call(store, 'GET', `/agent-auth/v1/authorizations/${authorizationId}`, undefined, { authorization: `Bearer ${client.token}` });
201
+ assert.equal(context.statusCode, 200);
202
+ assert.deepEqual(context.json(), {
203
+ authorization_id: authorizationId,
204
+ client: { app_id: client.app_id, name: client.name },
205
+ device: { name: 'Mac mini' },
206
+ requested_routes: ['orders'],
207
+ status: 'pending',
208
+ expires_at: authorization!.expires_at,
209
+ });
210
+ for (const secretField of ['redirect_uri', 'state', 'code_challenge']) assert.equal(secretField in context.json(), false);
211
+
212
+ const approveAuto = await call(store, 'POST', `/agent-auth/v1/authorizations/${authorizationId}/approve`, {
213
+ principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
214
+ on_behalf_of: 'tenant-2:user-7',
215
+ allowed_routes: ['auto'],
216
+ }, { authorization: `Bearer ${client.token}` });
217
+ assert.equal(approveAuto.statusCode, 400);
218
+ const approveWildcard = await call(store, 'POST', `/agent-auth/v1/authorizations/${authorizationId}/approve`, {
219
+ principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
220
+ on_behalf_of: 'tenant-2:user-7',
221
+ allowed_routes: ['*'],
222
+ }, { authorization: `Bearer ${client.token}` });
223
+ assert.equal(approveWildcard.statusCode, 400);
224
+
225
+ const approved = await call(store, 'POST', `/agent-auth/v1/authorizations/${authorizationId}/approve`, {
226
+ principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
227
+ on_behalf_of: 'tenant-2:user-7',
228
+ allowed_routes: ['orders'],
229
+ }, { authorization: `Bearer ${client.token}` });
230
+ assert.equal(approved.statusCode, 200);
231
+ assert.match(approvedCodeHash, /^[a-f0-9]{64}$/);
232
+ assert.ok(Date.parse(authorization!.code_expires_at!) - Date.now() <= 120_000);
233
+ const redirect = new URL(String(approved.json().redirect_uri));
234
+ const code = String(redirect.searchParams.get('code'));
235
+ assert.equal(redirect.origin + redirect.pathname, 'http://127.0.0.1:43123/callback');
236
+ assert.equal(redirect.searchParams.get('local'), '1');
237
+ assert.equal(redirect.searchParams.get('state'), 'state-12345678');
238
+ assert.equal(tokenHash(code), approvedCodeHash);
239
+
240
+ const mixedUp = await call(store, 'POST', '/agent-auth/v1/token', {
241
+ grant_type: 'authorization_code', client_app_id: otherClient.app_id, code, redirect_uri: redirectUri, code_verifier: verifier,
242
+ });
243
+ assert.equal(mixedUp.statusCode, 400);
244
+ assert.equal(mixedUp.json().error, 'invalid_grant');
245
+
246
+ const token = await call(store, 'POST', '/agent-auth/v1/token', {
247
+ grant_type: 'authorization_code', client_app_id: client.app_id, code, redirect_uri: redirectUri, code_verifier: verifier,
248
+ });
249
+ assert.equal(token.statusCode, 200);
250
+ assert.equal(token.headers['cache-control'], 'no-store');
251
+ assert.equal(token.headers['pragma'], 'no-cache');
252
+ assert.deepEqual(Object.keys(token.json()).sort(), ['access_token', 'client_app_id', 'expires_in', 'refresh_expires_in', 'refresh_token', 'session_id', 'token_type'].sort());
253
+ const accessToken = String(token.json().access_token);
254
+
255
+ const queryAccess = await call(store, 'GET', `/agent-auth/v1/session?token=${encodeURIComponent(accessToken)}`);
256
+ assert.equal(queryAccess.statusCode, 401);
257
+ const current = await call(store, 'GET', '/agent-auth/v1/session', undefined, { authorization: `Bearer ${accessToken}` });
258
+ assert.equal(current.statusCode, 200);
259
+ assert.equal(current.json().principal.id, 'user-7');
260
+ assert.equal(current.json().on_behalf_of, 'tenant-2:user-7');
261
+
262
+ const savedAuthorizeUrl = client.agent_authorize_url;
263
+ client.agent_authorize_url = 'http://business.example.com/agent-authorize';
264
+ const invalidConfig = await call(store, 'GET', '/agent-auth/v1/session', undefined, { authorization: `Bearer ${accessToken}` });
265
+ assert.equal(invalidConfig.statusCode, 401);
266
+ client.agent_authorize_url = savedAuthorizeUrl;
267
+ client.enabled = false;
268
+ const disabledClient = await call(store, 'GET', '/agent-auth/v1/session', undefined, { authorization: `Bearer ${accessToken}` });
269
+ assert.equal(disabledClient.statusCode, 401);
270
+ client.enabled = true;
271
+
272
+ const revokedByBusiness = await call(store, 'POST', `/agent-auth/v1/sessions/${token.json().session_id}/revoke`, {}, { authorization: `Bearer ${client.token}` });
273
+ assert.equal(revokedByBusiness.statusCode, 200);
274
+ const afterRevoke = await call(store, 'GET', '/agent-auth/v1/session', undefined, { authorization: `Bearer ${accessToken}` });
275
+ assert.equal(afterRevoke.statusCode, 401);
276
+ });