@zhin.js/core 1.5.15 → 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,91 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ const table = '__zhin_persistent_state';
3
+ const definition = {
4
+ id: { type: 'text', length: 64, primary: true, nullable: false },
5
+ revision: { type: 'text', length: 36, nullable: false },
6
+ value: { type: 'text', nullable: false },
7
+ expires_at: { type: 'bigint', nullable: true },
8
+ };
9
+ export function createDatabaseState(db, dialect, isStarted) {
10
+ const supported = dialect === 'sqlite' || dialect === 'mysql' || dialect === 'pg';
11
+ if (supported)
12
+ db.define(table, dialect === 'pg' ? {
13
+ ...definition,
14
+ // PostgreSQL TEXT has no length modifier; the hashed key is already bounded.
15
+ id: { type: 'text', primary: true, nullable: false },
16
+ revision: { type: 'text', nullable: false },
17
+ } : definition);
18
+ const requireDatabase = () => {
19
+ if (!supported)
20
+ throw new Error(`Atomic persistent state is not supported by database dialect '${dialect}'`);
21
+ if (!isStarted())
22
+ throw new Error('Persistent state database is not connected');
23
+ };
24
+ const execute = async (input, returning = false) => {
25
+ const built = db.buildQuery(input);
26
+ const sql = dialect === 'pg' && returning ? `${built.query} RETURNING "id"` : built.query;
27
+ return db.query(sql, built.params);
28
+ };
29
+ const changed = (result) => {
30
+ if (typeof result === 'number')
31
+ return result === 1;
32
+ if (Array.isArray(result))
33
+ return result.length === 1;
34
+ return !!result && typeof result === 'object'
35
+ && Number(result.affectedRows) === 1;
36
+ };
37
+ return {
38
+ async read(owner, scope, key) {
39
+ requireDatabase();
40
+ const rows = await execute({ type: 'select', tableName: table,
41
+ fields: ['revision', 'value', 'expires_at'], conditions: { id: address(owner, scope, key) } });
42
+ if (!Array.isArray(rows))
43
+ throw new Error('Invalid persistent state database result');
44
+ const row = rows[0];
45
+ if (!row)
46
+ return undefined;
47
+ return { revision: row.revision, value: JSON.parse(row.value),
48
+ expiresAt: row.expires_at === null ? null : Number(row.expires_at) };
49
+ },
50
+ async compareExchange(owner, scope, key, revision, value, expiresAt) {
51
+ requireDatabase();
52
+ const id = address(owner, scope, key);
53
+ if (revision === undefined) {
54
+ if (value === undefined)
55
+ return true;
56
+ try {
57
+ await execute({ type: 'insert', tableName: table,
58
+ data: { id, revision: randomUUID(), value: JSON.stringify(value), expires_at: expiresAt } });
59
+ return true;
60
+ }
61
+ catch (error) {
62
+ if (isUniqueConflict(error))
63
+ return false;
64
+ throw error;
65
+ }
66
+ }
67
+ return changed(await execute(value === undefined
68
+ ? { type: 'delete', tableName: table, conditions: { id, revision } }
69
+ : { type: 'update', tableName: table, conditions: { id, revision },
70
+ update: { revision: randomUUID(), value: JSON.stringify(value), expires_at: expiresAt } }, true));
71
+ },
72
+ };
73
+ }
74
+ function address(owner, scope, key) {
75
+ // Tuple encoding separates owners, users, conversations, parents and threads;
76
+ // hash keeps physical keys short and excludes NUL from SQL text identifiers.
77
+ const parts = scope.kind === 'plugin' ? ['plugin']
78
+ : scope.kind === 'user' ? ['user', scope.endpoint.adapter, scope.endpoint.id, scope.senderId]
79
+ : ['conversation', scope.target.endpoint.adapter, scope.target.endpoint.id, scope.target.kind,
80
+ scope.target.id, scope.target.parent?.kind ?? null, scope.target.parent?.id ?? null, scope.target.threadId ?? null];
81
+ return createHash('sha256').update(JSON.stringify([owner, parts, key])).digest('hex');
82
+ }
83
+ function isUniqueConflict(error) {
84
+ if (!error || typeof error !== 'object')
85
+ return false;
86
+ const failure = error;
87
+ return failure.code === '23505' || failure.code === 'ER_DUP_ENTRY' || failure.errno === 1062
88
+ || failure.code === 'SQLITE_CONSTRAINT_PRIMARYKEY' || failure.code === 'SQLITE_CONSTRAINT_UNIQUE'
89
+ || (failure.code === 'ERR_SQLITE_ERROR' && (failure.errcode === 1555 || failure.errcode === 2067))
90
+ || (failure.cause !== undefined && isUniqueConflict(failure.cause));
91
+ }
@@ -0,0 +1,8 @@
1
+ export * from './component-host-installer.js';
2
+ export * from './outbound-host-installer.js';
3
+ export * from './sender-enrichment.js';
4
+ export * from './conversation-migration.js';
5
+ export * from './locale-host-installer.js';
6
+ export * from './database-config.js';
7
+ export * from './database-state.js';
8
+ export * from './database-host-installer.js';
@@ -0,0 +1,8 @@
1
+ export * from './component-host-installer.js';
2
+ export * from './outbound-host-installer.js';
3
+ export * from './sender-enrichment.js';
4
+ export * from './conversation-migration.js';
5
+ export * from './locale-host-installer.js';
6
+ export * from './database-config.js';
7
+ export * from './database-state.js';
8
+ export * from './database-host-installer.js';
@@ -0,0 +1,3 @@
1
+ import { type DatabaseHost, type RootResourceInstaller } from '@zhin.js/plugin-runtime';
2
+ /** Uses the existing SQL state port; no file or memory persistence fallback. */
3
+ export declare function installLocaleHost(database: DatabaseHost): RootResourceInstaller;
@@ -0,0 +1,60 @@
1
+ import { commandFeatureId, defineCommand } from '@zhin.js/command';
2
+ import { createMessages, isLocale, PluginStateStore, rootPluginId, userLocalePreferencesToken, } from '@zhin.js/plugin-runtime';
3
+ const messages = createMessages({
4
+ usage: { 'zh-CN': '用法:{chinese} 或 {english}', en: 'Usage: {chinese} or {english}' },
5
+ unavailable: { 'zh-CN': '个人语言设置需要 SQLite、MySQL 或 PostgreSQL 持久存储;当前仍使用项目语言。', en: 'Personal language settings require SQLite, MySQL, or PostgreSQL storage. The project language is still in use.' },
6
+ identity: { 'zh-CN': '请在有真实发送者身份的聊天中设置个人语言。', en: 'Set your language from a chat with a sender identity.' },
7
+ commandUnavailable: { 'zh-CN': '当前环境无法确定语言指令的调用方式。', en: 'The language command is unavailable in this command environment.' },
8
+ saved: { 'zh-CN': '个人语言已设置为简体中文;新操作生效,进行中的交互保持原语言。', en: 'Your language is now English. New operations use it; ongoing interactions keep their original language.' },
9
+ failed: { 'zh-CN': '无法确认个人语言已保存,请稍后重新设置。', en: 'The language setting could not be confirmed. Please try setting it again later.' },
10
+ });
11
+ /** Uses the existing SQL state port; no file or memory persistence fallback. */
12
+ export function installLocaleHost(database) {
13
+ return (context) => {
14
+ let preferences;
15
+ if (database.state && ['sqlite', 'mysql', 'pg'].includes(database.dialect)) {
16
+ const state = new PluginStateStore(rootPluginId(), database.state, undefined, context.admission);
17
+ preferences = Object.freeze({
18
+ async get(endpoint, senderId) {
19
+ const value = await state.forUser(endpoint, senderId).get('locale');
20
+ return isLocale(value) ? value : undefined;
21
+ },
22
+ async set(endpoint, senderId, locale) {
23
+ if (!isLocale(locale))
24
+ throw new TypeError('Unsupported locale');
25
+ await state.forUser(endpoint, senderId).set('locale', locale);
26
+ },
27
+ });
28
+ context.resources.provide(userLocalePreferencesToken, preferences);
29
+ }
30
+ if (!context.hasFeature?.(commandFeatureId))
31
+ return;
32
+ context.addFeature(commandFeatureId, 'language', defineCommand({
33
+ description: '设置个人语言',
34
+ descriptionI18n: { en: 'Set your language' },
35
+ execute: async (command) => {
36
+ const requested = command.args.join(' ').trim();
37
+ const input = command.input;
38
+ if (!input?.sender?.id || !input.conversation)
39
+ return messages(command.locale, 'identity');
40
+ if (!isLocale(requested)) {
41
+ const invocation = command.formatCommand('language');
42
+ if (invocation === undefined)
43
+ return messages(command.locale, 'commandUnavailable');
44
+ return messages(command.locale, 'usage', {
45
+ chinese: `${invocation} zh-CN`, english: `${invocation} en`,
46
+ });
47
+ }
48
+ if (!preferences)
49
+ return messages(command.locale, 'unavailable');
50
+ try {
51
+ await preferences.set(input.conversation.endpoint, input.sender.id, requested);
52
+ }
53
+ catch {
54
+ return messages(command.locale, 'failed');
55
+ }
56
+ return messages(requested, 'saved');
57
+ },
58
+ }));
59
+ };
60
+ }
@@ -0,0 +1,8 @@
1
+ import type { EndpointRuntime } from '../endpoint-runtime.js';
2
+ import { type OutboundRootHost, type RootResourceInstaller } from '@zhin.js/plugin-runtime';
3
+ export interface OutboundRuntimePort {
4
+ readonly endpoints: Pick<EndpointRuntime, 'captureOperation' | 'capabilities' | 'send' | 'sendTarget' | 'addReaction' | 'removeReaction' | 'recall' | 'edit' | 'typing'>;
5
+ runWithSnapshotView<T>(operation: () => Promise<T>): Promise<T>;
6
+ }
7
+ export declare function createOutboundHost(im: OutboundRuntimePort): OutboundRootHost;
8
+ export declare function installOutboundHost(im: OutboundRuntimePort): RootResourceInstaller;
@@ -0,0 +1,153 @@
1
+ import { formatCompact, getLogger } from '@zhin.js/logger';
2
+ import { EndpointDeliveryError } from '@zhin.js/im-contract';
3
+ import { outboundHostToken, outboundRootHostToken, PluginOutboundHost, rootPluginId, } from '@zhin.js/plugin-runtime';
4
+ const logger = getLogger('OutboundHost');
5
+ export function createOutboundHost(im) {
6
+ return {
7
+ async sendTarget(target, content, requester, options) {
8
+ try {
9
+ const result = options
10
+ ? await im.endpoints.sendTarget(target, content, requester, options)
11
+ : await im.endpoints.sendTarget(target, content, requester);
12
+ return result.messageId || null;
13
+ }
14
+ catch (error) {
15
+ logger.debug(formatCompact({
16
+ op: 'outbound_send_failed',
17
+ adapter: target.endpoint.adapter,
18
+ endpointKey: target.endpoint.id,
19
+ error: error instanceof Error ? error.message : String(error),
20
+ }));
21
+ throw error;
22
+ }
23
+ },
24
+ captureOperation(input, requester) {
25
+ const captured = im.endpoints.captureOperation({ ...input, requester });
26
+ const control = captured.control;
27
+ return Object.freeze({
28
+ target: captured.target, signal: captured.signal,
29
+ send: async (content, options) => {
30
+ const receipt = await captured.send(content, options);
31
+ if (receipt.status !== 'sent') {
32
+ throw new EndpointDeliveryError(receipt.failure?.code ?? 'outbound_failed', receipt.failure?.message ?? 'Delivery was not confirmed.', receipt.failure?.deliveryUnknown ? 'unknown' : receipt.status === 'rejected' ? 'rejected' : 'not_sent');
33
+ }
34
+ return receipt.message?.id ?? null;
35
+ },
36
+ ...(control?.recall ? { recall: message => control.recall({ message }) } : {}),
37
+ ...(control?.edit ? { edit: (message, content) => control.edit({ message, content }) } : {}),
38
+ ...(control?.addReaction ? { addReaction: (message, emoji, hint) => control.addReaction({ message, emoji, hint }) } : {}),
39
+ ...(control?.removeReaction ? { removeReaction: (message, reactionId) => control.removeReaction({ message, reactionId }) } : {}),
40
+ ...(control?.typing ? { typing: (conversation, active) => control.typing({ conversation, active }) } : {}),
41
+ release: captured.release,
42
+ });
43
+ },
44
+ runWithView: (operation) => im.runWithSnapshotView(operation),
45
+ capabilities(input) {
46
+ const capabilities = im.endpoints.capabilities(input);
47
+ const operations = capabilities?.operations;
48
+ if (!operations)
49
+ return { operations: Object.freeze([]), ...(capabilities?.kinds ? { kinds: capabilities.kinds } : {}) };
50
+ return {
51
+ operations: Object.freeze(['recall', 'edit', 'reaction', 'typing']
52
+ .filter((operation) => operations[operation] === true)),
53
+ ...(capabilities?.kinds ? { kinds: capabilities.kinds } : {}),
54
+ };
55
+ },
56
+ async send(input) {
57
+ try {
58
+ const result = await im.endpoints.send({
59
+ adapter: input.adapter,
60
+ endpointKey: input.endpointKey,
61
+ conversation: input.conversation,
62
+ content: input.content,
63
+ ...(input.locale ? { locale: input.locale } : {}),
64
+ });
65
+ return result.messageId || null;
66
+ }
67
+ catch (error) {
68
+ logger.debug(formatCompact({
69
+ op: 'outbound_send_failed',
70
+ adapter: input.adapter,
71
+ endpointKey: input.endpointKey,
72
+ error: error instanceof Error ? error.message : String(error),
73
+ }));
74
+ // Business callers must distinguish failed delivery from a successful
75
+ // send without a platform message id. Optional activity feedback owns
76
+ // its best-effort handling at the call site.
77
+ throw error;
78
+ }
79
+ },
80
+ async addReaction(input) {
81
+ try {
82
+ return await im.endpoints.addReaction({
83
+ message: input.message,
84
+ emoji: input.emoji,
85
+ sceneType: input.sceneType,
86
+ channelId: input.channelId,
87
+ });
88
+ }
89
+ catch (error) {
90
+ logger.debug(formatCompact({
91
+ op: 'outbound_add_reaction_failed',
92
+ error: error instanceof Error ? error.message : String(error),
93
+ }));
94
+ return null;
95
+ }
96
+ },
97
+ async removeReaction(input) {
98
+ try {
99
+ await im.endpoints.removeReaction({
100
+ message: input.message,
101
+ reactionId: input.reactionId,
102
+ });
103
+ }
104
+ catch (error) {
105
+ logger.debug(formatCompact({
106
+ op: 'outbound_remove_reaction_failed',
107
+ error: error instanceof Error ? error.message : String(error),
108
+ }));
109
+ }
110
+ },
111
+ async recall(input) {
112
+ await im.endpoints.recall({
113
+ message: input.message,
114
+ });
115
+ },
116
+ async edit(input) {
117
+ try {
118
+ return await im.endpoints.edit({
119
+ message: input.message,
120
+ content: input.content,
121
+ });
122
+ }
123
+ catch (error) {
124
+ logger.debug(formatCompact({
125
+ op: 'outbound_edit_failed',
126
+ error: error instanceof Error ? error.message : String(error),
127
+ }));
128
+ return null;
129
+ }
130
+ },
131
+ async typing(input) {
132
+ try {
133
+ await im.endpoints.typing({
134
+ conversation: input.conversation,
135
+ active: input.active,
136
+ });
137
+ }
138
+ catch (error) {
139
+ logger.debug(formatCompact({
140
+ op: 'outbound_typing_failed',
141
+ error: error instanceof Error ? error.message : String(error),
142
+ }));
143
+ }
144
+ },
145
+ };
146
+ }
147
+ export function installOutboundHost(im) {
148
+ return ({ resources, admission }) => {
149
+ const host = createOutboundHost(im);
150
+ resources.provide(outboundRootHostToken, host);
151
+ resources.provide(outboundHostToken, new PluginOutboundHost(rootPluginId(), host, admission));
152
+ };
153
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * ADR 0056: inbound sender roles come from {@link ChatRoleService} (stored grants only), never from
3
+ * configuration lists or platform standing. This module wires that model into the IM Runtime hosts.
4
+ */
5
+ import { type AdapterIndex } from '@zhin.js/adapter';
6
+ import type { OperationSession } from '@zhin.js/feature-kit';
7
+ import type { RuntimeSnapshot } from '@zhin.js/plugin-runtime';
8
+ import { type ChatRoleService } from '../../../built/roles.js';
9
+ import type { ImRuntime } from '../im-runtime.js';
10
+ export type ConfigurationChatAuthorizer = (session: OperationSession<string>, adapters: AdapterIndex) => boolean;
11
+ export interface SenderEnricherOptions {
12
+ /** Chat role resolution of the instance; undefined while it is not available. */
13
+ readonly roles: () => ChatRoleService | undefined;
14
+ }
15
+ /** `ImRuntime` `enrichSender` option over the chat role model. */
16
+ export declare function createSenderEnricher(options: SenderEnricherOptions): NonNullable<NonNullable<ConstructorParameters<typeof ImRuntime>[0]>['enrichSender']>;
17
+ /**
18
+ * Whether the operation's sender holds `owner` on the Adapter that received it — at its adapter
19
+ * scope (or globally), or on *any* configured endpoint of that same Adapter. The identity stays on
20
+ * the receiving Adapter; owners of other Adapters (including another instance of the same Adapter
21
+ * package) never qualify. Removed / retiring endpoints never qualify.
22
+ */
23
+ export declare function senderOwnsReceivingAdapter(session: OperationSession<string>, adapters: AdapterIndex, roles: ChatRoleService | undefined, snapshot: Pick<RuntimeSnapshot, 'tree'> | undefined): boolean;
24
+ /**
25
+ * Whether the operation's sender (identity on the receiving Adapter) is a **global** `owner`
26
+ * (ADR 0056 §2): host-wide operations — restarting the instance, editing the project
27
+ * configuration — need it; owners of an adapter, account or conversation do not qualify.
28
+ */
29
+ export declare function senderIsGlobalOwner(session: OperationSession<string>, adapters: AdapterIndex, roles: ChatRoleService | undefined, snapshot: Pick<RuntimeSnapshot, 'tree'> | undefined): boolean;
30
+ /**
31
+ * In-chat configuration authority (C2): private chats only, and the sender is a global owner —
32
+ * `config set` edits the project configuration, a host-wide capability (ADR 0056 §2).
33
+ */
34
+ export declare function createConfigurationChatAuthorizer(roles: () => ChatRoleService | undefined, snapshot?: () => Pick<RuntimeSnapshot, 'tree'> | undefined): ConfigurationChatAuthorizer;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * ADR 0056: inbound sender roles come from {@link ChatRoleService} (stored grants only), never from
3
+ * configuration lists or platform standing. This module wires that model into the IM Runtime hosts.
4
+ */
5
+ import { isAdapterIndex } from '@zhin.js/adapter';
6
+ import { createChatRoleSenderEnricher, } from '../../../built/roles.js';
7
+ /** `ImRuntime` `enrichSender` option over the chat role model. */
8
+ export function createSenderEnricher(options) {
9
+ const enrich = createChatRoleSenderEnricher(options);
10
+ return (sender, conversation, snapshot) => enrich(sender, conversation, snapshot);
11
+ }
12
+ function instanceAlias(snapshot, owner) {
13
+ try {
14
+ return snapshot?.tree.get(owner)?.instanceKey;
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ /**
21
+ * Whether the operation's sender holds `owner` on the Adapter that received it — at its adapter
22
+ * scope (or globally), or on *any* configured endpoint of that same Adapter. The identity stays on
23
+ * the receiving Adapter; owners of other Adapters (including another instance of the same Adapter
24
+ * package) never qualify. Removed / retiring endpoints never qualify.
25
+ */
26
+ export function senderOwnsReceivingAdapter(session, adapters, roles, snapshot) {
27
+ if (!session.sender?.id || !isAdapterIndex(adapters) || session.signal.aborted)
28
+ return false;
29
+ const id = session.scene.endpoint.id;
30
+ const adapter = adapters.adapterForEndpoint(id);
31
+ const child = adapter?.find(id);
32
+ if (!adapter || !child || session.adapter !== adapter || session.endpoint !== adapter.getEndpoint(child.desired.instanceId))
33
+ return false;
34
+ if (!child.started)
35
+ return false;
36
+ const alias = instanceAlias(snapshot, adapter.descriptor.owner);
37
+ if (!roles || !alias)
38
+ return false;
39
+ const identity = { adapter: alias, userId: session.sender.id };
40
+ const owns = (key) => { try {
41
+ return roles.hasRole(identity, key, 'owner');
42
+ }
43
+ catch {
44
+ return false;
45
+ } };
46
+ if (owns(alias))
47
+ return true;
48
+ return adapter.list().some(entry => !entry.removed && !entry.retiring && owns(`${alias}/${entry.endpointId}`));
49
+ }
50
+ /**
51
+ * Whether the operation's sender (identity on the receiving Adapter) is a **global** `owner`
52
+ * (ADR 0056 §2): host-wide operations — restarting the instance, editing the project
53
+ * configuration — need it; owners of an adapter, account or conversation do not qualify.
54
+ */
55
+ export function senderIsGlobalOwner(session, adapters, roles, snapshot) {
56
+ if (!session.sender?.id || !isAdapterIndex(adapters) || session.signal.aborted || !roles)
57
+ return false;
58
+ const id = session.scene.endpoint.id;
59
+ const adapter = adapters.adapterForEndpoint(id);
60
+ const child = adapter?.find(id);
61
+ if (!adapter || !child || session.adapter !== adapter || session.endpoint !== adapter.getEndpoint(child.desired.instanceId))
62
+ return false;
63
+ if (!child.started)
64
+ return false;
65
+ const alias = instanceAlias(snapshot, adapter.descriptor.owner);
66
+ if (!alias)
67
+ return false;
68
+ try {
69
+ return roles.hasRole({ adapter: alias, userId: session.sender.id }, '', 'owner');
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
75
+ /**
76
+ * In-chat configuration authority (C2): private chats only, and the sender is a global owner —
77
+ * `config set` edits the project configuration, a host-wide capability (ADR 0056 §2).
78
+ */
79
+ export function createConfigurationChatAuthorizer(roles, snapshot = () => undefined) {
80
+ return (session, adapters) => session.scene.kind === 'private'
81
+ && senderIsGlobalOwner(session, adapters, roles(), snapshot());
82
+ }