acp.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. // Package acp 实现 ACP (Agent Client Protocol) 客户端
  2. // 基于 ACP v1 规范,通过 stdin/stdout ND-JSON 与 Agent 子进程通讯
  3. package acp
  4. import (
  5. "bufio"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "sync"
  13. "sync/atomic"
  14. "fwh-toolbox-server/utils/filestore"
  15. "go.uber.org/zap"
  16. )
  17. // ============ JSON-RPC 2.0 基础类型 ============
  18. // Request JSON-RPC 请求
  19. type Request struct {
  20. JSONRPC string `json:"jsonrpc"`
  21. ID int64 `json:"id"`
  22. Method string `json:"method"`
  23. Params any `json:"params,omitempty"`
  24. }
  25. // Response JSON-RPC 响应
  26. type Response struct {
  27. JSONRPC string `json:"jsonrpc"`
  28. ID *int64 `json:"id,omitempty"`
  29. Method string `json:"method,omitempty"`
  30. Result json.RawMessage `json:"result,omitempty"`
  31. Error *RPCError `json:"error,omitempty"`
  32. Params json.RawMessage `json:"params,omitempty"`
  33. }
  34. // RPCError JSON-RPC 错误
  35. type RPCError struct {
  36. Code int `json:"code"`
  37. Message string `json:"message"`
  38. }
  39. // ============ ACP 协议类型 ============
  40. // InitializeParams 初始化请求参数
  41. type InitializeParams struct {
  42. ProtocolVersion int `json:"protocolVersion"`
  43. ClientInfo ClientInfo `json:"clientInfo"`
  44. ClientCapabilities ClientCapabilities `json:"clientCapabilities"`
  45. }
  46. // ClientInfo 客户端信息
  47. type ClientInfo struct {
  48. Name string `json:"name"`
  49. Version string `json:"version"`
  50. }
  51. // ClientCapabilities 客户端能力声明
  52. type ClientCapabilities struct {
  53. FS *FSCapabilities `json:"fs,omitempty"`
  54. Terminal bool `json:"terminal,omitempty"`
  55. }
  56. // FSCapabilities 文件系统能力
  57. type FSCapabilities struct {
  58. ReadTextFile bool `json:"readTextFile"`
  59. WriteTextFile bool `json:"writeTextFile"`
  60. }
  61. // NewSessionParams 创建会话参数
  62. type NewSessionParams struct {
  63. CWD string `json:"cwd"`
  64. MCPServers []any `json:"mcpServers"`
  65. }
  66. // NewSessionResult 创建会话响应
  67. type NewSessionResult struct {
  68. SessionId string `json:"sessionId"`
  69. Modes *SessionModes `json:"modes,omitempty"`
  70. }
  71. // SessionModes 会话模式
  72. type SessionModes struct {
  73. CurrentModeId string `json:"currentModeId"`
  74. AvailableModes []SessionMode `json:"availableModes"`
  75. }
  76. // SessionMode 单个模式
  77. type SessionMode struct {
  78. Id string `json:"id"`
  79. Name string `json:"name"`
  80. Description string `json:"description"`
  81. Meta *SessionMeta `json:"_meta,omitempty"`
  82. }
  83. // SessionMeta 模式元数据
  84. type SessionMeta struct {
  85. WelcomeMessage string `json:"welcomeMessage"`
  86. }
  87. // PromptParams 发送消息参数
  88. type PromptParams struct {
  89. SessionId string `json:"sessionId"`
  90. Prompt []ContentBlock `json:"prompt"`
  91. }
  92. // ContentBlock 内容块
  93. type ContentBlock struct {
  94. Type string `json:"type"`
  95. Text string `json:"text"`
  96. }
  97. // PromptResult prompt 响应
  98. type PromptResult struct {
  99. StopReason string `json:"stopReason"`
  100. }
  101. // CancelParams 取消参数
  102. type CancelParams struct {
  103. SessionId string `json:"sessionId"`
  104. }
  105. // ============ Session Update 事件类型 ============
  106. // SessionUpdate 会话更新通知
  107. type SessionUpdate struct {
  108. SessionId string `json:"sessionId"`
  109. Update json.RawMessage `json:"update"`
  110. }
  111. // UpdateBase 更新基础类型
  112. type UpdateBase struct {
  113. SessionUpdate string `json:"sessionUpdate"`
  114. }
  115. // AgentMessageChunk Agent 文本流式输出
  116. type AgentMessageChunk struct {
  117. SessionUpdate string `json:"sessionUpdate"` // "agent_message_chunk"
  118. MessageId string `json:"messageId,omitempty"`
  119. Content ContentBlock `json:"content"`
  120. }
  121. // ToolCall 工具调用通知
  122. type ToolCall struct {
  123. SessionUpdate string `json:"sessionUpdate"` // "tool_call"
  124. ToolCallId string `json:"toolCallId"`
  125. Title string `json:"title"`
  126. Status string `json:"status"` // pending, running, completed, failed
  127. }
  128. // ToolCallUpdate 工具调用状态更新
  129. type ToolCallUpdate struct {
  130. SessionUpdate string `json:"sessionUpdate"` // "tool_call_update"
  131. ToolCallId string `json:"toolCallId"`
  132. Title string `json:"title,omitempty"`
  133. Status string `json:"status"`
  134. }
  135. // ============ 客户端事件(对外输出) ============
  136. // Event 输出给上层的事件
  137. type Event struct {
  138. Type string // "text", "tool_call", "tool_update", "done", "error", "permission"
  139. Content string
  140. ToolName string
  141. ToolStatus string
  142. SessionId string
  143. StopReason string
  144. // 权限请求相关
  145. Permission *PermissionEvent `json:"permission,omitempty"`
  146. }
  147. // PermissionEvent 权限请求事件(推给前端)
  148. type PermissionEvent struct {
  149. RequestId string `json:"requestId"` // 用于前端回传
  150. Title string `json:"title"` // 权限标题
  151. Options []PermissionOption `json:"options"` // 可选选项
  152. }
  153. // PermissionOption 权限选项
  154. type PermissionOption struct {
  155. OptionId string `json:"optionId"`
  156. Name string `json:"name"`
  157. Kind string `json:"kind"` // allow_once, allow_always, deny
  158. }
  159. // ============ ACP Client 实现 ============
  160. // Client ACP 客户端(管理单个 Agent 进程)
  161. type Client struct {
  162. cmd *exec.Cmd
  163. stdin io.WriteCloser
  164. scanner *bufio.Scanner
  165. sessionId string
  166. requestId int64
  167. mu sync.Mutex // 保护 stdin 写入
  168. readMu sync.Mutex // 保护 stdout 读取
  169. // 权限请求等待机制
  170. permissionCh chan string // 接收前端选择的 optionId
  171. eventCh chan<- Event // 当前 prompt 的事件通道(用于推送 permission 事件)
  172. // 文件存储
  173. FileStore *filestore.FileStore
  174. UserId string
  175. // 文本累积(用于合并日志输出)
  176. textBuffer string
  177. }
  178. // ClientConfig 客户端配置
  179. type ClientConfig struct {
  180. Command string // Agent 命令(如 "kiro-cli")
  181. Args []string // 命令参数(如 ["acp"])
  182. WorkingDir string // 工作目录
  183. Env []string // 额外环境变量(如 "HOME=/home/user")
  184. }
  185. // NewClient 创建并启动 ACP Client
  186. func NewClient(cfg ClientConfig) (*Client, error) {
  187. cmd := exec.Command(cfg.Command, cfg.Args...)
  188. // 确保工作目录是绝对路径
  189. absDir, err := filepath.Abs(cfg.WorkingDir)
  190. if err != nil {
  191. absDir = cfg.WorkingDir
  192. }
  193. cmd.Dir = absDir
  194. // 设置环境变量
  195. cmd.Env = append(os.Environ(), cfg.Env...)
  196. stdin, err := cmd.StdinPipe()
  197. if err != nil {
  198. return nil, fmt.Errorf("创建 stdin pipe 失败: %w", err)
  199. }
  200. stdout, err := cmd.StdoutPipe()
  201. if err != nil {
  202. return nil, fmt.Errorf("创建 stdout pipe 失败: %w", err)
  203. }
  204. // 捕获 stderr
  205. stderrPipe, _ := cmd.StderrPipe()
  206. go func() {
  207. if stderrPipe != nil {
  208. s := bufio.NewScanner(stderrPipe)
  209. for s.Scan() {
  210. zap.L().Warn("[ACP] agent stderr", zap.String("line", s.Text()))
  211. }
  212. }
  213. }()
  214. if err := cmd.Start(); err != nil {
  215. return nil, fmt.Errorf("启动 Agent 进程失败: %w", err)
  216. }
  217. scanner := bufio.NewScanner(stdout)
  218. scanner.Buffer(make([]byte, 0, 2*1024*1024), 2*1024*1024) // 2MB buffer
  219. return &Client{
  220. cmd: cmd,
  221. stdin: stdin,
  222. scanner: scanner,
  223. permissionCh: make(chan string, 1),
  224. FileStore: filestore.NewFileStore("upload"),
  225. }, nil
  226. }
  227. // ResolvePermission 前端回传权限选择结果
  228. func (c *Client) ResolvePermission(optionId string) {
  229. select {
  230. case c.permissionCh <- optionId:
  231. default:
  232. // 没有等待中的权限请求,忽略
  233. }
  234. }
  235. // Initialize 执行初始化握手
  236. func (c *Client) Initialize() error {
  237. params := InitializeParams{
  238. ProtocolVersion: 1,
  239. ClientInfo: ClientInfo{
  240. Name: "fwh-toolbox",
  241. Version: "1.0.0",
  242. },
  243. ClientCapabilities: ClientCapabilities{
  244. FS: &FSCapabilities{
  245. ReadTextFile: true,
  246. WriteTextFile: true,
  247. },
  248. Terminal: false, // 不声明终端能力,强制 Agent 使用 writeTextFile
  249. },
  250. }
  251. _, err := c.sendAndWait("initialize", params)
  252. return err
  253. }
  254. // NewSession 创建新会话,返回 sessionId 和 welcomeMessage
  255. func (c *Client) NewSession(cwd string) (string, string, error) {
  256. params := NewSessionParams{
  257. CWD: cwd,
  258. MCPServers: []any{},
  259. }
  260. result, err := c.sendAndWait("session/new", params)
  261. if err != nil {
  262. return "", "", err
  263. }
  264. var res NewSessionResult
  265. if err := json.Unmarshal(result, &res); err != nil {
  266. return "", "", fmt.Errorf("解析 session/new 响应失败: %w", err)
  267. }
  268. zap.L().Info("session/new", zap.String("result", string(result)))
  269. c.sessionId = res.SessionId
  270. // 提取当前 mode 的 welcomeMessage
  271. var welcomeMsg string
  272. if res.Modes != nil {
  273. for _, mode := range res.Modes.AvailableModes {
  274. if mode.Id == res.Modes.CurrentModeId && mode.Meta != nil {
  275. welcomeMsg = mode.Meta.WelcomeMessage
  276. break
  277. }
  278. }
  279. }
  280. return res.SessionId, welcomeMsg, nil
  281. }
  282. // ReplayMessage 回放的单条消息
  283. type ReplayMessage struct {
  284. Role string `json:"role"` // "user" 或 "assistant"
  285. Content string `json:"content"`
  286. MessageId string `json:"messageId,omitempty"`
  287. }
  288. // LoadSession 加载已有会话(恢复历史对话上下文),返回回放的消息列表
  289. func (c *Client) LoadSession(sessionId string, cwd string) (string, string, []ReplayMessage, error) {
  290. params := map[string]any{
  291. "sessionId": sessionId,
  292. "cwd": cwd,
  293. "mcpServers": []any{},
  294. }
  295. // 发送 session/load 请求
  296. id := c.sendRequest("session/load", params)
  297. // 收集回放消息
  298. var replayMessages []ReplayMessage
  299. currentMsg := &ReplayMessage{}
  300. // 读取回放事件直到收到 session/load 的 response
  301. for c.scanner.Scan() {
  302. line := c.scanner.Text()
  303. if line == "" {
  304. continue
  305. }
  306. var msg struct {
  307. JSONRPC string `json:"jsonrpc"`
  308. ID json.RawMessage `json:"id,omitempty"`
  309. Method string `json:"method,omitempty"`
  310. Result json.RawMessage `json:"result,omitempty"`
  311. Error *RPCError `json:"error,omitempty"`
  312. Params json.RawMessage `json:"params,omitempty"`
  313. }
  314. if err := json.Unmarshal([]byte(line), &msg); err != nil {
  315. continue
  316. }
  317. // 检查是否是 session/load 的响应
  318. hasId := len(msg.ID) > 0 && string(msg.ID) != "null"
  319. if hasId && msg.Method == "" {
  320. var numId int64
  321. json.Unmarshal(msg.ID, &numId)
  322. if numId == id {
  323. // session/load 完成
  324. if msg.Error != nil {
  325. return "", "", nil, fmt.Errorf("session/load 错误: %s", msg.Error.Message)
  326. }
  327. c.sessionId = sessionId
  328. // 追加最后一条未关闭的消息
  329. if currentMsg.Content != "" {
  330. replayMessages = append(replayMessages, *currentMsg)
  331. }
  332. // 解析响应中的 welcomeMessage
  333. var welcomeMsg string
  334. if len(msg.Result) > 0 {
  335. var res NewSessionResult
  336. if err := json.Unmarshal(msg.Result, &res); err == nil && res.Modes != nil {
  337. for _, mode := range res.Modes.AvailableModes {
  338. if mode.Id == res.Modes.CurrentModeId && mode.Meta != nil {
  339. welcomeMsg = mode.Meta.WelcomeMessage
  340. break
  341. }
  342. }
  343. }
  344. }
  345. return sessionId, welcomeMsg, replayMessages, nil
  346. }
  347. }
  348. // 处理回放的 session/update 通知
  349. if msg.Method == "session/update" || msg.Method == "_kiro.dev/session/update" {
  350. var notif SessionUpdate
  351. if err := json.Unmarshal(msg.Params, &notif); err != nil {
  352. continue
  353. }
  354. var base UpdateBase
  355. if err := json.Unmarshal(notif.Update, &base); err != nil {
  356. continue
  357. }
  358. switch base.SessionUpdate {
  359. case "user_message_chunk":
  360. // 新的用户消息 → 保存上一条并开始新消息
  361. if currentMsg.Content != "" {
  362. replayMessages = append(replayMessages, *currentMsg)
  363. }
  364. var chunk AgentMessageChunk
  365. json.Unmarshal(notif.Update, &chunk)
  366. currentMsg = &ReplayMessage{Role: "user", Content: chunk.Content.Text, MessageId: chunk.MessageId}
  367. case "agent_message_chunk":
  368. // AI 消息
  369. var chunk AgentMessageChunk
  370. json.Unmarshal(notif.Update, &chunk)
  371. if currentMsg.Role != "assistant" || (chunk.MessageId != "" && chunk.MessageId != currentMsg.MessageId) {
  372. // 新的 AI 消息 → 保存上一条
  373. if currentMsg.Content != "" {
  374. replayMessages = append(replayMessages, *currentMsg)
  375. }
  376. currentMsg = &ReplayMessage{Role: "assistant", Content: chunk.Content.Text, MessageId: chunk.MessageId}
  377. } else {
  378. // 同一条消息的续写
  379. currentMsg.Content += chunk.Content.Text
  380. }
  381. case "agent_thought_chunk":
  382. // 思考内容忽略(不显示给用户)
  383. case "tool_call", "tool_call_update", "tool_call_chunk":
  384. // 工具调用回放忽略
  385. default:
  386. // 其他类型忽略
  387. }
  388. continue
  389. }
  390. // 忽略其他通知(kiro 扩展等)
  391. }
  392. return "", "", nil, fmt.Errorf("session/load 未收到响应(进程可能已退出)")
  393. }
  394. // Prompt 发送消息并流式读取事件
  395. // eventCh 会在 turn 结束或出错时关闭
  396. func (c *Client) Prompt(sessionId string, message string, eventCh chan<- Event) {
  397. defer close(eventCh)
  398. // 设置当前事件通道(供 handleAgentRequest 推送 permission 事件)
  399. c.eventCh = eventCh
  400. params := PromptParams{
  401. SessionId: sessionId,
  402. Prompt: []ContentBlock{
  403. {Type: "text", Text: message},
  404. },
  405. }
  406. // 发送 prompt 请求
  407. promptId := c.sendRequest("session/prompt", params)
  408. zap.L().Debug("[ACP] prompt 已发送", zap.Int64("promptId", promptId), zap.String("sessionId", sessionId))
  409. // 持续读取直到收到 prompt 的 response
  410. for c.scanner.Scan() {
  411. line := c.scanner.Text()
  412. if line == "" {
  413. continue
  414. }
  415. zap.L().Debug("[ACP] <<< 收到", zap.String("raw", line[:min(len(line), 500)]))
  416. // 用宽松结构解析,兼容所有消息格式
  417. var msg struct {
  418. JSONRPC string `json:"jsonrpc"`
  419. ID json.RawMessage `json:"id,omitempty"`
  420. Method string `json:"method,omitempty"`
  421. Result json.RawMessage `json:"result,omitempty"`
  422. Error *RPCError `json:"error,omitempty"`
  423. Params json.RawMessage `json:"params,omitempty"`
  424. }
  425. if err := json.Unmarshal([]byte(line), &msg); err != nil {
  426. zap.L().Warn("[ACP] JSON解析失败,跳过", zap.String("line", line[:min(len(line), 100)]))
  427. continue
  428. }
  429. // 解析 ID(兼容 int64 和 string)
  430. hasId := len(msg.ID) > 0 && string(msg.ID) != "null"
  431. var numericId int64
  432. isPromptResp := false
  433. if hasId {
  434. json.Unmarshal(msg.ID, &numericId)
  435. isPromptResp = numericId == promptId && msg.Method == ""
  436. }
  437. // 收到 prompt 的响应 → turn 结束
  438. if isPromptResp {
  439. zap.L().Debug("[ACP] 收到 prompt 响应(turn结束)", zap.Int64("id", numericId))
  440. // 打印本轮完整回复
  441. if c.textBuffer != "" {
  442. zap.L().Info("[ACP] AI 回复完整内容", zap.String("text", c.textBuffer))
  443. c.textBuffer = ""
  444. }
  445. var result PromptResult
  446. if msg.Error != nil {
  447. eventCh <- Event{Type: "error", Content: msg.Error.Message}
  448. } else if err := json.Unmarshal(msg.Result, &result); err == nil {
  449. eventCh <- Event{Type: "done", SessionId: sessionId, StopReason: result.StopReason}
  450. }
  451. return
  452. }
  453. // 处理 notification (session/update 或 _kiro.dev/session/update)
  454. if !hasId && (msg.Method == "session/update" || msg.Method == "_kiro.dev/session/update") {
  455. c.handleSessionUpdate(msg.Params, eventCh)
  456. continue
  457. }
  458. // 处理 Agent→Client 反向请求(有 ID + Method = 请求)
  459. if hasId && msg.Method != "" {
  460. zap.L().Debug("[ACP] 收到 Agent 反向请求", zap.String("method", msg.Method), zap.String("id", string(msg.ID)))
  461. c.handleAgentRequest(msg.ID, msg.Method, msg.Params)
  462. continue
  463. }
  464. // 未匹配的消息(kiro扩展通知等)
  465. if msg.Method != "" {
  466. c.handleExtensionNotification(msg.Method, msg.Params, eventCh)
  467. } else {
  468. zap.L().Debug("[ACP] 未处理的消息", zap.String("line", line[:min(len(line), 200)]))
  469. }
  470. }
  471. // Scanner 结束说明进程退出
  472. eventCh <- Event{Type: "error", Content: "Agent 进程已断开"}
  473. }
  474. // Cancel 取消当前 prompt turn(ACP 协议:Notification, method="session/cancel", params={sessionId})
  475. func (c *Client) Cancel(sessionId string) {
  476. c.sendNotification("session/cancel", CancelParams{SessionId: sessionId})
  477. }
  478. // GetSessionId 获取当前会话 ID
  479. func (c *Client) GetSessionId() string {
  480. return c.sessionId
  481. }
  482. // Close 关闭 ACP Client,终止 Agent 进程
  483. func (c *Client) Close() {
  484. // 关闭 stdin 通知 Agent 退出
  485. c.stdin.Close()
  486. // 终止进程
  487. if c.cmd.Process != nil {
  488. c.cmd.Process.Kill()
  489. // Wait 回收子进程资源,防止僵尸进程
  490. go c.cmd.Wait()
  491. }
  492. // 解除可能阻塞在 permissionCh 上的 goroutine
  493. select {
  494. case c.permissionCh <- "deny":
  495. default:
  496. }
  497. // 清理 FileStore
  498. if c.FileStore != nil {
  499. c.FileStore.Clear()
  500. }
  501. }
  502. // IsAlive 检查 Agent 进程是否存活
  503. func (c *Client) IsAlive() bool {
  504. return c.cmd.ProcessState == nil
  505. }
  506. // ============ 内部方法 ============
  507. // sendRequest 发送请求(不等待响应),返回 request ID
  508. func (c *Client) sendRequest(method string, params any) int64 {
  509. c.mu.Lock()
  510. defer c.mu.Unlock()
  511. id := atomic.AddInt64(&c.requestId, 1)
  512. req := Request{
  513. JSONRPC: "2.0",
  514. ID: id,
  515. Method: method,
  516. Params: params,
  517. }
  518. data, err := json.Marshal(req)
  519. if err != nil {
  520. zap.L().Error("[ACP] 序列化请求失败", zap.Error(err))
  521. return id
  522. }
  523. zap.L().Debug("[ACP] >>> 发送", zap.String("raw", string(data)))
  524. data = append(data, '\n')
  525. if _, err := c.stdin.Write(data); err != nil {
  526. zap.L().Error("[ACP] 写入 stdin 失败", zap.String("method", method), zap.Error(err))
  527. }
  528. return id
  529. }
  530. // sendNotification 发送 JSON-RPC Notification(不带 id,不期望响应)
  531. func (c *Client) sendNotification(method string, params any) {
  532. c.mu.Lock()
  533. defer c.mu.Unlock()
  534. notif := struct {
  535. JSONRPC string `json:"jsonrpc"`
  536. Method string `json:"method"`
  537. Params any `json:"params,omitempty"`
  538. }{
  539. JSONRPC: "2.0",
  540. Method: method,
  541. Params: params,
  542. }
  543. data, err := json.Marshal(notif)
  544. if err != nil {
  545. zap.L().Error("[ACP] 序列化通知失败", zap.Error(err))
  546. return
  547. }
  548. zap.L().Debug("[ACP] >>> 发送(notification)", zap.String("raw", string(data)))
  549. data = append(data, '\n')
  550. if _, err := c.stdin.Write(data); err != nil {
  551. zap.L().Error("[ACP] 写入 stdin 失败(通知)", zap.String("method", method), zap.Error(err))
  552. }
  553. }
  554. // sendAndWait 发送请求并等待对应 ID 的响应
  555. func (c *Client) sendAndWait(method string, params any) (json.RawMessage, error) {
  556. id := c.sendRequest(method, params)
  557. // 读取响应(跳过 notification 和其他消息)
  558. for c.scanner.Scan() {
  559. line := c.scanner.Text()
  560. if line == "" {
  561. continue
  562. }
  563. var resp Response
  564. if err := json.Unmarshal([]byte(line), &resp); err != nil {
  565. continue
  566. }
  567. // 匹配 ID 的响应
  568. if resp.ID != nil && *resp.ID == id {
  569. if resp.Error != nil {
  570. return nil, fmt.Errorf("ACP 错误 [%d]: %s", resp.Error.Code, resp.Error.Message)
  571. }
  572. return resp.Result, nil
  573. }
  574. // 跳过 notification(session/new 之前可能收到 kiro 扩展通知)
  575. }
  576. return nil, fmt.Errorf("未收到 %s 的响应(进程可能已退出)", method)
  577. }
  578. // handleSessionUpdate 解析并分发 session/update 通知
  579. func (c *Client) handleSessionUpdate(params json.RawMessage, eventCh chan<- Event) {
  580. var notif SessionUpdate
  581. if err := json.Unmarshal(params, &notif); err != nil {
  582. return
  583. }
  584. // 解析 update 的类型
  585. var base UpdateBase
  586. if err := json.Unmarshal(notif.Update, &base); err != nil {
  587. return
  588. }
  589. // zap.L().Debug("[ACP] session/update", zap.String("type", base.SessionUpdate))
  590. switch base.SessionUpdate {
  591. case "agent_message_chunk":
  592. var chunk AgentMessageChunk
  593. if err := json.Unmarshal(notif.Update, &chunk); err == nil {
  594. c.textBuffer += chunk.Content.Text
  595. eventCh <- Event{Type: "text", Content: chunk.Content.Text}
  596. }
  597. case "agent_thought_chunk":
  598. var chunk AgentMessageChunk
  599. if err := json.Unmarshal(notif.Update, &chunk); err == nil {
  600. c.textBuffer += chunk.Content.Text
  601. eventCh <- Event{Type: "text", Content: chunk.Content.Text}
  602. }
  603. case "tool_call":
  604. var tc ToolCall
  605. if err := json.Unmarshal(notif.Update, &tc); err == nil {
  606. zap.L().Debug("[ACP] → tool_call", zap.String("title", tc.Title), zap.String("status", tc.Status), zap.String("id", tc.ToolCallId))
  607. eventCh <- Event{Type: "tool_call", ToolName: tc.Title, ToolStatus: tc.Status}
  608. }
  609. case "tool_call_update":
  610. var tcu ToolCallUpdate
  611. if err := json.Unmarshal(notif.Update, &tcu); err == nil {
  612. zap.L().Debug("[ACP] → tool_call_update", zap.String("title", tcu.Title), zap.String("status", tcu.Status), zap.String("id", tcu.ToolCallId))
  613. eventCh <- Event{Type: "tool_update", ToolName: tcu.Title, ToolStatus: tcu.Status}
  614. }
  615. case "tool_call_chunk":
  616. // 工具调用的流式参数输出(Kiro 扩展)
  617. zap.L().Debug("[ACP] → tool_call_chunk (ignored)")
  618. case "plan":
  619. zap.L().Debug("[ACP] → plan update")
  620. default:
  621. zap.L().Debug("[ACP] → 未知 session/update 类型", zap.String("type", base.SessionUpdate))
  622. }
  623. }
  624. // handleExtensionNotification 处理 Kiro 扩展通知
  625. func (c *Client) handleExtensionNotification(method string, params json.RawMessage, eventCh chan<- Event) {
  626. switch method {
  627. case "_kiro.dev/commands/available":
  628. // 可用命令和工具列表
  629. var data struct {
  630. SessionId string `json:"sessionId"`
  631. Commands []struct {
  632. Name string `json:"name"`
  633. Description string `json:"description"`
  634. } `json:"commands"`
  635. Tools []struct {
  636. Name string `json:"name"`
  637. Description string `json:"description"`
  638. Source string `json:"source"`
  639. } `json:"tools"`
  640. }
  641. if err := json.Unmarshal(params, &data); err == nil {
  642. zap.L().Debug("[ACP] 可用命令/工具更新",
  643. zap.Int("commands", len(data.Commands)),
  644. zap.Int("tools", len(data.Tools)),
  645. )
  646. // 推送工具列表给前端(可选)
  647. if len(data.Tools) > 0 {
  648. toolNames := make([]string, 0, len(data.Tools))
  649. for _, t := range data.Tools {
  650. toolNames = append(toolNames, t.Name)
  651. }
  652. eventCh <- Event{Type: "tools_available", Content: toJSONStr(toolNames)}
  653. }
  654. }
  655. case "_kiro.dev/metadata":
  656. // 上下文使用量和耗时
  657. var data struct {
  658. SessionId string `json:"sessionId"`
  659. ContextUsagePercentage float64 `json:"contextUsagePercentage"`
  660. TurnDurationMs int64 `json:"turnDurationMs,omitempty"`
  661. }
  662. if err := json.Unmarshal(params, &data); err == nil {
  663. if data.TurnDurationMs > 0 {
  664. zap.L().Debug("[ACP] metadata",
  665. zap.Float64("contextUsage%", data.ContextUsagePercentage),
  666. zap.Int64("turnMs", data.TurnDurationMs),
  667. )
  668. eventCh <- Event{
  669. Type: "metadata",
  670. Content: toJSONStr(map[string]any{
  671. "contextUsagePercent": data.ContextUsagePercentage,
  672. "turnDurationMs": data.TurnDurationMs,
  673. }),
  674. }
  675. }
  676. }
  677. case "_kiro.dev/subagent/list_update":
  678. // 子代理列表更新
  679. zap.L().Debug("[ACP] 子代理列表更新")
  680. case "_kiro.dev/mcp/server_initialized":
  681. // MCP Server 初始化完成
  682. var data struct {
  683. ServerName string `json:"serverName"`
  684. }
  685. json.Unmarshal(params, &data)
  686. zap.L().Info("[ACP] MCP Server 初始化完成", zap.String("server", data.ServerName))
  687. case "_kiro.dev/compaction/status":
  688. // 上下文压缩状态
  689. zap.L().Debug("[ACP] 上下文压缩中")
  690. case "_kiro.dev/clear/status":
  691. // 会话清除状态
  692. zap.L().Debug("[ACP] 会话清除中")
  693. default:
  694. zap.L().Debug("[ACP] 未处理的扩展通知", zap.String("method", method))
  695. }
  696. }
  697. // toJSONStr 序列化为 JSON 字符串
  698. func toJSONStr(v any) string {
  699. data, _ := json.Marshal(v)
  700. return string(data)
  701. }
  702. // handleAgentRequest 处理 Agent→Client 的反向请求
  703. func (c *Client) handleAgentRequest(rawId json.RawMessage, method string, rawParams json.RawMessage) {
  704. c.mu.Lock()
  705. defer c.mu.Unlock()
  706. zap.L().Debug("[ACP] 处理反向请求", zap.String("method", method), zap.String("id", string(rawId)), zap.String("params", string(rawParams[:min(len(rawParams), 200)])))
  707. var respData []byte
  708. switch method {
  709. case "readTextFile":
  710. // 读取文件:先从 FileStore 查找(MinIO),再从本地文件系统
  711. var params struct {
  712. Path string `json:"path"`
  713. Line *int `json:"line,omitempty"`
  714. Limit *int `json:"limit,omitempty"`
  715. }
  716. if err := json.Unmarshal(rawParams, &params); err == nil && params.Path != "" {
  717. var content string
  718. var readErr error
  719. // 优先从 FileStore(MinIO)读取
  720. if c.FileStore.HasFile(params.Path) {
  721. content, readErr = c.FileStore.ReadFile(params.Path)
  722. zap.L().Debug("[ACP] readTextFile 从 MinIO 读取", zap.String("path", params.Path))
  723. } else {
  724. // 回退到本地文件系统
  725. data, err := os.ReadFile(params.Path)
  726. if err == nil {
  727. content = string(data)
  728. zap.L().Debug("[ACP] readTextFile 从本地读取", zap.String("path", params.Path))
  729. } else {
  730. readErr = err
  731. }
  732. }
  733. if readErr == nil {
  734. result, _ := json.Marshal(map[string]string{"content": content})
  735. respData, _ = json.Marshal(map[string]any{
  736. "jsonrpc": "2.0",
  737. "id": rawId,
  738. "result": json.RawMessage(result),
  739. })
  740. }
  741. }
  742. if respData == nil {
  743. respData, _ = json.Marshal(map[string]any{
  744. "jsonrpc": "2.0",
  745. "id": rawId,
  746. "error": map[string]any{"code": -1, "message": "file not found"},
  747. })
  748. }
  749. case "writeTextFile":
  750. // 写入文件到 MinIO(不写本地)
  751. var params struct {
  752. Path string `json:"path"`
  753. Content string `json:"content"`
  754. }
  755. if err := json.Unmarshal(rawParams, &params); err == nil && params.Path != "" {
  756. record, err := c.FileStore.WriteFile(c.UserId, c.sessionId, params.Path, params.Content)
  757. if err == nil {
  758. respData, _ = json.Marshal(map[string]any{
  759. "jsonrpc": "2.0",
  760. "id": rawId,
  761. "result": map[string]any{},
  762. })
  763. _ = record // 文件下载通过前端标记检测实现,不再推送事件
  764. } else {
  765. zap.L().Error("[ACP] writeTextFile MinIO上传失败", zap.Error(err))
  766. }
  767. }
  768. if respData == nil {
  769. respData, _ = json.Marshal(map[string]any{
  770. "jsonrpc": "2.0",
  771. "id": rawId,
  772. "error": map[string]any{"code": -1, "message": "write failed"},
  773. })
  774. }
  775. case "requestPermission", "session/request_permission":
  776. // 解析权限请求参数
  777. var params struct {
  778. ToolCall *struct {
  779. Title string `json:"title"`
  780. } `json:"toolCall"`
  781. Options []struct {
  782. OptionId string `json:"optionId"`
  783. Name string `json:"name"`
  784. Kind string `json:"kind"`
  785. } `json:"options"`
  786. }
  787. json.Unmarshal(rawParams, &params)
  788. title := ""
  789. if params.ToolCall != nil {
  790. title = params.ToolCall.Title
  791. }
  792. // 判断是否涉及写操作(需要手动授权)
  793. isWriteOp := true
  794. // isWriteOp := false
  795. // if title != "" {
  796. // for _, keyword := range []string{"write", "Write", "create", "Create", "delete", "Delete", "修改", "写入", "创建", "删除"} {
  797. // if len(title) >= len(keyword) && containsStr(title, keyword) {
  798. // isWriteOp = true
  799. // break
  800. // }
  801. // }
  802. // }
  803. if isWriteOp && c.eventCh != nil {
  804. // 写操作:推送权限请求给前端,等待前端回复
  805. options := make([]PermissionOption, 0, len(params.Options))
  806. for _, opt := range params.Options {
  807. options = append(options, PermissionOption{
  808. OptionId: opt.OptionId,
  809. Name: opt.Name,
  810. Kind: opt.Kind,
  811. })
  812. }
  813. requestId := fmt.Sprintf("perm_%s", string(rawId))
  814. c.eventCh <- Event{
  815. Type: "permission",
  816. Permission: &PermissionEvent{
  817. RequestId: requestId,
  818. Title: title,
  819. Options: options,
  820. },
  821. }
  822. // 释放 mu 锁后等待前端回复(否则会死锁)
  823. c.mu.Unlock()
  824. selectedOptionId := <-c.permissionCh
  825. c.mu.Lock()
  826. respData, _ = json.Marshal(map[string]any{
  827. "jsonrpc": "2.0",
  828. "id": rawId,
  829. "result": map[string]any{
  830. "outcome": map[string]any{
  831. "outcome": "selected",
  832. "optionId": selectedOptionId,
  833. },
  834. },
  835. })
  836. } else {
  837. // 非写操作:自动允许
  838. respData, _ = json.Marshal(map[string]any{
  839. "jsonrpc": "2.0",
  840. "id": rawId,
  841. "result": map[string]any{
  842. "outcome": map[string]any{
  843. "outcome": "selected",
  844. "optionId": "allow_once",
  845. },
  846. },
  847. })
  848. }
  849. default:
  850. // 未知请求返回错误
  851. respData, _ = json.Marshal(map[string]any{
  852. "jsonrpc": "2.0",
  853. "id": rawId,
  854. "error": map[string]any{"code": -32601, "message": "method not supported"},
  855. })
  856. }
  857. if respData != nil {
  858. zap.L().Debug("[ACP] 发送反向响应", zap.String("method", method), zap.String("resp", string(respData[:min(len(respData), 200)])))
  859. respData = append(respData, '\n')
  860. c.stdin.Write(respData)
  861. } else {
  862. zap.L().Warn("[ACP] 反向请求无响应数据", zap.String("method", method))
  863. }
  864. }
  865. // containsStr 简单字符串包含检测
  866. func containsStr(s, substr string) bool {
  867. return len(s) >= len(substr) && (s == substr || len(s) > 0 && stringContains(s, substr))
  868. }
  869. func stringContains(s, substr string) bool {
  870. for i := 0; i <= len(s)-len(substr); i++ {
  871. if s[i:i+len(substr)] == substr {
  872. return true
  873. }
  874. }
  875. return false
  876. }
  877. func min(a, b int) int {
  878. if a < b {
  879. return a
  880. }
  881. return b
  882. }