*chat.nvim*  A lightweight lua chat plugin for Neovim with AI integration. 

Author: Eric Wong <wsdjeg@outlook.com>
Url: https://github.com/wsdjeg/chat.nvim

==============================================================================
CONTENTS                                                                *chat*

  1. Introduction                                          |chat-introduction|
  2. Features                                                  |chat-features|
  3. Installation                                          |chat-installation|
      Prerequisites                                        |chat-prerequisites|
      Package Manager Installation                |chat-package-manager-installation|
      Manual Installation                                |chat-manual-installation|
      Post-Installation Setup                        |chat-post-installation-setup|
      Quick Start                                            |chat-quick-start|
  4. Configuration                                        |chat-configuration|
      Basic Options                                        |chat-basic-options|
      Storage Paths                                        |chat-storage-paths|
      HTTP Server Configuration                    |chat-http-server-configuration|
      API Key Configuration                            |chat-api-key-configuration|
      File Access Control                              |chat-file-access-control|
      Context Window Configuration                |chat-context-window-configuration|
      Memory System Configuration                  |chat-memory-system-configuration|
      User Profile Configuration                    |chat-user-profile-configuration|
      Skills Configuration                            |chat-skills-configuration|
      Auto-Retry Configuration                      |chat-auto-retry-configuration|
      system_prompt Usage Examples                |chat-system_prompt-usage-examples|
      MCP Server Configuration                    |chat-mcp-server-configuration|
      IM Integration Configuration                |chat-im-integration-configuration|
      Complete Configuration Example              |chat-complete-configuration-example|
  5. Usage                                                        |chat-usage|
      Basic Commands                                   |chat-basic-commands|
      MCP Commands                                       |chat-mcp-commands|
      Parallel Sessions                                 |chat-parallel-sessions|
      Skills (Slash Commands)                      |chat-skills-slash-commands|
      Examples                                               |chat-examples|
      Key Bindings                                       |chat-key-bindings|
  6. Providers                                                |chat-providers|
      Built-in Providers                           |chat-built-in-providers|
      Custom Providers                               |chat-custom-providers|
      Protocols                                               |chat-protocols|
  7. Tools                                                        |chat-tools|
      MCP Tools                                               |chat-mcp-tools|
      Available Tools                                 |chat-available-tools|
      Third-party Tools                             |chat-third-party-tools|
      How to Use Tools                               |chat-how-to-use-tools|
      Custom Tools                                       |chat-custom-tools|
  8. HTTP API                                                    |chat-http-api|
      Enabling the HTTP Server                    |chat-enabling-the-http-server|
      API Endpoints                                       |chat-api-endpoints|
      Request Format                                     |chat-request-format|
      Response Format                                   |chat-response-format|
      Message Queue System                         |chat-message-queue-system|
      Usage Examples                                     |chat-usage-examples|
      Security Considerations                   |chat-security-considerations|
  9. Picker Integration                              |chat-picker-integration|
10. IM Integration                                         |chat-im-integration|
      Discord                                                 |chat-discord|
      Lark (Feishu)                                         |chat-lark|
      DingTalk                                               |chat-dingtalk|
      WeCom                                                     |chat-wecom|
      Weixin (Personal WeChat)                               |chat-weixin|
      Telegram                                               |chat-telegram|
      Slack                                                     |chat-slack|
  11. Self-Promotion                                      |chat-self-promotion|
  12. Feedback                                                  |chat-feedback|
  13. License                                                   |chat-license|

==============================================================================
 1. INTRODUCTION                                           *chat-introduction*

`chat.nvim` is a lightweight, extensible chat plugin for Neovim with AI
integration. Chat with AI assistants directly in your editor using a clean,
floating window interface.

==============================================================================
 2. FEATURES                                                  *chat-features*

- **Three-Tier Memory System**: Working memory (session tasks), daily memory
  (short-term goals), and long-term memory (permanent knowledge) with
  automatic extraction and priority-based retrieval
- **Parallel Sessions**: Run multiple independent conversations with different
  AI models, each maintaining separate context and settings
- **Multiple AI Providers**: Built-in support for 19+ providers including
  DeepSeek, GitHub AI, Moonshot, OpenRouter, Qwen, SiliconFlow, Tencent,
  BigModel, Volcengine, OpenAI, Anthropic Claude, Google Gemini, Ollama,
  LongCat, CherryIN, Yuanjing, Baidu, Xiaomi, Alibaba Cloud, and custom
  providers
- **Tool Call Integration**: 41+ built-in tools for file operations
  (`@read_file`, `@write_file`, `@find_files`, `@search_text`, `@copy_file`,
  `@move_file`, `@create_directory`, `@list_directory`, `@file_info`),
  version control (`@git_diff`, `@git_log`, `@git_status`, `@git_show`,
  `@git_rebase`, and more), conversation history (`@get_history`), memory
  management, task planning (`@plan`), scheduling (`@schedule_task`), user
  profiles (`@user_profile`), and more
- **Skills (Slash Commands)**: Type `/name [args]` in the prompt window to
  invoke built-in and custom commands without LLM round-trips. Built-in skills
  include `/clear`, `/new`, `/model`, `/provider`, `/cwd`, `/pin`, `/title`,
  `/retry`, and `/help`. Custom skills can be registered via configuration,
  Lua API, or file-based auto-load
- **User Profiles (人物画像)**: Store user preferences, skills, and background
  as markdown files for personalized AI assistance
- **Zettelkasten Integration**: Note-taking support via `@zettelkasten_create`
  and `@zettelkasten_get` tools for knowledge management
- **IM Integration**: Connect Discord, Lark (Feishu), DingTalk, WeCom
  (Enterprise WeChat), Weixin, Telegram, and Slack channels to chat.nvim
  sessions for remote AI interaction
- **HTTP API Server**: Built-in HTTP server for receiving external messages
  with API key authentication and message queue support
- **Session Management**: Commands for creating (`:Chat new`), navigating
  (`:Chat prev/next`), clearing (`:Chat clear`), deleting (`:Chat delete`),
  saving (`:Chat save`), loading (`:Chat load`), sharing (`:Chat share`),
  bridging (`:Chat bridge`), previewing (`:Chat preview`), and changing
  working directory (`:Chat cd`)
- **Picker Integration**: Seamless integration with picker.nvim for browsing
  chat history (`picker-chat`), switching providers (`chat_provider`), and
  selecting models (`chat_model`)
- **Floating Window Interface**: Clean, non-intrusive dual-window layout with
  configurable dimensions and borders
- **Streaming Responses**: Real-time AI responses with cancellation support
  (`Ctrl-C`) and retry mechanism (`r`)
- **Auto-Retry**: Automatic retry of LLM requests on connection errors and
  timeouts with configurable retry count and delay
- **Token Usage Tracking**: Display real-time token consumption for each
  response
- **Lightweight Implementation**: Pure Lua with minimal dependencies and
  comprehensive error handling
- **Customizable Configuration**: Flexible setup for API keys, allowed paths,
  memory settings, system prompts, storage paths, and more
- **Session HTML Preview**: Generate and open HTML previews of chat sessions
  in your browser via `:Chat preview` command
- **Custom Tools**: Support for creating custom tools via
  `lua/chat/tools/<tool_name>.lua` with automatic discovery
- **Custom Providers**: Support for creating custom AI providers with custom
  protocols
- **Custom Protocols**: Support for custom API response parsing (OpenAI,
  Anthropic, Gemini, and extensible)
- **Context Window Truncation**: Automatic context management with
  configurable trigger threshold and recent message preservation
- **MCP (Model Context Protocol) Support**: Native integration with MCP
  servers for extended tool capabilities
- **RenderMarkdown Integration**: Optional rich rendering of AI responses in
  the result buffer

==============================================================================
 3. INSTALLATION                                           *chat-installation*

------------------------------------------------------------------------------
 3.1 Prerequisites                                            *chat-prerequisites*

1. **System Dependencies** (optional but recommended for full functionality):
>
   # Ubuntu/Debian
   sudo apt install ripgrep curl git

   # macOS
   brew install ripgrep curl git

   # Arch Linux
   sudo pacman -S ripgrep curl git
<

2. **Neovim Plugin Dependencies**:
   - `job.nvim` - **Required** dependency for asynchronous operations
   - `picker.nvim` - **Recommended** for enhanced session and provider
     management

------------------------------------------------------------------------------
 3.2 Package Manager Installation                *chat-package-manager-installation*

Using nvim-plug:
>
    require('plug').add({
      {
        'wsdjeg/chat.nvim',
        depends = {
          {
            'wsdjeg/job.nvim', -- Required
            'wsdjeg/picker.nvim', -- Optional but recommended
          },
        },
      },
    })
<

Using lazy.nvim:
>
    {
      'wsdjeg/chat.nvim',
      dependencies = {
        'wsdjeg/job.nvim', -- Required
        'wsdjeg/picker.nvim', -- Optional but recommended
      },
    }
<

Using packer.nvim:
>
    use({
      'wsdjeg/chat.nvim',
      requires = {
        'wsdjeg/job.nvim', -- Required
        'wsdjeg/picker.nvim', -- Optional but recommended
      },
    })
<

------------------------------------------------------------------------------
 3.3 Manual Installation                                *chat-manual-installation*

1. Clone the repositories:
>
   git clone https://github.com/wsdjeg/chat.nvim ~/.local/share/nvim/site/pack/chat/start/chat.nvim
   git clone https://github.com/wsdjeg/job.nvim ~/.local/share/nvim/site/pack/chat/start/job.nvim
<

2. Add to your Neovim configuration:
>
   vim.cmd[[packadd job.nvim]]
   vim.cmd[[packadd chat.nvim]]
   require('chat').setup({
     -- Your configuration here
   })
