diff --git a/init.lua b/init.lua index 8d86430..acc220a 100644 --- a/init.lua +++ b/init.lua @@ -3,3 +3,4 @@ require("plugins") require("lsp") require("keymaps") require("debugging") +require("ai") diff --git a/lua/ai.lua b/lua/ai.lua new file mode 100644 index 0000000..44bd0b6 --- /dev/null +++ b/lua/ai.lua @@ -0,0 +1,188 @@ +-- CodeCompanion: AI chat / inline edits backed by agents over ACP (Agent +-- Client Protocol), so both use their own CLI login. No API keys needed. +-- claude_code -> `claude-agent-acp` (npm i -g @agentclientprotocol/claude-agent-acp), +-- which reuses the `claude` CLI login. +-- antigravity -> `agy acp` (Antigravity CLI: Gemini, plus Claude/GPT-OSS via +-- Google). Uses the `agy` Google login. +-- Chat uses Claude Code, inline uses Antigravity (Gemini 4 Hydrogen, high). +-- Agents read their own CLAUDE.md / GEMINI.md / AGENTS.md and settings, so +-- model, permissions and MCP servers come from the CLI configs unless pinned +-- here (only inline is). +-- In a chat: `ga` switches agent/model, `ge` effort, `?` lists all keymaps. +-- The winbar shows the current agent · model · effort. + +-- The ACP module directly: the generic adapters.extend() decides http vs acp +-- by looking the name up in the config, and gemini_cli is hidden from it. +local acp = require("codecompanion.adapters.acp") + +-- Antigravity (`agy acp`). There's no built-in adapter for it yet; its ACP +-- server speaks the same dialect as Gemini CLI (same auth method ids), so +-- reuse that adapter with a different command. `session_options` pins +-- model/effort/mode for new sessions (values match ids or display names). +local function antigravity(name, session_options) + return acp.extend("gemini_cli", { + name = name, -- must equal the key under adapters.acp + formatted_name = "Antigravity", + commands = { + default = { "agy", "acp" }, + yolo = { "agy", "acp", "--dangerously-skip-permissions" }, + }, + defaults = { + auth_method = "oauth-personal", -- Google login + session_config_options = session_options, + }, + }) +end + +-- Effort ("thought_level" in ACP terms; both agents report it under that +-- category). Opens a picker with just the effort levels of the current model, +-- the same one `/acp_session_options` shows after you pick "Effort" there. +-- Uses that slash command's module, which isn't public API (fine while +-- pinned to ^20). +local function pick_effort(chat) + local conn = chat.acp_connection + if not conn then + return vim.notify("Effort: only agent (ACP) chats have it", vim.log.levels.WARN) + end + for _, opt in ipairs(conn:get_config_options()) do + if opt.category == "thought_level" then + return require("codecompanion.interactions.chat.slash_commands.builtin.acp_session_options") + .new({ Chat = chat }) + :show_values(opt) + end + end + vim.notify("Effort: the agent hasn't reported one (still connecting, or this model has none)", + vim.log.levels.WARN) +end + +-- Display name of an ACP chat's current value for an option category, read +-- live from the agent connection. (The metadata CodeCompanion hands the +-- winbar caches its value->name map before the agent has sent its options, +-- so it only has raw ids there, e.g. Claude's model is just "default".) +local function acp_option_name(md, category) + local bufnr + for b, m in pairs(_G.codecompanion_chat_metadata or {}) do + if m == md then bufnr = b end + end + local chat = bufnr and require("codecompanion").buf_get_chat(bufnr) + local conn = chat and chat.acp_connection + if not conn then return nil end + for _, opt in ipairs(conn:get_config_options()) do + if opt.category == category and opt.currentValue then + for _, item in ipairs(opt.options or {}) do + for _, v in ipairs(item.options or { item }) do -- items may be grouped + if v.value == opt.currentValue then return v.name end + end + end + return opt.currentValue + end + end +end + +-- Chat winbar: title on the left, `agent · model · effort` on the right. +local function chat_winbar(md) + local title = (md.title or "CodeCompanion"):gsub("%%", "%%%%") + local parts = { md.adapter.name } + local model = acp_option_name(md, "model") or md.adapter.model -- HTTP: model id + if model then table.insert(parts, model) end + local effort = acp_option_name(md, "thought_level") + if effort then table.insert(parts, "effort " .. effort:lower()) end + local right = table.concat(parts, " · "):gsub("%%", "%%%%") + return string.format("%%#CodeCompanionChatHeader# %s%%*%%=%%#Comment#%s ", title, right) +end + +require("codecompanion").setup({ + adapters = { + acp = { + -- List only the two agents below in the adapter picker. + opts = { show_presets = false }, + + claude_code = function() + return acp.extend("claude_code", {}) + end, + + antigravity = function() return antigravity("antigravity") end, + + -- Inline edits: Gemini 4 Hydrogen at high effort. A separate + -- adapter because inline can only pin a model, not effort, and + -- setting effort on `antigravity` would change chats too. Hidden + -- from the `ga` picker below. + antigravity_inline = function() + return antigravity("antigravity_inline", { + model = "gemini-4-hydrogen", + thought_level = "high", + }) + end, + }, + http = { + -- The defaults (web search/fetch backends) plus the inline-only agent. + opts = { + hidden = { + duckduckgo = true, jina = true, markitdown = true, tavily = true, + antigravity_inline = true, + }, + }, + }, + }, + + interactions = { + chat = { + adapter = "claude_code", + keymaps = { + -- `ga` already switches agent + model; `ge` (normally "end of + -- previous word", only overridden in the chat buffer) switches + -- effort. Everything else: `/acp_session_options` (mode etc.). + change_effort = { + modes = { n = "ge" }, + callback = pick_effort, + description = "Change effort (reasoning level)", + }, + }, + }, + -- ACP agents edit a temp copy of the buffer and hand back a diff. + -- `ga` in the :CodeCompanion input box overrides this per buffer. + inline = { adapter = "antigravity_inline" }, + + -- These two only work with HTTP adapters (plain API calls), not + -- agents. They need ANTHROPIC_API_KEY; without it they stay unused + -- (background tasks are off by default; :CodeCompanionCmd errors). + -- The default would be Copilot, which isn't set up here. + cmd = { adapter = { name = "anthropic", model = "claude-haiku-5-5" } }, + background = { adapter = { name = "anthropic", model = "claude-haiku-5-5" } }, + + -- The full CLIs in a terminal split, with context sharing from + -- buffers (`:CodeCompanionCLI`, `:CodeCompanionCLI agent=antigravity`). + cli = { + agent = "claude_code", + agents = { + claude_code = { cmd = "claude", args = {}, description = "Claude Code CLI" }, + antigravity = { cmd = "agy", args = {}, description = "Antigravity CLI" }, + }, + }, + }, + + display = { + chat = { + window = { position = "right", width = 0.4 }, + -- Winbar instead of a heading in the buffer, so it stays visible. + title = { position = "winbar", text = { winbar = chat_winbar } }, + }, + }, +}) + +-- Progress float while an inline edit runs (see lua/ai_status.lua). +require("ai_status").setup() + +-- Keymaps: everything under a. Visual-mode maps use `:` rather than +-- so the selection is passed as a range ('<,'>). +local map = vim.keymap.set +map("n", "aa", "CodeCompanionChat Toggle", { desc = "AI: toggle chat" }) +map("x", "aa", ":CodeCompanionChat Add", { silent = true, desc = "AI: add selection to chat" }) +map("n", "ac", "CodeCompanionChat adapter=claude_code", { desc = "AI: new Claude Code chat" }) +map("n", "ag", "CodeCompanionChat adapter=antigravity", { desc = "AI: new Antigravity chat" }) +map({ "n", "x" }, "ai", ":CodeCompanion ", { desc = "AI: inline edit (type prompt)" }) +map("n", "ap", "CodeCompanionActions", { desc = "AI: action palette" }) +map("x", "ap", ":CodeCompanionActions", { silent = true, desc = "AI: action palette (selection)" }) +map("n", "at", "CodeCompanionCLI", { desc = "AI: CLI agent in terminal" }) +map("x", "at", ":CodeCompanionCLI", { silent = true, desc = "AI: send selection to CLI agent" }) +map("n", "ar", "CodeCompanionCodeReview", { desc = "AI: review agent changes" }) diff --git a/lua/ai_status.lua b/lua/ai_status.lua new file mode 100644 index 0000000..03f239d --- /dev/null +++ b/lua/ai_status.lua @@ -0,0 +1,163 @@ +-- Progress bar for inline edits (`:CodeCompanion`). While a request runs, a +-- one-line float sits in the bottom-right corner of the window being edited: +-- ⠹ Claude Code · Read ai.lua · 3 tools · 12s +-- CodeCompanion itself shows nothing until the diff appears. It does receive +-- the agent's progress over ACP (tool calls, thinking, reply), but inline +-- mode only keeps the reply text. So this wraps the internal method those +-- updates go through, and listens to the documented Inline* events for +-- start/stop. HTTP adapters get the spinner and timer only. +local api = vim.api +local M = {} + +local SPINNER = { "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏" } +local active = {} ---@type table inline bufnr -> state + +-- Tool titles contain paths. Inline agents edit a copy of the buffer in +-- Neovim's temp dir (e.g. /tmp/nvim.user/AbC123/1/foo.lua), so show just the +-- file name for those. Agents may write that path absolute or relative to +-- their cwd (agy does ../../nvim.user/...), so match the temp dir's unique +-- tail anywhere. Other absolute paths become cwd- or ~-relative. +local tmp_tail = vim.fn.fnamemodify(vim.fn.tempname(), ":h"):match("[^/]+/[^/]+$") +local function short_paths(s) + return (s:gsub("[%w%._%-@+~]*/[%w%._%-/@+~]+", function(p) + if tmp_tail and p:find(tmp_tail, 1, true) then return vim.fs.basename(p) end + if p:match("^/[^/]") then return vim.fn.fnamemodify(p, ":~:.") end + return p + end)) +end + +-- Window to anchor to: the current one if it shows the buffer, else any in +-- this tab that does. +local function target_win(bufnr) + if api.nvim_win_get_buf(0) == bufnr then return api.nvim_get_current_win() end + for _, win in ipairs(api.nvim_tabpage_list_wins(0)) do + if api.nvim_win_get_buf(win) == bufnr and api.nvim_win_get_config(win).relative == "" then + return win + end + end +end + +local function close_float(st) + if st.win and api.nvim_win_is_valid(st.win) then api.nvim_win_close(st.win, true) end + st.win = nil +end + +local function render(bufnr) + local st = active[bufnr] + if not st then return end + local anchor = target_win(bufnr) + if not anchor then return close_float(st) end + + st.frame = st.frame % #SPINNER + 1 + local parts = { SPINNER[st.frame] .. " " .. st.name, st.activity } + if st.tools > 0 then table.insert(parts, st.tools .. (st.tools == 1 and " tool" or " tools")) end + table.insert(parts, math.floor((vim.uv.now() - st.started) / 1000) .. "s") + local text = " " .. table.concat(parts, " · ") .. " " + + local max = api.nvim_win_get_width(anchor) - 2 + if vim.fn.strdisplaywidth(text) > max then + text = vim.fn.strcharpart(text, 0, max - 2) .. "… " + end + local width = vim.fn.strdisplaywidth(text) + + if not (st.buf and api.nvim_buf_is_valid(st.buf)) then + st.buf = api.nvim_create_buf(false, true) + vim.bo[st.buf].bufhidden = "wipe" + end + api.nvim_buf_set_lines(st.buf, 0, -1, false, { text }) + + local cfg = { + relative = "win", + win = anchor, + anchor = "SE", + row = api.nvim_win_get_height(anchor), + col = api.nvim_win_get_width(anchor), + width = width, + height = 1, + focusable = false, + zindex = 60, + border = "none", -- otherwise 'winborder' applies + } + if st.win and api.nvim_win_is_valid(st.win) then + api.nvim_win_set_config(st.win, cfg) + else + cfg.style = "minimal" + cfg.noautocmd = true + st.win = api.nvim_open_win(st.buf, false, cfg) + vim.wo[st.win].winhighlight = "Normal:StatusLine" + end +end + +local function stop(bufnr) + local st = active[bufnr] + if not st then return end + active[bufnr] = nil + st.timer:stop() + st.timer:close() + close_float(st) +end + +local function start(bufnr, adapter) + stop(bufnr) + local st = { + name = adapter and (adapter.formatted_name or adapter.name) or "AI", + activity = "starting…", + tools = 0, + frame = 0, + started = vim.uv.now(), + timer = vim.uv.new_timer(), + } + active[bufnr] = st + st.timer:start(0, 100, vim.schedule_wrap(function() render(bufnr) end)) +end + +-- ACP session/update -> one-line activity +local function on_update(st, u) + local kind = u.sessionUpdate + if kind == "tool_call" then + st.tools = st.tools + 1 + st.activity = short_paths(u.title or u.kind or "tool") + elseif kind == "tool_call_update" then + if u.title then st.activity = short_paths(u.title) end + if u.status == "failed" then st.activity = st.activity .. " (failed)" end + elseif kind == "agent_thought_chunk" then + st.activity = "thinking…" + elseif kind == "agent_message_chunk" then + st.activity = "replying…" + elseif kind == "plan" then + st.activity = "planning…" + end +end + +function M.setup() + local group = api.nvim_create_augroup("ai_inline_status", { clear = true }) + api.nvim_create_autocmd("User", { + group = group, + pattern = "CodeCompanionInlineStarted", + callback = function(ev) start(ev.data.bufnr, ev.data.adapter) end, + }) + api.nvim_create_autocmd("User", { + group = group, + pattern = { "CodeCompanionInlineFinished", "CodeCompanionRequestFinished" }, + callback = function(ev) + local d = ev.data or {} + if ev.match == "CodeCompanionInlineFinished" or d.interaction == "inline" then + stop(d.bufnr) + end + end, + }) + + -- Internal API (not part of CodeCompanion's public interface); fine + -- while the plugin is pinned to ^20. Prompt objects look methods up on + -- this table, so the wrapper applies to every prompt sent from now on. + local PromptBuilder = require("codecompanion.acp.prompt_builder") + local orig = PromptBuilder.handle_session_update + PromptBuilder.handle_session_update = function(self, params) + local o = self.options + local st = o and o.interaction == "inline" and active[o.bufnr] + if st and type(params) == "table" then pcall(on_update, st, params) end + return orig(self, params) + end +end + +return M diff --git a/lua/plugins.lua b/lua/plugins.lua index fba1cf2..79632c6 100644 --- a/lua/plugins.lua +++ b/lua/plugins.lua @@ -32,6 +32,8 @@ vim.pack.add({ { src = "https://github.com/hat0uma/csvview.nvim.git" }, { src = "https://github.com/folke/snacks.nvim" }, { src = "https://github.com/r-pletnev/pdfreader.nvim" }, + -- Pinned to the major version: breaking changes land on major bumps. + { src = "https://github.com/olimorris/codecompanion.nvim", version = vim.version.range("^20") }, }) pcall(vim.cmd.colorscheme, "gruvbox")