bailinghub 0.10.0 → 0.11.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 (259) hide show
  1. package/CONTRIBUTING.md +20 -0
  2. package/README.en.md +6 -6
  3. package/README.md +6 -6
  4. package/SECURITY.md +20 -0
  5. package/THIRD_PARTY_NOTICES.md +2 -2
  6. package/docker-compose.images.yml +2 -2
  7. package/docs/AGENT_CONVERSATION_AUDIT.en.md +8 -2
  8. package/docs/AGENT_CONVERSATION_AUDIT.md +8 -1
  9. package/docs/CHANGELOG.en.md +29 -1
  10. package/docs/CHANGELOG.md +29 -1
  11. package/docs/IMPLEMENTATION_STATUS.en.md +12 -3
  12. package/docs/IMPLEMENTATION_STATUS.md +12 -3
  13. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  14. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  15. package/docs/MODEL_CONTINUATION.en.md +8 -0
  16. package/docs/MODEL_CONTINUATION.md +8 -0
  17. package/docs/MODEL_OUTPUT_BUDGET.en.md +1 -0
  18. package/docs/MODEL_OUTPUT_BUDGET.md +1 -0
  19. package/docs/README.en.md +6 -0
  20. package/docs/README.md +6 -0
  21. package/docs/RELEASE_NOTES_v0.10.1.en.md +41 -0
  22. package/docs/RELEASE_NOTES_v0.10.1.md +41 -0
  23. package/docs/RELEASE_NOTES_v0.11.0.en.md +19 -0
  24. package/docs/RELEASE_NOTES_v0.11.0.md +19 -0
  25. package/docs/RELEASE_NOTES_v0.11.1.en.md +25 -0
  26. package/docs/RELEASE_NOTES_v0.11.1.md +25 -0
  27. package/docs/UPGRADE_v0.10.1.en.md +66 -0
  28. package/docs/UPGRADE_v0.10.1.md +66 -0
  29. package/docs/UPGRADE_v0.11.0.en.md +24 -0
  30. package/docs/UPGRADE_v0.11.0.md +24 -0
  31. package/docs/UPGRADE_v0.11.1.en.md +28 -0
  32. package/docs/UPGRADE_v0.11.1.md +28 -0
  33. package/docs/security/GRC_EVIDENCE.md +54 -0
  34. package/docs/user-guide/console-map.md +2 -2
  35. package/package.json +5 -3
  36. package/scripts/check-doc-links.mjs +6 -0
  37. package/scripts/check-image-tags.sh +1 -1
  38. package/scripts/check-php-sdk-artifacts.mjs +152 -0
  39. package/scripts/check-php-sdk-artifacts.test.mjs +99 -0
  40. package/scripts/check-release-consistency.test.mjs +2 -2
  41. package/scripts/copy-acr-platform-image.sh +42 -0
  42. package/scripts/e2e-console-runtime-audit.mjs +7 -0
  43. package/scripts/e2e-console-troubleshooting-extra.mjs +4 -4
  44. package/scripts/e2e-console.mjs +90 -23
  45. package/scripts/install.sh +1 -1
  46. package/scripts/notification-console-test.mjs +2 -1
  47. package/scripts/publish-images.sh +1 -1
  48. package/scripts/release-audit.mjs +13 -1
  49. package/scripts/restore-ghcr-version.sh +48 -0
  50. package/scripts/sdk-declaration-contract-test.ts +34 -0
  51. package/scripts/sdk-p1-check.mjs +62 -26
  52. package/scripts/test-acr-platform-copy.sh +152 -0
  53. package/scripts/verify-github-repo.mjs +12 -0
  54. package/sdk/dotnet/Bailing.Connect/BailingConnect.cs +4 -4
  55. package/sdk/dotnet/README.md +8 -0
  56. package/sdk/dotnet/tests/Declaration/Declaration.csproj +11 -0
  57. package/sdk/dotnet/tests/Declaration/Program.cs +74 -0
  58. package/sdk/go/README.md +8 -0
  59. package/sdk/go/bailingconnect/connect.go +5 -5
  60. package/sdk/go/bailingconnect/declaration_test.go +107 -0
  61. package/sdk/java/README.md +13 -0
  62. package/sdk/java/src/main/java/com/bailing/connect/BailingConnect.java +4 -4
  63. package/sdk/java/tests/DeclarationTest.java +70 -0
  64. package/sdk/node/README.md +8 -0
  65. package/sdk/node/src/index.mjs +4 -4
  66. package/sdk/node/tests/declaration.test.mjs +41 -0
  67. package/sdk/php/README.md +16 -0
  68. package/sdk/php/src/Attributes/AiTool.php +4 -4
  69. package/sdk/php/src/SpecBuilder.php +8 -8
  70. package/sdk/php/tests/declaration-serialization.php +103 -0
  71. package/sdk/php7/README.md +14 -0
  72. package/sdk/php7/src/ToolDef.php +3 -3
  73. package/sdk/php7/src/ToolSpec.php +8 -13
  74. package/sdk/php7/tests/declaration-serialization.php +103 -0
  75. package/sdk/python/README.md +8 -0
  76. package/sdk/python/bailing_connect/__init__.py +6 -6
  77. package/sdk/python/tests/test_declaration.py +61 -0
  78. package/src/core/config/console-task-location.test.ts +12 -24
  79. package/src/core/contracts/explicit-capability-values.test.ts +62 -0
  80. package/src/core/contracts/openapi-tools.ts +2 -2
  81. package/src/core/contracts/tool-annotations.ts +4 -4
  82. package/src/core/runtime/credential-resolver.ts +3 -3
  83. package/src/infrastructure/config/config-agent-conversation-audit-repository.test.ts +29 -0
  84. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +142 -9
  85. package/src/infrastructure/config/config-conversation-feed.integration.test.ts +134 -0
  86. package/src/infrastructure/config/config-conversation-ledger.test.ts +47 -1
  87. package/src/infrastructure/config/config-conversation-ledger.ts +24 -8
  88. package/src/infrastructure/config/config-observability-ledger.ts +32 -4
  89. package/src/infrastructure/config/config-recent-jobs.integration.test.ts +45 -0
  90. package/src/infrastructure/config/configstore.ts +4 -4
  91. package/src/infrastructure/config/conversation-delivery-message.ts +12 -0
  92. package/src/modules/usage/contracts.ts +1 -0
  93. package/src/modules/usage/model-context.test.ts +106 -0
  94. package/src/modules/usage/model-context.ts +54 -0
  95. package/src/modules/usage/model-continuation.test.ts +27 -0
  96. package/src/modules/usage/provider.test.ts +40 -0
  97. package/src/modules/usage/provider.ts +21 -3
  98. package/src/modules/usage/repository.ts +2 -1
  99. package/src/routes/admin-conversation-audit.ts +20 -3
  100. package/src/routes/admin-history-cursor.ts +12 -0
  101. package/src/routes/admin-runtime.test.ts +47 -0
  102. package/src/routes/admin-runtime.ts +32 -3
  103. package/src/routes/admin-usage.ts +12 -1
  104. package/src/routes/admin.ts +6 -1
  105. package/src/routes/agent-conversation-audit.test.ts +47 -3
  106. package/src/test-support/agent-conversation-audit-fixture.ts +9 -1
  107. package/web/connect/bailing-connect-php.tgz +0 -0
  108. package/web/connect/bailing-connect-php7.tgz +0 -0
  109. package/web/console/assets/{Accounts-Dhyw-7wF.js → Accounts-B1Ne8Xx2.js} +1 -1
  110. package/web/console/assets/AgentClients-CiGQ-n2i.js +1 -0
  111. package/web/console/assets/AgentClients-xEIfsj7w.css +1 -0
  112. package/web/console/assets/AgentTasks-CaCeYv60.css +1 -0
  113. package/web/console/assets/AgentTasks-CylHZHHq.js +2 -0
  114. package/web/console/assets/{Approvals-CQx1YWxW.js → Approvals-wD4Iv80G.js} +1 -1
  115. package/web/console/assets/{Audit--QcdVlMh.js → Audit-BStlxkPw.js} +1 -1
  116. package/web/console/assets/{BrandLockup-DQcaW4Nt.js → BrandLockup-BAhrPnhy.js} +1 -1
  117. package/web/console/assets/Channels-DAlIgNxo.js +105 -0
  118. package/web/console/assets/Channels-WwRHFKJn.css +1 -0
  119. package/web/console/assets/ChatEntries-CPx-E9aJ.js +7 -0
  120. package/web/console/assets/ChatEntries-DALYfRDP.css +1 -0
  121. package/web/console/assets/Clients-gqNFusNW.css +1 -0
  122. package/web/console/assets/Clients-w97QPpFD.js +3 -0
  123. package/web/console/assets/Cost-CNDZaif-.css +1 -0
  124. package/web/console/assets/Cost-CxtN0mca.js +1 -0
  125. package/web/console/assets/Credentials-6c6aktzZ.css +1 -0
  126. package/web/console/assets/Credentials-BhpoH-hR.js +1 -0
  127. package/web/console/assets/{Diagnostics-CyoM1XrZ.js → Diagnostics-DnC-ODuy.js} +1 -1
  128. package/web/console/assets/Executors-CCTYuZf4.js +1 -0
  129. package/web/console/assets/Executors-CQ8iw3kK.css +1 -0
  130. package/web/console/assets/{HelpTip-DLlhaGQp.js → HelpTip-piedkqU-.js} +1 -1
  131. package/web/console/assets/Kb-CFCa-7LY.css +1 -0
  132. package/web/console/assets/Kb-DKp3mwWB.js +2 -0
  133. package/web/console/assets/Login-g_aZWHQd.js +1 -0
  134. package/web/console/assets/Login-krXZsvoF.css +1 -0
  135. package/web/console/assets/Projects-BexeaCxT.css +1 -0
  136. package/web/console/assets/Projects-DurExYV9.js +1 -0
  137. package/web/console/assets/Routes-CKoIjkCM.css +1 -0
  138. package/web/console/assets/Routes-CX7Q7bkz.js +138 -0
  139. package/web/console/assets/Runs-C48kdEwk.css +1 -0
  140. package/web/console/assets/Runs-CQKEDsrH.js +3 -0
  141. package/web/console/assets/Setup-CtWCXXpj.css +1 -0
  142. package/web/console/assets/Setup-DzI8rEAc.js +1 -0
  143. package/web/console/assets/Shell-BQ-g_O7K.js +1 -0
  144. package/web/console/assets/Shell-Y2fZK5LV.css +1 -0
  145. package/web/console/assets/StorageBuckets-CWxzIh0x.css +1 -0
  146. package/web/console/assets/StorageBuckets-DoZIzA7B.js +1 -0
  147. package/web/console/assets/SystemSettings-C3pFFzAQ.js +1 -0
  148. package/web/console/assets/SystemSettings-C5nv0K2a.css +1 -0
  149. package/web/console/assets/SystemStatus-Bbxu2dp4.css +1 -0
  150. package/web/console/assets/SystemStatus-BgekIK52.js +1 -0
  151. package/web/console/assets/Targets-CbLq7rgm.css +1 -0
  152. package/web/console/assets/Targets-DH1ZcK0J.js +1 -0
  153. package/web/console/assets/Tools-CMS1wVOm.js +5 -0
  154. package/web/console/assets/Tools-Qk1c5Rp8.css +1 -0
  155. package/web/console/assets/Usage-C0OkK7Jg.js +1 -0
  156. package/web/console/assets/Usage-Cue7CYnT.css +1 -0
  157. package/web/console/assets/UsageAccess-CHdWXvE8.js +1 -0
  158. package/web/console/assets/UsageAccess-nOa03hGb.css +1 -0
  159. package/web/console/assets/{UsageHelp-BmuiE1Ew.js → UsageHelp-BkIsuFUj.js} +1 -1
  160. package/web/console/assets/{console-location-Csv-xsnl.js → console-location-C_az_xHo.js} +1 -1
  161. package/web/console/assets/index-CbI5fbiD.js +2 -0
  162. package/web/console/assets/{index-B_5UfiTw.js → index-DwlsLKwM.js} +1 -1
  163. package/web/console/assets/request-WgSVj8ie.js +1 -0
  164. package/web/console/assets/{schema-o3mK4mid.js → schema-rb4T_2cj.js} +1 -1
  165. package/web/console/assets/task-page-location-BGxGar7H.js +1 -0
  166. package/web/console/assets/{use-list-location-cIPy2cKM.js → use-list-location-DeVfTTII.js} +1 -1
  167. package/web/console/assets/{use-unsaved-form-DScKD0h9.js → use-unsaved-form-B10XHC-n.js} +1 -1
  168. package/web/console/assets/{util-B40VqOwl.js → util-C0YJ70YU.js} +1 -1
  169. package/web/console/assets/{vendor-element-BT8tHCFk.js → vendor-element-BCC2kYn_.js} +7 -7
  170. package/web/console/assets/{vendor-mammoth-CVIXVxTN.js → vendor-mammoth-C7l0Q30g.js} +1 -1
  171. package/web/console/index.html +2 -2
  172. package/web-admin/package-lock.json +4 -4
  173. package/web-admin/package.json +1 -1
  174. package/web-admin/scripts/agent-task-control-smoke.mjs +26 -3
  175. package/web-admin/src/components/AgentSetupPanel.vue +19 -15
  176. package/web-admin/src/components/ChannelThread.vue +441 -0
  177. package/web-admin/src/components/ClientConversations.vue +397 -134
  178. package/web-admin/src/components/ConversationSourceTag.vue +24 -0
  179. package/web-admin/src/components/JobStatusTag.vue +18 -0
  180. package/web-admin/src/components/NotificationOutboxPanel.vue +5 -2
  181. package/web-admin/src/components/UsageServiceReferences.vue +6 -24
  182. package/web-admin/src/components/conversation-audit.ts +67 -2
  183. package/web-admin/src/components/conversation-reading-position.ts +27 -0
  184. package/web-admin/src/layout/Shell.vue +15 -17
  185. package/web-admin/src/onboarding-state.ts +5 -5
  186. package/web-admin/src/pages/AgentClients.vue +33 -27
  187. package/web-admin/src/pages/AgentTasks.vue +88 -43
  188. package/web-admin/src/pages/Channels.vue +15 -41
  189. package/web-admin/src/pages/ChatEntries.vue +13 -51
  190. package/web-admin/src/pages/Clients.vue +2 -2
  191. package/web-admin/src/pages/Cost.vue +10 -51
  192. package/web-admin/src/pages/Credentials.vue +1 -1
  193. package/web-admin/src/pages/Executors.vue +4 -3
  194. package/web-admin/src/pages/Kb.vue +4 -4
  195. package/web-admin/src/pages/Login.vue +7 -8
  196. package/web-admin/src/pages/Projects.vue +1 -1
  197. package/web-admin/src/pages/Routes.vue +46 -83
  198. package/web-admin/src/pages/Runs.vue +239 -567
  199. package/web-admin/src/pages/Setup.vue +20 -20
  200. package/web-admin/src/pages/StorageBuckets.vue +1 -1
  201. package/web-admin/src/pages/SystemSettings.vue +1 -2
  202. package/web-admin/src/pages/SystemStatus.vue +4 -6
  203. package/web-admin/src/pages/Targets.vue +0 -2
  204. package/web-admin/src/pages/Tools.vue +31 -22
  205. package/web-admin/src/pages/Usage.vue +110 -60
  206. package/web-admin/src/pages/UsageAccess.vue +2 -5
  207. package/web-admin/src/request.ts +5 -1
  208. package/web-admin/src/task-page-location.ts +6 -12
  209. package/web-admin/src/task-trace-presentation.ts +143 -0
  210. package/web-admin/tests/conversation-audit.test.mjs +23 -1
  211. package/web-admin/tests/model-context.browser.mjs +238 -0
  212. package/web-admin/tests/model-output-budget.browser.mjs +1 -0
  213. package/web/console/assets/AgentClients-BA0M26-I.css +0 -1
  214. package/web/console/assets/AgentClients-DWxb8-ko.js +0 -1
  215. package/web/console/assets/AgentTasks-DOyxANnx.css +0 -1
  216. package/web/console/assets/AgentTasks-DUHD4dzr.js +0 -2
  217. package/web/console/assets/Channels-DJJU3ksE.css +0 -1
  218. package/web/console/assets/Channels-cGS5WfQ-.js +0 -105
  219. package/web/console/assets/ChatEntries-BYpji27B.css +0 -1
  220. package/web/console/assets/ChatEntries-nh23Iz5O.js +0 -7
  221. package/web/console/assets/Clients-CX5EeYio.js +0 -3
  222. package/web/console/assets/Clients-CbZAou8E.css +0 -1
  223. package/web/console/assets/Cost-C6oQvz9P.css +0 -1
  224. package/web/console/assets/Cost-DOZfdNS9.js +0 -1
  225. package/web/console/assets/Credentials--aHs57yV.css +0 -1
  226. package/web/console/assets/Credentials-sy6W9Sac.js +0 -1
  227. package/web/console/assets/Executors-2Upi6bOS.css +0 -1
  228. package/web/console/assets/Executors-BQqqiFwt.js +0 -1
  229. package/web/console/assets/Kb-5R3ce4UU.js +0 -5
  230. package/web/console/assets/Kb-BM_PYi11.css +0 -1
  231. package/web/console/assets/Login-YKeUwdgo.js +0 -1
  232. package/web/console/assets/Login-xtPwDB5_.css +0 -1
  233. package/web/console/assets/Projects-DHwHrPT9.css +0 -1
  234. package/web/console/assets/Projects-Grgb6fOv.js +0 -1
  235. package/web/console/assets/Routes-DR_Yf02e.css +0 -1
  236. package/web/console/assets/Routes-DYgrXlRJ.js +0 -138
  237. package/web/console/assets/Runs-CwTddJJj.js +0 -3
  238. package/web/console/assets/Runs-D4FOvNfu.css +0 -1
  239. package/web/console/assets/Setup-Ca0b1d1-.css +0 -1
  240. package/web/console/assets/Setup-D_xUPNDq.js +0 -1
  241. package/web/console/assets/Shell-BTg8Vw_L.css +0 -1
  242. package/web/console/assets/Shell-Dfam2Uoj.js +0 -1
  243. package/web/console/assets/StorageBuckets-7QLBpV4a.css +0 -1
  244. package/web/console/assets/StorageBuckets-CP6e50wI.js +0 -1
  245. package/web/console/assets/SystemSettings-BRYKyJNa.js +0 -1
  246. package/web/console/assets/SystemSettings-HsXGx0aH.css +0 -1
  247. package/web/console/assets/SystemStatus-B-VfRsQd.css +0 -1
  248. package/web/console/assets/SystemStatus-CbPsDsGt.js +0 -1
  249. package/web/console/assets/Targets-1j4-g6rC.css +0 -1
  250. package/web/console/assets/Targets-C2LkR2AF.js +0 -1
  251. package/web/console/assets/Tools-C9HPJqJb.css +0 -1
  252. package/web/console/assets/Tools-C9JNJUS0.js +0 -2
  253. package/web/console/assets/Usage-D1Mv6vGY.js +0 -1
  254. package/web/console/assets/Usage-DMOzUsqh.css +0 -1
  255. package/web/console/assets/UsageAccess-77LmGCm6.js +0 -1
  256. package/web/console/assets/UsageAccess-C6ZGxEgJ.css +0 -1
  257. package/web/console/assets/index-MjZJEFIN.js +0 -2
  258. package/web/console/assets/request-rqm6MT0s.js +0 -1
  259. package/web/console/assets/task-page-location-DWiGtAln.js +0 -1
