Skip to content

Jamie-Cui/magent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

62 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Magent - AI Coding Agent for Emacs

An Emacs Lisp AI coding agent with multi-agent architecture, permission-based tool access, and LLM integration via gptel.

Features

  • Multi-agent system with specialized agents (build, plan, explore, general)
  • Permission-based tool access with fine-grained control per agent
  • Custom agent support via .magent/agent/*.md files
  • LLM integration via gptel supporting Anthropic Claude, OpenAI GPT, and compatible APIs
  • 10 built-in tools: file operations, shell, grep, glob, web search, Emacs eval, agent delegation, skill invocation
  • Skill system for extending agent capabilities (built-in Emacs skill + custom skills from files)
  • Single-request lock for serializing concurrent requests
  • Project-scoped session management with conversation history and JSON persistence
  • Streaming responses with chunk batching and async fontification
  • Markdown-to-Org conversion for rendering assistant output in org-mode
  • Context-aware prompting via magent-dwim with automatic buffer context attachment

Requirements

Installation

Manual Installation

Add the project to your Emacs load path:

(add-to-list 'load-path "/path/to/magent")
(require 'magent)

Using use-package

(use-package magent
  :load-path "/path/to/magent"
  :config
  (global-magent-mode 1))

Configuration

Quick Start

Magent delegates all LLM communication to gptel. Configure your provider, model, and API key through gptel:

;; gptel handles provider/model/key configuration
(setq gptel-model 'claude-sonnet-4-20250514)
(setq gptel-api-key "sk-ant-...")  ; or use ANTHROPIC_API_KEY env var

See gptel documentation for full provider setup (Anthropic, OpenAI, Ollama, etc.).

Magent-Specific Options

Customize with M-x customize-group RET magent RET. Key settings:

OptionDefaultDescription
magent-system-prompt(built-in)Default system prompt for agents
magent-buffer-name"*magent*"Output buffer name
magent-auto-scrolltAuto-scroll output buffer
magent-enable-toolsall 10 toolsGlobally enabled tools
magent-project-root-functionnilCustom project root finder
magent-max-history100Max messages in history
magent-request-timeout120Timeout in seconds for LLM requests
magent-default-agent"build"Default agent for new sessions
magent-load-custom-agentstLoad custom agents from .magent/agent/*.md
magent-enable-loggingtEnable logging to *magent-log* buffer
magent-enable-audit-logtPersist compact audit logs for permission and sensitive actions
magent-assistant-prompt"ASSISTANT"Tag text in assistant section headers
magent-user-prompt"USER"Tag text in user section headers
magent-tool-call-prompt"tool"Tag text in tool call lines
magent-error-prompt"error"Tag text in error section headers
magent-agent-directory".magent/agent"Relative path to custom agent dir
magent-session-directory~/.emacs.d/magent-sessions/Base directory for global sessions and per-project session subdirectories
magent-audit-directorynilOverride directory for audit JSONL files; defaults to magent-session-directory/audit/
magent-grep-program"rg"Path to ripgrep binary
magent-grep-max-matches100Max matches from grep searches
magent-bash-timeout30Timeout in seconds for bash commands
magent-emacs-eval-timeout10Timeout in seconds for emacs_eval
magent-audit-preview-length120Max width for persisted audit summaries and previews
magent-include-reasoningtDisplay (t), keep out of the UI (ignore), or discard (nil) reasoning blocks
magent-auto-contexttAuto-attach buffer context in magent-dwim
magent-ui-batch-insert-delay0.05Delay in seconds for batching streaming chunks
magent-ui-fontify-threshold500Character threshold for async fontification

Usage

Interactive Commands

CommandKeybindingDescription
magent-dwimC-c m pSmart prompt: opens output buffer or prompts for input with auto-context
magent-diagnose-emacsC-c m dStart a structured diagnosis of the current Emacs session
magent-doctorC-c m DRun Magent self-check and diagnose Magent-specific issues
magent-prompt-regionC-c m rSend selected region to AI
magent-ask-at-pointC-c m aAsk about symbol at point
magent-clear-sessionC-c m cClear current session
magent-show-logC-c m lView API request/response log
magent-clear-logC-c m LClear the log buffer
magent-ui-toggle-sectionC-c m tToggle fold/unfold of section at point
magent-select-agentC-c m ASelect an agent for this session
magent-show-current-agentC-c m iShow current session’s agent
magent-list-agentsC-c m vList all available agents
magent-toggle-by-pass-permissionM-xToggle permission bypass for tool filtering and approval prompts

In the *magent* output buffer: TAB and S-TAB fold sections, ? opens the transient menu, C-c C-c submits input, and C-g interrupts.

The same bypass state is also exposed as the customize option magent-by-pass-permission under M-x customize-group RET magent RET.

Session Scope

Magent keeps a single *magent* buffer, but session state is scoped by project:

  • In a recognized project, prompts, agent selection, clear, and resume operate on that project’s current session.
  • Saved project sessions live under magent-session-directory/projects/<sha1(project-root)>/.
  • Outside any project, Magent falls back to the global session behavior and saves directly under magent-session-directory.
  • Compact audit logs for permission decisions and sensitive tools are written as daily JSONL files under magent-session-directory/audit/ unless magent-audit-directory is set.
  • magent-resume-session shows all sessions grouped by project, with the current project’s group first and global sessions in their own group.

Quick Example

;; Enable the mode
(magent-mode 1)

;; Or globally
(global-magent-mode 1)

;; Send a prompt
M-x magent-dwim

;; Or use keybinding
C-c m p

Agent System

Magent uses a multi-agent architecture where different agents have different capabilities and permissions.

Built-in Agents

AgentModeDescription
buildprimaryDefault agent for general coding tasks with full tool access
planprimaryPlanning agent with restricted file edits (only .magent/plan/*.md)
exploresubagentFast codebase exploration (read/grep/glob/bash only)
generalsubagentGeneral-purpose subagent for delegated tasks (no delegation)
compactionprimary (hidden)Session summarization / conversation compaction
titleprimary (hidden)Conversation title generation
summaryprimary (hidden)Pull-request style summary generation

Agent Modes

  • primary: User-facing agents that can be selected for sessions
  • subagent: Internal agents called by primary agents for subtasks
  • all: Can act as either primary or subagent

Permission System

Each agent has permission rules controlling tool access:

;; Example permission rules in an agent definition
(
 (read_file . allow)            ; Allow all file reads
 (write_file . ((deny "*.env")  ; Deny writing to .env files
                (deny "*.key")  ; Deny writing to .key files
                (allow "*")))   ; Allow writing to other files
 (bash . ask)                   ; Ask user before running bash commands
)

Permission actions:

  • allow: Tool is allowed
  • deny: Tool is blocked
  • ask: Prompt the user for confirmation

Custom Agents

Create custom agents by adding markdown files to .magent/agent/.

Example: ~.magent/agent/reviewer.md~

---
description: Code review specialist
mode: primary
hidden: false
temperature: 0.3
permissions:
  - (read_file . allow)
  - (write_file . deny)
  - (bash . deny)
  - (grep . allow)
  - (glob . allow)
---

You are a code review specialist. Analyze code for:
- Bugs and potential issues
- Code style and best practices
- Performance optimizations
- Security vulnerabilities

Provide constructive feedback with specific examples.

The YAML frontmatter supports:

  • description: Short description of the agent
  • mode: primary, subagent, or all
  • hidden: Hide from agent selection UI
  • temperature: Override default temperature
  • model: Override default model
  • permissions: List of permission rules

Available Tools

The AI agent has access to these tools (can be customized per agent):

ToolSide-effectDescription
read_filenoRead file contents from the filesystem
write_fileyesWrite or create a file (auto-creates parent dirs)
edit_fileyesReplace exact text in a file (must match once)
grepnoRegex search via ripgrep; returns file:line:content
globnoFind files matching a glob pattern
bashyesExecute shell commands (default timeout 30s)
emacs_evalyesEvaluate Emacs Lisp expressions (default timeout 10s)
delegateyesSpawn a nested request using a named subagent
skill_invokenoInvoke tool-type skills
web_searchnoSearch the web via DuckDuckGo

Tools with side effects prompt the user for confirmation before execution unless permission bypass is enabled with M-x magent-toggle-by-pass-permission or by customizing magent-by-pass-permission.

Tool availability is controlled by:

  1. Global magent-enable-tools setting
  2. Per-agent permission rules

Architecture

Core Flow

  1. Entry Point (magent.el): Defines magent-mode minor mode with the C-c m keybinding prefix. Full initialization (agent registry, skills) is lazy – triggered on first command via magent--ensure-initialized.
  2. Runtime (magent-runtime.el): Centralizes static initialization and project-local overlay activation for agents, skills, and capabilities.
  3. Agent System: Multi-agent architecture with permission-based tool access:
    • magent-agent.el: Builds gptel prompts, applies per-agent overrides, calls gptel-request
    • magent-agent-registry.el: Agent info struct, built-in agent definitions, and central registry
    • magent-agent-file.el: Custom agent loader (.magent/agent/*.md)
  4. Permission System (magent-permission.el): Rule-based tool access control per agent with file-pattern matching (glob syntax).
  5. Capability System (magent-capability.el): File-backed capability definitions score each request context and attach matching instruction skills.
  6. FSM (magent-fsm.el): Finite state machine for the tool-calling loop (INIT -> SEND -> WAIT -> PROCESS -> TOOL -> DONE/ERROR). Currently delegates HTTP to gptel.
  7. LLM Integration (via gptel): All LLM communication is handled by gptel. Provider, model, and API key configuration is managed entirely by gptel.
  8. Tools (magent-tools.el): 10 tool implementations registered as gptel-tool structs, filtered per agent based on permission rules.
  9. Skills (magent-skills.el): Two skill types – instruction (markdown injected into the system prompt) and tool (invoked via skill_invoke). The module contains the registry, built-in skill-creator definition, file-based skill loading, and interactive inspection commands. Skills load in priority order from: (1) built-in skills/ directory bundled with magent, (2) user directory ~/.emacs.d/magent-skills/<name>/SKILL.md, (3) project-local .magent/skills/<name>/SKILL.md.
  10. Session (magent-session.el): Conversation history management with per-project active sessions, global fallback outside projects, and JSON persistence. The buffer-content slot stores raw buffer text for lossless restore.
  11. Audit (magent-audit.el): Persistent JSONL audit logging for permission prompts and decisions plus sensitive actions such as bash, emacs_eval, write_file, edit_file, and delegate. Payloads are redacted to metadata and truncated previews.
  12. UI (magent-ui.el): The *magent* buffer derives from org-mode. It uses in-buffer input with * [USER] sections. Tool calls render as #+begin_tool~/~#+end_tool blocks; reasoning blocks as #+begin_think~/~#+end_think. Single-request serialization now lives here via magent-ui--processing and magent-ui--enqueue.
  13. Markdown-to-Org (magent-md2org.el): Converts markdown assistant output to org-mode format for rendering.
  14. File Loader (magent-file-loader.el): Shared definition loader for agent, skill, and capability files. It includes frontmatter parsing and supports booleans, numbers, quoted strings, and comma-separated lists.

File Structure

magent/
|-- magent.el                      # Main entry point and mode definition
|-- magent-config.el               # Configuration (customize group, defcustom vars)
|-- magent-runtime.el              # Static initialization and project overlay activation
|-- magent-session.el              # Session and message history (JSON persistence)
|-- magent-capability.el           # Capability registry and prompt-time resolution
|-- magent-audit.el                # Audit logging and JSONL persistence
|-- magent-tools.el                # Tool implementations (10 gptel-tool structs)
|-- magent-agent.el                # Agent logic (gptel integration)
|-- magent-agent-info.el           # Compatibility shim for legacy agent-info feature
|-- magent-agent-types.el          # Compatibility shim for legacy agent-types feature
|-- magent-agent-registry.el       # Agent struct, built-in definitions, and registry
|-- magent-agent-file.el           # Custom agent file loader (.magent/agent/*.md)
|-- magent-permission.el           # Permission system (allow/deny/ask with glob patterns)
|-- magent-fsm.el                  # FSM API (dispatches to gptel backend)
|-- magent-fsm-backend-gptel.el    # gptel FSM backend implementation
|-- magent-fsm-shared.el           # Shared FSM structs, tool wrapping, permission flow
|-- magent-file-loader.el          # Shared definition loader and frontmatter parser
|-- magent-md2org.el               # Markdown to org-mode converter
|-- magent-skills.el               # Skill registry, built-in skills, file loading, and skill commands
|-- magent-ui.el                   # In-buffer UI and output buffer (org-mode derived)
|-- magent-pkg.el                  # Package descriptor
|-- prompt.org                     # Default system prompt
|-- Makefile                       # Build, test, and clean targets
|-- skills/                        # Built-in skills (loaded automatically)
|   |-- brainstorming/SKILL.md
|   |-- systematic-debugging/SKILL.md
|   |-- test-driven-development/SKILL.md
|   |-- writing-plans/SKILL.md
|   |-- executing-plans/SKILL.md
|   |-- subagent-driven-development/SKILL.md
|   |-- verification-before-completion/SKILL.md
|   |-- git-workflow/SKILL.md
|   |-- requesting-code-review/SKILL.md
|   |-- receiving-code-review/SKILL.md
|   |-- finishing-a-development-branch/SKILL.md
|   |-- dispatching-parallel-agents/SKILL.md
|   |-- research/SKILL.md
|   |-- research-add/SKILL.md
|   |-- research-batch/SKILL.md
|   |-- research-explore/SKILL.md
|   `-- research-report/SKILL.md
`-- test/
    `-- magent-test.el             # ERT test suite

Key Data Structures

  • magent-agent-info: Agent configuration struct (name, description, mode, permissions, prompt, temperature, model, and related settings)
  • magent-session: Conversation state with message list, assigned agent, and history trimming
  • magent-fsm: FSM state for the tool-calling loop (state, session, agent, tools, pending-tools, and related fields)
  • magent-skill: Loaded skill definition (name, description, tools, body, dir)

Development

Build Commands

make compile    # Byte-compile all Elisp files
make test       # Run ERT tests
make clean      # Remove compiled .elc files

Single File Compilation

emacs -Q --batch -L . -L ~/path/to/gptel -f batch-byte-compile magent-foo.el

Session Persistence

Sessions are automatically saved to ~/.emacs.d/magent-sessions/ (configurable). Each session maintains:

  • Conversation history
  • Assigned agent
  • Message metadata
  • Raw buffer content for lossless restore

Troubleshooting

Enable Logging

View request and response logs:

(setq magent-enable-logging t)
M-x magent-show-log    ; C-c m l

Check Agent Configuration

M-x magent-list-agents        ; List all agents
M-x magent-show-current-agent ; Show current session's agent

Verify API Key

API keys are managed by gptel. Check with:

gptel-api-key  ; Should return your API key

License

This project is licensed under the GNU General Public License v3.0. See LICENSE for details.

Credits

Contributing

Contributions are welcome. Please ensure:

  • Code follows existing style conventions
  • All files byte-compile without warnings
  • Documentation is updated for new features

Links

About

An Emacs Lisp AI coding agent with multi-agent architecture, permission-based tool access, and LLM integration via gptel.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors