Repository navigation
Expand file tree
/
Copy pathcode_agent.lua
More file actions
511 lines (477 loc) · 13.6 KB
/
Copy pathcode_agent.lua
File metadata and controls
511 lines (477 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
--- Generic floating-terminal launcher.
---
--- Example:
--- local Launcher = require("kide.code_agent")
--- local lazygit = Launcher.new({ command = { "lazygit" }, title = "Lazygit" })
--- lazygit:toggle()
---
--- Supported agents are declared in `AGENTS` below; `M.select(name)` switches to one.
local M = {}
local DEFAULT_TIMEOUT_MS, DEFAULT_SETTLE_MS = 8000, 300
---@class KideLauncherState
---@field buf? integer
---@field win? integer
---@field job? integer
---@field ready boolean
---@field pending string[]
---@field generation integer
---@field startup_timer? table
---@field settle_timer? table
---@field output_seen boolean
---@class KideLauncher
---@field options KideLauncherOptions
---@field state KideLauncherState
local Launcher = {}
Launcher.__index = Launcher
local function command_of(command)
if type(command) == "string" then
return { command }
end
if type(command) == "table" and #command > 0 then
return vim.deepcopy(command)
end
end
local function window_options(title)
local width, height = math.floor(vim.o.columns * 0.9), math.floor(vim.o.lines * 0.9)
return {
relative = "editor",
style = "minimal",
border = "rounded",
focusable = true,
row = math.floor((vim.o.lines - height) * 0.5),
col = math.floor((vim.o.columns - width) * 0.5),
width = width,
height = height,
title = title,
title_pos = "center",
}
end
---@class KideLauncherOptions
---@field command string|string[] Command to launch (required).
---@field title? string Floating-window title.
---@field cwd? string Process working directory.
---@field ready_patterns? string[] Wait for one Lua pattern before flushing queued input.
---@field startup_timeout_ms? integer Ready-detection timeout.
---@field startup_settle_ms? integer Delay after initial output before considering ready.
---@field win_opts? table|fun(title: string): table Options for nvim_open_win.
---@field on_exit? fun(code: integer, signal: integer) Process-exit callback.
---@param opts KideLauncherOptions
---@return KideLauncher
function M.new(opts)
assert(
type(opts) == "table" and command_of(opts.command),
"`command` must be a non-empty string or list"
)
return setmetatable({
options = vim.deepcopy(opts),
state = {
buf = nil,
win = nil,
job = nil,
ready = false,
pending = {},
generation = 0,
startup_timer = nil,
settle_timer = nil,
output_seen = false,
},
}, Launcher)
end
function Launcher:is_running()
local job = self.state.job
return job and job > 0 and vim.fn.jobwait({ job }, 0)[1] == -1 or false
end
function Launcher:_stop_timer(name)
local timer = self.state[name]
if timer then
timer:stop()
timer:close()
self.state[name] = nil
end
end
function Launcher:_close_window(force)
local win = self.state.win
local closed = win
and vim.api.nvim_win_is_valid(win)
and pcall(vim.api.nvim_win_close, win, force or false)
self.state.win = nil
if closed then
vim.schedule(function()
pcall(function()
vim.cmd("checktime")
end)
end)
end
end
function Launcher:_reset()
self:_stop_timer("startup_timer")
self:_stop_timer("settle_timer")
self:_close_window(true)
if self.state.buf and vim.api.nvim_buf_is_valid(self.state.buf) then
vim.api.nvim_buf_delete(self.state.buf, { force = true })
end
local state = self.state
state.buf, state.job, state.ready, state.pending, state.output_seen = nil, nil, false, {}, false
state.generation = state.generation + 1
end
function Launcher:close()
self:_close_window(true)
end
function Launcher:_title()
return self.options.title or command_of(self.options.command)[1]
end
function Launcher:_win_opts()
local opts = self.options.win_opts
if type(opts) == "function" then
return opts(self:_title())
end
return opts and vim.deepcopy(opts) or window_options(self:_title())
end
function Launcher:_open_window()
if self.state.buf and vim.api.nvim_buf_is_valid(self.state.buf) then
self.state.win = vim.api.nvim_open_win(self.state.buf, true, self:_win_opts())
end
end
function Launcher:_focus()
if self.state.win and vim.api.nvim_win_is_valid(self.state.win) then
vim.api.nvim_set_current_win(self.state.win)
vim.cmd("startinsert!")
end
end
function Launcher:_write(text)
vim.fn.chansend(self.state.job, text)
if not text:match("\n$") then
vim.fn.chansend(self.state.job, "\n")
end
end
function Launcher:_mark_ready()
if not self:is_running() or self.state.ready then
return
end
self.state.ready = true
self:_stop_timer("startup_timer")
self:_stop_timer("settle_timer")
local pending = self.state.pending
self.state.pending = {}
for _, text in ipairs(pending) do
self:_write(text)
end
end
function Launcher:_buffer_is_ready()
local patterns = self.options.ready_patterns
if not patterns or #patterns == 0 then
return true
end
for _, line in ipairs(vim.api.nvim_buf_get_lines(self.state.buf, 0, -1, false)) do
if line:match("%S") then
self.state.output_seen = true
end
for _, pattern in ipairs(patterns) do
if line:lower():match(pattern:lower()) then
return true
end
end
end
return false
end
function Launcher:_watch_ready()
local state, generation = self.state, self.state.generation
if not self.options.ready_patterns or #self.options.ready_patterns == 0 then
self:_mark_ready()
return
end
vim.api.nvim_buf_attach(state.buf, false, {
on_lines = function()
if generation ~= state.generation or not self:is_running() or state.ready then
return true
end
if self:_buffer_is_ready() then
self:_mark_ready()
return true
end
if state.output_seen then
self:_stop_timer("settle_timer")
state.settle_timer = vim.uv.new_timer()
state.settle_timer:start(
self.options.startup_settle_ms or DEFAULT_SETTLE_MS,
0,
vim.schedule_wrap(function()
if
generation == state.generation
and self:is_running()
and not state.ready
and state.output_seen
then
self:_mark_ready()
end
end)
)
end
end,
})
state.startup_timer = vim.uv.new_timer()
state.startup_timer:start(
self.options.startup_timeout_ms or DEFAULT_TIMEOUT_MS,
0,
vim.schedule_wrap(function()
if generation == state.generation and self:is_running() and not state.ready then
self:_mark_ready()
end
end)
)
end
---@return boolean
function Launcher:start()
if self:is_running() then
return true
end
self:_reset()
local state, command = self.state, command_of(self.options.command)
state.buf = vim.api.nvim_create_buf(false, true)
vim.bo[state.buf].modified = false
vim.b[state.buf].q_close = false
pcall(require("kide").term_stl, state.buf, self:_title())
vim.api.nvim_create_autocmd("WinLeave", {
buf = state.buf,
callback = function()
self:_close_window(false)
end,
})
vim.api.nvim_create_autocmd(
"TermOpen",
{ buf = state.buf, command = "startinsert!", once = true }
)
self:_open_window()
local ok, job = pcall(vim.fn.jobstart, command, {
term = true,
cwd = self.options.cwd,
on_exit = function(_, code, signal)
local callback = self.options.on_exit
self:_reset()
if callback then
callback(code, signal)
end
end,
})
if not ok or job <= 0 then
self:_reset()
vim.notify(
("%s failed to start: %s"):format(self.options.title or command[1], tostring(job)),
vim.log.levels.ERROR
)
return false
end
state.job = job
self:_watch_ready()
return true
end
---@return boolean
function Launcher:toggle()
if vim.api.nvim_get_mode().mode == "i" then
vim.cmd("stopinsert")
end
if self:is_running() then
if self.state.win and vim.api.nvim_win_is_valid(self.state.win) then
self:_close_window(true)
else
self:_open_window()
self:_focus()
end
return true
end
if self:start() then
self:_focus()
return true
end
return false
end
---@param text string
---@param opt? { focus?: boolean }
---@return boolean
function Launcher:send(text, opt)
opt = opt or {}
if not text or text == "" then
return false
end
if not self:is_running() and not self:start() then
return false
end
if
opt.focus ~= false and (not self.state.win or not vim.api.nvim_win_is_valid(self.state.win))
then
self:_open_window()
end
if opt.focus ~= false then
self:_focus()
end
if self.state.ready then
self:_write(text)
else
table.insert(self.state.pending, text)
end
return true
end
M.Launcher = Launcher
--- 支持的 code agent。顺序即选择菜单顺序, `name` 同时是 `M.select` / `:Codex` 等入口名。
local AGENTS = {
{
name = "Codex",
command = { "codex" },
ready_patterns = { "esc to toggle", "cwd:", "model:", "tokens" },
},
{
name = "Zagent",
command = { "zagent" },
ready_patterns = { "zagent" },
},
{
name = "OpenCode",
command = { "opencode" },
ready_patterns = { "ask anything", "ctrl+p", "commands" },
},
{
name = "Claude",
command = { "claude" },
ready_patterns = { "welcome to claude code", "? for shortcuts" },
},
{
name = "Pi",
command = { "pi" },
ready_patterns = { "escape interrupt", "/ commands", "ctrl+o" },
},
}
--- 选择菜单用的名字, 与 `M.agents` 的键一一对应
M.agent_names = {}
---@type table<string, KideLauncher>
M.agents = {}
for _, agent in ipairs(AGENTS) do
local name = agent.name
M.agent_names[#M.agent_names + 1] = name
M.agents[name] = M.new({
command = agent.command,
title = name,
ready_patterns = agent.ready_patterns,
})
end
M.current = nil
---@param bufnr? integer
---@return string
function M.buffer_path(bufnr)
local filename = vim.api.nvim_buf_get_name(bufnr or vim.api.nvim_get_current_buf())
if filename == "" then
return ""
end
local cwd = vim.uv.cwd()
if not cwd or cwd == "" then
return filename
end
local relative = vim.fn.fnamemodify(filename, ":.")
if relative ~= "." and relative ~= filename and not relative:match("^%.%.") then
return relative
end
local prefix = cwd:sub(-1) == "/" and cwd or (cwd .. "/")
return filename:sub(1, #prefix) == prefix and filename:sub(#prefix + 1) or filename
end
function M.send(text, opt)
if M.current == nil then
M.toggle()
end
if M.current == nil then
vim.notify("No code agent selected", vim.log.levels.ERROR)
return false
end
return M.current:send(text, opt)
end
--- 把某个 agent 设为当前 agent 并打开
---@param name string
---@return boolean
function M.select(name)
local launcher = M.agents[name]
if not launcher then
vim.notify("Unknown code agent: " .. name, vim.log.levels.ERROR)
return false
end
M.current = launcher
launcher:toggle()
return true
end
local function _select_launcher()
vim.ui.select(M.agent_names, { prompt = "Select code agent:" }, function(choice)
if choice then
M.select(choice)
end
end)
end
function M.toggle()
if M.current == nil then
_select_launcher()
else
M.current:toggle()
end
end
---@param diagnostics vim.Diagnostic[]
---@param opt? { code?: string[], extra_prompt?: string, bufnr?: integer }
---@return string?
function M.build_fix_message(diagnostics, opt)
opt = opt or {}
if not diagnostics or vim.tbl_isempty(diagnostics) then
return nil
end
local bufnr = opt.bufnr or vim.api.nvim_get_current_buf()
local filename, filetype = M.buffer_path(bufnr), vim.bo[bufnr].filetype or "text"
local need_code = not opt.code
local message = { "请根据下面的 LSP/编译诊断直接修复代码。" }
if opt.extra_prompt and opt.extra_prompt ~= "" then
table.insert(message, "附加要求: " .. opt.extra_prompt)
end
if filename ~= "" then
table.insert(message, "文件: " .. filename)
end
for _, diagnostic in ipairs(diagnostics) do
local severity = diagnostic.severity == 1 and "ERROR"
or diagnostic.severity == 2 and "WARN"
or "INFO"
table.insert(message, "")
table.insert(message, "## " .. severity .. ": " .. (diagnostic.code or "Unknown Code"))
table.insert(message, "- Source: " .. (diagnostic.source or "Unknown Source"))
table.insert(
message,
("- Range: %d:%d - %d:%d"):format(
diagnostic.lnum + 1,
diagnostic.col + 1,
diagnostic.end_lnum + 1,
diagnostic.end_col + 1
)
)
local code = need_code
and vim.api.nvim_buf_get_lines(bufnr, diagnostic.lnum, diagnostic.end_lnum + 1, false)
or {}
if #code > 0 then
vim.list_extend(message, { "- Code Snippet", "```" .. filetype })
vim.list_extend(message, code)
table.insert(message, "```")
end
vim.list_extend(message, { "- Diagnostic Message", "```text" })
vim.list_extend(message, vim.split(diagnostic.message or "No message provided", "\n"))
table.insert(message, "```")
end
if opt.code and not vim.tbl_isempty(opt.code) then
vim.list_extend(message, { "", "## Selected Code", "```" .. filetype })
vim.list_extend(message, opt.code)
table.insert(message, "```")
end
return table.concat(message, "\n")
end
function M.fix_diagnostics(opt)
opt = opt or {}
local bufnr = opt.bufnr or vim.api.nvim_get_current_buf()
local diagnostics = opt.diagnostics
or vim.diagnostic.get(bufnr, { lnum = vim.api.nvim_win_get_cursor(0)[1] - 1 })
if vim.tbl_isempty(diagnostics) then
vim.notify("没有诊断信息", vim.log.levels.INFO)
return false
end
local message = M.build_fix_message(diagnostics, opt)
return message and M.send(message) or false
end
return M