create-entity-app-server 0.0.3

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 (675) hide show
  1. package/.env.example +68 -0
  2. package/.gitignore +8 -0
  3. package/LICENSE +66 -0
  4. package/README.md +36 -0
  5. package/bin/create.js +222 -0
  6. package/configs/cache.json +7 -0
  7. package/configs/cors.json +24 -0
  8. package/configs/database.json +30 -0
  9. package/configs/security.json +45 -0
  10. package/configs/server.json +31 -0
  11. package/docs/README.md +274 -0
  12. package/docs/architecture.md +295 -0
  13. package/docs/cache.md +217 -0
  14. package/docs/configs.md +261 -0
  15. package/docs/database.md +505 -0
  16. package/docs/design/board-api-design.md +2342 -0
  17. package/docs/flows.md +581 -0
  18. package/docs/getting-started.md +83 -0
  19. package/docs/hooks.md +600 -0
  20. package/docs/internals.md +60 -0
  21. package/docs/plugins/2fa.md +121 -0
  22. package/docs/plugins/alimtalk.md +212 -0
  23. package/docs/plugins/friendtalk.md +158 -0
  24. package/docs/plugins/holidays.md +98 -0
  25. package/docs/plugins/how-to-create.md +148 -0
  26. package/docs/plugins/identity.md +223 -0
  27. package/docs/plugins/llm.md +567 -0
  28. package/docs/plugins/oauth.md +121 -0
  29. package/docs/plugins/ocr.md +168 -0
  30. package/docs/plugins/pg.md +226 -0
  31. package/docs/plugins/push.md +178 -0
  32. package/docs/plugins/sms.md +228 -0
  33. package/docs/plugins/taxinvoice.md +197 -0
  34. package/docs/routes/README.md +247 -0
  35. package/docs/routes/account-routes.md +262 -0
  36. package/docs/routes/alimtalk-routes.md +187 -0
  37. package/docs/routes/board-routes.md +492 -0
  38. package/docs/routes/email-verification.md +269 -0
  39. package/docs/routes/friendtalk-routes.md +45 -0
  40. package/docs/routes/holidays-routes.md +170 -0
  41. package/docs/routes/how-to-create.md +150 -0
  42. package/docs/routes/identity-routes.md +310 -0
  43. package/docs/routes/llm-routes.md +921 -0
  44. package/docs/routes/ocr-routes.md +133 -0
  45. package/docs/routes/password-reset.md +234 -0
  46. package/docs/routes/pg-routes.md +144 -0
  47. package/docs/routes/push-routes.md +205 -0
  48. package/docs/routes/sms-routes.md +243 -0
  49. package/docs/routes/smtp-routes.md +155 -0
  50. package/docs/routes/tax-invoice-routes.md +109 -0
  51. package/docs/schedules/dormancy-and-retention.md +160 -0
  52. package/docs/schedules/how-to-create.md +255 -0
  53. package/docs/scripts-guide.md +310 -0
  54. package/docs/security.md +221 -0
  55. package/docs/system.md +297 -0
  56. package/package.json +111 -0
  57. package/scripts/_gen-table-type.ts +605 -0
  58. package/scripts/build-minify-plugins.mjs +124 -0
  59. package/scripts/build-obfuscate-system.mjs +38 -0
  60. package/scripts/build.sh +140 -0
  61. package/scripts/dist-tsconfig.json +18 -0
  62. package/scripts/entity.sh +224 -0
  63. package/scripts/gen-table-type.sh +169 -0
  64. package/scripts/push.sh +102 -0
  65. package/scripts/release.sh +51 -0
  66. package/scripts/reset-all.sh +208 -0
  67. package/scripts/run.sh +202 -0
  68. package/src/app/hooks/README.md +148 -0
  69. package/src/app/hooks/account.ts +26 -0
  70. package/src/app/hooks/index.ts +19 -0
  71. package/src/app/hooks/order.ts +230 -0
  72. package/src/app/hooks/post.ts +162 -0
  73. package/src/app/plugins/2fa/config.example.json +15 -0
  74. package/src/app/plugins/2fa/config.json +17 -0
  75. package/src/app/plugins/2fa/config.ts +44 -0
  76. package/src/app/plugins/2fa/docs/README.md +139 -0
  77. package/src/app/plugins/2fa/entities/account.json +30 -0
  78. package/src/app/plugins/2fa/handlers/disable.ts +114 -0
  79. package/src/app/plugins/2fa/handlers/index.ts +11 -0
  80. package/src/app/plugins/2fa/handlers/recovery.ts +98 -0
  81. package/src/app/plugins/2fa/handlers/regenerate.ts +99 -0
  82. package/src/app/plugins/2fa/handlers/setup-verify.ts +121 -0
  83. package/src/app/plugins/2fa/handlers/setup.ts +92 -0
  84. package/src/app/plugins/2fa/handlers/status.ts +47 -0
  85. package/src/app/plugins/2fa/handlers/utils.ts +222 -0
  86. package/src/app/plugins/2fa/handlers/verify.ts +92 -0
  87. package/src/app/plugins/2fa/index.ts +50 -0
  88. package/src/app/plugins/2fa/routes.ts +49 -0
  89. package/src/app/plugins/2fa/templates/auth/2fa_disabled.html +23 -0
  90. package/src/app/plugins/2fa/templates/auth/2fa_recovery_regenerated.html +31 -0
  91. package/src/app/plugins/2fa/templates/auth/2fa_setup_complete.html +43 -0
  92. package/src/app/plugins/2fa/totp-utils.ts +189 -0
  93. package/src/app/plugins/2fa/types.ts +95 -0
  94. package/src/app/plugins/README.md +118 -0
  95. package/src/app/plugins/ais/config.json +7 -0
  96. package/src/app/plugins/ais/config.ts +32 -0
  97. package/src/app/plugins/ais/docs/README.md +142 -0
  98. package/src/app/plugins/ais/docs/api.md +138 -0
  99. package/src/app/plugins/ais/entities/ais_vessel.json +64 -0
  100. package/src/app/plugins/ais/handlers.ts +88 -0
  101. package/src/app/plugins/ais/index.ts +21 -0
  102. package/src/app/plugins/ais/routes.ts +13 -0
  103. package/src/app/plugins/ais/service.ts +242 -0
  104. package/src/app/plugins/ais/types/index.ts +78 -0
  105. package/src/app/plugins/alimtalk/config.example.json +52 -0
  106. package/src/app/plugins/alimtalk/config.json +26 -0
  107. package/src/app/plugins/alimtalk/config.ts +75 -0
  108. package/src/app/plugins/alimtalk/docs/README.md +140 -0
  109. package/src/app/plugins/alimtalk/entities/alimtalk_log.json +65 -0
  110. package/src/app/plugins/alimtalk/entities/alimtalk_msg.json +53 -0
  111. package/src/app/plugins/alimtalk/entity-adapter.ts +196 -0
  112. package/src/app/plugins/alimtalk/handlers.ts +84 -0
  113. package/src/app/plugins/alimtalk/index.ts +80 -0
  114. package/src/app/plugins/alimtalk/providers/aligo.ts +151 -0
  115. package/src/app/plugins/alimtalk/providers/index.ts +29 -0
  116. package/src/app/plugins/alimtalk/providers/nhn.ts +254 -0
  117. package/src/app/plugins/alimtalk/providers/ppurio.ts +145 -0
  118. package/src/app/plugins/alimtalk/providers/solapi.ts +145 -0
  119. package/src/app/plugins/alimtalk/routes.ts +15 -0
  120. package/src/app/plugins/alimtalk/service.ts +423 -0
  121. package/src/app/plugins/alimtalk/template-cache.ts +42 -0
  122. package/src/app/plugins/alimtalk/templates/alimtalk.json +27 -0
  123. package/src/app/plugins/alimtalk/types/client.ts +48 -0
  124. package/src/app/plugins/alimtalk/types/config.ts +53 -0
  125. package/src/app/plugins/alimtalk/types/friendtalk.ts +90 -0
  126. package/src/app/plugins/alimtalk/types/index.ts +4 -0
  127. package/src/app/plugins/alimtalk/types/job.ts +56 -0
  128. package/src/app/plugins/alimtalk/webhook.ts +211 -0
  129. package/src/app/plugins/distance-server/config.json +6 -0
  130. package/src/app/plugins/distance-server/config.ts +50 -0
  131. package/src/app/plugins/distance-server/docs/README.md +114 -0
  132. package/src/app/plugins/distance-server/handlers.ts +104 -0
  133. package/src/app/plugins/distance-server/index.ts +23 -0
  134. package/src/app/plugins/distance-server/routes.ts +36 -0
  135. package/src/app/plugins/distance-server/service.ts +187 -0
  136. package/src/app/plugins/distance-server/types/index.ts +8 -0
  137. package/src/app/plugins/example/config.json +6 -0
  138. package/src/app/plugins/example/config.ts +46 -0
  139. package/src/app/plugins/example/docs/README.md +64 -0
  140. package/src/app/plugins/example/entity-adapter.ts +96 -0
  141. package/src/app/plugins/example/handlers.ts +94 -0
  142. package/src/app/plugins/example/index.ts +63 -0
  143. package/src/app/plugins/example/routes.ts +30 -0
  144. package/src/app/plugins/example/service.ts +31 -0
  145. package/src/app/plugins/example/types/config.ts +11 -0
  146. package/src/app/plugins/example/types/index.ts +1 -0
  147. package/src/app/plugins/friendtalk/config.example.json +35 -0
  148. package/src/app/plugins/friendtalk/config.json +11 -0
  149. package/src/app/plugins/friendtalk/config.ts +70 -0
  150. package/src/app/plugins/friendtalk/docs/README.md +110 -0
  151. package/src/app/plugins/friendtalk/entities/friendtalk_log.json +89 -0
  152. package/src/app/plugins/friendtalk/entities/friendtalk_msg.json +91 -0
  153. package/src/app/plugins/friendtalk/entity-adapter.ts +150 -0
  154. package/src/app/plugins/friendtalk/handlers.ts +56 -0
  155. package/src/app/plugins/friendtalk/routes.ts +12 -0
  156. package/src/app/plugins/friendtalk/templates/friendtalk.json +16 -0
  157. package/src/app/plugins/holidays/config.example.json +6 -0
  158. package/src/app/plugins/holidays/config.json +10 -0
  159. package/src/app/plugins/holidays/config.ts +44 -0
  160. package/src/app/plugins/holidays/docs/README.md +122 -0
  161. package/src/app/plugins/holidays/entities/holiday.json +22 -0
  162. package/src/app/plugins/holidays/handlers.ts +135 -0
  163. package/src/app/plugins/holidays/index.ts +78 -0
  164. package/src/app/plugins/holidays/routes.ts +18 -0
  165. package/src/app/plugins/holidays/service.ts +241 -0
  166. package/src/app/plugins/holidays/types/api.ts +49 -0
  167. package/src/app/plugins/holidays/types/config.ts +8 -0
  168. package/src/app/plugins/holidays/types/index.ts +2 -0
  169. package/src/app/plugins/identity/config.example.json +43 -0
  170. package/src/app/plugins/identity/config.json +30 -0
  171. package/src/app/plugins/identity/config.ts +138 -0
  172. package/src/app/plugins/identity/crypto.ts +51 -0
  173. package/src/app/plugins/identity/docs/README.md +164 -0
  174. package/src/app/plugins/identity/entities/account.json +27 -0
  175. package/src/app/plugins/identity/entities/identity_verification.json +113 -0
  176. package/src/app/plugins/identity/entity-adapter.ts +242 -0
  177. package/src/app/plugins/identity/handlers.ts +239 -0
  178. package/src/app/plugins/identity/index.ts +80 -0
  179. package/src/app/plugins/identity/providers/danal.ts +150 -0
  180. package/src/app/plugins/identity/providers/index.ts +38 -0
  181. package/src/app/plugins/identity/providers/kmc.ts +140 -0
  182. package/src/app/plugins/identity/providers/nice.ts +304 -0
  183. package/src/app/plugins/identity/routes.ts +22 -0
  184. package/src/app/plugins/identity/service.ts +361 -0
  185. package/src/app/plugins/identity/types/config.ts +35 -0
  186. package/src/app/plugins/identity/types/index.ts +2 -0
  187. package/src/app/plugins/identity/types/verification.ts +105 -0
  188. package/src/app/plugins/kobc_freight/config.json +6 -0
  189. package/src/app/plugins/kobc_freight/config.ts +28 -0
  190. package/src/app/plugins/kobc_freight/docs/README.md +316 -0
  191. package/src/app/plugins/kobc_freight/entities/kobc_freight_entry.json +31 -0
  192. package/src/app/plugins/kobc_freight/entities/kobc_kcci_entry.json +67 -0
  193. package/src/app/plugins/kobc_freight/entities/kobc_kpli_entry.json +27 -0
  194. package/src/app/plugins/kobc_freight/entities/kobc_ncfi_entry.json +99 -0
  195. package/src/app/plugins/kobc_freight/handlers.ts +283 -0
  196. package/src/app/plugins/kobc_freight/index.ts +21 -0
  197. package/src/app/plugins/kobc_freight/routes.ts +39 -0
  198. package/src/app/plugins/kobc_freight/service.ts +604 -0
  199. package/src/app/plugins/kobc_freight/types/index.ts +99 -0
  200. package/src/app/plugins/llm/cache.ts +138 -0
  201. package/src/app/plugins/llm/chatbot-store.ts +270 -0
  202. package/src/app/plugins/llm/chunker.ts +96 -0
  203. package/src/app/plugins/llm/config.example.json +260 -0
  204. package/src/app/plugins/llm/config.json +71 -0
  205. package/src/app/plugins/llm/config.ts +99 -0
  206. package/src/app/plugins/llm/conversation-store.ts +140 -0
  207. package/src/app/plugins/llm/docs/README.md +120 -0
  208. package/src/app/plugins/llm/docs/api.md +250 -0
  209. package/src/app/plugins/llm/document-store.ts +318 -0
  210. package/src/app/plugins/llm/entities/llm_chatbot.json +66 -0
  211. package/src/app/plugins/llm/entities/llm_conversation.json +61 -0
  212. package/src/app/plugins/llm/entities/llm_document.json +67 -0
  213. package/src/app/plugins/llm/entities/llm_usage.json +51 -0
  214. package/src/app/plugins/llm/entities/llm_user_profile.json +45 -0
  215. package/src/app/plugins/llm/handlers.ts +1114 -0
  216. package/src/app/plugins/llm/index.ts +90 -0
  217. package/src/app/plugins/llm/profile-store.ts +125 -0
  218. package/src/app/plugins/llm/providers/anthropic.ts +233 -0
  219. package/src/app/plugins/llm/providers/azure.ts +267 -0
  220. package/src/app/plugins/llm/providers/gemini.ts +252 -0
  221. package/src/app/plugins/llm/providers/index.ts +86 -0
  222. package/src/app/plugins/llm/providers/ollama.ts +237 -0
  223. package/src/app/plugins/llm/providers/openai.ts +244 -0
  224. package/src/app/plugins/llm/routes.ts +73 -0
  225. package/src/app/plugins/llm/service.ts +965 -0
  226. package/src/app/plugins/llm/template-loader.ts +135 -0
  227. package/src/app/plugins/llm/templates/prompts/extract_json.json +8 -0
  228. package/src/app/plugins/llm/templates/prompts/summarize.json +10 -0
  229. package/src/app/plugins/llm/templates/prompts/translate.json +10 -0
  230. package/src/app/plugins/llm/types/chat.ts +96 -0
  231. package/src/app/plugins/llm/types/chatbot.ts +143 -0
  232. package/src/app/plugins/llm/types/config.ts +47 -0
  233. package/src/app/plugins/llm/types/conversation.ts +116 -0
  234. package/src/app/plugins/llm/types/index.ts +7 -0
  235. package/src/app/plugins/llm/types/profile.ts +48 -0
  236. package/src/app/plugins/llm/types/store.ts +50 -0
  237. package/src/app/plugins/llm/types/usage.ts +27 -0
  238. package/src/app/plugins/llm/usage-store.ts +64 -0
  239. package/src/app/plugins/oauth/account/handlers/index.ts +4 -0
  240. package/src/app/plugins/oauth/account/handlers/link.ts +165 -0
  241. package/src/app/plugins/oauth/account/handlers/providers-list.ts +49 -0
  242. package/src/app/plugins/oauth/account/handlers/refresh.ts +92 -0
  243. package/src/app/plugins/oauth/account/handlers/unlink.ts +105 -0
  244. package/src/app/plugins/oauth/config.example.json +65 -0
  245. package/src/app/plugins/oauth/config.json +72 -0
  246. package/src/app/plugins/oauth/config.ts +182 -0
  247. package/src/app/plugins/oauth/docs/README.md +160 -0
  248. package/src/app/plugins/oauth/entities/account_oauth.json +74 -0
  249. package/src/app/plugins/oauth/handlers/callback.ts +314 -0
  250. package/src/app/plugins/oauth/handlers/index.ts +2 -0
  251. package/src/app/plugins/oauth/handlers/redirect.ts +47 -0
  252. package/src/app/plugins/oauth/index.ts +74 -0
  253. package/src/app/plugins/oauth/providers/index.ts +530 -0
  254. package/src/app/plugins/oauth/routes.ts +49 -0
  255. package/src/app/plugins/oauth/service.ts +14 -0
  256. package/src/app/plugins/oauth/state.ts +105 -0
  257. package/src/app/plugins/oauth/types/index.ts +52 -0
  258. package/src/app/plugins/oauth/upsert.ts +162 -0
  259. package/src/app/plugins/ocr/cache.ts +50 -0
  260. package/src/app/plugins/ocr/config.example.json +103 -0
  261. package/src/app/plugins/ocr/config.json +110 -0
  262. package/src/app/plugins/ocr/config.ts +126 -0
  263. package/src/app/plugins/ocr/direction.ts +48 -0
  264. package/src/app/plugins/ocr/dispatch.ts +130 -0
  265. package/src/app/plugins/ocr/docs/README.md +125 -0
  266. package/src/app/plugins/ocr/docs/api.md +159 -0
  267. package/src/app/plugins/ocr/entities/ocr_result.json +98 -0
  268. package/src/app/plugins/ocr/entities/ocr_usage.json +57 -0
  269. package/src/app/plugins/ocr/entity-adapter.ts +198 -0
  270. package/src/app/plugins/ocr/errors.ts +42 -0
  271. package/src/app/plugins/ocr/handlers.ts +250 -0
  272. package/src/app/plugins/ocr/index.ts +68 -0
  273. package/src/app/plugins/ocr/llm-parser.ts +164 -0
  274. package/src/app/plugins/ocr/parsing-pipeline.ts +87 -0
  275. package/src/app/plugins/ocr/pdf-converter.ts +136 -0
  276. package/src/app/plugins/ocr/preprocessor.ts +313 -0
  277. package/src/app/plugins/ocr/providers/aws.ts +200 -0
  278. package/src/app/plugins/ocr/providers/azure.ts +183 -0
  279. package/src/app/plugins/ocr/providers/google.ts +155 -0
  280. package/src/app/plugins/ocr/providers/index.ts +80 -0
  281. package/src/app/plugins/ocr/providers/naver.ts +186 -0
  282. package/src/app/plugins/ocr/providers/tesseract.ts +198 -0
  283. package/src/app/plugins/ocr/providers/upstage.ts +156 -0
  284. package/src/app/plugins/ocr/quota.ts +108 -0
  285. package/src/app/plugins/ocr/refiner.ts +112 -0
  286. package/src/app/plugins/ocr/routes.ts +19 -0
  287. package/src/app/plugins/ocr/service.ts +333 -0
  288. package/src/app/plugins/ocr/template-loader.ts +72 -0
  289. package/src/app/plugins/ocr/template-matcher.ts +422 -0
  290. package/src/app/plugins/ocr/templates/business_reg.json +145 -0
  291. package/src/app/plugins/ocr/templates/career_cert.json +93 -0
  292. package/src/app/plugins/ocr/templates/driver_license.json +89 -0
  293. package/src/app/plugins/ocr/templates/facility_card.json +82 -0
  294. package/src/app/plugins/ocr/templates/id_card.json +55 -0
  295. package/src/app/plugins/ocr/templates/invoice.json +92 -0
  296. package/src/app/plugins/ocr/templates/namecard.json +116 -0
  297. package/src/app/plugins/ocr/templates/prompts/business_reg.json +14 -0
  298. package/src/app/plugins/ocr/templates/prompts/career_cert.json +16 -0
  299. package/src/app/plugins/ocr/templates/prompts/driver_license.json +14 -0
  300. package/src/app/plugins/ocr/templates/prompts/facility_card.json +15 -0
  301. package/src/app/plugins/ocr/templates/prompts/general.json +13 -0
  302. package/src/app/plugins/ocr/templates/prompts/id_card.json +11 -0
  303. package/src/app/plugins/ocr/templates/prompts/invoice.json +17 -0
  304. package/src/app/plugins/ocr/templates/prompts/namecard.json +15 -0
  305. package/src/app/plugins/ocr/templates/prompts/receipt.json +14 -0
  306. package/src/app/plugins/ocr/templates/receipt.json +79 -0
  307. package/src/app/plugins/ocr/types/config.ts +60 -0
  308. package/src/app/plugins/ocr/types/driver.ts +71 -0
  309. package/src/app/plugins/ocr/types/index.ts +5 -0
  310. package/src/app/plugins/ocr/types/parsed.ts +101 -0
  311. package/src/app/plugins/ocr/types/store.ts +70 -0
  312. package/src/app/plugins/ocr/types/template.ts +89 -0
  313. package/src/app/plugins/ocr/utils.ts +18 -0
  314. package/src/app/plugins/pg/config.example.json +79 -0
  315. package/src/app/plugins/pg/config.json +35 -0
  316. package/src/app/plugins/pg/config.ts +58 -0
  317. package/src/app/plugins/pg/docs/README.md +176 -0
  318. package/src/app/plugins/pg/entities/pg_cancel.json +60 -0
  319. package/src/app/plugins/pg/entities/pg_order.json +115 -0
  320. package/src/app/plugins/pg/entities/pg_webhook_log.json +52 -0
  321. package/src/app/plugins/pg/entity-adapter.ts +144 -0
  322. package/src/app/plugins/pg/handlers.ts +240 -0
  323. package/src/app/plugins/pg/index.ts +98 -0
  324. package/src/app/plugins/pg/providers/danal.ts +178 -0
  325. package/src/app/plugins/pg/providers/hecto.ts +340 -0
  326. package/src/app/plugins/pg/providers/index.ts +53 -0
  327. package/src/app/plugins/pg/providers/inicis.ts +151 -0
  328. package/src/app/plugins/pg/providers/kakaopay.ts +242 -0
  329. package/src/app/plugins/pg/providers/kcp.ts +147 -0
  330. package/src/app/plugins/pg/providers/naverpay.ts +299 -0
  331. package/src/app/plugins/pg/providers/payco.ts +290 -0
  332. package/src/app/plugins/pg/providers/payletter.ts +377 -0
  333. package/src/app/plugins/pg/providers/paypal.ts +423 -0
  334. package/src/app/plugins/pg/providers/toss.ts +157 -0
  335. package/src/app/plugins/pg/providers/wanna.ts +163 -0
  336. package/src/app/plugins/pg/routes.ts +31 -0
  337. package/src/app/plugins/pg/service.ts +531 -0
  338. package/src/app/plugins/pg/types/client.ts +52 -0
  339. package/src/app/plugins/pg/types/config.ts +42 -0
  340. package/src/app/plugins/pg/types/error.ts +25 -0
  341. package/src/app/plugins/pg/types/index.ts +4 -0
  342. package/src/app/plugins/pg/types/payment.ts +145 -0
  343. package/src/app/plugins/providers/docs/README.md +32 -0
  344. package/src/app/plugins/providers/solapi-auth.ts +27 -0
  345. package/src/app/plugins/push/config.example.json +26 -0
  346. package/src/app/plugins/push/config.json +18 -0
  347. package/src/app/plugins/push/config.ts +119 -0
  348. package/src/app/plugins/push/docs/README.md +147 -0
  349. package/src/app/plugins/push/entities/push_log.json +86 -0
  350. package/src/app/plugins/push/entities/push_msg.json +56 -0
  351. package/src/app/plugins/push/entity-adapter.ts +326 -0
  352. package/src/app/plugins/push/handlers.ts +193 -0
  353. package/src/app/plugins/push/index.ts +85 -0
  354. package/src/app/plugins/push/providers/apns.ts +152 -0
  355. package/src/app/plugins/push/providers/fcm.ts +181 -0
  356. package/src/app/plugins/push/providers/index.ts +42 -0
  357. package/src/app/plugins/push/providers/utils.ts +30 -0
  358. package/src/app/plugins/push/routes.ts +24 -0
  359. package/src/app/plugins/push/service.ts +297 -0
  360. package/src/app/plugins/push/types/config.ts +32 -0
  361. package/src/app/plugins/push/types/index.ts +14 -0
  362. package/src/app/plugins/push/types/job.ts +79 -0
  363. package/src/app/plugins/shared/docs/README.md +11 -0
  364. package/src/app/plugins/sms/config.example.json +30 -0
  365. package/src/app/plugins/sms/config.json +33 -0
  366. package/src/app/plugins/sms/config.ts +158 -0
  367. package/src/app/plugins/sms/docs/README.md +236 -0
  368. package/src/app/plugins/sms/entities/sms_log.json +65 -0
  369. package/src/app/plugins/sms/entities/sms_msg.json +82 -0
  370. package/src/app/plugins/sms/entities/sms_verification.json +50 -0
  371. package/src/app/plugins/sms/entity-adapter.ts +213 -0
  372. package/src/app/plugins/sms/handlers.ts +149 -0
  373. package/src/app/plugins/sms/index.ts +93 -0
  374. package/src/app/plugins/sms/providers/aligo.ts +73 -0
  375. package/src/app/plugins/sms/providers/aws-sns.ts +182 -0
  376. package/src/app/plugins/sms/providers/index.ts +47 -0
  377. package/src/app/plugins/sms/providers/nhn.ts +82 -0
  378. package/src/app/plugins/sms/providers/ppurio.ts +76 -0
  379. package/src/app/plugins/sms/providers/solapi.ts +83 -0
  380. package/src/app/plugins/sms/routes.ts +23 -0
  381. package/src/app/plugins/sms/service.ts +239 -0
  382. package/src/app/plugins/sms/types/client.ts +41 -0
  383. package/src/app/plugins/sms/types/config.ts +46 -0
  384. package/src/app/plugins/sms/types/index.ts +3 -0
  385. package/src/app/plugins/sms/types/job.ts +51 -0
  386. package/src/app/plugins/sms/verification.ts +162 -0
  387. package/src/app/plugins/smtp/config.json +5 -0
  388. package/src/app/plugins/smtp/config.ts +41 -0
  389. package/src/app/plugins/smtp/docs/README.md +165 -0
  390. package/src/app/plugins/smtp/handlers.ts +52 -0
  391. package/src/app/plugins/smtp/index.ts +33 -0
  392. package/src/app/plugins/smtp/routes.ts +19 -0
  393. package/src/app/plugins/smtp/templates/layout.html +50 -0
  394. package/src/app/plugins/smtp/types/config.ts +8 -0
  395. package/src/app/plugins/smtp/types/index.ts +1 -0
  396. package/src/app/plugins/taxinvoice/config.example.json +60 -0
  397. package/src/app/plugins/taxinvoice/config.json +35 -0
  398. package/src/app/plugins/taxinvoice/config.ts +117 -0
  399. package/src/app/plugins/taxinvoice/docs/README.md +322 -0
  400. package/src/app/plugins/taxinvoice/entities/tax_invoice.json +229 -0
  401. package/src/app/plugins/taxinvoice/entities/tax_invoice_item.json +56 -0
  402. package/src/app/plugins/taxinvoice/entities/tax_invoice_log.json +50 -0
  403. package/src/app/plugins/taxinvoice/entities/tax_invoice_party.json +61 -0
  404. package/src/app/plugins/taxinvoice/entity-adapter.ts +285 -0
  405. package/src/app/plugins/taxinvoice/handlers.ts +120 -0
  406. package/src/app/plugins/taxinvoice/index.ts +74 -0
  407. package/src/app/plugins/taxinvoice/providers/barobill.ts +273 -0
  408. package/src/app/plugins/taxinvoice/providers/bolta.ts +193 -0
  409. package/src/app/plugins/taxinvoice/providers/esero.ts +201 -0
  410. package/src/app/plugins/taxinvoice/providers/index.ts +41 -0
  411. package/src/app/plugins/taxinvoice/providers/popbill.ts +258 -0
  412. package/src/app/plugins/taxinvoice/providers/sendbill.ts +443 -0
  413. package/src/app/plugins/taxinvoice/providers/smartbill.ts +234 -0
  414. package/src/app/plugins/taxinvoice/routes.ts +17 -0
  415. package/src/app/plugins/taxinvoice/service.ts +439 -0
  416. package/src/app/plugins/taxinvoice/types/client.ts +57 -0
  417. package/src/app/plugins/taxinvoice/types/config.ts +42 -0
  418. package/src/app/plugins/taxinvoice/types/index.ts +4 -0
  419. package/src/app/plugins/taxinvoice/types/invoice.ts +128 -0
  420. package/src/app/plugins/taxinvoice/types/queue.ts +22 -0
  421. package/src/app/plugins/vessel_kr/config.json +9 -0
  422. package/src/app/plugins/vessel_kr/config.ts +32 -0
  423. package/src/app/plugins/vessel_kr/docs/README.md +167 -0
  424. package/src/app/plugins/vessel_kr/entities/vessel_kr_entry.json +136 -0
  425. package/src/app/plugins/vessel_kr/handlers.ts +102 -0
  426. package/src/app/plugins/vessel_kr/index.ts +21 -0
  427. package/src/app/plugins/vessel_kr/routes.ts +15 -0
  428. package/src/app/plugins/vessel_kr/service.ts +264 -0
  429. package/src/app/plugins/vessel_kr/types/index.ts +100 -0
  430. package/src/app/routes/README.md +71 -0
  431. package/src/app/routes/account/change-password/config.json +5 -0
  432. package/src/app/routes/account/change-password/entities/password_history.json +18 -0
  433. package/src/app/routes/account/change-password/handlers.ts +204 -0
  434. package/src/app/routes/account/change-password/routes.ts +28 -0
  435. package/src/app/routes/account/config.json +5 -0
  436. package/src/app/routes/account/reactivate/config.json +5 -0
  437. package/src/app/routes/account/reactivate/handlers.ts +249 -0
  438. package/src/app/routes/account/reactivate/routes.ts +14 -0
  439. package/src/app/routes/account/register/config-loader.ts +34 -0
  440. package/src/app/routes/account/register/config.json +8 -0
  441. package/src/app/routes/account/register/handlers.ts +207 -0
  442. package/src/app/routes/account/register/routes.ts +25 -0
  443. package/src/app/routes/account/register/types/index.ts +50 -0
  444. package/src/app/routes/account/routes.ts +31 -0
  445. package/src/app/routes/account/templates/force_reset.html +18 -0
  446. package/src/app/routes/account/templates/welcome.html +14 -0
  447. package/src/app/routes/account/withdraw/handlers.ts +111 -0
  448. package/src/app/routes/account/withdraw/routes.ts +18 -0
  449. package/src/app/routes/approval/config.json +5 -0
  450. package/src/app/routes/approval/entities/approval.json +99 -0
  451. package/src/app/routes/approval/entities/comments.json +17 -0
  452. package/src/app/routes/approval/entities/reference.json +16 -0
  453. package/src/app/routes/approval/routes.ts +30 -0
  454. package/src/app/routes/auth/config.json +5 -0
  455. package/src/app/routes/auth/handlers.ts +245 -0
  456. package/src/app/routes/auth/routes.ts +16 -0
  457. package/src/app/routes/board/config.json +5 -0
  458. package/src/app/routes/board/entities/board_category.json +90 -0
  459. package/src/app/routes/board/entities/board_comment.json +83 -0
  460. package/src/app/routes/board/entities/board_like.json +51 -0
  461. package/src/app/routes/board/entities/board_mention.json +50 -0
  462. package/src/app/routes/board/entities/board_post.json +148 -0
  463. package/src/app/routes/board/entities/board_post_tag.json +41 -0
  464. package/src/app/routes/board/entities/board_rating.json +127 -0
  465. package/src/app/routes/board/entities/board_read_log.json +29 -0
  466. package/src/app/routes/board/entities/board_report.json +53 -0
  467. package/src/app/routes/board/entities/board_tag.json +21 -0
  468. package/src/app/routes/board/handlers/categories.ts +134 -0
  469. package/src/app/routes/board/handlers/comments.ts +207 -0
  470. package/src/app/routes/board/handlers/files.ts +104 -0
  471. package/src/app/routes/board/handlers/likes.ts +31 -0
  472. package/src/app/routes/board/handlers/mentions.ts +54 -0
  473. package/src/app/routes/board/handlers/posts.ts +577 -0
  474. package/src/app/routes/board/handlers/ratings.ts +60 -0
  475. package/src/app/routes/board/handlers/reports.ts +131 -0
  476. package/src/app/routes/board/handlers/tags.ts +81 -0
  477. package/src/app/routes/board/routes.ts +137 -0
  478. package/src/app/routes/calendar/config.json +5 -0
  479. package/src/app/routes/calendar/entities/calendar_attendees.json +23 -0
  480. package/src/app/routes/calendar/entities/calendar_comments.json +17 -0
  481. package/src/app/routes/calendar/entities/calendar_events.json +48 -0
  482. package/src/app/routes/calendar/entities/calendar_kind.json +11 -0
  483. package/src/app/routes/calendar/entities/calendar_method.json +11 -0
  484. package/src/app/routes/calendar/routes.ts +32 -0
  485. package/src/app/routes/email-verify/config-loader.ts +47 -0
  486. package/src/app/routes/email-verify/config.example.json +13 -0
  487. package/src/app/routes/email-verify/config.json +16 -0
  488. package/src/app/routes/email-verify/entities/account.json +23 -0
  489. package/src/app/routes/email-verify/handlers/activate.ts +103 -0
  490. package/src/app/routes/email-verify/handlers/change.ts +106 -0
  491. package/src/app/routes/email-verify/handlers/confirm.ts +87 -0
  492. package/src/app/routes/email-verify/handlers/index.ts +20 -0
  493. package/src/app/routes/email-verify/handlers/send.ts +157 -0
  494. package/src/app/routes/email-verify/handlers/status.ts +53 -0
  495. package/src/app/routes/email-verify/handlers/utils.ts +85 -0
  496. package/src/app/routes/email-verify/routes.ts +54 -0
  497. package/src/app/routes/email-verify/templates/verification.html +15 -0
  498. package/src/app/routes/email-verify/templates/verification_link.html +19 -0
  499. package/src/app/routes/email-verify/types/index.ts +77 -0
  500. package/src/app/routes/email-verify/verification-utils.ts +57 -0
  501. package/src/app/routes/example-db/config.json +5 -0
  502. package/src/app/routes/example-db/handlers.ts +220 -0
  503. package/src/app/routes/example-db/models/account-ext.ts +33 -0
  504. package/src/app/routes/example-db/models/users.ts +30 -0
  505. package/src/app/routes/example-db/routes.ts +23 -0
  506. package/src/app/routes/example-db/types/defaults.ts +21 -0
  507. package/src/app/routes/example-db/types/index.ts +4 -0
  508. package/src/app/routes/example-db/types/params.ts +3 -0
  509. package/src/app/routes/example-db/types/query.ts +6 -0
  510. package/src/app/routes/example-db/types/user.ts +11 -0
  511. package/src/app/routes/example-es/config.json +5 -0
  512. package/src/app/routes/example-es/handlers.ts +216 -0
  513. package/src/app/routes/example-es/routes.ts +24 -0
  514. package/src/app/routes/example-es/types/defaults.ts +30 -0
  515. package/src/app/routes/example-es/types/index.ts +4 -0
  516. package/src/app/routes/example-es/types/params.ts +3 -0
  517. package/src/app/routes/example-es/types/post.ts +12 -0
  518. package/src/app/routes/example-es/types/query.ts +14 -0
  519. package/src/app/routes/funeral/config.json +5 -0
  520. package/src/app/routes/funeral/entities/funeral.json +77 -0
  521. package/src/app/routes/funeral/entities/funeral_docs.json +36 -0
  522. package/src/app/routes/funeral/entities/funeral_mourner.json +31 -0
  523. package/src/app/routes/funeral/entities/funeral_order.json +48 -0
  524. package/src/app/routes/funeral/entities/funeral_room.json +61 -0
  525. package/src/app/routes/funeral/entities/funeral_schedule.json +39 -0
  526. package/src/app/routes/funeral/routes.ts +32 -0
  527. package/src/app/routes/health/config.json +5 -0
  528. package/src/app/routes/health/handlers.ts +69 -0
  529. package/src/app/routes/health/routes.ts +14 -0
  530. package/src/app/routes/hr/career/config.json +5 -0
  531. package/src/app/routes/hr/career/entities/employee_career.json +15 -0
  532. package/src/app/routes/hr/career/routes.ts +25 -0
  533. package/src/app/routes/hr/config.json +5 -0
  534. package/src/app/routes/hr/education/config.json +5 -0
  535. package/src/app/routes/hr/education/entities/employee_education.json +29 -0
  536. package/src/app/routes/hr/education/entities/employee_education_mans.json +25 -0
  537. package/src/app/routes/hr/education/entities/employee_school.json +19 -0
  538. package/src/app/routes/hr/education/routes.ts +28 -0
  539. package/src/app/routes/hr/employee/config.json +5 -0
  540. package/src/app/routes/hr/employee/entities/employee.json +59 -0
  541. package/src/app/routes/hr/employee/entities/employee_cert.json +19 -0
  542. package/src/app/routes/hr/employee/entities/employee_reward.json +21 -0
  543. package/src/app/routes/hr/employee/routes.ts +27 -0
  544. package/src/app/routes/hr/entities/hr_group.json +47 -0
  545. package/src/app/routes/hr/entities/hr_group_pv.json +20 -0
  546. package/src/app/routes/hr/entities/hr_role.json +43 -0
  547. package/src/app/routes/hr/entities/hr_role_pv.json +20 -0
  548. package/src/app/routes/hr/routes.ts +29 -0
  549. package/src/app/routes/messages/chat/config.json +5 -0
  550. package/src/app/routes/messages/chat/entities/user_chat.json +47 -0
  551. package/src/app/routes/messages/chat/entities/user_chat_room.json +38 -0
  552. package/src/app/routes/messages/chat/entities/user_chat_room_member.json +49 -0
  553. package/src/app/routes/messages/chat/routes.ts +28 -0
  554. package/src/app/routes/messages/msgbox/config.json +5 -0
  555. package/src/app/routes/messages/msgbox/entities/user_msgbox.json +73 -0
  556. package/src/app/routes/messages/msgbox/routes.ts +28 -0
  557. package/src/app/routes/password-reset/config.example.json +13 -0
  558. package/src/app/routes/password-reset/config.json +15 -0
  559. package/src/app/routes/password-reset/entities/account.json +13 -0
  560. package/src/app/routes/password-reset/handlers.ts +335 -0
  561. package/src/app/routes/password-reset/password-utils.ts +96 -0
  562. package/src/app/routes/password-reset/routes.ts +84 -0
  563. package/src/app/routes/password-reset/templates/password_reset.html +21 -0
  564. package/src/app/routes/password-reset/templates/password_reset_link.html +19 -0
  565. package/src/app/routes/password-reset/types/index.ts +95 -0
  566. package/src/app/routes/privilege/config.json +5 -0
  567. package/src/app/routes/privilege/entities/pv_group.json +29 -0
  568. package/src/app/routes/privilege/entities/pv_group_item.json +31 -0
  569. package/src/app/routes/privilege/entities/pv_item.json +176 -0
  570. package/src/app/routes/privilege/entities/user_pv_group.json +20 -0
  571. package/src/app/routes/privilege/entities/user_pv_item.json +20 -0
  572. package/src/app/routes/privilege/routes.ts +33 -0
  573. package/src/app/routes/user/config.json +5 -0
  574. package/src/app/routes/user/entities/user.json +64 -0
  575. package/src/app/routes/user/entities/user_biometric.json +28 -0
  576. package/src/app/routes/user/routes.ts +27 -0
  577. package/src/app/routes/vessel-tracking/config.json +3 -0
  578. package/src/app/routes/vessel-tracking/entities/tracked_vessel.json +261 -0
  579. package/src/app/routes/vessel-tracking/handlers.ts +134 -0
  580. package/src/app/routes/vessel-tracking/routes.ts +25 -0
  581. package/src/app/routes/vessel-tracking/types/index.ts +5 -0
  582. package/src/app/routes/vessel-tracking/types/vessel.ts +59 -0
  583. package/src/app/schedules/README.md +105 -0
  584. package/src/app/schedules/ais_sync/config.json +4 -0
  585. package/src/app/schedules/ais_sync/index.ts +69 -0
  586. package/src/app/schedules/data-retention/config.json +9 -0
  587. package/src/app/schedules/data-retention/index.ts +238 -0
  588. package/src/app/schedules/dormancy/config.json +15 -0
  589. package/src/app/schedules/dormancy/entities/account.json +14 -0
  590. package/src/app/schedules/dormancy/entities/privacy_cron_lock.json +23 -0
  591. package/src/app/schedules/dormancy/index.ts +289 -0
  592. package/src/app/schedules/dormancy/templates/dormancy_completed.html +21 -0
  593. package/src/app/schedules/dormancy/templates/dormancy_warning.html +20 -0
  594. package/src/app/schedules/kobc_freight_sync/config.json +4 -0
  595. package/src/app/schedules/kobc_freight_sync/index.ts +94 -0
  596. package/src/app/schedules/vessel_kr_sync/config.json +4 -0
  597. package/src/app/schedules/vessel_kr_sync/index.ts +72 -0
  598. package/src/system/app.ts +129 -0
  599. package/src/system/cache/_store-ref.ts +15 -0
  600. package/src/system/cache/config.ts +61 -0
  601. package/src/system/cache/drivers/memcached.ts +135 -0
  602. package/src/system/cache/drivers/memory.ts +92 -0
  603. package/src/system/cache/drivers/redis.ts +109 -0
  604. package/src/system/cache/index.ts +43 -0
  605. package/src/system/cache/namespaced.ts +79 -0
  606. package/src/system/cache/plugin.ts +59 -0
  607. package/src/system/cache/types.ts +81 -0
  608. package/src/system/config/config-path.ts +20 -0
  609. package/src/system/config/cors.ts +49 -0
  610. package/src/system/config/database.ts +190 -0
  611. package/src/system/config/entity-server.ts +8 -0
  612. package/src/system/config/env-substitution.ts +4 -0
  613. package/src/system/config/env.ts +30 -0
  614. package/src/system/config/json-config.ts +13 -0
  615. package/src/system/config/module-path.ts +16 -0
  616. package/src/system/config/packet-encrypt.ts +80 -0
  617. package/src/system/config/rate-limit.ts +4 -0
  618. package/src/system/config/security-loader.ts +25 -0
  619. package/src/system/config/security.ts +16 -0
  620. package/src/system/config/server.ts +81 -0
  621. package/src/system/crypto/cipher.ts +117 -0
  622. package/src/system/crypto/data-encrypt.ts +174 -0
  623. package/src/system/crypto/hash.ts +24 -0
  624. package/src/system/crypto/packet.test.ts +23 -0
  625. package/src/system/crypto/packet.ts +97 -0
  626. package/src/system/crypto/random.ts +19 -0
  627. package/src/system/email/sender.ts +85 -0
  628. package/src/system/email/template-engine.ts +147 -0
  629. package/src/system/entity-server/bootstrap.ts +270 -0
  630. package/src/system/entity-server/client.ts +64 -0
  631. package/src/system/hooks/loader.ts +32 -0
  632. package/src/system/hooks/runner.ts +159 -0
  633. package/src/system/hooks/types.ts +75 -0
  634. package/src/system/hooks/withdraw-hooks.ts +42 -0
  635. package/src/system/http/cookie.ts +62 -0
  636. package/src/system/http/response.ts +16 -0
  637. package/src/system/index.ts +48 -0
  638. package/src/system/logging/log-format.ts +50 -0
  639. package/src/system/logging/logger.ts +104 -0
  640. package/src/system/middleware/_db-ref.ts +26 -0
  641. package/src/system/middleware/_push-ref.ts +28 -0
  642. package/src/system/middleware/access-log.ts +34 -0
  643. package/src/system/middleware/auth.ts +67 -0
  644. package/src/system/middleware/csrf.ts +172 -0
  645. package/src/system/middleware/database.ts +44 -0
  646. package/src/system/middleware/error-handler.ts +51 -0
  647. package/src/system/middleware/extension-loader.ts +111 -0
  648. package/src/system/middleware/packet-encrypt.ts +281 -0
  649. package/src/system/middleware/request-id.ts +18 -0
  650. package/src/system/plugins/access-log.ts +34 -0
  651. package/src/system/plugins/packet-encrypt.ts +281 -0
  652. package/src/system/proxy/register.ts +37 -0
  653. package/src/system/public-api.ts +140 -0
  654. package/src/system/push/sender.ts +131 -0
  655. package/src/system/routes/entity-interceptor.ts +327 -0
  656. package/src/system/routes/loader.ts +215 -0
  657. package/src/system/scheduler/cron-utils.ts +150 -0
  658. package/src/system/scheduler/distributed-lock.ts +141 -0
  659. package/src/system/scheduler/schedule-loader.ts +105 -0
  660. package/src/system/security/anonymous-device-id.ts +41 -0
  661. package/src/system/security/anonymous-device.ts +98 -0
  662. package/src/system/security/anonymous-packet-token.ts +23 -0
  663. package/src/system/security/packet-bootstrap.ts +16 -0
  664. package/src/system/security/password-policy.ts +191 -0
  665. package/src/system/startup-banner.ts +191 -0
  666. package/src/system/types/fastify.d.ts +53 -0
  667. package/src/system/utils/app-path.ts +31 -0
  668. package/src/system/utils/coerce.ts +28 -0
  669. package/src/system/utils/date-prefixed-log-stream.ts +176 -0
  670. package/src/system/utils/errors.ts +66 -0
  671. package/src/system/utils/format.ts +45 -0
  672. package/src/system/utils/http-client.ts +79 -0
  673. package/src/system/utils/user-agent.ts +82 -0
  674. package/tsconfig.app.json +17 -0
  675. package/tsconfig.json +39 -0
@@ -0,0 +1,965 @@
1
+ /**
2
+ * LLM Service — 프로바이더 풀 관리 + Chat/Stream/Embed/Session/RAG
3
+ *
4
+ * Go entity-server internal/llm/service.go + chat.go + session.go + embed.go + rag.go 기반 포팅
5
+ */
6
+
7
+ import { logger } from "@gateway/api";
8
+ import type {
9
+ LlmConfig,
10
+ LlmProviderConfig,
11
+ Provider,
12
+ RateLimiter,
13
+ LlmClient,
14
+ ChatRequest,
15
+ ChatResponse,
16
+ ChatOption,
17
+ StreamChunk,
18
+ TokenUsage,
19
+ EmbedResponse,
20
+ Message,
21
+ ConversationStore,
22
+ ConversationResponse,
23
+ DocumentStore,
24
+ RAGOptions,
25
+ RAGResponse,
26
+ SearchResult,
27
+ UsageQuerier,
28
+ LlmUsageRecord,
29
+ ProfileStore,
30
+ } from "./types/index.ts";
31
+ import type { ChatbotStore, ChatbotChatResponse } from "./types/chatbot.ts";
32
+ import { createClient } from "./providers/index.ts";
33
+ import {
34
+ CacheStats,
35
+ MemoryCacheStore,
36
+ generateCacheKey,
37
+ type CacheKeyInput,
38
+ } from "./cache.ts";
39
+ import {
40
+ loadTemplate,
41
+ listTemplates,
42
+ renderTemplate,
43
+ validateVars,
44
+ type LlmPromptTemplate,
45
+ type RenderedTemplate,
46
+ } from "./template-loader.ts";
47
+
48
+ // ─── Token-Bucket Rate Limiter ───────────────────────────────────────────────
49
+
50
+ class TokenBucketLimiter implements RateLimiter {
51
+ private tokens: number;
52
+ private lastRefill: number;
53
+ private readonly maxTokens: number;
54
+ private readonly refillRate: number; // tokens per ms
55
+
56
+ /** TokenBucketLimiter를 초기화한다 */
57
+ constructor(rpm: number) {
58
+ this.maxTokens = rpm;
59
+ this.tokens = rpm;
60
+ this.refillRate = rpm / 60_000;
61
+ this.lastRefill = Date.now();
62
+ }
63
+
64
+ /** 토큰 확보를 시도한다 */
65
+ tryAcquire(): boolean {
66
+ this.refill();
67
+ if (this.tokens >= 1) {
68
+ this.tokens -= 1;
69
+ return true;
70
+ }
71
+ return false;
72
+ }
73
+
74
+ /** 토큰을 보충한다 */
75
+ private refill(): void {
76
+ const now = Date.now();
77
+ const elapsed = now - this.lastRefill;
78
+ this.tokens = Math.min(
79
+ this.maxTokens,
80
+ this.tokens + elapsed * this.refillRate,
81
+ );
82
+ this.lastRefill = now;
83
+ }
84
+ }
85
+
86
+ class InfiniteRateLimiter implements RateLimiter {
87
+ /** 항상 허용하는 무제한 리밋터 */
88
+ tryAcquire(): boolean {
89
+ return true;
90
+ }
91
+ }
92
+
93
+ // ─── Service ─────────────────────────────────────────────────────────────────
94
+
95
+ export class LlmService {
96
+ private readonly config: LlmConfig;
97
+ private readonly providers: Map<string, Provider>;
98
+ private cache: MemoryCacheStore | null = null;
99
+ private readonly cacheStats = new CacheStats();
100
+
101
+ /** 외부에서 주입 */
102
+ convStore: ConversationStore | null = null;
103
+ docStore: DocumentStore | null = null;
104
+ usageQuerier: UsageQuerier | null = null;
105
+ chatbotStore: ChatbotStore | null = null;
106
+ profileStore: ProfileStore | null = null;
107
+
108
+ /** LlmService를 설정과 프로바이더 클라이언트로 초기화한다 */
109
+ constructor(config: LlmConfig) {
110
+ this.config = config;
111
+ this.providers = new Map();
112
+
113
+ // 프로바이더 초기화
114
+ for (const [name, cfg] of Object.entries(config.providers)) {
115
+ try {
116
+ const client = createClient(cfg);
117
+ const rpm = cfg.rate_limit_rpm ?? 0;
118
+ const limiter: RateLimiter =
119
+ rpm > 0
120
+ ? new TokenBucketLimiter(rpm)
121
+ : new InfiniteRateLimiter();
122
+
123
+ this.providers.set(name, {
124
+ name,
125
+ client,
126
+ config: cfg,
127
+ rateLimiter: limiter,
128
+ });
129
+ logger.info(
130
+ `LLM provider registered: ${name} (${cfg.driver}/${cfg.model})`,
131
+ );
132
+ } catch (err) {
133
+ logger.error({ err }, `Failed to create LLM provider: ${name}`);
134
+ }
135
+ }
136
+
137
+ // 캐시 초기화
138
+ if (config.cache?.enabled) {
139
+ this.cache = new MemoryCacheStore(config.cache.max_entries);
140
+ logger.info(
141
+ "LLM response cache enabled (TTL=%ds)",
142
+ config.cache.ttl_seconds,
143
+ );
144
+ }
145
+ }
146
+
147
+ // ─── Getters ─────────────────────────────────────────────────────────
148
+
149
+ /** LLM 설정을 반환한다 */
150
+ getConfig(): LlmConfig {
151
+ return this.config;
152
+ }
153
+
154
+ /** 등록된 프로바이더 맵을 반환한다 */
155
+ getProviders(): Map<string, Provider> {
156
+ return this.providers;
157
+ }
158
+
159
+ /** 기본 프로바이더 이름을 반환한다 */
160
+ defaultProviderName(): string {
161
+ return this.config.default;
162
+ }
163
+
164
+ /** 이름으로 프로바이더를 조회한다 */
165
+ private getProvider(name?: string): Provider {
166
+ const key = name || this.config.default;
167
+ const p = this.providers.get(key);
168
+ if (!p) throw new Error(`LLM provider "${key}" not found`);
169
+ return p;
170
+ }
171
+
172
+ // ─── Chat ────────────────────────────────────────────────────────────
173
+
174
+ /** 채팅 완성을 실행한다 */
175
+ async chat(
176
+ providerName: string | undefined,
177
+ req: ChatRequest,
178
+ ...opts: ChatOption[]
179
+ ): Promise<ChatResponse> {
180
+ for (const o of opts) o(req);
181
+
182
+ const provider = this.getProvider(providerName);
183
+
184
+ // 캐시 조회
185
+ let cacheKey: string | null = null;
186
+ if (this.cache && this.config.cache?.enabled) {
187
+ const excluded = this.config.cache.exclude_providers?.includes(
188
+ provider.name,
189
+ );
190
+ if (!excluded) {
191
+ cacheKey = generateCacheKey({
192
+ provider: provider.name,
193
+ model: provider.config.model,
194
+ messages: req.messages,
195
+ system: req.system,
196
+ temperature: req.temperature,
197
+ maxTokens: req.maxTokens,
198
+ jsonMode: req.jsonMode,
199
+ });
200
+
201
+ const cached = this.cache.get(cacheKey);
202
+ if (cached.found) {
203
+ try {
204
+ const resp: ChatResponse = JSON.parse(cached.value);
205
+ resp.cached = true;
206
+ this.cacheStats.recordHit();
207
+ return resp;
208
+ } catch {
209
+ /* parse 실패 → 캐시 미스 처리 */
210
+ }
211
+ }
212
+ this.cacheStats.recordMiss();
213
+ }
214
+ }
215
+
216
+ // Rate limit
217
+ if (!provider.rateLimiter.tryAcquire()) {
218
+ throw new Error(
219
+ `LLM rate limit exceeded for provider "${provider.name}"`,
220
+ );
221
+ }
222
+
223
+ const start = Date.now();
224
+ try {
225
+ const resp = await provider.client.chat(req);
226
+ const elapsed = Date.now() - start;
227
+
228
+ // 비동기 사용량 기록
229
+ this.recordUsageAsync(
230
+ provider.name,
231
+ provider.config.model,
232
+ resp,
233
+ elapsed,
234
+ "success",
235
+ );
236
+
237
+ // 캐시 저장
238
+ if (cacheKey && resp.finishReason === "stop") {
239
+ const ttlMs = (this.config.cache?.ttl_seconds ?? 3600) * 1000;
240
+ this.cache!.set(cacheKey, JSON.stringify(resp), ttlMs);
241
+ }
242
+
243
+ return resp;
244
+ } catch (err) {
245
+ const elapsed = Date.now() - start;
246
+ this.recordUsageAsync(
247
+ provider.name,
248
+ provider.config.model,
249
+ null,
250
+ elapsed,
251
+ "error",
252
+ );
253
+ throw err;
254
+ }
255
+ }
256
+
257
+ // ─── Chat Stream ─────────────────────────────────────────────────────
258
+
259
+ /** 스트리밍 채팅을 실행한다 */
260
+ async *chatStream(
261
+ providerName: string | undefined,
262
+ req: ChatRequest,
263
+ ...opts: ChatOption[]
264
+ ): AsyncGenerator<StreamChunk> {
265
+ for (const o of opts) o(req);
266
+
267
+ const provider = this.getProvider(providerName);
268
+
269
+ if (!provider.rateLimiter.tryAcquire()) {
270
+ throw new Error(
271
+ `LLM rate limit exceeded for provider "${provider.name}"`,
272
+ );
273
+ }
274
+
275
+ const stream = provider.client.chatStream(req);
276
+ let lastUsage: TokenUsage | undefined;
277
+
278
+ for await (const chunk of stream) {
279
+ if (chunk.usage) lastUsage = chunk.usage;
280
+ yield chunk;
281
+ if (chunk.done) break;
282
+ }
283
+
284
+ // 스트리밍 완료 후 사용량 기록
285
+ if (lastUsage) {
286
+ this.recordUsageFromTokensAsync(
287
+ provider.name,
288
+ provider.config.model,
289
+ lastUsage,
290
+ "success",
291
+ );
292
+ }
293
+ }
294
+
295
+ // ─── Simple Chat ─────────────────────────────────────────────────────
296
+
297
+ /** 단일 메시지로 간편 채팅한다 */
298
+ async simpleChat(
299
+ providerName: string | undefined,
300
+ system: string,
301
+ user: string,
302
+ ...opts: ChatOption[]
303
+ ): Promise<string> {
304
+ const req: ChatRequest = {
305
+ system,
306
+ messages: [{ role: "user", content: user }],
307
+ };
308
+ const resp = await this.chat(providerName, req, ...opts);
309
+ return resp.content;
310
+ }
311
+
312
+ // ─── Template Chat ────────────────────────────────────────────────────
313
+
314
+ /**
315
+ * 프롬프트 템플릿을 로드해 변수를 주입하고 chat을 실행한다.
316
+ *
317
+ * @param templateName templates/llm/prompts/{name}.json 의 name
318
+ * @param vars {{variable}} 치환에 사용할 변수 맵
319
+ * @param providerName 사용할 LLM 프로바이더 (생략 시 default)
320
+ * @param userMessage user_msg 템플릿을 무시하고 직접 전달할 사용자 메시지 (선택)
321
+ */
322
+ async chatWithTemplate(
323
+ templateName: string,
324
+ vars: Record<string, string>,
325
+ providerName?: string,
326
+ userMessage?: string,
327
+ ): Promise<{
328
+ content: string;
329
+ model: string;
330
+ template: string;
331
+ missing?: string[];
332
+ }> {
333
+ const tpl = loadTemplate(templateName);
334
+ if (!tpl) throw new Error(`LLM template "${templateName}" not found`);
335
+
336
+ const missing = validateVars(tpl, vars);
337
+ const rendered = renderTemplate(tpl, vars);
338
+
339
+ const userContent = userMessage ?? rendered.userMsg;
340
+ if (!userContent) {
341
+ throw new Error(
342
+ `Template "${templateName}" has no user_msg — provide "message" in request body`,
343
+ );
344
+ }
345
+
346
+ const req: ChatRequest = {
347
+ system: rendered.system,
348
+ messages: [{ role: "user", content: userContent }],
349
+ maxTokens: rendered.maxTokens,
350
+ temperature: rendered.temperature,
351
+ };
352
+
353
+ const resp = await this.chat(providerName, req);
354
+ return {
355
+ content: resp.content,
356
+ model: resp.model ?? "",
357
+ template: templateName,
358
+ missing: missing.length > 0 ? missing : undefined,
359
+ };
360
+ }
361
+
362
+ /**
363
+ * 프롬프트 템플릿 기반 스트리밍 채팅을 실행한다.
364
+ */
365
+ async *chatStreamWithTemplate(
366
+ templateName: string,
367
+ vars: Record<string, string>,
368
+ providerName?: string,
369
+ userMessage?: string,
370
+ ): AsyncGenerator<StreamChunk> {
371
+ const tpl = loadTemplate(templateName);
372
+ if (!tpl) throw new Error(`LLM template "${templateName}" not found`);
373
+
374
+ const rendered = renderTemplate(tpl, vars);
375
+ const userContent = userMessage ?? rendered.userMsg;
376
+ if (!userContent) {
377
+ throw new Error(
378
+ `Template "${templateName}" has no user_msg — provide "message" in request body`,
379
+ );
380
+ }
381
+
382
+ const req: ChatRequest = {
383
+ system: rendered.system,
384
+ messages: [{ role: "user", content: userContent }],
385
+ maxTokens: rendered.maxTokens,
386
+ temperature: rendered.temperature,
387
+ };
388
+
389
+ yield* this.chatStream(providerName, req);
390
+ }
391
+
392
+ /**
393
+ * 사용 가능한 템플릿 목록을 반환한다.
394
+ */
395
+ getTemplateList(): Array<{
396
+ name: string;
397
+ label?: string;
398
+ variables?: string[];
399
+ }> {
400
+ return listTemplates().map((name) => {
401
+ const tpl = loadTemplate(name);
402
+ return {
403
+ name,
404
+ label: tpl?.label,
405
+ variables: tpl?.variables,
406
+ };
407
+ });
408
+ }
409
+
410
+ // ─── Embed ───────────────────────────────────────────────────────────
411
+
412
+ /** 텍스트 임베딩을 실행한다 */
413
+ async embed(
414
+ providerName: string | undefined,
415
+ input: string[],
416
+ ): Promise<EmbedResponse> {
417
+ const provider = this.getProvider(providerName);
418
+ if (!provider.rateLimiter.tryAcquire()) {
419
+ throw new Error(
420
+ `LLM rate limit exceeded for provider "${provider.name}"`,
421
+ );
422
+ }
423
+
424
+ return provider.client.embed({
425
+ input,
426
+ model: provider.config.embed_model || provider.config.model,
427
+ });
428
+ }
429
+
430
+ /** 단일 텍스트의 임베딩 벡터를 반환한다 */
431
+ async embedOne(
432
+ providerName: string | undefined,
433
+ text: string,
434
+ ): Promise<number[]> {
435
+ const resp = await this.embed(providerName, [text]);
436
+ if (resp.embeddings.length === 0)
437
+ throw new Error("No embedding returned");
438
+ return resp.embeddings[0];
439
+ }
440
+
441
+ // ─── Session Chat ────────────────────────────────────────────────────
442
+
443
+ /** 대화 세션 컨텍스트로 채팅한다 */
444
+ async chatInSession(
445
+ providerName: string | undefined,
446
+ conversationSeq: number,
447
+ userMsg: string,
448
+ userSeq?: number,
449
+ ...opts: ChatOption[]
450
+ ): Promise<ConversationResponse> {
451
+ if (!this.convStore)
452
+ throw new Error("Conversation store not configured");
453
+
454
+ const provider = this.getProvider(providerName);
455
+ if (!provider.rateLimiter.tryAcquire()) {
456
+ throw new Error(
457
+ `LLM rate limit exceeded for provider "${provider.name}"`,
458
+ );
459
+ }
460
+
461
+ let messages: Message[] = [];
462
+ let systemMsg = "";
463
+ let convSeq = conversationSeq;
464
+
465
+ if (conversationSeq > 0) {
466
+ // 기존 세션: 히스토리 로드
467
+ const conv = await this.convStore.getConversation(conversationSeq);
468
+ messages = conv.messages;
469
+ systemMsg = conv.systemMsg ?? "";
470
+ } else {
471
+ // 새 세션 생성
472
+ convSeq = await this.convStore.createConversation({
473
+ providerName: provider.name,
474
+ title: truncate(userMsg, 100),
475
+ userSeq,
476
+ });
477
+ }
478
+
479
+ messages.push({ role: "user", content: userMsg });
480
+
481
+ // Profile Memory 주입
482
+ if (this.profileStore && userSeq) {
483
+ const profileText = await this.profileStore
484
+ .formatForPrompt({ userSeq })
485
+ .catch(() => "");
486
+ if (profileText) {
487
+ systemMsg = systemMsg
488
+ ? `${systemMsg}\n\n${profileText}`
489
+ : profileText;
490
+ }
491
+ }
492
+
493
+ const req: ChatRequest = {
494
+ system: systemMsg,
495
+ messages,
496
+ maxTokens: provider.config.max_tokens,
497
+ temperature: provider.config.temperature,
498
+ };
499
+ for (const o of opts) o(req);
500
+
501
+ const start = Date.now();
502
+ const resp = await provider.client.chat(req);
503
+ const elapsed = Date.now() - start;
504
+
505
+ const newMessages: Message[] = [
506
+ { role: "user", content: userMsg },
507
+ { role: "assistant", content: resp.content },
508
+ ];
509
+
510
+ // 비동기 히스토리 저장
511
+ this.convStore
512
+ .appendMessages(convSeq, newMessages, resp.usage)
513
+ .catch((err) =>
514
+ logger.error({ err }, "Failed to append conversation messages"),
515
+ );
516
+
517
+ // 비동기 사용량 기록
518
+ this.recordUsageAsync(
519
+ provider.name,
520
+ provider.config.model,
521
+ resp,
522
+ elapsed,
523
+ "success",
524
+ );
525
+
526
+ return {
527
+ conversationSeq: convSeq,
528
+ content: resp.content,
529
+ finishReason: resp.finishReason,
530
+ usage: resp.usage,
531
+ model: resp.model,
532
+ };
533
+ }
534
+
535
+ // ─── RAG Chat ────────────────────────────────────────────────────────
536
+
537
+ /** RAG 기반 채팅을 실행한다 */
538
+ async chatWithRAG(
539
+ providerName: string | undefined,
540
+ userMsg: string,
541
+ opts?: RAGOptions,
542
+ ): Promise<RAGResponse> {
543
+ if (!this.docStore) throw new Error("Document store not configured");
544
+
545
+ const _opts = opts ?? {};
546
+ const embedProvider = _opts.embedProvider || providerName;
547
+ const topK = _opts.topK || 5;
548
+ const minScore = _opts.minScore || 0.7;
549
+
550
+ // 유사 문서 검색
551
+ const results = await this.docStore.searchSimilar({
552
+ query: userMsg,
553
+ providerName: embedProvider,
554
+ topK,
555
+ minScore,
556
+ tenantId: _opts.tenantId,
557
+ metadata: _opts.metadata,
558
+ });
559
+
560
+ // 시스템 프롬프트 조립
561
+ let systemMsg = _opts.systemMsg || DEFAULT_RAG_SYSTEM_PROMPT;
562
+ if (results.length > 0) {
563
+ systemMsg += "\n\n[참고 자료]\n" + buildRAGContext(results);
564
+ }
565
+
566
+ const req: ChatRequest = {
567
+ system: systemMsg,
568
+ messages: [{ role: "user", content: userMsg }],
569
+ };
570
+
571
+ const resp = await this.chat(providerName, req);
572
+
573
+ return {
574
+ content: resp.content,
575
+ finishReason: resp.finishReason,
576
+ usage: resp.usage,
577
+ model: resp.model,
578
+ sources: results,
579
+ };
580
+ }
581
+
582
+ // ─── Chatbot Chat ─────────────────────────────────────────────────────
583
+
584
+ /**
585
+ * 챗봇과 대화한다 (RAG + 히스토리 통합).
586
+ *
587
+ * @param chatbotSeq llm_chatbot.seq
588
+ * @param userMsg 사용자 메시지
589
+ * @param sessionSeq 기존 세션 seq (0이면 신규 생성)
590
+ * @param userSeq 로그인 사용자 seq (선택)
591
+ * @param sessionId 비로그인 세션 식별자 (선택)
592
+ */
593
+ async chatWithBot(
594
+ chatbotSeq: number,
595
+ userMsg: string,
596
+ sessionSeq: number,
597
+ userSeq?: number,
598
+ sessionId?: string,
599
+ ): Promise<ChatbotChatResponse> {
600
+ if (!this.chatbotStore) throw new Error("Chatbot store not configured");
601
+
602
+ const bot = await this.chatbotStore.getChatbot(chatbotSeq);
603
+ if (bot.status !== "active")
604
+ throw new Error(`Chatbot "${bot.name}" is not active`);
605
+
606
+ const providerName = bot.providerName || undefined;
607
+ const provider = this.getProvider(providerName);
608
+
609
+ // Rate limit
610
+ if (!provider.rateLimiter.tryAcquire()) {
611
+ throw new Error(
612
+ `LLM rate limit exceeded for provider "${provider.name}"`,
613
+ );
614
+ }
615
+
616
+ // 세션 로드 또는 신규 생성
617
+ let curSessionSeq = sessionSeq;
618
+ let history: Message[] = [];
619
+ const isNewSession = sessionSeq <= 0;
620
+
621
+ if (!isNewSession) {
622
+ const session =
623
+ await this.chatbotStore.getSessionMessages(curSessionSeq);
624
+ history = session.messages;
625
+ } else {
626
+ curSessionSeq = await this.chatbotStore.createSession(
627
+ chatbotSeq,
628
+ provider.name,
629
+ truncate(userMsg, 80),
630
+ userSeq,
631
+ sessionId,
632
+ bot.systemMsg ?? undefined,
633
+ );
634
+ }
635
+
636
+ // Profile Memory 주입
637
+ let profileInjection = "";
638
+ if (this.profileStore && userSeq) {
639
+ profileInjection = await this.profileStore
640
+ .formatForPrompt({
641
+ userSeq,
642
+ chatbotSeq,
643
+ scope: `chatbot_${chatbotSeq}`,
644
+ })
645
+ .catch(() => "");
646
+ if (!profileInjection) {
647
+ profileInjection = await this.profileStore
648
+ .formatForPrompt({ userSeq })
649
+ .catch(() => "");
650
+ }
651
+ }
652
+
653
+ // RAG 컨텍스트 조립
654
+ let systemMsg = bot.systemMsg ?? "";
655
+ if (profileInjection) {
656
+ systemMsg = systemMsg
657
+ ? `${systemMsg}\n\n${profileInjection}`
658
+ : profileInjection;
659
+ }
660
+ let ragSources: SearchResult[] | undefined;
661
+ if (bot.ragEnabled && this.docStore) {
662
+ ragSources = await this.docStore.searchSimilar({
663
+ query: userMsg,
664
+ providerName,
665
+ topK: bot.ragTopK ?? 5,
666
+ minScore: bot.ragMinScore ?? 0.7,
667
+ tenantId: bot.ragTenantId ?? undefined,
668
+ metadata: bot.ragMetadata ?? undefined,
669
+ });
670
+ if (ragSources.length > 0) {
671
+ systemMsg += "\n\n[참고 자료]\n" + buildRAGContext(ragSources);
672
+ }
673
+ }
674
+
675
+ const messages: Message[] = [
676
+ ...history,
677
+ { role: "user", content: userMsg },
678
+ ];
679
+
680
+ const req: ChatRequest = {
681
+ system: systemMsg,
682
+ messages,
683
+ maxTokens: provider.config.max_tokens,
684
+ temperature: provider.config.temperature,
685
+ };
686
+
687
+ const start = Date.now();
688
+ const resp = await provider.client.chat(req);
689
+ const elapsed = Date.now() - start;
690
+
691
+ // 히스토리 저장 (비동기)
692
+ const newMessages: Message[] = [
693
+ { role: "user", content: userMsg },
694
+ { role: "assistant", content: resp.content },
695
+ ];
696
+ this.chatbotStore
697
+ .appendSessionMessages(curSessionSeq, newMessages, resp.usage)
698
+ .catch((err) =>
699
+ logger.error(
700
+ { err },
701
+ "Failed to append chatbot session messages",
702
+ ),
703
+ );
704
+
705
+ // 사용량 기록 (비동기)
706
+ this.recordUsageAsync(
707
+ provider.name,
708
+ provider.config.model,
709
+ resp,
710
+ elapsed,
711
+ "success",
712
+ );
713
+
714
+ return {
715
+ sessionSeq: curSessionSeq,
716
+ content: resp.content,
717
+ sources: ragSources?.length ? ragSources : undefined,
718
+ usage: resp.usage,
719
+ model: resp.model ?? "",
720
+ isNewSession,
721
+ };
722
+ }
723
+
724
+ /**
725
+ * 챗봇과 스트리밍 대화한다 (RAG + 히스토리 통합).
726
+ *
727
+ * 반환: { sessionSeq, stream }
728
+ */
729
+ async chatStreamWithBot(
730
+ chatbotSeq: number,
731
+ userMsg: string,
732
+ sessionSeq: number,
733
+ userSeq?: number,
734
+ sessionId?: string,
735
+ ): Promise<{ sessionSeq: number; stream: AsyncGenerator<StreamChunk> }> {
736
+ if (!this.chatbotStore) throw new Error("Chatbot store not configured");
737
+
738
+ const bot = await this.chatbotStore.getChatbot(chatbotSeq);
739
+ if (bot.status !== "active")
740
+ throw new Error(`Chatbot "${bot.name}" is not active`);
741
+
742
+ const providerName = bot.providerName || undefined;
743
+ const provider = this.getProvider(providerName);
744
+
745
+ if (!provider.rateLimiter.tryAcquire()) {
746
+ throw new Error(
747
+ `LLM rate limit exceeded for provider "${provider.name}"`,
748
+ );
749
+ }
750
+
751
+ let curSessionSeq = sessionSeq;
752
+ let history: Message[] = [];
753
+
754
+ if (curSessionSeq > 0) {
755
+ const session =
756
+ await this.chatbotStore.getSessionMessages(curSessionSeq);
757
+ history = session.messages;
758
+ } else {
759
+ curSessionSeq = await this.chatbotStore.createSession(
760
+ chatbotSeq,
761
+ provider.name,
762
+ truncate(userMsg, 80),
763
+ userSeq,
764
+ sessionId,
765
+ bot.systemMsg ?? undefined,
766
+ );
767
+ }
768
+
769
+ // Profile Memory 주입 (스트리밍)
770
+ let streamProfileInjection = "";
771
+ if (this.profileStore && userSeq) {
772
+ streamProfileInjection = await this.profileStore
773
+ .formatForPrompt({
774
+ userSeq,
775
+ chatbotSeq,
776
+ scope: `chatbot_${chatbotSeq}`,
777
+ })
778
+ .catch(() => "");
779
+ if (!streamProfileInjection) {
780
+ streamProfileInjection = await this.profileStore
781
+ .formatForPrompt({ userSeq })
782
+ .catch(() => "");
783
+ }
784
+ }
785
+
786
+ let systemMsg = bot.systemMsg ?? "";
787
+ if (streamProfileInjection) {
788
+ systemMsg = systemMsg
789
+ ? `${systemMsg}\n\n${streamProfileInjection}`
790
+ : streamProfileInjection;
791
+ }
792
+ if (bot.ragEnabled && this.docStore) {
793
+ const results = await this.docStore.searchSimilar({
794
+ query: userMsg,
795
+ providerName,
796
+ topK: bot.ragTopK ?? 5,
797
+ minScore: bot.ragMinScore ?? 0.7,
798
+ tenantId: bot.ragTenantId ?? undefined,
799
+ metadata: bot.ragMetadata ?? undefined,
800
+ });
801
+ if (results.length > 0) {
802
+ systemMsg += "\n\n[참고 자료]\n" + buildRAGContext(results);
803
+ }
804
+ }
805
+
806
+ const messages: Message[] = [
807
+ ...history,
808
+ { role: "user", content: userMsg },
809
+ ];
810
+
811
+ const req: ChatRequest = {
812
+ system: systemMsg,
813
+ messages,
814
+ maxTokens: provider.config.max_tokens,
815
+ temperature: provider.config.temperature,
816
+ };
817
+
818
+ const self = this;
819
+ const store = this.chatbotStore;
820
+
821
+ async function* gen(): AsyncGenerator<StreamChunk> {
822
+ let fullContent = "";
823
+ let lastUsage: import("./types/index.ts").TokenUsage | undefined;
824
+
825
+ for await (const chunk of provider.client.chatStream(req)) {
826
+ if (chunk.content) fullContent += chunk.content;
827
+ if (chunk.usage) lastUsage = chunk.usage;
828
+ yield chunk;
829
+ if (chunk.done) break;
830
+ }
831
+
832
+ // 히스토리 저장
833
+ const newMessages: Message[] = [
834
+ { role: "user", content: userMsg },
835
+ { role: "assistant", content: fullContent },
836
+ ];
837
+ store
838
+ .appendSessionMessages(curSessionSeq, newMessages, lastUsage)
839
+ .catch((err) =>
840
+ logger.error(
841
+ { err },
842
+ "Failed to append chatbot stream messages",
843
+ ),
844
+ );
845
+
846
+ // 사용량 기록
847
+ if (lastUsage) {
848
+ self.recordUsageFromTokensAsync(
849
+ provider.name,
850
+ provider.config.model,
851
+ lastUsage,
852
+ "success",
853
+ );
854
+ }
855
+ }
856
+
857
+ return { sessionSeq: curSessionSeq, stream: gen() };
858
+ }
859
+
860
+ // ─── Cache Stats ─────────────────────────────────────────────────────
861
+
862
+ /** 캐시 통계를 반환한다 */
863
+ getCacheStats(): Record<string, unknown> {
864
+ const enabled = this.config.cache?.enabled ?? false;
865
+ return {
866
+ enabled,
867
+ hits: this.cacheStats.hits,
868
+ misses: this.cacheStats.misses,
869
+ hit_rate: this.cacheStats.hitRate(),
870
+ ttl_seconds: this.config.cache?.ttl_seconds ?? 0,
871
+ };
872
+ }
873
+
874
+ /** 캐시를 비운다 */
875
+ clearCache(): void {
876
+ this.cache?.flush();
877
+ }
878
+
879
+ // ─── Cleanup ─────────────────────────────────────────────────────────
880
+
881
+ /** 모든 프로바이더 클라이언트를 정리한다 */
882
+ close(): void {
883
+ for (const p of this.providers.values()) {
884
+ p.client.close();
885
+ }
886
+ }
887
+
888
+ // ─── Private: Usage Recording ────────────────────────────────────────
889
+
890
+ /** 비동기로 사용량을 기록한다 */
891
+ private recordUsageAsync(
892
+ providerName: string,
893
+ model: string,
894
+ resp: ChatResponse | null,
895
+ elapsedMs: number,
896
+ status: string,
897
+ ): void {
898
+ if (!this.usageQuerier || !this.config.usage_tracking) return;
899
+
900
+ const record: LlmUsageRecord = {
901
+ providerName,
902
+ model,
903
+ promptTokens: resp?.usage?.promptTokens ?? 0,
904
+ completionTokens: resp?.usage?.completionTokens ?? 0,
905
+ totalTokens: resp?.usage?.totalTokens ?? 0,
906
+ requestTimeMs: elapsedMs,
907
+ status: status as LlmUsageRecord["status"],
908
+ requestedAt: new Date().toISOString(),
909
+ };
910
+
911
+ this.usageQuerier
912
+ .recordUsage(record)
913
+ .catch((err) => logger.error({ err }, "LLM usage record error"));
914
+ }
915
+
916
+ /** 토큰 사용량을 비동기로 기록한다 */
917
+ private recordUsageFromTokensAsync(
918
+ providerName: string,
919
+ model: string,
920
+ usage: TokenUsage,
921
+ status: string,
922
+ ): void {
923
+ if (!this.usageQuerier || !this.config.usage_tracking) return;
924
+
925
+ const record: LlmUsageRecord = {
926
+ providerName,
927
+ model,
928
+ promptTokens: usage.promptTokens,
929
+ completionTokens: usage.completionTokens,
930
+ totalTokens: usage.totalTokens,
931
+ requestTimeMs: 0,
932
+ status: status as LlmUsageRecord["status"],
933
+ requestedAt: new Date().toISOString(),
934
+ };
935
+
936
+ this.usageQuerier
937
+ .recordUsage(record)
938
+ .catch((err) => logger.error({ err }, "LLM usage record error"));
939
+ }
940
+ }
941
+
942
+ // ─── Constants ───────────────────────────────────────────────────────────────
943
+
944
+ const DEFAULT_RAG_SYSTEM_PROMPT = `당신은 제공된 참고 자료를 기반으로 정확하게 답변하는 AI 어시스턴트입니다.
945
+
946
+ [규칙]
947
+ 1. 참고 자료에 있는 정보만 사용하여 답변합니다.
948
+ 2. 참고 자료에 해당 정보가 없으면 솔직하게 "제공된 자료에서 해당 정보를 찾을 수 없습니다"라고 안내합니다.
949
+ 3. 한국어로 친절하게 답변합니다.`;
950
+
951
+ /** RAG 컨텍스트 문자열을 생성한다 */
952
+ function buildRAGContext(results: SearchResult[]): string {
953
+ return results
954
+ .map(
955
+ (r, i) =>
956
+ `--- 문서 ${i + 1}: ${r.title} (score: ${r.score.toFixed(2)}) ---\n${r.content}\n`,
957
+ )
958
+ .join("\n");
959
+ }
960
+
961
+ /** 문자열을 최대 길이로 자른다 */
962
+ function truncate(s: string, maxLen: number): string {
963
+ const arr = [...s];
964
+ return arr.length <= maxLen ? s : arr.slice(0, maxLen).join("");
965
+ }