<

------------------------------------------------------------------------------
 3.4 Post-Installation Setup                        *chat-post-installation-setup*

1. **API Keys**: Configure at least one AI provider API key in the `api_key`
   table
2. **File Access**: Set `allowed_path` to control which directories tools can
   access
3. **Memory System**: Configure memory settings based on your needs
4. **HTTP Server** (optional): Configure HTTP server settings if you want to
   enable external message integration

------------------------------------------------------------------------------
 3.5 Quick Start                                                *chat-quick-start*

After installation, you can immediately start using chat.nvim:
>
   :Chat          " Open chat window
   :Chat new      " Start a new session
   :Chat prev     " Switch to previous session
   :Chat next     " Switch to next session
<

==============================================================================
 4. CONFIGURATION                                        *chat-configuration*

chat.nvim provides flexible configuration options through the
`require('chat').setup()` function. All configurations have sensible defaults.

------------------------------------------------------------------------------
 4.1 Basic Options                                            *chat-basic-options*

| Option            | Type               | Default                         |
| ----------------- | ------------------ | ------------------------------- |
| `width`           | number             | `0.8`                           |
| `height`          | number             | `0.8`                           |
| `auto_scroll`     | boolean            | `true`                          |
| `border`          | string             | `'rounded'`                     |
| `provider`        | string             | `'deepseek'`                    |
| `model`           | string             | `'deepseek-v4-flash'`           |
| `strftime`        | string             | `'%m-%d %H:%M:%S'`              |
| `render_markdown` | boolean            | `true`                          |
| `system_prompt`   | string or function | `''`                            |
| `storage_dir`     | string             | `stdpath('data')/chat.nvim/`    |
| `highlights`      | table              | `{title = 'ChatNvimTitle', ...}`|
| `winhighlight`    | string             | `'NormalFloat:Normal,...'`      |

Width/height are percentages of screen (0.0-1.0).

`render_markdown` enables the RenderMarkdown plugin for the result buffer
(requires render-markdown.nvim). Set to `false` for plain markdown highlighting.

`storage_dir` is the base storage directory for all persistent data (sessions,
plans, scheduler, memory, user profiles). Sub-module directories are
automatically derived unless explicitly overridden.

`winhighlight` configures the floating window highlight.

------------------------------------------------------------------------------
 4.2 Storage Paths                                          *chat-storage-paths*

All persistent data is stored under `storage_dir`. Sub-module storage
directories are automatically derived unless explicitly overridden:

| Module        | Config Key           | Derived Path                  |
| ------------- | -------------------- | ----------------------------- |
| Sessions      | -                    | `storage_dir`                 |
| Plans         | -                    | `storage_dir .. 'plans/'`     |
| Scheduler     | -                    | `storage_dir .. 'scheduler/'` |
| Memory        | `memory.storage_dir` | `storage_dir .. 'memory/'`    |
| User Profiles | `user.storage_dir`   | `storage_dir .. 'users/'`     |

To override a specific module's storage path:
>
    require('chat').setup({
      storage_dir = '/my/custom/path/',
      memory = {
        storage_dir = '/separate/memory/path/',
      },
    })
<

------------------------------------------------------------------------------
 4.3 HTTP Server Configuration                    *chat-http-server-configuration*

Configure the built-in HTTP server for receiving external messages:
>
    http = {
      host = '127.0.0.1',
      port = 7777,
      api_key = 'your-secret-api-key-here',
    }
<

Notes:
- The HTTP server is automatically started when `http.api_key` is not empty
- Incoming requests must include the API key in the `X-API-Key` header
- Messages are queued and processed when the chat window is not busy

------------------------------------------------------------------------------
 4.4 API Key Configuration                            |chat-api-key-configuration*

Configure API keys for the AI providers you plan to use:
>
    api_key = {
      deepseek = 'sk-xxxxxxxxxxxx',        -- DeepSeek AI
      github = 'github_pat_xxxxxxxx',      -- GitHub AI
      moonshot = 'sk-xxxxxxxxxxxx',        -- Moonshot AI
      openrouter = 'sk-or-xxxxxxxx',       -- OpenRouter
      qwen = 'qwen-xxxxxxxx',              -- Alibaba Qwen (DashScope)
      aliyuncs = 'sk-xxxxxxxxxxxx',        -- Alibaba Cloud (Bailian)
      siliconflow = 'xxxxxxxx-xxxx-xxxx',  -- SiliconFlow
      tencent = 'xxxxxxxx-xxxx-xxxx',      -- Tencent Hunyuan
      baidu = 'xxxxxxxx-xxxx-xxxx',        -- Baidu Qianfan
      bigmodel = 'xxxxxxxx-xxxx-xxxx',     -- BigModel AI
      volcengine = 'xxxxxxxx-xxxx-xxxx',   -- Volcengine AI
      xiaomi = 'xxxxxxxx-xxxx-xxxx',       -- Xiaomi MiMo
      openai = 'sk-xxxxxxxxxxxx',          -- OpenAI
      anthropic = 'sk-ant-xxxxxxxxxxxx',   -- Anthropic Claude
      gemini = 'AIxxxxxxxxxxxxxxxxxxxx',   -- Google Gemini
      longcat = 'lc-xxxxxxxxxxxx',         -- LongCat AI
      cherryin = 'sk-xxxxxxxxxxxx',        -- CherryIN AI
      yuanjing = 'xxxxxxxx-xxxx-xxxx',     -- Yuanjing AI
    }
<

Only configure keys for providers you plan to use; others can be omitted.

------------------------------------------------------------------------------
 4.5 File Access Control                              |chat-file-access-control*

Control which file paths tools can access for security:
>
    -- Option 1: Disable all file access (default)
    allowed_path = ''

    -- Option 2: Allow a single directory
    allowed_path = '/home/user/projects'

    -- Option 3: Allow multiple directories
    allowed_path = {
      vim.fn.getcwd(),               -- Current working directory
      vim.fn.expand('~/.config/nvim'), -- Neovim config directory
      '/etc',                        -- System configuration files
    }
<

------------------------------------------------------------------------------
 4.6 Context Window Configuration                |chat-context-window-configuration*

Configure automatic context truncation to manage token usage:
>
    context = {
      enable = true,           -- Enable/disable context truncation
      trigger_threshold = 50,  -- Number of messages to trigger truncation
      keep_recent = 10,        -- Keep recent N messages
    }
<

------------------------------------------------------------------------------
 4.7 Memory System Configuration                  |chat-memory-system-configuration*

chat.nvim implements a sophisticated three-tier memory system:

**Memory Architecture:**

1. **Working Memory** ⚡ - High-priority, session-scoped memory for current
   tasks and decisions
2. **Daily Memory** 📅 - Temporary memory for daily tasks and short-term
   goals (auto-expires)
3. **Long-term Memory** 💾 - Permanent knowledge storage for facts,
   preferences, and skills

**Configuration:**
>
    memory = {
      enable = true,  -- Global memory system switch

      -- Long-term memory: Permanent knowledge (never expires)
      long_term = {
        enable = true,
        max_memories = 500,           -- Maximum memories to store
        retrieval_limit = 3,          -- Maximum memories to retrieve per query
        similarity_threshold = 0.3,   -- Text similarity threshold (0-1)
      },

      -- Daily memory: Temporary tasks and goals (auto-expires)
      daily = {
        enable = true,
        retention_days = 7,           -- Days before auto-deletion
        max_memories = 100,           -- Maximum daily memories
        similarity_threshold = 0.4,
      },

      -- Working memory: Current session focus (highest priority)
      working = {
        enable = true,
        max_memories = 20,            -- Maximum working memories per session
        priority_weight = 2.0,        -- Priority multiplier
      },

      -- Storage location (optional, defaults to storage_dir .. 'memory/')
      -- storage_dir = '/custom/memory/path/',
    }
<

**Memory Type Characteristics:**

| Type      | Lifetime     | Priority | Use Case                                   |
| --------- | ------------ | -------- | ------------------------------------------ |
| Working   | Session only | Highest  | Current tasks, decisions, active context   |
| Daily     | 7-30 days    | Medium   | Short-term goals, today's tasks, reminders |
| Long-term | Permanent    | Normal   | Facts, preferences, skills, knowledge      |

`memory.storage_dir` defaults to `nil`, which means it is automatically derived
from the top-level `storage_dir`. Only set this if you want to use a different
location.

------------------------------------------------------------------------------
 4.8 User Profile Configuration                  *chat-user-profile-configuration*

chat.nvim supports user profiles (人物画像) for personalized AI assistance.
Profiles store user preferences, skills, and background information as
markdown files.
>
    require('chat').setup({
      user = {
        enable = true,        -- Enable user profile system
        id = '',              -- User ID (auto-detected if empty)
        -- storage_dir = '/custom/users/path/',  -- Optional
      },
    })
<

| Option             | Type    | Default                            |
| ------------------ | ------- | ---------------------------------- |
| `user.enable`      | boolean | `true`                             |
| `user.id`          | string  | `''` (auto-detected from username) |
| `user.storage_dir` | string  | `nil` (derived from `storage_dir`) |

When enabled, the AI can use `@user_profile` to read, update, and manage user
profiles, providing personalized and context-aware responses.

------------------------------------------------------------------------------
 4.9 Skills Configuration                          *chat-skills-configuration*

chat.nvim includes a skill (slash command) system. Type `/name [args]` in the
prompt window to invoke commands without sending to the LLM.
>
    require('chat').setup({
      skills = {
        {
          name = 'greet',
          description = 'Say hello',
          handler = function(args, ctx)
            return 'Hello, ' .. (args or 'world') .. '!'
          end,
        },
      },
    })
<

Each skill spec contains:

