aiChatServices.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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.archiveToRedis(userId, sess)
  97. sess.Client.Close()
  98. delete(m.sessions, userId)
  99. }
  100. return m.createSession(userId)
  101. }
  102. // LoadSession 加载历史会话(恢复 AI 上下文)
  103. func (m *ACPManager) LoadSession(userId string, sessionId string) (*ACPSession, error) {
  104. m.mu.Lock()
  105. defer m.mu.Unlock()
  106. // 如果已经是当前会话,直接返回
  107. if sess, ok := m.sessions[userId]; ok {
  108. if sess.SessionId == sessionId {
  109. sess.LastActive = time.Now()
  110. return sess, nil
  111. }
  112. // 归档当前活跃会话
  113. m.archiveToRedis(userId, sess)
  114. sess.Client.Close()
  115. delete(m.sessions, userId)
  116. }
  117. // 从 Redis 历史列表中获取标题
  118. item := m.getSessionListFromRedisHistory(userId, sessionId)
  119. if item == nil {
  120. return nil, fmt.Errorf("redis session/load 失败")
  121. }
  122. // 从 Redis 历史列表中移除该会话(因为它即将变为活跃)
  123. m.removeFromRedisHistory(userId, sessionId)
  124. // 启动 ACP 进程并 load 会话
  125. client, err := acp.NewClient(m.acpConfig)
  126. if err != nil {
  127. return nil, err
  128. }
  129. if err := client.Initialize(); err != nil {
  130. client.Close()
  131. return nil, err
  132. }
  133. loadedId, welcomeMsg, replayMessages, err := client.LoadSession(sessionId, m.serviceDir)
  134. if err != nil {
  135. client.Close()
  136. return nil, fmt.Errorf("session/load 失败: %w", err)
  137. }
  138. zap.L().Info("[AIChat] session/load 回放完成",
  139. zap.String("sessionId", loadedId),
  140. zap.String("welcomeMsg", welcomeMsg),
  141. zap.Int("replayCount", len(replayMessages)),
  142. )
  143. sess := &ACPSession{
  144. UserId: userId,
  145. SessionId: sessionId,
  146. Title: item.Title,
  147. WelcomeMessage: welcomeMsg,
  148. ReplayMessages: replayMessages,
  149. Client: client,
  150. LastActive: time.Now(),
  151. CreatedAt: time.UnixMilli(item.CreatedAt),
  152. }
  153. client.UserId = userId
  154. m.sessions[userId] = sess
  155. // 更新 Redis 活跃会话
  156. repositories.SaveAiSession(userId, repositories.AiActiveSession{
  157. SessionId: sess.SessionId,
  158. Title: sess.Title,
  159. CreatedAt: sess.CreatedAt.UnixMilli(),
  160. LastActive: sess.LastActive.UnixMilli(),
  161. })
  162. zap.L().Info("[AIChat] 会话加载成功", zap.String("userId", userId), zap.String("sessionId", sessionId))
  163. return sess, nil
  164. }
  165. // ============ 会话列表查询 ============
  166. // GetSessionList 获取用户的会话列表(当前活跃 + Redis 历史)
  167. func (m *ACPManager) GetSessionList(userId string) []SessionListItem {
  168. m.mu.Lock()
  169. defer m.mu.Unlock()
  170. list := make([]SessionListItem, 0)
  171. // 当前活跃会话排在最前
  172. if sess, ok := m.sessions[userId]; ok {
  173. list = append(list, SessionListItem{
  174. SessionId: sess.SessionId,
  175. Title: sess.Title,
  176. CreatedAt: sess.CreatedAt.UnixMilli(),
  177. LastActive: sess.LastActive.UnixMilli(),
  178. IsActive: true,
  179. })
  180. } else {
  181. // 内存无活跃会话(后端重启),从 Redis 恢复完整会话到内存
  182. activeSess, err := repositories.GetAiSession(userId)
  183. if err == nil && activeSess != nil {
  184. sess, err := m.startAndLoadSession(userId, activeSess)
  185. if err == nil {
  186. list = append(list, SessionListItem{
  187. SessionId: sess.SessionId,
  188. Title: sess.Title,
  189. CreatedAt: sess.CreatedAt.UnixMilli(),
  190. LastActive: sess.LastActive.UnixMilli(),
  191. IsActive: true,
  192. })
  193. zap.L().Info("[AIChat] GetSessionList 恢复会话到内存", zap.String("userId", userId), zap.String("sessionId", sess.SessionId))
  194. }
  195. }
  196. }
  197. // 从 Redis 获取历史列表
  198. redisItems, err := repositories.GetAiSessionList(userId)
  199. if err == nil && len(redisItems) > 0 {
  200. for _, item := range redisItems {
  201. list = append(list, SessionListItem{
  202. SessionId: item.SessionId,
  203. Title: item.Title,
  204. CreatedAt: item.CreatedAt,
  205. LastActive: item.LastActive,
  206. IsActive: false,
  207. })
  208. }
  209. }
  210. return list
  211. }
  212. // ============ 会话操作 ============
  213. // UpdateSessionTitle 更新会话标题
  214. func (m *ACPManager) UpdateSessionTitle(userId string, sessionId string, title string) {
  215. m.mu.Lock()
  216. defer m.mu.Unlock()
  217. // 检查当前活跃会话
  218. if sess, ok := m.sessions[userId]; ok && sess.SessionId == sessionId {
  219. sess.Title = title
  220. // 同步到 Redis 活跃会话 key
  221. repositories.SaveAiSession(userId, repositories.AiActiveSession{
  222. SessionId: sess.SessionId,
  223. Title: sess.Title,
  224. CreatedAt: sess.CreatedAt.UnixMilli(),
  225. LastActive: sess.LastActive.UnixMilli(),
  226. })
  227. return
  228. }
  229. // 同步到 Redis 历史列表
  230. repositories.UpdateAiSessionTitle(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. repositories.DeleteAiSession(userId)
  241. return
  242. }
  243. // 从 Redis 历史列表中移除
  244. m.removeFromRedisHistory(userId, sessionId)
  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. repositories.DeleteAiSession(userId)
  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. // 持久化活跃会话到 Redis
  343. repositories.SaveAiSession(userId, repositories.AiActiveSession{
  344. SessionId: sess.SessionId,
  345. Title: sess.Title,
  346. CreatedAt: sess.CreatedAt.UnixMilli(),
  347. LastActive: sess.LastActive.UnixMilli(),
  348. })
  349. zap.L().Info("[AIChat] 会话创建成功", zap.String("userId", userId), zap.String("sessionId", sessionId))
  350. return sess, nil
  351. }
  352. // startAndLoadSession 启动 ACP 进程并 load 指定会话(用于 Redis 恢复)
  353. func (m *ACPManager) startAndLoadSession(userId string, active *repositories.AiActiveSession) (*ACPSession, error) {
  354. client, err := acp.NewClient(m.acpConfig)
  355. if err != nil {
  356. return nil, err
  357. }
  358. if err := client.Initialize(); err != nil {
  359. client.Close()
  360. return nil, err
  361. }
  362. _, welcomeMsg, _, err := client.LoadSession(active.SessionId, m.serviceDir)
  363. if err != nil {
  364. client.Close()
  365. return nil, fmt.Errorf("session/load 失败: %w", err)
  366. }
  367. now := time.Now()
  368. sess := &ACPSession{
  369. UserId: userId,
  370. SessionId: active.SessionId,
  371. Title: active.Title,
  372. WelcomeMessage: welcomeMsg,
  373. Client: client,
  374. LastActive: now,
  375. CreatedAt: time.UnixMilli(active.CreatedAt),
  376. }
  377. client.UserId = userId
  378. m.sessions[userId] = sess
  379. return sess, nil
  380. }
  381. // archiveToRedis 将会话归档到 Redis 历史列表
  382. func (m *ACPManager) archiveToRedis(userId string, sess *ACPSession) {
  383. item := repositories.AiSessionItem{
  384. SessionId: sess.SessionId,
  385. Title: sess.Title,
  386. CreatedAt: sess.CreatedAt.UnixMilli(),
  387. LastActive: sess.LastActive.UnixMilli(),
  388. }
  389. // 读取现有历史
  390. list, _ := repositories.GetAiSessionList(userId)
  391. // 插入头部
  392. list = append([]repositories.AiSessionItem{item}, list...)
  393. // 超过 50 条:删除多余的 Kiro 会话
  394. if len(list) > 50 {
  395. overflow := list[50:]
  396. list = list[:50]
  397. // 后台异步删除多余会话
  398. go func() {
  399. for _, old := range overflow {
  400. m.deleteKiroSession(old.SessionId)
  401. }
  402. }()
  403. }
  404. if err := repositories.SaveAiSessionList(userId, list); err != nil {
  405. zap.L().Warn("[AIChat] 归档会话到Redis失败", zap.String("userId", userId), zap.Error(err))
  406. }
  407. }
  408. // archiveActiveSessionFromRedis 将 Redis session key 中的活跃会话归档到历史列表
  409. // 用于后端重启后、内存中无活跃会话时的归档保护
  410. // removeFromRedisHistory 从 Redis 历史列表中移除指定会话
  411. func (m *ACPManager) removeFromRedisHistory(userId string, sessionId string) {
  412. list, err := repositories.GetAiSessionList(userId)
  413. if err != nil || len(list) == 0 {
  414. return
  415. }
  416. for i := range list {
  417. if list[i].SessionId == sessionId {
  418. list = append(list[:i], list[i+1:]...)
  419. repositories.SaveAiSessionList(userId, list)
  420. return
  421. }
  422. }
  423. }
  424. // getSessionListFromRedisHistory 从 Redis 历史列表中获取会话
  425. func (m *ACPManager) getSessionListFromRedisHistory(userId string, sessionId string) *repositories.AiSessionItem {
  426. list, err := repositories.GetAiSessionList(userId)
  427. if err != nil {
  428. zap.L().Warn("[AIChat] 从redis读取AiSessionList失败", zap.String("err", err.Error()))
  429. return nil
  430. }
  431. for _, item := range list {
  432. if item.SessionId == sessionId {
  433. return &item
  434. }
  435. }
  436. return nil
  437. }
  438. // deleteKiroSession 通过 kiro-cli 命令删除会话
  439. func (m *ACPManager) deleteKiroSession(sessionId string) {
  440. cmd := exec.Command("kiro-cli", "chat", "--delete-session", sessionId)
  441. cmd.Dir = m.serviceDir
  442. if output, err := cmd.CombinedOutput(); err != nil {
  443. zap.L().Warn("[AIChat] 删除Kiro会话失败",
  444. zap.String("sessionId", sessionId),
  445. zap.Error(err),
  446. zap.String("output", string(output)),
  447. )
  448. } else {
  449. zap.L().Info("[AIChat] 删除Kiro会话成功", zap.String("sessionId", sessionId))
  450. }
  451. }
  452. // ============ 工具函数 ============
  453. func toJSON(v any) string {
  454. data, _ := json.Marshal(v)
  455. return string(data)
  456. }