### Setup and Teardown Handlers Source: https://codecompanion.olimorris.dev/extending/adapters Implement `setup` before a request to perform initialization and `teardown` after a request to clean up resources. The `setup` handler must return a boolean to indicate whether to proceed. ```lua handlers = { lifecycle = { setup = function(self) -- Perform initialization return true -- Must return boolean end, teardown = function(self) -- Clean up resources end, }, } ``` -------------------------------- ### Configure Azure OpenAI HTTP Adapter Source: https://codecompanion.olimorris.dev/configuration/adapters-http Example setup for the Azure OpenAI HTTP adapter. Includes configuring API key, endpoint, deployment name, and default interactions. ```lua require("codecompanion").setup({ adapters = { http = { azure_openai = function() return require("codecompanion.adapters").extend("azure_openai", { env = { api_key = "YOUR_AZURE_OPENAI_API_KEY", endpoint = "YOUR_AZURE_OPENAI_ENDPOINT", }, schema = { model = { default = "YOUR_DEPLOYMENT_NAME", }, }, }) end, }, }, interactions = { chat = { adapter = "azure_openai", }, inline = { adapter = "azure_openai", }, }, }) ``` -------------------------------- ### CodeCompanion Setup with Calculator Tool Source: https://codecompanion.olimorris.dev/extending/tools Configures CodeCompanion with the calculator tool, defining its description, name, and command logic. Includes a system prompt to guide the LLM on its capabilities. ```lua require("codecompanion").setup({ interactions = { chat = { tools = { calculator = { description = "Perform calculations", name = "calculator", cmds = { ---@param self CodeCompanion.Tool.Calculator The Calculator tool ---@param args table The arguments from the LLM's tool call ---@param opts { input: any, output_cb: fun(result: table) } ---@return nil|{ status: "success"|"error", data: string } function(self, args, opts) -- Get the numbers and operation requested by the LLM local num1 = tonumber(args.num1) local num2 = tonumber(args.num2) local operation = args.operation -- Validate input if not num1 then return { status = "error", data = "First number is missing or invalid" } end if not num2 then return { status = "error", data = "Second number is missing or invalid" } end if not operation then return { status = "error", data = "Operation is missing" } end -- Perform the calculation local result if operation == "add" then result = num1 + num2 elseif operation == "subtract" then result = num1 - num2 elseif operation == "multiply" then result = num1 * num2 elseif operation == "divide" then if num2 == 0 then return { status = "error", data = "Cannot divide by zero" } end result = num1 / num2 else return { status = "error", data = "Invalid operation: must be add, subtract, multiply, or divide", } end return { status = "success", data = result } end, }, system_prompt = [[## Calculator Tool (`calculator`) ## CONTEXT - You have access to a calculator tool running within CodeCompanion, in Neovim. - You can use it to add, subtract, multiply or divide two numbers. ### OBJECTIVE - Do a mathematical operation on two numbers when the user asks ``` -------------------------------- ### Extend Chat Keymaps in Extension Setup Source: https://codecompanion.olimorris.dev/extending/extensions Add custom actions to the chat keymaps within an extension's setup function. This example adds an 'Open Saved Chats' action. ```lua --This is called on codecompanion setup. --You can access config via require("codecompanion.config") and chat via require("codecompanion.chat").last_chat() etc function Extension.setup(opts) -- Add action to chat keymaps local chat_keymaps = require("codecompanion.config").interactions.chat.keymaps chat_keymaps.open_saved_chats = { modes = { n = opts.keymap or "gh", }, description = "Open Saved Chats", callback = function(chat) -- Implementation of opening saved chats vim.notify("Opening saved chats for " .. chat.id) end } end ``` -------------------------------- ### Lazy.nvim Configuration for CodeCompanion Source: https://codecompanion.olimorris.dev/getting-started This example demonstrates how to integrate CodeCompanion into a lazy.nvim configuration. It includes the plugin, its dependencies, and the setup options, including the Anthropic adapter and log level. ```lua { "olimorris/codecompanion.nvim", dependencies = { "nvim-lua/plenary.nvim" }, opts = { interactions = { chat = { adapter = "anthropic", model = "claude-sonnet-4-20250514" }, }, -- NOTE: The log_level is in `opts.opts` opts = { log_level = "DEBUG", }, }, } ``` -------------------------------- ### Install and Configure mcphub.nvim Extension Source: https://codecompanion.olimorris.dev/installation Install the mcphub.nvim extension alongside CodeCompanion.nvim using Lazy.nvim. Configure CodeCompanion.nvim to use the mcphub extension with specified options. ```lua -- Lazy.nvim { "olimorris/codecompanion.nvim", dependencies = { "ravitemer/mcphub.nvim" } } ``` ```lua require("codecompanion").setup({ extensions = { mcphub = { callback = "mcphub.extensions.codecompanion", opts = { make_vars = true, make_slash_commands = true, show_result_in_chat = true } } } }) ``` -------------------------------- ### Install CodeCompanion.nvim with Packer.nvim Source: https://codecompanion.olimorris.dev/installation Set up Packer.nvim to install CodeCompanion.nvim, specifying the tag for versioning and listing required plugins. Configuration is done within the 'config' function. ```lua use({ "olimorris/codecompanion.nvim", tag = "^19.0.0", config = function() require("codecompanion").setup() end, requires = { "nvim-lua/plenary.nvim", "nvim-treesitter/nvim-treesitter", }, }), ``` -------------------------------- ### Install CodeCompanion.nvim with vim.pack Source: https://codecompanion.olimorris.dev/installation Install CodeCompanion.nvim and its dependencies using vim.pack. Remember to call require('codecompanion').setup() in your configuration. ```lua vim.pack.add({ "https://www.github.com/nvim-lua/plenary.nvim" }) vim.pack.add({ "https://github.com/nvim-treesitter/nvim-treesitter" }) vim.pack.add({ { src = "https://www.github.com/olimorris/codecompanion.nvim", version = vim.version.range("^19.0.0") } }) -- Somewhere in your config require("codecompanion").setup() ``` -------------------------------- ### File-based Per-Project Configuration Example Source: https://codecompanion.olimorris.dev/configuration/others An example of a valid Lua table structure for file-based per-project configuration. This defines interaction settings, including the chat adapter and tools. ```lua return { interactions = { chat = { adapter = { name = "copilot", model = "claude-sonnet-4.6", }, tools = { opts = { default_tools = { "memory", }, }, }, }, }, } ``` -------------------------------- ### Install mcphub Extension with lazy.nvim Source: https://codecompanion.olimorris.dev/configuration/extensions Use this snippet to install the mcphub.nvim extension as a dependency when setting up codecompanion.nvim with lazy.nvim. ```lua { "olimorris/codecompanion.nvim", dependencies = { -- Add mcphub.nvim as a dependency "ravitemer/mcphub.nvim" } } ``` -------------------------------- ### Basic Rule Group Setup Source: https://codecompanion.olimorris.dev/configuration/rules Defines a basic rule group with a description and a list of literal file paths. ```lua require("codecompanion").setup({ rules = { my_project_rules = { -- [!code focus:9] description = "Rule files for My Project", files = { -- Literal file paths (absolute or relative to cwd) "~/.claude/CLAUDE.md", "CLAUDE.md", "CLAUDE.local.md", }, }, }, }) ``` -------------------------------- ### Tool Handlers: Setup and On-Exit Source: https://codecompanion.olimorris.dev/extending/tools Defines functions to be executed before (setup) and after (on_exit) a tool runs. These handlers are useful for dynamic setup or post-execution notifications. ```lua handlers = { ---@param self CodeCompanion.Tool.Calculator ---@param meta { tools: CodeCompanion.Tools } setup = function(self, meta) return vim.notify("setup function called", vim.log.levels.INFO) end, ---@param self CodeCompanion.Tool.Calculator ---@param meta { tools: CodeCompanion.Tools } on_exit = function(self, meta) return vim.notify("on_exit function called", vim.log.levels.INFO) end, }, ``` -------------------------------- ### Install CodeCompanion.nvim with Lazy.nvim Source: https://codecompanion.olimorris.dev/installation Configure Lazy.nvim to install CodeCompanion.nvim, including its dependencies. Ensure you specify the version and any necessary options. ```lua { "olimorris/codecompanion.nvim", version = "^19.0.0", opts = {}, dependencies = { "nvim-lua/plenary.nvim", "nvim-treesitter/nvim-treesitter", }, }, ``` -------------------------------- ### Example Event Data for CodeCompanionRequestStarted Source: https://codecompanion.olimorris.dev/usage/events This is an example of the data payload received when the `CodeCompanionRequestStarted` event is fired. It includes buffer information, adapter details, and request identifiers. ```lua { buf = 10, data = { adapter = { formatted_name = "Copilot", model = "o3-mini-2025-01-31", name = "copilot" }, bufnr = 10, id = 6107753, interaction = "chat" }, event = "User", file = "CodeCompanionRequestStarted", group = 14, id = 30, match = "CodeCompanionRequestStarted" } ``` -------------------------------- ### Install and Configure History Extension Source: https://codecompanion.olimorris.dev/extending/extensions Install the history extension as a dependency and enable it in your CodeCompanion setup. You can specify the directory to save chat history. ```lua -- Install the extension { "olimorris/codecompanion.nvim", dependencies = { "ravitemer/codecompanion-history.nvim" -- history extension } } -- Configure in your setup require("codecompanion").setup({ extensions = { history = { enabled = true, -- defaults to true opts = { dir_to_save = vim.fn.stdpath("data") .. "/codecompanion_chats.json", } } } }) ``` -------------------------------- ### Old Handler Format Example Source: https://codecompanion.olimorris.dev/extending/adapters An example of the previous flat handler structure for adapters. This format is still supported but the new nested structure is recommended for better organization. ```lua handlers = { setup = function(self) end, form_parameters = function(self, params, messages) end, form_messages = function(self, messages) end, chat_output = function(self, data, tools) end, inline_output = function(self, data, context) end, on_exit = function(self, data) end, teardown = function(self) end, tools = { format_tool_calls = function(self, tools) end, output_response = function(self, tool_call, output) end, }, } ``` -------------------------------- ### Example Rule File for codecompanion Parser Source: https://codecompanion.olimorris.dev/usage/chat-buffer/rules An example of a rules file that can be processed by the `codecompanion` parser. It includes a system prompt section and a context section that references another file. ```markdown # Example Rules File ## System Prompt What ever goes in this section is used as a system prompt in the chat buffer. So you can specify instructions: - Here - And here ...and anywhere here ## My other header @./lua/codecompanion/interactions/chat/tools/init.lua Anything in this section is added as context to the chat buffer. The file above is also shared ``` -------------------------------- ### Lua Utility Function Example Source: https://codecompanion.olimorris.dev/configuration/prompt-library An example of a Lua utility file defining a function to get staged git diff output, intended to be used by markdown prompts. ```lua return { diff = function(args) return vim.system({ "git", "diff", "--no-ext-diff", "--staged" }, { text = true }):wait().stdout end, } ``` -------------------------------- ### MCP Default Servers Configuration Source: https://codecompanion.olimorris.dev/configuration/mcp Configure which MCP servers start automatically with their tools added to the chat buffer. Servers not listed can be started on-demand. ```lua require("codecompanion").setup({ mcp = { servers = { ["sequential-thinking"] = { cmd = { "npx", "-y", "@modelcontextprotocol/server-sequential-thinking" }, }, ["tavily-mcp"] = { cmd = { "npx", "-y", "tavily-mcp@latest" }, }, }, opts = { default_servers = { "sequential-thinking" }, }, }, }) ``` -------------------------------- ### Lua Prompt: Specify Adapter Source: https://codecompanion.olimorris.dev/configuration/prompt-library Configures a Lua prompt to use a specific adapter and model, equivalent to the markdown example. ```lua opts = { adapter = { name = "ollama", model = "deepseek-coder:6.7b", }, } ``` -------------------------------- ### Basic Extension Structure Source: https://codecompanion.olimorris.dev/extending/extensions Define the structure for a CodeCompanion extension, including the `setup` function and optional `exports`. The `init.lua` file should export a module conforming to the `CodeCompanion.Extension` type. ```lua --@class CodeCompanion.Extension --@field setup fun(opts: table) Function called when extension is loaded --@field exports? table Functions exposed via codecompanion.extensions.your_extension local Extension = {} --@param opts table Configuration options function Extension.setup(opts) -- Initialize extension -- Add actions, keymaps etc. end -- Optional: Functions exposed via codecompanion.extensions.your_extension Extension.exports = { clear_history = function() end } return Extension ``` -------------------------------- ### Markdown Prompt Example Source: https://codecompanion.olimorris.dev/configuration/prompt-library A basic markdown prompt with frontmatter for configuration and sections for system and user messages. Uses placeholders for dynamic content. ```markdown --- name: Explain Code interaction: chat description: Explain how code works --- ## system You are an expert programmer who excels at explaining code clearly and concisely. ## user Please explain the following code: ```${context.filetype} ${context.code} ``` ``` -------------------------------- ### Example Rule File for Claude Parser Source: https://codecompanion.olimorris.dev/usage/chat-buffer/rules An example of a rules file that can be parsed with the Claude parser. It includes references to other files which are added as context to the chat buffer. ```markdown # Example Claude Rules File @./lua/codecompanion/interactions/chat/tools/init.lua @INSTRUCTIONS.md This is a rules file that can be parsed with the Claude parser. Anything in this file is added as context to the chat buffer. Including the files above. ``` -------------------------------- ### Tool Replacement Message Example Source: https://codecompanion.olimorris.dev/usage/chat-buffer/agents-tools Demonstrates how CodeCompanion replaces tool calls in prompts with a readable message for the LLM. This ensures efficient tool usage while maintaining prompt clarity. ```markdown Use @{lorem_ipsum} to generate a random paragraph ``` ```markdown Use the lorem_ipsum tool to generate a random paragraph ``` -------------------------------- ### Define Calculator Tool Schema and Handlers Source: https://codecompanion.olimorris.dev/extending/tools This snippet shows how to define a 'calculator' tool with its schema, including parameters for mathematical operations, and sets up setup, on_exit, success, and error handlers. ```lua return CodeCompanion.Tool.new({ name = "calculator", schema = { type = "function", ["function"] = { name = "calculator", description = "Perform simple mathematical operations on a user's machine", parameters = { type = "object", properties = { num1 = { type = "integer", description = "The first number in the calculation", }, num2 = { type = "integer", description = "The second number in the calculation", }, operation = { type = "string", enum = { "add", "subtract", "multiply", "divide" }, description = "The mathematical operation to perform on the two numbers", }, }, required = { "num1", "num2", "operation", }, additionalProperties = false, }, strict = true, }, }, handlers = { --@param self CodeCompanion.Tool.Calculator --@param meta { tools: CodeCompanion.Tools } setup = function(self, meta) return vim.notify("setup function called", vim.log.levels.INFO) end, --@param self CodeCompanion.Tool.Calculator --@param meta { tools: CodeCompanion.Tools } on_exit = function(self, meta) return vim.notify("on_exit function called", vim.log.levels.INFO) end, }, output = { --@param self CodeCompanion.Tool.Calculator --@param stdout table --@param meta { tools: CodeCompanion.Tools, cmd: table } success = function(self, stdout, meta) local chat = meta.tools.chat return chat:add_tool_output(self, tostring(stdout[1])) end, --@param self CodeCompanion.Calculator --@param stderr table The error output from the command --@param meta { tools: CodeCompanion.Tools, cmd: table } error = function(self, stderr, meta) return vim.notify("An error occurred", vim.log.levels.ERROR) end, }, }) ``` }, { ``` -------------------------------- ### Configure Inline Keymaps Source: https://codecompanion.olimorris.dev/configuration/inline Set up keymaps for accepting and rejecting inline code changes. This example assigns 'ga' to accept and 'gr' to reject changes in normal mode. ```lua require("codecompanion").setup({ interactions = { inline = { keymaps = { accept_change = { modes = { n = "ga" }, description = "Accept the suggested change", }, reject_change = { modes = { n = "gr" }, opts = { nowait = true }, description = "Reject the suggested change", }, }, }, }, }) ``` -------------------------------- ### New Nested Handler Format Example Source: https://codecompanion.olimorris.dev/extending/adapters The recommended new nested handler structure for adapters, offering improved organization for lifecycle, request, response, and tools management. ```lua handlers = { lifecycle = { setup = function(self) end, on_exit = function(self, data) end, teardown = function(self) end, }, request = { build_parameters = function(self, params, messages) end, build_messages = function(self, messages) end, }, response = { parse_chat = function(self, data, tools) end, parse_inline = function(self, data, context) end, }, tools = { format_calls = function(self, tools) end, format_response = function(self, tool_call, output) end, }, } ``` -------------------------------- ### Lua Context Fields Example Source: https://codecompanion.olimorris.dev/configuration/prompt-library Illustrates the structure and available fields within the Lua context object, providing details about the current buffer and cursor position. ```lua { bufnr = 7, buftype = "", code = [[local function hello(text) return "hello " .. text end]], cursor_pos = { 10, 3 }, end_col = 3, end_line = 10, filetype = "lua", is_normal = false, is_visual = true, lines = { "local function hello(text)", ' return "hello " .. text', "end" }, mode = "V", start_col = 1, start_line = 8, winnr = 1000 } ``` -------------------------------- ### Markdown Workflow Example Source: https://codecompanion.olimorris.dev/configuration/prompt-library Defines a multi-step chat workflow using Markdown. Note: Agentic workflows are not supported in Markdown prompts. ```markdown --- name: Oli's test workflow interaction: chat description: Use a workflow to test the plugin opts: adapter: name: copilot model: gpt-4.1 ignore_system_prompt: true is_workflow: true --- ## user Generate a Python class for managing a book library with methods for adding, removing, and searching books ## user Write unit tests for the library class you just created ## user Create a TypeScript interface for a complex e-commerce shopping cart system ``` -------------------------------- ### Configure mcphub Extension Options Source: https://codecompanion.olimorris.dev/configuration/extensions Configure the mcphub extension within your CodeCompanion setup by specifying the callback and options. This allows customization of its behavior, such as variable creation and result display. ```lua -- Configure in your setup require("codecompanion").setup({ extensions = { mcphub = { callback = "mcphub.extensions.codecompanion", opts = { make_vars = true, make_slash_commands = true, show_result_in_chat = true } } } }) ``` -------------------------------- ### Synchronous Function-Based Tool (Calculator) Source: https://codecompanion.olimorris.dev/extending/tools Implement a synchronous tool using a Lua function. This example demonstrates a calculator that performs basic arithmetic operations based on arguments provided by the LLM. Input validation is included. ```lua cmds = { ---@param self CodeCompanion.Tool.Calculator The Calculator tool ---@param args table The arguments from the LLM's tool call ---@param opts { input: any, output_cb: fun(result: table) } ---@return nil|{ status: "success"|"error", data: string } function(self, args, opts) -- Get the numbers and operation requested by the LLM local num1 = tonumber(args.num1) local num2 = tonumber(args.num2) local operation = args.operation -- Validate input if not num1 then return { status = "error", data = "First number is missing or invalid" } end if not num2 then return { status = "error", data = "Second number is missing or invalid" } end if not operation then return { status = "error", data = "Operation is missing" } end -- Perform the calculation local result if operation == "add" then result = num1 + num2 elseif operation == "subtract" then result = num1 - num2 elseif operation == "multiply" then result = num1 * num2 elseif operation == "divide" then if num2 == 0 then return { status = "error", data = "Cannot divide by zero" } end result = num1 / num2 else return { status = "error", data = "Invalid operation: must be add, subtract, multiply, or divide" } end return { status = "success", data = result } end, } ``` -------------------------------- ### Hooking into 'CodeCompanionInline' Events Source: https://codecompanion.olimorris.dev/usage/events This snippet sets up an autocommand to execute a callback when a 'CodeCompanionInline*' event is triggered. It specifically formats the buffer when the 'CodeCompanionInlineFinished' event occurs. Ensure the 'conform' plugin is installed and configured. ```lua local group = vim.api.nvim_create_augroup("CodeCompanionHooks", {}) vim.api.nvim_create_autocmd({ "User" }, { pattern = "CodeCompanionInline*", group = group, callback = function(request) if request.match == "CodeCompanionInlineFinished" then -- Format the buffer after the inline request has completed require("conform").format({ bufnr = request.buf }) end end, }) ``` -------------------------------- ### Example Lua Workflow Definition Source: https://codecompanion.olimorris.dev/configuration/prompt-library Defines a chat interaction workflow with multiple user prompts and specifies adapter options. This is a basic structure for a multi-turn conversation or task sequence. ```lua ["Oli's test workflow"] = { interaction = "chat", description = "Use a workflow to test the plugin", opts = { adapter = { name = "copilot", model = "gpt-4.1", }, ignore_system_prompt = true, is_workflow = true, }, prompts = { { { role = "user", content = "Generate a Python class for managing a book library with methods for adding, removing, and searching books", }, }, { { role = "user", content = "Write unit tests for the library class you just created", }, }, { { role = "user", content = "Create a TypeScript interface for a complex e-commerce shopping cart system", }, }, { { role = "user", content = "Write a recursive algorithm to balance a binary search tree in Java", }, }, }, }, ``` -------------------------------- ### Custom Agent Group Configuration Source: https://codecompanion.olimorris.dev/usage/chat-buffer/agents-tools Define a custom agent group with a dynamic system prompt and specific tools. This example shows how to ignore default system prompts and collapse tools into a single reference. ```lua groups = { ["my_agent"] = { description = "My custom agent", system_prompt = function(group, ctx) return string.format( "You are a coding agent. The date is %s. The user is on %s.", ctx.date, ctx.os ) end, tools = { "read_file", "insert_edit_into_file", "run_command" }, opts = { collapse_tools = true, ignore_system_prompt = true, -- Remove the chat's default system prompt ignore_tool_system_prompt = true, -- Remove the default tool system prompt }, }, }, ``` -------------------------------- ### Using Agent Mode Source: https://codecompanion.olimorris.dev/usage/chat-buffer/agents-tools Initiate agent mode to leverage a curated set of tools and a specific system prompt for autonomous coding tasks. This mode replaces default prompts, guiding the LLM's behavior. ```markdown @{agent} Can we create a todo list app in Vue.js? ``` -------------------------------- ### Ensure Handlers Called Once for Multiple Tools Source: https://codecompanion.olimorris.dev/extending/tools This example shows how to set `use_handlers_once = true` within a tool's `opts` table. This option prevents the `setup` and `on_exit` handler functions from being called more than once, even if the same tool is invoked multiple times in a single LLM response. ```lua return { name = "editor", opts = { use_handlers_once = true, }, -- More code follows... } ``` -------------------------------- ### Initialize CLI Instance with Options Source: https://codecompanion.olimorris.dev/usage/cli The `require('codecompanion').cli()` function can accept an options table to configure the new CLI instance, such as specifying the agent. ```lua require("codecompanion").cli({ agent = "claude_code" }) ``` -------------------------------- ### Initialize CLI Instance with No Arguments Source: https://codecompanion.olimorris.dev/usage/cli Calling `require('codecompanion').cli()` with no arguments creates a new CLI instance and opens it. ```lua require("codecompanion").cli() ``` -------------------------------- ### Configure Per-Project Directories Source: https://codecompanion.olimorris.dev/configuration/others Set up per-project configurations by defining paths to specific project directories and their associated configurations. This allows for tailored settings across different projects. ```lua require("codecompanion").setup({ opts = { per_project_config = { paths = { ["~/Code/Python/New-Startup"] = { interactions = { chat = { adapter = { name = "copilot", model = "claude-opus-4.6", }, }, }, }, }, }, }, }) ``` -------------------------------- ### MCP Server Configuration with Environment Variables Source: https://codecompanion.olimorris.dev/configuration/mcp Configure an MCP server with environment variables, demonstrating how to securely fetch API keys using external tools like 1Password CLI. ```lua require("codecompanion").setup({ mcp = { servers = { ["tavily-mcp"] = { cmd = { "npx", "-y", "tavily-mcp@latest" }, env = { TAVILY_API_KEY = "cmd:op read op://personal/Tavily_API/credential --no-newline", }, }, }, }, }) ``` -------------------------------- ### Configure Hybrid Tool with Client-Side Implementation Source: https://codecompanion.olimorris.dev/extending/tools This snippet illustrates how to define a hybrid tool, such as the 'memory' tool, which requires both an adapter and a client-side implementation. The `client_tool` option in the `opts` table specifies the path to the client-side component. ```lua ["memory"] = { -- ...existing code here opts = { -- Allow a hybrid tool -> One that also has a client side implementation client_tool = "interactions.chat.tools.memory", }, }, ``` -------------------------------- ### Configure Per-Project Files Source: https://codecompanion.olimorris.dev/configuration/others Enable per-project configurations by specifying a list of files to look for in the current working directory. These files will be loaded and merged with the default configuration. ```lua require("codecompanion").setup({ opts = { per_project_config = { files = { ".codecompanion", ".codecompanion.lua", }, }, }, }) ``` -------------------------------- ### Get Diagnostics for a File Source: https://codecompanion.olimorris.dev/usage/chat-buffer/agents-tools Use the get_diagnostics tool to check for issues in the current file. It can optionally filter diagnostics by severity level. ```markdown Use @{get_diagnostics} to check for any issues in the current file ``` -------------------------------- ### Creating a File Source: https://codecompanion.olimorris.dev/usage/chat-buffer/agents-tools Use the create_file tool to generate a new file in the current working directory. User approval can be optionally required before execution. ```markdown Can you create some test fixtures using @{create_file}? ``` -------------------------------- ### Basic MCP Server Configuration Source: https://codecompanion.olimorris.dev/configuration/mcp This snippet shows the most basic configuration for an MCP server, specifying the command to execute. ```lua require("codecompanion").setup({ mcp = { servers = { ["tavily-mcp"] = { cmd = { "npx", "-y", "tavily-mcp@latest" }, }, }, }, }) ``` -------------------------------- ### Configure the Default Terminal Provider Source: https://codecompanion.olimorris.dev/configuration/cli Set up the default terminal provider for CLI interactions, which uses Neovim's `jobstart()` function to run agents in a terminal buffer. This is the standard provider for CLI execution. ```lua require("codecompanion").setup({ interactions = { cli = { providers = { terminal = { path = "interactions.cli.providers.terminal", description = "Terminal CLI provider", }, }, }, }, }) ``` -------------------------------- ### Register Chat Callback in Prompt Library Source: https://codecompanion.olimorris.dev/configuration/chat-buffer Register a callback specifically for chats initiated from a particular prompt in the prompt library. This example uses 'on_before_submit'. ```lua require("codecompanion").setup({ prompt_library = { ["My Prompt"] = { opts = { callbacks = { on_before_submit = function(chat, info) -- Only applies to chats opened from this prompt end, }, }, }, }, }) ``` -------------------------------- ### Register Chat Callback for All Chats Source: https://codecompanion.olimorris.dev/configuration/chat-buffer Register a callback for the 'CodeCompanionChatCreated' event to hook into the chat buffer's lifecycle. This example adds an 'on_before_submit' callback. ```lua vim.api.nvim_create_autocmd("User", { pattern = "CodeCompanionChatCreated", callback = function(args) local chat = require("codecompanion").buf_get_chat(args.data.bufnr) chat:add_callback("on_before_submit", function(c, info) -- Access the adapter via info.adapter -- Access messages via c.messages end) end, }) ``` -------------------------------- ### Cancel Inline Request Keymap Source: https://codecompanion.olimorris.dev/configuration/inline Configure a keymap to cancel an ongoing inline request. This example uses 'q' in normal mode to stop the request. ```lua require("codecompanion").setup({ interactions = { inline = { keymaps = { stop = { modes = { n = "q" }, index = 4, callback = "keymaps.stop", description = "Stop request", }, }, }, }, }) ``` -------------------------------- ### Configure Tools System Prompt Source: https://codecompanion.olimorris.dev/configuration/system-prompt Set up a system prompt specifically for tool interactions. This prompt can be enabled and configured to either replace or supplement the main system prompt. ```lua require("codecompanion").setup({ interactions = { chat = { tools = { opts = { system_prompt = { enabled = true, -- Enable the tools system prompt? replace_main_system_prompt = false, -- Replace the main system prompt with the tools system prompt? --@param args { ctx: CodeCompanion.SystemPrompt.Context, tools: string[]} The tools available --@return string prompt = function(args) return "My custom tools prompt" end, }, }, }, }, }, }) ``` -------------------------------- ### Change Inline Adapter Source: https://codecompanion.olimorris.dev/configuration/inline Configure CodeCompanion to use a different HTTP adapter for inline interactions. This example sets the adapter to 'anthropic' with a specific model. ```lua require("codecompanion").setup({ interactions = { inline = { adapter = { name = "anthropic", model = "claude-haiku-4-5-20251001" }, }, }, }) ``` -------------------------------- ### OpenAI Chat Completions API Request Example Source: https://codecompanion.olimorris.dev/extending/adapters Demonstrates the structure of a cURL request to the OpenAI Chat Completions API, including authentication and message formatting. ```sh curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{ \ "model": "gpt-4-0125-preview", \ "messages": [ \ { \ "role": "user", \ "content": "Explain Ruby in two words" \ } \ ] \ }' ``` -------------------------------- ### Configure Diff Window Options Source: https://codecompanion.olimorris.dev/configuration/chat-buffer Sets up diff display in a floating window with custom width, height, and line numbering. Highlights additions and deletions. ```lua require("codecompanion").setup({ display = { diff = { enabled = true, window = { ---@return number|fun(): number width = function() return math.min(120, vim.o.columns - 10) end, ---@return number|fun(): number height = function() return vim.o.lines - 4 end, opts = { number = true, }, }, word_highlights = { additions = true, deletions = true, }, }, }, }) ``` -------------------------------- ### Override Tool with a Custom System Prompt Source: https://codecompanion.olimorris.dev/configuration/mcp Append custom instructions to the system prompt for a specific tool. This guides the AI's behavior when using that tool. ```lua require("codecompanion").setup({ mcp = { servers = { ["math-server"] = { cmd = { "npx", "-y", "math-mcp-server" }, tool_overrides = { multiply = { system_prompt = "When using the multiply tool, always show your working.", }, }, }, }, }, }) ``` -------------------------------- ### Basic Inline Prompt Source: https://codecompanion.olimorris.dev/usage/inline Run a basic inline prompt in Neovim. ```vim `:CodeCompanion ` ``` -------------------------------- ### Local Extension with Callback Function Source: https://codecompanion.olimorris.dev/extending/extensions Define a local extension directly in your configuration using a callback function. This example adds a message editor extension to chat keymaps. ```lua -- Example: Adding a message editor extension require("codecompanion").setup({ extensions = { editor = { enabled = true, opts = {}, callback = { setup = function(ext_config) -- Add a new action to chat keymaps local open_editor = { modes = { n = "ge", -- Keymap to open editor }, description = "Open Editor", callback = function(chat) -- Implementation of editor opening logic -- You have access to the chat buffer via the chat parameter vim.notify("Editor opened for chat " .. chat.id) end, } -- Add the action to chat keymaps config local chat_keymaps = require("codecompanion.config").interactions.chat.keymaps chat_keymaps.open_editor = open_editor end, -- Optional: Expose functions exports = { is_editor_open = function() return false -- Implementation end } } } } }) ``` -------------------------------- ### Specifying MCP Servers (Markdown) Source: https://codecompanion.olimorris.dev/configuration/prompt-library Configures a prompt to load specific MCP servers. This allows for custom server environments to be active when the prompt is used. ```markdown --- name: Prompt with MCP servers interaction: chat description: A prompt that starts MCP servers mcp_servers: - tavily-mcp - filesystem --- ``` -------------------------------- ### Open and Toggle Chat Buffer with Options Source: https://codecompanion.olimorris.dev/usage/chat-buffer Demonstrates how to open or toggle the chat buffer with custom window layout options. Use this to control the appearance of the chat window. ```lua require("codecompanion").chat({ window_opts = { layout = "float", width = 0.6 }}) -- or: require("codecompanion").toggle({ window_opts = { layout = "float", width = 0.6 }}) ``` -------------------------------- ### Add Custom Editor Context Source: https://codecompanion.olimorris.dev/configuration/inline Add a custom editor context item for use in inline prompts. This example defines 'my_new_context_item' with a callback to a local Lua file. ```lua require("codecompanion").setup({ interactions = { inline = { editor_context = { ["my_new_context_item"] = { --@return string callback = "/Users/Oli/Code/my_context_item.lua", description = "My shiny new context item", opts = { contains_code = true, }, }, } } } }) ``` -------------------------------- ### Send String Prompt with Options Source: https://codecompanion.olimorris.dev/usage/cli Combine a string prompt with an options table in `require('codecompanion').cli()` to send the prompt with specific configurations like submission and focus. ```lua require("codecompanion").cli("Fix #{diagnostics}", { submit = true, focus = false }) ``` -------------------------------- ### Configure GitHub Gist Token for /share Command Source: https://codecompanion.olimorris.dev/usage/chat-buffer/slash-commands Set the GITHUB_GIST_TOKEN environment variable to enable the /share command for creating GitHub Gists. This configuration is part of the codecompanion setup. ```lua require("codecompanion").setup({ interactions = { chat = { slash_commands = { ["share"] = { opts = { token = os.getenv("GITHUB_GIST_TOKEN"), }, }, }, }, }, }) ``` -------------------------------- ### Configure llama.cpp HTTP Adapter Source: https://codecompanion.olimorris.dev/configuration/adapters-http Set up the 'llama.cpp' HTTP adapter for CodeCompanion. Ensure your llama.cpp instance is running and accessible at the specified URL. This configuration includes a custom handler for parsing message metadata. ```lua require("codecompanion").setup({ adapters = { http = { ["llama.cpp"] = function() return require("codecompanion.adapters").extend("openai_compatible", { env = { url = "http://127.0.0.1:8080", -- replace with your llama.cpp instance api_key = "TERM", chat_url = "/v1/chat/completions", }, handlers = { parse_message_meta = function(self, data) local extra = data.extra if extra and extra.reasoning_content then data.output.reasoning = { content = extra.reasoning_content } if data.output.content == "" then data.output.content = nil end end return data end, }, }) end, }, }, interactions = { chat = { adapter = "llama.cpp", }, inline = { adapter = "llama.cpp", }, }, }) ``` -------------------------------- ### Markdown Prompt: Specify Adapter Source: https://codecompanion.olimorris.dev/configuration/prompt-library Demonstrates how to specify a custom adapter and model for a markdown prompt, useful for directing prompts to specific LLMs. ```markdown --- name: My Prompt interaction: chat description: Uses a specific model opts: adapter: name: ollama model: deepseek-coder:6.7b --- ``` -------------------------------- ### Getting Changed Files Source: https://codecompanion.olimorris.dev/usage/chat-buffer/agents-tools Retrieve git diffs for any file modifications in the current working directory using the get_changed_files tool. The output can include staged, unstaged, and merge-conflict information. ```markdown Use @{get_changed_files} see what's changed ``` -------------------------------- ### Set HTTP Adapter Environment Variable (Command) Source: https://codecompanion.olimorris.dev/configuration/adapters-http Configure an HTTP adapter to fetch an API key using a shell command. The command is executed at runtime to retrieve the secret. ```lua require("codecompanion").setup({ adapters = { http = { anthropic = function() return require("codecompanion.adapters").extend("anthropic", { env = { api_key = "cmd:op read op://personal/Anthropic/credential --no-newline", }, }) end, }, }, }) ``` -------------------------------- ### Conditionally Enable/Disable Adapter Schema Parameter Source: https://codecompanion.olimorris.dev/configuration/adapters-http Dynamically enable or disable schema parameters based on adapter properties, such as the selected model. This example disables 'top_p' if the model name contains 'codex'. ```lua require("codecompanion").setup({ adapters = { http = { openai_responses = function() return require("codecompanion.adapters").extend("openai_responses", { schema = { top_p = { ---@type fun(self: CodeCompanion.HTTPAdapter): boolean | boolean enabled = function(self) local model = self.schema.model.default if model:find("codex%") then return false end return true end }, }, }) end, }, }, }) ``` -------------------------------- ### Modify Adapter Schema Parameter (top_p) Source: https://codecompanion.olimorris.dev/configuration/adapters-http Customize adapter schema parameters like 'top_p' by extending the adapter configuration. This example sets the default value for 'top_p' to 0 for the 'openai_responses' adapter. ```lua require("codecompanion").setup({ adapters = { http = { openai_responses = function() return require("codecompanion.adapters").extend("openai_responses", { schema = { top_p = { default = 0 }, }, }) end, }, }, }) ``` -------------------------------- ### Using Built-in Helpers in Prompts Source: https://codecompanion.olimorris.dev/configuration/prompt-library Shows how to use built-in context variables like buffer number and file type within prompts. These helpers provide dynamic information about the current environment. ```lua -- ${context.bufnr} - Current buffer number -- ${context.filetype} - Current filetype -- ${context.start_line} - Visual selection start -- ${context.end_line} - Visual selection end ``` -------------------------------- ### Configure Editing and Compaction Triggers with Decimals Source: https://codecompanion.olimorris.dev/configuration/chat-buffer Set triggers for editing and compaction based on a percentage of the context window. Editing is set to 65% and compaction to 85%. ```lua require("codecompanion").setup({ interactions = { chat = { opts = { context_management = { editing = { trigger = 0.65, -- 65% of the context window }, compaction = { trigger = 0.85, -- 85% of the context window }, }, }, }, }, }) ``` -------------------------------- ### Configure Ollama HTTP Adapter Directly Source: https://codecompanion.olimorris.dev/configuration/adapters-http Configure the 'ollama' HTTP adapter directly within CodeCompanion's setup. This method allows for custom headers, including authentication via an API key. ```lua require("codecompanion").setup({ adapters = { http = { ollama = function() return require("codecompanion.adapters").extend("ollama", { env = { url = "https://my_ollama_url", api_key = "OLLAMA_API_KEY", }, headers = { ["Content-Type"] = "application/json", ["Authorization"] = "Bearer ${api_key}", }, parameters = { sync = true, }, }) end, }, }, }) ``` -------------------------------- ### Enable User Approval for a Tool Source: https://codecompanion.olimorris.dev/extending/tools Add `require_approval_before = true` to a tool's `opts` table to enable user approval before execution. ```lua require("codecompanion").setup({ interactions = { chat = { tools = { calculator = { description = "Perform calculations", path = "path.to.calculator", opts = { require_approval_before = true, }, } } } } }) ``` -------------------------------- ### Loading Context from Files (Markdown) Source: https://codecompanion.olimorris.dev/configuration/prompt-library Configures a prompt to load context from specified files using Markdown format. This pre-loads chat buffers with relevant code or information. ```markdown --- name: Test Context interaction: chat description: Add some context context: - type: file path: - lua/codecompanion/health.lua - lua/codecompanion/http.lua - type: symbols path: lua/codecompanion/interactions/chat/init.lua - type: url url: https://raw.githubusercontent.com/olimorris/codecompanion.nvim/refs/heads/main/lua/codecompanion/commands.lua --- ## user I'll think of something clever to put here... ``` -------------------------------- ### Truncate Tool Output with on_tool_output Source: https://codecompanion.olimorris.dev/configuration/chat-buffer The `on_tool_output` callback allows modification of tool output before it's added to the chat. Mutate `args.for_llm` and `args.for_user` to change the output. This example truncates output exceeding a token limit. ```lua vim.api.nvim_create_autocmd("User", { pattern = "CodeCompanionChatCreated", callback = function(args) local chat = require("codecompanion").buf_get_chat(args.data.bufnr) chat:add_callback("on_tool_output", function(c, data) local tokens = require("codecompanion.utils.tokens") local max_tokens = 10000 if data.for_llm and tokens.calculate(data.for_llm) > max_tokens then -- Trim to roughly max_tokens worth of characters local max_chars = max_tokens * 6 data.for_llm = data.for_llm:sub(1, max_chars) .. "\n\n[Output truncated]" data.for_user = data.for_llm vim.notify( string.format("Tool output from '%s' truncated (~%d tokens)", data.tool, max_tokens), vim.log.levels.WARN ) end end) end, }) ```