bailinghub 0.9.4 → 0.10.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 (334) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/docker-compose.images.yml +2 -2
  5. package/docs/AGENT_CLIENT_QUICKSTART.en.md +1 -3
  6. package/docs/AGENT_CLIENT_QUICKSTART.md +1 -1
  7. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +87 -2
  8. package/docs/AGENT_CLIENT_RUNTIME_API.md +36 -2
  9. package/docs/AGENT_KNOWLEDGE_API.en.md +77 -0
  10. package/docs/AGENT_KNOWLEDGE_API.md +86 -0
  11. package/docs/AGENT_TASK_CONTROL.md +4 -4
  12. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +1 -1
  13. package/docs/ARCHITECTURE.md +4 -0
  14. package/docs/CHANGELOG.en.md +24 -1
  15. package/docs/CHANGELOG.md +24 -1
  16. package/docs/COMPATIBILITY.en.md +27 -1
  17. package/docs/CONTRACT.en.md +1 -1
  18. package/docs/CONTRACT.md +1 -1
  19. package/docs/IMPLEMENTATION_STATUS.en.md +28 -15
  20. package/docs/IMPLEMENTATION_STATUS.md +28 -15
  21. package/docs/INDEPENDENT_VALIDATION.en.md +6 -4
  22. package/docs/INDEPENDENT_VALIDATION.md +6 -4
  23. package/docs/INTEGRATION_WALKTHROUGH.md +65 -0
  24. package/docs/MODEL_BILLING.en.md +2 -0
  25. package/docs/MODEL_BILLING.md +6 -2
  26. package/docs/MODEL_CONTINUATION.en.md +54 -0
  27. package/docs/MODEL_CONTINUATION.md +54 -0
  28. package/docs/MODEL_OUTPUT_BUDGET.en.md +69 -0
  29. package/docs/MODEL_OUTPUT_BUDGET.md +69 -0
  30. package/docs/OPERATIONS.en.md +16 -4
  31. package/docs/OPERATIONS.md +16 -4
  32. package/docs/QUICKSTART.md +1 -1
  33. package/docs/README.en.md +7 -0
  34. package/docs/README.md +7 -0
  35. package/docs/RELEASE_NOTES_NEXT.en.md +3 -3
  36. package/docs/RELEASE_NOTES_NEXT.md +3 -3
  37. package/docs/RELEASE_NOTES_v0.10.0.en.md +58 -0
  38. package/docs/RELEASE_NOTES_v0.10.0.md +58 -0
  39. package/docs/RELEASE_NOTES_v0.10.1.en.md +41 -0
  40. package/docs/RELEASE_NOTES_v0.10.1.md +41 -0
  41. package/docs/UPGRADE_PLAN.en.md +118 -0
  42. package/docs/UPGRADE_PLAN.md +124 -0
  43. package/docs/UPGRADE_v0.10.0.en.md +47 -0
  44. package/docs/UPGRADE_v0.10.0.md +47 -0
  45. package/docs/UPGRADE_v0.10.1.en.md +66 -0
  46. package/docs/UPGRADE_v0.10.1.md +66 -0
  47. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +38 -22
  48. package/package.json +10 -5
  49. package/schemas/tool-definition.schema.json +13 -0
  50. package/scripts/check-doc-links.mjs +6 -0
  51. package/scripts/check-image-tags.sh +1 -1
  52. package/scripts/check-php-sdk-artifacts.mjs +152 -0
  53. package/scripts/check-php-sdk-artifacts.test.mjs +99 -0
  54. package/scripts/check-release-consistency.test.mjs +2 -2
  55. package/scripts/doctor-upgrade-plan.test.ts +205 -0
  56. package/scripts/doctor-upgrade-plan.ts +276 -0
  57. package/scripts/doctor.ts +4 -1
  58. package/scripts/e2e-console-approval-details.mjs +134 -0
  59. package/scripts/e2e-console-config-races.mjs +180 -0
  60. package/scripts/e2e-console-kb-audit.mjs +170 -0
  61. package/scripts/e2e-console-operations-audit.mjs +152 -0
  62. package/scripts/e2e-console-runtime-audit.mjs +179 -0
  63. package/scripts/e2e-console-settings-audit.mjs +125 -0
  64. package/scripts/e2e-console-troubleshooting-extra.mjs +267 -0
  65. package/scripts/e2e-console.mjs +476 -7
  66. package/scripts/install.sh +1 -1
  67. package/scripts/publish-images.sh +1 -1
  68. package/scripts/release-audit.mjs +9 -1
  69. package/scripts/sdk-declaration-contract-test.ts +34 -0
  70. package/scripts/sdk-p1-check.mjs +62 -26
  71. package/scripts/verify-github-repo.mjs +8 -0
  72. package/sdk/dotnet/Bailing.Connect/BailingConnect.cs +4 -4
  73. package/sdk/dotnet/README.md +8 -0
  74. package/sdk/dotnet/tests/Declaration/Declaration.csproj +11 -0
  75. package/sdk/dotnet/tests/Declaration/Program.cs +74 -0
  76. package/sdk/go/README.md +8 -0
  77. package/sdk/go/bailingconnect/connect.go +5 -5
  78. package/sdk/go/bailingconnect/declaration_test.go +107 -0
  79. package/sdk/java/README.md +13 -0
  80. package/sdk/java/src/main/java/com/bailing/connect/BailingConnect.java +4 -4
  81. package/sdk/java/tests/DeclarationTest.java +70 -0
  82. package/sdk/node/README.md +8 -0
  83. package/sdk/node/src/index.mjs +4 -4
  84. package/sdk/node/tests/declaration.test.mjs +41 -0
  85. package/sdk/php/README.md +16 -0
  86. package/sdk/php/src/Attributes/AiTool.php +4 -4
  87. package/sdk/php/src/SpecBuilder.php +8 -8
  88. package/sdk/php/tests/declaration-serialization.php +103 -0
  89. package/sdk/php7/README.md +14 -0
  90. package/sdk/php7/src/ToolDef.php +3 -3
  91. package/sdk/php7/src/ToolSpec.php +8 -13
  92. package/sdk/php7/tests/declaration-serialization.php +103 -0
  93. package/sdk/python/README.md +8 -0
  94. package/sdk/python/bailing_connect/__init__.py +6 -6
  95. package/sdk/python/tests/test_declaration.py +61 -0
  96. package/src/app/agent-client-runtime.test.ts +115 -2
  97. package/src/app/agent-client-runtime.ts +40 -11
  98. package/src/app/agent-knowledge.test.ts +171 -0
  99. package/src/app/agent-knowledge.ts +233 -0
  100. package/src/app/agent-tool-catalog-revision.test.ts +31 -0
  101. package/src/app/agent-tool-invocations.test.ts +7 -2
  102. package/src/app/agent-tool-invocations.ts +67 -7
  103. package/src/app/approval-continuations.test.ts +49 -1
  104. package/src/app/http.test.ts +16 -1
  105. package/src/app/http.ts +3 -3
  106. package/src/app/kernel-boot-recovery.mysql.test.ts +132 -0
  107. package/src/app/kernel-boot-recovery.test.ts +157 -0
  108. package/src/app/kernel.ts +12 -8
  109. package/src/app/readiness.mysql.test.ts +120 -0
  110. package/src/app/readiness.test.ts +111 -26
  111. package/src/app/readiness.ts +26 -22
  112. package/src/app/runtime-lifecycle.ts +34 -3
  113. package/src/app/tool-approvals.test.ts +83 -0
  114. package/src/app/tool-approvals.ts +25 -7
  115. package/src/app/tool-proxy-payload.test.ts +81 -0
  116. package/src/app/tool-proxy.ts +24 -2
  117. package/src/core/config/console-diagnostic-location.test.ts +36 -0
  118. package/src/core/config/console-form-guard.test.ts +69 -0
  119. package/src/core/config/console-task-location.test.ts +64 -0
  120. package/src/core/contracts/explicit-capability-values.test.ts +62 -0
  121. package/src/core/contracts/openapi-tools.ts +18 -7
  122. package/src/core/contracts/schema-readiness.ts +11 -0
  123. package/src/core/contracts/tool-annotations.ts +4 -4
  124. package/src/core/contracts/tool-definition.ts +26 -0
  125. package/src/core/contracts/tool-guidance.test.ts +77 -0
  126. package/src/core/contracts/tool-guidance.ts +31 -0
  127. package/src/core/contracts/tool-input-limits.ts +15 -0
  128. package/src/core/contracts/tools-idempotency.test.ts +90 -0
  129. package/src/core/contracts/tools.ts +52 -9
  130. package/src/core/runtime/agent-execution-memory.test.ts +64 -0
  131. package/src/core/runtime/agent-execution-memory.ts +63 -0
  132. package/src/core/state/state-contracts.ts +3 -0
  133. package/src/infrastructure/config/config-observability-ledger.ts +2 -0
  134. package/src/infrastructure/schema/schema-readiness.ts +29 -0
  135. package/src/infrastructure/state/state-mysql.ts +3 -0
  136. package/src/modules/usage/contracts.ts +7 -0
  137. package/src/modules/usage/http.ts +2 -0
  138. package/src/modules/usage/model-continuation.test.ts +109 -0
  139. package/src/modules/usage/model-gateway.ts +5 -1
  140. package/src/modules/usage/output-budget.mysql.test.ts +84 -0
  141. package/src/modules/usage/output-budget.test.ts +167 -0
  142. package/src/modules/usage/output-budget.ts +73 -0
  143. package/src/modules/usage/provider-stream.test.ts +22 -0
  144. package/src/modules/usage/provider.ts +2 -3
  145. package/src/modules/usage/repository.ts +6 -0
  146. package/src/modules/usage/test-harness.ts +4 -2
  147. package/src/routes/admin-approval-view.test.ts +109 -0
  148. package/src/routes/admin-approval-view.ts +36 -0
  149. package/src/routes/admin-readiness.test.ts +52 -0
  150. package/src/routes/admin-runtime-ux.test.ts +51 -0
  151. package/src/routes/admin-runtime-ux.ts +25 -0
  152. package/src/routes/admin-runtime.ts +36 -8
  153. package/src/routes/admin.ts +9 -0
  154. package/src/routes/agent-api.test.ts +80 -1
  155. package/src/routes/agent-api.ts +63 -4
  156. package/src/routes/agent-tool-detail.test.ts +140 -0
  157. package/src/routes/public-default.ts +1 -1
  158. package/src/services/kb-agent.test.ts +84 -0
  159. package/src/services/kb.ts +73 -0
  160. package/web/connect/bailing-connect-php.tgz +0 -0
  161. package/web/connect/bailing-connect-php7.tgz +0 -0
  162. package/web/console/assets/Accounts-CjIBO3sU.css +1 -0
  163. package/web/console/assets/Accounts-Dhyw-7wF.js +3 -0
  164. package/web/console/assets/AgentClients-BA0M26-I.css +1 -0
  165. package/web/console/assets/AgentClients-DWxb8-ko.js +1 -0
  166. package/web/console/assets/AgentTasks-DOyxANnx.css +1 -0
  167. package/web/console/assets/AgentTasks-DUHD4dzr.js +2 -0
  168. package/web/console/assets/Approvals-Brl-2uJq.css +1 -0
  169. package/web/console/assets/Approvals-CQx1YWxW.js +1 -0
  170. package/web/console/assets/Audit--QcdVlMh.js +1 -0
  171. package/web/console/assets/Audit-DAdmOnIs.css +1 -0
  172. package/web/console/assets/{BrandLockup-CffORQse.js → BrandLockup-DQcaW4Nt.js} +1 -1
  173. package/web/console/assets/Channels-DJJU3ksE.css +1 -0
  174. package/web/console/assets/Channels-cGS5WfQ-.js +105 -0
  175. package/web/console/assets/ChatEntries-BYpji27B.css +1 -0
  176. package/web/console/assets/ChatEntries-nh23Iz5O.js +7 -0
  177. package/web/console/assets/Clients-CX5EeYio.js +3 -0
  178. package/web/console/assets/Clients-CbZAou8E.css +1 -0
  179. package/web/console/assets/Cost-C6oQvz9P.css +1 -0
  180. package/web/console/assets/Cost-DOZfdNS9.js +1 -0
  181. package/web/console/assets/Credentials--aHs57yV.css +1 -0
  182. package/web/console/assets/Credentials-sy6W9Sac.js +1 -0
  183. package/web/console/assets/Diagnostics-CKs27Dnv.css +1 -0
  184. package/web/console/assets/Diagnostics-CyoM1XrZ.js +1 -0
  185. package/web/console/assets/Executors-2Upi6bOS.css +1 -0
  186. package/web/console/assets/Executors-BQqqiFwt.js +1 -0
  187. package/web/console/assets/HelpTip-DLlhaGQp.js +1 -0
  188. package/web/console/assets/HelpTip-bbDEyuqV.css +1 -0
  189. package/web/console/assets/Kb-5R3ce4UU.js +5 -0
  190. package/web/console/assets/Kb-BM_PYi11.css +1 -0
  191. package/web/console/assets/{Login-CGgLGTE1.js → Login-YKeUwdgo.js} +1 -1
  192. package/web/console/assets/Projects-DHwHrPT9.css +1 -0
  193. package/web/console/assets/Projects-Grgb6fOv.js +1 -0
  194. package/web/console/assets/Routes-DR_Yf02e.css +1 -0
  195. package/web/console/assets/Routes-DYgrXlRJ.js +138 -0
  196. package/web/console/assets/Runs-CwTddJJj.js +3 -0
  197. package/web/console/assets/Runs-D4FOvNfu.css +1 -0
  198. package/web/console/assets/Setup-Ca0b1d1-.css +1 -0
  199. package/web/console/assets/Setup-D_xUPNDq.js +1 -0
  200. package/web/console/assets/Shell-BTg8Vw_L.css +1 -0
  201. package/web/console/assets/Shell-Dfam2Uoj.js +1 -0
  202. package/web/console/assets/StorageBuckets-7QLBpV4a.css +1 -0
  203. package/web/console/assets/StorageBuckets-CP6e50wI.js +1 -0
  204. package/web/console/assets/SystemSettings-BRYKyJNa.js +1 -0
  205. package/web/console/assets/SystemSettings-HsXGx0aH.css +1 -0
  206. package/web/console/assets/SystemStatus-B-VfRsQd.css +1 -0
  207. package/web/console/assets/SystemStatus-CbPsDsGt.js +1 -0
  208. package/web/console/assets/Targets-1j4-g6rC.css +1 -0
  209. package/web/console/assets/Targets-C2LkR2AF.js +1 -0
  210. package/web/console/assets/Tools-C9HPJqJb.css +1 -0
  211. package/web/console/assets/Tools-C9JNJUS0.js +2 -0
  212. package/web/console/assets/Usage-D1Mv6vGY.js +1 -0
  213. package/web/console/assets/Usage-DMOzUsqh.css +1 -0
  214. package/web/console/assets/UsageAccess-77LmGCm6.js +1 -0
  215. package/web/console/assets/UsageAccess-C6ZGxEgJ.css +1 -0
  216. package/web/console/assets/{UsageHelp-CzS2gI40.js → UsageHelp-BmuiE1Ew.js} +1 -1
  217. package/web/console/assets/client-route-draft-DxZRxKPT.js +1 -0
  218. package/web/console/assets/console-location-Csv-xsnl.js +1 -0
  219. package/web/console/assets/form-guard-8GrFpry0.js +1 -0
  220. package/web/console/assets/{index-65JiiUr4.js → index-B_5UfiTw.js} +1 -1
  221. package/web/console/assets/index-MjZJEFIN.js +2 -0
  222. package/web/console/assets/{request-DKycpD7z.js → request-rqm6MT0s.js} +1 -1
  223. package/web/console/assets/runtime-feedback-gPfZVNvY.js +1 -0
  224. package/web/console/assets/{schema-SCiNxBlR.js → schema-o3mK4mid.js} +1 -1
  225. package/web/console/assets/task-page-location-DWiGtAln.js +1 -0
  226. package/web/console/assets/use-list-location-FvLFt0Tq.css +1 -0
  227. package/web/console/assets/use-list-location-cIPy2cKM.js +1 -0
  228. package/web/console/assets/use-unsaved-form-DScKD0h9.js +1 -0
  229. package/web/console/assets/{util-DZYfJ5Zo.js → util-B40VqOwl.js} +1 -1
  230. package/web/console/assets/{vendor-element-8cVcdt5T.js → vendor-element-BT8tHCFk.js} +1 -1
  231. package/web/console/assets/{vendor-mammoth-CnDA23N0.js → vendor-mammoth-CVIXVxTN.js} +1 -1
  232. package/web/console/assets/{vendor-vue-Co7x2FW6.js → vendor-vue-DhbG0vd4.js} +7 -7
  233. package/web/console/index.html +3 -3
  234. package/web-admin/package-lock.json +4 -4
  235. package/web-admin/package.json +1 -1
  236. package/web-admin/src/client-route-draft.ts +25 -0
  237. package/web-admin/src/components/AgentSetupPanel.vue +54 -41
  238. package/web-admin/src/components/HelpTip.vue +4 -1
  239. package/web-admin/src/components/ListLocationBar.vue +22 -0
  240. package/web-admin/src/components/NotificationOutboxPanel.vue +35 -7
  241. package/web-admin/src/console-entry.test.ts +26 -0
  242. package/web-admin/src/console-entry.ts +20 -0
  243. package/web-admin/src/console-location.ts +35 -0
  244. package/web-admin/src/form-guard.ts +35 -0
  245. package/web-admin/src/layout/Shell.vue +18 -65
  246. package/web-admin/src/onboarding-state.test.ts +174 -0
  247. package/web-admin/src/onboarding-state.ts +122 -0
  248. package/web-admin/src/pages/Accounts.vue +44 -24
  249. package/web-admin/src/pages/AgentClients.vue +47 -29
  250. package/web-admin/src/pages/AgentTasks.vue +57 -12
  251. package/web-admin/src/pages/Approvals.vue +105 -25
  252. package/web-admin/src/pages/Audit.vue +15 -6
  253. package/web-admin/src/pages/Channels.vue +136 -43
  254. package/web-admin/src/pages/ChatEntries.vue +96 -41
  255. package/web-admin/src/pages/Clients.vue +87 -26
  256. package/web-admin/src/pages/Cost.vue +15 -4
  257. package/web-admin/src/pages/Credentials.vue +63 -32
  258. package/web-admin/src/pages/Diagnostics.vue +103 -54
  259. package/web-admin/src/pages/Executors.vue +103 -40
  260. package/web-admin/src/pages/Kb.vue +278 -128
  261. package/web-admin/src/pages/Projects.vue +44 -16
  262. package/web-admin/src/pages/Routes.vue +168 -247
  263. package/web-admin/src/pages/Runs.vue +163 -91
  264. package/web-admin/src/pages/Setup.vue +182 -291
  265. package/web-admin/src/pages/StorageBuckets.vue +61 -25
  266. package/web-admin/src/pages/SystemSettings.vue +76 -51
  267. package/web-admin/src/pages/SystemStatus.vue +54 -30
  268. package/web-admin/src/pages/Targets.vue +45 -17
  269. package/web-admin/src/pages/Tools.vue +133 -68
  270. package/web-admin/src/pages/Usage.vue +64 -25
  271. package/web-admin/src/pages/UsageAccess.vue +11 -8
  272. package/web-admin/src/route-call-snippets.test.ts +82 -0
  273. package/web-admin/src/route-call-snippets.ts +178 -0
  274. package/web-admin/src/router.ts +11 -29
  275. package/web-admin/src/runtime-feedback.ts +43 -0
  276. package/web-admin/src/task-page-location.ts +66 -0
  277. package/web-admin/src/usage-output-budget.test.ts +26 -0
  278. package/web-admin/src/usage-output-budget.ts +46 -0
  279. package/web-admin/src/use-list-location.ts +24 -0
  280. package/web-admin/src/use-unsaved-form.ts +38 -0
  281. package/web-admin/tests/model-output-budget.browser.mjs +69 -0
  282. package/web/console/assets/Accounts-Bervi5JU.css +0 -1
  283. package/web/console/assets/Accounts-Dhj6PjXP.js +0 -3
  284. package/web/console/assets/AgentClients-CMy8StAH.js +0 -1
  285. package/web/console/assets/AgentClients-i52AI6YV.css +0 -1
  286. package/web/console/assets/AgentTasks-BsG850Il.css +0 -1
  287. package/web/console/assets/AgentTasks-DA1xZdmP.js +0 -2
  288. package/web/console/assets/Approvals-DIsd7R8N.js +0 -1
  289. package/web/console/assets/Approvals-DlTSHl_7.css +0 -1
  290. package/web/console/assets/Audit-AUDABLTX.js +0 -1
  291. package/web/console/assets/Audit-CSu6_3oD.css +0 -1
  292. package/web/console/assets/Channels-B8rjsM0S.js +0 -105
  293. package/web/console/assets/Channels-CCn0L1jg.css +0 -1
  294. package/web/console/assets/ChatEntries-DsYtcXN6.css +0 -1
  295. package/web/console/assets/ChatEntries-iZjJMEUZ.js +0 -7
  296. package/web/console/assets/Clients-CSHIsaWU.css +0 -1
  297. package/web/console/assets/Clients-CwgpGCSD.js +0 -3
  298. package/web/console/assets/Cost-B2tNxu71.js +0 -1
  299. package/web/console/assets/Cost-CjT39DSZ.css +0 -1
  300. package/web/console/assets/Credentials-BuwFB-fV.js +0 -1
  301. package/web/console/assets/Credentials-ioLP0qYN.css +0 -1
  302. package/web/console/assets/Diagnostics-Ya05PTDp.css +0 -1
  303. package/web/console/assets/Diagnostics-z5glms11.js +0 -1
  304. package/web/console/assets/Executors-Bc4SvjeH.js +0 -1
  305. package/web/console/assets/Executors-CjhEM54c.css +0 -1
  306. package/web/console/assets/HelpTip-CA6Bm7Nx.css +0 -1
  307. package/web/console/assets/HelpTip-Dtdt2tKR.js +0 -1
  308. package/web/console/assets/Kb-BRbRHxLy.js +0 -5
  309. package/web/console/assets/Kb-CzIzd9xr.css +0 -1
  310. package/web/console/assets/Projects-Bm8AjsNx.css +0 -1
  311. package/web/console/assets/Projects-CPWw3con.js +0 -1
  312. package/web/console/assets/Routes-CMIaE0Bx.js +0 -124
  313. package/web/console/assets/Routes-CyXV4Pba.css +0 -1
  314. package/web/console/assets/Runs-B8HuE700.js +0 -3
  315. package/web/console/assets/Runs-Bv6CV_Hk.css +0 -1
  316. package/web/console/assets/Setup-D7nxgn-9.css +0 -1
  317. package/web/console/assets/Setup-G8RKzliR.js +0 -1
  318. package/web/console/assets/Shell-DimHgraJ.js +0 -1
  319. package/web/console/assets/Shell-ykb-tUfo.css +0 -1
  320. package/web/console/assets/StorageBuckets-CVgpZRWY.css +0 -1
  321. package/web/console/assets/StorageBuckets-CiVYXIE2.js +0 -1
  322. package/web/console/assets/SystemSettings-BjiHyrXO.css +0 -1
  323. package/web/console/assets/SystemSettings-DF8sZNen.js +0 -1
  324. package/web/console/assets/SystemStatus-BlHywK13.js +0 -1
  325. package/web/console/assets/SystemStatus-I11I67rw.css +0 -1
  326. package/web/console/assets/Targets-BXaoPoAJ.js +0 -1
  327. package/web/console/assets/Targets-DTb5tn6z.css +0 -1
  328. package/web/console/assets/Tools-B22lNHXq.js +0 -2
  329. package/web/console/assets/Tools-DU8ei6sd.css +0 -1
  330. package/web/console/assets/Usage-C02EzoI2.js +0 -1
  331. package/web/console/assets/Usage-CAeDGjrb.css +0 -1
  332. package/web/console/assets/UsageAccess-CGGaWTuj.css +0 -1
  333. package/web/console/assets/UsageAccess-DOb-cyPE.js +0 -1
  334. package/web/console/assets/index-CK0ZCTZv.js +0 -2
@@ -42,6 +42,28 @@ test('provider semantics are preserved for local parsing, never rejected by the
42
42
  }
43
43
  });
44
44
 
45
+ test('output-limit JSON and SSE preserve partial answers, reasoning and unfinished tool arguments without retry', async () => {
46
+ const message = { role: 'assistant', content: '已完成第一步,下一步继续。', reasoning_content: 'Synthetic reasoning only',
47
+ tool_calls: [{ id: 'unfinished-original', type: 'function', function: { name: 'save_draft', arguments: '{"title":"未完成' } }] };
48
+ const usage = { prompt_tokens: 10, completion_tokens: 8, total_tokens: 18, completion_tokens_details: { reasoning_tokens: 5 } };
49
+ const jsonBody = JSON.stringify({ id: 'original-json', choices: [{ index: 0, message, finish_reason: 'length' }], usage });
50
+ const sseBody = event({ id: 'original-sse', choices: [{ index: 0, delta: message, finish_reason: null }] })
51
+ + event({ id: 'original-sse', choices: [{ index: 0, delta: {}, finish_reason: 'length' }], usage }) + 'data: [DONE]\r\n\r\n';
52
+ for (const [format, body] of [['json', jsonBody], ['sse', sseBody]] as const) {
53
+ const packets: Record<string, unknown>[] = [];
54
+ const result = await readProviderExchange(new Response(body, { headers: { 'content-type': format === 'sse' ? 'text/event-stream' : 'application/json' } }),
55
+ async packet => { packets.push(packet); });
56
+ assert.equal(result.response.body, body);
57
+ assert.equal(packets.map(packet => packet.data).join(''), body);
58
+ assert.equal(result.response.format, format);
59
+ assert.deepEqual(result.usage, { inputTokens: 10, outputTokens: 8 });
60
+ assert.equal((result.rawUsage?.completion_tokens_details as Record<string, unknown>).reasoning_tokens, 5);
61
+ assert(body.includes('length') && body.includes('unfinished-original'));
62
+ // Transport does not repair JSON arguments or manufacture a tool execution.
63
+ assert.equal(JSON.parse(jsonBody).choices[0].message.tool_calls[0].function.arguments, '{"title":"未完成');
64
+ }
65
+ });
66
+
45
67
  test('JSON and HTTP error responses keep native body/status; metering is independent', async () => {
46
68
  for (const status of [200, 400, 401, 404, 429, 503]) {
47
69
  const body = JSON.stringify({ unknown: 'extension', choices: [], error: { type: 'synthetic_error' }, usage: { total_tokens: 123 } });
@@ -2,6 +2,7 @@ import type { ResolvedLlmCredential } from '../../core/runtime/credential-resolv
2
2
  import type { UsageServiceConfig } from './contracts';
3
3
  import { UsageError, usageAssert } from './errors';
4
4
  import { readProviderExchange } from './provider-stream';
5
+ import { resolveOutputBudget } from './output-budget';
5
6
 
6
7
  export type JsonObject = Record<string, unknown>;
7
8
  export interface UsageModelRequest {
@@ -106,9 +107,7 @@ export function providerBody(request: UsageModelRequest, config: UsageServiceCon
106
107
  'USAGE_UNSUPPORTED_INPUT', 'This model service is configured for text input only.', 400);
107
108
  const options = request.provider_options ?? {};
108
109
  validateProviderOptions(options);
109
- const outputKey = options.max_completion_tokens === undefined ? 'max_tokens' : 'max_completion_tokens';
110
- const requested = Number(options[outputKey] ?? config.maxOutputTokens);
111
- usageAssert(requested <= config.maxOutputTokens, 'USAGE_OUTPUT_LIMIT', 'The requested output limit exceeds the model service limit.', 413);
110
+ const { parameter: outputKey, tokens: requested } = resolveOutputBudget(config, options);
112
111
  const result: JsonObject = { ...options, model: config.model, messages: request.messages, stream: streaming, [outputKey]: requested,
113
112
  ...(streaming ? { stream_options: { include_usage: true } } : {}) };
114
113
  for (const name of ['tools', 'tool_choice', 'temperature'] as const) if (request[name] !== undefined) result[name] = request[name];
@@ -1,5 +1,6 @@
1
1
  import { validatePricingBinding } from './pricing';
2
2
  import { validateModelToolConfig } from './model-tools';
3
+ import { outputBudgetPolicy } from './output-budget';
3
4
  import { createHash, randomUUID } from "node:crypto";
4
5
  import type { Pool, PoolConnection, RowDataPacket } from "mysql2/promise";
5
6
  import type { CreateUsageAccountInput, UsageAccount, UsageActor, UsageActorValidator, UsageService, UsageServiceConfig } from "./contracts";
@@ -474,6 +475,10 @@ export class UsageRepository {
474
475
  "providerScope",
475
476
  "maxInputBytes",
476
477
  "maxOutputTokens",
478
+ "defaultOutputTokens",
479
+ "outputTokenParameter",
480
+ "outputBudgetScope",
481
+ "modelMaxOutputTokens",
477
482
  "timeoutMs",
478
483
  "contextWindowTokens",
479
484
  "inputModalities",
@@ -505,6 +510,7 @@ export class UsageRepository {
505
510
  key(i.config.providerScope);
506
511
  integer(i.config.maxInputBytes, "maxInputBytes", 1, 16 * 1024 * 1024);
507
512
  integer(i.config.maxOutputTokens, "maxOutputTokens", 1, 131072);
513
+ outputBudgetPolicy(i.config);
508
514
  integer(i.config.timeoutMs, "timeoutMs", 1000, 600000);
509
515
  return this.withTransaction(async (c) => {
510
516
  const r = (
@@ -25,10 +25,12 @@ export async function createUsageTestHarness() {
25
25
  const identity = getUsageIdentity(repository);
26
26
  const fixturePrice = {source:'openrouter' as const,modelId:'synthetic/model',endpointId:'synthetic',currency:'USD' as const,fetchedAt:Date.now(),lines:[{billable:'prompt',unit:'token' as const,costUsd:'1'},{billable:'completion',unit:'token' as const,costUsd:'1'}]};
27
27
  await pool.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)',[createHash('sha256').update('chat:synthetic/model').digest('hex'),JSON.stringify({fetchedAt:Date.now(),items:[{id:'synthetic',pricing:fixturePrice}]}),Date.now()]);
28
- const state = { calls: 0, counts: 0, mode: 'ok' as 'ok' | 'missing_usage' | 'error' | 'incomplete' | 'delay' | 'stream' | 'stream_drop' | 'stream_tools_nullable', release: null as (() => void) | null };
28
+ const state = { calls: 0, counts: 0, bodies: [] as Record<string, unknown>[], mode: 'ok' as 'ok' | 'missing_usage' | 'error' | 'incomplete' | 'delay' | 'stream' | 'stream_drop' | 'stream_tools_nullable', release: null as (() => void) | null };
29
29
  const provider = createServer(async (req, res) => {
30
- for await (const _chunk of req) { /* consume synthetic input */ }
30
+ const chunks: Buffer[] = [];
31
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
31
32
  if (req.url === '/v1/count-input') { state.counts++; send(res, 200, { input_tokens: 20 }); return; }
33
+ state.bodies.push(JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>);
32
34
  state.calls++;
33
35
  if (state.mode === 'error') { send(res, 503, { error: 'synthetic_failure' }); return; }
34
36
  if (state.mode === 'incomplete') {
@@ -0,0 +1,109 @@
1
+ import assert from 'node:assert/strict';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import test from 'node:test';
4
+ import type { ToolApproval } from '../core/contracts/types';
5
+ import { approvalDetailView, approvalListView } from './admin-approval-view';
6
+ import { handleAdminRuntimeApiFor, type AdminRuntimeApiDeps } from './admin-runtime';
7
+
8
+ function approval(args = { source: { html: '<p>合成页面</p>', css: '' } }): ToolApproval {
9
+ const argsJson = JSON.stringify(args);
10
+ const intent = { args, args_hash: 'a'.repeat(64), method: 'POST', path: '/validate', readonly: false };
11
+ return {
12
+ id: 31, job_id: 'synthetic-job', request_id: 'synthetic-request', provider: 'synthetic-business',
13
+ tool: 'shop_ai_decoration_save', scope: 'shop.decoration.save', risk: 'high', status: 'pending',
14
+ args_json: argsJson, args_hash: 'a'.repeat(64), intent, intent_json: JSON.stringify(intent),
15
+ created_at: '2026-10-21T01:00:00.000Z',
16
+ };
17
+ }
18
+
19
+ test('small approval snapshots remain compatible and are labelled complete', () => {
20
+ const row = approval();
21
+ const view = approvalListView(row);
22
+ assert.deepEqual(view, { ...row, args_bytes: Buffer.byteLength(row.args_json!), args_truncated: false, details_available: false });
23
+ });
24
+
25
+ test('50 large approvals have bounded previews and no nested or raw duplicate full arguments', () => {
26
+ const row = approval({ source: { html: '合成😀"\\'.repeat(75_000), css: '' } });
27
+ const rows = Array.from({ length: 50 }, (_, index) => approvalListView({ ...row, id: index + 1 }));
28
+ for (const view of rows) {
29
+ assert.equal(view.args_json, undefined);
30
+ assert.equal(view.intent, undefined);
31
+ assert.equal(view.intent_json, undefined);
32
+ assert.equal(view.args_bytes, Buffer.byteLength(row.args_json!, 'utf8'));
33
+ assert.equal(view.args_hash, row.args_hash);
34
+ assert.equal(view.args_truncated, true);
35
+ assert.equal(view.details_available, true);
36
+ assert.ok(Buffer.byteLength(String(view.args_preview), 'utf8') <= 4096);
37
+ assert.equal(String(view.args_preview).includes('\ufffd'), false);
38
+ }
39
+ assert.ok(Buffer.byteLength(JSON.stringify(rows), 'utf8') < 600_000, 'list must stay bounded independently of full payload size');
40
+ assert.equal(row.intent?.args !== undefined, true, 'presentation does not mutate the execution snapshot');
41
+ });
42
+
43
+ test('large legacy intent_json is also deferred when the separate args_json is small', () => {
44
+ const row = approval();
45
+ row.intent_json = JSON.stringify({ args: { legacy: 'x'.repeat(100_000) } });
46
+ const view = approvalListView(row);
47
+ assert.equal(view.details_available, true);
48
+ assert.equal(view.intent_json, undefined);
49
+ assert.equal(view.intent, undefined);
50
+ assert.equal(view.args_json, undefined);
51
+ assert.equal(view.args_truncated, false);
52
+ assert.equal(view.args_preview, row.args_json);
53
+ });
54
+
55
+ test('single approval details preserve exact stored JSON and intent, never the list preview', () => {
56
+ const row = approval({ source: { html: 'x'.repeat(256 * 1024), css: 'body{}' } });
57
+ const detail = approvalDetailView(row);
58
+ assert.equal(detail.args_json, row.args_json);
59
+ assert.deepEqual(detail.intent, row.intent);
60
+ assert.equal(detail.args_bytes, Buffer.byteLength(row.args_json!, 'utf8'));
61
+ assert.equal(detail.args_truncated, false);
62
+ assert.equal(detail.details_available, false);
63
+ });
64
+
65
+ async function request(path: string, permissions: string[], row: ToolApproval | null = approval()) {
66
+ let reads = 0, code = 0, response = '';
67
+ const deps = {
68
+ configStore: { approvals: {
69
+ get: async (id: number) => { reads++; assert.equal(id, 31); return row; },
70
+ list: async () => { reads++; return row ? [row] : []; },
71
+ } },
72
+ stateStore: { getJob: async () => null },
73
+ } as unknown as AdminRuntimeApiDeps;
74
+ const res = { writeHead(status: number) { code = status; }, end(value: string) { response += value; } } as unknown as ServerResponse;
75
+ const handled = await handleAdminRuntimeApiFor(deps, 'GET', path, { url: path } as IncomingMessage, res,
76
+ { kind: 'admin', via: 'session', username: 'reader', permissions });
77
+ return { code, body: JSON.parse(response), reads, handled };
78
+ }
79
+
80
+ test('approval detail is runs:read-only, retrieves one snapshot and does not decide or continue', async () => {
81
+ const row = approval({ source: { html: 'x'.repeat(64 * 1024), css: '' } });
82
+ const result = await request('/admin/api/tool-approvals/31/details', ['runs:read'], row);
83
+ assert.equal(result.handled, true);
84
+ assert.equal(result.code, 200);
85
+ assert.equal(result.reads, 1);
86
+ assert.equal(result.body.args_json, row.args_json);
87
+ assert.equal(result.body.status, 'pending');
88
+ const list = await request('/admin/api/tool-approvals', ['runs:read'], row);
89
+ assert.equal(list.code, 200);
90
+ assert.equal(list.body[0].args_json, undefined);
91
+ assert.equal(list.body[0].details_available, true);
92
+ });
93
+
94
+ test('approval list and details deny missing runs:read before repository access', async () => {
95
+ for (const path of ['/admin/api/tool-approvals', '/admin/api/tool-approvals/31/details']) {
96
+ const denied = await request(path, ['tools:read']);
97
+ assert.equal(denied.code, 403);
98
+ assert.equal(denied.reads, 0);
99
+ }
100
+ });
101
+
102
+ test('missing approval details return 404; invalid numeric id cannot reach a repository', async () => {
103
+ assert.equal((await request('/admin/api/tool-approvals/31/details', ['runs:read'], null)).code, 404);
104
+ for (const id of ['0', '999999999999999999999']) {
105
+ const invalid = await request(`/admin/api/tool-approvals/${id}/details`, ['runs:read']);
106
+ assert.equal(invalid.code, 400);
107
+ assert.equal(invalid.reads, 0);
108
+ }
109
+ });
@@ -0,0 +1,36 @@
1
+ import type { ToolApproval } from '../core/contracts/types';
2
+ import { truncateUtf8 } from '../core/platform/http-body';
3
+
4
+ const INLINE_ARGUMENTS_MAX_BYTES = 4096;
5
+ const INLINE_INTENT_MAX_BYTES = 8192;
6
+
7
+ /** List polling carries small historical snapshots, never repeated MiB-scale execution input. */
8
+ export function approvalListView(approval: ToolApproval): Record<string, unknown> {
9
+ const args = approval.args_json ?? '';
10
+ const argsBytes = Buffer.byteLength(args, 'utf8');
11
+ const intentBytes = Buffer.byteLength(JSON.stringify(approval.intent ?? {}), 'utf8');
12
+ const intentJsonBytes = Buffer.byteLength(approval.intent_json ?? '', 'utf8');
13
+ const deferred = argsBytes > INLINE_ARGUMENTS_MAX_BYTES
14
+ || intentBytes > INLINE_INTENT_MAX_BYTES || intentJsonBytes > INLINE_INTENT_MAX_BYTES;
15
+ if (!deferred) return {
16
+ ...approval, args_bytes: argsBytes, args_truncated: false, details_available: false,
17
+ };
18
+ const { args_json: _args, intent: _intent, intent_json: _intentJson, ...metadata } = approval;
19
+ return {
20
+ ...metadata,
21
+ args_preview: truncateUtf8(args, INLINE_ARGUMENTS_MAX_BYTES),
22
+ args_bytes: argsBytes,
23
+ args_truncated: argsBytes > INLINE_ARGUMENTS_MAX_BYTES,
24
+ details_available: true,
25
+ };
26
+ }
27
+
28
+ /** Authorized, explicitly requested single-record view; no preview replaces the stored input. */
29
+ export function approvalDetailView(approval: ToolApproval): Record<string, unknown> {
30
+ return {
31
+ ...approval,
32
+ args_bytes: Buffer.byteLength(approval.args_json ?? '', 'utf8'),
33
+ args_truncated: false,
34
+ details_available: false,
35
+ };
36
+ }
@@ -0,0 +1,52 @@
1
+ import assert from 'node:assert/strict';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import test from 'node:test';
4
+ import { BAILINGHUB_CORE_ARTIFACT_V1 as artifact } from '../kernel-api/v1/artifact';
5
+ import { checkReadinessFor } from '../app/readiness';
6
+ import { handleAdminApiFor, type AdminApiDeps } from './admin';
7
+
8
+ const checkedAt = '2026-01-01T01:02:03.000Z';
9
+ function fixture(fault: 'none' | 'state' | 'configuration' | 'checksum' | 'connection') {
10
+ let probes = 0;
11
+ const db = (side: string) => ({ query: async (sql: string) => {
12
+ probes++;
13
+ assert.ok(sql === 'SELECT 1' || sql.startsWith('SELECT filename, checksum_sha256'), 'probe stays read-only');
14
+ if (fault === 'connection') throw new Error('private database password and host');
15
+ if (sql === 'SELECT 1') return [[{ one: 1 }], []];
16
+ const rows = artifact.migrations.map(m => ({ filename: m.filename, checksum_sha256: m.checksumSha256 }));
17
+ if (fault === side) rows.pop();
18
+ if (fault === 'checksum' && side === 'state') rows[0]!.checksum_sha256 = '0'.repeat(64);
19
+ return [rows, []];
20
+ } });
21
+ const deps = {
22
+ cfg: { root: '/unused', state: { backend: 'mysql' } },
23
+ configStore: { db: db('configuration') }, stateStore: { schemaReadinessDb: db('state') }, now: () => checkedAt,
24
+ } as unknown as AdminApiDeps;
25
+ return { deps, probes: () => probes };
26
+ }
27
+ async function request(deps: AdminApiDeps, permissions: string[] = ['audit:read']) {
28
+ let code = 0; let body = '';
29
+ const res = { writeHead(status: number) { code = status; }, end(chunk: string) { body += chunk; } } as unknown as ServerResponse;
30
+ const handled = await handleAdminApiFor(deps, 'GET', '/admin/api/readiness', {} as IncomingMessage, res,
31
+ { kind: 'admin', via: 'session', username: 'reader', permissions });
32
+ return { handled, code, body: JSON.parse(body) };
33
+ }
34
+
35
+ for (const fault of ['none', 'state', 'configuration', 'checksum', 'connection'] as const) {
36
+ test(`console readiness agrees with runtime readiness (${fault}) and timestamps its report`, async () => {
37
+ const { deps } = fixture(fault);
38
+ const expected = await checkReadinessFor(deps.cfg, deps.configStore, deps.stateStore);
39
+ const result = await request(deps);
40
+ assert.equal(result.handled, true);
41
+ assert.equal(result.code, 200, 'a failed probe is a report, not a failed request');
42
+ assert.deepEqual(result.body, { ...expected, checked_at: checkedAt });
43
+ assert.equal(result.body.ready, fault === 'none');
44
+ assert.doesNotMatch(JSON.stringify(result.body), /password|private database/);
45
+ });
46
+ }
47
+ test('readiness requires audit:read and denied requests do not query stores', async () => {
48
+ const f = fixture('none');
49
+ const result = await request(f.deps, ['runs:read']);
50
+ assert.equal(result.code, 403);
51
+ assert.equal(f.probes(), 0);
52
+ });
@@ -0,0 +1,51 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import type { Job } from '../core/contracts/types';
4
+ import { consoleExecution, approvalContinuationView } from './admin-runtime-ux';
5
+ import { approvalFeedback, approvalProgress, canOfferRerun, rerunHint } from '../../web-admin/src/runtime-feedback';
6
+
7
+ function job(overrides: Partial<Job> = {}): Job {
8
+ return { job_id: 'synthetic-job', request_id: 'synthetic-request', status: 'done', profile: 'general',
9
+ project: '', source: 'synthetic', input_preview: '', metadata: {},
10
+ created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z', ...overrides };
11
+ }
12
+
13
+ test('console rerun presentation rejects in-flight and uncertain outcomes without mutating records', () => {
14
+ for (const status of ['queued', 'running', 'dispatched'] as const) {
15
+ const snapshot = job({ status });
16
+ assert.deepEqual(consoleExecution(snapshot), { kind: 'hub_task', rerun: { available: false, reason: 'in_flight' } });
17
+ assert.equal(snapshot.status, status);
18
+ }
19
+ for (const overrides of [
20
+ { result: { governance_state: 'reconciliation_required', auto_retry_allowed: false } },
21
+ { result: { state: 'reconciliation_required' } },
22
+ { error: 'tool_execution_reconciliation_required' },
23
+ ]) {
24
+ const snapshot = job(overrides), before = JSON.stringify(snapshot);
25
+ const execution = consoleExecution(snapshot);
26
+ assert.equal(execution.rerun.reason, 'outcome_unknown');
27
+ assert.equal(canOfferRerun(execution), false);
28
+ assert.match(rerunHint(execution), /不要重新执行/);
29
+ assert.equal(JSON.stringify(snapshot), before);
30
+ }
31
+ assert.equal(canOfferRerun(consoleExecution(job({ status: 'error' }))), true);
32
+ });
33
+
34
+ test('old API responses and missing linked records never promise automatic execution', () => {
35
+ assert.equal(canOfferRerun(undefined), false);
36
+ assert.match(rerunHint(undefined), /未提供重跑边界/);
37
+ assert.deepEqual(approvalContinuationView(null), { continuation_mode: 'unknown', continuation_pending: null, job_status: null });
38
+ assert.doesNotMatch(approvalFeedback({ rerun: false }, 'approve'), /任务在途|自动重跑|执行成功/);
39
+ assert.match(approvalProgress({ status: 'approved' }), /请查看原任务/);
40
+ });
41
+
42
+ test('manual approval, queued admission and recovery stay distinct from business success', () => {
43
+ assert.match(approvalFeedback({ continuation_mode: 'manual', rerun: false }, 'approve'), /原客户端.*同一调用标识/);
44
+ assert.match(approvalFeedback({ continuation_mode: 'rerun', rerun: true }, 'approve'), /重新入队/);
45
+ assert.match(approvalFeedback({ continuation_mode: 'rerun', continuation_pending: true }, 'approve'), /决策已保存,续办处理中/);
46
+ assert.match(approvalProgress({ status: 'approved', used_at: '2026-01-01', job_status: 'error' }), /批准已使用.*业务结果请查看原任务/);
47
+ assert.match(approvalProgress({ status: 'approved', continuation_mode: 'manual', continuation_pending: false }), /等待原客户端/);
48
+ assert.match(approvalProgress({ status: 'approved', continuation_mode: 'rerun', job_status: 'queued' }), /尚未确认执行结果/);
49
+ assert.match(approvalProgress({ status: 'approved', continuation_mode: 'manual', continuation_pending: true }), /续办处理中/);
50
+ assert.match(approvalProgress({ status: 'denied' }), /不会.*重新执行/);
51
+ });
@@ -0,0 +1,25 @@
1
+ import type { Job } from '../core/contracts/types';
2
+ import type { ApprovalContinuation } from '../core/contracts/approval-continuation';
3
+ import { isAgentToolInvocationJob } from '../app/agent-tool-job';
4
+
5
+ /** Read-only presentation metadata. Existing mutation routes remain authoritative. */
6
+ export function consoleExecution(job: Job) {
7
+ const kind = isAgentToolInvocationJob(job) ? 'agent_tool' : 'hub_task';
8
+ const result = job.result ?? {};
9
+ const uncertain = result['governance_state'] === 'reconciliation_required'
10
+ || result['state'] === 'reconciliation_required'
11
+ || job.error === 'tool_execution_reconciliation_required';
12
+ const reason = uncertain ? 'outcome_unknown' : kind === 'agent_tool' ? 'original_client'
13
+ : ['queued', 'running', 'dispatched'].includes(job.status) ? 'in_flight' : null;
14
+ return { kind, rerun: { available: reason === null, reason } } as const;
15
+ }
16
+
17
+ export function approvalContinuationView(job: Job | null, intent?: ApprovalContinuation | null) {
18
+ // Never infer an automatic continuation from a missing job or failed lookup.
19
+ const mode = job ? (isAgentToolInvocationJob(job) ? 'manual' : 'rerun') : 'unknown';
20
+ return {
21
+ continuation_mode: mode,
22
+ continuation_pending: intent === undefined ? null : Boolean(intent && !intent.completed),
23
+ job_status: job?.status ?? null,
24
+ };
25
+ }
@@ -10,12 +10,14 @@ import { buildAgentClientTrace } from '../core/runtime/agent-client-trace';
10
10
  import type { RuntimeStateStore } from '../core/state/state-contracts';
11
11
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
12
12
  import type { AgentClientRunRecord } from '../infrastructure/config/config-agent-client-runtime-repository';
13
- import type { Principal } from '../app/auth';
13
+ import { can, type Principal } from '../app/auth';
14
14
  import type { ChannelMessage, ChannelSendResult } from '../app/channels';
15
15
  import { isAgentToolInvocationJob } from '../app/agent-tool-job';
16
16
  import { continueApprovalDecisionFor, supportsApprovalContinuations } from '../app/approval-continuations';
17
17
  import { classifyDeliveryDlq, replayExecutorDeliveryDlq, DeliveryReplayError } from '../app/delivery-dlq-replay';
18
18
  import { handleAdminNotificationsFor } from './admin-notifications';
19
+ import { approvalContinuationView, consoleExecution } from './admin-runtime-ux';
20
+ import { approvalDetailView, approvalListView } from './admin-approval-view';
19
21
 
20
22
  export type AdminChannelSender = (channelName: string, recipient: string, message: string | ChannelMessage) => Promise<ChannelSendResult>;
21
23
 
@@ -192,7 +194,7 @@ export async function handleAdminRuntimeApiFor(
192
194
  configStore.deliveryDlq.listByParentJob(jobId, true, 100).catch(() => []),
193
195
  routeKey ? configStore.routes.get(routeKey).catch(() => null) : Promise.resolve(null),
194
196
  ]);
195
- const jobWithRaw = { ...job, raw_input: rawInput, ...await conversationLinkForJob(job) };
197
+ const jobWithRaw = { ...job, raw_input: rawInput, ...await conversationLinkForJob(job), console_execution: consoleExecution(job) };
196
198
  const trace = buildJobTrace({ job, audit, approvals, messages });
197
199
  const dispatchSnapshot = {
198
200
  status: job.status,
@@ -466,7 +468,7 @@ export async function handleAdminRuntimeApiFor(
466
468
  if (method === 'GET' && !mRun[2]) {
467
469
  // raw_input = 未装配的原始触发输入(总账 in 消息),供审计区分"用户发了啥"与"我们组装成的 input";无总账时前端回落 input_preview
468
470
  const rawInput = await configStore.conversations.rawInputForJob(jobId).catch(() => null);
469
- send(res, 200, { ...job, raw_input: rawInput });
471
+ send(res, 200, { ...job, raw_input: rawInput, console_execution: consoleExecution(job) });
470
472
  return true;
471
473
  }
472
474
  if (method === 'GET' && mRun[2] === '/audit') {
@@ -493,10 +495,33 @@ export async function handleAdminRuntimeApiFor(
493
495
  }
494
496
  }
495
497
 
496
- // ---- 工具审批(确认车道 B:批准后自动重跑;批准范围锁定当时那个调用快照)----
498
+ // ---- 工具审批(批准范围锁定调用快照;中枢任务续办,Agent 直调由原客户端继续)----
497
499
  if (path === '/admin/api/tool-approvals' && method === 'GET') {
500
+ if (!can(principal, 'runs:read')) { send(res, 403, { error: '当前角色无此权限' }); return true; }
498
501
  const status = new URL(req.url ?? '/', 'http://x').searchParams.get('status') ?? 'pending';
499
- send(res, 200, await configStore.approvals.list(status === 'all' ? undefined : status));
502
+ const approvals = await configStore.approvals.list(status === 'all' ? undefined : status);
503
+ const rows = [];
504
+ // Bound the extra read-only lookups; a missing old record must not hide its decision.
505
+ for (let offset = 0; offset < approvals.length; offset += 8) {
506
+ rows.push(...await Promise.all(approvals.slice(offset, offset + 8).map(async (approval) => {
507
+ const [job, intent] = await Promise.all([
508
+ stateStore.getJob(approval.job_id).catch(() => null),
509
+ configStore.approvals.getContinuation?.(approval.id).catch(() => undefined),
510
+ ]);
511
+ return { ...approvalListView(approval), ...approvalContinuationView(job, intent) };
512
+ })));
513
+ }
514
+ send(res, 200, rows);
515
+ return true;
516
+ }
517
+ const mApprovalDetail = path.match(/^\/admin\/api\/tool-approvals\/(\d+)\/details$/);
518
+ if (mApprovalDetail && method === 'GET') {
519
+ if (!can(principal, 'runs:read')) { send(res, 403, { error: '当前角色无此权限' }); return true; }
520
+ const id = Number(mApprovalDetail[1]);
521
+ if (!Number.isSafeInteger(id) || id < 1) { send(res, 400, { error: '审批单标识无效' }); return true; }
522
+ const approval = await configStore.approvals.get(id);
523
+ if (!approval) { send(res, 404, { error: '审批单不存在' }); return true; }
524
+ send(res, 200, approvalDetailView(approval));
500
525
  return true;
501
526
  }
502
527
  const mApproval = path.match(/^\/admin\/api\/tool-approvals\/(\d+)\/(approve|deny)$/);
@@ -515,11 +540,13 @@ export async function handleAdminRuntimeApiFor(
515
540
  send(res, 503, { error: '审批持久续办需要配套状态与配置仓储', code: 'approval_continuations_unavailable' }); return true;
516
541
  }
517
542
  let recorded: 'decided' | 'same' | 'conflict';
543
+ let continuationMode: 'manual' | 'rerun';
518
544
  try {
519
545
  const job = await stateStore.getJob(appr.job_id);
520
546
  if (!job) { send(res, 404, { error: '审批单关联任务不存在' }); return true; }
547
+ continuationMode = isAgentToolInvocationJob(job) ? 'manual' : 'rerun';
521
548
  recorded = await configStore.approvals.decideWithContinuation!(id, decision, by, {
522
- source: 'console', auth: 'admin-console', mode: isAgentToolInvocationJob(job) ? 'manual' : 'rerun',
549
+ source: 'console', auth: 'admin-console', mode: continuationMode,
523
550
  });
524
551
  } catch {
525
552
  send(res, 503, { error: '审批决策持久化暂不可用,请重试原审批单', code: 'approval_continuations_unavailable' }); return true;
@@ -528,9 +555,10 @@ export async function handleAdminRuntimeApiFor(
528
555
  try {
529
556
  const continued = await continueApprovalDecisionFor(continuationDeps, id);
530
557
  send(res, 200, { ok: true, id, status: decision, idempotent: recorded === 'same',
531
- rerun: continued.rerun, continuation_pending: continued.pending });
558
+ rerun: continued.rerun, continuation_mode: continuationMode, continuation_pending: continued.pending });
532
559
  } catch {
533
- send(res, 503, { error: '审批决策已保存,原任务续办等待恢复', decision_recorded: true, continuation_pending: true });
560
+ send(res, 503, { error: '审批决策已保存,原任务续办等待恢复', decision_recorded: true,
561
+ continuation_mode: continuationMode, continuation_pending: true });
534
562
  }
535
563
  return true;
536
564
  }
@@ -9,6 +9,7 @@ import { normalizeHttpMountPath, readBody, send } from '../app/http';
9
9
  import { type Principal, ROLE_PERMS, SESSION_COOKIE, can, permsOf, readCookie } from '../app/auth';
10
10
  import { hashPassword, verifyPassword } from '../core/platform/password';
11
11
  import { buildVersionInfo } from '../core/platform/version';
12
+ import { checkReadinessFor } from '../app/readiness';
12
13
  import { inspectConfig } from '../core/config/config-diagnostics';
13
14
  import { runHubSmoke } from '../core/runtime/smoke-runtime';
14
15
  import { handleAdminAccessApiFor } from './admin-access';
@@ -137,6 +138,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
137
138
  [/^\/admin\/api\/delivery-dlq/, 'runs:read', 'runs:write'], // 送达死信队列(查看/重投),运行面操作
138
139
  [/^\/admin\/api\/notification-outbox/, 'runs:read', 'runs:write'],
139
140
  [/^\/admin\/api\/version/, 'audit:read', 'audit:read'], // 版本/数据库结构状态:系统可观测
141
+ [/^\/admin\/api\/readiness/, 'audit:read', 'audit:read'],
140
142
  ];
141
143
  for (const [re, readPerm, writePerm] of PERM_RULES) {
142
144
  if (!re.test(path)) continue;
@@ -163,6 +165,13 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
163
165
  send(res, 200, buildVersionInfo(deps.cfg.root, await configStore.observability.listSchemaMigrations()));
164
166
  return true;
165
167
  }
168
+ if (path === '/admin/api/readiness' && method === 'GET') {
169
+ const report = await checkReadinessFor(deps.cfg, configStore, deps.stateStore);
170
+ // The console consumes the same actual stores and check as /readyz. A failed
171
+ // probe is a valid report, distinct from failing to retrieve this endpoint.
172
+ send(res, 200, { ...report, checked_at: deps.now() });
173
+ return true;
174
+ }
166
175
  if (path === '/admin/api/config-diagnostics' && method === 'GET') {
167
176
  send(res, 200, await inspectConfig(configStore, { cfg: deps.cfg, kbService: deps.kbService }));
168
177
  return true;
@@ -11,6 +11,7 @@ import type { RuntimeStateStore } from '../core/state/state-contracts';
11
11
  import { tokenHash } from './agent-auth';
12
12
  import { handleAgentApiHttpFor } from './agent-api';
13
13
  import type { ToolProxyDeps } from '../app/tool-proxy';
14
+ import { TOOL_ARGUMENTS_MAX_BYTES, TOOL_INVOCATION_BODY_MAX_BYTES } from '../core/contracts/tool-input-limits';
14
15
 
15
16
  class FakeResponse {
16
17
  statusCode = 0;
@@ -141,9 +142,27 @@ test('Agent Tool API: envelope 严格拒绝非对象 arguments 与字段漂移',
141
142
  assert.equal(extra.statusCode, 400);
142
143
 
143
144
  const oversized = new FakeResponse();
144
- await handleAgentApiHttpFor(deps, request('POST', headers, { ...base, future: 'x'.repeat(20_000) }), oversized as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
145
+ const oversizedBody = { ...base, future: 'x'.repeat(TOOL_INVOCATION_BODY_MAX_BYTES) };
146
+ await handleAgentApiHttpFor(deps, request('POST', headers, oversizedBody), oversized as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
145
147
  assert.equal(oversized.statusCode, 413);
146
148
  assert.equal(oversized.json()['error'], 'arguments_too_large');
149
+ assert.equal(oversized.json()['origin'], 'core');
150
+ assert.equal(oversized.json()['dispatch'], 'not_dispatched');
151
+ assert.equal(oversized.json()['limit_scope'], 'request_body');
152
+ assert.equal(oversized.json()['max_bytes'], 2 * 1024 * 1024);
153
+ assert.equal(oversized.json()['observed_bytes'], Buffer.byteLength(JSON.stringify(oversizedBody), 'utf8'));
154
+
155
+ const argumentsOverflow = new FakeResponse();
156
+ const oversizedArgs = { source: { html: 'private-design-marker'.repeat(Math.ceil(TOOL_ARGUMENTS_MAX_BYTES / 21)) } };
157
+ const actualBytes = Buffer.byteLength(JSON.stringify(oversizedArgs), 'utf8');
158
+ assert.ok(actualBytes > TOOL_ARGUMENTS_MAX_BYTES && actualBytes < TOOL_INVOCATION_BODY_MAX_BYTES);
159
+ await handleAgentApiHttpFor(deps, request('POST', headers, { ...base, arguments: oversizedArgs }), argumentsOverflow as unknown as ServerResponse, new URL('https://hub.example.com/agent-api/v1/tool-invocations'));
160
+ assert.equal(argumentsOverflow.statusCode, 413);
161
+ assert.equal(argumentsOverflow.json()['limit_scope'], 'arguments');
162
+ assert.equal(argumentsOverflow.json()['actual_bytes'], actualBytes);
163
+ assert.equal(argumentsOverflow.json()['max_bytes'], 1024 * 1024);
164
+ assert.equal(argumentsOverflow.json()['dispatch'], 'not_dispatched');
165
+ assert.equal(argumentsOverflow.body.includes(Buffer.from('private-design-marker')), false);
147
166
 
148
167
  for (const invalidBody of [[], null, 'x', 7]) {
149
168
  const res = new FakeResponse();
@@ -342,6 +361,7 @@ function runtimeHttpFixture() {
342
361
  };
343
362
  return {
344
363
  token,
364
+ routes,
345
365
  deps: { configStore, stateStore, isPaused: () => false, handleRun: async () => undefined, toolProxyDeps, kbService: null },
346
366
  completeCalls: () => completeCalls,
347
367
  };
@@ -370,6 +390,65 @@ test('Agent Runtime HTTP: workspace 只列授权交集,turn 可省 page_contex
370
390
  assert.equal(unknown.json()['error'], 'invalid_request');
371
391
  });
372
392
 
393
+ test('Agent knowledge HTTP is read-only, strict and available without direct business tools', async () => {
394
+ const fx = runtimeHttpFixture();
395
+ fx.routes[0]!.tools = {};
396
+ const headers = { authorization: `Bearer ${fx.token}` };
397
+ const call = async (method: string, suffix: string, body?: unknown) => {
398
+ const res = new FakeResponse();
399
+ await handleAgentApiHttpFor(fx.deps, request(method, headers, body), res as unknown as ServerResponse,
400
+ new URL(`https://hub.example.com/agent-api/v1/workspaces/allowed/knowledge/${suffix}`));
401
+ assert.equal(res.headers['cache-control'], 'no-store');
402
+ return res;
403
+ };
404
+ const caps = await call('GET', 'capabilities');
405
+ assert.equal(caps.statusCode, 200);
406
+ assert.equal(caps.json()['supported'], true);
407
+ assert.equal(caps.json()['enabled'], false);
408
+ assert.equal(caps.json()['protocol'], 'bailing.agent-knowledge.v1');
409
+ const search = await call('POST', 'search', { query: '退款窗口' });
410
+ assert.equal(search.statusCode, 200);
411
+ assert.equal(search.json()['status'], 'disabled');
412
+ assert.deepEqual(search.json()['hints'], []);
413
+ assert.equal((await call('GET', 'search')).statusCode, 405);
414
+ assert.equal((await call('GET', 'capabilities?kb_ids=private')).statusCode, 400);
415
+ for (const body of [{ query: '退款', kb_ids: ['private'] }, { query: '退款', limit: 4 }, { query: '退款', run_id: null }, { limit: 1 }]) {
416
+ assert.equal((await call('POST', 'search', body)).statusCode, 400);
417
+ }
418
+ for (const body of [{ ref: 'forged', doc_id: 7 }, { ref: 'forged', max_bytes: 32769 }, { ref: 'forged', cursor: 1 }, {}]) {
419
+ assert.equal((await call('POST', 'read', body)).statusCode, 400);
420
+ }
421
+ for (const key of ['audience-denied', 'agent-off', 'session-denied', 'client-denied']) {
422
+ const res = new FakeResponse();
423
+ await handleAgentApiHttpFor(fx.deps, request('GET', headers), res as unknown as ServerResponse,
424
+ new URL(`https://hub.example.com/agent-api/v1/workspaces/${key}/knowledge/capabilities`));
425
+ assert.equal(res.statusCode, 403, key);
426
+ }
427
+ });
428
+
429
+ test('Agent turn HTTP accepts only the explicit on-demand mode and preserves required instructions', async () => {
430
+ const fx = runtimeHttpFixture();
431
+ const headers = { authorization: `Bearer ${fx.token}` };
432
+ const input = { client_conversation_id: 'c1', client_turn_id: 't1', user_message_id: 'm1', user_input: '规则问答' };
433
+ for (const mode of ['hint', 'off', 'full', null, {}, true]) {
434
+ const res = new FakeResponse();
435
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, { ...input, knowledge_delivery: mode }), res as unknown as ServerResponse,
436
+ new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/turns'));
437
+ assert.equal(res.statusCode, 400);
438
+ }
439
+ fx.routes[0]!.tools = {};
440
+ const res = new FakeResponse();
441
+ await handleAgentApiHttpFor(fx.deps, request('POST', headers, { ...input, knowledge_delivery: 'on_demand' }), res as unknown as ServerResponse,
442
+ new URL('https://hub.example.com/agent-api/v1/workspaces/allowed/turns'));
443
+ assert.equal(res.statusCode, 200, JSON.stringify(res.json()));
444
+ const context = res.json()['context'] as Record<string, any>;
445
+ assert.equal(context.knowledge_delivery.mode, 'on_demand');
446
+ assert.equal(context.knowledge_delivery.status, 'disabled');
447
+ assert.equal(context.instructions, '【路由系统规则】\nsafe system');
448
+ assert.deepEqual(context.knowledge, []);
449
+ assert.deepEqual(res.json()['active_tools'], []);
450
+ });
451
+
373
452
  test('Agent Runtime HTTP: complete 拒绝 hidden reasoning 且不触达 repository', async () => {
374
453
  const fx = runtimeHttpFixture();
375
454
  const res = new FakeResponse();