@zhin.js/core 1.5.16 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (328) hide show
  1. package/README.md +78 -195
  2. package/lib/ai-completion-contract.d.ts +135 -0
  3. package/lib/ai-completion-contract.js +69 -0
  4. package/lib/built/ai-access.d.ts +2 -21
  5. package/lib/built/ai-access.js +1 -46
  6. package/lib/built/ai-outbound/index.d.ts +0 -2
  7. package/lib/built/ai-outbound/index.js +0 -2
  8. package/lib/built/ai-outbound/prompt.d.ts +2 -0
  9. package/lib/built/ai-outbound/prompt.js +2 -0
  10. package/lib/built/ai-outbound/types.d.ts +1 -10
  11. package/lib/built/ai-trigger.d.ts +39 -78
  12. package/lib/built/ai-trigger.js +3 -254
  13. package/lib/built/common-adapter-tools.d.ts +21 -6
  14. package/lib/built/common-adapter-tools.js +28 -17
  15. package/lib/built/generic-segment-mapper.js +4 -1
  16. package/lib/built/html-segment-fallback.d.ts +6 -7
  17. package/lib/built/html-segment-fallback.js +1 -16
  18. package/lib/built/html-to-text.d.ts +0 -3
  19. package/lib/built/html-to-text.js +131 -40
  20. package/lib/built/interaction-messages.d.ts +1 -0
  21. package/lib/built/interaction-messages.js +30 -0
  22. package/lib/built/interactive-segments/action.d.ts +3 -4
  23. package/lib/built/interactive-segments/action.js +2 -5
  24. package/lib/built/interactive-segments/index.d.ts +0 -2
  25. package/lib/built/interactive-segments/index.js +0 -2
  26. package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
  27. package/lib/built/interactive-segments/keyboard-segment.js +0 -1
  28. package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
  29. package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
  30. package/lib/built/interactive-segments/resolve.d.ts +2 -3
  31. package/lib/built/interactive-segments/resolve.js +21 -14
  32. package/lib/built/interactive-segments/types.d.ts +2 -7
  33. package/lib/built/interactive-segments/types.js +22 -2
  34. package/lib/built/login-assist.d.ts +13 -11
  35. package/lib/built/login-assist.js +32 -26
  36. package/lib/built/message-enrich.d.ts +24 -27
  37. package/lib/built/message-enrich.js +53 -49
  38. package/lib/built/outbound-content-arrays.d.ts +4 -0
  39. package/lib/built/outbound-content-arrays.js +32 -0
  40. package/lib/built/outbound-media-trust.d.ts +46 -0
  41. package/lib/built/outbound-media-trust.js +245 -0
  42. package/lib/built/outbound-media-utils.d.ts +5 -3
  43. package/lib/built/outbound-media-utils.js +5 -3
  44. package/lib/built/readable-link.d.ts +4 -0
  45. package/lib/built/readable-link.js +32 -0
  46. package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
  47. package/lib/built/rich-segments/markdown-to-text.js +141 -17
  48. package/lib/built/roles.d.ts +141 -12
  49. package/lib/built/roles.js +253 -52
  50. package/lib/built/segment-contract/assert.js +8 -2
  51. package/lib/built/segment-contract/delivery.js +1 -0
  52. package/lib/built/segment-contract/index.d.ts +3 -3
  53. package/lib/built/segment-contract/index.js +2 -2
  54. package/lib/built/segment-contract/json-schema.d.ts +39 -5
  55. package/lib/built/segment-contract/json-schema.js +207 -24
  56. package/lib/built/segment-contract/preview.js +8 -1
  57. package/lib/built/segment-contract/text.js +1 -1
  58. package/lib/built/segment-contract/types.d.ts +2 -2
  59. package/lib/built/segment-contract/validate.d.ts +1553 -224
  60. package/lib/built/segment-contract/validate.js +39 -3
  61. package/lib/built/tool-access.d.ts +5 -0
  62. package/lib/built/tool-access.js +17 -0
  63. package/lib/built/user-interaction.d.ts +5 -4
  64. package/lib/built/user-interaction.js +64 -52
  65. package/lib/errors.d.ts +1 -18
  66. package/lib/errors.js +1 -26
  67. package/lib/feature/command-public-api.d.ts +5 -0
  68. package/lib/feature/command-public-api.js +5 -0
  69. package/lib/feature/command.d.ts +2 -0
  70. package/lib/feature/command.js +1 -0
  71. package/lib/feature/component.d.ts +1 -0
  72. package/lib/feature/component.js +1 -0
  73. package/lib/feature/handler.d.ts +13 -7
  74. package/lib/feature/handler.js +2 -1
  75. package/lib/feature/middleware-public-api.d.ts +6 -0
  76. package/lib/feature/middleware-public-api.js +6 -0
  77. package/lib/feature/middleware.d.ts +22 -2
  78. package/lib/feature/middleware.js +7 -2
  79. package/lib/im-scene.d.ts +4 -3
  80. package/lib/im-scene.js +9 -9
  81. package/lib/im-session-id.d.ts +20 -12
  82. package/lib/im-session-id.js +8 -8
  83. package/lib/index.d.ts +19 -48
  84. package/lib/index.js +14 -41
  85. package/lib/jsx/intrinsic-elements.d.ts +83 -0
  86. package/lib/jsx/message-renderer.d.ts +13 -0
  87. package/lib/jsx/message-renderer.js +128 -0
  88. package/lib/jsx/message-tags.d.ts +133 -0
  89. package/lib/jsx/message-tags.js +50 -0
  90. package/lib/jsx-dev-runtime.d.ts +2 -2
  91. package/lib/jsx-dev-runtime.js +1 -2
  92. package/lib/jsx-runtime.d.ts +2 -12
  93. package/lib/jsx-runtime.js +1 -10
  94. package/lib/jsx.d.ts +6 -30
  95. package/lib/jsx.js +3 -93
  96. package/lib/message.d.ts +0 -40
  97. package/lib/message.js +1 -27
  98. package/lib/models/system-log.d.ts +0 -2
  99. package/lib/models/system-log.js +1 -8
  100. package/lib/models/user.d.ts +0 -2
  101. package/lib/models/user.js +1 -7
  102. package/lib/notice.d.ts +38 -33
  103. package/lib/notice.js +23 -7
  104. package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
  105. package/lib/plugin-runtime/im/command-feedback.js +148 -0
  106. package/lib/plugin-runtime/im/contracts.d.ts +217 -32
  107. package/lib/plugin-runtime/im/contracts.js +141 -23
  108. package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
  109. package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
  110. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +89 -0
  111. package/lib/plugin-runtime/im/endpoint-runtime.js +381 -0
  112. package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
  113. package/lib/plugin-runtime/im/feature-gate.js +88 -0
  114. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  115. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  116. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  117. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  118. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  119. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  120. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +29 -0
  121. package/lib/plugin-runtime/im/host/database-host-installer.js +442 -0
  122. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  123. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  124. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  125. package/lib/plugin-runtime/im/host/index.js +8 -0
  126. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  127. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  128. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  129. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  130. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
  131. package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
  132. package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
  133. package/lib/plugin-runtime/im/im-runtime.js +234 -1059
  134. package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
  135. package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
  136. package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
  137. package/lib/plugin-runtime/im/inbound-origin.js +183 -0
  138. package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
  139. package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
  140. package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
  141. package/lib/plugin-runtime/im/inbound-spine.js +335 -0
  142. package/lib/plugin-runtime/im/index.d.ts +15 -4
  143. package/lib/plugin-runtime/im/index.js +11 -4
  144. package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
  145. package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
  146. package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
  147. package/lib/plugin-runtime/im/interactive-router.js +382 -0
  148. package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
  149. package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
  150. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
  151. package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
  152. package/lib/plugin-runtime/im/message-events.d.ts +85 -0
  153. package/lib/plugin-runtime/im/message-events.js +113 -0
  154. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
  155. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
  156. package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
  157. package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
  158. package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
  159. package/lib/plugin-runtime/im/outbound-segments.js +130 -36
  160. package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
  161. package/lib/plugin-runtime/im/progressive-reply.js +501 -0
  162. package/lib/plugin-runtime/im/public-api.d.ts +1 -1
  163. package/lib/request.d.ts +27 -36
  164. package/lib/request.js +14 -6
  165. package/lib/side-event/base.d.ts +64 -44
  166. package/lib/side-event/base.js +72 -19
  167. package/lib/side-event/index.d.ts +1 -1
  168. package/lib/side-event/index.js +1 -1
  169. package/lib/side-event/normalize.d.ts +7 -38
  170. package/lib/side-event/normalize.js +4 -109
  171. package/lib/side-event/scene-events.d.ts +40 -0
  172. package/lib/side-event/scene-events.js +147 -0
  173. package/lib/side-event/types.d.ts +4 -13
  174. package/lib/side-event/types.js +1 -55
  175. package/lib/system-event.d.ts +17 -12
  176. package/lib/system-event.js +8 -6
  177. package/lib/types.d.ts +23 -167
  178. package/lib/utils.d.ts +50 -33
  179. package/lib/utils.js +12 -185
  180. package/lib/venue/contracts.d.ts +21 -0
  181. package/lib/venue/contracts.js +3 -0
  182. package/lib/venue/floor-controller.d.ts +11 -0
  183. package/lib/venue/floor-controller.js +63 -0
  184. package/lib/venue/index.d.ts +13 -0
  185. package/lib/venue/index.js +11 -0
  186. package/lib/venue/membership-port.d.ts +23 -0
  187. package/lib/venue/membership-port.js +141 -0
  188. package/lib/venue/projector.d.ts +38 -0
  189. package/lib/venue/projector.js +45 -0
  190. package/lib/venue/registry.d.ts +16 -0
  191. package/lib/venue/registry.js +63 -0
  192. package/lib/venue/router.d.ts +19 -0
  193. package/lib/venue/router.js +101 -0
  194. package/lib/venue/send-limiter.d.ts +17 -0
  195. package/lib/venue/send-limiter.js +73 -0
  196. package/lib/venue/validator.d.ts +6 -0
  197. package/lib/venue/validator.js +160 -0
  198. package/package.json +24 -50
  199. package/lib/adapter.d.ts +0 -145
  200. package/lib/adapter.js +0 -377
  201. package/lib/built/adapter-process.d.ts +0 -58
  202. package/lib/built/adapter-process.js +0 -128
  203. package/lib/built/agent-preset.d.ts +0 -64
  204. package/lib/built/agent-preset.js +0 -79
  205. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  206. package/lib/built/ai-outbound/adapter-access.js +0 -9
  207. package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
  208. package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
  209. package/lib/built/authorization.d.ts +0 -10
  210. package/lib/built/authorization.js +0 -76
  211. package/lib/built/command.d.ts +0 -72
  212. package/lib/built/command.js +0 -105
  213. package/lib/built/component.d.ts +0 -67
  214. package/lib/built/component.js +0 -97
  215. package/lib/built/config.d.ts +0 -98
  216. package/lib/built/config.js +0 -372
  217. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  218. package/lib/built/connect-endpoint-instance.js +0 -42
  219. package/lib/built/database.d.ts +0 -68
  220. package/lib/built/database.js +0 -106
  221. package/lib/built/dispatcher.d.ts +0 -141
  222. package/lib/built/dispatcher.js +0 -383
  223. package/lib/built/endpoint-commands.d.ts +0 -3
  224. package/lib/built/endpoint-commands.js +0 -99
  225. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  226. package/lib/built/endpoint-lifecycle-service.js +0 -242
  227. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  228. package/lib/built/endpoint-lifecycle.js +0 -36
  229. package/lib/built/endpoint-manager.d.ts +0 -34
  230. package/lib/built/html-renderer-loader.d.ts +0 -13
  231. package/lib/built/html-renderer-loader.js +0 -33
  232. package/lib/built/inbound-pipeline.d.ts +0 -37
  233. package/lib/built/inbound-pipeline.js +0 -63
  234. package/lib/built/inbound-runner.d.ts +0 -22
  235. package/lib/built/inbound-runner.js +0 -34
  236. package/lib/built/interactive-segment-contract.d.ts +0 -6
  237. package/lib/built/interactive-segment-contract.js +0 -9
  238. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  239. package/lib/built/interactive-segments/fallback-store.js +0 -63
  240. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  241. package/lib/built/interactive-segments/handlers.js +0 -74
  242. package/lib/built/introspection-format.d.ts +0 -10
  243. package/lib/built/introspection-format.js +0 -28
  244. package/lib/built/management-command-guard.d.ts +0 -15
  245. package/lib/built/management-command-guard.js +0 -25
  246. package/lib/built/message-filter.d.ts +0 -176
  247. package/lib/built/message-filter.js +0 -239
  248. package/lib/built/optional-peer-import.d.ts +0 -3
  249. package/lib/built/optional-peer-import.js +0 -33
  250. package/lib/built/outbound-media-contract.d.ts +0 -22
  251. package/lib/built/outbound-media-contract.js +0 -10
  252. package/lib/built/permission.d.ts +0 -51
  253. package/lib/built/permission.js +0 -99
  254. package/lib/built/permit-check.d.ts +0 -7
  255. package/lib/built/permit-check.js +0 -35
  256. package/lib/built/permit-parse.d.ts +0 -16
  257. package/lib/built/permit-parse.js +0 -32
  258. package/lib/built/platform-permit.d.ts +0 -20
  259. package/lib/built/platform-permit.js +0 -91
  260. package/lib/built/queue-im-field-contract.d.ts +0 -32
  261. package/lib/built/queue-im-field-contract.js +0 -67
  262. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  263. package/lib/built/rich-segments/adapter-policies.js +0 -27
  264. package/lib/built/rich-segments/base.d.ts +0 -11
  265. package/lib/built/rich-segments/base.js +0 -24
  266. package/lib/built/rich-segments/builtins.d.ts +0 -4
  267. package/lib/built/rich-segments/builtins.js +0 -40
  268. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  269. package/lib/built/rich-segments/capabilities.js +0 -38
  270. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  271. package/lib/built/rich-segments/html-segment.js +0 -62
  272. package/lib/built/rich-segments/index.d.ts +0 -13
  273. package/lib/built/rich-segments/index.js +0 -13
  274. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  275. package/lib/built/rich-segments/markdown-segment.js +0 -58
  276. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  277. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  278. package/lib/built/rich-segments/registry.d.ts +0 -16
  279. package/lib/built/rich-segments/registry.js +0 -52
  280. package/lib/built/rich-segments/resolve.d.ts +0 -5
  281. package/lib/built/rich-segments/resolve.js +0 -87
  282. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  283. package/lib/built/rich-segments/tts-segment.js +0 -51
  284. package/lib/built/rich-segments/types.d.ts +0 -79
  285. package/lib/built/rich-segments/types.js +0 -17
  286. package/lib/built/runtime-io.d.ts +0 -9
  287. package/lib/built/runtime-io.js +0 -67
  288. package/lib/built/schedule.d.ts +0 -54
  289. package/lib/built/schedule.js +0 -112
  290. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  291. package/lib/built/schema-endpoint-manager.js +0 -73
  292. package/lib/built/schema-feature.d.ts +0 -77
  293. package/lib/built/schema-feature.js +0 -130
  294. package/lib/built/skill.d.ts +0 -120
  295. package/lib/built/skill.js +0 -151
  296. package/lib/built/speech-loader.d.ts +0 -14
  297. package/lib/built/speech-loader.js +0 -32
  298. package/lib/built/tool.d.ts +0 -151
  299. package/lib/built/tool.js +0 -388
  300. package/lib/command.d.ts +0 -50
  301. package/lib/command.js +0 -106
  302. package/lib/component.d.ts +0 -26
  303. package/lib/component.js +0 -583
  304. package/lib/endpoint-capabilities.d.ts +0 -46
  305. package/lib/endpoint-capabilities.js +0 -55
  306. package/lib/endpoint.d.ts +0 -19
  307. package/lib/endpoint.js +0 -3
  308. package/lib/host-plugin-registry.d.ts +0 -8
  309. package/lib/host-plugin-registry.js +0 -12
  310. package/lib/plugin-context.d.ts +0 -27
  311. package/lib/plugin-context.js +0 -64
  312. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  313. package/lib/plugin-runtime/im/interactive.js +0 -46
  314. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  315. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  316. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  317. package/lib/plugin-runtime/im/message-bus.js +0 -40
  318. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  319. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  320. package/lib/plugin.d.ts +0 -268
  321. package/lib/plugin.js +0 -583
  322. package/lib/schema-interaction.d.ts +0 -117
  323. package/lib/schema-interaction.js +0 -247
  324. package/lib/side-event/dispatch.d.ts +0 -15
  325. package/lib/side-event/dispatch.js +0 -140
  326. package/lib/tool-zod.d.ts +0 -43
  327. package/lib/tool-zod.js +0 -184
  328. /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