| Field         | Type     | Description                                       |
| ------------- | -------- | ------------------------------------------------- |
| `name`        | string   | Unique identifier (used as `/name`)               |
| `description` | string   | Short description shown in `/help`                |
| `handler`     | function | `function(args: string, ctx: table): string|nil`  |
| `complete`    | function | Optional completion function                      |

You can also register skills at runtime via
`require('chat').register_skill(spec)` and unregister with
`require('chat').unregister_skill(name)`.

Runtime skills can be auto-loaded from `lua/chat/skills/*.lua` files in your
Neovim runtime path. Each file must return a table with `name` and `handler`
fields.

See |chat-skills-slash-commands| for the list of built-in skills.

------------------------------------------------------------------------------
 4.10 Auto-Retry Configuration                    *chat-auto-retry-configuration*

chat.nvim automatically retries LLM requests that fail due to connection
errors or timeouts.
>
    retry = {
      max_retries = 3,       -- Maximum retry attempts per request
      retry_delay = 2000,    -- Delay between retries in milliseconds
    }
<

How it works:
- When an LLM request fails with a retryable error (connection failure or
  timeout), an error message with retry status is appended to the session
- The system schedules a retry after the configured delay
- Retry count is per-session and reset on each new user message
- User can cancel a pending retry with `Ctrl-C`
- HTTP errors (400, 429, 500, etc.) are **not** retried

Retryable curl exit codes: 6 (DNS), 7 (connect), 28 (timeout), 35 (SSL),
52 (empty reply), 56 (receive failure).

------------------------------------------------------------------------------
 4.11 system_prompt Usage Examples                |chat-system_prompt-usage-examples*

Here are different ways to use the `system_prompt` option:

**String (simple):**
>
    system_prompt = 'You are a helpful programming assistant.',
<

**Function loading from file:**
>
    system_prompt = function()
      local path = vim.fn.expand('~/.config/nvim/AGENTS.md')
      if vim.fn.filereadable(path) == 1 then
        return table.concat(vim.fn.readfile(path), '\n')
      end
      return 'Default system prompt'
    end
<

**Function with project-specific prompts:**
>
    system_prompt = function()
      local cwd = vim.fn.getcwd()
      if string.find(cwd, 'chat%.nvim') then
        return 'You are a specialized assistant for chat.nvim plugin development.'
      elseif string.find(cwd, 'picker%.nvim') then
        return 'You are a specialized assistant for picker.nvim plugin development.'
      end
      return 'You are a general programming assistant.'
    end
<

------------------------------------------------------------------------------
 4.12 MCP Server Configuration                    *chat-mcp-server-configuration*

chat.nvim supports Model Context Protocol (MCP) servers for extended tool
capabilities. MCP allows you to connect external tool servers that provide
additional functionality.

**Basic Configuration (stdio transport):**
>
    mcp = {
      -- Example: Web search MCP server
      open_webSearch = {
        command = 'npx',
        args = { '-y', 'open-websearch@latest' },
        disabled = false,  -- Set to true to disable this server
      },
    }
<

**HTTP Transport Configuration:**
>
    mcp = {
      -- HTTP-based MCP server
      my_http_server = {
        url = 'https://mcp-server.example.com',
        headers = {
          ['Authorization'] = 'Bearer YOUR_TOKEN',
        },
      },
    }
<

**MCP Tool Naming:**

MCP tools are automatically prefixed with `mcp_<server>_<tool>` format:

- Original MCP tool: `search`
- MCP server name: `open_webSearch`
- Final tool name: `mcp_open_webSearch_search`

**Usage in Chat:**
>
    @mcp_open_webSearch_search query="neovim plugins" limit=10
<

------------------------------------------------------------------------------
 4.13 IM Integration Configuration                *chat-im-integration-configuration*

Configure instant messaging platform integrations:
>
    integrations = {
      -- Discord
      discord = {
        token = 'YOUR_DISCORD_BOT_TOKEN',
        channel_id = 'YOUR_CHANNEL_ID',
      },

      -- Lark (Feishu)
      lark = {
        app_id = 'YOUR_APP_ID',
        app_secret = 'YOUR_APP_SECRET',
        chat_id = 'YOUR_CHAT_ID',
      },

      -- DingTalk
      dingtalk = {
        webhook = 'https://oapi.dingtalk.com/robot/send?access_token=XXX',
      },

      -- WeCom (Enterprise WeChat)
      wecom = {
        webhook_key = 'YOUR_WEBHOOK_KEY',
      },

      -- Telegram
      telegram = {
        bot_token = 'YOUR_BOT_TOKEN',
        chat_id = 'YOUR_CHAT_ID',
      },

      -- Slack
      slack = {
        bot_token = 'xoxb-YOUR-BOT-TOKEN',
        channel_id = 'CXXXXXXXXXX',
      },
    }
<

------------------------------------------------------------------------------
 4.14 Complete Configuration Example              *chat-complete-configuration-example*

>
    require('chat').setup({
      -- Window settings
      width = 0.8,
      height = 0.8,
      auto_scroll = true,
      border = 'rounded',

      -- AI provider settings
      provider = 'deepseek',
      model = 'deepseek-v4-flash',
      api_key = {
        deepseek = 'sk-xxxxxxxxxxxx',
        github = 'github_pat_xxxxxxxx',
      },

      -- HTTP server configuration
      http = {
        host = '127.0.0.1',
        port = 7777,
        api_key = 'your-secret-key-here',
      },

      -- File access control
      allowed_path = {
        vim.fn.getcwd(),
        vim.fn.expand('~/.config/nvim'),
      },

      -- Base storage directory for all persistent data
      storage_dir = vim.fn.stdpath('data') .. '/chat.nvim/',

      -- Other settings
      strftime = '%Y-%m-%d %H:%M',
      render_markdown = true,
      system_prompt = function()
        local path = vim.fn.expand('./AGENTS.md')
        if vim.fn.filereadable(path) == 1 then
          return table.concat(vim.fn.readfile(path), '\n')
        end
        return 'You are a helpful programming assistant.'
      end,

      -- Memory system
      memory = {
        enable = true,
        long_term = {
          max_memories = 500,
          retrieval_limit = 3,
        },
        daily = {
          retention_days = 7,
          max_memories = 100,
        },
        working = {
          max_memories = 20,
          priority_weight = 2.0,
        },
      },

      -- Auto-retry on connection errors and timeouts
      retry = {
        max_retries = 3,
        retry_delay = 2000,
      },

      -- User profile system (人物画像)
      user = {
        enable = true,
        id = '',
      },

      -- Custom skills (slash commands)
      skills = {
        {
          name = 'greet',
          description = 'Say hello',
          handler = function(args, ctx)
            return 'Hello, ' .. (args or 'world') .. '!'
          end,
        },
      },

      -- MCP servers configuration
      mcp = {
        open_webSearch = {
          command = 'npx',
          args = { '-y', 'open-websearch@latest' },
        },
      },

      -- IM integrations
      integrations = {
        discord = {
          token = 'YOUR_DISCORD_BOT_TOKEN',
          channel_id = 'YOUR_CHANNEL_ID',
        },
      },
    })
<

==============================================================================
 5. USAGE                                                         *chat-usage*

------------------------------------------------------------------------------
 5.1 Basic Commands                                      *chat-basic-commands*

| Command             | Description                                         |
| ------------------- | --------------------------------------------------- |
| `:Chat`             | Open the chat window with the current session       |
| `:Chat new`         | Start a new chat session                            |
| `:Chat prev`        | Switch to the previous chat session                 |
| `:Chat next`        | Switch to the next chat session                     |
| `:Chat delete`      | Delete current session and create new empty session |
| `:Chat clear`       | Clear all messages in current session               |
| `:Chat cd <dir>`    | Change current session cwd, open chat window        |
| `:Chat save <path>` | Save current session to specified file path         |
| `:Chat load <path>` | Load session from file path or URL                  |
| `:Chat share`       | Share current session via pastebin                  |
| `:Chat preview`     | Open HTML preview of current session in browser     |
| `:Chat bridge`      | Bind current session to external platform (Discord) |
| `:Chat unbridge [im]` | Unbind integration (all or specific platform)     |
| `:Chat mcp stop`    | Stop all MCP servers                                |
| `:Chat mcp start`   | Start all MCP servers                               |
| `:Chat mcp restart` | Restart all MCP servers                             |

------------------------------------------------------------------------------
 5.2 MCP Commands                                            *chat-mcp-commands*

Manage MCP (Model Context Protocol) servers with the following commands:

1. **Stop MCP servers**:
>
   :Chat mcp stop
<
   Stops all running MCP servers and cleans up resources.

2. **Start MCP servers**:
>
   :Chat mcp start
<
   Starts all configured MCP servers. Note: Servers are automatically started
   when opening the chat window.

3. **Restart MCP servers**:
>
   :Chat mcp restart
<
   Restarts all MCP servers (stops and starts with a delay for cleanup).

------------------------------------------------------------------------------
 5.3 Parallel Sessions                                 |chat-parallel-sessions*

chat.nvim supports running multiple chat sessions simultaneously, with each
session operating independently:

- **Independent Model Selection**: Each session can use a different AI model
- **Separate Contexts**: Sessions maintain their own conversation history,
  working directory, and settings
- **Quick Switching**: Use `:Chat prev` and `:Chat next` to navigate between
  active sessions
- **Isolated Workflows**: Perfect for comparing model responses or working on
  multiple projects simultaneously

**Workflow Example:**

1. Start a session with DeepSeek: `:Chat new` (then select DeepSeek model)
2. Switch to GitHub AI for a different task: `:Chat new` (select GitHub model)
3. Toggle between sessions: `:Chat prev` / `:Chat next`

