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
@@ -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,' +
@@ -0,0 +1,29 @@
1
+ import type { SchemaReadinessCheck, SchemaReadinessDatabase } from '../../core/contracts/schema-readiness';
2
+ import { BAILINGHUB_CORE_ARTIFACT_V1 } from '../../kernel-api/v1/artifact';
3
+
4
+ const failedMigrations = (): SchemaReadinessCheck => ({ database: 'ok', pendingFilenames: [], migrations: { status: 'failed', pending: 0 } });
5
+
6
+ /** No DDL, checksum backfill or new connections. The installed artifact owns the inventory. */
7
+ export async function inspectCoreSchemaReadiness(database: SchemaReadinessDatabase): Promise<SchemaReadinessCheck> {
8
+ try { await database.query('SELECT 1'); }
9
+ catch { return { database: 'failed', pendingFilenames: [], migrations: { status: 'failed', pending: 0 } }; }
10
+ try {
11
+ const [payload] = await database.query('SELECT filename, checksum_sha256 FROM bz_schema_migrations ORDER BY filename');
12
+ if (!Array.isArray(payload)) return failedMigrations();
13
+ const artifact = BAILINGHUB_CORE_ARTIFACT_V1;
14
+ const known = new Map([...artifact.migrations, ...artifact.retiredMigrations].map(file => [file.filename, file.checksumSha256]));
15
+ const applied = new Set<string>();
16
+ for (const row of payload) {
17
+ if (!row || typeof row !== 'object' || Array.isArray(row)) return failedMigrations();
18
+ const { filename, checksum_sha256: checksum } = row as Record<string, unknown>;
19
+ if (typeof filename !== 'string' || applied.has(filename) || !known.has(filename)
20
+ || typeof checksum !== 'string' || !/^[a-f0-9]{64}$/i.test(checksum.trim())
21
+ || checksum.trim().toLowerCase() !== known.get(filename)) return failedMigrations();
22
+ applied.add(filename);
23
+ }
24
+ // Retired records are optional historical evidence, never pending work.
25
+ const pendingFilenames = artifact.migrations.filter(file => !applied.has(file.filename)).map(file => file.filename);
26
+ const pending = pendingFilenames.length;
27
+ return { database: 'ok', pendingFilenames, migrations: { status: pending ? 'pending' : 'ok', pending } };
28
+ } catch { return failedMigrations(); }
29
+ }
@@ -24,6 +24,9 @@ export class MysqlStore implements RuntimeStateStore {
24
24
  this.poolOwner = poolOwner ?? new MysqlPoolOwner(cfg);
25
25
  }
26
26
 
27
+ /** Reuses the store's existing pool; readiness never opens a fallback connection. */
28
+ get schemaReadinessDb(): Pool { return this.pool; }
29
+
27
30
  async init(): Promise<void> {
28
31
  this.pool = await this.poolOwner.get();
29
32
  }
