acp.go 29 KB

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