acp.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. c.sessionId = res.SessionId
  269. // 提取当前 mode 的 welcomeMessage
  270. var welcomeMsg string
  271. if res.Modes != nil {
  272. for _, mode := range res.Modes.AvailableModes {
  273. if mode.Id == res.Modes.CurrentModeId && mode.Meta != nil {
  274. welcomeMsg = mode.Meta.WelcomeMessage
  275. break
  276. }
  277. }
  278. }
  279. return res.SessionId, welcomeMsg, nil
  280. }
  281. // ReplayMessage 回放的单条消息
  282. type ReplayMessage struct {
  283. Role string `json:"role"` // "user" 或 "assistant"
  284. Content string `json:"content"`
  285. MessageId string `json:"messageId,omitempty"`
  286. }
  287. // LoadSession 加载已有会话(恢复历史对话上下文),返回回放的消息列表
  288. func (c *Client) LoadSession(sessionId string, cwd string) (string, []ReplayMessage, error) {
  289. params := map[string]any{
  290. "sessionId": sessionId,
  291. "cwd": cwd,
  292. "mcpServers": []any{},
  293. }
  294. // 发送 session/load 请求
  295. id := c.sendRequest("session/load", params)
  296. // 收集回放消息
  297. var replayMessages []ReplayMessage
  298. currentMsg := &ReplayMessage{}
  299. // 读取回放事件直到收到 session/load 的 response
  300. for c.scanner.Scan() {
  301. line := c.scanner.Text()
  302. if line == "" {
  303. continue
  304. }
  305. var msg struct {
  306. JSONRPC string `json:"jsonrpc"`
  307. ID json.RawMessage `json:"id,omitempty"`
  308. Method string `json:"method,omitempty"`
  309. Result json.RawMessage `json:"result,omitempty"`
  310. Error *RPCError `json:"error,omitempty"`
  311. Params json.RawMessage `json:"params,omitempty"`
  312. }
  313. if err := json.Unmarshal([]byte(line), &msg); err != nil {
  314. continue
  315. }
  316. // 检查是否是 session/load 的响应
  317. hasId := len(msg.ID) > 0 && string(msg.ID) != "null"
  318. if hasId && msg.Method == "" {
  319. var numId int64
  320. json.Unmarshal(msg.ID, &numId)
  321. if numId == id {
  322. // session/load 完成
  323. if msg.Error != nil {
  324. return "", nil, fmt.Errorf("session/load 错误: %s", msg.Error.Message)
  325. }
  326. c.sessionId = sessionId
  327. // 追加最后一条未关闭的消息
  328. if currentMsg.Content != "" {
  329. replayMessages = append(replayMessages, *currentMsg)
  330. }
  331. return sessionId, replayMessages, nil
  332. }
  333. }
  334. // 处理回放的 session/update 通知
  335. if msg.Method == "session/update" || msg.Method == "_kiro.dev/session/update" {
  336. var notif SessionUpdate
  337. if err := json.Unmarshal(msg.Params, &notif); err != nil {
  338. continue
  339. }
  340. var base UpdateBase
  341. if err := json.Unmarshal(notif.Update, &base); err != nil {
  342. continue
  343. }
  344. switch base.SessionUpdate {
  345. case "user_message_chunk":
  346. // 新的用户消息 → 保存上一条并开始新消息
  347. if currentMsg.Content != "" {
  348. replayMessages = append(replayMessages, *currentMsg)
  349. }
  350. var chunk AgentMessageChunk
  351. json.Unmarshal(notif.Update, &chunk)
  352. currentMsg = &ReplayMessage{Role: "user", Content: chunk.Content.Text, MessageId: chunk.MessageId}
  353. case "agent_message_chunk":
  354. // AI 消息
  355. var chunk AgentMessageChunk
  356. json.Unmarshal(notif.Update, &chunk)
  357. if currentMsg.Role != "assistant" || (chunk.MessageId != "" && chunk.MessageId != currentMsg.MessageId) {
  358. // 新的 AI 消息 → 保存上一条
  359. if currentMsg.Content != "" {
  360. replayMessages = append(replayMessages, *currentMsg)
  361. }
  362. currentMsg = &ReplayMessage{Role: "assistant", Content: chunk.Content.Text, MessageId: chunk.MessageId}
  363. } else {
  364. // 同一条消息的续写
  365. currentMsg.Content += chunk.Content.Text
  366. }
  367. case "agent_thought_chunk":
  368. // 思考内容忽略(不显示给用户)
  369. case "tool_call", "tool_call_update", "tool_call_chunk":
  370. // 工具调用回放忽略
  371. default:
  372. // 其他类型忽略
  373. }
  374. continue
  375. }
  376. // 忽略其他通知(kiro 扩展等)
  377. }
  378. return "", nil, fmt.Errorf("session/load 未收到响应(进程可能已退出)")
  379. }
  380. // Prompt 发送消息并流式读取事件
  381. // eventCh 会在 turn 结束或出错时关闭
  382. func (c *Client) Prompt(sessionId string, message string, eventCh chan<- Event) {
  383. defer close(eventCh)
  384. // 设置当前事件通道(供 handleAgentRequest 推送 permission 事件)
  385. c.eventCh = eventCh
  386. params := PromptParams{
  387. SessionId: sessionId,
  388. Prompt: []ContentBlock{
  389. {Type: "text", Text: message},
  390. },
  391. }
  392. // 发送 prompt 请求
  393. promptId := c.sendRequest("session/prompt", params)
  394. zap.L().Debug("[ACP] prompt 已发送", zap.Int64("promptId", promptId), zap.String("sessionId", sessionId))
  395. // 持续读取直到收到 prompt 的 response
  396. for c.scanner.Scan() {
  397. line := c.scanner.Text()
  398. if line == "" {
  399. continue
  400. }
  401. // 用宽松结构解析,兼容所有消息格式
  402. var msg struct {
  403. JSONRPC string `json:"jsonrpc"`
  404. ID json.RawMessage `json:"id,omitempty"`
  405. Method string `json:"method,omitempty"`
  406. Result json.RawMessage `json:"result,omitempty"`
  407. Error *RPCError `json:"error,omitempty"`
  408. Params json.RawMessage `json:"params,omitempty"`
  409. }
  410. if err := json.Unmarshal([]byte(line), &msg); err != nil {
  411. zap.L().Warn("[ACP] JSON解析失败,跳过", zap.String("line", line[:min(len(line), 100)]))
  412. continue
  413. }
  414. // 解析 ID(兼容 int64 和 string)
  415. hasId := len(msg.ID) > 0 && string(msg.ID) != "null"
  416. var numericId int64
  417. isPromptResp := false
  418. if hasId {
  419. json.Unmarshal(msg.ID, &numericId)
  420. isPromptResp = numericId == promptId && msg.Method == ""
  421. }
  422. // 收到 prompt 的响应 → turn 结束
  423. if isPromptResp {
  424. zap.L().Debug("[ACP] 收到 prompt 响应(turn结束)", zap.Int64("id", numericId))
  425. // 打印本轮完整回复
  426. if c.textBuffer != "" {
  427. zap.L().Info("[ACP] AI 回复完整内容", zap.String("text", c.textBuffer))
  428. c.textBuffer = ""
  429. }
  430. var result PromptResult
  431. if msg.Error != nil {
  432. eventCh <- Event{Type: "error", Content: msg.Error.Message}
  433. } else if err := json.Unmarshal(msg.Result, &result); err == nil {
  434. eventCh <- Event{Type: "done", SessionId: sessionId, StopReason: result.StopReason}
  435. }
  436. return
  437. }
  438. // 处理 notification (session/update 或 _kiro.dev/session/update)
  439. if !hasId && (msg.Method == "session/update" || msg.Method == "_kiro.dev/session/update") {
  440. c.handleSessionUpdate(msg.Params, eventCh)
  441. continue
  442. }
  443. // 处理 Agent→Client 反向请求(有 ID + Method = 请求)
  444. if hasId && msg.Method != "" {
  445. zap.L().Debug("[ACP] 收到 Agent 反向请求", zap.String("method", msg.Method), zap.String("id", string(msg.ID)))
  446. c.handleAgentRequest(msg.ID, msg.Method, msg.Params)
  447. continue
  448. }
  449. // 未匹配的消息(kiro扩展通知等)
  450. if msg.Method != "" {
  451. c.handleExtensionNotification(msg.Method, msg.Params, eventCh)
  452. } else {
  453. zap.L().Debug("[ACP] 未处理的消息", zap.String("line", line[:min(len(line), 200)]))
  454. }
  455. }
  456. // Scanner 结束说明进程退出
  457. eventCh <- Event{Type: "error", Content: "Agent 进程已断开"}
  458. }
  459. // Cancel 取消当前操作
  460. func (c *Client) Cancel(sessionId string) {
  461. c.sendRequest("session/cancel", CancelParams{SessionId: sessionId})
  462. }
  463. // GetSessionId 获取当前会话 ID
  464. func (c *Client) GetSessionId() string {
  465. return c.sessionId
  466. }
  467. // Close 关闭 ACP Client,终止 Agent 进程
  468. func (c *Client) Close() {
  469. // 关闭 stdin 通知 Agent 退出
  470. c.stdin.Close()
  471. // 终止进程
  472. if c.cmd.Process != nil {
  473. c.cmd.Process.Kill()
  474. // Wait 回收子进程资源,防止僵尸进程
  475. go c.cmd.Wait()
  476. }
  477. // 解除可能阻塞在 permissionCh 上的 goroutine
  478. select {
  479. case c.permissionCh <- "deny":
  480. default:
  481. }
  482. // 清理 FileStore
  483. if c.FileStore != nil {
  484. c.FileStore.Clear()
  485. }
  486. }
  487. // IsAlive 检查 Agent 进程是否存活
  488. func (c *Client) IsAlive() bool {
  489. return c.cmd.ProcessState == nil
  490. }
  491. // ============ 内部方法 ============
  492. // sendRequest 发送请求(不等待响应),返回 request ID
  493. func (c *Client) sendRequest(method string, params any) int64 {
  494. c.mu.Lock()
  495. defer c.mu.Unlock()
  496. id := atomic.AddInt64(&c.requestId, 1)
  497. req := Request{
  498. JSONRPC: "2.0",
  499. ID: id,
  500. Method: method,
  501. Params: params,
  502. }
  503. data, err := json.Marshal(req)
  504. if err != nil {
  505. zap.L().Error("[ACP] 序列化请求失败", zap.Error(err))
  506. return id
  507. }
  508. data = append(data, '\n')
  509. if _, err := c.stdin.Write(data); err != nil {
  510. zap.L().Error("[ACP] 写入 stdin 失败", zap.String("method", method), zap.Error(err))
  511. }
  512. return id
  513. }
  514. // sendAndWait 发送请求并等待对应 ID 的响应
  515. func (c *Client) sendAndWait(method string, params any) (json.RawMessage, error) {
  516. id := c.sendRequest(method, params)
  517. // 读取响应(跳过 notification 和其他消息)
  518. for c.scanner.Scan() {
  519. line := c.scanner.Text()
  520. if line == "" {
  521. continue
  522. }
  523. var resp Response
  524. if err := json.Unmarshal([]byte(line), &resp); err != nil {
  525. continue
  526. }
  527. // 匹配 ID 的响应
  528. if resp.ID != nil && *resp.ID == id {
  529. if resp.Error != nil {
  530. return nil, fmt.Errorf("ACP 错误 [%d]: %s", resp.Error.Code, resp.Error.Message)
  531. }
  532. return resp.Result, nil
  533. }
  534. // 跳过 notification(session/new 之前可能收到 kiro 扩展通知)
  535. }
  536. return nil, fmt.Errorf("未收到 %s 的响应(进程可能已退出)", method)
  537. }
  538. // handleSessionUpdate 解析并分发 session/update 通知
  539. func (c *Client) handleSessionUpdate(params json.RawMessage, eventCh chan<- Event) {
  540. var notif SessionUpdate
  541. if err := json.Unmarshal(params, &notif); err != nil {
  542. return
  543. }
  544. // 解析 update 的类型
  545. var base UpdateBase
  546. if err := json.Unmarshal(notif.Update, &base); err != nil {
  547. return
  548. }
  549. // zap.L().Debug("[ACP] session/update", zap.String("type", base.SessionUpdate))
  550. switch base.SessionUpdate {
  551. case "agent_message_chunk":
  552. var chunk AgentMessageChunk
  553. if err := json.Unmarshal(notif.Update, &chunk); err == nil {
  554. c.textBuffer += chunk.Content.Text
  555. eventCh <- Event{Type: "text", Content: chunk.Content.Text}
  556. }
  557. case "agent_thought_chunk":
  558. var chunk AgentMessageChunk
  559. if err := json.Unmarshal(notif.Update, &chunk); err == nil {
  560. c.textBuffer += chunk.Content.Text
  561. eventCh <- Event{Type: "text", Content: chunk.Content.Text}
  562. }
  563. case "tool_call":
  564. var tc ToolCall
  565. if err := json.Unmarshal(notif.Update, &tc); err == nil {
  566. zap.L().Debug("[ACP] → tool_call", zap.String("title", tc.Title), zap.String("status", tc.Status), zap.String("id", tc.ToolCallId))
  567. eventCh <- Event{Type: "tool_call", ToolName: tc.Title, ToolStatus: tc.Status}
  568. }
  569. case "tool_call_update":
  570. var tcu ToolCallUpdate
  571. if err := json.Unmarshal(notif.Update, &tcu); err == nil {
  572. zap.L().Debug("[ACP] → tool_call_update", zap.String("title", tcu.Title), zap.String("status", tcu.Status), zap.String("id", tcu.ToolCallId))
  573. eventCh <- Event{Type: "tool_update", ToolName: tcu.Title, ToolStatus: tcu.Status}
  574. }
  575. case "tool_call_chunk":
  576. // 工具调用的流式参数输出(Kiro 扩展)
  577. zap.L().Debug("[ACP] → tool_call_chunk (ignored)")
  578. case "plan":
  579. zap.L().Debug("[ACP] → plan update")
  580. default:
  581. zap.L().Debug("[ACP] → 未知 session/update 类型", zap.String("type", base.SessionUpdate))
  582. }
  583. }
  584. // handleExtensionNotification 处理 Kiro 扩展通知
  585. func (c *Client) handleExtensionNotification(method string, params json.RawMessage, eventCh chan<- Event) {
  586. switch method {
  587. case "_kiro.dev/commands/available":
  588. // 可用命令和工具列表
  589. var data struct {
  590. SessionId string `json:"sessionId"`
  591. Commands []struct {
  592. Name string `json:"name"`
  593. Description string `json:"description"`
  594. } `json:"commands"`
  595. Tools []struct {
  596. Name string `json:"name"`
  597. Description string `json:"description"`
  598. Source string `json:"source"`
  599. } `json:"tools"`
  600. }
  601. if err := json.Unmarshal(params, &data); err == nil {
  602. zap.L().Debug("[ACP] 可用命令/工具更新",
  603. zap.Int("commands", len(data.Commands)),
  604. zap.Int("tools", len(data.Tools)),
  605. )
  606. // 推送工具列表给前端(可选)
  607. if len(data.Tools) > 0 {
  608. toolNames := make([]string, 0, len(data.Tools))
  609. for _, t := range data.Tools {
  610. toolNames = append(toolNames, t.Name)
  611. }
  612. eventCh <- Event{Type: "tools_available", Content: toJSONStr(toolNames)}
  613. }
  614. }
  615. case "_kiro.dev/metadata":
  616. // 上下文使用量和耗时
  617. var data struct {
  618. SessionId string `json:"sessionId"`
  619. ContextUsagePercentage float64 `json:"contextUsagePercentage"`
  620. TurnDurationMs int64 `json:"turnDurationMs,omitempty"`
  621. }
  622. if err := json.Unmarshal(params, &data); err == nil {
  623. if data.TurnDurationMs > 0 {
  624. zap.L().Debug("[ACP] metadata",
  625. zap.Float64("contextUsage%", data.ContextUsagePercentage),
  626. zap.Int64("turnMs", data.TurnDurationMs),
  627. )
  628. eventCh <- Event{
  629. Type: "metadata",
  630. Content: toJSONStr(map[string]any{
  631. "contextUsagePercent": data.ContextUsagePercentage,
  632. "turnDurationMs": data.TurnDurationMs,
  633. }),
  634. }
  635. }
  636. }
  637. case "_kiro.dev/subagent/list_update":
  638. // 子代理列表更新
  639. zap.L().Debug("[ACP] 子代理列表更新")
  640. case "_kiro.dev/mcp/server_initialized":
  641. // MCP Server 初始化完成
  642. var data struct {
  643. ServerName string `json:"serverName"`
  644. }
  645. json.Unmarshal(params, &data)
  646. zap.L().Info("[ACP] MCP Server 初始化完成", zap.String("server", data.ServerName))
  647. case "_kiro.dev/compaction/status":
  648. // 上下文压缩状态
  649. zap.L().Debug("[ACP] 上下文压缩中")
  650. case "_kiro.dev/clear/status":
  651. // 会话清除状态
  652. zap.L().Debug("[ACP] 会话清除中")
  653. default:
  654. zap.L().Debug("[ACP] 未处理的扩展通知", zap.String("method", method))
  655. }
  656. }
  657. // toJSONStr 序列化为 JSON 字符串
  658. func toJSONStr(v any) string {
  659. data, _ := json.Marshal(v)
  660. return string(data)
  661. }
  662. // handleAgentRequest 处理 Agent→Client 的反向请求
  663. func (c *Client) handleAgentRequest(rawId json.RawMessage, method string, rawParams json.RawMessage) {
  664. c.mu.Lock()
  665. defer c.mu.Unlock()
  666. zap.L().Debug("[ACP] 处理反向请求", zap.String("method", method), zap.String("id", string(rawId)), zap.String("params", string(rawParams[:min(len(rawParams), 200)])))
  667. var respData []byte
  668. switch method {
  669. case "readTextFile":
  670. // 读取文件:先从 FileStore 查找(MinIO),再从本地文件系统
  671. var params struct {
  672. Path string `json:"path"`
  673. Line *int `json:"line,omitempty"`
  674. Limit *int `json:"limit,omitempty"`
  675. }
  676. if err := json.Unmarshal(rawParams, &params); err == nil && params.Path != "" {
  677. var content string
  678. var readErr error
  679. // 优先从 FileStore(MinIO)读取
  680. if c.FileStore.HasFile(params.Path) {
  681. content, readErr = c.FileStore.ReadFile(params.Path)
  682. zap.L().Debug("[ACP] readTextFile 从 MinIO 读取", zap.String("path", params.Path))
  683. } else {
  684. // 回退到本地文件系统
  685. data, err := os.ReadFile(params.Path)
  686. if err == nil {
  687. content = string(data)
  688. zap.L().Debug("[ACP] readTextFile 从本地读取", zap.String("path", params.Path))
  689. } else {
  690. readErr = err
  691. }
  692. }
  693. if readErr == nil {
  694. result, _ := json.Marshal(map[string]string{"content": content})
  695. respData, _ = json.Marshal(map[string]any{
  696. "jsonrpc": "2.0",
  697. "id": rawId,
  698. "result": json.RawMessage(result),
  699. })
  700. }
  701. }
  702. if respData == nil {
  703. respData, _ = json.Marshal(map[string]any{
  704. "jsonrpc": "2.0",
  705. "id": rawId,
  706. "error": map[string]any{"code": -1, "message": "file not found"},
  707. })
  708. }
  709. case "writeTextFile":
  710. // 写入文件到 MinIO(不写本地)
  711. var params struct {
  712. Path string `json:"path"`
  713. Content string `json:"content"`
  714. }
  715. if err := json.Unmarshal(rawParams, &params); err == nil && params.Path != "" {
  716. record, err := c.FileStore.WriteFile(c.UserId, c.sessionId, params.Path, params.Content)
  717. if err == nil {
  718. respData, _ = json.Marshal(map[string]any{
  719. "jsonrpc": "2.0",
  720. "id": rawId,
  721. "result": map[string]any{},
  722. })
  723. _ = record // 文件下载通过前端标记检测实现,不再推送事件
  724. } else {
  725. zap.L().Error("[ACP] writeTextFile MinIO上传失败", zap.Error(err))
  726. }
  727. }
  728. if respData == nil {
  729. respData, _ = json.Marshal(map[string]any{
  730. "jsonrpc": "2.0",
  731. "id": rawId,
  732. "error": map[string]any{"code": -1, "message": "write failed"},
  733. })
  734. }
  735. case "requestPermission", "session/request_permission":
  736. // 解析权限请求参数
  737. var params struct {
  738. ToolCall *struct {
  739. Title string `json:"title"`
  740. } `json:"toolCall"`
  741. Options []struct {
  742. OptionId string `json:"optionId"`
  743. Name string `json:"name"`
  744. Kind string `json:"kind"`
  745. } `json:"options"`
  746. }
  747. json.Unmarshal(rawParams, &params)
  748. title := ""
  749. if params.ToolCall != nil {
  750. title = params.ToolCall.Title
  751. }
  752. // 判断是否涉及写操作(需要手动授权)
  753. isWriteOp := true
  754. // isWriteOp := false
  755. // if title != "" {
  756. // for _, keyword := range []string{"write", "Write", "create", "Create", "delete", "Delete", "修改", "写入", "创建", "删除"} {
  757. // if len(title) >= len(keyword) && containsStr(title, keyword) {
  758. // isWriteOp = true
  759. // break
  760. // }
  761. // }
  762. // }
  763. if isWriteOp && c.eventCh != nil {
  764. // 写操作:推送权限请求给前端,等待前端回复
  765. options := make([]PermissionOption, 0, len(params.Options))
  766. for _, opt := range params.Options {
  767. options = append(options, PermissionOption{
  768. OptionId: opt.OptionId,
  769. Name: opt.Name,
  770. Kind: opt.Kind,
  771. })
  772. }
  773. requestId := fmt.Sprintf("perm_%s", string(rawId))
  774. c.eventCh <- Event{
  775. Type: "permission",
  776. Permission: &PermissionEvent{
  777. RequestId: requestId,
  778. Title: title,
  779. Options: options,
  780. },
  781. }
  782. // 释放 mu 锁后等待前端回复(否则会死锁)
  783. c.mu.Unlock()
  784. selectedOptionId := <-c.permissionCh
  785. c.mu.Lock()
  786. respData, _ = json.Marshal(map[string]any{
  787. "jsonrpc": "2.0",
  788. "id": rawId,
  789. "result": map[string]any{
  790. "outcome": map[string]any{
  791. "outcome": "selected",
  792. "optionId": selectedOptionId,
  793. },
  794. },
  795. })
  796. } else {
  797. // 非写操作:自动允许
  798. respData, _ = json.Marshal(map[string]any{
  799. "jsonrpc": "2.0",
  800. "id": rawId,
  801. "result": map[string]any{
  802. "outcome": map[string]any{
  803. "outcome": "selected",
  804. "optionId": "allow_once",
  805. },
  806. },
  807. })
  808. }
  809. default:
  810. // 未知请求返回错误
  811. respData, _ = json.Marshal(map[string]any{
  812. "jsonrpc": "2.0",
  813. "id": rawId,
  814. "error": map[string]any{"code": -32601, "message": "method not supported"},
  815. })
  816. }
  817. if respData != nil {
  818. zap.L().Debug("[ACP] 发送反向响应", zap.String("method", method), zap.String("resp", string(respData[:min(len(respData), 200)])))
  819. respData = append(respData, '\n')
  820. c.stdin.Write(respData)
  821. } else {
  822. zap.L().Warn("[ACP] 反向请求无响应数据", zap.String("method", method))
  823. }
  824. }
  825. // containsStr 简单字符串包含检测
  826. func containsStr(s, substr string) bool {
  827. return len(s) >= len(substr) && (s == substr || len(s) > 0 && stringContains(s, substr))
  828. }
  829. func stringContains(s, substr string) bool {
  830. for i := 0; i <= len(s)-len(substr); i++ {
  831. if s[i:i+len(substr)] == substr {
  832. return true
  833. }
  834. }
  835. return false
  836. }
  837. func min(a, b int) int {
  838. if a < b {
  839. return a
  840. }
  841. return b
  842. }