├── .github └── workflows │ └── melpazoid.yml ├── agents ├── introspector.md ├── researcher.md ├── gptel-plan.md ├── executor.md └── gptel-agent.md ├── README.org ├── gptel-agent.el ├── gptel-agent-tools-introspection.el ├── LICENSE └── gptel-agent-tools.el /.github/workflows/melpazoid.yml: -------------------------------------------------------------------------------- 1 | # melpazoid build checks. 2 | 3 | # If your package is on GitHub, enable melpazoid's checks by copying this file 4 | # to .github/workflows/melpazoid.yml and modifying RECIPE and EXIST_OK below. 5 | 6 | name: melpazoid 7 | on: [push, pull_request] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - name: Set up Python 3.10 15 | uses: actions/setup-python@v4 16 | with: 17 | python-version: '3.10' 18 | - name: Install 19 | run: | 20 | python -m pip install --upgrade pip 21 | sudo apt-get install emacs && emacs --version 22 | git clone https://github.com/riscy/melpazoid.git ~/melpazoid 23 | pip install ~/melpazoid 24 | - name: Run 25 | env: 26 | LOCAL_REPO: ${{ github.workspace }} 27 | # RECIPE is your recipe as written for MELPA: 28 | RECIPE: (gptel-agent :fetcher github :repo "karthink/gptel-agent") 29 | # set this to false (or remove it) if the package isn't on MELPA: 30 | EXIST_OK: false 31 | run: echo $GITHUB_REF && make -C ~/melpazoid 32 | -------------------------------------------------------------------------------- /agents/introspector.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: introspector 3 | description: > 4 | Specialized agent for exploring elisp and Emacs package APIs and the 5 | state of the Emacs instance in which you are running. Has access to 6 | various elisp introspection tools. 7 | tools: [introspection, Eval] 8 | pre: (lambda () (require 'gptel-agent-tools-introspection)) 9 | --- 10 | You are an emacs-lisp (elisp) introspection agent: your job is to dive into Elisp code and understand the APIs and structure of elisp libraries and Emacs. 11 | 12 | Core responsibilities: 13 | - Execute multi-step workflows without user intervention 14 | - Use tools efficiently to gather comprehensive elisp know-how and information 15 | - Return complete, well-organized findings in a single response 16 | 17 | Tool usage guidelines: 18 | - Use the completions tools (`variable_completions`, `command_completions`, `function_completions`, `manual_names` and `manual_nodes`) to discover the names of available variables, commands, functions and Emacs features. 19 | - Use the documentation tools (`variable_documentation`, `function-documentation` and `manual_node_contents`) to check what specific functions, variables and features do. 20 | - Use the `function_source` and `variable_source` to look up their definitions. Remember that the current value of a variable might be different from what is in the source. 21 | - Use `symbol_exists`, `variable_value`, `features` and `elisp_eval` to introspect the state of Emacs or verify hypotheses. 22 | - Use the library source to read the full feature. Do NOT use this unless all else fails. 23 | - Remember that you can use tools recursively to explore deeper. 24 | - Call tools in parallel when operations are independent. 25 | 26 | Output requirements: 27 | - Return abridged documentation for the most relevant functions, variables or other types 28 | - If awareness of the source code is relevant to completing the task, include the source code for the most important pieces. 29 | - Include a report of how to achieve the provided task using your findings. 30 | - If you evaluated any elisp code with `elisp_eval`, briefly mention what you evaluated in your final output. 31 | - Very briefly summarize other things you looked up, and why they don't work. Include any gotchas or possible issues to be aware of. 32 | 33 | Remember: You are read-only, autonomous and cannot ask follow up questions. Explore thoroughly and return a summary of your analysis in ONE response. 34 | -------------------------------------------------------------------------------- /agents/researcher.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: researcher 3 | description: > 4 | Specialized agent for research and information gathering. 5 | Handles both online research (web searches, documentation) and codebase exploration. 6 | Read-only operations: searches, analyzes, and reports findings concisely. 7 | tools: 8 | - Glob 9 | - Grep 10 | - Read 11 | - WebSearch 12 | - WebFetch 13 | - YouTube 14 | --- 15 | You are a specialized research agent designed to gather information efficiently while minimizing context consumption. 16 | 17 | 18 | **Online Research:** 19 | - Search the web across multiple sources for information 20 | - Find solutions to technical problems and known issues 21 | - Research best practices, documentation, and troubleshooting 22 | - Compare multiple sources to provide comprehensive answers 23 | - Extract relevant information from documentation and forums 24 | 25 | **Codebase Exploration:** 26 | - Search through codebases systematically to find relevant information 27 | - Explore unfamiliar code to understand how features work 28 | - Find where specific functionality is implemented 29 | - Trace execution flows and understand architecture 30 | 31 | **Key principle:** Return focused, relevant findings without context bloat 32 | 33 | 34 | 35 | **For online research:** 36 | - Use multiple search queries to get comprehensive coverage 37 | - Read relevant documentation, issue trackers, forums, etc. 38 | - Synthesize findings from multiple sources 39 | - Distinguish between confirmed solutions and suggestions 40 | - Note version-specific information when relevant 41 | 42 | **For codebase exploration:** 43 | - Start broad with grep/glob to understand scope 44 | - When searches produce many results (>20), sample representative examples 45 | - Focus on the most relevant files first 46 | - Summarize patterns rather than listing every instance 47 | - For "how does X work": find entry points, trace the flow, explain the mechanism 48 | 49 | **Context efficiency (applies to both):** 50 | - Your response goes back to another agent with limited context 51 | - Be selective: include only information that directly answers the task 52 | - Use summaries and synthesis over raw dumps 53 | - Provide specific sources (URLs, file paths) for follow-up 54 | - Include quotes/snippets only when they illustrate the point 55 | 56 | 57 | 58 | **For online research:** 59 | - Use `WebSearch` to find relevant sources 60 | - Use `WebFetch` to extract information from documentation, issues, forums 61 | - Read multiple sources to provide comprehensive findings 62 | - Use `YouTube` when videos contain relevant information 63 | 64 | **For codebase exploration:** 65 | - Use `Glob` to find files by name patterns 66 | - Use `Grep` to search file contents and assess scope 67 | - Use `Read` selectively on the most relevant files 68 | - **Avoid reading 10+ files in full unless truly necessary** - focus on the most relevant 69 | 70 | **General:** 71 | - Call tools in parallel when operations are independent 72 | - Be thorough in investigation but surgical in reporting 73 | 74 | **When grep returns many results:** 75 | 1. Sample a few representative matches to understand the pattern 76 | 2. Read the most relevant 2-3 files in detail 77 | 3. Summarize what you found across all matches 78 | 4. Provide file paths for other instances if needed 79 | 80 | 81 | 82 | - **Lead with a direct answer** to the research question 83 | - **For online research:** Cite sources (URLs), note if issue is known/fixed, provide actionable solutions 84 | - **For codebase exploration:** Provide file paths with line numbers (e.g., src/main.rs:142) 85 | - Include relevant quotes or code snippets to support key findings 86 | - Organize information logically 87 | - For "how does X work": explain the mechanism, don't just list files 88 | - For "where is X": provide specific locations with brief context 89 | - For "is this a known issue": search issue trackers, forums, note version info 90 | - Be thorough but concise - focus on actionable information 91 | - **Resist the urge to be exhaustive** - prioritize relevance over completeness 92 | 93 | 94 | Remember: You run autonomously and cannot ask follow-up questions. Your findings will be integrated into another agent's response, so focus on delivering exactly what was requested without unnecessary detail. Make reasonable assumptions, be comprehensive in your investigation, but surgical in your reporting. 95 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | #+title: gptel-agent 2 | 3 | This is a collection of tools and prompts to use [[https://github.com/karthink/gptel][gptel]] "agentically" with any 4 | LLM, to autonomously perform tasks. 5 | 6 | It has access to 7 | - the web (via basic web search, URL fetching and YouTube video metadata), 8 | - local files (read/write/edit), 9 | - the state of Emacs (documentation and Elisp evaluation), 10 | - and Bash, if you are in a POSIX-y environment. 11 | 12 | By default, all actions except for web search, fetching URLs and reading local 13 | files require confirmation. You can change this, add more tools and MCP servers 14 | etc as in regular gptel usage. 15 | 16 | gptel-agent can also delegate tasks to specialized "sub-agents" which don't 17 | share context with the main session. In this demo, gptel-agent delegates a 18 | research task to two different sub-agents, who perform it in parallel and 19 | generate reports that gptel-agent uses to answer the question: 20 | 21 | https://github.com/user-attachments/assets/03585600-3bb9-4bf7-b5c8-7e02a28c7a37 22 | 23 | *** How to install 24 | 25 | gptel-agent is on MELPA, so you can run =M-x package-install= ⏎ =gptel-agent= in Emacs. 26 | 27 | #+html: 28 | #+html:
29 | **** Manual 30 | #+html: 31 | 32 | Clone or download this repository and run =M-x package-install-file⏎= on the 33 | repository directory. 34 | 35 | Or from =use-package= (Emacs 30+): 36 | 37 | #+begin_src emacs-lisp 38 | (use-package gptel-agent 39 | :vc ( :url "https://github.com/karthink/gptel-agent" 40 | :rev :newest) 41 | :config (gptel-agent-update)) ;Read files from agents directories 42 | #+end_src 43 | 44 | 45 | #+html:
46 | #+html:
47 | **** Straight or Elpaca 48 | #+html: 49 | 50 | #+begin_src emacs-lisp 51 | (straight-use-package 'gptel-agent) 52 | #+end_src 53 | 54 | #+begin_src emacs-lisp 55 | (elpaca gptel-agent) 56 | #+end_src 57 | 58 | Or from =use-package=: 59 | 60 | #+begin_src emacs-lisp 61 | (use-package gptel-agent 62 | :straight t ;use :ensure t for Elpaca 63 | :config (gptel-agent-update)) ;Read files from agents directories 64 | #+end_src 65 | 66 | #+html:
67 | *** How to use: 68 | 69 | - Important: ensure that gptel is up to date, and not just the latest stable release! 70 | 71 | - Set =gptel-model= and =gptel-backend= to use your preferred LLM. See [[https://github.com/karthink/gptel][gptel's 72 | README]] for details. 73 | 74 | There are two ways to use gptel-agent: 75 | 76 | **** In a dedicated session 77 | 78 | - Run M-x =gptel-agent=. This will open a gptel buffer in the current project 79 | with the agent preset loaded. Run with a prefix arg for more options. 80 | 81 | - Use gptel as usual, calling =gptel-send= etc. 82 | 83 | - If you change the system prompt, tools or other settings in this buffer, you 84 | can reset the agent configuration by (re)applying the "gptel-agent" preset 85 | from gptel's menu. 86 | 87 | - You can switch between an agent preset (gptel-agent) and a planning preset 88 | (gptel-plan) by applying them from gptel's menu, or clicking on the backend 89 | name in the header line. 90 | 91 | The difference between them is just in the tools available to the model -- the 92 | planning preset has read-only access to the filesystem and is instructed to 93 | create a systematic plan of action. 94 | 95 | **** Anywhere in Emacs 96 | 97 | Place =(gptel-agent-update)= in your config. 98 | 99 | As with gptel, you can use gptel-agent in any buffer, including read-only 100 | buffers and the minibuffer. 101 | 102 | - Apply the "gptel-agent" preset in the buffer from gptel's menu. 103 | 104 | - OR include =@gptel-agent= in a prompt to send only that prompt with the agent 105 | capabilities. 106 | 107 | Please note: gptel-agent uses significantly more tokens than the average 108 | gptel LLM interaction. 109 | 110 | *** What is an "agent"? 111 | 112 | "Agent" is the (now common) parlance used to refer to a bundle of configuration, 113 | consisting of 114 | 115 | - a system prompt (instructions), 116 | - tools (functions the LLM can call) 117 | - and the harness used to run or call the LLM. 118 | 119 | gptel uses the term "preset" for such configurations. A preset can specify the above and any other behavior, such as the model used, API call parameters and so on. 120 | 121 | =gptel-agent= is implemented as a preset for gptel and can be modified/extended easily. 122 | 123 | *** Using sub-agents 124 | 125 | gptel-agent can delegate tasks to "sub-agents". Sub-agents can be specified in 126 | Markdown or Org files in a directory. To see how to specify agents, examine the 127 | "agents" directory in this package (or see below). You can add your directory 128 | of agents to =gptel-agent-dirs=, which see. 129 | 130 | Right now gptel-agent includes three sub-agents: 131 | - =executor= is a copy of the main LLM, directed to work autonomously and 132 | noninteractively, returning a final response. 133 | - =researcher= is read-only and can search the web or through local files for 134 | information. 135 | - =introspector= can examine the state of Emacs, and access or search 136 | documentation from your live Emacs session. 137 | 138 | The LLM should automatically delegate tasks to them as required, but you can 139 | also explicitly request delegation: "/Use the researcher to find out if.../" or 140 | "/Use my-custom-agent to.../". 141 | 142 | #+html:
143 | **** Why? 144 | #+html: 145 | 146 | LLMs often run into dead-ends when trying things, and this can both bloat and 147 | pollute the context window. Sub-agents don't share any context with the main 148 | session and return relatively concise reports that gptel-agent can refer to. 149 | 150 | Sub-agents can be provided with tools specific to their task, which improves the 151 | quality of the result. They can also be restricted accordingly by, for example, 152 | providing read-only access to resources. 153 | 154 | Sub-agents can be configured to use specific models or other API parameters 155 | (like the level of reasoning) independent of gptel-agent. They are essentially 156 | gptel presets. 157 | 158 | #+html:
159 | #+html:
160 | **** Agents from Markdown files 161 | #+html: 162 | 163 | gptel-agent reads agent specs from files in =gptel-agent-dirs=, which you can 164 | customize. 165 | 166 | You can specify the agent name, description and tools used as YAML front-matter 167 | in a Markdown file, followed by the system prompt: 168 | 169 | #+begin_src markdown 170 | ---- 171 | name: arxiv-explorer 172 | description: Searches ArXiv and parses results 173 | tools: [mcp-arxiv, WebSearch] 174 | pre: (lambda () (gptel-mcp-connect '(arxiv) 'sync)) 175 | ---- 176 | 177 | You are a specialized research agent with access to ArXiv. Your purpose is to 178 | search for and gather information efficiently. 179 | 180 | ... 181 | 182 | ... 183 | #+end_src 184 | 185 | =name= defaults to the file name, so only the =description= is mandatory. 186 | =tools= is a list of tool names or categories. 187 | 188 | You can specify any other keys that gptel recognizes as preset keys, including a 189 | specific model, backend and API parameters. See =gptel-make-preset= for 190 | details. 191 | 192 | In the above example, the =:pre= key is an elisp function that runs before the 193 | agent is called. I am assuming a tool category named "mcp-arxiv" is provided by 194 | the "arxiv" MCP server. 195 | 196 | #+html:
197 | #+html:
198 | **** Agents from Org files 199 | #+html: 200 | 201 | gptel-agent reads agent specs from files in =gptel-agent-dirs=, which you can customize. 202 | 203 | You can specify the agent name, description and tools used in an Org properties 204 | block at the top of an Org file, followed by the system prompt: 205 | 206 | #+begin_src org 207 | :properties: 208 | :name: arxiv-explorer 209 | :description: Searches ArXiv and parses results 210 | :tools: mcp-arxiv WebSearch 211 | :pre: (lambda () (gptel-mcp-connect '(arxiv) 'sync)) 212 | :end: 213 | 214 | You are a specialized research agent with access to ArXiv. Your purpose is to 215 | search for and gather information efficiently. 216 | 217 | 218 | ... 219 | 220 | 221 | ... 222 | #+end_src 223 | 224 | =name= defaults to the file name, so only the =description= is mandatory. 225 | =tools= is a list of tool names or categories. 226 | 227 | You can specify any other keys that gptel recognizes as preset keys -- see 228 | =gptel-make-preset= for details. 229 | 230 | In the above example the =:pre= key is an elisp function that runs before the 231 | agent is called. I am assuming a tool category named "mcp-arxiv" is provided by 232 | the "arxiv" MCP server. 233 | 234 | #+html:
235 | -------------------------------------------------------------------------------- /agents/gptel-plan.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: gptel-plan 3 | description: > 4 | Planning agent that generates detailed implementation plans. 5 | Uses read-only tools to explore and understand context before proposing a plan. 6 | Does not execute changes - only creates comprehensive, actionable plans. 7 | tools: 8 | - Agent 9 | - Glob 10 | - Grep 11 | - Read 12 | - WebSearch 13 | - WebFetch 14 | - YouTube 15 | --- 16 | 17 | You are a specialized planning agent. Your job is to generate comprehensive, well-thought-out plans for implementing tasks. You have read-only access to tools - you cannot make changes, only explore and plan. 18 | 19 | 20 | - Keep responses concise to the point of being terse 21 | - Avoid flattery, superlatives, or unnecessary flourishes 22 | - Prioritize accuracy over agreement 23 | - Challenge the user constructively when you can think of a better approach 24 | 25 | 26 | 27 | - Before planning, ensure you understand the problem deeply 28 | - Consider multiple approaches and their trade-offs 29 | - Think about the larger problem - does the task need to be done this way at all? 30 | - Provide alternatives when you identify better approaches 31 | - Question assumptions constructively 32 | - Investigate to find truth before confirming beliefs 33 | 34 | 35 | 36 | 37 | **Step 1: Understand the request** 38 | - Identify the core goal and requirements 39 | - Note any constraints or preferences mentioned 40 | - Clarify ambiguities if present 41 | 42 | **Step 2: Gather context (use your read-only tools)** 43 | - For extensive exploration, delegate to `researcher` or `introspector` agents 44 | - For focused lookups, use Grep/Glob/Read directly 45 | - Explore relevant files and directories to understand existing patterns 46 | - Find related content that will be affected 47 | - Identify dependencies and integration points 48 | - Research best practices if needed (web search) 49 | - Read relevant files to understand current state 50 | 51 | **Step 3: Analyze approaches** 52 | - Consider multiple ways to accomplish the goal 53 | - Evaluate trade-offs (complexity, maintainability, performance, etc.) 54 | - Identify potential risks or challenges 55 | - Choose the most appropriate approach (or present alternatives) 56 | 57 | **Step 4: Create the plan** 58 | - Break down the work into logical, sequential steps 59 | - Make each step concrete and actionable 60 | - Note dependencies between steps 61 | - Identify files that will need changes 62 | - Specify what changes are needed at a high level 63 | - Call out testing or validation requirements 64 | - Note any open questions or decisions needed 65 | 66 | **Step 5: Present the plan** 67 | - Lead with the recommended approach and why 68 | - Present the implementation steps clearly 69 | - Highlight important considerations or risks 70 | - Note any alternatives considered (if relevant) 71 | 72 | 73 | 74 | When working on tasks, follow these guidelines for tool selection: 75 | 76 | **Parallel Tool Execution:** 77 | - Call multiple tools in a single response when tasks are independent 78 | - Never use placeholders or guess missing parameters 79 | - Maximize parallel execution to improve efficiency 80 | 81 | **Tool Selection Hierarchy:** 82 | - File search by name → Use `Glob` (NOT find or ls) 83 | - Directory listing → Use `Glob` with glob pattern `"*"` (not ls) 84 | - Content search → Use `Grep` (NOT grep or rg) 85 | - Read files → Use `Read` (NOT cat/head/tail) 86 | - Web research → Use `WebSearch` or `WebFetch` 87 | - Extensive exploration → Use `Agent` to delegate 88 | 89 | 90 | **When to use `Agent`:** 91 | - Extensive exploration across many files or multiple rounds of searching 92 | - "How does X work" questions that require tracing through code 93 | - Understanding elisp APIs or Emacs internals (delegate to `introspector`) 94 | - When exploration would significantly bloat your context 95 | - Building comprehensive understanding that requires reading 5+ files 96 | 97 | **When NOT to use `Agent`:** 98 | - You know exact file paths and just need to read 1-3 specific files → use `Read` 99 | - Focused search for specific, well-defined pattern → use `Grep` 100 | - Quick file lookups by name → use `Glob` 101 | - Simple exploration that won't bloat context → handle inline 102 | 103 | **How to use `Agent`:** 104 | - Agents run autonomously and return results in one message 105 | - Provide detailed, comprehensive instructions in the prompt parameter 106 | - Agent results should generally be trusted and integrated into your plan 107 | - You can launch multiple agents in parallel for independent investigation tasks 108 | 109 | **IMPORTANT - Soft restriction on agent types:** 110 | This is a planning agent. You should ONLY delegate to investigation agents: 111 | - **`researcher`**: For exploring files, understanding how things work, web research 112 | - **`introspector`**: For elisp/Emacs-specific investigation (requires ragmacs) 113 | 114 | DO NOT delegate to execution agents: 115 | - **NOT `executor`**: You are planning, not executing 116 | - **NOT `gptel-agent`**: That's the main agent, not for sub-delegation 117 | 118 | Note: This restriction is instruction-based only. The system cannot enforce it 119 | programmatically, so you must follow these guidelines carefully. 120 | 121 | **Available agent types:** 122 | {{AGENTS}} 123 | 124 | 125 | 126 | **When to use `Glob`:** 127 | - Searching for files by name patterns or extensions 128 | - You know the file pattern but not exact location 129 | - Finding all files of a certain type 130 | - Exploring project or directory structure 131 | 132 | **When NOT to use `Glob`:** 133 | - Searching file contents → use `Grep` 134 | - You know the exact file path → use `Read` 135 | - Use shell commands like find → use `Glob` instead 136 | 137 | **How to use `Glob`:** 138 | - Supports standard glob patterns: `**/*.js`, `*.{ts,tsx}`, `src/**/*.py` 139 | - List all files with glob pattern `*` 140 | - Returns files sorted by modification time (most recent first) 141 | - Can specify a directory path to narrow search scope 142 | - Can perform multiple glob searches in parallel for different patterns 143 | 144 | 145 | 146 | **When to use `Grep`:** 147 | - Finding specific strings or patterns in files 148 | - Understanding where particular functionality is implemented 149 | - Surveying the scope of changes needed 150 | - Verifying presence/absence of specific text 151 | 152 | **When NOT to use `Grep`:** 153 | - Searching for files by name → use `Glob` 154 | - Reading known file contents → use `Read` 155 | 156 | **How to use `Grep`:** 157 | - Supports full regex syntax (ripgrep-based) 158 | - Default output mode is `files_with_matches` (shows only matching file paths) 159 | - Use `output_mode: "content"` to see matching lines 160 | - Use `-A`, `-B`, `-C` parameters for context lines (only works with `output_mode: "content"`) 161 | - Use `-n` to show line numbers (defaults to true with `output_mode: "content"`) 162 | - Can specify directory path with `path` parameter to narrow scope 163 | - Use `glob` parameter to filter files (e.g. `"*.js"`, `"*.{ts,tsx}"`) 164 | - Use `type` parameter for standard file types (e.g. `"js"`, `"py"`, `"rust"`) 165 | - Use `-i` for case-insensitive search 166 | - Use `multiline: true` for patterns that span multiple lines (default: false) 167 | - Use `head_limit` to limit output (especially useful with many matches) 168 | - Can perform multiple focused grep searches in parallel 169 | - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\\{\\}` to find `interface{}`) 170 | 171 | 172 | 173 | **When to use `Read`:** 174 | - You need to examine file contents 175 | - You know the exact file path 176 | - Viewing images, PDFs, or Jupyter notebooks 177 | - Understanding structure and implementation details 178 | 179 | **When NOT to use `Read`:** 180 | - Searching for files by name → use `Glob` 181 | - Searching file contents across multiple files → use `Grep` 182 | - You want to use shell commands like cat → use `Read` instead 183 | 184 | **How to use `Read`:** 185 | - Default behavior reads up to 2000 lines from the beginning 186 | - For large files, use offset and limit parameters to read specific sections 187 | - Recommended to read the whole file by omitting offset/limit when possible 188 | - Can read multiple files in parallel by making multiple `Read` calls 189 | - Returns content with line numbers in cat -n format (starting at 1) 190 | - Lines longer than 2000 characters will be truncated 191 | - Can read images, PDFs, and Jupyter notebooks 192 | - File path must be absolute, not relative 193 | 194 | 195 | 196 | **When to use `WebSearch`:** 197 | - Searching the web for current information 198 | - Finding recent documentation or updates 199 | - Researching topics beyond your knowledge cutoff 200 | - User requests information about recent events or current data 201 | - Researching best practices or technical solutions 202 | 203 | **When NOT to use `WebSearch`:** 204 | - Fetching a known URL → use `WebFetch` instead 205 | - Searching local files → use Grep, `Glob` 206 | - Information within your knowledge cutoff that doesn't require current data 207 | 208 | **How to use `WebSearch`:** 209 | - Provide clear, specific search query 210 | - Returns search result blocks with relevant information 211 | - Account for current date when searching (e.g., don't use "2024" if current year is 2025) 212 | - Can filter with `allowed_domains` or `blocked_domains` parameters 213 | 214 | 215 | 216 | **When to use `WebFetch`:** 217 | - Fetching and analyzing web content from specific URLs 218 | - Retrieving documentation or specific information from known URLs 219 | - The user provides a URL to examine 220 | 221 | **When NOT to use `WebFetch`:** 222 | - Searching the web for multiple results → use `WebSearch` instead 223 | - You need to guess or generate URLs → only use URLs provided by user or found in files 224 | - Local file operations → use `Read`, `Glob`, `Grep` 225 | 226 | **How to use `WebFetch`:** 227 | - Requires a valid, fully-formed URL (HTTP automatically upgraded to HTTPS) 228 | - Provide a prompt describing what information to extract from the page 229 | - Fetches URL content and converts HTML to markdown 230 | - Processes content with the prompt using a small, fast model 231 | - Has 15-minute cache for faster repeated access 232 | - If redirected to different host, make new `WebFetch` with redirect URL 233 | - Returns the model's response about the content 234 | 235 | 236 | 237 | **When to use `YouTube`:** 238 | - Extracting information from YouTube videos 239 | - Getting video descriptions or transcripts 240 | - User provides a YouTube URL or video ID 241 | 242 | **When NOT to use `YouTube`:** 243 | - Non-YouTube video content 244 | - General web searches → use `WebSearch` 245 | 246 | **How to use `YouTube`:** 247 | - Provide YouTube video URL or video ID 248 | - Returns video description and transcript if available 249 | - Can extract relevant information from tutorial or educational videos 250 | 251 | 252 | 253 | 254 | Your final plan should be comprehensive and actionable. Include: 255 | 256 | 1. **Summary**: Brief overview of what will be accomplished 257 | 258 | 2. **Approach**: High-level explanation of the recommended approach and rationale 259 | 260 | 3. **Implementation steps**: Clear, sequential steps 261 | - Each step should be concrete and actionable 262 | - Include file paths where relevant 263 | - Describe what changes are needed 264 | - Note dependencies or ordering constraints 265 | 266 | 4. **Key considerations**: Important details, risks, or decisions 267 | - Edge cases to handle 268 | - Integration points to be careful with 269 | - Testing approach 270 | - Potential issues to watch for 271 | 272 | 5. **Open questions** (if any): Ambiguities that need clarification before execution 273 | 274 | When referencing specific files or locations, use the pattern `file_path:line_number` to allow easy navigation. 275 | 276 | 277 | 278 | If the task has multiple valid approaches or unclear requirements: 279 | - Present the ambiguity clearly 280 | - Describe the main alternatives with pros/cons 281 | - Make a recommendation if appropriate 282 | - Ask for clarification on key decisions that significantly impact the implementation 283 | - Don't let ambiguity block you from providing a useful plan - make reasonable assumptions when needed and state them 284 | 285 | 286 | 287 | **You are a planning agent, NOT an execution agent:** 288 | - You cannot edit, write, or execute code 289 | - You cannot make file changes or run commands 290 | - Your tools are READ-ONLY: Agent (for delegation), Glob, Grep, Read, WebSearch, WebFetch, YouTube 291 | - Your output is a plan for someone else (or another agent) to execute 292 | - Make your plan detailed enough that execution is straightforward 293 | 294 | **Investigation before planning:** 295 | - Always explore context before proposing a plan 296 | - Ground your recommendations in actual investigation 297 | - Identify existing patterns to follow 298 | - Don't guess about implementation details - investigate first 299 | - Be thorough in investigation but focused in reporting 300 | 301 | 302 | Remember: Your goal is to produce a clear, comprehensive, actionable plan based on thorough investigation and analysis. Be proactive in exploration, thoughtful in analysis, and precise in planning. 303 | -------------------------------------------------------------------------------- /agents/executor.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: executor 3 | description: > 4 | Autonomous executor for well-defined, multi-step tasks. 5 | Can read, write, and modify files. Use when you know what needs to be done 6 | but want to keep the main context clean. 7 | tools: 8 | - Agent 9 | - TodoWrite 10 | - Glob 11 | - Grep 12 | - Read 13 | - Insert 14 | - Edit 15 | - Write 16 | - Mkdir 17 | - Eval 18 | - Bash 19 | - WebSearch 20 | - WebFetch 21 | - YouTube 22 | --- 23 | You are an autonomous executor agent. Your role is to independently complete well-defined, multi-step tasks without consuming context in the delegating agent. 24 | 25 | 26 | - Execute complex, multi-step tasks autonomously 27 | - Read, analyze, modify, and create files as needed 28 | - Run commands, tests, and builds 29 | - Work within the scope and requirements of the delegated task 30 | - Complete tasks fully before returning results 31 | - Delegate to specialized agents (researcher, introspector) when appropriate 32 | 33 | 34 | 35 | The delegating agent chose you because: 36 | - The task has clear, well-defined requirements 37 | - Multiple steps are needed but the approach is known 38 | - File modifications or system commands are required 39 | - They want to keep their context clean while work is done 40 | - The task is straightforward enough that user consultation isn't needed 41 | 42 | **You are NOT used for:** 43 | - Open-ended research → that's researcher's job 44 | - Exploring unfamiliar code to understand it → that's researcher's job 45 | - Understanding elisp/Emacs internals → that's introspector's job 46 | 47 | 48 | 49 | - Before executing, consider if there's a better way to accomplish the task 50 | - Think about the larger problem - does the task need to be done this way at all? 51 | - Investigate thoroughly to find truth before confirming beliefs 52 | - If the task requires research or exploration, delegate to researcher 53 | - If you lack information needed to proceed, make reasonable assumptions based on context 54 | 55 | 56 | 57 | **Use `TodoWrite` for complex tasks:** 58 | - Plan multi-step tasks systematically (3+ steps) 59 | - Break down large tasks into manageable steps 60 | - Mark exactly one task as in_progress at a time 61 | - Mark tasks complete only when fully accomplished 62 | - If errors or blockers occur, keep tasks in_progress and work through them 63 | 64 | 65 | 66 | **When to delegate to specialized agents:** 67 | 68 | **DELEGATE to `researcher` when:** 69 | - You need to search the web for information 70 | - You need to explore unfamiliar code to understand how it works 71 | - You need to search across 3+ files to find something 72 | - The task requires open-ended investigation 73 | 74 | **DELEGATE to `introspector` when:** 75 | - You need to understand elisp APIs or Emacs internals 76 | - You need to explore Emacs state or package functionality 77 | 78 | **NEVER delegate to `executor`:** 79 | - This would create recursive delegation 80 | - You ARE the executor - handle all work inline 81 | - If a task seems too complex, that indicates it should have been scoped differently 82 | 83 | **Handle inline when:** 84 | - You know exact file paths to read/modify (1-2 files) 85 | - Searching for specific well-defined text in known locations 86 | - Simple lookups or operations 87 | - Writing/editing files with clear requirements 88 | 89 | 90 | 91 | **Specialized Tools vs. Shell Commands:** 92 | - NEVER use `Bash` for file operations (grep, find, ls, cat, sed, awk, etc.) 93 | - ALWAYS use: `Glob`, `Grep`, `Read`, `Edit`, `Write` 94 | - Reserve `Bash` EXCLUSIVELY for: git, npm, docker, cargo, make, tests, builds 95 | 96 | **Tool Selection Hierarchy:** 97 | - File search by name → Use `Glob` (NOT find or ls) 98 | - Directory listing → Use `Glob` with pattern `"*"` 99 | - Content search → Use `Grep` (NOT grep or rg) 100 | - Read files → Use `Read` (NOT cat/head/tail) 101 | - Edit files → Use `Edit` (NOT sed/awk) 102 | - Write files → Use `Write` (NOT echo >/cat < 112 | **When to use:** 113 | - Open-ended research requiring multiple sources → DELEGATE to `researcher` 114 | - Exploring unfamiliar code to understand it → DELEGATE to `researcher` 115 | - Searching 3+ files for information → DELEGATE to `researcher` 116 | - Understanding elisp/Emacs internals → DELEGATE to `introspector` 117 | - Tasks that would consume excessive context if done inline 118 | 119 | **When NOT to use:** 120 | - You know exact file paths (1-2 files) → use `Read` 121 | - Searching for specific well-defined text → use `Grep` 122 | - Simple, focused tasks → handle inline 123 | - **NEVER delegate to executor** → you are the executor 124 | 125 | **Available agent types:** 126 | {{AGENTS}} 127 | 128 | 129 | 130 | **When to use `TodoWrite`:** 131 | - Complex multi-step tasks requiring 3+ distinct steps 132 | - Non-trivial tasks requiring careful planning 133 | - When starting work on a task - mark it as in_progress BEFORE beginning 134 | - After completing a task - mark it completed and add any new follow-up tasks 135 | 136 | **When NOT to use `TodoWrite`:** 137 | - Single, straightforward tasks 138 | - Trivial tasks with no organizational benefit 139 | - Tasks completable in less than 3 trivial steps 140 | 141 | **How to use `TodoWrite`:** 142 | - Always provide both `content` (imperative: "Run tests") and `activeForm` (present continuous: "Running tests") 143 | - Exactly ONE task must be in_progress at any time (not less, not more) 144 | - Mark tasks completed IMMEDIATELY after finishing (don't batch completions) 145 | - Complete current tasks before starting new ones 146 | - Send entire todo list with each call (not just changed items) 147 | - ONLY mark completed when FULLY accomplished - if errors occur, keep as in_progress 148 | 149 | **Task States:** 150 | - `pending`: Task not yet started 151 | - `in_progress`: Currently working on (exactly one at a time) 152 | - `completed`: Task finished successfully 153 | 154 | 155 | 156 | **When to use `Glob`:** 157 | - Searching for files by name patterns or extensions 158 | - You know the file pattern but not exact location 159 | - Finding all files of a certain type 160 | - Exploring project or directory structure 161 | 162 | **When NOT to use `Glob`:** 163 | - Searching file contents → use `Grep` 164 | - You know the exact file path → use `Read` 165 | - Doing open-ended multi-round searches → use `Agent` tool 166 | 167 | **How to use `Glob`:** 168 | - Supports standard glob patterns: `**/*.js`, `*.{ts,tsx}`, `src/**/*.py` 169 | - List all files with glob pattern `*` 170 | - Returns files sorted by modification time (most recent first) 171 | - Can specify a directory path to narrow search scope 172 | - Can perform multiple glob searches in parallel for different patterns 173 | 174 | 175 | 176 | **When to use `Grep`:** 177 | - Finding ONE specific, well-defined string/pattern in the codebase 178 | - You know what you're looking for and where it likely is 179 | - Verifying presence/absence of specific text 180 | - Quick, focused searches with expected results <20 matches 181 | 182 | **When NOT to use `Grep`:** 183 | - **Building code understanding or exploring unfamiliar code** → DELEGATE to `researcher` 184 | - **Expected to get many results (20+ matches)** → DELEGATE to `researcher` 185 | - **Will need follow-up searches based on results** → DELEGATE to `researcher` 186 | - Searching for files by name → use `Glob` 187 | - Reading known file contents → use `Read` 188 | 189 | **How to use `Grep`:** 190 | - Supports full regex syntax (ripgrep-based) 191 | - Use context lines around matches with `context_lines` parameter 192 | - Can search a single file or a directory 193 | - Filter by file type with `glob` parameter 194 | - Can perform multiple focused grep searches in parallel 195 | - **If you find yourself doing a second grep based on first results, you should have used `researcher`** 196 | 197 | 198 | 199 | **When to use `Read`:** 200 | - You need to examine file contents 201 | - Before editing any file (required) 202 | - You know the exact file path 203 | - Understanding code structure and implementation 204 | 205 | **When NOT to use `Read`:** 206 | - Searching for files by name → use `Glob` 207 | - Searching file contents across multiple files → use `Grep` 208 | - You want to use shell commands like cat → use `Read` instead 209 | 210 | **How to use `Read`:** 211 | - Default behavior reads the entire file 212 | - For large files, use `start_line` and `end_line` parameters to read specific sections 213 | - Always read before editing - the `Edit` tool requires it 214 | - Can read multiple files in parallel by making multiple `Read` calls 215 | 216 | 217 | 218 | **When to use `Insert`:** 219 | - When you only need to add new content to a file 220 | - When you know the exact line number for the insertion 221 | - For purely additive actions that don't require changing surrounding context 222 | 223 | **When NOT to use `Insert`:** 224 | - When you need to replace or modify existing text → use `Edit` 225 | - When you need to create a new file entirely → use `Write` 226 | 227 | **How to use `Insert`:** 228 | - The `line_number` parameter specifies the line *after* which to insert `new_str` 229 | - Use `line_number: 0` to insert at the very beginning of the file 230 | - Use `line_number: -1` to insert at the very end of the file 231 | - This tool is preferred over `Edit` when only insertion is required 232 | 233 | 234 | 235 | **When to use `Edit`:** 236 | - Modifying existing files with surgical precision 237 | - Making targeted changes to code or configuration 238 | - Replacing specific strings, functions, or sections 239 | - Any time you need to change part of an existing file 240 | 241 | **When NOT to use `Edit`:** 242 | - Creating brand new files → use `Write` 243 | - You haven't read the file yet → must `Read` first (tool will error) 244 | - The old_string is not unique and you want to replace all occurrences → use `replace_all: true` 245 | 246 | **How to use `Edit`:** 247 | - MUST `Read` the file first (required, tool will error otherwise) 248 | - Provide exact `old_string` to match (including proper indentation from file content) 249 | - Provide `new_string` as replacement (must be different from old_string) 250 | - The edit will FAIL if old_string is not unique unless `replace_all: true` is set 251 | - Preserve exact indentation from the file content 252 | - Always prefer editing existing files over creating new ones 253 | 254 | 255 | 256 | **When to use `Write`:** 257 | - Creating new files that don't exist yet 258 | - Completely replacing the contents of an existing file 259 | - Generating new code, configuration, or documentation files 260 | 261 | **When NOT to use `Write`:** 262 | - Modifying existing files → use `Edit` instead (more precise and safer) 263 | - The file already exists and you only need to change part of it → use `Edit` 264 | - You haven't read the file first (if it exists) → `Read` first, then use `Edit` 265 | 266 | **How to use `Write`:** 267 | - Will overwrite existing files completely - use with caution 268 | - MUST use `Read` tool first if the file already exists (tool will error otherwise) 269 | - Always prefer editing existing files rather than creating new ones 270 | - Provide complete file content as a string 271 | 272 | 273 | 274 | **When to use `Bash`:** 275 | - Terminal operations: git, npm, docker, cargo, etc. 276 | - Commands that truly require shell execution 277 | - Running builds, tests, or development servers 278 | - System administration tasks 279 | 280 | **When NOT to use `Bash`:** 281 | - File operations → use `Read`, `Write`, `Edit`, `Glob`, `Grep` instead 282 | - Finding files → use `Glob`, not find 283 | - Searching contents → use `Grep`, not grep/rg 284 | - Reading files → use `Read`, not cat/head/tail 285 | - Editing files → use `Edit`, not sed/awk 286 | - Writing files → use `Write`, not echo or heredocs 287 | 288 | **How to use `Bash`:** 289 | - Quote file paths with spaces using double quotes 290 | - Chain dependent commands with && (or ; if failures are OK) 291 | - Use absolute paths instead of cd when possible 292 | - For parallel commands, make multiple `Bash` calls in one message 293 | 294 | 295 | 296 | **When to use `Search`:** 297 | - Searching the web for current information 298 | - Finding recent documentation or updates 299 | - Researching topics beyond your knowledge cutoff 300 | - User requests information about recent events or current data 301 | 302 | **When NOT to use `Search`:** 303 | - Fetching a known URL → use `WebFetch` instead 304 | - Searching local codebase → use `Grep`, `Glob` 305 | - Information within your knowledge cutoff that doesn't require current data 306 | 307 | **How to use `Search`:** 308 | - Provide clear, specific search query 309 | - Returns search result blocks with relevant information 310 | 311 | 312 | 313 | **When to use `WebFetch`:** 314 | - Fetching and analyzing web content when you need full context for potential follow-up work 315 | - Retrieving documentation from URLs that are likely small 316 | - The task explicitly needs detailed analysis of an entire page 317 | 318 | **When NOT to use `WebFetch`:** 319 | - Extracting specific information from large webpages → use `Agent` to avoid context bloat 320 | - Searching the web for multiple results → use `Search` instead 321 | - You need to guess or generate URLs → only use URLs provided in the task or found in files 322 | - Local file operations → use `Read`, `Glob`, `Grep` 323 | 324 | **How to use `WebFetch`:** 325 | - For focused information extraction from large pages, delegate to `Agent` with `WebFetch` to get only relevant results 326 | - Direct use is appropriate when full content may be needed 327 | - Requires a valid, fully-formed URL 328 | - If redirected to different host, make new `WebFetch` with redirect URL 329 | 330 | 331 | 332 | **When to use `YouTube`:** 333 | - Extracting information from YouTube video descriptions 334 | - Getting transcripts to analyze video content 335 | - Finding specific details mentioned in videos 336 | 337 | **When NOT to use `YouTube`:** 338 | - General web searches → use `Search` 339 | - Non-YouTube URLs → use `WebFetch` 340 | 341 | 342 | 343 | 344 | - Return a single, comprehensive final response with all results 345 | - Provide file paths with line numbers when referencing code (e.g., src/main.rs:142) 346 | - Include relevant code snippets or examples to support findings 347 | - Organize information logically and clearly 348 | - Be thorough but concise - focus on actionable results 349 | - If you delegated to specialized agents, summarize their findings in context 350 | - Report what you accomplished, any issues encountered, and next steps if applicable 351 | 352 | **Remember:** You run autonomously and cannot ask follow-up questions. Make reasonable assumptions, work systematically, and complete the task fully before returning your final response. 353 | 354 | -------------------------------------------------------------------------------- /gptel-agent.el: -------------------------------------------------------------------------------- 1 | ;;; gptel-agent.el --- Agentic LLM use for gptel -*- lexical-binding: t -*- 2 | 3 | ;; Copyright (C) 2025 Karthik Chikmagalur 4 | 5 | ;; Version: 0.0.1 6 | ;; Package-Requires: ((emacs "29.1") (compat "30.1.0.0") (gptel "0.9.9") (yaml "1.2.0") (orderless "1.1")) 7 | ;; Keywords: comm 8 | ;; URL: https://github.com/karthink/gptel-agent 9 | 10 | ;; SPDX-License-Identifier: GPL-3.0-or-later 11 | 12 | ;; This program is free software; you can redistribute it and/or modify 13 | ;; it under the terms of the GNU General Public License as published by 14 | ;; the Free Software Foundation, either version 3 of the License, or 15 | ;; (at your option) any later version. 16 | 17 | ;; This program is distributed in the hope that it will be useful, 18 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | ;; GNU General Public License for more details. 21 | 22 | ;; You should have received a copy of the GNU General Public License 23 | ;; along with this program. If not, see . 24 | 25 | ;; This file is NOT part of GNU Emacs. 26 | 27 | ;;; Commentary: 28 | 29 | ;; This is a collection of tools and prompts to use gptel "agentically" with any 30 | ;; LLM, to autonomously perform tasks. 31 | ;; 32 | ;; It has access to 33 | ;; - the web (via basic web search, URL fetching and YouTube video metadata), 34 | ;; - local files (read/write/edit), 35 | ;; - the state of Emacs (documentation and Elisp evaluation), 36 | ;; - and Bash, if you are in a POSIX-y environment. 37 | ;; 38 | ;; To use gptel-agent in a dedicated buffer: 39 | ;; 40 | ;; - Set `gptel-model' and `gptel-backend' to use your preferred LLM. 41 | ;; 42 | ;; - Run M-x `gptel-agent'. This will open a buffer with the agent preset 43 | ;; loaded. 44 | ;; 45 | ;; - Use gptel as usual, calling `gptel-send' etc. 46 | ;; 47 | ;; - If you change the system prompt, tools or other settings in this buffer, you 48 | ;; can reset the agent state by (re)applying the "gptel-agent" preset from 49 | ;; gptel's menu. 50 | ;; 51 | ;; To use gptel-agent anywhere in Emacs: 52 | ;; 53 | ;; - As with gptel, you can use gptel-agent in any buffer. Just apply the 54 | ;; "gptel-agent" preset in the buffer, or include "@gptel-agent" in a prompt. 55 | ;; 56 | ;; gptel-agent can delegate tasks to "sub-agents". Sub-agents can be specified 57 | ;; in Markdown or Org files in a directory. To see how to specify agents, 58 | ;; examine the "agents" directory in this package. You can add your directory 59 | ;; of agents to `gptel-agent-dirs', which see. 60 | ;; 61 | ;; Please note: gptel-agent uses significantly more tokens than the average 62 | ;; gptel LLM interaction. 63 | ;; 64 | ;;; Code: 65 | 66 | (require 'compat) 67 | (require 'gptel) 68 | (require 'gptel-agent-tools) 69 | (eval-when-compile (require 'cl-lib)) 70 | 71 | (declare-function yaml-parse-string "yaml") 72 | (declare-function project-current "project") 73 | (declare-function project-root "project") 74 | (declare-function project-root "project") 75 | (declare-function org-get-property-block "org") 76 | (declare-function org-entry-properties "org") 77 | (defvar org-inhibit-startup) 78 | (defvar project-prompter) 79 | 80 | ;;; User options 81 | (defcustom gptel-agent-dirs 82 | (list (expand-file-name 83 | "./agents/" (file-name-directory 84 | (or load-file-name (buffer-file-name))))) 85 | "Agent definition directories for `gptel-agent'. 86 | 87 | Markdown (.md) and Org (.org) files in these directories will be scanned 88 | for gptel sub-agent definitions by `gptel-agent'." 89 | :type '(repeat directory) 90 | :group 'gptel-agent) 91 | 92 | ;;; State update 93 | (defvar gptel-agent--agents nil) 94 | 95 | (defun gptel-agent-read-file (agent-file &optional templates) 96 | "Read a preset/agent from AGENT-FILE. 97 | 98 | If TEMPLATES is-nil, read only the front-matter and do not apply 99 | any templates to the system prompt." 100 | (if (not (and (file-readable-p agent-file) 101 | (file-regular-p agent-file))) 102 | (prog1 nil 103 | (message "gptel-agent: File %s is not parseable" agent-file)) 104 | (let* ((agent-plist 105 | (pcase (file-name-extension agent-file) 106 | ("org" (gptel-agent-parse-org-properties 107 | agent-file nil templates)) 108 | ("md" (gptel-agent-parse-markdown-frontmatter 109 | agent-file nil templates)))) 110 | (name (or (plist-get agent-plist :name) 111 | (let ((filename (file-name-base agent-file))) 112 | (replace-regexp-in-string " " "-" filename))))) 113 | (cl-remf agent-plist :name) 114 | (cons name agent-plist)))) 115 | 116 | ;;;###autoload 117 | (defun gptel-agent-update () 118 | "Update agent definitions from `gptel-agent-dirs'." 119 | ;; First pass: discover all agents and collect their file paths 120 | (setq gptel-agent--agents nil) 121 | (let ((agent-files nil)) ; Alist of (agent-name . file-path) 122 | (mapc (lambda (dir) 123 | (dolist (agent-file (cl-delete-if-not #'file-regular-p 124 | (directory-files dir 'full))) 125 | (pcase-let ((`(,name . ,agent-plist) ;call without templates 126 | (gptel-agent-read-file agent-file))) 127 | (setf (alist-get name gptel-agent--agents nil t #'equal) 128 | agent-plist) 129 | (push (cons name agent-file) agent-files)))) 130 | gptel-agent-dirs) 131 | 132 | ;; Second pass: reload agents with template expansion 133 | (dolist (agent-entry gptel-agent--agents) 134 | (let* ((name (car agent-entry)) 135 | (agent-file (cdr (assoc name agent-files))) 136 | ;; Format the agent list for template substitution 137 | (agents-list-str 138 | (cl-loop for entry in gptel-agent--agents 139 | unless (or (string= (car entry) name) 140 | (string= (car entry) "gptel-agent") 141 | (string= (car entry) "gptel-plan")) 142 | collect (format "`%s`: %s\n" 143 | (car entry) (plist-get (cdr entry) :description)) 144 | into agent-list 145 | finally return (apply #'concat agent-list))) 146 | ;; Create templates alist 147 | (templates (list (cons "AGENTS" agents-list-str)))) 148 | (when agent-file ; Parse the agent file with templates 149 | (setf (alist-get name gptel-agent--agents nil t #'equal) 150 | (cdr (gptel-agent-read-file agent-file templates))))))) 151 | 152 | ;; Update the enum for Agent tool 153 | (setf (plist-get (car (gptel-tool-args (gptel-get-tool "Agent"))) :enum) 154 | (vconcat (delete "gptel-agent" (mapcar #'car gptel-agent--agents)))) 155 | 156 | ;; Apply gptel-agent preset if it exists 157 | (when-let* ((gptel-agent-plist (assoc-default "gptel-agent" gptel-agent--agents nil nil))) 158 | (apply #'gptel-make-preset 'gptel-agent gptel-agent-plist)) 159 | (when-let* ((gptel-plan-plist (assoc-default "gptel-plan" gptel-agent--agents nil nil))) 160 | (apply #'gptel-make-preset 'gptel-plan gptel-plan-plist)) 161 | gptel-agent--agents) 162 | 163 | ;;; Sub-agent definition parsers for Markdown and Org 164 | 165 | (defalias 'gptel-agent-validator-default #'always) 166 | 167 | (defun gptel-agent--expand-templates (start templates) 168 | "Expand template variables in the current buffer from START to point-max. 169 | 170 | START is the buffer position where to start expanding. 171 | TEMPLATES is an alist of (VAR-NAME . VAR-VALUE) pairs. 172 | 173 | Template variables in the format {{VAR-NAME}} are replaced with VAR-VALUE. 174 | Substitution happens in-place in the buffer." 175 | (dolist (template templates) 176 | (let ((var-name (car template)) 177 | (var-value (cdr template))) 178 | (goto-char start) 179 | (while (search-forward (format "{{%s}}" var-name) nil t) 180 | (replace-match var-value t t))))) 181 | 182 | ;; Parsing utilities for gptel subagent definition files, from 183 | ;; - Markdown files with YAML frontmatter 184 | ;; - Org files with PROPERTIES blocks 185 | 186 | (defun gptel-agent-parse-markdown-frontmatter (file-path &optional validator templates) 187 | "Parse a markdown file with optional YAML frontmatter. 188 | 189 | FILE-PATH is the path to a markdown file. 190 | 191 | VALIDATOR is an optional predicate function that takes a keyword symbol 192 | and returns t if the key is allowed, nil otherwise. If not provided, 193 | defaults to `gptel-agent-validator-default'. 194 | 195 | TEMPLATES is an optional alist of (VAR-NAME . VAR-VALUE) for template 196 | expansion. Template variables in the format {{VAR-NAME}} in the markdown 197 | body will be replaced with VAR-VALUE. 198 | 199 | Returns a plist with: 200 | - All YAML frontmatter keys as keywords 201 | - :system containing the markdown body text after frontmatter (with 202 | templates expanded) 203 | 204 | If no frontmatter block exists, returns a plist with just the :system 205 | key containing the entire file content. 206 | 207 | Signals an error if: 208 | - The frontmatter block is malformed (opening without closing delimiter) 209 | - A key in the frontmatter is not allowed by the validator" 210 | (unless validator 211 | (setq validator #'gptel-agent-validator-default)) 212 | (require 'yaml) 213 | 214 | (with-temp-buffer 215 | (insert-file-contents file-path) 216 | 217 | ;; Check if file starts with frontmatter delimiter 218 | (if (not (looking-at-p "^---[ \t]*$")) 219 | ;; No frontmatter - return plist with :system key containing entire file content 220 | (let ((file-content (buffer-string))) 221 | (if templates 222 | (progn ;Apply template substitutions 223 | (gptel-agent--expand-templates (point-min) templates) 224 | ;; Extract the expanded body text 225 | (list :system (buffer-substring-no-properties (point-min) (point-max)))) 226 | ;; Return plist with system content as-is 227 | (list :system file-content))) 228 | 229 | ;; Move past opening delimiter 230 | (forward-line 1) 231 | (let ((frontmatter-start (point))) 232 | 233 | ;; Search for closing delimiter 234 | (unless (re-search-forward "^---[ \t]*$" nil t) 235 | (error "Malformed frontmatter: opening delimiter '---' found but no closing delimiter")) 236 | 237 | ;; Extract frontmatter text (from start to beginning of closing delimiter) 238 | (let* ((frontmatter-end (match-beginning 0)) 239 | (frontmatter-str (buffer-substring-no-properties frontmatter-start frontmatter-end)) 240 | (body-start (1+ (match-end 0)))) 241 | 242 | ;; Parse YAML frontmatter 243 | (let ((parsed-yaml (yaml-parse-string 244 | frontmatter-str 245 | :object-type 'plist 246 | :object-key-type 'keyword 247 | :sequence-type 'list))) 248 | (let ((tail parsed-yaml)) 249 | (while tail 250 | (let ((key (pop tail)) 251 | (val (pop tail))) 252 | (pcase key 253 | ((or :pre :post) (plist-put parsed-yaml key (eval (read val) t))) 254 | (:parents (plist-put parsed-yaml key 255 | (mapcar #'intern (ensure-list (read val))))))))) 256 | 257 | ;; Validate all keys in the parsed YAML 258 | (let ((current-plist parsed-yaml)) 259 | (while current-plist 260 | (let ((key (car current-plist))) 261 | (unless (funcall validator key) 262 | (error "Invalid frontmatter key: %s" key))) 263 | (setq current-plist (cddr current-plist)))) 264 | 265 | (if (not templates) 266 | parsed-yaml 267 | ;; Apply template substitutions in place, then extract body text 268 | (gptel-agent--expand-templates body-start templates) 269 | ;; Extract the expanded body text 270 | (let ((expanded-body (buffer-substring-no-properties body-start (point-max)))) 271 | (plist-put parsed-yaml :system expanded-body))))))))) 272 | 273 | (defun gptel-agent-parse-org-properties (file-path &optional validator templates) 274 | "Parse an Org file with properties in a :PROPERTIES: drawer. 275 | 276 | FILE-PATH is the path to an Org file. 277 | 278 | VALIDATOR is an optional predicate function that takes a keyword 279 | symbol and returns t if the key is allowed, nil otherwise. 280 | If not provided, defaults to `gptel-agent-validator-default'. 281 | 282 | TEMPLATES is an optional alist of (VAR-NAME . VAR-VALUE) for template 283 | expansion. Template variables in the format {{VAR-NAME}} in the Org body 284 | will be replaced with VAR-VALUE. 285 | 286 | The function expects a :PROPERTIES: block at the top of the file 287 | (before any headlines), with keys like name, description, tools, 288 | backend, model, etc. Property names are case-insensitive and will 289 | be converted to lowercase keyword symbols. 290 | 291 | Returns a plist with: 292 | - All properties from the :PROPERTIES: drawer as keywords 293 | - :system containing the Org file body text after the property 294 | block (with templates expanded) 295 | 296 | If no property block exists, returns a plist with just the :system 297 | key containing the entire file content. 298 | 299 | Signals an error if: 300 | - A key in the property block is not allowed by the validator" 301 | (unless validator 302 | (setq validator #'gptel-agent-validator-default)) 303 | 304 | (with-temp-buffer 305 | (insert-file-contents file-path) 306 | (let ((org-inhibit-startup t)) 307 | (delay-mode-hooks (org-mode))) 308 | 309 | ;; Try to get the property block at this position 310 | (let ((prop-range (org-get-property-block))) 311 | (if (not prop-range) 312 | ;; No property block - return plist with :system key containing entire file content 313 | (let ((file-content (buffer-string))) 314 | (if templates 315 | (progn ;Apply template substitutions 316 | (gptel-agent--expand-templates (point-min) templates) 317 | ;; Extract the expanded body text 318 | (list :system (buffer-substring-no-properties (point-min) (point-max)))) 319 | ;; Return plist with system content as-is 320 | (list :system file-content))) 321 | 322 | ;; Extract properties as an alist 323 | (let* ((props-alist (org-entry-properties (point-min) 'standard)) 324 | (props-plist nil) 325 | (body-start (save-excursion 326 | (goto-char (cdr prop-range)) 327 | (forward-line 1) ; Move past the :END: line 328 | (while (looking-at-p "^\\s-*$") (forward-line 1)) 329 | (point)))) 330 | 331 | ;; Process each property 332 | (dolist (pair props-alist) 333 | (let* ((key-str (downcase (car pair))) 334 | (key-sym (intern (concat ":" key-str))) 335 | (value (cdr pair))) 336 | 337 | (pcase key-sym 338 | (:tools (setq value (split-string value)))) 339 | 340 | ;; Skip CATEGORY property (added automatically by Org) 341 | (unless (string-equal key-str "category") 342 | ;; Validate the key 343 | (unless (funcall validator key-sym) 344 | (error "Invalid property key: %s" key-sym)) 345 | 346 | ;; Add to plist 347 | (setq props-plist (plist-put props-plist key-sym value))))) 348 | 349 | (let ((tail props-plist)) 350 | (while tail 351 | (let ((key (pop tail)) 352 | (val (pop tail))) 353 | (pcase key 354 | ((or :pre :post) (plist-put props-plist key (eval (read val) t))) 355 | (:parents (plist-put props-plist key 356 | (mapcar #'intern (ensure-list (read val))))))))) 357 | 358 | (if (not templates) 359 | props-plist 360 | ;; Apply template substitutions in place, then extract body text 361 | (gptel-agent--expand-templates body-start templates) 362 | ;; Extract the expanded body text 363 | (let ((expanded-body (buffer-substring-no-properties 364 | body-start (point-max)))) 365 | (plist-put props-plist :system expanded-body)))))))) 366 | 367 | ;;; Commands 368 | 369 | ;;;###autoload 370 | (defun gptel-agent (&optional project-dir agent-preset) 371 | "Start a `gptel-agent' session in the current project. 372 | 373 | With optional prefix arg, query for PROJECT-DIR. Load AGENT-PRESET in 374 | this session, which defaults to the default `gptel-agent'." 375 | (interactive 376 | (list (if current-prefix-arg 377 | (funcall project-prompter) 378 | (if-let ((proj (project-current))) 379 | (project-root proj) 380 | default-directory)) 381 | 'gptel-agent)) 382 | (let ((gptel-buf 383 | (gptel (generate-new-buffer-name 384 | (format "*gptel-agent:%s*" 385 | (cadr (nreverse (file-name-split project-dir))))) 386 | nil 387 | (and (use-region-p) 388 | (buffer-substring (region-beginning) 389 | (region-end))) 390 | 'interactive))) 391 | (with-current-buffer gptel-buf 392 | (setq default-directory project-dir) 393 | (gptel-agent-update) ;Update all agent definitions 394 | (gptel--apply-preset ;Apply the gptel-agent preset 395 | (or agent-preset 'gptel-agent) 396 | (lambda (sym val) (set (make-local-variable sym) val))) 397 | (unless gptel-max-tokens ;Agent tasks typically need 398 | (setq gptel-max-tokens 8192)) ;a higher than usual value 399 | (when gptel-use-header-line 400 | (let* ((agent-mode t) 401 | (switch-mode 402 | (lambda (&rest _) 403 | (gptel--apply-preset 404 | (if agent-mode 'gptel-plan 'gptel-agent) 405 | (lambda (sym val) (set (make-local-variable sym) val))) 406 | (setq agent-mode (not agent-mode)) 407 | (force-mode-line-update))) 408 | (display-mode 409 | (lambda () (concat 410 | (propertize " " 'display '(space :align-to 0)) 411 | (format "%s" (gptel-backend-name gptel-backend)) 412 | (if agent-mode 413 | (propertize (buttonize "[Agent]" switch-mode nil 414 | "Switch to planning preset") 415 | 'face 'font-lock-keyword-face) 416 | (propertize (buttonize "[Plan]" switch-mode nil 417 | "Switch to agent preset") 418 | 'face 'font-lock-doc-face)))))) 419 | (setcar header-line-format 420 | `(:eval (funcall ,display-mode)))))))) 421 | 422 | (provide 'gptel-agent) 423 | 424 | ;;; gptel-agent.el ends here 425 | -------------------------------------------------------------------------------- /gptel-agent-tools-introspection.el: -------------------------------------------------------------------------------- 1 | ;;; gptel-agent-tools-introspection.el --- Emacs introspection tools for gptel-agent -*- lexical-binding: t; -*- 2 | 3 | ;; Copyright (C) 2025 Karthik Chikmagalur 4 | 5 | ;; Author: Karthik Chikmagalur 6 | ;; Keywords: convenience 7 | 8 | ;; This program is free software; you can redistribute it and/or modify 9 | ;; it under the terms of the GNU General Public License as published by 10 | ;; the Free Software Foundation, either version 3 of the License, or 11 | ;; (at your option) any later version. 12 | 13 | ;; This program is distributed in the hope that it will be useful, 14 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | ;; GNU General Public License for more details. 17 | 18 | ;; You should have received a copy of the GNU General Public License 19 | ;; along with this program. If not, see . 20 | 21 | ;;; Commentary: 22 | 23 | ;; Emacs introspection tools for gptel-agent. 24 | ;; 25 | ;; These tools provide LLMs with access to Emacs' introspection facilities: 26 | ;; - Symbol lookup and completion 27 | ;; - Documentation retrieval 28 | ;; - Source code inspection 29 | ;; - Manual/info documentation 30 | ;; - Feature and library inspection 31 | ;; - Elisp evaluation 32 | ;; 33 | ;; Adapted from ragmacs.el by Positron Solutions. 34 | 35 | ;;; Code: 36 | 37 | (require 'gptel-request) 38 | (require 'info) 39 | (require 'find-func) 40 | (eval-when-compile (require 'cl-lib)) 41 | 42 | (declare-function custom-variable-documentation "cus-edit") 43 | (declare-function orderless-filter "orderless") 44 | 45 | ;;; Helper functions 46 | 47 | (defun gptel-agent--introspect-manual-node-contents (manual node) 48 | "Return contents of NODE in Info MANUAL." 49 | (condition-case err 50 | (progn 51 | (save-window-excursion 52 | (Info-goto-node (format "(%s)%s" manual node)) 53 | (buffer-substring-no-properties (point-min) (point-max)))) 54 | (user-error 55 | (error (error-message-string err))))) 56 | 57 | (defun gptel-agent--introspect-symbol-in-manual (symbol) 58 | "Return the Info documentation for SYMBOL, if it exists." 59 | (when-let* ((symbol (intern-soft symbol))) 60 | (save-window-excursion 61 | (info-lookup-symbol symbol #'emacs-lisp-mode) 62 | (buffer-substring-no-properties (point-min) (point-max))))) 63 | 64 | (defun gptel-agent--introspect-library-source (library-name) 65 | "Return the source code of LIBRARY-NAME as a string." 66 | (if-let ((library (find-library-name library-name))) 67 | (with-temp-buffer 68 | (progn 69 | (insert-file-contents library) 70 | (buffer-string))) 71 | (error "Library not found: %s" library-name))) 72 | 73 | (defun gptel-agent--introspect-source (symbol &optional type) 74 | "Retrieve the source code for SYMBOL of TYPE. 75 | SYMBOL should be a function or variable name, given as a string or symbol. 76 | TYPE can be nil for functions, defvar for variables, or defface for faces. 77 | Returns the source code as a string, or nil if the definition is not found." 78 | (when-let* ((callable (intern-soft symbol)) 79 | (save-silently t) ; suppresses message in 80 | ; find-file-noselect 81 | (vc-follow-symlinks t) ; don't ask, we're not editing. 82 | (buffer-point (find-definition-noselect callable type))) 83 | (with-current-buffer (car buffer-point) 84 | (goto-char (cdr buffer-point)) 85 | (buffer-substring-no-properties 86 | (point) 87 | (progn (if (null type) 88 | (end-of-defun) 89 | (cond ((derived-mode-p 'c-mode) 90 | (forward-sexp 2) 91 | (forward-char)) 92 | ((derived-mode-p 'emacs-lisp-mode) 93 | (forward-sexp)) 94 | (t (error "Unexpected file mode")))) 95 | (point)))))) 96 | 97 | ;;; Tool declarations 98 | 99 | (gptel-make-tool 100 | :function (lambda (name) (intern-soft name)) 101 | :name "symbol_exists" 102 | :include t 103 | :category "introspection" 104 | :args '(( :name "symbol" 105 | :type string 106 | :description "A symbol that will be in `obarray' if they \ 107 | actually exist")) 108 | :description "Check if SYMBOL exists in `obarray'. \ 109 | Returns the name of a symbol if that symbol has been interned or \"nil\" 110 | if not. Uses `intern-soft' to perform the check. This tool is 111 | extremely cheap to call.") 112 | 113 | (gptel-make-tool 114 | :function (lambda () (string-join load-path "\n")) 115 | :name "load_paths" 116 | :include t 117 | :category "introspection" 118 | :args nil 119 | :description "Return the users load paths. 120 | This can reveal information about what packages the user has available. 121 | You can also learn about what kind of package management they are using 122 | and which packages are likely shadowed by their Elisp dependency 123 | manager. The location of default packages can tell you about the user's 124 | Emacs installation.") 125 | 126 | (gptel-make-tool 127 | :function (lambda () (mapconcat #'symbol-name features "\n")) 128 | :name "features" 129 | :include t 130 | :category "introspection" 131 | :args nil 132 | :description "Return the list of loaded features. 133 | This tool can be used to see what packages are already loaded in the 134 | running Emacs. Use this to understand the user's typical set of 135 | packages and typical usage patterns. Especially if the solution depends 136 | on the user's choice of packages, you will want to look at the features 137 | and load paths.") 138 | 139 | (gptel-make-tool 140 | :function (lambda () 141 | (json-serialize (vconcat (info--filter-manual-names 142 | (info--manual-names nil))))) 143 | :name "manual_names" 144 | :include t 145 | :category "introspection" 146 | :args nil 147 | :description "Return a list of available manual names. 148 | Call this tool in order to determine if a particular manual is 149 | available. This can also help determine which packages are available on 150 | the user's Emacs. This tool is a good starting point for general 151 | questions about Emacs, Elisp, and common built-in packages. 152 | 153 | Manuals are usually named the same as the symbol of the package prefix 154 | that they document. The Common Lisp manual is called \"cl\". The Emacs 155 | Lisp manual is called \"elisp\". 156 | 157 | You will usually follow this call with a subsequent call to 158 | `manual_nodes' in order to see the sections in the manual, which are 159 | somewhat like a summary. This call is extremely cheap and should be 160 | used liberally.") 161 | 162 | (gptel-make-tool 163 | :function (lambda (name) 164 | (json-serialize 165 | (vconcat (mapcar #'car (Info-build-node-completions name))))) 166 | :name "manual_nodes" 167 | :include t 168 | :category "introspection" 169 | :args '(( :name "manual" 170 | :type string 171 | :description "The name of the manual. 172 | Examples include \"cl\", \"elisp\", or \"transient\".")) 173 | :description "Retrieve a listing of topic nodes within MANUAL. 174 | Return value is a list of all nodes in MANUAL. The list of topic nodes 175 | provides a good summary of MANUAL. 176 | 177 | MANUAL is one of the results returned from `manual_names'. If you are 178 | sure a manual exists, you may skip first calling `manual_names'. When 179 | you believe MANUAL exists, this tool is very useful to find places to 180 | broaden your search. 181 | 182 | You will usually follow this call with a subsequent call to 183 | `manual_node_contents' to view the actual full contents of a node in the 184 | manual. This call is extremely cheap and should be used liberally. 185 | 186 | In the Elisp manual, you can find more answers about code and 187 | implementations that a programmer can used to deeply customize. The 188 | Emacs manual contains descriptions about built-in features and behavior 189 | that can be used to understand the context for what is being programmed 190 | in the Elisp manual.") 191 | 192 | (gptel-make-tool 193 | :function #'gptel-agent--introspect-manual-node-contents 194 | :name "manual_node_contents" 195 | :include t 196 | :category "introspection" 197 | :args '(( :name "manual_name" 198 | :type string 199 | :description "The name of MANUAL. 200 | Examples manuals include \"cl\", \"elisp\", or \"transient\".") 201 | ( :name "node" 202 | :type string 203 | :description "The name of the NODE in a MANUAL. 204 | Example nodes from the elisp manual include \"Records\" or \"Sequences 205 | Arrays \ Vectors\".")) 206 | :description "Retrieve the contents of NODE in MANUAL. 207 | The return value is the full contents of NODE in MANUAL. Contents 208 | include high-level grouping of related functions and variables. Hidden 209 | behavior is described. This tool is awesome! You should try to call it 210 | all the time. 211 | 212 | Pay attention to the entries in the Menu. You can do recursive look-ups 213 | of more specific manual sections. Example menu: 214 | 215 | * Menu: 216 | 217 | * Good Node:: 218 | * A Node:: 219 | 220 | You can recursively look up \"Good Node\" and other relevant menu nodes 221 | in this same MANUAL. Sometimes there are links, such as, \"*Note 222 | Narrowing::.\". \"Narrowing\" is a node in this example. Use this tool 223 | recursively. 224 | 225 | If both Elisp and Emacs manuals are available, open both but prefer Elisp manual 226 | style language anc content.") 227 | 228 | (gptel-make-tool 229 | :function (lambda (feature) 230 | (if-let ((feature-symbol (intern-soft feature))) 231 | (when (featurep feature-symbol) 232 | feature) 233 | (find-library-name feature))) 234 | :name "features" 235 | :include t 236 | :category "introspection" 237 | :args '(( :name "feature" 238 | :type string 239 | :description "FEATURE to look for.")) 240 | :description "Check if FEATURE is loaded or available. 241 | Returns non-nil if FEATURE is loaded or available for loading. Not all 242 | users have all features loaded. Before recommending the user to try a 243 | particular solution, you might check if the necessary features are 244 | loaded. If you are using all built-in Emacs libraries, you don't need 245 | to check. Use this mainly to check for 3rd party packages that the user 246 | would obtain from MELPA and Non-GNU ELPA etc.") 247 | 248 | (gptel-make-tool 249 | :function #'gptel-agent--introspect-library-source 250 | :name "library_source" 251 | :include t 252 | :category "introspection" 253 | :args '(( :name "library" 254 | :type string 255 | :description "LIBRARY to look for.")) 256 | :description "Read the source code for LIBRARY. 257 | LIBRARY can either be a C or Elisp source code library. Examples would 258 | include \"transient\" or \"fns.c\". When looking for C libraries, they 259 | must contain the .c suffix. 260 | 261 | This tool is a bit expensive, and you can usually find what you want by 262 | looking up symbols in the package first by calling 263 | `function_completions' and `variable_completions' to get a high-level 264 | summary of what definitions might be contained in a library. 265 | 266 | Watch for for sub-packages. Some multi-file packages will have symbols 267 | that are defined in a sub-package. If you see a common prefix in the 268 | function or variable completions and those symbols are not in the 269 | top-level package, there are likely sub-packages and you should 270 | recursively look them up.") 271 | 272 | (gptel-make-tool 273 | :name "symbol_manual_section" 274 | :include t 275 | :function #'gptel-agent--introspect-symbol-in-manual 276 | :category "introspection" 277 | :args '(( :name "symbol" 278 | :type string 279 | :description "Name of a SYMBOL, such as \ 280 | \"find-file-noselect\".")) 281 | :description "Returns contents of manual node for SYMBOL. 282 | SYMBOL can be a function, macro, defcustom, or defvar. If symbol is not 283 | known to be in a manual, this functon will return nil. 284 | 285 | The returned manual contents are similar to the `manual_node_contents' 286 | tool. You sould recursively inspect any links or menu entries that look 287 | relevant. Check the node list for the manual if a link or menu entry 288 | returns nil. 289 | 290 | If you can't find anything, you should try looking up its source or 291 | docstring next and finally try to complete the prefix of the symbol .") 292 | 293 | (gptel-make-tool 294 | :name "function_source" 295 | :include t 296 | :function (lambda (symbol) 297 | (when-let ((symbol (intern-soft symbol))) 298 | (gptel-agent--introspect-source symbol))) 299 | :category "introspection" 300 | :args '(( :name "function" 301 | :type string 302 | :description "Name of a FUNCTION, such as \ 303 | \"find-file-noselect\".")) 304 | :description "Returns the source code for FUNCTION. 305 | Return the source code for FUNCTION. FUNCTION can be a function or 306 | macro. The signature and docstring can supply extremely valuable 307 | information about how to call a function correctly and what behaviors 308 | are controlled by its arguments. You can understand the side-effects 309 | and what variables a function reacts to by reading its body. 310 | 311 | You can use the source code for functions to recursively look up other 312 | functions & variables and make inferences about how implementations work 313 | in order to connect the behaviors and implementation details that the 314 | user will need. 315 | 316 | Because the docstring is embedded in the source, you should prefer this 317 | tool over just retrieving the documentation. If the result seems 318 | incomplete, you can try returning the docstring using 319 | `function_documentation' or the entire source for a library feature by 320 | using `library_source'. This tool is cheap. Use it liberally.") 321 | 322 | (gptel-make-tool 323 | :name "variable_source" 324 | :function (lambda (symbol) 325 | (when-let ((symbol (intern-soft symbol))) 326 | (gptel-agent--introspect-source symbol 'defvar))) 327 | :category "introspection" 328 | :include t 329 | :args '(( :name "variable" 330 | :type string 331 | :description "Name of a VARIABLE, such as \ 332 | \"last-kbd-macro\".")) 333 | :description "Returns the source code for VARIABLE. 334 | Return value is the source code for VARIABLE. VARIABLE can be a defvar 335 | or defcustom. The returned source code can be extremely insightful 336 | because nothing is more accurate than looking at the code and the source 337 | code contains the docstring too. 338 | 339 | You can use source code for variables to see the forms used in setting 340 | their defaults and make inferences about what forms will be interpreted 341 | correctly. If the result seems incomplete, you can try returning the 342 | docstring using `variable_documentation' or the entire source for a 343 | library feature by using `library_source'. This tool is cheap and fast. 344 | Call it liberally.") 345 | 346 | (gptel-make-tool 347 | :name "variable_value" 348 | :function (lambda (symbol) 349 | (when-let ((symbol (intern-soft symbol))) 350 | (default-value symbol))) 351 | :category "introspection" 352 | :confirm t 353 | :include t 354 | :args '(( :name "variable" 355 | :type string 356 | :description "Name of a VARIABLE, such as \ 357 | \"last-kbd-macro\".")) 358 | :description "Returns the global value for VARIABLE. 359 | Return value is the global (not buffer-local) value for VARIABLE. 360 | VARIABLE can be a defvar or defcustom. Use this when behavior depends 361 | on the state of a variable or you want to infer if a package has indeed 362 | configured a variable. By observing expected side-effects, you can 363 | build a coherent view of the interaction between functions and settings. 364 | 365 | Use of this tool could leak private data, so don't call it for any 366 | VARIABLE that contains initialized authentication data. 367 | 368 | If the result is confusing, you can try returning the docstring using 369 | `variable_documentation' to gain insights into the structure of values 370 | contained.") 371 | 372 | (gptel-make-tool 373 | :name "function_documentation" 374 | :function (lambda (symbol) 375 | (when-let ((symbol (intern-soft symbol))) 376 | (documentation symbol))) 377 | :category "introspection" 378 | :include t 379 | :args '(( :name "function" 380 | :type string 381 | :description "Name of a FUNCTION, such as \"mapcar\".")) 382 | :description "Returns the docstring for FUNCTION. 383 | Return value is a docstring for FUNCTION. FUNCTION can be a function or 384 | macro. Can be used to infer the purpose or correct forms for arguments 385 | and behavior changes related to those arguments. This is more reliable 386 | than `function_source', so if `function_source' seems off, try this. 387 | This tool is very cheap and very fast. Call it very liberally.") 388 | 389 | (gptel-make-tool 390 | :name "variable_documentation" 391 | :function (lambda (symbol) 392 | (when-let* ((symbol (intern-soft symbol))) 393 | (require 'cus-edit) 394 | (custom-variable-documentation symbol))) 395 | :category "introspection" 396 | :include t 397 | :args '(( :name "variable" 398 | :type string 399 | :description "Name of a VARIABLE, such as \ 400 | \"cursor-type\".")) 401 | :description "Returns the docstring VARIABLE. 402 | Return value is a docstring for VARIABLE. VARIABLE can be a defcustom 403 | or defvar. Can be used to infer the correct forms for setting a 404 | variable, such as when configuring packages in use-package expressions 405 | or leading the user through diagnosing something. This tool is very 406 | cheap and very fast. Call it very liberally.") 407 | 408 | (gptel-make-tool 409 | :name "function_completions" 410 | :function (lambda (prefix) 411 | (require 'orderless) 412 | (string-join (orderless-filter prefix obarray #'functionp) "\n")) 413 | :category "introspection" 414 | :include t 415 | :args '(( :name "function_prefix" 416 | :type string 417 | :description "FUNCTION_PREFIX of functions you are searching for.")) 418 | :description "Returns a list of functions beginning with FUNCTION_PREFIX. 419 | Use this to prepare for subsequent calls to `function_source' or 420 | `function_documentation' to look up the source code or docstrings of 421 | multiple functions. You can also use this tool to verify which 422 | functions and macros can be called. If you want to search for all 423 | functions defined in foo and its sub-packages, you this tool is a very 424 | good starting point. This tool is very cheap and very fast. Call it 425 | very liberally.") 426 | 427 | (gptel-make-tool 428 | :name "command_completions" 429 | :function (lambda (prefix) 430 | (require 'orderless) 431 | (string-join (orderless-filter prefix obarray #'commandp) "\n")) 432 | :category "introspection" 433 | :include t 434 | :args '(( :name "command_prefix" 435 | :type string 436 | :description "COMMAND_PREFIX of commands you are searching for.")) 437 | :description "Returns a list of commands beginning with COMMAND_PREFIX. 438 | This tool is very similar to `function_completions' but will only return 439 | commands that can be called interactively. This can tell you about the 440 | entry points where a user begins interacting with a package. Because 441 | commands are functions, you will follow up this tool with calls to 442 | `function_source' and `function_documentation'. This tool is very cheap 443 | and very fast. Call it very liberally.") 444 | 445 | (gptel-make-tool 446 | :name "variable_completions" 447 | :function (lambda (prefix) 448 | (require 'orderless) 449 | (string-join (orderless-filter prefix obarray #'boundp) "\n")) 450 | :category "introspection" 451 | :include t 452 | :args '(( :name "variable_prefix" 453 | :type string 454 | :description "VARIABLE_PREFIX of variables you are searching for.")) 455 | :description "Returns a list of variables beginning with VARIABLE_PREFIX. 456 | The variables returned include defvars and custom variables. Defvars 457 | tell you what states a package relies on for its implementation. 458 | Defcustom tells you what configuration options the user should know 459 | about when configuring a package, such as if they are working on 460 | use-package expressions. 461 | 462 | Use this to prepare for subsequent calls to `variable_source' or 463 | `variable_documentation' to look up the source code or docstrings of 464 | multiple variables. If you want to search for all variables defined 465 | under a prefix, you this tool is a very good starting point. This tool 466 | is very cheap and very fast. Call it very liberally.") 467 | 468 | (provide 'gptel-agent-tools-introspection) 469 | ;;; gptel-agent-tools-introspection.el ends here 470 | -------------------------------------------------------------------------------- /agents/gptel-agent.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: gptel-agent 3 | description: The default gptel-agent 4 | tools: 5 | - Agent 6 | - TodoWrite 7 | - Glob 8 | - Grep 9 | - Read 10 | - Insert 11 | - Edit 12 | - Write 13 | - Mkdir 14 | - Eval 15 | - Bash 16 | - WebSearch 17 | - WebFetch 18 | - YouTube 19 | --- 20 | 21 | You are an AI assistant that helps users accomplish their goals. 22 | 23 | 24 | - Keep responses concise to the point of being terse 25 | - Avoid flattery, superlatives, or unnecessary flourishes 26 | - Prioritize accuracy over agreement 27 | - Challenge the user constructively when you can think of a better approach 28 | - Never use bash echo or command-line tools for communication. Instead, output text directly to the user. 29 | - Do not write documentation files unless asked for. Provide responses directly to the user instead. 30 | 31 | 32 | 33 | - Before executing, consider if there's a better way to accomplish the task 34 | - Think about the larger problem - does the task need to be done this way at all? 35 | - Provide alternatives when you identify better approaches 36 | - Question assumptions constructively 37 | - Investigate to find truth before confirming beliefs 38 | 39 | 40 | 41 | 42 | Before starting ANY task, run this mental checklist: 43 | 44 | 1. **Is this multi-step work?** If the task requires 3 or more distinct steps → CREATE A TODO LIST IMMEDIATELY using `TodoWrite`. This is not optional. 45 | 46 | **What counts as a "step"?** 47 | - Individual file edits/modifications (even if similar) 48 | - Distinct phases of work (research → implement → test) 49 | - Independent subtasks that could fail separately 50 | - Actions that need to be tracked/verified 51 | 52 | **Examples requiring todos:** 53 | - "Replace 5+ similar patterns across a file" → YES (each replacement is a step) 54 | - "Refactor functions in 3 files" → YES (each file is a step) 55 | - "Research X, then implement Y" → YES (2+ distinct phases) 56 | 57 | **Examples NOT requiring todos:** 58 | - "Read file X and tell me Y" → NO (single action) 59 | - "Fix this one bug" → NO (unless fix spans multiple files) 60 | 61 | 2. **Does this task need delegation?** 62 | 63 | **DELEGATE to `researcher` when:** 64 | - Open-ended web research (multiple sources, uncertain approach) 65 | - Searching codebase for understanding/information gathering (not just finding a specific known item) 66 | - Task involves exploring unfamiliar code where you don't know exact locations 67 | - Searching across 3+ files or when you expect many search results 68 | - Building understanding of how something works by reading multiple files 69 | - User asks "how does X work", "where is X implemented", "find all places that do X" 70 | 71 | **DELEGATE to `introspector` when:** 72 | - Understanding elisp package APIs or Emacs internals. 73 | - Exploring Emacs state or package functionality. 74 | - For elisp tasks, `introspector` is better than using `researcher` as the 75 | results will be the "source of truth", from the live Emacs session. 76 | Consider using both in sequence (`introspector` first) for complex tasks. 77 | 78 | **DELEGATE to `executor` when:** 79 | - Task involves modifying 3+ files (even simple changes across many files) 80 | - Task involves 2+ files with complex/interdependent changes 81 | - Systematic refactoring (renaming across files, updating patterns, migration tasks) 82 | - Batch operations (applying same change to multiple locations) 83 | - Multi-phase work (research → implement → test → fix → verify) 84 | - Task has clear requirements but will take 5+ tool calls to complete 85 | - You have multiple independent tasks in your todo list that can run in parallel 86 | - The execution is well-defined but you need to plan/consult on other tasks 87 | 88 | **Key signals for delegation:** 89 | - User says: "refactor X to Y", "migrate from A to B", "update all instances of Z" 90 | - You're thinking: "I need to edit file1, then file2, then file3..." 91 | - You have a clear plan but executing it will consume significant context 92 | - The task is repetitive/mechanical (perfect for autonomous execution) 93 | 94 | **Handle inline when:** 95 | - You know exact file paths to read (1-2 files) 96 | - Searching for specific well-defined text in known locations 97 | - Simple lookups or single-file operations 98 | - User provides specific file paths to examine 99 | - Quick edits to 1-2 files 100 | 101 | 3. **Pattern matching for delegation:** 102 | - "how does...", "where is...", "find all...", "search for...", "explore..." → Use `researcher` 103 | - "I need to understand..." about codebase → Use `researcher` 104 | - "I need to understand..." about elisp/Emacs → Use `introspector` 105 | - "create/modify these files...", "implement feature Z" (with clear spec) → Use `executor` 106 | - "refactor X to Y", "migrate from A to B", "update all X" → Use `executor` 107 | - "rename X to Y across the codebase" → Use `executor` 108 | - "apply this change to all/multiple files" → Use `executor` 109 | - "This task has multiple phases/stages" → Use `TodoWrite` (or delegate to `executor` if it will bloat context) 110 | 111 | **Key principle for researcher**: If you're about to grep/glob and aren't sure what you'll find or will need to follow up with more searches, delegate to `researcher`. It's better to delegate early than fill context with irrelevant results. 112 | 113 | **Key principle for executor**: If you find yourself planning "I'll edit file A, then B, then C...", that's a signal to delegate to `executor`. Let it handle the mechanical execution while you stay available for higher-level decisions. 114 | 115 | Once you delegate to a specialized agent, trust their results and integrate them into your response. 116 | 117 | 118 | 119 | When working on tasks, follow these guidelines for tool selection: 120 | 121 | **Specialized Tools vs. Shell Commands (CRITICAL):** 122 | - NEVER use `Bash` for file operations with grep, find, ls, cat, head, tail, sed or awk. 123 | - ALWAYS use: `Glob`, `Grep`, `Read`, `Edit`, `Write` 124 | - Reserve `Bash` EXCLUSIVELY for: git, npm, docker, cargo, make, system services and other non-file commands 125 | - Using bash for file operations violates the tool hierarchy and creates technical debt 126 | 127 | **Parallel Tool Execution:** 128 | - Call multiple tools in a single response when tasks are independent 129 | - Launch multiple executor agents in parallel for independent Todo tasks 130 | - Never use placeholders or guess missing parameters 131 | - Maximize parallel execution to improve efficiency 132 | 133 | **Tool Selection Hierarchy:** 134 | - File search by name → Use `Glob` (NOT find or ls) 135 | - Directory listing → Use `Glob` with glob pattern `"*"` (not ls) 136 | - Content search → Use `Grep` (NOT grep or rg) 137 | - Read files → Use `Read` (NOT cat/head/tail) 138 | - Edit files → Use `Edit` (NOT sed/awk) 139 | - Write files → Use `Write` (NOT echo >/cat < 143 | **MANDATORY delegation scenarios (use Agent immediately):** 144 | - Open-ended web research with multiple sources → DELEGATE to `researcher` 145 | - **Searching codebase for code understanding or information gathering** → DELEGATE to `researcher` 146 | - Exploring unfamiliar code with uncertain search paths → DELEGATE to `researcher` 147 | - **Expected to search 3+ files or get many search results** → DELEGATE to `researcher` 148 | - Understanding elisp APIs or Emacs internals → DELEGATE to `introspector` 149 | - **Well-defined multi-step task that will bloat your context** → DELEGATE to `executor` 150 | - **Creating/modifying 3+ files with clear requirements** → DELEGATE to `executor` 151 | - Task explicitly requires specialized investigation → Use appropriate agent 152 | 153 | **When NOT to use `Agent`:** 154 | - You know exact file paths and just need to read 1-2 specific files → use `Read` 155 | - Searching for ONE specific, well-defined string in known location → use `Grep` 156 | - User provides specific file paths to examine → handle inline 157 | - Simple, focused task with all information available → handle inline 158 | - Quick edits to 1-2 files → handle inline 159 | 160 | **Critical distinctions:** 161 | - **Finding a specific item** (e.g., "read the config in settings.py") → Handle inline 162 | - **Understanding/exploring** (e.g., "how does authentication work?") → DELEGATE to `researcher` 163 | - **Executing well-defined work** (e.g., "refactor all tests to use new API") → DELEGATE to `executor` 164 | 165 | **How to use the `Agent` tool:** 166 | - Agents run autonomously and return results in one message 167 | - Provide detailed, comprehensive instructions in the prompt parameter 168 | - You can launch multiple agents in parallel for independent tasks 169 | - Agent results should generally be trusted 170 | - Integrate results into your response - don't pass responsibility back to the user 171 | 172 | **Available agent types:** 173 | {{AGENTS}} 174 | 175 | 176 | 177 | **MANDATORY: Use TodoWrite for any multi-step work (3+ steps)** 178 | 179 | You MUST create a todo list immediately when: 180 | - Task has 3+ distinct steps or phases 181 | - Task will span multiple responses or tool calls 182 | - Task requires careful planning or coordination 183 | - You receive new instructions with multiple requirements 184 | - Work might benefit from tracking progress 185 | 186 | **When NOT to use `TodoWrite`:** 187 | - Single, straightforward tasks (one clear action) 188 | - Trivial tasks with no organizational benefit 189 | - Tasks completable in less than 3 steps 190 | - Purely conversational or informational requests 191 | - User provides a simple question requiring a simple answer 192 | 193 | **How to use `TodoWrite`:** 194 | - Always provide both `content` (imperative: "Run tests") and `activeForm` (present continuous: "Running tests") 195 | - Exactly ONE task must be in_progress at any time when you're executing tasks yourself 196 | - When delegating to executor agents in parallel, multiple tasks can be in_progress simultaneously 197 | - Mark tasks completed IMMEDIATELY after finishing (don't batch completions) 198 | - Complete current tasks before starting new ones 199 | - Send entire todo list with each call (not just changed items) 200 | - ONLY mark completed when FULLY accomplished - if errors occur, keep as in_progress 201 | 202 | **Pattern to recognize:** If you're planning 3+ steps before executing, CREATE A TODO LIST FIRST. 203 | - Send entire todo list with each call (not just changed items) 204 | - Remove tasks that are no longer relevant 205 | - ONLY mark completed when FULLY accomplished - if errors occur, keep as in_progress 206 | - Create new tasks for blockers/issues that arise 207 | 208 | **Task States:** 209 | - `pending`: Task not yet started 210 | - `in_progress`: Currently working on (exactly one at a time) 211 | - `completed`: Task finished successfully 212 | 213 | 214 | 215 | **When to use `Glob`:** 216 | - Searching for files by name patterns or extensions 217 | - You know the file pattern but not exact location 218 | - Finding all files of a certain type 219 | - Exploring project or directory structure 220 | 221 | **When NOT to use `Glob`:** 222 | - Searching file contents → use `Grep` 223 | - You know the exact file path → use `Read` 224 | - Doing open-ended multi-round searches → use `Agent` tool with general-purpose agent 225 | - Use shell commands like find → use `Glob` instead 226 | 227 | **How to use `Glob`:** 228 | - Supports standard glob patterns: `**/*.js`, `*.{ts,tsx}`, `src/**/*.py` 229 | - List all files with glob pattern `*` 230 | - Returns files sorted by modification time (most recent first) 231 | - Can specify a directory path to narrow search scope 232 | - Can perform multiple glob searches in parallel for different patterns 233 | 234 | 235 | 236 | **When to use `Grep`:** 237 | - Finding ONE specific, well-defined string/pattern in the codebase 238 | - You know what you're looking for and where it likely is 239 | - Verifying presence/absence of specific text 240 | - Quick, focused searches with expected results <20 matches 241 | 242 | **When NOT to use `Grep`:** 243 | - **Building code understanding or exploring unfamiliar code** → DELEGATE to `researcher` 244 | - **Expected to get many results (20+ matches)** → DELEGATE to `researcher` 245 | - **Will need follow-up searches based on results** → DELEGATE to `researcher` 246 | - Searching for files by name → use `Glob` 247 | - Reading known file contents → use `Read` 248 | 249 | **How to use `Grep`:** 250 | - Supports full regex syntax (ripgrep-based) 251 | - Can specify directory path and glob pattern to narrow scope 252 | - Use `context_lines` parameter to see surrounding lines 253 | - Can perform multiple focused grep searches in parallel 254 | - **If you find yourself doing a second grep based on first results, you should have used `researcher`** 255 | 256 | 257 | 258 | **When to use `Read`:** 259 | - You need to examine file contents 260 | - Before editing any file (required) 261 | - You know the exact file path 262 | - Viewing images, PDFs, or Jupyter notebooks 263 | - Understanding code structure and implementation 264 | 265 | **When NOT to use `Read`:** 266 | - Searching for files by name → use `Glob` 267 | - Searching file contents across multiple files → use `Grep` 268 | - You want to use shell commands like cat → use `Read` instead 269 | 270 | **How to use `Read`:** 271 | - Default behavior reads up to 2000 lines from the beginning 272 | - For large files, use offset and limit parameters to read specific sections 273 | - Recommended to read the whole file by omitting offset/limit when possible 274 | - Always read before editing - the `Edit` tool will error otherwise 275 | - Can read multiple files in parallel by making multiple `Read` calls 276 | 277 | 278 | 279 | **When to use `Insert`:** 280 | - When you only need to add new content to a file. 281 | - When you know the exact line number for the insertion. 282 | - For purely additive actions that don't require changing surrounding context. 283 | 284 | **When NOT to use `Insert`:** 285 | - When you need to replace or modify existing text → use `Edit`. 286 | - When you need to create a new file entirely → use `Write`. 287 | 288 | **How to use `Insert`:** 289 | - The `line_number` parameter specifies the line *after* which to insert `new_str`. 290 | - Use `line_number: 0` to insert at the very beginning of the file. 291 | - Use `line_number: -1` to insert at the very end of the file. 292 | - This tool is preferred over `Edit` when only insertion is required. 293 | 294 | 295 | 296 | **When to use `Bash`:** 297 | - Terminal operations: git, npm, docker, cargo, etc. 298 | - Commands that truly require shell execution 299 | - Running builds, tests, or development servers 300 | - System administration tasks 301 | 302 | **When NOT to use `Bash`:** 303 | - File operations → use `Read`, `Write`, `Edit`, `Glob`, `Grep` instead 304 | - Finding files → use `Glob`, not find 305 | - Searching contents → use `Grep`, not grep/rg 306 | - Reading files → use `Edit`, not cat/head/tail 307 | - Editing files → use `Edit`, not sed/awk 308 | - Writing files → use `Write`, not echo or heredocs 309 | - Communication with user → output text directly, not echo 310 | 311 | **How to use `Bash`:** 312 | - Quote file paths with spaces using double quotes 313 | - Chain dependent commands with && (or ; if failures are OK) 314 | - Use absolute paths instead of cd when possible 315 | - For parallel commands, make multiple `Bash` calls in one message 316 | 317 | 318 | 319 | **When to use `Eval`:** 320 | - Testing elisp code snippets or expressions 321 | - Verifying code changes work correctly 322 | - Checking variable values or function behavior 323 | - Demonstrating elisp functionality to users 324 | - Calculating results instead of saying "I can't calculate that" 325 | - Quickly changing user settings or checking configuration 326 | - Exploring Emacs state or testing hypotheses 327 | 328 | **When NOT to use `Eval`:** 329 | - Multi-expression evaluations → make one call per expression (no progn) 330 | - Complex code that requires multiple statements → break into individual expressions 331 | - When you need to modify files → use `Edit` instead 332 | - For bash/shell operations → use `Bash` 333 | 334 | **How to use `Eval`:** 335 | - Provide a single elisp expression as a string 336 | - Can be function calls, variables, quasi-quoted expressions, or any valid elisp 337 | - Only the first sexp will be read and evaluated 338 | - Return values are formatted using %S (strings appear escaped, literals are `read`-compatible) 339 | - Some objects without printed representation show as # 340 | - Make one call per expression - don't combine with progn 341 | - Use for quick settings changes, variable checks, or demonstrations 342 | 343 | **Examples of good usage:** 344 | - `user-emacs-directory` → check variable value 345 | - `(setq my-var "new-value")` → change setting 346 | - `(length my-list)` → get list length 347 | - `(file-exists-p "/path/to/file")` → test file existence 348 | 349 | 350 | 351 | **When to use `Edit`:** 352 | - Modifying existing files with surgical precision 353 | - Making targeted changes to code or configuration 354 | - Replacing specific strings, functions, or sections 355 | - Any time you need to change part of an existing file 356 | 357 | **When NOT to use `Edit`:** 358 | - Creating brand new files → use `Write` 359 | - You haven't read the file yet → must `Read` first (tool will error) 360 | - The old_string is not unique and you want to replace all occurrences → use `replace_all: true` 361 | 362 | **How to use `Edit`:** 363 | - MUST `Read` the file first (required, tool will error otherwise) 364 | - Provide exact `old_string` to match (including proper indentation from file content, not line number prefixes) 365 | - Provide `new_string` as replacement (must be different from old_string) 366 | - The edit will FAIL if old_string is not unique 367 | - Preserve exact indentation from the file content (ignore line number prefixes from `Read` output) 368 | - Always prefer editing existing files over creating new ones 369 | 370 | 371 | 372 | **When to use `Write`:** 373 | - Creating new files that don't exist yet 374 | - Completely replacing the contents of an existing file 375 | - Generating new code, configuration, or documentation files 376 | 377 | **When NOT to use `Write`:** 378 | - Modifying existing files → use `Edit` instead (more precise and safer) 379 | - The file already exists and you only need to change part of it → use `Edit` 380 | - You haven't read the file first (if it exists) → `Read` first, then use `Edit` 381 | 382 | **How to use `Write`:** 383 | - Will overwrite existing files completely - use with caution 384 | - MUST use `Read` tool first if the file already exists (tool will error otherwise) 385 | - Always prefer editing existing files rather than creating new ones 386 | - Provide complete file content as a string 387 | - File path must be absolute, not relative 388 | 389 | 390 | 391 | **When to use `WebSearch`:** 392 | - Searching the web for current information 393 | - Finding recent documentation or updates 394 | - Researching topics beyond your knowledge cutoff 395 | - User requests information about recent events or current data 396 | 397 | **When NOT to use `WebSearch`:** 398 | - Fetching a known URL → use `WebFetch` instead 399 | - Searching local codebase → use Grep, `Glob` 400 | - Information within your knowledge cutoff that doesn't require current data 401 | 402 | **How to use `WebSearch`:** 403 | - Provide clear, specific search query 404 | - Returns search result blocks with relevant information 405 | - Account for current date when searching (e.g., don't use "2024" if current year is 2025) 406 | 407 | 408 | 409 | **When to use `WebFetch`:** 410 | - Fetching and analyzing web content when you need full context for potential follow-up questions 411 | - Retrieving documentation from URLs that are likely small (<1000 lines) 412 | - The user explicitly wants detailed analysis of the entire page 413 | 414 | **When NOT to use `WebFetch`:** 415 | - Extracting specific information from large webpages → use `Agent` to avoid context bloat 416 | - Searching the web for multiple results → use `WebSearch` instead 417 | - You need to guess or generate URLs → only use URLs provided by user or found in files 418 | - Local file operations → use `Read`, `Glob`, `Grep` 419 | 420 | **How to use `WebFetch`:** 421 | - For focused information extraction, delegate to `Agent` with `WebFetch` to get only relevant results 422 | - Direct use is appropriate when full content may be needed for follow-up questions 423 | - Requires a valid, fully-formed URL (HTTP automatically upgraded to HTTPS) 424 | - Provide a prompt describing what information to extract 425 | - Has 15-minute cache for faster repeated access 426 | - If redirected to different host, make new `WebFetch` with redirect URL 427 | 428 | 429 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /gptel-agent-tools.el: -------------------------------------------------------------------------------- 1 | ;;; gptel-agent-tools.el --- LLM tools for gptel-agent -*- lexical-binding: t; -*- 2 | 3 | ;; Copyright (C) 2025 Karthik Chikmagalur 4 | 5 | ;; Author: Karthik Chikmagalur 6 | ;; Keywords: 7 | 8 | ;; This program is free software; you can redistribute it and/or modify 9 | ;; it under the terms of the GNU General Public License as published by 10 | ;; the Free Software Foundation, either version 3 of the License, or 11 | ;; (at your option) any later version. 12 | 13 | ;; This program is distributed in the hope that it will be useful, 14 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | ;; GNU General Public License for more details. 17 | 18 | ;; You should have received a copy of the GNU General Public License 19 | ;; along with this program. If not, see . 20 | 21 | ;;; Commentary: 22 | 23 | ;; Adds the following gptel tools. 24 | ;; System: 25 | ;; - "Bash" : Execute a Bash command. 26 | ;; 27 | ;; Web: 28 | ;; - "WebSearch" : Search the web for the first five results to a query. 29 | ;; - "Read" : Fetch and read the contents of a URL. 30 | ;; - "YouTube" : Find the description and video transcript for a youtube video. 31 | ;; 32 | ;; Filesystem: 33 | ;; - "Mkdir" : Create a new directory. 34 | ;; - "Glob" : Find files matching a glob pattern 35 | ;; - "Grep" : Grep for text in file(s). 36 | ;; - "Read" : Read a specific line range from a file. 37 | ;; - "Insert" : Insert text at a specific line number in a file. 38 | ;; - "Edit" : Replace text in file(s) using string match or unified diff. 39 | ;; - "Write" : Create a new file with content. 40 | 41 | ;;; Code: 42 | 43 | 44 | 45 | (require 'gptel) 46 | (require 'eww) 47 | (require 'url-http) 48 | (eval-when-compile (require 'cl-lib)) 49 | 50 | (declare-function org-escape-code-in-region "org-src") 51 | 52 | (defvar url-http-end-of-headers) 53 | (defvar gptel-agent--agents) 54 | (defconst gptel-agent--hrule 55 | (propertize "\n" 'face '(:inherit shadow :underline t :extend t))) 56 | 57 | ;;; Tool use preview 58 | (defun gptel-agent--confirm-overlay (from to &optional no-hide) 59 | "Set up tool call preview overlay FROM TO. 60 | 61 | If NO-HIDE is non-nil, don't hide the overlay body by default." 62 | (let ((ov (make-overlay from to nil t))) 63 | (overlay-put ov 'evaporate t) 64 | (overlay-put ov 'gptel-agent-tool t) 65 | (overlay-put ov 'priority 10) 66 | (overlay-put ov 'keymap 67 | (make-composed-keymap 68 | (define-keymap 69 | "n" 'gptel-agent--next-overlay 70 | "p" 'gptel-agent--previous-overlay 71 | "q" 'gptel--reject-tool-calls 72 | "" 'gptel-agent--cycle-overlay 73 | "TAB" 'gptel-agent--cycle-overlay) 74 | gptel-tool-call-actions-map)) 75 | (unless no-hide 76 | (gptel-agent--cycle-overlay ov)) 77 | ov)) 78 | 79 | (defun gptel-agent--cycle-overlay (ov) 80 | "Cycle tool call preview overlay OV at point." 81 | (interactive (list (cdr (get-char-property-and-overlay 82 | (point) 'gptel-agent-tool)))) 83 | (save-excursion 84 | (goto-char (overlay-start ov)) 85 | (let ((line-end (line-end-position)) 86 | (end (overlay-end ov))) 87 | (pcase-let ((`(,value . ,hide-ov) 88 | (get-char-property-and-overlay line-end 'invisible))) 89 | (if (and hide-ov (eq value t)) 90 | (delete-overlay hide-ov) 91 | (unless hide-ov (setq hide-ov (make-overlay line-end (1- end) nil t))) 92 | (overlay-put hide-ov 'evaporate t) 93 | (overlay-put hide-ov 'invisible t) 94 | (overlay-put hide-ov 'before-string " ▼")))))) 95 | 96 | (defun gptel-agent--next-overlay () 97 | "Jump to the next `gptel-agent' tool overlay." 98 | (interactive) 99 | (when-let* ((ov (cdr (get-char-property-and-overlay 100 | (point) 'gptel-agent-tool))) 101 | (end (overlay-end ov))) 102 | (when (get-char-property end 'gptel-tool) 103 | (goto-char end)))) 104 | 105 | (defun gptel-agent--previous-overlay () 106 | "Jump to the previous `gptel-agent' tool overlay." 107 | (interactive) 108 | (when-let* ((ov (cdr (get-char-property-and-overlay 109 | (1- (point)) 'gptel-agent-tool)))) 110 | (goto-char (overlay-start ov)))) 111 | 112 | (defsubst gptel-agent--block-bg () 113 | "Return a background face suitable for displaying code." 114 | (cond 115 | ((derived-mode-p 'org-mode) 'org-block) 116 | ((derived-mode-p 'markdown-mode) 'markdown-code-face) 117 | (t `( :background ,(face-attribute 'mode-line-inactive :background) 118 | :extend t)))) 119 | 120 | (defun gptel-agent--fontify-block (path-or-mode start end) 121 | "Fontify region from START to END. 122 | 123 | Fontification is assuming it is the contents of file PATH-OR-MODE (if it 124 | is a string), or major-mode (if it is a symbol). Applied font-lock-face 125 | properties persist through refontification." 126 | (let ((lang-mode) ; (org-src-get-lang-mode lang) 127 | (org-buffer (current-buffer))) 128 | (with-temp-buffer 129 | (insert-buffer-substring-no-properties org-buffer start end) 130 | (insert " ") ; Add space to ensure property change 131 | (if (symbolp path-or-mode) 132 | (setq lang-mode path-or-mode) 133 | (let ((buffer-file-name path-or-mode)) 134 | (setq lang-mode 135 | (or (cdr (assoc-string 136 | (concat 137 | "\\." (file-name-extension path-or-mode) "\\'") 138 | auto-mode-alist)) 139 | (progn (set-auto-mode t) major-mode))))) 140 | (delay-mode-hooks (funcall lang-mode)) 141 | (font-lock-ensure) 142 | (let ((pos (point-min))) 143 | (while (< pos (1- (point-max))) ; Skip the added space 144 | (let* ((next (next-property-change pos nil (1- (point-max)))) 145 | (face-prop (get-text-property pos 'face))) 146 | (when face-prop 147 | (put-text-property 148 | (+ start (- pos (point-min))) 149 | (+ start (- (or next (1- (point-max))) (point-min))) 150 | 'font-lock-face face-prop org-buffer)) 151 | (setq pos (or next (1- (point-max)))))))))) 152 | 153 | ;;; System tools 154 | ;; "Execute Bash commands to inspect files and system state. 155 | 156 | ;; This tool provides access to a Bash shell with GNU coreutils (or equivalents) 157 | ;; available. You can use any standard Linux commands including: cd, ls, file, cat, 158 | ;; grep, awk, sed, head, tail, wc, find, sort, uniq, cut, tr, and more. 159 | 160 | ;; PURPOSE: 161 | ;; - Efficiently inspect files and system state WITHOUT consuming excessive 162 | ;; tokens. This is preferred over reading entire large files. 163 | ;; - Modify files or system state as appropriate, using cp, mv, rm, patch, 164 | ;; git subcommands (git log, commit, branch and more) and so on. 165 | 166 | ;; BEST PRACTICES: 167 | ;; - Use pipes to combine commands: 'cat file.log | grep ERROR | tail -20' 168 | ;; - For large files, use head/tail: 'head -50 file.txt' or 'tail -100 file.log' 169 | ;; - Use grep with context: 'grep -A 5 -B 5 pattern file.txt' 170 | ;; - Check file sizes first: 'wc -l file.txt' before reading 171 | ;; - Use file command to identify file types: 'file *' 172 | ;; - Combine with other tools: 'find . -name \"*.el\" | head -10' 173 | 174 | ;; EXAMPLES: 175 | ;; - List files with details: 'ls -lah /path/to/dir' 176 | ;; - Print lines 25-35 of a long file/stream: 'sed -n \"25,35p\" app.log' 177 | ;; - Find recent errors: 'grep -i error /var/log/app.log | tail -20' 178 | ;; - Check file type: 'file document.pdf' 179 | ;; - Count lines: 'wc -l *.txt' 180 | ;; - Search with context: 'grep -A 3 \"function foo\" script.sh' 181 | 182 | ;; The command will be executed in the current working directory. Output is 183 | ;; returned as a string. Long outputs should be filtered/limited using pipes." 184 | 185 | ;; - Can run commands in background with `run_in_background: true` 186 | ;; - Default timeout is 2 minutes (120000ms), max is 10 minutes 187 | 188 | (defun gptel-agent--eval-elisp-preview-setup (arg-values _info) 189 | "Setup preview overlay for Elisp evaluation tool call. 190 | 191 | ARG-VALUES is the list of arguments for the tool call." 192 | (let ((expr (car arg-values)) 193 | (from (point)) (inner-from)) 194 | (insert 195 | "(" (propertize "Eval" 'font-lock-face 'font-lock-keyword-face) 196 | ")\n") 197 | (setq inner-from (point)) 198 | (insert expr) 199 | (gptel-agent--fontify-block 'emacs-lisp-mode inner-from (point)) 200 | ;; (add-text-properties inner-from (point) '(line-prefix " " wrap-prefix " ")) 201 | (insert "\n\n") 202 | (font-lock-append-text-property 203 | inner-from (1- (point)) 'font-lock-face (gptel-agent--block-bg)) 204 | (gptel-agent--confirm-overlay from (point) t))) 205 | 206 | (defun gptel-agent--execute-bash-preview-setup (arg-values _info) 207 | "Setup preview overlay for Bash command execution tool call. 208 | 209 | ARG-VALUES is the list of arguments for the tool call." 210 | (let ((command (car arg-values)) 211 | (from (point)) (inner-from)) 212 | (insert 213 | "(" (propertize "Bash" 'font-lock-face 'font-lock-keyword-face) 214 | ")\n") 215 | (setq inner-from (point)) 216 | (insert command) 217 | (gptel-agent--fontify-block 'sh-mode inner-from (point)) 218 | (insert "\n\n") 219 | (font-lock-append-text-property 220 | inner-from (1- (point)) 'font-lock-face (gptel-agent--block-bg)) 221 | (gptel-agent--confirm-overlay from (point) t))) 222 | 223 | ;;; Web tools 224 | 225 | (defun gptel-agent--fetch-with-timeout (url url-cb tool-cb failed-msg &rest args) 226 | "Fetch URL and call URL-CB in the result buffer. 227 | 228 | Call TOOL-CB if there is an error or a timeout. TOOL-CB and ARGS are 229 | passed to URL-CB. FAILED-MSG is a fragment used for messaging. Handles 230 | cleanup." 231 | (let* ((timeout 30) timer done 232 | (inherit-process-coding-system t) 233 | (proc-buffer 234 | (url-retrieve 235 | url (lambda (status) 236 | (setq done t) 237 | (when timer (cancel-timer timer)) 238 | (if-let* ((err (plist-get status :error))) 239 | (funcall tool-cb 240 | (format "Error: %s failed with error: %S" failed-msg err)) 241 | (apply url-cb tool-cb args)) 242 | (kill-buffer (current-buffer))) 243 | args 'silent))) 244 | (setq timer 245 | (run-at-time 246 | timeout nil 247 | (lambda (buf cb) 248 | (unless done 249 | (setq done t) 250 | (let ((kill-buffer-query-functions)) (kill-buffer buf)) 251 | (funcall 252 | cb (format "Error: %s timed out after %d seconds." 253 | failed-msg timeout)))) 254 | proc-buffer tool-cb)) 255 | proc-buffer)) 256 | 257 | ;;;; Web search 258 | (defun gptel-agent--shr-next-link () 259 | "Jump to the next SHR link in the buffer. Return jump position." 260 | (let ((current-prop (get-char-property (point) 'shr-url)) 261 | (next-pos (point))) 262 | (while (and (not (eobp)) 263 | (setq next-pos 264 | (or (next-single-property-change (point) 'shr-url) 265 | (point-max))) 266 | (let ((next-prop (get-char-property next-pos 'shr-url))) 267 | (or (equal next-prop current-prop) 268 | (equal next-prop nil)))) 269 | (goto-char next-pos)) 270 | (goto-char next-pos))) 271 | 272 | (defvar gptel-agent--web-search-active nil) 273 | 274 | (defun gptel-agent--web-search-eww (tool-cb query &optional count) 275 | "Search the web using eww's default search engine (usually DuckDuckGo). 276 | 277 | Call TOOL-CB with the results as a string. QUERY is the search string. 278 | COUNT is the number of results to return (default 5)." 279 | ;; No more than two active searches at one time 280 | (setq gptel-agent--web-search-active 281 | (cl-delete-if-not 282 | (lambda (buf) (and (buffer-live-p buf) 283 | (process-live-p (get-buffer-process buf)))) 284 | gptel-agent--web-search-active)) 285 | (if (>= (length gptel-agent--web-search-active) 2) 286 | (progn (message "Web search: waiting for turn") 287 | (run-at-time 5 nil #'gptel-agent--web-search-eww 288 | tool-cb query count)) 289 | (push (gptel-agent--fetch-with-timeout 290 | (concat eww-search-prefix (url-hexify-string query)) 291 | #'gptel-agent--web-search-eww-callback 292 | tool-cb (format "Web search for \"%s\"" query)) 293 | gptel-agent--web-search-active))) 294 | 295 | (defun gptel-agent--web-fix-unreadable () 296 | "Replace invalid characters from point to end in current buffer." 297 | (while (and (skip-chars-forward "\0-\x3fff7f") 298 | (not (eobp))) 299 | (display-warning 300 | '(gptel gptel-agent-tools) 301 | (format "Invalid character in buffer \"%s\"" (buffer-name))) 302 | (delete-char 1) (insert "?"))) 303 | 304 | (defun gptel-agent--web-search-eww-callback (cb) 305 | "Extract website text and run callback CB with it." 306 | (let* ((count 5) (results)) 307 | (goto-char (point-min)) 308 | (goto-char url-http-end-of-headers) 309 | ;; (gptel-agent--web-fix-unreadable) 310 | (let* ((dom (libxml-parse-html-region (point) (point-max))) 311 | (result-count 0)) 312 | (eww-score-readability dom) 313 | ;; (erase-buffer) (buffer-disable-undo) 314 | (with-temp-buffer 315 | (shr-insert-document (eww-highest-readability dom)) 316 | (goto-char (point-min)) 317 | (while (and (not (eobp)) (< result-count count)) 318 | (let ((pos (point)) 319 | (url (get-char-property (point) 'shr-url)) 320 | (next-pos (gptel-agent--shr-next-link))) 321 | (when-let* (((stringp url)) 322 | (idx (string-search "http" url)) 323 | (url-fmt (url-unhex-string (substring url idx)))) 324 | (cl-incf result-count) 325 | (push (concat url-fmt "\n\n" 326 | (string-trim 327 | (buffer-substring-no-properties pos next-pos)) 328 | "\n\n----\n") 329 | results)))))) 330 | (funcall cb (apply #'concat (nreverse results))))) 331 | 332 | ;;;; Read URLs 333 | (defun gptel-agent--read-url (tool-cb url) 334 | "Fetch URL text and call TOOL-CB with it." 335 | (gptel-agent--fetch-with-timeout 336 | url 337 | (lambda (cb) 338 | (goto-char (point-min)) (forward-paragraph) 339 | (condition-case errdata 340 | (let ((dom (libxml-parse-html-region (point) (point-max)))) 341 | (with-temp-buffer 342 | (eww-score-readability dom) 343 | (shr-insert-document (eww-highest-readability dom)) 344 | (decode-coding-region (point-min) (point-max) 'utf-8) 345 | (funcall 346 | cb (buffer-substring-no-properties 347 | (point-min) (point-max))))) 348 | (error (funcall cb (format "Error: Request failed with error data:\n%S" 349 | errdata))))) 350 | tool-cb (format "Fetch for \"%s\"" url))) 351 | 352 | ;;;; Fetch youtube transcript 353 | (defun gptel-agent--yt-parse-captions (xml-string) 354 | "Parse YouTube caption XML-STRING and return DOM." 355 | (with-temp-buffer 356 | (insert xml-string) 357 | (goto-char (point-min)) 358 | ;; Clean up the XML 359 | (dolist (reps '(("\n" . " ") 360 | ("&" . "&") 361 | (""" . "\"") 362 | ("'" . "'") 363 | ("<" . "<") 364 | (">" . ">"))) 365 | (save-excursion 366 | (while (search-forward (car reps) nil t) 367 | (replace-match (cdr reps) nil t)))) 368 | (libxml-parse-xml-region (point-min) (point-max)))) 369 | 370 | (defun gptel-agent--yt-format-captions (caption-dom &optional chunk-time) 371 | "Format CAPTION-DOM as paragraphs with timestamps. 372 | 373 | CHUNK-TIME is the number of seconds per paragraph (default 30)." 374 | (when (and (listp caption-dom) 375 | (eq (car-safe caption-dom) 'transcript)) 376 | (let ((chunk-time (or chunk-time 30)) 377 | (result "") 378 | (current-para "") 379 | (para-start-time 0)) 380 | (dolist (elem (cddr caption-dom)) ;; Process each text element 381 | (when (and (listp elem) (eq (car elem) 'text)) 382 | (let* ((attrs (cadr elem)) 383 | (text (caddr elem)) 384 | (start (string-to-number (cdr (assoc 'start attrs)))) 385 | ;; Check if we've crossed into a new chunk-time boundary 386 | (should-chunk (and (> (abs (- start para-start-time)) 3) 387 | (not (= (floor para-start-time chunk-time) 388 | (floor start chunk-time)))))) 389 | (when (and should-chunk (> (length current-para) 0)) 390 | ;; Add completed paragraph 391 | (setq result (concat result 392 | (format "[%d:%02d]\n%s\n\n" 393 | (floor para-start-time 60) 394 | (mod para-start-time 60) 395 | (string-trim current-para)))) 396 | (setq current-para "") 397 | (setq para-start-time start)) 398 | 399 | (when text 400 | (setq current-para (concat current-para " " text)))))) 401 | 402 | ;; Add final paragraph 403 | (when (> (length current-para) 0) 404 | (setq result (concat result 405 | (format "[%d:%02d]\n%s\n\n" 406 | (floor para-start-time 60) 407 | (mod para-start-time 60) 408 | (string-trim current-para))))) 409 | result))) 410 | 411 | (defun gptel-agent--yt-fetch-watch-page (callback video-id) 412 | "Step 1: Fetch YouTube watch page for VIDEO-ID. 413 | 414 | Call CALLBACK with error or proceeds to fetch InnerTube data." 415 | (url-retrieve 416 | (format "https://youtube.com/watch?v=%s" video-id) 417 | (lambda (status callback video-id) 418 | (if-let ((error (plist-get status :error))) 419 | (funcall callback (format "Error fetching page: %s" error)) 420 | (goto-char (point-min)) 421 | (search-forward "\n\n" nil t) 422 | (let* ((html (buffer-substring (point) (point-max))) 423 | (api-key (and (string-match 424 | "\"INNERTUBE_API_KEY\":\"\\([a-zA-Z0-9_-]+\\)" 425 | html) 426 | (match-string 1 html)))) 427 | (if api-key 428 | (gptel-agent--yt--fetch-innertube callback video-id api-key) 429 | (funcall callback "Error: Could not extract API key"))))) 430 | (list callback video-id))) 431 | 432 | (defun gptel-agent--yt--fetch-innertube (callback video-id api-key) 433 | "Step 2: Fetch VIDEO-ID metadata from YouTube InnerTube API. 434 | 435 | Call CALLBACK with error or proceeds to fetch captions." 436 | (let ((url-request-method "POST") 437 | (url-request-extra-headers 438 | '(("Content-Type" . "application/json") 439 | ("Accept-Language" . "en-US"))) 440 | (url-request-data 441 | (encode-coding-string 442 | (json-encode 443 | `((context . ((client . ((clientName . "ANDROID") 444 | (clientVersion . "20.10.38"))))) 445 | (videoId . ,video-id))) 446 | 'utf-8))) 447 | (url-retrieve 448 | (format "https://www.youtube.com/youtubei/v1/player?key=%s" api-key) 449 | (lambda (status callback) 450 | (if-let ((error (plist-get status :error))) 451 | (funcall callback (format "Error fetching metadata: %s" error)) 452 | (goto-char (point-min)) 453 | (search-forward "\n\n" nil t) 454 | (let* ((json-data (ignore-errors 455 | (json-parse-buffer :object-type 'plist))) 456 | (video-details (plist-get json-data :videoDetails)) 457 | (description (plist-get video-details :shortDescription)) 458 | (caption-tracks (map-nested-elt 459 | json-data 460 | '(:captions 461 | :playerCaptionsTracklistRenderer 462 | :captionTracks)))) 463 | (gptel-agent--yt-fetch-captions callback description caption-tracks)))) 464 | (list callback)))) 465 | 466 | (defun gptel-agent--yt-fetch-captions (callback description caption-tracks) 467 | "Step 3: Find and fetch English captions for CAPTION-TRACKS. 468 | 469 | Call CALLBACK with formatted result containing DESCRIPTION and transcript." 470 | (if (not caption-tracks) 471 | (funcall callback 472 | (format "# Description\n\n%s\n\n# Transcript\n\nNo transcript available." 473 | (or description "No description available."))) 474 | (let ((en-caption 475 | (cl-find-if 476 | (lambda (track) 477 | (string-match-p "^en" (or (plist-get track :languageCode) ""))) 478 | caption-tracks))) 479 | (if (not en-caption) 480 | (funcall callback 481 | (format "# Description\n\n%s\n\n# Transcript\n\nNo English transcript available." 482 | (or description "No description available."))) 483 | (let ((base-url (replace-regexp-in-string 484 | "&fmt=srv3" "" 485 | (plist-get en-caption :baseUrl)))) 486 | (url-retrieve 487 | base-url 488 | (lambda (status callback description) 489 | (if-let ((error (plist-get status :error))) 490 | (funcall callback 491 | (format "# Description\n\n%s\n\n# Transcript\n\nError fetching transcript: %s" 492 | (or description "No description available.") 493 | error)) 494 | (goto-char (point-min)) 495 | (search-forward "\n\n" nil t) 496 | (let* ((xml-string (buffer-substring (point) (point-max))) 497 | (caption-dom (gptel-agent--yt-parse-captions xml-string)) 498 | (formatted-transcript 499 | (gptel-agent--yt-format-captions caption-dom 30))) 500 | (funcall callback 501 | (format "# Description\n\n%s\n\n# Transcript\n\n%s" 502 | (or description "No description available.") 503 | (or formatted-transcript "Error parsing transcript.")))))) 504 | (list callback description))))))) 505 | 506 | (defun gptel-agent--yt-read-url (callback url) 507 | "Fetch YouTube metadata and transcript for URL, calling CALLBACK with result. 508 | CALLBACK is called with a markdown-formatted string containing the video 509 | description and transcript formatted as timestamped paragraphs." 510 | (if-let* ((video-id 511 | (and (string-match 512 | (rx bol (opt "http" (opt "s") "://") 513 | (opt "www.") "youtu" (or ".be" "be.com") "/" 514 | (opt "watch?v=") 515 | (group (one-or-more (not (any "?&"))))) 516 | url) 517 | (match-string 1 url)))) 518 | (gptel-agent--yt-fetch-watch-page callback video-id) 519 | (funcall callback "Error: Invalid YouTube URL"))) 520 | 521 | ;;; Code tools 522 | ;;;; Diagnostics from flymake 523 | (declare-function flymake--project-diagnostics "flymake") 524 | (declare-function flymake--diag-beg "flymake") 525 | (declare-function flymake--diag-type "flymake") 526 | (declare-function flymake--diag-text "flymake") 527 | (declare-function flymake-diagnostic-buffer "flymake") 528 | 529 | (defun gptel-agent--flymake-diagnostics (&optional all) 530 | "Collect flymake errors across all open buffers in the current project. 531 | 532 | Errors with low severity are not collected. With ALL, collect all 533 | diagnostics." 534 | (let ((project (project-current))) 535 | (unless project 536 | (error "Not in a project. Cannot collect flymake diagnostics")) 537 | (require 'flymake) 538 | (let ((results '())) 539 | (dolist (diag (flymake--project-diagnostics project)) 540 | (let ((severity (flymake--diag-type diag))) 541 | (when (memq severity `(:error :warning ,@(and all '(:note)))) 542 | (with-current-buffer (flymake-diagnostic-buffer diag) 543 | (let* ((beg (flymake--diag-beg diag)) 544 | (line-num (line-number-at-pos beg)) 545 | (line-text (buffer-substring-no-properties 546 | (line-beginning-position) (line-end-position)))) 547 | (push (format "File: %s:%d\nSeverity: %s\nMessage: %s\n---\n%s" 548 | (buffer-file-name) 549 | line-num 550 | severity 551 | (flymake--diag-text diag) 552 | line-text) 553 | results)))))) 554 | (string-join (nreverse results) "\n\n")))) 555 | 556 | ;;; Filesystem tools 557 | ;;;; Make directories 558 | ;;;; Writing to files 559 | (defun gptel-agent--edit-files-preview-setup (arg-values _info) 560 | "Insert tool call preview for ARG-VALUES for \"Edit\" tool." 561 | (pcase-let ((from (point)) (files-affected) (description) 562 | (`(,path ,old-str ,new-str-or-diff ,diffp) arg-values)) 563 | 564 | (if (and diffp (not (eq diffp :json-false))) 565 | (progn ;Patch 566 | (insert new-str-or-diff) 567 | (save-excursion 568 | (while (re-search-backward "^\\+\\+\\+ \\(.*\\)$" from t) 569 | (push (match-string 1) files-affected)) 570 | (goto-char from) 571 | (when (looking-at "^ *```\\(diff\\|patch\\)\\s-*\n") 572 | (delete-region (match-beginning 0) (match-end 0)))) 573 | (skip-chars-backward " \t\r\n") (forward-line 0) 574 | (when (looking-at-p "^ *```\\s-*\\'") 575 | (delete-region (line-beginning-position) (line-end-position))) 576 | (setq description "Patch") 577 | (require 'diff-mode) 578 | (gptel-agent--fontify-block 'diff-mode from (point))) 579 | (when old-str ;Text replacement 580 | (push path files-affected) 581 | (setq description "ReplaceIn") 582 | (insert 583 | (propertize old-str 'font-lock-face 'diff-removed 584 | 'line-prefix (propertize "-" 'face 'diff-removed)) 585 | "\n" (propertize new-str-or-diff 'font-lock-face 'diff-added 586 | 'line-prefix (propertize "+" 'face 'diff-added)) 587 | "\n"))) 588 | (insert "\n") 589 | (font-lock-append-text-property 590 | from (1- (point)) 'font-lock-face (gptel-agent--block-bg)) 591 | (when (derived-mode-p 'org-mode) 592 | (org-escape-code-in-region from (1- (point)))) 593 | (save-excursion 594 | (goto-char from) 595 | (insert 596 | "(" (propertize description 'font-lock-face 'font-lock-keyword-face) 597 | " " (mapconcat (lambda (f) (propertize (concat "\"" f "\"") 598 | 'font-lock-face 'font-lock-constant-face)) 599 | files-affected " ") 600 | ")\n")) 601 | (gptel-agent--confirm-overlay from (point) t))) 602 | 603 | (defun gptel-agent--fix-patch-headers () 604 | "Fix line numbers in hunks in diff at point." 605 | ;; Find and process each hunk header 606 | (while (re-search-forward "^@@ -\\([0-9]+\\),\\([0-9]+\\) +\\+\\([0-9]+\\),\\([0-9]+\\) @@" nil t) 607 | (let ((hunk-start (line-beginning-position)) 608 | (orig-line (string-to-number (match-string 1))) 609 | (new-line (string-to-number (match-string 3))) 610 | (orig-count 0) 611 | (new-count 0)) 612 | 613 | ;; Count lines in this hunk until we hit the next @@ or EOF 614 | (goto-char hunk-start) 615 | (forward-line 1) 616 | (save-match-data 617 | (while (and (not (eobp)) 618 | (not (looking-at-p "^@@"))) 619 | (cond 620 | ;; Removed lines (not ---) 621 | ((looking-at-p "^-[^-]") 622 | (cl-incf orig-count)) 623 | ;; Added lines (not +++) 624 | ((looking-at-p "^\\+[^+]") 625 | (cl-incf new-count)) 626 | ;; Context lines (space at start) 627 | ((looking-at-p "^ ") 628 | (cl-incf orig-count) 629 | (cl-incf new-count))) 630 | (forward-line 1))) 631 | 632 | ;; Replace the hunk header with corrected counts 633 | (goto-char hunk-start) 634 | (delete-line) 635 | (insert (format "@@ -%d,%d +%d,%d @@\n" 636 | orig-line orig-count new-line new-count))))) 637 | 638 | (defun gptel-agent--edit-files (path &optional old-str new-str-or-diff diffp) 639 | "Replace text in file(s) at PATH using either string matching or unified diff. 640 | 641 | This function supports two distinct modes of operation: 642 | 643 | 1. STRING REPLACEMENT MODE (DIFFP is nil or :json-false): 644 | - Searches for OLD-STR in the file at PATH 645 | - Replaces it with NEW-STR-OR-DIFF 646 | - Requires OLD-STR to match exactly once (uniquely) in the file 647 | - Only works on single files, not directories 648 | 649 | 2. DIFF/PATCH MODE (when DIFFP is non-nil and not :json-false): 650 | - Applies NEW-STR-OR-DIFF as a unified diff using the `patch` command 651 | - Works on both single files and directories 652 | - OLD-STR is ignored in this mode 653 | - NEW-STR-OR-DIFF can contain the diff in fenced code blocks 654 | (=diff or =patch) 655 | - Uses the -N (--forward) option to ignore already-applied patches 656 | 657 | PATH - File or directory path to modify (must be readable) 658 | OLD-STR - (String mode only) Exact text to find and replace 659 | NEW-STR-OR-DIFF - Replacement text (string mode) or unified diff (diff mode) 660 | DIFFP - If non-nil (and not :json-false), use diff/patch mode 661 | 662 | Error Conditions: 663 | - PATH not readable 664 | - (String mode) PATH is a directory 665 | - (String mode) OLD-STR not found in file 666 | - (String mode) OLD-STR matches multiple times (ambiguous) 667 | - (Diff mode) patch command fails (exit status non-zero) 668 | 669 | Returns: 670 | Success message string describing what was changed 671 | 672 | Signals: 673 | error - On any failure condition (caught and displayed by gptel)" 674 | (unless (file-readable-p path) 675 | (error "Error: File or directory %s is not readable" path)) 676 | 677 | (unless new-str-or-diff 678 | (error "Required argument `new_str' missing")) 679 | 680 | (if (or (eq diffp :json-false) old-str) 681 | ;; Replacement by Text 682 | (progn 683 | (when (file-directory-p path) 684 | (error "Error: String replacement is intended for single files, not directories (%s)" 685 | path)) 686 | (with-temp-buffer 687 | (insert-file-contents path) 688 | (if (search-forward old-str nil t) 689 | (if (save-excursion (search-forward old-str nil t)) 690 | (error "Error: Match is not unique.\ 691 | Consider providing more context for the replacement, or a unified diff") 692 | ;; TODO: More robust backspace escaping 693 | (replace-match (string-replace "\\" "\\\\" new-str-or-diff)) 694 | (write-region nil nil path) 695 | (format "Successfully replaced %s (truncated) with %s (truncated)" 696 | (truncate-string-to-width old-str 20 nil nil t) 697 | (truncate-string-to-width new-str-or-diff 20 nil nil t))) 698 | (error "Error: Could not find old_str \"%s\" in file %s" 699 | (truncate-string-to-width old-str 20) path)))) 700 | ;; Replacement by Diff 701 | (unless (executable-find "patch") 702 | (error "Error: Command \"patch\" not available, cannot apply diffs.\ 703 | Use string replacement instead")) 704 | (let* ((out-buf-name (generate-new-buffer-name "*patch-stdout*")) 705 | ;; (err-buf-name (generate-new-buffer-name "*patch-stderr*")) 706 | (target-file (expand-file-name path)) 707 | (exit-status -1) ; Initialize to a known non-zero value 708 | (result-output "") 709 | ;; (result-error "") 710 | ) 711 | (unwind-protect 712 | (let ((default-directory (file-name-directory (expand-file-name path))) 713 | (patch-options '("--forward" "--verbose"))) 714 | 715 | (with-temp-message 716 | (format "Applying diff to: `%s` with options: %s" 717 | target-file patch-options) 718 | (with-temp-buffer 719 | (insert new-str-or-diff) 720 | ;; Insert trailing newline, required by patch 721 | (unless (eq (char-before (point-max)) ?\n) 722 | (goto-char (point-max)) 723 | (insert "\n")) 724 | (goto-char (point-min)) 725 | ;; Remove code fences, if present 726 | (when (looking-at-p "^ *```diff\n") 727 | (save-excursion 728 | (delete-line) 729 | (goto-char (point-max)) 730 | (forward-line -1) ;guaranteed to be at a blank newline 731 | (when (looking-at-p "^ *```") (delete-line)))) 732 | ;; Fix line numbers in hunk headers 733 | (gptel-agent--fix-patch-headers) 734 | 735 | (setq exit-status 736 | (apply #'call-process-region (point-min) (point-max) 737 | "patch" nil (list out-buf-name t) ; stdout/stderr buffer names 738 | nil patch-options)))) 739 | 740 | ;; Retrieve content from buffers using their names 741 | (when-let* ((stdout-buf (get-buffer out-buf-name))) 742 | (when (buffer-live-p stdout-buf) 743 | (with-current-buffer stdout-buf 744 | (setq result-output (buffer-string))))) 745 | 746 | (if (= exit-status 0) 747 | (format "Diff successfully applied to %s. 748 | Patch command options: %s 749 | Patch STDOUT:\n%s" 750 | target-file patch-options result-output) 751 | ;; Signal an Elisp error, which gptel will catch and display. 752 | ;; The arguments to 'error' become the error message. 753 | (error "Error: Failed to apply diff to %s (exit status %s). 754 | Patch command options: %s 755 | Patch STDOUT:\n%s" 756 | target-file exit-status patch-options 757 | result-output))) 758 | (let ((stdout-buf-obj (get-buffer out-buf-name))) ;Clean up 759 | (when (buffer-live-p stdout-buf-obj) (kill-buffer stdout-buf-obj))))))) 760 | 761 | (defun gptel-agent--insert-in-file-preview-setup (arg-values _info) 762 | "Preview setup for Insert. 763 | INFO is the tool call info plist. 764 | ARG-VALUES is a list: (path line-number new-str)" 765 | (let ((from (point)) (line-offset) 766 | (face-bg (gptel-agent--block-bg)) 767 | (cb (current-buffer))) 768 | (pcase-let ((`(,path ,line-number ,new-str) arg-values)) 769 | (insert "(" 770 | (propertize "insert_into_file " 'font-lock-face 'font-lock-keyword-face) 771 | (propertize (concat "\"" path "\"") 772 | 'font-lock-face 'font-lock-constant-face) 773 | ")\n") 774 | (if (file-readable-p path) 775 | (insert 776 | (with-temp-buffer ;NEW-STR with context lines, styled as a diff 777 | (insert-file-contents path) 778 | (pcase line-number 779 | (-1 (goto-char (point-max))) 780 | (_ (forward-line line-number))) 781 | (save-excursion 782 | (forward-line -6) 783 | (setq line-offset (line-number-at-pos)) 784 | (delete-region (point-min) (point)) 785 | (dotimes (_ 12) 786 | (put-text-property 787 | (line-beginning-position) (line-end-position) 788 | 'line-prefix (propertize (format "%4d " line-offset) 'face 789 | `(:inherit ,face-bg :inherit line-number))) 790 | (forward-line 1) (when (eolp) (insert " ")) 791 | (cl-incf line-offset))) 792 | (insert (propertize new-str 'font-lock-face 'diff-added 793 | 'fontified t 'font-lock-multiline t 794 | 'line-prefix (propertize " + " 'face 'diff-added))) 795 | (save-excursion 796 | (forward-line 6) 797 | (delete-region (point) (point-max))) 798 | (font-lock-append-text-property 799 | (point-min) (point-max) 'font-lock-face face-bg) 800 | (when (provided-mode-derived-p 801 | (buffer-local-value 'major-mode cb) 'org-mode) 802 | (org-escape-code-in-region (point-min) (point-max))) 803 | (buffer-string)) "\n") 804 | (insert (propertize "[File not readable]\n\n" 'font-lock-face 'error))) 805 | (gptel-agent--confirm-overlay from (point))))) 806 | 807 | (defun gptel-agent--insert-in-file (path line-number new-str) 808 | "Insert NEW-STR at LINE-NUMBER in file at PATH. 809 | 810 | LINE-NUMBER conventions: 811 | - 0 inserts at the beginning of the file 812 | - -1 inserts at the end of the file 813 | - N > 1 inserts before line N" 814 | (unless (file-readable-p path) 815 | (error "Error: File %s is not readable" path)) 816 | 817 | (when (file-directory-p path) 818 | (error "Error: Cannot insert into directory %s" path)) 819 | 820 | (with-temp-buffer 821 | (insert-file-contents path) 822 | 823 | (pcase line-number 824 | (0 (goto-char (point-min))) ; Insert at the beginning 825 | (-1 (goto-char (point-max))) ; Insert at the end 826 | (_ (goto-char (point-min)) 827 | (forward-line line-number))) ; Insert before line N 828 | 829 | ;; Insert the new string 830 | (insert new-str) 831 | 832 | ;; Ensure there's a newline after the inserted text if not already present 833 | (unless (or (string-suffix-p "\n" new-str) (eobp)) 834 | (insert "\n")) 835 | 836 | ;; Write the modified content back to the file 837 | (write-region nil nil path) 838 | 839 | (format "Successfully inserted text at line %d in %s" line-number path))) 840 | 841 | (defun gptel-agent--write-file-preview-setup (arg-values _info) 842 | "Setup preview overlay for Write file tool call. 843 | 844 | ARG-VALUES is the list of arguments for the tool call." 845 | (pcase-let ((from (point)) 846 | (`(,path ,filename ,content) arg-values)) 847 | (insert 848 | "(" (propertize "Write " 'font-lock-face 'font-lock-keyword-face) 849 | (propertize (prin1-to-string path) 'font-lock-face 'font-lock-constant-face) " " 850 | (propertize (prin1-to-string filename) 'font-lock-face 'font-lock-constant-face) 851 | ")\n") 852 | (let ((inner-from (point))) 853 | (insert content) 854 | (gptel-agent--fontify-block filename inner-from (point)) 855 | (insert "\n\n") 856 | (font-lock-append-text-property 857 | inner-from (1- (point)) 'font-lock-face (gptel-agent--block-bg)) 858 | (when (derived-mode-p 'org-mode) 859 | (org-escape-code-in-region inner-from (1- (point))))) 860 | (gptel-agent--confirm-overlay from (point)))) 861 | 862 | ;;;; Read files or directories 863 | (defun gptel-agent--read-file-lines (filename start-line end-line) 864 | "Return lines START-LINE to END-LINE fom FILENAME." 865 | (unless (file-readable-p filename) 866 | (error "Error: File %s is not readable" filename)) 867 | 868 | (when (file-directory-p filename) 869 | (error "Error: Cannot read directory %s as file" filename)) 870 | 871 | (when (file-symlink-p filename) 872 | (setq filename (file-truename filename))) 873 | 874 | (if (and (not start-line) (not end-line)) ;read full file 875 | (if (> (file-attribute-size (file-attributes filename)) 876 | (* 512 1024)) 877 | (error "Error: File is too large (> 512 KB).\ 878 | Please specify a line range to read") 879 | (with-temp-buffer 880 | (insert-file-contents filename) 881 | (buffer-string))) 882 | ;; TODO: Handle nil start-line OR nil end-line 883 | (cl-decf start-line) 884 | (let* ((file-size (nth 7 (file-attributes filename))) 885 | (chunk-size (min file-size (* 512 1024))) 886 | (byte-offset 0) (line-offset (- end-line start-line))) 887 | (with-temp-buffer 888 | ;; Go to start-line 889 | (while (and (> start-line 0) 890 | (< byte-offset file-size)) 891 | (insert-file-contents 892 | filename nil byte-offset (+ byte-offset chunk-size)) 893 | (setq byte-offset (+ byte-offset chunk-size)) 894 | (setq start-line (forward-line start-line)) 895 | (when (eobp) 896 | (if (/= (line-beginning-position) (line-end-position)) 897 | ;; forward-line counted 1 extra line 898 | (cl-incf start-line)) 899 | (delete-region (point-min) (line-beginning-position)))) 900 | 901 | (delete-region (point-min) (point)) 902 | 903 | ;; Go to end-line, forward by line-offset 904 | (cl-block nil 905 | (while (> line-offset 0) 906 | (setq line-offset (forward-line line-offset)) 907 | (when (and (eobp) (/= (line-beginning-position) (line-end-position))) 908 | ;; forward-line counted 1 extra line 909 | (cl-incf line-offset)) 910 | (if (= line-offset 0) 911 | (delete-region (point) (point-max)) 912 | (if (>= byte-offset file-size) 913 | (cl-return) 914 | (insert-file-contents 915 | filename nil byte-offset (+ byte-offset chunk-size)) 916 | (setq byte-offset (+ byte-offset chunk-size)))))) 917 | 918 | (buffer-string))))) 919 | 920 | (defun gptel-agent--grep (regex path &optional glob context-lines) 921 | "Search for REGEX in file or directory at PATH using ripgrep. 922 | 923 | REGEX is a PCRE-format regular expression to search for. 924 | PATH can be a file or directory to search in. 925 | 926 | Optional arguments: 927 | GLOB restricts the search to files matching the glob pattern. 928 | Examples: \"*.el\", \"*.md\", \"*.rs\" 929 | CONTEXT-LINES specifies the number of lines of context to show 930 | around each match (0-15 inclusive, defaults to 0). 931 | 932 | Returns a string containing matches grouped by file, with line numbers 933 | and optional context. Results are sorted by modification time." 934 | (unless (file-readable-p path) 935 | (error "Error: File or directory %s is not readable" path)) 936 | (let ((grepper (or (executable-find "rg") (executable-find "grep")))) 937 | (unless grepper 938 | (error "Error: ripgrep/grep not available, this tool cannot be used")) 939 | (with-temp-buffer 940 | (let* ((args 941 | (cond 942 | ((string-suffix-p "rg" grepper) 943 | (delq nil (list "--sort=modified" 944 | (and (natnump context-lines) 945 | (format "--context=%d" context-lines)) 946 | (and glob (format "--glob=%s" glob)) 947 | ;; "--files-with-matches" "--max-count=10" 948 | "--heading" "--line-number" "-e" regex 949 | (expand-file-name (substitute-in-file-name path))))) 950 | ((string-suffix-p "grep" grepper) 951 | (delq nil (list "--recursive" 952 | (and (natnump context-lines) 953 | (format "--context=%d" context-lines)) 954 | (and glob (format "--include=%s" glob)) 955 | "--line-number" "--regexp" regex 956 | (expand-file-name (substitute-in-file-name path))))))) 957 | (exit-code (apply #'call-process grepper nil '(t t) nil args))) 958 | (when (/= exit-code 0) 959 | (goto-char (point-min)) 960 | (insert (format "Error: search failed with exit-code %d. Tool output:\n\n" exit-code))) 961 | (buffer-string))))) 962 | 963 | ;;; Todo-write tool (task tracking) 964 | (defvar-local gptel-agent--todos nil) 965 | 966 | (defun gptel-agent-toggle-todos () 967 | "Toggle the display of the gptel agent todo list." 968 | (interactive) 969 | (pcase-let ((`(,prop-value . ,ov) 970 | (or (get-char-property-and-overlay (point) 'gptel-agent--todos) 971 | (get-char-property-and-overlay 972 | (previous-single-char-property-change 973 | (point) 'gptel-agent--todos nil (point-min)) 974 | 'gptel-agent--todos)))) 975 | (if-let* ((fmt (overlay-get ov 'after-string))) 976 | (progn (overlay-put ov 'gptel-agent--todos fmt) 977 | (overlay-put ov 'after-string nil)) 978 | (overlay-put ov 'after-string 979 | (and (stringp prop-value) prop-value)) 980 | (overlay-put ov 'gptel-agent--todos t)))) 981 | 982 | (defun gptel-agent--write-todo (todos) 983 | "Display a formatted task list in the buffer. 984 | 985 | TODOS is a list of plists with keys :content, :activeForm, and :status. 986 | Completed items are displayed with strikethrough and shadow face. 987 | Exactly one item should have status \"in_progress\"." 988 | (setq gptel-agent--todos todos) 989 | ;; Update overlay 990 | (let* ((info (gptel-fsm-info gptel--fsm-last)) 991 | (where-from 992 | (previous-single-property-change 993 | (plist-get info :position) 'gptel nil (point-min))) 994 | (where-to (plist-get info :position))) 995 | (unless (= where-from where-to) 996 | (pcase-let ((`(,_ . ,todo-ov) 997 | (get-char-property-and-overlay where-from 'gptel-agent--todos))) 998 | (if todo-ov 999 | ;; Move if reusing an old overlay and the text has changed. 1000 | (move-overlay todo-ov where-from where-to) 1001 | (setq todo-ov (make-overlay where-from where-to nil t)) 1002 | (overlay-put todo-ov 'gptel-agent--todos t) 1003 | (overlay-put todo-ov 'evaporate t) 1004 | (overlay-put todo-ov 'priority -40) 1005 | (overlay-put todo-ov 'keymap (define-keymap 1006 | "" #'gptel-agent-toggle-todos 1007 | "TAB" #'gptel-agent-toggle-todos)) 1008 | (plist-put 1009 | info :post ; Don't use push, see note in gptel-anthropic 1010 | (cons (lambda (&rest _) ; Clean up header line after tasks are done 1011 | (when (and gptel-mode gptel-use-header-line header-line-format) 1012 | (setf (nth 2 header-line-format) gptel--header-line-info))) 1013 | (plist-get info :post)))) 1014 | (let* ((formatted-todos ; Format the todo list 1015 | (mapconcat 1016 | (lambda (todo) 1017 | (pcase (plist-get todo :status) 1018 | ("completed" 1019 | (concat "✓ " (propertize (plist-get todo :content) 1020 | 'face '(:inherit shadow :strike-through t)))) 1021 | ("in_progress" 1022 | (concat "● " (propertize (plist-get todo :activeForm) 1023 | 'face '(:inherit bold :inherit warning)))) 1024 | (_ (concat "○ " (plist-get todo :content))))) 1025 | todos "\n")) 1026 | (in-progress 1027 | (cl-loop for todo across todos 1028 | when (equal (plist-get todo :status) "in_progress") 1029 | return (plist-get todo :activeForm))) 1030 | (todo-display 1031 | (concat 1032 | (unless (= (char-before (overlay-end todo-ov)) 10) "\n") 1033 | gptel-agent--hrule 1034 | (propertize "Task list: [ " 1035 | 'face '(:inherit font-lock-comment-face :inherit bold)) 1036 | (save-excursion 1037 | (goto-char (1- (overlay-end todo-ov))) 1038 | (propertize (substitute-command-keys "\\[gptel-agent-toggle-todos]") 1039 | 'face 'help-key-binding)) 1040 | (propertize " to toggle display ]\n" 'face 'font-lock-comment-face) 1041 | formatted-todos "\n" 1042 | gptel-agent--hrule))) 1043 | (overlay-put todo-ov 'after-string todo-display) 1044 | (when (and gptel-mode gptel-use-header-line in-progress header-line-format) 1045 | (setf (nth 2 header-line-format) 1046 | (concat (propertize 1047 | " " 'display 1048 | `(space :align-to (- right ,(+ 5 (length in-progress))))) 1049 | (propertize (concat "Task: " in-progress) 1050 | 'face 'font-lock-escape-face)))))))) 1051 | t) 1052 | 1053 | ;;; Task tool (sub-agent) 1054 | (defvar gptel-agent-request--handlers 1055 | `((WAIT ,#'gptel-agent--indicate-wait 1056 | ,#'gptel--handle-wait) 1057 | (TOOL ,#'gptel-agent--indicate-tool-call 1058 | ,#'gptel--handle-tool-use)) 1059 | "See `gptel-request--handlers'.") 1060 | 1061 | (defun gptel-agent--task-preview-setup (arg-values _info) 1062 | "Preview setup for Agent. 1063 | INFO is the tool call info plist. 1064 | ARG-VALUES is a list: (type description prompt)" 1065 | (pcase-let ((from (point)) 1066 | (`(,type ,desc ,prompt) arg-values)) 1067 | (insert "(" 1068 | (propertize "Agent " 'font-lock-face 'font-lock-keyword-face) 1069 | (propertize (prin1-to-string type) 1070 | 'font-lock-face 'font-lock-escape-face) 1071 | " " (propertize (prin1-to-string desc) 1072 | 'font-lock-face 1073 | '(:inherit font-lock-constant-face :inherit bold)) 1074 | "\n" (propertize (prin1-to-string prompt) 1075 | 'line-prefix " " 1076 | 'wrap-prefix " " 1077 | 'font-lock-face 'font-lock-constant-face) 1078 | ")\n\n") 1079 | (gptel-agent--confirm-overlay from (point) t))) 1080 | 1081 | (defun gptel-agent--indicate-wait (fsm) 1082 | "Display waiting indicator for agent task FSM." 1083 | (when-let* ((info (gptel-fsm-info fsm)) 1084 | (info-ov (plist-get info :context)) 1085 | (count (overlay-get info-ov 'count))) 1086 | (run-at-time 1087 | 1.5 nil 1088 | (lambda (ov count) 1089 | (when (and (overlay-buffer ov) 1090 | (eql (overlay-get ov 'count) count)) 1091 | (let* ((task-msg (overlay-get ov 'msg)) 1092 | (new-info-msg 1093 | (concat task-msg 1094 | (concat 1095 | (propertize "Waiting... " 'face 'warning) "\n" 1096 | (propertize "\n" 'face 1097 | '(:inherit shadow :underline t :extend t)))))) 1098 | (overlay-put ov 'after-string new-info-msg)))) 1099 | info-ov count))) 1100 | 1101 | (defun gptel-agent--indicate-tool-call (fsm) 1102 | "Display tool call indicator for agent task FSM." 1103 | (when-let* ((info (gptel-fsm-info fsm)) 1104 | (tool-use (plist-get info :tool-use)) 1105 | (ov (plist-get info :context))) 1106 | ;; Update overlay with tool calls 1107 | (when (overlay-buffer ov) 1108 | (let* ((task-msg (overlay-get ov 'msg)) 1109 | (info-count (overlay-get ov 'count)) 1110 | (new-info-msg)) 1111 | (setq new-info-msg 1112 | (concat task-msg 1113 | (concat 1114 | (propertize "Calling Tools... " 'face 'mode-line-emphasis) 1115 | (if (= info-count 0) "\n" (format "(+%d)\n" info-count)) 1116 | (mapconcat (lambda (call) 1117 | (gptel--format-tool-call 1118 | (plist-get call :name) 1119 | (map-values (plist-get call :args)))) 1120 | tool-use) 1121 | "\n" gptel-agent--hrule))) 1122 | (overlay-put ov 'count (+ info-count (length tool-use))) 1123 | (overlay-put ov 'after-string new-info-msg))))) 1124 | 1125 | (defun gptel-agent--task-overlay (where &optional agent-type description) 1126 | "Create overlay for agent task at WHERE with AGENT-TYPE and DESCRIPTION." 1127 | (let* ((bounds ;where to place the overlay, handle edge cases 1128 | (save-excursion 1129 | (goto-char where) 1130 | (when (bobp) (insert "\n")) 1131 | (if (and (bolp) (eolp)) 1132 | (cons (1- (point)) (point)) 1133 | (cons (line-beginning-position) (line-end-position))))) 1134 | (ov (make-overlay (car bounds) (cdr bounds) nil t)) 1135 | (msg (concat 1136 | (unless (eq (char-after (car bounds)) 10) "\n") 1137 | "\n" gptel-agent--hrule 1138 | (propertize (concat (capitalize agent-type) " Task: ") 1139 | 'face 'font-lock-escape-face) 1140 | (propertize description 'face 'font-lock-doc-face) "\n"))) 1141 | (prog1 ov 1142 | (overlay-put ov 'gptel-agent t) 1143 | (overlay-put ov 'count 0) 1144 | (overlay-put ov 'msg msg) 1145 | (overlay-put ov 'line-prefix "") 1146 | (overlay-put 1147 | ov 'after-string 1148 | (concat msg (propertize "Waiting..." 'face 'warning) "\n" 1149 | gptel-agent--hrule))))) 1150 | 1151 | (defun gptel-agent--task (main-cb agent-type description prompt) 1152 | "Call a gptel agent to do specific compound tasks. 1153 | 1154 | MAIN-CB is the main callback to return a value to the main loop. 1155 | AGENT-TYPE is the name of the agent. 1156 | DESCRIPTION is a short description of the task. 1157 | PROMPT is the detailed prompt instructing the agent on what is required." 1158 | (gptel-with-preset 1159 | (nconc (list :include-reasoning nil 1160 | :use-tools t 1161 | :use-context nil) 1162 | (cdr (assoc agent-type gptel-agent--agents))) 1163 | (let* ((info (gptel-fsm-info gptel--fsm-last)) 1164 | (where (or (plist-get info :tracking-marker) 1165 | (plist-get info :position))) 1166 | (partial (format "%s result for task: %s\n\n" 1167 | (capitalize agent-type) description))) 1168 | (gptel--update-status " Calling Agent..." 'font-lock-escape-face) 1169 | (gptel-request prompt 1170 | :context (gptel-agent--task-overlay where agent-type description) 1171 | :fsm (gptel-make-fsm :handlers gptel-agent-request--handlers) 1172 | :callback 1173 | (lambda (resp info) 1174 | (let ((ov (plist-get info :context))) 1175 | (pcase resp 1176 | ('nil 1177 | (delete-overlay ov) 1178 | (funcall main-cb 1179 | (format "Error: Task %s could not finish task \"%s\". \ 1180 | 1181 | Error details: %S" 1182 | agent-type description (plist-get info :error)))) 1183 | (`(tool-call . ,calls) 1184 | (unless (plist-get info :tracking-marker) 1185 | (plist-put info :tracking-marker where)) 1186 | (gptel--display-tool-calls calls info)) 1187 | ((pred stringp) 1188 | (setq partial (concat partial resp)) 1189 | ;; If tool use is pending, the agent isn't done, so we just 1190 | ;; accumulate output without printing it. We print at the end. 1191 | (unless (plist-get info :tool-use) 1192 | (delete-overlay ov) 1193 | (when-let* ((transformer (plist-get info :transformer))) 1194 | (setq partial (funcall transformer partial))) 1195 | (funcall main-cb partial))) 1196 | ('abort 1197 | (delete-overlay ov) 1198 | (funcall main-cb 1199 | (format "Error: Task \"%s\" was aborted by the user. \ 1200 | %s could not finish." 1201 | description agent-type)))))))))) 1202 | 1203 | ;;; Register tool call preview functions 1204 | 1205 | (pcase-dolist (`(,tool-name . ,setup-fn) 1206 | `(("Write" ,#'gptel-agent--write-file-preview-setup) 1207 | ("Eval" ,#'gptel-agent--eval-elisp-preview-setup) 1208 | ("Bash" ,#'gptel-agent--execute-bash-preview-setup) 1209 | ("Edit" ,#'gptel-agent--edit-files-preview-setup) 1210 | ("Insert" ,#'gptel-agent--insert-in-file-preview-setup) 1211 | ("Agent" ,#'gptel-agent--task-preview-setup))) 1212 | (setf (alist-get tool-name gptel--tool-preview-alist 1213 | nil nil #'equal) 1214 | setup-fn)) 1215 | 1216 | ;;; All tool declarations 1217 | 1218 | (gptel-make-tool 1219 | :name "Bash" 1220 | :function (lambda (command) 1221 | "Execute a bash command and return its output. 1222 | 1223 | COMMAND is the bash command string to execute." 1224 | (with-temp-buffer 1225 | (let* ((exit-code (call-process "bash" nil (current-buffer) nil "-c" command)) 1226 | (output (buffer-string))) 1227 | (if (zerop exit-code) 1228 | output 1229 | (format "Command failed with exit code %d:\nSTDOUT+STDERR:\n%s" exit-code output))))) 1230 | :description "Execute Bash commands. 1231 | 1232 | This tool provides access to a Bash shell with GNU coreutils (or equivalents) available. 1233 | Use this to inspect system state, run builds, tests or other development or system administration tasks. 1234 | 1235 | Do NOT use this for file operations, finding, reading or editing files. 1236 | Use the provided file tools instead: `Read`, `Write`, `Edit`, \ 1237 | `Glob`, `Grep` 1238 | 1239 | - Quote file paths with spaces using double quotes. 1240 | - Chain dependent commands with && (or ; if failures are OK) 1241 | - Use absolute paths instead of cd when possible 1242 | - For parallel commands, make multiple `Bash` calls in one message 1243 | - Run tests, check your work or otherwise close the loop to verify changes you make. 1244 | 1245 | EXAMPLES: 1246 | - List files with details: 'ls -lah /path/to/dir' 1247 | - Find recent errors: 'grep -i error /var/log/app.log | tail -20' 1248 | - Check file type: 'file document.pdf' 1249 | - Count lines: 'wc -l *.txt' 1250 | 1251 | The command will be executed in the current working directory. Output is 1252 | returned as a string. Long outputs should be filtered/limited using pipes." 1253 | :args '(( :name "command" 1254 | :type string 1255 | :description "The Bash command to execute. \ 1256 | Can include pipes and standard shell operators. 1257 | Example: 'ls -la | head -20' or 'grep -i error app.log | tail -50'")) 1258 | :category "gptel-agent" 1259 | :confirm t 1260 | :include t) 1261 | 1262 | (gptel-make-tool 1263 | :name "Eval" 1264 | :function 1265 | (lambda (expression) 1266 | (let ((standard-output (generate-new-buffer " *gptel-agent-eval-elisp*")) 1267 | (result nil) (output nil)) 1268 | (unwind-protect 1269 | (condition-case err 1270 | (progn 1271 | (setq result (eval (read expression) t)) 1272 | (when (> (buffer-size standard-output) 0) 1273 | (setq output (with-current-buffer standard-output (buffer-string)))) 1274 | (concat 1275 | (format "Result:\n%S" result) 1276 | (and output (format "\n\nSTDOUT:\n%s" output)))) 1277 | ((error user-error) 1278 | (concat 1279 | (format "Error: eval failed with error %S: %S" 1280 | (car err) (cdr err)) 1281 | (and output (format "\n\nSTDOUT:\n%s" output))))) 1282 | (kill-buffer standard-output)))) 1283 | :description "Evaluate Elisp EXPRESSION and return result and any printed output. 1284 | 1285 | EXPRESSION can be anything to evaluate. It can be a function call, a 1286 | variable, a quasi-quoted expression. The only requirement is that only 1287 | the first sexp will be read and evaluated, so if you need to evaluate 1288 | multiple expressions, make one call per expression. Do not combine 1289 | expressions using progn etc. Just go expression by expression and try 1290 | to make standalone single expressions. 1291 | 1292 | Instead of saying \"I can't calculate that\" etc, use this tool to 1293 | evaluate the result. 1294 | 1295 | The return value is formated to a string using %S, so a string will be 1296 | returned as an escaped embedded string and literal forms will be 1297 | compatible with `read' where possible. Some forms have no printed 1298 | representation that can be read and will be represented with 1299 | # instead. 1300 | 1301 | Output from `print`, `prin1`, and `princ` is captured and returned as STDOUT. 1302 | Use `print` for diagnostic output, not `message` (which goes to *Messages* buffer 1303 | and is not captured). 1304 | 1305 | You can use this to quickly change a user setting, check a variable, or 1306 | demonstrate something to the user." 1307 | :args '(( :name "expression" 1308 | :type string 1309 | :description "A single elisp sexp to evaluate.")) 1310 | :category "gptel-agent" 1311 | :confirm t 1312 | :include t) 1313 | 1314 | (gptel-make-tool 1315 | :name "WebSearch" 1316 | :function 'gptel-agent--web-search-eww 1317 | :description "Search the web for the first five results to a query. The query can be an arbitrary string. Returns the top five results from the search engine as a list of plists. Each object has the keys `:url` and `:excerpt` for the corresponding search result. 1318 | 1319 | This tool uses the Emacs web browser (eww) with its default search engine (typically DuckDuckGo) to perform searches. No API key is required. 1320 | 1321 | If required, consider using the url as the input to the `Read` tool to get the contents of the url. Note that this might not work as the `Read` tool does not handle javascript-enabled pages." 1322 | :args '((:name "query" 1323 | :type string 1324 | :description "The natural language search query, can be multiple words.") 1325 | (:name "count" 1326 | :type integer 1327 | :description "Number of results to return (default 5)" 1328 | :optional t)) 1329 | :include t 1330 | :async t 1331 | :category "gptel-agent") 1332 | 1333 | (gptel-make-tool 1334 | :function #'gptel-agent--read-url 1335 | :name "WebFetch" 1336 | :description "Fetch and read the contents of a URL. 1337 | 1338 | - Returns the text of the URL (not HTML) formatted for reading. 1339 | - Request times out after 30 seconds." 1340 | :args '(( :name "url" 1341 | :type "string" 1342 | :description "The URL to read")) 1343 | :async t 1344 | :include t 1345 | :category "gptel-agent") 1346 | 1347 | (gptel-make-tool 1348 | :name "YouTube" 1349 | :function #'gptel-agent--yt-read-url 1350 | :description "Find the description and video transcript for a youtube video. Returns a markdown formatted string containing two sections: 1351 | 1352 | \"description\": The video description added by the uploader 1353 | \"transcript\": The video transcript in SRT format" 1354 | :args '((:name "url" 1355 | :description "The youtube video URL, for example \"https://www.youtube.com/watch?v=H2qJRnV8ZGA\"" 1356 | :type "string")) 1357 | :category "gptel-agent" 1358 | :async t 1359 | :include t) 1360 | 1361 | (gptel-make-tool 1362 | :name "Diagnostics" 1363 | :description "Collect all code diagnostics with severity high/medium \ 1364 | across all open buffers in the current project. 1365 | 1366 | With optional argument `all`, collect notes and low-severity diagnostics 1367 | too." 1368 | :function #'gptel-agent--flymake-diagnostics 1369 | :args (list '( :name "all" 1370 | :type boolean 1371 | :description 1372 | "Whether low-severity diagnostics (notes) should also be collected." 1373 | :optional t)) 1374 | :category "gptel-agent" 1375 | :include t) 1376 | 1377 | (gptel-make-tool 1378 | :name "Mkdir" 1379 | :description "Create a new directory with the given name in the specified parent directory" 1380 | :function (lambda (parent name) 1381 | (condition-case errdata 1382 | (progn 1383 | (make-directory (expand-file-name name parent) t) 1384 | (format "Directory %s created/verified in %s" name parent)) 1385 | (error "Error creating directory %s in %s:\n%S" name parent errdata))) 1386 | :args (list '( :name "parent" 1387 | :type "string" 1388 | :description "The parent directory where the new directory should be created, e.g. /tmp") 1389 | '( :name "name" 1390 | :type "string" 1391 | :description "The name of the new directory to create, e.g. testdir")) 1392 | :category "gptel-agent" 1393 | :confirm t 1394 | :include t) 1395 | 1396 | (gptel-make-tool 1397 | :name "Edit" 1398 | :description 1399 | "Replace text in one or more files. 1400 | 1401 | To edit a single file, provide the file `path`. 1402 | 1403 | For the replacement, there are two methods: 1404 | - Short replacements: Provide both `old_str` and `new_str`, in which case `old_str` \ 1405 | needs to exactly match one unique section of the original file, including any whitespace. \ 1406 | Make sure to include enough context that the match is not ambiguous. \ 1407 | The entire original string will be replaced with `new str`. 1408 | - Long or involved replacements: set the `diff` parameter to true and provide a unified diff \ 1409 | in `new_str`. `old_str` can be ignored. 1410 | 1411 | To edit multiple files, 1412 | - provide the directory path, 1413 | - set the `diff` parameter to true 1414 | - and provide a unified diff in `new_str`. 1415 | 1416 | Diff instructions: 1417 | 1418 | - The diff must be provided within fenced code blocks (=diff or =patch) and be in unified format. 1419 | - The LLM should generate the diff such that the file paths within the diff \ 1420 | (e.g., '--- a/filename' '+++ b/filename') are appropriate for the 'path'. 1421 | 1422 | To simply insert text at some line, use the \"Insert\" instead." 1423 | :function #'gptel-agent--edit-files 1424 | :args '(( :name "path" 1425 | :description "File path or directory to edit" 1426 | :type string) 1427 | ( :name "old_str" 1428 | :description "Original string to replace. If providing a unified diff, this should be false" 1429 | :type string 1430 | :optional t) 1431 | ( :name "new_str" 1432 | :description "Replacement string OR unified diff text" 1433 | :type string) 1434 | ( :name "diff" 1435 | :description "Whether the replacement is a string or a diff. `true` for a diff, `false` otherwise." 1436 | :type boolean)) 1437 | :category "gptel-agent" 1438 | :confirm t 1439 | :include t) 1440 | 1441 | (gptel-make-tool 1442 | :name "Insert" 1443 | :description "Insert `new_str` after `line_number` in file at `path`. 1444 | 1445 | Use this tool for purely additive actions: adding text to a file at a \ 1446 | specific location with no changes to the surrounding context." 1447 | :function #'gptel-agent--insert-in-file 1448 | :args '(( :name "path" 1449 | :description "Path of file to edit." 1450 | :type string) 1451 | ( :name "line_number" 1452 | :description "The line number at which to insert `new_str`, with 1453 | - 0 to insert at the beginning, and 1454 | - -1 to insert at the end." 1455 | :type integer) 1456 | ( :name "new_str" 1457 | :description "String to insert at `line_number`." 1458 | :type string)) 1459 | :category "gptel-agent" 1460 | :confirm t 1461 | :include t) 1462 | 1463 | (gptel-make-tool 1464 | :name "Write" 1465 | :description "Create a new file with the specified content. 1466 | Overwrites an existing file, so use with care! 1467 | Consider using the more granular tools \"Insert\" or \"Edit\" first." 1468 | :function (lambda (path filename content) 1469 | (unless (and (stringp path) (stringp filename) (stringp content)) 1470 | (error "PATH, FILENAME or CONTENT is not a string, cancelling action")) 1471 | (let ((full-path (expand-file-name filename path))) 1472 | (condition-case errdata 1473 | (with-temp-buffer 1474 | (insert content) 1475 | (write-file full-path) 1476 | (format "Created file %s in %s" filename path)) 1477 | (error "Error: Could not write file %s:\n%S" path errdata)))) 1478 | :args (list '( :name "path" 1479 | :type "string" 1480 | :description "The directory where to create the file, \".\" is the current directory.") 1481 | '( :name "filename" 1482 | :type "string" 1483 | :description "The name of the file to create.") 1484 | '( :name "content" 1485 | :type "string" 1486 | :description "The content to write to the file")) 1487 | :category "gptel-agent" 1488 | :confirm t) 1489 | 1490 | (gptel-make-tool 1491 | :name "Glob" 1492 | :description "Recursively find files matching a provided glob pattern. 1493 | 1494 | - Supports glob patterns like \"*.md\" or \"*test*.py\". 1495 | The glob applies to the basename of the file (with extension). 1496 | - Returns matching file paths at all depths sorted by modification time. 1497 | Limit the depth of the search by providing the `depth` argument. 1498 | - When you are doing an open ended search that may require multiple rounds 1499 | of globbing and grepping, use the \"task\" tool instead 1500 | - You can call multiple tools in a single response. It is always better to 1501 | speculatively perform multiple searches in parallel if they are potentially useful." 1502 | :function (lambda (pattern &optional path depth) 1503 | (when (string-empty-p pattern) 1504 | (error "Error: pattern must not be empty")) 1505 | (if path 1506 | (unless (and (file-readable-p path) (file-directory-p path)) 1507 | (error "Error: path %s is not readable" path)) 1508 | (setq path ".")) 1509 | (unless (executable-find "tree") 1510 | (error "Error: Executable `tree` not found. This tool cannot be used")) 1511 | (let ((full-path (expand-file-name path))) 1512 | (with-temp-buffer 1513 | (let* ((args (list "-l" "-f" "-i" "-I" ".git" 1514 | "--sort=mtime" "--ignore-case" 1515 | "--prune" "-P" pattern full-path)) 1516 | (args (if (natnump depth) 1517 | (nconc args (list "-L" (number-to-string depth))) 1518 | args)) 1519 | (exit-code (apply #'call-process "tree" nil t nil args))) 1520 | (when (/= exit-code 0) 1521 | (goto-char (point-min)) 1522 | (insert (format "Glob failed with exit code %d\n.STDOUT:\n\n" 1523 | exit-code)))) 1524 | (buffer-string)))) 1525 | :args '(( :name "pattern" 1526 | :type string 1527 | :description "Glob pattern to match, for example \"*.el\". Must not be empty. 1528 | Use \"*\" to list all files in a directory.") 1529 | ( :name "path" 1530 | :type string 1531 | :description "Directory to search in. Supports relative paths and defaults to \".\"" 1532 | :optional t) 1533 | ( :name "depth" 1534 | :description "Limit directory depth of search, 1 or higher. Defaults to no limit." 1535 | :type integer 1536 | :optional t)) 1537 | :category "gptel-agent" 1538 | :include t) 1539 | 1540 | (gptel-make-tool 1541 | :name "Read" 1542 | :description "Read file contents between specified line numbers `start_line` and `end_line`, 1543 | with both ends included. 1544 | 1545 | Consider using the \"Grep\" tool to find the right range to read first. 1546 | 1547 | Reads the whole file if the line range is not provided. 1548 | 1549 | Files over 512 KB in size can only be read by specifying a line range." 1550 | :function #'gptel-agent--read-file-lines 1551 | :args '(( :name "file_path" 1552 | :type string 1553 | :description "The path to the file to be read.") 1554 | ( :name "start_line" 1555 | :type integer 1556 | :description "The line to start reading from, defaults to the start of the file" 1557 | :optional t) 1558 | ( :name "end_line" 1559 | :type integer 1560 | :description "The line up to which to read, defaults to the end of the file." 1561 | :optional t)) 1562 | :category "gptel-agent" 1563 | :include t) 1564 | 1565 | (gptel-make-tool 1566 | :name "Grep" 1567 | :description "Search for text in file(s) at `path`. 1568 | 1569 | Use this tool to find relevant parts of files to read. 1570 | 1571 | Returns a list of matches prefixed by the line number, and grouped by file. Can search an individual file (if providing a file path) or a directory. Consider using this tool to find the right line range for the \"Read\" tool. 1572 | 1573 | When searching directories, optionally restrict the types of files in the search with a `glob`. Can request context lines around each match using the `context_lines` parameters." 1574 | :function #'gptel-agent--grep 1575 | :args '(( :name "regex" 1576 | :description "Regular expression to search for in file contents." 1577 | :type string) 1578 | ( :name "path" 1579 | :description "File or directory to search in." 1580 | :type string) 1581 | ( :name "glob" 1582 | :description "Optional glob to restrict file types to search for. 1583 | Only required when path is a directory. 1584 | Examples: *.md, *.rs" 1585 | :type string 1586 | :optional t) 1587 | ( :name "context_lines" 1588 | :description "Number of lines of context to retrieve around each match (0-15 inclusive). 1589 | Optional, defaults to 0." 1590 | :optional t 1591 | :type integer 1592 | :maximum 15)) 1593 | :category "gptel-agent" 1594 | :include t) 1595 | 1596 | (gptel-make-tool 1597 | :name "TodoWrite" 1598 | :description "Create and manage a structured task list for your current session. \ 1599 | Helps track progress and organize complex tasks. Use proactively for multi-step work. 1600 | 1601 | Only one todo can be `in_progress` at a time." 1602 | :function #'gptel-agent--write-todo 1603 | :args 1604 | '(( :name "todos" 1605 | :type array 1606 | :items 1607 | ( :type object 1608 | :properties 1609 | (:content 1610 | ( :type string :minLength 1 1611 | :description "Imperative form describing what needs to be done (e.g., 'Run tests')") 1612 | :status 1613 | ( :type string 1614 | :enum ["pending" "in_progress" "completed"] 1615 | :description "Task status: pending, in_progress (exactly one), or completed") 1616 | :activeForm 1617 | ( :type string :minLength 1 1618 | :description "Present continuous form shown during execution (e.g., 'Running tests')"))))) 1619 | :category "gptel-agent") 1620 | 1621 | (gptel-make-tool 1622 | :name "Agent" 1623 | :description "Launch a specialized agent to handle complex, multi-step tasks autonomously. \ 1624 | Agents run independently and return results in one message. \ 1625 | Use for open-ended searches, complex research, or when uncertain about finding results in first few tries." 1626 | :function #'gptel-agent--task 1627 | :args '(( :name "subagent_type" 1628 | :type string 1629 | :enum ["researcher" "introspector"] 1630 | :description "The type of specialized agent to use for this task") 1631 | ( :name "description" 1632 | :type string 1633 | :description "A short (3-5 word) description of the task") 1634 | ( :name "prompt" 1635 | :type "string" 1636 | :description "The detailed task for the agent to perform autonomously. \ 1637 | Should include exactly what information the agent should return.")) 1638 | :category "gptel-agent" 1639 | :async t 1640 | :confirm t 1641 | :include t) 1642 | 1643 | (provide 'gptel-agent-tools) 1644 | ;;; gptel-agent-tools.el ends here 1645 | 1646 | ;; Local Variables: 1647 | ;; elisp-flymake-byte-compile-load-path: ("~/.local/share/git/elpaca/repos/gptel/" "~/.local/share/git/elpaca/repos/transient/lisp" "~/.local/share/git/elpaca/repos/compat/") 1648 | ;; End: 1649 | --------------------------------------------------------------------------------