HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
feat: Qwen Code backend — verified binary-first, normalizer is the claude passthrough
richard-epsilla60e664fae851
diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex edba11f1..4bbb8b8f 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -172,7 +172,7 @@ export HOSTNAME=0.0.0.0TOOLS="$DATA_DIR/agent-tools"export PATH="$TOOLS/bin:$PATH"export NODE_PATH="$TOOLS/lib/node_modules"-export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode}"+export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,qwen}"wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }# The executable IS the definition of "installed" — an installer that exits 0 without producing@@ -186,6 +186,7 @@ backend_bin() {pi) echo "$TOOLS/bin/pi" ;;dsh) echo "$TOOLS/dsh-venv/bin/dsh-ready" ;;opencode) echo "$TOOLS/bin/opencode" ;;+ qwen) echo "$TOOLS/bin/qwen" ;;esac}@@ -248,6 +249,11 @@ install_backends() {try_install "opencode" install_opencode || truefi+ if wanted qwen && [ ! -x "$(backend_bin qwen)" ]; then+ echo "[harnessrouter] installing Qwen Code (Apache-2.0)…"+ try_install "Qwen Code" npm install -g --prefix "$TOOLS" --no-audit --no-fund @qwen-code/qwen-code || true+ fi+if wanted codex && [ ! -x "$(backend_bin codex)" ]; thenecho "[harnessrouter] installing Codex (Apache-2.0)…"try_install "Codex" npm install -g --prefix "$TOOLS" --no-audit --no-fund @openai/codex || truediff --git a/gateway/app.py b/gateway/app.pyindex 19b43de7..20368aa5 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -948,6 +948,11 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {("openrouter", "opencode"): "openai-api",("tokenrouter", "opencode"): "tokenrouter", ("vercel", "opencode"): "tokenrouter",("llmtr", "opencode"): "tokenrouter",+ ("anthropic", "qwen"): "anthropic", ("openai", "qwen"): "openai",+ ("azure-foundry", "qwen"): "azure",+ ("openrouter", "qwen"): "openai-api",+ ("tokenrouter", "qwen"): "tokenrouter", ("vercel", "qwen"): "tokenrouter",+ ("llmtr", "qwen"): "tokenrouter",# custom: user-supplied endpoint + model + key. Maps to runner providers that can actually# drive a bring-your-own OpenAI/Anthropic endpoint — NOT codex, whose current releases speak# only the OpenAI Responses API and so cannot reach a custom chat/completions endpoint.@@ -4605,6 +4610,17 @@ _MODEL_CATALOG: dict[str, dict] = {"gemini-3.6-flash", "deepseek-v4-pro", "deepseek-v4-flash", "kimi-k3","kimi-k2.7-code", "qwen3.7-max", "qwen3.8-max","mistral-medium-3.5", "step-3.7-flash"]},+ # qwen-code speaks OPENAI_BASE_URL/OPENAI_API_KEY at the same relays; serving paths are pi's.+ # Unprobed per-model on this backend (one live turn each of qwen3.7-max and gpt-5.4 verified,+ # 2026-08-25) — substitution-check before leaning on any single row.+ "qwen": {"default": "qwen3.7-max",+ "models": ["qwen3.7-max", "qwen3.8-max",+ "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5",+ "gpt-5.4", "gpt-5.4-mini", "gpt-5.2", "gpt-5.3-codex",+ "claude-opus-5", "claude-fable-5", "claude-opus-4.8", "claude-sonnet-5",+ "claude-opus-4.7", "claude-sonnet-4.6", "claude-haiku-4.5",+ "gemini-3.6-flash", "deepseek-v4-pro", "deepseek-v4-flash", "kimi-k3",+ "kimi-k2.7-code", "mistral-medium-3.5", "step-3.7-flash"]},"pi": {"default": "gpt-5.4","models": ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5","gpt-5.4", "gpt-5.4-mini", "gpt-5.2", "gpt-5.3-codex",@@ -11252,6 +11268,18 @@ _BASE_CATALOG: dict[str, dict] = {# as claude's permissions.deny and pi's -xt, not the instruction-only tier."tool_enforcement": "hard",},+ "qwen": {+ "label": "Qwen Code", "backend": "qwen", "status": "ready",+ "system_prompt": ("You are Qwen Code, an autonomous coding agent. You work on a real git "+ "workspace with shell and file access, reading and editing files and "+ "running commands to complete the task end to end."),+ # From the live init event's tool list (0.22.1). No per-tool kill switch on the CLI, so+ # disabling is an instruction to the model — same tier as codex/hermes/dsh.+ "tools": [("read_file", "File Read"), ("write_file", "File Write"), ("edit", "Edit"),+ ("grep_search", "Search"), ("glob", "Glob"), ("web_fetch", "Web Fetch"),+ ("todo_write", "Todo"), ("skill", "Skill"), ("agent", "Subagent")],+ "tool_enforcement": "instruction",+ },}# Bases this server can execute. Derived from the catalog above so the two cannot disagree —diff --git a/runner/server.py b/runner/server.pyindex 2c884d12..6e0d3cc2 100644--- a/runner/server.py+++ b/runner/server.py@@ -359,6 +359,7 @@ HERMES_DEFAULT_MODEL = os.environ.get("HERMES_DEFAULT_MODEL", "gpt-5.4")# Pi default — pi is multi-family the same way hermes is; same reasoning, same default.PI_DEFAULT_MODEL = os.environ.get("PI_DEFAULT_MODEL", "gpt-5.4")OPENCODE_DEFAULT_MODEL = os.environ.get("OPENCODE_DEFAULT_MODEL", "gpt-5.4")+QWEN_DEFAULT_MODEL = os.environ.get("QWEN_DEFAULT_MODEL", "qwen3.7-max")DSH_DEFAULT_MODEL = os.environ.get("DSH_DEFAULT_MODEL", "deepseek-v4-pro")CODEX_REASONING_EFFORT = os.environ.get("CODEX_REASONING_EFFORT", "medium")CODEX_CONTEXT_WINDOW = os.environ.get("CODEX_CONTEXT_WINDOW", "400000")@@ -643,6 +644,10 @@ def _write_skills(cwd: str, skills: list[dict], backend: str = "claude") -> list# $HERMES_HOME/skills/<name>/SKILL.md: the <available_skills> index hermes builds itselfrootrels = [".harness/home/.hermes/skills"]entryroot = ".harness/home/.hermes/skills"+ elif backend == "qwen":+ # ~/.qwen/skills under the redirected HOME — the dir the shipped 0.22.1 creates itself.+ rootrels = [".harness/home/.qwen/skills"]+ entryroot = ".harness/home/.qwen/skills"elif backend == "opencode":# opencode's `skills` config key takes ARBITRARY paths ("Additional paths or URLs to# discover skills from"), so there is no per-CLI home directory to guess here — we write@@ -766,6 +771,8 @@ def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:Getting this wrong is silent: the file is written either way, and a backend that does not readthe name we chose simply never sees the harness's instructions."""+ if backend == "qwen":+ return pathlib.Path(cwd) / "QWEN.md" # qwen-code's own context file (bundle default)return pathlib.Path(cwd) / ("AGENTS.md" if backend in ("codex", "hermes", "pi", "dsh", "opencode") else "CLAUDE.md")@@ -2356,6 +2363,66 @@ def _hermes_prepare_env(provider: str | None, auth: Auth, cwd: str, env: dict,return list(mcp)+QWEN_PROVIDERS = {"anthropic", "openai", "azure", "openai-api", "tokenrouter"}+++def _qwen_settings(home: pathlib.Path, mcp_servers: list[dict] | None) -> None:+ """~/.qwen/settings.json under the redirected HOME. Only mcpServers is written (gemini-cli+ schema: command/args/env for stdio, url/httpUrl for remote); auth stays in the ENVIRONMENT+ (OPENAI_API_KEY / OPENAI_BASE_URL + --auth-type openai), so unlike pi and opencode no+ credential ever lands on disk for this backend."""+ qdir = home / ".qwen"+ qdir.mkdir(parents=True, exist_ok=True)+ servers: dict = {}+ for i, sv in enumerate(mcp_servers or []):+ if not isinstance(sv, dict):+ continue+ name = _skill_dir_name(sv.get("name") or sv.get("id") or f"server{i}")+ url = (sv.get("url") or "").strip()+ if url:+ entry: dict = {"httpUrl": url}+ hdrs = sv.get("headers")+ if isinstance(hdrs, dict) and hdrs:+ entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ elif sv.get("command"):+ cmd = sv["command"]+ argv = cmd if isinstance(cmd, list) else [str(cmd)]+ entry = {"command": argv[0], "args": [str(x) for x in argv[1:]] + [str(x) for x in (sv.get("args") or [])]}+ envv = sv.get("env")+ if isinstance(envv, dict) and envv:+ entry["env"] = {str(k): str(v) for k, v in envv.items()}+ else:+ continue+ servers[name] = entry+ cfg: dict = {}+ if servers:+ cfg["mcpServers"] = servers+ (qdir / "settings.json").write_text(json.dumps(cfg, indent=2))+++def _build_qwen(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,+ resume_session_id: str | None = None, mcp_servers: list[dict] | None = None) -> list[str]:+ pr = provider or "openai-api"+ if pr not in QWEN_PROVIDERS:+ raise HTTPException(400, f"unknown qwen provider '{pr}' (one of {sorted(QWEN_PROVIDERS)})")+ if not auth.base_url:+ raise HTTPException(400, "qwen needs a base_url (none configured)")+ home = pathlib.Path(cwd) / ".harness" / "home"+ home.mkdir(parents=True, exist_ok=True)+ env["HOME"] = str(home) # sessions/skills/settings live INSIDE the workspace+ env["OPENAI_API_KEY"] = auth.api_key or ""+ env["OPENAI_BASE_URL"] = auth.base_url+ _qwen_settings(home, mcp_servers)+ cmd = ["qwen", "-p", prompt, "-o", "stream-json", "-m", model,+ # Resume REQUIRES an explicit auth type in non-interactive mode (verified on 0.22.1:+ # without it every -r run dies "No auth type is selected"); fresh runs take it too for+ # one deterministic path.+ "--auth-type", "openai"]+ if resume_session_id:+ cmd += ["-r", resume_session_id]+ return cmd++def _opencode_eof(state: dict, rc: int) -> list[dict]:"""Synthesize the turn's result at end of stream.@@ -2635,6 +2702,11 @@ BACKENDS = {"normalize": _dsh_to_claude},"opencode": {"providers": sorted(OPENCODE_PROVIDERS), "default_model": OPENCODE_DEFAULT_MODEL,"normalize": _opencode_to_claude},+ # qwen-code emits claude's stream-json natively (verified against the shipped 0.22.1:+ # system/init with session_id, assistant/message, result/subtype/usage in claude's field+ # names) — so its normalizer IS the claude passthrough.+ "qwen": {"providers": sorted(QWEN_PROVIDERS), "default_model": QWEN_DEFAULT_MODEL,+ "normalize": _claude_passthrough},}@@ -3662,6 +3734,10 @@ def turn(req: TurnReq, identifier: str = "") -> dict:cmd = _build_pi(req.provider, auth, model, req.prompt, cwd, env,resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,tools_disabled=req.tools_disabled, vision=bool(req.vision))+ elif backend == "qwen":+ model = model or QWEN_DEFAULT_MODEL+ cmd = _build_qwen(req.provider, auth, model, req.prompt, cwd, env,+ resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers)elif backend == "opencode":model = model or OPENCODE_DEFAULT_MODEL# _write_skills already ran for this backend, so the directory it produced is on disk anddiff --git a/runner/tests/test_qwen_build.py b/runner/tests/test_qwen_build.pynew file mode 100644index 00000000..c5c493fb--- /dev/null+++ b/runner/tests/test_qwen_build.py@@ -0,0 +1,71 @@+"""The qwen backend, against facts measured on the shipped 0.22.1 binary."""+import json+import pathlib+import sys+import tempfile++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+from server import Auth, _agent_doc_path, _build_qwen, _claude_passthrough, BACKENDS # noqa: E402+++def _argv(**kw):+ d = tempfile.mkdtemp()+ env: dict = {}+ cmd = _build_qwen("openai-api", Auth(api_key="sk-t", base_url="https://relay.example/v1"),+ "qwen3.7-max", "do it", d, env, **kw)+ return cmd, d, env+++def test_argv_is_headless_stream_json_with_explicit_auth_type():+ """--auth-type is load bearing: without it every -r run on 0.22.1 dies+ 'No auth type is selected' — verified live, both directions."""+ cmd, _, _ = _argv()+ assert cmd[:3] == ["qwen", "-p", "do it"]+ assert ["-o", "stream-json"] == cmd[3:5]+ assert "--auth-type" in cmd and "openai" in cmd+++def test_resume_uses_dash_r():+ cmd, _, _ = _argv(resume_session_id="8e039a38-f91f")+ assert cmd[-2:] == ["-r", "8e039a38-f91f"]+++def test_auth_is_environment_only_never_disk():+ """qwen is the one backend with NO credential at rest: env OPENAI_API_KEY/BASE_URL only.+ settings.json must not carry the key."""+ _, d, env = _argv()+ assert env["OPENAI_API_KEY"] == "sk-t"+ assert env["OPENAI_BASE_URL"] == "https://relay.example/v1"+ st = pathlib.Path(d, ".harness", "home", ".qwen", "settings.json").read_text()+ assert "sk-t" not in st+++def test_home_is_redirected_into_the_workspace():+ """Sessions live at ~/.qwen/projects/<cwd>/chats; HOME inside the workspace makes resume+ travel with the checkpoint."""+ _, d, env = _argv()+ assert env["HOME"] == f"{d}/.harness/home"+++def test_mcp_settings_use_the_gemini_schema():+ d = tempfile.mkdtemp()+ env: dict = {}+ _build_qwen("openai-api", Auth(api_key="k", base_url="https://relay.example/v1"),+ "qwen3.7-max", "hi", d, env,+ mcp_servers=[{"name": "docs", "url": "https://mcp.example/sse",+ "headers": {"Authorization": "Bearer t"}},+ {"name": "fs", "command": "npx", "args": ["-y", "server-fs"]}])+ cfg = json.loads(pathlib.Path(d, ".harness", "home", ".qwen", "settings.json").read_text())+ assert cfg["mcpServers"]["docs"] == {"httpUrl": "https://mcp.example/sse",+ "headers": {"Authorization": "Bearer t"}}+ assert cfg["mcpServers"]["fs"] == {"command": "npx", "args": ["-y", "server-fs"]}+++def test_normalizer_is_the_claude_passthrough():+ """qwen emits claude's stream-json natively (system/init, assistant, result with claude field+ names — captured from a live 0.22.1 turn), so the registry must wire the passthrough."""+ assert BACKENDS["qwen"]["normalize"] is _claude_passthrough+++def test_instruction_file_is_qwen_md():+ assert _agent_doc_path("/ws", "qwen").name == "QWEN.md"diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.tsindex a8293de7..8e1ee856 100644--- a/ui/src/lib/harness.ts+++ b/ui/src/lib/harness.ts@@ -20,7 +20,7 @@ export interface OobHarness {defaultModel?: string; // the backend default, NOT necessarily models[0]moreModels?: number; // "+N" pillstatus: 'ready' | 'soon';- backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | null; // gateway backend; null = coming soon+ backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'qwen' | null; // gateway backend; null = coming soonsystemPrompt: string; // the harness's built-in system prompt (shown read-only)tools: string[]; // built-in tools (read-only)skills: string[]; // built-in skills (read-only)@@ -82,6 +82,11 @@ export const OOB: OobHarness[] = [models: ['gpt-5.4', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4-mini', 'gpt-5.2', 'gpt-5.3-codex', 'claude-opus-5', 'claude-fable-5', 'claude-opus-4.8', 'claude-sonnet-5', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5', 'gemini-3.6-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.7-max', 'qwen3.8-max', 'mistral-medium-3.5', 'step-3.7-flash'], defaultModel: 'gpt-5.4', moreModels: 0,systemPrompt: 'You are OpenCode, an autonomous coding agent. You work on a real git workspace with shell and file access, reading and editing files and running commands to complete the task end to end.',tools: [], skills: [] },+ { id: 'qwen', name: 'Qwen Code', version: 'v0.22.1', backend: 'qwen', status: 'ready',+ // Same relay reach as pi/opencode; qwen family first since it is the backend's home family.+ models: ['qwen3.7-max', 'qwen3.8-max', 'gpt-5.4', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4-mini', 'gpt-5.2', 'gpt-5.3-codex', 'claude-opus-5', 'claude-fable-5', 'claude-opus-4.8', 'claude-sonnet-5', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5', 'gemini-3.6-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'mistral-medium-3.5', 'step-3.7-flash'], defaultModel: 'qwen3.7-max', moreModels: 0,+ systemPrompt: 'You are Qwen Code, an autonomous coding agent. You work on a real git workspace with shell and file access, reading and editing files and running commands to complete the task end to end.',+ tools: [], skills: [] },];export const oobById = (id: string) => OOB.find((o) => o.id === id) || null;