蓝色天空.知识 · 实践 · 创造
我的收藏
OpenCode 教程目录 28章
OpenCode / LEARN BY DOING

OpenCode 自定义命令:模板、参数与子会话

用 JSON 和 Markdown 定义常用命令,实测参数、文件引用、Shell 输出和子会话。

学完这一章,你能够

  • 用 JSON 和 Markdown 定义常用命令,实测参数、文件引用、Shell 输出和子会话。

定义、发现和触发

在聊天输入框输入 / 后继续键入名称或查看候选命令,再选中并提交。名称承担注册键的作用,描述帮助在列表里识别用途。启动同一工作区时检查内置命令和团队同名命令的实际覆盖,避免意外替换常用入口。

V1 在 opencode.json 或 opencode.jsonc 的 command 对象里用名称作为键。可为模板设置 description、agent、model 和 subtask。若想团队共享,在项目 .opencode/commands/ 放文件,例如 stock-lines.md 对应 /stock-lines。YAML frontmatter 放元数据,Markdown 正文放模板。

用户级目录可提供跨项目通用命令,项目目录适合随版本控制共享。名称、层级和优先级需按使用端的版本核对。本站测试确认本机 V1 同时注册了 JSON 和项目 Markdown 定义。

把输入放进模板

使用 $ARGUMENTS 时可一次插入命令名之后的参数字符串,适合检索、摘要等自由输入。分字段使用 $1、$2 等位置参数。含空格的单个字段用引号包住。若最大占位符后仍有额外文本,当前官方文档说明它会收纳余下参数,写多字段命令时应说明该边界。

库存演示提交 /stock-lines "copper dock" high "check spare crates",让模板按地点、严重级别和摘要三行展开。核对真实模型请求,而后再把同样布局用于提交端点路径、请求方法和生成要求。

如需依据项目状态,可在模板写 ! 后紧跟反引号包住的本机命令。执行输出进入提示内容,脚本的工作目录、权限与工具可用性要单独确认。本站只运行受控的 echo 演示。列目录、查看 Git 或运行检查前先检查命令,输入参数不得直接拼入可执行 Shell。

使用 @notes/stock-rules.txt 引用项目文件,让模型获得可读的上下文。检查文件路径、项目权限与文件类型。本站在原生日志中确认文件消息部分和实际发送给模型的文本。使用命令前检查附件或 Shell 输出是否含秘密或私有数据。

选模型和会话位置

常规命令沿用当前会话。可用 agent 指定执行角色,使用 provider/model 指定命令需要的模型。使用前检查模型是否已配置并可调用,尤其要区分代理配置默认模型与当前客户端选中模型。

V1 默认会根据 agent 的类型决定是否委托。subtask: true 传入委托执行请求,子会话有自己的上下文并向父会话返回结果。指定 subtask: false 可以将演示中的子角色指引放入当前会话。委托将任务执行放在子会话,父会话仍可能收到工具或模型返回的信息。

把复杂任务拆成简短输入合同。例如端点命令要求方法、路径及说明,审查命令接收本机变更与测试结果,健康摘要读取依赖、版本和仓库状态。写出观察点,运行时逐步核对命令返回值与真实变更。

配置迁移

V2 单数 command 改为 commands,用 subagent 指定是否委托,subtask 是历史兼容用法。迁移时检查同名覆盖、文件发现、模型回退和参数展开。本站演示运行的是 V1.19.5。

存储方式

方式用途作用域
JSON 对象把模板与其它项目设置一同维护。用户或项目配置文件。
Markdown 文件将较长指引保存在独立文件中,元数据放在开头。用户目录或项目 .opencode/commands/。

按位置接收输入

标识意义演示值
$1第一项参数。copper dock
$2第二项参数。high
$3此模板最后一个位置,接收第三项及剩余文本。check spare crates

V1 自定义命令字段

字段用法
template定义发送内容。JSON 定义提供该字段,Markdown 使用正文。
description提供命令菜单里的识别文本。
agent选择角色,角色类型也影响是否自动委托。
subtask覆盖是否委托到子任务。V2 对应 subagent。
model为命令选择配置好的提供商及模型,可覆盖常规选择。

检查给库存命令的参数和附件实际如何展开

含完整源码 · 89 行
展开查看收起
python
"""Exercise OpenCode V1 JSON and Markdown commands against an isolated local project."""

from hashlib import file_digest
from http.server import ThreadingHTTPServer
import json
import os
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
from threading import Thread

from cli_sessions import profile,server
from first_use import request
from rules_lab import Fixture, initialize


def put(path,value):
    path.parent.mkdir(parents=True,exist_ok=True)
    path.write_text(value,encoding="utf8")