------------------------------------------------------------------------------
 5.4 Skills (Slash Commands)                      *chat-skills-slash-commands*

chat.nvim includes a built-in skill system. Type `/name [args]` in the prompt
window to invoke commands without sending a message to the LLM.

**Built-in Skills:**

| Skill              | Description                                          |
| ------------------ | ---------------------------------------------------- |
| `/clear`           | Clear all messages in current session                |
| `/new`             | Create a new session                                 |
| `/delete`          | Delete current session                               |
| `/model [name]`    | Switch model (shows selection UI if no name given)   |
| `/provider [name]` | Switch provider (shows selection UI if no name given)|
| `/cwd <path>`      | Change working directory                             |
| `/pin`             | Toggle pin status of current session                 |
| `/title [text]`    | Set session title (shows input UI if no text given)  |
| `/retry`           | Retry last request                                   |
| `/help`            | Show all available skills                            |

**Usage:**
>
    /model gpt-4o
    /provider openai
    /cwd /tmp
    /clear
    /help
<

When no arguments are provided for `/model` and `/provider`, a selection UI
(`vim.ui.select`) is shown. `/title` without arguments uses `vim.ui.input`.

See |chat-skills-configuration| for custom skill registration and file-based
auto-load.

------------------------------------------------------------------------------
 5.5 Examples                                                  *chat-examples*

1. **Start a new conversation**:
>
   :Chat new
<
   This creates a fresh session and opens the chat window.

2. **Resume a previous conversation**:
>
   :Chat prev
<
   Cycles backward through your saved sessions.

3. **Switch to the next conversation**:
>
   :Chat next
<
   Cycles forward through your saved sessions.

4. **Open or forced to the chat window**:
>
   :Chat
<
   This command will not change current sessions.

5. **Delete current session**:
>
   :Chat delete
<
   Cycles to next session or create a new session if current session is
   latest one.

6. **Change the working directory of current session**:
>
   :Chat cd ../picker.nvim/
<
   If the current session is in progress, the working directory will not be
   changed, and a warning message will be printed.

7. **Clear messages in current session**:
>
   :Chat clear
<
   If the current session is in progress, a warning message will be printed,
   and current session will not be cleared. This command also will forced
   to chat window.

8. **Work with multiple parallel sessions**:
>
   " Start first session with DeepSeek
   :Chat new
   " Select DeepSeek as provider and choose a model

   " Start second session with GitHub AI
   :Chat new
   " Select GitHub as provider and choose a model

   " Switch between sessions
   :Chat prev  " Go to first session
   :Chat next  " Go to second session
<
   This enables simultaneous conversations with different AI assistants for
   different tasks.

9. **Save current session to a file**:
>
   :Chat save ~/sessions/my-session.json
<
   Saves the current session to a JSON file for backup or sharing.

10. **Load session from file**:
>
    :Chat load ~/sessions/my-session.json
<
    Loads a previously saved session from a JSON file.

11. **Load session from URL**:
>
    :Chat load https://paste.rs/xxxxx
<
    Loads a session from a URL (e.g., from paste.rs).

12. **Share current session**:
>
    :Chat share
<
    Uploads the current session to paste.rs and copies the URL to clipboard.

13. **Preview current session in browser**:
>
    :Chat preview
<
    Opens an HTML preview of the current session in your default browser.

------------------------------------------------------------------------------
 5.6 Key Bindings                                          *chat-key-bindings*

NOTE: The plugin is currently in active development phase.
Key bindings may change and may reflect the author's personal preferences.
Configuration options for customizing key bindings are planned for future
releases.

The following key bindings are available in the `Input` window:

| Mode     | Key Binding  | Description                             |
| -------- | ------------ | --------------------------------------- |
| `Normal` | `<Enter>`    | Send message                            |
| `Normal` | `q`          | Close chat window                       |
| `Normal` | `<Tab>`      | Switch between input and result windows |
| `Normal` | `Ctrl-C`     | Cancel current request                  |
| `Normal` | `Ctrl-N`     | Open new session                        |
| `Normal` | `Ctrl-D`     | Delete current session                  |
| `Normal` | `r`          | Retry last cancelled request            |
| `Normal` | `alt-h`      | previous chat session                   |
| `Normal` | `alt-l`      | next chat session                       |
| `Normal` | `<Leader>fr` | run `:Picker chat`                      |
| `Normal` | `<Leader>fp` | run `:Picker chat_provider`             |
| `Normal` | `<Leader>fm` | run `:Picker chat_model`                |
| `Normal` | `<M-t>`      | Rename current session title            |
The following key bindings are available in the `Result` window:

| Mode     | Key Binding  | Description                             |
| -------- | ------------ | --------------------------------------- |
| `Normal` | `q`          | Close chat window                       |
| `Normal` | `<Tab>`      | Switch between input and result windows |
| `Normal` | `<Leader>fr` | Run `:Picker chat`                      |

The result window uses `markdown` filetype, enabling syntax highlighting and
RenderMarkdown integration for rich rendering of AI responses.

==============================================================================
 6. PROVIDERS                                                 *chat-providers*

chat.nvim uses a two-layer architecture for AI service integration:

- **Providers**: Handle HTTP requests to specific AI services (DeepSeek,
  OpenAI, GitHub, etc.)
- **Protocols**: Parse API responses from different AI services (OpenAI,
  Anthropic, etc.)

Most AI services use OpenAI-compatible APIs, so the default protocol is
`openai`. Providers can specify a custom protocol via the `protocol` field
if needed.

------------------------------------------------------------------------------
 6.1 Built-in Providers                              *chat-built-in-providers*

1. `deepseek` - https://platform.deepseek.com/
2. `github` - https://github.com/features/ai
3. `moonshot` - https://platform.moonshot.cn/
4. `openrouter` - https://openrouter.ai/
5. `qwen` - https://www.aliyun.com/product/bailian
6. `siliconflow` - https://www.siliconflow.cn/
7. `tencent` - https://cloud.tencent.com/document/product/1729
8. `bigmodel` - https://bigmodel.cn/
9. `volcengine` - https://console.volcengine.com
10. `openai` - https://developers.openai.com/api/docs/
11. `anthropic` - https://www.anthropic.com/
12. `gemini` - https://ai.google.dev/
13. `ollama` - https://ollama.ai/
14. `longcat` - https://longcat.chat/platform/docs/
15. `cherryin` - https://open.cherryin.ai/
16. `yuanjing` - https://maas.ai-yuanjing.com/
17. `baidu` - https://qianfan.baidubce.com/
18. `xiaomi` - https://www.xiaomimimo.com/
19. `aliyuncs` - https://www.aliyun.com/product/bailian

Note: Most built-in providers use the OpenAI protocol by default. Exceptions:
- `anthropic` uses the Anthropic protocol
- `gemini` uses the Gemini protocol

------------------------------------------------------------------------------
 6.2 Custom Providers                                  *chat-custom-providers*

You can create custom providers for AI services not in the built-in list.
Create a file at `~/.config/nvim/lua/chat/providers/<provider_name>.lua`.

A provider module must implement:

1. **`available_models()`** - Return a list of available model names
2. **`request(opt)`** - Send HTTP request and return job ID

**Optional fields:**
- **`protocol`** - Specify which protocol to use (default: `openai`)

**Example custom provider:**
>
    -- ~/.config/nvim/lua/chat/providers/my_provider.lua
    local M = {}
    local job = require('job')
    local sessions = require('chat.sessions')
    local config = require('chat.config')

    function M.available_models()
      return {
        'model-1',
        'model-2',
      }
    end

    function M.request(opt)
      local cmd = {
        'curl',
        '-s',
        'https://api.example.com/v1/chat/completions',
        '-H',
        'Content-Type: application/json',
        '-H',
        'Authorization: Bearer ' .. config.config.api_key.my_provider,
        '-X',
        'POST',
        '-d',
        '@-',
      }

      local body = vim.json.encode({
        model = sessions.get_session_model(opt.session),
        messages = opt.messages,
        stream = true,
        stream_options = { include_usage = true },
        tools = require('chat.tools').available_tools(),
      })

      local jobid = job.start(cmd, {
        on_stdout = opt.on_stdout,
        on_stderr = opt.on_stderr,
        on_exit = opt.on_exit,
      })
      job.send(jobid, body)
      job.send(jobid, nil)
      sessions.set_session_jobid(opt.session, jobid)

      return jobid
    end

    -- Optional: specify custom protocol (defaults to 'openai')
    -- M.protocol = 'anthropic'

    return M
<

------------------------------------------------------------------------------
 6.3 Protocols                                               *chat-protocols*

Protocols handle parsing of API responses. Currently, chat.nvim supports:

- **`openai`**: OpenAI-compatible API format (default for all built-in
  providers)
- **`anthropic`**: Anthropic Claude API format
- **`gemini`**: Google Gemini API format

If you need a custom protocol, create a file at
`~/.config/nvim/lua/chat/protocol/<protocol_name>.lua` and implement:

- `on_stdout(id, data)` - Handle stdout data from curl
- `on_stderr(id, data)` - Handle stderr data
- `on_exit(id, code, signal)` - Handle request completion

See `lua/chat/protocol/openai.lua` for reference implementation.

==============================================================================
 7. TOOLS                                                         *chat-tools*

chat.nvim supports tool call functionality, allowing the AI assistant to
interact with your filesystem, manage memories, and perform other operations
during conversations. Tools are invoked using the `@tool_name` syntax directly
in your messages.

------------------------------------------------------------------------------
 7.1 MCP Tools                                                 *chat-mcp-tools*

MCP (Model Context Protocol) tools are automatically discovered and integrated
when MCP servers are configured. These tools follow the naming pattern
`mcp_<server>_<tool>` and work seamlessly with built-in tools.

