acp.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. "os/user"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "sync/atomic"
  17. "syscall"
  18. "fwh-toolbox-server/utils/filestore"
  19. "go.uber.org/zap"
  20. )
  21. // ============ JSON-RPC 2.0 基础类型 ============
  22. // Request JSON-RPC 请求
  23. type Request struct {
  24. JSONRPC string `json:"jsonrpc"`
  25. ID int64 `json:"id"`
  26. Method string `json:"method"`
  27. Params any `json:"params,omitempty"`
  28. }
  29. // Response JSON-RPC 响应
  30. type Response struct {
  31. JSONRPC string `json:"jsonrpc"`
  32. ID *int64 `json:"id,omitempty"`
  33. Method string `json:"method,omitempty"`
  34. Result json.RawMessage `json:"result,omitempty"`
  35. Error *RPCError `json:"error,omitempty"`
  36. Params json.RawMessage `json:"params,omitempty"`
  37. }
  38. // RPCError JSON-RPC 错误
  39. type RPCError struct {
  40. Code int `json:"code"`
  41. Message string `json:"message"`
  42. Data string `json:"data,omitempty"`
  43. }
  44. // FullMessage 返回包含 data 的完整错误信息
  45. func (e *RPCError) FullMessage() string {
  46. if e.Data != "" {
  47. return fmt.Sprintf("%s: %s", e.Message, e.Data)
  48. }
  49. return e.Message
  50. }
  51. // ============ ACP 协议类型 ============
  52. // InitializeParams 初始化请求参数
  53. type InitializeParams struct {
  54. ProtocolVersion int `json:"protocolVersion"`
  55. ClientInfo ClientInfo `json:"clientInfo"`
  56. ClientCapabilities ClientCapabilities `json:"clientCapabilities"`
  57. }
  58. // ClientInfo 客户端信息
  59. type ClientInfo struct {
  60. Name string `json:"name"`
  61. Version string `json:"version"`
  62. }
  63. // ClientCapabilities 客户端能力声明
  64. type ClientCapabilities struct {
  65. FS *FSCapabilities `json:"fs,omitempty"`
  66. Terminal bool `json:"terminal,omitempty"`
  67. }
  68. // FSCapabilities 文件系统能力
  69. type FSCapabilities struct {
  70. ReadTextFile bool `json:"readTextFile"`
  71. WriteTextFile bool `json:"writeTextFile"`
  72. }
  73. // NewSessionParams 创建会话参数
  74. type NewSessionParams struct {
  75. CWD string `json:"cwd"`
  76. MCPServers []any `json:"mcpServers"`
  77. }
  78. // NewSessionResult 创建会话响应
  79. type NewSessionResult struct {
  80. SessionId string `json:"sessionId"`
  81. Modes *SessionModes `json:"modes,omitempty"`
  82. Models *SessionModels `json:"models,omitempty"`
  83. }
  84. // SessionModes 会话模式
  85. type SessionModes struct {
  86. CurrentModeId string `json:"currentModeId"`
  87. AvailableModes []SessionMode `json:"availableModes"`
  88. }
  89. // SessionMode 单个模式
  90. type SessionMode struct {
  91. Id string `json:"id"`
  92. Name string `json:"name"`
  93. Description string `json:"description"`
  94. Meta *SessionMeta `json:"_meta,omitempty"`
  95. }
  96. // SessionMeta 模式元数据
  97. type SessionMeta struct {
  98. WelcomeMessage string `json:"welcomeMessage"`
  99. }
  100. // SessionModels 会话可用模型
  101. type SessionModels struct {
  102. CurrentModelId string `json:"currentModelId"`
  103. AvailableModels []SessionModel `json:"availableModels"`
  104. }
  105. // SessionModel 单个模型
  106. type SessionModel struct {
  107. ModelId string `json:"modelId"`
  108. Name string `json:"name"`
  109. Description string `json:"description"`
  110. }
  111. // PromptParams 发送消息参数
  112. type PromptParams struct {
  113. SessionId string `json:"sessionId"`
  114. Prompt []ContentBlock `json:"prompt"`
  115. }
  116. // ContentBlock 内容块
  117. type ContentBlock struct {
  118. Type string `json:"type"`
  119. Text string `json:"text"`
  120. }
  121. // PromptResult prompt 响应
  122. type PromptResult struct {
  123. StopReason string `json:"stopReason"`
  124. }
  125. // CancelParams 取消参数
  126. type CancelParams struct {
  127. SessionId string `json:"sessionId"`
  128. }
  129. // ============ Session Update 事件类型 ============
  130. // SessionUpdate 会话更新通知
  131. type SessionUpdate struct {
  132. SessionId string `json:"sessionId"`
  133. Update json.RawMessage `json:"update"`
  134. }
  135. // UpdateBase 更新基础类型
  136. type UpdateBase struct {
  137. SessionUpdate string `json:"sessionUpdate"`
  138. }
  139. // AgentMessageChunk Agent 文本流式输出
  140. type AgentMessageChunk struct {
  141. SessionUpdate string `json:"sessionUpdate"` // "agent_message_chunk"
  142. MessageId string `json:"messageId,omitempty"`
  143. Content ContentBlock `json:"content"`
  144. }
  145. // ToolCall 工具调用通知
  146. type ToolCall struct {
  147. SessionUpdate string `json:"sessionUpdate"` // "tool_call"
  148. ToolCallId string `json:"toolCallId"`
  149. Title string `json:"title"`
  150. Status string `json:"status"` // pending, running, completed, failed
  151. }
  152. // ToolCallUpdate 工具调用状态更新
  153. type ToolCallUpdate struct {
  154. SessionUpdate string `json:"sessionUpdate"` // "tool_call_update"
  155. ToolCallId string `json:"toolCallId"`
  156. Title string `json:"title,omitempty"`
  157. Status string `json:"status"`
  158. }
  159. // ============ 客户端事件(对外输出) ============
  160. // Event 输出给上层的事件
  161. type Event struct {
  162. Type string // "text", "tool_call", "tool_update", "done", "error", "permission"
  163. Content string
  164. ToolCallId string // 工具调用唯一ID(用于前端按 id 关联状态更新)
  165. ToolName string
  166. ToolStatus string
  167. SessionId string
  168. StopReason string
  169. // 权限请求相关
  170. Permission *PermissionEvent `json:"permission,omitempty"`
  171. }
  172. // PermissionEvent 权限请求事件(推给前端)
  173. type PermissionEvent struct {
  174. RequestId string `json:"requestId"` // 用于前端回传
  175. Title string `json:"title"` // 权限标题
  176. Options []PermissionOption `json:"options"` // 可选选项
  177. }
  178. // PermissionOption 权限选项
  179. type PermissionOption struct {
  180. OptionId string `json:"optionId"`
  181. Name string `json:"name"`
  182. Kind string `json:"kind"` // allow_once, allow_always, deny
  183. }
  184. // ============ ACP Client 实现 ============
  185. // Client ACP 客户端(管理单个 Agent 进程)
  186. type Client struct {
  187. cmd *exec.Cmd
  188. stdin io.WriteCloser
  189. scanner *bufio.Scanner
  190. sessionId string
  191. requestId int64
  192. mu sync.Mutex // 保护 stdin 写入
  193. readMu sync.Mutex // 保护 stdout 读取
  194. // 权限请求等待机制
  195. permissionCh chan string // 接收前端选择的 optionId
  196. eventCh chan<- Event // 当前 prompt 的事件通道(用于推送 permission 事件)
  197. // 文件存储:会话身份(用于定位 MinIO 中的文件)
  198. UserId string
  199. // 文本累积(用于合并日志输出)
  200. textBuffer string
  201. // 最近一次上下文用量与耗时(供首屏展示,读取需加 metaMu)
  202. metaMu sync.Mutex
  203. lastContextUsage float64
  204. lastTurnDurationMs int64
  205. }
  206. // ClientConfig 客户端配置
  207. type ClientConfig struct {
  208. Command string // Agent 命令(如 "kiro-cli")
  209. Args []string // 命令参数(如 ["acp"])
  210. WorkingDir string // 工作目录
  211. Env []string // 额外环境变量(如 "HOME=/home/user")
  212. RunAsUser string // 降权运行的目标系统用户名,为空则不降权
  213. }
  214. // ApplyRunAsUser 让 cmd 以指定系统用户身份运行(降权)。
  215. // runAsUser 为空时不做任何处理(沿用当前进程用户)。
  216. // 该函数会:
  217. // 1. 解析目标用户的 uid/gid,并设置 cmd.SysProcAttr.Credential;
  218. // 2. 附带解析该用户的补充组(supplementary groups);
  219. // 3. 修正 HOME/USER/LOGNAME 环境变量为目标用户的值,避免 kiro-cli
  220. // 仍读取 root 的家目录导致配置/凭证路径错误。
  221. //
  222. // 注意:设置 Credential 需要当前进程具备相应权限(通常为 root)。
  223. func ApplyRunAsUser(cmd *exec.Cmd, runAsUser string) error {
  224. runAsUser = strings.TrimSpace(runAsUser)
  225. if runAsUser == "" {
  226. return nil
  227. }
  228. u, err := user.Lookup(runAsUser)
  229. if err != nil {
  230. return fmt.Errorf("查找降权用户 %q 失败: %w", runAsUser, err)
  231. }
  232. uid, err := strconv.ParseUint(u.Uid, 10, 32)
  233. if err != nil {
  234. return fmt.Errorf("解析用户 %q 的 uid(%s) 失败: %w", runAsUser, u.Uid, err)
  235. }
  236. gid, err := strconv.ParseUint(u.Gid, 10, 32)
  237. if err != nil {
  238. return fmt.Errorf("解析用户 %q 的 gid(%s) 失败: %w", runAsUser, u.Gid, err)
  239. }
  240. // 解析补充组(失败不致命,仅记录告警)
  241. var groups []uint32
  242. if gidStrs, gErr := u.GroupIds(); gErr == nil {
  243. for _, gs := range gidStrs {
  244. if g, pErr := strconv.ParseUint(gs, 10, 32); pErr == nil {
  245. groups = append(groups, uint32(g))
  246. }
  247. }
  248. } else {
  249. zap.L().Warn("[ACP] 读取降权用户补充组失败", zap.String("user", runAsUser), zap.Error(gErr))
  250. }
  251. if cmd.SysProcAttr == nil {
  252. cmd.SysProcAttr = &syscall.SysProcAttr{}
  253. }
  254. cmd.SysProcAttr.Credential = &syscall.Credential{
  255. Uid: uint32(uid),
  256. Gid: uint32(gid),
  257. Groups: groups,
  258. }
  259. // 修正环境变量,确保子进程使用目标用户的身份。
  260. // USER/LOGNAME 强制设为目标用户;HOME 尊重上层(配置)已传入的值,
  261. // 仅在未提供时才回退到用户家目录。
  262. if cmd.Env == nil {
  263. cmd.Env = os.Environ()
  264. }
  265. cmd.Env = overrideEnv(cmd.Env, map[string]string{
  266. "USER": u.Username,
  267. "LOGNAME": u.Username,
  268. })
  269. cmd.Env = fillEnvIfAbsent(cmd.Env, "HOME", u.HomeDir)
  270. effectiveHome := u.HomeDir
  271. for _, e := range cmd.Env {
  272. if strings.HasPrefix(e, "HOME=") {
  273. effectiveHome = strings.TrimPrefix(e, "HOME=")
  274. break
  275. }
  276. }
  277. zap.L().Info("[ACP] 子进程降权运行",
  278. zap.String("user", u.Username),
  279. zap.String("uid", u.Uid),
  280. zap.String("gid", u.Gid),
  281. zap.String("home", effectiveHome),
  282. )
  283. return nil
  284. }
  285. // fillEnvIfAbsent 仅当 env 中不存在 key 时才追加 key=value,否则原样返回。
  286. func fillEnvIfAbsent(env []string, key, value string) []string {
  287. prefix := key + "="
  288. for _, e := range env {
  289. if strings.HasPrefix(e, prefix) {
  290. return env
  291. }
  292. }
  293. return append(env, prefix+value)
  294. }
  295. // overrideEnv 用 kv 覆盖 env 中已存在的同名变量,不存在则追加。
  296. func overrideEnv(env []string, kv map[string]string) []string {
  297. out := make([]string, 0, len(env)+len(kv))
  298. seen := make(map[string]bool, len(kv))
  299. for _, e := range env {
  300. key := e
  301. if idx := strings.IndexByte(e, '='); idx >= 0 {
  302. key = e[:idx]
  303. }
  304. if v, ok := kv[key]; ok {
  305. out = append(out, key+"="+v)
  306. seen[key] = true
  307. } else {
  308. out = append(out, e)
  309. }
  310. }
  311. for k, v := range kv {
  312. if !seen[k] {
  313. out = append(out, k+"="+v)
  314. }
  315. }
  316. return out
  317. }
  318. // NewClient 创建并启动 ACP Client
  319. func NewClient(cfg ClientConfig) (*Client, error) {
  320. cmd := exec.Command(cfg.Command, cfg.Args...)
  321. // 确保工作目录是绝对路径
  322. absDir, err := filepath.Abs(cfg.WorkingDir)
  323. if err != nil {
  324. absDir = cfg.WorkingDir
  325. }
  326. cmd.Dir = absDir
  327. // 设置环境变量
  328. cmd.Env = append(os.Environ(), cfg.Env...)
  329. // 若配置了降权用户,则以该用户身份拉起子进程
  330. if err := ApplyRunAsUser(cmd, cfg.RunAsUser); err != nil {
  331. return nil, err
  332. }
  333. stdin, err := cmd.StdinPipe()
  334. if err != nil {
  335. return nil, fmt.Errorf("创建 stdin pipe 失败: %w", err)
  336. }
  337. stdout, err := cmd.StdoutPipe()
  338. if err != nil {
  339. return nil, fmt.Errorf("创建 stdout pipe 失败: %w", err)
  340. }
  341. // 捕获 stderr
  342. stderrPipe, _ := cmd.StderrPipe()
  343. go func() {
  344. if stderrPipe != nil {
  345. s := bufio.NewScanner(stderrPipe)
  346. for s.Scan() {
  347. zap.L().Warn("[ACP] agent stderr", zap.String("line", s.Text()))
  348. }
  349. }
  350. }()
  351. if err := cmd.Start(); err != nil {
  352. return nil, fmt.Errorf("启动 Agent 进程失败: %w", err)
  353. }
  354. scanner := bufio.NewScanner(stdout)
  355. scanner.Buffer(make([]byte, 0, 2*1024*1024), 2*1024*1024) // 2MB buffer
  356. return &Client{
  357. cmd: cmd,
  358. stdin: stdin,
  359. scanner: scanner,
  360. permissionCh: make(chan string, 1),
  361. }, nil
  362. }
  363. // ResolvePermission 前端回传权限选择结果
  364. func (c *Client) ResolvePermission(optionId string) {
  365. select {
  366. case c.permissionCh <- optionId:
  367. default:
  368. // 没有等待中的权限请求,忽略
  369. }
  370. }
  371. // setMeta 更新最近的上下文用量与耗时(值 >0 时才覆盖)
  372. func (c *Client) setMeta(usage float64, turnMs int64) {
  373. c.metaMu.Lock()
  374. defer c.metaMu.Unlock()
  375. if usage > 0 {
  376. c.lastContextUsage = usage
  377. }
  378. if turnMs > 0 {
  379. c.lastTurnDurationMs = turnMs
  380. }
  381. }
  382. // GetMeta 返回最近的上下文用量(百分比)与上一轮耗时(毫秒)
  383. func (c *Client) GetMeta() (float64, int64) {
  384. c.metaMu.Lock()
  385. defer c.metaMu.Unlock()
  386. return c.lastContextUsage, c.lastTurnDurationMs
  387. }
  388. // Initialize 执行初始化握手
  389. func (c *Client) Initialize() error {
  390. params := InitializeParams{
  391. ProtocolVersion: 1,
  392. ClientInfo: ClientInfo{
  393. Name: "fwh-toolbox",
  394. Version: "1.0.0",
  395. },
  396. ClientCapabilities: ClientCapabilities{
  397. FS: &FSCapabilities{
  398. ReadTextFile: true,
  399. WriteTextFile: true,
  400. },
  401. Terminal: false, // 不声明终端能力,强制 Agent 使用 writeTextFile
  402. },
  403. }
  404. _, err := c.sendAndWait("initialize", params)
  405. return err
  406. }
  407. // NewSession 创建新会话,返回 sessionId、welcomeMessage、实际生效的 agentId 和 modelId
  408. func (c *Client) NewSession(cwd string) (sessionId string, welcomeMsg string, agentId string, modelId string, err error) {
  409. params := NewSessionParams{
  410. CWD: cwd,
  411. MCPServers: []any{},
  412. }
  413. result, err := c.sendAndWait("session/new", params)
  414. if err != nil {
  415. return "", "", "", "", err
  416. }
  417. var res NewSessionResult
  418. if err := json.Unmarshal(result, &res); err != nil {
  419. return "", "", "", "", fmt.Errorf("解析 session/new 响应失败: %w", err)
  420. }
  421. zap.L().Info("session/new", zap.String("result", string(result)))
  422. c.sessionId = res.SessionId
  423. // 提取当前 mode 的 welcomeMessage 和实际生效的 agentId
  424. if res.Modes != nil {
  425. agentId = res.Modes.CurrentModeId
  426. for _, mode := range res.Modes.AvailableModes {
  427. if mode.Id == res.Modes.CurrentModeId && mode.Meta != nil {
  428. welcomeMsg = mode.Meta.WelcomeMessage
  429. break
  430. }
  431. }
  432. }
  433. // 提取实际生效的 modelId
  434. if res.Models != nil {
  435. modelId = res.Models.CurrentModelId
  436. }
  437. // 捕获 session/new 之后 Kiro 紧跟发送的初始用量 metadata 通知
  438. c.drainInitialMeta()
  439. return res.SessionId, welcomeMsg, agentId, modelId, nil
  440. }
  441. // drainInitialMeta 读取 session/new 之后紧跟的一批通知,捕获其中的初始上下文用量。
  442. // Kiro 在 session/new 响应后会发送 commands/available、subagent/list_update、metadata 等
  443. // 一批通知,且 metadata(含 contextUsagePercentage)位于这批通知的末尾。这里读取直到
  444. // 遇到 metadata 通知即停止,避免读空后阻塞。设置行数上限作为安全兜底。
  445. func (c *Client) drainInitialMeta() {
  446. const maxLines = 30
  447. for i := 0; i < maxLines; i++ {
  448. if !c.scanner.Scan() {
  449. return
  450. }
  451. line := c.scanner.Text()
  452. if line == "" {
  453. continue
  454. }
  455. var msg struct {
  456. Method string `json:"method,omitempty"`
  457. Params json.RawMessage `json:"params,omitempty"`
  458. ID json.RawMessage `json:"id,omitempty"`
  459. }
  460. if err := json.Unmarshal([]byte(line), &msg); err != nil {
  461. continue
  462. }
  463. if msg.Method == "_kiro.dev/metadata" {
  464. var data struct {
  465. ContextUsagePercentage float64 `json:"contextUsagePercentage"`
  466. TurnDurationMs int64 `json:"turnDurationMs,omitempty"`
  467. }
  468. if err := json.Unmarshal(msg.Params, &data); err == nil {
  469. zap.L().Debug("[ACP] 初始 metadata", zap.Float64("contextUsage%", data.ContextUsagePercentage))
  470. c.setMeta(data.ContextUsagePercentage, data.TurnDurationMs)
  471. }
  472. return
  473. }
  474. // 其他 pre-prompt 通知(commands/available、subagent 等)忽略
  475. }
  476. zap.L().Debug("[ACP] drainInitialMeta 未在上限内捕获到 metadata")
  477. }
  478. // ReplayMessage 回放的单条消息
  479. type ReplayMessage struct {
  480. Role string `json:"role"` // "user" 或 "assistant"
  481. Content string `json:"content"`
  482. MessageId string `json:"messageId,omitempty"`
  483. }
  484. // LoadSession 加载已有会话(恢复历史对话上下文),返回回放的消息列表
  485. func (c *Client) LoadSession(sessionId string, cwd string) (string, string, string, string, []ReplayMessage, error) {
  486. params := map[string]any{
  487. "sessionId": sessionId,
  488. "cwd": cwd,
  489. "mcpServers": []any{},
  490. }
  491. // 发送 session/load 请求
  492. id := c.sendRequest("session/load", params)
  493. // 收集回放消息
  494. var replayMessages []ReplayMessage
  495. currentMsg := &ReplayMessage{}
  496. // 读取回放事件直到收到 session/load 的 response
  497. for c.scanner.Scan() {
  498. line := c.scanner.Text()
  499. if line == "" {
  500. continue
  501. }
  502. var msg struct {
  503. JSONRPC string `json:"jsonrpc"`
  504. ID json.RawMessage `json:"id,omitempty"`
  505. Method string `json:"method,omitempty"`
  506. Result json.RawMessage `json:"result,omitempty"`
  507. Error *RPCError `json:"error,omitempty"`
  508. Params json.RawMessage `json:"params,omitempty"`
  509. }
  510. if err := json.Unmarshal([]byte(line), &msg); err != nil {
  511. continue
  512. }
  513. // 检查是否是 session/load 的响应
  514. hasId := len(msg.ID) > 0 && string(msg.ID) != "null"
  515. if hasId && msg.Method == "" {
  516. var numId int64
  517. json.Unmarshal(msg.ID, &numId)
  518. if numId == id {
  519. // session/load 完成
  520. if msg.Error != nil {
  521. return "", "", "", "", nil, fmt.Errorf("session/load 错误: %s", msg.Error.FullMessage())
  522. }
  523. c.sessionId = sessionId
  524. // 追加最后一条未关闭的消息
  525. if currentMsg.Content != "" {
  526. replayMessages = append(replayMessages, *currentMsg)
  527. }
  528. // 解析响应中的 welcomeMessage、实际生效的 agentId 和 modelId
  529. var welcomeMsg string
  530. var agentId string
  531. var modelId string
  532. if len(msg.Result) > 0 {
  533. var res NewSessionResult
  534. if err := json.Unmarshal(msg.Result, &res); err == nil {
  535. if res.Modes != nil {
  536. agentId = res.Modes.CurrentModeId
  537. for _, mode := range res.Modes.AvailableModes {
  538. if mode.Id == res.Modes.CurrentModeId && mode.Meta != nil {
  539. welcomeMsg = mode.Meta.WelcomeMessage
  540. break
  541. }
  542. }
  543. }
  544. if res.Models != nil {
  545. modelId = res.Models.CurrentModelId
  546. }
  547. }
  548. }
  549. // 捕获 session/load 之后紧跟的初始用量 metadata 通知
  550. c.drainInitialMeta()
  551. return sessionId, welcomeMsg, agentId, modelId, replayMessages, nil
  552. }
  553. }
  554. // 处理回放的 session/update 通知
  555. if msg.Method == "session/update" || msg.Method == "_kiro.dev/session/update" {
  556. var notif SessionUpdate
  557. if err := json.Unmarshal(msg.Params, &notif); err != nil {
  558. continue
  559. }
  560. var base UpdateBase
  561. if err := json.Unmarshal(notif.Update, &base); err != nil {
  562. continue
  563. }
  564. switch base.SessionUpdate {
  565. case "user_message_chunk":
  566. // 新的用户消息 → 保存上一条并开始新消息
  567. if currentMsg.Content != "" {
  568. replayMessages = append(replayMessages, *currentMsg)
  569. }
  570. var chunk AgentMessageChunk
  571. json.Unmarshal(notif.Update, &chunk)
  572. currentMsg = &ReplayMessage{Role: "user", Content: chunk.Content.Text, MessageId: chunk.MessageId}
  573. case "agent_message_chunk":
  574. // AI 消息
  575. var chunk AgentMessageChunk
  576. json.Unmarshal(notif.Update, &chunk)
  577. if currentMsg.Role != "assistant" || (chunk.MessageId != "" && chunk.MessageId != currentMsg.MessageId) {
  578. // 新的 AI 消息 → 保存上一条
  579. if currentMsg.Content != "" {
  580. replayMessages = append(replayMessages, *currentMsg)
  581. }
  582. currentMsg = &ReplayMessage{Role: "assistant", Content: chunk.Content.Text, MessageId: chunk.MessageId}
  583. } else {
  584. // 同一条消息的续写
  585. currentMsg.Content += chunk.Content.Text
  586. }
  587. case "agent_thought_chunk":
  588. // 思考内容忽略(不显示给用户)
  589. case "tool_call", "tool_call_update", "tool_call_chunk":
  590. // 工具调用回放忽略
  591. default:
  592. // 其他类型忽略
  593. }
  594. continue
  595. }
  596. // 忽略其他通知(kiro 扩展等)
  597. }
  598. return "", "", "", "", nil, fmt.Errorf("session/load 未收到响应(进程可能已退出)")
  599. }
  600. // Prompt 发送消息并流式读取事件
  601. // eventCh 会在 turn 结束或出错时关闭
  602. func (c *Client) Prompt(sessionId string, message string, eventCh chan<- Event) {
  603. defer close(eventCh)
  604. // 设置当前事件通道(供 handleAgentRequest 推送 permission 事件)
  605. c.eventCh = eventCh
  606. params := PromptParams{
  607. SessionId: sessionId,
  608. Prompt: []ContentBlock{
  609. {Type: "text", Text: message},
  610. },
  611. }
  612. // 发送 prompt 请求
  613. promptId := c.sendRequest("session/prompt", params)
  614. zap.L().Debug("[ACP] prompt 已发送", zap.Int64("promptId", promptId), zap.String("sessionId", sessionId))
  615. // 持续读取直到收到 prompt 的 response
  616. for c.scanner.Scan() {
  617. line := c.scanner.Text()
  618. if line == "" {
  619. continue
  620. }
  621. zap.L().Debug("[ACP] <<< 收到", zap.String("raw", line[:min(len(line), 500)]))
  622. // 用宽松结构解析,兼容所有消息格式
  623. var msg struct {
  624. JSONRPC string `json:"jsonrpc"`
  625. ID json.RawMessage `json:"id,omitempty"`
  626. Method string `json:"method,omitempty"`
  627. Result json.RawMessage `json:"result,omitempty"`
  628. Error *RPCError `json:"error,omitempty"`
  629. Params json.RawMessage `json:"params,omitempty"`
  630. }
  631. if err := json.Unmarshal([]byte(line), &msg); err != nil {
  632. zap.L().Warn("[ACP] JSON解析失败,跳过", zap.String("line", line[:min(len(line), 100)]))
  633. continue
  634. }
  635. // 解析 ID(兼容 int64 和 string)
  636. hasId := len(msg.ID) > 0 && string(msg.ID) != "null"
  637. var numericId int64
  638. isPromptResp := false
  639. if hasId {
  640. json.Unmarshal(msg.ID, &numericId)
  641. isPromptResp = numericId == promptId && msg.Method == ""
  642. }
  643. // 收到 prompt 的响应 → turn 结束
  644. if isPromptResp {
  645. zap.L().Debug("[ACP] 收到 prompt 响应(turn结束)", zap.Int64("id", numericId))
  646. // 打印本轮完整回复
  647. if c.textBuffer != "" {
  648. zap.L().Info("[ACP] AI 回复完整内容", zap.String("text", c.textBuffer))
  649. c.textBuffer = ""
  650. }
  651. var result PromptResult
  652. if msg.Error != nil {
  653. eventCh <- Event{Type: "error", Content: msg.Error.FullMessage()}
  654. } else if err := json.Unmarshal(msg.Result, &result); err == nil {
  655. eventCh <- Event{Type: "done", SessionId: sessionId, StopReason: result.StopReason}
  656. }
  657. return
  658. }
  659. // 处理 notification (session/update 或 _kiro.dev/session/update)
  660. if !hasId && (msg.Method == "session/update" || msg.Method == "_kiro.dev/session/update") {
  661. c.handleSessionUpdate(msg.Params, eventCh)
  662. continue
  663. }
  664. // 处理 Agent→Client 反向请求(有 ID + Method = 请求)
  665. if hasId && msg.Method != "" {
  666. zap.L().Debug("[ACP] 收到 Agent 反向请求", zap.String("method", msg.Method), zap.String("id", string(msg.ID)))
  667. c.handleAgentRequest(msg.ID, msg.Method, msg.Params)
  668. continue
  669. }
  670. // 未匹配的消息(kiro扩展通知等)
  671. if msg.Method != "" {
  672. c.handleExtensionNotification(msg.Method, msg.Params, eventCh)
  673. } else {
  674. zap.L().Debug("[ACP] 未处理的消息", zap.String("line", line[:min(len(line), 200)]))
  675. }
  676. }
  677. // Scanner 结束说明进程退出
  678. eventCh <- Event{Type: "error", Content: "Agent 进程已断开"}
  679. }
  680. // Cancel 取消当前 prompt turn(ACP 协议:Notification, method="session/cancel", params={sessionId})
  681. func (c *Client) Cancel(sessionId string) {
  682. c.sendNotification("session/cancel", CancelParams{SessionId: sessionId})
  683. }
  684. // GetSessionId 获取当前会话 ID
  685. func (c *Client) GetSessionId() string {
  686. return c.sessionId
  687. }
  688. // Close 关闭 ACP Client,终止 Agent 进程
  689. func (c *Client) Close() {
  690. // 关闭 stdin 通知 Agent 退出
  691. c.stdin.Close()
  692. // 终止进程
  693. if c.cmd.Process != nil {
  694. c.cmd.Process.Kill()
  695. // Wait 回收子进程资源,防止僵尸进程
  696. go c.cmd.Wait()
  697. }
  698. // 解除可能阻塞在 permissionCh 上的 goroutine
  699. select {
  700. case c.permissionCh <- "deny":
  701. default:
  702. }
  703. }
  704. // IsAlive 检查 Agent 进程是否存活
  705. func (c *Client) IsAlive() bool {
  706. return c.cmd.ProcessState == nil
  707. }
  708. // ============ 内部方法 ============
  709. // sendRequest 发送请求(不等待响应),返回 request ID
  710. func (c *Client) sendRequest(method string, params any) int64 {
  711. c.mu.Lock()
  712. defer c.mu.Unlock()
  713. id := atomic.AddInt64(&c.requestId, 1)
  714. req := Request{
  715. JSONRPC: "2.0",
  716. ID: id,
  717. Method: method,
  718. Params: params,
  719. }
  720. data, err := json.Marshal(req)
  721. if err != nil {
  722. zap.L().Error("[ACP] 序列化请求失败", zap.Error(err))
  723. return id
  724. }
  725. zap.L().Debug("[ACP] >>> 发送", zap.String("raw", string(data)))
  726. data = append(data, '\n')
  727. if _, err := c.stdin.Write(data); err != nil {
  728. zap.L().Error("[ACP] 写入 stdin 失败", zap.String("method", method), zap.Error(err))
  729. }
  730. return id
  731. }
  732. // sendNotification 发送 JSON-RPC Notification(不带 id,不期望响应)
  733. func (c *Client) sendNotification(method string, params any) {
  734. c.mu.Lock()
  735. defer c.mu.Unlock()
  736. notif := struct {
  737. JSONRPC string `json:"jsonrpc"`
  738. Method string `json:"method"`
  739. Params any `json:"params,omitempty"`
  740. }{
  741. JSONRPC: "2.0",
  742. Method: method,
  743. Params: params,
  744. }
  745. data, err := json.Marshal(notif)
  746. if err != nil {
  747. zap.L().Error("[ACP] 序列化通知失败", zap.Error(err))
  748. return
  749. }
  750. zap.L().Debug("[ACP] >>> 发送(notification)", zap.String("raw", string(data)))
  751. data = append(data, '\n')
  752. if _, err := c.stdin.Write(data); err != nil {
  753. zap.L().Error("[ACP] 写入 stdin 失败(通知)", zap.String("method", method), zap.Error(err))
  754. }
  755. }
  756. // sendAndWait 发送请求并等待对应 ID 的响应
  757. func (c *Client) sendAndWait(method string, params any) (json.RawMessage, error) {
  758. id := c.sendRequest(method, params)
  759. // 读取响应(跳过 notification 和其他消息)
  760. for c.scanner.Scan() {
  761. line := c.scanner.Text()
  762. if line == "" {
  763. continue
  764. }
  765. var resp Response
  766. if err := json.Unmarshal([]byte(line), &resp); err != nil {
  767. continue
  768. }
  769. // 匹配 ID 的响应
  770. if resp.ID != nil && *resp.ID == id {
  771. if resp.Error != nil {
  772. return nil, fmt.Errorf("ACP 错误 [%d]: %s", resp.Error.Code, resp.Error.FullMessage())
  773. }
  774. return resp.Result, nil
  775. }
  776. // 跳过 notification(session/new 之前可能收到 kiro 扩展通知)
  777. }
  778. return nil, fmt.Errorf("未收到 %s 的响应(进程可能已退出)", method)
  779. }
  780. // handleSessionUpdate 解析并分发 session/update 通知
  781. func (c *Client) handleSessionUpdate(params json.RawMessage, eventCh chan<- Event) {
  782. var notif SessionUpdate
  783. if err := json.Unmarshal(params, &notif); err != nil {
  784. return
  785. }
  786. // 解析 update 的类型
  787. var base UpdateBase
  788. if err := json.Unmarshal(notif.Update, &base); err != nil {
  789. return
  790. }
  791. // zap.L().Debug("[ACP] session/update", zap.String("type", base.SessionUpdate))
  792. switch base.SessionUpdate {
  793. case "agent_message_chunk":
  794. var chunk AgentMessageChunk
  795. if err := json.Unmarshal(notif.Update, &chunk); err == nil {
  796. c.textBuffer += chunk.Content.Text
  797. eventCh <- Event{Type: "text", Content: chunk.Content.Text}
  798. }
  799. case "agent_thought_chunk":
  800. var chunk AgentMessageChunk
  801. if err := json.Unmarshal(notif.Update, &chunk); err == nil {
  802. c.textBuffer += chunk.Content.Text
  803. eventCh <- Event{Type: "text", Content: chunk.Content.Text}
  804. }
  805. case "tool_call":
  806. var tc ToolCall
  807. if err := json.Unmarshal(notif.Update, &tc); err == nil {
  808. zap.L().Debug("[ACP] → tool_call", zap.String("title", tc.Title), zap.String("status", tc.Status), zap.String("id", tc.ToolCallId))
  809. eventCh <- Event{Type: "tool_call", ToolCallId: tc.ToolCallId, ToolName: tc.Title, ToolStatus: tc.Status}
  810. }
  811. case "tool_call_update":
  812. var tcu ToolCallUpdate
  813. if err := json.Unmarshal(notif.Update, &tcu); err == nil {
  814. zap.L().Debug("[ACP] → tool_call_update", zap.String("title", tcu.Title), zap.String("status", tcu.Status), zap.String("id", tcu.ToolCallId))
  815. eventCh <- Event{Type: "tool_update", ToolCallId: tcu.ToolCallId, ToolName: tcu.Title, ToolStatus: tcu.Status}
  816. }
  817. case "tool_call_chunk":
  818. // 工具调用的流式参数输出(Kiro 扩展)
  819. zap.L().Debug("[ACP] → tool_call_chunk (ignored)")
  820. case "plan":
  821. zap.L().Debug("[ACP] → plan update")
  822. default:
  823. zap.L().Debug("[ACP] → 未知 session/update 类型", zap.String("type", base.SessionUpdate))
  824. }
  825. }
  826. // handleExtensionNotification 处理 Kiro 扩展通知
  827. func (c *Client) handleExtensionNotification(method string, params json.RawMessage, eventCh chan<- Event) {
  828. switch method {
  829. case "_kiro.dev/commands/available":
  830. // 可用命令和工具列表
  831. var data struct {
  832. SessionId string `json:"sessionId"`
  833. Commands []struct {
  834. Name string `json:"name"`
  835. Description string `json:"description"`
  836. } `json:"commands"`
  837. Tools []struct {
  838. Name string `json:"name"`
  839. Description string `json:"description"`
  840. Source string `json:"source"`
  841. } `json:"tools"`
  842. }
  843. if err := json.Unmarshal(params, &data); err == nil {
  844. zap.L().Debug("[ACP] 可用命令/工具更新",
  845. zap.Int("commands", len(data.Commands)),
  846. zap.Int("tools", len(data.Tools)),
  847. )
  848. // 推送工具列表给前端(可选)
  849. if len(data.Tools) > 0 {
  850. toolNames := make([]string, 0, len(data.Tools))
  851. for _, t := range data.Tools {
  852. toolNames = append(toolNames, t.Name)
  853. }
  854. eventCh <- Event{Type: "tools_available", Content: toJSONStr(toolNames)}
  855. }
  856. }
  857. case "_kiro.dev/metadata":
  858. // 上下文使用量和耗时
  859. var data struct {
  860. SessionId string `json:"sessionId"`
  861. ContextUsagePercentage float64 `json:"contextUsagePercentage"`
  862. TurnDurationMs int64 `json:"turnDurationMs,omitempty"`
  863. }
  864. if err := json.Unmarshal(params, &data); err == nil {
  865. zap.L().Debug("[ACP] metadata",
  866. zap.Float64("contextUsage%", data.ContextUsagePercentage),
  867. zap.Int64("turnMs", data.TurnDurationMs),
  868. )
  869. // 缓存最近用量/耗时,供首屏读取
  870. c.setMeta(data.ContextUsagePercentage, data.TurnDurationMs)
  871. // 上下文用量每条通知都会带(turnDurationMs 仅 turn 结束那条才有),
  872. // 因此总是转发用量,耗时有值时才附带
  873. content := map[string]any{
  874. "contextUsagePercent": data.ContextUsagePercentage,
  875. }
  876. if data.TurnDurationMs > 0 {
  877. content["turnDurationMs"] = data.TurnDurationMs
  878. }
  879. eventCh <- Event{
  880. Type: "metadata",
  881. Content: toJSONStr(content),
  882. }
  883. }
  884. case "_kiro.dev/subagent/list_update":
  885. // 子代理列表更新
  886. zap.L().Debug("[ACP] 子代理列表更新")
  887. case "_kiro.dev/mcp/server_initialized":
  888. // MCP Server 初始化完成
  889. var data struct {
  890. ServerName string `json:"serverName"`
  891. }
  892. json.Unmarshal(params, &data)
  893. zap.L().Info("[ACP] MCP Server 初始化完成", zap.String("server", data.ServerName))
  894. case "_kiro.dev/compaction/status":
  895. // 上下文压缩状态
  896. zap.L().Debug("[ACP] 上下文压缩中")
  897. case "_kiro.dev/clear/status":
  898. // 会话清除状态
  899. zap.L().Debug("[ACP] 会话清除中")
  900. default:
  901. zap.L().Debug("[ACP] 未处理的扩展通知", zap.String("method", method))
  902. }
  903. }
  904. // toJSONStr 序列化为 JSON 字符串
  905. func toJSONStr(v any) string {
  906. data, _ := json.Marshal(v)
  907. return string(data)
  908. }
  909. // handleAgentRequest 处理 Agent→Client 的反向请求
  910. func (c *Client) handleAgentRequest(rawId json.RawMessage, method string, rawParams json.RawMessage) {
  911. c.mu.Lock()
  912. defer c.mu.Unlock()
  913. zap.L().Debug("[ACP] 处理反向请求", zap.String("method", method), zap.String("id", string(rawId)), zap.String("params", string(rawParams[:min(len(rawParams), 200)])))
  914. var respData []byte
  915. switch method {
  916. case "readTextFile":
  917. // 读取文件:先从 FileStore 查找(MinIO),再从本地文件系统
  918. var params struct {
  919. Path string `json:"path"`
  920. Line *int `json:"line,omitempty"`
  921. Limit *int `json:"limit,omitempty"`
  922. }
  923. if err := json.Unmarshal(rawParams, &params); err == nil && params.Path != "" {
  924. var content string
  925. var readErr error
  926. // 优先从 FileStore(MinIO)读取:先按路径解析出 object key
  927. key, keyErr := filestore.FindKeyByPath("upload", c.UserId, c.sessionId, params.Path)
  928. if keyErr == nil && key != "" {
  929. content, readErr = filestore.ReadFile(key)
  930. zap.L().Debug("[ACP] readTextFile 从 MinIO 读取", zap.String("path", params.Path), zap.String("key", key))
  931. } else {
  932. // 回退到本地文件系统
  933. data, err := os.ReadFile(params.Path)
  934. if err == nil {
  935. content = string(data)
  936. zap.L().Debug("[ACP] readTextFile 从本地读取", zap.String("path", params.Path))
  937. } else {
  938. readErr = err
  939. }
  940. }
  941. if readErr == nil {
  942. result, _ := json.Marshal(map[string]string{"content": content})
  943. respData, _ = json.Marshal(map[string]any{
  944. "jsonrpc": "2.0",
  945. "id": rawId,
  946. "result": json.RawMessage(result),
  947. })
  948. }
  949. }
  950. if respData == nil {
  951. respData, _ = json.Marshal(map[string]any{
  952. "jsonrpc": "2.0",
  953. "id": rawId,
  954. "error": map[string]any{"code": -1, "message": "file not found"},
  955. })
  956. }
  957. case "writeTextFile":
  958. // 写入文件到 MinIO(不写本地)
  959. var params struct {
  960. Path string `json:"path"`
  961. Content string `json:"content"`
  962. }
  963. if err := json.Unmarshal(rawParams, &params); err == nil && params.Path != "" {
  964. record, err := filestore.UploadFile(c.UserId, c.sessionId, filepath.Base(params.Path), params.Content)
  965. if err == nil {
  966. respData, _ = json.Marshal(map[string]any{
  967. "jsonrpc": "2.0",
  968. "id": rawId,
  969. "result": map[string]any{},
  970. })
  971. _ = record // 文件下载通过前端标记检测实现,不再推送事件
  972. } else {
  973. zap.L().Error("[ACP] writeTextFile MinIO上传失败", zap.Error(err))
  974. }
  975. }
  976. if respData == nil {
  977. respData, _ = json.Marshal(map[string]any{
  978. "jsonrpc": "2.0",
  979. "id": rawId,
  980. "error": map[string]any{"code": -1, "message": "write failed"},
  981. })
  982. }
  983. case "requestPermission", "session/request_permission":
  984. // 解析权限请求参数
  985. var params struct {
  986. ToolCall *struct {
  987. Title string `json:"title"`
  988. } `json:"toolCall"`
  989. Options []struct {
  990. OptionId string `json:"optionId"`
  991. Name string `json:"name"`
  992. Kind string `json:"kind"`
  993. } `json:"options"`
  994. }
  995. json.Unmarshal(rawParams, &params)
  996. title := ""
  997. if params.ToolCall != nil {
  998. title = params.ToolCall.Title
  999. }
  1000. // 判断是否涉及写操作(需要手动授权)
  1001. isWriteOp := true
  1002. // isWriteOp := false
  1003. // if title != "" {
  1004. // for _, keyword := range []string{"write", "Write", "create", "Create", "delete", "Delete", "修改", "写入", "创建", "删除"} {
  1005. // if len(title) >= len(keyword) && containsStr(title, keyword) {
  1006. // isWriteOp = true
  1007. // break
  1008. // }
  1009. // }
  1010. // }
  1011. if isWriteOp && c.eventCh != nil {
  1012. // 写操作:推送权限请求给前端,等待前端回复
  1013. options := make([]PermissionOption, 0, len(params.Options))
  1014. for _, opt := range params.Options {
  1015. options = append(options, PermissionOption{
  1016. OptionId: opt.OptionId,
  1017. Name: opt.Name,
  1018. Kind: opt.Kind,
  1019. })
  1020. }
  1021. requestId := fmt.Sprintf("perm_%s", string(rawId))
  1022. c.eventCh <- Event{
  1023. Type: "permission",
  1024. Permission: &PermissionEvent{
  1025. RequestId: requestId,
  1026. Title: title,
  1027. Options: options,
  1028. },
  1029. }
  1030. // 释放 mu 锁后等待前端回复(否则会死锁)
  1031. c.mu.Unlock()
  1032. selectedOptionId := <-c.permissionCh
  1033. c.mu.Lock()
  1034. respData, _ = json.Marshal(map[string]any{
  1035. "jsonrpc": "2.0",
  1036. "id": rawId,
  1037. "result": map[string]any{
  1038. "outcome": map[string]any{
  1039. "outcome": "selected",
  1040. "optionId": selectedOptionId,
  1041. },
  1042. },
  1043. })
  1044. } else {
  1045. // 非写操作:自动允许
  1046. respData, _ = json.Marshal(map[string]any{
  1047. "jsonrpc": "2.0",
  1048. "id": rawId,
  1049. "result": map[string]any{
  1050. "outcome": map[string]any{
  1051. "outcome": "selected",
  1052. "optionId": "allow_once",
  1053. },
  1054. },
  1055. })
  1056. }
  1057. default:
  1058. // 未知请求返回错误
  1059. respData, _ = json.Marshal(map[string]any{
  1060. "jsonrpc": "2.0",
  1061. "id": rawId,
  1062. "error": map[string]any{"code": -32601, "message": "method not supported"},
  1063. })
  1064. }
  1065. if respData != nil {
  1066. zap.L().Debug("[ACP] 发送反向响应", zap.String("method", method), zap.String("resp", string(respData[:min(len(respData), 200)])))
  1067. respData = append(respData, '\n')
  1068. c.stdin.Write(respData)
  1069. } else {
  1070. zap.L().Warn("[ACP] 反向请求无响应数据", zap.String("method", method))
  1071. }
  1072. }
  1073. // containsStr 简单字符串包含检测
  1074. func containsStr(s, substr string) bool {
  1075. return len(s) >= len(substr) && (s == substr || len(s) > 0 && stringContains(s, substr))
  1076. }
  1077. func stringContains(s, substr string) bool {
  1078. for i := 0; i <= len(s)-len(substr); i++ {
  1079. if s[i:i+len(substr)] == substr {
  1080. return true
  1081. }
  1082. }
  1083. return false
  1084. }
  1085. func min(a, b int) int {
  1086. if a < b {
  1087. return a
  1088. }
  1089. return b
  1090. }