bailinghub 0.9.4 → 0.10.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 (298) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  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 +12 -0
  15. package/docs/CHANGELOG.md +12 -0
  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 +19 -15
  20. package/docs/IMPLEMENTATION_STATUS.md +19 -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 +5 -0
  34. package/docs/README.md +5 -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/UPGRADE_PLAN.en.md +118 -0
  40. package/docs/UPGRADE_PLAN.md +124 -0
  41. package/docs/UPGRADE_v0.10.0.en.md +47 -0
  42. package/docs/UPGRADE_v0.10.0.md +47 -0
  43. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +38 -22
  44. package/package.json +8 -5
  45. package/schemas/tool-definition.schema.json +13 -0
  46. package/scripts/check-doc-links.mjs +4 -0
  47. package/scripts/check-image-tags.sh +1 -1
  48. package/scripts/check-release-consistency.test.mjs +2 -2
  49. package/scripts/doctor-upgrade-plan.test.ts +205 -0
  50. package/scripts/doctor-upgrade-plan.ts +276 -0
  51. package/scripts/doctor.ts +4 -1
  52. package/scripts/e2e-console-approval-details.mjs +134 -0
  53. package/scripts/e2e-console-config-races.mjs +180 -0
  54. package/scripts/e2e-console-kb-audit.mjs +170 -0
  55. package/scripts/e2e-console-operations-audit.mjs +152 -0
  56. package/scripts/e2e-console-runtime-audit.mjs +179 -0
  57. package/scripts/e2e-console-settings-audit.mjs +125 -0
  58. package/scripts/e2e-console-troubleshooting-extra.mjs +267 -0
  59. package/scripts/e2e-console.mjs +476 -7
  60. package/scripts/install.sh +1 -1
  61. package/scripts/publish-images.sh +1 -1
  62. package/scripts/release-audit.mjs +4 -0
  63. package/scripts/verify-github-repo.mjs +4 -0
  64. package/src/app/agent-client-runtime.test.ts +115 -2
  65. package/src/app/agent-client-runtime.ts +40 -11
  66. package/src/app/agent-knowledge.test.ts +171 -0
  67. package/src/app/agent-knowledge.ts +233 -0
  68. package/src/app/agent-tool-catalog-revision.test.ts +31 -0
  69. package/src/app/agent-tool-invocations.test.ts +7 -2
  70. package/src/app/agent-tool-invocations.ts +67 -7
  71. package/src/app/approval-continuations.test.ts +49 -1
  72. package/src/app/http.test.ts +16 -1
  73. package/src/app/http.ts +3 -3
  74. package/src/app/kernel-boot-recovery.mysql.test.ts +132 -0
  75. package/src/app/kernel-boot-recovery.test.ts +157 -0
  76. package/src/app/kernel.ts +12 -8
  77. package/src/app/readiness.mysql.test.ts +120 -0
  78. package/src/app/readiness.test.ts +111 -26
  79. package/src/app/readiness.ts +26 -22
  80. package/src/app/runtime-lifecycle.ts +34 -3
  81. package/src/app/tool-approvals.test.ts +83 -0
  82. package/src/app/tool-approvals.ts +25 -7
  83. package/src/app/tool-proxy-payload.test.ts +81 -0
  84. package/src/app/tool-proxy.ts +24 -2
  85. package/src/core/config/console-diagnostic-location.test.ts +36 -0
  86. package/src/core/config/console-form-guard.test.ts +69 -0
  87. package/src/core/config/console-task-location.test.ts +64 -0
  88. package/src/core/contracts/openapi-tools.ts +16 -5
  89. package/src/core/contracts/schema-readiness.ts +11 -0
  90. package/src/core/contracts/tool-definition.ts +26 -0
  91. package/src/core/contracts/tool-guidance.test.ts +77 -0
  92. package/src/core/contracts/tool-guidance.ts +31 -0
  93. package/src/core/contracts/tool-input-limits.ts +15 -0
  94. package/src/core/contracts/tools-idempotency.test.ts +90 -0
  95. package/src/core/contracts/tools.ts +52 -9
  96. package/src/core/runtime/agent-execution-memory.test.ts +64 -0
  97. package/src/core/runtime/agent-execution-memory.ts +63 -0
  98. package/src/core/state/state-contracts.ts +3 -0
  99. package/src/infrastructure/config/config-observability-ledger.ts +2 -0
  100. package/src/infrastructure/schema/schema-readiness.ts +29 -0
  101. package/src/infrastructure/state/state-mysql.ts +3 -0
  102. package/src/modules/usage/contracts.ts +7 -0
  103. package/src/modules/usage/http.ts +2 -0
  104. package/src/modules/usage/model-continuation.test.ts +109 -0
  105. package/src/modules/usage/model-gateway.ts +5 -1
  106. package/src/modules/usage/output-budget.mysql.test.ts +84 -0
  107. package/src/modules/usage/output-budget.test.ts +167 -0
  108. package/src/modules/usage/output-budget.ts +73 -0
  109. package/src/modules/usage/provider-stream.test.ts +22 -0
  110. package/src/modules/usage/provider.ts +2 -3
  111. package/src/modules/usage/repository.ts +6 -0
  112. package/src/modules/usage/test-harness.ts +4 -2
  113. package/src/routes/admin-approval-view.test.ts +109 -0
  114. package/src/routes/admin-approval-view.ts +36 -0
  115. package/src/routes/admin-readiness.test.ts +52 -0
  116. package/src/routes/admin-runtime-ux.test.ts +51 -0
  117. package/src/routes/admin-runtime-ux.ts +25 -0
  118. package/src/routes/admin-runtime.ts +36 -8
  119. package/src/routes/admin.ts +9 -0
  120. package/src/routes/agent-api.test.ts +80 -1
  121. package/src/routes/agent-api.ts +63 -4
  122. package/src/routes/agent-tool-detail.test.ts +140 -0
  123. package/src/routes/public-default.ts +1 -1
  124. package/src/services/kb-agent.test.ts +84 -0
  125. package/src/services/kb.ts +73 -0
  126. package/web/console/assets/Accounts-CjIBO3sU.css +1 -0
  127. package/web/console/assets/Accounts-Dhyw-7wF.js +3 -0
  128. package/web/console/assets/AgentClients-BA0M26-I.css +1 -0
  129. package/web/console/assets/AgentClients-DWxb8-ko.js +1 -0
  130. package/web/console/assets/AgentTasks-DOyxANnx.css +1 -0
  131. package/web/console/assets/AgentTasks-DUHD4dzr.js +2 -0
  132. package/web/console/assets/Approvals-Brl-2uJq.css +1 -0
  133. package/web/console/assets/Approvals-CQx1YWxW.js +1 -0
  134. package/web/console/assets/Audit--QcdVlMh.js +1 -0
  135. package/web/console/assets/Audit-DAdmOnIs.css +1 -0
  136. package/web/console/assets/{BrandLockup-CffORQse.js → BrandLockup-DQcaW4Nt.js} +1 -1
  137. package/web/console/assets/Channels-DJJU3ksE.css +1 -0
  138. package/web/console/assets/Channels-cGS5WfQ-.js +105 -0
  139. package/web/console/assets/ChatEntries-BYpji27B.css +1 -0
  140. package/web/console/assets/ChatEntries-nh23Iz5O.js +7 -0
  141. package/web/console/assets/Clients-CX5EeYio.js +3 -0
  142. package/web/console/assets/Clients-CbZAou8E.css +1 -0
  143. package/web/console/assets/Cost-C6oQvz9P.css +1 -0
  144. package/web/console/assets/Cost-DOZfdNS9.js +1 -0
  145. package/web/console/assets/Credentials--aHs57yV.css +1 -0
  146. package/web/console/assets/Credentials-sy6W9Sac.js +1 -0
  147. package/web/console/assets/Diagnostics-CKs27Dnv.css +1 -0
  148. package/web/console/assets/Diagnostics-CyoM1XrZ.js +1 -0
  149. package/web/console/assets/Executors-2Upi6bOS.css +1 -0
  150. package/web/console/assets/Executors-BQqqiFwt.js +1 -0
  151. package/web/console/assets/HelpTip-DLlhaGQp.js +1 -0
  152. package/web/console/assets/HelpTip-bbDEyuqV.css +1 -0
  153. package/web/console/assets/Kb-5R3ce4UU.js +5 -0
  154. package/web/console/assets/Kb-BM_PYi11.css +1 -0
  155. package/web/console/assets/{Login-CGgLGTE1.js → Login-YKeUwdgo.js} +1 -1
  156. package/web/console/assets/Projects-DHwHrPT9.css +1 -0
  157. package/web/console/assets/Projects-Grgb6fOv.js +1 -0
  158. package/web/console/assets/Routes-DR_Yf02e.css +1 -0
  159. package/web/console/assets/Routes-DYgrXlRJ.js +138 -0
  160. package/web/console/assets/Runs-CwTddJJj.js +3 -0
  161. package/web/console/assets/Runs-D4FOvNfu.css +1 -0
  162. package/web/console/assets/Setup-Ca0b1d1-.css +1 -0
  163. package/web/console/assets/Setup-D_xUPNDq.js +1 -0
  164. package/web/console/assets/Shell-BTg8Vw_L.css +1 -0
  165. package/web/console/assets/Shell-Dfam2Uoj.js +1 -0
  166. package/web/console/assets/StorageBuckets-7QLBpV4a.css +1 -0
  167. package/web/console/assets/StorageBuckets-CP6e50wI.js +1 -0
  168. package/web/console/assets/SystemSettings-BRYKyJNa.js +1 -0
  169. package/web/console/assets/SystemSettings-HsXGx0aH.css +1 -0
  170. package/web/console/assets/SystemStatus-B-VfRsQd.css +1 -0
  171. package/web/console/assets/SystemStatus-CbPsDsGt.js +1 -0
  172. package/web/console/assets/Targets-1j4-g6rC.css +1 -0
  173. package/web/console/assets/Targets-C2LkR2AF.js +1 -0
  174. package/web/console/assets/Tools-C9HPJqJb.css +1 -0
  175. package/web/console/assets/Tools-C9JNJUS0.js +2 -0
  176. package/web/console/assets/Usage-D1Mv6vGY.js +1 -0
  177. package/web/console/assets/Usage-DMOzUsqh.css +1 -0
  178. package/web/console/assets/UsageAccess-77LmGCm6.js +1 -0
  179. package/web/console/assets/UsageAccess-C6ZGxEgJ.css +1 -0
  180. package/web/console/assets/{UsageHelp-CzS2gI40.js → UsageHelp-BmuiE1Ew.js} +1 -1
  181. package/web/console/assets/client-route-draft-DxZRxKPT.js +1 -0
  182. package/web/console/assets/console-location-Csv-xsnl.js +1 -0
  183. package/web/console/assets/form-guard-8GrFpry0.js +1 -0
  184. package/web/console/assets/{index-65JiiUr4.js → index-B_5UfiTw.js} +1 -1
  185. package/web/console/assets/index-MjZJEFIN.js +2 -0
  186. package/web/console/assets/{request-DKycpD7z.js → request-rqm6MT0s.js} +1 -1
  187. package/web/console/assets/runtime-feedback-gPfZVNvY.js +1 -0
  188. package/web/console/assets/{schema-SCiNxBlR.js → schema-o3mK4mid.js} +1 -1
  189. package/web/console/assets/task-page-location-DWiGtAln.js +1 -0
  190. package/web/console/assets/use-list-location-FvLFt0Tq.css +1 -0
  191. package/web/console/assets/use-list-location-cIPy2cKM.js +1 -0
  192. package/web/console/assets/use-unsaved-form-DScKD0h9.js +1 -0
  193. package/web/console/assets/{util-DZYfJ5Zo.js → util-B40VqOwl.js} +1 -1
  194. package/web/console/assets/{vendor-element-8cVcdt5T.js → vendor-element-BT8tHCFk.js} +1 -1
  195. package/web/console/assets/{vendor-mammoth-CnDA23N0.js → vendor-mammoth-CVIXVxTN.js} +1 -1
  196. package/web/console/assets/{vendor-vue-Co7x2FW6.js → vendor-vue-DhbG0vd4.js} +7 -7
  197. package/web/console/index.html +3 -3
  198. package/web-admin/package-lock.json +4 -4
  199. package/web-admin/package.json +1 -1
  200. package/web-admin/src/client-route-draft.ts +25 -0
  201. package/web-admin/src/components/AgentSetupPanel.vue +54 -41
  202. package/web-admin/src/components/HelpTip.vue +4 -1
  203. package/web-admin/src/components/ListLocationBar.vue +22 -0
  204. package/web-admin/src/components/NotificationOutboxPanel.vue +35 -7
  205. package/web-admin/src/console-entry.test.ts +26 -0
  206. package/web-admin/src/console-entry.ts +20 -0
  207. package/web-admin/src/console-location.ts +35 -0
  208. package/web-admin/src/form-guard.ts +35 -0
  209. package/web-admin/src/layout/Shell.vue +18 -65
  210. package/web-admin/src/onboarding-state.test.ts +174 -0
  211. package/web-admin/src/onboarding-state.ts +122 -0
  212. package/web-admin/src/pages/Accounts.vue +44 -24
  213. package/web-admin/src/pages/AgentClients.vue +47 -29
  214. package/web-admin/src/pages/AgentTasks.vue +57 -12
  215. package/web-admin/src/pages/Approvals.vue +105 -25
  216. package/web-admin/src/pages/Audit.vue +15 -6
  217. package/web-admin/src/pages/Channels.vue +136 -43
  218. package/web-admin/src/pages/ChatEntries.vue +96 -41
  219. package/web-admin/src/pages/Clients.vue +87 -26
  220. package/web-admin/src/pages/Cost.vue +15 -4
  221. package/web-admin/src/pages/Credentials.vue +63 -32
  222. package/web-admin/src/pages/Diagnostics.vue +103 -54
  223. package/web-admin/src/pages/Executors.vue +103 -40
  224. package/web-admin/src/pages/Kb.vue +278 -128
  225. package/web-admin/src/pages/Projects.vue +44 -16
  226. package/web-admin/src/pages/Routes.vue +168 -247
  227. package/web-admin/src/pages/Runs.vue +163 -91
  228. package/web-admin/src/pages/Setup.vue +182 -291
  229. package/web-admin/src/pages/StorageBuckets.vue +61 -25
  230. package/web-admin/src/pages/SystemSettings.vue +76 -51
  231. package/web-admin/src/pages/SystemStatus.vue +54 -30
  232. package/web-admin/src/pages/Targets.vue +45 -17
  233. package/web-admin/src/pages/Tools.vue +133 -68
  234. package/web-admin/src/pages/Usage.vue +64 -25
  235. package/web-admin/src/pages/UsageAccess.vue +11 -8
  236. package/web-admin/src/route-call-snippets.test.ts +82 -0
  237. package/web-admin/src/route-call-snippets.ts +178 -0
  238. package/web-admin/src/router.ts +11 -29
  239. package/web-admin/src/runtime-feedback.ts +43 -0
  240. package/web-admin/src/task-page-location.ts +66 -0
  241. package/web-admin/src/usage-output-budget.test.ts +26 -0
  242. package/web-admin/src/usage-output-budget.ts +46 -0
  243. package/web-admin/src/use-list-location.ts +24 -0
  244. package/web-admin/src/use-unsaved-form.ts +38 -0
  245. package/web-admin/tests/model-output-budget.browser.mjs +69 -0
  246. package/web/console/assets/Accounts-Bervi5JU.css +0 -1
  247. package/web/console/assets/Accounts-Dhj6PjXP.js +0 -3
  248. package/web/console/assets/AgentClients-CMy8StAH.js +0 -1
  249. package/web/console/assets/AgentClients-i52AI6YV.css +0 -1
  250. package/web/console/assets/AgentTasks-BsG850Il.css +0 -1
  251. package/web/console/assets/AgentTasks-DA1xZdmP.js +0 -2
  252. package/web/console/assets/Approvals-DIsd7R8N.js +0 -1
  253. package/web/console/assets/Approvals-DlTSHl_7.css +0 -1
  254. package/web/console/assets/Audit-AUDABLTX.js +0 -1
  255. package/web/console/assets/Audit-CSu6_3oD.css +0 -1
  256. package/web/console/assets/Channels-B8rjsM0S.js +0 -105
  257. package/web/console/assets/Channels-CCn0L1jg.css +0 -1
  258. package/web/console/assets/ChatEntries-DsYtcXN6.css +0 -1
  259. package/web/console/assets/ChatEntries-iZjJMEUZ.js +0 -7
  260. package/web/console/assets/Clients-CSHIsaWU.css +0 -1
  261. package/web/console/assets/Clients-CwgpGCSD.js +0 -3
  262. package/web/console/assets/Cost-B2tNxu71.js +0 -1
  263. package/web/console/assets/Cost-CjT39DSZ.css +0 -1
  264. package/web/console/assets/Credentials-BuwFB-fV.js +0 -1
  265. package/web/console/assets/Credentials-ioLP0qYN.css +0 -1
  266. package/web/console/assets/Diagnostics-Ya05PTDp.css +0 -1
  267. package/web/console/assets/Diagnostics-z5glms11.js +0 -1
  268. package/web/console/assets/Executors-Bc4SvjeH.js +0 -1
  269. package/web/console/assets/Executors-CjhEM54c.css +0 -1
  270. package/web/console/assets/HelpTip-CA6Bm7Nx.css +0 -1
  271. package/web/console/assets/HelpTip-Dtdt2tKR.js +0 -1
  272. package/web/console/assets/Kb-BRbRHxLy.js +0 -5
  273. package/web/console/assets/Kb-CzIzd9xr.css +0 -1
  274. package/web/console/assets/Projects-Bm8AjsNx.css +0 -1
  275. package/web/console/assets/Projects-CPWw3con.js +0 -1
  276. package/web/console/assets/Routes-CMIaE0Bx.js +0 -124
  277. package/web/console/assets/Routes-CyXV4Pba.css +0 -1
  278. package/web/console/assets/Runs-B8HuE700.js +0 -3
  279. package/web/console/assets/Runs-Bv6CV_Hk.css +0 -1
  280. package/web/console/assets/Setup-D7nxgn-9.css +0 -1
  281. package/web/console/assets/Setup-G8RKzliR.js +0 -1
  282. package/web/console/assets/Shell-DimHgraJ.js +0 -1
  283. package/web/console/assets/Shell-ykb-tUfo.css +0 -1
  284. package/web/console/assets/StorageBuckets-CVgpZRWY.css +0 -1
  285. package/web/console/assets/StorageBuckets-CiVYXIE2.js +0 -1
  286. package/web/console/assets/SystemSettings-BjiHyrXO.css +0 -1
  287. package/web/console/assets/SystemSettings-DF8sZNen.js +0 -1
  288. package/web/console/assets/SystemStatus-BlHywK13.js +0 -1
  289. package/web/console/assets/SystemStatus-I11I67rw.css +0 -1
  290. package/web/console/assets/Targets-BXaoPoAJ.js +0 -1
  291. package/web/console/assets/Targets-DTb5tn6z.css +0 -1
  292. package/web/console/assets/Tools-B22lNHXq.js +0 -2
  293. package/web/console/assets/Tools-DU8ei6sd.css +0 -1
  294. package/web/console/assets/Usage-C02EzoI2.js +0 -1
  295. package/web/console/assets/Usage-CAeDGjrb.css +0 -1
  296. package/web/console/assets/UsageAccess-CGGaWTuj.css +0 -1
  297. package/web/console/assets/UsageAccess-DOb-cyPE.js +0 -1
  298. package/web/console/assets/index-CK0ZCTZv.js +0 -2
