"""Exercise first-use workflows in a temporary OpenCode V1 Git project."""
from contextlib import contextmanager
from hashlib import file_digest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
from subprocess import PIPE, Popen, run
import sys
from tempfile import TemporaryDirectory
from threading import Thread
from time import monotonic, sleep
from urllib.parse import quote
from urllib.request import urlopen, Request
PROMPTS = {
"read": "Read src/stock.py before answering. What invariant does allocate maintain?",
"plan": "Review the request for a short route code. Do not edit the source.",
"build": "Add a route label to the approved source file.",
}
BASE = """def route_name(zone: str) -> str:
return zone.strip().lower()
def allocate(stock: int, requested: int) -> int:
if stock < 0 or requested < 0:
raise ValueError("nonnegative counts required")
return min(stock, requested)
"""
CHANGE = BASE + "\ndef route_label(zone: str) -> str:\n return 'route:' + route_name(zone)\n"
INSTRUCTIONS = "# Inventory exercise\n\nRun the focused stock test before editing the route helper.\n"
SCRIPT_REPLIES = {"read":"Allocation never exceeds stock.",
"plan":"Checked plan status.","build":"Approved source was updated.","init":"Project instructions created."}
class Model(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
messages = body["messages"]
if self.path != "/v1/chat/completions":
self.send_error(404)
return
users = [str(m.get("content","")) for m in messages if m["role"]=="user"]
last = users[-1] if users else ""
task = next((key for key,value in PROMPTS.items() if value in last), "init" if "AGENTS.md" in last else None)
available = [x["function"]["name"] for x in body.get("tools",[]) if x["type"]=="function"]
last_tool = messages[-1].get("content") if messages[-1]["role"]=="tool" else None
self.server.observations.append(dict(task=task,offered_tools=available,tool_result=last_tool,
request_path=self.path))
root = self.server.root
if task is None or not available:
delta, finish = {"content":"Inventory training session"}, "stop"
elif last_tool is not None:
delta, finish = {"content":SCRIPT_REPLIES[task]}, "stop"
else:
if task == "read":
tool = "read"
args = {"filePath":str(root/"src/stock.py")}
else:
tool = "write"
args = {"filePath":str(root/("AGENTS.md" if task=="init" else "src/stock.py")),
"content":INSTRUCTIONS if task=="init" else CHANGE}
delta = {"tool_calls":[dict(index=0,id="call_"+task,type="function",
function=dict(name=tool,arguments=json.dumps(args)))]}
finish = "tool_calls"
self.send_response(200)
self.send_header("Content-Type","text/event-stream")
self.end_headers()
meta = dict(id="stock-first-use",object="chat.completion.chunk",created=1700000000,model=body["model"])
for payload, why in (({"role":"assistant"},None),(delta,None),({},finish)):
chunk = dict(meta,choices=[dict(index=0,delta=payload,finish_reason=why)])
self.wfile.write(("data: "+json.dumps(chunk)+"\n\n").encode())
self.wfile.write(b"data: [DONE]\n\n")
def request(origin, path, data=None):
url = origin + path
req = Request(url, data=json.dumps(data).encode() if data is not None else None,
headers={"Content-Type":"application/json"})
with urlopen(req,timeout=18) as reply:
return json.load(reply)
@contextmanager
def server(exe, root, env):
proc = Popen([str(exe),"serve","--hostname","127.0.0.1","--port","0","--pure"],cwd=root,env=env,
stdout=PIPE,stderr=PIPE)
lines = []
def read_output():
for row in proc.stdout:
lines.append(row.decode("utf-8","replace").strip())
reader = Thread(target=read_output,daemon=True)
reader.start()
try:
deadline = monotonic()+12
host = None
while not host and proc.poll() is None and monotonic()<deadline:
host = next((s.split("http://",1)[1] for s in lines if "http://127.0.0.1:" in s),None)
if not host:
sleep(0.04)
assert host,lines
yield "http://"+host
finally:
if proc.poll() is None:
proc.terminate()
proc.communicate(timeout=10)
reader.join(timeout=2)
def check(exe):
with TemporaryDirectory(prefix="mbsky-first-run-") as tmp, ThreadingHTTPServer(("127.0.0.1",0),Model) as mock:
base=Path(tmp)
root=base/"repo"
(root/"src").mkdir(parents=True)
source=root/"src/stock.py"
source.write_bytes(BASE.encode())
stock_test=root/"test_stock.py"
stock_test.write_text("from src.stock import allocate\nassert allocate(6,8)==6\nassert allocate(6,2)==2\n"
"try:\n allocate(6,-1)\nexcept ValueError:\n pass\nelse:\n raise AssertionError('negative')\n"
"print('stock-tests-ok')\n",encoding="utf-8")
env={k:os.environ[k] for k in ("SystemRoot","WINDIR","PATH","TEMP","TMP","COMSPEC") if k in os.environ}
env.update({f"XDG_{name}_HOME":str(base/name.lower()) for name in ("CONFIG","DATA","STATE","CACHE")})
env.update(OPENCODE_DISABLE_AUTOUPDATE="1",OPENCODE_DISABLE_DEFAULT_PLUGINS="1",OPENCODE_DISABLE_MODELS_FETCH="1",
NO_COLOR="1",HTTPS_PROXY="http://127.0.0.1:1",HTTP_PROXY="http://127.0.0.1:1",NO_PROXY="127.0.0.1,localhost")
def git(*args):
return run(["git",*args],cwd=root,env=env,capture_output=True,encoding="utf-8",timeout=12,check=True).stdout.strip()
git("init","-q")
git("add","src/stock.py","test_stock.py")
git("-c","user.name=MBsky","-c","user.email=fixture@example.invalid","commit","-qm","fixture baseline")
config={"model":"openai/stock-local","small_model":"openai/stock-local","snapshot":True,"share":"disabled",
"enabled_providers":["openai"],"permission":{"read":"allow","edit":"allow","bash":"deny","webfetch":"deny"},
"agent":{"plan":{"permission":{"edit":"deny","bash":"deny"}}},
"provider":{"openai":{"npm":"@ai-sdk/openai-compatible","name":"Stock replay",
"options":{"baseURL":f"http://127.0.0.1:{mock.server_port}/v1","apiKey":"training-token"},
"models":{"stock-local":{"name":"Stock Replay","tool_call":True,"limit":{"context":32768,"output":4096}}}}}}
(root/"opencode.json").write_text(json.dumps(config),encoding="utf-8")
mock.root=root
mock.observations=[]
worker=Thread(target=mock.serve_forever,daemon=True)
worker.start()
try:
with server(exe,root,env) as origin:
health=request(origin,"/global/health")
assert health["healthy"] and health["version"]=="1.19.5",health
commands=request(origin,"/command")
init=next(x for x in commands if x["name"]=="init")
paths=request(origin,"/find/file?query=stock.py")
assert "src/stock.py" in [x.replace("\\","/") for x in paths],paths
found=request(origin,"/file/content?path="+quote("src/stock.py"))
assert "def allocate" in json.dumps(found),found
refs={}
def new(title):
return "/session/"+request(origin,"/session",{"title":title})["id"]
def prompt(sid, task, agent):
body={"agent":agent,"model":{"providerID":"openai","modelID":"stock-local"},
"parts":[{"type":"text","text":PROMPTS[task]}]}
return request(origin,sid+"/message",body)
sid=new("Initialize instructions")
init_reply=request(origin,sid+"/command",{"agent":"build","model":"openai/stock-local",
"command":"init","arguments":""})
assert (root/"AGENTS.md").read_bytes()==INSTRUCTIONS.encode(),(init_reply,mock.observations[-3:])
refs["init"]=[init["name"],(root/"AGENTS.md").read_text(encoding="utf-8").splitlines()[0]]
read_result=prompt(new("Read project"),"read","plan")
assert any("Allocation never exceeds stock." in part.get("text","") for part in read_result["parts"]),read_result
assert any("def allocate" in str(r["tool_result"]) for r in mock.observations if r["task"]=="read")
refs["file_reference"]=[paths,"allocation invariant retrieved"]
plan_result=prompt(new("Plan change"),"plan","plan")
assert source.read_bytes()==BASE.encode()
plan_rows=[r for r in mock.observations if r["task"]=="plan"]
assert any("write" not in r["offered_tools"] or any(t in str(r["tool_result"]).lower()
for t in ("unavailable","denied","prevents")) for r in plan_rows),plan_rows
refs["plan"]=[True,False]
sid=new("Build change")
build_result=prompt(sid,"build","build")
assert source.read_bytes()==CHANGE.encode(),(build_result,mock.observations[-4:])
status=git("diff","--name-only")
assert status=="src/stock.py",status
test = run([sys.executable,"-B",str(stock_test)],cwd=root,env=env,capture_output=True,
encoding="utf-8",check=True,timeout=10).stdout.strip()
assert test=="stock-tests-ok",test
refs["build"]=[status,test]
messages=request(origin,sid+"/message")
last=next(row["info"]["id"] for row in messages if row["info"]["role"]=="user")
reverted=request(origin,sid+"/revert",{"messageID":last})
assert source.read_bytes()==BASE.encode(),reverted
restored=request(origin,sid+"/unrevert",{})
assert source.read_bytes()==CHANGE.encode(),restored
refs["snapshot"]=[True,True]
finally:
mock.shutdown()
worker.join()
with Path(exe).open("rb") as f:
digest=file_digest(f,"sha256").hexdigest()
return dict(opencode="1.19.5",binary_sha256=digest,observations=refs,tool_calls=mock.observations)
if __name__=="__main__":
import argparse
cli=argparse.ArgumentParser()
cli.add_argument("opencode",type=lambda x:Path(x).resolve())
print(json.dumps(check(cli.parse_args().opencode),ensure_ascii=False,indent=2))
本例需在 Windows x64、OpenCode 1.19.5、Git 和 CPython 3.12。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、OpenCode 1.19.5、Git 和 CPython 3.12。
入口文件:projects/opencode-first-use-vscode/first_use.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
first_use.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、OpenCode 1.19.5、Git 和 CPython 3.12。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a242.zip
课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip