bailinghub 0.7.0 → 0.9.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 (263) hide show
  1. package/README.en.md +7 -9
  2. package/README.md +7 -9
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
  5. package/docs/AGENT_CLIENT_RUNTIME_API.md +34 -0
  6. package/docs/AGENT_TASK_CONTROL.en.md +25 -0
  7. package/docs/AGENT_TASK_CONTROL.md +94 -0
  8. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
  9. package/docs/ARCHITECTURE.md +1 -1
  10. package/docs/CHANGELOG.en.md +22 -1
  11. package/docs/CHANGELOG.md +22 -1
  12. package/docs/COMPATIBILITY.en.md +6 -0
  13. package/docs/CONTRACT.en.md +2 -0
  14. package/docs/CONTRACT.md +2 -0
  15. package/docs/GENERATED_ARTIFACTS.en.md +46 -0
  16. package/docs/GENERATED_ARTIFACTS.md +108 -0
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/INVOCATION_RECEIPTS.md +111 -0
  20. package/docs/MODEL_BILLING.en.md +123 -0
  21. package/docs/MODEL_BILLING.md +125 -0
  22. package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
  23. package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
  24. package/docs/README.en.md +7 -0
  25. package/docs/README.md +7 -0
  26. package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
  27. package/docs/RELEASE_NOTES_NEXT.md +4 -2
  28. package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
  29. package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
  30. package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
  31. package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
  32. package/docs/TOOL_RATE_LIMITS.md +50 -0
  33. package/docs/UPGRADE_v0.8.0.en.md +71 -0
  34. package/docs/UPGRADE_v0.8.0.md +73 -0
  35. package/docs/UPGRADE_v0.9.0.en.md +54 -0
  36. package/docs/UPGRADE_v0.9.0.md +54 -0
  37. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +6 -0
  38. package/package.json +1 -1
  39. package/schemas/config/route.schema.json +1 -0
  40. package/schemas/config/tool-provider.schema.json +2 -1
  41. package/scripts/check-doc-links.mjs +5 -0
  42. package/scripts/check-image-tags.sh +1 -1
  43. package/scripts/check-release-consistency.test.mjs +2 -2
  44. package/scripts/e2e-console.mjs +32 -2
  45. package/scripts/install.sh +1 -1
  46. package/scripts/publish-images.sh +1 -1
  47. package/scripts/release-audit.mjs +2 -0
  48. package/scripts/sdk-runtime-test.mjs +6 -0
  49. package/scripts/verify-billing-install-upgrade.mjs +225 -0
  50. package/scripts/verify-github-repo.mjs +2 -0
  51. package/sdk/node/README.md +17 -0
  52. package/sdk/node/examples/billing.mjs +21 -0
  53. package/sdk/node/package.json +5 -1
  54. package/sdk/node/src/index.mjs +2 -0
  55. package/sdk/node/src/usage.d.mts +74 -0
  56. package/sdk/node/src/usage.mjs +62 -0
  57. package/sdk/node/tests/usage-types.mts +23 -0
  58. package/sdk/node/tests/usage.test.mjs +81 -0
  59. package/sdk/php7/README.md +19 -2
  60. package/sdk/php7/examples/billing.php +27 -0
  61. package/sdk/php7/examples/well-known.php +1 -1
  62. package/sdk/php7/src/ToolSpec.php +1 -1
  63. package/sdk/php7/src/UsageClient.php +95 -0
  64. package/sdk/php7/src/UsageClientException.php +22 -0
  65. package/sdk/php7/tests/billing-core-http.php +59 -0
  66. package/sdk/php7/tests/usage-client.php +78 -0
  67. package/sql/060_agent_artifacts.sql +11 -0
  68. package/sql/061_tool_rate_limit_policies.sql +3 -0
  69. package/sql/062_agent_task_control.sql +92 -0
  70. package/sql/063_usage_model_billing.sql +153 -0
  71. package/sql/064_period_plan_allowance.sql +25 -0
  72. package/sql/README.en.md +12 -4
  73. package/sql/README.md +14 -6
  74. package/src/adapters/storage/object-storage.ts +15 -3
  75. package/src/adapters/storage/oss-signature.test.ts +40 -0
  76. package/src/adapters/storage/oss-signature.ts +21 -0
  77. package/src/app/agent-artifacts.test.ts +165 -0
  78. package/src/app/agent-artifacts.ts +85 -0
  79. package/src/app/agent-client-runtime.test.ts +76 -1
  80. package/src/app/agent-client-runtime.ts +13 -0
  81. package/src/app/agent-invocation-snapshot.ts +35 -0
  82. package/src/app/agent-task-control.ts +187 -0
  83. package/src/app/agent-task-runtime.ts +68 -0
  84. package/src/app/agent-tool-invocations.test.ts +329 -1
  85. package/src/app/agent-tool-invocations.ts +223 -10
  86. package/src/app/agent-tool-job.test.ts +11 -1
  87. package/src/app/agent-tool-job.ts +8 -1
  88. package/src/app/auth.ts +2 -0
  89. package/src/app/builtin-tools.ts +4 -0
  90. package/src/app/oss-edition.ts +2 -0
  91. package/src/app/tool-approvals.ts +4 -0
  92. package/src/app/tool-assembly.ts +5 -0
  93. package/src/core/config/artifact-config.ts +15 -0
  94. package/src/core/config/config-codec.ts +3 -1
  95. package/src/core/config/config-models.ts +11 -1
  96. package/src/core/config/route-config.ts +3 -2
  97. package/src/core/contracts/tool-rate-limits.test.ts +59 -0
  98. package/src/core/contracts/tool-rate-limits.ts +48 -0
  99. package/src/core/contracts/tools.ts +122 -43
  100. package/src/core/contracts/types.ts +3 -1
  101. package/src/core/runtime/agent-task-control.test.ts +114 -0
  102. package/src/core/runtime/agent-task-control.ts +227 -0
  103. package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
  104. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
  105. package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
  106. package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
  107. package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
  108. package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
  109. package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
  110. package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
  111. package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
  112. package/src/infrastructure/config/configstore.ts +15 -1
  113. package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
  114. package/src/modules/usage/billing-contracts.ts +59 -0
  115. package/src/modules/usage/billing-decimal.test.ts +22 -0
  116. package/src/modules/usage/billing-decimal.ts +36 -0
  117. package/src/modules/usage/billing-external.ts +39 -0
  118. package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
  119. package/src/modules/usage/billing-ledger.test.ts +51 -0
  120. package/src/modules/usage/billing-ledger.ts +104 -0
  121. package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
  122. package/src/modules/usage/billing-presentation.test.ts +49 -0
  123. package/src/modules/usage/billing-presentation.ts +34 -0
  124. package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
  125. package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
  126. package/src/modules/usage/billing-repository.ts +463 -0
  127. package/src/modules/usage/contracts.ts +49 -0
  128. package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
  129. package/src/modules/usage/errors.ts +19 -0
  130. package/src/modules/usage/http.ts +85 -0
  131. package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
  132. package/src/modules/usage/identity.mysql.test.ts +120 -0
  133. package/src/modules/usage/identity.ts +303 -0
  134. package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
  135. package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
  136. package/src/modules/usage/model-gateway.ts +229 -0
  137. package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
  138. package/src/modules/usage/model-tool-provider.test.ts +37 -0
  139. package/src/modules/usage/model-tool-provider.ts +110 -0
  140. package/src/modules/usage/model-tools.test.ts +36 -0
  141. package/src/modules/usage/model-tools.ts +62 -0
  142. package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
  143. package/src/modules/usage/period.test.ts +26 -0
  144. package/src/modules/usage/period.ts +96 -0
  145. package/src/modules/usage/pricing.test.ts +178 -0
  146. package/src/modules/usage/pricing.ts +228 -0
  147. package/src/modules/usage/provider-failure.ts +37 -0
  148. package/src/modules/usage/provider-stream.test.ts +85 -0
  149. package/src/modules/usage/provider-stream.ts +77 -0
  150. package/src/modules/usage/provider.test.ts +67 -0
  151. package/src/modules/usage/provider.ts +142 -0
  152. package/src/modules/usage/repository.ts +539 -0
  153. package/src/modules/usage/service-availability.mysql.test.ts +68 -0
  154. package/src/modules/usage/service-availability.ts +13 -0
  155. package/src/modules/usage/service-delete.mysql.test.ts +87 -0
  156. package/src/modules/usage/stream-http.ts +32 -0
  157. package/src/modules/usage/test-harness.ts +108 -0
  158. package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
  159. package/src/modules/usage/usage-deletion.ts +119 -0
  160. package/src/modules/usage/validation.test.ts +18 -0
  161. package/src/modules/usage/validation.ts +33 -0
  162. package/src/routes/admin-agent-tasks.ts +32 -0
  163. package/src/routes/admin-billing-usage.ts +73 -0
  164. package/src/routes/admin-tool-providers.test.ts +22 -0
  165. package/src/routes/admin-tool-providers.ts +9 -1
  166. package/src/routes/admin-usage.ts +147 -0
  167. package/src/routes/admin.ts +7 -0
  168. package/src/routes/agent-api.test.ts +76 -0
  169. package/src/routes/agent-api.ts +42 -1
  170. package/src/routes/agent-artifacts.ts +29 -0
  171. package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
  172. package/src/routes/private.ts +9 -0
  173. package/src/routes/run.ts +2 -1
  174. package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
  175. package/web/connect/bailing-connect-php7.tgz +0 -0
  176. package/web/console/assets/Accounts-Bervi5JU.css +1 -0
  177. package/web/console/assets/Accounts-DnddhY6t.js +3 -0
  178. package/web/console/assets/AgentClients-VInbD7JS.js +1 -0
  179. package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
  180. package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
  181. package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
  182. package/web/console/assets/{Approvals-Bs6FGbp2.js → Approvals-34qUPHf0.js} +1 -1
  183. package/web/console/assets/{Audit-4WWYhkFM.js → Audit-BbVgkSm2.js} +1 -1
  184. package/web/console/assets/{BrandLockup-D2GhCipL.js → BrandLockup-DgscF28e.js} +1 -1
  185. package/web/console/assets/{Channels-CmoGpiCJ.js → Channels-Bp-yuk8d.js} +1 -1
  186. package/web/console/assets/{ChatEntries-BFRMtwta.js → ChatEntries-C9Ft60TS.js} +1 -1
  187. package/web/console/assets/{Clients-DGkkSXyA.js → Clients-NPldD-DD.js} +1 -1
  188. package/web/console/assets/{Cost-BmGt0MfS.js → Cost-DZcuB-EB.js} +1 -1
  189. package/web/console/assets/{Credentials-CR-sYINT.js → Credentials-RTT7N6zl.js} +1 -1
  190. package/web/console/assets/{Diagnostics-DAPbKSJp.js → Diagnostics-_LeK8cce.js} +1 -1
  191. package/web/console/assets/{Executors-CgpiT3o8.js → Executors-Bi7H8rIm.js} +1 -1
  192. package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
  193. package/web/console/assets/{Kb-Cm9dVSQw.js → Kb-BHamz8NP.js} +2 -2
  194. package/web/console/assets/{Login-CyUcsTZ_.js → Login-C1rJR-6w.js} +1 -1
  195. package/web/console/assets/{Projects-DldFPgWg.js → Projects-BRA4a48v.js} +1 -1
  196. package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
  197. package/web/console/assets/Routes-CyXV4Pba.css +1 -0
  198. package/web/console/assets/{Runs-1hxgkuR4.js → Runs-B_fa_BlD.js} +1 -1
  199. package/web/console/assets/{Setup-DBLOnI2_.js → Setup-C1_d0mFy.js} +1 -1
  200. package/web/console/assets/Shell-CHEV6RGC.js +1 -0
  201. package/web/console/assets/Shell-ykb-tUfo.css +1 -0
  202. package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
  203. package/web/console/assets/StorageBuckets-DlG3ojhA.js +1 -0
  204. package/web/console/assets/{SystemSettings-cDkudo2y.js → SystemSettings-DYo2gg6d.js} +1 -1
  205. package/web/console/assets/{SystemStatus-DZd6s8OX.js → SystemStatus-DKCoUZlq.js} +1 -1
  206. package/web/console/assets/{Targets-DYNGq1NU.js → Targets-CdkG6BPR.js} +1 -1
  207. package/web/console/assets/Tools-DU8ei6sd.css +1 -0
  208. package/web/console/assets/Tools-DVpCt0ox.js +2 -0
  209. package/web/console/assets/Usage-CAeDGjrb.css +1 -0
  210. package/web/console/assets/Usage-DWCpLugC.js +1 -0
  211. package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
  212. package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
  213. package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
  214. package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
  215. package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
  216. package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
  217. package/web/console/assets/index-H1kfa0Mj.js +2 -0
  218. package/web/console/assets/{request-B7MLvOqo.js → request-DLsP1_ot.js} +1 -1
  219. package/web/console/assets/{schema-CMuwjYdJ.js → schema-BLOHvAJQ.js} +1 -1
  220. package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
  221. package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
  222. package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
  223. package/web/console/index.html +3 -3
  224. package/web-admin/README.md +17 -0
  225. package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
  226. package/web-admin/src/components/AgentSetupPanel.vue +13 -0
  227. package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
  228. package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
  229. package/web-admin/src/components/UsageHelp.vue +72 -0
  230. package/web-admin/src/components/UsageServiceReferences.vue +169 -0
  231. package/web-admin/src/layout/Shell.vue +23 -6
  232. package/web-admin/src/pages/Accounts.vue +3 -3
  233. package/web-admin/src/pages/AgentClients.vue +3 -1
  234. package/web-admin/src/pages/AgentTasks.vue +281 -0
  235. package/web-admin/src/pages/Routes.vue +5 -1
  236. package/web-admin/src/pages/StorageBuckets.vue +6 -6
  237. package/web-admin/src/pages/Tools.vue +53 -4
  238. package/web-admin/src/pages/Usage.vue +2470 -0
  239. package/web-admin/src/pages/UsageAccess.vue +1147 -0
  240. package/web-admin/src/router.ts +10 -4
  241. package/web-admin/src/styles/base.css +57 -0
  242. package/web-admin/src/table-widths.ts +16 -1
  243. package/web-admin/src/usage-deletion.ts +40 -0
  244. package/web-admin/src/usage-management.ts +13 -0
  245. package/web-admin/src/usage-presentation.test.ts +21 -0
  246. package/web-admin/src/usage-presentation.ts +107 -0
  247. package/web-admin/src/usage-price-preview.test.ts +60 -0
  248. package/web-admin/src/usage-price-preview.ts +54 -0
  249. package/web-admin/tests/token-usage.browser.mjs +773 -0
  250. package/web-admin/tests/usage-access.browser.mjs +398 -0
  251. package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
  252. package/web/console/assets/Accounts-ChL9k-XA.js +0 -3
  253. package/web/console/assets/AgentClients-Bs7UgVDj.js +0 -1
  254. package/web/console/assets/AgentClients-DkgPTEbq.css +0 -1
  255. package/web/console/assets/Routes-DkMIjMQA.css +0 -1
  256. package/web/console/assets/Routes-DubfjlBD.js +0 -124
  257. package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
  258. package/web/console/assets/Shell-gJ5Vz_E7.js +0 -1
  259. package/web/console/assets/StorageBuckets-DkDW16tj.js +0 -1
  260. package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
  261. package/web/console/assets/Tools-A20oaMaQ.css +0 -1
  262. package/web/console/assets/Tools-DpWM59vV.js +0 -2
  263. package/web/console/assets/index-DGqs28gI.js +0 -2
@@ -1,4 +1,5 @@
1
1
  import assert from 'node:assert/strict';
2
+ import { createHash } from 'node:crypto';
2
3
  import { Readable } from 'node:stream';
3
4
  import type { IncomingMessage, ServerResponse } from 'node:http';
4
5
  import test from 'node:test';
@@ -191,6 +192,74 @@ test('Agent Tool API: pause 在读取请求与工具治理链前拦截 invoke/re
191
192
  assert.equal(resume.json()['error'], 'hub_paused');
192
193
  });
193
194
 
195
+ test('Agent receipt HTTP: authenticated capability negotiation and inspection work during global pause', async () => {
196
+ const fx = runtimeHttpFixture();
197
+ const headers = { authorization: `Bearer ${fx.token}` };
198
+ const session = (await fx.deps.configStore.agentAuth!.getSessionByAccessHash(tokenHash(fx.token)))!;
199
+ const invocationId = 'a'.repeat(64);
200
+ const runId = '22222222-2222-4222-8222-222222222222';
201
+ const requestId = `agent-tool:${createHash('sha256').update(`bailing.agent-tool.v1\0${session.session_id}\0${invocationId}`).digest('hex')}`;
202
+ const job: Job = {
203
+ job_id: '33333333-3333-4333-8333-333333333333', request_id: requestId, target: 'agent-tool-v1',
204
+ status: 'done', profile: 'general', project: '', source: `agent-tool:${session.client_app_id}`,
205
+ client_app_id: session.client_app_id, agent_session_id: session.session_id, session_id: runId,
206
+ on_behalf_of: session.on_behalf_of, input_preview: 'Synthetic invocation',
207
+ metadata: {
208
+ agent_tool_job_marker: 'bailing.agent-tool-job.v1', agent_tool_call_v1: true,
209
+ agent_invocation_id: invocationId, agent_run_id: runId, agent_route: 'allowed', agent_tool: 'staff_list',
210
+ agent_args_hash: 'b'.repeat(64), agent_capability_revision: 'c'.repeat(64), agent_execution_fingerprint: 'd'.repeat(64),
211
+ agent_dispatch_attempted: true, principal: session.principal,
212
+ },
213
+ dispatch: { route_key: 'allowed' },
214
+ result: {
215
+ schema_version: 'bailing.agent-tool-invocation.v1', invocation_id: invocationId, route: 'allowed', tool: 'staff_list',
216
+ state: 'executed', ok: true, auto_retry_allowed: false, text: 'Synthetic result', business_status: 200,
217
+ },
218
+ created_at: '2026-01-01T00:00:00.000Z', updated_at: '2026-01-01T00:00:00.000Z',
219
+ };
220
+ const before = JSON.stringify(job);
221
+ let stateReads = 0;
222
+ fx.deps.stateStore.findByRequestId = async (id: string) => { stateReads++; return id === requestId ? job : null; };
223
+ fx.deps.configStore.toolCalls.get = async () => null;
224
+ fx.deps.configStore.approvals.forJob = async () => [];
225
+ const denied = async () => { throw new Error('unexpected_inspection_mutation'); };
226
+ fx.deps.stateStore.createJob = denied;
227
+ fx.deps.stateStore.updateJob = denied;
228
+ fx.deps.stateStore.acquireRuntimeLock = denied;
229
+ fx.deps.stateStore.appendAudit = denied;
230
+ fx.deps.isPaused = () => true;
231
+ const capabilityUrl = new URL('https://hub.example.com/agent-api/v1/tool-invocations/inspection-capabilities');
232
+ const receiptUrl = new URL(`https://hub.example.com/agent-api/v1/tool-invocations/${invocationId}/receipt`);
233
+ const capabilities = new FakeResponse();
234
+ await handleAgentApiHttpFor(fx.deps, request('GET', headers), capabilities as unknown as ServerResponse, capabilityUrl);
235
+ assert.deepEqual(capabilities.json(), {
236
+ schema_version: 'bailing.agent-invocation-inspection-capabilities.v1',
237
+ receipt_schema: 'bailing.agent-invocation-receipt.v1', read_only: true,
238
+ });
239
+ assert.equal(stateReads, 0);
240
+ const response = new FakeResponse();
241
+ await handleAgentApiHttpFor(fx.deps, request('GET', headers), response as unknown as ServerResponse, receiptUrl);
242
+ assert.equal(response.statusCode, 200);
243
+ assert.equal(response.headers['cache-control'], 'no-store');
244
+ assert.equal(response.json()['read_only'], true);
245
+ assert.equal(response.json()['business_operation_performed'], false);
246
+ assert.equal((response.json()['result'] as Record<string, unknown>)['text'], 'Synthetic result');
247
+ assert.equal(stateReads, 1);
248
+ assert.equal(JSON.stringify(job), before);
249
+
250
+ for (const url of [capabilityUrl, receiptUrl]) {
251
+ const anonymous = new FakeResponse();
252
+ await handleAgentApiHttpFor(fx.deps, request('GET'), anonymous as unknown as ServerResponse, url);
253
+ assert.equal(anonymous.statusCode, 401);
254
+ const changed = new URL(url);
255
+ changed.searchParams.set('route', 'another-target');
256
+ const parameters = new FakeResponse();
257
+ await handleAgentApiHttpFor(fx.deps, request('GET', headers), parameters as unknown as ServerResponse, changed);
258
+ assert.equal(parameters.statusCode, 400);
259
+ }
260
+ assert.equal(stateReads, 1, 'rejected inspection envelopes must not read invocation records');
261
+ });
262
+
194
263
  function runtimeHttpFixture() {
195
264
  const token = `bha_${'r'.repeat(43)}`;
196
265
  const client: Client = {
@@ -264,6 +333,8 @@ function runtimeHttpFixture() {
264
333
  toolProviders: { get: async () => provider },
265
334
  conversations: { getThreadMemory: async () => ({ summary: null, summary_upto_id: 0 }), recentMessagesAfter: async () => [] },
266
335
  agentClientRuntime: runtimeRepo,
336
+ toolCalls: { get: async () => null },
337
+ approvals: { forJob: async () => [] },
267
338
  } as unknown as ConfigStoreContract;
268
339
  const stateStore = { appendAudit: async () => undefined } as unknown as RuntimeStateStore;
269
340
  const toolProxyDeps: ToolProxyDeps = {
@@ -376,4 +447,9 @@ test('Agent Runtime HTTP: 客户端文本与 renderers 非法时 400,空搜索
376
447
  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
448
  assert.equal(search.statusCode, 200, JSON.stringify(search.json()));
378
449
  assert.equal(search.json()['query'], '查询员工');
450
+ assert.deepEqual(search.json()['discovery'], {
451
+ mode: 'ranked_candidates', scope: 'current_authorization', returned_count: 1, authorized_total: 1,
452
+ matched_total: null, matched_total_exact: false, limit: 1, truncated: false, has_more: false,
453
+ truncation_scope: 'authorized_catalog', pagination: 'unsupported',
454
+ }, 'HTTP serialization must preserve discovery semantics for SDK and host consumers');
379
455
  });
@@ -1,9 +1,12 @@
1
+ import { handleAgentArtifacts } from './agent-artifacts';
1
2
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
3
  import { PayloadTooLargeError, readBody, send } from '../app/http';
3
4
  import type { Principal } from '../app/auth';
4
5
  import type { ToolProxyDeps } from '../app/tool-proxy';
5
6
  import {
6
7
  AgentToolApiError,
8
+ agentInvocationInspectionCapabilities,
9
+ inspectAgentToolInvocationFor,
7
10
  invokeAgentToolFor,
8
11
  listAgentToolsFor,
9
12
  resumeAgentToolFor,
@@ -15,6 +18,8 @@ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
15
18
  import { authenticateAgentAccess } from './agent-auth';
16
19
  import { handleAgentConversationAuditFor } from './agent-conversation-audit';
17
20
  import { getAgentSystemInfoFor } from '../app/agent-system-info';
21
+ import { agentTaskCapabilitiesFor, inspectAgentTaskFor, assertAgentLegacyTaskAllowedFor, taskErrorStatus, publicAgentTaskError } from '../app/agent-task-control';
22
+ import { AgentTaskControlError } from '../core/runtime/agent-task-control';
18
23
  import type { KbService } from '../services/kb';
19
24
  import {
20
25
  completeAgentRunFor,
@@ -33,6 +38,7 @@ export interface AgentApiHttpDeps {
33
38
  /** 未注入时仅关闭新的无模型直调面,保持旧宿主的 Agent Auth / run 兼容。 */
34
39
  toolProxyDeps?: ToolProxyDeps;
35
40
  kbService?: KbService | null;
41
+ artifactRoot?: string;
36
42
  }
37
43
 
38
44
  // 64000 个 UTF-16 code units 在 JSON 中最坏可被转义为约 384 KB;512 KiB 还可容纳
@@ -55,6 +61,11 @@ function declaredFields(body: Record<string, unknown>, allowedFields: string[],
55
61
  }
56
62
 
57
63
  function sendAgentToolError(res: ServerResponse, error: unknown): void {
64
+ if (error instanceof AgentTaskControlError) {
65
+ const visible = publicAgentTaskError(error);
66
+ send(res, taskErrorStatus(visible), { error: visible.code, message: visible.message });
67
+ return;
68
+ }
58
69
  if (error instanceof AgentToolApiError) {
59
70
  send(res, error.statusCode, { error: error.code, message: error.message });
60
71
  return;
@@ -93,6 +104,19 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
93
104
  if (!auth) { send(res, 401, { error: 'unauthorized' }); return true; }
94
105
  const principal: Principal = { kind: 'agent', session: auth.session, client: auth.client };
95
106
  const method = req.method ?? 'GET';
107
+ if (method === 'GET' && path === '/agent-api/v1/task-control/capabilities') {
108
+ try { send(res, 200, await agentTaskCapabilitiesFor(deps.configStore, auth, Boolean(deps.toolProxyDeps))); }
109
+ catch { send(res, 503, { error: 'TASK_UNAVAILABLE', message: 'Task control could not be verified.' }); }
110
+ return true;
111
+ }
112
+ const taskMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/tasks\/([0-9a-f-]{36})$/i) : null;
113
+ if (taskMatch) {
114
+ try { send(res, 200, await inspectAgentTaskFor(deps.configStore, auth, taskMatch[1]!,
115
+ url.searchParams.get('workspace') ?? '', url.searchParams.get('client_conversation_id') ?? '')); }
116
+ catch (error) { sendAgentToolError(res, error); }
117
+ return true;
118
+ }
119
+ if (await handleAgentArtifacts({ configStore: deps.configStore, root: deps.artifactRoot, isPaused: deps.isPaused }, auth, req, res, path)) return true;
96
120
  if (await handleAgentConversationAuditFor(deps.configStore, auth, req, res, path)) return true;
97
121
  const systemInfoMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/system-info$/) : null;
98
122
  if (systemInfoMatch) {
@@ -125,7 +149,7 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
125
149
  if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
126
150
  const body = await readAgentToolBody(req, res, AGENT_RUNTIME_JSON_BODY_MAX_BYTES);
127
151
  if (!body) return true;
128
- 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'])
152
+ if (!declaredFields(body, ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input', 'page_context', 'renderers', 'task_binding'], ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input'])
129
153
  || typeof body['client_conversation_id'] !== 'string'
130
154
  || typeof body['client_turn_id'] !== 'string'
131
155
  || typeof body['user_message_id'] !== 'string'
@@ -140,6 +164,7 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
140
164
  user_message_id: body['user_message_id'], user_input: body['user_input'],
141
165
  ...(record(body['page_context']) ? { page_context: record(body['page_context'])! } : {}),
142
166
  ...(Array.isArray(body['renderers']) ? { renderers: body['renderers'] as string[] } : {}),
167
+ ...(Object.hasOwn(body, 'task_binding') ? { task_binding: body['task_binding'] } : {}),
143
168
  }));
144
169
  } catch (error) { sendAgentToolError(res, error); }
145
170
  return true;
@@ -199,6 +224,20 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
199
224
  catch (error) { sendAgentToolError(res, error); }
200
225
  return true;
201
226
  }
227
+ if (method === 'GET' && path === '/agent-api/v1/tool-invocations/inspection-capabilities') {
228
+ if (!deps.toolProxyDeps || !deps.configStore) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
229
+ if (url.search) { send(res, 400, { error: 'invalid_request', message: 'Invocation inspection does not accept query parameters.' }); return true; }
230
+ send(res, 200, agentInvocationInspectionCapabilities());
231
+ return true;
232
+ }
233
+ const receiptMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/tool-invocations\/([a-f0-9]{64})\/receipt$/) : null;
234
+ if (receiptMatch) {
235
+ if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
236
+ if (url.search) { send(res, 400, { error: 'invalid_request', message: 'Invocation inspection does not accept query parameters.' }); return true; }
237
+ try { send(res, 200, await inspectAgentToolInvocationFor(deps.toolProxyDeps, auth, { invocation_id: receiptMatch[1]! })); }
238
+ catch (error) { sendAgentToolError(res, error); }
239
+ return true;
240
+ }
202
241
  if (method === 'POST' && path === '/agent-api/v1/tool-invocations') {
203
242
  if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
204
243
  if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
@@ -243,6 +282,8 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
243
282
  return true;
244
283
  }
245
284
  if (method === 'POST' && path === '/agent-api/v1/run') {
285
+ try { await assertAgentLegacyTaskAllowedFor(deps.configStore, auth.session.session_id); }
286
+ catch (error) { sendAgentToolError(res, error); return true; }
246
287
  await deps.handleRun(req, res, principal);
247
288
  return true;
248
289
  }
@@ -0,0 +1,29 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { send } from '../app/http';
3
+ import { AgentToolApiError, type AgentToolAuthContext } from '../app/agent-tool-invocations';
4
+ import { ARTIFACT_MAX_BYTES } from '../core/config/artifact-config';
5
+ import { artifactError, artifactMetadata, readAgentArtifact, uploadAgentArtifact, type ArtifactDeps } from '../app/agent-artifacts';
6
+
7
+ export async function handleAgentArtifacts(deps: ArtifactDeps & { isPaused: () => boolean }, auth: AgentToolAuthContext, req: IncomingMessage, res: ServerResponse, path: string): Promise<boolean> {
8
+ const m = path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/artifacts\/([a-f0-9]{64})$/);
9
+ if (!m) return false;
10
+ try {
11
+ if (req.method === 'GET') send(res, 200, await readAgentArtifact(deps, auth, m[1]!, m[2]!));
12
+ else if (req.method === 'POST') {
13
+ if (deps.isPaused()) artifactError(503, 'hub_paused');
14
+ const raw = req.headers['x-bailing-artifact'];
15
+ if (typeof raw !== 'string' || raw.length > 4096 || !/^[a-zA-Z0-9_-]+$/.test(raw)) artifactError(400, 'artifact_invalid_request');
16
+ let value: unknown;
17
+ try { value = JSON.parse(Buffer.from(raw as string, 'base64url').toString('utf8')); } catch { artifactError(400, 'artifact_invalid_request'); }
18
+ const metadata = artifactMetadata(value);
19
+ if (req.headers['content-type'] !== metadata.mime || (req.headers['content-length'] !== undefined && Number(req.headers['content-length']) !== metadata.bytes)) artifactError(400, 'artifact_content_mismatch');
20
+ const chunks: Buffer[] = []; let size = 0;
21
+ for await (const chunk of req) { const data = Buffer.from(chunk); size += data.length; if (size > Math.min(metadata.bytes, ARTIFACT_MAX_BYTES)) artifactError(413, 'artifact_too_large'); chunks.push(data); }
22
+ send(res, 200, await uploadAgentArtifact(deps, auth, m[1]!, m[2]!, metadata, Buffer.concat(chunks)));
23
+ } else send(res, 405, { error: 'method_not_allowed' });
24
+ } catch (error) {
25
+ if (error instanceof AgentToolApiError) send(res, error.statusCode, { error: error.code });
26
+ else send(res, 503, { error: 'artifact_storage_unavailable' });
27
+ }
28
+ return true;
29
+ }
@@ -0,0 +1,246 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomBytes, randomUUID } from 'node:crypto';
3
+ import { createServer, type Server } from 'node:http';
4
+ import test from 'node:test';
5
+ import type { AppConfig } from '../core/config/config';
6
+ import type { Principal } from '../app/auth';
7
+ import { send } from '../app/http';
8
+ import { ConfigStore } from '../infrastructure/config/configstore';
9
+ import { MysqlStore } from '../infrastructure/state/state-mysql';
10
+ import type { ToolProxyDeps } from '../app/tool-proxy';
11
+ import { handleAgentApiHttpFor } from './agent-api';
12
+ import { handleAdminAgentTasksApiFor } from './admin-agent-tasks';
13
+ import { tokenHash } from './agent-auth';
14
+ import { openTaskMysqlFixture, seedTaskMysqlMembers, taskMysqlConfigPath } from '../test-support/agent-task-control-mysql-fixture';
15
+
16
+ const listen = (server: Server) => new Promise<string>((resolve) => server.listen(0, '127.0.0.1', () => {
17
+ const address = server.address(); assert.ok(address && typeof address === 'object'); resolve(`http://127.0.0.1:${address.port}`);
18
+ }));
19
+ const close = (server: Server) => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
20
+ const id = () => randomBytes(32).toString('hex');
21
+ const tools = ['product_update', 'inventory_read', 'product_review'];
22
+ function spec() {
23
+ const operation = (name: string, write: boolean, approval: boolean) => ({
24
+ operationId: name, summary: name,
25
+ 'x-agent-capability': { version: 1, enabled: true, scope: write ? 'products.write' : 'inventory.read', subject: { required: true },
26
+ ...(approval ? { risk: { level: 'high' } } : {}) },
27
+ ...(write ? { requestBody: { content: { 'application/json': { schema: { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'], additionalProperties: false } } } } }
28
+ : { parameters: [{ name: 'id', in: 'query', schema: { type: 'integer' } }] }),
29
+ });
30
+ return JSON.stringify({ openapi: '3.0.0', info: { title: 'Example shop and inventory', version: '1' }, paths: {
31
+ '/product': { post: operation('product_update', true, false) },
32
+ '/inventory': { get: operation('inventory_read', false, false) },
33
+ '/review': { post: operation('product_review', true, true) },
34
+ } });
35
+ }
36
+
37
+ test('task control gates real HTTP dispatch through the persisted Core runtime', { skip: !taskMysqlConfigPath }, async (t) => {
38
+ const pool = await openTaskMysqlFixture();
39
+ const owner = { get: async () => pool, close: async () => undefined };
40
+ const config = new ConfigStore({} as AppConfig['state']['mysql'], owner);
41
+ const state = new MysqlStore({} as AppConfig['state']['mysql'], owner);
42
+ await config.init(); await state.init();
43
+ const requests: Array<{ url: string; subject: string }> = [];
44
+ let dropResponse = false;
45
+ let holdBusinessResponse: Promise<void> | null = null;
46
+ let dropCoreAck = false;
47
+ const business = createServer(async (req, res) => {
48
+ requests.push({ url: req.url ?? '', subject: String(req.headers['x-agent-on-behalf-of'] ?? '') });
49
+ if (dropResponse) { req.socket.destroy(); return; }
50
+ if (holdBusinessResponse) await holdBusinessResponse;
51
+ send(res, 200, { ok: true, synthetic: true });
52
+ });
53
+ const businessUrl = await listen(business);
54
+ const cfg = { brand: { name: 'BailingHub' }, server: { token: 'synthetic-test-server-secret' } } as AppConfig;
55
+ const toolProxyDeps: ToolProxyDeps = { cfg, configStore: config, stateStore: state, toolIndex: null,
56
+ now: () => new Date().toISOString(), sleep: async () => undefined };
57
+ let legacyRuns = 0;
58
+ const core = createServer(async (req, res) => {
59
+ try {
60
+ const url = new URL(req.url!, 'http://127.0.0.1');
61
+ if (dropCoreAck && url.pathname === '/agent-api/v1/tool-invocations' && req.method === 'POST') {
62
+ dropCoreAck = false;
63
+ res.end = (() => { res.destroy(); return res; }) as typeof res.end;
64
+ }
65
+ if (url.pathname.startsWith('/admin/')) {
66
+ const principal: Principal = req.headers.authorization === 'Bearer synthetic-admin'
67
+ ? { kind: 'admin', via: 'token' } : { kind: 'admin', via: 'session', role: 'viewer' };
68
+ if (await handleAdminAgentTasksApiFor(config, req.method!, url.pathname, req, res, principal)) return;
69
+ }
70
+ if (await handleAgentApiHttpFor({ configStore: config, stateStore: state, isPaused: () => false, toolProxyDeps,
71
+ handleRun: async (_req, result) => { legacyRuns++; send(result, 200, {}); } }, req, res, url)) return;
72
+ send(res, 404, { error: 'not_found' });
73
+ } catch (error) { send(res, 500, { error: error instanceof Error ? error.message : 'test_server_error' }); }
74
+ });
75
+ const coreUrl = await listen(core);
76
+ const request = async (path: string, bearer: string, body?: unknown) => {
77
+ const response = await fetch(`${coreUrl}${path}`, { method: body === undefined ? 'GET' : 'POST',
78
+ headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json' }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
79
+ return { status: response.status, body: await response.json() as any };
80
+ };
81
+ const setup = async (maxWrites: number | null = 2, longClientId = false) => {
82
+ const members = await seedTaskMysqlMembers(pool);
83
+ const bearers: string[] = [];
84
+ for (const member of members) {
85
+ if (longClientId) {
86
+ const fullId = `business-${id()}`.slice(0, 64);
87
+ await pool.query('UPDATE bz_clients SET app_id=? WHERE app_id=?', [fullId, member.clientAppId]);
88
+ await pool.query('UPDATE bz_agent_sessions SET client_app_id=? WHERE session_id=?', [fullId, member.sessionId]);
89
+ await pool.query('UPDATE bz_agent_client_runs SET client_app_id=? WHERE run_id=?', [fullId, member.runId]);
90
+ member.clientAppId = fullId;
91
+ }
92
+ const bearer = `bha_${randomBytes(32).toString('base64url')}`; bearers.push(bearer);
93
+ await pool.query('UPDATE bz_agent_sessions SET access_token_hash=? WHERE session_id=?', [tokenHash(bearer), member.sessionId]);
94
+ await config.toolProviders.upsert({ name: member.clientAppId, base_url: businessUrl, secret: 'synthetic-provider-secret',
95
+ enabled: true, spec_source: 'inline', spec_json: spec(), log_payload: false, timeout_ms: 1000, rate_limit_per_min: 0, auto_refresh_min: 0 });
96
+ const route = (await config.routes.get(member.route))!;
97
+ await config.routes.upsert({ ...route, permission: 'full', audience: { enabled: true, roles: ['manager'], clients: [member.clientAppId] },
98
+ tools: { sources: [{ provider: member.clientAppId, allow: ['products.write', 'inventory.read'] }], max_calls: 12,
99
+ agent_direct: { enabled: true, write_tools: ['product_update', 'product_review'] } }, agent_client: { enabled: true } });
100
+ }
101
+ const body = { request_id: randomUUID(), members: members.map((m) => ({ session_id: m.sessionId, client_app_id: m.clientAppId,
102
+ workspace: m.route, client_conversation_id: m.clientConversationId, allowed_tools: tools })),
103
+ policy: { max_write_calls: maxWrites, max_concurrent: 2, expires_at: null } };
104
+ const created = await request('/admin/api/agent-tasks', 'synthetic-admin', body);
105
+ assert.equal(created.status, 200, JSON.stringify(created.body));
106
+ const task = created.body;
107
+ const binding = { schema_version: 'bailing.agent-task-binding.v1', task_id: task.task_id, scope_hash: task.scope_hash };
108
+ const turnBody = (index = 0) => ({ client_conversation_id: members[index]!.clientConversationId, client_turn_id: randomUUID(),
109
+ user_message_id: randomUUID(), user_input: 'synthetic product task', task_binding: binding });
110
+ const turn = async (index = 0) => {
111
+ const result = await request(`/agent-api/v1/workspaces/${members[index]!.route}/turns`, bearers[index]!, turnBody(index));
112
+ assert.equal(result.status, 200, JSON.stringify(result.body)); assert.deepEqual(result.body.task_binding, binding); return result.body;
113
+ };
114
+ const invoke = async (context: any, tool = 'product_update', index = 0, invocationId = id()) => {
115
+ const input = { invocation_id: invocationId, route: members[index]!.route, capability_revision: context.capability_revision,
116
+ agent_run_id: context.run_id, tool, arguments: { id: 1 } };
117
+ return { ...await request('/agent-api/v1/tool-invocations', bearers[index]!, input), input };
118
+ };
119
+ const detail = () => request(`/admin/api/agent-tasks/${task.task_id}`, 'synthetic-admin');
120
+ const control = async (action: string) => {
121
+ const current = (await detail()).body.task;
122
+ const result = await request(`/admin/api/agent-tasks/${task.task_id}/control`, 'synthetic-admin', {
123
+ request_id: randomUUID(), expected_revision: current.revision, action });
124
+ assert.equal(result.status, 200, JSON.stringify(result.body)); return result.body;
125
+ };
126
+ return { members, bearers, task, body, binding, turnBody, turn, invoke, detail, control };
127
+ };
128
+ try {
129
+ await t.test('admin scope creation is idempotent, snapshots disclose only the original member, and omission cannot bypass task admission', async () => {
130
+ const fx = await setup();
131
+ assert.equal((await request('/admin/api/agent-tasks', 'synthetic-admin', fx.body)).body.task_id, fx.task.task_id);
132
+ assert.equal((await request('/admin/api/agent-tasks', fx.bearers[0]!, fx.body)).status, 403);
133
+ const capabilities = await request('/agent-api/v1/task-control/capabilities', fx.bearers[0]!);
134
+ assert.equal(capabilities.body.supported, true); assert.equal(capabilities.body.mode, 'required');
135
+ const snapshot = await request(`/agent-api/v1/tasks/${fx.task.task_id}?workspace=${fx.members[0]!.route}&client_conversation_id=${fx.members[0]!.clientConversationId}`, fx.bearers[0]!);
136
+ assert.equal(snapshot.status, 200); assert.equal(snapshot.body.member_count, 2);
137
+ assert.equal(snapshot.body.member.session_id, fx.members[0]!.sessionId);
138
+ assert.equal(JSON.stringify(snapshot.body).includes(fx.members[1]!.sessionId), false);
139
+ assert.equal(JSON.stringify(snapshot.body).includes('identityHash'), false);
140
+ const { task_binding: _binding, ...withoutTask } = fx.turnBody();
141
+ const omitted = await request(`/agent-api/v1/workspaces/${fx.members[0]!.route}/turns`, fx.bearers[0]!, withoutTask);
142
+ assert.equal(omitted.body.error, 'TASK_REQUIRED');
143
+ const legacy = await request('/agent-api/v1/run', fx.bearers[0]!, {});
144
+ assert.equal(legacy.body.error, 'TASK_REQUIRED'); assert.equal(legacyRuns, 0);
145
+ const [rows]: any = await pool.query('SELECT COUNT(*) AS n FROM bz_agent_client_runs WHERE client_turn_id=?', [withoutTask.client_turn_id]);
146
+ assert.equal(Number(rows[0].n), 0);
147
+ });
148
+ await t.test('two systems and new turns share cumulative writes; readonly calls do not spend write budget; fences survive result persistence', async () => {
149
+ const fx = await setup(2); const before = requests.length;
150
+ const a = await fx.turn(0), b = await fx.turn(1);
151
+ for (const [context, index] of [[a, 0], [b, 1]] as const) {
152
+ const result = await fx.invoke(context, 'product_update', index);
153
+ assert.equal(result.body.state, 'executed', JSON.stringify(result.body));
154
+ const duplicate = await request('/agent-api/v1/tool-invocations', fx.bearers[index]!, result.input);
155
+ assert.equal(duplicate.body.state, 'executed');
156
+ }
157
+ const next = await fx.turn(0);
158
+ assert.equal((await fx.invoke(next)).body.error, 'TASK_WRITE_BUDGET_EXHAUSTED');
159
+ assert.equal((await fx.invoke(next, 'inventory_read')).body.state, 'executed');
160
+ assert.equal(requests.length - before, 3);
161
+ const detail = (await fx.detail()).body;
162
+ assert.equal(detail.task.counters.write_consumed, 2); assert.equal(detail.task.counters.write_reserved, 0);
163
+ assert.equal(detail.task.counters.active_permits, 0);
164
+ for (const invocation of detail.invocations) {
165
+ const job = (await state.getJob(invocation.job_id))!;
166
+ assert.equal(job.metadata.agent_task_id, fx.task.task_id); assert.equal(job.metadata.agent_dispatch_attempted, true);
167
+ assert.ok(job.metadata.agent_task_permit_id); assert.equal(job.metadata.agent_frozen_arguments, undefined);
168
+ }
169
+ });
170
+ await t.test('approval only reserves; paused resume cannot consume approval; inspection is read only; explicit original resume dispatches once', async () => {
171
+ const fx = await setup(1); const before = requests.length;
172
+ const context = await fx.turn(); const result = await fx.invoke(context, 'product_review');
173
+ assert.equal(result.body.state, 'awaiting_approval', JSON.stringify(result.body));
174
+ const approvalId = result.body.approval_id;
175
+ assert.equal((await fx.detail()).body.task.counters.write_reserved, 1);
176
+ await pool.query("UPDATE bz_tool_approvals SET status='approved' WHERE id=?", [approvalId]);
177
+ await fx.control('pause');
178
+ const path = `/agent-api/v1/tool-invocations/${result.input.invocation_id}`;
179
+ const receipt = await request(`${path}/receipt`, fx.bearers[0]!);
180
+ assert.equal(receipt.body.read_only, true, JSON.stringify(receipt)); assert.equal(receipt.body.approval.status, 'approved');
181
+ const paused = await request(`${path}/resume`, fx.bearers[0]!, {});
182
+ assert.equal(paused.body.error, 'TASK_PAUSED', JSON.stringify(paused.body));
183
+ const [rows]: any = await pool.query('SELECT used_at FROM bz_tool_approvals WHERE id=?', [approvalId]);
184
+ assert.equal(rows[0].used_at, null); assert.equal(requests.length, before);
185
+ await fx.control('resume');
186
+ const resumed = await request(`${path}/resume`, fx.bearers[0]!, {});
187
+ assert.equal(resumed.body.state, 'executed', JSON.stringify(resumed.body));
188
+ assert.equal((await request(`${path}/resume`, fx.bearers[0]!, {})).body.state, 'executed');
189
+ assert.equal(requests.length, before + 1);
190
+ assert.equal((await fx.detail()).body.task.counters.write_consumed, 1);
191
+ });
192
+ await t.test('lost business response holds the original reservation and permit; resume never duplicates the write', async () => {
193
+ const fx = await setup(1); const before = requests.length; const context = await fx.turn();
194
+ dropResponse = true;
195
+ const result = await fx.invoke(context); dropResponse = false;
196
+ assert.equal(result.body.state, 'reconciliation_required', JSON.stringify(result.body));
197
+ const retried = await request(`/agent-api/v1/tool-invocations/${result.input.invocation_id}/resume`, fx.bearers[0]!, {});
198
+ assert.equal(retried.body.state, 'reconciliation_required'); assert.equal(requests.length, before + 1);
199
+ const counters = (await fx.detail()).body.task.counters;
200
+ assert.equal(counters.write_reserved, 1); assert.equal(counters.write_consumed, 0); assert.equal(counters.active_permits, 1);
201
+ });
202
+ await t.test('revoking any original member blocks dispatch in the other system; cancel does not unenroll the Session', async () => {
203
+ const fx = await setup(); const before = requests.length; const context = await fx.turn();
204
+ await pool.query('UPDATE bz_agent_sessions SET revoked_at=NOW() WHERE session_id=?', [fx.members[1]!.sessionId]);
205
+ assert.equal((await fx.invoke(context)).body.error, 'TASK_SCOPE_BLOCKED');
206
+ assert.equal(requests.length, before); assert.equal((await fx.detail()).body.task.state, 'blocked');
207
+ await fx.control('cancel');
208
+ const { task_binding: _binding, ...withoutTask } = fx.turnBody();
209
+ assert.equal((await request(`/agent-api/v1/workspaces/${fx.members[0]!.route}/turns`, fx.bearers[0]!, withoutTask)).body.error, 'TASK_REQUIRED');
210
+ });
211
+ await t.test('a lost Core acknowledgement is recovered from the original journal without a second business request', async () => {
212
+ const fx = await setup(1); const context = await fx.turn(); const before = requests.length;
213
+ const invocationId = id(); dropCoreAck = true;
214
+ await assert.rejects(fx.invoke(context, 'product_update', 0, invocationId));
215
+ const receipt = await request(`/agent-api/v1/tool-invocations/${invocationId}/receipt`, fx.bearers[0]!);
216
+ assert.equal(receipt.body.result.state, 'executed', JSON.stringify(receipt));
217
+ assert.equal((await request(`/agent-api/v1/tool-invocations/${invocationId}/resume`, fx.bearers[0]!, {})).body.state, 'executed');
218
+ assert.equal(requests.length, before + 1); assert.equal((await fx.detail()).body.task.counters.write_consumed, 1);
219
+ });
220
+ await t.test('maximum-length client IDs dispatch and inspect without losing the full authorization identity', async () => {
221
+ const fx = await setup(1, true); const context = await fx.turn(); const before = requests.length;
222
+ const result = await fx.invoke(context);
223
+ assert.equal(result.body.state, 'executed', JSON.stringify(result.body)); assert.equal(requests.length, before + 1);
224
+ const invocation = (await fx.detail()).body.invocations[0]; const job = (await state.getJob(invocation.job_id))!;
225
+ assert.equal(job.source.length, 32); assert.equal(job.client_app_id, fx.members[0]!.clientAppId); assert.equal(job.client_app_id!.length, 64);
226
+ const receipt = await request(`/agent-api/v1/tool-invocations/${result.input.invocation_id}/receipt`, fx.bearers[0]!);
227
+ assert.equal(receipt.body.result.state, 'executed', JSON.stringify(receipt.body));
228
+ });
229
+ await t.test('read and write share concurrency; cancel retains prior permits and accepts their late receipts', async () => {
230
+ const fx = await setup(4); const context = await fx.turn(); const before = requests.length;
231
+ let release!: () => void; holdBusinessResponse = new Promise<void>((resolve) => { release = resolve; });
232
+ const pending = [fx.invoke(context), fx.invoke(context, 'inventory_read')];
233
+ try {
234
+ for (let i = 0; requests.length < before + 2 && i < 100; i++) await new Promise((resolve) => setTimeout(resolve, 5));
235
+ assert.equal(requests.length, before + 2);
236
+ assert.equal((await fx.invoke(context, 'inventory_read')).body.error, 'TASK_CONCURRENCY_EXHAUSTED');
237
+ assert.equal((await fx.detail()).body.task.counters.active_permits, 2);
238
+ await fx.control('cancel');
239
+ } finally { holdBusinessResponse = null; release(); }
240
+ const results = await Promise.all(pending); results.forEach((result) => assert.equal(result.body.state, 'executed', JSON.stringify(result.body)));
241
+ const detail = (await fx.detail()).body.task;
242
+ assert.equal(detail.state, 'cancelled'); assert.equal(detail.counters.active_permits, 0); assert.equal(detail.counters.write_consumed, 1);
243
+ assert.equal((await fx.invoke(context)).body.error, 'TASK_CANCELLED'); assert.equal(requests.length, before + 2);
244
+ });
245
+ } finally { await close(core); await close(business); await pool.end(); }
246
+ });
@@ -14,6 +14,8 @@ import type { TargetRegistry } from '../core/targets/registry';
14
14
  import type { KernelHostAdminSessionV1, KernelIdentityProviderV1 } from '../kernel-api/v1/contracts';
15
15
  import { handleAgentAuthHttpFor } from './agent-auth';
16
16
  import { handleAgentApiHttpFor } from './agent-api';
17
+ import { handleUsageApiFor } from '../modules/usage/http';
18
+ import { handleModelGatewayApiFor } from '../modules/usage/model-gateway';
17
19
 
18
20
  export interface PrivateHttpDeps extends AuthRuntimeDeps {
19
21
  cfg: AppConfig;
@@ -104,6 +106,12 @@ export async function handlePrivateHttpFor(deps: PrivateHttpDeps, req: IncomingM
104
106
  const path = url.pathname;
105
107
  const method = req.method ?? 'GET';
106
108
 
109
+ // Usage credentials are independent of admin, business Client Token and Agent authorization.
110
+ if (await handleUsageApiFor({ usage: deps.configStore?.usage ?? null }, req, res, url)) return;
111
+ if (await handleModelGatewayApiFor({ usage: deps.configStore?.usage ?? null, cfg: deps.cfg,
112
+ credentials: deps.configStore?.credentials, isPaused: deps.isPaused }, req, res, url)) return;
113
+
114
+
107
115
  // 企微入站(公开面,自带验签,不走 admin/接入方鉴权):GET 验 URL / POST 收消息。
108
116
  const mWecom = (method === 'GET' || method === 'POST') ? path.match(/^\/wecom\/([a-zA-Z0-9_-]{2,64})$/) : null;
109
117
  if (mWecom) { await deps.handleWecomInbound(req, res, mWecom[1]!, url); return; }
@@ -121,6 +129,7 @@ export async function handlePrivateHttpFor(deps: PrivateHttpDeps, req: IncomingM
121
129
  handleRun: deps.handleRun,
122
130
  toolProxyDeps: toolProxyDeps(deps),
123
131
  kbService: deps.kbService,
132
+ artifactRoot: deps.cfg.runtimeRoot ?? deps.cfg.root,
124
133
  }, req, res, url)) return;
125
134
 
126
135
  if (method === 'POST' && path === '/admin/login') {
package/src/routes/run.ts CHANGED
@@ -36,7 +36,8 @@ function agentAllowsRoute(principal: Extract<Principal, { kind: 'agent' }>, rout
36
36
  }
37
37
 
38
38
  function agentUserMetadata(value: Record<string, unknown>): Record<string, unknown> {
39
- return Object.fromEntries(Object.entries(value).filter(([key]) => !AGENT_RESERVED_METADATA_FIELDS.has(key)));
39
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !AGENT_RESERVED_METADATA_FIELDS.has(key)
40
+ && !key.startsWith('agent_task') && key !== 'task_binding' && key !== 'task_id'));
40
41
  }
41
42
 
42
43
  function agentSubjectScope(principal: Extract<Principal, { kind: 'agent' }>): string {
@@ -0,0 +1,75 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
3
+ import { readFileSync } from 'node:fs';
4
+ import { createPool, type Pool } from 'mysql2/promise';
5
+ import { migrateBailingHubCoreSchema } from '../infrastructure/schema/core-schema-migrator';
6
+
7
+ /** Opt-in, disposable loopback database only. Never reads application configuration. */
8
+ export const taskMysqlConfigPath = process.env.BAILING_TASK_TEST_MYSQL_CONFIG;
9
+
10
+ export async function openTaskMysqlFixture(): Promise<Pool> {
11
+ assert.ok(taskMysqlConfigPath, 'Explicit disposable test database configuration is required');
12
+ const input = JSON.parse(readFileSync(taskMysqlConfigPath, 'utf8'));
13
+ assert.equal(input.host, '127.0.0.1', 'Task tests must use a local disposable database');
14
+ assert.match(input.database, /^bailing_task_test(?:_[a-z0-9]+)?$/, 'Dedicated test database required');
15
+ const mysql = { host: input.host, port: Number(input.port), database: input.database,
16
+ user: input.user, password: input.password, connectionLimit: 8 };
17
+ await migrateBailingHubCoreSchema({ mysql });
18
+ const repeated = await migrateBailingHubCoreSchema({ mysql });
19
+ assert.deepEqual(repeated.appliedFiles, [], 'Repeated migration must not replay SQL');
20
+ assert.equal(repeated.executedStatements, 0);
21
+ return createPool({ ...mysql, timezone: 'Z', dateStrings: true });
22
+ }
23
+
24
+ /** Only synthetic shop/inventory identities and empty conversation bodies. */
25
+ export async function seedTaskMysqlMembers(pool: Pool) {
26
+ const suffix = randomBytes(5).toString('hex');
27
+ const conversationId = `conversation-${suffix}`;
28
+ const members = [];
29
+ for (const system of ['shop', 'inventory']) {
30
+ const sessionId = randomUUID();
31
+ const clientAppId = `${system}-${suffix}`;
32
+ const route = `${system}-${suffix}`;
33
+ const runId = randomUUID();
34
+ const principal = { id: 'example-operator', tenant: `${system}-example`, roles: ['manager'] };
35
+ const subject = `${system}-example:example-operator`;
36
+ await pool.query('INSERT INTO bz_clients (app_id,name,token,allowed_routes,rate_limit_per_min,enabled,agent_authorize_url,created_at,updated_at) VALUES (?,?,?,?,0,1,?,NOW(),NOW())',
37
+ [clientAppId, `Example ${system}`, randomBytes(16).toString('hex'), JSON.stringify([route]), 'https://business.example.com/authorize']);
38
+ await pool.query('INSERT INTO bz_routes (route_key,name,enabled,profile,tools,agent_client,created_at,updated_at) VALUES (?,?,1,?,?,?,?,NOW())',
39
+ [route, `Example ${system}`, 'general', JSON.stringify({ agent_direct: { enabled: true } }), JSON.stringify({ enabled: true }), '2026-01-01 00:00:00']);
40
+ await pool.query('INSERT INTO bz_agent_sessions (session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_token_hash,access_expires_at,refresh_expires_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,\'2099-01-01\',\'2099-02-01\',NOW(),NOW())',
41
+ [sessionId, clientAppId, `Example ${system}`, JSON.stringify(principal), subject, JSON.stringify([route]), randomBytes(32).toString('hex')]);
42
+ await pool.query('INSERT INTO bz_agent_client_runs (run_id,session_id,client_app_id,route_key,thread_id,client_conversation_id,client_turn_id,user_message_id,request_hash,user_input,status,created_at,updated_at) VALUES (?,?,?,?,1,?,?,?,?,\'\',\'context_ready\',NOW(),NOW())',
43
+ [runId, sessionId, clientAppId, route, conversationId, `turn-${suffix}`, `message-${system}-${suffix}`, 'a'.repeat(64)]);
44
+ members.push({ sessionId, clientAppId, route, clientConversationId: conversationId, runId, principal, subject });
45
+ }
46
+ return members;
47
+ }
48
+
49
+ export async function seedTaskMysqlInvocation(pool: Pool, member: Awaited<ReturnType<typeof seedTaskMysqlMembers>>[number],
50
+ options: { tool?: string; readonly?: boolean; approvalRequired?: boolean; runId?: string; extraMetadata?: Record<string, unknown> } = {}) {
51
+ const invocationId = randomBytes(32).toString('hex');
52
+ const jobId = randomUUID();
53
+ const tool = options.tool ?? 'product_update';
54
+ const runId = options.runId ?? member.runId;
55
+ const argsHash = 'b'.repeat(64);
56
+ const executionFingerprint = 'c'.repeat(64);
57
+ const metadata = {
58
+ agent_tool_job_marker: 'bailing.agent-tool-job.v1', principal: member.principal,
59
+ agent_tool_call_v1: true, agent_dispatch_attempted: false,
60
+ agent_invocation_id: invocationId, agent_run_id: runId,
61
+ agent_route: member.route, agent_tool: tool,
62
+ agent_args_hash: argsHash, agent_capability_revision: 'd'.repeat(64),
63
+ agent_execution_fingerprint: executionFingerprint,
64
+ agent_task_tool_contract: { schema_version: 'bailing.agent-task-tool-contract.v1',
65
+ readonly: options.readonly === true, approval_required: options.approvalRequired === true,
66
+ args_hash: argsHash, execution_fingerprint: executionFingerprint },
67
+ ...options.extraMetadata,
68
+ };
69
+ const requestId = `agent-tool:${createHash('sha256').update(`bailing.agent-tool.v1\0${member.sessionId}\0${invocationId}`).digest('hex')}`;
70
+ await pool.query('INSERT INTO bz_jobs (job_id,request_id,status,profile,target,source,session_id,client_app_id,agent_session_id,on_behalf_of,metadata,dispatch,created_at,updated_at) VALUES (?,?,\'running\',\'general\',\'agent-tool-v1\',?,?,?,?,?,?,?,NOW(),NOW())',
71
+ [jobId, requestId, `agent-tool:${member.clientAppId}`, runId, member.clientAppId, member.sessionId, member.subject,
72
+ JSON.stringify(metadata), JSON.stringify({ route_key: member.route })]);
73
+ return { sessionId: member.sessionId, runId, invocationId, jobId, tool, argsHash, executionFingerprint,
74
+ readonly: options.readonly === true, approvalRequired: options.approvalRequired === true };
75
+ }
@@ -0,0 +1 @@
1
+ .head[data-v-3f42f008]{display:flex;align-items:center;gap:10px}.muted[data-v-3f42f008]{color:var(--el-text-color-secondary);font-size:12px}.mono[data-v-3f42f008]{font-family:var(--bz-mono);font-size:12px}.account-main[data-v-3f42f008],.account-stack[data-v-3f42f008]{display:flex;flex-direction:column;align-items:flex-start;gap:4px;min-width:0;line-height:1.35}.account-main b[data-v-3f42f008],.account-main code[data-v-3f42f008]{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.account-main b[data-v-3f42f008]{color:var(--el-text-color-primary);font-size:13px}.account-main code[data-v-3f42f008]{color:var(--el-text-color-secondary);font-family:var(--bz-mono);font-size:12px}