**Example MCP Tools:**

- `mcp_open_webSearch_search` - Web search via MCP server
- `mcp_open_webSearch_fetchGithubReadme` - Fetch GitHub README via MCP

MCP tools are automatically available when their servers are configured in the
`mcp` section of your setup configuration.

**Using MCP Tools:**
>
    @mcp_open_webSearch_search query="neovim plugins" engines=["bing"] limit=10
    @mcp_open_webSearch_fetchGithubReadme url="https://github.com/wsdjeg/chat.nvim"
<

------------------------------------------------------------------------------
 7.2 Available Tools                                    *chat-available-tools*

**read_file**                                              *chat-tool-read_file*

Reads the content of a file or specific line range.

Usage:
>
    @read_file <filepath>
    @read_file <filepath> line_start=10 line_to=20
<

Output Format:
- Returns structured XML output for easier parsing
- Full file: `<FileContent>\ncontent\n</FileContent>`
- With range: `<FileContent lines="start-end">\ncontent\n</FileContent>`

Notes:
- Line numbers are 1-indexed (first line is line 1)
- File path must be within `allowed_path` configuration

**write_file**                                            *chat-tool-write_file*

Write, modify, or delete file content with automatic parent directory
creation.

Actions:
- `create` - Create new file (fails if exists)
- `overwrite` - Overwrite entire file content
- `append` - Append content to end of file
- `insert` - Insert content at specific line
- `delete` - Delete specific line range
- `replace` - Replace specific line range with new content
- `str_replace` - Replace string by matching old_str (no line numbers needed)
- `remove` - Delete entire file

Examples:
>
    @write_file filepath="./src/main.lua" action="create" content="print('hello')"
    @write_file filepath="./src/main.lua" action="overwrite" content="new content"
    @write_file filepath="./src/main.lua" action="str_replace" old_str="old" new_str="new"
    @write_file filepath="./src/main.lua" action="str_replace" old_str="TODO" new_str="DONE" replace_all=true
    @write_file filepath="./src/main.lua" action="remove"
<

Notes:
- `str_replace` uses literal string matching (no regex), supports multi-line
- By default, `old_str` must match exactly once; use `replace_all=true` for all
- `new_str` can be empty to delete the matched text
- Use `validate=true` for code files to catch syntax errors (Lua, Python)
- Use `backup=true` to create backup before modification

**copy_file**                                              *chat-tool-copy_file*

Copy a file or directory (recursive).

Usage:
>
    @copy_file source="./config.json" destination="./config.backup.json"
    @copy_file source="./src" destination="./src_copy"
    @copy_file source="./templates/" destination="./new_project/templates/" overwrite=true
<

**create_directory**                                *chat-tool-create_directory*

Create a directory (including parent directories). Equivalent to `mkdir -p`.

Usage:
>
    @create_directory path="./src/utils"
<

**file_info**                                              *chat-tool-file_info*

Get file or directory metadata (type, size, modification time, permissions,
line count).

Usage:
>
    @file_info filepath="./src/main.lua"
    @file_info filepath="./src/"
<

**list_directory**                                    *chat-tool-list_directory*

List directory contents with file metadata.

Usage:
>
    @list_directory path="./src"
    @list_directory path="./" recursive=true
    @list_directory path="./test" show_hidden=true
<

**move_file**                                              *chat-tool-move_file*

Move or rename a file/directory.

Usage:
>
    @move_file source="./src/old.lua" destination="./src/new.lua"
    @move_file source="./old_dir" destination="./new_dir" overwrite=true
<

**find_files**                                            *chat-tool-find_files*

Finds files in the current working directory that match a given pattern.

Usage:
>
    @find_files <pattern>
<
Examples:
- `@find_files *.lua` - Find all Lua files in the current directory
- `@find_files **/*.md` - Recursively find all Markdown files
- `@find_files src/**/*.js` - Find JavaScript files in the `src` directory

**search_text**                                          *chat-tool-search_text*

Advanced text search using ripgrep (rg) with regex support.

Usage:
>
    @search_text <pattern> [options]
<
Parameters:
- `pattern` - Text pattern to search for (supports regex)
- `directory` - Directory path to search in
- `ignore_case` - Whether to ignore case (default: false)
- `regex` - Whether to use regex (default: true)
- `max_results` - Maximum number of results (default: 100)
- `context_lines` - Number of context lines to show (default: 0)
- `whole_word` - Whether to match whole words only (default: false)
- `file_types` - File type filter, e.g., `["*.py", "*.md"]`
- `exclude_patterns` - Exclude file patterns, e.g., `["*.log", "node_modules/*"]`

**extract_memory**                                      *chat-tool-extract_memory*

Extract memories from conversation text into three-tier memory system.

Memory Types:
- `working` - Session only, highest priority
- `daily` - 7-30 days, medium priority
- `long_term` - Permanent, normal priority

Usage:
>
    @extract_memory text="Python的GIL是全局解释器锁" memory_type="long_term"
    @extract_memory text="今天要完成用户登录功能" memory_type="daily"
    @extract_memory text="当前正在修复登录bug" memory_type="working"
<

**recall_memory**                                        *chat-tool-recall_memory*

Retrieve relevant information from the three-tier memory system.

Usage:
>
    @recall_memory query="vim configuration"
    @recall_memory query="current task" memory_type="working"
    @recall_memory query="today" memory_type="daily"
<

**set_prompt**                                            *chat-tool-set_prompt*

Read a prompt file and set it as the current session's system prompt.

Usage:
>
    @set_prompt ./AGENTS.md
    @set_prompt ~/.config/chat.nvim/default_prompt.md
<

**fetch_web**                                              *chat-tool-fetch_web*

Fetch content from web URLs using curl.

Usage:
>
    @fetch_web url="https://example.com"
    @fetch_web url="https://api.github.com/repos/neovim/neovim" timeout=60
    @fetch_web url="https://api.example.com/data" method="POST" data='{"key":"value"}'
<

**web_search**                                            *chat-tool-web_search*

Search the web using Firecrawl, Google Custom Search API, or SerpAPI.

Engines:
- `firecrawl` (default): https://firecrawl.dev
- `google`: Google Custom Search JSON API
- `serpapi`: https://serpapi.com

Usage:
>
    @web_search query="firecrawl web scraping"
    @web_search query="neovim plugins" engine="google"
    @web_search query="latest news" engine="serpapi" serpapi_engine="bing"
<

**get_time**                                                *chat-tool-get_time*

Get current time and date information.

Usage:
>
    @get_time
    @get_time format="iso"
    @get_time timezone="utc"
    @get_time format="human"
<

Formats: `iso`, `unix`, `human`, `all` (default). Timezone: `local` (default)
or `utc`.

**get_weather**                                          *chat-tool-get_weather*

Get weather data from Meizu weather API.

Usage:
>
    @get_weather
    @get_weather city_id="101010100"
    @get_weather city_ids=["101010100", "101020100"]
<

If no city ID is provided, defaults to 101240101 (南昌).

**lsp_diagnostics**                                    *chat-tool-lsp_diagnostics*

Get LSP diagnostics (errors, warnings, hints) for a file.

Usage:
>
    @lsp_diagnostics filepath="./src/main.lua"
    @lsp_diagnostics filepath="./src/main.lua" severity=Error
    @lsp_diagnostics filepath="./src/main.lua" line_start=10 line_to=20
<

Parameters:
- `severity` - Filter: Error, Warn, Info, Hint, or All (default: All)
- `line_start` - Starting line number (1-indexed, inclusive)
- `line_to` - Ending line number (1-indexed, inclusive)

Notes:
- Requires an LSP client to be attached to the buffer
- Line numbers are 1-indexed

**officecli**                                              *chat-tool-officecli*

View office documents (currently supports Excel .xlsx).

Usage:
>
    @officecli filepath="data.xlsx"
    @officecli filepath="data.xlsx" mode="text"
    @officecli filepath="data.xlsx" mode="annotated"
    @officecli filepath="data.xlsx" mode="outline"
    @officecli filepath="data.xlsx" mode="stats"
    @officecli filepath="data.xlsx" mode="issues"
    @officecli filepath="data.xlsx" mode="html" browser=true
<

View Modes: `text`, `annotated`, `outline`, `stats`, `issues`, `html`.

**git_diff**                                                *chat-tool-git_diff*

Run git diff to show changes between working directory and index.

Usage:
>
    @git_diff
    @git_diff cached=true
    @git_diff branch="main"
    @git_diff path="./src"
<

**git_log**                                                *chat-tool-git_log*

Show commit logs with various filters and options.

Usage:
>
    @git_log
    @git_log count=10
    @git_log path="./src/main.lua"
    @git_log author="john" since="2024-01-01"
    @git_log from="v1.0.0" to="v2.0.0"
<

**git_status**                                            *chat-tool-git_status*

Show the working tree status.

Usage:
>
    @git_status
    @git_status path="./src"
<

**git_show**                                                *chat-tool-git_show*

Show detailed changes of a specific commit.

Usage:
>
    @git_show commit="abc123"
    @git_show commit="v1.0.0"
    @git_show commit="HEAD~1"
    @git_show commit="abc123" stat=true
<

**git_add**                                                  *chat-tool-git_add*

Stage file changes for commit.

Usage:
>
    @git_add path="file.lua"
    @git_add path=["a.lua", "b.lua"]
    @git_add all=true
<

**git_branch**                                            *chat-tool-git_branch*

Manage git branches.

Usage:
>
    @git_branch                    -- List local branches
    @git_branch all=true           -- List all branches including remote
    @git_branch branch="feature-x" create=true  -- Create new branch
    @git_branch branch="old-feature" delete=true -- Delete branch
<

