蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

核对角色配置及允许和拒绝委托的实际结果

PYTHONWindows、OpenCode V1.19.5、Python 3.12、Git 与本机测试模型。agent_role_probe.py
agent_role_probe.py121 行
"""Inspect native V1 loading and model selection for JSON and Markdown agents."""

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

from cli_sessions import profile,server
from first_use import request


class CaptureModel(BaseHTTPRequestHandler):
    def log_message(self, *_):
        pass

    def do_POST(self):
        if self.path!="/v1/chat/completions":
            self.send_error(404)
            return
        body=json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        self.server.incoming.append(dict(model=body["model"],messages=body["messages"],temperature=body.get("temperature"),top_p=body.get("top_p")))
        texts=[m.get("content","") for m in body["messages"] if m["role"]=="user"]
        latest=body["messages"][-1]
        chosen={"Delegate the inventory audit":"warehouse-review","Delegate the blocked audit":"warehouse-blocked"}
        if texts and isinstance(texts[-1],str) and texts[-1] in chosen and latest["role"]=="user":
            call=dict(description="Inspect inventory totals",subagent_type=chosen[texts[-1]],
                      prompt="Read the role context and report the audit")
            delta={"tool_calls":[dict(index=0,id="warehouse_delegate",type="function",
                          function=dict(name="task",arguments=json.dumps(call)))]}
            why="tool_calls"
        else:
            delta,why={"content":"Fixture role observed."},"stop"
        self.send_response(200)
        self.send_header("Content-Type","text/event-stream")
        self.end_headers()
        meta=dict(id="roles-fixture",object="chat.completion.chunk",created=1700000000,model=body["model"])
        for data,stop in (({"role":"assistant"},None),(delta,None),({},why)):
            chunk=dict(meta,choices=[dict(index=0,delta=data,finish_reason=stop)])
            self.wfile.write(("data: "+json.dumps(chunk)+"\n\n").encode())
        self.wfile.write(b"data: [DONE]\n\n")


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


def check(executable):
    with TemporaryDirectory(prefix="mbsky-opencode-role-") as tmp, ThreadingHTTPServer(("127.0.0.1",0),CaptureModel) as model:
        base=Path(tmp);project=base/"warehouse";project.mkdir()
        env=profile(base)
        env.update(HOME=str(base),USERPROFILE=str(base),GIT_CONFIG_GLOBAL=os.devnull,
                   GIT_CONFIG_NOSYSTEM="1",OPENCODE_DISABLE_LSP_DOWNLOAD="1",OPENCODE_DISABLE_CLAUDE_CODE="1")
        subprocess.run(["git","init","-q"],cwd=project,env=env,check=True,timeout=8)
        put(project/"prompts/warehouse-plan.txt","fixture-role-root: preserve reserve counts.")
        put(project/".opencode/agents/warehouse-review.md",
            "---\ndescription: Reports nested warehouse audit details\nmode: subagent\n"
            "model: openai/warehouse-review-model\nhidden: true\npermission:\n  edit: deny\n---\n"
            "fixture-role-child: report reorder thresholds.\n")
        put(project/".opencode/agents/warehouse-blocked.md",
            "---\ndescription: This role should be blocked by the parent\nmode: subagent\n---\n"
            "fixture-role-blocked: blocked role marker.\n")
        capabilities=dict(tool_call=True,temperature=True,limit=dict(context=32768,output=4096))
        models={name:dict(name=name,**capabilities) for name in ("warehouse-plan-model","warehouse-review-model")}
        config=dict(model="openai/warehouse-plan-model",small_model="openai/warehouse-plan-model",share="disabled",
                    enabled_providers=["openai"],permission={"*":"deny"},
                    agent={"warehouse-plan":dict(description="Plans stock updates",mode="primary",
                               model="openai/warehouse-plan-model",prompt="{file:./prompts/warehouse-plan.txt}",
                               temperature=0.2,top_p=0.65,
                               permission={"task":{"*":"deny","warehouse-review":"allow"}}),
                           "warehouse-disabled":dict(description="Disabled role",disable=True)},
                    provider={"openai":dict(npm="@ai-sdk/openai-compatible",name="Roles fixture",models=models,
                           options=dict(baseURL=f"http://127.0.0.1:{model.server_port}/v1",apiKey="fixture"))})
        put(project/"opencode.json",json.dumps(config))
        model.incoming=[]
        worker=Thread(target=model.serve_forever,daemon=True);worker.start()
        try:
            with server(executable,project,env) as origin:
                health=request(origin,"/global/health")
                agents={a["name"]:a for a in request(origin,"/agent")}
                primary=agents["warehouse-plan"]
                secondary=agents["warehouse-review"]
                parent=request(origin,"/session",{"title":"Warehouse review"})["id"]
                request(origin,f"/session/{parent}/message",dict(agent="warehouse-plan",
                              parts=[dict(type="text",text="Delegate the inventory audit")]))
                kids=request(origin,f"/session/{parent}/children")
                parent_parts=request(origin,f"/session/{parent}/message")
                blocked=request(origin,"/session",{"title":"Blocked warehouse role"})["id"]
                request(origin,f"/session/{blocked}/message",dict(agent="warehouse-plan",
                            parts=[dict(type="text",text="Delegate the blocked audit")]))
                blocked_kids=request(origin,f"/session/{blocked}/children")
                blocked_parts=request(origin,f"/session/{blocked}/message")
                denied=[p["state"]["status"] for m in blocked_parts for p in m["parts"]
                           if p.get("type")=="tool" and p.get("tool")=="task"]
                parent_request=next(x for x in model.incoming if "fixture-role-root" in json.dumps(x["messages"]))
                tool_states=[p["state"]["status"] for m in parent_parts for p in m["parts"]
                             if p.get("type")=="tool" and p.get("tool")=="task"]
                def visibility(marker,model_name):
                    return any(marker in json.dumps(x["messages"]) and x["model"]==model_name for x in model.incoming)
                actual=dict(primary_mode=primary["mode"],secondary_mode=secondary["mode"],
                            secondary_hidden=secondary.get("hidden"),parent_prompt_and_model=visibility("fixture-role-root","warehouse-plan-model"),
                            child_prompt_and_model=visibility("fixture-role-child","warehouse-review-model"),
                            child_count=len(kids),tool_states=tool_states,
                            blocked_child_count=len(blocked_kids),blocked_tool_states=denied,
                            disabled_visible="warehouse-disabled" in agents,
                            parent_sampling=[parent_request["temperature"],parent_request["top_p"]])
        finally:
            model.shutdown()
            worker.join(timeout=5)
    with executable.open("rb") as f:digest=file_digest(f,"sha256").hexdigest()
    return dict(version=health["version"],binary_sha256=digest,actual=actual)


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、Git 与本机测试模型。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、OpenCode V1.19.5、Python 3.12、Git 与本机测试模型。

入口文件:projects/opencode-agent-roles/agent_role_probe.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 agent_role_probe.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、OpenCode V1.19.5、Python 3.12、Git 与本机测试模型。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:OpenCode

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

下载课程关联工程包:OpenCode

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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