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
@@ -0,0 +1,103 @@
1
+ <?php
2
+
3
+ // Run with PHP >= 7.3. An optional SDK root verifies an extracted distribution:
4
+ // php tests/declaration-serialization.php /path/to/bailing-connect-php7
5
+ $sdkRoot = isset($argv[1]) ? rtrim($argv[1], '/\\') : dirname(__DIR__);
6
+ require_once $sdkRoot . '/src/ToolDef.php';
7
+ require_once $sdkRoot . '/src/ToolSpec.php';
8
+
9
+ use Bailing\Connect\ToolDef;
10
+ use Bailing\Connect\ToolSpec;
11
+
12
+ $checks = 0;
13
+ $errors = array();
14
+ $matrix = array();
15
+ $idempotence = array();
16
+
17
+ function serializationCheck($condition, $label)
18
+ {
19
+ global $checks, $errors;
20
+ $checks++;
21
+ if (!$condition) {
22
+ $errors[] = $label;
23
+ }
24
+ }
25
+
26
+ function generatedCapability($method, $readonly, $risk, $idempotent = null, $governance = false)
27
+ {
28
+ $builder = ToolSpec::create('Synthetic declaration regression')->tool(
29
+ 'serialization_case', $method, '/serialization-case', 'example.record.read',
30
+ 'Synthetic declaration regression case',
31
+ function (ToolDef $tool) use ($method, $readonly, $risk, $idempotent, $governance) {
32
+ if ($method === 'GET') {
33
+ $tool->query('record_id', 'integer', true);
34
+ } else {
35
+ $tool->body('record_id', 'integer', true);
36
+ }
37
+ if ($readonly !== null) $tool->readonly($readonly);
38
+ if ($risk !== null) $tool->risk($risk);
39
+ if ($idempotent !== null) $tool->idempotent($idempotent);
40
+ if ($governance) {
41
+ $tool->requiresSubject()->confirm('Approve {record_id}')->confirmWhen(array(
42
+ array('param' => 'record_id', 'op' => '>', 'value' => 100),
43
+ ));
44
+ }
45
+ }
46
+ );
47
+ // Test the actual JSON wire output, not a copied private serialization function.
48
+ $spec = json_decode($builder->buildJson(false), true);
49
+ if (!is_array($spec) || !isset($spec['paths']['/serialization-case'][strtolower($method)]['x-agent-capability'])) {
50
+ throw new RuntimeException('Generator did not emit a valid ACC operation');
51
+ }
52
+ return $spec['paths']['/serialization-case'][strtolower($method)]['x-agent-capability'];
53
+ }
54
+
55
+ foreach (array('GET', 'POST') as $method) {
56
+ foreach (array(null, false, true) as $readonly) {
57
+ foreach (array(null, 'low', 'medium', 'high') as $risk) {
58
+ $capability = generatedCapability($method, $readonly, $risk);
59
+ $execution = isset($capability['execution']) ? $capability['execution'] : array();
60
+ $label = $method . '/readonly=' . json_encode($readonly) . '/risk=' . json_encode($risk);
61
+ serializationCheck($capability['version'] === 1 && $capability['enabled'] === true && $capability['scope'] === 'example.record.read', $label . ': declaration identity');
62
+ serializationCheck(array_key_exists('risk', $capability) === ($risk !== null), $label . ': risk presence');
63
+ if ($risk !== null) serializationCheck(isset($capability['risk']['level']) && $capability['risk']['level'] === $risk, $label . ': risk value');
64
+ serializationCheck(array_key_exists('readonly', $execution) === ($readonly !== null), $label . ': readonly presence');
65
+ if ($readonly !== null) serializationCheck(array_key_exists('readonly', $execution) && $execution['readonly'] === $readonly, $label . ': readonly value');
66
+ serializationCheck(!array_key_exists('idempotent', $execution), $label . ': unset idempotent remains omitted');
67
+
68
+ // ACC v1 + OpenAPI binding: explicit values win; GET is only a fallback.
69
+ $expectedReadonly = $readonly === null ? $method === 'GET' : $readonly;
70
+ $expectedRisk = $risk === null ? ($expectedReadonly ? 'low' : 'medium') : $risk;
71
+ $wireReadonly = array_key_exists('readonly', $execution) ? $execution['readonly'] : $method === 'GET';
72
+ $effectiveRisk = isset($capability['risk']['level']) ? $capability['risk']['level'] : ($wireReadonly ? 'low' : 'medium');
73
+ serializationCheck($effectiveRisk === $expectedRisk, $label . ': effective risk');
74
+ $matrix[] = array('method' => $method, 'readonly' => $readonly, 'risk' => $risk, 'capability' => $capability, 'expectedRisk' => $expectedRisk, 'effectiveRisk' => $effectiveRisk);
75
+ }
76
+ }
77
+ foreach (array(null, false, true) as $idempotent) {
78
+ $capability = generatedCapability($method, null, null, $idempotent);
79
+ $execution = isset($capability['execution']) ? $capability['execution'] : array();
80
+ $label = $method . '/idempotent=' . json_encode($idempotent);
81
+ serializationCheck(array_key_exists('idempotent', $execution) === ($idempotent !== null), $label . ': presence');
82
+ if ($idempotent !== null) serializationCheck(array_key_exists('idempotent', $execution) && $execution['idempotent'] === $idempotent, $label . ': value');
83
+ serializationCheck(!array_key_exists('risk', $capability) && !array_key_exists('readonly', $execution), $label . ': unrelated unset fields remain omitted');
84
+ $idempotence[] = array('method' => $method, 'idempotent' => $idempotent, 'capability' => $capability);
85
+ }
86
+ }
87
+
88
+ $governance = generatedCapability('POST', false, 'low', false, true);
89
+ serializationCheck($governance === array(
90
+ 'version' => 1, 'enabled' => true, 'scope' => 'example.record.read',
91
+ 'risk' => array('level' => 'low'),
92
+ 'approval' => array('required' => true, 'when' => array(array('param' => 'record_id', 'op' => '>', 'value' => 100)), 'prompt' => 'Approve {record_id}'),
93
+ 'subject' => array('required' => true),
94
+ 'execution' => array('readonly' => false, 'idempotent' => false),
95
+ ), 'explicit low and false do not remove approval or subject requirements');
96
+
97
+ echo json_encode(array(
98
+ 'sdk' => 'php7', 'phpVersion' => PHP_VERSION,
99
+ 'matrixCases' => count($matrix), 'idempotenceCases' => count($idempotence),
100
+ 'checks' => $checks, 'passed' => !$errors, 'errors' => $errors,
101
+ 'matrix' => $matrix, 'idempotence' => $idempotence,
102
+ ), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
103
+ exit($errors ? 1 : 0);
@@ -105,3 +105,11 @@ job = hub.run(
105
105
  result = hub.get_job(job["job_id"])
106
106
  hub.send("notice_1001", "team-im", "user_001", "任务已完成")
107
107
  ```
108
+
109
+ ## 声明字段的省略与显式值
110
+
111
+ 未设置的 `risk`、`readonly`、`idempotent` 不会写入 ACC 声明。显式的 `risk: low/medium/high` 和布尔值 `false/true` 都会保留,包括 GET 上的 `false`。省略风险时,按 ACC OpenAPI binding:显式只读优先于 HTTP 方法;未声明只读的 GET 默认 low,其余非只读操作默认 medium。风险声明不代替审批或业务最终授权。
112
+
113
+ 升级后应重新生成声明并比较差异;不要把以前省略的字段一律补成 low。 `tool()["risk"]` 在未设置时现在为 `None`,不再是 `"low"`;直接读取构建中间对象的调用方需兼容未设置状态。
114
+
115
+ 回归:`python3 sdk/python/tests/test_declaration.py`(24种只读/风险组合及6种幂等组合)。
@@ -85,7 +85,7 @@ def tool(**opts):
85
85
  "path": opts["path"],
86
86
  "method": str(opts.get("method", "GET")).upper(),
87
87
  "name": opts.get("name"),
88
- "risk": opts.get("risk", "low"),
88
+ "risk": opts.get("risk"),
89
89
  "confirm": bool(opts.get("confirm", False)),
90
90
  "confirmWhen": opts.get("confirmWhen", []),
91
91
  "readonly": opts.get("readonly"),
@@ -130,7 +130,7 @@ def _normalize_rate_limit(value: Any) -> Optional[Dict[str, Any]]:
130
130
 
131
131
  def _build_capability(t: Dict[str, Any], method: str) -> Dict[str, Any]:
132
132
  capability: Dict[str, Any] = {"version": 1, "enabled": True, "scope": t["scope"]}
133
- if t.get("risk") and t["risk"] != "low":
133
+ if t.get("risk") is not None:
134
134
  capability["risk"] = {"level": t["risk"]}
135
135
  if t.get("confirm") or t.get("confirmWhen") or t.get("confirmPrompt"):
136
136
  approval: Dict[str, Any] = {}
@@ -144,10 +144,10 @@ def _build_capability(t: Dict[str, Any], method: str) -> Dict[str, Any]:
144
144
  if t.get("requiresSubject"):
145
145
  capability["subject"] = {"required": True}
146
146
  execution: Dict[str, Any] = {}
147
- if t.get("readonly") is True and method != "GET":
148
- execution["readonly"] = True
149
- if t.get("idempotent") is True and method != "GET":
150
- execution["idempotent"] = True
147
+ if isinstance(t.get("readonly"), bool):
148
+ execution["readonly"] = t["readonly"]
149
+ if isinstance(t.get("idempotent"), bool):
150
+ execution["idempotent"] = t["idempotent"]
151
151
  rate_limit = _normalize_rate_limit(t.get("rateLimit"))
152
152
  if rate_limit:
153
153
  execution["rate_limit"] = rate_limit
@@ -0,0 +1,61 @@
1
+ """Exercise the public builder and its actual JSON output, without business calls."""
2
+ import json
3
+ from pathlib import Path
4
+ import sys
5
+ import unittest
6
+
7
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
8
+ from bailing_connect import build_openapi_spec, param, tool
9
+
10
+
11
+ def capability(method, options):
12
+ spec = build_openapi_spec(tools=[tool(
13
+ name="serialization_fixture", description="Declaration serialization fixture",
14
+ path="/fixture", scope="fixture.write", method=method,
15
+ params=[param("fixture", type="string")], **options)])
16
+ return json.loads(json.dumps(spec))["paths"]["/fixture"][method.lower()]["x-agent-capability"]
17
+
18
+
19
+ class DeclarationTests(unittest.TestCase):
20
+ def test_readonly_risk_matrix(self):
21
+ combinations = 0
22
+ for method in ("GET", "POST"):
23
+ for readonly in (None, False, True):
24
+ for risk in (None, "low", "medium", "high"):
25
+ combinations += 1
26
+ with self.subTest(method=method, readonly=readonly, risk=risk):
27
+ options = {}
28
+ if readonly is not None:
29
+ options["readonly"] = readonly
30
+ if risk is not None:
31
+ options["risk"] = risk
32
+ cap = capability(method, options)
33
+ self.assertEqual("readonly" in cap.get("execution", {}), readonly is not None)
34
+ if readonly is not None:
35
+ self.assertIs(cap["execution"]["readonly"], readonly)
36
+ self.assertEqual("risk" in cap, risk is not None)
37
+ if risk is not None:
38
+ self.assertEqual(cap["risk"]["level"], risk)
39
+ expected_readonly = readonly if readonly is not None else method == "GET"
40
+ expected_risk = risk if risk is not None else ("low" if expected_readonly else "medium")
41
+ actual_readonly = cap.get("execution", {}).get("readonly", method == "GET")
42
+ actual_risk = cap.get("risk", {}).get("level", "low" if actual_readonly else "medium")
43
+ self.assertEqual(actual_risk, expected_risk)
44
+ self.assertEqual(cap["version"], 1)
45
+ self.assertEqual(combinations, 24)
46
+
47
+ def test_idempotent_presence_and_value(self):
48
+ combinations = 0
49
+ for method in ("GET", "POST"):
50
+ for value in (None, False, True):
51
+ combinations += 1
52
+ with self.subTest(method=method, idempotent=value):
53
+ cap = capability(method, {} if value is None else {"idempotent": value})
54
+ self.assertEqual("idempotent" in cap.get("execution", {}), value is not None)
55
+ if value is not None:
56
+ self.assertIs(cap["execution"]["idempotent"], value)
57
+ self.assertEqual(combinations, 6)
58
+
59
+
60
+ if __name__ == "__main__":
61
+ unittest.main()
@@ -1,6 +1,7 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import test from 'node:test';
3
- import { filterLoadedRuns, patchTaskQuery, readOutboxLocation, readRunFilters, readRunsLocation, RUN_FILTER_STATUSES, runsTabQuery, safeTaskReturnPath } from '../../../web-admin/src/task-page-location';
3
+ import { jobStatusLabel } from '../../../web-admin/src/task-trace-presentation';
4
+ import { runFilterParams, patchTaskQuery, readOutboxLocation, readRunFilters, readRunsLocation, RUN_FILTER_STATUSES, runsTabQuery, safeTaskReturnPath } from '../../../web-admin/src/task-page-location';
4
5
 
5
6
  test('task tabs restore canonical and legacy links without a job stealing an explicit delivery tab', () => {
6
7
  assert.equal(readRunsLocation({ tab: 'outbox', job: 'original' }).tab, 'notifications');
@@ -37,28 +38,15 @@ test('job filters accept the actual job status contract and keep diagnostic and
37
38
  assert.deepEqual(readRunFilters(query), { status: '', route: 'orders', period: '7d' });
38
39
  assert.equal(query.detail, 'original-job'); assert.equal(query.return_to, '/diagnostics'); assert.equal(query.future, 'kept');
39
40
  });
40
- test('loaded job filtering composes exact status and route without searching body text', () => {
41
- const rows = [
42
- { id: 'match', status: 'error', route_key: 'orders', created_at: '2026-10-21T00:00:00Z' },
43
- { id: 'prefix', status: 'error', route_key: 'orders-next', input_preview: 'orders', created_at: '2026-10-21T00:00:00Z' },
44
- { id: 'body-only', status: 'error', input_preview: 'orders', created_at: '2026-10-21T00:00:00Z' },
45
- { id: 'wrong-status', status: 'done', route_key: 'orders', created_at: '2026-10-21T00:00:00Z' },
46
- { id: 'old', status: 'error', route_key: 'orders', created_at: '2026-10-10T00:00:00Z' },
47
- ];
48
- const found = filterLoadedRuns(rows, { status: 'error', route: 'orders', period: '24h' }, Date.parse('2026-10-21T10:00:00Z'));
49
- assert.deepEqual(found.map(row => row.id), ['match']);
50
- assert.equal(rows.length, 5, 'filtering does not mutate or replace the loaded snapshot');
51
- assert.deepEqual(filterLoadedRuns(rows, { status: '', route: '', period: 'all' }, 0), rows);
41
+ test('dispatch filters are sent to the server, including routes outside the loaded page', () => {
42
+ const filters = readRunFilters({ run_status: 'error', run_route: 'orders & returns', run_period: '24h' });
43
+ assert.deepEqual(Object.fromEntries(runFilterParams(filters)), { status: 'error', route_key: 'orders & returns', period: '24h' });
44
+ assert.equal(runFilterParams(readRunFilters({})).toString(), '');
45
+ assert.deepEqual(Object.fromEntries(runFilterParams(readRunFilters({ run_period: '7d' }))), { period: '7d' });
52
46
  });
53
- test('time windows include their exact boundary and exclude invalid, future, and older timestamps', () => {
54
- const now = Date.parse('2026-10-21T10:00:00Z');
55
- const rows = [
56
- { id: '24h', created_at: new Date(now - 86400000).toISOString() },
57
- { id: '7d', created_at: new Date(now - 7 * 86400000).toISOString() },
58
- { id: 'older', created_at: new Date(now - 7 * 86400000 - 1).toISOString() },
59
- { id: 'future', created_at: new Date(now + 1).toISOString() },
60
- { id: 'invalid', created_at: 'unknown' },
61
- ];
62
- assert.deepEqual(filterLoadedRuns(rows, { status: '', route: '', period: '24h' }, now).map(row => row.id), ['24h']);
63
- assert.deepEqual(filterLoadedRuns(rows, { status: '', route: '', period: '7d' }, now).map(row => row.id), ['24h', '7d']);
47
+
48
+ test('job status labels cover the job lifecycle and preserve unknown raw values', () => {
49
+ assert.deepEqual(RUN_FILTER_STATUSES.map(jobStatusLabel), ['等待执行', '执行中', '已派发', '已完成', '执行错误', '已拒绝']);
50
+ for (const status of [undefined, null, ' ', '']) assert.equal(jobStatusLabel(status), '未记录');
51
+ for (const status of ['paused', 'completed', 'constructor', 'toString', '__proto__']) assert.equal(jobStatusLabel(status), status);
64
52
  });
@@ -0,0 +1,62 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { compileOpenApiTools } from './openapi-tools';
4
+
5
+ function compile(method: string, capability: Record<string, unknown>) {
6
+ const result = compileOpenApiTools(JSON.stringify({
7
+ openapi: '3.0.0',
8
+ info: { title: 'Explicit capability values', version: '1' },
9
+ paths: {
10
+ '/fixture': {
11
+ [method.toLowerCase()]: {
12
+ operationId: 'fixture_operation',
13
+ summary: 'Isolated declaration fixture',
14
+ parameters: [{ name: 'id', in: 'query', schema: { type: 'string' } }],
15
+ 'x-agent-capability': { version: 1, enabled: true, scope: 'fixture.operation', ...capability },
16
+ },
17
+ },
18
+ },
19
+ }));
20
+ assert.equal(result.diagnostics.filter(d => d.severity === 'error').length, 0);
21
+ assert.equal(result.tools.length, 1);
22
+ return result.tools[0]!;
23
+ }
24
+
25
+ for (const method of ['GET', 'POST']) {
26
+ for (const readonly of [undefined, false, true]) {
27
+ for (const risk of [undefined, 'low', 'medium', 'high']) {
28
+ test(`ACC explicit values: ${method}, readonly=${readonly}, risk=${risk}`, () => {
29
+ const tool = compile(method, {
30
+ ...(readonly === undefined ? {} : { execution: { readonly } }),
31
+ ...(risk === undefined ? {} : { risk: { level: risk } }),
32
+ });
33
+ const expectedReadonly = readonly ?? (method === 'GET');
34
+ assert.equal(tool.readonly, expectedReadonly);
35
+ assert.equal(tool.risk, risk ?? (expectedReadonly ? 'low' : 'medium'));
36
+ });
37
+ }
38
+ }
39
+ for (const idempotent of [undefined, false, true]) {
40
+ test(`ACC explicit idempotency: ${method}, idempotent=${idempotent}`, () => {
41
+ const tool = compile(method, idempotent === undefined ? {} : { execution: { idempotent } });
42
+ assert.equal(tool.idempotent, idempotent ?? (method === 'GET'));
43
+ });
44
+ }
45
+ }
46
+
47
+ test('Explicit low risk does not erase approval or subject requirements', () => {
48
+ const conditions = [{ param: 'id', op: '==', value: 'review' }];
49
+ const tool = compile('POST', {
50
+ risk: { level: 'low' },
51
+ execution: { readonly: false, idempotent: false },
52
+ approval: { required: true, when: conditions, prompt: 'Review this operation' },
53
+ subject: { required: true },
54
+ audit: { sensitive: true },
55
+ });
56
+ assert.equal(tool.risk, 'low');
57
+ assert.equal(tool.confirmRequired, true);
58
+ assert.deepEqual(tool.confirmWhen, conditions);
59
+ assert.equal(tool.confirmPrompt, 'Review this operation');
60
+ assert.equal(tool.requiresSubject, true);
61
+ assert.equal(tool.sensitive, true);
62
+ });
@@ -129,7 +129,7 @@ export function compileOpenApiTools(specText: string): ToolCompileResult {
129
129
  const confirmWhen = parseConfirmWhen(ann.confirmWhen, loc, diagnostics);
130
130
  if (confirmWhen === null) continue;
131
131
 
132
- const ro = m === 'GET' ? true : ann.readonly === true;
132
+ const ro = ann.readonly ?? (m === 'GET');
133
133
  const inputSchema = { type: 'object', properties: props, ...(required.length ? { required: [...new Set(required)] } : {}) };
134
134
  const tool: ToolDefinition = {
135
135
  schemaVersion: TOOL_DEFINITION_SCHEMA_VERSION,
@@ -148,7 +148,7 @@ export function compileOpenApiTools(specText: string): ToolCompileResult {
148
148
  requiresSubject: ann.requiresSubject,
149
149
  sensitive: ann.sensitive,
150
150
  readonly: ro,
151
- idempotent: m === 'GET' ? true : ann.idempotent === true,
151
+ idempotent: ann.idempotent ?? (m === 'GET'),
152
152
  timeoutMs: ann.timeoutMs,
153
153
  ...(confirmWhen.length ? { confirmWhen } : {}),
154
154
  confirmPrompt: ann.confirmPrompt,
@@ -52,8 +52,8 @@ export function toolAnnotationsOf(op: Record<string, unknown>): ToolAnnotations
52
52
  rateLimitPerMin: rateLimit ? rateLimitToPerMin(rateLimit) : 0,
53
53
  requiresSubject: subject?.['required'] === true,
54
54
  sensitive: audit?.['sensitive'] === true,
55
- readonly: execution?.['readonly'] === true ? true : null,
56
- idempotent: execution?.['idempotent'] === true ? true : null,
55
+ readonly: typeof execution?.['readonly'] === 'boolean' ? execution['readonly'] : null,
56
+ idempotent: typeof execution?.['idempotent'] === 'boolean' ? execution['idempotent'] : null,
57
57
  timeoutPresent: !!execution && Object.hasOwn(execution, 'timeout_ms'),
58
58
  timeoutRaw: execution?.['timeout_ms'],
59
59
  timeoutMs: parseTimeout(execution?.['timeout_ms']),
@@ -67,10 +67,10 @@ export function toolAnnotationsOf(op: Record<string, unknown>): ToolAnnotations
67
67
  };
68
68
  }
69
69
 
70
- export function deriveRisk(explicit: unknown, method: string, readonly: boolean): ToolRisk {
70
+ export function deriveRisk(explicit: unknown, _method: string, readonly: boolean): ToolRisk {
71
71
  const v = String(explicit ?? '').toLowerCase();
72
72
  if (v === 'low' || v === 'medium' || v === 'high') return v;
73
- return method !== 'GET' && !readonly ? 'medium' : 'low';
73
+ return readonly ? 'low' : 'medium';
74
74
  }
75
75
 
76
76
  function parseRateLimit(v: unknown): ToolRateLimit | undefined {
@@ -27,15 +27,15 @@ function usableDbCredential(c: Credential | null): ResolvedLlmCredential | null
27
27
  export async function resolveLlmCredential(
28
28
  name: string,
29
29
  cfg: Pick<AppConfig, 'llmCredentials'>,
30
- store?: CredentialStoreLike | null,
30
+ store?: (Pick<CredentialStoreLike, 'get'> & Partial<Pick<CredentialStoreLike, 'touch'>>) | null,
31
31
  ): Promise<ResolvedCredentialRef | null> {
32
32
  const credName = String(name ?? '').trim();
33
33
  if (!credName) return null;
34
- const fileCred = cfg.llmCredentials[credName] as ResolvedLlmCredential | undefined;
34
+ const fileCred = Object.hasOwn(cfg.llmCredentials, credName) ? cfg.llmCredentials[credName] : undefined;
35
35
  if (fileCred) return { name: credName, source: 'config', credential: fileCred };
36
36
  const dbCred = usableDbCredential(store ? await store.get(credName).catch(() => null) : null);
37
37
  if (!dbCred) return null;
38
- void store?.touch(credName).catch(() => { /* 观测字段 */ });
38
+ void store?.touch?.(credName).catch(() => { /* 观测字段 */ });
39
39
  return { name: credName, source: 'db', credential: dbCred };
40
40
  }
41
41
 
@@ -68,6 +68,35 @@ test('full visible events are stored once, paginated without truncation, and lin
68
68
  for (const id of [AUDIT_SESSION_A, AUDIT_SESSION_B]) assert.ok(fx.queries.slice(0, writeIndex).some(({ sql, params, transactional }) => sql.includes('FROM bz_agent_sessions') && sql.includes('FOR UPDATE') && params[0] === id && transactional));
69
69
  });
70
70
 
71
+ test('admin titles take a bounded preview from the first user message of each exact archive', async () => {
72
+ const fx = conversationAuditFixture();
73
+ const first = await fx.ready();
74
+ const input = fx.input({ client_archive_id: '423e4567-e89b-42d3-a456-426614174001' });
75
+ const other = await fx.repo.create(fx.auth(), input);
76
+ await fx.repo.confirm(fx.auth(AUDIT_SESSION_B), other.conversation_id);
77
+ const turn = { client_turn_id: 'turn-1' };
78
+ const start = { ...turn, sequence: 1, event_id: 'start', kind: 'turn_start' as const };
79
+ const assistant = { ...turn, sequence: 2, event_id: 'reply', kind: 'assistant_message' as const, content: 'Assistant-only record' };
80
+ const preview = '门'.repeat(95) + '🚀';
81
+ await fx.repo.append(fx.auth(), first.conversation_id, [
82
+ start, assistant, { ...turn, sequence: 3, event_id: 'user-1', kind: 'user_message', content: preview + 'TAIL' },
83
+ { ...turn, sequence: 4, event_id: 'user-2', kind: 'user_message', content: 'Later message' },
84
+ ]);
85
+ await fx.repo.append(fx.auth(), other.conversation_id, [start, assistant]);
86
+
87
+ const queryCount = fx.queries.length;
88
+ const list = await fx.repo.listForAdmin();
89
+ assert.equal(fx.queries.length - queryCount, 1);
90
+ assert.deepEqual(new Map(list.items.map((row: any) => [row.conversation_id, row.first_user_preview])), new Map([
91
+ [first.conversation_id, preview], [other.conversation_id, null],
92
+ ]));
93
+ const afterUser = await fx.repo.detailForAdmin(first.conversation_id, 3, 1);
94
+ assert.equal(afterUser!.conversation.first_user_preview, preview);
95
+ assert.equal(afterUser!.events[0].content, 'Later message');
96
+ const retry = await fx.repo.create(fx.auth(), fx.input());
97
+ assert.ok(!Object.hasOwn(retry, 'first_user_preview'));
98
+ });
99
+
71
100
  test('changed retries, gaps and event-id reuse fail atomically', async () => {
72
101
  const fx = conversationAuditFixture();
73
102
  const created = await fx.ready();
@@ -1,8 +1,9 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { CHANNEL_DELIVERY_MESSAGE_SQL } from './conversation-delivery-message';
2
3
  import { dt, rowClient, rowRoute } from '../../core/config/config-codec';
3
4
  import type { AgentSession, Client, Route } from '../../core/contracts/types';
4
5
  import {
5
- assertAuditMemberActive, auditError, auditHash, auditIdentityHash,
6
+ assertAuditMemberActive, auditError, auditHash, auditIdentityHash, auditUuid, ConversationAuditError,
6
7
  CONVERSATION_AUDIT_MAX_BYTES, CONVERSATION_AUDIT_MAX_EVENTS,
7
8
  type CreateConversationAuditInput, type ConversationAuditEventInput,
8
9
  type CreateCrossBindingConversationAuditInput,
@@ -10,6 +11,22 @@ import {
10
11
 
11
12
  type Auth = { session: AgentSession; client: Client };
12
13
  type Row = Record<string, any>;
14
+ export const ADMIN_CONVERSATION_SOURCES = ['all', 'client', 'web', 'wecom', 'delivery', 'other'] as const;
15
+ export type AdminConversationSource = (typeof ADMIN_CONVERSATION_SOURCES)[number];
16
+ type FeedCursor = { at: Date; kind: 'audit' | 'thread'; id: number | string; position: number };
17
+
18
+ function readFeedCursor(raw: string, source: AdminConversationSource): FeedCursor {
19
+ const parts = raw.split('|');
20
+ const [issuedFor, time, kind, id, position] = parts;
21
+ const at = new Date(time ?? '');
22
+ if (parts.length !== 5 || issuedFor !== source || !time || !Number.isFinite(at.getTime()) ||
23
+ at.toISOString() !== time || !position || !/^\d+$/.test(position) || !Number.isSafeInteger(Number(position)) ||
24
+ !id || (kind !== 'audit' && (kind !== 'thread' || !/^[1-9]\d*$/.test(id) || !Number.isSafeInteger(Number(id))))) {
25
+ throw new ConversationAuditError(400, 'invalid_request', 'Invalid conversation feed cursor.');
26
+ }
27
+ return { at, kind, id: kind === 'audit' ? auditUuid(id) : Number(id), position: Number(position) };
28
+ }
29
+
13
30
  const SESSION_COLUMNS = 'session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,created_at,access_expires_at,refresh_expires_at,revoked_at';
14
31
 
15
32
  function json(value: unknown): any {
@@ -39,6 +56,18 @@ function head(row: Row): Row {
39
56
  };
40
57
  }
41
58
 
59
+ // Admin-only projection. The primary key (conversation_id, sequence) scopes the
60
+ // lookup to this archive and orders it in the same sequence as the transcript.
61
+ const ADMIN_HEAD_COLUMNS = `a.*, (
62
+ SELECT LEFT(e.content, 96) FROM bz_agent_conversation_events e
63
+ WHERE e.conversation_id = a.conversation_id AND e.kind = 'user_message'
64
+ ORDER BY e.sequence LIMIT 1
65
+ ) AS first_user_preview`;
66
+
67
+ function adminHead(row: Row): Row {
68
+ return { ...head(row), first_user_preview: row.first_user_preview ?? null };
69
+ }
70
+
42
71
  function eventView(row: Row): Row {
43
72
  return {
44
73
  event_id: row.event_id, sequence: Number(row.sequence), client_turn_id: row.client_turn_id, kind: row.kind,
@@ -324,28 +353,132 @@ export class AgentConversationAuditRepository {
324
353
  async listForAdmin(limit = 50, offset = 0): Promise<Row> {
325
354
  const n = Math.min(Math.max(Math.floor(limit) || 50, 1), 100);
326
355
  const off = Math.max(Math.floor(offset) || 0, 0);
327
- const [rows] = await this.pool.query('SELECT * FROM bz_agent_conversation_audits ORDER BY updated_at DESC,conversation_id DESC LIMIT ? OFFSET ?', [n + 1, off]);
328
- const items = (rows as Row[]).slice(0, n).map(head);
356
+ const [rows] = await this.pool.query(`SELECT ${ADMIN_HEAD_COLUMNS} FROM (
357
+ SELECT conversation_id, updated_at FROM bz_agent_conversation_audits
358
+ ORDER BY updated_at DESC, conversation_id DESC LIMIT ? OFFSET ?
359
+ ) page JOIN bz_agent_conversation_audits a ON a.conversation_id = page.conversation_id
360
+ ORDER BY page.updated_at DESC, page.conversation_id DESC`, [n + 1, off]);
361
+ const items = (rows as Row[]).slice(0, n).map(adminHead);
329
362
  return { items, has_more: rows.length > n, next_offset: rows.length > n ? off + n : null };
330
363
  }
331
364
 
332
- async detailForAdmin(conversationId: string, afterSequence = 0, limit = 100): Promise<Row | null> {
333
- const [rows] = await this.pool.query('SELECT * FROM bz_agent_conversation_audits WHERE conversation_id=?', [conversationId]);
365
+ /** Read-only union of client archives, independent inbound threads and delivery-only threads. */
366
+ async listFeedForAdmin(source: AdminConversationSource, limit = 50, offset = 0, after?: string): Promise<Row> {
367
+ const n = Math.min(Math.max(Math.floor(limit) || 50, 1), 100);
368
+ const off = Math.max(Math.floor(offset) || 0, 0);
369
+ const cursor = after === undefined ? null : readFeedCursor(after, source);
370
+ if (cursor && off) throw new ConversationAuditError(400, 'invalid_request', 'Choose cursor or offset pagination.');
371
+ const candidateLimit = Math.min(Number.MAX_SAFE_INTEGER, off + n + 1);
372
+ // At identical times archives precede threads; within each kind IDs descend.
373
+ let archiveWindow = '', threadWindow = '';
374
+ const archiveArgs: unknown[] = [], threadArgs: unknown[] = [];
375
+ if (cursor?.kind === 'audit') {
376
+ archiveWindow = ' AND (a.updated_at, a.conversation_id) < (?, ?)';
377
+ archiveArgs.push(cursor.at, cursor.id);
378
+ threadWindow = ' AND t.last_active_at <= ?';
379
+ threadArgs.push(cursor.at);
380
+ } else if (cursor) {
381
+ archiveWindow = ' AND a.updated_at < ?';
382
+ archiveArgs.push(cursor.at);
383
+ threadWindow = ' AND (t.last_active_at, t.thread_id) < (?, ?)';
384
+ threadArgs.push(cursor.at, cursor.id);
385
+ }
386
+ // Thread identity is not a substitute for a run link. A thread can contain a
387
+ // mixture of archived and unarchived runs. Keep it if any incoming message
388
+ // remains independent; use that message for its title and channel.
389
+ const [rows] = await this.pool.query(`WITH candidates AS (
390
+ (SELECT 'audit' AS kind, 'client' AS source, a.conversation_id, NULL AS thread_id,
391
+ NULL AS first_message_id, a.updated_at
392
+ FROM bz_agent_conversation_audits a WHERE ? IN ('all','client')${archiveWindow}
393
+ ORDER BY a.updated_at DESC, a.conversation_id DESC LIMIT ?)
394
+ UNION ALL
395
+ (SELECT 'thread' AS kind, CASE
396
+ WHEN first_message.channel LIKE 'agent:%' THEN 'client'
397
+ WHEN first_message.channel LIKE 'chat:%' THEN 'web'
398
+ WHEN first_message.channel LIKE 'wecom:%' THEN 'wecom'
399
+ ELSE 'other' END AS source,
400
+ NULL AS conversation_id, t.thread_id, first_message.id AS first_message_id, t.last_active_at AS updated_at
401
+ FROM bz_threads t JOIN bz_messages first_message ON first_message.id=(
402
+ SELECT m.id FROM bz_messages m FORCE INDEX (idx_thread)
403
+ WHERE m.thread_id=t.thread_id AND m.direction='in'
404
+ AND (m.agent_run_id IS NULL OR NOT EXISTS (SELECT 1 FROM bz_agent_conversation_events e
405
+ WHERE e.run_id=m.agent_run_id AND e.thread_id=m.thread_id AND e.kind='run_link'))
406
+ ORDER BY m.id LIMIT 1)
407
+ WHERE ? <> 'delivery'${threadWindow}
408
+ HAVING ?='all' OR source=?
409
+ ORDER BY t.last_active_at DESC, t.thread_id DESC LIMIT ?)
410
+ UNION ALL
411
+ (SELECT 'thread' AS kind, 'delivery' AS source, NULL AS conversation_id, t.thread_id,
412
+ (SELECT m.id FROM bz_messages m FORCE INDEX (idx_thread)
413
+ WHERE m.thread_id=t.thread_id AND ${CHANNEL_DELIVERY_MESSAGE_SQL}
414
+ ORDER BY m.id LIMIT 1) AS first_message_id, t.last_active_at AS updated_at
415
+ FROM bz_threads t
416
+ WHERE ? IN ('all','delivery')${threadWindow}
417
+ AND NOT EXISTS (SELECT 1 FROM bz_messages inbound WHERE inbound.thread_id=t.thread_id AND inbound.direction='in')
418
+ HAVING first_message_id IS NOT NULL
419
+ ORDER BY t.last_active_at DESC, t.thread_id DESC LIMIT ?)
420
+ ), page AS (
421
+ SELECT * FROM candidates ORDER BY updated_at DESC, kind ASC, conversation_id DESC, thread_id DESC LIMIT ? OFFSET ?
422
+ )
423
+ SELECT p.kind, p.source, p.conversation_id, p.thread_id, p.updated_at,
424
+ CASE WHEN p.kind='audit' THEN (
425
+ SELECT LEFT(e.content,96) FROM bz_agent_conversation_events e
426
+ WHERE e.conversation_id=p.conversation_id AND e.kind='user_message' ORDER BY e.sequence LIMIT 1
427
+ ) ELSE LEFT(m.content,96) END AS title,
428
+ CASE WHEN p.source='delivery' THEN
429
+ CASE WHEN t.scope_key LIKE 'wecom:%:%' THEN SUBSTRING_INDEX(SUBSTRING(t.scope_key,7),':',1)
430
+ ELSE '' END
431
+ ELSE COALESCE(a.client_app_id, ce.name, c.name, m.channel) END AS source_label,
432
+ COALESCE(a.route_key,t.route_key) AS route_key, COALESCE(a.message_count,t.message_count) AS message_count,
433
+ a.turn_count, a.last_turn_status, a.state, a.client_conversation_id,
434
+ COALESCE(a.client_app_id, c.app_id, IF(p.source='client', SUBSTRING(m.channel,7), NULL)) AS client_app_id
435
+ FROM page p
436
+ LEFT JOIN bz_agent_conversation_audits a ON a.conversation_id=p.conversation_id
437
+ LEFT JOIN bz_threads t ON t.thread_id=p.thread_id
438
+ LEFT JOIN bz_messages m ON m.id=p.first_message_id
439
+ LEFT JOIN bz_chat_entries ce ON p.source='web' AND ce.entry_key=SUBSTRING(m.channel,6)
440
+ LEFT JOIN bz_clients c ON p.kind='thread' AND p.source IN ('client','other')
441
+ AND c.app_id=IF(p.source='client', SUBSTRING(m.channel,7), m.channel)
442
+ ORDER BY p.updated_at DESC, p.kind ASC, p.conversation_id DESC, p.thread_id DESC`,
443
+ [source, ...archiveArgs, candidateLimit, source, ...threadArgs, source, source, candidateLimit,
444
+ source, ...threadArgs, candidateLimit, n + 1, off]);
445
+ const items: Row[] = (rows as Row[]).slice(0, n).map(row => ({
446
+ ...row, thread_id: row.thread_id == null ? null : Number(row.thread_id),
447
+ updated_at: iso(row.updated_at), message_count: Number(row.message_count),
448
+ turn_count: row.turn_count == null ? null : Number(row.turn_count),
449
+ }));
450
+ const last = items.at(-1);
451
+ const nextOffset = rows.length > n ? (cursor?.position ?? off) + n : null;
452
+ return { items, has_more: nextOffset !== null, next_offset: nextOffset,
453
+ next_cursor: nextOffset !== null && last
454
+ ? [source, last.updated_at, last.kind, last.conversation_id ?? last.thread_id, nextOffset].join('|') : null };
455
+ }
456
+
457
+ async detailForAdmin(conversationId: string, afterSequence = 0, limit = 100, beforeSequence?: number | null): Promise<Row | null> {
458
+ const [rows] = await this.pool.query(`SELECT ${ADMIN_HEAD_COLUMNS} FROM bz_agent_conversation_audits a WHERE a.conversation_id=?`, [conversationId]);
334
459
  if (!rows[0]) return null;
335
460
  const n = Math.min(Math.max(Math.floor(limit) || 100, 1), 200);
336
461
  const after = Math.max(Math.floor(afterSequence) || 0, 0);
337
462
  const [members] = await this.pool.query('SELECT * FROM bz_agent_conversation_members WHERE conversation_id=? ORDER BY session_id', [conversationId]);
338
- const [rowsOfEvents] = await this.pool.query('SELECT * FROM bz_agent_conversation_events WHERE conversation_id=? AND sequence>? ORDER BY sequence LIMIT ?', [conversationId, after, n + 1]);
463
+ const backward = beforeSequence !== undefined;
464
+ const [rowsOfEvents] = backward
465
+ ? await this.pool.query('SELECT * FROM bz_agent_conversation_events WHERE conversation_id=? AND sequence<? ORDER BY sequence DESC LIMIT ?',
466
+ [conversationId, beforeSequence ?? Number(rows[0].last_sequence) + 1, n + 1])
467
+ : await this.pool.query('SELECT * FROM bz_agent_conversation_events WHERE conversation_id=? AND sequence>? ORDER BY sequence LIMIT ?', [conversationId, after, n + 1]);
468
+ const hasMore = rowsOfEvents.length > n;
339
469
  const events = (rowsOfEvents as Row[]).slice(0, n).map(eventView);
470
+ if (backward) events.reverse();
340
471
  return {
341
- conversation: head(rows[0]), members: (members as Row[]).map((member) => ({
472
+ conversation: adminHead(rows[0]), members: (members as Row[]).map((member) => ({
342
473
  session_id: member.session_id, display_label: member.display_label, confirmed: Boolean(member.confirmed_at),
343
474
  ...(Number(rows[0].membership_version) === 2 ? {
344
475
  client_app_id: member.client_app_id, client_name: member.client_name, route_key: member.route_key,
345
476
  } : {}),
346
477
  ...(member.confirmed_at ? { principal: json(member.principal_json), on_behalf_of: member.on_behalf_of } : {}),
347
- })), events, has_more: rowsOfEvents.length > n,
348
- next_after_sequence: events.length ? events.at(-1)!.sequence : after,
478
+ })), events,
479
+ ...(backward
480
+ ? { has_earlier: hasMore, next_before_sequence: hasMore ? events[0]!.sequence : null }
481
+ : { has_more: hasMore, next_after_sequence: events.length ? events.at(-1)!.sequence : after }),
349
482
  };
350
483
  }
351
484