Skip to content

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.

feat(runner): cline is the eighth backend, and every claim about it was measured first

richard-epsilla8dbda3c149a0
diff --git a/Dockerfile b/Dockerfile
index 57c2e123..2c27eeb8 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -17,7 +17,7 @@
# They land in the data volume, so the cost is paid once per volume rather than once per start.
# Choose backends at RUN time:
#
-# docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode ... # the default
+# docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,qwen,cline ... # the default
# docker run -e HR_BACKENDS=opencode ... # lean
#
# WITH_BROWSER is still a build arg because Chromium and its system libraries genuinely belong
diff --git a/README.md b/README.md
index f8ecd7da..3fa6445d 100644
--- a/README.md
+++ b/README.md
@@ -577,7 +577,7 @@ Backends are installed into your data volume rather than baked into the image, s
want is a run-time setting:
```bash
-docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode ... # the default
+docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,qwen,cline ... # the default
docker run -e HR_BACKENDS=opencode ... # lean
```
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 4bbb8b8f..1596891c 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -172,7 +172,7 @@ export HOSTNAME=0.0.0.0
TOOLS="$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,qwen}"
+export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,qwen,cline}"
wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }
# The executable IS the definition of "installed" — an installer that exits 0 without producing
@@ -187,6 +187,7 @@ backend_bin() {
dsh) echo "$TOOLS/dsh-venv/bin/dsh-ready" ;;
opencode) echo "$TOOLS/bin/opencode" ;;
qwen) echo "$TOOLS/bin/qwen" ;;
+ cline) echo "$TOOLS/bin/cline" ;;
esac
}
@@ -254,6 +255,14 @@ install_backends() {
try_install "Qwen Code" npm install -g --prefix "$TOOLS" --no-audit --no-fund @qwen-code/qwen-code || true
fi
+ if wanted cline && [ ! -x "$(backend_bin cline)" ]; then
+ echo "[harnessrouter] installing Cline (Apache-2.0)…"
+ # Pinned: 3.0.60 is the release every behavior in runner/server.py was verified against —
+ # the settings-file auth wiring, the one-word-prompt parse, and the broken --json --id resume
+ # this port deliberately does not use. A silent major bump would re-gamble all three.
+ try_install "Cline" npm install -g --prefix "$TOOLS" --no-audit --no-fund "cline@${HR_CLINE_VERSION:-3.0.60}" || true
+ fi
+
if wanted codex && [ ! -x "$(backend_bin codex)" ]; then
echo "[harnessrouter] installing Codex (Apache-2.0)…"
try_install "Codex" npm install -g --prefix "$TOOLS" --no-audit --no-fund @openai/codex || true
diff --git a/gateway/app.py b/gateway/app.py
index d12d76fb..fa443109 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -986,6 +986,14 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {
("openrouter", "qwen"): "openai-api",
("tokenrouter", "qwen"): "tokenrouter", ("vercel", "qwen"): "tokenrouter",
("llmtr", "qwen"): "tokenrouter",
+ # cline is a pure openai-compatible client through the runner's loopback relay (3.0.60,
+ # verified: the relay repairs shapes in flight, so every provider on an OpenAI-or-repairable
+ # surface drives it) — wired like qwen for the same reason.
+ ("anthropic", "cline"): "anthropic", ("openai", "cline"): "openai",
+ ("azure-foundry", "cline"): "azure",
+ ("openrouter", "cline"): "openai-api",
+ ("tokenrouter", "cline"): "tokenrouter", ("vercel", "cline"): "tokenrouter",
+ ("llmtr", "cline"): "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.
@@ -993,6 +1001,7 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {
("custom", "hermes"): "openai-api", ("custom", "opencode"): "tokenrouter",
("custom", "pi"): "tokenrouter", ("custom", "dsh"): "tokenrouter",
("custom", "qwen"): "openai-api",
+ ("custom", "cline"): "openai-api",
}
@@ -3678,7 +3687,7 @@ def _provider_backends(provider: str) -> list[str]:
_CUSTOM_FORMAT_BACKENDS = {
# qwen-code is a pure OPENAI_BASE_URL/OPENAI_API_KEY client (0.22.1, verified), so a custom
# OpenAI endpoint drives it directly; it speaks nothing else, so it stays off the anthropic set.
- "openai": {"hermes", "opencode", "pi", "dsh", "qwen"},
+ "openai": {"hermes", "opencode", "pi", "dsh", "qwen", "cline"},
"anthropic": {"claude", "opencode", "pi", "dsh"},
}
@@ -4712,6 +4721,10 @@ _MODEL_CATALOG: dict[str, dict] = {
"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"]},
+ # cline: deliberately short. A model earns its row here only after a real turn completed
+ # against the live provider through this backend, substitution-checked — these two were.
+ "cline": {"default": "gpt-5.4",
+ "models": ["gpt-5.4", "gpt-5.4-mini"]},
"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",
@@ -4830,6 +4843,8 @@ def _backend_of_harness(hv: dict | None) -> str:
return "claude"
if base == "hermes":
return "hermes"
+ if base == "cline":
+ return "cline"
if base == "pi":
return "pi"
if base in ("dsh", "deepseek-harness"):
@@ -11518,6 +11533,20 @@ _BASE_CATALOG: dict[str, dict] = {
("todo_write", "Todo"), ("skill", "Skill"), ("agent", "Subagent")],
"tool_enforcement": "instruction",
},
+ "cline": {
+ "label": "Cline", "backend": "cline", "status": "ready",
+ "system_prompt": ("You are Cline, 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 tools array a live 3.0.60 run sent its provider (captured at a stub upstream).
+ # The CLI exposes no per-tool kill switch headless, so disabling is an instruction to the
+ # model — the codex/hermes/dsh/qwen tier, not claude's hard deny.
+ "tools": [("run_commands", "Shell"), ("read_files", "File Read"),
+ ("editor", "Editor"), ("search_codebase", "Search"),
+ ("fetch_web_content", "Web Fetch"), ("ask_question", "Question"),
+ ("spawn_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.py
index 348b8450..28530847 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -360,6 +360,7 @@ HERMES_DEFAULT_MODEL = os.environ.get("HERMES_DEFAULT_MODEL", "gpt-5.4")
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")
+CLINE_DEFAULT_MODEL = os.environ.get("CLINE_DEFAULT_MODEL", "gpt-5.4")
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")
@@ -659,6 +660,13 @@ def _write_skills(cwd: str, skills: list[dict], backend: str = "claude") -> list
# dsh has no skill loader; the AGENTS.md block below is the only door
rootrels = [".harness/skills"]
entryroot = ".harness/skills"
+ # cline lands in the else on purpose, with the evidence written down so nobody "fixes" it:
+ # its own `skill list` attributes ~/.agents/skills to agent "Cline" and .claude/skills to
+ # "Claude Code", but a headless 3.0.60 run injects NEITHER into the system prompt — probed
+ # with skills installed at .claude/skills, ~/.agents/skills and ./.agents/skills against a
+ # stub upstream that dumps the system message: zero mentions, all three locations. So the
+ # loader that its tooling implies does not run headless, and the AGENTS.md advertisement is
+ # the one mechanism that verifiably reaches the model.
installed: list[dict] = []
for sk in skills or []:
name = _skill_dir_name((sk or {}).get("name") or (sk or {}).get("id") or "")
@@ -774,7 +782,8 @@ def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:
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")
+ "AGENTS.md" if backend in ("codex", "hermes", "pi", "dsh", "opencode", "cline")
+ else "CLAUDE.md")
def _write_agent_doc(cwd: str, backend: str, agent_doc: str | None, skills_meta: list[dict]) -> None:
@@ -2546,6 +2555,189 @@ def _build_qwen(provider: str, auth: Auth, model: str, prompt: str, cwd: str, en
return cmd
+CLINE_PROVIDERS = {"anthropic", "openai", "azure", "openai-api", "tokenrouter"}
+
+
+def _cline_settings(home: pathlib.Path, base_url: str, api_key: str, model: str,
+ mcp_servers: list[dict] | None) -> None:
+ """~/.cline/data/settings/{providers.json, cline_mcp_settings.json} under the redirected HOME.
+
+ Written directly rather than through `cline auth` — the file is trivial, and a subprocess per
+ turn to produce four JSON fields is a second mechanism for one behaviour. Shapes verified
+ against what 3.0.60's own `auth` and `mcp install --yes` write, not inferred from source.
+
+ The apiKey that lands on disk is the per-turn loopback relay token, never the provider key:
+ every cline turn rides the hermes relay exactly as qwen's does. cline was verified to IGNORE
+ CLINE_API_KEY/CLINE_API_BASE_URL for this provider (a stub upstream never saw the request;
+ api.openai.com did), so the settings file is the only wiring that actually works — and inside
+ the per-session sandbox it is readable only by the session's own uid, which can read its own
+ process environment anyway.
+ """
+ sdir = home / ".cline" / "data" / "settings"
+ sdir.mkdir(parents=True, exist_ok=True)
+ (sdir / "providers.json").write_text(json.dumps({
+ "version": 1,
+ "lastUsedProvider": "openai-compatible",
+ "modes": {},
+ "providers": {"openai-compatible": {
+ "settings": {"provider": "openai-compatible", "apiKey": api_key,
+ "model": model, "baseUrl": base_url},
+ # REQUIRED, not decoration: without updatedAt 3.0.60's settings schema rejects the
+ # whole provider entry — silently — and the CLI dials api.openai.com with no key.
+ # Bisected live: the identical file with only this field added runs; without it the
+ # entry is rewritten down to {provider, model} and the turn dies on OpenAI's 401.
+ "updatedAt": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()),
+ "tokenSource": "manual"}},
+ }, indent=2))
+ servers: dict = {}
+ for i, sv in enumerate(mcp_servers or []):
+ if not isinstance(sv, dict) or sv.get("enabled") is False:
+ continue
+ url = (sv.get("url") or "").strip()
+ if not url:
+ continue # cline's file also takes stdio; the harness config is URL-only
+ name = _skill_dir_name(sv.get("name") or sv.get("id") or f"server{i}")
+ entry: dict = {"transport": {"type": "streamableHttp", "url": url}}
+ hdrs = sv.get("headers")
+ if isinstance(hdrs, dict) and hdrs:
+ entry["transport"]["headers"] = {str(k): str(v) for k, v in hdrs.items()}
+ servers[name] = entry
+ (sdir / "cline_mcp_settings.json").write_text(json.dumps({"mcpServers": servers}, indent=2))
+
+
+def _build_cline(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 CLINE_PROVIDERS:
+ raise HTTPException(400, f"unknown cline provider '{pr}' (one of {sorted(CLINE_PROVIDERS)})")
+ if not auth.base_url:
+ raise HTTPException(400, "cline needs a base_url (none configured)")
+ if auth.api_key:
+ # Every cline turn rides the loopback relay (the qwen rationale, verbatim): request shapes
+ # strict endpoints refuse are repaired in flight, and the real key never reaches the CLI —
+ # what lands in its settings file is a placeholder valid for this turn, from loopback only.
+ relay_base, relay_tok = _hermes_relay_route(auth.base_url, auth.api_key)
+ auth = auth.model_copy(update={"base_url": relay_base, "api_key": relay_tok})
+ home = pathlib.Path(cwd) / ".harness" / "home"
+ home.mkdir(parents=True, exist_ok=True)
+ env["HOME"] = str(home) # sessions/settings/db live INSIDE the checkpointed workspace
+ _cline_settings(home, auth.base_url, auth.api_key or "", model, mcp_servers)
+ # A prompt with no whitespace is parsed as a SUBCOMMAND ("Unknown command or unquoted
+ # prompt: hi") and `--` does not rescue it. A trailing newline does, verified on 3.0.60,
+ # and is invisible to the model.
+ if prompt and not any(ch.isspace() for ch in prompt):
+ prompt = prompt + "\n"
+ # NO resume flag, deliberately. 3.0.60's `--json --id <session>` refuses every way of passing
+ # a prompt (argument, =form, piped stdin — all verified individually, and the identical argv
+ # without --id runs), so headless resume is unusable in this release. A follow-up turn starts
+ # a fresh conversation over the same workspace: the files, AGENTS.md and the session store
+ # under HOME all persist through the checkpoint, so when a release fixes the flag, resume
+ # lights up here with no storage work.
+ # `-z` (background hub daemon) must never be added: one process per turn is the runner's
+ # execution model, and the hub is a resident service with its own update/restart lifecycle.
+ return ["cline", prompt, "--json", "--auto-approve", "true",
+ "-c", cwd, "-P", "openai-compatible", "-m", model]
+
+
+def _cline_eof(state: dict, rc: int) -> list[dict]:
+ """Synthesize the terminal result if the process dies before its own run_result event.
+
+ cline DOES emit a terminal run_result (unlike opencode), so on a healthy turn this adds
+ nothing — _cline_to_claude marks the state done and this returns []. It exists for the
+ crash-mid-turn case, where otherwise the trace would end without a result event at all."""
+ if state.get("_cl_done"):
+ return []
+ usage = state.get("_cl_usage") or {}
+ err = state.get("_cl_error", "")
+ if rc == 0 and not err:
+ return [{"type": "result", "subtype": "success", "is_error": False,
+ "result": state.get("final", ""), "usage": usage}]
+ return [{"type": "result", "subtype": "error", "is_error": True,
+ "result": err or f"cline exited {rc} without reporting a result", "usage": usage}]
+
+
+def _cline_to_claude(obj: dict, state: dict) -> list[dict]:
+ """Map ONE `cline --json` line to zero+ canonical claude stream-json events.
+
+ The emitter writes {ts, type, ...} per line, three types that matter here (verified on 3.0.60
+ against a stub upstream, tool round-trip included):
+
+ hook_event agent_start/tool_call/tool_result/agent_end/agent_error — lifecycle markers;
+ agent_start carries taskId, the only session-ish id the stream has.
+ agent_event {event:{type: iteration_start|content_start|content_update|content_end|usage|
+ iteration_end|done|error}}. content_* carry contentType "text" or "tool";
+ text arrives WHOLE on content_start and again on content_end (chunk-level, not
+ token-level — do not advertise token streaming); tool carries toolName,
+ toolCallId and full input on start, output on end.
+ run_result the terminal event: finishReason, text, usage {inputTokens, outputTokens,
+ cacheReadTokens, cacheWriteTokens}.
+ """
+ t = obj.get("type")
+ pre: list[dict] = []
+ if t == "hook_event":
+ if obj.get("hookEventName") == "agent_start" and not state.get("_cl_init"):
+ state["_cl_init"] = True
+ pre = [{"type": "system", "subtype": "init",
+ "session_id": str(obj.get("taskId") or ""), "model": state.get("model")}]
+ return pre
+ if t == "agent_event":
+ e = obj.get("event") if isinstance(obj.get("event"), dict) else {}
+ et = e.get("type")
+ ct = e.get("contentType")
+ if et == "content_end" and ct == "text":
+ txt = e.get("text") or ""
+ if not txt:
+ return []
+ state["final"] = txt # claude result semantics: the LAST assistant text
+ return [{"type": "assistant", "message": {"content": [{"type": "text", "text": txt}]}}]
+ if et == "content_end" and ct in ("reasoning", "thinking"):
+ txt = e.get("text") or ""
+ return ([{"type": "assistant",
+ "message": {"content": [{"type": "thinking", "thinking": txt}]}}]
+ if txt else [])
+ if et == "content_start" and ct == "tool":
+ return [{"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": e.get("toolCallId") or "tool",
+ "name": e.get("toolName") or "tool", "input": e.get("input") or {}}]}}]
+ if et == "content_end" and ct == "tool":
+ out = e.get("output")
+ body = out if isinstance(out, str) else json.dumps(out or [])
+ return [{"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": e.get("toolCallId") or "tool",
+ "content": body}]}}]
+ if et == "error":
+ err = e.get("error")
+ msg = str((err or {}).get("message") or err or "cline error") if isinstance(err, (dict, str)) else "cline error"
+ state["_cl_error"] = msg
+ return []
+ return []
+ if t == "run_result":
+ u = obj.get("usage") or {}
+ usage = {"input_tokens": int(u.get("inputTokens") or 0),
+ "output_tokens": int(u.get("outputTokens") or 0),
+ "cache_read_tokens": int(u.get("cacheReadTokens") or 0),
+ "cache_write_tokens": int(u.get("cacheWriteTokens") or 0)}
+ state["_cl_usage"] = usage
+ state["_cl_done"] = True
+ reason = str(obj.get("finishReason") or "")
+ ok = reason == "completed"
+ txt = obj.get("text") or state.get("final", "")
+ if ok:
+ state["final"] = txt
+ return [{"type": "result", "subtype": "success" if ok else "error",
+ "is_error": not ok,
+ "result": txt if ok else (state.get("_cl_error") or txt or f"cline ended: {reason}"),
+ "usage": usage}]
+ if t == "error":
+ state["_cl_error"] = str(obj.get("message") or "cline error")
+ return []
+ return []
+
+
+_cline_to_claude.eof = _cline_eof # type: ignore[attr-defined]
+
+
def _opencode_eof(state: dict, rc: int) -> list[dict]:
"""Synthesize the turn's result at end of stream.
@@ -2867,6 +3059,8 @@ BACKENDS = {
# names) — so its normalizer IS the claude passthrough.
"qwen": {"providers": sorted(QWEN_PROVIDERS), "default_model": QWEN_DEFAULT_MODEL,
"normalize": _claude_passthrough},
+ "cline": {"providers": sorted(CLINE_PROVIDERS), "default_model": CLINE_DEFAULT_MODEL,
+ "normalize": _cline_to_claude},
}
@@ -3898,6 +4092,10 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
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 == "cline":
+ model = model or CLINE_DEFAULT_MODEL
+ cmd = _build_cline(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 and
diff --git a/runner/tests/test_cline_backend.py b/runner/tests/test_cline_backend.py
new file mode 100644
index 00000000..5ffc64e9
--- /dev/null
+++ b/runner/tests/test_cline_backend.py
@@ -0,0 +1,144 @@
+"""The cline backend, against facts measured on the shipped 3.0.60 binary.
+
+Every assertion here encodes something verified live against a stub upstream, not read from
+documentation: the settings file is the only auth wiring that works (the env vars the binary
+carries are ignored for openai-compatible), a whitespace-free prompt is parsed as a subcommand,
+--json --id refuses every way of passing a prompt, and the event stream's tool round trip.
+"""
+import json
+import pathlib
+import sys
+import tempfile
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+from server import (Auth, BACKENDS, _agent_doc_path, _build_cline, _cline_eof, # noqa: E402
+ _cline_to_claude)
+
+
+def _argv(prompt="do the thing", **kw):
+ d = tempfile.mkdtemp()
+ env: dict = {}
+ cmd = _build_cline("openai-api", Auth(api_key="", base_url="https://relay.example/v1"),
+ "gpt-5.4", prompt, d, env, **kw)
+ return cmd, d, env
+
+
+def test_argv_is_headless_json_with_auto_approve():
+ cmd, d, env = _argv()
+ assert cmd[0] == "cline" and cmd[1] == "do the thing"
+ assert "--json" in cmd and "--auto-approve" in cmd
+ assert "-P" in cmd and "openai-compatible" in cmd
+ assert "-z" not in cmd, "the background hub daemon must never be part of a turn"
+
+
+def test_home_is_redirected_and_settings_land_inside_the_workspace():
+ """The credentials file is the ONLY wiring cline honours for openai-compatible: the binary
+ carries CLINE_API_KEY/CLINE_API_BASE_URL but a live probe showed them ignored (the stub
+ upstream never saw the request; api.openai.com did). So the settings file must exist, inside
+ the checkpointed workspace, before the process starts."""
+ cmd, d, env = _argv()
+ assert env["HOME"] == str(pathlib.Path(d) / ".harness" / "home")
+ p = pathlib.Path(env["HOME"]) / ".cline" / "data" / "settings" / "providers.json"
+ assert p.exists()
+ cfg = json.loads(p.read_text())
+ st = cfg["providers"]["openai-compatible"]["settings"]
+ assert st["baseUrl"] == "https://relay.example/v1"
+ assert st["model"] == "gpt-5.4"
+ # updatedAt is REQUIRED by 3.0.60's settings schema. Bisected live: the identical file
+ # without it is silently rejected wholesale, the entry is rewritten down to
+ # {provider, model}, and the turn dies on api.openai.com's keyless 401.
+ assert cfg["providers"]["openai-compatible"].get("updatedAt"), \
+ "updatedAt missing: cline will silently discard the whole provider entry"
+
+
+def test_a_whitespace_free_prompt_gets_a_trailing_newline():
+ """A single-token prompt is parsed as a SUBCOMMAND ('Unknown command or unquoted prompt: hi')
+ and `--` does not rescue it. A trailing newline does — verified on 3.0.60 both ways."""
+ cmd, _, _ = _argv(prompt="hi")
+ assert cmd[1] == "hi\n"
+ cmd2, _, _ = _argv(prompt="hi there")
+ assert cmd2[1] == "hi there"
+
+
+def test_resume_is_deliberately_not_wired():
+ """3.0.60's `--json --id` refuses every way of passing a prompt (argument, =form, piped
+ stdin — each verified individually, and the identical argv without --id runs). Passing a
+ resume id must therefore change nothing rather than produce a turn that cannot start."""
+ cmd, _, _ = _argv(resume_session_id="1788124440212_6s446")
+ assert "--id" not in cmd
+
+
+def test_mcp_servers_land_in_clines_own_settings_file():
+ d = tempfile.mkdtemp()
+ env: dict = {}
+ _build_cline("openai-api", Auth(api_key="", base_url="https://r.example/v1"), "gpt-5.4",
+ "go", d, env,
+ mcp_servers=[{"name": "graph", "url": "https://mcp.example/mcp",
+ "headers": {"x-k": "v"}},
+ {"name": "off", "url": "https://x.example", "enabled": False}])
+ p = pathlib.Path(env["HOME"]) / ".cline" / "data" / "settings" / "cline_mcp_settings.json"
+ servers = json.loads(p.read_text())["mcpServers"]
+ assert servers["graph"]["transport"] == {"type": "streamableHttp",
+ "url": "https://mcp.example/mcp",
+ "headers": {"x-k": "v"}}
+ assert "off" not in servers, "a disabled server must not be contacted, so it is not written"
+
+
+def test_agent_doc_is_agents_md():
+ assert _agent_doc_path("/w", "cline").name == "AGENTS.md"
+
+
+def test_registered_with_a_normalizer_and_an_eof():
+ assert BACKENDS["cline"]["normalize"] is _cline_to_claude
+ assert getattr(_cline_to_claude, "eof", None) is _cline_eof
+
+
+# ── the event stream, exactly as 3.0.60 emitted it against a stub upstream ──────────
+
+def _ev(line, state):
+ return _cline_to_claude(json.loads(line), state)
+
+
+def test_the_verified_tool_round_trip_normalizes():
+ state = {"model": "gpt-5.4"}
+ out = []
+ for line in [
+ '{"ts":"t","type":"hook_event","hookEventName":"agent_start","taskId":"conv_1","parentAgentId":null}',
+ '{"ts":"t","type":"agent_event","event":{"type":"iteration_start","iteration":1}}',
+ '{"ts":"t","type":"agent_event","event":{"type":"content_start","contentType":"tool","toolName":"run_commands","toolCallId":"call_1","input":{"commands":["echo hi"]}}}',
+ '{"ts":"t","type":"agent_event","event":{"type":"content_end","contentType":"tool","toolName":"run_commands","toolCallId":"call_1","output":[{"query":"echo hi","result":"","success":true}],"durationMs":3}}',
+ '{"ts":"t","type":"agent_event","event":{"type":"content_start","contentType":"text","text":"Done.","accumulated":"Done."}}',
+ '{"ts":"t","type":"agent_event","event":{"type":"content_end","contentType":"text","text":"Done."}}',
+ '{"ts":"t","type":"run_result","finishReason":"completed","iterations":2,"usage":{"inputTokens":21,"outputTokens":11,"cacheReadTokens":0,"cacheWriteTokens":0,"totalCost":0},"durationMs":29,"text":"Done.","model":{"id":"gpt-5.4"}}',
+ ]:
+ out.extend(_ev(line, state))
+ types = [(e["type"], (e.get("message") or {}).get("content", [{}])[0].get("type"))
+ for e in out]
+ assert types[0] == ("system", None)
+ assert ("assistant", "tool_use") in types
+ assert ("user", "tool_result") in types
+ # text arrives whole on content_start AND content_end; only content_end may emit, once
+ assert sum(1 for t in types if t == ("assistant", "text")) == 1
+ final = out[-1]
+ assert final["type"] == "result" and final["is_error"] is False
+ assert final["result"] == "Done."
+ assert final["usage"] == {"input_tokens": 21, "output_tokens": 11,
+ "cache_read_tokens": 0, "cache_write_tokens": 0}
+ assert _cline_eof(state, 0) == [], "a healthy turn already has its result; eof must add nothing"
+
+
+def test_the_verified_error_shape_fails_the_turn():
+ """Captured live: a bad credential emits agent_event{type:error} and run_result
+ finishReason 'error' whose text restates the message."""
+ state = {}
+ _ev('{"ts":"t","type":"agent_event","event":{"type":"error","error":{"name":"Error","message":"no key"},"errorClass":"unknown","recoverable":false,"iteration":1}}', state)
+ out = _ev('{"ts":"t","type":"run_result","finishReason":"error","iterations":1,"usage":{"inputTokens":0,"outputTokens":0},"text":"no key","model":{"id":"m"}}', state)
+ assert out[-1]["type"] == "result" and out[-1]["is_error"] is True
+ assert "no key" in out[-1]["result"]
+
+
+def test_a_crash_before_run_result_still_yields_a_result():
+ state = {"final": "partial answer"}
+ out = _cline_eof(state, 1)
+ assert out and out[0]["is_error"] is True
+ assert "exited 1" in out[0]["result"] or state.get("_cl_error", "") in out[0]["result"]