aiChatServices.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. package services
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "fwh-toolbox-server/repositories"
  6. "fwh-toolbox-server/utils/acp"
  7. "os/exec"
  8. "sync"
  9. "time"
  10. "go.uber.org/zap"
  11. )
  12. // AIChatEvent SSE 事件(输出给前端)
  13. type AIChatEvent struct {
  14. Type string `json:"type"` // text, tool_call, tool_update, done, error
  15. Content string `json:"content,omitempty"` // 文本内容
  16. ToolName string `json:"name,omitempty"` // 工具名
  17. Status string `json:"status,omitempty"` // 工具状态
  18. SessionId string `json:"sessionId,omitempty"` // 会话ID
  19. StopReason string `json:"stopReason,omitempty"`
  20. }
  21. // ACPSession 单个用户的 ACP 会话
  22. type ACPSession struct {
  23. UserId string
  24. SessionId string
  25. Title string
  26. WelcomeMessage string
  27. ReplayMessages []acp.ReplayMessage // session/load 回放的历史消息
  28. Client *acp.Client
  29. Mutex sync.Mutex
  30. LastActive time.Time
  31. CreatedAt time.Time
  32. }
  33. // SessionListItem 会话列表项(返回给前端)
  34. type SessionListItem struct {
  35. SessionId string `json:"sessionId"`
  36. Title string `json:"title"`
  37. CreatedAt int64 `json:"createdAt"`
  38. LastActive int64 `json:"lastActive"`
  39. IsActive bool `json:"isActive"`
  40. }
  41. // ACPManager 管理所有用户的 ACP 会话
  42. type ACPManager struct {
  43. sessions map[string]*ACPSession // key: userId -> 当前活跃会话(持有进程引用)
  44. mu sync.Mutex
  45. serviceDir string
  46. acpConfig acp.ClientConfig
  47. }
  48. // NewACPManager 创建 ACP 管理器
  49. func NewACPManager(serviceDir string, env []string) *ACPManager {
  50. return &ACPManager{
  51. sessions: make(map[string]*ACPSession),
  52. serviceDir: serviceDir,
  53. acpConfig: acp.ClientConfig{
  54. Command: "kiro-cli",
  55. Args: []string{"acp", "--agent", "fwh-toolbox-agent"},
  56. WorkingDir: serviceDir,
  57. Env: env,
  58. },
  59. }
  60. }
  61. // ============ 会话生命周期 ============
  62. // GetOrCreateSession 获取或创建用户的 ACP 会话
  63. // 优先级:内存活跃会话 → Redis 持久化恢复 → 创建新会话
  64. func (m *ACPManager) GetOrCreateSession(userId string) (*ACPSession, error) {
  65. m.mu.Lock()
  66. defer m.mu.Unlock()
  67. // 1. 检查内存中是否有活跃会话
  68. if sess, ok := m.sessions[userId]; ok {
  69. if sess.Client.IsAlive() {
  70. sess.LastActive = time.Now()
  71. return sess, nil
  72. }
  73. sess.Client.Close()
  74. delete(m.sessions, userId)
  75. }
  76. // 2. 尝试从 Redis 恢复会话
  77. savedSession, err := repositories.GetAiSession(userId)
  78. if err == nil && savedSession != nil {
  79. sess, err := m.startAndLoadSession(userId, savedSession)
  80. if err == nil {
  81. zap.L().Info("[AIChat] 从 Redis 恢复会话成功", zap.String("userId", userId), zap.String("sessionId", savedSession.SessionId))
  82. return sess, nil
  83. }
  84. zap.L().Warn("[AIChat] 从 Redis 恢复会话失败,将创建新会话", zap.String("userId", userId), zap.Error(err))
  85. repositories.DeleteAiSession(userId)
  86. }
  87. // 3. 创建新会话
  88. return m.createSession(userId)
  89. }
  90. // CreateNewSession 强制创建一个新会话(归档旧会话到 Redis 历史)
  91. func (m *ACPManager) CreateNewSession(userId string) (*ACPSession, error) {
  92. m.mu.Lock()
  93. defer m.mu.Unlock()
  94. // 归档当前活跃会话
  95. if sess, ok := m.sessions[userId]; ok {
  96. m.archiveSession(userId, sess)
  97. sess.Client.Close()
  98. delete(m.sessions, userId)
  99. }
  100. return m.createSession(userId)
  101. }
  102. // LoadSession 加载历史会话(恢复 AI 上下文,切换会话)
  103. // 仅切换会话并恢复上下文,不返回回放消息(回放消息通过 SSE 接口单独获取)
  104. func (m *ACPManager) LoadSession(userId string, sessionId string) (*ACPSession, error) {
  105. m.mu.Lock()
  106. defer m.mu.Unlock()
  107. // 如果已经是当前会话,直接返回
  108. if sess, ok := m.sessions[userId]; ok {
  109. if sess.SessionId == sessionId {
  110. sess.LastActive = time.Now()
  111. return sess, nil
  112. }
  113. // 归档当前活跃会话
  114. m.archiveSession(userId, sess)
  115. sess.Client.Close()
  116. delete(m.sessions, userId)
  117. }
  118. // 从 Redis 历史列表中获取标题
  119. item := m.getSessionListFromRedisHistory(userId, sessionId)
  120. if item == nil {
  121. return nil, fmt.Errorf("redis session/load 失败")
  122. }
  123. // 从 Redis 历史列表中移除该会话(因为它即将变为活跃)
  124. m.removeFromRedisHistory(userId, sessionId)
  125. // 启动 ACP 进程并 load 会话
  126. client, err := acp.NewClient(m.acpConfig)
  127. if err != nil {
  128. return nil, err
  129. }
  130. if err := client.Initialize(); err != nil {
  131. client.Close()
  132. return nil, err
  133. }
  134. loadedId, welcomeMsg, replayMessages, err := client.LoadSession(sessionId, m.serviceDir)
  135. if err != nil {
  136. client.Close()
  137. return nil, fmt.Errorf("session/load 失败: %w", err)
  138. }
  139. zap.L().Info("[AIChat] session/load 回放完成",
  140. zap.String("sessionId", loadedId),
  141. zap.String("welcomeMsg", welcomeMsg),
  142. zap.Int("replayCount", len(replayMessages)),
  143. )
  144. sess := &ACPSession{
  145. UserId: userId,
  146. SessionId: sessionId,
  147. Title: item.Title,
  148. WelcomeMessage: welcomeMsg,
  149. ReplayMessages: replayMessages,
  150. Client: client,
  151. LastActive: time.Now(),
  152. CreatedAt: time.UnixMilli(item.CreatedAt),
  153. }
  154. client.UserId = userId
  155. m.sessions[userId] = sess
  156. // 持久化
  157. m.activateSession(userId, sess)
  158. zap.L().Info("[AIChat] 会话加载成功", zap.String("userId", userId), zap.String("sessionId", sessionId))
  159. return sess, nil
  160. }
  161. // GetReplayMessages 获取指定用户当前活跃会话的回放消息
  162. // 用于 SSE 流式推送
  163. func (m *ACPManager) GetReplayMessages(userId string) []acp.ReplayMessage {
  164. m.mu.Lock()
  165. defer m.mu.Unlock()
  166. if sess, ok := m.sessions[userId]; ok {
  167. return sess.ReplayMessages
  168. }
  169. return nil
  170. }
  171. // ============ 会话列表查询 ============
  172. // GetSessionList 获取用户的会话列表(当前活跃 + Redis 历史)
  173. func (m *ACPManager) GetSessionList(userId string) []SessionListItem {
  174. m.mu.Lock()
  175. defer m.mu.Unlock()
  176. list := make([]SessionListItem, 0)
  177. // 当前活跃会话排在最前
  178. if sess, ok := m.sessions[userId]; ok {
  179. list = append(list, SessionListItem{
  180. SessionId: sess.SessionId,
  181. Title: sess.Title,
  182. CreatedAt: sess.CreatedAt.UnixMilli(),
  183. LastActive: sess.LastActive.UnixMilli(),
  184. IsActive: true,
  185. })
  186. } else {
  187. // 内存无活跃会话(后端重启),从 Redis 恢复完整会话到内存
  188. activeSess, err := repositories.GetAiSession(userId)
  189. if err == nil && activeSess != nil {
  190. sess, err := m.startAndLoadSession(userId, activeSess)
  191. if err == nil {
  192. list = append(list, SessionListItem{
  193. SessionId: sess.SessionId,
  194. Title: sess.Title,
  195. CreatedAt: sess.CreatedAt.UnixMilli(),
  196. LastActive: sess.LastActive.UnixMilli(),
  197. IsActive: true,
  198. })
  199. zap.L().Info("[AIChat] GetSessionList 恢复会话到内存", zap.String("userId", userId), zap.String("sessionId", sess.SessionId))
  200. }
  201. }
  202. }
  203. // 从 Redis 获取历史列表
  204. redisItems, err := repositories.GetAiSessionList(userId)
  205. if err == nil && len(redisItems) > 0 {
  206. for _, item := range redisItems {
  207. list = append(list, SessionListItem{
  208. SessionId: item.SessionId,
  209. Title: item.Title,
  210. CreatedAt: item.CreatedAt,
  211. LastActive: item.LastActive,
  212. IsActive: false,
  213. })
  214. }
  215. }
  216. return list
  217. }
  218. // ============ 会话操作 ============
  219. // UpdateSessionTitle 更新会话标题
  220. func (m *ACPManager) UpdateSessionTitle(userId string, sessionId string, title string) {
  221. m.mu.Lock()
  222. defer m.mu.Unlock()
  223. // 检查当前活跃会话
  224. if sess, ok := m.sessions[userId]; ok && sess.SessionId == sessionId {
  225. sess.Title = title
  226. m.saveSessionTitle(userId, sess)
  227. return
  228. }
  229. // 历史会话
  230. m.saveHistorySessionTitle(userId, sessionId, title)
  231. }
  232. // DeleteSessionFromHistory 删除某会话
  233. func (m *ACPManager) DeleteSessionFromHistory(userId string, sessionId string) {
  234. m.mu.Lock()
  235. defer m.mu.Unlock()
  236. // 如果是当前活跃会话,关闭它
  237. if sess, ok := m.sessions[userId]; ok && sess.SessionId == sessionId {
  238. sess.Client.Close()
  239. delete(m.sessions, userId)
  240. m.removeSession(userId, sessionId, true)
  241. return
  242. }
  243. // 历史会话
  244. m.removeSession(userId, sessionId, false)
  245. }
  246. // DeleteSession 删除当前活跃会话
  247. func (m *ACPManager) DeleteSession(userId string) {
  248. m.mu.Lock()
  249. defer m.mu.Unlock()
  250. if sess, ok := m.sessions[userId]; ok {
  251. sess.Client.Close()
  252. delete(m.sessions, userId)
  253. m.removeSession(userId, sess.SessionId, true)
  254. zap.L().Info("[AIChat] 会话已删除", zap.String("userId", userId))
  255. }
  256. }
  257. // GetSessionInfo 获取用户当前活跃会话信息
  258. func (m *ACPManager) GetSessionInfo(userId string) *ACPSession {
  259. m.mu.Lock()
  260. defer m.mu.Unlock()
  261. return m.sessions[userId]
  262. }
  263. // Cancel 取消当前操作
  264. func (m *ACPManager) Cancel(sess *ACPSession) {
  265. sess.Client.Cancel(sess.SessionId)
  266. }
  267. // ResolvePermission 前端回传权限选择
  268. func (m *ACPManager) ResolvePermission(userId string, optionId string) error {
  269. sess := m.GetSessionInfo(userId)
  270. if sess == nil {
  271. return fmt.Errorf("没有活跃的会话")
  272. }
  273. sess.Client.ResolvePermission(optionId)
  274. return nil
  275. }
  276. // ============ 消息发送 ============
  277. // Prompt 发送消息并流式读取响应
  278. func (m *ACPManager) Prompt(sess *ACPSession, message string, eventCh chan<- AIChatEvent) {
  279. sess.Mutex.Lock()
  280. defer sess.Mutex.Unlock()
  281. sess.LastActive = time.Now()
  282. // 首次发消息时自动设置标题(取消息前 30 字)
  283. if sess.Title == "" && message != "" {
  284. title := message
  285. if len([]rune(title)) > 30 {
  286. title = string([]rune(title)[:30]) + "..."
  287. }
  288. sess.Title = title
  289. }
  290. // 注入会话上下文(让 AI 在调用 MCP Tool 时能传入正确的 userId 和 sessionId)
  291. contextMessage := fmt.Sprintf("[context] userId=%s, sessionId=%s\n\n%s", sess.UserId, sess.SessionId, message)
  292. // 用 acp.Client.Prompt 流式读取
  293. acpEvents := make(chan acp.Event, 50)
  294. go sess.Client.Prompt(sess.SessionId, contextMessage, acpEvents)
  295. // 转换 acp.Event → AIChatEvent
  296. for event := range acpEvents {
  297. switch event.Type {
  298. case "text":
  299. eventCh <- AIChatEvent{Type: "text", Content: event.Content}
  300. case "tool_call":
  301. eventCh <- AIChatEvent{Type: "tool_call", ToolName: event.ToolName, Status: event.ToolStatus}
  302. case "tool_update":
  303. eventCh <- AIChatEvent{Type: "tool_update", ToolName: event.ToolName, Status: event.ToolStatus}
  304. case "permission":
  305. eventCh <- AIChatEvent{Type: "permission", Content: toJSON(event.Permission)}
  306. case "done":
  307. eventCh <- AIChatEvent{Type: "done", SessionId: event.SessionId, StopReason: event.StopReason}
  308. case "error":
  309. eventCh <- AIChatEvent{Type: "error", Content: event.Content}
  310. }
  311. }
  312. close(eventCh)
  313. }
  314. // ============ 内部方法 ============
  315. // createSession 创建新 ACP 会话
  316. func (m *ACPManager) createSession(userId string) (*ACPSession, error) {
  317. client, err := acp.NewClient(m.acpConfig)
  318. if err != nil {
  319. return nil, err
  320. }
  321. if err := client.Initialize(); err != nil {
  322. client.Close()
  323. return nil, err
  324. }
  325. sessionId, welcomeMsg, err := client.NewSession(m.serviceDir)
  326. if err != nil {
  327. client.Close()
  328. return nil, err
  329. }
  330. now := time.Now()
  331. sess := &ACPSession{
  332. UserId: userId,
  333. SessionId: sessionId,
  334. Title: "",
  335. WelcomeMessage: welcomeMsg,
  336. Client: client,
  337. LastActive: now,
  338. CreatedAt: now,
  339. }
  340. client.UserId = userId
  341. m.sessions[userId] = sess
  342. // 持久化
  343. m.saveNewSession(userId, sess)
  344. zap.L().Info("[AIChat] 会话创建成功", zap.String("userId", userId), zap.String("sessionId", sessionId))
  345. return sess, nil
  346. }
  347. // startAndLoadSession 启动 ACP 进程并 load 指定会话(用于 Redis 恢复)
  348. func (m *ACPManager) startAndLoadSession(userId string, active *repositories.AiActiveSession) (*ACPSession, error) {
  349. client, err := acp.NewClient(m.acpConfig)
  350. if err != nil {
  351. return nil, err
  352. }
  353. if err := client.Initialize(); err != nil {
  354. client.Close()
  355. return nil, err
  356. }
  357. _, welcomeMsg, _, err := client.LoadSession(active.SessionId, m.serviceDir)
  358. if err != nil {
  359. client.Close()
  360. return nil, fmt.Errorf("session/load 失败: %w", err)
  361. }
  362. now := time.Now()
  363. sess := &ACPSession{
  364. UserId: userId,
  365. SessionId: active.SessionId,
  366. Title: active.Title,
  367. WelcomeMessage: welcomeMsg,
  368. Client: client,
  369. LastActive: now,
  370. CreatedAt: time.UnixMilli(active.CreatedAt),
  371. }
  372. client.UserId = userId
  373. m.sessions[userId] = sess
  374. return sess, nil
  375. }
  376. // ============ 内部方法:会话存储 ============
  377. // persistNewSession 持久化新创建的活跃会话(Redis + MongoDB)
  378. func (m *ACPManager) saveNewSession(userId string, sess *ACPSession) {
  379. repositories.SaveAiSession(userId, repositories.AiActiveSession{
  380. SessionId: sess.SessionId,
  381. Title: sess.Title,
  382. CreatedAt: sess.CreatedAt.UnixMilli(),
  383. LastActive: sess.LastActive.UnixMilli(),
  384. })
  385. repositories.DeactivateAllAiChatSessions(userId)
  386. repositories.UpsertAiChatSession(repositories.AiChatSession{
  387. UserId: userId,
  388. SessionId: sess.SessionId,
  389. Title: sess.Title,
  390. IsActive: true,
  391. CreatedAt: sess.CreatedAt,
  392. LastActive: sess.LastActive,
  393. })
  394. }
  395. // persistActivateSession 持久化会话激活(Redis + MongoDB)
  396. func (m *ACPManager) activateSession(userId string, sess *ACPSession) {
  397. repositories.SaveAiSession(userId, repositories.AiActiveSession{
  398. SessionId: sess.SessionId,
  399. Title: sess.Title,
  400. CreatedAt: sess.CreatedAt.UnixMilli(),
  401. LastActive: sess.LastActive.UnixMilli(),
  402. })
  403. repositories.DeactivateAllAiChatSessions(userId)
  404. repositories.UpdateAiChatSessionActive(userId, sess.SessionId, true)
  405. }
  406. // persistArchiveSession 持久化会话归档(Redis + MongoDB)
  407. func (m *ACPManager) archiveSession(userId string, sess *ACPSession) {
  408. item := repositories.AiSessionItem{
  409. SessionId: sess.SessionId,
  410. Title: sess.Title,
  411. CreatedAt: sess.CreatedAt.UnixMilli(),
  412. LastActive: sess.LastActive.UnixMilli(),
  413. }
  414. list, _ := repositories.GetAiSessionList(userId)
  415. list = append([]repositories.AiSessionItem{item}, list...)
  416. if len(list) > 50 {
  417. overflow := list[50:]
  418. list = list[:50]
  419. go func() {
  420. for _, old := range overflow {
  421. m.deleteKiroSession(old.SessionId)
  422. }
  423. }()
  424. }
  425. if err := repositories.SaveAiSessionList(userId, list); err != nil {
  426. zap.L().Warn("[AIChat] 归档会话到Redis失败", zap.String("userId", userId), zap.Error(err))
  427. }
  428. repositories.UpdateAiChatSessionActive(userId, sess.SessionId, false)
  429. }
  430. // persistUpdateTitle 持久化标题更新(Redis + MongoDB)
  431. func (m *ACPManager) saveSessionTitle(userId string, sess *ACPSession) {
  432. repositories.SaveAiSession(userId, repositories.AiActiveSession{
  433. SessionId: sess.SessionId,
  434. Title: sess.Title,
  435. CreatedAt: sess.CreatedAt.UnixMilli(),
  436. LastActive: sess.LastActive.UnixMilli(),
  437. })
  438. repositories.UpdateAiChatSessionTitle(userId, sess.SessionId, sess.Title)
  439. }
  440. // persistUpdateHistoryTitle 持久化历史会话标题更新(Redis + MongoDB)
  441. func (m *ACPManager) saveHistorySessionTitle(userId string, sessionId string, title string) {
  442. repositories.UpdateAiSessionTitle(userId, sessionId, title)
  443. repositories.UpdateAiChatSessionTitle(userId, sessionId, title)
  444. }
  445. // persistDeleteSession 持久化删除会话(Redis + MongoDB)
  446. func (m *ACPManager) removeSession(userId string, sessionId string, isActive bool) {
  447. if isActive {
  448. repositories.DeleteAiSession(userId)
  449. } else {
  450. m.removeFromRedisHistory(userId, sessionId)
  451. }
  452. repositories.DeleteAiChatSession(userId, sessionId)
  453. }
  454. // ============ 内部方法:Redis 操作 ============
  455. func (m *ACPManager) removeFromRedisHistory(userId string, sessionId string) {
  456. list, err := repositories.GetAiSessionList(userId)
  457. if err != nil || len(list) == 0 {
  458. return
  459. }
  460. for i := range list {
  461. if list[i].SessionId == sessionId {
  462. list = append(list[:i], list[i+1:]...)
  463. repositories.SaveAiSessionList(userId, list)
  464. return
  465. }
  466. }
  467. }
  468. // getSessionListFromRedisHistory 从 Redis 历史列表中获取会话
  469. func (m *ACPManager) getSessionListFromRedisHistory(userId string, sessionId string) *repositories.AiSessionItem {
  470. list, err := repositories.GetAiSessionList(userId)
  471. if err != nil {
  472. zap.L().Warn("[AIChat] 从redis读取AiSessionList失败", zap.String("err", err.Error()))
  473. return nil
  474. }
  475. for _, item := range list {
  476. if item.SessionId == sessionId {
  477. return &item
  478. }
  479. }
  480. return nil
  481. }
  482. // deleteKiroSession 通过 kiro-cli 命令删除会话
  483. func (m *ACPManager) deleteKiroSession(sessionId string) {
  484. cmd := exec.Command("kiro-cli", "chat", "--delete-session", sessionId)
  485. cmd.Dir = m.serviceDir
  486. if output, err := cmd.CombinedOutput(); err != nil {
  487. zap.L().Warn("[AIChat] 删除Kiro会话失败",
  488. zap.String("sessionId", sessionId),
  489. zap.Error(err),
  490. zap.String("output", string(output)),
  491. )
  492. } else {
  493. zap.L().Info("[AIChat] 删除Kiro会话成功", zap.String("sessionId", sessionId))
  494. }
  495. }
  496. // ============ 工具函数 ============
  497. func toJSON(v any) string {
  498. data, _ := json.Marshal(v)
  499. return string(data)
  500. }