@@ -26,7 +26,14 @@ export interface UsageServiceConfig {
26
26
  model: string;
27
27
  providerScope: string;
28
28
  maxInputBytes: number;
29
+ /** Operator service ceiling, not the model vendor's maximum capability. */
29
30
  maxOutputTokens: number;
31
+ /** Explicit output policy is an all-or-none group; absent means legacy behavior. */
32
+ defaultOutputTokens?: number;
33
+ outputTokenParameter?: 'max_tokens' | 'max_completion_tokens';
34
+ outputBudgetScope?: 'completion_total' | 'final_answer';
35
+ /** Verified vendor maximum for the configured parameter/scope; unknown remains absent. */
36
+ modelMaxOutputTokens?: number;
30
37
  timeoutMs: number;
31
38
  /** Operator-verified model metadata; absence means unknown, never a guessed context window. */
32
39
  contextWindowTokens?: number;
@@ -27,6 +27,8 @@ export function usageHttpError(res: ServerResponse, error: unknown, context: { d
27
27
  const message = known ? error.message : invalid ? '请求格式不正确或超过大小限制。' : '用量服务暂时不可用,请保留原请求重试。';
28
28
  const feedback = { schema: 'bailing.usage-feedback.v1', origin: 'hub_usage', code, dispatch, next_action, retryable: dispatch === 'not_dispatched' && next_action === 'retry_original',
29
29
  ...(known && error.details?.input_limit ? { input_limit: error.details.input_limit } : {}),
30
+ ...(known && code === 'USAGE_OUTPUT_LIMIT' && error.details?.output_limit ? { output_limit: error.details.output_limit } : {}),
31
+ ...(known && code === 'USAGE_OUTPUT_PARAMETER_MISMATCH' && error.details?.output_budget ? { output_budget: error.details.output_budget } : {}),
30
32
  ...(Number.isSafeInteger(resetAt) ? { resetAt, reset_at: resetAt } : {}), ...(context.operation_id ? { operation_id: context.operation_id } : {}) };
31
33
  send(res, known ? error.status : error instanceof PayloadTooLargeError ? 413 : invalid ? 400 : 503,
32
34
  { ...feedback, schema: 'bailing.usage-error.v1', error: code, message, feedback,
@@ -0,0 +1,109 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createHash } from 'node:crypto';
4
+ import { runModelRequest, type ModelInput } from './model-gateway';
5
+ import { getBillingRepository } from './billing-repository';
6
+ import { referencePricing } from './pricing';
7
+ import type { UsageRepository } from './repository';
8
+ import type { UsageSessionContext } from './identity';
9
+ import type { UsageService } from './contracts';
10
+ import type { BillingRequest } from './billing-contracts';
11
+
12
+ /** Gateway ordering acceptance with synthetic persistence/pricing ports. Not a DB/transaction proof. */
13
+ function fixture() {
14
+ const actor: UsageSessionContext = { accountId: 'account', userId: 'user', sessionId: 'session', serviceId: 'model',
15
+ issuerId: 'synthetic', expiresAt: Date.now() + 60000 };
16
+ const service: UsageService = { id: 'model', label: 'Synthetic', state: 'active', revision: 1,
17
+ config: { credential: 'synthetic', model: 'synthetic', providerScope: 'synthetic', maxInputBytes: 65536,
18
+ maxOutputTokens: 64, timeoutMs: 5000 } };
19
+ const repository = { backgroundWork: { acceptingRequests: true }, getService: async () => service } as unknown as UsageRepository;
20
+ const ledger = getBillingRepository(repository), records = new Map<string, BillingRequest>();
21
+ const price = { source: 'openrouter' as const, modelId: 'synthetic/model', endpointId: 'synthetic', currency: 'USD' as const,
22
+ fetchedAt: Date.now(), lines: [{ billable: 'prompt', unit: 'token' as const, costUsd: '1' }, { billable: 'completion', unit: 'token' as const, costUsd: '1' }] };
23
+ const allowance = { mode: 'credits' as const, priceUsd: 1000, duration: { unit: 'month' as const, count: 1 } };
24
+ ledger.summary = async () => ({ schema: 'bailing.billing-summary.v1', accountId: actor.accountId,
25
+ grant: { id: 'grant', accountId: actor.accountId, planId: 'plan', planRevision: 1, label: 'Synthetic', revision: 1,
26
+ state: 'active', sourceOwner: 'synthetic', startsAt: Date.now(), expiresAt: null, config: allowance },
27
+ plan: { id: 'plan', label: 'Synthetic', revision: 1, serviceIds: ['model'], multiplier: 1 },
28
+ availableUsd: 1000, consumedUsd: 0, currentPeriodConsumedUsd: 0, overageUsd: 0, resetAt: null,
29
+ expiresAt: null, pendingRequests: 0, presentation: { schema: 'bailing.usage-presentation.v1', kind: 'credits',
30
+ state: 'active', remaining: 1000, total: 1000, displayValue: '1000' } });
31
+ ledger.findRequest = async (_actor, operationId) => records.get(operationId) ?? null;
32
+ ledger.admit = async input => {
33
+ const record: BillingRequest = { id: input.operationId, operationId: input.operationId, accountId: actor.accountId, userId: actor.userId,
34
+ sessionId: actor.sessionId, model: input.model, grantId: 'grant', grantRevision: 1, grantConfig: allowance,
35
+ periodStart: Date.now(), periodEnd: null, cancelledAt: null, updatedAt: Date.now(),
36
+ serviceId: input.serviceId, conversationId: input.conversationId, turnId: input.turnId, requestHash: input.requestHash,
37
+ serviceConfig: structuredClone(input.serviceConfig), serviceRevision: input.expectedServiceRevision,
38
+ billingRate: { planId: 'plan', planRevision: 1, multiplier: 1, price }, revision: 1,
39
+ state: 'admitted', resultState: 'pending', billingState: 'pending', fence: null, response: null, resultHash: null,
40
+ usage: null, rawUsage: null, referenceCostUsd: null, billedUsd: null, overageUsd: null, createdAt: Date.now() };
41
+ records.set(input.operationId, record); return { ...record, created: true };
42
+ };
43
+ ledger.commitDispatch = async id => { const record = records.get(id)!; record.state = 'dispatch_committed'; record.fence = 'synthetic-fence'; return record; };
44
+ ledger.recordCompletion = async (id, _fence, input) => {
45
+ const record = records.get(id)!;
46
+ Object.assign(record, { state: 'completed', resultState: 'complete', response: input.response,
47
+ resultHash: createHash('sha256').update(JSON.stringify(input.response)).digest('hex'), rawUsage: input.rawUsage ?? null,
48
+ usage: input.usage ? { ...input.usage, totalTokens: input.usage.inputTokens + input.usage.outputTokens } : null });
49
+ return record;
50
+ };
51
+ ledger.markUnknown = async (id, _fence, _reason) => {
52
+ const record = records.get(id)!; record.state = 'unknown'; record.resultState = 'unknown'; return record;
53
+ };
54
+ referencePricing(repository).snapshot = async () => price;
55
+ const bodies: Record<string, unknown>[] = [];
56
+ let mode: 'length' | 'stop' | 'lost' = 'length';
57
+ const fetcher: typeof fetch = async (_url, init) => {
58
+ bodies.push(JSON.parse(String(init?.body)));
59
+ if (mode === 'lost') throw new Error('Synthetic transport loss after dispatch');
60
+ return new Response(JSON.stringify({ id: `supplier-${bodies.length}`, choices: [{ index: 0,
61
+ message: { role: 'assistant', content: mode === 'length' ? '第一步已完成;第二步' : '第二步已完成。' }, finish_reason: mode }],
62
+ usage: { prompt_tokens: 10, completion_tokens: 8, total_tokens: 18 } }), { headers: { 'content-type': 'application/json' } });
63
+ };
64
+ const deps = { usage: repository, cfg: { llmCredentials: { synthetic: { base_url: 'http://127.0.0.1:1/v1', api_key: 'SYNTHETIC_ONLY' } } }, fetcher };
65
+ const input = (operation_id: string): ModelInput => ({ operation_id, conversation_id: 'conversation', turn_id: 'task',
66
+ messages: [{ role: 'user', content: 'Synthetic multi-step task' }] });
67
+ return { actor, ledger, records, bodies, deps, input, setMode(value: typeof mode) { mode = value; } };
68
+ }
69
+
70
+ test('length is a completed provider exchange; original recovery never dispatches and a host continuation is a distinct request', async () => {
71
+ const h = fixture(), original = h.input('original');
72
+ original.messages.push({ role: 'assistant', content: null, tool_calls: [{ id: 'completed-call', type: 'function',
73
+ function: { name: 'inspect_step_1', arguments: '{}' } }] },
74
+ { role: 'tool', tool_call_id: 'completed-call', content: 'Step 1 already completed; immutable original result.' });
75
+ const before = JSON.stringify(original);
76
+ const first = await runModelRequest(h.deps, h.actor, original);
77
+ assert.equal(first.result_state, 'complete'); assert.equal(first.dispatch, 'completed'); assert.equal(first.billing_state, 'pending');
78
+ const response = first.response!;
79
+ const partial = JSON.parse(String(response.body));
80
+ assert.equal(partial.choices[0].finish_reason, 'length'); assert.equal(h.bodies.length, 1);
81
+ const recovery = h.ledger.view((await h.ledger.findRequest(h.actor, original.operation_id))!);
82
+ assert.deepEqual(recovery.response, response);
83
+ const repeated = await runModelRequest(h.deps, h.actor, original);
84
+ assert.deepEqual(repeated.response, response); assert.equal(h.bodies.length, 1);
85
+ await assert.rejects(runModelRequest(h.deps, h.actor, { ...original, messages: [...original.messages, { role: 'user', content: 'different' }] }),
86
+ { code: 'USAGE_IDEMPOTENCY_CONFLICT' });
87
+ assert.equal(h.bodies.length, 1);
88
+ h.setMode('stop');
89
+ const next = { ...h.input('continuation-1'), messages: [...original.messages,
90
+ { role: 'assistant', content: partial.choices[0].message.content },
91
+ { role: 'system', content: 'Runtime continuation context: continue from the saved result; do not repeat completed step 1.' }] };
92
+ const completed = await runModelRequest(h.deps, h.actor, next);
93
+ assert.equal(completed.result_state, 'complete'); assert.equal(completed.operation_id, 'continuation-1');
94
+ assert.equal(h.bodies.length, 2); assert.deepEqual(h.bodies[1]!.messages, next.messages);
95
+ assert.deepEqual((h.bodies[1]!.messages as Record<string, unknown>[]).filter(message => message.role === 'tool'),
96
+ original.messages.filter(message => message.role === 'tool'), 'the next model request receives the saved tool result, not a request to rerun it');
97
+ assert.equal(JSON.stringify(original), before, 'continuation must not mutate the original intent');
98
+ assert.deepEqual((await runModelRequest(h.deps, h.actor, original)).response, response); assert.equal(h.bodies.length, 2);
99
+ });
100
+
101
+ test('transport uncertainty remains original-ID recovery and is not an automatic new model call', async () => {
102
+ const h = fixture(); h.setMode('lost'); const original = h.input('original-lost');
103
+ const result = await runModelRequest(h.deps, h.actor, original);
104
+ assert.equal(result.result_state, 'unknown'); assert.equal(result.dispatch, 'unknown'); assert.equal(result.next_action, 'inspect_original');
105
+ assert.equal(h.bodies.length, 1);
106
+ h.setMode('stop');
107
+ const repeated = await runModelRequest(h.deps, h.actor, original);
108
+ assert.equal(repeated.result_state, 'unknown'); assert.equal(h.bodies.length, 1);
109
+ });
@@ -18,6 +18,7 @@ import { getBillingRepository } from './billing-repository';
18
18
  import type { UsageRepository } from './repository';
19
19
  import { referencePricing } from './pricing';
20
20
  import { executeModelTool, modelToolBody, modelToolEndpoint } from './model-tool-provider';
21
+ import { outputBudgetDescriptor, outputBudgetPolicy } from './output-budget';
21
22
 
22
23
  export interface UsageGatewayDeps {
23
24
  usage: UsageRepository | null;
@@ -43,6 +44,7 @@ function scheduleResponseCleanup(repository: UsageRepository): void {
43
44
  export const MODEL_GATEWAY_CAPABILITIES = {
44
45
  schema: 'bailing.model-gateway.v1', supported: true, orchestration: 'host', streaming: true, provider_response: 'bailing.provider-response.v1', settlement: 'asynchronous',
45
46
  model_tools: { schema: 'bailing.model-tools.v1', directory: true, execution: true, tools_path: '/usage/v1/model/tools' },
47
+ output_budget: { schema: 'bailing.model-output-budget.v1', separate_default: true, explicit_parameter: true, explicit_scope: true },
46
48
  requests_path: '/usage/v1/model/requests', models_path: '/usage/v1/model/models',
47
49
  summary_path: '/usage/v1/model/summary', billing_unit: 'USD', turn_required: false,
48
50
  } as const;
@@ -76,6 +78,7 @@ export function modelAllowedServices(actor: UsageSessionContext, serviceIds: str
76
78
  return actor.modelAccess === 'token_gateway' ? serviceIds : serviceIds.filter(id => id === actor.serviceId);
77
79
  }
78
80
  export function modelDescriptor(service: UsageService, multiplier = 1) {
81
+ const policy = outputBudgetPolicy(service.config);
79
82
  return { schema: 'bailing.usage-model.v1', service_id: service.id, service_revision: service.revision,
80
83
  label: service.label, model: service.config.model, state: service.state, orchestration: 'host', streaming: true,
81
84
  billing_rate: { multiplier },
@@ -83,7 +86,8 @@ export function modelDescriptor(service: UsageService, multiplier = 1) {
83
86
  context_window_tokens: service.config.contextWindowTokens ?? null, max_input_bytes: service.config.maxInputBytes,
84
87
  input_limit_scope: 'serialized_provider_request', max_messages: 1024, max_tools: 128,
85
88
  max_output_tokens: service.config.maxOutputTokens, timeout_ms: service.config.timeoutMs,
86
- provider_options: ['max_tokens','max_completion_tokens','top_p','stop','seed','presence_penalty','frequency_penalty','parallel_tool_calls','response_format','reasoning_effort','enable_thinking','thinking','verbosity'] };
89
+ ...outputBudgetDescriptor(service.config),
90
+ provider_options: [...(policy ? [policy.parameter] : ['max_tokens','max_completion_tokens']), 'top_p','stop','seed','presence_penalty','frequency_penalty','parallel_tool_calls','response_format','reasoning_effort','enable_thinking','thinking','verbosity'] };
87
91
  }
88
92
 
89
93
  /** One durable request, one provider dispatch; accounting never drives the local agent loop. */
@@ -0,0 +1,84 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createUsageTestHarness } from './test-harness';
5
+ import type { UsageServiceConfig } from './contracts';
6
+
7
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
8
+ const input = (provider_options?: Record<string, unknown>) => ({ operation_id: randomUUID(), messages: [{ role: 'user', content: 'Synthetic budget acceptance' }],
9
+ ...(provider_options ? { provider_options } : {}) });
10
+
11
+ test('Model budget HTTP: persisted policy, live directory, explicit defaults, exact cap and safe pre-dispatch rejection', { skip: !enabled }, async () => {
12
+ const h = await createUsageTestHarness();
13
+ try {
14
+ const user = await h.seedUser();
15
+ const policy: UsageServiceConfig = { ...h.service.config, maxOutputTokens: 131072, defaultOutputTokens: 32768,
16
+ outputTokenParameter: 'max_completion_tokens', outputBudgetScope: 'completion_total', modelMaxOutputTokens: 131072 };
17
+ const saved = await h.repository.putService({ id: h.service.id, label: h.service.label, expectedRevision: 1, config: policy });
18
+ assert.equal(saved.revision, 2);
19
+ assert.deepEqual((await h.repository.getService(h.service.id))?.config, policy);
20
+ const directory = await h.request('/usage/v1/model/models', user.token);
21
+ const descriptor = directory.body.items[0];
22
+ assert.equal(descriptor.default_output_tokens, 32768);
23
+ assert.equal(descriptor.max_output_tokens, 131072);
24
+ assert.equal(descriptor.model_max_output_tokens, 131072);
25
+ assert.equal(descriptor.output_token_parameter, 'max_completion_tokens');
26
+ assert.equal(descriptor.output_budget_scope, 'completion_total');
27
+ assert(!descriptor.provider_options.includes('max_tokens'));
28
+ for (const tokens of [undefined, 8192, 16384, 65536, 131072]) {
29
+ const result = await h.request('/usage/v1/model/requests', user.token, 'POST', input(tokens === undefined ? undefined : { max_completion_tokens: tokens }));
30
+ assert.equal(result.status, 200, JSON.stringify(result.body));
31
+ assert.equal(h.state.bodies.at(-1)?.max_completion_tokens, tokens ?? 32768);
32
+ assert.equal(h.state.bodies.at(-1)?.max_tokens, undefined);
33
+ }
34
+ const calls = h.state.calls;
35
+ const above = await h.request('/usage/v1/model/requests', user.token, 'POST', input({ max_completion_tokens: 131073 }));
36
+ assert.equal(above.status, 413);
37
+ assert.deepEqual(above.body.feedback.output_limit, { actual: 131073, allowed: 131072, parameter: 'max_completion_tokens', scope: 'completion_total' });
38
+ assert.equal(above.body.feedback.dispatch, 'not_dispatched');
39
+ const wrong = await h.request('/usage/v1/model/requests', user.token, 'POST', input({ max_tokens: 32768 }));
40
+ assert.equal(wrong.status, 400);
41
+ assert.deepEqual(wrong.body.feedback.output_budget, { expected_parameter: 'max_completion_tokens', scope: 'completion_total' });
42
+ assert.equal(wrong.body.feedback.dispatch, 'not_dispatched');
43
+ const both = await h.request('/usage/v1/model/requests', user.token, 'POST', input({ max_tokens: 1, max_completion_tokens: 1 }));
44
+ assert.equal(both.status, 400);
45
+ assert.equal(h.state.calls, calls);
46
+ assert.equal(JSON.stringify([wrong.body, above.body]).includes('Synthetic budget acceptance'), false);
47
+ } finally { await h.close(); }
48
+ });
49
+
50
+ test('Model budget HTTP: already admitted original stays recoverable after policy changes; unadmitted old intent is not rewritten', { skip: !enabled }, async () => {
51
+ const h = await createUsageTestHarness();
52
+ try {
53
+ const user = await h.seedUser();
54
+ const original = input({ max_tokens: 80 });
55
+ const before = JSON.stringify(original);
56
+ const first = await h.request('/usage/v1/model/requests', user.token, 'POST', original);
57
+ assert.equal(first.status, 200);
58
+ assert.equal(h.state.bodies[0]?.max_tokens, 80);
59
+ await h.tokens.drainSettlements();
60
+ const policy: UsageServiceConfig = { ...h.service.config, maxOutputTokens: 65536, defaultOutputTokens: 32768,
61
+ outputTokenParameter: 'max_completion_tokens', outputBudgetScope: 'completion_total' };
62
+ await h.repository.putService({ id: h.service.id, label: h.service.label, expectedRevision: 1, config: policy });
63
+ const recovery = await h.request(`/usage/v1/model/requests/${original.operation_id}`, user.token);
64
+ assert.equal(recovery.status, 200);
65
+ assert.deepEqual(recovery.body.response, first.body.response);
66
+ const repeat = await h.request('/usage/v1/model/requests', user.token, 'POST', original);
67
+ assert.equal(repeat.status, 200);
68
+ assert.deepEqual(repeat.body.response, first.body.response);
69
+ assert.equal(h.state.calls, 1, 'policy refresh must never dispatch an admitted operation twice');
70
+ const unadmitted = { ...original, operation_id: randomUUID() };
71
+ const rejected = await h.request('/usage/v1/model/requests', user.token, 'POST', unadmitted);
72
+ assert.equal(rejected.status, 400);
73
+ assert.equal(rejected.body.error, 'USAGE_OUTPUT_PARAMETER_MISMATCH');
74
+ assert.equal(rejected.body.dispatch, 'not_dispatched');
75
+ assert.equal(h.state.calls, 1);
76
+ assert.equal(JSON.stringify(original), before);
77
+ const next = await h.request('/usage/v1/model/requests', user.token, 'POST', input({ max_completion_tokens: 32768 }));
78
+ assert.equal(next.status, 200);
79
+ assert.equal(h.state.bodies[1]?.max_completion_tokens, 32768);
80
+ await h.tokens.drainSettlements();
81
+ const summary = await h.request('/usage/v1/model/summary', user.token);
82
+ assert.equal(summary.body.consumedUsd, 50, 'only two genuine provider dispatches are billed');
83
+ } finally { await h.close(); }
84
+ });
@@ -0,0 +1,167 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createServer, type ServerResponse } from 'node:http';
4
+ import { once } from 'node:events';
5
+ import type { AddressInfo } from 'node:net';
6
+ import type { UsageService, UsageServiceConfig } from './contracts';
7
+ import { outputBudgetDescriptor, outputBudgetPolicy } from './output-budget';
8
+ import { providerBody, normalizeModelRequest, executeProvider } from './provider';
9
+ import { modelDescriptor } from './model-gateway';
10
+ import { UsageRepository } from './repository';
11
+ import { usageHttpError } from './http';
12
+ import { UsageError } from './errors';
13
+
14
+ const legacy: UsageServiceConfig = { credential: 'private-credential', model: 'synthetic-only', providerScope: 'private-route',
15
+ maxInputBytes: 16384, maxOutputTokens: 65536, timeoutMs: 1000 };
16
+ const explicit: UsageServiceConfig = { ...legacy, defaultOutputTokens: 32768, outputTokenParameter: 'max_completion_tokens',
17
+ outputBudgetScope: 'completion_total', modelMaxOutputTokens: 131072 };
18
+ const input = (provider_options?: Record<string, unknown>) => normalizeModelRequest({ operation_id: 'synthetic-budget',
19
+ messages: [{ role: 'user', content: 'Synthetic request; never a paid model call.' }], ...(provider_options ? { provider_options } : {}) });
20
+ const service = (config: UsageServiceConfig): UsageService => ({ id: 'synthetic', label: 'Synthetic', revision: 2, state: 'active', config });
21
+
22
+ function errorJson(error: unknown) {
23
+ let raw = '';
24
+ const res = { writeHead() {}, end(value: string) { raw = value; } } as unknown as ServerResponse;
25
+ usageHttpError(res, error);
26
+ return JSON.parse(raw);
27
+ }
28
+
29
+ test('legacy policy does not invent an independent default, vendor maximum or reasoning scope', () => {
30
+ assert.equal(outputBudgetPolicy(legacy), null);
31
+ assert.deepEqual(outputBudgetDescriptor(legacy), {});
32
+ const descriptor = modelDescriptor(service(legacy));
33
+ assert.equal(descriptor.max_output_tokens, 65536);
34
+ for (const field of ['default_output_tokens', 'output_token_parameter', 'output_budget_scope', 'model_max_output_tokens'])
35
+ assert.equal(Object.hasOwn(descriptor, field), false);
36
+ assert(descriptor.provider_options.includes('max_tokens'));
37
+ assert(descriptor.provider_options.includes('max_completion_tokens'));
38
+ assert.equal(providerBody(input(), legacy).max_tokens, 65536);
39
+ assert.equal(providerBody(input({ max_completion_tokens: 1234 }), legacy).max_completion_tokens, 1234);
40
+ assert.equal(providerBody(input({ max_tokens: 1234 }), legacy).max_tokens, 1234);
41
+ });
42
+
43
+ test('explicit default is distinct from the service ceiling and advertised parameter matches actual dispatch', () => {
44
+ assert.deepEqual(outputBudgetPolicy(explicit), { defaultTokens: 32768, maxTokens: 65536, parameter: 'max_completion_tokens',
45
+ scope: 'completion_total', modelMaxTokens: 131072 });
46
+ const descriptor = modelDescriptor(service(explicit));
47
+ assert.equal(descriptor.default_output_tokens, 32768);
48
+ assert.equal(descriptor.max_output_tokens, 65536);
49
+ assert.equal(descriptor.model_max_output_tokens, 131072);
50
+ assert.equal(descriptor.output_token_parameter, 'max_completion_tokens');
51
+ assert.equal(descriptor.output_budget_scope, 'completion_total');
52
+ assert(!descriptor.provider_options.includes('max_tokens'));
53
+ assert(descriptor.provider_options.includes('max_completion_tokens'));
54
+ assert.equal(JSON.stringify(descriptor).includes('private-'), false);
55
+ const original = input();
56
+ const before = JSON.stringify(original);
57
+ const body = providerBody(original, explicit);
58
+ assert.equal(body.max_completion_tokens, 32768);
59
+ assert.equal(Object.hasOwn(body, 'max_tokens'), false);
60
+ assert.equal(JSON.stringify(original), before, 'wire default must not mutate prepared intent');
61
+ assert.equal(providerBody(input({ max_completion_tokens: 65536 }), explicit).max_completion_tokens, 65536);
62
+ for (const scope of ['final_answer', 'completion_total'] as const) {
63
+ const config = { ...explicit, outputTokenParameter: 'max_tokens' as const, outputBudgetScope: scope };
64
+ assert.equal(providerBody(input(), config).max_tokens, 32768);
65
+ assert.equal(modelDescriptor(service(config)).output_budget_scope, scope);
66
+ }
67
+ });
68
+
69
+ test('partial, ambiguous and impossible policies fail before repository persistence', async () => {
70
+ let transactions = 0;
71
+ const repository = new UsageRepository(() => { throw new Error('must not touch a database for invalid config'); });
72
+ repository.withTransaction = async () => { transactions++; throw new Error('invalid config reached persistence'); };
73
+ const invalid = [
74
+ { ...legacy, defaultOutputTokens: 32768 }, { ...legacy, outputTokenParameter: 'max_tokens' },
75
+ { ...legacy, outputBudgetScope: 'final_answer' }, { ...legacy, modelMaxOutputTokens: 131072 },
76
+ { ...explicit, outputTokenParameter: 'unknown' }, { ...explicit, outputBudgetScope: 'unknown' },
77
+ { ...explicit, outputBudgetScope: 'final_answer' },
78
+ { ...explicit, defaultOutputTokens: 65537 }, { ...explicit, defaultOutputTokens: 0 },
79
+ { ...explicit, defaultOutputTokens: '32768' }, { ...explicit, defaultOutputTokens: null },
80
+ { ...explicit, defaultOutputTokens: 1.5 }, { ...explicit, defaultOutputTokens: Infinity },
81
+ { ...explicit, maxOutputTokens: 131073 }, { ...explicit, modelMaxOutputTokens: 65535 },
82
+ { ...explicit, modelMaxOutputTokens: 0 }, { ...explicit, modelMaxOutputTokens: '131072' },
83
+ { ...explicit, modelMaxOutputTokens: 10000001 },
84
+ ];
85
+ for (const config of invalid) {
86
+ assert.throws(() => outputBudgetPolicy(config as UsageServiceConfig), { code: 'USAGE_INVALID_INPUT', status: 400 });
87
+ await assert.rejects(repository.putService({ id: 'synthetic', label: 'Synthetic', expectedRevision: 0,
88
+ config: config as UsageServiceConfig }), { code: 'USAGE_INVALID_INPUT', status: 400 });
89
+ }
90
+ assert.equal(transactions, 0);
91
+ assert.equal(outputBudgetPolicy({ ...explicit, defaultOutputTokens: 1 })?.defaultTokens, 1);
92
+ assert.equal(outputBudgetPolicy({ ...explicit, modelMaxOutputTokens: 10000000 })?.modelMaxTokens, 10000000);
93
+ assert.equal(outputBudgetPolicy({ ...legacy, purpose: 'tool' }), null, 'old image residue remains inert');
94
+ assert.throws(() => outputBudgetPolicy({ ...explicit, purpose: 'tool' }), { code: 'USAGE_INVALID_INPUT' });
95
+ });
96
+
97
+ test('wrong parameter is rejected without renaming and over-limit feedback contains only safe scalars', () => {
98
+ const original = input({ max_tokens: 32768 });
99
+ const before = JSON.stringify(original);
100
+ assert.throws(() => providerBody(original, explicit), (error: unknown) => {
101
+ assert(error instanceof UsageError);
102
+ assert.equal(error.code, 'USAGE_OUTPUT_PARAMETER_MISMATCH');
103
+ assert.equal(error.status, 400);
104
+ const result = errorJson(error);
105
+ assert.deepEqual(result.feedback.output_budget, { expected_parameter: 'max_completion_tokens', scope: 'completion_total' });
106
+ assert.equal(result.feedback.dispatch, 'not_dispatched');
107
+ assert.equal(result.feedback.retryable, false);
108
+ assert.equal(result.feedback.next_action, 'resolve_error');
109
+ assert.equal(JSON.stringify(result).includes('Synthetic request'), false);
110
+ return true;
111
+ });
112
+ assert.equal(JSON.stringify(original), before);
113
+ for (const config of [legacy, explicit]) {
114
+ const parameter = config.outputTokenParameter ?? 'max_tokens';
115
+ assert.throws(() => providerBody(input({ [parameter]: 65537 }), config), (error: unknown) => {
116
+ assert(error instanceof UsageError);
117
+ assert.equal(error.code, 'USAGE_OUTPUT_LIMIT');
118
+ assert.equal(error.status, 413);
119
+ const result = errorJson(error);
120
+ assert.equal(result.feedback.dispatch, 'not_dispatched');
121
+ assert.deepEqual(result.feedback.output_limit, { actual: 65537, allowed: 65536, parameter,
122
+ ...(config.outputBudgetScope ? { scope: config.outputBudgetScope } : {}) });
123
+ assert.equal(JSON.stringify(result).includes('private-'), false);
124
+ return true;
125
+ });
126
+ }
127
+ for (const options of [ { max_tokens: 1, max_completion_tokens: 1 }, { max_completion_tokens: 0 },
128
+ { max_completion_tokens: -1 }, { max_completion_tokens: 1.5 }, { max_completion_tokens: '32768' } ]) {
129
+ assert.throws(() => input(options), { code: 'USAGE_INVALID_INPUT' });
130
+ }
131
+ });
132
+
133
+ test('synthetic HTTP provider receives configured parameter and budget with reasoning settings preserved', async () => {
134
+ const bodies: Record<string, unknown>[] = [];
135
+ const server = createServer(async (req, res) => {
136
+ const chunks: Buffer[] = [];
137
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
138
+ bodies.push(JSON.parse(Buffer.concat(chunks).toString('utf8')));
139
+ res.writeHead(200, { 'content-type': 'application/json' });
140
+ res.end(JSON.stringify({ choices: [{ message: { content: 'synthetic' }, finish_reason: 'stop' }],
141
+ usage: { prompt_tokens: 10, completion_tokens: 8, total_tokens: 18, completion_tokens_details: { reasoning_tokens: 5 } } }));
142
+ }).listen(0, '127.0.0.1');
143
+ await once(server, 'listening');
144
+ try {
145
+ const credential = { base_url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`, api_key: 'synthetic-test-only' };
146
+ const configs: UsageServiceConfig[] = [legacy, explicit, { ...explicit, outputTokenParameter: 'max_tokens', outputBudgetScope: 'final_answer' }];
147
+ for (const config of configs) {
148
+ const options = { reasoning_effort: 'high', thinking: { budget_tokens: 8192 } };
149
+ const result = await executeProvider(credential, config, providerBody(input(options), config));
150
+ assert.deepEqual(result.usage, { inputTokens: 10, outputTokens: 8 }, 'reasoning subset is not charged a second time');
151
+ }
152
+ assert.equal(bodies.length, 3, 'no automatic retry or token probe');
153
+ assert.equal(bodies[0]?.max_tokens, 65536);
154
+ assert.equal(bodies[1]?.max_completion_tokens, 32768);
155
+ assert.equal(bodies[1]?.max_tokens, undefined);
156
+ assert.equal(bodies[2]?.max_tokens, 32768);
157
+ assert.equal(bodies[2]?.max_completion_tokens, undefined);
158
+ for (const body of bodies) {
159
+ assert.equal(body.reasoning_effort, 'high');
160
+ assert.deepEqual(body.thinking, { budget_tokens: 8192 });
161
+ assert.equal(body.credential, undefined);
162
+ assert.equal(body.providerScope, undefined);
163
+ }
164
+ } finally {
165
+ server.close(); server.closeAllConnections(); await once(server, 'close');
166
+ }
167
+ });
@@ -0,0 +1,73 @@
1
+ import type { UsageServiceConfig } from './contracts';
2
+ import { UsageError, usageAssert } from './errors';
3
+ import { integer } from './validation';
4
+
5
+ export const OUTPUT_TOKEN_PARAMETERS = ['max_tokens', 'max_completion_tokens'] as const;
6
+ export const OUTPUT_BUDGET_SCOPES = ['completion_total', 'final_answer'] as const;
7
+ export type OutputTokenParameter = typeof OUTPUT_TOKEN_PARAMETERS[number];
8
+ export type OutputBudgetScope = typeof OUTPUT_BUDGET_SCOPES[number];
9
+
10
+ export interface OutputBudgetPolicy {
11
+ defaultTokens: number;
12
+ maxTokens: number;
13
+ parameter: OutputTokenParameter;
14
+ scope: OutputBudgetScope;
15
+ modelMaxTokens?: number;
16
+ }
17
+
18
+ export interface OutputBudgetDescriptor {
19
+ default_output_tokens?: number;
20
+ output_token_parameter?: OutputTokenParameter;
21
+ output_budget_scope?: OutputBudgetScope;
22
+ model_max_output_tokens?: number;
23
+ }
24
+
25
+ /** An operator selects verified provider semantics; model names never imply a policy. */
26
+ export function outputBudgetPolicy(config: UsageServiceConfig): OutputBudgetPolicy | null {
27
+ const fields = [config.defaultOutputTokens, config.outputTokenParameter, config.outputBudgetScope];
28
+ const present = fields.filter(value => value !== undefined).length;
29
+ if (present === 0 && config.modelMaxOutputTokens === undefined) return null;
30
+ usageAssert(config.purpose !== 'tool', 'USAGE_INVALID_INPUT', 'Image/model tools do not use a chat output budget.', 400);
31
+ usageAssert(present === fields.length, 'USAGE_INVALID_INPUT', 'Configure the output default, parameter and scope together.', 400);
32
+ const maxTokens = integer(config.maxOutputTokens, 'maxOutputTokens', 1, 131072);
33
+ const defaultTokens = integer(config.defaultOutputTokens, 'defaultOutputTokens', 1, maxTokens);
34
+ usageAssert(OUTPUT_TOKEN_PARAMETERS.includes(config.outputTokenParameter!), 'USAGE_INVALID_INPUT', 'Unsupported output token parameter.', 400);
35
+ usageAssert(OUTPUT_BUDGET_SCOPES.includes(config.outputBudgetScope!), 'USAGE_INVALID_INPUT', 'Unsupported output budget scope.', 400);
36
+ usageAssert(config.outputTokenParameter !== 'max_completion_tokens' || config.outputBudgetScope === 'completion_total',
37
+ 'USAGE_INVALID_INPUT', 'max_completion_tokens requires a completion_total budget.', 400);
38
+ let modelMaxTokens: number | undefined;
39
+ if (config.modelMaxOutputTokens !== undefined) {
40
+ modelMaxTokens = integer(config.modelMaxOutputTokens, 'modelMaxOutputTokens', 1, 10000000);
41
+ usageAssert(maxTokens <= modelMaxTokens, 'USAGE_INVALID_INPUT', 'The service output ceiling exceeds the verified model maximum.', 400);
42
+ }
43
+ return { defaultTokens, maxTokens, parameter: config.outputTokenParameter!, scope: config.outputBudgetScope!,
44
+ ...(modelMaxTokens === undefined ? {} : { modelMaxTokens }) };
45
+ }
46
+
47
+ /** Old descriptors omit the new group rather than inventing provider semantics. */
48
+ export function outputBudgetDescriptor(config: UsageServiceConfig): OutputBudgetDescriptor {
49
+ const policy = outputBudgetPolicy(config);
50
+ return policy ? {
51
+ default_output_tokens: policy.defaultTokens,
52
+ output_token_parameter: policy.parameter,
53
+ output_budget_scope: policy.scope,
54
+ ...(policy.modelMaxTokens === undefined ? {} : { model_max_output_tokens: policy.modelMaxTokens }),
55
+ } : {};
56
+ }
57
+
58
+ export function resolveOutputBudget(config: UsageServiceConfig, options: Record<string, unknown>): {
59
+ parameter: OutputTokenParameter; tokens: number;
60
+ } {
61
+ const policy = outputBudgetPolicy(config);
62
+ const supplied = OUTPUT_TOKEN_PARAMETERS.find(key => options[key] !== undefined);
63
+ if (policy && supplied && supplied !== policy.parameter) throw new UsageError('USAGE_OUTPUT_PARAMETER_MISMATCH',
64
+ `Use ${policy.parameter} for this service's ${policy.scope} output budget. Refresh the model descriptor before preparing a new request.`, 400,
65
+ { output_budget: { expected_parameter: policy.parameter, scope: policy.scope } });
66
+ const parameter = policy?.parameter ?? supplied ?? 'max_tokens';
67
+ const tokens = Number(options[parameter] ?? policy?.defaultTokens ?? config.maxOutputTokens);
68
+ if (tokens > config.maxOutputTokens) throw new UsageError('USAGE_OUTPUT_LIMIT',
69
+ 'The requested output limit exceeds the model service limit.', 413,
70
+ { output_limit: { actual: tokens, allowed: config.maxOutputTokens, parameter,
71
+ ...(policy ? { scope: policy.scope } : {}) } });
72
+ return { parameter, tokens };
73
+ }