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.

fix(runner): a Codex history resumed under another account is replayed as content; under the same account it is kept whole (#81)

github-actions[bot]145d325c8187
diff --git a/runner/server.py b/runner/server.py
index 9e491b1b..476cbbdd 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -1259,12 +1259,6 @@ model_reasoning_effort = "{effort}"
approval_policy = "never"
sandbox_mode = "danger-full-access"
model_context_window = {ctx}
-[features]
-# Compaction happens locally. Remote compaction is a call to OpenAI's own backend
-# (/responses/compact under the Responses-Lite header) that an API key at api.openai.com refused
-# ("requires reasoning.context to be all_turns") and that Azure, TokenRouter, OpenRouter and
-# Vercel do not serve at all; local compaction works on every provider we front.
-remote_compaction_v2 = false
[model_providers.{provider}]
name = "{name}"
base_url = "{base_url}"
@@ -1355,6 +1349,20 @@ def _codex_prepare_env(provider: str, auth: Auth, model: str, cwd: str,
# why codex state used to vanish. (auth.json inside is still creds-excluded.)
cfg_dir = pathlib.Path(env.get("HOME") or cwd) / ".codex"
cfg_dir.mkdir(parents=True, exist_ok=True)
+ # Which account serves this turn, as a fingerprint that never names the key. A resume under the
+ # account that minted the history keeps it whole; under another it is replayed as content
+ # (see _sanitize_codex_rollout). The marker lives in the checkpointed home, beside the rollouts.
+ fp = hashlib.sha256(f"{p}|{base_url}|{auth.api_key or ''}".encode()).hexdigest()[:16]
+ marker = cfg_dir / "hr-account"
+ try:
+ prior = marker.read_text().strip()
+ except OSError:
+ prior = ""
+ env["HR_CODEX_ACCOUNT_CHANGED"] = "0" if prior == fp else "1"
+ try:
+ marker.write_text(fp)
+ except OSError:
+ pass
# codex only speaks the OpenAI Responses API now — current releases removed
# `wire_api = "chat"` entirely, so a custom chat-completions endpoint cannot be driven by
# codex at all (the gateway greys codex out for those integrations). Always the supported
@@ -1385,7 +1393,7 @@ def _codex_prepare_env(provider: str, auth: Auth, model: str, cwd: str,
return cfg_dir
-def _sanitize_codex_rollout(rollouts: list[str]) -> dict:
+def _sanitize_codex_rollout(rollouts: list[str], *, content_only: bool = True) -> dict:
"""Make a codex rollout safe to replay, without destroying any of it.
Two hazards live in the same file, and the fix for one used to create the other.
@@ -1429,6 +1437,14 @@ def _sanitize_codex_rollout(rollouts: list[str]) -> dict:
# function_call_output form; `ctc_` the custom_tool_call form.
MINTED = ("msg_", "rs_", "fc_", "fcr_", "ctc_")
counts = {"reasoning": 0, "deref": 0, "damaged": 0}
+ # The same account serving the resume can resolve its own ids and decrypt its own blobs, and
+ # keeping both is what lets a model switch inside one resource (two Azure deployments) and a
+ # follow-up on one key keep their reasoning continuity. Only a resume under another account
+ # (the July thread born on Azure, resumed on the org's own OpenAI key; a chain fallback; a
+ # rotated key) is turned into content. Richard's rule (2026-09-06): a session that changes
+ # provider is not supported; everything on one provider must work.
+ if not content_only:
+ return counts
for path in rollouts:
try:
@@ -1447,28 +1463,32 @@ def _sanitize_codex_rollout(rollouts: list[str]) -> dict:
except ValueError:
parsed.append((line, None)) # unparseable: preserve verbatim
- # Pass 1 — drop the account-bound blob, keep the item and its id.
- has_reasoning = False
+ # Pass 1 — drop the account-bound blob, keep the item; its id goes in pass 2.
for i, (line, o) in enumerate(parsed):
if not o or o.get("type") != "response_item":
continue
pay = o.get("payload")
if not isinstance(pay, dict) or pay.get("type") != "reasoning":
continue
- has_reasoning = True
if pay.pop("encrypted_content", None) is not None:
counts["reasoning"] += 1
parsed[i] = (json.dumps(o), o)
- # Pass 2 — repair a rollout the old delete-based strip already damaged. Only when there is
- # no reasoning item left to anchor the ids: with reasoning present the references resolve
- # and stripping ids would needlessly discard continuity.
+ # Pass 2 — a replayed history is content, never a reference. Every provider-minted id is
+ # removed on every resume: an id is a lookup into the state of the deployment or account
+ # that minted it, and a resumed thread is routinely served by another one (a July thread
+ # born on Azure resumed on the org's own OpenAI key answered 404 on every turn; a switch
+ # between two deployments of one Azure resource answered "message provided without its
+ # required reasoning item"; both 2026-09-06). With the ids gone the provider reads the
+ # items as ordinary content; `call_id`, `phase`, `role`, `content`, `name` and `arguments`
+ # stay, so tool pairing and the transcript survive. This trades server-side reasoning
+ # continuity for a replay that works wherever the next turn runs.
minted = [
(i, o) for i, (line, o) in enumerate(parsed)
if o and o.get("type") == "response_item" and isinstance(o.get("payload"), dict)
and str((o["payload"] or {}).get("id") or "").startswith(MINTED)
]
- if minted and not has_reasoning:
+ if minted:
counts["damaged"] += 1
for i, o in minted:
o["payload"].pop("id", None)
@@ -1499,7 +1519,7 @@ def _build_codex(provider: str, auth: Auth, model: str, prompt: str, cwd: str,
# Make the rollout safe to replay: drop account-bound reasoning blobs, and repair a
# rollout an older build already damaged (see the helper). Logged unconditionally —
# staying silent at zero is what hid this step during the investigation.
- c = _sanitize_codex_rollout(rollouts)
+ c = _sanitize_codex_rollout(rollouts, content_only=env.get("HR_CODEX_ACCOUNT_CHANGED") != "0")
print(f"[resume] codex: sanitised rollout — dropped {c['reasoning']} reasoning blob(s), "
f"de-referenced {c['deref']} id(s) across {c['damaged']} damaged file(s)", flush=True)
# CODEX_HOME is PER-SESSION (hydrate wipes + restores only THIS session's workspace), so
@@ -3316,7 +3336,8 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, promp
resume_thread = _codex_resume_thread_id(cfg_dir, resume_session_id)
if resume_thread:
import glob as _glob
- c = _sanitize_codex_rollout(_glob.glob(str(cfg_dir / "sessions" / "**" / "*.jsonl"), recursive=True))
+ c = _sanitize_codex_rollout(_glob.glob(str(cfg_dir / "sessions" / "**" / "*.jsonl"), recursive=True),
+ content_only=env.get("HR_CODEX_ACCOUNT_CHANGED") != "0")
print(f"[resume] codex app-server: thread {resume_thread}{' (newest rollout, wanted ' + resume_session_id + ')' if resume_thread != resume_session_id else ''}; "
f"dropped {c['reasoning']} reasoning blob(s), de-referenced {c['deref']} id(s)", flush=True)
else:
diff --git a/runner/tests/test_codex_reasoning_strip.py b/runner/tests/test_codex_reasoning_strip.py
index 6e8aad88..f8e853bb 100644
--- a/runner/tests/test_codex_reasoning_strip.py
+++ b/runner/tests/test_codex_reasoning_strip.py
@@ -58,107 +58,77 @@ def _minted_ids(path: Path) -> list[str]:
return [str(p.get("id")) for p in _items(path) if str(p.get("id") or "").startswith(MINTED)]
-def test_reasoning_survives_with_its_id_only_the_blob_is_dropped(tmp_path):
- """The account-bound blob is what must go; the item and its id are what the server checks."""
+def test_content_only_replay_drops_every_blob_and_every_minted_id(tmp_path):
+ """A resume under another account replays content: no encrypted blob (it is bound to the
+ account that minted it) and no provider-minted id (it is a lookup into that account's state).
+ Items are never deleted, so tool pairing and the transcript survive."""
f = _load("codex_rollout_healthy.jsonl", tmp_path)
before_lines = len(f.read_text().splitlines())
- before_reasoning = [p for p in _items(f) if p.get("type") == "reasoning"]
- before_msg_ids = [i for i in _minted_ids(f) if i.startswith("msg_")]
- assert before_reasoning, "fixture must contain reasoning items"
- assert before_msg_ids, "fixture must contain provider-minted message ids"
-
- counts = rn._sanitize_codex_rollout([str(f)])
-
- after_reasoning = [p for p in _items(f) if p.get("type") == "reasoning"]
- assert len(after_reasoning) == len(before_reasoning), "reasoning items must NOT be deleted"
- assert all("encrypted_content" not in p for p in after_reasoning), "blob must be gone"
- assert all(p.get("id") for p in after_reasoning), "reasoning items keep their id"
- assert counts["reasoning"] == len(before_reasoning)
- # Nothing else moved: same line count, same message ids, and the repair branch stayed shut.
- assert len(f.read_text().splitlines()) == before_lines
- assert [i for i in _minted_ids(f) if i.startswith("msg_")] == before_msg_ids
- assert counts["damaged"] == 0 and counts["deref"] == 0
+ before_items = _items(f)
+ before_reasoning = [p for p in before_items if p.get("type") == "reasoning"]
+ assert before_reasoning and _minted_ids(f), "fixture must carry reasoning items and minted ids"
+
+ counts = rn._sanitize_codex_rollout([str(f)], content_only=True)
+
+ after_items = _items(f)
+ assert len(after_items) == len(before_items) and len(f.read_text().splitlines()) == before_lines
+ assert all("encrypted_content" not in p for p in after_items if p.get("type") == "reasoning")
+ assert _minted_ids(f) == []
+ assert counts["reasoning"] == len(before_reasoning) and counts["deref"] > 0 and counts["damaged"] == 1
+ # what the transcript and the tool pairing need is still there
+ for pb, pa in zip(before_items, after_items):
+ for k in ("type", "call_id", "phase", "role", "content", "name", "arguments", "output"):
+ assert pb.get(k) == pa.get(k), k
+
+
+def test_same_account_replay_is_untouched(tmp_path):
+ """The account that minted the history can resolve its ids and decrypt its blobs: a follow-up
+ or a model switch on the same key keeps the whole history, byte for byte."""
+ f = _load("codex_rollout_healthy.jsonl", tmp_path)
+ before = f.read_text()
+ counts = rn._sanitize_codex_rollout([str(f)], content_only=False)
+ assert f.read_text() == before
+ assert counts == {"reasoning": 0, "deref": 0, "damaged": 0}
def test_damaged_rollout_is_repaired_by_dropping_every_minted_id(tmp_path):
- """The real wedged session. With reasoning already destroyed, the ids must go — all of them.
-
- A half-measure (de-id only messages, say) does not fix anything: it relocates the same 400 to
- whichever item type still carries an id.
- """
+ """A rollout an older build already stripped of its reasoning items has message ids that
+ reference nothing; content-only replay removes them the same way."""
f = _load("codex_rollout_damaged.jsonl", tmp_path)
- before_lines = len(f.read_text().splitlines())
- assert not [p for p in _items(f) if p.get("type") == "reasoning"], "fixture is the damaged one"
- assert _minted_ids(f), "fixture must carry provider-minted ids"
- before_calls = [p.get("call_id") for p in _items(f) if p.get("call_id")]
- before_roles = [p.get("role") for p in _items(f) if p.get("role")]
-
- counts = rn._sanitize_codex_rollout([str(f)])
-
- assert _minted_ids(f) == [], "no provider-minted id may survive in a damaged rollout"
- assert counts["damaged"] == 1 and counts["deref"] > 0
- # The transcript itself is preserved — this repairs the replay, it does not erase history.
- assert [p.get("call_id") for p in _items(f) if p.get("call_id")] == before_calls
- assert [p.get("role") for p in _items(f) if p.get("role")] == before_roles
- assert len(f.read_text().splitlines()) == before_lines
-
-
-def test_no_minted_id_is_ever_left_without_a_reasoning_anchor(tmp_path):
- """The invariant, stated once. This is the assertion that would have caught the original bug,
- and it will catch the next variant of it whatever shape codex sends."""
- for name in ("codex_rollout_healthy.jsonl", "codex_rollout_damaged.jsonl"):
- d = tmp_path / name.replace(".jsonl", "")
- d.mkdir(parents=True, exist_ok=True)
- f = _load(name, d)
- rn._sanitize_codex_rollout([str(f)])
- has_reasoning = any(p.get("type") == "reasoning" for p in _items(f))
- if not has_reasoning:
- assert _minted_ids(f) == [], f"{name}: dangling references would 400 on replay"
+ assert _minted_ids(f), "fixture must carry orphaned minted ids"
+ counts = rn._sanitize_codex_rollout([str(f)], content_only=True)
+ assert _minted_ids(f) == [] and counts["damaged"] == 1 and counts["deref"] > 0
def test_sanitise_is_idempotent(tmp_path):
- """Run twice, byte-identical after the first pass — a resume may sanitise the same file again."""
- for name in ("codex_rollout_healthy.jsonl", "codex_rollout_damaged.jsonl"):
- d = tmp_path / name.replace(".jsonl", "")
- d.mkdir(parents=True, exist_ok=True)
- f = d / name
- f.write_text((FIXTURES / name).read_text())
- rn._sanitize_codex_rollout([str(f)])
- once = f.read_text()
- rn._sanitize_codex_rollout([str(f)])
- assert f.read_text() == once, f"{name}: second pass changed the file"
-
-
-def test_reasoning_without_encrypted_content_is_still_kept(tmp_path):
- """A provider that returns reasoning WITHOUT a blob must not trip anything.
-
- The old predicate keyed on the literal substring `"encrypted_content"`, so such an item was
- invisible to it. Nothing may depend on that substring any more.
- """
- f = tmp_path / "r.jsonl"
- f.write_text("\n".join(json.dumps(o) for o in [
- {"type": "response_item", "payload": {"type": "reasoning", "id": "rs_1", "summary": []}},
- {"type": "response_item", "payload": {"type": "message", "id": "msg_1", "role": "assistant",
- "content": [{"type": "output_text", "text": "hi"}]}},
- ]) + "\n")
- counts = rn._sanitize_codex_rollout([str(f)])
- items = _items(f)
- assert any(p.get("type") == "reasoning" and p.get("id") == "rs_1" for p in items)
- # Reasoning is present, so the ids resolve and the repair branch must stay shut.
- assert counts["damaged"] == 0
- assert any(p.get("id") == "msg_1" for p in items)
+ f = _load("codex_rollout_healthy.jsonl", tmp_path)
+ rn._sanitize_codex_rollout([str(f)], content_only=True)
+ once = f.read_text()
+ counts = rn._sanitize_codex_rollout([str(f)], content_only=True)
+ assert f.read_text() == once and counts["reasoning"] == 0 and counts["deref"] == 0
def test_tolerates_missing_and_malformed(tmp_path):
- """Unchanged from the original suite: a missing file is skipped, bad lines survive verbatim."""
- good = tmp_path / "ok.jsonl"
- good.write_text('{"type": "response_item", "payload": {"type": "reasoning", "id": "rs_1",'
- ' "encrypted_content": "gAAA"}}\nnot json at all\n')
- rn._sanitize_codex_rollout([str(tmp_path / "nope.jsonl"), str(good)])
- text = good.read_text()
- assert "not json at all" in text
- assert "encrypted_content" not in text
- assert '"rs_1"' in text
+ missing = tmp_path / "nope.jsonl"
+ bad = tmp_path / "bad.jsonl"
+ bad.write_text('{"type":"response_item","payload":{"type":"reasoning","id":"rs_1","encrypted_content":"x"}}\nnot json {"response_item"\n')
+ counts = rn._sanitize_codex_rollout([str(missing), str(bad)], content_only=True)
+ lines = bad.read_text().splitlines()
+ assert len(lines) == 2 and lines[1] == 'not json {"response_item"'
+ items = _items(bad)
+ assert items and "encrypted_content" not in items[0] and "id" not in items[0]
+ assert counts["reasoning"] == 1 and counts["deref"] == 1
+
+
+def test_the_account_marker_decides_content_only(tmp_path):
+ """First turn on a key: no marker, so a resume (if any) is content-only. Same key next turn:
+ untouched. A different key: content-only again. The marker never names the key."""
+ import server as rs
+ for auth, expect in ((rs.Auth(api_key="k1"), "1"), (rs.Auth(api_key="k1"), "0"), (rs.Auth(api_key="k2"), "1"), (rs.Auth(api_key="k2"), "0")):
+ env = {"HOME": str(tmp_path)}
+ cfg_dir = rs._codex_prepare_env("openai", auth, "gpt-5.5", str(tmp_path), env)
+ assert env["HR_CODEX_ACCOUNT_CHANGED"] == expect
+ assert "k1" not in (cfg_dir / "hr-account").read_text() and "k2" not in (cfg_dir / "hr-account").read_text()
def test_a_resumed_session_keeps_every_provider_id_it_ran_under(tmp_path, monkeypatch):
@@ -201,13 +171,16 @@ def test_app_server_resumes_the_rollout_that_is_here(tmp_path):
assert _codex_resume_thread_id(home, "t-missing") == "t-new", "not here: the newest rollout is this conversation"
-def test_codex_config_compacts_locally(tmp_path, monkeypatch):
- """Remote compaction is off in every Codex config the runner writes: it is an OpenAI-backend
- call that other providers do not serve and that an API key was refused on."""
+def test_codex_config_declares_the_catalog_window_and_no_feature_overrides(tmp_path, monkeypatch):
+ """The runner declares the window Codex's own catalog has for gpt-5.x and leaves Codex's
+ feature flags alone: compaction was measured to work on every provider once the broker stopped
+ stripping `reasoning`, with the remote-compaction flag on or off (Codex compacts locally when a
+ provider has no compaction endpoint)."""
import server as rs
env = {"HOME": str(tmp_path)}
cfg_dir = rs._codex_prepare_env("openai", rs.Auth(api_key="k"), "gpt-5.5", str(tmp_path), env)
cfg = (cfg_dir / "config.toml").read_text()
- assert "[features]\n" in cfg and "remote_compaction_v2 = false" in cfg
+ assert "model_context_window = 272000" in cfg and "[features]" not in cfg
import tomllib
- assert tomllib.loads(cfg)["features"]["remote_compaction_v2"] is False
+ parsed = tomllib.loads(cfg)
+ assert parsed["model_providers"]["hr-openai"]["wire_api"] == "responses"