@@ -1,6 +1,7 @@
1
1
  import { parseDocument } from 'yaml';
2
2
  import { AGENT_CAPABILITY_KEY, deriveRisk, toolAnnotationsOf } from './tool-annotations';
3
3
  import { TOOL_DEFINITION_SCHEMA_VERSION, hasToolDefinitionErrors, validateToolDefinition, type ToolCompileResult, type ToolConfirmCondition, type ToolConfirmOp, type ToolDefinition, type ToolDiagnostic, type ToolParamLocation } from './tool-definition';
4
+ import { boundedToolText, TOOL_DESCRIPTION_MAX_CHARS, TOOL_USAGE_GUIDANCE_MAX_BYTES, TOOL_USAGE_GUIDANCE_MAX_CHARS } from './tool-guidance';
4
5
 
5
6
  const CONFIRM_OPS = new Set<ToolConfirmOp>(['>', '>=', '<', '<=', '==', '!=', 'in', 'contains', 'exists']);
6
7
  const SUPPORTED_PARAMETER_LOCATIONS = new Set<ToolParamLocation>(['query', 'path', 'header']);
@@ -110,13 +111,21 @@ export function compileOpenApiTools(specText: string): ToolCompileResult {
110
111
  continue;
111
112
  }
112
113
 
113
- let desc = String(op.summary ?? op.description ?? scope);
114
+ const summary = typeof op.summary === 'string' ? op.summary.trim() : '';
115
+ const description = typeof op.description === 'string' ? op.description.trim() : '';
116
+ let desc = summary || description || scope;
117
+ const guidanceParts = [summary || description || scope];
118
+ if (summary && description && summary !== description) guidanceParts.push(description);
114
119
  if (!op.summary && !op.description) diagnostics.push({ severity: 'warning', path: loc, code: 'missing_summary', message: '缺少 summary/description,已回落到 scope 作为工具描述', suggestion: '补充面向 Agent 的 summary,并用 x-agent-capability.guidance.when_to_use 说明适用场景' });