**git_checkout**                                        *chat-tool-git_checkout*

Switch branches or restore working tree files.

Usage:
>
    @git_checkout branch="main"                -- Switch to existing branch
    @git_checkout new_branch="feature-x"      -- Create and checkout new branch
    @git_checkout branch="origin/feature" track=true -- Track remote branch
    @git_checkout file="src/main.lua"         -- Restore file from HEAD
<

**git_commit**                                            *chat-tool-git_commit*

Create a git commit with staged changes.

Usage:
>
    @git_commit message="feat: add new feature"
    @git_commit message="fix: bug fix" allow_empty=true
    @git_commit message="update" amend=true
<

**git_config**                                            *chat-tool-git_config*

Get, set, or list git configuration.

Usage:
>
    @git_config action="get" key="user.name"
    @git_config action="set" key="user.email" value="test@example.com"
    @git_config action="list"
    @git_config action="list" global=true
<

**git_fetch**                                              *chat-tool-git_fetch*

Fetch changes from remote repository without merging.

Usage:
>
    @git_fetch                           -- Fetch from origin (default)
    @git_fetch remote="upstream"         -- Fetch from specific remote
    @git_fetch branch="main"             -- Fetch specific branch
    @git_fetch all=true                  -- Fetch all remotes
<

**git_merge**                                              *chat-tool-git_merge*

Merge branches.

Usage:
>
    @git_merge branch="feature-x"                     -- Merge feature branch
    @git_merge branch="main" message="Merge main"    -- Merge with custom message
    @git_merge branch="feature" no_ff=true           -- Force merge commit
    @git_merge abort=true                            -- Abort current merge
<

**git_pull**                                                *chat-tool-git_pull*

Pull changes from remote repository and merge.

Usage:
>
    @git_pull                           -- Pull from origin (current branch)
    @git_pull branch="main"             -- Pull specific branch from origin
    @git_pull remote="upstream"         -- Pull from different remote
    @git_pull rebase=true               -- Use rebase instead of merge
<

**git_push**                                                *chat-tool-git_push*

Push commits to remote repository.

Usage:
>
    @git_push                           -- Push to origin (current branch)
    @git_push branch="main"             -- Push specific branch
    @git_push set_upstream=true         -- Set upstream (-u)
    @git_push force=true                -- Force push
<

**git_rebase**                                            *chat-tool-git_rebase*

Rebase current branch onto another branch.

Usage:
>
    @git_rebase branch="main"                    -- Rebase current branch onto main
    @git_rebase branch="develop"                 -- Rebase onto develop
    @git_rebase abort=true                       -- Abort current rebase
    @git_rebase continue=true                    -- Continue after conflict resolution
    @git_rebase skip=true                        -- Skip current commit and continue
<

Notes:
- Rebase rewrites history. Use with caution on shared branches
- Use `abort` to cancel an in-progress rebase after conflicts
- Use `continue` after resolving rebase conflicts
- Use `skip` to skip the current commit that has conflicts

**git_remote**                                            *chat-tool-git_remote*

Manage set of tracked repositories (read-only).

Usage:
>
    @git_remote                                    -- List all remotes
    @git_remote action="get-url" name="origin"     -- Get origin URL
<

**git_reset**                                              *chat-tool-git_reset*

Reset current HEAD to the specified state.

Modes:
- `soft`: Moves HEAD only, keeps changes staged
- `mixed`: Moves HEAD, unstages changes (default)
- `hard`: Moves HEAD, discards all changes (use with caution!)

Usage:
>
    @git_reset commit="abc123" mode="soft"  -- Reset to commit, keep staged
    @git_reset mode="mixed"                 -- Unstage changes
    @git_reset mode="hard"                  -- Discard all changes
<

**git_stash**                                              *chat-tool-git_stash*

Stash changes in git repository.

Usage:
>
    @git_stash action="save" message="WIP"
    @git_stash action="list"
    @git_stash action="pop"
    @git_stash action="drop" index=2
<

**git_tag**                                                  *chat-tool-git_tag*

Manage git tags for marking specific commits.

Usage:
>
    @git_tag action="create" name="v1.0.0" message="Release 1.0"
    @git_tag action="list"
    @git_tag action="delete" name="v1.0.0"
    @git_tag action="push" name="v1.0.0"
<

**make**                                                        *chat-tool-make*

Run make targets and return results.

Usage:
>
    @make                           -- Run default target
    @make target="test"             -- Run make test
    @make target="build"            -- Run make build
    @make target="test" args=["-j4"] -- Run with options
    @make directory="./subproject"  -- Run in subdirectory
<

**get_history**                                          *chat-tool-get_history*

Get conversation history messages from the current session.

Usage:
>
    @get_history
    @get_history offset=0 limit=20
    @get_history offset=20 limit=20
    @get_history search="error"
    @get_history search="config" offset=0 limit=10
<

Parameters:
- `offset` - Starting index (0 = oldest, default: 0)
- `limit` - Number of messages to retrieve (default: 20, max: 50)
- `search` - Filter messages by keyword (case-insensitive)

**plan**                                                        *chat-tool-plan*

Plan mode for creating, managing, and reviewing task plans.

Actions:
- `create` - Create new plan with title and optional steps
- `show` - Show plan details by ID
- `list` - List plans (optional status filter, `include_project` for same-dir)
- `add` - Add step to existing plan
- `next` - Start next pending step
- `done` - Mark current/completed step as done
- `cancel_step` - Cancel a step (mark as cancelled)
- `delete_step` - Delete a step from plan
- `update_step` - Update step content
- `reorder_steps` - Reorder steps by providing ordered step IDs
- `pause` - Pause an in-progress plan
- `resume` - Resume a paused plan
- `review` - Review completed or abandoned plan with summary
- `update_title` - Update plan title
- `cancel` - Abandon a plan (mark as abandoned)
- `reopen` - Reopen a completed or abandoned plan
- `delete` - Delete a plan

Usage:
>
    @plan action="create" title="Implement feature X" steps=["Design API", "Write code", "Test"]
    @plan action="list"
    @plan action="list" include_project=true
    @plan action="next" plan_id="plan-20250110-xxxx"
    @plan action="done" plan_id="plan-20250110-xxxx" step_id=1 notes="Done"
    @plan action="cancel_step" plan_id="plan-xxxx" step_id=2 notes="No longer needed"
    @plan action="reorder_steps" plan_id="plan-xxxx" step_ids=[3, 1, 2]
    @plan action="pause" plan_id="plan-xxxx" pause_reason="Waiting for API"
    @plan action="cancel" plan_id="plan-xxxx" notes="Requirements changed"
    @plan action="reopen" plan_id="plan-xxxx"
    @plan action="review" plan_id="plan-xxxx" summary="Done" lessons=["L1"]
<

**user_profile**                                        *chat-tool-user_profile*

Manage user profiles (人物画像) for personalized assistance.

Actions: `get` (default), `update`, `list`, `delete`.

Usage:
>
    @user_profile action="get"
    @user_profile action="get" user_id="alice"
    @user_profile action="update" user_id="alice" content="# Profile..."
    @user_profile action="list"
    @user_profile action="delete" user_id="temp-user"
<

Can look up ANY user's profile by passing their `user_id`.

**schedule_task**                                    *chat-tool-schedule_task*

Schedule a task to be executed at a future time. Tasks persist across Neovim
restarts.

Actions: `create` (default), `list`, `cancel`.

Usage:
>
    @schedule_task action="create" message="Check server" delay_seconds=3600
    @schedule_task action="create" message="Daily summary" interval=86400 repeat_count=7
    @schedule_task action="create" message="定期检查" interval=1800 skip_if_busy=true
    @schedule_task action="list"
    @schedule_task action="cancel" task_id="1717200000-12345"
<

Parameters:
- `delay_seconds` - Delay in seconds (one-time, max 2592000/30 days)
- `trigger_at` - Unix timestamp (one-time, alternative to delay)
- `interval` - Interval in seconds for periodic tasks
- `repeat_count` - Max repetitions for periodic (nil = unlimited)
- `skip_if_busy` - Skip if session in progress (periodic only, default: false)

------------------------------------------------------------------------------
 7.3 Third-party Tools                                |chat-third-party-tools*

**zettelkasten_create**                          *chat-tool-zettelkasten_create*

Create new zettelkasten notes, provided by zettelkasten.nvim.

Usage:
>
    @zettelkasten_create title="Note title" content="Note content" tags=["tag1", "tag2"]
<

**zettelkasten_get**                              *chat-tool-zettelkasten_get*

Retrieve zettelkasten notes by tags, provided by zettelkasten.nvim.

Usage:
>
    @zettelkasten_get tags=["programming", "vim"]
<

**zettelkasten_update**                          *chat-tool-zettelkasten_update*

Update an existing zettelkasten note.

Actions: `update_title`, `add_tags`, `remove_tags`, `replace_text`.

Usage:
>
    @zk update id="2024-01-15-10-30-00" action="update_title" title="New Title"
    @zk update id="2024-01-15-10-30-00" action="add_tags" tags=["python", "web"]
    @zk update id="2024-01-15-10-30-00" action="replace_text" old_text="old" new_text="new"
<

------------------------------------------------------------------------------
 7.4 How to Use Tools                                  *chat-how-to-use-tools*

1. **Direct invocation**: Include the tool call directly in your message:
>
   Can you review this code? @read_file ./my_script.lua
<

2. **Multiple tools**: Combine multiple tools in a single message:
>
   Compare these two files: @read_file ./config1.json @read_file ./config2.json
<

3. **Natural integration**: The tool calls can be embedded naturally within
   your questions:
>
   What's wrong with this function? @read_file ./utils.lua
<

The AI assistant will process the tool calls, execute the specified operations,
and incorporate their results into its response.

------------------------------------------------------------------------------
 7.5 Custom Tools                                          *chat-custom-tools*

chat.nvim supports both synchronous and asynchronous custom tools. Users can
create `lua/chat/tools/<tool_name>.lua` file in their Neovim runtime path.

This module should provide at least two functions: `scheme()` and
`<tool_name>` function. The `scheme()` function returns a table describing the
tool's schema (name, description, parameters). The `<tool_name>` function is
the actual implementation that will be called when the tool is invoked.

**Synchronous Tool**: Returns `{ content = "..." }` or `{ error = "..." }`
directly.

**Asynchronous Tool**: Returns `{ jobid = <number> }` and calls
`ctx.callback({ content = "..." })` when done.

**Synchronous Tool Example:**

>
    local M = {}

    ---@param action { city: string, unit?: string }
    function M.get_weather(action)
      if not action.city or action.city == '' then
        return { error = 'City name is required for weather information.' }
      end

      -- ... synchronous implementation ...

      return { content = 'Weather in ...' }
    end

    function M.scheme()
      return {
        type = 'function',
        ['function'] = {
          name = 'get_weather',
          description = 'Get weather information for a specific city.',
          parameters = { ... },
        },
      }
    end

    return M
<

**Asynchronous Tool Example:**

For long-running operations, you can create asynchronous tools using `job.nvim`:
>
    local M = {}
    local job = require('job')

    ---@param action { url: string }
    ---@param ctx { cwd: string, session: string, callback: function }
    function M.fetch_data(action, ctx)
      if not action.url or action.url == '' then
        return { error = 'URL is required.' }
      end

      local stdout = {}
      local stderr = {}

      local jobid = job.start({
        'curl',
        '-s',
        action.url,
      }, {
        on_stdout = function(_, data)
          for _, v in ipairs(data) do
            table.insert(stdout, v)
          end
        end,
        on_stderr = function(_, data)
          for _, v in ipairs(data) do
            table.insert(stderr, v)
          end
        end,
        on_exit = function(id, code, signal)
          if code == 0 and signal == 0 then
            ctx.callback({
              content = table.concat(stdout, '\n'),
              jobid = id,
            })
          else
            ctx.callback({
              error = 'Failed to fetch data: ' .. table.concat(stderr, '\n'),
              jobid = id,
            })
          end
        end,
      })

      if jobid > 0 then
        return { jobid = jobid }
      else
        return { error = 'Failed to start job' }
      end
    end

    function M.scheme()
      return {
        type = 'function',
        ['function'] = {
          name = 'fetch_data',
          description = 'Fetch data from a URL asynchronously.',
          parameters = {
            type = 'object',
            properties = {
              url = {
                type = 'string',
                description = 'URL to fetch data from',
              },
            },
            required = { 'url' },
          },
        },
      }
    end

    return M
<

==============================================================================
 8. HTTP API                                                    *chat-http-api*

chat.nvim includes a built-in HTTP server that allows external applications
to send messages to your chat sessions.

------------------------------------------------------------------------------
 8.1 Enabling the HTTP Server                    |chat-enabling-the-http-server|

The HTTP server is automatically started when the `http.api_key` configuration
is set to a non-empty value:
>
    require('chat').setup({
      http = {
        host = '127.0.0.1',
        port = 7777,
        api_key = 'your-secret-key',
      },
    })
<

------------------------------------------------------------------------------
 8.2 API Endpoints                                       *chat-api-endpoints*

**Base URL**: `http://{host}:{port}/` (default: `127.0.0.1:7777`)

**Authentication**: All requests require the `X-API-Key` header containing your
configured API key (except `GET /session` HTML preview).

| Endpoint                  | Method | Description                                         |
| ------------------------- | ------ | --------------------------------------------------- |
| `/`                       | POST   | Send messages to a specified chat session           |
| `/sessions`               | GET    | Get a list of all sessions with details             |
| `/sessions/:id`           | GET    | Get details for a single session                    |
| `/sessions/:id/raw`       | GET    | Get raw cache JSON for a session                    |
| `/providers`              | GET    | Get a list of all supported AI providers and models |
| `/messages`               | GET    | Get messages for a session (requires `session`, optional `since`) |
| `/session/new`            | POST   | Create a new session                                |
| `/session/:id`            | DELETE | Delete a session                                    |
| `/session/:id/stop`       | POST   | Stop generation for a session                       |
| `/session/:id/clear`      | POST   | Clear all messages in a session                     |
| `/session/:id/retry`      | POST   | Retry the last message in a session                 |
| `/session/:id/provider`   | PUT    | Set provider for a session                          |
| `/session/:id/model`      | PUT    | Set model for a session                             |
| `/session/:id/cwd`        | PUT    | Set working directory for a session                 |
| `/session/:id/pin`        | PUT    | Set pin status for a session                        |
| `/session/:id/title`      | PUT    | Set title for a session                             |
| `/session`                | GET    | Get HTML preview of a session (no auth required)    |

Query Parameters for `/messages`:
- `session` (required): Session ID
- `since` (optional): 1-indexed message index, returns messages[index..end]

GET `/sessions`:
- **Success**: HTTP 200 OK, returns a JSON array of session objects
>
    [
      {
        "id": "2024-01-15-10-30-00",
        "title": "Help me write a Lua plugin...",
        "cwd": "/home/user/project",
        "provider": "openai",
        "model": "gpt-4o",
        "pin": false,
        "in_progress": false,
        "message_count": 15,
        "last_message": {
          "role": "assistant",
          "content": "Here's the code you requested...",
          "created": "2024-01-15T10:35:00"
        }
      }
    ]
<
POST `/session/new`:
- Create a new chat session
- **Optional Request Body**: `{"provider": "openai", "model": "gpt-4o"}`
- **Success**: HTTP 200 OK, returns the new session object
>
    {
      "id": "2024-01-15-12-00-00",
      "title": "",
      "cwd": "/home/user/project",
      "provider": "openai",
      "model": "gpt-4o",
      "in_progress": false,
      "message_count": 0,
      "last_message": null
    }
<
PUT `/session/:id/provider`:
- Set the provider for a session
- **Request Body**: `{"provider": "anthropic"}`
- **Success**: HTTP 204 No Content

PUT `/session/:id/model`:
- Set the model for a session
- **Request Body**: `{"model": "gpt-4o"}`
- **Success**: HTTP 204 No Content

PUT `/session/:id/cwd`:
- Set the working directory for a session
- **Request Body**: `{"cwd": "/path/to/project"}`
- **Success**: HTTP 204 No Content

PUT `/session/:id/pin`:
- Set the pin status for a session
- **Request Body**: `{"pin": true}` or `{"pin": false}`
- **Success**: HTTP 204 No Content

PUT `/session/:id/title`:
- Set a custom title for a session
- **Request Body**: `{"title": "My custom title"}`
- **Success**: HTTP 204 No Content

POST `/session/:id/stop`:
- Stop generation for a session
- **Success**: HTTP 204 No Content

POST `/session/:id/clear`:
- Clear all messages in a session (session preserved)
- **Success**: HTTP 204 No Content
- **In Progress**: HTTP 409 Conflict

POST `/session/:id/retry`:
- Retry the last user message
- Only works if the last message is not from the assistant
- **Success**: HTTP 204 No Content
- **No Message**: HTTP 400 Bad Request

DELETE `/session/:id`:
- Delete a session
- **Success**: HTTP 204 No Content
- **In Progress**: HTTP 409 Conflict

GET `/session`:
- Returns HTML preview (no authentication required)
- **Success**: HTTP 200 OK, returns HTML content
- **Missing ID**: HTTP 400 Bad Request
- **Session Not Found**: HTTP 404 Not Found

------------------------------------------------------------------------------
 8.3 Message Queue System                         *chat-message-queue-system*

Incoming messages are processed through an intelligent queue system:

1. Messages are immediately queued upon receipt
2. If the session is idle, the message is delivered instantly via
   `vim.schedule` - no timer delay
3. If the session is busy, a timer starts polling every 5 seconds
4. When the session becomes idle, queued messages are delivered in FIFO order
5. Once all messages are delivered, the timer stops automatically
6. If delivery fails, the message is retried up to 3 times before being dropped

------------------------------------------------------------------------------
 8.4 Usage Examples                                     *chat-usage-examples*

Using curl:
>
    # Send a message to a session
    curl -X POST http://127.0.0.1:7777/ \
      -H "X-API-Key: your-secret-key" \
      -H "Content-Type: application/json" \
      -d '{"session": "my-session", "content": "Hello from curl!"}'

    # Get all sessions
    curl -H "X-API-Key: your-secret-key" http://127.0.0.1:7777/sessions

    # Get session details
    curl -H "X-API-Key: your-secret-key" http://127.0.0.1:7777/sessions/2024-01-15-10-30-00

    # List providers
    curl -H "X-API-Key: your-secret-key" http://127.0.0.1:7777/providers

    # Create new session
    curl -X POST http://127.0.0.1:7777/session/new \
      -H "X-API-Key: your-secret-key" \
      -H "Content-Type: application/json" \
      -d '{"provider": "openai", "model": "gpt-4o"}'

    # Set title
    curl -X PUT http://127.0.0.1:7777/session/2024-01-15-10-30-00/title \
      -H "X-API-Key: your-secret-key" \
      -H "Content-Type: application/json" \
      -d '{"title": "My custom title"}'
<

Using Python:
>
    import requests

    # Send a message to a session
    url = "http://127.0.0.1:7777/"
    headers = {
        "X-API-Key": "your-secret-key",
        "Content-Type": "application/json"
    }
    data = {
        "session": "python-script",
        "content": "Message from Python script"
    }
    response = requests.post(url, json=data, headers=headers)
    print(f"Status: {response.status_code}")