def check(executable):
    with TemporaryDirectory(prefix="mbsky-opencode-commands-") as temp, ThreadingHTTPServer(("127.0.0.1",0),Fixture) as model:
        root=Path(temp)
        workspace=root/"work"
        env=profile(root)
        env.update(HOME=str(root),USERPROFILE=str(root),GIT_CONFIG_GLOBAL=os.devnull,GIT_CONFIG_NOSYSTEM="1")
        initialize(workspace,env,model)
        op=workspace/"opencode.json"
        config=json.loads(op.read_bytes())
        config["permission"]={"*":"deny","read":"allow","task":"allow","bash":{"*":"deny","echo fixture-stock-report":"allow"}}
        config["agent"]={"stock-review":dict(mode="subagent",description="Reviews warehouse inventory",permission={"edit":"deny"})}
        config["command"]={
            "count-report":dict(description="Report a restock quantity",template="Inspect the warehouse route: $ARGUMENTS."),
            "forced-review":dict(description="Review in a delegated context",agent="stock-review",
                                 subtask=True,template="Review stock independently."),
            "inline-review":dict(description="Review in the present context",agent="stock-review",
                                 subtask=False,template="Review stock inline."),
            "template-shell":dict(description="Collect the fixture command output",
                                  template="Review this report output:\n!`echo fixture-stock-report`\nOnly summarize."),
        }
        put(op,json.dumps(config))
        put(workspace/".opencode/commands/stock-lines.md","---\ndescription: Label fields for a stock note\n---\n"
            "Location: $1\nSeverity: $2\nSummary: $3\n")
        put(workspace/".opencode/commands/stock-reference.md","---\ndescription: Review a stock policy\n---\n"
            "Check restock policy with the following reference.\n@notes/stock-rules.txt\n")
        put(workspace/"notes/stock-rules.txt","fixture-warehouse-rule: cap reservations at 17.\n")
        model.model_contexts=[]
        worker=Thread(target=model.serve_forever,daemon=True);worker.start()
        try:
            with server(executable,workspace,env) as origin:
                ver=request(origin,"/global/health")["version"]
                registered={x["name"]:x for x in request(origin,"/command")}
                def run(name,arguments=""):
                    start=len(model.model_contexts)
                    sid=request(origin,"/session",{"title":"Command "+name})["id"]
                    request(origin,f"/session/{sid}/command",dict(command=name,arguments=arguments,
                                                                  model="openai/rule-fixture",agent="build"))
                    messages=request(origin,f"/session/{sid}/message")
                    children=request(origin,f"/session/{sid}/children")
                    return ("\n".join(model.model_contexts[start:]),messages,len(children))
                joined,_,_=run("count-report","north row 16")
                quoted,_,_=run("stock-lines",'"copper dock" high "check spare crates"')
                shell,_,_=run("template-shell")
                file,history,_=run("stock-reference")
                force_context,_,forced_children=run("forced-review")
                inline_context,_,inline_children=run("inline-review")
                attachments=[p for msg in history for p in msg["parts"] if p.get("type")=="file"]
                result=dict(json_command=registered["count-report"]["description"]=="Report a restock quantity",
                    markdown_command=registered["stock-lines"]["description"]=="Label fields for a stock note",
                    arguments_text="Inspect the warehouse route: north row 16." in joined,
                    positions=["Location: copper dock" in quoted,"Severity: high" in quoted,
                               "Summary: check spare crates" in quoted],
                    shell_output="fixture-stock-report" in shell and "echo fixture-stock-report" not in shell,
                    file_part=any(str(p.get("filename","")).endswith("stock-rules.txt") for p in attachments),
                    file_contents="fixture-warehouse-rule: cap reservations at 17." in file,
                    subtask_true_children=forced_children,subtask_false_children=inline_children,
                    subtask_true_prompt="Review stock independently." in force_context,
                    subtask_false_prompt="Review stock inline." in inline_context)
        finally:
            model.shutdown()
            worker.join(timeout=4)
    with executable.open("rb") as f:digest=file_digest(f,"sha256").hexdigest()
    return dict(version=ver,binary_sha256=digest,python_version=sys.version.split()[0],actual=result)


if __name__=="__main__":
    print(json.dumps(check(Path(sys.argv[1]).resolve()),ensure_ascii=False,indent=2))
本机 V1 注册两种格式的命令,并实际展开整串与位置输入。回环模型收到 Shell 输出或文件内容。真值配置产生子会话,假值配置保持当前会话。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

运行库存命令练习

使用 Python 运行 command_templates_lab.py,传入当前机器上的 OpenCode V1.19.5 可执行文件路径。

下载本章实验包 (mbskycom202612a239.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:OpenCode

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a239.zip

下载课程关联工程包:OpenCode

课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

用带空格的地点、严重级别和多词摘要调用命令,观察模型请求中三行标签和内容。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习