115
120
  if (!op.operationId) diagnostics.push({ severity: 'warning', path: loc, code: 'missing_operation_id', message: '缺少 operationId,工具名将由 method+path 生成;路径变化会导致工具名变化', suggestion: '为 operation 设置稳定 operationId,作为 AI 工具名' });
116
- if (ann.whenToUse) desc += `。何时用:${ann.whenToUse}`;
117
- if (ann.returns) desc += `。返回:${ann.returns}`;
121
+ if (ann.whenToUse) { desc += `。何时用:${ann.whenToUse}`; guidanceParts.push(`何时用:${ann.whenToUse}`); }
122
+ if (ann.returns) { desc += `。返回:${ann.returns}`; guidanceParts.push(`返回:${ann.returns}`); }
118
123
  const ex = ann.examples.length ? ann.examples[0] : null;
119
- if (ex && typeof ex === 'object') desc += `。示例参数:${JSON.stringify(ex)}`;
124
+ if (ex && typeof ex === 'object') { desc += `。示例参数:${JSON.stringify(ex)}`; guidanceParts.push(`示例参数:${JSON.stringify(ex)}`); }
125
+ const shortDescription = boundedToolText(desc, TOOL_DESCRIPTION_MAX_CHARS);
126
+ const usageGuidance = boundedToolText(guidanceParts.join('\n\n'), TOOL_USAGE_GUIDANCE_MAX_CHARS, TOOL_USAGE_GUIDANCE_MAX_BYTES);
127
+ if (shortDescription.truncated) diagnostics.push({ severity: 'warning', path: loc, code: 'tool_description_truncated', message: `工具短说明超过 ${TOOL_DESCRIPTION_MAX_CHARS} 字符,已截断;使用指导可按工具名读取`, suggestion: '保持 summary 简洁,将前置条件和冲突处理写入 description;机器约束仍需声明在 schema / ACC 字段中' });
128
+ if (usageGuidance.truncated) diagnostics.push({ severity: 'warning', path: loc, code: 'tool_usage_guidance_truncated', message: `工具使用指导超过 ${TOOL_USAGE_GUIDANCE_MAX_CHARS} 字符或 ${TOOL_USAGE_GUIDANCE_MAX_BYTES} UTF-8 字节,详情也只保留有界前缀`, suggestion: '缩短 operation.description / guidance,将重要限制前置,并用业务知识文档承载扩展说明;不要依赖被截断的文字执行机器校验' });
120
129
  const confirmWhen = parseConfirmWhen(ann.confirmWhen, loc, diagnostics);
121
130
  if (confirmWhen === null) continue;
122
131
 
@@ -128,7 +137,9 @@ export function compileOpenApiTools(specText: string): ToolCompileResult {
128
137
  source: 'openapi',
129
138
  method: m,
130
139
  path: p,
131
- description: desc.slice(0, 500),
140
+ description: shortDescription.text,
141
+ ...(shortDescription.truncated ? { descriptionTruncated: true } : {}),
142
+ ...((shortDescription.truncated || usageGuidance.truncated || (summary && description && summary !== description)) ? { usageGuidance } : {}),
132
143
  scope,
133
144
  risk: deriveRisk(ann.riskLevel, m, ro),
134
145
  confirmRequired: ann.confirmRequired,
@@ -0,0 +1,11 @@
1
+ /** Existing database resource used only for fixed, read-only schema probes. */
2
+ export interface SchemaReadinessDatabase {
3
+ query(sql: string): Promise<[unknown, unknown]>;
4
+ }
5
+
6
+ export interface SchemaReadinessCheck {
7
+ database: 'ok' | 'failed';
8
+ /** Internal aggregation only; HTTP responses expose a count, never ledger rows. */
9
+ pendingFilenames: string[];
10
+ migrations: { status: 'ok' | 'pending' | 'failed'; pending: number };
11
+ }
@@ -1,3 +1,5 @@
1
+ import { TOOL_USAGE_GUIDANCE_MAX_BYTES, TOOL_USAGE_GUIDANCE_MAX_CHARS, type ToolUsageGuidance } from './tool-guidance';
2
+
1
3
  export type ToolSourceKind = 'openapi' | 'overlay' | 'sdk' | 'mcp' | 'manual';
2
4
  export type ToolRisk = 'low' | 'medium' | 'high';
3
5
  export type ToolParamLocation = 'query' | 'body' | 'path' | 'header';
@@ -41,6 +43,10 @@ export interface ToolDefinition {
41
43
  method: string;
42
44
  path: string;
43
45
  description: string;
46
+ /** Only the short discovery description was shortened; separate guidance is not implied truncation. */
47
+ descriptionTruncated?: boolean;
48
+ /** Explicitly retrievable, bounded authored guidance; never passed to models as an inline description. */
49
+ usageGuidance?: ToolUsageGuidance;
44
50
  scope: string;
45
51
  risk: ToolRisk;
46
52
  confirmRequired: boolean;
@@ -146,6 +152,26 @@ export function validateToolDefinition(tool: unknown, opts: { path?: string } =
146
152
  if (typeof tool['method'] !== 'string' || !METHODS.has(tool['method'])) fail('invalid_method', 'method 必须是大写 HTTP 方法');
147
153
  if (typeof tool['path'] !== 'string' || !tool['path'].startsWith('/')) fail('invalid_path', 'path 必须以 / 开头');
148
154
  if (typeof tool['description'] !== 'string' || !tool['description'].trim()) fail('invalid_description', 'description 必须是非空字符串', '补充面向 AI 的一句话用途说明');
155
+ if (tool['descriptionTruncated'] !== undefined && typeof tool['descriptionTruncated'] !== 'boolean') fail('invalid_description_truncated', 'descriptionTruncated 必须是 boolean');
156
+ if (tool['usageGuidance'] !== undefined) {
157
+ const guidance = tool['usageGuidance'];
158
+ if (!isRecord(guidance) || typeof guidance['text'] !== 'string' || !guidance['text'].trim()
159
+ || typeof guidance['truncated'] !== 'boolean' || !Number.isSafeInteger(guidance['sourceChars']) || Number(guidance['sourceChars']) < 0
160
+ || !Number.isSafeInteger(guidance['sourceBytes']) || Number(guidance['sourceBytes']) < 0) {
161
+ fail('invalid_usage_guidance', 'usageGuidance 必须包含 text / truncated / sourceChars / sourceBytes');
162
+ } else {
163
+ const retainedChars = Array.from(guidance['text']).length;
164
+ const retainedBytes = Buffer.byteLength(guidance['text'], 'utf8');
165
+ const sourceChars = Number(guidance['sourceChars']);
166
+ const sourceBytes = Number(guidance['sourceBytes']);
167
+ if (retainedChars > TOOL_USAGE_GUIDANCE_MAX_CHARS || retainedBytes > TOOL_USAGE_GUIDANCE_MAX_BYTES
168
+ || sourceChars < retainedChars || sourceBytes < retainedBytes
169
+ || (!guidance['truncated'] && (sourceChars !== retainedChars || sourceBytes !== retainedBytes))
170
+ || (guidance['truncated'] && (sourceChars === retainedChars || sourceBytes === retainedBytes))) {
171
+ fail('invalid_usage_guidance', 'usageGuidance 超过大小限制或截断状态与原始长度不一致');
172
+ }
173
+ }
174
+ }
149
175
  if (typeof tool['scope'] !== 'string' || !tool['scope'].trim()) fail('invalid_scope', 'scope 必须是非空字符串', '为工具声明稳定权限标签,例如 tenant.staff.read');
150
176
  if (!RISKS.includes(tool['risk'] as ToolRisk)) fail('invalid_risk', 'risk 必须是 low / medium / high 之一');
151
177
 
@@ -0,0 +1,77 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { compileOpenApiTools } from './openapi-tools';
4
+ import { hasToolDefinitionErrors, validateToolDefinition } from './tool-definition';
5
+ import { boundedToolText, TOOL_DESCRIPTION_MAX_CHARS, TOOL_USAGE_GUIDANCE_MAX_BYTES, TOOL_USAGE_GUIDANCE_MAX_CHARS } from './tool-guidance';
6
+
7
+ function compile(summary: string | undefined, description: string, extra = {}) {
8
+ return compileOpenApiTools(JSON.stringify({ paths: { '/page': { get: {
9
+ operationId: 'page_get', ...(summary !== undefined ? { summary } : {}), description,
10
+ 'x-agent-capability': { enabled: true, scope: 'page.read', ...extra },
11
+ 'x-business-private': 'must-not-be-guidance',
12
+ } } } }));
13
+ }
14
+
15
+ test('OpenAPI summary remains short while full description and authored guidance remain retrievable', () => {
16
+ const result = compile('读取首页', '必须先绑定页面设置,否则前台不会生效。冲突时读取原修订。', {
17
+ guidance: { when_to_use: '核对首页绑定', returns: '返回当前页面和修订', examples: [{ page_id: 1 }] },
18
+ });
19
+ const tool = result.tools[0]!;
20
+ assert.ok(tool.description.startsWith('读取首页'));
21
+ assert.ok(!tool.description.includes('冲突时'));
22
+ assert.equal(tool.descriptionTruncated, undefined, 'separate detail does not mean summary was truncated');
23
+ assert.match(tool.usageGuidance!.text, /必须先绑定页面设置/);
24
+ assert.match(tool.usageGuidance!.text, /冲突时读取原修订/);
25
+ assert.match(tool.usageGuidance!.text, /核对首页绑定/);
26
+ assert.match(tool.usageGuidance!.text, /返回当前页面和修订/);
27
+ assert.match(tool.usageGuidance!.text, /page_id/);
28
+ assert.doesNotMatch(tool.usageGuidance!.text, /must-not-be-guidance/);
29
+ assert.equal(tool.usageGuidance!.truncated, false);
30
+ assert.equal(hasToolDefinitionErrors(validateToolDefinition(tool)), false);
31
+ });
32
+
33
+ test('long summaries explicitly diagnose short-description truncation and preserve the tail in detail', () => {
34
+ const description = `${'说明'.repeat(300)}。末尾约束:禁止自动重放写操作。`;
35
+ const result = compile(undefined, description);
36
+ const tool = result.tools[0]!;
37
+ assert.equal(Array.from(tool.description).length, TOOL_DESCRIPTION_MAX_CHARS);
38
+ assert.equal(tool.descriptionTruncated, true);
39
+ assert.equal(tool.usageGuidance!.text, description);
40
+ assert.equal(tool.usageGuidance!.truncated, false);
41
+ assert.ok(result.diagnostics.some((d) => d.code === 'tool_description_truncated' && d.severity === 'warning'));
42
+ });
43
+
44
+ test('guidance has simultaneous character and UTF-8 byte budgets, complete characters, and explicit diagnostics', () => {
45
+ for (const source of ['a'.repeat(TOOL_USAGE_GUIDANCE_MAX_CHARS + 1), '中'.repeat(30_000), '𠮷'.repeat(20_000)]) {
46
+ const result = compile('短摘要', source);
47
+ const guidance = result.tools[0]!.usageGuidance!;
48
+ assert.equal(guidance.truncated, true);
49
+ assert.ok(Array.from(guidance.text).length <= TOOL_USAGE_GUIDANCE_MAX_CHARS);
50
+ assert.ok(Buffer.byteLength(guidance.text, 'utf8') <= TOOL_USAGE_GUIDANCE_MAX_BYTES);
51
+ assert.equal(guidance.sourceChars, Array.from(`短摘要\n\n${source}`).length);
52
+ assert.equal(guidance.sourceBytes, Buffer.byteLength(`短摘要\n\n${source}`, 'utf8'));
53
+ assert.equal(guidance.text.includes('\ufffd'), false);
54
+ assert.ok(result.diagnostics.some((d) => d.code === 'tool_usage_guidance_truncated'));
55
+ assert.equal(hasToolDefinitionErrors(validateToolDefinition(result.tools[0])), false);
56
+ }
57
+ const exact = boundedToolText('中'.repeat(100), 100, 300);
58
+ assert.equal(exact.truncated, false);
59
+ const over = boundedToolText('中'.repeat(101), 100, 300);
60
+ assert.equal(over.truncated, true);
61
+ assert.equal(over.text, exact.text);
62
+ });
63
+
64
+ test('empty summary falls back to description and optional guidance cannot bypass its bounds', () => {
65
+ const tool = compile('', '读取当前页面').tools[0]!;
66
+ assert.equal(tool.description, '读取当前页面');
67
+ assert.equal(tool.usageGuidance, undefined);
68
+ assert.equal(tool.descriptionTruncated, undefined);
69
+ assert.ok(validateToolDefinition({ ...tool, usageGuidance: { text: 'a'.repeat(32 * 1024 + 1), truncated: false, sourceChars: 33 * 1024, sourceBytes: 33 * 1024 } })
70
+ .some((d) => d.code === 'invalid_usage_guidance'));
71
+ assert.ok(validateToolDefinition({ ...tool, usageGuidance: { text: 'ok', truncated: false, sourceChars: 3, sourceBytes: 3 } })
72
+ .some((d) => d.code === 'invalid_usage_guidance'), 'an allegedly complete detail must not hide omitted source text');
73
+ const inlineGuidance = compile('读取页面', '', { guidance: { when_to_use: '核对绑定', returns: '当前页面' } }).tools[0]!;
74
+ assert.equal(inlineGuidance.usageGuidance, undefined, 'formatting differences alone must not advertise additional detail');
75
+ assert.match(inlineGuidance.description, /核对绑定/);
76
+ assert.match(inlineGuidance.description, /当前页面/);
77
+ });
@@ -0,0 +1,31 @@
1
+ /** Discovery descriptions stay short; authored usage guidance is read explicitly by name. */
2
+ export const TOOL_DESCRIPTION_MAX_CHARS = 500;
3
+ export const TOOL_USAGE_GUIDANCE_MAX_CHARS = 32 * 1024;
4
+ export const TOOL_USAGE_GUIDANCE_MAX_BYTES = 64 * 1024;
5
+
6
+ export interface ToolUsageGuidance {
7
+ text: string;
8
+ truncated: boolean;
9
+ sourceChars: number;
10
+ sourceBytes: number;
11
+ }
12
+
13
+ /** Remove control characters without losing paragraphs or cutting a UTF-8 character. */
14
+ export function boundedToolText(value: string, maxChars: number, maxBytes = Number.POSITIVE_INFINITY): ToolUsageGuidance {
15
+ const clean = value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ' ').trim();
16
+ let sourceChars = 0;
17
+ let usedBytes = 0;
18
+ let text = '';
19
+ let stopped = false;
20
+ for (const char of clean) {
21
+ sourceChars++;
22
+ const bytes = Buffer.byteLength(char, 'utf8');
23
+ if (!stopped && sourceChars <= maxChars && usedBytes + bytes <= maxBytes) {
24
+ text += char;
25
+ usedBytes += bytes;
26
+ } else {
27
+ stopped = true;
28
+ }
29
+ }
30
+ return { text, truncated: stopped, sourceChars, sourceBytes: Buffer.byteLength(clean, 'utf8') };
31
+ }
@@ -0,0 +1,15 @@
1
+ // Runtime transport budgets; business capability field limits remain independent.
2
+ // Count the UTF-8 bytes of JSON.stringify(arguments), including JSON escaping.
3
+ export const TOOL_ARGUMENTS_MAX_BYTES = 1024 * 1024;
4
+ export const TOOL_INVOCATION_BODY_MAX_BYTES = 2 * 1024 * 1024;
5
+
6
+ export interface ToolInputLimitDetails {
7
+ origin: 'core';
8
+ dispatch: 'not_dispatched';
9
+ limit_scope: 'arguments' | 'request_body';
10
+ max_bytes: number;
11
+ /** Exact serialized arguments size. Never includes argument contents. */
12
+ actual_bytes?: number;
13
+ /** Bytes read before stopping an oversized stream; the full body can be larger. */
14
+ observed_bytes?: number;
15
+ }
@@ -4,6 +4,96 @@ import { test } from 'node:test';
4
4
  import assert from 'node:assert/strict';
5
5
  import { TOOL_DEFINITION_SCHEMA_VERSION, type ToolDefinition } from './tool-definition';
6
6
  import { argsHash, AUDIT_MAX_BYTES, buildToolRuntime, toolCallIdempotencyKey, type ToolExecutionJournalEntry, type ToolRuntimeDeps } from './tools';
7
+ import { TOOL_ARGUMENTS_MAX_BYTES } from './tool-input-limits';
8
+
9
+ function sourceArgsWithBytes(bytes: number): Record<string, unknown> {
10
+ const prefix = 'synthetic-中😀"\\';
11
+ const args = { source: { html: prefix, css: '' } };
12
+ const used = Buffer.byteLength(JSON.stringify(args), 'utf8');
13
+ assert.ok(bytes >= used);
14
+ args.source.html += 'x'.repeat(bytes - used);
15
+ assert.equal(Buffer.byteLength(JSON.stringify(args), 'utf8'), bytes);
16
+ return args;
17
+ }
18
+
19
+ function sourceTool(over: Partial<ToolDefinition> = {}): ToolDefinition {
20
+ return mkTool({ inputSchema: { type: 'object', properties: { source: { type: 'object', properties: {
21
+ html: { type: 'string' }, css: { type: 'string' },
22
+ }, required: ['html', 'css'], additionalProperties: false } }, required: ['source'] }, ...over });
23
+ }
24
+
25
+ test('runtime transport preserves JSON source and signatures through the inclusive 1 MiB budget', async () => {
26
+ const originalFetch = globalThis.fetch;
27
+ const sent: string[] = [];
28
+ globalThis.fetch = async (_url, init) => {
29
+ const body = String(init?.body);
30
+ const headers = new Headers(init?.headers);
31
+ const ts = Number(headers.get('x-bailing-timestamp'));
32
+ const { signToolCall } = await import('./tools');
33
+ assert.equal(headers.get('x-bailing-signature'), signToolCall('s', ts, 'POST', '/create', body, 'u1', 'job1'));
34
+ sent.push(body);
35
+ return new Response('{"ok":true}', { status: 200 });
36
+ };
37
+ try {
38
+ for (const bytes of [4395, 5183, 16 * 1024, 64 * 1024, 256 * 1024, TOOL_ARGUMENTS_MAX_BYTES]) {
39
+ const args = sourceArgsWithBytes(bytes);
40
+ const out = await mkRuntime(sourceTool({ readonly: true })).invoke('create_thing', args);
41
+ assert.equal(out.ok, true);
42
+ assert.equal(sent.at(-1), JSON.stringify(args));
43
+ assert.deepEqual(JSON.parse(sent.at(-1)!), args);
44
+ }
45
+ assert.equal(sent.length, 6);
46
+ } finally { globalThis.fetch = originalFetch; }
47
+ });
48
+
49
+ test('runtime over-limit rejection precedes every approval, rate and dispatch side effect', async () => {
50
+ const audits: Array<Record<string, unknown>> = [];
51
+ const forbidden = async (): Promise<never> => { throw new Error('must not reach a governed side effect'); };
52
+ const originalFetch = globalThis.fetch; globalThis.fetch = forbidden;
53
+ try {
54
+ const runtime = mkRuntime(sourceTool({ risk: 'high' }), async (_event, detail) => { audits.push(detail); }, undefined, {
55
+ rateLimitAll: forbidden, beforeDispatch: forbidden,
56
+ approvals: { consumeApproved: forbidden, findPending: forbidden, findApprovedAnyArgs: forbidden, create: forbidden, notify: forbidden },
57
+ idempotency: { get: forbidden, reserve: forbidden, recordResponse: forbidden, complete: forbidden, markUncertain: forbidden, markEvidenceDegraded: forbidden },
58
+ });
59
+ const args = sourceArgsWithBytes(TOOL_ARGUMENTS_MAX_BYTES + 1);
60
+ const out = await runtime.invoke('create_thing', args);
61
+ assert.equal(out.error, 'arguments_too_large'); assert.equal(out.status, 413);
62
+ assert.equal(out.dispatch, 'not_dispatched'); assert.equal(out.origin, 'core');
63
+ assert.equal(out.governance_state, 'rejected_before_dispatch'); assert.equal(out.auto_retry_allowed, false);
64
+ assert.equal(out.actual_bytes, TOOL_ARGUMENTS_MAX_BYTES + 1); assert.equal(out.max_bytes, TOOL_ARGUMENTS_MAX_BYTES);
65
+ assert.equal(out.limit_scope, 'arguments');
66
+ assert.equal(audits.length, 1); assert.ok(JSON.stringify(audits).length < 300);
67
+ assert.equal(JSON.stringify(out).includes('synthetic-'), false);
68
+ } finally { globalThis.fetch = originalFetch; }
69
+ });
70
+
71
+ test('large approval keeps exact frozen arguments and resumes once while notification is only a labelled view', async () => {
72
+ const args = sourceArgsWithBytes(TOOL_ARGUMENTS_MAX_BYTES);
73
+ const encoded = JSON.stringify(args); const hash = argsHash(args);
74
+ let approved = false, consumed = 0, calls = 0; const snapshots: any[] = [], notices: any[] = [];
75
+ const runtime = mkRuntime(sourceTool({ risk: 'high', confirmPrompt: '{source}' }), undefined, undefined, {
76
+ approvals: {
77
+ consumeApproved: async (_tool, seen) => { assert.equal(seen, hash); if (!approved) return null; consumed++; return 7; },
78
+ findPending: async () => null, findApprovedAnyArgs: async () => null,
79
+ create: async snap => { snapshots.push(snap); return 7; },
80
+ notify: async (_id, snap) => { notices.push(snap); },
81
+ },
82
+ });
83
+ const originalFetch = globalThis.fetch;
84
+ globalThis.fetch = async (_url, init) => { calls++; assert.equal(String(init?.body), encoded); return new Response('{"ok":true}'); };
85
+ try {
86
+ assert.equal((await runtime.invoke('create_thing', args)).governance_state, 'awaiting_approval');
87
+ assert.equal(calls, 0); assert.equal(snapshots[0].args_json, encoded); assert.equal(snapshots[0].args_hash, hash);
88
+ assert.equal(notices[0].args_truncated, true); assert.equal(notices[0].args_bytes, TOOL_ARGUMENTS_MAX_BYTES);
89
+ assert.equal(notices[0].args_hash, hash); assert.ok(Buffer.byteLength(notices[0].args_json, 'utf8') <= 1000);
90
+ assert.equal(JSON.parse(notices[0].args_json).truncated, true);
91
+ approved = true;
92
+ assert.equal((await runtime.invoke('create_thing', JSON.parse(snapshots[0].args_json))).ok, true);
93
+ assert.equal((await runtime.invoke('create_thing', args)).ok, true);
94
+ assert.equal(calls, 1); assert.equal(consumed, 1);
95
+ } finally { globalThis.fetch = originalFetch; }
96
+ });
7
97
 
8
98
  function mkTool(over: Partial<ToolDefinition>): ToolDefinition {
9
99
  return {
@@ -8,6 +8,7 @@ import { readResponseBody, truncateUtf8 } from '../platform/http-body';
8
8
  import type { ToolProvider } from './types';
9
9
  import { schemaAtPath, schemaTypes, valueMatchesSchemaType, type ToolConfirmCondition, type ToolDefinition } from './tool-definition';
10
10
  import { toolSummary } from './tool-definition';
11
+ import { TOOL_ARGUMENTS_MAX_BYTES } from './tool-input-limits';
11
12
 
12
13
  /** 路由 allow 白名单匹配:精确 scope 或前缀通配("tenant.staff.*")。 */
13
14
  export function scopeAllowed(scope: string, allow: string[]): boolean {
@@ -97,15 +98,17 @@ function isJsonOmitted(v: unknown): boolean {
97
98
  return v === undefined || typeof v === 'function' || typeof v === 'symbol';
98
99
  }
99
100
 
100
- function normalizeToolArgs(args: Record<string, unknown>): { ok: true; args: Record<string, unknown> } | { ok: false; error: string } {
101
+ function normalizeToolArgs(args: Record<string, unknown>): { ok: true; args: Record<string, unknown>; encoded: string; bytes: number } | { ok: false; error: string; bytes?: number } {
101
102
  try {
102
103
  // 以实际 HTTP JSON 语义为准:对象中的 undefined 被省略、数组中的 undefined 变为 null。
103
104
  // 审批快照、幂等哈希和外发请求必须消费同一份规范化参数。
104
105
  const encoded = JSON.stringify(args);
105
106
  if (!encoded) return { ok: false, error: 'tool_args_not_json_object' };
107
+ const bytes = Buffer.byteLength(encoded, 'utf8');
108
+ if (bytes > TOOL_ARGUMENTS_MAX_BYTES) return { ok: false, error: 'arguments_too_large', bytes };
106
109
  const decoded: unknown = JSON.parse(encoded);
107
110
  if (!isRecord(decoded)) return { ok: false, error: 'tool_args_not_json_object' };
108
- return { ok: true, args: decoded };
111
+ return { ok: true, args: decoded, encoded, bytes };
109
112
  } catch {
110
113
  return { ok: false, error: 'tool_args_not_json_serializable' };
111
114
  }
@@ -331,6 +334,12 @@ export interface ToolInvokeResult {
331
334
  retry_after_ms?: number;
332
335
  rate_limit?: ToolRateLimitFeedback;
333
336
  approval_id?: number;
337
+ error?: 'arguments_too_large';
338
+ origin?: 'core';
339
+ dispatch?: 'not_dispatched';
340
+ actual_bytes?: number;
341
+ max_bytes?: number;
342
+ limit_scope?: 'arguments';
334
343
  }
335
344
 
336
345
  /**
@@ -416,10 +425,36 @@ export interface ApprovalIntentSnap {
416
425
  path: string;
417
426
  args_json: string;
418
427
  args_hash: string;
428
+ /** Notification previews only; persisted execution arguments remain complete. */
429
+ args_bytes?: number;
430
+ args_truncated?: boolean;
419
431
  summary?: string;
420
432
  confirm_when?: ConfirmHit;
421
433
  }
422
434
 
435
+ const APPROVAL_NOTIFICATION_ARGUMENTS_MAX_BYTES = 1000;
436
+
437
+ /** Bounded, explicitly labelled notification view; never an execution snapshot. */
438
+ export function approvalNotificationSnapshot(snap: ApprovalIntentSnap): ApprovalIntentSnap {
439
+ const encodedBytes = Buffer.byteLength(snap.args_json, 'utf8');
440
+ const bytes = snap.args_truncated && Number.isSafeInteger(snap.args_bytes) && Number(snap.args_bytes) >= encodedBytes
441
+ ? Number(snap.args_bytes) : encodedBytes;
442
+ const base = { ...snap, ...(snap.summary ? { summary: truncateUtf8(snap.summary, 512) } : {}) };
443
+ if (encodedBytes <= APPROVAL_NOTIFICATION_ARGUMENTS_MAX_BYTES) return { ...base, args_bytes: bytes };
444
+ return {
445
+ ...base,
446
+ args_json: JSON.stringify({
447
+ preview: truncateUtf8(snap.args_json, 384),
448
+ truncated: true,
449
+ args_bytes: bytes,
450
+ args_hash: snap.args_hash,
451
+ note: 'Full arguments are available in the authorized approval console.',
452
+ }),
453
+ args_bytes: bytes,
454
+ args_truncated: true,
455
+ };
456
+ }
457
+
423
458
  export interface ToolRuntimeDeps {
424
459
  provider: ToolProvider;
425
460
  allowedTools: ToolDefinition[]; // 已过双闸的清单
@@ -512,7 +547,15 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
512
547
  if (!t) return { ok: false, text: `工具 ${name} 不在本路由白名单内,调用被拒。`, status: 0, governance_state: 'rejected_before_dispatch', auto_retry_allowed: false };
513
548
  const normalized = normalizeToolArgs(args);
514
549
  if (!normalized.ok) {
515
- await d.audit('tool_blocked', { tool: name, scope: t.scope, reason: normalized.error }).catch(() => undefined);
550
+ const details = normalized.error === 'arguments_too_large'
551
+ ? { actual_bytes: normalized.bytes!, max_bytes: TOOL_ARGUMENTS_MAX_BYTES, limit_scope: 'arguments' as const }
552
+ : {};
553
+ await d.audit('tool_blocked', { tool: name, scope: t.scope, reason: normalized.error, ...details }).catch(() => undefined);
554
+ if (normalized.error === 'arguments_too_large') return {
555
+ ok: false, status: 413, text: `Tool arguments contain ${normalized.bytes} bytes; the limit is ${TOOL_ARGUMENTS_MAX_BYTES} bytes. The invocation was not dispatched.`,
556
+ error: 'arguments_too_large', origin: 'core', dispatch: 'not_dispatched',
557
+ governance_state: 'rejected_before_dispatch', auto_retry_allowed: false, ...details,
558
+ };
516
559
  return { ok: false, text: `工具 ${name} 参数不是合法 JSON 对象,调用已拒绝。请按工具参数 schema 重新传参。`, status: 0, governance_state: 'rejected_before_dispatch', auto_retry_allowed: false };
517
560
  }
518
561
  const callArgs = normalized.args;
@@ -644,18 +687,18 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
644
687
  await d.audit('tool_args_drift', { tool: name, approval_id: drifted.id, got_args: JSON.stringify(callArgs).slice(0, 500) }).catch(() => undefined);
645
688
  return { ok: false, text: `该工具已有人工批准的调用(审批单 ${drifted.id}),但你本次的参数与批准的不一致。请使用原审批快照续执行,不要更改参数。`, status: 0, governance_state: 'rejected_before_dispatch', auto_retry_allowed: false };
646
689
  }
647
- const argsJson = JSON.stringify(callArgs);
690
+ const argsJson = normalized.encoded;
648
691
  const reason = approvalReason(t, confirmHit);
649
- const summary = t.confirmPrompt ? t.confirmPrompt.replace(/\{(\w+)\}/g, (_, k) => String(callArgs[k] ?? `{${k}}`)) : undefined;
692
+ const summary = t.confirmPrompt ? truncateUtf8(t.confirmPrompt.replace(/\{(\w+)\}/g, (_, k) => String(callArgs[k] ?? `{${k}}`)), 512) : undefined;
650
693
  const snap: ApprovalIntentSnap = {
651
694
  tool: name, scope: t.scope, risk: t.risk, policy: approvalPolicy(t, confirmHit), reason,
652
- method: t.method, path: t.path, args_json: argsJson.slice(0, 4096), args_hash: hash,
695
+ method: t.method, path: t.path, args_json: argsJson, args_hash: hash,
653
696
  ...(summary ? { summary } : {}),
654
697
  ...(confirmHit ? { confirm_when: confirmHit } : {}),
655
698
  };
656
699
  const id = await d.approvals.create(snap);
657
700
  await d.audit('tool_approval_pending', { approval_id: id, tool: name, scope: t.scope, risk: t.risk, confirm_required: t.confirmRequired, ...(confirmHit ? { confirm_when: confirmHit } : {}) }).catch(() => undefined);
658
- await d.approvals.notify(id, { ...snap, args_json: argsJson.slice(0, 1000) }).catch(() => undefined);
701
+ await d.approvals.notify(id, approvalNotificationSnapshot(snap)).catch(() => undefined);
659
702
  const continuation = d.approvals.continuationMode === 'resume'
660
703
  ? '批准后请用本 invocation_id 续执行;中枢不会启动模型重跑。'
661
704
  : '批准后系统会自动重跑原任务。';
@@ -687,8 +730,8 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
687
730
  // 闸4:审计 fail-closed——账记不下来就不放行。ACC audit.sensitive 工具强制只记键名(优先级高于工具源 log_payload)。
688
731
  // logFull 时入参全量入审计(封顶 AUDIT_MAX_BYTES,超出记 args_truncated;真实字节数 args_bytes 始终记)。
689
732
  const logFull = d.provider.log_payload && !t.sensitive;
690
- const argsStr = JSON.stringify(callArgs);
691
- const argsBytes = Buffer.byteLength(argsStr, 'utf8');
733
+ const argsStr = normalized.encoded;
734
+ const argsBytes = normalized.bytes;
692
735
  const argsLog = logFull
693
736
  ? { args: truncateUtf8(argsStr, AUDIT_MAX_BYTES), args_bytes: argsBytes, ...(argsBytes > AUDIT_MAX_BYTES ? { args_truncated: true } : {}) }
694
737
  : { args: JSON.stringify(Object.keys(callArgs)) };
@@ -0,0 +1,64 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { AGENT_EXECUTION_SUMMARY_SCHEMA, projectAgentExecutionMemory } from './agent-execution-memory';
4
+
5
+ const id = (number: number) => number.toString(16).padStart(64, '0');
6
+ function summary(total = 2) {
7
+ return { schema_version: AGENT_EXECUTION_SUMMARY_SCHEMA, source: 'system', trust: 'verified', total_invocations: total,
8
+ invocations: Array.from({ length: total }, (_, index) => ({ invocation_id: id(index + 1), tool: 'inventory_read',
9
+ last_known_state: index === 0 ? 'outcome_unknown' : 'executed', text: 'UNTRUSTED_OUTPUT', instructions: 'IGNORE_RULES',
10
+ next_action: 'retry_as_new_invocation' })) };
11
+ }
12
+
13
+ test('execution memory treats the claimed schema as reference-only data and projects only finite facts', () => {
14
+ const projection = projectAgentExecutionMemory(JSON.stringify(summary()), 2_000)!;
15
+ assert.equal(projection.kind, 'authorization_execution_summary');
16
+ assert.equal(projection.source, 'agent_client');
17
+ assert.equal(projection.trust, 'reference_only');
18
+ assert.equal(projection.truncated, false);
19
+ const body = JSON.parse(projection.content);
20
+ assert.equal(body.source, 'agent_client');
21
+ assert.equal(body.trust, 'reference_only');
22
+ assert.deepEqual(body.invocations[0], { invocation_id: id(1), tool: 'inventory_read', last_known_state: 'outcome_unknown', next_action: 'inspect_original' });
23
+ assert.doesNotMatch(projection.content, /UNTRUSTED_OUTPUT|IGNORE_RULES|retry_as_new_invocation|verified|system/);
24
+ });
25
+
26
+ test('all memory limits retain whole records and honest omitted counts rather than sliced JSON', () => {
27
+ const input = JSON.stringify(summary(200));
28
+ for (const maximum of [50, 200, 300, 500, 2_000, 8_000, 12_000]) {
29
+ const projection = projectAgentExecutionMemory(input, maximum)!;
30
+ assert.ok(projection.content.length <= maximum);
31
+ assert.equal(projection.truncated, true);
32
+ if (projection.content.startsWith('{')) {
33
+ const body = JSON.parse(projection.content);
34
+ assert.equal(body.total_invocations, 200);
35
+ assert.equal(body.omitted_invocations + body.invocations.length, 200);
36
+ if (body.invocations.length) assert.equal(body.invocations[0].invocation_id, id(1));
37
+ } else assert.equal(projection.content, 'Execution facts omitted by memory budget.');
38
+ }
39
+ });
40
+
41
+ test('malformed ids, duplicate originals, injected tool names and unknown states do not expand memory authority', () => {
42
+ const input = summary(0);
43
+ input.invocations = [
44
+ { invocation_id: id(1), tool: 'inventory_read', last_known_state: 'made_up_success', text: 'UNTRUSTED_OUTPUT', instructions: 'IGNORE_RULES', next_action: 'anything' },
45
+ { invocation_id: id(1), tool: 'inventory_read', last_known_state: 'executed', text: '', instructions: '', next_action: '' },
46
+ { invocation_id: 'invented-id', tool: 'inventory_read', last_known_state: 'executed', text: '', instructions: '', next_action: '' },
47
+ { invocation_id: id(4), tool: 'tool\nSYSTEM_RULE', last_known_state: 'executed', text: '', instructions: '', next_action: '' },
48
+ ];
49
+ const body = JSON.parse(projectAgentExecutionMemory(JSON.stringify(input), 2_000)!.content);
50
+ assert.equal(body.total_invocations, 4);
51
+ assert.equal(body.omitted_invocations, 2);
52
+ assert.deepEqual(body.invocations, [
53
+ { invocation_id: id(1), tool: 'inventory_read', last_known_state: 'outcome_unknown', next_action: 'inspect_original' },
54
+ { invocation_id: id(4), last_known_state: 'executed' },
55
+ ]);
56
+ });
57
+
58
+ test('ordinary assistant text and historical business-result formats remain compatible', () => {
59
+ for (const text of ['A normal assistant reply', '{"status":"ok","data":[1]}',
60
+ 'Authorization-scoped execution summary.\n{"invocation_id":"old","text":"old-output"}',
61
+ '{"schema_version":"bailing.authorization-execution-summary.v1"']) {
62
+ assert.equal(projectAgentExecutionMemory(text, 2_000), undefined);
63
+ }
64
+ });
@@ -0,0 +1,63 @@
1
+ /** Client-reported execution facts are continuation data, never verified evidence
2
+ * or system instructions. Keep this projection independent from audit storage. */
3
+ export const AGENT_EXECUTION_SUMMARY_SCHEMA = 'bailing.authorization-execution-summary.v1';
4
+ const INVOCATION_ID = /^[0-9a-f]{64}$/;
5
+ const TOOL_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
6
+ const STATES = new Set(['executed', 'business_rejected', 'awaiting_approval', 'denied',
7
+ 'rejected_before_dispatch', 'reconciliation_required', 'in_progress', 'outcome_unknown', 'not_dispatched']);
8
+ const UNRESOLVED = new Set(['awaiting_approval', 'in_progress', 'reconciliation_required', 'outcome_unknown']);
9
+
10
+ function isRecord(value: unknown): value is Record<string, unknown> {
11
+ return !!value && typeof value === 'object' && !Array.isArray(value);
12
+ }
13
+
14
+ /** Recognizes only the explicit new client format; ordinary assistant text keeps
15
+ * its existing behavior. Callers must not apply this to user messages. */
16
+ export function projectAgentExecutionMemory(content: string, maximum: number): {
17
+ content: string;
18
+ kind: 'authorization_execution_summary';
19
+ source: 'agent_client';
20
+ trust: 'reference_only';
21
+ truncated: boolean;
22
+ } | undefined {
23
+ let parsed: unknown;
24
+ try { parsed = JSON.parse(content); } catch { return undefined; }
25
+ if (!isRecord(parsed) || parsed['schema_version'] !== AGENT_EXECUTION_SUMMARY_SCHEMA) return undefined;
26
+ const raw = Array.isArray(parsed['invocations']) ? parsed['invocations'] : [];
27
+ const claimedTotal = Number.isSafeInteger(parsed['total_invocations']) && Number(parsed['total_invocations']) >= 0
28
+ ? Math.min(Number(parsed['total_invocations']), 1_000_000_000) : 0;
29
+ const total = Math.max(claimedTotal, raw.length);
30
+ const summary = {
31
+ schema_version: AGENT_EXECUTION_SUMMARY_SCHEMA,
32
+ source: 'agent_client',
33
+ trust: 'reference_only',
34
+ total_invocations: total,
35
+ omitted_invocations: total,
36
+ invocations: [] as Array<Record<string, unknown>>,
37
+ };
38
+ const metadata = { kind: 'authorization_execution_summary', source: 'agent_client', trust: 'reference_only' } as const;
39
+ if (JSON.stringify(summary).length > maximum) {
40
+ return { ...metadata, content: 'Execution facts omitted by memory budget.', truncated: true };
41
+ }
42
+ const seen = new Set<string>();
43
+ for (const entry of raw) {
44
+ if (!isRecord(entry) || typeof entry['invocation_id'] !== 'string' || !INVOCATION_ID.test(entry['invocation_id']) || seen.has(entry['invocation_id'])) continue;
45
+ seen.add(entry['invocation_id']);
46
+ const state = typeof entry['last_known_state'] === 'string' && STATES.has(entry['last_known_state'])
47
+ ? entry['last_known_state'] : 'outcome_unknown';
48
+ const fact = {
49
+ invocation_id: entry['invocation_id'],
50
+ ...(typeof entry['tool'] === 'string' && TOOL_NAME.test(entry['tool']) ? { tool: entry['tool'] } : {}),
51
+ last_known_state: state,
52
+ ...(UNRESOLVED.has(state) ? { next_action: 'inspect_original' } : {}),
53
+ };
54
+ summary.invocations.push(fact);
55
+ summary.omitted_invocations = total - summary.invocations.length;
56
+ if (JSON.stringify(summary).length > maximum) {
57
+ summary.invocations.pop();
58
+ summary.omitted_invocations = total - summary.invocations.length;
59
+ break;
60
+ }
61
+ }
62
+ return { ...metadata, content: JSON.stringify(summary), truncated: summary.omitted_invocations > 0 };
63
+ }
@@ -2,6 +2,7 @@ import type { AuditEntry, Job, JobStatus } from '../contracts/types';
2
2
  import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../contracts/approval-continuation';
3
3
  import type { DeliveryRequeueInput, DeliveryRequeueOutcome } from '../contracts/delivery-replay';
4
4
  import type { NotificationOutboxRepository } from '../contracts/notification-outbox';
5
+ import type { SchemaReadinessDatabase } from '../contracts/schema-readiness';
5
6
 
6
7
  export interface JobOperationalMetricsSnapshot {
7
8
  byStatus: Record<JobStatus, number>;
@@ -51,6 +52,8 @@ export interface RuntimeLockRepository {
51
52
  }
52
53
 
53
54
  export interface RuntimeStateStore extends JobRepository, AuditLedger, RuntimeLockRepository {
55
+ /** Optional extension contract; MySQL readiness fails closed if its actual DB cannot be checked. */
56
+ readonly schemaReadinessDb?: SchemaReadinessDatabase;
54
57
  readonly notificationOutbox?: NotificationOutboxRepository;
55
58
  /** Fenced terminal transition and notification intentions in the same durable write. */
56
59
  completeJobWithNotifications?(original: Job, patch: Partial<Job>, context?: { brandName?: string }): Promise<Job | null>;
@@ -111,6 +111,8 @@ export class ObservabilityLedger {
111
111
  const off = Math.max(Math.floor(Number(offset) || 0), 0);
112
112
  const [rows] = await this.pool.query(
113
113
  'SELECT job_id,request_id,status,target,profile,project,source,client_app_id,session_id,input_preview,' +
114
+ 'JSON_UNQUOTE(JSON_EXTRACT(dispatch,"$.route_key")) AS route_key,' +
115
+ 'JSON_UNQUOTE(JSON_EXTRACT(dispatch,"$.route_name")) AS route_name,' +
114
116
  'JSON_UNQUOTE(JSON_EXTRACT(metadata,"$.visitor_uid")) AS visitor_uid,' +
115
117
  'JSON_UNQUOTE(JSON_EXTRACT(metadata,"$.thread_id")) AS thread_id,' +
116
118
  'JSON_UNQUOTE(JSON_EXTRACT(result,"$.report.severity")) AS severity,' +