aiChatControllers.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. package controllers
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "os/user"
  9. "path/filepath"
  10. "sort"
  11. "strings"
  12. "time"
  13. "github.com/gofiber/fiber/v2"
  14. "github.com/gofiber/fiber/v2/utils"
  15. "github.com/minio/minio-go/v7"
  16. "go.uber.org/zap"
  17. "fwh-toolbox-server/middleware"
  18. "fwh-toolbox-server/services"
  19. "fwh-toolbox-server/utils/filestore"
  20. minioUtil "fwh-toolbox-server/utils/minio"
  21. )
  22. var acpManager *services.ACPManager
  23. // InitAIChat 初始化 AI Chat 模块
  24. // runAsUser 指定拉起 kiro-cli 子进程时降权到的系统用户名,为空则不降权。
  25. // home 指定 kiro-cli 子进程的 HOME 目录;为空时回退到降权用户的家目录,
  26. // 若仍无法推导则使用默认值。
  27. // debugLog 为调试日志宏开关,开启时向 kiro-cli 子进程注入 KIRO_LOG_LEVEL=debug。
  28. func InitAIChat(serviceDir string, runAsUser string, home string, debugLog bool) {
  29. home = strings.TrimSpace(home)
  30. // 未显式配置 HOME 时的回退:优先推导降权用户的家目录,否则用默认值。
  31. if home == "" {
  32. home = "/home/jerry-remote"
  33. if u := strings.TrimSpace(runAsUser); u != "" {
  34. if usr, err := user.Lookup(u); err == nil {
  35. home = usr.HomeDir
  36. } else {
  37. zap.L().Warn("[AIChat] 查找降权用户失败,沿用默认 HOME",
  38. zap.String("user", u), zap.String("home", home), zap.Error(err))
  39. }
  40. }
  41. }
  42. // 组装传给 kiro-cli 子进程的环境变量。
  43. childEnv := []string{"HOME=" + home}
  44. if debugLog {
  45. // 宏开关:开启 kiro-cli debug 级日志。
  46. // 日志输出路径(Linux,kiro-cli acp 默认):/tmp/kiro-log/logs/kiro-chat.log
  47. childEnv = append(childEnv, "KIRO_LOG_LEVEL=debug")
  48. }
  49. zap.L().Info("[AIChat] 初始化 ACP",
  50. zap.String("runAsUser", runAsUser), zap.String("home", home),
  51. zap.Bool("debugLog", debugLog))
  52. acpManager = services.NewACPManager(serviceDir, childEnv, runAsUser)
  53. }
  54. // AiChat 发送消息(SSE 流式响应)
  55. // POST /ai/chat
  56. func AiChat(c *fiber.Ctx) error {
  57. var req struct {
  58. Message string `json:"message"`
  59. SessionId string `json:"sessionId"`
  60. }
  61. if err := c.BodyParser(&req); err != nil {
  62. return Fail(c, "Invalid request body")
  63. }
  64. if req.Message == "" {
  65. return Fail(c, "message 不能为空")
  66. }
  67. userId := middleware.AuthGetUserName(c)
  68. sess, err := acpManager.GetOrCreateSession(userId)
  69. if err != nil {
  70. return Error(c, fmt.Sprintf("AI 会话创建失败: %v", err))
  71. }
  72. // SSE 流式响应
  73. c.Set("Content-Type", "text/event-stream")
  74. c.Set("Cache-Control", "no-cache")
  75. c.Set("Connection", "keep-alive")
  76. c.Set("X-Accel-Buffering", "no")
  77. c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
  78. // 发送 session_info 事件,包含实际生效的 agent 和 model
  79. infoContent, _ := json.Marshal(fiber.Map{"agentId": sess.AgentId, "modelId": sess.ModelId})
  80. infoEvent, _ := json.Marshal(services.AIChatEvent{Type: "session_info", Content: string(infoContent)})
  81. fmt.Fprintf(w, "event: session_info\ndata: %s\n\n", string(infoEvent))
  82. w.Flush()
  83. // 如果有欢迎消息且是新会话,先发送 welcome 事件
  84. if sess.WelcomeMessage != "" {
  85. welcomeEvent, _ := json.Marshal(services.AIChatEvent{Type: "welcome", Content: sess.WelcomeMessage})
  86. fmt.Fprintf(w, "event: welcome\ndata: %s\n\n", string(welcomeEvent))
  87. w.Flush()
  88. }
  89. eventCh := make(chan services.AIChatEvent, 50)
  90. go acpManager.Prompt(sess, req.Message, eventCh)
  91. for event := range eventCh {
  92. data, _ := json.Marshal(event)
  93. fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event.Type, string(data))
  94. w.Flush()
  95. }
  96. })
  97. return nil
  98. }
  99. // GetAiSessionList 获取用户的会话历史列表
  100. // GET /ai/sessions/list
  101. func GetAiSessionList(c *fiber.Ctx) error {
  102. userId := middleware.AuthGetUserName(c)
  103. list := acpManager.GetSessionList(userId)
  104. return Success(c, list)
  105. }
  106. // GetCurrentAiSession 获取当前活跃会话信息(含实际生效的 agent/model 与最近用量)
  107. // GET /ai/sessions/current
  108. func GetCurrentAiSession(c *fiber.Ctx) error {
  109. userId := middleware.AuthGetUserName(c)
  110. sess := acpManager.GetSessionInfo(userId)
  111. if sess == nil {
  112. // 无活跃会话,返回空对象
  113. return Success(c, fiber.Map{})
  114. }
  115. var contextUsagePercent float64
  116. var turnDurationMs int64
  117. if sess.Client != nil {
  118. contextUsagePercent, turnDurationMs = sess.Client.GetMeta()
  119. }
  120. return Success(c, fiber.Map{
  121. "sessionId": sess.SessionId,
  122. "title": sess.Title,
  123. "agentId": sess.AgentId,
  124. "modelId": sess.ModelId,
  125. "contextUsagePercent": contextUsagePercent,
  126. "turnDurationMs": turnDurationMs,
  127. })
  128. }
  129. // CreateAiSession 创建新的 AI 会话(保留旧会话到历史)
  130. // POST /ai/sessions/new
  131. func CreateAiSession(c *fiber.Ctx) error {
  132. userId := middleware.AuthGetUserName(c)
  133. // 创建新会话(旧会话自动归档到历史)
  134. sess, err := acpManager.CreateNewSession(userId)
  135. if err != nil {
  136. return Error(c, fmt.Sprintf("创建会话失败: %v", err))
  137. }
  138. return Success(c, fiber.Map{
  139. "sessionId": sess.SessionId,
  140. "welcomeMessage": sess.WelcomeMessage,
  141. "agentId": sess.AgentId,
  142. "modelId": sess.ModelId,
  143. })
  144. }
  145. // SwitchAiSession 切换到历史会话(恢复 AI 上下文,轻量响应)
  146. // POST /ai/sessions/:id
  147. func SwitchAiSession(c *fiber.Ctx) error {
  148. sessionId := utils.CopyString(c.Params("id"))
  149. if sessionId == "" {
  150. return Fail(c, "sessionId 不能为空")
  151. }
  152. userId := middleware.AuthGetUserName(c)
  153. sess, err := acpManager.LoadSession(userId, sessionId)
  154. if err != nil {
  155. return Error(c, fmt.Sprintf("加载会话失败: %v", err))
  156. }
  157. return Success(c, fiber.Map{
  158. "sessionId": sess.SessionId,
  159. "title": sess.Title,
  160. "welcomeMessage": sess.WelcomeMessage,
  161. "agentId": sess.AgentId,
  162. "modelId": sess.ModelId,
  163. })
  164. }
  165. // StreamLoadAiSession SSE 流式推送回放消息
  166. // GET /ai/sessions/:id/load
  167. func StreamLoadAiSession(c *fiber.Ctx) error {
  168. sessionId := utils.CopyString(c.Params("id"))
  169. if sessionId == "" {
  170. return Fail(c, "sessionId 不能为空")
  171. }
  172. userId := middleware.AuthGetUserName(c)
  173. // 获取回放消息(会话必须已通过 SwitchAiSession 加载)
  174. replayMessages := acpManager.GetReplayMessages(userId)
  175. if replayMessages == nil {
  176. return Fail(c, "会话未加载,请先调用切换会话接口")
  177. }
  178. // SSE 流式响应
  179. c.Set("Content-Type", "text/event-stream")
  180. c.Set("Cache-Control", "no-cache")
  181. c.Set("Connection", "keep-alive")
  182. c.Set("X-Accel-Buffering", "no")
  183. c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
  184. var totalBytes int
  185. for _, msg := range replayMessages {
  186. data, _ := json.Marshal(msg)
  187. totalBytes += len(msg.Content)
  188. fmt.Fprintf(w, "event: message\ndata: %s\n\n", string(data))
  189. w.Flush()
  190. }
  191. // 发送 done 事件,包含统计信息和建议
  192. suggestNewSession := totalBytes >= 100*1024 // 100KB 以上建议新建
  193. donePayload, _ := json.Marshal(fiber.Map{
  194. "sessionId": sessionId,
  195. "totalMessages": len(replayMessages),
  196. "totalBytes": totalBytes,
  197. "suggestNewSession": suggestNewSession,
  198. })
  199. fmt.Fprintf(w, "event: done\ndata: %s\n\n", string(donePayload))
  200. w.Flush()
  201. })
  202. return nil
  203. }
  204. // UpdateAiSessionTitle 更新会话标题
  205. // PATCH /ai/sessions/:id
  206. func UpdateAiSessionTitle(c *fiber.Ctx) error {
  207. sessionId := utils.CopyString(c.Params("id"))
  208. if sessionId == "" {
  209. return Fail(c, "sessionId 不能为空")
  210. }
  211. var req struct {
  212. Title string `json:"title"`
  213. }
  214. if err := c.BodyParser(&req); err != nil {
  215. return Fail(c, "Invalid request body")
  216. }
  217. userId := middleware.AuthGetUserName(c)
  218. acpManager.UpdateSessionTitle(userId, sessionId, req.Title)
  219. return Success[any](c, nil, "标题已更新")
  220. }
  221. // DeleteAiSession 删除 AI 会话
  222. // DELETE /ai/sessions/:id
  223. func DeleteAiSession(c *fiber.Ctx) error {
  224. sessionId := utils.CopyString(c.Params("id"))
  225. userId := middleware.AuthGetUserName(c)
  226. if sessionId == "" {
  227. // 无 id 参数,删除当前活跃会话
  228. acpManager.DeleteSession(userId)
  229. } else {
  230. // 删除指定会话
  231. acpManager.DeleteSessionFromHistory(userId, sessionId)
  232. }
  233. return Success[any](c, nil, "会话已删除")
  234. }
  235. // CancelAiChat 取消当前 AI 操作
  236. // POST /ai/cancel
  237. func CancelAiChat(c *fiber.Ctx) error {
  238. userId := middleware.AuthGetUserName(c)
  239. sess := acpManager.GetSessionInfo(userId)
  240. if sess == nil {
  241. return Fail(c, "没有活跃的会话")
  242. }
  243. acpManager.Cancel(sess)
  244. return Success[any](c, nil, "已取消")
  245. }
  246. // ResolvePermission 前端回传写权限选择
  247. // POST /ai/permission
  248. func ResolvePermission(c *fiber.Ctx) error {
  249. var req struct {
  250. OptionId string `json:"optionId"`
  251. }
  252. if err := c.BodyParser(&req); err != nil {
  253. return Fail(c, "Invalid request body")
  254. }
  255. if req.OptionId == "" {
  256. return Fail(c, "optionId 不能为空")
  257. }
  258. userId := middleware.AuthGetUserName(c)
  259. if err := acpManager.ResolvePermission(userId, req.OptionId); err != nil {
  260. return Fail(c, err.Error())
  261. }
  262. return Success[any](c, nil, "已回复")
  263. }
  264. // DownloadAiFile 下载 AI 生成的文件
  265. // GET /ai/files/download?key=xxx
  266. func DownloadAiFile(c *fiber.Ctx) error {
  267. key := utils.CopyString(c.Query("key"))
  268. if key == "" {
  269. return Fail(c, "key 不能为空")
  270. }
  271. // 直接从 MinIO 读取文件(key 即 objectKey)
  272. obj, err := minioUtil.Client.GetObject(context.Background(), filestore.AIFileBucket, key, minio.GetObjectOptions{})
  273. if err != nil {
  274. return Fail(c, "文件不存在")
  275. }
  276. defer obj.Close()
  277. // 获取文件信息
  278. stat, err := obj.Stat()
  279. if err != nil {
  280. return Fail(c, fmt.Sprintf("文件不存在: %v", err))
  281. }
  282. // 读取全部内容
  283. data, err := io.ReadAll(obj)
  284. if err != nil {
  285. return Error(c, fmt.Sprintf("读取文件失败: %v", err))
  286. }
  287. // 从 key 中提取文件名(key 格式: prefix/userId/sessionId/uuid_fileName)
  288. fileName := filepath.Base(key)
  289. // 去掉 uuid 前缀(前9个字符: 8位uuid + 下划线)
  290. if len(fileName) > 9 {
  291. fileName = fileName[9:]
  292. }
  293. c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  294. c.Set("Content-Type", stat.ContentType)
  295. return c.Send(data)
  296. }
  297. // UploadAiFile 上传文件给 AI 分析
  298. // POST /ai/files/upload
  299. func UploadAiFile(c *fiber.Ctx) error {
  300. userId := middleware.AuthGetUserName(c)
  301. sess, err := acpManager.GetOrCreateSession(userId)
  302. if err != nil {
  303. return Error(c, fmt.Sprintf("AI 会话创建失败: %v", err))
  304. }
  305. // 读取上传文件
  306. file, err := c.FormFile("file")
  307. if err != nil {
  308. return Fail(c, "请选择要上传的文件")
  309. }
  310. // 限制文件大小(最大 2MB)
  311. if file.Size > 2*1024*1024 {
  312. return Fail(c, "文件大小不能超过 2MB")
  313. }
  314. // 读取文件内容
  315. f, err := file.Open()
  316. if err != nil {
  317. return Error(c, "打开文件失败")
  318. }
  319. defer f.Close()
  320. data, err := io.ReadAll(f)
  321. if err != nil {
  322. return Error(c, "读取文件失败")
  323. }
  324. // 写入 FileStore(存到 ACP 的 FileStore,这样 Agent readTextFile 可以读到)
  325. virtualPath := fmt.Sprintf("/uploads/%s", file.Filename)
  326. record, err := sess.Client.FileStore.WriteFile(userId, sess.SessionId, virtualPath, string(data))
  327. if err != nil {
  328. return Error(c, fmt.Sprintf("保存文件失败: %v", err))
  329. }
  330. return Success(c, fiber.Map{
  331. "key": record.Key,
  332. "fileName": record.FileName,
  333. "path": record.Path,
  334. "size": record.Size,
  335. })
  336. }
  337. // ListAiFiles 获取用户的 AI 文件列表
  338. // GET /ai/files/list?type=upload|download
  339. func ListAiFiles(c *fiber.Ctx) error {
  340. userId := middleware.AuthGetUserName(c)
  341. fileType := utils.CopyString(c.Query("type"))
  342. if fileType != "upload" && fileType != "download" {
  343. return Fail(c, "type 参数必须为 upload 或 download")
  344. }
  345. // 按用户前缀列出 MinIO 文件
  346. prefix := fmt.Sprintf("%s/%s/", fileType, userId)
  347. objects, err := minioUtil.ListFilesObjectFromBucket(filestore.AIFileBucket, prefix, true)
  348. if err != nil {
  349. return Error(c, fmt.Sprintf("获取文件列表失败: %v", err))
  350. }
  351. type FileItem struct {
  352. Key string `json:"key"`
  353. FileName string `json:"fileName"`
  354. Size int64 `json:"size"`
  355. CreatedAt int64 `json:"createdAt"` // Unix ms
  356. ExpiresAt int64 `json:"expiresAt"` // Unix ms(0 表示不过期)
  357. }
  358. now := time.Now()
  359. list := make([]FileItem, 0, len(objects))
  360. for _, obj := range objects {
  361. // 跳过已过期的文件(MinIO 可能延迟清理)
  362. if !obj.Expires.IsZero() && obj.Expires.Before(now) {
  363. continue
  364. }
  365. // 从 key 中提取文件名: {prefix}/{userId}/{sessionId}/{uuid}_{fileName}
  366. fileName := filepath.Base(obj.Key)
  367. if len(fileName) > 9 { // 去掉 "uuid_" 前缀(8位uuid + 下划线)
  368. fileName = fileName[9:]
  369. }
  370. var expiresAt int64
  371. if !obj.Expires.IsZero() {
  372. expiresAt = obj.Expires.UnixMilli()
  373. }
  374. list = append(list, FileItem{
  375. Key: obj.Key,
  376. FileName: fileName,
  377. Size: obj.Size,
  378. CreatedAt: obj.LastModified.UnixMilli(),
  379. ExpiresAt: expiresAt,
  380. })
  381. }
  382. // 按创建时间倒序
  383. sort.Slice(list, func(i, j int) bool {
  384. return list[i].CreatedAt > list[j].CreatedAt
  385. })
  386. return Success(c, list)
  387. }