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,395 @@
1
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { namedRateLimitedFor } from '../app/auth';
4
+ import { ipOf, readBody, send } from '../app/http';
5
+ import type { AgentBusinessPrincipal, AgentSession, Client } from '../core/contracts/types';
6
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
+
8
+ export const AGENT_AUTHORIZATION_TTL_SEC = 10 * 60;
9
+ export const AGENT_AUTHORIZATION_CODE_TTL_SEC = 2 * 60;
10
+ export const AGENT_ACCESS_TTL_SEC = 15 * 60;
11
+ export const AGENT_REFRESH_TTL_SEC = 30 * 24 * 60 * 60;
12
+
13
+ const RESOURCE_RE = /^[a-z0-9][a-z0-9_-]{1,63}$/;
14
+ const PKCE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/;
15
+ const PKCE_VERIFIER_RE = /^[A-Za-z0-9._~-]{43,128}$/;
16
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
17
+
18
+ type RecordValue = Record<string, unknown>;
19
+
20
+ export interface AgentAuthHttpDeps {
21
+ configStore: ConfigStoreContract | null;
22
+ }
23
+
24
+ function record(value: unknown): RecordValue | null {
25
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : null;
26
+ }
27
+
28
+ function allowedFields(value: RecordValue, fields: readonly string[]): boolean {
29
+ const known = new Set(fields);
30
+ return Object.keys(value).every((key) => known.has(key));
31
+ }
32
+
33
+ function stringList(value: unknown): string[] | null {
34
+ if (!Array.isArray(value) || value.length < 1 || value.length > 64) return null;
35
+ const items = value.map((item) => typeof item === 'string' ? item.trim() : '');
36
+ if (items.some((item) => !item || item === 'auto' || item === '*' || !RESOURCE_RE.test(item))) return null;
37
+ const unique = [...new Set(items)];
38
+ return unique.length === items.length ? unique : null;
39
+ }
40
+
41
+ function hasStrictLoopbackHttpAuthority(value: string): boolean {
42
+ const match = /^http:\/\/(?:127\.0\.0\.1|\[::1\]):([0-9]{1,5})(?:[/?#]|$)/i.exec(value);
43
+ if (!match) return false;
44
+ const port = Number(match[1]);
45
+ return Number.isInteger(port) && port >= 1 && port <= 65535;
46
+ }
47
+
48
+ function isAgentAuthorizeUrl(value: string): boolean {
49
+ try {
50
+ const url = new URL(value);
51
+ const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
52
+ const loopbackDev = hasStrictLoopbackHttpAuthority(value) && (hostname === '127.0.0.1' || hostname === '::1');
53
+ return (url.protocol === 'https:' || loopbackDev) && !url.username && !url.password && !url.hash;
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+
59
+ export function isLoopbackRedirectUri(value: string): boolean {
60
+ if (!value || value.length > 2048) return false;
61
+ try {
62
+ const url = new URL(value);
63
+ const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
64
+ const loopback = hostname === '127.0.0.1' || hostname === '::1';
65
+ return url.protocol === 'http:' && loopback && hasStrictLoopbackHttpAuthority(value) && !url.username && !url.password && !url.hash;
66
+ } catch {
67
+ return false;
68
+ }
69
+ }
70
+
71
+ export function tokenHash(value: string): string {
72
+ return createHash('sha256').update(value, 'utf8').digest('hex');
73
+ }
74
+
75
+ export function pkceChallenge(codeVerifier: string): string {
76
+ return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');
77
+ }
78
+
79
+ function randomSecret(prefix: 'bha' | 'bhr' | 'bhc'): string {
80
+ return `${prefix}_${randomBytes(32).toString('base64url')}`;
81
+ }
82
+
83
+ function authorizationUrl(base: string, authorizationId: string): string | null {
84
+ if (!isAgentAuthorizeUrl(base) || base.length > 2048) return null;
85
+ const url = new URL(base);
86
+ url.searchParams.set('authorization_id', authorizationId);
87
+ return url.toString();
88
+ }
89
+
90
+ function redirectResult(base: string, result: { code?: string; error?: string }, state: string): string {
91
+ const url = new URL(base);
92
+ url.searchParams.delete('code');
93
+ url.searchParams.delete('error');
94
+ if (result.code) url.searchParams.set('code', result.code);
95
+ if (result.error) url.searchParams.set('error', result.error);
96
+ url.searchParams.set('state', state);
97
+ return url.toString();
98
+ }
99
+
100
+ function clientAllowsRoute(client: Client, route: string): boolean {
101
+ return client.allowed_routes.includes('*') || client.allowed_routes.includes(route);
102
+ }
103
+
104
+ function requestedAllowsRoute(requested: string[], route: string): boolean {
105
+ return requested.includes('*') || requested.includes(route);
106
+ }
107
+
108
+ function parsePrincipal(value: unknown): AgentBusinessPrincipal | null {
109
+ const item = record(value);
110
+ if (!item || !allowedFields(item, ['id', 'tenant', 'roles', 'audience', 'channel'])) return null;
111
+ const id = typeof item['id'] === 'string' ? item['id'].trim() : '';
112
+ const tenant = typeof item['tenant'] === 'string' ? item['tenant'].trim() : '';
113
+ const audience = typeof item['audience'] === 'string' ? item['audience'].trim() : '';
114
+ const channel = typeof item['channel'] === 'string' ? item['channel'].trim() : '';
115
+ const roles = Array.isArray(item['roles'])
116
+ ? item['roles'].map((role) => typeof role === 'string' ? role.trim() : '')
117
+ : [];
118
+ if (!id || id.length > 128 || tenant.length > 128 || audience.length > 64 || channel.length > 128 ||
119
+ roles.length > 64 || roles.some((role) => !role || role.length > 64)) return null;
120
+ return {
121
+ id,
122
+ ...(tenant ? { tenant } : {}),
123
+ roles: [...new Set(roles)],
124
+ ...(audience ? { audience } : {}),
125
+ ...(channel ? { channel } : {}),
126
+ };
127
+ }
128
+
129
+ async function businessClient(deps: AgentAuthHttpDeps, req: IncomingMessage, url: URL): Promise<Client | null> {
130
+ const token = bearerToken(req);
131
+ if (!token || !deps.configStore) return null;
132
+ const client = await deps.configStore.clients.getByToken(token);
133
+ return client?.enabled ? client : null;
134
+ }
135
+
136
+ function bearerToken(req: IncomingMessage): string {
137
+ const header = (req.headers['authorization'] ?? '').toString();
138
+ const match = /^Bearer ([^\s]+)$/i.exec(header);
139
+ return match?.[1] ?? '';
140
+ }
141
+
142
+ function publicSession(session: AgentSession): RecordValue {
143
+ return {
144
+ session_id: session.session_id,
145
+ client_app_id: session.client_app_id,
146
+ device_label: session.device_label,
147
+ principal: session.principal,
148
+ on_behalf_of: session.on_behalf_of,
149
+ allowed_routes: session.allowed_routes,
150
+ created_at: session.created_at,
151
+ expires_at: session.access_expires_at,
152
+ refresh_expires_at: session.refresh_expires_at,
153
+ };
154
+ }
155
+
156
+ async function createAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
157
+ if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
158
+ const body = record(await readBody(req).catch(() => null));
159
+ if (!body || !allowedFields(body, ['client_app_id', 'redirect_uri', 'state', 'requested_routes', 'device_label', 'code_challenge', 'code_challenge_method'])) {
160
+ send(res, 400, { error: 'invalid_request' }); return;
161
+ }
162
+ const clientAppId = typeof body['client_app_id'] === 'string' ? body['client_app_id'].trim() : '';
163
+ const redirectUri = typeof body['redirect_uri'] === 'string' ? body['redirect_uri'] : '';
164
+ const state = typeof body['state'] === 'string' ? body['state'] : '';
165
+ const requestedRoutes = stringList(body['requested_routes']);
166
+ const deviceLabel = typeof body['device_label'] === 'string' ? body['device_label'].trim() : '';
167
+ const codeChallenge = typeof body['code_challenge'] === 'string' ? body['code_challenge'] : '';
168
+ if (!RESOURCE_RE.test(clientAppId) || !isLoopbackRedirectUri(redirectUri) || state.length < 8 || state.length > 512 ||
169
+ !requestedRoutes || !deviceLabel || deviceLabel.length > 128 || !PKCE_CHALLENGE_RE.test(codeChallenge) || body['code_challenge_method'] !== 'S256') {
170
+ send(res, 400, { error: 'invalid_request' }); return;
171
+ }
172
+ const client = await deps.configStore.clients.get(clientAppId);
173
+ if (!client?.enabled || !client.agent_authorize_url || requestedRoutes.some((route) => !clientAllowsRoute(client, route))) {
174
+ send(res, 400, { error: 'invalid_client' }); return;
175
+ }
176
+ if (await namedRateLimitedFor(deps.configStore, `agent-auth:create:${clientAppId}:${ipOf(req)}`, 10, 60)) {
177
+ send(res, 429, { error: 'rate_limited' }); return;
178
+ }
179
+ const authorizationId = randomUUID();
180
+ const authorizeUrl = authorizationUrl(client.agent_authorize_url, authorizationId);
181
+ if (!authorizeUrl) { send(res, 503, { error: 'agent_authorize_url_invalid' }); return; }
182
+ const expiresAt = new Date(Date.now() + AGENT_AUTHORIZATION_TTL_SEC * 1000).toISOString();
183
+ await deps.configStore.agentAuth.createAuthorization({
184
+ authorizationId,
185
+ clientAppId,
186
+ redirectUri,
187
+ state,
188
+ requestedRoutes,
189
+ deviceLabel,
190
+ codeChallenge,
191
+ expiresAt,
192
+ });
193
+ send(res, 201, { authorization_id: authorizationId, authorization_url: authorizeUrl, expires_in: AGENT_AUTHORIZATION_TTL_SEC });
194
+ }
195
+
196
+ async function authorizationContext(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
197
+ if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
198
+ const client = await businessClient(deps, req, url);
199
+ if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
200
+ const item = await deps.configStore.agentAuth.getAuthorization(authorizationId);
201
+ if (!item || item.client_app_id !== client.app_id) { send(res, 404, { error: 'not_found' }); return; }
202
+ const status = item.status === 'pending' && Date.parse(item.expires_at) <= Date.now() ? 'expired' : item.status;
203
+ send(res, 200, {
204
+ authorization_id: item.authorization_id,
205
+ client: { app_id: client.app_id, name: client.name },
206
+ device: { name: item.device_label },
207
+ requested_routes: item.requested_routes,
208
+ status,
209
+ expires_at: item.expires_at,
210
+ });
211
+ }
212
+
213
+ async function approveAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
214
+ if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
215
+ const client = await businessClient(deps, req, url);
216
+ if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
217
+ const body = record(await readBody(req).catch(() => null));
218
+ if (!body || !allowedFields(body, ['principal', 'on_behalf_of', 'allowed_routes'])) { send(res, 400, { error: 'invalid_request' }); return; }
219
+ const principal = parsePrincipal(body['principal']);
220
+ const onBehalfOf = typeof body['on_behalf_of'] === 'string' ? body['on_behalf_of'].trim() : '';
221
+ const allowedRoutes = stringList(body['allowed_routes']);
222
+ if (!principal || !onBehalfOf || onBehalfOf.length > 191 || !allowedRoutes) { send(res, 400, { error: 'invalid_request' }); return; }
223
+ const pending = await deps.configStore.agentAuth.getAuthorization(authorizationId);
224
+ if (!pending || pending.client_app_id !== client.app_id) { send(res, 404, { error: 'not_found' }); return; }
225
+ if (allowedRoutes.some((route) => !requestedAllowsRoute(pending.requested_routes, route) || !clientAllowsRoute(client, route))) {
226
+ send(res, 403, { error: 'route_not_allowed' }); return;
227
+ }
228
+ const code = randomSecret('bhc');
229
+ const result = await deps.configStore.agentAuth.approveAuthorization({
230
+ authorizationId,
231
+ clientAppId: client.app_id,
232
+ principal: { ...principal },
233
+ onBehalfOf,
234
+ allowedRoutes,
235
+ codeHash: tokenHash(code),
236
+ codeExpiresAt: new Date(Date.now() + AGENT_AUTHORIZATION_CODE_TTL_SEC * 1000).toISOString(),
237
+ });
238
+ if (!result.ok) {
239
+ const status = result.reason === 'not_found' || result.reason === 'wrong_client' ? 404 : result.reason === 'expired' ? 410 : 409;
240
+ send(res, status, { error: result.reason }); return;
241
+ }
242
+ send(res, 200, { redirect_uri: redirectResult(result.authorization.redirect_uri, { code }, result.authorization.state) });
243
+ }
244
+
245
+ async function denyAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
246
+ if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
247
+ const client = await businessClient(deps, req, url);
248
+ if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
249
+ const body = record(await readBody(req).catch(() => ({}))) ?? {};
250
+ if (!allowedFields(body, [])) { send(res, 400, { error: 'invalid_request' }); return; }
251
+ const result = await deps.configStore.agentAuth.denyAuthorization({ authorizationId, clientAppId: client.app_id });
252
+ if (!result.ok) {
253
+ const status = result.reason === 'not_found' || result.reason === 'wrong_client' ? 404 : result.reason === 'expired' ? 410 : 409;
254
+ send(res, status, { error: result.reason }); return;
255
+ }
256
+ send(res, 200, { redirect_uri: redirectResult(result.authorization.redirect_uri, { error: 'access_denied' }, result.authorization.state) });
257
+ }
258
+
259
+ function tokenResponse(session: AgentSession, accessToken: string, refreshToken: string): RecordValue {
260
+ return {
261
+ token_type: 'Bearer',
262
+ access_token: accessToken,
263
+ expires_in: AGENT_ACCESS_TTL_SEC,
264
+ refresh_token: refreshToken,
265
+ refresh_expires_in: Math.max(0, Math.floor((Date.parse(session.refresh_expires_at) - Date.now()) / 1000)),
266
+ session_id: session.session_id,
267
+ client_app_id: session.client_app_id,
268
+ };
269
+ }
270
+
271
+ async function exchangeToken(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
272
+ if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
273
+ const body = record(await readBody(req).catch(() => null));
274
+ if (!body || typeof body['grant_type'] !== 'string') { send(res, 400, { error: 'invalid_request' }); return; }
275
+ const clientAppId = typeof body['client_app_id'] === 'string' ? body['client_app_id'].trim() : '';
276
+ if (!RESOURCE_RE.test(clientAppId)) { send(res, 400, { error: 'invalid_request' }); return; }
277
+ const client = await deps.configStore.clients.get(clientAppId);
278
+ if (!client?.enabled || !client.agent_authorize_url || !isAgentAuthorizeUrl(client.agent_authorize_url)) { send(res, 400, { error: 'invalid_grant' }); return; }
279
+ const accessToken = randomSecret('bha');
280
+ const refreshToken = randomSecret('bhr');
281
+ const accessExpiresAt = new Date(Date.now() + AGENT_ACCESS_TTL_SEC * 1000).toISOString();
282
+ const refreshExpiresAt = new Date(Date.now() + AGENT_REFRESH_TTL_SEC * 1000).toISOString();
283
+
284
+ if (body['grant_type'] === 'authorization_code') {
285
+ if (!allowedFields(body, ['grant_type', 'client_app_id', 'code', 'redirect_uri', 'code_verifier'])) { send(res, 400, { error: 'invalid_request' }); return; }
286
+ const code = typeof body['code'] === 'string' ? body['code'] : '';
287
+ const redirectUri = typeof body['redirect_uri'] === 'string' ? body['redirect_uri'] : '';
288
+ const verifier = typeof body['code_verifier'] === 'string' ? body['code_verifier'] : '';
289
+ if (!code.startsWith('bhc_') || code.length < 40 || !isLoopbackRedirectUri(redirectUri) || !PKCE_VERIFIER_RE.test(verifier)) {
290
+ send(res, 400, { error: 'invalid_grant' }); return;
291
+ }
292
+ const result = await deps.configStore.agentAuth.exchangeAuthorizationCode({
293
+ codeHash: tokenHash(code),
294
+ clientAppId,
295
+ redirectUri,
296
+ codeChallenge: pkceChallenge(verifier),
297
+ sessionId: randomUUID(),
298
+ accessTokenHash: tokenHash(accessToken),
299
+ refreshTokenHash: tokenHash(refreshToken),
300
+ accessExpiresAt,
301
+ refreshExpiresAt,
302
+ });
303
+ if (!result.ok) { send(res, 400, { error: 'invalid_grant' }); return; }
304
+ send(res, 200, tokenResponse(result.session, accessToken, refreshToken));
305
+ return;
306
+ }
307
+
308
+ if (body['grant_type'] === 'refresh_token') {
309
+ if (!allowedFields(body, ['grant_type', 'client_app_id', 'refresh_token'])) { send(res, 400, { error: 'invalid_request' }); return; }
310
+ const current = typeof body['refresh_token'] === 'string' ? body['refresh_token'] : '';
311
+ if (!current.startsWith('bhr_') || current.length < 40) { send(res, 400, { error: 'invalid_grant' }); return; }
312
+ const result = await deps.configStore.agentAuth.rotateRefreshToken({
313
+ refreshTokenHash: tokenHash(current),
314
+ clientAppId,
315
+ accessTokenHash: tokenHash(accessToken),
316
+ nextRefreshTokenHash: tokenHash(refreshToken),
317
+ accessExpiresAt,
318
+ });
319
+ if (!result.ok) { send(res, 400, { error: 'invalid_grant' }); return; }
320
+ send(res, 200, tokenResponse(result.session, accessToken, refreshToken));
321
+ return;
322
+ }
323
+
324
+ send(res, 400, { error: 'unsupported_grant_type' });
325
+ }
326
+
327
+ export async function authenticateAgentAccess(deps: AgentAuthHttpDeps, req: IncomingMessage, url: URL): Promise<{ session: AgentSession; client: Client } | null> {
328
+ if (!deps.configStore?.agentAuth) return null;
329
+ const token = bearerToken(req);
330
+ if (!token.startsWith('bha_') || token.length < 40) return null;
331
+ const session = await deps.configStore.agentAuth.getSessionByAccessHash(tokenHash(token));
332
+ if (!session) return null;
333
+ const client = await deps.configStore.clients.get(session.client_app_id);
334
+ return client?.enabled && client.agent_authorize_url && isAgentAuthorizeUrl(client.agent_authorize_url) ? { session, client } : null;
335
+ }
336
+
337
+ async function readSession(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
338
+ const auth = await authenticateAgentAccess(deps, req, url);
339
+ if (!auth) { send(res, 401, { error: 'unauthorized' }); return; }
340
+ send(res, 200, publicSession(auth.session));
341
+ }
342
+
343
+ async function revokeSession(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
344
+ if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
345
+ const token = bearerToken(req);
346
+ if (token) {
347
+ if (!token.startsWith('bha_')) { send(res, 401, { error: 'unauthorized' }); return; }
348
+ await deps.configStore.agentAuth.revokeByAccessHash(tokenHash(token));
349
+ send(res, 200, { revoked: true });
350
+ return;
351
+ }
352
+ const body = record(await readBody(req).catch(() => null));
353
+ if (!body || !allowedFields(body, ['client_app_id', 'refresh_token'])) { send(res, 400, { error: 'invalid_request' }); return; }
354
+ const clientAppId = typeof body['client_app_id'] === 'string' ? body['client_app_id'].trim() : '';
355
+ const refreshToken = typeof body['refresh_token'] === 'string' ? body['refresh_token'] : '';
356
+ if (!RESOURCE_RE.test(clientAppId) || !refreshToken.startsWith('bhr_')) { send(res, 400, { error: 'invalid_request' }); return; }
357
+ await deps.configStore.agentAuth.revokeByRefreshHash(clientAppId, tokenHash(refreshToken));
358
+ send(res, 200, { revoked: true });
359
+ }
360
+
361
+ async function businessRevokeSession(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, sessionId: string): Promise<void> {
362
+ if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
363
+ const client = await businessClient(deps, req, url);
364
+ if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
365
+ if (!UUID_RE.test(sessionId)) { send(res, 404, { error: 'not_found' }); return; }
366
+ const revoked = await deps.configStore.agentAuth.revokeSessionForClient(client.app_id, sessionId);
367
+ if (!revoked) { send(res, 404, { error: 'not_found' }); return; }
368
+ send(res, 200, { revoked: true });
369
+ }
370
+
371
+ /** Returns true when the request belongs to the dedicated Agent Auth surface. */
372
+ export async function handleAgentAuthHttpFor(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
373
+ const method = req.method ?? 'GET';
374
+ const path = url.pathname;
375
+ if (!path.startsWith('/agent-auth/')) return false;
376
+ res.setHeader('cache-control', 'no-store');
377
+ if (path === '/agent-auth/v1/token') res.setHeader('pragma', 'no-cache');
378
+ if (method === 'POST' && path === '/agent-auth/v1/authorizations') { await createAuthorization(deps, req, res); return true; }
379
+ const authorizationMatch = path.match(/^\/agent-auth\/v1\/authorizations\/([0-9a-f-]{36})(?:\/(approve|deny))?$/i);
380
+ if (authorizationMatch) {
381
+ const id = authorizationMatch[1]!;
382
+ const action = authorizationMatch[2];
383
+ if (!UUID_RE.test(id)) { send(res, 404, { error: 'not_found' }); return true; }
384
+ if (method === 'GET' && !action) { await authorizationContext(deps, req, res, url, id); return true; }
385
+ if (method === 'POST' && action === 'approve') { await approveAuthorization(deps, req, res, url, id); return true; }
386
+ if (method === 'POST' && action === 'deny') { await denyAuthorization(deps, req, res, url, id); return true; }
387
+ send(res, 405, { error: 'method_not_allowed' }); return true;
388
+ }
389
+ if (method === 'POST' && path === '/agent-auth/v1/token') { await exchangeToken(deps, req, res); return true; }
390
+ if (method === 'GET' && path === '/agent-auth/v1/session') { await readSession(deps, req, res, url); return true; }
391
+ if (method === 'POST' && path === '/agent-auth/v1/revoke') { await revokeSession(deps, req, res, url); return true; }
392
+ const revokeMatch = method === 'POST' ? path.match(/^\/agent-auth\/v1\/sessions\/([0-9a-f-]{36})\/revoke$/i) : null;
393
+ if (revokeMatch) { await businessRevokeSession(deps, req, res, url, revokeMatch[1]!); return true; }
394
+ send(res, 404, { error: 'not_found' }); return true;
395
+ }
@@ -10,6 +10,7 @@ import { parseApprovalDecisionEnvelope } from '../core/contracts/approval-decisi
10
10
  import type { AppConfig } from '../core/config/config';
11
11
  import type { RuntimeStateStore } from '../core/state/state-contracts';
12
12
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
13
+ import { isAgentToolInvocationJob } from '../app/agent-tool-job';
13
14
 
14
15
  export interface ApprovalDecisionDeps {
15
16
  cfg: AppConfig;
@@ -111,7 +112,9 @@ export async function handleApprovalDecisionFor(deps: ApprovalDecisionDeps, req:
111
112
  let rerun = false;
112
113
  if (decision.decision === 'approved') {
113
114
  const latest = await deps.stateStore.getJob(approval.job_id);
114
- if (latest && (latest.status === 'done' || latest.status === 'error' || latest.status === 'rejected')) {
115
+ // Agent 直调没有中枢模型这一层;批准后由原本地 Agent 持 invocation_id
116
+ // 续执行冻结快照。绝不得把 synthetic Job 重排进 LLM 调度器。
117
+ if (latest && !isAgentToolInvocationJob(latest) && (latest.status === 'done' || latest.status === 'error' || latest.status === 'rejected')) {
115
118
  await deps.engineRuntime.requeueForRerun(latest, decision.approver, `approval_${approvalId}`);
116
119
  rerun = true;
117
120
  }
@@ -5,7 +5,8 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
5
5
  import type { Principal } from '../app/auth';
6
6
  import type { AppConfig } from '../core/config/config';
7
7
  import type { RuntimeContext } from '../core/edition';
8
- import type { Client, Job, Route, ToolApproval } from '../core/contracts/types';
8
+ import type { AgentSession, Client, Job, Route, ToolApproval } from '../core/contracts/types';
9
+ import type { LaunchSpec } from '../core/runtime/launch-runtime';
9
10
  import type { RuntimeStateStore } from '../core/state/state-contracts';
10
11
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
11
12
  import { handleRunFor, type RunApiDeps } from './run';
@@ -183,6 +184,184 @@ test('POST /run: request_id 不能跨接入方碰撞', async () => {
183
184
  assert.match(String(res.json()['error']), /其他接入方冲突/);
184
185
  });
185
186
 
187
+ test('POST /agent-api/v1/run: 业务主体和 Agent Session 由服务端注入,metadata 不能劫持', async () => {
188
+ const route: Route = {
189
+ route_key: 'orders',
190
+ name: 'Orders',
191
+ enabled: true,
192
+ target: 'llm',
193
+ target_config: {},
194
+ profile: 'general',
195
+ session_policy: 'per_key',
196
+ session_key_field: 'arbitrary_user_key',
197
+ };
198
+ const session: AgentSession = {
199
+ session_id: '123e4567-e89b-42d3-a456-426614174000',
200
+ client_app_id: client.app_id,
201
+ device_label: 'Mac mini',
202
+ principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'], audience: 'employee' },
203
+ on_behalf_of: 'tenant-2:user-7',
204
+ allowed_routes: ['orders'],
205
+ created_at: '2026-01-01T00:00:00.000Z',
206
+ access_expires_at: '2026-01-01T01:00:00.000Z',
207
+ refresh_expires_at: '2026-02-01T00:00:00.000Z',
208
+ };
209
+ const agentPrincipal: Principal = { kind: 'agent', client, session };
210
+ let trustedScope: string | null = null;
211
+ let launch: LaunchSpec | null = null;
212
+ const config = {
213
+ routes: { get: async () => route },
214
+ conversations: {
215
+ resolveSession: async () => { throw new Error('Agent per_key must not resolve from metadata'); },
216
+ sessionForScope: async (routeKey: string, scopeKey: string) => {
217
+ assert.equal(routeKey, route.route_key);
218
+ trustedScope = scopeKey;
219
+ return { sessionId: 'brain-session-1', isContinue: true, scopeKey };
220
+ },
221
+ },
222
+ targets: { list: async () => [] },
223
+ clients: { touch: async () => undefined },
224
+ rateLimits: { consume: async () => false },
225
+ } as unknown as ConfigStoreContract;
226
+ const state = { findByRequestId: async () => null } as unknown as RuntimeStateStore;
227
+ const deps: RunApiDeps = {
228
+ cfg: { defaultProfile: 'general' },
229
+ isPaused: () => false,
230
+ runtimeContextFor: async ({ requestId }) => runtimeContext(requestId, 'run'),
231
+ runtimeStoresFor: () => ({ state, config }),
232
+ resolveProjectPathFor: async () => null,
233
+ engineForContext: () => ({
234
+ launchJob: async (spec) => {
235
+ launch = spec;
236
+ return job({
237
+ job_id: 'job-agent',
238
+ request_id: spec.requestId,
239
+ client_app_id: client.app_id,
240
+ agent_session_id: spec.agentAttribution?.agentSessionId,
241
+ on_behalf_of: spec.agentAttribution?.onBehalfOf,
242
+ metadata: spec.metadata,
243
+ });
244
+ },
245
+ }),
246
+ };
247
+ const res = new FakeResponse();
248
+ await handleRunFor(
249
+ deps,
250
+ jsonRequest({
251
+ request_id: 'agent-request-1',
252
+ route: 'orders',
253
+ input: 'query orders',
254
+ metadata: {
255
+ custom_hint: 'keep-me',
256
+ principal: { id: 'attacker', roles: ['admin'] },
257
+ subject: { id: 'attacker-2' },
258
+ visitor_uid: 'attacker',
259
+ operator_uid: 'attacker',
260
+ tenant: 'other-tenant',
261
+ roles: ['admin'],
262
+ session_id: 'hijacked-brain-session',
263
+ arbitrary_user_key: 'victim-history-scope',
264
+ on_behalf_of: 'attacker',
265
+ agent_session_id: 'attacker-session',
266
+ source: 'forged',
267
+ },
268
+ }),
269
+ res as unknown as ServerResponse,
270
+ agentPrincipal,
271
+ );
272
+
273
+ assert.equal(res.statusCode, 202);
274
+ assert.match(trustedScope ?? '', /^agent-subject:[a-f0-9]{64}$/);
275
+ assert.notEqual(trustedScope, 'victim-history-scope');
276
+ const firstClientScope = trustedScope ?? '';
277
+ assert.ok(launch);
278
+ const launchSpec = launch as unknown as LaunchSpec;
279
+ assert.equal(launchSpec.metadata['visitor_uid'], session.on_behalf_of);
280
+ assert.equal(launchSpec.metadata['operator_uid'], session.on_behalf_of);
281
+ assert.equal(launchSpec.metadata['session_id'], undefined);
282
+ assert.equal(launchSpec.metadata['tenant'], undefined);
283
+ assert.equal((launchSpec.metadata['principal'] as Record<string, unknown>)['id'], session.principal.id);
284
+ assert.equal((launchSpec.metadata['principal'] as Record<string, unknown>)['tenant'], session.principal.tenant);
285
+ assert.deepEqual((launchSpec.metadata['principal'] as Record<string, unknown>)['roles'], session.principal.roles);
286
+ assert.equal(launchSpec.metadata['custom_hint'], 'keep-me');
287
+ assert.equal(launchSpec.source, `agent:${client.app_id}`);
288
+ assert.equal(launchSpec.callbackUrl, undefined);
289
+ assert.deepEqual(launchSpec.agentAttribution, {
290
+ agentSessionId: session.session_id,
291
+ clientAppId: client.app_id,
292
+ subjectId: 'user-7',
293
+ businessTenantRef: 'tenant-2',
294
+ onBehalfOf: session.on_behalf_of,
295
+ });
296
+
297
+ const otherClient: Client = { ...client, app_id: 'client-b', name: 'Client B', token: 'other-client-token' };
298
+ const otherSession: AgentSession = {
299
+ ...session,
300
+ session_id: '223e4567-e89b-42d3-a456-426614174000',
301
+ client_app_id: otherClient.app_id,
302
+ };
303
+ const otherRes = new FakeResponse();
304
+ await handleRunFor(
305
+ deps,
306
+ jsonRequest({
307
+ request_id: 'agent-request-other-client',
308
+ route: 'orders',
309
+ input: 'same subject, another client',
310
+ metadata: { arbitrary_user_key: 'victim-history-scope' },
311
+ }),
312
+ otherRes as unknown as ServerResponse,
313
+ { kind: 'agent', client: otherClient, session: otherSession },
314
+ );
315
+ assert.equal(otherRes.statusCode, 202);
316
+ assert.match(trustedScope ?? '', /^agent-subject:[a-f0-9]{64}$/);
317
+ assert.notEqual(trustedScope, firstClientScope, '同 route 下不同 Client 的同名主体不得共用会话 scope');
318
+ });
319
+
320
+ test('POST /agent-api/v1/run: fixed 与 passthrough 会话策略对 Agent 失败关闭', async (t) => {
321
+ const session: AgentSession = {
322
+ session_id: '123e4567-e89b-42d3-a456-426614174000',
323
+ client_app_id: client.app_id,
324
+ device_label: 'Mac mini',
325
+ principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
326
+ on_behalf_of: 'tenant-2:user-7',
327
+ allowed_routes: ['orders'],
328
+ created_at: '2026-01-01T00:00:00.000Z',
329
+ access_expires_at: '2026-01-01T01:00:00.000Z',
330
+ refresh_expires_at: '2026-02-01T00:00:00.000Z',
331
+ };
332
+ const agentPrincipal: Principal = { kind: 'agent', client, session };
333
+ for (const policy of ['fixed', 'passthrough'] as const) {
334
+ await t.test(policy, async () => {
335
+ const route: Route = {
336
+ route_key: 'orders', name: 'Orders', enabled: true, target: 'llm', target_config: {}, profile: 'general',
337
+ session_policy: policy,
338
+ ...(policy === 'fixed' ? { session_fixed_id: 'shared-session' } : { session_key_field: 'session_id' }),
339
+ };
340
+ const config = {
341
+ routes: { get: async () => route },
342
+ conversations: { resolveSession: async () => { throw new Error('unsafe session resolver must not run'); } },
343
+ targets: { list: async () => [] },
344
+ clients: { touch: async () => undefined },
345
+ rateLimits: { consume: async () => false },
346
+ } as unknown as ConfigStoreContract;
347
+ const res = new FakeResponse();
348
+ await handleRunFor(
349
+ runDeps({ findByRequestId: async () => null } as unknown as RuntimeStateStore, config),
350
+ jsonRequest({
351
+ request_id: `agent-${policy}`,
352
+ route: 'orders',
353
+ input: 'query orders',
354
+ metadata: { session_id: 'victim-session' },
355
+ }),
356
+ res as unknown as ServerResponse,
357
+ agentPrincipal,
358
+ );
359
+ assert.equal(res.statusCode, 403);
360
+ assert.match(String(res.json()['error']), new RegExp(`session_policy=${policy}`));
361
+ });
362
+ }
363
+ });
364
+
186
365
  function approval(status: ToolApproval['status'] = 'pending'): ToolApproval {
187
366
  return {
188
367
  id: 7,
@@ -261,6 +440,61 @@ test('审批决策: 同一 decision_id 的同一决策幂等返回', async () =>
261
440
  assert.equal(res.json()['rerun'], false);
262
441
  });
263
442
 
443
+ test('审批决策: 普通任务伪造 direct metadata 仍按原模型任务重跑', async () => {
444
+ let reruns = 0;
445
+ const item = approval();
446
+ const forged = job({
447
+ status: 'done',
448
+ target: 'llm',
449
+ client_app_id: 'client-a',
450
+ agent_session_id: '123e4567-e89b-42d3-a456-426614174000',
451
+ on_behalf_of: 'tenant-1:user-7',
452
+ session_id: '223e4567-e89b-42d3-a456-426614174000',
453
+ source: 'agent:client-a',
454
+ dispatch: { route_key: 'orders' },
455
+ metadata: {
456
+ agent_tool_job_marker: 'bailing.agent-tool-job.v1',
457
+ agent_tool_call_v1: true,
458
+ agent_invocation_id: 'a'.repeat(64),
459
+ agent_run_id: '223e4567-e89b-42d3-a456-426614174000',
460
+ agent_route: 'orders',
461
+ agent_tool: 'refund_create',
462
+ agent_args_hash: 'b'.repeat(64),
463
+ agent_capability_revision: 'c'.repeat(64),
464
+ agent_execution_fingerprint: 'd'.repeat(64),
465
+ },
466
+ });
467
+ const deps: ApprovalDecisionDeps = {
468
+ cfg: { server: { token: 'admin-token' } } as unknown as AppConfig,
469
+ configStore: {
470
+ approvals: {
471
+ get: async () => item,
472
+ getByDecisionId: async () => null,
473
+ decide: async () => true,
474
+ },
475
+ } as unknown as ConfigStoreContract,
476
+ stateStore: {
477
+ getJob: async () => forged,
478
+ appendAudit: async () => undefined,
479
+ } as unknown as RuntimeStateStore,
480
+ now: () => '2026-01-01T00:00:00.000Z',
481
+ sleep: async () => undefined,
482
+ secretForJob: async () => 'approval-secret',
483
+ engineRuntime: { requeueForRerun: async () => { reruns++; } },
484
+ };
485
+ const res = new FakeResponse();
486
+ await handleApprovalDecisionFor(
487
+ deps,
488
+ jsonRequest(approvalBody(), { authorization: 'Bearer admin-token' }),
489
+ res as unknown as ServerResponse,
490
+ 7,
491
+ new URL('http://local/approvals/7/decision'),
492
+ );
493
+ assert.equal(res.statusCode, 200);
494
+ assert.equal(res.json()['rerun'], true);
495
+ assert.equal(reruns, 1);
496
+ });
497
+
264
498
  test('执行器回报: 过期 claim_token 的迟到结果不会覆盖新认领任务', async () => {
265
499
  let finishCalls = 0;
266
500
  const state = {