"""Run a GitLab-style local task with an isolated OpenCode V1 client."""
from hashlib import file_digest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import re
import subprocess
import sys
from tempfile import TemporaryDirectory
from threading import Thread
class LocalModel(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_POST(self):
if self.path != "/v1/chat/completions":
self.send_error(404)
return
request = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
text = [str(item.get("content","")) for item in request["messages"] if item["role"] == "user"][-1]
valid_auth = self.headers.get("Authorization") == f"Bearer {self.server.fixture_token}"
self.server.received.append(dict(model=request["model"], prompt=text, expected_auth_header=valid_auth))
if not valid_auth:
self.send_error(401)
return
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
meta = dict(id="gitlab-job", object="chat.completion.chunk", created=1700000000, model=request["model"])
for delta, stop in (({"role":"assistant"},None),({"content":"Inventory report prepared."},None),({},"stop")):
item = dict(meta, choices=[dict(index=0,delta=delta,finish_reason=stop)])
self.wfile.write(("data: "+json.dumps(item)+"\n\n").encode())
self.wfile.write(b"data: [DONE]\n\n")
def select_task(event, handle="inventory-agent"):
if event["kind"] == "note":
if event["actor_role"] not in {"developer", "maintainer"}:
return None
pattern = re.escape("@"+handle)
match = re.fullmatch(pattern+r"\s+(\S[\s\S]*)", event["body"])
if not match:
return None
target = event["target"]
if target not in {"issue","merge_request"}:
return None
return dict(config_dir="review", message=f"{target} #{event['iid']}\n{match[1]}")
if event["kind"] == "schedule":
return dict(config_dir="reports", message="List inventory TODOs for the weekly report.")
if event["kind"] == "merge_request_event" and event["source_project_id"] == event["target_project_id"]:
return dict(config_dir="review", message=f"Check merge request #{event['iid']} for empty-order errors.")
return None
def read_auth_file(variable_value):
path = Path(variable_value)
if not path.is_file():
raise ValueError("Expected a file-type CI variable")
data = json.loads(path.read_text(encoding="utf-8"))
return data["openai"]["key"]
def profile(base, config):
keys = ("SystemRoot","WINDIR","PATH","TEMP","TMP","COMSPEC")
env = {key:os.environ[key] for key in keys if key in os.environ}
env.update({f"XDG_{name}_HOME":str(base/name.lower()) for name in ("CONFIG","DATA","STATE","CACHE")})
env.update(OPENCODE_CONFIG_DIR=str(config),HOME=str(base),USERPROFILE=str(base),
OPENCODE_DISABLE_DEFAULT_PLUGINS="1",OPENCODE_DISABLE_AUTOUPDATE="1",
OPENCODE_DISABLE_MODELS_FETCH="1",OPENCODE_DISABLE_LSP_DOWNLOAD="1",
HTTP_PROXY="http://127.0.0.1:1",HTTPS_PROXY="http://127.0.0.1:1",NO_PROXY="127.0.0.1,localhost")
return env
def run_task(executable, workspace, case_root, task, model_name, auth_path, local):
config = case_root/task["config_dir"]
config.mkdir(parents=True)
# The mock credential is read through the same file-path shape as a GitLab File variable.
config_data = {
"model":f"openai/{model_name}","small_model":f"openai/{model_name}","share":"disabled",
"enabled_providers":["openai"],"permission":{"*":"deny"},
"provider":{"openai":{"npm":"@ai-sdk/openai-compatible","name":"Inventory fixture",
"options":{"baseURL":f"http://127.0.0.1:{local.server_port}/v1","apiKey":read_auth_file(auth_path)},
"models":{model_name:{"name":model_name,"tool_call":True,"limit":{"context":32768,"output":4096}}}}},
}
(config/"opencode.json").write_text(json.dumps(config_data),encoding="utf-8")
result = subprocess.run([str(executable),"run","--format","json","--",task["message"]],
cwd=workspace,env=profile(case_root,config),capture_output=True,encoding="utf-8",timeout=25,check=True)
events = [json.loads(line) for line in result.stdout.splitlines() if line.startswith("{")]
assert not any(row["type"]=="error" for row in events),result.stdout
return [row["part"]["text"] for row in events if row["type"]=="text"]
def check(executable):
cases = []
def record(name, inputs, expected, actual, operation):
assert expected == actual, (name, actual)
cases.append(dict(name=name, inputs=inputs, expected=expected, actual=actual, operation=operation))
note = dict(kind="note",actor_role="developer",target="issue",iid=19,body="@inventory-agent explain the stock mismatch")
fix = {**note,"body":"@inventory-agent propose a fix for duplicate reservation"}
review = {**note,"target":"merge_request","iid":4,"body":"@inventory-agent check empty orders"}
scheduled = dict(kind="schedule")
same = dict(kind="merge_request_event",source_project_id=18,target_project_id=18,iid=4)
fork = {**same,"source_project_id":27}
outsider = {**note,"actor_role":"guest"}
custom = {**note,"body":"@inventory-audit check packing limits"}
record("issue_explain",note,dict(config_dir="review",message="issue #19\nexplain the stock mismatch"),select_task(note),
"将模拟的议题评论按目标和账号规则分流")
record("issue_fix",fix,dict(config_dir="review",message="issue #19\npropose a fix for duplicate reservation"),select_task(fix),
"分流修复请求并保留显式任务文本")
record("mr_review",review,dict(config_dir="review",message="merge_request #4\ncheck empty orders"),select_task(review),
"保留合并请求的目标编号与审查提示")
record("external_guards",[outsider,fork],[None,None],[select_task(outsider),select_task(fork)],
"检查非受信评论与外部分叉不会进入演练作业")
record("custom_mention",custom,[None,"issue #19\ncheck packing limits"],
[select_task(custom),select_task(custom,"inventory-audit")["message"]],"分别使用默认账号名与已配置账号名")
record("mr_pipeline",same,dict(config_dir="review",message="Check merge request #4 for empty-order errors."),
select_task(same),"同项目 MR 进入预设审查任务")
record("scheduled_report",scheduled,dict(config_dir="reports",message="List inventory TODOs for the weekly report."),
select_task(scheduled),"定时事件配置固定报告任务")
with TemporaryDirectory(prefix="mbsky-gitlab-ci-") as tmp, ThreadingHTTPServer(("127.0.0.1", 0), LocalModel) as local:
base=Path(tmp)
work=base/"work"
work.mkdir()
target=work/"inventory.txt"
target.write_bytes(b"package units: 8\n")
fake_token="inventory-test-fixture"
auth=base/"file-variable.json"
auth.write_text(json.dumps({"openai":{"type":"api","key":fake_token}}),encoding="utf-8")
record("file_variable",["临时 File 变量","缺失的文件路径"],[True,True],
[read_auth_file(str(auth))==fake_token,rejects_missing(str(base/"missing.json"))],
"从 File 变量指向的实际文件读取测试 JSON 并校验遗漏输入")
local.fixture_token = fake_token
local.received = []
thread=Thread(target=local.serve_forever,daemon=True)
thread.start()
try:
outputs=[]
for label,event,model in [("review",review,"inventory-review"),("schedule",scheduled,"inventory-report")]:
task=select_task(event)
before=len(local.received)
texts=run_task(executable,work,base/label,task,model,str(auth),local)
requests=local.received[before:]
assert requests and all(item["model"] == model and item["expected_auth_header"] for item in requests)
request=next(item for item in requests if task["message"] in item["prompt"])
outputs.append(dict(model=request["model"], has_prompt=task["message"] in request["prompt"],
valid_fixture_auth=request["expected_auth_header"], native_events=texts))
expected=[dict(model=m,has_prompt=True,valid_fixture_auth=True,native_events=["Inventory report prepared."])
for m in ("inventory-review","inventory-report")]
record("native_job_config",["review","reports","同一本机模拟服务"],expected,outputs,
"用两套配置执行原生 OpenCode CLI 并核对实际模型、输入、鉴权与事件")
record("read_only_workspace",["inventory.txt","本地审查和报告"],b"package units: 8\n".decode(),
target.read_text(encoding="utf8"),"核对两次运行后的实际文件内容")
finally:
local.shutdown()
thread.join(timeout=5)
assert len(local.received)>=2
with executable.open("rb") as file:
binary_sha256=file_digest(file,"sha256").hexdigest()
return dict(cases=cases,python_version=sys.version.split()[0],binary_sha256=binary_sha256)
def rejects_missing(path):
try:
read_auth_file(path)
except ValueError:
return True
return False
if __name__ == "__main__":
print(json.dumps(check(Path(sys.argv[1]).resolve()),ensure_ascii=False,indent=2))
本例需在 Windows、OpenCode V1.19.5、Python 3.12 与回环模型测试服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、OpenCode V1.19.5、Python 3.12 与回环模型测试服务。
入口文件:projects/opencode-gitlab/gitlab_job.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
gitlab_job.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、OpenCode V1.19.5、Python 3.12 与回环模型测试服务。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a245.zip