@@ -41,6 +41,46 @@ test('usage preserves unknown and does not add cached or reasoning subsets twice
41
41
  assert.deepEqual(verifiedUsage({ prompt_tokens: 5, completion_tokens: 2, total_tokens: 7, prompt_tokens_details: { cached_tokens: 4 }, completion_tokens_details: { reasoning_tokens: 1 } }), { inputTokens: 5, outputTokens: 2 });
42
42
  });
43
43
 
44
+ test('only a recognized TokenHub context rejection gets a safe receipt diagnostic', async () => {
45
+ const base = 'https://tokenhub.tencentmaas.com/v1';
46
+ const raw = JSON.stringify({ error: { code: '400003', message: 'private input detail', request_id: 'private-id',
47
+ context_window_tokens: 17 }, diagnostic: { code: 'supplied-by-provider' } });
48
+ const check = async (baseUrl: string, status: number, responseBody: string, window?: number, streaming = false) => {
49
+ const configSnapshot = { ...config, contextWindowTokens: window };
50
+ const packets: Record<string, unknown>[] = [];
51
+ let calls = 0;
52
+ const result = await executeProvider({ base_url: baseUrl, api_key: 'synthetic' }, configSnapshot,
53
+ providerBody(input, configSnapshot, streaming), async (_url, init) => {
54
+ calls++;
55
+ assert.equal(JSON.parse(String(init?.body)).stream, streaming);
56
+ assert.equal(init?.redirect, 'error');
57
+ return new Response(responseBody, { status, headers: { 'content-type': 'application/json' } });
58
+ }, streaming ? async packet => { packets.push(packet); } : undefined);
59
+ assert.equal(result.response.body, responseBody);
60
+ assert.equal(result.response.status, status);
61
+ assert.equal(calls, 1);
62
+ if (streaming) assert.equal(packets.map(packet => packet.data).join(''), responseBody);
63
+ return result.response.diagnostic;
64
+ };
65
+ const expected = { code: 'CONTEXT_WINDOW_EXCEEDED', http_status: 400, provider_code: '400003' };
66
+ for (const streaming of [false, true]) {
67
+ assert.deepEqual(await check(base, 400, raw, 1048576, streaming), { ...expected, context_window_tokens: 1048576 });
68
+ }
69
+ for (const missingOrInvalid of [undefined, 0, -5, 1.5, 10_000_001]) {
70
+ assert.deepEqual(await check(base, 400, raw, missingOrInvalid), expected);
71
+ }
72
+ assert.deepEqual(await check('https://TOKENHUB.tencentmaas.com:443/v1/', 400, '{"error":{"code":400003}}'), expected);
73
+ for (const otherRoute of ['https://other.invalid/v1', 'https://tokenhub.tencentmaas.com.other.invalid/v1',
74
+ 'http://tokenhub.tencentmaas.com/v1', 'https://tokenhub.tencentmaas.com:8443/v1', base + '/another']) {
75
+ assert.equal(await check(otherRoute, 400, raw), undefined);
76
+ }
77
+ for (const status of [200, 413, 429, 500]) assert.equal(await check(base, status, raw), undefined);
78
+ for (const otherBody of ['{', 'null', '{"error":{"code":"400001","message":"CodeInputTooLong 400003"}}',
79
+ '{"code":"400003"}', '{"error":{"code":"4000030"}}']) {
80
+ assert.equal(await check(base, 400, otherBody), undefined);
81
+ }
82
+ });
83
+
44
84
  test('real HTTP provider receives only the service output bound, no automatic retry', async () => {
45
85
  let modelCalls = 0; const bodies: Record<string, unknown>[] = [];
46
86
  const server = createServer(async (req, res) => {
@@ -1,5 +1,5 @@
1
1
  import type { ResolvedLlmCredential } from '../../core/runtime/credential-resolver';
2
- import type { UsageServiceConfig } from './contracts';
2
+ import { MAX_CONTEXT_WINDOW_TOKENS, type UsageServiceConfig } from './contracts';
3
3
  import { UsageError, usageAssert } from './errors';
4
4
  import { readProviderExchange } from './provider-stream';
5
5
  import { resolveOutputBudget } from './output-budget';
@@ -130,12 +130,30 @@ export function verifiedUsage(value: unknown): ProviderResult['usage'] {
130
130
  if (value.total_tokens !== undefined && (!tokenCount(value.total_tokens) || value.total_tokens !== Number(value.prompt_tokens) + Number(value.completion_tokens))) return undefined;
131
131
  return { inputTokens: Number(value.prompt_tokens), outputTokens: Number(value.completion_tokens) };
132
132
  }
133
+ // TokenHub returns its pre-generation rejection as JSON, including for streaming requests.
134
+ // Classify only at dispatch, where the actual destination and frozen service configuration are known.
135
+ function tokenHubContextDiagnostic(endpoint: string, exchange: JsonObject, window: number | undefined) {
136
+ if (endpoint !== 'https://tokenhub.tencentmaas.com/v1/chat/completions' || exchange.status !== 400
137
+ || exchange.format !== 'json' || typeof exchange.body !== 'string') return;
138
+ let payload: unknown;
139
+ try { payload = JSON.parse(exchange.body); } catch { return; }
140
+ if (!object(payload) || !object(payload.error)
141
+ || (payload.error.code !== '400003' && payload.error.code !== 400003)) return;
142
+ return { code: 'CONTEXT_WINDOW_EXCEEDED', http_status: 400, provider_code: '400003',
143
+ ...(typeof window === 'number' && Number.isSafeInteger(window) && window > 0 && window <= MAX_CONTEXT_WINDOW_TOKENS
144
+ ? { context_window_tokens: window } : {}) };
145
+ }
146
+
133
147
  /** Transport completion and model semantics are separate. The local adapter owns the latter. */
134
148
  export async function executeProvider(credential: ResolvedLlmCredential, config: UsageServiceConfig, body: JsonObject, fetcher: typeof fetch = fetch,
135
149
  onProvider?: (packet: JsonObject) => Promise<void>): Promise<ProviderResult> {
136
150
  const signal = AbortSignal.timeout(config.timeoutMs);
137
- const response = await fetcher(providerUrl(credential, 'chat/completions'), { method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json', authorization: `Bearer ${credential.api_key}` }, body: JSON.stringify(body), signal });
151
+ const endpoint = providerUrl(credential, 'chat/completions');
152
+ const response = await fetcher(endpoint, { method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json', authorization: `Bearer ${credential.api_key}` }, body: JSON.stringify(body), signal });
138
153
  // HTTP error bodies are also returned to the local provider adapter. Do not
139
154
  // retry them or mistake a transport-complete error response for a missing body.
140
- return readProviderExchange(response, onProvider, signal);
155
+ const result = await readProviderExchange(response, onProvider, signal);
156
+ const diagnostic = tokenHubContextDiagnostic(endpoint, result.response, config.contextWindowTokens);
157
+ if (diagnostic) result.response.diagnostic = diagnostic;
158
+ return result;
141
159
  }
@@ -4,6 +4,7 @@ import { outputBudgetPolicy } from './output-budget';
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import type { Pool, PoolConnection, RowDataPacket } from "mysql2/promise";
6
6
  import type { CreateUsageAccountInput, UsageAccount, UsageActor, UsageActorValidator, UsageService, UsageServiceConfig } from "./contracts";
7
+ import { MAX_CONTEXT_WINDOW_TOKENS } from "./contracts";
7
8
  import { integer, assertKnownFields } from "./validation";
8
9
  import { usageAssert } from "./errors";
9
10
  import { UsageBackgroundWork } from './background-work';
@@ -492,7 +493,7 @@ export class UsageRepository {
492
493
  if (i.config.pricing !== undefined) validatePricingBinding(i.config.pricing);
493
494
  if (i.config.pricing) usageAssert(i.config.pricing.kind === (i.config.purpose === "tool" ? "image" : "chat"), "USAGE_INVALID_INPUT", "参考价格类型与服务用途不一致。", 400);
494
495
  if (i.config.contextWindowTokens !== undefined)
495
- integer(i.config.contextWindowTokens, "contextWindowTokens", 1, 10000000);
496
+ integer(i.config.contextWindowTokens, "contextWindowTokens", 1, MAX_CONTEXT_WINDOW_TOKENS);
496
497
  if (i.config.inputModalities !== undefined)
497
498
  usageAssert(Array.isArray(i.config.inputModalities) && i.config.inputModalities.includes('text')
498
499
  && i.config.inputModalities.every(value => ['text', 'image'].includes(value))
@@ -1,9 +1,12 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { send } from '../app/http';
3
+ import { readHistoryCursor } from './admin-history-cursor';
3
4
  import { can, type Principal } from '../app/auth';
4
5
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
5
6
  import { auditUuid, ConversationAuditError } from '../core/runtime/agent-conversation-audit';
6
7
 
8
+ import { ADMIN_CONVERSATION_SOURCES, type AdminConversationSource } from '../infrastructure/config/config-agent-conversation-audit-repository';
9
+
7
10
  export async function handleAdminConversationAuditFor(
8
11
  store: ConfigStoreContract | null, method: string, path: string,
9
12
  req: IncomingMessage, res: ServerResponse, principal: Principal,
@@ -15,8 +18,9 @@ export async function handleAdminConversationAuditFor(
15
18
  return true;
16
19
  }
17
20
  res.setHeader('cache-control', 'no-store');
21
+ const feed = path === `${base}/feed`;
18
22
  const detail = path.match(/^\/admin\/api\/conversation-audits\/([0-9a-f-]{36})$/i);
19
- if (method !== 'GET' || (path !== base && !detail)) {
23
+ if (method !== 'GET' || (path !== base && !feed && !detail)) {
20
24
  send(res, 404, { error: 'not_found' });
21
25
  return true;
22
26
  }
@@ -32,10 +36,23 @@ export async function handleAdminConversationAuditFor(
32
36
  if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value))) throw new ConversationAuditError(400, 'invalid_request', 'Pagination requires non-negative safe integers.');
33
37
  return Number(value);
34
38
  };
35
- if (path === base) {
39
+ if (feed) {
40
+ const source = query.get('source') ?? 'all';
41
+ if (!ADMIN_CONVERSATION_SOURCES.includes(source as AdminConversationSource)) {
42
+ throw new ConversationAuditError(400, 'invalid_request', 'Unknown conversation source.');
43
+ }
44
+ if (!store.agentConversationAudit.listFeedForAdmin) {
45
+ send(res, 503, { error: 'conversation_feed_unavailable' });
46
+ return true;
47
+ }
48
+ send(res, 200, { schema: 'bailing.admin-conversation-feed.v1',
49
+ ...await store.agentConversationAudit.listFeedForAdmin(source as AdminConversationSource, number('limit', 50), number('offset', 0), query.get('cursor') ?? undefined) });
50
+ } else if (path === base) {
36
51
  send(res, 200, { schema: 'bailing.agent-conversation-audit-list.v1', ...await store.agentConversationAudit.listForAdmin(number('limit', 50), number('offset', 0)) });
37
52
  } else {
38
- const result = await store.agentConversationAudit.detailForAdmin(auditUuid(detail![1]), number('after_sequence', 0), number('limit', 100));
53
+ const cursor = readHistoryCursor(query, 'sequence');
54
+ if (!cursor) throw new ConversationAuditError(400, 'invalid_request', 'Invalid history cursor.');
55
+ const result = await store.agentConversationAudit.detailForAdmin(auditUuid(detail![1]), cursor.after, number('limit', 100), cursor.before);
39
56
  send(res, result ? 200 : 404, result ? { schema: 'bailing.agent-conversation-audit-detail.v1', ...result } : { error: 'conversation_audit_not_found' });
40
57
  }
41
58
  } catch (error) {
@@ -0,0 +1,12 @@
1
+ /** No parameters keeps the original oldest-first detail endpoint. */
2
+ export function readHistoryCursor(query: URLSearchParams, key: 'sequence' | 'id'): { after: number; before?: number | null } | null {
3
+ const after = query.get(`after_${key}`);
4
+ const before = query.get(`before_${key}`);
5
+ const tail = query.get('tail');
6
+ if (tail !== null) return tail === '1' && before === null && after === null ? { after: 0, before: null } : null;
7
+ if (before !== null && after !== null) return null;
8
+ const raw = before ?? after ?? '0';
9
+ const value = Number(raw);
10
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value)) return null;
11
+ return before !== null ? { after: 0, before: value } : { after: value };
12
+ }
@@ -275,3 +275,50 @@ test('event-linked native dead letters have one retry entry point, while legacy
275
275
  assert.equal((await invoke()).statusCode, 200);
276
276
  assert.equal(sends, 1); assert.equal(resolves, 1);
277
277
  });
278
+
279
+ test('dispatch list validates filters and pagination, preserves the array response and masks error previews', async () => {
280
+ const deps = depsFor();
281
+ const calls: unknown[][] = [];
282
+ deps.configStore.observability.listFilteredJobs = async (...args) => {
283
+ calls.push(args);
284
+ return [{ job_id: VALID_JOB_ID, error_preview: 'invalid address: example@example.org' }];
285
+ };
286
+ async function read(query: string) {
287
+ const res = new FakeResponse();
288
+ const path = '/admin/api/runs';
289
+ await handleAdminRuntimeApiFor(deps, 'GET', path, { url: path + '?' + query } as IncomingMessage, res as unknown as ServerResponse,
290
+ { kind: 'admin', via: 'session', username: 'reader', role: 'viewer' });
291
+ return res;
292
+ }
293
+ for (const query of ['status=failed', 'period=2h', 'before_job_id=' + VALID_JOB_ID, 'before_created_at=bad&before_job_id=bad']) {
294
+ assert.equal((await read(query)).statusCode, 400);
295
+ }
296
+ assert.equal(calls.length, 0);
297
+ const response = await read('limit=51&status=error&route_key=orders&period=24h');
298
+ assert.equal(response.statusCode, 200);
299
+ assert.deepEqual(response.json(), [{ job_id: VALID_JOB_ID, error_preview: 'invalid address: [REDACTED_EMAIL]' }]);
300
+ assert.deepEqual(calls[0], [51, 0, {status:'error', routeKey:'orders', period:'24h'}]);
301
+ assert.equal((await read('')).statusCode, 200);
302
+ assert.deepEqual(calls[1], [50, 0, {}]);
303
+ delete deps.configStore.observability.listFilteredJobs;
304
+ deps.configStore.observability.listRecentJobs = async () => [{ job_id: VALID_JOB_ID }];
305
+ assert.equal((await read('status=error')).statusCode, 503);
306
+ assert.equal((await read('')).json()[0].job_id, VALID_JOB_ID);
307
+ });
308
+
309
+ test('thread detail accepts tail and exclusive before cursors while retaining forward paging', async () => {
310
+ const base = depsFor();
311
+ const calls: unknown[][] = [];
312
+ const conversations = { threadDetail: async (...args: unknown[]) => { calls.push(args); return null; } };
313
+ const deps = { ...base, configStore: { ...base.configStore, conversations } as ConfigStoreContract };
314
+ const path = '/admin/api/threads/42';
315
+ const get = async (query: string) => {
316
+ const res = new FakeResponse();
317
+ await handleAdminRuntimeApiFor(deps, 'GET', path, { url: path + query } as IncomingMessage, res as unknown as ServerResponse,
318
+ { kind: 'admin', via: 'session', role: 'viewer' });
319
+ return res.statusCode;
320
+ };
321
+ for (const query of ['', '?after_id=5', '?tail=1', '?before_id=10']) assert.equal(await get(query), 404);
322
+ for (const query of ['?tail=0', '?before_id=-2', '?after_id=1&before_id=2', '?tail=1&after_id=0']) assert.equal(await get(query), 400);
323
+ assert.deepEqual(calls, [[42, 0, undefined], [42, 5, undefined], [42, 0, null], [42, 0, 10]]);
324
+ });
@@ -3,7 +3,7 @@
3
3
  import type { IncomingMessage, ServerResponse } from 'node:http';
4
4
  import type { EngineRuntime } from '../app/engine';
5
5
  import { send } from '../app/http';
6
- import { redactValue, redactionSummary } from '../core/runtime/redaction-runtime';
6
+ import { redactText, redactValue, redactionSummary } from '../core/runtime/redaction-runtime';
7
7
  import { renderDebugReport } from '../core/runtime/debug-report';
8
8
  import { buildJobTrace } from '../core/runtime/trace-runtime';
9
9
  import { buildAgentClientTrace } from '../core/runtime/agent-client-trace';
@@ -16,7 +16,10 @@ import { isAgentToolInvocationJob } from '../app/agent-tool-job';
16
16
  import { continueApprovalDecisionFor, supportsApprovalContinuations } from '../app/approval-continuations';
17
17
  import { classifyDeliveryDlq, replayExecutorDeliveryDlq, DeliveryReplayError } from '../app/delivery-dlq-replay';
18
18
  import { handleAdminNotificationsFor } from './admin-notifications';
19
+ import { readHistoryCursor } from './admin-history-cursor';
19
20
  import { approvalContinuationView, consoleExecution } from './admin-runtime-ux';
21
+ import { JOB_STATUSES, type JobStatus } from '../core/contracts/types';
22
+ import type { RecentJobFilters } from '../infrastructure/config/config-observability-ledger';
20
23
  import { approvalDetailView, approvalListView } from './admin-approval-view';
21
24
 
22
25
  export type AdminChannelSender = (channelName: string, recipient: string, message: string | ChannelMessage) => Promise<ChannelSendResult>;
@@ -338,7 +341,31 @@ export async function handleAdminRuntimeApiFor(
338
341
 
339
342
  if (path === '/admin/api/runs' && method === 'GET') {
340
343
  const q = new URL(req.url ?? '/', 'http://x').searchParams;
341
- send(res, 200, await configStore.observability.listRecentJobs(Number(q.get('limit')) || 50, Number(q.get('offset')) || 0));
344
+ const status = q.get('status'), period = q.get('period'), routeKey = q.get('route_key')?.trim();
345
+ const time = q.get('before_created_at'), id = q.get('before_job_id');
346
+ if ((status && !JOB_STATUSES.some(value => value === status)) || (period && !['all', '24h', '7d'].includes(period))) {
347
+ send(res, 400, { error: '无效的任务状态或时间范围' }); return true;
348
+ }
349
+ const filters: RecentJobFilters = {};
350
+ if (time !== null || id !== null) {
351
+ if (!time || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(time) || !Number.isFinite(Date.parse(time))
352
+ || !id || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)) {
353
+ send(res, 400, { error: '无效的任务分页位置' }); return true;
354
+ }
355
+ filters.before = { createdAt: Date.parse(time), jobId: id };
356
+ }
357
+ if (status) filters.status = status as JobStatus;
358
+ if (period === '24h' || period === '7d') filters.period = period;
359
+ if (routeKey) filters.routeKey = routeKey;
360
+ const ledger = configStore.observability;
361
+ if (!ledger.listFilteredJobs && (filters.status || filters.routeKey || filters.period)) {
362
+ send(res, 503, { error: '当前存储不支持按条件查询任务,可清除筛选查看全部记录。' }); return true;
363
+ }
364
+ const limit = Number(q.get('limit')) || 50, offset = Number(q.get('offset')) || 0;
365
+ const rows = ledger.listFilteredJobs
366
+ ? await ledger.listFilteredJobs(limit, offset, filters)
367
+ : await ledger.listRecentJobs(limit, offset);
368
+ send(res, 200, rows.map(row => ({ ...row, error_preview: row.error_preview ? redactText(String(row.error_preview)).slice(0, 200) : null })));
342
369
  return true;
343
370
  }
344
371
 
@@ -391,7 +418,9 @@ export async function handleAdminRuntimeApiFor(
391
418
  }
392
419
  const mThread = path.match(/^\/admin\/api\/threads\/(\d+)$/);
393
420
  if (mThread && method === 'GET') {
394
- const d = await configStore.conversations.threadDetail(Number(mThread[1]));
421
+ const cursor = readHistoryCursor(new URL(req.url ?? '/', 'http://x').searchParams, 'id');
422
+ if (!cursor) { send(res, 400, { error: '无效的消息分页位置' }); return true; }
423
+ const d = await configStore.conversations.threadDetail(Number(mThread[1]), cursor.after, cursor.before);
395
424
  if (!d) { send(res, 404, { error: '会话不存在' }); return true; }
396
425
  send(res, 200, d);
397
426
  return true;
@@ -12,15 +12,26 @@ import { usageAssert } from '../modules/usage/errors';
12
12
  import { getUsageIdentity, usageFields, usageKey, usageString } from '../modules/usage/identity';
13
13
  import { USAGE_CAPABILITIES, usageHttpError, usagePage, usageRequestKey, usageRevision } from '../modules/usage/http';
14
14
  import type { UsageRepository } from '../modules/usage/repository';
15
+ import type { ModelContextSpec } from '../modules/usage/model-context';
15
16
 
16
17
  /** Console uses domain services too; ordinary usage credentials never gain admin permissions. */
17
18
  export async function handleAdminUsageApiFor(repository: UsageRepository | null | undefined, method: string, path: string,
18
- req: IncomingMessage, res: ServerResponse, principal: Principal): Promise<boolean> {
19
+ req: IncomingMessage, res: ServerResponse, principal: Principal,
20
+ lookupModelContext?: (credential: string, model: string) => Promise<ModelContextSpec>): Promise<boolean> {
19
21
  if (path !== '/admin/api/usage' && !path.startsWith('/admin/api/usage/')) return false;
20
22
  try {
21
23
  usageAssert(principal.kind === 'admin' && can(principal, method === 'GET' ? 'usage:read' : 'usage:write'), 'USAGE_FORBIDDEN', '当前账号没有用户与用量管理权限。', 403);
22
24
  if (path === '/admin/api/usage' && method === 'GET') { send(res, 200, { ...USAGE_CAPABILITIES, supported: Boolean(repository && await getUsageIdentity(repository).ready() && await getBillingRepository(repository).ready()) }); return true; }
23
25
  usageAssert(repository, 'USAGE_UNSUPPORTED', '此实例尚未配置用量模块。', 503);
26
+ if (path === '/admin/api/usage/model-context') {
27
+ usageAssert(can(principal, 'usage:issuers'), 'USAGE_FORBIDDEN', '查询供应商规格需要模型服务管理权限。', 403);
28
+ if (method !== 'GET') { send(res, 405, { error: 'method_not_allowed' }); return true; }
29
+ const query = new URL(req.url ?? path, 'http://bailing.local').searchParams;
30
+ const credential = usageString(query.get('credential'), 'credential', 128);
31
+ const model = usageString(query.get('model'), 'model', 191);
32
+ usageAssert(lookupModelContext, 'USAGE_UNSUPPORTED', '模型规格查询不可用。', 503);
33
+ send(res, 200, await lookupModelContext(credential, model)); return true;
34
+ }
24
35
  const identity = getUsageIdentity(repository), url = new URL(req.url ?? path, 'http://bailing.local');
25
36
  usageAssert(await identity.ready(), 'USAGE_UNSUPPORTED', '用量模块尚未就绪,请核对版本与迁移。', 503);
26
37
  if (await handleAdminBillingUsage(repository, method, path, req, res, principal)) return true;
@@ -24,6 +24,8 @@ import { handleAdminBrandingApiFor } from './admin-branding';
24
24
  import { handleAdminAgentClientsApiFor } from './admin-agent-clients';
25
25
  import { handleAdminAgentTasksApiFor } from './admin-agent-tasks';
26
26
  import { handleAdminUsageApiFor } from './admin-usage';
27
+ import { resolveLlmCredential } from '../core/runtime/credential-resolver';
28
+ import { providerModelContext } from '../modules/usage/model-context';
27
29
  import { handleAdminDemoDatasetApiFor, type DemoDatasetServiceContract } from './admin-demo-dataset';
28
30
  import { refreshTargets, type TargetRegistry } from '../core/targets/registry';
29
31
  import type { AppConfig } from '../core/config/config';
@@ -96,7 +98,10 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
96
98
  return true;
97
99
  }
98
100
  if (path === '/admin/api/usage' || path.startsWith('/admin/api/usage/')) {
99
- return handleAdminUsageApiFor(configStore.usage ?? null, method, path, req, res, principal);
101
+ return handleAdminUsageApiFor(configStore.usage ?? null, method, path, req, res, principal, async (name, model) => {
102
+ const ref = await resolveLlmCredential(name, deps.cfg, { get: id => configStore.credentials.get(id) });
103
+ return providerModelContext(ref?.credential ?? null, model);
104
+ });
100
105
  }
101
106
  if (deps.demoDataset && await handleAdminDemoDatasetApiFor(
102
107
  { demoDataset: deps.demoDataset, refreshTargets: deps.refreshTargets },
@@ -98,21 +98,36 @@ test('only an administrator with runs:read can read complete conversation pages'
98
98
  { kind: 'admin', via: 'session', role: 'kb_editor' },
99
99
  { kind: 'admin', via: 'session', role: 'admin', permissions: [] },
100
100
  ] as Principal[]) {
101
- const denied = await admin(path, principal);
102
- assert.equal(denied.statusCode, 403);
103
- assert.doesNotMatch(denied.body, /ADMIN_ONLY_VISIBLE_TEXT/);
101
+ for (const deniedPath of [path, `${path}?tail=1`, `${path}?before_sequence=2`, '/admin/api/conversation-audits', '/admin/api/conversation-audits/feed']) {
102
+ const denied = await admin(deniedPath, principal);
103
+ assert.equal(denied.statusCode, 403);
104
+ assert.doesNotMatch(denied.body, /ADMIN_ONLY_VISIBLE_TEXT/);
105
+ }
104
106
  }
105
107
  const viewer: Principal = { kind: 'admin', via: 'session', role: 'viewer' };
106
108
  const first = await admin(`${path}?limit=1`, viewer);
107
109
  assert.equal(first.statusCode, 200);
108
110
  assert.equal(first.json().schema, 'bailing.agent-conversation-audit-detail.v1');
109
111
  assert.equal(first.json().has_more, true);
112
+ assert.equal(first.json().conversation.first_user_preview, 'ADMIN_ONLY_VISIBLE_TEXT');
110
113
  assert.equal(first.json().next_after_sequence, 1);
111
114
  const second = await admin(`${path}?limit=1&after_sequence=1`, viewer);
112
115
  assert.equal(second.json().events[0].content, 'ADMIN_ONLY_VISIBLE_TEXT');
113
116
  assert.equal(second.headers['cache-control'], 'no-store');
114
117
  assert.equal((await admin(`${path}?after_sequence=-1`, viewer)).statusCode, 400);
118
+ const latest = (await admin(`${path}?tail=1&limit=2`, viewer)).json();
119
+ assert.deepEqual(latest.events.map((event: { sequence: number }) => event.sequence), [2, 3]);
120
+ assert.equal(latest.has_earlier, true);
121
+ assert.equal(latest.next_before_sequence, 2);
122
+ const earlier = (await admin(`${path}?before_sequence=${latest.next_before_sequence}&limit=2`, viewer)).json();
123
+ assert.deepEqual(earlier.events.map((event: { sequence: number }) => event.sequence), [1]);
124
+ assert.equal(earlier.has_earlier, false);
125
+ assert.equal(earlier.next_before_sequence, null);
126
+ for (const query of ['tail=1&before_sequence=2', 'before_sequence=2&after_sequence=1', 'tail=0', 'before_sequence=-1']) {
127
+ assert.equal((await admin(`${path}?${query}`, viewer)).statusCode, 400);
128
+ }
115
129
  const listed = await admin('/admin/api/conversation-audits?limit=1', viewer);
130
+ assert.equal(listed.json().items[0].first_user_preview, 'ADMIN_ONLY_VISIBLE_TEXT');
116
131
  assert.equal(listed.json().items[0].message_count, 1);
117
132
  assert.equal(listed.json().items[0].turn_count, 1);
118
133
  assert.equal(listed.json().items[0].last_turn_status, 'cancelled');
@@ -129,3 +144,32 @@ test('missing storage is explicit and unexpected internal errors never expose ra
129
144
  assert.equal(failure.json().error, 'conversation_audit_internal_error');
130
145
  assert.doesNotMatch(failure.body, /PASSWORD|DATABASE_DETAIL/);
131
146
  });
147
+
148
+ test('admin feed validates source and pagination and reports a legacy Host without the combined feed', async () => {
149
+ const path = '/admin/api/conversation-audits/feed';
150
+ const viewer: Principal = { kind: 'admin', via: 'session', role: 'viewer' };
151
+ const calls: unknown[][] = [];
152
+ const store = { agentConversationAudit: { listFeedForAdmin: async (...args: unknown[]) => {
153
+ calls.push(args);
154
+ return { items: [], has_more: false, next_offset: null };
155
+ } } } as unknown as ConfigStoreContract;
156
+ async function read(target: ConfigStoreContract | null, query: string, method = 'GET') {
157
+ const res = new Response();
158
+ await handleAdminConversationAuditFor(target, method, path, request(method, path + query), res as unknown as ServerResponse, viewer);
159
+ return res;
160
+ }
161
+ const success = await read(store, '?source=web&limit=2&offset=17');
162
+ assert.equal(success.statusCode, 200);
163
+ assert.equal(success.headers['cache-control'], 'no-store');
164
+ assert.deepEqual(success.json(), { schema: 'bailing.admin-conversation-feed.v1', items: [], has_more: false, next_offset: null });
165
+ assert.equal((await read(store, '')).statusCode, 200);
166
+ assert.equal((await read(store, '?source=delivery')).statusCode, 200);
167
+ assert.equal((await read(store, '?source=unknown')).statusCode, 400);
168
+ assert.equal((await read(store, '?offset=-1')).statusCode, 400);
169
+ assert.equal((await read(store, '', 'POST')).statusCode, 404);
170
+ assert.deepEqual(calls, [['web', 2, 17, undefined], ['all', 50, 0, undefined], ['delivery', 50, 0, undefined]]);
171
+ const unsupported = await read({ agentConversationAudit: {} } as ConfigStoreContract, '');
172
+ assert.equal(unsupported.statusCode, 503);
173
+ assert.equal(unsupported.json().error, 'conversation_feed_unavailable');
174
+ assert.equal((await read(null, '')).statusCode, 503);
175
+ });
@@ -71,8 +71,15 @@ export function conversationAuditFixture(options: { crossBinding?: boolean; sche
71
71
  result = { affectedRows: existing ? 0 : 1 };
72
72
  } else if (sql.startsWith('SELECT') && sql.includes('FROM bz_agent_conversation_audits')) {
73
73
  if (sql.includes('WHERE creator_session_id')) result = [...archives.values()].filter((row) => row.creator_session_id === params[0] && row.route_key === params[1] && row.client_archive_id === params[2]);
74
- else if (sql.includes('WHERE conversation_id')) result = archives.has(params[0]) ? [archives.get(params[0])] : [];
74
+ else if (sql.includes('WHERE conversation_id=?') || sql.includes('WHERE a.conversation_id=?')) result = archives.has(params[0]) ? [archives.get(params[0])] : [];
75
75
  else result = [...archives.values()].sort((a, b) => b.updated_at.localeCompare(a.updated_at) || b.conversation_id.localeCompare(a.conversation_id)).slice(params[1], params[1] + params[0]);
76
+ if (sql.includes(' AS first_user_preview')) {
77
+ result = result.map((archive: Row) => {
78
+ const first = [...events.values()].filter(event => event.conversation_id === archive.conversation_id && event.kind === 'user_message')
79
+ .sort((a, b) => a.sequence - b.sequence)[0];
80
+ return { ...archive, first_user_preview: first ? Array.from(String(first.content)).slice(0, 96).join('') : null };
81
+ });
82
+ }
76
83
  } else if (sql.startsWith('INSERT INTO bz_agent_conversation_members')) {
77
84
  const row = structuredClone(params[0]);
78
85
  const key = `${row.conversation_id}:${row.session_id}`;
@@ -105,6 +112,7 @@ export function conversationAuditFixture(options: { crossBinding?: boolean; sche
105
112
  result = [...events.values()].filter((event) => event.conversation_id === params[0]);
106
113
  if (sql.includes('(sequence=? OR event_id=?)')) result = result.filter((event: Row) => event.sequence === params[1] || event.event_id === params[2]);
107
114
  else if (sql.includes("kind='turn_start'")) result = result.filter((event: Row) => event.client_turn_id === params[1] && event.kind === 'turn_start');
115
+ else if (sql.includes('sequence<?')) result = result.filter((event: Row) => event.sequence < params[1]).sort((a: Row, b: Row) => b.sequence - a.sequence).slice(0, params[2]);
108
116
  else if (sql.includes('sequence>?')) result = result.filter((event: Row) => event.sequence > params[1]).sort((a: Row, b: Row) => a.sequence - b.sequence).slice(0, params[2]);
109
117
  }
110
118
  } else throw new Error(`Unexpected synthetic query: ${sql}`);
Binary file
@@ -1,3 +1,3 @@
1
- import{d as te,z as ne,c as M,S as t,J as l,u as N,R as $,r as f,ai as i,o as v,I as g,P as n,Q as _,O as E,K as oe,e as o,a0 as se,a3 as ue,q as ie,as as de}from"./vendor-vue-DhbG0vd4.js";import{aj as re,E as j}from"./vendor-element-BT8tHCFk.js";import{a as S}from"./request-rqm6MT0s.js";import{f as me,c as pe}from"./util-B40VqOwl.js";import{u as fe}from"./index-MjZJEFIN.js";import{H as x}from"./HelpTip-DLlhaGQp.js";import{u as ve}from"./use-unsaved-form-DScKD0h9.js";import{_ as _e}from"./_plugin-vue_export-helper-DlAUqK2U.js";import"./form-guard-8GrFpry0.js";const ce={class:"head"},be={class:"account-main"},ge={class:"account-stack"},ye={class:"muted"},we={class:"account-stack"},ke={class:"muted"},Ve=te({__name:"Accounts",setup(Ce){const U={admin:"全能",kb_editor:"知识库维护",viewer:"只读任务",usage_operator:"用量管理",usage_auditor:"用量只读"},q=fe(),T=f([]),B=f(["admin","kb_editor","viewer"]),p=f(!1),y=f(!1),r=f(!1),d=f(!1),O=f(!1),m=f(""),c=f(""),u=ie({username:"",display_name:"",role:"kb_editor",password:"",enabled:!0}),w=ve({active:()=>p.value,saving:()=>r.value,snapshot:()=>u,name:"后台账号"});async function R(){await w.confirmLeave()&&(p.value=!1)}async function V(){var s;if(!d.value){d.value=!0,m.value="";try{const e=await S("/admin/api/admins");T.value=e.list,(s=e.roles)!=null&&s.length&&(B.value=e.roles),O.value=!0}catch(e){m.value=e.message}finally{d.value=!1}}}function z(s){return s==="admin"?"admin":s==="kb_editor"?"kb_editor":s==="viewer"?"viewer":s}function F(s){return s?`最近登录 ${me(s)}`:"从未登录"}function H(){d.value||m.value||p.value||r.value||(y.value=!1,Object.assign(u,{username:"",display_name:"",role:"kb_editor",password:"",enabled:!0}),c.value="",p.value=!0,w.begin())}function J(s){d.value||m.value||p.value||r.value||(y.value=!0,Object.assign(u,{username:s.username,display_name:s.display_name||"",role:s.role,password:"",enabled:!!s.enabled}),c.value="",p.value=!0,w.begin())}async function P(){if(r.value)return;r.value=!0,c.value="";let s;try{s=await S("/admin/api/admins",{method:"POST",body:JSON.stringify(u)})}catch(e){c.value=e.message,r.value=!1;return}if(w.markSaved(),p.value=!1,r.value=!1,u.password="",V(),s.generated_password)try{await re.alert(`账号 ${s.username} 的初始密码(只显示这一次,请立即保存):
1
+ import{d as te,z as ne,c as M,S as t,J as l,u as N,R as $,r as f,ai as i,o as v,I as g,P as n,Q as _,O as E,K as oe,e as o,a0 as se,a3 as ue,q as ie,as as de}from"./vendor-vue-DhbG0vd4.js";import{aj as re,E as j}from"./vendor-element-BCC2kYn_.js";import{a as S}from"./request-WgSVj8ie.js";import{f as me,c as pe}from"./util-C0YJ70YU.js";import{u as fe}from"./index-CbI5fbiD.js";import{H as x}from"./HelpTip-piedkqU-.js";import{u as ve}from"./use-unsaved-form-B10XHC-n.js";import{_ as _e}from"./_plugin-vue_export-helper-DlAUqK2U.js";import"./form-guard-8GrFpry0.js";const ce={class:"head"},be={class:"account-main"},ge={class:"account-stack"},ye={class:"muted"},we={class:"account-stack"},ke={class:"muted"},Ve=te({__name:"Accounts",setup(Ce){const U={admin:"全能",kb_editor:"知识库维护",viewer:"只读任务",usage_operator:"用量管理",usage_auditor:"用量只读"},q=fe(),T=f([]),B=f(["admin","kb_editor","viewer"]),p=f(!1),y=f(!1),r=f(!1),d=f(!1),O=f(!1),m=f(""),c=f(""),u=ie({username:"",display_name:"",role:"kb_editor",password:"",enabled:!0}),w=ve({active:()=>p.value,saving:()=>r.value,snapshot:()=>u,name:"后台账号"});async function R(){await w.confirmLeave()&&(p.value=!1)}async function V(){var s;if(!d.value){d.value=!0,m.value="";try{const e=await S("/admin/api/admins");T.value=e.list,(s=e.roles)!=null&&s.length&&(B.value=e.roles),O.value=!0}catch(e){m.value=e.message}finally{d.value=!1}}}function z(s){return s==="admin"?"admin":s==="kb_editor"?"kb_editor":s==="viewer"?"viewer":s}function F(s){return s?`最近登录 ${me(s)}`:"从未登录"}function H(){d.value||m.value||p.value||r.value||(y.value=!1,Object.assign(u,{username:"",display_name:"",role:"kb_editor",password:"",enabled:!0}),c.value="",p.value=!0,w.begin())}function J(s){d.value||m.value||p.value||r.value||(y.value=!0,Object.assign(u,{username:s.username,display_name:s.display_name||"",role:s.role,password:"",enabled:!!s.enabled}),c.value="",p.value=!0,w.begin())}async function P(){if(r.value)return;r.value=!0,c.value="";let s;try{s=await S("/admin/api/admins",{method:"POST",body:JSON.stringify(u)})}catch(e){c.value=e.message,r.value=!1;return}if(w.markSaved(),p.value=!1,r.value=!1,u.password="",V(),s.generated_password)try{await re.alert(`账号 ${s.username} 的初始密码(只显示这一次,请立即保存):
2
2
 
3
3
  ${s.generated_password}`,"账号已创建",{confirmButtonText:"复制密码",distinguishCancelAndClose:!0}),await pe(s.generated_password,"密码已复制")}catch{}else j.success("已保存")}async function K(s){try{await S("/admin/api/admins/"+encodeURIComponent(s),{method:"DELETE"}),await V()}catch(e){j.error(e.message)}}return ne(V),(s,e)=>{const b=i("el-button"),A=i("el-alert"),C=i("el-table-column"),D=i("el-tag"),Q=i("el-popconfirm"),G=i("el-table"),W=i("el-card"),L=i("el-input"),k=i("el-form-item"),X=i("el-option"),Y=i("el-select"),Z=i("el-switch"),h=i("el-form"),ee=i("el-drawer"),le=de("loading");return v(),M($,null,[t(W,{shadow:"never"},{header:l(()=>[o("div",ce,[e[10]||(e[10]=o("b",null,"后台账号",-1)),e[11]||(e[11]=n()),t(x,{title:"后台账号 / 角色"},{default:l(()=>[...e[7]||(e[7]=[o("p",null,"后台账号只用于维护中枢控制台,不等同于业务系统用户,也不参与聊天/工具调用的业务身份。",-1),o("p",null,[n("角色决定可见板块与管理权限:"),o("code",null,"admin"),n(" 管全局配置,"),o("code",null,"kb_editor"),n(" 维护知识库,"),o("code",null,"viewer"),n(" 查看运行记录;"),o("code",null,"usage_operator"),n(" 管理AI额度,"),o("code",null,"usage_auditor"),n(" 只读消费明细。")],-1)])]),_:1}),t(b,{loading:d.value,style:{"margin-left":"auto"},onClick:V},{default:l(()=>[...e[8]||(e[8]=[n("刷新",-1)])]),_:1},8,["loading"]),t(b,{type:"primary",disabled:d.value||!!m.value,onClick:H},{default:l(()=>[...e[9]||(e[9]=[n("新建账号",-1)])]),_:1},8,["disabled"])])]),default:l(()=>[m.value?(v(),g(A,{key:0,title:m.value,type:"error",closable:!1,"show-icon":""},{default:l(()=>[n(_(O.value?"以下为上次读取的旧快照,请刷新后再编辑。":"账号读取失败,请重试。"),1)]),_:1},8,["title"])):E("",!0),oe((v(),g(G,{data:T.value,"empty-text":m.value?"账号读取失败":d.value?"正在读取账号":"暂无账号"},{default:l(()=>[t(C,{label:"账号","min-width":"240","show-overflow-tooltip":""},{default:l(({row:a})=>[o("div",be,[o("b",null,_(a.display_name||a.username),1),o("code",null,_(a.username),1)])]),_:1}),t(C,{label:"角色权限","min-width":"220"},{default:l(({row:a})=>[o("div",ge,[t(D,{type:a.role==="admin"?"warning":"info",effect:"plain"},{default:l(()=>[n(_(z(a.role)),1)]),_:2},1032,["type"]),o("span",ye,_(U[a.role]||"自定义角色"),1)])]),_:1}),t(C,{label:"登录状态","min-width":"190"},{default:l(({row:a})=>[o("div",we,[t(D,{type:a.enabled?"success":"info",effect:"plain"},{default:l(()=>[n(_(a.enabled?"启用":"停用"),1)]),_:2},1032,["type"]),o("span",ke,_(F(a.last_login_at)),1)])]),_:1}),t(C,{"min-width":"80",align:"right"},{default:l(({row:a})=>{var I;return[t(b,{link:"",type:"primary",disabled:d.value||!!m.value,onClick:ae=>J(a)},{default:l(()=>[...e[12]||(e[12]=[n("编辑",-1)])]),_:1},8,["disabled","onClick"]),a.username!==((I=N(q).me)==null?void 0:I.username)?(v(),g(Q,{key:0,title:"删除该账号?其登录会话立即失效。",width:"240",onConfirm:ae=>K(a.username)},{reference:l(()=>[t(b,{link:"",type:"danger",disabled:d.value||!!m.value},{default:l(()=>[...e[13]||(e[13]=[n("删",-1)])]),_:1},8,["disabled"])]),_:1},8,["onConfirm"])):E("",!0)]}),_:1})]),_:1},8,["data","empty-text"])),[[le,d.value]])]),_:1}),t(ee,{modelValue:p.value,"onUpdate:modelValue":e[6]||(e[6]=a=>p.value=a),title:y.value?"编辑账号":"新建账号",size:"420px","before-close":N(w).beforeClose},{footer:l(()=>[t(b,{disabled:r.value,onClick:R},{default:l(()=>[...e[23]||(e[23]=[n("取消",-1)])]),_:1},8,["disabled"]),t(b,{type:"primary",loading:r.value,onClick:P},{default:l(()=>[...e[24]||(e[24]=[n("保存",-1)])]),_:1},8,["loading"])]),default:l(()=>[c.value?(v(),g(A,{key:0,title:c.value,type:"error",closable:!1,"show-icon":"",style:{"margin-bottom":"12px"}},null,8,["title"])):E("",!0),t(h,{name:"managed-account-settings",autocomplete:"off","label-position":"top",disabled:r.value,onSubmit:e[5]||(e[5]=se(()=>{},["prevent"]))},{default:l(()=>[t(k,null,{label:l(()=>[...e[14]||(e[14]=[n("用户名 ",-1),o("span",{class:"field-required"},"必填",-1)])]),default:l(()=>[t(L,{modelValue:u.username,"onUpdate:modelValue":e[0]||(e[0]=a=>u.username=a),name:"managed-account-username",autocomplete:"off",disabled:y.value,placeholder:"如 ops-admin",class:"mono"},null,8,["modelValue","disabled"])]),_:1}),t(k,{label:"显示名(可选)"},{default:l(()=>[t(L,{modelValue:u.display_name,"onUpdate:modelValue":e[1]||(e[1]=a=>u.display_name=a)},null,8,["modelValue"])]),_:1}),t(k,null,{label:l(()=>[e[16]||(e[16]=n("角色 ",-1)),e[17]||(e[17]=o("span",{class:"field-required"},"必填",-1)),e[18]||(e[18]=n()),t(x,{title:"角色"},{default:l(()=>[...e[15]||(e[15]=[o("p",null,[o("b",null,"admin"),n(":管理全局配置与账号;"),o("b",null,"kb_editor"),n(":维护知识库;"),o("b",null,"viewer"),n(":只读查看运行记录;"),o("b",null,"usage_operator"),n(":管理AI额度;"),o("b",null,"usage_auditor"),n(":只读消费明细。用量角色不会获得业务会话正文权限。")],-1)])]),_:1})]),default:l(()=>[t(Y,{modelValue:u.role,"onUpdate:modelValue":e[2]||(e[2]=a=>u.role=a),style:{width:"100%"}},{default:l(()=>[(v(!0),M($,null,ue(B.value,a=>(v(),g(X,{key:a,value:a,label:a+(U[a]?"("+U[a]+")":"")},null,8,["value","label"]))),128))]),_:1},8,["modelValue"])]),_:1}),t(k,null,{label:l(()=>[e[20]||(e[20]=n("密码 ",-1)),t(x,{title:"密码"},{default:l(()=>[...e[19]||(e[19]=[o("p",null,"新建时留空会自动生成,并只显示一次。编辑时留空表示不修改;填写后该账号其他登录会话会立即下线。",-1)])]),_:1})]),default:l(()=>[t(L,{modelValue:u.password,"onUpdate:modelValue":e[3]||(e[3]=a=>u.password=a),name:"managed-account-new-password",type:"password","show-password":"",autocomplete:"new-password",placeholder:"至少 8 位"},null,8,["modelValue"])]),_:1}),y.value?(v(),g(k,{key:0},{label:l(()=>[e[22]||(e[22]=n("启用 ",-1)),t(x,{title:"启用状态"},{default:l(()=>[...e[21]||(e[21]=[o("p",null,"停用账号会立即使其登录会话失效。",-1)])]),_:1})]),default:l(()=>[t(Z,{modelValue:u.enabled,"onUpdate:modelValue":e[4]||(e[4]=a=>u.enabled=a)},null,8,["modelValue"])]),_:1})):E("",!0)]),_:1},8,["disabled"])]),_:1},8,["modelValue","title","before-close"])],64)}}}),De=_e(Ve,[["__scopeId","data-v-a51ceecc"]]);export{De as default};