从一次性 Prompt 到 Agent 工作流:GitHub Copilot CLI Custom Agents 搭建教程
适用对象:想把团队内重复的安全检查、发布说明、IaC 合规、事故响应等流程固化为可复用 Agent 工作流的研发/运维/平台团队。
原文:<https://github.blog/ai-and-ml/github-copilot/from-one-off-prompts-to-workflows-how-to-use-custom-agents-in-github-copilot-cli/>
原文标题:From one-off prompts to workflows: How to use custom agents in GitHub Copilot CLI
作者 / 来源:Natalie Guevara / GitHub Blog
发布时间:2026-06-09
相关入口:GitHub Copilot CLI <https://github.com/features/copilot/cli>;GitHub Docs custom agents <https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/create-custom-agents>
1. 先说结论
不要把 Agent 工作流理解成“写一个更长的 Prompt”。更稳的做法是:
- 把重复任务拆成固定输入、固定工具、固定步骤、固定输出。
- 用
.github/agents/*.agent.md把这些规则写进仓库。 - 让 GitHub Copilot CLI 通过
/agent选择并执行对应 Agent。 - 把工具缺失、敏感信息、失败路径、输出格式都写成明确规则。
- 让 Agent 编排工具和生成报告,而不是让 LLM 凭空替代安全扫描、IaC 校验或发布流程。
这篇教程会按“可复制搭建”的方式,把原文中的思路整理成一个从 0 到 1 的 Agent 工作流落地模板。
---
2. 原文事实、本文提炼与实践扩展的边界
2.1 原文事实
原文明确提到:
- Custom agents 是用 Markdown 文件定义的 Copilot Agent。
- Agent profile 放在目标仓库的
.github/agents/目录下。 - Agent profile 文件以
.agent.md结尾,例如accessibility.agent.md。 - Agent profile 使用 YAML frontmatter 描述
name、description、model、tools等信息。 - 在 Copilot CLI 中通过
/agentslash command 选择自定义 Agent。 - 原文示例覆盖四类工作流:
- Security audit
- Infrastructure as Code compliance
- Release documentation
- Incident response
- 原文强调工具缺失时不要编造结果,应报告 coverage gap。
- 原文强调不要泄露 secrets 或完整 vulnerable payload,应对 token 和凭证脱敏。
2.2 本文提炼
本文把原文方法提炼成一套通用搭建流程:
任务识别 → Agent 边界设计 → 工具清单 → Agent Profile 编写 → 本地结构校验 → CLI 调用 → 团队评审 → 持续迭代2.3 实践扩展
为了让教程可落地,本文额外补充了:
- 一个最小可运行的目录结构。
- 两个可复制的
.agent.md示例。 - 一个使用 Python 标准库编写的 Agent Profile 结构校验脚本。
- 失败案例与验收标准。
这些扩展是基于原文思想的教学脚手架,不是原文逐字提供的完整项目。
---
3. Agent 工作流适合解决什么问题
适合封装为 custom agent 的任务通常有几个特征:
- 经常重复执行。
- 每次都要解释项目上下文。
- 依赖固定命令或固定工具。
- 输出需要给团队或 PR 使用。
- 有安全边界、格式边界或审查边界。
典型例子:
- 每次发版前生成 release note。
- 每次 PR 前跑安全扫描并整理 checklist。
- 每次 Terraform/K8s 变更前做合规检查。
- 每次事故后收集部署、错误率、日志摘要。
- 每次代码评审前按团队规范检查变更。
不适合一开始就封装为 Agent 的任务:
- 一次性探索。
- 没有稳定输入输出的开放分析。
- 需要生产写操作但没有审批流程的任务。
- 工具链还不稳定、人工步骤还没跑顺的流程。
---
4. 目标架构
推荐的最小结构如下:
your-repo/
├── .github/
│ └── agents/
│ ├── security-audit.agent.md
│ └── release-docs.agent.md
├── scripts/
│ └── validate_agent_profiles.py
├── .semgrep.yml # 可选:安全扫描配置
├── .trivyignore # 可选:Trivy 忽略规则
├── .gitleaks.toml # 可选:Gitleaks 配置
└── CHANGELOG.md # 可选:发布说明输入/输出其中:
.github/agents/:存放 Agent Profile。scripts/validate_agent_profiles.py:本教程提供的离线结构校验脚本。- 工具配置文件:由实际工具读取,Agent 只负责编排和报告。
---
5. 第一步:选择第一个 Agent 场景
建议从低风险、只读、可回滚的流程开始。
优先级推荐:
- Release docs Agent:风险低,主要读 git/PR 信息并生成文档草稿。
- Security audit Agent:价值高,但要小心敏感信息脱敏。
- IaC compliance Agent:适合平台团队,但要明确只读和 dry-run。
- Incident response Agent:信息源复杂,建议最后做。
本教程用两个示例:
security-audit.agent.mdrelease-docs.agent.md
---
6. 第二步:编写 Security Audit Agent
文件路径:.github/agents/security-audit.agent.md
---
name: Security audit
description: Run standard security checks and produce a PR-ready checklist grouped by severity.
model: GPT-4.1
tools:
- gh
- git
- semgrep
- trivy
- gitleaks
- jq
---
# Security audit
## Goal
For the repository provided by the user, run standard security checks, summarize findings by severity, and output a PR-ready checklist with owners and next steps.
## Operating rules
- Prefer existing repository configuration files: `.semgrep.yml`, `.trivyignore`, `.gitleaks.toml`.
- If a tool is missing, record it as a **High** severity coverage gap instead of inventing results.
- Do not paste secrets or full vulnerable payloads. Redact tokens and credentials.
- Output must include severity, owner, evidence, recommended fix, and verification command.
## Standard checks
1. Secret scanning: `gitleaks detect --redact --no-git --source .`
2. Container/filesystem scan: `trivy fs .`
3. SAST scan: `semgrep scan --config .semgrep.yml`
## Ownership mapping
- `backend/**`: @api-team
- `frontend/**`: @web-platform
- `.github/workflows/**`: @platform-eng
- `terraform/**`: @infra-oncall
- everything else: @security-champions
## Output format
Security audit report
Date: March 23, 2026 Repository: <repo>
Critical
- [ ] <finding>
- Owner: <team>
- Evidence: <redacted evidence>
- Fix: <recommended fix>
- Verify:
<command>
High
...
Coverage gaps
- [ ] <missing tool/config>
设计要点:
tools只列真实会用的工具。- 缺工具时明确报告 coverage gap,不让 Agent 编造扫描结果。
- 输出格式固定,便于贴到 PR、Issue 或审计记录。
- 安全边界写在 Agent Profile 内,而不是靠调用者临时提醒。
---
7. 第三步:编写 Release Docs Agent
文件路径:.github/agents/release-docs.agent.md
---
name: Release docs
description: Generate release notes from git tags, merged PRs, and CHANGELOG.md.
model: GPT-4.1
tools:
- git
- gh
- jq
---
# Release docs
## Goal
Create a release note draft for the requested version range.
## Inputs
- Current release version
- Previous release tag, or fallback to the latest Git tag
## Workflow
1. Identify the version range with `git tag --sort=-creatordate`.
2. Collect merged pull requests with `gh pr list --state merged`.
3. Read existing `CHANGELOG.md` if available.
4. Group changes into Added, Changed, Fixed, Security, Performance, and Maintenance.
5. Produce a Markdown release note draft.
## Rules
- Do not invent PRs or contributors.
- If GitHub CLI is unavailable, report the missing tool and continue with git log only.
- Keep breaking changes and migration notes near the top.
- Include verification notes when available.
## Output format
Release notes: <version>
Highlights
- <short user-facing change>
Added
- <item> (#PR, @author)
Changed
- <item>
Fixed
- <item>
Security
- <item>
Upgrade notes
- <migration or compatibility note>
Verification
- <test/build evidence>
这个 Agent 风险较低,适合作为团队第一个 custom agent:它主要读取 git/PR 信息并生成草稿,不应该直接发布 release 或 push commit。
---
8. 第四步:加一个离线结构校验脚本
GitHub Copilot CLI 的真实执行依赖 CLI 环境和账号能力。为了在团队评审前先保证 Agent Profile 不太离谱,可以加一个轻量校验脚本。
文件路径:scripts/validate_agent_profiles.py
from __future__ import annotations
import sys
from pathlib import Path
REQUIRED_FIELDS = ("name:", "description:", "tools:")
def validate_agent(path: Path) -> list[str]:
text = path.read_text(encoding="utf-8")
errors: list[str] = []
if not path.name.endswith(".agent.md"):
errors.append("file name must end with .agent.md")
if not text.startswith("---\n") or "\n---\n" not in text[4:]:
errors.append("missing YAML frontmatter")
frontmatter = text.split("---", 2)[1]
for field in REQUIRED_FIELDS:
if field not in frontmatter:
errors.append(f"missing frontmatter field: {field}")
if "Do not" not in text and "不要" not in text:
errors.append("missing explicit safety boundary")
return errors
def main() -> int:
root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
files = sorted((root / ".github" / "agents").glob("*.agent.md"))
if not files:
print("FAIL: no .agent.md files found")
return 1
failed = False
for path in files:
errors = validate_agent(path)
if errors:
failed = True
print(f"FAIL: {path}")
for error in errors:
print(f" - {error}")
continue
print(f"PASS: {path}")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())运行:
python3 scripts/validate_agent_profiles.py .期望输出:
PASS: .github/agents/release-docs.agent.md
PASS: .github/agents/security-audit.agent.md这个脚本只做结构校验,不代表 Copilot CLI 已真实执行成功。它的价值是把“文件名、frontmatter、安全边界”这类低级问题前置拦截。
---
9. 第五步:在 Copilot CLI 中调用 Agent
原文给出的调用方式是:
/agent基本流程:
- 在目标仓库目录中启动 GitHub Copilot CLI。
- 输入
/agent。 - 选择
.github/agents/下定义的 custom agent。 - 输入本次任务参数,例如:
Run security audit for this repository. Use existing config files when available. Do not expose secrets. Produce a PR-ready checklist.或者:
Generate release notes for v1.8.0. Compare against the previous git tag. Do not invent PRs. Put breaking changes first.注意:真实调用前应确认当前 CLI 版本、账号权限、仓库权限和工具安装情况。本文提供的是工作流搭建教程,不声称已在你的 GitHub Copilot CLI 账号中完成真实 smoke test。
---
10. 第六步:为 Agent 设计输入契约
不要让用户每次自由发挥。每个 Agent 都应该定义最小输入。
Security audit Agent 的输入契约:
Repository: 当前仓库或指定仓库
Scope: full / changed-files-only
Output target: PR comment / Markdown file / terminal only
Risk mode: read-onlyRelease docs Agent 的输入契约:
Version: v1.8.0
Previous tag: v1.7.3 或 auto
Audience: internal / customer-facing
Output target: CHANGELOG draft / GitHub release draftIncident response Agent 的输入契约:
Service: payments-api
Environment: production / staging
Start time: March 23, 2026 10:00 am PT
End time: March 23, 2026 11:30 am PT
Incident commander: @name
Output target: incident timeline / postmortem draft输入契约越清楚,Agent 越不容易漂移。
---
11. 第七步:把工具能力与 LLM 能力分开
一个常见错误是让 LLM “直接判断有没有漏洞”。更稳的模式是:
专业工具负责事实 → Agent 负责调度与整理 → 人负责确认和批准例如:
gitleaks负责密钥扫描。trivy负责镜像/文件系统漏洞扫描。semgrep负责 SAST。terraform validate负责 Terraform 语法和 provider 级校验。conftest/opa负责策略校验。kubeconform负责 Kubernetes manifest schema 校验。- Agent 负责把结果按严重性、责任人、修复建议、验证命令整理成统一输出。
这也是原文最重要的工程启发:Agent 不应该是“万能脑补器”,而应该是“工具编排器 + 报告生成器 + 团队规则执行器”。
---
12. 第八步:加入失败处理规则
每个 Agent Profile 至少写清 4 类失败处理:
12.1 工具缺失
If a required tool is missing, do not invent results. Record it as a High severity coverage gap and include the install or remediation hint.12.2 配置缺失
If `.semgrep.yml` is missing, do not run a generic broad scan silently. Report the missing config and explain what was skipped.12.3 敏感信息
Never print secrets, tokens, private keys, or full vulnerable payloads. Redact them before including evidence.12.4 外部副作用
Default to read-only mode. Do not push commits, publish releases, create tickets, change infrastructure, or delete resources unless the user explicitly confirms that step.这类规则比“请谨慎一点”更有用,因为它们能直接约束输出和动作。
---
13. 第九步:用 PR Review 管理 Agent 变更
Agent Profile 应当像生产脚本一样 review。
建议 PR checklist:
## Agent profile review checklist
- [ ] 文件位于 `.github/agents/`
- [ ] 文件名以 `.agent.md` 结尾
- [ ] frontmatter 包含 `name`、`description`、`tools`
- [ ] 工具列表只包含团队实际支持的工具
- [ ] 写明工具缺失时的行为
- [ ] 写明敏感信息脱敏规则
- [ ] 写明默认只读边界
- [ ] 写明输出格式
- [ ] 示例命令可以在本地或 CI 中验证
- [ ] 不包含 token、密码、私有 IP 或内部密钥如果 Agent 会调用生产系统、云资源、数据库或发布流程,还应该增加审批要求:
- [ ] 所有写操作都需要人工确认
- [ ] 默认 dry-run
- [ ] 有回滚说明
- [ ] 输出中明确标记未执行的建议动作---
14. 第十步:把 Agent 纳入 CI 或本地检查
最小 CI 检查可以只跑结构校验:
name: Agent profile checks
on:
pull_request:
paths:
- ".github/agents/**"
- "scripts/validate_agent_profiles.py"
jobs:
validate-agents:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: python3 scripts/validate_agent_profiles.py .这个 CI 不会验证 Copilot CLI 的真实行为,但能确保团队不会提交明显残缺的 Agent Profile。
---
15. 三个可复用模板
15.1 安全审计 Agent 模板
适用场景:PR 前安全检查、仓库周期性巡检、上线前风险报告。
最小字段:
目标:扫描并生成安全 checklist
工具:gitleaks / trivy / semgrep
边界:只读、脱敏、不编造结果
输出:按严重性分组的 Markdown
验收:每条发现有 owner、evidence、fix、verify command15.2 发布说明 Agent 模板
适用场景:发版前生成 changelog 或 GitHub release draft。
最小字段:
目标:根据 git tag 和 merged PR 生成 release notes
工具:git / gh / jq
边界:不发布、不 push、不编造 PR
输出:Highlights + 分类变更 + Upgrade notes + Verification
验收:所有条目能追溯到 commit、PR 或 CHANGELOG15.3 事故响应 Agent 模板
适用场景:事故期间快速整理 timeline 和初步影响面。
最小字段:
目标:收集部署、错误率、延迟、日志摘要并生成事故快照
工具:日志平台 CLI / metrics API / git / deploy history
边界:脱敏、只读、不自动回滚、不自动扩容
输出:timeline + impact + suspected causes + next actions
验收:每条结论都标注来源或不确定性---
16. 最小落地路线图
第 1 周:做一个只读 Agent
- 选择 release docs 或 security audit。
- 写
.agent.md。 - 加结构校验脚本。
- 本地验证文件结构。
- 找 1 个真实 PR 做人工 dry-run。
第 2 周:把输出接入团队流程
- 固定输出格式。
- 让团队评审 Agent 输出是否可用。
- 补充 owner mapping。
- 补充工具缺失与配置缺失处理。
第 3 周:纳入 CI 和文档
- Agent Profile 变更触发 CI 校验。
- README 中说明如何调用
/agent。 - 记录常见失败和处理方式。
第 4 周:扩展到第二个场景
- 从 release docs 扩展到 security audit,或从 security audit 扩展到 IaC compliance。
- 不要一次做十个 Agent。
- 每个 Agent 都要有明确的 owner 和 review 机制。
---
17. 验收标准
一个 Agent 工作流可以进入团队试用,至少满足:
- Agent Profile 在
.github/agents/下。 - 文件名以
.agent.md结尾。 - frontmatter 包含
name、description、tools。 - 工具列表真实可用或有 coverage gap 规则。
- 输出格式固定。
- 明确禁止泄露 secrets。
- 明确默认只读或 dry-run。
- 本地结构校验通过。
- 至少一次人工 dry-run 输出被团队 review。
- 真实执行前清楚区分“建议动作”和“已执行动作”。
---
18. 常见坑
坑 1:把 Agent 写成泛泛 Prompt
坏例子:
你是一个资深安全专家,请帮我检查项目安全问题。好例子:
Run gitleaks, trivy, and semgrep using repository configs. If a tool is missing, report a High severity coverage gap. Redact secrets. Output a PR-ready checklist grouped by severity.坑 2:没有工具缺失策略
如果没有写缺工具规则,Agent 很容易输出看似完整但不可验证的结果。
坑 3:让 Agent 自动执行高风险动作
不要默认让 Agent:
- push commit
- publish release
- apply Terraform
- delete resources
- auto rollback production
- create external tickets
这些应作为单独确认步骤。
坑 4:输出格式不固定
没有固定输出格式,团队很难消费结果。PR checklist、release note、incident timeline 都应该模板化。
坑 5:Agent Profile 不进 review
Agent Profile 会影响团队自动化行为,应进入正常代码评审流程。
---
19. 本教程的离线验证结果
为验证本文中的教学脚手架,已构造一个最小 demo:
/tmp/copilot-agent-workflow-demo/
├── .github/agents/release-docs.agent.md
├── .github/agents/security-audit.agent.md
└── scripts/validate_agent_profiles.py执行命令:
python3 /tmp/copilot-agent-workflow-demo/scripts/validate_agent_profiles.py /tmp/copilot-agent-workflow-demo实际输出:
PASS: /tmp/copilot-agent-workflow-demo/.github/agents/release-docs.agent.md
PASS: /tmp/copilot-agent-workflow-demo/.github/agents/security-audit.agent.md验证级别说明:
static_publish_ok:本文发布后验证。mock_code_run_ok:离线结构校验脚本已运行通过。real_backend_contract_ok:本文给出的.agent.md结构与原文描述的 custom agent profile 约定一致。real_backend_smoke_ok:未执行。本文没有在真实 GitHub Copilot CLI 账号中调用/agent。
---
20. 最后给一份可直接复制的落地清单
# Custom Agent 落地清单
## 任务边界
- [ ] 这个任务是否重复发生?
- [ ] 是否有固定输入?
- [ ] 是否有固定工具?
- [ ] 是否有固定输出格式?
- [ ] 是否默认只读或 dry-run?
## Agent Profile
- [ ] 文件在 `.github/agents/`
- [ ] 文件名以 `.agent.md` 结尾
- [ ] 有 YAML frontmatter
- [ ] 包含 `name`、`description`、`tools`
- [ ] 工具列表真实可用
- [ ] 写明工具缺失处理
- [ ] 写明敏感信息脱敏规则
- [ ] 写明输出模板
## 验证
- [ ] 本地结构校验通过
- [ ] 至少一次人工 dry-run
- [ ] 输出能被 PR / Issue / Release / Incident 文档直接使用
- [ ] 团队 review 通过
## 上线边界
- [ ] 不自动执行生产写操作
- [ ] 不自动发布 release
- [ ] 不自动修改基础设施
- [ ] 高风险动作需要人工确认---
21. 一句话复盘
Custom agents 的价值不在于“让 Prompt 更长”,而在于把团队反复执行的工程流程写成可审查、可版本化、可验证的仓库资产;LLM 负责理解上下文和整理报告,专业 CLI 工具负责产生事实,人工负责高风险决策。