@@ -0,0 +1,114 @@
1
+ const SUPPORTED_DIALECTS = new Set(['memory', 'mongodb', 'mysql', 'pg', 'redis', 'sqlite']);
2
+ function configurationError(path, expectation, envExample) {
3
+ const envHint = envExample
4
+ ? `若这里引用环境变量,请在项目根目录 .env 中设置 ${envExample}。`
5
+ : '若这里引用环境变量,请检查项目根目录 .env 中的对应变量。';
6
+ return new TypeError(`数据库配置 ${path} ${expectation}。${envHint}也可运行 \`zhin setup --database\` 重新配置。`);
7
+ }
8
+ function normalizePort(value, path, envExample) {
9
+ if (value === undefined)
10
+ return undefined;
11
+ const normalized = typeof value === 'number'
12
+ ? value
13
+ : typeof value === 'string' && /^\d+$/u.test(value.trim())
14
+ ? Number(value.trim())
15
+ : Number.NaN;
16
+ if (!Number.isInteger(normalized) || normalized < 1 || normalized > 65535) {
17
+ throw configurationError(path, '必须是 1-65535 的整数,当前值为空或无效', envExample);
18
+ }
19
+ return normalized;
20
+ }
21
+ function normalizeOptionalText(config, key, path, envExample) {
22
+ if (!(key in config))
23
+ return;
24
+ const value = config[key];
25
+ if (typeof value !== 'string' || value.trim() === '') {
26
+ throw configurationError(path, '不能为空', envExample);
27
+ }
28
+ config[key] = value.trim();
29
+ }
30
+ function normalizeRequiredText(config, key, path, envExample) {
31
+ if (!(key in config))
32
+ config[key] = undefined;
33
+ normalizeOptionalText(config, key, path, envExample);
34
+ }
35
+ function normalizeRedisDatabase(value) {
36
+ if (value === undefined)
37
+ return undefined;
38
+ const normalized = typeof value === 'number'
39
+ ? value
40
+ : typeof value === 'string' && /^\d+$/u.test(value.trim())
41
+ ? Number(value.trim())
42
+ : Number.NaN;
43
+ if (!Number.isInteger(normalized) || normalized < 0) {
44
+ throw configurationError('database.database', '必须是大于或等于 0 的整数', 'REDIS_DB=0');
45
+ }
46
+ return normalized;
47
+ }
48
+ /**
49
+ * Validate and normalize the expanded Root database configuration before a
50
+ * third-party driver sees it. Dotenv expansion produces strings, while the
51
+ * network clients require numeric ports and otherwise surface opaque NaN
52
+ * socket errors.
53
+ */
54
+ export function normalizeDatabaseHostConfig(input) {
55
+ const dialect = input.dialect;
56
+ if (!SUPPORTED_DIALECTS.has(dialect)) {
57
+ throw new TypeError(`数据库配置 database.dialect 不支持 ${JSON.stringify(dialect)};`
58
+ + '可选值为 sqlite、mysql、pg、mongodb、redis、memory。');
59
+ }
60
+ const config = { ...input, dialect };
61
+ switch (dialect) {
62
+ case 'mysql':
63
+ normalizeOptionalText(config, 'host', 'database.host', 'DB_HOST=127.0.0.1');
64
+ normalizeOptionalText(config, 'user', 'database.user', 'DB_USER=root');
65
+ normalizeOptionalText(config, 'database', 'database.database', 'DB_DATABASE=zhin_bot');
66
+ normalizeOptionalText(config, 'uri', 'database.uri');
67
+ config.port = normalizePort(config.port, 'database.port', 'DB_PORT=3306');
68
+ if (config.port === undefined)
69
+ delete config.port;
70
+ break;
71
+ case 'pg':
72
+ normalizeOptionalText(config, 'host', 'database.host', 'DB_HOST=127.0.0.1');
73
+ normalizeOptionalText(config, 'user', 'database.user', 'DB_USER=postgres');
74
+ normalizeOptionalText(config, 'database', 'database.database', 'DB_DATABASE=zhin_bot');
75
+ normalizeOptionalText(config, 'connectionString', 'database.connectionString');
76
+ config.port = normalizePort(config.port, 'database.port', 'DB_PORT=5432');
77
+ if (config.port === undefined)
78
+ delete config.port;
79
+ break;
80
+ case 'mongodb':
81
+ normalizeRequiredText(config, 'url', 'database.url', 'DB_URL=mongodb://127.0.0.1:27017');
82
+ normalizeRequiredText(config, 'dbName', 'database.dbName', 'DB_NAME=zhin_bot');
83
+ if (!/^mongodb(?:\+srv)?:\/\//u.test(String(config.url))) {
84
+ throw configurationError('database.url', '必须使用 mongodb:// 或 mongodb+srv://');
85
+ }
86
+ break;
87
+ case 'redis': {
88
+ normalizeOptionalText(config, 'url', 'database.url', 'REDIS_URL=redis://127.0.0.1:6379');
89
+ if (config.socket !== undefined) {
90
+ if (!config.socket || typeof config.socket !== 'object' || Array.isArray(config.socket)) {
91
+ throw configurationError('database.socket', '必须是对象');
92
+ }
93
+ const socket = { ...config.socket };
94
+ normalizeOptionalText(socket, 'host', 'database.socket.host', 'REDIS_HOST=127.0.0.1');
95
+ socket.port = normalizePort(socket.port, 'database.socket.port', 'REDIS_PORT=6379');
96
+ if (socket.port === undefined)
97
+ delete socket.port;
98
+ config.socket = Object.freeze(socket);
99
+ }
100
+ config.database = normalizeRedisDatabase(config.database);
101
+ if (config.database === undefined)
102
+ delete config.database;
103
+ break;
104
+ }
105
+ case 'sqlite':
106
+ if (config.filename === undefined)
107
+ config.filename = './data/bot.db';
108
+ normalizeOptionalText(config, 'filename', 'database.filename');
109
+ break;
110
+ case 'memory':
111
+ break;
112
+ }
113
+ return Object.freeze(config);
114
+ }
@@ -0,0 +1,29 @@
1
+ import { type DatabaseHost, type DatabaseHostModel, type ConfigDocumentPort, type RootResourceInstaller, type RuntimeConfigDocument } from '@zhin.js/plugin-runtime';
2
+ import { type DatabaseHostConfig } from './database-config.js';
3
+ export type { DatabaseHostConfig } from './database-config.js';
4
+ /**
5
+ * Root-only view of the gateway-owned `console_*` tables. Only a standalone composition (no
6
+ * gateway, dev / test) hands it to its in-process Console access control; every other path of
7
+ * the host refuses those tables.
8
+ */
9
+ export interface GatewayTableHost {
10
+ readonly dialect: string;
11
+ readonly started: boolean;
12
+ define(name: string, definition: Record<string, unknown>): void;
13
+ tables(): readonly string[];
14
+ readonly models: {
15
+ get(name: string): DatabaseHostModel | undefined;
16
+ };
17
+ }
18
+ export declare function createDatabaseHost(config: DatabaseHostConfig): DatabaseHost & {
19
+ readonly db: {
20
+ define: (name: string, definition: unknown) => void;
21
+ start(): Promise<void>;
22
+ stop(): Promise<void>;
23
+ models: Map<string, unknown>;
24
+ };
25
+ /** See {@link GatewayTableHost}; never pass it to plugins, Agent or Console database RPC. */
26
+ gatewayTableHost(): GatewayTableHost;
27
+ };
28
+ export declare function resolveDatabaseConfig(projectRoot: string, config: RuntimeConfigDocument | ConfigDocumentPort): Promise<DatabaseHostConfig>;
29
+ export declare function installDatabaseHost(host: DatabaseHost): RootResourceInstaller;
@@ -0,0 +1,442 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { Registry, assertInstanceTable, ensureDatabaseColumns, GatewayOwnedTableError, isGatewayOwnedTable, referencesGatewayOwnedTable } from '@zhin.js/database';
5
+ import { formatCompact, getLogger } from '@zhin.js/logger';
6
+ import { guardTransactionModel, databaseHostToken, databaseRootHostToken, PluginDatabaseHost, rootPluginId, } from '@zhin.js/plugin-runtime';
7
+ import { normalizeDatabaseHostConfig, } from './database-config.js';
8
+ import { createDatabaseState } from './database-state.js';
9
+ const logger = getLogger('Database');
10
+ function wrapModel(model, db, tableName) {
11
+ return {
12
+ ...(model.aggregate && db && ['sqlite', 'mysql', 'pg'].includes(db.dialectName) ? { aggregate: () => {
13
+ const source = model.aggregate();
14
+ const chain = {
15
+ min(field, alias) { source.min(field, alias); return chain; },
16
+ max(field, alias) { source.max(field, alias); return chain; },
17
+ groupBy(...fields) { source.groupBy(...fields); return chain; },
18
+ where(query) { source.where(query); return chain; },
19
+ then(resolve, reject) { return Promise.resolve(source).then(resolve, reject); },
20
+ };
21
+ return Object.freeze(chain);
22
+ } } : {}),
23
+ select: (...fields) => {
24
+ if (fields.includes('*')) {
25
+ throw new TypeError('select() requires explicit column names; "*" is not supported '
26
+ + '(pass real column names, e.g. select("id", "title")), or use count() for counting.');
27
+ }
28
+ const selection = model.select(...fields);
29
+ // 链式 + 可 await:console logs 页需要 orderBy/limit,插件侧 `await select().where(q)` 不变
30
+ const chain = {
31
+ where: (query) => { selection.where(query); return chain; },
32
+ orderBy: (field, direction) => { selection.orderBy?.(field, direction); return chain; },
33
+ limit: (count) => { selection.limit?.(count); return chain; },
34
+ then: (onfulfilled, onrejected) => Promise.resolve(selection)
35
+ .then(onfulfilled, onrejected),
36
+ };
37
+ return chain;
38
+ },
39
+ insert: (row) => Promise.resolve(model.insert(row)),
40
+ delete: () => ({
41
+ where: (query) => Promise.resolve(model.delete(query)),
42
+ }),
43
+ update: (patch) => ({
44
+ where: (query) => Promise.resolve(model.update(patch).where(query)),
45
+ }),
46
+ // DB 侧 count 聚合(console /api/logs/stats 不再为计数整表加载);
47
+ // 方言不支持 aggregate(如 redis/mongodb)时降级为 select('id') 计数。
48
+ count: async (where) => {
49
+ const filter = where ?? {};
50
+ if (db && tableName) {
51
+ try {
52
+ const counted = await db.aggregate(tableName).count('*', 'total').where(filter);
53
+ const total = Number(counted[0]?.total);
54
+ if (Number.isFinite(total))
55
+ return total;
56
+ }
57
+ catch {
58
+ /* fall through to select('id') */
59
+ }
60
+ }
61
+ const selection = model.select('id');
62
+ const result = Object.keys(filter).length > 0 ? selection.where(filter) : selection;
63
+ const rows = await Promise.resolve(result);
64
+ return rows.length;
65
+ },
66
+ };
67
+ }
68
+ export function createDatabaseHost(config) {
69
+ const { dialect, ...connectionConfig } = config;
70
+ const db = Registry.create(dialect, connectionConfig);
71
+ let started = false;
72
+ const state = createDatabaseState(db, config.dialect, () => started);
73
+ const wrapped = new Map();
74
+ const definedTables = new Set();
75
+ const definitions = new Map();
76
+ const additions = new Map();
77
+ let rawGuard;
78
+ let gatewayView;
79
+ const consolePort = createDatabaseConsole(db, config.dialect, () => started, definedTables, definitions);
80
+ const modelOf = (name) => {
81
+ if (!started)
82
+ return undefined;
83
+ const cached = wrapped.get(name);
84
+ if (cached)
85
+ return cached;
86
+ const raw = db.models.get(name);
87
+ if (!raw)
88
+ return undefined;
89
+ const model = wrapModel(raw, db, name);
90
+ wrapped.set(name, model);
91
+ return model;
92
+ };
93
+ const defineTable = (name, definition, options) => {
94
+ const migration = Object.fromEntries((options?.addColumns ?? []).map(field => {
95
+ const column = Object.hasOwn(definition, field) ? definition[field] : undefined;
96
+ if (!column || typeof column !== 'object' || Array.isArray(column)
97
+ || !('type' in column) || ('primary' in column && column.primary)
98
+ || ('autoIncrement' in column && column.autoIncrement)
99
+ || (!('nullable' in column && column.nullable === true) && !('default' in column))) {
100
+ throw new TypeError(`Additive column '${field}' in '${name}' must be declared, nullable or defaulted, and not a primary key`);
101
+ }
102
+ return [field, structuredClone(column)];
103
+ }));
104
+ const existing = definitions.get(name);
105
+ // Host 跨世代共享:reload 后新世代会重复 define 同名表,
106
+ // 定义一致则幂等跳过(即使已 started),不一致才报错。
107
+ if (existing !== undefined) {
108
+ if (isDeepStrictEqual(existing, definition)) {
109
+ const previous = additions.get(name) ?? {};
110
+ const merged = { ...previous, ...migration };
111
+ if (started && !isDeepStrictEqual(previous, merged)) {
112
+ throw new Error(`DatabaseHost already started; restart to migrate table ${name}`);
113
+ }
114
+ if (Object.keys(merged).length)
115
+ additions.set(name, merged);
116
+ return;
117
+ }
118
+ throw new Error(`Table '${name}' already defined with a different definition`);
119
+ }
120
+ if (started) {
121
+ throw new Error(`DatabaseHost already started; cannot define table ${name}`);
122
+ }
123
+ definedTables.add(name);
124
+ definitions.set(name, definition);
125
+ if (Object.keys(migration).length)
126
+ additions.set(name, migration);
127
+ db.define(name, definition);
128
+ };
129
+ return {
130
+ db,
131
+ state,
132
+ get dialect() {
133
+ return config.dialect;
134
+ },
135
+ get started() {
136
+ return started;
137
+ },
138
+ define(name, definition, options) {
139
+ assertInstanceTable(name);
140
+ defineTable(name, definition, options);
141
+ },
142
+ tables() {
143
+ return [...definedTables].filter(name => !isGatewayOwnedTable(name));
144
+ },
145
+ models: {
146
+ get(name) {
147
+ return isGatewayOwnedTable(name) ? undefined : modelOf(name);
148
+ },
149
+ },
150
+ gatewayTableHost() {
151
+ return gatewayView ??= Object.freeze({
152
+ get dialect() { return config.dialect; },
153
+ get started() { return started; },
154
+ define(name, definition) {
155
+ if (!isGatewayOwnedTable(name))
156
+ throw new Error(`Table '${name}' is not a gateway table`);
157
+ defineTable(name, definition);
158
+ },
159
+ tables: () => [...definedTables].filter(isGatewayOwnedTable),
160
+ models: Object.freeze({ get: (name) => (isGatewayOwnedTable(name) ? modelOf(name) : undefined) }),
161
+ });
162
+ },
163
+ async transaction(callback) {
164
+ if (!started)
165
+ throw new Error('Database is not connected');
166
+ if (!['sqlite', 'mysql', 'pg'].includes(config.dialect))
167
+ throw new Error(`Transactions are not supported by '${config.dialect}'`);
168
+ return db.transaction(async (transaction) => {
169
+ let active = true;
170
+ try {
171
+ return await callback({ model(name) {
172
+ if (!active)
173
+ throw new Error('Database transaction is already closed');
174
+ assertInstanceTable(name);
175
+ if (!definedTables.has(name))
176
+ throw new Error(`Table '${name}' is not registered`);
177
+ return guardTransactionModel({
178
+ select: (...fields) => {
179
+ if (fields.includes('*')) {
180
+ throw new TypeError('select() requires explicit column names; "*" is not supported '
181
+ + '(pass real column names, e.g. select("id", "title")), or use count() for counting.');
182
+ }
183
+ const selection = transaction.select(name, fields);
184
+ const chain = {
185
+ where: (query) => { selection.where(query); return chain; },
186
+ orderBy: (field, direction) => { selection.orderBy?.(field, direction); return chain; },
187
+ limit: (count) => { selection.limit?.(count); return chain; },
188
+ then: (onfulfilled, onrejected) => Promise.resolve(selection)
189
+ .then(onfulfilled, onrejected),
190
+ };
191
+ return chain;
192
+ },
193
+ insert: row => transaction.insert(name, row),
194
+ update: patch => ({ where: async (query) => transaction.update(name, patch).where(query) }),
195
+ delete: () => ({ where: async (query) => transaction.delete(name).where(query) }),
196
+ }, () => { if (!active)
197
+ throw new Error('Database transaction is already closed'); });
198
+ } });
199
+ }
200
+ finally {
201
+ active = false;
202
+ }
203
+ }, { isolationLevel: 'REPEATABLE_READ' });
204
+ },
205
+ console: consolePort,
206
+ getRawDatabase() {
207
+ if (!started)
208
+ return undefined;
209
+ return rawGuard ??= guardRawDatabase(db);
210
+ },
211
+ async start() {
212
+ if (started)
213
+ return;
214
+ try {
215
+ await db.start();
216
+ for (const [table, columns] of additions) {
217
+ await ensureDatabaseColumns(db, table, columns);
218
+ }
219
+ started = true;
220
+ wrapped.clear();
221
+ logger.debug(formatCompact({ op: 'database_start', dialect: config.dialect }));
222
+ }
223
+ catch (error) {
224
+ await db.stop().catch(() => undefined);
225
+ throw error;
226
+ }
227
+ },
228
+ async stop() {
229
+ if (!started)
230
+ return;
231
+ await db.stop();
232
+ started = false;
233
+ wrapped.clear();
234
+ },
235
+ };
236
+ }
237
+ function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, definitions) {
238
+ const type = databaseType(configuredDialect);
239
+ const requireModel = (table) => {
240
+ // Gateway tables (console_users, sessions, tokens, audit) are never reachable from here.
241
+ assertInstanceTable(table);
242
+ if (!isStarted())
243
+ throw new Error('Database is not connected');
244
+ const model = db.models.get(table);
245
+ if (!model)
246
+ throw new Error(`Table '${table}' not found`);
247
+ return model;
248
+ };
249
+ const port = {
250
+ info: () => ({
251
+ dialect: configuredDialect,
252
+ type,
253
+ tables: [...tableNames].filter(name => !isGatewayOwnedTable(name)),
254
+ connected: isStarted(),
255
+ }),
256
+ tables: () => [...tableNames].filter(name => !isGatewayOwnedTable(name)).map((name) => ({
257
+ name,
258
+ columns: definitions.get(name),
259
+ })),
260
+ async select(table, page, pageSize, where) {
261
+ const model = requireModel(table);
262
+ if (type === 'keyvalue') {
263
+ if (!model.entries)
264
+ throw new Error(`Table '${table}' is not a key-value bucket`);
265
+ const all = await model.entries();
266
+ const start = (page - 1) * pageSize;
267
+ return {
268
+ rows: all.slice(start, start + pageSize).map(([key, value]) => ({ key, value })),
269
+ total: all.length,
270
+ page,
271
+ pageSize,
272
+ };
273
+ }
274
+ const filter = where ?? {};
275
+ let total;
276
+ try {
277
+ const counted = await db.aggregate(table).count('*', 'total').where(filter);
278
+ total = Number(counted[0]?.total ?? 0);
279
+ }
280
+ catch {
281
+ const all = await model.select();
282
+ total = all.length;
283
+ }
284
+ let selection = model.select();
285
+ if (Object.keys(filter).length > 0)
286
+ selection = selection.where(filter);
287
+ const rows = await selection.limit(pageSize).offset((page - 1) * pageSize);
288
+ return { rows, total, page, pageSize };
289
+ },
290
+ async insert(table, row) {
291
+ const model = requireModel(table);
292
+ if (type === 'keyvalue') {
293
+ if (!model.set || row.key == null)
294
+ throw new Error('key is required for KV insert');
295
+ await model.set(String(row.key), row.value);
296
+ }
297
+ else if (type === 'document' && model.create) {
298
+ await model.create(row);
299
+ }
300
+ else {
301
+ await model.insert(row);
302
+ }
303
+ },
304
+ async update(table, row, where) {
305
+ const model = requireModel(table);
306
+ if (type === 'keyvalue') {
307
+ if (!model.set || where.key == null)
308
+ throw new Error('key is required for KV update');
309
+ await model.set(String(where.key), row.value);
310
+ return 1;
311
+ }
312
+ if (type === 'document' && where._id != null && model.updateById) {
313
+ return await model.updateById(String(where._id), row);
314
+ }
315
+ return await model.update(row).where(where);
316
+ },
317
+ async delete(table, where) {
318
+ const model = requireModel(table);
319
+ if (type === 'keyvalue') {
320
+ if (!model.deleteByKey || where.key == null)
321
+ throw new Error('key is required for KV delete');
322
+ await model.deleteByKey(String(where.key));
323
+ return 1;
324
+ }
325
+ if (type === 'document' && where._id != null && model.deleteById) {
326
+ return await model.deleteById(String(where._id));
327
+ }
328
+ return await model.delete(where);
329
+ },
330
+ async dropTable(table) {
331
+ requireModel(table);
332
+ await db.query(db.dialect.formatDropTable(table, true));
333
+ db.models.delete(table);
334
+ db.definitions.delete(table);
335
+ tableNames.delete(table);
336
+ definitions.delete(table);
337
+ },
338
+ async kvGet(table, key) {
339
+ const model = requireModel(table);
340
+ if (!model.get)
341
+ throw new Error(`Table '${table}' is not a key-value bucket`);
342
+ return await model.get(key);
343
+ },
344
+ async kvSet(table, key, value, ttl) {
345
+ const model = requireModel(table);
346
+ if (!model.set)
347
+ throw new Error(`Table '${table}' is not a key-value bucket`);
348
+ await model.set(key, value, ttl);
349
+ },
350
+ async kvDelete(table, key) {
351
+ const model = requireModel(table);
352
+ if (!model.deleteByKey)
353
+ throw new Error(`Table '${table}' is not a key-value bucket`);
354
+ await model.deleteByKey(key);
355
+ },
356
+ async kvEntries(table) {
357
+ const model = requireModel(table);
358
+ if (!model.entries)
359
+ throw new Error(`Table '${table}' is not a key-value bucket`);
360
+ return (await model.entries()).map(([key, value]) => ({ key, value }));
361
+ },
362
+ };
363
+ return Object.freeze(port);
364
+ }
365
+ /**
366
+ * Root-only raw registry with the gateway's tables cut off: raw SQL naming them and table-name
367
+ * arguments (`model`, `define`, `select`, …) are refused. Methods run on the real registry.
368
+ */
369
+ function guardRawDatabase(db) {
370
+ const wrapped = new Map();
371
+ return new Proxy(db, {
372
+ get(target, property, receiver) {
373
+ const value = Reflect.get(target, property, receiver);
374
+ if (typeof value !== 'function')
375
+ return value;
376
+ const cached = wrapped.get(property);
377
+ if (cached)
378
+ return cached;
379
+ const guarded = function (...args) {
380
+ const [first] = args;
381
+ if (property === 'query' && typeof first === 'string' && referencesGatewayOwnedTable(first)) {
382
+ throw new GatewayOwnedTableError();
383
+ }
384
+ if (typeof first === 'string')
385
+ assertInstanceTable(first);
386
+ return value.apply(target, args);
387
+ };
388
+ wrapped.set(property, guarded);
389
+ return guarded;
390
+ },
391
+ });
392
+ }
393
+ function databaseType(dialect) {
394
+ if (dialect === 'mongodb')
395
+ return 'document';
396
+ if (dialect === 'redis')
397
+ return 'keyvalue';
398
+ return 'related';
399
+ }
400
+ export async function resolveDatabaseConfig(projectRoot, config) {
401
+ const document = await readConfigDocument(config);
402
+ const configured = document && typeof document === 'object'
403
+ ? document.database
404
+ : undefined;
405
+ if (configured && typeof configured === 'object' && !Array.isArray(configured)) {
406
+ const value = configured;
407
+ const dialect = typeof value.dialect === 'string' ? value.dialect : 'sqlite';
408
+ return normalizeDatabaseHostConfig({ ...value, dialect });
409
+ }
410
+ const filename = join(projectRoot, '.zhin', 'data.sqlite');
411
+ await mkdir(dirname(filename), { recursive: true });
412
+ return Object.freeze({ dialect: 'sqlite', filename });
413
+ }
414
+ export function installDatabaseHost(host) {
415
+ return ({ resources, handoff, admission }) => {
416
+ // Domain tables (e.g. github_oauth_users) are defined by owning plugins in setup().
417
+ // Plugins receive a root-scoped facade through the historical token. The
418
+ // raw host remains available only to CLI composition through its root token.
419
+ resources.provide(databaseRootHostToken, host);
420
+ resources.provide(databaseHostToken, new PluginDatabaseHost(rootPluginId(), host, admission));
421
+ // Host 是进程级共享资源:不能随世代 dispose / 回滚 stop(旧世代仍在用)。
422
+ // start 幂等,stop 由进程退出路径(start-command control.stop)统一触发。
423
+ handoff.add({
424
+ activateNext: async (signal) => {
425
+ signal.throwIfAborted();
426
+ await host.start();
427
+ signal.throwIfAborted();
428
+ },
429
+ });
430
+ };
431
+ }
432
+ async function readConfigDocument(config) {
433
+ if (!isConfigDocumentPort(config))
434
+ return config;
435
+ return (await config.read()).document;
436
+ }
437
+ function isConfigDocumentPort(value) {
438
+ if (!value || typeof value !== 'object')
439
+ return false;
440
+ const candidate = value;
441
+ return typeof candidate.read === 'function';
442
+ }
@@ -0,0 +1,9 @@
1
+ import type { BuildQueryResult, QueryParams } from '@zhin.js/database';
2
+ import type { PersistentStatePort } from '@zhin.js/plugin-runtime';
3
+ /** Uses the process-owned database's normal builders and connection. */
4
+ export interface StateDatabase {
5
+ define(name: string, definition: unknown): void;
6
+ buildQuery(input: QueryParams<Record<string, Record<string, unknown>>, string>): BuildQueryResult<string>;
7
+ query(query: string, params?: unknown[]): Promise<unknown>;
8
+ }
9
+ export declare function createDatabaseState(db: StateDatabase, dialect: string, isStarted: () => boolean): PersistentStatePort;