@reglow/reglow 0.4.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 (405) hide show
  1. package/README.md +267 -0
  2. package/dist/index.d.ts +25 -0
  3. package/dist/index.js +28 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/reglow/common/errors.d.ts +92 -0
  6. package/dist/reglow/common/errors.js +127 -0
  7. package/dist/reglow/common/errors.js.map +1 -0
  8. package/dist/reglow/common/exception_handler.d.ts +14 -0
  9. package/dist/reglow/common/exception_handler.js +135 -0
  10. package/dist/reglow/common/exception_handler.js.map +1 -0
  11. package/dist/reglow/common/i18n.d.ts +15 -0
  12. package/dist/reglow/common/i18n.js +61 -0
  13. package/dist/reglow/common/i18n.js.map +1 -0
  14. package/dist/reglow/common/middleware.d.ts +5 -0
  15. package/dist/reglow/common/middleware.js +131 -0
  16. package/dist/reglow/common/middleware.js.map +1 -0
  17. package/dist/reglow/common/response.d.ts +28 -0
  18. package/dist/reglow/common/response.js +42 -0
  19. package/dist/reglow/common/response.js.map +1 -0
  20. package/dist/reglow/common/serialize.d.ts +6 -0
  21. package/dist/reglow/common/serialize.js +39 -0
  22. package/dist/reglow/common/serialize.js.map +1 -0
  23. package/dist/reglow/common/utils/date_utils.d.ts +10 -0
  24. package/dist/reglow/common/utils/date_utils.js +30 -0
  25. package/dist/reglow/common/utils/date_utils.js.map +1 -0
  26. package/dist/reglow/common/utils/parse-user-agent.d.ts +11 -0
  27. package/dist/reglow/common/utils/parse-user-agent.js +80 -0
  28. package/dist/reglow/common/utils/parse-user-agent.js.map +1 -0
  29. package/dist/reglow/common/utils/string_utils.d.ts +14 -0
  30. package/dist/reglow/common/utils/string_utils.js +31 -0
  31. package/dist/reglow/common/utils/string_utils.js.map +1 -0
  32. package/dist/reglow/core/auth.d.ts +15 -0
  33. package/dist/reglow/core/auth.js +184 -0
  34. package/dist/reglow/core/auth.js.map +1 -0
  35. package/dist/reglow/core/cache.d.ts +6 -0
  36. package/dist/reglow/core/cache.js +15 -0
  37. package/dist/reglow/core/cache.js.map +1 -0
  38. package/dist/reglow/core/config.d.ts +45 -0
  39. package/dist/reglow/core/config.js +83 -0
  40. package/dist/reglow/core/config.js.map +1 -0
  41. package/dist/reglow/core/data_scope.d.ts +21 -0
  42. package/dist/reglow/core/data_scope.js +20 -0
  43. package/dist/reglow/core/data_scope.js.map +1 -0
  44. package/dist/reglow/core/database.d.ts +4 -0
  45. package/dist/reglow/core/database.js +43 -0
  46. package/dist/reglow/core/database.js.map +1 -0
  47. package/dist/reglow/core/email.d.ts +12 -0
  48. package/dist/reglow/core/email.js +277 -0
  49. package/dist/reglow/core/email.js.map +1 -0
  50. package/dist/reglow/core/entities.d.ts +462 -0
  51. package/dist/reglow/core/entities.js +6 -0
  52. package/dist/reglow/core/entities.js.map +1 -0
  53. package/dist/reglow/core/fastify.d.ts +21 -0
  54. package/dist/reglow/core/fastify.js +2 -0
  55. package/dist/reglow/core/fastify.js.map +1 -0
  56. package/dist/reglow/core/logging.d.ts +8 -0
  57. package/dist/reglow/core/logging.js +32 -0
  58. package/dist/reglow/core/logging.js.map +1 -0
  59. package/dist/reglow/core/models.d.ts +98 -0
  60. package/dist/reglow/core/models.js +57 -0
  61. package/dist/reglow/core/models.js.map +1 -0
  62. package/dist/reglow/core/observability.d.ts +17 -0
  63. package/dist/reglow/core/observability.js +92 -0
  64. package/dist/reglow/core/observability.js.map +1 -0
  65. package/dist/reglow/core/payment.d.ts +107 -0
  66. package/dist/reglow/core/payment.js +1177 -0
  67. package/dist/reglow/core/payment.js.map +1 -0
  68. package/dist/reglow/core/plugin.d.ts +19 -0
  69. package/dist/reglow/core/plugin.js +85 -0
  70. package/dist/reglow/core/plugin.js.map +1 -0
  71. package/dist/reglow/core/rate_limit.d.ts +2 -0
  72. package/dist/reglow/core/rate_limit.js +28 -0
  73. package/dist/reglow/core/rate_limit.js.map +1 -0
  74. package/dist/reglow/core/redis.d.ts +30 -0
  75. package/dist/reglow/core/redis.js +278 -0
  76. package/dist/reglow/core/redis.js.map +1 -0
  77. package/dist/reglow/core/redis_keys.d.ts +22 -0
  78. package/dist/reglow/core/redis_keys.js +59 -0
  79. package/dist/reglow/core/redis_keys.js.map +1 -0
  80. package/dist/reglow/core/security.d.ts +25 -0
  81. package/dist/reglow/core/security.js +64 -0
  82. package/dist/reglow/core/security.js.map +1 -0
  83. package/dist/reglow/core/session.d.ts +17 -0
  84. package/dist/reglow/core/session.js +194 -0
  85. package/dist/reglow/core/session.js.map +1 -0
  86. package/dist/reglow/core/sms.d.ts +19 -0
  87. package/dist/reglow/core/sms.js +33 -0
  88. package/dist/reglow/core/sms.js.map +1 -0
  89. package/dist/reglow/core/storage.d.ts +45 -0
  90. package/dist/reglow/core/storage.js +249 -0
  91. package/dist/reglow/core/storage.js.map +1 -0
  92. package/dist/reglow/modules/agreement/controller.d.ts +7 -0
  93. package/dist/reglow/modules/agreement/controller.js +242 -0
  94. package/dist/reglow/modules/agreement/controller.js.map +1 -0
  95. package/dist/reglow/modules/agreement/repository.d.ts +30 -0
  96. package/dist/reglow/modules/agreement/repository.js +160 -0
  97. package/dist/reglow/modules/agreement/repository.js.map +1 -0
  98. package/dist/reglow/modules/agreement/router.d.ts +13 -0
  99. package/dist/reglow/modules/agreement/router.js +10 -0
  100. package/dist/reglow/modules/agreement/router.js.map +1 -0
  101. package/dist/reglow/modules/agreement/schema.d.ts +30 -0
  102. package/dist/reglow/modules/agreement/schema.js +27 -0
  103. package/dist/reglow/modules/agreement/schema.js.map +1 -0
  104. package/dist/reglow/modules/agreement/service.d.ts +42 -0
  105. package/dist/reglow/modules/agreement/service.js +349 -0
  106. package/dist/reglow/modules/agreement/service.js.map +1 -0
  107. package/dist/reglow/modules/ai/controller.d.ts +25 -0
  108. package/dist/reglow/modules/ai/controller.js +1143 -0
  109. package/dist/reglow/modules/ai/controller.js.map +1 -0
  110. package/dist/reglow/modules/ai/router.d.ts +9 -0
  111. package/dist/reglow/modules/ai/router.js +7 -0
  112. package/dist/reglow/modules/ai/router.js.map +1 -0
  113. package/dist/reglow/modules/ai/schema.d.ts +48 -0
  114. package/dist/reglow/modules/ai/schema.js +40 -0
  115. package/dist/reglow/modules/ai/schema.js.map +1 -0
  116. package/dist/reglow/modules/ai/service.d.ts +8 -0
  117. package/dist/reglow/modules/ai/service.js +137 -0
  118. package/dist/reglow/modules/ai/service.js.map +1 -0
  119. package/dist/reglow/modules/article/controller.d.ts +6 -0
  120. package/dist/reglow/modules/article/controller.js +204 -0
  121. package/dist/reglow/modules/article/controller.js.map +1 -0
  122. package/dist/reglow/modules/article/repository.d.ts +37 -0
  123. package/dist/reglow/modules/article/repository.js +184 -0
  124. package/dist/reglow/modules/article/repository.js.map +1 -0
  125. package/dist/reglow/modules/article/router.d.ts +10 -0
  126. package/dist/reglow/modules/article/router.js +8 -0
  127. package/dist/reglow/modules/article/router.js.map +1 -0
  128. package/dist/reglow/modules/article/schema.d.ts +66 -0
  129. package/dist/reglow/modules/article/schema.js +66 -0
  130. package/dist/reglow/modules/article/schema.js.map +1 -0
  131. package/dist/reglow/modules/article/service.d.ts +81 -0
  132. package/dist/reglow/modules/article/service.js +254 -0
  133. package/dist/reglow/modules/article/service.js.map +1 -0
  134. package/dist/reglow/modules/auth/controller.d.ts +6 -0
  135. package/dist/reglow/modules/auth/controller.js +127 -0
  136. package/dist/reglow/modules/auth/controller.js.map +1 -0
  137. package/dist/reglow/modules/auth/router.d.ts +9 -0
  138. package/dist/reglow/modules/auth/router.js +7 -0
  139. package/dist/reglow/modules/auth/router.js.map +1 -0
  140. package/dist/reglow/modules/auth/schema.d.ts +59 -0
  141. package/dist/reglow/modules/auth/schema.js +56 -0
  142. package/dist/reglow/modules/auth/schema.js.map +1 -0
  143. package/dist/reglow/modules/auth/service.d.ts +69 -0
  144. package/dist/reglow/modules/auth/service.js +492 -0
  145. package/dist/reglow/modules/auth/service.js.map +1 -0
  146. package/dist/reglow/modules/config/controller.d.ts +7 -0
  147. package/dist/reglow/modules/config/controller.js +297 -0
  148. package/dist/reglow/modules/config/controller.js.map +1 -0
  149. package/dist/reglow/modules/config/repository.d.ts +17 -0
  150. package/dist/reglow/modules/config/repository.js +88 -0
  151. package/dist/reglow/modules/config/repository.js.map +1 -0
  152. package/dist/reglow/modules/config/router.d.ts +13 -0
  153. package/dist/reglow/modules/config/router.js +8 -0
  154. package/dist/reglow/modules/config/router.js.map +1 -0
  155. package/dist/reglow/modules/config/schema.d.ts +37 -0
  156. package/dist/reglow/modules/config/schema.js +25 -0
  157. package/dist/reglow/modules/config/schema.js.map +1 -0
  158. package/dist/reglow/modules/customer_service/controller.d.ts +3 -0
  159. package/dist/reglow/modules/customer_service/controller.js +443 -0
  160. package/dist/reglow/modules/customer_service/controller.js.map +1 -0
  161. package/dist/reglow/modules/customer_service/document_parser.d.ts +5 -0
  162. package/dist/reglow/modules/customer_service/document_parser.js +84 -0
  163. package/dist/reglow/modules/customer_service/document_parser.js.map +1 -0
  164. package/dist/reglow/modules/customer_service/repository.d.ts +72 -0
  165. package/dist/reglow/modules/customer_service/repository.js +376 -0
  166. package/dist/reglow/modules/customer_service/repository.js.map +1 -0
  167. package/dist/reglow/modules/customer_service/router.d.ts +14 -0
  168. package/dist/reglow/modules/customer_service/router.js +9 -0
  169. package/dist/reglow/modules/customer_service/router.js.map +1 -0
  170. package/dist/reglow/modules/customer_service/schema.d.ts +97 -0
  171. package/dist/reglow/modules/customer_service/schema.js +91 -0
  172. package/dist/reglow/modules/customer_service/schema.js.map +1 -0
  173. package/dist/reglow/modules/customer_service/sdk_template.html +666 -0
  174. package/dist/reglow/modules/customer_service/service.d.ts +92 -0
  175. package/dist/reglow/modules/customer_service/service.js +1642 -0
  176. package/dist/reglow/modules/customer_service/service.js.map +1 -0
  177. package/dist/reglow/modules/customer_service/ws.d.ts +29 -0
  178. package/dist/reglow/modules/customer_service/ws.js +182 -0
  179. package/dist/reglow/modules/customer_service/ws.js.map +1 -0
  180. package/dist/reglow/modules/dept/controller.d.ts +6 -0
  181. package/dist/reglow/modules/dept/controller.js +122 -0
  182. package/dist/reglow/modules/dept/controller.js.map +1 -0
  183. package/dist/reglow/modules/dept/repository.d.ts +24 -0
  184. package/dist/reglow/modules/dept/repository.js +140 -0
  185. package/dist/reglow/modules/dept/repository.js.map +1 -0
  186. package/dist/reglow/modules/dept/router.d.ts +9 -0
  187. package/dist/reglow/modules/dept/router.js +7 -0
  188. package/dist/reglow/modules/dept/router.js.map +1 -0
  189. package/dist/reglow/modules/dept/schema.d.ts +37 -0
  190. package/dist/reglow/modules/dept/schema.js +33 -0
  191. package/dist/reglow/modules/dept/schema.js.map +1 -0
  192. package/dist/reglow/modules/dept/service.d.ts +33 -0
  193. package/dist/reglow/modules/dept/service.js +88 -0
  194. package/dist/reglow/modules/dept/service.js.map +1 -0
  195. package/dist/reglow/modules/dict/controller.d.ts +5 -0
  196. package/dist/reglow/modules/dict/controller.js +87 -0
  197. package/dist/reglow/modules/dict/controller.js.map +1 -0
  198. package/dist/reglow/modules/dict/model.d.ts +7 -0
  199. package/dist/reglow/modules/dict/model.js +8 -0
  200. package/dist/reglow/modules/dict/model.js.map +1 -0
  201. package/dist/reglow/modules/dict/repository.d.ts +16 -0
  202. package/dist/reglow/modules/dict/repository.js +103 -0
  203. package/dist/reglow/modules/dict/repository.js.map +1 -0
  204. package/dist/reglow/modules/dict/router.d.ts +9 -0
  205. package/dist/reglow/modules/dict/router.js +7 -0
  206. package/dist/reglow/modules/dict/router.js.map +1 -0
  207. package/dist/reglow/modules/dict/schema.d.ts +38 -0
  208. package/dist/reglow/modules/dict/schema.js +37 -0
  209. package/dist/reglow/modules/dict/schema.js.map +1 -0
  210. package/dist/reglow/modules/dict/service.d.ts +15 -0
  211. package/dist/reglow/modules/dict/service.js +88 -0
  212. package/dist/reglow/modules/dict/service.js.map +1 -0
  213. package/dist/reglow/modules/employee/controller.d.ts +6 -0
  214. package/dist/reglow/modules/employee/controller.js +167 -0
  215. package/dist/reglow/modules/employee/controller.js.map +1 -0
  216. package/dist/reglow/modules/employee/repository.d.ts +22 -0
  217. package/dist/reglow/modules/employee/repository.js +129 -0
  218. package/dist/reglow/modules/employee/repository.js.map +1 -0
  219. package/dist/reglow/modules/employee/router.d.ts +9 -0
  220. package/dist/reglow/modules/employee/router.js +7 -0
  221. package/dist/reglow/modules/employee/router.js.map +1 -0
  222. package/dist/reglow/modules/employee/schema.d.ts +57 -0
  223. package/dist/reglow/modules/employee/schema.js +58 -0
  224. package/dist/reglow/modules/employee/schema.js.map +1 -0
  225. package/dist/reglow/modules/employee/service.d.ts +30 -0
  226. package/dist/reglow/modules/employee/service.js +193 -0
  227. package/dist/reglow/modules/employee/service.js.map +1 -0
  228. package/dist/reglow/modules/log/controller.d.ts +6 -0
  229. package/dist/reglow/modules/log/controller.js +137 -0
  230. package/dist/reglow/modules/log/controller.js.map +1 -0
  231. package/dist/reglow/modules/log/data-scope.d.ts +9 -0
  232. package/dist/reglow/modules/log/data-scope.js +108 -0
  233. package/dist/reglow/modules/log/data-scope.js.map +1 -0
  234. package/dist/reglow/modules/log/router.d.ts +9 -0
  235. package/dist/reglow/modules/log/router.js +7 -0
  236. package/dist/reglow/modules/log/router.js.map +1 -0
  237. package/dist/reglow/modules/material/controller.d.ts +3 -0
  238. package/dist/reglow/modules/material/controller.js +400 -0
  239. package/dist/reglow/modules/material/controller.js.map +1 -0
  240. package/dist/reglow/modules/material/repository.d.ts +37 -0
  241. package/dist/reglow/modules/material/repository.js +183 -0
  242. package/dist/reglow/modules/material/repository.js.map +1 -0
  243. package/dist/reglow/modules/material/router.d.ts +14 -0
  244. package/dist/reglow/modules/material/router.js +11 -0
  245. package/dist/reglow/modules/material/router.js.map +1 -0
  246. package/dist/reglow/modules/material/schema.d.ts +40 -0
  247. package/dist/reglow/modules/material/schema.js +34 -0
  248. package/dist/reglow/modules/material/schema.js.map +1 -0
  249. package/dist/reglow/modules/material/service.d.ts +85 -0
  250. package/dist/reglow/modules/material/service.js +292 -0
  251. package/dist/reglow/modules/material/service.js.map +1 -0
  252. package/dist/reglow/modules/menu/controller.d.ts +6 -0
  253. package/dist/reglow/modules/menu/controller.js +69 -0
  254. package/dist/reglow/modules/menu/controller.js.map +1 -0
  255. package/dist/reglow/modules/menu/repository.d.ts +14 -0
  256. package/dist/reglow/modules/menu/repository.js +37 -0
  257. package/dist/reglow/modules/menu/repository.js.map +1 -0
  258. package/dist/reglow/modules/menu/router.d.ts +9 -0
  259. package/dist/reglow/modules/menu/router.js +7 -0
  260. package/dist/reglow/modules/menu/router.js.map +1 -0
  261. package/dist/reglow/modules/menu/schema.d.ts +39 -0
  262. package/dist/reglow/modules/menu/schema.js +37 -0
  263. package/dist/reglow/modules/menu/schema.js.map +1 -0
  264. package/dist/reglow/modules/menu/service.d.ts +31 -0
  265. package/dist/reglow/modules/menu/service.js +89 -0
  266. package/dist/reglow/modules/menu/service.js.map +1 -0
  267. package/dist/reglow/modules/message/controller.d.ts +7 -0
  268. package/dist/reglow/modules/message/controller.js +260 -0
  269. package/dist/reglow/modules/message/controller.js.map +1 -0
  270. package/dist/reglow/modules/message/repository.d.ts +27 -0
  271. package/dist/reglow/modules/message/repository.js +145 -0
  272. package/dist/reglow/modules/message/repository.js.map +1 -0
  273. package/dist/reglow/modules/message/router.d.ts +13 -0
  274. package/dist/reglow/modules/message/router.js +8 -0
  275. package/dist/reglow/modules/message/router.js.map +1 -0
  276. package/dist/reglow/modules/message/schema.d.ts +39 -0
  277. package/dist/reglow/modules/message/schema.js +37 -0
  278. package/dist/reglow/modules/message/schema.js.map +1 -0
  279. package/dist/reglow/modules/message/service.d.ts +70 -0
  280. package/dist/reglow/modules/message/service.js +199 -0
  281. package/dist/reglow/modules/message/service.js.map +1 -0
  282. package/dist/reglow/modules/notice/controller.d.ts +6 -0
  283. package/dist/reglow/modules/notice/controller.js +123 -0
  284. package/dist/reglow/modules/notice/controller.js.map +1 -0
  285. package/dist/reglow/modules/notice/repository.d.ts +25 -0
  286. package/dist/reglow/modules/notice/repository.js +145 -0
  287. package/dist/reglow/modules/notice/repository.js.map +1 -0
  288. package/dist/reglow/modules/notice/router.d.ts +9 -0
  289. package/dist/reglow/modules/notice/router.js +7 -0
  290. package/dist/reglow/modules/notice/router.js.map +1 -0
  291. package/dist/reglow/modules/notice/schema.d.ts +23 -0
  292. package/dist/reglow/modules/notice/schema.js +22 -0
  293. package/dist/reglow/modules/notice/schema.js.map +1 -0
  294. package/dist/reglow/modules/notice/service.d.ts +45 -0
  295. package/dist/reglow/modules/notice/service.js +149 -0
  296. package/dist/reglow/modules/notice/service.js.map +1 -0
  297. package/dist/reglow/modules/payment/controller.d.ts +6 -0
  298. package/dist/reglow/modules/payment/controller.js +186 -0
  299. package/dist/reglow/modules/payment/controller.js.map +1 -0
  300. package/dist/reglow/modules/payment/router.d.ts +10 -0
  301. package/dist/reglow/modules/payment/router.js +8 -0
  302. package/dist/reglow/modules/payment/router.js.map +1 -0
  303. package/dist/reglow/modules/payment/schema.d.ts +52 -0
  304. package/dist/reglow/modules/payment/schema.js +43 -0
  305. package/dist/reglow/modules/payment/schema.js.map +1 -0
  306. package/dist/reglow/modules/payment/service.d.ts +28 -0
  307. package/dist/reglow/modules/payment/service.js +219 -0
  308. package/dist/reglow/modules/payment/service.js.map +1 -0
  309. package/dist/reglow/modules/photo/controller.d.ts +2 -0
  310. package/dist/reglow/modules/photo/controller.js +323 -0
  311. package/dist/reglow/modules/photo/controller.js.map +1 -0
  312. package/dist/reglow/modules/photo/controller_client.d.ts +2 -0
  313. package/dist/reglow/modules/photo/controller_client.js +293 -0
  314. package/dist/reglow/modules/photo/controller_client.js.map +1 -0
  315. package/dist/reglow/modules/photo/repository.d.ts +50 -0
  316. package/dist/reglow/modules/photo/repository.js +240 -0
  317. package/dist/reglow/modules/photo/repository.js.map +1 -0
  318. package/dist/reglow/modules/photo/router.d.ts +15 -0
  319. package/dist/reglow/modules/photo/router.js +10 -0
  320. package/dist/reglow/modules/photo/router.js.map +1 -0
  321. package/dist/reglow/modules/photo/schema.d.ts +69 -0
  322. package/dist/reglow/modules/photo/schema.js +66 -0
  323. package/dist/reglow/modules/photo/schema.js.map +1 -0
  324. package/dist/reglow/modules/photo/service.d.ts +98 -0
  325. package/dist/reglow/modules/photo/service.js +295 -0
  326. package/dist/reglow/modules/photo/service.js.map +1 -0
  327. package/dist/reglow/modules/post/controller.d.ts +6 -0
  328. package/dist/reglow/modules/post/controller.js +61 -0
  329. package/dist/reglow/modules/post/controller.js.map +1 -0
  330. package/dist/reglow/modules/post/repository.d.ts +12 -0
  331. package/dist/reglow/modules/post/repository.js +46 -0
  332. package/dist/reglow/modules/post/repository.js.map +1 -0
  333. package/dist/reglow/modules/post/router.d.ts +9 -0
  334. package/dist/reglow/modules/post/router.js +7 -0
  335. package/dist/reglow/modules/post/router.js.map +1 -0
  336. package/dist/reglow/modules/post/schema.d.ts +19 -0
  337. package/dist/reglow/modules/post/schema.js +18 -0
  338. package/dist/reglow/modules/post/schema.js.map +1 -0
  339. package/dist/reglow/modules/post/service.d.ts +18 -0
  340. package/dist/reglow/modules/post/service.js +44 -0
  341. package/dist/reglow/modules/post/service.js.map +1 -0
  342. package/dist/reglow/modules/role/controller.d.ts +6 -0
  343. package/dist/reglow/modules/role/controller.js +103 -0
  344. package/dist/reglow/modules/role/controller.js.map +1 -0
  345. package/dist/reglow/modules/role/repository.d.ts +22 -0
  346. package/dist/reglow/modules/role/repository.js +84 -0
  347. package/dist/reglow/modules/role/repository.js.map +1 -0
  348. package/dist/reglow/modules/role/router.d.ts +9 -0
  349. package/dist/reglow/modules/role/router.js +7 -0
  350. package/dist/reglow/modules/role/router.js.map +1 -0
  351. package/dist/reglow/modules/role/schema.d.ts +32 -0
  352. package/dist/reglow/modules/role/schema.js +29 -0
  353. package/dist/reglow/modules/role/schema.js.map +1 -0
  354. package/dist/reglow/modules/role/service.d.ts +22 -0
  355. package/dist/reglow/modules/role/service.js +72 -0
  356. package/dist/reglow/modules/role/service.js.map +1 -0
  357. package/dist/reglow/modules/user/controller.d.ts +6 -0
  358. package/dist/reglow/modules/user/controller.js +126 -0
  359. package/dist/reglow/modules/user/controller.js.map +1 -0
  360. package/dist/reglow/modules/user/controller_client.d.ts +2 -0
  361. package/dist/reglow/modules/user/controller_client.js +291 -0
  362. package/dist/reglow/modules/user/controller_client.js.map +1 -0
  363. package/dist/reglow/modules/user/repository.d.ts +12 -0
  364. package/dist/reglow/modules/user/repository.js +71 -0
  365. package/dist/reglow/modules/user/repository.js.map +1 -0
  366. package/dist/reglow/modules/user/router.d.ts +16 -0
  367. package/dist/reglow/modules/user/router.js +11 -0
  368. package/dist/reglow/modules/user/router.js.map +1 -0
  369. package/dist/reglow/modules/user/schema.d.ts +92 -0
  370. package/dist/reglow/modules/user/schema.js +82 -0
  371. package/dist/reglow/modules/user/schema.js.map +1 -0
  372. package/dist/reglow/modules/user/service.d.ts +43 -0
  373. package/dist/reglow/modules/user/service.js +311 -0
  374. package/dist/reglow/modules/user/service.js.map +1 -0
  375. package/dist/reglow/modules/video/controller.d.ts +2 -0
  376. package/dist/reglow/modules/video/controller.js +254 -0
  377. package/dist/reglow/modules/video/controller.js.map +1 -0
  378. package/dist/reglow/modules/video/repository.d.ts +38 -0
  379. package/dist/reglow/modules/video/repository.js +186 -0
  380. package/dist/reglow/modules/video/repository.js.map +1 -0
  381. package/dist/reglow/modules/video/router.d.ts +10 -0
  382. package/dist/reglow/modules/video/router.js +8 -0
  383. package/dist/reglow/modules/video/router.js.map +1 -0
  384. package/dist/reglow/modules/video/schema.d.ts +62 -0
  385. package/dist/reglow/modules/video/schema.js +61 -0
  386. package/dist/reglow/modules/video/schema.js.map +1 -0
  387. package/dist/reglow/modules/video/service.d.ts +80 -0
  388. package/dist/reglow/modules/video/service.js +251 -0
  389. package/dist/reglow/modules/video/service.js.map +1 -0
  390. package/dist/reglow/scripts/init-data.d.ts +44 -0
  391. package/dist/reglow/scripts/init-data.js +472 -0
  392. package/dist/reglow/scripts/init-data.js.map +1 -0
  393. package/dist/reglow/scripts/remove-business-menu.d.ts +1 -0
  394. package/dist/reglow/scripts/remove-business-menu.js +124 -0
  395. package/dist/reglow/scripts/remove-business-menu.js.map +1 -0
  396. package/dist/reglow/scripts/schema.d.ts +9 -0
  397. package/dist/reglow/scripts/schema.js +746 -0
  398. package/dist/reglow/scripts/schema.js.map +1 -0
  399. package/dist/reglow/scripts/sync-menu-mysql-to-sqlite.d.ts +1 -0
  400. package/dist/reglow/scripts/sync-menu-mysql-to-sqlite.js +304 -0
  401. package/dist/reglow/scripts/sync-menu-mysql-to-sqlite.js.map +1 -0
  402. package/dist/server.d.ts +1 -0
  403. package/dist/server.js +162 -0
  404. package/dist/server.js.map +1 -0
  405. package/package.json +79 -0
@@ -0,0 +1,1642 @@
1
+ /**
2
+ * 智能客服 Service - 业务逻辑核心
3
+ * 对应 backend-python 的 reglow/modules/customer_service/service.py
4
+ */
5
+ import crypto from "node:crypto";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { knex } from "../../core/database.js";
9
+ import { ModelRegistry } from "../../core/models.js";
10
+ import { getRedisStore } from "../../core/redis.js";
11
+ import { csVectorKey, csAgentOnlineKey } from "../../core/redis_keys.js";
12
+ import { AppException, ErrorCode } from "../../common/errors.js";
13
+ import { logger } from "../../core/logging.js";
14
+ import settings from "../../core/config.js";
15
+ import { mapTimestamp } from "../../common/serialize.js";
16
+ import { getProviderConfig } from "../ai/controller.js";
17
+ import { CSRepository } from "./repository.js";
18
+ import { parseDocument, splitText, SUPPORTED_EXTS } from "./document_parser.js";
19
+ import { wsManager } from "./ws.js";
20
+ import { resolveVisibility } from "../log/data-scope.js";
21
+ const uploadRoot = path.resolve(process.cwd(), settings.UPLOAD_DIR);
22
+ const _MIME_MAP = {
23
+ ".jpg": "image/jpeg",
24
+ ".jpeg": "image/jpeg",
25
+ ".png": "image/png",
26
+ ".gif": "image/gif",
27
+ ".webp": "image/webp",
28
+ };
29
+ // 默认 system prompt
30
+ const DEFAULT_SYSTEM_PROMPT = `你是一个专业、热情的智能客服助手。请遵循以下规则:
31
+ 1. 只基于提供的知识库资料回答问题,资料中没有的信息不要编造
32
+ 2. 涉及价格、库存、订单状态等实时信息,告知用户正在查询或建议联系人工客服
33
+ 3. 回答简洁明了,先给结论再补充细节
34
+ 4. 语气友好专业,主动帮助用户解决问题
35
+ 5. 如果用户情绪激动,先表示理解再给出解决方案
36
+ 6. 无法回答时,主动建议转人工客服`;
37
+ // 智能转人工:触发关键词(命中后调用 LLM 确认,避免误判)
38
+ const _AUTO_TRANSFER_KEYWORDS = [
39
+ "人工",
40
+ "真人",
41
+ "客服人员",
42
+ "转人工",
43
+ "找人工",
44
+ "人工客服",
45
+ "投诉",
46
+ "举报",
47
+ "差评",
48
+ "退款",
49
+ "赔偿",
50
+ "曝光",
51
+ "12315",
52
+ "太垃圾",
53
+ "什么破",
54
+ "气死",
55
+ "失望透顶",
56
+ "再也不",
57
+ "骗人",
58
+ ];
59
+ const _LLM_ROLE_MAP = {
60
+ user: "user",
61
+ assistant: "assistant",
62
+ system: "system",
63
+ // 人工坐席回复视为 assistant,LLM 兼容 API 不接受 agent 角色
64
+ agent: "assistant",
65
+ };
66
+ function llmRole(role) {
67
+ return _LLM_ROLE_MAP[role] ?? "assistant";
68
+ }
69
+ function tokenHex(bytes) {
70
+ return crypto.randomBytes(bytes).toString("hex");
71
+ }
72
+ function sse(obj) {
73
+ return `data: ${JSON.stringify(obj)}\n\n`;
74
+ }
75
+ function toJson(value) {
76
+ if (value === null || value === undefined)
77
+ return null;
78
+ if (typeof value === "string")
79
+ return value;
80
+ return JSON.stringify(value);
81
+ }
82
+ function fromJson(value) {
83
+ if (value === null || value === undefined)
84
+ return null;
85
+ if (typeof value !== "string")
86
+ return value;
87
+ try {
88
+ return JSON.parse(value);
89
+ }
90
+ catch {
91
+ return value;
92
+ }
93
+ }
94
+ function parseMixedContent(content) {
95
+ try {
96
+ const data = JSON.parse(content);
97
+ return { text: data.text ?? null, imageUrl: data.image_url ?? null };
98
+ }
99
+ catch {
100
+ return { text: null, imageUrl: content };
101
+ }
102
+ }
103
+ function appendMultimodalMessage(messages, msg) {
104
+ let text = null;
105
+ let imgUrl = null;
106
+ if (msg.content_type === "mixed") {
107
+ const parsed = parseMixedContent(msg.content);
108
+ text = parsed.text;
109
+ imgUrl = parsed.imageUrl;
110
+ }
111
+ else {
112
+ imgUrl = msg.content;
113
+ }
114
+ const parts = [];
115
+ if (text)
116
+ parts.push({ type: "text", text });
117
+ if (imgUrl)
118
+ parts.push({ type: "image_url", image_url: { url: imgUrl } });
119
+ if (parts.length) {
120
+ messages.push({ role: llmRole(msg.role), content: parts });
121
+ }
122
+ else {
123
+ messages.push({ role: llmRole(msg.role), content: msg.content || "" });
124
+ }
125
+ }
126
+ function resolveLocalImagesInMessages(messages) {
127
+ for (const msg of messages) {
128
+ const content = msg.content;
129
+ if (!Array.isArray(content))
130
+ continue;
131
+ for (const part of content) {
132
+ if (!part || typeof part !== "object")
133
+ continue;
134
+ const p = part;
135
+ if (p.type !== "image_url")
136
+ continue;
137
+ const imageUrl = p.image_url;
138
+ if (!imageUrl)
139
+ continue;
140
+ const url = typeof imageUrl.url === "string" ? imageUrl.url : "";
141
+ if (!url || url.startsWith("data:"))
142
+ continue;
143
+ let pathName = "";
144
+ try {
145
+ pathName = new URL(url, "http://local").pathname;
146
+ }
147
+ catch {
148
+ continue;
149
+ }
150
+ if (!pathName.startsWith("/uploads/"))
151
+ continue;
152
+ const rel = pathName.slice("/uploads/".length);
153
+ if (rel.includes("..") || rel.startsWith("/"))
154
+ continue;
155
+ const filePath = path.join(uploadRoot, rel);
156
+ if (!fs.existsSync(filePath))
157
+ continue;
158
+ try {
159
+ const imgData = fs.readFileSync(filePath).toString("base64");
160
+ const ext = path.extname(filePath).toLowerCase();
161
+ const mime = _MIME_MAP[ext] || "image/jpeg";
162
+ imageUrl.url = `data:${mime};base64,${imgData}`;
163
+ }
164
+ catch (e) {
165
+ logger.warning(`图片 base64 转换失败 ${filePath}: ${e.message}`);
166
+ }
167
+ }
168
+ }
169
+ }
170
+ // ─── 后台任务(不阻塞接口响应) ───
171
+ async function embedChunkBackground(kbId, chunkId) {
172
+ try {
173
+ const service = new CSService();
174
+ const chunk = await service.repo.findChunkById(chunkId);
175
+ if (!chunk || chunk.deleted_at)
176
+ return;
177
+ await service._embedAndStore(kbId, chunk);
178
+ }
179
+ catch (e) {
180
+ logger.error(`后台向量化失败 chunk_id=${chunkId}: ${e.message}`);
181
+ }
182
+ }
183
+ async function generateSummaryBackground(sessionPk) {
184
+ try {
185
+ const service = new CSService();
186
+ const session = await service.repo.findSessionByPk(sessionPk);
187
+ if (!session)
188
+ return;
189
+ await service.generateSessionSummary(session);
190
+ }
191
+ catch (e) {
192
+ logger.error(`后台生成会话摘要失败 session_pk=${sessionPk}: ${e.message}`);
193
+ }
194
+ }
195
+ async function streamSseLines(body) {
196
+ const decoder = new TextDecoder();
197
+ let buf = "";
198
+ const lines = [];
199
+ const reader = body.getReader();
200
+ while (true) {
201
+ const { done, value } = await reader.read();
202
+ if (done)
203
+ break;
204
+ buf += decoder.decode(value, { stream: true });
205
+ let idx;
206
+ while ((idx = buf.indexOf("\n")) >= 0) {
207
+ lines.push(buf.slice(0, idx).replace(/\r$/, ""));
208
+ buf = buf.slice(idx + 1);
209
+ }
210
+ }
211
+ buf += decoder.decode();
212
+ if (buf)
213
+ lines.push(buf);
214
+ return lines;
215
+ }
216
+ // ─── DTO 映射 ───
217
+ function toConfigDto(c) {
218
+ return mapTimestamp({
219
+ id: c.id,
220
+ app_id: c.app_id,
221
+ app_name: c.app_name,
222
+ welcome_message: c.welcome_message ?? null,
223
+ system_prompt: c.system_prompt ?? null,
224
+ provider: c.provider ?? "deepseek",
225
+ model: c.model ?? "deepseek-v4-flash",
226
+ vision_model: c.vision_model ?? null,
227
+ embedding_provider: c.embedding_provider ?? "aliyun",
228
+ embedding_model: c.embedding_model ?? "text-embedding-v3",
229
+ business_hours: fromJson(c.business_hours),
230
+ agent_mode: c.agent_mode ?? null,
231
+ agent_ids: fromJson(c.agent_ids),
232
+ is_active: c.is_active ?? 1,
233
+ created_at: c.created_at ?? null,
234
+ updated_at: c.updated_at ?? null,
235
+ }, ["created_at", "updated_at"]);
236
+ }
237
+ function toKbDto(kb) {
238
+ return mapTimestamp({
239
+ id: kb.id,
240
+ name: kb.name,
241
+ description: kb.description ?? null,
242
+ status: kb.status ?? 1,
243
+ chunk_count: kb.chunk_count ?? 0,
244
+ created_at: kb.created_at ?? null,
245
+ updated_at: kb.updated_at ?? null,
246
+ }, ["created_at", "updated_at"]);
247
+ }
248
+ function toChunkDto(c) {
249
+ return mapTimestamp({
250
+ id: c.id,
251
+ kb_id: c.kb_id,
252
+ title: c.title ?? null,
253
+ content: c.content,
254
+ source_type: c.source_type ?? "manual",
255
+ source_file: c.source_file ?? null,
256
+ chunk_index: c.chunk_index ?? 0,
257
+ embedding_model: c.embedding_model ?? null,
258
+ embedding_status: c.embedding_status ?? 0,
259
+ created_at: c.created_at ?? null,
260
+ }, ["created_at"]);
261
+ }
262
+ function toSessionDto(s) {
263
+ return mapTimestamp({
264
+ id: s.id,
265
+ session_id: s.session_id,
266
+ app_id: s.app_id ?? null,
267
+ app_name: null,
268
+ visitor_id: s.visitor_id ?? null,
269
+ visitor_name: s.visitor_name ?? null,
270
+ visitor_avatar: s.visitor_avatar ?? null,
271
+ source: s.source ?? "h5",
272
+ status: s.status ?? 0,
273
+ agent_id: s.agent_id ?? null,
274
+ agent_name: null,
275
+ message_count: s.message_count ?? 0,
276
+ summary: s.summary ?? null,
277
+ emotion: s.emotion ?? null,
278
+ rating: s.rating ?? null,
279
+ created_at: s.created_at ?? null,
280
+ updated_at: s.updated_at ?? null,
281
+ }, ["created_at", "updated_at"]);
282
+ }
283
+ function toAgentDto(a) {
284
+ return mapTimestamp({
285
+ id: a.id,
286
+ employee_id: a.employee_id,
287
+ display_name: a.display_name ?? null,
288
+ avatar: a.avatar ?? null,
289
+ agent_key: a.agent_key ?? null,
290
+ enabled: a.enabled ?? 1,
291
+ status: a.status ?? "offline",
292
+ last_active_at: a.last_active_at ?? null,
293
+ created_at: a.created_at ?? null,
294
+ }, ["last_active_at", "created_at"]);
295
+ }
296
+ function toMessageDto(m) {
297
+ let displayContent = null;
298
+ let imageUrl = null;
299
+ const content = m.content ?? "";
300
+ if (m.content_type === "mixed") {
301
+ try {
302
+ const data = JSON.parse(content);
303
+ const parts = [];
304
+ if (data.text)
305
+ parts.push(data.text);
306
+ if (data.image_url) {
307
+ parts.push("[图片]");
308
+ imageUrl = data.image_url;
309
+ }
310
+ displayContent = parts.length ? parts.join(" ") : content;
311
+ }
312
+ catch {
313
+ displayContent = content;
314
+ }
315
+ }
316
+ else if (m.content_type === "image") {
317
+ imageUrl = content;
318
+ displayContent = "[图片]";
319
+ }
320
+ else {
321
+ displayContent = content;
322
+ }
323
+ return mapTimestamp({
324
+ id: m.id,
325
+ session_id: m.session_id,
326
+ role: m.role,
327
+ content,
328
+ content_type: m.content_type ?? "text",
329
+ knowledge_refs: fromJson(m.knowledge_refs),
330
+ model: m.model ?? null,
331
+ tokens: m.tokens ?? 0,
332
+ response_time: m.response_time ?? 0,
333
+ created_at: m.created_at ?? null,
334
+ display_content: displayContent,
335
+ image_url: imageUrl,
336
+ }, ["created_at"]);
337
+ }
338
+ export class CSService {
339
+ repo = new CSRepository();
340
+ // ─── 配置管理 ───
341
+ static _generateAppId() {
342
+ return "cs_" + tokenHex(12);
343
+ }
344
+ async listConfigs(page, size, keyword) {
345
+ const { items, total } = await this.repo.listConfigs(page, size, keyword);
346
+ return { items: items.map(toConfigDto), total };
347
+ }
348
+ async createConfig(data, creatorId) {
349
+ const appId = CSService._generateAppId();
350
+ const config = await this.repo.createConfig({
351
+ app_id: appId,
352
+ app_name: data.app_name,
353
+ welcome_message: data.welcome_message || "您好,有什么可以帮您的吗?",
354
+ system_prompt: data.system_prompt || DEFAULT_SYSTEM_PROMPT,
355
+ provider: data.provider || "deepseek",
356
+ model: data.model || "deepseek-v4-flash",
357
+ vision_model: data.vision_model ?? null,
358
+ embedding_provider: data.embedding_provider || "aliyun",
359
+ embedding_model: data.embedding_model || "text-embedding-v3",
360
+ business_hours: toJson(data.business_hours ?? null),
361
+ agent_mode: data.agent_mode || "pool",
362
+ agent_ids: toJson(data.agent_ids ?? null),
363
+ is_active: data.is_active ?? 1,
364
+ creator_id: creatorId ?? null,
365
+ });
366
+ return toConfigDto(config);
367
+ }
368
+ async updateConfig(configId, data) {
369
+ const config = await this.repo.findConfigById(configId);
370
+ if (!config)
371
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "客服配置不存在", 404);
372
+ const updateData = {};
373
+ const textFields = [
374
+ "app_name",
375
+ "welcome_message",
376
+ "system_prompt",
377
+ "provider",
378
+ "model",
379
+ "vision_model",
380
+ "embedding_provider",
381
+ "embedding_model",
382
+ "agent_mode",
383
+ ];
384
+ for (const f of textFields) {
385
+ const v = data[f];
386
+ if (v !== undefined && v !== null)
387
+ updateData[f] = v;
388
+ }
389
+ if (data.business_hours !== undefined && data.business_hours !== null) {
390
+ updateData.business_hours = toJson(data.business_hours);
391
+ }
392
+ if (data.agent_ids !== undefined && data.agent_ids !== null) {
393
+ updateData.agent_ids = toJson(data.agent_ids);
394
+ }
395
+ if (data.is_active !== undefined && data.is_active !== null) {
396
+ updateData.is_active = data.is_active;
397
+ }
398
+ const updated = await this.repo.updateConfig(configId, updateData);
399
+ return toConfigDto(updated);
400
+ }
401
+ async deleteConfig(configId) {
402
+ const config = await this.repo.findConfigById(configId);
403
+ if (!config)
404
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "客服配置不存在", 404);
405
+ await knex(ModelRegistry.get("CSConfig"))
406
+ .where("id", configId)
407
+ .update({ deleted_at: new Date(), updated_at: new Date() });
408
+ }
409
+ // ─── 配置-知识库关联 ───
410
+ async listConfigKbs(configId) {
411
+ const config = await this.repo.findConfigById(configId);
412
+ if (!config)
413
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "客服配置不存在", 404);
414
+ const kbs = await this.repo.listConfigKbs(configId);
415
+ return kbs.map(toKbDto);
416
+ }
417
+ async bindConfigKbs(configId, kbIds) {
418
+ const config = await this.repo.findConfigById(configId);
419
+ if (!config)
420
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "客服配置不存在", 404);
421
+ const validIds = [];
422
+ for (const kbId of [...new Set(kbIds)]) {
423
+ const kb = await this.repo.findKbById(kbId);
424
+ if (kb)
425
+ validIds.push(kbId);
426
+ }
427
+ await this.repo.replaceConfigKbs(configId, validIds);
428
+ return validIds;
429
+ }
430
+ // ─── 知识库管理 ───
431
+ async listKbs(page, size, keyword) {
432
+ const { items, total } = await this.repo.listKbs(page, size, keyword);
433
+ return { items: items.map(toKbDto), total };
434
+ }
435
+ async createKb(data, creatorId) {
436
+ const kb = await this.repo.createKb({
437
+ name: data.name,
438
+ description: data.description ?? null,
439
+ creator_id: creatorId ?? null,
440
+ });
441
+ return toKbDto(kb);
442
+ }
443
+ async updateKb(kbId, data) {
444
+ const kb = await this.repo.findKbById(kbId);
445
+ if (!kb)
446
+ throw new AppException(ErrorCode.CS_KB_NOT_FOUND, "知识库不存在", 404);
447
+ const updateData = {};
448
+ for (const f of ["name", "description", "status"]) {
449
+ const v = data[f];
450
+ if (v !== undefined && v !== null)
451
+ updateData[f] = v;
452
+ }
453
+ const updated = await this.repo.updateKb(kbId, updateData);
454
+ return toKbDto(updated);
455
+ }
456
+ async deleteKb(kbId) {
457
+ const kb = await this.repo.findKbById(kbId);
458
+ if (!kb)
459
+ throw new AppException(ErrorCode.CS_KB_NOT_FOUND, "知识库不存在", 404);
460
+ await this.repo.softDeleteKb(kbId);
461
+ try {
462
+ await getRedisStore().delete(csVectorKey(kbId));
463
+ }
464
+ catch {
465
+ /* ignore */
466
+ }
467
+ }
468
+ // ─── 文档导入 ───
469
+ async importDocument(kbId, filename, content) {
470
+ const kb = await this.repo.findKbById(kbId);
471
+ if (!kb)
472
+ throw new AppException(ErrorCode.CS_KB_NOT_FOUND, "知识库不存在", 404);
473
+ const ext = path.extname(filename).toLowerCase();
474
+ if (!SUPPORTED_EXTS.includes(ext)) {
475
+ throw new AppException(ErrorCode.PARAM_ERROR, `仅支持 ${SUPPORTED_EXTS.join("/")} 格式`);
476
+ }
477
+ // 1. 保存原文件(便于追溯)
478
+ const docDir = path.join(uploadRoot, "cs_docs");
479
+ fs.mkdirSync(docDir, { recursive: true });
480
+ const safeName = crypto.randomUUID().replace(/-/g, "") + ext;
481
+ const filepath = path.join(docDir, safeName);
482
+ fs.writeFileSync(filepath, content);
483
+ // 2. 解析文本
484
+ let text;
485
+ try {
486
+ text = parseDocument(filename, filepath);
487
+ }
488
+ catch (e) {
489
+ throw new AppException(ErrorCode.PARAM_ERROR, e.message);
490
+ }
491
+ if (!text.trim())
492
+ throw new AppException(ErrorCode.PARAM_ERROR, "文档内容为空,无法导入");
493
+ // 3. 切块
494
+ const chunks = splitText(text);
495
+ if (!chunks.length)
496
+ throw new AppException(ErrorCode.PARAM_ERROR, "文档未切分出有效内容");
497
+ // 4. 批量建块(source_type=file)
498
+ const existing = await this.repo.listChunks(kbId, 1, 1);
499
+ const startIndex = existing.total > 0 ? existing.total : 0;
500
+ const chunkObjs = chunks.map((c, i) => ({
501
+ kb_id: kbId,
502
+ title: `${filename} · 第${i + 1}段`,
503
+ content: c,
504
+ source_type: "file",
505
+ source_file: filename,
506
+ chunk_index: startIndex + i,
507
+ embedding_status: 0,
508
+ }));
509
+ const created = await this.repo.batchCreateChunks(chunkObjs);
510
+ // 5. 后台向量化(不阻塞接口)
511
+ for (const chunk of created) {
512
+ void embedChunkBackground(kbId, chunk.id);
513
+ }
514
+ await this.repo.updateKbChunkCount(kbId);
515
+ logger.info(`文档导入成功 kb_id=${kbId} file=${filename} chunks=${chunks.length}`);
516
+ return { total: chunks.length, filename };
517
+ }
518
+ // ─── 人工坐席 ───
519
+ async listAgents(page, size, keyword) {
520
+ const { items, total } = await this.repo.listAgents(page, size, keyword);
521
+ const employeeIds = items.map((a) => a.employee_id);
522
+ const nameMap = await this._batchEmployeeNames(employeeIds);
523
+ const result = items.map((a) => {
524
+ const dto = toAgentDto(a);
525
+ dto.display_name = (a.display_name ||
526
+ nameMap.get(a.employee_id) ||
527
+ `坐席${a.id}`);
528
+ return dto;
529
+ });
530
+ return { items: result, total };
531
+ }
532
+ async createAgent(data) {
533
+ const employeeId = data.employee_id;
534
+ const existing = await this.repo.findAgentByEmployeeIdAny(employeeId);
535
+ if (existing)
536
+ throw new AppException(ErrorCode.PARAM_ERROR, "该员工已绑定坐席");
537
+ const agentKey = String(data.agent_key ?? "").trim() || String(employeeId);
538
+ const dup = await this.repo.findAgentByAgentKeyAny(agentKey);
539
+ if (dup)
540
+ throw new AppException(ErrorCode.PARAM_ERROR, `接入标识 ${agentKey} 已被使用`);
541
+ const nameMap = await this._batchEmployeeNames([employeeId]);
542
+ const displayName = data.display_name ||
543
+ nameMap.get(employeeId) ||
544
+ `坐席${employeeId}`;
545
+ const agent = await this.repo.createAgent({
546
+ employee_id: employeeId,
547
+ display_name: displayName,
548
+ avatar: data.avatar ?? null,
549
+ agent_key: agentKey,
550
+ });
551
+ return toAgentDto(agent);
552
+ }
553
+ async updateAgent(agentId, data) {
554
+ const agent = await this.repo.findAgentById(agentId);
555
+ if (!agent)
556
+ throw new AppException(ErrorCode.PARAM_ERROR, "坐席不存在", 404);
557
+ const updateData = {};
558
+ for (const f of ["display_name", "avatar", "agent_key"]) {
559
+ const v = data[f];
560
+ if (v !== undefined && v !== null)
561
+ updateData[f] = v;
562
+ }
563
+ if (updateData.agent_key) {
564
+ const dup = await this.repo.findAgentByAgentKeyAny(String(updateData.agent_key));
565
+ if (dup && dup.id !== agentId) {
566
+ throw new AppException(ErrorCode.PARAM_ERROR, `接入标识 ${updateData.agent_key} 已被使用`);
567
+ }
568
+ }
569
+ const updated = await this.repo.updateAgent(agentId, updateData);
570
+ return toAgentDto(updated);
571
+ }
572
+ async deleteAgent(agentId) {
573
+ const agent = await this.repo.findAgentById(agentId);
574
+ if (!agent)
575
+ throw new AppException(ErrorCode.PARAM_ERROR, "坐席不存在", 404);
576
+ // 物理删除:唯一索引(employee_id/agent_key)需随之释放
577
+ await this.repo.deleteAgent(agentId);
578
+ }
579
+ async setAgentEnabled(agentId, enabled) {
580
+ const agent = await this.repo.findAgentById(agentId);
581
+ if (!agent)
582
+ throw new AppException(ErrorCode.PARAM_ERROR, "坐席不存在", 404);
583
+ const updated = await this.repo.updateAgent(agentId, {
584
+ enabled: enabled ? 1 : 0,
585
+ });
586
+ return toAgentDto(updated);
587
+ }
588
+ async agentSetOnline(agentId, online) {
589
+ const store = getRedisStore();
590
+ if (online) {
591
+ await store.setJson(csAgentOnlineKey(agentId), { at: Math.floor(Date.now() / 1000) }, 45);
592
+ await this.repo.setAgentOnlineStatus(agentId, "online", new Date());
593
+ try {
594
+ await this._assignWaitingSessions(agentId);
595
+ }
596
+ catch (e) {
597
+ logger.error(`坐席上线自动接管失败 agent_id=${agentId}: ${e.message}`);
598
+ }
599
+ }
600
+ else {
601
+ await store.delete(csAgentOnlineKey(agentId));
602
+ await this.repo.setAgentOnlineStatus(agentId, "offline");
603
+ }
604
+ }
605
+ async agentPing(agentId) {
606
+ await getRedisStore().setJson(csAgentOnlineKey(agentId), { at: Math.floor(Date.now() / 1000) }, 45);
607
+ await this.repo.setAgentOnlineStatus(agentId, "online", new Date());
608
+ }
609
+ async requireAgentByEmployee(employeeId) {
610
+ const agent = await this.repo.findAgentByEmployeeId(employeeId);
611
+ if (!agent)
612
+ throw new AppException(ErrorCode.PARAM_ERROR, "当前账号未绑定坐席,请联系管理员", 403);
613
+ return agent;
614
+ }
615
+ async _assignWaitingSessions(agentId, maxCount = 5) {
616
+ const agent = await this.repo.findAgentById(agentId);
617
+ if (!agent)
618
+ return;
619
+ const { items } = await this.repo.listWaitingSessions(1, maxCount);
620
+ for (const session of items) {
621
+ await this.repo.updateSession(session.id, {
622
+ agent_id: agentId,
623
+ last_agent_active_at: new Date(),
624
+ });
625
+ const history = await this.repo.listMessages(session.id, 20);
626
+ await wsManager.sendToAgent(agentId, {
627
+ type: "session_assigned",
628
+ session_id: session.session_id,
629
+ visitor_name: session.visitor_name,
630
+ app_id: session.app_id,
631
+ history: history.map((m) => ({
632
+ role: m.role,
633
+ content: m.content,
634
+ content_type: m.content_type,
635
+ created_at: m.created_at
636
+ ? new Date(m.created_at)
637
+ .toISOString()
638
+ .slice(0, 19)
639
+ .replace("T", " ")
640
+ : null,
641
+ })),
642
+ });
643
+ await wsManager.sendToUser(session.session_id, {
644
+ type: "agent_online",
645
+ agent_id: agent.id,
646
+ agent_name: agent.display_name,
647
+ agent_avatar: agent.avatar,
648
+ });
649
+ }
650
+ }
651
+ async _notifyAgentsNewSession(session) {
652
+ try {
653
+ const { items } = await this.repo.listAgents(1, 200);
654
+ for (const a of items) {
655
+ if (!(await this._agentIsOnline(a)))
656
+ continue;
657
+ await wsManager.sendToAgent(a.id, {
658
+ type: "new_session",
659
+ session_id: session.session_id,
660
+ visitor_name: session.visitor_name || "匿名访客",
661
+ });
662
+ }
663
+ }
664
+ catch (e) {
665
+ logger.warning(`通知坐席新会话失败: ${e.message}`);
666
+ }
667
+ }
668
+ async _agentIsOnline(agent) {
669
+ if (agent.enabled !== 1)
670
+ return false;
671
+ if (agent.status !== "online")
672
+ return false;
673
+ const store = getRedisStore();
674
+ try {
675
+ return (await store.getJson(csAgentOnlineKey(agent.id))) !== null;
676
+ }
677
+ catch {
678
+ return true; // Redis 不可用时信任 DB 状态
679
+ }
680
+ }
681
+ async _pickAgent(csConfig, agentKey) {
682
+ if (agentKey) {
683
+ const agent = await this.repo.findAgentByAgentKey(agentKey);
684
+ if (agent)
685
+ return (await this._agentIsOnline(agent)) ? agent : null;
686
+ logger.warning(`接入标识 ${agentKey} 未配置,降级为坐席池分配`);
687
+ }
688
+ let candidates = [];
689
+ if (csConfig.agent_mode === "specified" && csConfig.agent_ids) {
690
+ const ids = Array.isArray(csConfig.agent_ids)
691
+ ? csConfig.agent_ids
692
+ : fromJson(csConfig.agent_ids) || [];
693
+ for (const a of await this.repo.listAgentsByIds(ids)) {
694
+ if (await this._agentIsOnline(a))
695
+ candidates.push(a);
696
+ }
697
+ }
698
+ else {
699
+ const { items } = await this.repo.listAgents(1, 200);
700
+ for (const a of items) {
701
+ if (await this._agentIsOnline(a))
702
+ candidates.push(a);
703
+ }
704
+ }
705
+ if (!candidates.length)
706
+ return null;
707
+ let best = null;
708
+ let bestLoad = -1;
709
+ for (const a of candidates) {
710
+ const load = await this.repo.countActiveSessionsByAgent(a.id);
711
+ if (best === null || load < bestLoad) {
712
+ best = a;
713
+ bestLoad = load;
714
+ }
715
+ }
716
+ return best;
717
+ }
718
+ async requestTransfer(appId, sessionId, agentKey, visitorName) {
719
+ const csConfig = await this.repo.findConfigByAppId(appId);
720
+ if (!csConfig)
721
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "无效的应用ID", 404);
722
+ if (csConfig.is_active !== 1)
723
+ throw new AppException(ErrorCode.CS_CONFIG_INACTIVE, "客服服务未启用", 403);
724
+ let session;
725
+ if (sessionId) {
726
+ session = await this.repo.findSessionBySessionId(sessionId);
727
+ if (!session)
728
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
729
+ }
730
+ else {
731
+ sessionId = "sess_" + tokenHex(16);
732
+ session = await this.repo.createSession({
733
+ session_id: sessionId,
734
+ app_id: appId,
735
+ visitor_id: visitorName || sessionId,
736
+ visitor_name: visitorName ?? null,
737
+ source: "h5",
738
+ status: 0,
739
+ });
740
+ }
741
+ if (session.status === 2)
742
+ throw new AppException(ErrorCode.PARAM_ERROR, "会话已结束", 400);
743
+ const agent = await this._pickAgent(csConfig, agentKey);
744
+ if (!agent) {
745
+ await this.repo.updateSession(session.id, { status: 1 });
746
+ return {
747
+ session_id: session.session_id,
748
+ status: 1,
749
+ agent_id: null,
750
+ agent_name: null,
751
+ agent_avatar: null,
752
+ message: "已进入人工排队,坐席上线后将尽快为您服务",
753
+ };
754
+ }
755
+ await this.repo.updateSession(session.id, {
756
+ status: 1,
757
+ agent_id: agent.id,
758
+ last_agent_active_at: new Date(),
759
+ });
760
+ const notice = `已为您接入人工坐席 ${agent.display_name || "客服"},请描述您的问题`;
761
+ await this.repo.createMessage({
762
+ session_id: session.id,
763
+ role: "system",
764
+ content: notice,
765
+ content_type: "text",
766
+ });
767
+ const history = await this.repo.listMessages(session.id, 20);
768
+ await wsManager.sendToAgent(agent.id, {
769
+ type: "session_assigned",
770
+ session_id: session.session_id,
771
+ visitor_name: session.visitor_name,
772
+ app_id: session.app_id,
773
+ history: history.map((m) => ({
774
+ role: m.role,
775
+ content: m.content,
776
+ content_type: m.content_type,
777
+ created_at: m.created_at
778
+ ? new Date(m.created_at).toISOString().slice(0, 19).replace("T", " ")
779
+ : null,
780
+ })),
781
+ });
782
+ await wsManager.sendToUser(session.session_id, {
783
+ type: "agent_online",
784
+ agent_id: agent.id,
785
+ agent_name: agent.display_name,
786
+ agent_avatar: agent.avatar,
787
+ });
788
+ try {
789
+ void generateSummaryBackground(session.id);
790
+ }
791
+ catch {
792
+ /* ignore */
793
+ }
794
+ return {
795
+ session_id: session.session_id,
796
+ status: 1,
797
+ agent_id: agent.id,
798
+ agent_name: agent.display_name ?? null,
799
+ agent_avatar: agent.avatar ?? null,
800
+ message: notice,
801
+ };
802
+ }
803
+ async agentSendReply(agentId, sessionId, content) {
804
+ const session = await this.repo.findSessionBySessionId(sessionId);
805
+ if (!session)
806
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
807
+ if (session.status !== 1)
808
+ throw new AppException(ErrorCode.PARAM_ERROR, "会话不在人工服务状态", 400);
809
+ if (session.agent_id !== agentId)
810
+ throw new AppException(ErrorCode.PARAM_ERROR, "该会话不属于当前坐席", 403);
811
+ const msg = await this.repo.createMessage({
812
+ session_id: session.id,
813
+ role: "agent",
814
+ content,
815
+ content_type: "text",
816
+ });
817
+ await this.repo.incrementSessionMessageCount(session.id);
818
+ await this.repo.updateSession(session.id, {
819
+ last_agent_active_at: new Date(),
820
+ });
821
+ const agent = await this.repo.findAgentById(agentId);
822
+ await wsManager.sendToUser(session.session_id, {
823
+ type: "agent_message",
824
+ content,
825
+ agent_name: agent?.display_name || "客服",
826
+ created_at: msg.created_at
827
+ ? new Date(msg.created_at).toISOString().slice(0, 19).replace("T", " ")
828
+ : null,
829
+ });
830
+ return toMessageDto(msg);
831
+ }
832
+ async agentTakeover(agentId, sessionId) {
833
+ const session = await this.repo.findSessionBySessionId(sessionId);
834
+ if (!session)
835
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
836
+ if (session.status === 2)
837
+ throw new AppException(ErrorCode.PARAM_ERROR, "会话已结束", 400);
838
+ await this.repo.updateSession(session.id, {
839
+ status: 1,
840
+ agent_id: agentId,
841
+ last_agent_active_at: new Date(),
842
+ });
843
+ await wsManager.sendToUser(session.session_id, {
844
+ type: "agent_online",
845
+ agent_name: `坐席${agentId}`,
846
+ });
847
+ }
848
+ async agentClose(agentId, sessionId, summary) {
849
+ const session = await this.repo.findSessionBySessionId(sessionId);
850
+ if (!session)
851
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
852
+ if (session.agent_id !== agentId)
853
+ throw new AppException(ErrorCode.PARAM_ERROR, "该会话不属于当前坐席", 403);
854
+ await this.repo.updateSession(session.id, {
855
+ status: 2,
856
+ summary: summary || session.summary || null,
857
+ last_agent_active_at: new Date(),
858
+ });
859
+ if (!summary && !session.summary) {
860
+ try {
861
+ void generateSummaryBackground(session.id);
862
+ }
863
+ catch {
864
+ /* ignore */
865
+ }
866
+ }
867
+ await wsManager.sendToUser(session.session_id, {
868
+ type: "session_closed",
869
+ content: "本次人工服务已结束,感谢您的咨询",
870
+ });
871
+ }
872
+ async listAgentSessions(tab, page, size, agentEmployeeId) {
873
+ let agentPk = null;
874
+ if (agentEmployeeId !== undefined && agentEmployeeId !== null) {
875
+ const agent = await this.repo.findAgentByEmployeeId(agentEmployeeId);
876
+ if (!agent)
877
+ throw new AppException(ErrorCode.PARAM_ERROR, "当前账号未绑定坐席", 403);
878
+ agentPk = agent.id;
879
+ }
880
+ let items;
881
+ let total;
882
+ if (tab === "waiting") {
883
+ ({ items, total } = await this.repo.listWaitingSessions(page, size));
884
+ }
885
+ else if (tab === "active") {
886
+ ({ items, total } = await this.repo.listSessionsByStatus(1, page, size, agentPk));
887
+ }
888
+ else if (tab === "closed") {
889
+ ({ items, total } = await this.repo.listSessionsByStatus(2, page, size, agentPk));
890
+ }
891
+ else {
892
+ throw new AppException(ErrorCode.PARAM_ERROR, "无效的会话类型", 400);
893
+ }
894
+ const result = await this._resolveSessionAgentNames(items);
895
+ return { items: result, total };
896
+ }
897
+ async _resolveSessionAgentNames(sessions) {
898
+ const agentIds = [
899
+ ...new Set(sessions.filter((s) => s.agent_id).map((s) => s.agent_id)),
900
+ ];
901
+ const agentMap = new Map();
902
+ if (agentIds.length) {
903
+ const agents = await this.repo.listAgentsByIds(agentIds);
904
+ for (const a of agents)
905
+ agentMap.set(a.id, a.display_name || `坐席${a.id}`);
906
+ }
907
+ return sessions.map((s) => {
908
+ const dto = toSessionDto(s);
909
+ dto.agent_name = s.agent_id ? (agentMap.get(s.agent_id) ?? null) : null;
910
+ return dto;
911
+ });
912
+ }
913
+ async _batchEmployeeNames(employeeIds) {
914
+ const ids = employeeIds.filter(Boolean);
915
+ const result = new Map();
916
+ if (!ids.length)
917
+ return result;
918
+ try {
919
+ const table = ModelRegistry.get("Employee");
920
+ const rows = (await knex(table)
921
+ .whereIn("id", ids)
922
+ .select("id", "nickname", "real_name"));
923
+ for (const r of rows) {
924
+ result.set(r.id, r.real_name || r.nickname || String(r.id));
925
+ }
926
+ }
927
+ catch {
928
+ /* ignore */
929
+ }
930
+ return result;
931
+ }
932
+ // ─── 知识块管理 + 向量化 ───
933
+ async listChunks(kbId, page, size) {
934
+ const { items, total } = await this.repo.listChunks(kbId, page, size);
935
+ return { items: items.map(toChunkDto), total };
936
+ }
937
+ async addChunk(kbId, data) {
938
+ const kb = await this.repo.findKbById(kbId);
939
+ if (!kb)
940
+ throw new AppException(ErrorCode.CS_KB_NOT_FOUND, "知识库不存在", 404);
941
+ const existing = await this.repo.listChunks(kbId, 1, 1);
942
+ const chunkIndex = existing.total > 0 ? existing.total : 0;
943
+ const chunk = await this.repo.createChunk({
944
+ kb_id: kbId,
945
+ title: data.title ?? null,
946
+ content: data.content,
947
+ source_type: "manual",
948
+ chunk_index: chunkIndex,
949
+ });
950
+ void embedChunkBackground(kbId, chunk.id);
951
+ await this.repo.updateKbChunkCount(kbId);
952
+ return toChunkDto(chunk);
953
+ }
954
+ async updateChunk(chunkId, data) {
955
+ const chunk = await this.repo.findChunkById(chunkId);
956
+ if (!chunk)
957
+ throw new AppException(ErrorCode.CS_CHUNK_NOT_FOUND, "知识块不存在", 404);
958
+ const updateData = {};
959
+ for (const f of ["title", "content"]) {
960
+ const v = data[f];
961
+ if (v !== undefined && v !== null)
962
+ updateData[f] = v;
963
+ }
964
+ const updated = await this.repo.updateChunk(chunkId, updateData);
965
+ void embedChunkBackground(updated.kb_id, updated.id);
966
+ return toChunkDto(updated);
967
+ }
968
+ async deleteChunk(chunkId) {
969
+ // 幂等:允许重复删除,已软删的资源直接返回成功
970
+ const chunk = await this.repo.findChunkByIdIncludeDeleted(chunkId);
971
+ if (!chunk)
972
+ throw new AppException(ErrorCode.CS_CHUNK_NOT_FOUND, "知识块不存在", 404);
973
+ if (chunk.deleted_at)
974
+ return;
975
+ const kbId = chunk.kb_id;
976
+ await this.repo.softDeleteChunk(chunkId);
977
+ await this.repo.updateKbChunkCount(kbId);
978
+ // 重建向量缓存(失败不影响删除结果)
979
+ try {
980
+ await this._rebuildVectorCache(kbId);
981
+ }
982
+ catch (e) {
983
+ logger.error(`重建向量缓存失败 kb_id=${kbId}: ${e.message}`);
984
+ }
985
+ }
986
+ async rebuildIndex(kbId) {
987
+ const kb = await this.repo.findKbById(kbId);
988
+ if (!kb)
989
+ throw new AppException(ErrorCode.CS_KB_NOT_FOUND, "知识库不存在", 404);
990
+ const chunks = await this.repo.listAllChunks(kbId);
991
+ let successCount = 0;
992
+ for (const chunk of chunks) {
993
+ try {
994
+ await this._embedAndStore(kbId, chunk);
995
+ successCount += 1;
996
+ }
997
+ catch (e) {
998
+ logger.error(`向量化失败 chunk_id=${chunk.id}: ${e.message}`);
999
+ await this.repo.updateChunk(chunk.id, { embedding_status: 2 });
1000
+ }
1001
+ }
1002
+ return { total: chunks.length, success: successCount };
1003
+ }
1004
+ async _getEmbeddingConfig(csConfig) {
1005
+ const providerConfig = await getProviderConfig(csConfig.embedding_provider || "aliyun");
1006
+ if (!providerConfig || !providerConfig.api_key) {
1007
+ throw new AppException(ErrorCode.CS_EMBEDDING_FAILED, "Embedding 服务未配置");
1008
+ }
1009
+ const baseUrls = {
1010
+ aliyun: "https://dashscope.aliyuncs.com/compatible-mode/v1",
1011
+ deepseek: "https://api.deepseek.com/v1",
1012
+ zhipu: "https://open.bigmodel.cn/api/paas/v4",
1013
+ volcano: "https://ark.cn-beijing.volces.com/api/v3",
1014
+ };
1015
+ const baseUrl = baseUrls[csConfig.embedding_provider || ""] || providerConfig.base_url;
1016
+ return [
1017
+ providerConfig.api_key,
1018
+ baseUrl,
1019
+ csConfig.embedding_model || "text-embedding-v3",
1020
+ ];
1021
+ }
1022
+ async _embedText(text, csConfig) {
1023
+ const [apiKey, baseUrl, model] = await this._getEmbeddingConfig(csConfig);
1024
+ const url = `${baseUrl}/embeddings`;
1025
+ const headers = {
1026
+ Authorization: `Bearer ${apiKey}`,
1027
+ "Content-Type": "application/json",
1028
+ };
1029
+ const payload = { model, input: text };
1030
+ const resp = await fetch(url, {
1031
+ method: "POST",
1032
+ headers,
1033
+ body: JSON.stringify(payload),
1034
+ signal: AbortSignal.timeout(10_000),
1035
+ });
1036
+ if (resp.status !== 200) {
1037
+ const body = await resp.text();
1038
+ logger.error(`Embedding API 失败: ${resp.status} ${body.slice(0, 300)}`);
1039
+ throw new AppException(ErrorCode.CS_EMBEDDING_FAILED, `向量化失败: ${body.slice(0, 200)}`);
1040
+ }
1041
+ const result = (await resp.json());
1042
+ return result.data[0].embedding;
1043
+ }
1044
+ async _embedAndStore(kbId, chunk) {
1045
+ const config = await this._getFirstConfig();
1046
+ if (!config) {
1047
+ logger.warning("无客服配置,跳过向量化");
1048
+ await this.repo.updateChunk(chunk.id, { embedding_status: 2 });
1049
+ return;
1050
+ }
1051
+ const embeddingModel = config.embedding_model;
1052
+ try {
1053
+ const embedding = await this._embedText(chunk.content, config);
1054
+ const vectorKey = csVectorKey(kbId);
1055
+ const redis = getRedisStore();
1056
+ const existingRaw = await redis.getJson(vectorKey);
1057
+ const existing = existingRaw || [];
1058
+ const filtered = existing.filter((item) => item.chunk_id !== chunk.id);
1059
+ filtered.push({
1060
+ chunk_id: chunk.id,
1061
+ title: chunk.title || "",
1062
+ content: chunk.content,
1063
+ embedding,
1064
+ });
1065
+ await redis.setJson(vectorKey, filtered, 0);
1066
+ await this.repo.updateChunk(chunk.id, {
1067
+ embedding_model: embeddingModel,
1068
+ embedding_status: 1,
1069
+ });
1070
+ }
1071
+ catch (e) {
1072
+ await this.repo.updateChunk(chunk.id, { embedding_status: 2 });
1073
+ if (e instanceof AppException)
1074
+ throw e;
1075
+ logger.error(`向量化异常 chunk_id=${chunk.id}: ${e.message}`);
1076
+ }
1077
+ }
1078
+ async _getFirstConfig() {
1079
+ const { items } = await this.repo.listConfigs(1, 1);
1080
+ return items[0] || null;
1081
+ }
1082
+ async _rebuildVectorCache(kbId) {
1083
+ const chunks = await this.repo.listAllChunks(kbId);
1084
+ const vectorKey = csVectorKey(kbId);
1085
+ const redis = getRedisStore();
1086
+ await redis.delete(vectorKey);
1087
+ const config = await this._getFirstConfig();
1088
+ if (!config)
1089
+ return;
1090
+ const vectorData = [];
1091
+ for (const chunk of chunks) {
1092
+ try {
1093
+ const embedding = await this._embedText(chunk.content, config);
1094
+ vectorData.push({
1095
+ chunk_id: chunk.id,
1096
+ title: chunk.title || "",
1097
+ content: chunk.content,
1098
+ embedding,
1099
+ });
1100
+ }
1101
+ catch (e) {
1102
+ logger.error(`重建索引失败 chunk_id=${chunk.id}: ${e.message}`);
1103
+ }
1104
+ }
1105
+ if (vectorData.length)
1106
+ await redis.setJson(vectorKey, vectorData, 0);
1107
+ }
1108
+ // ─── RAG 检索 ───
1109
+ async searchKnowledge(query, kbIds, topK = 3) {
1110
+ const results = [];
1111
+ const config = await this._getFirstConfig();
1112
+ if (!config)
1113
+ return results;
1114
+ const queryEmbedding = await this._embedText(query, config);
1115
+ const redis = getRedisStore();
1116
+ for (const kbId of kbIds) {
1117
+ const stored = await redis.getJson(csVectorKey(kbId));
1118
+ if (!stored)
1119
+ continue;
1120
+ for (const item of stored) {
1121
+ const score = cosineSimilarity(queryEmbedding, item.embedding);
1122
+ results.push({
1123
+ chunk_id: item.chunk_id,
1124
+ title: item.title,
1125
+ content: item.content,
1126
+ score,
1127
+ kb_id: kbId,
1128
+ });
1129
+ }
1130
+ }
1131
+ results.sort((a, b) => b.score - a.score);
1132
+ return results.slice(0, topK);
1133
+ }
1134
+ // ─── 对话编排 ───
1135
+ async _getLlmConfig(csConfig) {
1136
+ const providerConfig = await getProviderConfig(csConfig.provider || "deepseek");
1137
+ if (!providerConfig || !providerConfig.api_key) {
1138
+ throw new AppException(ErrorCode.PARAM_ERROR, `AI 服务未配置,请配置 ${csConfig.provider} 的 API Key`);
1139
+ }
1140
+ return [
1141
+ providerConfig.api_key,
1142
+ providerConfig.base_url,
1143
+ csConfig.model || "deepseek-v4-flash",
1144
+ ];
1145
+ }
1146
+ async *chatStream(appId, sessionId, message, imageUrl, visitorName) {
1147
+ // 1. 验证配置
1148
+ const csConfig = await this.repo.findConfigByAppId(appId);
1149
+ if (!csConfig)
1150
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "无效的应用ID", 404);
1151
+ if (csConfig.is_active !== 1)
1152
+ throw new AppException(ErrorCode.CS_CONFIG_INACTIVE, "客服服务未启用", 403);
1153
+ // 2. 获取或创建会话
1154
+ let session;
1155
+ if (sessionId) {
1156
+ session = await this.repo.findSessionBySessionId(sessionId);
1157
+ if (!session)
1158
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
1159
+ if (session.status === 2) {
1160
+ logger.info(`会话 ${sessionId} 已结束,客户重新咨询,开启新会话`);
1161
+ sessionId = "sess_" + tokenHex(16);
1162
+ session = await this.repo.createSession({
1163
+ session_id: sessionId,
1164
+ app_id: appId,
1165
+ visitor_id: session.visitor_id || session.session_id,
1166
+ visitor_name: visitorName || session.visitor_name || null,
1167
+ source: "h5",
1168
+ status: 0,
1169
+ });
1170
+ await this._notifyAgentsNewSession(session);
1171
+ }
1172
+ }
1173
+ else {
1174
+ sessionId = "sess_" + tokenHex(16);
1175
+ session = await this.repo.createSession({
1176
+ session_id: sessionId,
1177
+ app_id: appId,
1178
+ visitor_id: visitorName || sessionId,
1179
+ visitor_name: visitorName || null,
1180
+ source: "h5",
1181
+ status: 0,
1182
+ });
1183
+ await this._notifyAgentsNewSession(session);
1184
+ }
1185
+ // 3. 保存用户消息
1186
+ const isImageMsg = Boolean(imageUrl);
1187
+ const hasText = Boolean(message);
1188
+ let msgContent;
1189
+ let msgContentType;
1190
+ if (isImageMsg && hasText) {
1191
+ msgContent = JSON.stringify({ text: message, image_url: imageUrl });
1192
+ msgContentType = "mixed";
1193
+ }
1194
+ else {
1195
+ msgContent = (imageUrl || message);
1196
+ msgContentType = isImageMsg ? "image" : "text";
1197
+ }
1198
+ await this.repo.createMessage({
1199
+ session_id: session.id,
1200
+ role: "user",
1201
+ content: msgContent,
1202
+ content_type: msgContentType,
1203
+ });
1204
+ await this.repo.incrementSessionMessageCount(session.id);
1205
+ // 3.5 人工服务模式:已接入坐席的会话直接转发,不调用 LLM
1206
+ if (session.status === 1 && session.agent_id != null) {
1207
+ await this._forwardToAgent(session, msgContent, msgContentType);
1208
+ yield sse({ type: "session", session_id: sessionId, welcome: false });
1209
+ yield sse({ type: "handled_by_agent" });
1210
+ yield sse({ type: "done" });
1211
+ return;
1212
+ }
1213
+ // 3.6 智能转人工判断(已在"待接待"排队时不重复触发)
1214
+ if (message && !(session.status === 1 && session.agent_id == null)) {
1215
+ try {
1216
+ const recent = await this.repo.listMessages(session.id, 10);
1217
+ const [needHuman, reason] = await this._shouldTransfer(csConfig, message, recent);
1218
+ if (needHuman) {
1219
+ const transfer = await this.requestTransfer(appId, session.session_id, undefined, visitorName);
1220
+ yield sse({
1221
+ type: "session",
1222
+ session_id: session.session_id,
1223
+ welcome: false,
1224
+ });
1225
+ yield sse({
1226
+ type: "transfer_required",
1227
+ agent_id: transfer.agent_id,
1228
+ agent_name: transfer.agent_name,
1229
+ message: transfer.message,
1230
+ reason,
1231
+ });
1232
+ yield sse({ type: "done" });
1233
+ return;
1234
+ }
1235
+ }
1236
+ catch (e) {
1237
+ logger.warning(`智能转人工判断异常,继续正常对话: ${e.message}`);
1238
+ }
1239
+ }
1240
+ // 4. RAG 检索知识库
1241
+ let knowledgeRefs = [];
1242
+ let knowledgeContext = "";
1243
+ if (message) {
1244
+ try {
1245
+ const boundKbs = await this.repo.listActiveBoundKbs(csConfig.id);
1246
+ const activeKbIds = boundKbs.map((kb) => kb.id);
1247
+ if (activeKbIds.length) {
1248
+ const results = await this.searchKnowledge(message, activeKbIds, 3);
1249
+ if (results.length) {
1250
+ knowledgeRefs = results.map((r) => r.chunk_id);
1251
+ knowledgeContext = results
1252
+ .map((r, i) => `【参考资料${i + 1}】${r.title}\n${r.content}`)
1253
+ .join("\n\n");
1254
+ }
1255
+ }
1256
+ }
1257
+ catch (e) {
1258
+ logger.warning(`RAG 检索失败,继续无知识库对话: ${e.message}`);
1259
+ }
1260
+ }
1261
+ // 5. 构建消息列表
1262
+ let systemPrompt = csConfig.system_prompt || DEFAULT_SYSTEM_PROMPT;
1263
+ if (knowledgeContext) {
1264
+ systemPrompt += `\n\n以下是从知识库中检索到的相关资料,请基于这些资料回答:\n${knowledgeContext}`;
1265
+ }
1266
+ const messages = [
1267
+ { role: "system", content: systemPrompt },
1268
+ ];
1269
+ const history = await this.repo.listMessages(session.id, 10);
1270
+ for (const msg of history.slice(0, -1)) {
1271
+ if (msg.role === "system")
1272
+ continue;
1273
+ if (msg.content_type === "image" || msg.content_type === "mixed") {
1274
+ appendMultimodalMessage(messages, msg);
1275
+ }
1276
+ else {
1277
+ messages.push({ role: llmRole(msg.role), content: msg.content });
1278
+ }
1279
+ }
1280
+ if (isImageMsg) {
1281
+ const contentParts = [];
1282
+ if (hasText)
1283
+ contentParts.push({ type: "text", text: message });
1284
+ contentParts.push({ type: "image_url", image_url: { url: imageUrl } });
1285
+ messages.push({ role: "user", content: contentParts });
1286
+ }
1287
+ else {
1288
+ messages.push({ role: "user", content: message });
1289
+ }
1290
+ // 6. 判断是否需要多模态模型
1291
+ const useVision = isImageMsg;
1292
+ if (useVision && !csConfig.vision_model) {
1293
+ throw new AppException(ErrorCode.PARAM_ERROR, "客服配置未设置视觉模型,无法处理图片消息");
1294
+ }
1295
+ // 7. 调用 LLM (流式)
1296
+ const [apiKey, baseUrl, baseModel] = await this._getLlmConfig(csConfig);
1297
+ const model = useVision ? csConfig.vision_model : baseModel;
1298
+ resolveLocalImagesInMessages(messages);
1299
+ const url = `${baseUrl}/chat/completions`;
1300
+ const headers = {
1301
+ Authorization: `Bearer ${apiKey}`,
1302
+ "Content-Type": "application/json",
1303
+ };
1304
+ const payload = {
1305
+ model,
1306
+ messages,
1307
+ temperature: 0.7,
1308
+ max_tokens: 4096,
1309
+ stream: true,
1310
+ };
1311
+ const startTime = Date.now();
1312
+ let fullReply = "";
1313
+ let tokenCount = 0;
1314
+ yield sse({ type: "session", session_id: sessionId, welcome: false });
1315
+ try {
1316
+ const resp = await fetch(url, {
1317
+ method: "POST",
1318
+ headers,
1319
+ body: JSON.stringify(payload),
1320
+ signal: AbortSignal.timeout(120_000),
1321
+ });
1322
+ if (resp.status !== 200) {
1323
+ const body = await resp.text();
1324
+ let errorMsg = `AI 服务返回错误 (${resp.status})`;
1325
+ try {
1326
+ const errDetail = JSON.parse(body).error?.message;
1327
+ if (typeof errDetail === "string" && errDetail) {
1328
+ errorMsg = `AI 服务错误: ${errDetail}`;
1329
+ }
1330
+ }
1331
+ catch {
1332
+ /* ignore */
1333
+ }
1334
+ yield sse({ type: "error", content: errorMsg });
1335
+ return;
1336
+ }
1337
+ if (!resp.body) {
1338
+ yield sse({ type: "done" });
1339
+ return;
1340
+ }
1341
+ for (const line of await streamSseLines(resp.body)) {
1342
+ if (!line || !line.startsWith("data: "))
1343
+ continue;
1344
+ const dataStr = line.slice(6);
1345
+ if (dataStr.trim() === "[DONE]")
1346
+ break;
1347
+ try {
1348
+ const chunkData = JSON.parse(dataStr);
1349
+ const content = chunkData.choices?.[0]?.delta?.content ?? "";
1350
+ if (content) {
1351
+ fullReply += content;
1352
+ tokenCount += 1;
1353
+ yield sse({ type: "content", content });
1354
+ }
1355
+ }
1356
+ catch {
1357
+ continue;
1358
+ }
1359
+ }
1360
+ yield sse({ type: "done" });
1361
+ }
1362
+ catch (e) {
1363
+ logger.error("客服对话流式异常", e);
1364
+ yield sse({
1365
+ type: "error",
1366
+ content: `对话失败: ${e.message}`,
1367
+ });
1368
+ }
1369
+ finally {
1370
+ // 保存 AI 回复
1371
+ if (fullReply) {
1372
+ const responseTime = Date.now() - startTime;
1373
+ await this.repo.createMessage({
1374
+ session_id: session.id,
1375
+ role: "assistant",
1376
+ content: fullReply,
1377
+ knowledge_refs: toJson(knowledgeRefs),
1378
+ model,
1379
+ tokens: tokenCount,
1380
+ response_time: responseTime,
1381
+ });
1382
+ await this.repo.incrementSessionMessageCount(session.id);
1383
+ }
1384
+ }
1385
+ }
1386
+ async _forwardToAgent(session, msgContent, contentType) {
1387
+ let agent = null;
1388
+ if (session.agent_id) {
1389
+ agent = await this.repo.findAgentById(session.agent_id);
1390
+ }
1391
+ if (!agent)
1392
+ return;
1393
+ const now = new Date();
1394
+ const pad = (n) => String(n).padStart(2, "0");
1395
+ await wsManager.sendToAgent(agent.id, {
1396
+ type: "user_message",
1397
+ session_id: session.session_id,
1398
+ content: msgContent,
1399
+ content_type: contentType,
1400
+ visitor_name: session.visitor_name,
1401
+ created_at: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`,
1402
+ });
1403
+ }
1404
+ // ─── 二期:AI 辅助 / 摘要 / 评分 / 智能转人工 ───
1405
+ async _callLlmText(csConfig, prompt, maxTokens = 500, temperature = 0.5) {
1406
+ const [apiKey, baseUrl, model] = await this._getLlmConfig(csConfig);
1407
+ const url = `${baseUrl}/chat/completions`;
1408
+ const headers = {
1409
+ Authorization: `Bearer ${apiKey}`,
1410
+ "Content-Type": "application/json",
1411
+ };
1412
+ const payload = {
1413
+ model,
1414
+ messages: [{ role: "user", content: prompt }],
1415
+ temperature,
1416
+ max_tokens: maxTokens,
1417
+ stream: false,
1418
+ };
1419
+ const resp = await fetch(url, {
1420
+ method: "POST",
1421
+ headers,
1422
+ body: JSON.stringify(payload),
1423
+ signal: AbortSignal.timeout(30_000),
1424
+ });
1425
+ if (resp.status !== 200) {
1426
+ const body = await resp.text();
1427
+ logger.error(`LLM 调用失败 ${resp.status}: ${body.slice(0, 200)}`);
1428
+ throw new AppException(ErrorCode.PARAM_ERROR, "AI 服务调用失败");
1429
+ }
1430
+ const data = (await resp.json());
1431
+ return data.choices[0].message.content.trim();
1432
+ }
1433
+ async agentAiDraft(agentId, sessionId, instruction) {
1434
+ const session = await this.repo.findSessionBySessionId(sessionId);
1435
+ if (!session)
1436
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
1437
+ if (session.agent_id !== agentId)
1438
+ throw new AppException(ErrorCode.PARAM_ERROR, "该会话不属于当前坐席", 403);
1439
+ const csConfig = await this.repo.findConfigByAppId(session.app_id || "");
1440
+ if (!csConfig)
1441
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "客服配置不存在", 404);
1442
+ const history = await this.repo.listMessages(session.id, 20);
1443
+ const convLines = [];
1444
+ for (const m of history) {
1445
+ const roleLabel = m.role === "user"
1446
+ ? "访客"
1447
+ : m.role === "agent"
1448
+ ? "坐席"
1449
+ : m.role === "assistant"
1450
+ ? "AI客服"
1451
+ : "系统";
1452
+ convLines.push(`${roleLabel}: ${m.content}`);
1453
+ }
1454
+ const context = convLines.slice(-16).join("\n") || "(暂无历史消息)";
1455
+ let prompt = "你是一名专业客服坐席的 AI 起草助手。请基于以下会话上下文,以坐席口吻" +
1456
+ "起草一条自然、礼貌、有帮助的回复。只输出回复正文,不要输出任何前缀、" +
1457
+ "引号或解释。\n\n" +
1458
+ `会话上下文:\n${context}\n`;
1459
+ if (instruction)
1460
+ prompt += `\n坐席补充要求:${instruction}\n`;
1461
+ prompt += "\n请起草回复:";
1462
+ return await this._callLlmText(csConfig, prompt, 400, 0.7);
1463
+ }
1464
+ async generateSessionSummary(session) {
1465
+ try {
1466
+ const csConfig = await this.repo.findConfigByAppId(session.app_id || "");
1467
+ if (!csConfig)
1468
+ return null;
1469
+ const history = await this.repo.listMessages(session.id, 30);
1470
+ if (!history.length)
1471
+ return null;
1472
+ const convLines = history.map((m) => `${m.role === "user" ? "访客" : m.role === "agent" ? "客服" : "AI"}: ${m.content}`);
1473
+ const prompt = "请为以下客服会话生成简洁摘要,严格按此格式输出(不要多余内容):\n" +
1474
+ "问题:<客户的核心问题>\n已处理:<已完成的处理>\n待办:<仍需处理的事项,没有写无>\n" +
1475
+ "情绪:<客户情绪,如 平静/不满/愤怒/满意>\n\n会话记录:\n" +
1476
+ convLines.slice(-30).join("\n");
1477
+ const summary = await this._callLlmText(csConfig, prompt, 300, 0.3);
1478
+ let emotion = null;
1479
+ for (const line of summary.split("\n")) {
1480
+ if (line.startsWith("情绪")) {
1481
+ emotion = line.split(":", 2)[1]?.trim().slice(0, 20) || null;
1482
+ break;
1483
+ }
1484
+ }
1485
+ await this.repo.updateSession(session.id, {
1486
+ summary,
1487
+ emotion: emotion || null,
1488
+ });
1489
+ return summary;
1490
+ }
1491
+ catch (e) {
1492
+ logger.warning(`生成会话摘要失败 session=${session.session_id}: ${e.message}`);
1493
+ return null;
1494
+ }
1495
+ }
1496
+ async submitRating(sessionId, rating, comment) {
1497
+ const session = await this.repo.findSessionBySessionId(sessionId);
1498
+ if (!session)
1499
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
1500
+ if (!(rating >= 1 && rating <= 5))
1501
+ throw new AppException(ErrorCode.PARAM_ERROR, "评分范围 1-5");
1502
+ await this.repo.updateSession(session.id, { rating });
1503
+ if (comment) {
1504
+ await this.repo.createMessage({
1505
+ session_id: session.id,
1506
+ role: "system",
1507
+ content: `用户满意度评价:${rating} 分。${comment || ""}`.trim(),
1508
+ content_type: "text",
1509
+ });
1510
+ }
1511
+ return { session_id: session.session_id, rating };
1512
+ }
1513
+ async _shouldTransfer(csConfig, message, recentHistory) {
1514
+ const text = (message || "").trim();
1515
+ if (!text)
1516
+ return [false, ""];
1517
+ const hit = _AUTO_TRANSFER_KEYWORDS.filter((kw) => text.includes(kw));
1518
+ if (!hit.length)
1519
+ return [false, ""];
1520
+ try {
1521
+ const lastConv = recentHistory
1522
+ .slice(-6)
1523
+ .map((m) => `${m.role === "user" ? "访客" : m.role === "agent" ? "客服" : "AI"}: ${m.content}`)
1524
+ .join("\n");
1525
+ const prompt = "你是智能客服的转人工决策器。根据客户最近消息判断是否应该转人工客服。\n" +
1526
+ "转人工条件:1) 客户明确要求人工/真人/投诉/退款/曝光;2) 情绪强烈负面且无法安抚;" +
1527
+ "3) 涉及法律、医疗、大额资金等敏感场景。\n" +
1528
+ '只输出 JSON:{"need_human": true|false, "reason": "一句话原因"}\n\n' +
1529
+ `会话记录:\n${lastConv}\n当前客户消息:${text}\n`;
1530
+ const result = await this._callLlmText(csConfig, prompt, 100, 0);
1531
+ const start = result.indexOf("{");
1532
+ const end = result.lastIndexOf("}");
1533
+ if (start >= 0 && end > start) {
1534
+ const data = JSON.parse(result.slice(start, end + 1));
1535
+ if (data.need_human) {
1536
+ return [true, data.reason || "客户情绪激烈"];
1537
+ }
1538
+ }
1539
+ }
1540
+ catch (e) {
1541
+ logger.warning(`智能转人工 LLM 判断失败: ${e.message}`);
1542
+ // LLM 失败时降级:命中人工请求类关键词直接转
1543
+ const fallback = ["人工", "真人", "客服人员", "投诉", "退款", "12315"];
1544
+ if (fallback.some((kw) => text.includes(kw))) {
1545
+ return [true, "客户明确要求人工服务"];
1546
+ }
1547
+ }
1548
+ return [false, ""];
1549
+ }
1550
+ // ─── 会话和消息查看 ───
1551
+ async listSessions(page, size, status, keyword, appId, employee) {
1552
+ const { items, total } = await this.repo.listSessions(page, size, status, keyword, appId, employee);
1553
+ let result = await this._resolveSessionAgentNames(items);
1554
+ result = await this._resolveSessionAppNames(result, items);
1555
+ return { items: result, total };
1556
+ }
1557
+ async _resolveSessionAppNames(sessions, rawSessions) {
1558
+ const appIds = [
1559
+ ...new Set(rawSessions.filter((s) => s.app_id).map((s) => s.app_id)),
1560
+ ];
1561
+ const appMap = new Map();
1562
+ if (appIds.length) {
1563
+ const configs = await this.repo.listConfigsByAppIds(appIds);
1564
+ for (const c of configs)
1565
+ appMap.set(c.app_id, c.app_name);
1566
+ }
1567
+ return sessions.map((dto) => {
1568
+ const s = rawSessions.find((r) => r.id === dto.id);
1569
+ dto.app_name = s?.app_id ? (appMap.get(s.app_id) ?? null) : null;
1570
+ return dto;
1571
+ });
1572
+ }
1573
+ async listMessages(sessionId, employee) {
1574
+ const session = await this.repo.findSessionBySessionId(sessionId);
1575
+ if (!session)
1576
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
1577
+ // 数据权限:会话归属人 = 坐席关联的员工;越权视为不存在
1578
+ if (employee && !(await this._sessionVisible(session, employee))) {
1579
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
1580
+ }
1581
+ const messages = await this.repo.listMessages(session.id);
1582
+ return messages.map(toMessageDto);
1583
+ }
1584
+ async _sessionVisible(session, employee) {
1585
+ const scope = await resolveVisibility(employee);
1586
+ if (scope.allData)
1587
+ return true;
1588
+ if (!session.agent_id)
1589
+ return false;
1590
+ const agent = await this.repo.findAgentById(session.agent_id);
1591
+ if (!agent)
1592
+ return false;
1593
+ if (scope.selfOnly)
1594
+ return agent.employee_id === employee.id;
1595
+ if (scope.deptIds.length) {
1596
+ const rows = (await knex(ModelRegistry.get("EmployeeDept"))
1597
+ .whereIn("dept_id", scope.deptIds)
1598
+ .select("employee_id"));
1599
+ return rows.some((r) => r.employee_id === agent.employee_id);
1600
+ }
1601
+ return false;
1602
+ }
1603
+ // ─── SDK 脚本生成 ───
1604
+ async generateSdkScript(appId) {
1605
+ const config = await this.repo.findConfigByAppId(appId);
1606
+ if (!config)
1607
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "无效的应用ID", 404);
1608
+ // 优先级:sys_config(cs_api_base) > CDN_DOMAIN > window.location.origin
1609
+ const row = (await knex(ModelRegistry.get("SysConfig"))
1610
+ .where("key", "cs_api_base")
1611
+ .select("value")
1612
+ .first());
1613
+ let apiBase = (row?.value || "").trim().replace(/\/+$/, "");
1614
+ if (!apiBase) {
1615
+ apiBase = (settings.CDN_DOMAIN || "").replace(/\/+$/, "");
1616
+ }
1617
+ const welcome = (config.welcome_message || "您好,有什么可以帮您的吗?").replace(/'/g, "\\'");
1618
+ const apiBaseJs = apiBase ? `'${apiBase}'` : "window.location.origin";
1619
+ const templatePath = new URL("./sdk_template.html", import.meta.url);
1620
+ const template = fs.readFileSync(templatePath, "utf-8");
1621
+ return template
1622
+ .replace("{{APP_ID}}", appId)
1623
+ .replace("{{WELCOME}}", welcome)
1624
+ .replace("{{API_BASE_JS}}", apiBaseJs);
1625
+ }
1626
+ }
1627
+ function cosineSimilarity(a, b) {
1628
+ if (a.length !== b.length)
1629
+ return 0.0;
1630
+ let dot = 0;
1631
+ let normA = 0;
1632
+ let normB = 0;
1633
+ for (let i = 0; i < a.length; i++) {
1634
+ dot += a[i] * b[i];
1635
+ normA += a[i] * a[i];
1636
+ normB += b[i] * b[i];
1637
+ }
1638
+ if (normA === 0 || normB === 0)
1639
+ return 0.0;
1640
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
1641
+ }
1642
+ //# sourceMappingURL=service.js.map