<

------------------------------------------------------------------------------
 8.5 Security Considerations                   *chat-security-considerations*

1. **API Key Protection**: Keep your API key secure and never commit it to
   version control
2. **Network Security**: By default, the server binds to localhost (127.0.0.1).
   Only allow external access if you have proper network security measures
3. **Input Validation**: All incoming messages are validated for proper JSON
   format and required fields

==============================================================================
 9. Picker Integration                               *chat-picker-integration*

chat.nvim provides built-in picker sources for seamless integration with
picker.nvim. These sources allow you to quickly access and manage your chat
sessions, providers, and models.

Available Sources:

1. `chat` - Search through your chat history sessions
   - Displays the project name (cwd tail) and first message of each session
   - Quickly resume previous conversations
   - Quickly locate sessions by project

   Keyboard Shortcuts in chat picker:
   - `<CR>` (Enter): Open selected session
   - `<C-d>`: Delete selected session
   - `<C-o>`: Open HTML preview in browser

2. `chat_provider` - Switch between different AI providers
   - Dynamically change between supported providers
   - Real-time switching without restarting Neovim

3. `chat_model` - Select available models for the current provider
   - Lists all compatible models for your selected provider
   - Intelligent filtering based on provider capabilities

==============================================================================
 10. IM Integration                                         *chat-im-integration*

chat.nvim supports integration with multiple instant messaging platforms for
remote AI interaction.

Supported Platforms:

| Platform | Icon | Bidirectional | Features                                |
| -------- | ---- | ------------- | --------------------------------------- |
| Discord  | 💬   | ✅ Yes        | Full-featured bot with session binding  |
| Lark     | 🐦   | ✅ Yes        | Feishu/Lark bot with message polling    |
| DingTalk | 📱   | ✅ Yes*       | Webhook (one-way) or API (two-way)      |
| WeCom    | 💼   | ✅ Yes*       | Enterprise WeChat webhook or API        |
| Weixin   | 💬   | ✅ Yes*       | Personal WeChat via external API        |
| Telegram | ✈️   | ✅ Yes        | Bot API with group/private chat support |
| Slack    | 💼   | ✅ Yes        | Workspace bot with message polling      |

------------------------------------------------------------------------------
 10.1 Discord                                                 *chat-discord*

Discord integration allows you to interact with AI assistants via Discord
messages.

Features:
- **Bidirectional Communication**: Send messages from Discord to chat.nvim
  and receive responses
- **Session Binding**: Bind specific Discord channels to chat.nvim sessions
- **Automatic Polling**: Bot polls for new messages every 3 seconds
- **Long Message Support**: Auto-chunking for messages > 2,000 characters

Setup Guide:

1. Create Discord Application at https://discord.com/developers/applications
2. Create Bot User and copy the **Token**
3. Enable "Message Content Intent" under "Privileged Gateway Intents"
4. Get Channel ID (enable Developer Mode in Discord, right-click channel ->
   Copy ID)
5. Invite Bot to Server with required permissions
6. Configure chat.nvim:
>
    integrations = {
      discord = {
        token = 'YOUR_DISCORD_BOT_TOKEN',
        channel_id = 'YOUR_CHANNEL_ID',
      },
    }
<

Commands:
- `:Chat bridge discord` - Bind current chat.nvim session to Discord channel
- `/session` (in Discord) - Bind current Discord channel to active session
- `/clear` (in Discord) - Clear messages in the bound session

------------------------------------------------------------------------------
 10.2 Lark (Feishu)                                         *chat-lark*

Lark/Feishu integration for enterprise communication.

Features:
- **Bidirectional Communication**: Send and receive messages via Lark bot
- **Session Binding**: Bind Lark chats to chat.nvim sessions
- **Automatic Polling**: Polls for new messages every 3 seconds

Setup Guide:

1. Create Lark App at https://open.feishu.cn/app
2. Copy **App ID** and **App Secret**
3. Configure Bot Permissions:
   - `im:message.group_msg` - Get all messages in groups
   - `im:message` - Get and send messages in private chats and groups
4. Get Chat ID
5. Configure chat.nvim:
>
    integrations = {
      lark = {
        app_id = 'YOUR_APP_ID',
        app_secret = 'YOUR_APP_SECRET',
        chat_id = 'YOUR_CHAT_ID',
      },
    }
<

Commands:
- `:Chat bridge lark` - Bind current session to Lark chat

------------------------------------------------------------------------------
 10.3 DingTalk                                               *chat-dingtalk*

DingTalk integration with webhook or API mode.

Features:
- **Two Modes**: Webhook (simple, one-way) or API (bidirectional)
- **Message Queue**: Sequential message processing

Setup Guide (Webhook Mode):
1. Create a custom robot in DingTalk group
2. Copy the webhook URL
3. Configure:
>
    integrations = {
      dingtalk = {
        webhook = 'https://oapi.dingtalk.com/robot/send?access_token=XXX',
      },
    }
<

------------------------------------------------------------------------------
 10.4 WeCom                                                     *chat-wecom*

WeCom (Enterprise WeChat) integration with webhook or API mode.

Features:
- **Two Modes**: Webhook (simple, one-way) or API (bidirectional)
- **Corporate Integration**: Full enterprise WeChat support

Setup Guide (Webhook Mode):
1. Add a webhook robot in WeCom group
2. Copy the webhook key
3. Configure:
>
    integrations = {
      wecom = {
        webhook_key = 'YOUR_WEBHOOK_KEY',
      },
    }
<

------------------------------------------------------------------------------
 10.5 Weixin (Personal WeChat)                               *chat-weixin*

Weixin integration for personal WeChat accounts via QR code login.

Features:
- **QR Code Login**: Scan with WeChat to login
- **Auto Credential Caching**: Login credentials saved locally
- **Auto Reconnect**: Automatically reconnects on restart
- **Long Message Support**: Auto-chunking for messages > 2,048 characters

Setup Guide:

1. **First-Time Login**

   Run the following Lua command in Neovim:
>
    :lua require('chat.integrations.weixin').login()
<
   A QR code will be displayed in a floating window.

2. **Scan QR Code**

   - Open WeChat on your phone
   - Scan the QR code
   - Confirm login on your phone

3. **Done!**

   Login credentials are automatically saved to:
>
    stdpath('data')/chat-weixin-state.json
<
   Subsequent restarts will auto-connect using saved credentials.

Commands:
- `:lua require('chat.integrations.weixin').login()` - Start QR code login
- `:lua require('chat.integrations.weixin').logout()` - Logout and clear credentials
- `:lua require('chat.integrations.weixin').get_state()` - Check connection status

Technical Details:
- **API**: OpenClaw WeChat Gateway
- **Authentication**: QR Code Login (auto-refresh)
- **Message Limit**: 2,048 characters (auto-chunking)
- **State Persistence**: `stdpath('data')/chat-weixin-state.json`
- **Polling**: Long-poll every 3 seconds

------------------------------------------------------------------------------
10.6 Telegram                                               *chat-telegram*

Telegram bot integration with full feature support.

Features:
- **Full Bot API Support**: Works in groups and private chats
- **Markdown Support**: Send formatted messages with Markdown
- **Long Message Support**: Auto-chunking for messages > 4,096 characters

Setup Guide:

1. Create Telegram Bot: Open Telegram and search for `@BotFather`
2. Send `/newbot` command and follow instructions
3. Copy the **Bot Token**
4. Get Chat ID by visiting:
   `https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates`
5. Configure chat.nvim:
>
    integrations = {
      telegram = {
        bot_token = 'YOUR_BOT_TOKEN',
        chat_id = 'YOUR_CHAT_ID',
      },
    }
<

Commands:
- `:Chat bridge telegram` - Bind current session to Telegram chat
- `/session` (in Telegram) - Bind current Telegram chat to active session
- `/clear` (in Telegram) - Clear messages in the bound session

------------------------------------------------------------------------------
10.7 Slack                                                     *chat-slack*

Slack integration for workspace communication.

Features:
- **Bidirectional Communication**: Send and receive messages via Slack bot
- **Session Binding**: Bind Slack channels to chat.nvim sessions
- **Automatic Polling**: Polls for new messages every 3 seconds

Setup Guide:

1. Create Slack App at https://api.slack.com/apps
2. Configure Bot Permissions (required scopes):
   - `channels:history` - Read messages in channels
   - `chat:write` - Send messages
   - `groups:history` - Read messages in private channels
   - `im:history` - Read messages in direct messages
   - `mpim:history` - Read messages in multiparty direct messages
3. Install to Workspace and copy **Bot User OAuth Token** (starts with
   `xoxb-`)
4. Get Channel ID from URL or right-click channel -> "Copy Link"
5. Invite Bot to Channel: `/invite @YourBotName`
6. Configure chat.nvim:
>
    integrations = {
      slack = {
        bot_token = 'xoxb-YOUR-BOT-TOKEN',
        channel_id = 'CXXXXXXXXXX',
      },
    }
<

Commands:
- `:Chat bridge slack` - Bind current session to Slack channel

==============================================================================
 11. Self-Promotion                                       *chat-self-promotion*

Like this plugin? Star the repository on GitHub.

Love this plugin? Follow me (https://wsdjeg.net/) on
GitHub (https://github.com/wsdjeg).

==============================================================================
 12. Feedback                                                   *chat-feedback*

If you encounter any bugs or have suggestions, please file an issue in the
issue tracker: https://github.com/wsdjeg/chat.nvim/issues

==============================================================================
 13. License                                                   *chat-license*

This project is licensed under the GPL-3.0 License.

 vim:cc=78:tw=78:ts=4:sw=4:et:ft=help:norl:

