@reglow/reglow 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +101 -41
  2. package/dist/reglow/core/config.js +1 -1
  3. package/dist/reglow/core/entities.d.ts +135 -0
  4. package/dist/reglow/core/models.d.ts +22 -0
  5. package/dist/reglow/core/models.js +15 -0
  6. package/dist/reglow/core/models.js.map +1 -1
  7. package/dist/reglow/core/storage.js +6 -2
  8. package/dist/reglow/core/storage.js.map +1 -1
  9. package/dist/reglow/core/tenant_context.d.ts +45 -0
  10. package/dist/reglow/core/tenant_context.js +77 -0
  11. package/dist/reglow/core/tenant_context.js.map +1 -0
  12. package/dist/reglow/core/tenant_guard.js +17 -5
  13. package/dist/reglow/core/tenant_guard.js.map +1 -1
  14. package/dist/reglow/modules/ai/controller.js +129 -0
  15. package/dist/reglow/modules/ai/controller.js.map +1 -1
  16. package/dist/reglow/modules/ai_usage/controller.d.ts +8 -0
  17. package/dist/reglow/modules/ai_usage/controller.js +278 -0
  18. package/dist/reglow/modules/ai_usage/controller.js.map +1 -0
  19. package/dist/reglow/modules/ai_usage/model.d.ts +216 -0
  20. package/dist/reglow/modules/ai_usage/model.js +25 -0
  21. package/dist/reglow/modules/ai_usage/model.js.map +1 -0
  22. package/dist/reglow/modules/ai_usage/pricing.d.ts +80 -0
  23. package/dist/reglow/modules/ai_usage/pricing.js +276 -0
  24. package/dist/reglow/modules/ai_usage/pricing.js.map +1 -0
  25. package/dist/reglow/modules/ai_usage/reconcile.d.ts +34 -0
  26. package/dist/reglow/modules/ai_usage/reconcile.js +179 -0
  27. package/dist/reglow/modules/ai_usage/reconcile.js.map +1 -0
  28. package/dist/reglow/modules/ai_usage/recorder.d.ts +14 -0
  29. package/dist/reglow/modules/ai_usage/recorder.js +227 -0
  30. package/dist/reglow/modules/ai_usage/recorder.js.map +1 -0
  31. package/dist/reglow/modules/ai_usage/router.d.ts +10 -0
  32. package/dist/reglow/modules/ai_usage/router.js +10 -0
  33. package/dist/reglow/modules/ai_usage/router.js.map +1 -0
  34. package/dist/reglow/modules/ai_usage/schema.d.ts +152 -0
  35. package/dist/reglow/modules/ai_usage/schema.js +8 -0
  36. package/dist/reglow/modules/ai_usage/schema.js.map +1 -0
  37. package/dist/reglow/modules/ai_usage/service.d.ts +40 -0
  38. package/dist/reglow/modules/ai_usage/service.js +654 -0
  39. package/dist/reglow/modules/ai_usage/service.js.map +1 -0
  40. package/dist/reglow/modules/ai_usage/sync.d.ts +98 -0
  41. package/dist/reglow/modules/ai_usage/sync.js +954 -0
  42. package/dist/reglow/modules/ai_usage/sync.js.map +1 -0
  43. package/dist/reglow/modules/ai_usage/xlsx_io.d.ts +35 -0
  44. package/dist/reglow/modules/ai_usage/xlsx_io.js +494 -0
  45. package/dist/reglow/modules/ai_usage/xlsx_io.js.map +1 -0
  46. package/dist/reglow/modules/billing/controller.d.ts +6 -0
  47. package/dist/reglow/modules/billing/controller.js +112 -0
  48. package/dist/reglow/modules/billing/controller.js.map +1 -0
  49. package/dist/reglow/modules/billing/repository.d.ts +20 -0
  50. package/dist/reglow/modules/billing/repository.js +101 -0
  51. package/dist/reglow/modules/billing/repository.js.map +1 -0
  52. package/dist/reglow/modules/billing/router.d.ts +10 -0
  53. package/dist/reglow/modules/billing/router.js +8 -0
  54. package/dist/reglow/modules/billing/router.js.map +1 -0
  55. package/dist/reglow/modules/billing/schema.d.ts +38 -0
  56. package/dist/reglow/modules/billing/schema.js +42 -0
  57. package/dist/reglow/modules/billing/schema.js.map +1 -0
  58. package/dist/reglow/modules/billing/service.d.ts +22 -0
  59. package/dist/reglow/modules/billing/service.js +179 -0
  60. package/dist/reglow/modules/billing/service.js.map +1 -0
  61. package/dist/reglow/modules/customer_service/controller.js +81 -3
  62. package/dist/reglow/modules/customer_service/controller.js.map +1 -1
  63. package/dist/reglow/modules/customer_service/repository.d.ts +9 -1
  64. package/dist/reglow/modules/customer_service/repository.js +56 -2
  65. package/dist/reglow/modules/customer_service/repository.js.map +1 -1
  66. package/dist/reglow/modules/customer_service/schema.d.ts +2 -0
  67. package/dist/reglow/modules/customer_service/schema.js +8 -0
  68. package/dist/reglow/modules/customer_service/schema.js.map +1 -1
  69. package/dist/reglow/modules/customer_service/sdk_template.html +276 -5
  70. package/dist/reglow/modules/customer_service/service.d.ts +45 -4
  71. package/dist/reglow/modules/customer_service/service.js +352 -96
  72. package/dist/reglow/modules/customer_service/service.js.map +1 -1
  73. package/dist/reglow/modules/customer_service/ws.d.ts +8 -1
  74. package/dist/reglow/modules/customer_service/ws.js +38 -1
  75. package/dist/reglow/modules/customer_service/ws.js.map +1 -1
  76. package/dist/reglow/modules/open_api/auth.d.ts +28 -0
  77. package/dist/reglow/modules/open_api/auth.js +65 -0
  78. package/dist/reglow/modules/open_api/auth.js.map +1 -0
  79. package/dist/reglow/modules/open_api/controller.d.ts +8 -0
  80. package/dist/reglow/modules/open_api/controller.js +109 -0
  81. package/dist/reglow/modules/open_api/controller.js.map +1 -0
  82. package/dist/reglow/modules/open_api/repository.d.ts +20 -0
  83. package/dist/reglow/modules/open_api/repository.js +111 -0
  84. package/dist/reglow/modules/open_api/repository.js.map +1 -0
  85. package/dist/reglow/modules/open_api/router.d.ts +10 -0
  86. package/dist/reglow/modules/open_api/router.js +8 -0
  87. package/dist/reglow/modules/open_api/router.js.map +1 -0
  88. package/dist/reglow/modules/open_api/schema.d.ts +24 -0
  89. package/dist/reglow/modules/open_api/schema.js +26 -0
  90. package/dist/reglow/modules/open_api/schema.js.map +1 -0
  91. package/dist/reglow/modules/open_api/security.d.ts +19 -0
  92. package/dist/reglow/modules/open_api/security.js +53 -0
  93. package/dist/reglow/modules/open_api/security.js.map +1 -0
  94. package/dist/reglow/modules/open_api/service.d.ts +28 -0
  95. package/dist/reglow/modules/open_api/service.js +158 -0
  96. package/dist/reglow/modules/open_api/service.js.map +1 -0
  97. package/dist/reglow/modules/principal/controller.d.ts +6 -0
  98. package/dist/reglow/modules/principal/controller.js +158 -0
  99. package/dist/reglow/modules/principal/controller.js.map +1 -0
  100. package/dist/reglow/modules/principal/repository.d.ts +20 -0
  101. package/dist/reglow/modules/principal/repository.js +76 -0
  102. package/dist/reglow/modules/principal/repository.js.map +1 -0
  103. package/dist/reglow/modules/principal/router.d.ts +9 -0
  104. package/dist/reglow/modules/principal/router.js +7 -0
  105. package/dist/reglow/modules/principal/router.js.map +1 -0
  106. package/dist/reglow/modules/principal/schema.d.ts +81 -0
  107. package/dist/reglow/modules/principal/schema.js +85 -0
  108. package/dist/reglow/modules/principal/schema.js.map +1 -0
  109. package/dist/reglow/modules/principal/service.d.ts +21 -0
  110. package/dist/reglow/modules/principal/service.js +193 -0
  111. package/dist/reglow/modules/principal/service.js.map +1 -0
  112. package/dist/reglow/modules/principal_member/controller.d.ts +6 -0
  113. package/dist/reglow/modules/principal_member/controller.js +64 -0
  114. package/dist/reglow/modules/principal_member/controller.js.map +1 -0
  115. package/dist/reglow/modules/principal_member/repository.d.ts +13 -0
  116. package/dist/reglow/modules/principal_member/repository.js +80 -0
  117. package/dist/reglow/modules/principal_member/repository.js.map +1 -0
  118. package/dist/reglow/modules/principal_member/router.d.ts +10 -0
  119. package/dist/reglow/modules/principal_member/router.js +8 -0
  120. package/dist/reglow/modules/principal_member/router.js.map +1 -0
  121. package/dist/reglow/modules/principal_member/schema.d.ts +27 -0
  122. package/dist/reglow/modules/principal_member/schema.js +28 -0
  123. package/dist/reglow/modules/principal_member/schema.js.map +1 -0
  124. package/dist/reglow/modules/principal_member/service.d.ts +16 -0
  125. package/dist/reglow/modules/principal_member/service.js +135 -0
  126. package/dist/reglow/modules/principal_member/service.js.map +1 -0
  127. package/dist/reglow/modules/studio/mcp/client.js +2 -2
  128. package/dist/reglow/modules/tenant/controller.d.ts +6 -0
  129. package/dist/reglow/modules/tenant/controller.js +99 -0
  130. package/dist/reglow/modules/tenant/controller.js.map +1 -0
  131. package/dist/reglow/modules/tenant/repository.d.ts +18 -0
  132. package/dist/reglow/modules/tenant/repository.js +71 -0
  133. package/dist/reglow/modules/tenant/repository.js.map +1 -0
  134. package/dist/reglow/modules/tenant/router.d.ts +9 -0
  135. package/dist/reglow/modules/tenant/router.js +7 -0
  136. package/dist/reglow/modules/tenant/router.js.map +1 -0
  137. package/dist/reglow/modules/tenant/schema.d.ts +33 -0
  138. package/dist/reglow/modules/tenant/schema.js +42 -0
  139. package/dist/reglow/modules/tenant/schema.js.map +1 -0
  140. package/dist/reglow/modules/tenant/service.d.ts +16 -0
  141. package/dist/reglow/modules/tenant/service.js +75 -0
  142. package/dist/reglow/modules/tenant/service.js.map +1 -0
  143. package/dist/reglow/modules/workflow/controller.d.ts +7 -0
  144. package/dist/reglow/modules/workflow/controller.js +133 -0
  145. package/dist/reglow/modules/workflow/controller.js.map +1 -0
  146. package/dist/reglow/modules/workflow/dsl.d.ts +41 -0
  147. package/dist/reglow/modules/workflow/dsl.js +173 -0
  148. package/dist/reglow/modules/workflow/dsl.js.map +1 -0
  149. package/dist/reglow/modules/workflow/model.d.ts +15 -0
  150. package/dist/reglow/modules/workflow/model.js +16 -0
  151. package/dist/reglow/modules/workflow/model.js.map +1 -0
  152. package/dist/reglow/modules/workflow/repository.d.ts +27 -0
  153. package/dist/reglow/modules/workflow/repository.js +151 -0
  154. package/dist/reglow/modules/workflow/repository.js.map +1 -0
  155. package/dist/reglow/modules/workflow/router.d.ts +10 -0
  156. package/dist/reglow/modules/workflow/router.js +8 -0
  157. package/dist/reglow/modules/workflow/router.js.map +1 -0
  158. package/dist/reglow/modules/workflow/schema.d.ts +32 -0
  159. package/dist/reglow/modules/workflow/schema.js +39 -0
  160. package/dist/reglow/modules/workflow/schema.js.map +1 -0
  161. package/dist/reglow/modules/workflow/service.d.ts +65 -0
  162. package/dist/reglow/modules/workflow/service.js +209 -0
  163. package/dist/reglow/modules/workflow/service.js.map +1 -0
  164. package/dist/reglow/scripts/init-data.js +157 -1
  165. package/dist/reglow/scripts/init-data.js.map +1 -1
  166. package/dist/reglow/scripts/schema.js +360 -0
  167. package/dist/reglow/scripts/schema.js.map +1 -1
  168. package/dist/server.js +3 -0
  169. package/dist/server.js.map +1 -1
  170. package/package.json +21 -21
@@ -19,6 +19,10 @@ import { parseDocument, splitText, SUPPORTED_EXTS } from "./document_parser.js";
19
19
  import { wsManager } from "./ws.js";
20
20
  import { resolveVisibility } from "../log/data-scope.js";
21
21
  const uploadRoot = path.resolve(process.cwd(), settings.UPLOAD_DIR);
22
+ // 单坐席默认并发会话上限(cs_agent.max_sessions 为空时生效)
23
+ const AGENT_DEFAULT_MAX_SESSIONS = 5;
24
+ // 排队/分配时单次扫描的等待会话上限
25
+ const QUEUE_SCAN_LIMIT = 200;
22
26
  const _MIME_MAP = {
23
27
  ".jpg": "image/jpeg",
24
28
  ".jpeg": "image/jpeg",
@@ -282,6 +286,7 @@ function toSessionDto(s) {
282
286
  status: s.status ?? 0,
283
287
  agent_id: s.agent_id ?? null,
284
288
  agent_name: null,
289
+ agent_avatar: null,
285
290
  message_count: s.message_count ?? 0,
286
291
  summary: s.summary ?? null,
287
292
  emotion: s.emotion ?? null,
@@ -300,6 +305,7 @@ function toAgentDto(a) {
300
305
  enabled: a.enabled ?? 1,
301
306
  status: a.status ?? "offline",
302
307
  last_active_at: a.last_active_at ?? null,
308
+ max_sessions: a.max_sessions ?? null,
303
309
  created_at: a.created_at ?? null,
304
310
  }, ["last_active_at", "created_at"]);
305
311
  }
@@ -345,6 +351,12 @@ function toMessageDto(m) {
345
351
  image_url: imageUrl,
346
352
  }, ["created_at"]);
347
353
  }
354
+ /** 排队位次文案:位次 1(无人在前)与其余情况区分 */
355
+ function queueMessage(ahead) {
356
+ if (ahead <= 0)
357
+ return "正在为您安排人工坐席,请稍候";
358
+ return `当前咨询人数较多,您前面还有 ${ahead} 位,请稍候`;
359
+ }
348
360
  export class CSService {
349
361
  repo = new CSRepository();
350
362
  // ─── 配置管理 ───
@@ -580,6 +592,7 @@ export class CSService {
580
592
  display_name: displayName,
581
593
  avatar: data.avatar ?? null,
582
594
  agent_key: agentKey,
595
+ max_sessions: data.max_sessions ?? null,
583
596
  });
584
597
  return toAgentDto(agent);
585
598
  }
@@ -593,6 +606,9 @@ export class CSService {
593
606
  if (v !== undefined && v !== null)
594
607
  updateData[f] = v;
595
608
  }
609
+ if (data.max_sessions !== undefined && data.max_sessions !== null) {
610
+ updateData.max_sessions = data.max_sessions;
611
+ }
596
612
  if (updateData.agent_key) {
597
613
  const dup = await this.repo.findAgentByAgentKeyAny(String(updateData.agent_key));
598
614
  if (dup && dup.id !== agentId) {
@@ -600,6 +616,15 @@ export class CSService {
600
616
  }
601
617
  }
602
618
  const updated = await this.repo.updateAgent(agentId, updateData);
619
+ // 容量调大后立刻派单,避免排队客户继续空等
620
+ if ("max_sessions" in updateData) {
621
+ try {
622
+ await this.dispatchQueue();
623
+ }
624
+ catch (e) {
625
+ logger.error(`坐席容量调整后派单失败 agent_id=${agentId}: ${e.message}`);
626
+ }
627
+ }
603
628
  return toAgentDto(updated);
604
629
  }
605
630
  async deleteAgent(agentId) {
@@ -642,7 +667,7 @@ export class CSService {
642
667
  last_agent_active_at: new Date(),
643
668
  });
644
669
  session = (await this.repo.findSessionByPk(session.id));
645
- const history = await this.repo.listMessages(session.id, 20);
670
+ const history = await this._messagesWithCarry(session, 20);
646
671
  await wsManager.sendToAgent(agent.id, {
647
672
  type: "session_assigned",
648
673
  session_id: session.session_id,
@@ -674,64 +699,202 @@ export class CSService {
674
699
  if (online) {
675
700
  await store.setJson(csAgentOnlineKey(agentId), { at: Math.floor(Date.now() / 1000) }, 45);
676
701
  await this.repo.setAgentOnlineStatus(agentId, "online", new Date());
702
+ // 上线后按容量把排队会话派给所有可用坐席(FIFO)
677
703
  try {
678
- await this._assignWaitingSessions(agentId);
704
+ await this.dispatchQueue();
679
705
  }
680
706
  catch (e) {
681
- logger.error(`坐席上线自动接管失败 agent_id=${agentId}: ${e.message}`);
707
+ logger.error(`坐席上线派单失败 agent_id=${agentId}: ${e.message}`);
682
708
  }
683
709
  }
684
710
  else {
685
- await store.delete(csAgentOnlineKey(agentId));
686
- await this.repo.setAgentOnlineStatus(agentId, "offline");
711
+ // 下线不删除心跳、不直接置离线:以 Redis 心跳 45s TTL 自然过期为准,
712
+ // 再由 30s 校正器把 DB 状态改为 offline(多实例/多标签页互不误判)。
713
+ logger.debug(`坐席 WS 断开 agent_id=${agentId}:等待心跳过期后校正为离线`);
687
714
  }
688
715
  }
689
716
  async agentPing(agentId) {
690
717
  await getRedisStore().setJson(csAgentOnlineKey(agentId), { at: Math.floor(Date.now() / 1000) }, 45);
691
718
  await this.repo.setAgentOnlineStatus(agentId, "online", new Date());
692
719
  }
720
+ /**
721
+ * 在线校正:DB=online 但心跳缺失的坐席置离线(多实例可同时执行,幂等)。
722
+ * Redis 不可用时跳过,避免把全部坐席误判离线。
723
+ */
724
+ async reconcileOnlineAgents() {
725
+ const store = getRedisStore();
726
+ const { items } = await this.repo.listAgents(1, 500);
727
+ const stale = [];
728
+ for (const a of items) {
729
+ if (a.status !== "online")
730
+ continue;
731
+ const alive = await store.exists(csAgentOnlineKey(a.id));
732
+ if (alive)
733
+ continue;
734
+ // exists 失败与 key 不存在都返回 false:用 ping 区分 Redis 故障
735
+ if (!(await store.ping()))
736
+ return 0;
737
+ stale.push(a);
738
+ }
739
+ for (const a of stale) {
740
+ await this.repo.setAgentOnlineStatus(a.id, "offline");
741
+ }
742
+ return stale.length;
743
+ }
693
744
  async requireAgentByEmployee(employeeId) {
694
745
  const agent = await this.repo.findAgentByEmployeeId(employeeId);
695
746
  if (!agent)
696
747
  throw new AppException(ErrorCode.PARAM_ERROR, "当前账号未绑定坐席,请联系管理员", 403);
697
748
  return agent;
698
749
  }
699
- async _assignWaitingSessions(agentId, maxCount = 5) {
700
- const agent = await this.repo.findAgentById(agentId);
701
- if (!agent)
702
- return;
703
- const { items } = await this.repo.listWaitingSessions(1, maxCount);
750
+ async _agentCapacity(agent) {
751
+ const value = agent.max_sessions ?? 0;
752
+ return value > 0 ? value : AGENT_DEFAULT_MAX_SESSIONS;
753
+ }
754
+ /** 坐席当前进行中会话数(实时统计,不落库避免多实例漂移) */
755
+ async _agentActiveCount(agentId) {
756
+ return this.repo.countActiveSessionsByAgent(agentId);
757
+ }
758
+ async _agentHasCapacity(agent) {
759
+ return ((await this._agentActiveCount(agent.id)) <
760
+ (await this._agentCapacity(agent)));
761
+ }
762
+ /** 所有已启用且在线的坐席(心跳优先,Redis 故障时降级信任 DB) */
763
+ async _onlineAgents() {
764
+ const { items } = await this.repo.listAgents(1, QUEUE_SCAN_LIMIT);
765
+ const result = [];
766
+ for (const a of items) {
767
+ if (await this._agentIsOnline(a))
768
+ result.push(a);
769
+ }
770
+ return result;
771
+ }
772
+ /**
773
+ * 按 FIFO 把排队会话分配给仍有容量的在线坐席(坐席上线/会话结束/容量调整时调用)。
774
+ * 每个会话按其 app_id 对应的客服配置解析坐席池(指定坐席 / 坐席池),
775
+ * 分不到就跳过继续看下一条,最后给仍在排队的客户推送最新位次。
776
+ */
777
+ async dispatchQueue() {
778
+ const { items } = await this.repo.listWaitingSessions(1, QUEUE_SCAN_LIMIT);
779
+ if (!items.length)
780
+ return 0;
781
+ let assigned = 0;
704
782
  for (const session of items) {
705
- await this.repo.updateSession(session.id, {
706
- agent_id: agentId,
707
- last_agent_active_at: new Date(),
708
- });
709
- const history = await this.repo.listMessages(session.id, 20);
710
- await wsManager.sendToAgent(agentId, {
711
- type: "session_assigned",
712
- session_id: session.session_id,
713
- visitor_name: session.visitor_name,
714
- app_id: session.app_id,
715
- history: history.map((m) => ({
716
- role: m.role,
717
- content: m.content,
718
- content_type: m.content_type,
719
- created_at: m.created_at
720
- ? new Date(m.created_at)
721
- .toISOString()
722
- .slice(0, 19)
723
- .replace("T", " ")
724
- : null,
725
- })),
726
- });
727
- await wsManager.sendToUser(session.session_id, {
728
- type: "agent_online",
729
- agent_id: agent.id,
730
- agent_name: agent.display_name,
731
- agent_avatar: agent.avatar,
783
+ const csConfig = session.app_id
784
+ ? await this.repo.findConfigByAppId(session.app_id)
785
+ : null;
786
+ const agent = await this._pickAgent(csConfig);
787
+ if (!agent)
788
+ continue;
789
+ await this._assignSession(session, agent);
790
+ assigned += 1;
791
+ }
792
+ if (assigned)
793
+ await this._notifyQueuePositions();
794
+ return assigned;
795
+ }
796
+ /** 把会话分配给坐席:更新归属、写系统提示、通知坐席与客户 */
797
+ async _assignSession(session, agent) {
798
+ await this.repo.updateSession(session.id, {
799
+ status: 1,
800
+ agent_id: agent.id,
801
+ last_agent_active_at: new Date(),
802
+ });
803
+ const notice = `已为您接入人工坐席 ${agent.display_name || "客服"},请描述您的问题`;
804
+ await this.repo.createMessage({
805
+ session_id: session.id,
806
+ role: "system",
807
+ content: notice,
808
+ content_type: "text",
809
+ });
810
+ const history = await this._messagesWithCarry(session, 20);
811
+ await wsManager.sendToAgent(agent.id, {
812
+ type: "session_assigned",
813
+ session_id: session.session_id,
814
+ visitor_name: session.visitor_name,
815
+ app_id: session.app_id,
816
+ history: history.map((m) => ({
817
+ role: m.role,
818
+ content: m.content,
819
+ content_type: m.content_type,
820
+ created_at: m.created_at
821
+ ? new Date(m.created_at).toISOString().slice(0, 19).replace("T", " ")
822
+ : null,
823
+ })),
824
+ });
825
+ await wsManager.sendToUser(session.session_id, {
826
+ type: "agent_online",
827
+ agent_id: agent.id,
828
+ agent_name: agent.display_name,
829
+ agent_avatar: agent.avatar,
830
+ });
831
+ return notice;
832
+ }
833
+ /** 向仍在排队的客户推送最新位次(断线时由 queue-status 轮询兜底) */
834
+ async _notifyQueuePositions() {
835
+ const { items } = await this.repo.listWaitingSessions(1, QUEUE_SCAN_LIMIT);
836
+ const total = items.length;
837
+ for (let i = 0; i < items.length; i += 1) {
838
+ const position = i + 1;
839
+ await wsManager.sendToUser(items[i].session_id, {
840
+ type: "queue_update",
841
+ queue_position: position,
842
+ waiting_total: total,
843
+ ahead: Math.max(0, position - 1),
732
844
  });
733
845
  }
734
846
  }
847
+ /** 客户排队状态:无坐席 / 排队中 / 已接入 / 已结束 */
848
+ async getQueueStatus(sessionId) {
849
+ const session = await this.repo.findSessionBySessionId(sessionId);
850
+ if (!session)
851
+ throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
852
+ const online = await this._onlineAgents();
853
+ const waitingTotal = await this.repo.countWaitingSessions();
854
+ const base = {
855
+ queue_position: 0,
856
+ waiting_total: waitingTotal,
857
+ online_agents: online.length,
858
+ };
859
+ if (session.status === 2) {
860
+ return {
861
+ status: 2,
862
+ agent_id: null,
863
+ agent_name: null,
864
+ message: "会话已结束",
865
+ ...base,
866
+ };
867
+ }
868
+ if (session.status === 1 && session.agent_id != null) {
869
+ const agent = await this.repo.findAgentById(session.agent_id);
870
+ return {
871
+ status: 1,
872
+ agent_id: session.agent_id,
873
+ agent_name: agent?.display_name ?? null,
874
+ message: "已接入人工坐席",
875
+ ...base,
876
+ };
877
+ }
878
+ if (session.status === 1) {
879
+ const position = await this.repo.getQueuePosition(session.id);
880
+ return {
881
+ status: 1,
882
+ agent_id: null,
883
+ agent_name: null,
884
+ queue_position: position,
885
+ waiting_total: waitingTotal,
886
+ online_agents: online.length,
887
+ message: queueMessage(Math.max(0, position - 1)),
888
+ };
889
+ }
890
+ return {
891
+ status: 0,
892
+ agent_id: null,
893
+ agent_name: null,
894
+ message: "当前人工坐席忙,请稍后重试",
895
+ ...base,
896
+ };
897
+ }
735
898
  async _notifyAgentsNewSession(session) {
736
899
  try {
737
900
  const { items } = await this.repo.listAgents(1, 200);
@@ -755,22 +918,29 @@ export class CSService {
755
918
  if (agent.status !== "online")
756
919
  return false;
757
920
  const store = getRedisStore();
758
- try {
759
- return (await store.getJson(csAgentOnlineKey(agent.id))) !== null;
760
- }
761
- catch {
762
- return true; // Redis 不可用时信任 DB 状态
763
- }
921
+ const key = csAgentOnlineKey(agent.id);
922
+ if (await store.exists(key))
923
+ return true;
924
+ // exists 失败与 key 不存在都返回 false:Redis 不可用时信任 DB 状态
925
+ return !(await store.ping());
764
926
  }
765
- async _pickAgent(csConfig, agentKey) {
927
+ async _pickAgent(csConfig, agentKey, excludeAgentId) {
928
+ // 1. 指定接入标识(如业务页面传入 agent_key)
766
929
  if (agentKey) {
767
930
  const agent = await this.repo.findAgentByAgentKey(agentKey);
768
- if (agent)
769
- return (await this._agentIsOnline(agent)) ? agent : null;
931
+ if (agent) {
932
+ if (!(await this._agentIsOnline(agent)))
933
+ return null;
934
+ return (await this._agentHasCapacity(agent)) ? agent : null;
935
+ }
936
+ // 指定标识不存在时降级走坐席池,避免前端误传页面 id 导致转人工失败
770
937
  logger.warning(`接入标识 ${agentKey} 未配置,降级为坐席池分配`);
771
938
  }
939
+ // 2. 配置指定坐席 / 3. 坐席池(仅保留已启用且在线)
772
940
  let candidates = [];
773
- if (csConfig.agent_mode === "specified" && csConfig.agent_ids) {
941
+ if (csConfig !== null &&
942
+ csConfig.agent_mode === "specified" &&
943
+ csConfig.agent_ids) {
774
944
  const ids = Array.isArray(csConfig.agent_ids)
775
945
  ? csConfig.agent_ids
776
946
  : fromJson(csConfig.agent_ids) || [];
@@ -788,10 +958,19 @@ export class CSService {
788
958
  }
789
959
  if (!candidates.length)
790
960
  return null;
961
+ // 重新转人工:优先换一个在线坐席(仅当还有其它在线坐席时)
962
+ if (excludeAgentId != null && candidates.length > 1) {
963
+ const filtered = candidates.filter((a) => a.id !== excludeAgentId);
964
+ if (filtered.length)
965
+ candidates = filtered;
966
+ }
967
+ // 最少进行中会话优先(负载均衡);已满容量的坐席不参与分配
791
968
  let best = null;
792
969
  let bestLoad = -1;
793
970
  for (const a of candidates) {
794
- const load = await this.repo.countActiveSessionsByAgent(a.id);
971
+ const load = await this._agentActiveCount(a.id);
972
+ if (load >= (await this._agentCapacity(a)))
973
+ continue;
795
974
  if (best === null || load < bestLoad) {
796
975
  best = a;
797
976
  bestLoad = load;
@@ -805,70 +984,93 @@ export class CSService {
805
984
  throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "无效的应用ID", 404);
806
985
  if (csConfig.is_active !== 1)
807
986
  throw new AppException(ErrorCode.CS_CONFIG_INACTIVE, "客服服务未启用", 403);
987
+ // 会话:复用 / 已结束新开一轮 / 已接入坐席重新分配(结束当前轮,开启新一轮)
808
988
  let session;
989
+ let prevAgentId = null;
809
990
  if (sessionId) {
810
- session = await this.repo.findSessionBySessionId(sessionId);
811
- if (!session)
991
+ const found = await this.repo.findSessionBySessionId(sessionId);
992
+ if (!found)
812
993
  throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
994
+ if (found.status === 2) {
995
+ // 已结束:开启新一轮;「当天记录」由消息接口回溯携带
996
+ session = await this._createNextRound(found, csConfig);
997
+ }
998
+ else if (found.status === 1 && found.agent_id != null) {
999
+ // 重新点击转人工:结束当前轮并重新分配新坐席
1000
+ prevAgentId = found.agent_id;
1001
+ await this.repo.updateSession(found.id, { status: 2 });
1002
+ session = await this._createNextRound(found, csConfig);
1003
+ }
1004
+ else {
1005
+ session = found;
1006
+ }
813
1007
  }
814
1008
  else {
815
- sessionId = "sess_" + tokenHex(16);
1009
+ const newSessionId = "sess_" + tokenHex(16);
816
1010
  session = await this.repo.createSession({
817
- session_id: sessionId,
1011
+ session_id: newSessionId,
818
1012
  app_id: appId,
819
- visitor_id: visitorName || sessionId,
1013
+ visitor_id: visitorName || newSessionId,
820
1014
  visitor_name: visitorName ?? null,
821
1015
  source: "h5",
822
1016
  status: 0,
823
1017
  });
824
1018
  }
825
- if (session.status === 2)
826
- throw new AppException(ErrorCode.PARAM_ERROR, "会话已结束", 400);
827
- const agent = await this._pickAgent(csConfig, agentKey);
1019
+ const onlineAgents = await this._onlineAgents();
1020
+ let waitingTotal = await this.repo.countWaitingSessions();
1021
+ // 没有任何在线坐席:不排队,保持 AI 模式,提示稍后重试
1022
+ if (!onlineAgents.length) {
1023
+ await this._leaveQueue(session);
1024
+ return {
1025
+ session_id: session.session_id,
1026
+ status: 0,
1027
+ agent_id: null,
1028
+ agent_name: null,
1029
+ agent_avatar: null,
1030
+ message: "当前人工坐席忙,请稍后重试",
1031
+ queue_position: 0,
1032
+ waiting_total: waitingTotal,
1033
+ online_agents: 0,
1034
+ };
1035
+ }
1036
+ // 指定坐席但当前离线:同样不排队,明确提示忙
1037
+ if (agentKey) {
1038
+ const keyAgent = await this.repo.findAgentByAgentKey(agentKey);
1039
+ if (keyAgent && !(await this._agentIsOnline(keyAgent))) {
1040
+ await this._leaveQueue(session);
1041
+ return {
1042
+ session_id: session.session_id,
1043
+ status: 0,
1044
+ agent_id: null,
1045
+ agent_name: null,
1046
+ agent_avatar: null,
1047
+ message: "当前人工坐席忙,请稍后重试",
1048
+ queue_position: 0,
1049
+ waiting_total: waitingTotal,
1050
+ online_agents: onlineAgents.length,
1051
+ };
1052
+ }
1053
+ }
1054
+ const agent = await this._pickAgent(csConfig, agentKey, prevAgentId);
828
1055
  if (!agent) {
1056
+ // 有在线坐席但都已满负荷:进入排队并告知位次
829
1057
  await this.repo.updateSession(session.id, { status: 1 });
1058
+ const position = await this.repo.getQueuePosition(session.id);
1059
+ waitingTotal = await this.repo.countWaitingSessions();
830
1060
  return {
831
1061
  session_id: session.session_id,
832
1062
  status: 1,
833
1063
  agent_id: null,
834
1064
  agent_name: null,
835
1065
  agent_avatar: null,
836
- message: "已进入人工排队,坐席上线后将尽快为您服务",
1066
+ message: queueMessage(Math.max(0, position - 1)),
1067
+ queue_position: position,
1068
+ waiting_total: waitingTotal,
1069
+ online_agents: onlineAgents.length,
837
1070
  };
838
1071
  }
839
- await this.repo.updateSession(session.id, {
840
- status: 1,
841
- agent_id: agent.id,
842
- last_agent_active_at: new Date(),
843
- });
844
- const notice = `已为您接入人工坐席 ${agent.display_name || "客服"},请描述您的问题`;
845
- await this.repo.createMessage({
846
- session_id: session.id,
847
- role: "system",
848
- content: notice,
849
- content_type: "text",
850
- });
851
- const history = await this.repo.listMessages(session.id, 20);
852
- await wsManager.sendToAgent(agent.id, {
853
- type: "session_assigned",
854
- session_id: session.session_id,
855
- visitor_name: session.visitor_name,
856
- app_id: session.app_id,
857
- history: history.map((m) => ({
858
- role: m.role,
859
- content: m.content,
860
- content_type: m.content_type,
861
- created_at: m.created_at
862
- ? new Date(m.created_at).toISOString().slice(0, 19).replace("T", " ")
863
- : null,
864
- })),
865
- });
866
- await wsManager.sendToUser(session.session_id, {
867
- type: "agent_online",
868
- agent_id: agent.id,
869
- agent_name: agent.display_name,
870
- agent_avatar: agent.avatar,
871
- });
1072
+ const notice = await this._assignSession(session, agent);
1073
+ // 转人工时后台生成会话摘要(不阻塞)
872
1074
  try {
873
1075
  void generateSummaryBackground(session.id);
874
1076
  }
@@ -882,8 +1084,17 @@ export class CSService {
882
1084
  agent_name: agent.display_name ?? null,
883
1085
  agent_avatar: agent.avatar ?? null,
884
1086
  message: notice,
1087
+ queue_position: 0,
1088
+ waiting_total: waitingTotal,
1089
+ online_agents: onlineAgents.length,
885
1090
  };
886
1091
  }
1092
+ /** 客户不再排队:回到 AI 模式(会话仍可继续与 AI 对话) */
1093
+ async _leaveQueue(session) {
1094
+ if (session.status !== 0) {
1095
+ await this.repo.updateSession(session.id, { status: 0 });
1096
+ }
1097
+ }
887
1098
  /**
888
1099
  * 创建/复用访客会话(对应 java CustomerServiceService.createSession)。
889
1100
  * 校验配置存在后,复用 _getOrCreateVisitorSession 获取会话。
@@ -914,6 +1125,27 @@ export class CSService {
914
1125
  await this._notifyAgentsNewSession(session);
915
1126
  return session;
916
1127
  }
1128
+ /** 基于上一轮会话开启新一轮(同访客/同应用);当天记录由消息接口回溯携带 */
1129
+ async _createNextRound(prev, config) {
1130
+ return this.repo.createSession({
1131
+ session_id: "sess_" + tokenHex(16),
1132
+ app_id: prev.app_id || config.app_id,
1133
+ visitor_id: prev.visitor_id || prev.session_id,
1134
+ visitor_name: prev.visitor_name,
1135
+ source: prev.source || "h5",
1136
+ status: 0,
1137
+ });
1138
+ }
1139
+ /** 当前会话消息 + 同一访客当天历史会话消息(升序) */
1140
+ async _messagesWithCarry(session, limit = 20) {
1141
+ if (!session.visitor_id) {
1142
+ return this.repo.listMessages(session.id, limit);
1143
+ }
1144
+ const now = new Date();
1145
+ const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
1146
+ const prevIds = await this.repo.listPreviousSessionIds(session.visitor_id, session.app_id, session.id);
1147
+ return this.repo.listMessagesWithCarry(session.id, prevIds, start, limit);
1148
+ }
917
1149
  async agentSendReply(agentId, sessionId, content) {
918
1150
  const session = await this.repo.findSessionBySessionId(sessionId);
919
1151
  if (!session)
@@ -982,6 +1214,13 @@ export class CSService {
982
1214
  type: "session_closed",
983
1215
  content: "本次人工服务已结束,感谢您的咨询",
984
1216
  });
1217
+ // 释放的并发容量立刻派给排队客户
1218
+ try {
1219
+ await this.dispatchQueue();
1220
+ }
1221
+ catch (e) {
1222
+ logger.error(`会话结束后派单失败 session=${session.session_id}: ${e.message}`);
1223
+ }
985
1224
  }
986
1225
  async listAgentSessions(tab, page, size, agentEmployeeId) {
987
1226
  let agentPk = null;
@@ -1016,11 +1255,16 @@ export class CSService {
1016
1255
  if (agentIds.length) {
1017
1256
  const agents = await this.repo.listAgentsByIds(agentIds);
1018
1257
  for (const a of agents)
1019
- agentMap.set(a.id, a.display_name || `坐席${a.id}`);
1258
+ agentMap.set(a.id, {
1259
+ name: a.display_name || `坐席${a.id}`,
1260
+ avatar: a.avatar ?? null,
1261
+ });
1020
1262
  }
1021
1263
  return sessions.map((s) => {
1022
1264
  const dto = toSessionDto(s);
1023
- dto.agent_name = s.agent_id ? (agentMap.get(s.agent_id) ?? null) : null;
1265
+ const agent = s.agent_id ? agentMap.get(s.agent_id) : null;
1266
+ dto.agent_name = agent?.name ?? null;
1267
+ dto.agent_avatar = agent?.avatar ?? null;
1024
1268
  return dto;
1025
1269
  });
1026
1270
  }
@@ -1044,8 +1288,8 @@ export class CSService {
1044
1288
  return result;
1045
1289
  }
1046
1290
  // ─── 知识块管理 + 向量化 ───
1047
- async listChunks(kbId, page, size, sortBy, sortOrder) {
1048
- const { items, total } = await this.repo.listChunks(kbId, page, size, sortBy, sortOrder);
1291
+ async listChunks(kbId, page, size, sortBy, sortOrder, keyword) {
1292
+ const { items, total } = await this.repo.listChunks(kbId, page, size, sortBy, sortOrder, keyword);
1049
1293
  return { items: items.map(toChunkDto), total };
1050
1294
  }
1051
1295
  async addChunk(kbId, data) {
@@ -1350,8 +1594,10 @@ export class CSService {
1350
1594
  });
1351
1595
  yield sse({
1352
1596
  type: "transfer_required",
1597
+ status: transfer.status,
1353
1598
  agent_id: transfer.agent_id,
1354
1599
  agent_name: transfer.agent_name,
1600
+ queue_position: transfer.queue_position,
1355
1601
  message: transfer.message,
1356
1602
  reason,
1357
1603
  });
@@ -1696,7 +1942,7 @@ export class CSService {
1696
1942
  return dto;
1697
1943
  });
1698
1944
  }
1699
- async listMessages(sessionId, employee) {
1945
+ async listMessages(sessionId, employee, carryOver = false) {
1700
1946
  const session = await this.repo.findSessionBySessionId(sessionId);
1701
1947
  if (!session)
1702
1948
  throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
@@ -1704,7 +1950,17 @@ export class CSService {
1704
1950
  if (employee && !(await this._sessionVisible(session, employee))) {
1705
1951
  throw new AppException(ErrorCode.CS_SESSION_NOT_FOUND, "会话不存在", 404);
1706
1952
  }
1707
- const messages = await this.repo.listMessages(session.id);
1953
+ let messages;
1954
+ if (carryOver && session.visitor_id) {
1955
+ // 坐席端:携带同一访客「当天」历史会话记录(不含更早历史)
1956
+ const now = new Date();
1957
+ const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
1958
+ const prevIds = await this.repo.listPreviousSessionIds(session.visitor_id, session.app_id, session.id);
1959
+ messages = await this.repo.listMessagesWithCarry(session.id, prevIds, start, 100);
1960
+ }
1961
+ else {
1962
+ messages = await this.repo.listMessages(session.id);
1963
+ }
1708
1964
  return messages.map(toMessageDto);
1709
1965
  }
1710
1966
  async _sessionVisible(session, employee) {