### Custom System Prompt Example Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md An example of how to define a custom system prompt string in the generation options for summarization. ```lua generation_opts = { system_prompt = [[You are a technical summary specialist. Summarize focusing on: 1. What was accomplished 2. Key technical decisions 3. Code changes made Be concise and structured.]], } ``` -------------------------------- ### Install VectorCode CLI Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Follow the official installation guide for VectorCode CLI. Ensure it is added to your system's PATH. ```bash # See https://github.com/Davidyz/VectorCode/blob/main/docs/cli.md#installation ``` -------------------------------- ### Install codecompanion.nvim with history extension Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/doc/codecompanion-history.txt Install the codecompanion.nvim plugin and its history extension using lazy.nvim. Ensure the history extension is listed under dependencies. ```lua { "olimorris/codecompanion.nvim", dependencies = { --other plugins "ravitemer/codecompanion-history.nvim" } } ``` -------------------------------- ### Setup CodeCompanion History Extension Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md Include the history extension in your CodeCompanion setup by enabling it and providing an options table. ```lua require("codecompanion").setup({ extensions = { history = { enabled = true, opts = { -- configuration goes here } } } }) ``` -------------------------------- ### Generate Summary Example Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/README.md Illustrates how to generate a summary for the current chat. ```APIDOC ## Generate Summary ```lua local history = require("codecompanion").extensions.history local chat = require("codecompanion").last_chat() if chat then history.generate_summary(chat) end ``` ``` -------------------------------- ### @memory Tool Output Example Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Example of the output returned by the @memory tool, containing a status and a list of matching memories with their filename, content, and similarity score. ```json { "status": "success", "data": [ { "filename": "1672531200.md", "content": "# Summary\n\n...", "similarity": 0.85 }, -- ... more results ] } ``` -------------------------------- ### Example Usage of History Extension API Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/doc/codecompanion-history.txt Demonstrates how to use the history extension's API for browsing chats with a project filter, getting chat metadata, loading, deleting, and duplicating chats. Also shows summary operations. ```lua local history = require("codecompanion").extensions.history -- Browse chats with project filter history.browse_chats(function(chat_data) return chat_data.project_root == utils.find_project_root() end) -- Get all saved chats metadata local chats = history.get_chats() local chat_data = history.load_chat("some_save_id") history.delete_chat("some_save_id") -- Duplicate a chat with custom title local new_save_id = history.duplicate_chat("some_save_id", "My Custom Copy") -- Duplicate a chat with auto-generated title (appends "(1)") local new_save_id = history.duplicate_chat("some_save_id") -- Summary operations history.generate_summary() -- generates for current chat local summaries = history.get_summaries() local summary_content = history.load_summary("some_save_id") history.preview_summary() -- opens summary for editing ``` -------------------------------- ### Example: Refresh Title Every 3 User Prompts Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md This example demonstrates how to configure title generation to refresh every 3 user prompts and includes a custom function to format the generated title by removing markdown. ```lua title_generation_opts = { adapter = "openai", model = "gpt-4o-mini", refresh_every_n_prompts = 3, -- Refresh after 3rd, 6th, 9th message etc. max_refreshes = 10, format_title = function(title) -- Remove markdown formatting if needed return title:gsub("%*%*", "") end } ``` -------------------------------- ### Check VectorCode Installation Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Verify if the VectorCode executable is installed and accessible in the system's PATH. This function returns a boolean indicating availability. ```lua function has_vectorcode(): boolean end ``` ```lua local vectorcode = require("codecompanion._extensions.history.vectorcode") if vectorcode.has_vectorcode() then print("VectorCode is installed") else print("VectorCode not found") end ``` -------------------------------- ### Complete CodeCompanion History Configuration Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md This example shows all available options for configuring the history extension, including file storage, chat expiration, auto-save behavior, keymaps, picker settings, title generation, summary system, memory system, chat filtering, and logging. It demonstrates how to customize various aspects of the history functionality. ```lua require("codecompanion").setup({ extensions = { history = { enabled = true, opts = { -- File storage dir_to_save = vim.fn.stdpath("data") .. "/codecompanion-history", -- Chat expiration expiration_days = 30, -- Delete chats older than 30 days -- Auto-save behavior auto_save = true, continue_last_chat = false, delete_on_clearing_chat = false, -- Keymaps keymap = "gh", save_chat_keymap = "sc", -- Picker picker = "telescope", -- auto-resolved if not specified picker_keymaps = { rename = { n = "r", i = "" }, delete = { n = "d", i = "" }, duplicate = { n = "", i = "" }, }, -- Title generation auto_generate_title = true, title_generation_opts = { adapter = "openai", model = "gpt-4o-mini", refresh_every_n_prompts = 3, max_refreshes = 10, format_title = function(title) return title end }, -- Summary system summary = { create_summary_keymap = "gcs", browse_summaries_keymap = "gbs", generation_opts = { adapter = "openai", model = "gpt-4o-mini", context_size = 90000, include_references = true, include_tool_outputs = true, } }, -- Memory system (requires VectorCode) memory = { auto_create_memories_on_summary_generation = true, vectorcode_exe = "vectorcode", tool_opts = { default_num = 10 }, notify = true, index_on_startup = false, }, -- Chat filtering chat_filter = function(chat_data) -- Show all chats return true end, -- Logging enable_logging = false, } } } }) ``` -------------------------------- ### Minimum CodeCompanion History Configuration Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/README.md Shows the essential configuration required to enable the history extension. Ensure this is included in your Neovim setup. ```lua require("codecompanion").setup({ extensions = { history = { enabled = true, } } }) ``` -------------------------------- ### Example: Show Only Specific Adapter Chats Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md Filter chats to display only those that used a specific adapter, such as 'openai'. ```lua chat_filter = function(chat_data) return chat_data.adapter == "openai" end ``` -------------------------------- ### Browse Chats Example Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/README.md Shows how to browse all saved chats or filter them based on a custom function. ```APIDOC ## Browse Chats ```lua local history = require("codecompanion").extensions.history -- Browse all history.browse_chats() -- Browse with filter history.browse_chats(function(chat_data) return chat_data.project_root == vim.fn.getcwd() end) ``` ``` -------------------------------- ### @memory Tool Invocation Example Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Example of how an LLM invokes the @memory tool with search keywords and an optional count. The tool searches indexed summaries for relevant conversations. ```json { "name": "memory", "arguments": { "keywords": ["feature", "database", "optimization"], "count": 5 } } ``` -------------------------------- ### Save a Chat Example Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/README.md Demonstrates how to save the last chat using the `save_chat` function. ```APIDOC ## Save a Chat ```lua local history = require("codecompanion").extensions.history local chat = require("codecompanion").last_chat() if chat then history.save_chat(chat) end ``` ``` -------------------------------- ### Error Cases for Memory Tool Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Illustrates potential error responses from the Memory tool, such as missing keywords, VectorCode not being installed, or no indexed summaries. ```lua -- No keywords provided { status = "error", data = "You must provide a non-empty list of keywords..." } -- VectorCode not found { status = "error", data = "VectorCode is not installed..." } -- No summaries indexed { status = "success", data = {} -- Empty results } ``` -------------------------------- ### History.new Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/History.md Creates a new History extension instance with specified configuration options. It handles the setup of storage, title generation, UI integration, Neovim autocommands, and keymaps. ```APIDOC ## History.new ### Description Creates a new History extension instance. ### Method `History.new(opts: CodeCompanion.History.Opts): CodeCompanion.History` ### Parameters #### Path Parameters - **opts** (CodeCompanion.History.Opts) - Required - Configuration options for the extension ### Response #### Success Response (200) - **CodeCompanion.History** - Initialized history extension instance ### Request Example ```lua local opts = { dir_to_save = vim.fn.stdpath("data") .. "/codecompanion-history", auto_save = true, auto_generate_title = true, } local history = require("codecompanion._extensions.history").History.new(opts) ``` ``` -------------------------------- ### Example: Show Only Current Project Chats Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md Filter chats to display only those associated with the current project's root directory. ```lua chat_filter = function(chat_data) return chat_data.project_root == vim.fn.getcwd() end ``` -------------------------------- ### Get System Prompt for Summarization Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Retrieves the system prompt for the summarizer. This can be a custom function or string from configuration, or a built-in comprehensive prompt. ```lua function SummaryGenerator:_get_system_prompt(): string ``` -------------------------------- ### Configure codecompanion-history.nvim extension Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/doc/codecompanion-history.txt Enable the history extension and configure its options within the main codecompanion setup. Key options include keymaps, auto-save, expiration, picker interface, and title generation. ```lua require("codecompanion").setup({ extensions = { history = { enabled = true, opts = { -- Keymap to open history from chat buffer (default: gh) keymap = "gh", -- Keymap to save the current chat manually (when auto_save is disabled) save_chat_keymap = "sc", -- Save all chats by default (disable to save only manually using 'sc') auto_save = true, -- Number of days after which chats are automatically deleted (0 to disable) expiration_days = 0, -- Picker interface (auto resolved to a valid picker) picker = "telescope", --- ("telescope", "snacks", "fzf-lua", or "default") ---Optional filter function to control which chats are shown when browsing chat_filter = nil, -- function(chat_data) return boolean end -- Customize picker keymaps (optional) picker_keymaps = { rename = { n = "r", i = "" }, delete = { n = "d", i = "" }, duplicate = { n = "", i = "" }, }, ---Automatically generate titles for new chats auto_generate_title = true, title_generation_opts = { ---Adapter for generating titles (defaults to current chat adapter) adapter = nil, -- "copilot" ---Model for generating titles (defaults to current chat model) model = nil, -- "gpt-4o" ---Number of user prompts after which to refresh the title (0 to disable) refresh_every_n_prompts = 0, -- e.g., 3 to refresh after every 3rd user prompt ---Maximum number of times to refresh the title (default: 3) max_refreshes = 3, format_title = function(original_title) -- this can be a custom function that applies some custom -- formatting to the title. return original_title end }, continue_last_chat = false, delete_on_clearing_chat = false, dir_to_save = vim.fn.stdpath("data") .. "/codecompanion-history", enable_logging = false, -- Summary system summary = { -- Keymap to generate summary for current chat (default: "gcs") create_summary_keymap = "gcs", -- Keymap to browse summaries (default: "gbs") browse_summaries_keymap = "gbs", generation_opts = { adapter = nil, -- defaults to current chat adapter ``` -------------------------------- ### _get_system_prompt Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Retrieves the system prompt used for guiding the summarization process. The prompt can be custom or use a built-in default. ```APIDOC ## _get_system_prompt ### Description Retrieves the system prompt used for guiding the summarization process. The prompt can be custom or use a built-in default. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```lua function SummaryGenerator:_get_system_prompt(): string ``` ### Returns `string` — System prompt for the summarizer ### Notes - The default prompt instructs the summarizer to capture key technical concepts, decisions, solutions, include specific library/function names, focus on reusable knowledge, maintain consistent structure, and be concise. - Output format includes Title, Overview, Key Achievements, Technical Patterns, Important Decisions, and Code Context. - Custom prompts can be provided via configuration. ``` -------------------------------- ### CodeCompanion History API Usage Examples Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/README.md Demonstrates how to use the CodeCompanion History extension API for browsing, loading, deleting, and duplicating chats, as well as managing summaries. ```lua local history = require("codecompanion").extensions.history -- Browse chats with project filter history.browse_chats(function(chat_data) return chat_data.project_root == utils.find_project_root() end) -- Get all saved chats metadata local chats = history.get_chats() local chat_data = history.load_chat("some_save_id") history.delete_chat("some_save_id") -- Duplicate a chat with custom title local new_save_id = history.duplicate_chat("some_save_id", "My Custom Copy") -- Duplicate a chat with auto-generated title (appends "(1)") local new_save_id = history.duplicate_chat("some_save_id") -- Summary operations history.generate_summary() -- generates for current chat local summaries = history.get_summaries() local summary_content = history.load_summary("some_save_id") ``` -------------------------------- ### has_vectorcode() Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Checks if the VectorCode CLI is installed and available in the system's PATH. This is a prerequisite for using the memory system's indexing and search functionalities. ```APIDOC ## has_vectorcode() ### Description Check if VectorCode is installed and available. ### Returns - `boolean` — true if VectorCode executable is found ### Example ```lua local vectorcode = require("codecompanion._extensions.history.vectorcode") if vectorcode.has_vectorcode() then print("VectorCode is installed") else print("VectorCode not found") end ``` ``` -------------------------------- ### Error Handling with Callbacks Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/README.md Provides an example of how to handle errors returned via callback functions. The callback receives a result and an error argument; check for the error before using the result. ```lua function(result, error) if error then vim.notify("Error: " .. error, vim.log.levels.ERROR) return end -- use result end ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/CONTRIBUTING.md Clone the repository and navigate into the project directory to begin development. ```bash git clone https://github.com/ravitemer/codecompanion-history.nvim cd codecompanion-history.nvim ``` -------------------------------- ### Generate Plugin Documentation Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/CONTRIBUTING.md Run the 'make docs' command to generate the plugin's documentation using panvimdoc. ```bash make docs # Generate plugin documentation ``` -------------------------------- ### Initialize History Extension Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/History.md Creates a new History extension instance with specified options. Ensure the directory for saving history is valid to avoid errors. ```lua local opts = { dir_to_save = vim.fn.stdpath("data") .. "/codecompanion-history", auto_save = true, auto_generate_title = true, } local history = require("codecompanion._extensions.history").History.new(opts) ``` -------------------------------- ### UI.new Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/UI.md Creates a new UI instance, initializing the UI layer with provided options, storage, and title generator. ```APIDOC ## UI.new ### Description Creates a new UI instance. ### Parameters - **opts** (CodeCompanion.History.Opts) - Yes - Configuration options - **storage** (CodeCompanion.History.Storage) - Yes - Storage instance for data access - **title_generator** (CodeCompanion.History.TitleGenerator) - Yes - Title generator instance ### Returns - **CodeCompanion.History.UI** — Initialized UI instance ### Example ```lua local storage = Storage.new(opts) local title_gen = TitleGenerator.new(opts) local ui = UI.new(opts, storage, title_gen) ``` ``` -------------------------------- ### Create New UI Instance Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/UI.md Initializes the UI layer by storing references, resolving the picker interface, and setting up keymaps. Requires configuration options, a storage instance, and a title generator. ```lua local storage = Storage.new(opts) local title_gen = TitleGenerator.new(opts) local ui = UI.new(opts, storage, title_gen) ``` -------------------------------- ### Run All Tests Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/CONTRIBUTING.md Execute all tests for the extension using the 'make test' command. ```bash make test # Run all tests ``` -------------------------------- ### Configure Memory Options Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Set up memory system configurations, including automatic indexing, VectorCode executable path, and default search result count. ```lua memory = { auto_create_memories_on_summary_generation = true, vectorcode_exe = "vectorcode", tool_opts = { default_num = 10 -- Default number of results }, notify = true, index_on_startup = false, } ``` -------------------------------- ### Configure Memory System (VectorCode) Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md Set up the memory system using VectorCode, enabling automatic memory creation on summary generation and specifying the path to the VectorCode executable. ```lua memory = { auto_create_memories_on_summary_generation = true, vectorcode_exe = "vectorcode", tool_opts = { default_num = 10 -- default number of memories to retrieve }, notify = true, -- show notifications for indexing index_on_startup = false, -- index all memories when plugin loads } ``` -------------------------------- ### Example: Show Only Recent Chats Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md Filter chats to display only those updated within the last seven days. ```lua chat_filter = function(chat_data) local seven_days_ago = os.time() - (7 * 24 * 60 * 60) return chat_data.updated_at >= seven_days_ago end ``` -------------------------------- ### Create Summary Object Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Packages summary content with metadata for storage. Use this to create a complete summary object including IDs, timestamps, and project root. ```lua function SummaryGenerator:_create_summary_object(chat: CodeCompanion.History.Chat, project_root: string, summary_content: string): SummaryData end ``` -------------------------------- ### Initialize SummaryGenerator Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Creates a new SummaryGenerator instance with specified options. Merges user options with default settings for context size, reference inclusion, and tool output inclusion. ```lua local opts = { summary = { generation_opts = { adapter = "openai", model = "gpt-4o-mini", context_size = 90000, include_references = true, include_tool_outputs = true, } } } local summary_gen = SummaryGenerator.new(opts) ``` -------------------------------- ### Get Chats Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/History.md Loads the chat index and returns metadata for all chats. Useful for filtering and custom UI. ```lua local history = require("codecompanion").extensions.history -- Get all chats local all_chats = history.get_chats() for save_id, chat_data in pairs(all_chats) do print(chat_data.title .. " (" .. chat_data.message_count .. " messages)") end -- Get chats from specific adapter local chats = history.get_chats(function(chat_data) return chat_data.adapter == "openai" end) ``` -------------------------------- ### Ensure Storage Directories Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Storage.md Creates the necessary directory structure and index files for storage if they do not already exist. ```lua function Storage:_ensure_storage_dirs(): nil ``` -------------------------------- ### Open Summaries Picker Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/UI.md Opens the summary picker to browse, preview, select, or delete generated summaries. Requires an initialized UI instance. ```lua local ui = UI.new(opts, storage, title_gen) ui:open_summaries() ``` -------------------------------- ### History Extension Interface Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/History.md The structure for the History module when exported as a CodeCompanion Extension. Includes setup and exports for the public API. ```lua { setup = function(opts: CodeCompanion.History.Opts) -- Called by CodeCompanion to initialize the extension end, exports = { -- Public API functions documented above }, History = History -- For testing purposes } ``` -------------------------------- ### find_project_root Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Utils.md Auto-detects the project root directory by searching for common project markers. It can optionally start searching from a specified path. ```APIDOC ## find_project_root(start_path) ### Description Auto-detect the project root directory. Looks for common project markers (git, package.json, etc.) and returns the root. Used for project-aware features. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **start_path** (string) - Optional - Starting directory. Defaults to current working directory. ### Request Example ```lua local root = utils.find_project_root("/home/user/project/src") print(root) -- "/home/user/project" ``` ### Response #### Success Response (200) - **Return Value** (string) - Project root path or start_path if no markers found #### Response Example ```json { "example": "/home/user/project" } ``` ``` -------------------------------- ### Configure Summary System Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md Configure the summary generation and browsing features, including keymaps for generating and browsing summaries, and generation options. ```lua summary = { create_summary_keymap = "gcs", -- Keymap to generate summary browse_summaries_keymap = "gbs",-- Keymap to browse summaries generation_opts = { adapter = nil, -- defaults to current chat adapter model = nil, -- defaults to current chat model context_size = 90000, -- max tokens for context window include_references = true, -- include slash command content include_tool_outputs = true,-- include tool execution results system_prompt = nil, -- custom system prompt (string or function) format_summary = nil, -- custom formatting function } } ``` -------------------------------- ### Storage.new Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Storage.md Creates a new Storage instance, initializing the storage layer and performing cleanup of expired chats. ```APIDOC ## Storage.new(opts) ### Description Creates a new Storage instance. ### Method `Storage.new` ### Parameters #### Path Parameters - **opts** (CodeCompanion.History.Opts) - Required - Configuration options including `dir_to_save` and `expiration_days` ### Returns `CodeCompanion.History.Storage` - Initialized storage instance ### Description Initializes the storage layer by: 1. Creating base directory structure if needed 2. Initializing index.json and summaries_index.json 3. Running cleanup of expired chats based on `expiration_days` setting 4. Setting up internal state for caching ### Side Effects: - Creates directories: `base_path`, `base_path/chats`, `base_path/summaries` - Creates index files: `index.json`, `summaries_index.json` - Deletes chats older than `expiration_days` (if > 0) ### Example: ```lua local opts = { dir_to_save = vim.fn.stdpath("data") .. "/codecompanion-history", expiration_days = 30, } local storage = require("codecompanion._extensions.history.storage").new(opts) ``` ``` -------------------------------- ### Get Chat Storage Location Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/History.md Retrieves the base directory path where chat conversations are stored. Returns nil if the extension has not been initialized. ```lua local storage_path = require("codecompanion").extensions.history.get_location() print("Chats stored at: " .. (storage_path or "not initialized")) ``` -------------------------------- ### _make_adapter_request Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Makes the actual LLM request for summarization using the provided system and user prompts. ```APIDOC ## _make_adapter_request ### Description Makes the actual LLM request for summarization using the provided system and user prompts. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```lua function SummaryGenerator:_make_adapter_request(chat: CodeCompanion.History.Chat, system_prompt: string, user_prompt: string, callback: function): nil ``` ### Parameters Details - **chat** (CodeCompanion.History.Chat) - Required - Chat for adapter info - **system_prompt** (string) - Required - System prompt for the LLM - **user_prompt** (string) - Required - User prompt with messages - **callback** (function) - Required - Callback with (content, error) ### Returns `nil` ### Notes - Uses custom adapter/model if configured, else current chat's. - Disables streaming for clean response parsing. - Calls adapter with system + user prompts. - Parses response and returns content or error via callback. - Requires an HTTP-based adapter (HTTPAdapter). - ACP adapters are not supported. - Must support role mapping. - Logs all errors and passes detailed error messages to the callback. ``` -------------------------------- ### Memory Configuration with Index on Startup Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Configures the memory system to automatically index all summaries on Neovim startup. It's recommended to disable this after the first run. ```lua memory = { auto_create_memories_on_summary_generation = true, vectorcode_exe = "vectorcode", tool_opts = { default_num = 10 }, notify = true, index_on_startup = true, -- Index all on startup } -- Then disable after first run to avoid re-indexing ``` -------------------------------- ### Create User Prompt for Summarization Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Constructs the user prompt for the LLM, including either the previous summary and additional messages for updates, or just the initial messages for a new summary. ```lua function SummaryGenerator:_create_user_prompt(messages: string[], chat: CodeCompanion.History.Chat, previous_summary: string|nil): string ``` -------------------------------- ### Initialize Storage Instance Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Storage.md Creates a new Storage instance with specified options for saving directory and expiration days. This initializes the storage layer, including directory structure, index files, and cleanup of expired chats. ```lua local opts = { dir_to_save = vim.fn.stdpath("data") .. "/codecompanion-history", expiration_days = 30, } local storage = require("codecompanion._extensions.history.storage").new(opts) ``` -------------------------------- ### Get Storage Location Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Storage.md Retrieves the absolute path to the base directory where chat data is stored. Useful for debugging or external access to storage files. ```lua local storage = Storage.new(opts) local path = storage:get_location() print("Storage at: " .. path) -- ~/.local/share/nvim/codecompanion-history ``` -------------------------------- ### Add Development Runtime Path Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/CONTRIBUTING.md Prepend the extension's directory to Neovim's runtime path for development. ```lua vim.opt.runtimepath:prepend(os.getenv("HOME") .. "path/to/codecompanion-history.nvim") ``` -------------------------------- ### Get Summaries Metadata Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/History.md Retrieves metadata for all generated summaries. Use this to list available summaries and their generation times without loading their full content. ```lua local history = require("codecompanion").extensions.history local summaries = history.get_summaries() for summary_id, summary_data in pairs(summaries) do print(summary_data.chat_title .. " (generated: " .. os.date("%c", summary_data.generated_at) .. ")") end ``` -------------------------------- ### Custom Summary Prompt and Formatting Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/configuration.md Configure custom system prompts for summarization and define a function to format the generated summary, such as removing unwanted tags. ```lua generation_opts = { system_prompt = [[You are a technical summarizer. Summarize the following conversation focusing on: 1. What was accomplished 2. Key technical decisions 3. Code changes made Provide a concise, structured summary.]], format_summary = function(summary) -- Remove OpenAI thinking tags return summary:gsub(".-", "") end } ``` -------------------------------- ### Initial Generation Prompt Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/TitleGenerator.md The prompt used for the initial generation of a chat title. It specifies a maximum of 5 words and no special characters, providing examples for clarity. ```text Generate a very short and concise title (max 5 words) for this chat based on the following conversation: Do not include any special characters or quotes. Your response shouldn't contain any other text, just the title. === Examples: 1. User: What is the capital of France? Title: Capital of France 2. User: How do I create a new file in Vim? Title: Vim File Creation === Conversation: {conversation_context} Title: ``` -------------------------------- ### Basic Memory Configuration Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md A minimal Lua configuration for the memory system, enabling automatic memory creation on summary generation and setting a default number of results. ```lua memory = { auto_create_memories_on_summary_generation = true, vectorcode_exe = "vectorcode", tool_opts = { default_num = 10 }, notify = true, index_on_startup = false, } ``` -------------------------------- ### Lua Type Checking Example Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Utils.md Demonstrates basic input validation in Lua using the `type()` function to ensure variables have the expected data type before proceeding with operations. ```lua -- Input validation if type(timestamp) ~= "number" then error("Invalid timestamp: expected a number") end ``` -------------------------------- ### SummaryGenerator.new Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Creates a new SummaryGenerator instance with specified options. It merges user-provided configuration with default settings for context size, reference inclusion, and tool output inclusion. ```APIDOC ## SummaryGenerator.new(opts) ### Description Creates a new SummaryGenerator instance, initializing it with provided options and merging them with default configuration values. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **opts** (CodeCompanion.History.Opts) - Required - Configuration including summary.generation_opts. ### Request Example ```lua local opts = { summary = { generation_opts = { adapter = "openai", model = "gpt-4o-mini", context_size = 90000, include_references = true, include_tool_outputs = true, } } } local summary_gen = SummaryGenerator.new(opts) ``` ### Response #### Success Response - **CodeCompanion.History.SummaryGenerator** - Initialized generator instance. #### Response Example (Instance of SummaryGenerator) ``` -------------------------------- ### Chat Management Functions Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/doc/codecompanion-history.txt Provides functions to interact with the chat history, such as retrieving storage location, saving, browsing, getting metadata, loading, deleting, and duplicating chats. ```APIDOC ## Chat Management Functions ### Description Functions for managing chat history, including saving, browsing, loading, deleting, and duplicating chats. ### Functions - **get_location()**: `string?` - Get the storage location for chats. - **save_chat(chat?: CodeCompanion.Chat)**: Saves the current or provided chat to storage. - **browse_chats(filter_fn?: function(ChatIndexData): boolean)**: Browses chats using a custom filter function. - **get_chats(filter_fn?: function(ChatIndexData): boolean)**: Returns metadata for all saved chats, with optional filtering. - **load_chat(save_id: string)**: `ChatData?` - Loads a specific chat by its save_id. - **delete_chat(save_id: string)**: `boolean` - Deletes a chat by its save_id. - **duplicate_chat(save_id: string, new_title?: string)**: `string?` - Duplicates a chat by its save_id, optionally with a new title. ``` -------------------------------- ### _make_adapter_request Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/TitleGenerator.md Makes the actual LLM request for title generation. This is an internal method that resolves the adapter, gets settings, disables streaming, sends the request, and parses the response. ```APIDOC ## _make_adapter_request(chat, prompt, callback) ### Description Internal method that makes the actual LLM request for title generation. It resolves the LLM adapter, gets adapter default settings, disables streaming, sends the request, and parses the response, then calls the provided callback. ### Method Internal Lua function ### Parameters #### Path Parameters - **chat** (CodeCompanion.History.Chat) - Required - Chat object for adapter info - **prompt** (string) - Required - The prompt to send to the LLM - **callback** (function) - Required - Callback function that receives (title, error) ### Returns `nil` ### Example ```lua local prompt = "Generate a title for this chat" title_gen:_make_adapter_request(chat, prompt, function(title, error) if error then print(error) end end) ``` ``` -------------------------------- ### SummaryOpts Type for Summary System Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/types.md Configuration options for the summary system within Code Companion history. It defines keymaps for generating and browsing summaries, and allows for specific generation settings. ```lua type CodeCompanion.History.SummaryOpts = { create_summary_keymap?: string | table, -- Keymap for generation (default: "gcs") browse_summaries_keymap?: string | table, -- Keymap for browsing (default: "gbs") generation_opts?: SummaryGenerationOpts, -- Generation settings } ``` -------------------------------- ### Get All Summaries Metadata Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Storage.md Reads and returns metadata for all stored summaries from the summaries index. The results are cached for performance. The return type is a dictionary mapping summary IDs to their metadata. ```lua function Storage:get_summaries(): table ``` ```lua local summaries = storage:get_summaries() for id, summary_data in pairs(summaries) do print(summary_data.chat_title) end ``` -------------------------------- ### Memory Configuration with Custom VectorCode Path Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Sets up the memory system to use a specific, custom path for the VectorCode executable. ```lua memory = { auto_create_memories_on_summary_generation = true, vectorcode_exe = "/usr/local/bin/vectorcode", -- Full path tool_opts = { default_num = 15 }, notify = true, index_on_startup = false, } ``` -------------------------------- ### Generate Chat Summary Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/History.md Initiates an asynchronous summary generation for a chat conversation. Displays loading indicators and notifies the user upon completion. Optionally indexes the summary with VectorCode if installed. ```lua local codecompanion = require("codecompanion") local chat = codecompanion.last_chat() if chat then local history = require("codecompanion").extensions.history history.generate_summary(chat) end ``` -------------------------------- ### Run Specific Test File Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/CONTRIBUTING.md Run tests from a specific file by providing the file path to the 'make test_file' command. ```bash make test_file FILE=path/to/test_file.lua # Run specific test file ``` -------------------------------- ### Get Last Chat Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Storage.md Retrieves the most recently updated chat data. An optional filter function can be provided to narrow down the results. Returns the full chat data or nil if no chats are found. ```lua function Storage:get_last_chat(filter_fn?: function(chat_data: ChatIndexData): boolean): ChatData|nil ``` ```lua -- Get most recent chat overall local recent = storage:get_last_chat() -- Get most recent chat from current project local recent = storage:get_last_chat(function(chat_data) return chat_data.project_root == vim.fn.getcwd() end) ``` -------------------------------- ### Memory System Configuration Options Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/types.md Specifies the configuration for the memory system, which requires the VectorCode CLI. It includes settings for automatic memory creation, the path to the VectorCode executable, tool options, notification preferences, and startup indexing. ```lua type CodeCompanion.History.MemoryOpts = { auto_create_memories_on_summary_generation: boolean, vectorcode_exe: string, tool_opts: MemoryTool.Opts, notify: boolean, index_on_startup: boolean, } ``` -------------------------------- ### Available Picker Implementations Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/types.md A literal union type representing the different picker implementations supported by the history extension. The extension automatically resolves the best available picker based on installed plugins. ```lua type CodeCompanion.History.Pickers = "telescope" | "snacks" | "fzf-lua" | "default" ``` -------------------------------- ### _create_user_prompt Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Constructs the user prompt for the LLM, including previous summaries and conversation messages. ```APIDOC ## _create_user_prompt ### Description Constructs the user prompt for the LLM, including previous summaries and conversation messages. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```lua function SummaryGenerator:_create_user_prompt(messages: string[], chat: CodeCompanion.History.Chat, previous_summary: string|nil): string ``` ### Parameters Details - **messages** (string[]) - Required - Formatted messages to summarize - **chat** (CodeCompanion.History.Chat) - Required - Chat object (for context) - **previous_summary** (string | nil) - Optional - Summary from previous chunk ### Returns `string` — Formatted prompt for the LLM ### Notes - For initial summarization, the format is: ``` CONVERSATION: {formatted_messages} Please generate a structured summary of this technical conversation. ``` - For chunk updates, the format is: ``` PREVIOUS SUMMARY: {previous_summary} ADDITIONAL CONVERSATION: {formatted_messages} Please update and extend the previous summary with the additional conversation content above. ``` ``` -------------------------------- ### Configurable Chat Filtering Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/doc/codecompanion-history.txt Define custom functions to filter chat history. The first example filters by the current working directory, and the second filters for chats updated within the last 7 days. ```lua chat_filter = function(chat_data) return chat_data.cwd == vim.fn.getcwd() end ``` ```lua -- Recent chats only (last 7 days) chat_filter = function(chat_data) local seven_days_ago = os.time() - (7 * 24 * 60 * 60) return chat_data.updated_at >= seven_days_ago end ``` -------------------------------- ### Get Editor Information Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Utils.md Retrieves comprehensive information about the current editor state, including open buffers, the last active buffer, cursor positions, and file modification status. Useful for context-aware operations. ```lua function get_editor_info(): CodeCompanion.History.EditorInfo end ``` ```lua { last_active = BufferInfo | nil, -- Most recently used buffer buffers = BufferInfo[] -- All open file buffers } ``` ```lua local editor_info = utils.get_editor_info() print("Last active: " .. (editor_info.last_active and editor_info.last_active.name or "none")) for _, buf in ipairs(editor_info.buffers) do if buf.is_modified then print("Modified: " .. buf.name) end end ``` -------------------------------- ### Initial Summarization Prompt Format Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md The format used for the initial summarization prompt when no previous summary exists. ```text CONVERSATION: {formatted_messages} Please generate a structured summary of this technical conversation. ``` -------------------------------- ### Make Adapter Request for Title Generation Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/TitleGenerator.md Internal method to make the actual LLM request for title generation. It resolves the adapter, gets default settings, disables streaming, sends the request, and parses the response. ```lua function TitleGenerator:_make_adapter_request(chat: CodeCompanion.History.Chat, prompt: string, callback: function): nil end ``` ```lua local prompt = "Generate a title for this chat" title_gen:_make_adapter_request(chat, prompt, function(title, error) if error then print(error) end end) ``` -------------------------------- ### Format Code with Stylua Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/CONTRIBUTING.md Format the codebase using Stylua by running the 'make format' command. This should be done before submitting pull requests. ```bash make format ``` -------------------------------- ### Summary Generation Options Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/types.md Defines the configuration options for the summary generation algorithm, including adapter, model, context size, and inclusion of references or tool outputs. Custom system prompts and summary formatting functions can also be provided. ```lua type CodeCompanion.History.SummaryGenerationOpts = { adapter?: string, model?: string, context_size?: number, include_references?: boolean, include_tool_outputs?: boolean, system_prompt?: string | function, format_summary?: function, } ``` -------------------------------- ### Make LLM Adapter Request Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/SummaryGenerator.md Makes the actual LLM request for summarization using the specified chat, system prompt, and user prompt. It handles adapter selection, disables streaming, and parses the response. ```lua function SummaryGenerator:_make_adapter_request(chat: CodeCompanion.History.Chat, system_prompt: string, user_prompt: string, callback: function): nil ``` -------------------------------- ### Configuring Custom Storage Directory Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/README.md Shows how to change the default directory where chat history and summaries are stored. This is useful for managing storage location. ```lua opts = { dir_to_save = vim.fn.stdpath("data") .. "/my-chats", } ``` -------------------------------- ### UI:create_chat(chat_data) Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/UI.md Creates and opens a new chat in CodeCompanion using provided chat data, restoring messages, tools, settings, and context. ```APIDOC ## UI:create_chat(chat_data) ### Description Create and open a new chat from loaded chat data. This method is called internally when restoring a chat from storage, recreating the chat with all its components. ### Method `UI:create_chat(chat_data)` ### Parameters #### Path Parameters - **chat_data** (ChatData) - Required - The chat data to restore ### Returns `nil` ### Side Effects - Creates new CodeCompanion chat buffer - Populates with messages and tools from chat_data - Restores LLM settings and adapter - Reestablishes tool registry and context items ### Example ```lua local chat_data = storage:load_chat(save_id) if chat_data then ui:create_chat(chat_data) end ``` ``` -------------------------------- ### Automatic Summary Indexing Event Listener Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Sets up an autocommand to listen for the 'CodeCompanionHistorySummarySaved' event and automatically index the saved summary using vectorise. ```lua vim.api.nvim_create_autocmd("User", { pattern = "CodeCompanionHistorySummarySaved", callback = function(args) if args.data.path then vectorcode.vectorise(args.data.path) end end, }) ``` -------------------------------- ### Memory Submodule Options Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/README.md Configure the memory submodule, including automatic summary creation, VectorCode executable path, default number of memories to retrieve, and index update behavior. ```lua opts.memory = { auto_create_memories_on_summary_generation = true, -- path to the `vectorcode` executable vectorcode_exe = "vectorcode", tool_opts = { -- default number of memories to retrieve default_num = 10 }, -- whether to enable notification notify = true, -- whether to automatically update the index of all existing memories on startup -- (requires VectorCode 0.6.12+ for efficient incremental indexing) index_on_startup = false, } ``` -------------------------------- ### VectorCode Search Command Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Demonstrates the bash command for querying VectorCode with keywords and specifying the number of results. ```bash vectorcode query --project_root {summaries_dir} --pipe -n {count} {keyword1} {keyword2}... ``` -------------------------------- ### make_memory_tool(opts) Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Memory.md Creates the `@memory` tool definition for CodeCompanion, enabling LLM to search indexed summaries. ```APIDOC ## make_memory_tool(opts) ### Description Create the @memory tool definition for CodeCompanion. ### Parameters #### Path Parameters - **opts** (CodeCompanion.History.MemoryTool.Opts) - Optional - Tool configuration options ### Returns - `CodeCompanion.Agent.Tool` — Tool definition for CodeCompanion ### Tool Properties - **Name:** `memory` - **Description:** "This tool gives you access to previous conversations..." - **Parameters:** - `keywords` (required) — Array of search keywords - `count` (optional) — Number of results (defaults to `default_num`) ### Example ```lua local vectorcode = require("codecompanion._extensions.history.vectorcode") if vectorcode.has_vectorcode() then local tool = vectorcode.make_memory_tool({ default_num = 10 }) -- Tool is automatically registered by History extension end ``` ``` -------------------------------- ### Write Content to File Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/Utils.md Writes string content to a file. Parent directories are created if they do not exist. ```lua function write_file(file_path: string, content: string): {ok: boolean, error: string|nil} ``` ```lua local summary = "# Summary\n\nThis chat was about..." local result = utils.write_file("/path/to/summary.md", summary) ``` -------------------------------- ### UI:open_summaries() Source: https://github.com/ravitemer/codecompanion-history.nvim/blob/main/_autodocs/api-reference/UI.md Opens the summary picker, allowing users to browse, preview, select, or delete generated summaries. This function is asynchronous and opens a picker interface. ```APIDOC ## UI:open_summaries() ### Description Opens the summary picker displaying all generated summaries. Provides handlers for preview, selection, and deletion. ### Method `UI:open_summaries()` ### Returns `nil` — Opens picker asynchronously ### Picker Actions - `` — Add summary to current chat as a reference - `d` (normal) / `` (insert) — Delete summary(s) ### Notifications - "No summaries found" - "No active chat to attach summary to" - "Summary added to chat" ### Example ```lua local ui = UI.new(opts, storage, title_gen) ui:open_summaries() ``` ```