OpenCode Skills使用实践

OpenCode是一款AI编程工具,产品是开源的,且提供MiniMax 2.1,GLM 4.7和Grok Code Fast 1等免费模型;

本文主要整理「个人使用OpenCode Skills过程中总结的经验」

TOC

Agent

Agent 可以当成对LLM的“角色设定”,例如"你是一个资深的前端开发工程师",“你是一个DevOps专家”,“你是一个计划制定者” etc

从 OpenCode 源码来看,一个 Agent 接口,需要包含 namedescriptionmode 三个基本字段,除此之外还有一些可选字段,例如限定可使用的工具,持有的权限等:

interface Agent {  name: string;           // Agent 名称  description: string;    // 描述,告诉 AI 这个角色是干嘛的  mode: 'primary' | 'subagent';  //  Agent 还是子 Agent  model?: string;         // 使用的 AI 模型  prompt?: string;        // 系统提示词  tools?: {               // 允许使用的工具    write?: boolean;    edit?: boolean;    bash?: boolean;    // ... 其他工具  };  permission?: {          // 权限设置    edit?: 'allow' | 'deny' | 'ask';    // ... 其他权限  };  // ... 其他配置}

Agent Skills

Agent skills let OpenCode discover reusable instructions from your repo or home directory. Skills are loaded on-demand via the native skill tool—agents see available skills and can load the full content when needed.

Skills定义了一套可复用的行为规范,Skill 文件采用特定的目录结构进行组织,目录可以放在 ~/.config/opencode/skills/ 或项目的 .opencode/skills/ 目录下,分别对应全局和项目级别的技能。

$ tree ~/.config/opencode/skills/Users/gjx/.config/opencode/skills├── generate-git-commit-message   ├── assets   ├── references   ├── scripts   └── SKILL.md├── markdown-codeblock   └── SKILL.md└── skill-creator    ├── LICENSE.txt    ├── references       ├── output-patterns.md       └── workflows.md    ├── scripts       ├── init_skill.py       ├── package_skill.py       └── quick_validate.py    └── SKILL.md9 directories, 9 files

Create A Skill

Q: 如何编写一个Skill?
A: 懒人可以下载 skill-creator 这个skill,然后让AI帮你写。此章节结束

AI直接生成Skill基本没什么大问题,格式什么的都ok,内容的话最好还是自己审查一下。

格式规范很简单,每个 SKILL.md 以 YAML Frontmatter [1] 开头,其中 namedescription 是必须的字段,其他字段可选。

---name: git-releasedescription: Create consistent releases and changelogslicense: MITcompatibility: opencodemetadata:  audience: maintainers  workflow: github---content

关于如何写好一个skill,在 awesome-claude-skills/skill-creator/SKILL.md 已经有很完整的建议了

这里简单记录两条Skill[2],分别解决我平时开发中的两个需求:

痛点:写好Git Commit Message属于不难,但是麻烦的事情。所以VSCode的Copilot支持自动生成Commit Message,但可能其内置的Prompt写的不够好,总结往往过于简洁。Cline生成的Commit Message则很详细,推测内置的Prompt写的不错,但是diff的范围是当前所有的改动,而我只想提交stage的改动。

所以写了这个skill,让AI使用 git --no-pager diff --cached [3]来获取暂存区的变更内容,然后按照我的需求生成commit message,

后面每次提交代码时,只需要stage好改动,然后运行 opencode --prompt "Generate git commit message" 就可以自动生成并提交commit了,省时省力。

---name: generate-git-commit-messagedescription: Generate and execute git commit messages for the current repository based on staged changes. Use when you need to commit staged files with an automatically generated conventional commit message.---# Generate git commit message for current repo## OverviewThis skill automates the process of generating a conventional commit message based on staged changes in a git repository and executes the commit.## WorkflowFollow these steps to generate and execute a commit:1. **Check staged changes**: Run `git status` to verify there are staged files. If no staged changes, inform the user.2. **Analyze changes**: Run `git --no-pager diff --cached` to examine the staged modifications.3. **Generate message**: Create a conventional commit message based on the changes:   - Determine type: `feat` (new feature), `fix` (bug fix), `docs` (documentation), `style` (formatting), `refactor` (code restructuring), `test` (testing), `chore` (maintenance)   - Add optional scope in parentheses if applicable (e.g., component name)   - Write concise description (50 chars max)   - Add body if explanation needed, separated by blank line4. **Execute commit**: Run `git commit -m "generated message"`## Examples- For adding a new user authentication feature: `feat: implement user authentication`- For fixing a login bug: `fix: resolve login validation error`- For updating documentation: `docs: update API reference`

痛点:AI输出的markdown文本,代码块的嵌套经常出问题。另外我希望让AI帮我按照Shiki的语法来为行内代码标记语言,为代码块添加语言标记/文件名,并且使用Shiki的transformer marks来标记diff、highlight、focus、error、warning等。

---name: markdown-codeblockdescription: Use when the user wants to highlight code in markdown files, including inline code highlighting with {lang} prefix syntax, code blocks with language fences and titles, and transformer marks for diffs, highlights, focus, errors, and warnings. Always read this skill file when inserting code blocks or inline code in markdown.---# Shiki Code Highlighting for Markdown Blogs## Inline Code SyntaxApply to code wrapped in **single backticks**:```md`{python} print("Hello")``{javascript} console.log("x")``{html} <div></div>``{rust} fn main() {}``{shell} echo "hi"````**Do NOT** use `{lang}` prefix on triple-backtick code blocks.## Code BlocksUse language name in opening fence. Optionally add filename after language:```pythondef greet(name):    return f"Hello, {name}!"``````typescript hello.tsconst add = (a: number, b: number): number => a + b;```### Nested Code BlocksThe default number of backticks for code blocks is 3. When there are nested code blocks inside the content, the outer code block's backticks increase by one per nesting level. If there are multiple layers of nesting, continue adding backticks accordingly.For example, if the inner content contains triple backticks, use 4 backticks for the outer wrapper:````md```typescript// Your code example here that might contain ``` in it```````If the inner content has 4 backticks, use 5 for the outer, and so on.## Transformer MarksAdd marks in comments after `#`. Use marks to draw attention or add semantic meaning:| Mark                  | When to Use                                         || --------------------- | --------------------------------------------------- || `# [!code --]`        | Show code removal (before  after comparisons)      || `# [!code ++]`        | Show code addition (before  after comparisons)     || `# [!code highlight]` | Emphasize important or key lines                    || `# [!code word:term]` | Highlight specific identifier, keyword, or term     || `# [!code focus]`     | De-emphasize surrounding code, focus on one section || `# [!code error]`     | Mark lines with errors, invalid code, or exceptions || `# [!code warning]`   | Mark lines with warnings, deprecations, or cautions |### Diff (Before  After)```rustlet x = 5; // [!code --]let x = 10; // [!code ++]```### Line Highlight (Key Lines)```pythondef calculate(items):    total = 0    for item in items:  # [!code highlight]        total += item.price    return total  # [!code highlight]```### Word Highlight (Specific Terms)```typescript// [!code word:interface]interface User {  id: number;  // [!code word:id]  name: string;  // [!code word:name]}```### Focus (Main Topic)```go// [!code focus]func (s *Service) Process() error {    return s.validate()}func (s *Service) validate() error {    // validation logic}```### Error (Problematic Code)```javascriptconst result = JSON.parse(userInput); // [!code error]try {    await riskyOperation(); // [!code error]} catch (e) {    handleError(e); // [!code warning]}```

Why Skills

个人觉得Skill比较实用的一些地方:

  • 避免重复指令
    将常用的指令和工作流程封装为可复用的模块,遵循 DRY (Don’t Repeat Yourself) 原则。后续再执行任务时,无需重新如何工作,要遵循什么规则。节省时间、精力。
    例如,每次生成 Git commit message 时,如果没有 Skill,就需要重复描述怎么获取变更信息,格式要求有什么要求;而有了 Skill,只需一句"Generate git commit message"就能自动完成。
  • 版本控制 & 知识共享
    一个Skill在本质上是一个目录,因此可以提交到代码库进行版本控制,并与社区共享
  • 上下文控制
  • 精细的权限控制

Awesome Skills

本章节记录一些个人觉得实用的Skill

插件市场:

此外还有一些idea


  1. Frontmatter is a way to add metadata to your Markdown documents using YAML, TOML, or JSON at the beginning of the file. It’s widely used in static site generators and content management systems. Using Frontmatter in Markdown - Markdown Documentation ↩︎

  2. GitHub Link dotfiles/tui_cli/ai_skills at main · Efterklang/dotfiles ↩︎

  3. --no-pager Do not pipe Git output into a pager;意思就是直接输出plain text,对AI更友好。Git - git Documentation ↩︎

OpenCode Skills使用实践

https://vluv.space/ai_skills/

Author

GnixAij

Posted

2026-01-07

Updated

2026-01-08

License