OpenCode使用指南

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

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

Table of Contents:

Intro

要讲的模块。包括slash commands, agent, agent skills,都是OpenCode中比较重要的功能模块。

Location

这些模块在存储形式上采用Markdown文件进行存储和管理。可以分为两种层级:

  • 全局:~/.config/opencode/
    • Slash Commands:~/.config/opencode/commands/
    • Agent:~/.config/opencode/agents/
    • Agent Skills:~/.config/opencode/skills/
  • 项目级别:.opencode/
    • Slash Commands:.opencode/commands/
    • Agent:.opencode/agents/
    • Agent Skills:.opencode/skills/

Usage Scenarios

  • Slash Commands:将常用的单步操作封装成命令,例如创建Git提交、检查拼写。这些操作一般都是用户明确调用的,且相对简单
  • Skill:对于需要多步操作,且步骤有规范要求的技能,可以封装成Skill中。例如对Office文件(.pptx, docx)的处理,需要分解成多个步骤:读取文件内容、分析内容、生成修改建议、输出结果,有些操作还要调用python脚本来辅助完成

Slash Commands

Custom commands let you specify a prompt you want to run when that command is executed in the TUI.

Commands | OpenCode

作用就是将常用的prompt指令封装成快捷命令,避免每次都要重复输入相同的prompt内容。

例如,可以让AI根据git暂存区的变更内容,生成符合规范的Git Commit Message,并执行提交操作。

git-commit.md
---description: create git commitsubtask: true---Follow these steps to generate and execute a commit:1. **Analyze changes**: Run `git --no-pager diff --cached` to examine the staged modifications.2. **Generate message**: Create a conventional commit message based on the changes using the format:   - Determine type: `feat` , `fix` , `docs` , `style` , `refactor` , `test` , `chore`   - Add optional scope in parentheses if applicable, for example, `doc(api)`   - Write concise description (50 chars max)   - Add body if explanation needed, separated by blank line, prefer to explain WHY something was done from an end user perspective instead of WHAT was done.   - The output language should be English if not specified otherwise.1. **Execute commit**: Run `git commit -m "generated message"`
Command 参数

<command_name>.md 中,使用 $ARGUMENTS 表示命令行参数。例如执行 /<command> Button 时,OpenCode会将 $ARGUMENTS 替换为 Button

对于多个参数,可分别用 $1$2 代替

该Command解决的痛点是:

  • VSCode的Copilot自动生成Commit Message总结往往过于简洁
  • Cline生成的Commit Message则很详细,但是diff的范围是当前所有的改动,而我只想提交已stage的改动。

有了这个Command,以后只需在对话框中输入 /git-commit 即可让AI生成符合规范的Git提交信息,无需每次都强调"要遵循Conventional Commit specification",“要使用 git --no-pager diff --cached [1]来获取变更”

Agent

Agents are specialized AI assistants that can be configured for specific tasks and workflows. They allow you to create focused tools with custom prompts, models, and tool access.

Agents | OpenCode

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

<agent-name.md> 的FrontMatter[2]中,可以指定Agent的配置,例如使用的model、可用的Tools[3]等:

Create An Agent

---mode: primaryhidden: truemodel: opencode/claude-haiku-4-5color: "#E67E22"tools:  "*": false  "github-pr-search": true---You are a duplicate PR detection agent. When a PR is opened, your job is to search for potentially duplicate or related open PRs.Use the github-pr-search tool to search for PRs that might be addressing the same issue or feature.IMPORTANT: The input will contain a line `CURRENT_PR_NUMBER: NNNN`. This is the current PR number, you should not mark that the current PR as a duplicate of itself.Search using keywords from the PR title and description. Try multiple searches with different relevant terms.If you find potential duplicates:- List them with their titles and URLs- Briefly explain why they might be relatedIf no duplicates are found, say so clearly. BUT ONLY SAY "No duplicate PRs found" (don't say anything else if no dups)Keep your response concise and actionable.

Awesome Agents

  • Web Interface Guidelines Vercel的Web界面设计规范Agent,底部有提供 AGENTS.md,可以帮你检查UI设计是否符合Vercel的设计规范

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.

Agent Skills | OpenCode

Skills定义了一套可复用的行为规范,Skill 文件采用特定的目录结构进行组织:

~/.config/opencode/skills/skill-creator├── LICENSE.txt├── references  # 在SKILLS.md中引用的参考文档   ├── output-patterns.md   └── workflows.md├── scripts # 在SKILLS.md中引用的脚本   ├── init_skill.py   ├── package_skill.py   └── quick_validate.py└── SKILL.md

Create A Skill

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

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

格式依旧是以 YAML Frontmatter 开头,其中 namedescription 是必须的字段,其他字段可选。

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

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

  • 清晰规范FrontMatter中的元数据
  • 合理搭配 scriptsreferencesassets 等资源

这里分享一个 markdown-codeblock Skill,供参考,解决AI输出markdown代码块时常出错的问题:

  1. 代码块的嵌套层级不对
  2. 为方便预览,希望
    1. LLM按照Shiki的语法来为行内代码标记语言
    2. 使用Shiki的Transformer,为代码添加diff、highlight等标记
---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 |### Examples```rustlet x = 5; // [!code --]let x = 10; // [!code ++]```Word Highlight```typescript// [!code word:interface]interface User {  id: number;  // [!code word:id]  name: string;  // [!code word:name]}```

Why Skills

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

复用

Skill类似于企业工作中所说的SOP,解释执行任务的各步骤要怎么去做。将这些说明存储在md中,避免LLM自由发挥,也方便复用

例如,在没有 Skill 的情况下,每次执行特定任务(如生成符合特定规范的 Git Commit Message)时,用户必须反复输入获取变更的方法(如 git diff --cached)以及复杂的格式要求。

共享

一个Skill在本质上是一个目录,因此可以提交到代码库进行版本控制,确保团队成员在同一个项目中使用一致的开发规范。用户也可以分享自己的技能包,或从 Skill 市场获取成熟的解决方案

Context Control

Skill的核心特性在于"渐进式披露"。OpenCode在初始只会加载各个 Skill.md 中的FrontMatter,即Skill名称和描述等元数据,等到实际调用某个Skill时才会加载技能的全部内容,避免了将所有规则一次性全部塞入 LLM 的上下文,从而防止上下文窗口过载

Awesome Skills

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

插件市场:

此外还有一些idea


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

  2. 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 ↩︎

  3. Tools allow the LLM to perform actions in your codebase. OpenCode comes with a set of built-in tools, but you can extend it with custom tools or MCP servers.Tools | OpenCode ↩︎

OpenCode使用指南

https://vluv.space/ai_skills/

Author

GnixAij

Posted

2026-01-07

Updated

2026-02-03

License