"""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))
本例需在 OpenCode V1.19.5、Windows、Python 3.12、Git 与回环测试服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:OpenCode V1.19.5、Windows、Python 3.12、Git 与回环测试服务。
入口文件:projects/opencode-custom-commands/command_templates_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
command_templates_lab.py,或下载右侧课程工程包。 - 确认本地已准备 OpenCode V1.19.5、Windows、Python 3.12、Git 与回环测试服务。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a239.zip
课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip