Hotdry.
ai-systems

AGENTS.md格式规范:编码代理的开放标准与解析器实现

深入分析AGENTS.md格式的设计原理、语法规范与扩展机制,实现解析器并与现有AI工具链集成,对比其他agent规范优劣。

在 AI 编码代理日益普及的今天,如何为这些 "数字同事" 提供清晰、一致的指导成为了开发团队面临的新挑战。AGENTS.md 应运而生 —— 一个简单、开放的格式标准,旨在为编码代理提供专属的上下文和指令文档。本文将深入分析这一格式的设计哲学、技术实现,并提供可落地的解析器方案。

设计哲学:AI 代理的专属 README

AGENTS.md 的核心定位是 "AI 代理的 README"。正如项目官方文档所述:"README.md 文件是为人类设计的:快速入门、项目描述和贡献指南。AGENTS.md 通过包含编码代理所需的额外、有时是详细的上下文来补充这一点:构建步骤、测试和约定,这些可能会使 README 变得杂乱,或者与人类贡献者无关。"

这一设计决策体现了几个关键考量:

  1. 关注点分离:将人类可读文档与机器可读指令分离,避免信息过载
  2. 代理友好性:提供专门针对 AI 代理优化的指令格式
  3. 向后兼容:不破坏现有的 README 结构,而是作为补充

截至 2026 年 1 月,AGENTS.md 已被超过 60,000 个开源项目采用,支持包括 OpenAI Codex、Google Jules、Cursor、Aider、GitHub Copilot 等在内的主流 AI 编码工具。

格式规范:极简主义的 Markdown 扩展

基础语法结构

AGENTS.md 采用标准 Markdown 格式,没有任何强制性的结构要求。这种极简主义设计降低了采用门槛,同时保持了灵活性。典型的 AGENTS.md 文件结构如下:

# AGENTS.md

## 开发环境配置
- 安装依赖:`pnpm install`
- 启动开发服务器:`pnpm dev`
- 运行测试:`pnpm test`

## 代码风格指南
- TypeScript严格模式
- 使用单引号,不加分号
- 尽可能使用函数式编程模式

## 测试指令
-`.github/workflows`文件夹中找到CI计划
- 运行`pnpm turbo run test --filter <project_name>`运行为该包定义的所有检查
- 修复所有测试或类型错误,直到整个测试套件通过

嵌套与优先级机制

对于大型项目或 monorepo,AGENTS.md 支持嵌套文件结构。解析器遵循 "最近优先" 原则:

  1. 路径解析算法:从当前编辑文件所在目录开始,向上遍历目录树
  2. 优先级规则:最接近被编辑文件的 AGENTS.md 具有最高优先级
  3. 用户覆盖:明确的用户聊天提示始终覆盖文件内容

这种设计使得不同子项目可以拥有独立的指令集,同时保持整体一致性。例如,OpenAI 的主要仓库在撰写本文时包含 88 个 AGENTS.md 文件。

解析器实现:TypeScript 实战方案

基础解析器架构

以下是 AGENTS.md 解析器的 TypeScript 实现核心:

interface AgentsMdConfig {
  filePath: string;
  content: string;
  priority: number; // 基于路径深度的优先级
}

class AgentsMdParser {
  private readonly AGENTS_MD_FILENAME = 'AGENTS.md';
  
  /**
   * 查找最近的AGENTS.md文件
   */
  async findNearestAgentsMd(currentPath: string): Promise<AgentsMdConfig | null> {
    const dirs = this.getParentDirectories(currentPath);
    
    for (const dir of dirs) {
      const agentsMdPath = path.join(dir, this.AGENTS_MD_FILENAME);
      if (await this.fileExists(agentsMdPath)) {
        const content = await fs.readFile(agentsMdPath, 'utf-8');
        const priority = this.calculatePriority(currentPath, dir);
        
        return {
          filePath: agentsMdPath,
          content,
          priority
        };
      }
    }
    
    return null;
  }
  
  /**
   * 解析AGENTS.md内容为结构化指令
   */
  parseContent(content: string): Record<string, string[]> {
    const sections: Record<string, string[]> = {};
    let currentSection = 'general';
    let currentItems: string[] = [];
    
    const lines = content.split('\n');
    
    for (const line of lines) {
      const sectionMatch = line.match(/^##\s+(.+)$/);
      if (sectionMatch) {
        // 保存前一个部分
        if (currentItems.length > 0) {
          sections[currentSection] = currentItems;
        }
        
        // 开始新部分
        currentSection = sectionMatch[1].toLowerCase().replace(/\s+/g, '-');
        currentItems = [];
      } else if (line.trim().startsWith('- ')) {
        // 列表项
        currentItems.push(line.trim().substring(2));
      }
    }
    
    // 保存最后一个部分
    if (currentItems.length > 0) {
      sections[currentSection] = currentItems;
    }
    
    return sections;
  }
  
  private calculatePriority(currentPath: string, agentsMdDir: string): number {
    const currentDepth = currentPath.split(path.sep).length;
    const agentsDepth = agentsMdDir.split(path.sep).length;
    return currentDepth - agentsDepth; // 深度差越小,优先级越高
  }
}

缓存与性能优化

考虑到 AGENTS.md 文件通常不会频繁变更,实现缓存机制可以显著提升性能:

class AgentsMdCache {
  private cache = new Map<string, { content: string; timestamp: number }>();
  private readonly CACHE_TTL = 5 * 60 * 1000; // 5分钟
  
  async getOrParse(filePath: string): Promise<string> {
    const cached = this.cache.get(filePath);
    const now = Date.now();
    
    if (cached && (now - cached.timestamp) < this.CACHE_TTL) {
      return cached.content;
    }
    
    const content = await fs.readFile(filePath, 'utf-8');
    this.cache.set(filePath, { content, timestamp: now });
    
    return content;
  }
  
  invalidate(filePath: string): void {
    this.cache.delete(filePath);
  }
}

与 AI 工具链集成

Aider 配置集成

Aider 作为流行的 AI 编码助手,可以通过配置文件支持 AGENTS.md:

# .aider.conf.yml
context:
  - AGENTS.md
  - README.md
  - package.json
  
model: gpt-4-turbo
temperature: 0.1

Gemini CLI 集成

Google 的 Gemini CLI 同样支持 AGENTS.md 格式:

{
  "contextFileName": "AGENTS.md",
  "includePatterns": ["**/*.md", "**/*.json"],
  "excludePatterns": ["node_modules/**", ".git/**"]
}

VS Code 扩展开发

为 VS Code 开发 AGENTS.md 支持扩展:

// extension.ts
import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
  // 注册AGENTS.md文件提供者
  const agentsMdProvider = new AgentsMdContentProvider();
  context.subscriptions.push(
    vscode.workspace.registerTextDocumentContentProvider(
      'agentsmd',
      agentsMdProvider
    )
  );
  
  // 添加命令:打开最近的AGENTS.md
  const openAgentsMdCommand = vscode.commands.registerCommand(
    'agentsmd.openNearest',
    async () => {
      const editor = vscode.window.activeTextEditor;
      if (!editor) return;
      
      const filePath = editor.document.uri.fsPath;
      const agentsMdPath = await findNearestAgentsMd(filePath);
      
      if (agentsMdPath) {
        const document = await vscode.workspace.openTextDocument(agentsMdPath);
        await vscode.window.showTextDocument(document);
      }
    }
  );
  
  context.subscriptions.push(openAgentsMdCommand);
}

与其他 Agent 规范的对比分析

与 Claude Skills 对比

Claude Skills 是 Anthropic 为 Claude Code 设计的技能系统,与 AGENTS.md 存在显著差异:

特性 AGENTS.md Claude Skills
格式 标准 Markdown 专用.skill 文件
定位 项目级指导 技能级复用
范围 整个项目 特定任务
集成 文件系统级 Claude 专用

AGENTS.md 的优势在于其通用性和工具无关性,而 Claude Skills 在深度集成和任务特定优化方面更胜一筹。

与 MCP(Model Context Protocol)对比

MCP 是模型上下文协议,提供标准化的工具调用接口:

维度 AGENTS.md MCP
协议类型 文档格式 RPC 协议
主要用途 提供指令 提供工具
复杂性 中高
采用门槛 极低 中等

AGENTS.md 更适合提供静态指导,而 MCP 适合动态工具集成。两者可以互补使用:AGENTS.md 提供项目规范,MCP 提供运行时工具。

与传统配置文件对比

与传统配置文件(如.eslintrc、.prettierrc)相比:

  1. 可读性:AGENTS.md 使用自然语言,更易理解
  2. 灵活性:无严格 schema,适应性强
  3. AI 优化:专门为 AI 代理设计
  4. 人类友好:同时可供人类阅读

最佳实践与落地建议

1. 内容组织策略

  • 分层结构:根目录提供通用指导,子目录提供特定指导
  • 优先级明确:确保嵌套文件不会产生冲突指令
  • 版本控制:将 AGENTS.md 纳入版本控制,随项目演进

2. 指令编写指南

  • 具体明确:避免模糊表述,提供可执行命令
  • 上下文完整:包含环境变量、依赖版本等关键信息
  • 测试覆盖:提供完整的测试指令和预期结果
  • 安全考虑:包含安全最佳实践和潜在风险提示

3. 工具链集成方案

// 集成示例:将AGENTS.md注入AI代理上下文
async function injectAgentsMdContext(agent: AIAgent, filePath: string) {
  const parser = new AgentsMdParser();
  const agentsMd = await parser.findNearestAgentsMd(filePath);
  
  if (agentsMd) {
    const instructions = parser.parseContent(agentsMd.content);
    
    // 将指令转换为系统提示
    const systemPrompt = this.formatAsSystemPrompt(instructions);
    agent.setSystemPrompt(systemPrompt);
    
    // 记录使用情况
    this.telemetry.trackAgentsMdUsage({
      filePath: agentsMd.filePath,
      priority: agentsMd.priority,
      sections: Object.keys(instructions)
    });
  }
}

4. 监控与优化

建立 AGENTS.md 使用监控体系:

  1. 使用频率跟踪:记录哪些指令最常被引用
  2. 有效性评估:通过代码质量指标评估指令效果
  3. 版本演进:定期审查和更新指令内容
  4. 用户反馈:收集开发者和 AI 代理的反馈

局限性与未来展望

当前局限性

  1. 标准化不足:缺乏官方 schema 验证
  2. 工具差异:不同代理实现可能有不同解析行为
  3. 动态性有限:主要提供静态指导,缺乏运行时适配

演进方向

  1. Schema 标准化:定义可选的 JSON schema 用于验证
  2. 条件指令:支持基于环境的条件性指令
  3. 智能合并:自动合并多个 AGENTS.md 文件的指令
  4. 生态系统扩展:建立插件系统支持自定义扩展

结语

AGENTS.md 代表了 AI 时代软件开发文档化的新范式。它通过极简的设计、灵活的扩展机制和广泛的工具支持,为编码代理提供了标准化的指导框架。虽然当前版本存在一些局限性,但其开放性和社区驱动的特性为其持续演进提供了坚实基础。

对于开发团队而言,采用 AGENTS.md 不仅是技术决策,更是组织文化的体现 —— 它标志着团队开始系统性地思考如何与 AI 协作,如何将人类智慧转化为机器可执行的指导。在这个 AI 辅助开发日益普及的时代,建立这样的标准化沟通机制,将成为提升开发效率和代码质量的关键因素。

资料来源

查看归档