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
runner: a codex command's stored output is what the model was given, never the item's output that drops the first chunk (#580)
github-actions[bot]c6ebaa79db25
diff --git a/gateway/app.py b/gateway/app.pyindex dae4c402..85d9cf6b 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -6486,7 +6486,9 @@ def _blocks_from_canonical(ev: dict) -> list[tuple[str, object]]:content = "\n".join((x.get("text", "") if isinstance(x, dict) else str(x)) for x in content)out.append(("tool_result", {"call_id": c.get("tool_use_id") or "","output": str(content if content is not None else ""),- "is_error": bool(c.get("is_error"))}))+ "is_error": bool(c.get("is_error")),+ # the runner had no complete record of the output (codex)+ "incomplete": bool(c.get("incomplete"))}))elif t == "result":out.append(("result", {"text": ev.get("result") or "", "usage": ev.get("usage"),"is_error": bool(ev.get("is_error")),@@ -6716,8 +6718,10 @@ class _RespTranslator:evs += self._close_cur()self.out_index += 1oid = _rid("fco")+ # `incomplete`: the output may lack part of what the tool printed, and says so, never+ # passed off as the whole of ititem = {"id": oid, "type": "function_call_output", "call_id": payload["call_id"],- "output": payload["output"], "status": "completed"}+ "output": payload["output"], "status": "incomplete" if payload.get("incomplete") else "completed"}evs.append(self._ev("response.output_item.added", output_index=self.out_index, item=item))evs.append(self._ev("response.output_item.done", output_index=self.out_index, item=item))self.output.append(item)diff --git a/gateway/tests/test_tool_output_incomplete.py b/gateway/tests/test_tool_output_incomplete.pynew file mode 100644index 00000000..635c62d4--- /dev/null+++ b/gateway/tests/test_tool_output_incomplete.py@@ -0,0 +1,27 @@+"""A tool output the runner could not back with a complete record is marked incomplete.++The runner reads a codex command's output from codex's own record of what the model was given+(openai/codex#28207: codex's command item drops the output printed first). When no complete+record is found, its tool_result says `incomplete`, and the response's function_call_output item+carries status "incomplete" instead of "completed", so it is never passed off as the whole output.+"""+import pathlib+import sys++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402+++def _outputs(*results: dict) -> list[dict]:+ tr = gw._RespTranslator("resp_t", "m", None, False, 0.0)+ tr.feed({"type": "assistant", "message": {"content": [+ {"type": "tool_use", "id": r["tool_use_id"], "name": "Bash", "input": {"command": "x"}} for r in results]}})+ tr.feed({"type": "user", "message": {"content": list(results)}})+ return [o for o in tr.output if o.get("type") == "function_call_output"]+++def test_an_output_without_a_complete_record_is_an_incomplete_item():+ out = _outputs({"type": "tool_result", "tool_use_id": "call_A", "content": "LAST\n", "incomplete": True},+ {"type": "tool_result", "tool_use_id": "call_B", "content": "FIRST\nLAST\n"})+ assert [(o["call_id"], o["status"], o["output"]) for o in out] == [+ ("call_A", "incomplete", "LAST\n"), ("call_B", "completed", "FIRST\nLAST\n")]diff --git a/runner/server.py b/runner/server.pyindex 804525cc..a21a5c7a 100644--- a/runner/server.py+++ b/runner/server.py@@ -2258,17 +2258,154 @@ def _codex_item_kind(it: dict) -> str:return _CAMEL.sub(lambda m: "_" + m.group(1).lower(), str(it.get("type") or "")).lower()-def _codex_tool_item(it: dict) -> list[dict]:+# A command's output comes from codex's own record of what the model was given, never from the+# command item's aggregatedOutput: codex drops a command's output printed before it opens the item+# (openai/codex#28207, open since 0.139.0; reproduced on 0.154.0, 2026-10-24). For+# `echo FIRST-LINE; sleep 3; echo LAST-LINE` the model got both lines, while the item's+# outputDelta and aggregatedOutput carried only LAST-LINE, and the record kept only that. The+# rollout file holds the same text the model saw, so reading it widens nothing.+#+# codex answers an exec_command or write_stdin call with a header (chunk id, wall time, whether the+# process exited or is still running, token count), then "Output:" and the output. The header is+# codex's own and is dropped; the output after it is kept exactly as the model saw it, codex's+# truncation notice included. An answer of any other shape is kept whole.+_CODEX_EXEC_HEAD = re.compile(r"\A((?:[A-Z][A-Za-z ]*: [^\n]*\n|Process (?:exited with code -?\d+|running with session ID \d+)\n)*)Output:\n")+_CODEX_RUNNING = re.compile(r"^Process running with session ID (\d+)$", re.M)+# How long a command's record may trail its item/completed: measured 1 ms ahead to 3 ms behind+# (four commands, 2026-10-24); the bound is far past that, and costs nothing unless a record is+# really missing.+_CODEX_RECORD_WAIT_S = 5.0+++def _codex_exec_answer(text: str) -> tuple[str, str | None]:+ """codex's answer to an exec_command or write_stdin call -> (the output in it, the session id+ when it says the process is still running)."""+ m = _CODEX_EXEC_HEAD.match(text)+ if not m:+ return text, None+ running = _CODEX_RUNNING.search(m.group(1))+ return text[m.end():], (running.group(1) if running else None)+++def _codex_output_text(out) -> str:+ """A function_call_output's `output` as text: a string, or content parts carrying text."""+ if isinstance(out, str):+ return out+ if isinstance(out, dict) and isinstance(out.get("content"), (str, list)):+ out = out["content"]+ if isinstance(out, str):+ return out+ if isinstance(out, list):+ return "".join(str(p.get("text") or "") for p in out if isinstance(p, dict))+ return json.dumps(out, default=str)+++class _CodexRollout:+ """codex's own record of one thread, <CODEX_HOME>/sessions/**/rollout-*-<thread id>.jsonl: one+ JSON line per item, among them every tool call the model made and the answer codex gave it.+ Read from where the last read stopped, whole lines only (codex may be mid-line)."""++ def __init__(self, cfg_dir: pathlib.Path, thread_id: str):+ self.cfg_dir, self.thread_id = cfg_dir, thread_id+ self.path: pathlib.Path | None = None+ self.offset = 0+ self.calls: list[tuple[str, str, dict]] = [] # (call_id, name, arguments), in the model's order+ self.answers: dict[str, str] = {} # call_id -> the answer's text++ def read(self) -> None:+ if self.path is None:+ hits = sorted((self.cfg_dir / "sessions").rglob(f"rollout-*-{self.thread_id}.jsonl")) if self.thread_id else []+ if not hits:+ return+ self.path = hits[-1]+ try:+ with open(self.path, "rb") as f:+ f.seek(self.offset)+ data = f.read()+ except OSError:+ return+ end = data.rfind(b"\n")+ if end < 0:+ return+ self.offset += end + 1+ for line in data[:end].splitlines():+ try:+ p = (json.loads(line) or {}).get("payload")+ except (ValueError, AttributeError):+ continue+ if not isinstance(p, dict) or not p.get("call_id"):+ continue+ cid = str(p["call_id"])+ if p.get("type") == "function_call":+ try:+ args = json.loads(p.get("arguments") or "{}")+ except ValueError:+ args = {}+ self.calls.append((cid, str(p.get("name") or ""), args if isinstance(args, dict) else {}))+ elif p.get("type") == "function_call_output":+ self.answers[cid] = _codex_output_text(p.get("output"))++ def command_output(self, call_id: str) -> tuple[str | None, bool]:+ """What the model was given as the output of the command it started with `call_id`+ -> (text, complete). The call's own answer, and while that says the process is still+ running, each later write_stdin answer for the same session, until one no longer says so.+ (None, False): no answer recorded for the call. (text, False): the session's answers stop+ short of the process's end."""+ first = self.answers.get(call_id)+ if first is None:+ return None, False+ text, running = _codex_exec_answer(first)+ if running is None:+ return text, True+ start = next((i for i, c in enumerate(self.calls) if c[0] == call_id), None)+ if start is None:+ return text, False+ parts = [text]+ for cid, name, args in self.calls[start + 1:]:+ if name != "write_stdin" or str(args.get("session_id")) != running:+ continue+ answer = self.answers.get(cid)+ if answer is None:+ break+ more, still = _codex_exec_answer(answer)+ parts.append(more)+ if still is None:+ return "".join(parts), True+ return "".join(parts), False+++def _codex_command_output(rollout: _CodexRollout | None, call_id: str,+ wait_s: float | None = None) -> tuple[str | None, bool]:+ """The record's command output for `call_id`, read again until it is complete or `wait_s`+ (default _CODEX_RECORD_WAIT_S) has passed: it may land a few ms after the item that announces+ the command."""+ if rollout is None:+ return None, False+ deadline = time.monotonic() + (_CODEX_RECORD_WAIT_S if wait_s is None else wait_s)+ while True:+ rollout.read()+ text, complete = rollout.command_output(call_id)+ if complete or time.monotonic() >= deadline:+ return text, complete+ time.sleep(0.02)+++def _codex_tool_item(it: dict, output: str | None = None, incomplete: bool = False) -> list[dict]:"""A completed codex tool item (command/file/mcp) -> canonical tool_use + tool_result events.Shared by the exec normalizer and the app-server driver (the `item` shape is the same, thetype spelling is not: see _codex_item_kind). A message or reasoning item is not a tool and- yields nothing here (its text streams as deltas)."""+ yields nothing here (its text streams as deltas).++ `output`: a command's output from codex's record (see _CodexRollout), in place of the item's+ own. `incomplete`: no complete record was found, so the output may lack part of what the+ command printed; the tool_result says so, and the response marks its item incomplete."""kind = _codex_item_kind(it)if kind in ("user_message", "agent_message", "reasoning"):return []if kind == "command_execution":tuid = it.get("id") or "cmd"- out = it.get("aggregated_output") or it.get("aggregatedOutput") or it.get("output") or ""+ out = output if output is not None else (+ it.get("aggregated_output") or it.get("aggregatedOutput") or it.get("output") or "")ec = it.get("exit_code", it.get("exitCode"))return [{"type": "assistant", "message": {"content": [@@ -2276,7 +2413,8 @@ def _codex_tool_item(it: dict) -> list[dict]:"input": {"command": it.get("command") or ""}}]}},{"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": tuid,- "is_error": bool(ec not in (0, None)), "content": str(out)}]}},+ "is_error": bool(ec not in (0, None)), "content": str(out),+ **({"incomplete": True} if incomplete else {})}]}},]if kind == "file_change":changes = it.get("changes") or []@@ -2361,7 +2499,14 @@ def _codex_to_claude(obj: dict, state: dict) -> list[dict]:return [{"type": "assistant", "message": {"content": [{"type": "thinking", "thinking": d}]}}] if d else []return [{"type": "assistant","message": {"content": [{"type": "thinking", "thinking": it.get("text") or ""}]}}]- return _codex_tool_item(it) # command_execution / file_change / mcp_tool_call / other+ if _codex_item_kind(it) == "command_execution":+ # `codex exec` names its items item_0, item_1, ..., not by the call id codex's record+ # keeps, so nothing ties this output to what the model was given, and it has the gap+ # the app-server's has (openai/codex#28207): it may lack what the command printed first.+ print(f"[codex] command {it.get('id') or 'cmd'}: exec mode has no record to read its output from; "+ "stored marked incomplete", flush=True)+ return _codex_tool_item(it, incomplete=True)+ return _codex_tool_item(it) # file_change / mcp_tool_call / otherif t == "turn.completed":return [{"type": "result", "subtype": "success", "is_error": False,"result": state.get("final", ""),@@ -12198,6 +12343,8 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, prompusage: dict = {}turn_status = Nonethread_id = None+ rollout: _CodexRollout | None = None+ incomplete = 0 # commands whose output no complete record backed (logged one by one above)id_init = id_thread = id_turn = Nonetry:id_init = send("initialize", {"clientInfo": {"name": "harness-runner", "title": "HarnessRouter", "version": "1"},@@ -12231,6 +12378,8 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, prompif thread_id:append({"type": "system", "subtype": "init", "session_id": thread_id, "model": model})rec["session_id"] = thread_id+ rollout = _CodexRollout(pathlib.Path(env.get("CODEX_HOME") or (pathlib.Path(env.get("HOME") or cwd) / ".codex")),+ thread_id)id_turn = send("turn/start", {"threadId": thread_id, "model": model,"approvalPolicy": _CODEX_APPROVAL, "input": [{"type": "text", "text": prompt}]})continue@@ -12255,7 +12404,17 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, prompappend({"type": "assistant", "message": {"content": [{"type": "thinking", "thinking": d}]}})elif method == "item/completed":it = p.get("item") or {}- for ev in _codex_tool_item(it): # messages and reasoning yield nothing: already streamed as deltas+ evs = None+ if _codex_item_kind(it) == "command_execution":+ # the output the model was given, from codex's record (see _CodexRollout)+ out, complete = _codex_command_output(rollout, str(it.get("id") or ""))+ if not complete:+ incomplete += 1+ print(f"[codex] command {it.get('id') or 'cmd'}: "+ f"{'no record of its output' if out is None else 'its output recorded only in part'} "+ f"within {_CODEX_RECORD_WAIT_S:g} s; stored marked incomplete", flush=True)+ evs = _codex_tool_item(it, output=out, incomplete=not complete)+ for ev in evs if evs is not None else _codex_tool_item(it): # messages and reasoning yield nothing: already streamed as deltasappend(ev)# The step budget, as _run_turn_bg counts it for `codex exec` (#471): codex has no# limit of its own, and this is the path the image runs codex on by default.@@ -12301,6 +12460,8 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, promp_kill_proc_tree(proc) # one turn per process — never reuseexcept Exception: # noqa: BLE001pass+ if incomplete:+ print(f"[codex] turn {turn_id}: {incomplete} command output(s) stored marked incomplete", flush=True)# A turn that produced a final agent answer SUCCEEDED from the caller's view — even if codex then# fumbles the turn close. gpt-5.5 refusals are the sharp case: the model returns a clean finaldiff --git a/runner/tests/test_codex_command_output.py b/runner/tests/test_codex_command_output.pynew file mode 100644index 00000000..3d78382d--- /dev/null+++ b/runner/tests/test_codex_command_output.py@@ -0,0 +1,235 @@+"""A codex command's stored output is what the model was given (openai/codex#28207).++codex drops a command's output printed before it opens the command item: for+`echo FIRST-LINE; sleep 3; echo LAST-LINE` the model got both lines, while the item's outputDelta+and aggregatedOutput carried only LAST-LINE, and the record kept only that (codex-cli 0.154.0,+reproduced on the test VM 2026-10-24). codex's own record of the thread, the rollout file, holds+the answer the model was given, so the output is read from there, by call id. A command whose+record never arrives is stored marked incomplete, never passed off as whole.++The record lines below are the shapes codex 0.154.0 wrote on the test VM.+"""+import json+import os+import pathlib+import sys+import threading+import time+import uuid++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import server as rs # noqa: E402+from server import _turns # noqa: E402++THREAD = "01a16c3d-9116-7920-bea4-edb0a4a4f7a8"+++def _answer(output: str, *, running: str | None = None, code: int = 0, tokens: int = 6) -> str:+ """codex's answer to an exec_command or write_stdin call, header and all."""+ state = f"Process running with session ID {running}" if running else f"Process exited with code {code}"+ return f"Chunk ID: 72e949\nWall time: 2.8587 seconds\n{state}\nOriginal token count: {tokens}\nOutput:\n{output}"+++def _call(call_id: str, name: str, args: dict) -> dict:+ return {"timestamp": "2026-10-24T04:49:01.000Z", "type": "response_item",+ "payload": {"type": "function_call", "name": name, "arguments": json.dumps(args), "call_id": call_id}}+++def _out(call_id: str, output: str) -> dict:+ return {"timestamp": "2026-10-24T04:49:02.319Z", "type": "response_item",+ "payload": {"type": "function_call_output", "call_id": call_id, "output": output}}+++def _rollout_file(codex_home: pathlib.Path, thread: str = THREAD) -> pathlib.Path:+ d = codex_home / "sessions" / "2026" / "10" / "24"+ d.mkdir(parents=True, exist_ok=True)+ return d / f"rollout-2026-10-24T04-48-56-{thread}.jsonl"+++def _write(path: pathlib.Path, *records: dict) -> None:+ with open(path, "a") as f:+ for r in records:+ f.write(json.dumps(r) + "\n")+++def test_the_output_is_the_answer_the_model_was_given(tmp_path):+ path = _rollout_file(tmp_path)+ _write(path, {"type": "session_meta", "payload": {"id": THREAD}},+ _call("call_A", "exec_command", {"cmd": "echo FIRST-LINE; sleep 3; echo LAST-LINE"}),+ _out("call_A", _answer("FIRST-LINE\nLAST-LINE\n")))+ ro = rs._CodexRollout(tmp_path, THREAD)+ assert rs._codex_command_output(ro, "call_A", wait_s=0) == ("FIRST-LINE\nLAST-LINE\n", True)+++def test_a_record_that_lands_after_the_item_is_waited_for(tmp_path):+ """The record trails item/completed by a few ms (measured); the same read is made again."""+ path = _rollout_file(tmp_path)+ _write(path, _call("call_A", "exec_command", {"cmd": "x"}))+ later = threading.Timer(0.3, _write, args=(path, _out("call_A", _answer("FIRST-LINE\nLAST-LINE\n"))))+ later.start()+ t0 = time.monotonic()+ got = rs._codex_command_output(rs._CodexRollout(tmp_path, THREAD), "call_A", wait_s=5)+ later.join()+ assert got == ("FIRST-LINE\nLAST-LINE\n", True)+ assert 0.25 < time.monotonic() - t0 < 2+++def test_a_record_that_never_lands_is_reported_missing(tmp_path):+ path = _rollout_file(tmp_path)+ _write(path, _call("call_A", "exec_command", {"cmd": "x"}))+ assert rs._codex_command_output(rs._CodexRollout(tmp_path, THREAD), "call_A", wait_s=0.2) == (None, False)+ # and no rollout at all+ assert rs._codex_command_output(rs._CodexRollout(tmp_path, "no-such-thread"), "call_A", wait_s=0.1) == (None, False)+++def test_two_calls_in_a_turn_each_get_their_own_output(tmp_path):+ path = _rollout_file(tmp_path)+ _write(path, _call("call_A", "exec_command", {"cmd": "a"}), _out("call_A", _answer("A-FIRST\nA-LAST\n")),+ _call("call_B", "exec_command", {"cmd": "b"}), _out("call_B", _answer("B-FIRST\nB-LAST\n")))+ ro = rs._CodexRollout(tmp_path, THREAD)+ assert rs._codex_command_output(ro, "call_B", wait_s=0) == ("B-FIRST\nB-LAST\n", True)+ assert rs._codex_command_output(ro, "call_A", wait_s=0) == ("A-FIRST\nA-LAST\n", True)+++def test_a_large_output_is_kept_as_codex_cut_it_for_the_model(tmp_path):+ """codex cut 169 KB to about 1 KB for the model, and says so in the output; that is the record."""+ cut = ("Warning: truncated output (original token count: 42228)\nBIG-START\n1\n2\n"+ "…42028 tokens truncated…\n29999\n30000\nBIG-END\n")+ path = _rollout_file(tmp_path)+ _write(path, _call("call_A", "exec_command", {"cmd": "seq"}), _out("call_A", _answer(cut, tokens=42228)))+ assert rs._codex_command_output(rs._CodexRollout(tmp_path, THREAD), "call_A", wait_s=0) == (cut, True)+++def test_a_polled_command_joins_the_answers_for_its_session(tmp_path):+ """A command that outlives its first wait: the model polls it with write_stdin, and each answer+ carries the next part. Another session's poll in between is not this command's."""+ path = _rollout_file(tmp_path)+ _write(path,+ _call("call_A", "exec_command", {"cmd": "echo P-FIRST; sleep 8; echo P-MID; sleep 8; echo P-LAST"}),+ _out("call_A", _answer("P-FIRST\n", running="28925")),+ _call("call_X", "write_stdin", {"session_id": 99, "chars": ""}),+ _out("call_X", _answer("OTHER\n", running="99")),+ _call("call_B", "write_stdin", {"session_id": 28925, "chars": ""}),+ _out("call_B", _answer("P-MID\n", running="28925")))+ ro = rs._CodexRollout(tmp_path, THREAD)+ assert rs._codex_command_output(ro, "call_A", wait_s=0.1) == ("P-FIRST\nP-MID\n", False)+ _write(path, _call("call_C", "write_stdin", {"session_id": 28925, "chars": ""}),+ _out("call_C", _answer("P-LAST\n")))+ assert rs._codex_command_output(ro, "call_A", wait_s=0) == ("P-FIRST\nP-MID\nP-LAST\n", True)+++def test_a_line_codex_is_still_writing_is_read_once_it_is_whole(tmp_path):+ path = _rollout_file(tmp_path)+ line = json.dumps(_out("call_A", _answer("FIRST-LINE\n")))+ _write(path, _call("call_A", "exec_command", {"cmd": "x"}))+ with open(path, "a") as f:+ f.write(line[:40])+ ro = rs._CodexRollout(tmp_path, THREAD)+ assert rs._codex_command_output(ro, "call_A", wait_s=0) == (None, False)+ with open(path, "a") as f:+ f.write(line[40:] + "\n")+ assert rs._codex_command_output(ro, "call_A", wait_s=0) == ("FIRST-LINE\n", True)+++def test_an_answer_of_another_shape_is_kept_whole():+ assert rs._codex_exec_answer("Exit code: 0\nhello\n") == ("Exit code: 0\nhello\n", None)+ assert rs._codex_output_text([{"type": "input_text", "text": "a"}, {"type": "input_text", "text": "b"}]) == "ab"+ assert rs._codex_output_text({"content": "c", "success": True}) == "c"+++def test_the_exec_path_marks_a_command_output_incomplete():+ """`codex exec` names its items item_0, item_1, ...: nothing ties the output to the record."""+ evs = rs._codex_to_claude({"type": "item.completed", "item": {+ "id": "item_2", "type": "command_execution", "command": "echo E-FIRST; sleep 3; echo E-LAST",+ "aggregated_output": "E-LAST\n", "exit_code": 0}}, {})+ res = evs[1]["message"]["content"][0]+ assert res["type"] == "tool_result" and res["content"] == "E-LAST\n" and res["incomplete"] is True+++_FAKE = '''+import json, os, pathlib, sys, threading, time+home = pathlib.Path(os.environ["CODEX_HOME"]) / "sessions" / "2026" / "10" / "24"+home.mkdir(parents=True, exist_ok=True)+rollout = home / "rollout-2026-10-24T04-48-56-th1.jsonl"+cmds = json.loads(os.environ["FAKE_CMDS"])+def out(o):+ print(json.dumps(o), flush=True)+def record(*recs):+ with open(rollout, "a") as f:+ for r in recs:+ f.write(json.dumps(r) + "\\n")+for line in sys.stdin:+ m = json.loads(line)+ meth, mid = m.get("method"), m.get("id")+ if meth == "initialize":+ out({"id": mid, "result": {}})+ elif meth in ("thread/start", "thread/resume"):+ out({"id": mid, "result": {"thread": {"id": "th1"}}})+ elif meth == "turn/start":+ out({"id": mid, "result": {"turn": {"id": "tu1"}}})+ for c in cmds:+ record({"type": "response_item", "payload": {"type": "function_call", "name": "exec_command",+ "arguments": json.dumps({"cmd": c["cmd"]}), "call_id": c["id"]}})+ out({"method": "item/started", "params": {"item": {"type": "commandExecution", "id": c["id"],+ "command": c["cmd"], "aggregatedOutput": None}}})+ out({"method": "item/commandExecution/outputDelta", "params": {"itemId": c["id"], "delta": c["seen_by_item"]}})+ answer = {"type": "response_item", "payload": {"type": "function_call_output", "call_id": c["id"],+ "output": "Chunk ID: 1\\nWall time: 3.0 seconds\\nProcess exited with code 0\\nOriginal token count: 4\\nOutput:\\n" + c["model_saw"]}}+ if c.get("record") == "late":+ threading.Timer(0.2, record, args=(answer,)).start()+ elif c.get("record") != "never":+ record(answer)+ out({"method": "item/completed", "params": {"item": {"type": "commandExecution", "id": c["id"],+ "command": c["cmd"], "aggregatedOutput": c["seen_by_item"], "exitCode": 0}}})+ time.sleep(0.4)+ out({"method": "item/agentMessage/delta", "params": {"delta": "DONE"}})+ out({"method": "turn/completed", "params": {"turn": {"status": "completed"}}})+'''+++def _turn(tmp_path, cmds: list[dict]) -> dict:+ """codex on the app-server path (the image's default) against a fake app-server that writes a+ rollout the way codex does and drops the first chunk from the item the way codex does."""+ bindir = tmp_path / "bin"+ bindir.mkdir()+ fake = bindir / "codex"+ fake.write_text(f"#!{sys.executable}\n" + _FAKE)+ fake.chmod(0o755)+ env = {**os.environ, "PATH": f"{bindir}:{os.environ.get('PATH', '')}",+ "CODEX_HOME": str(tmp_path / "codex-home"), "FAKE_CMDS": json.dumps(cmds)}+ turn_id = "codex-out-" + uuid.uuid4().hex+ _turns[turn_id] = {"status": "running", "events": [], "result": "", "done": False,+ "started": time.time(), "backend": "codex", "model": "m"}+ try:+ rs._run_codex_appserver_bg(turn_id, str(tmp_path), env, "m", "go", None, 30, None)+ return _turns[turn_id]+ finally:+ _turns.pop(turn_id, None)+++def _results(rec: dict) -> dict:+ return {b["tool_use_id"]: b for ev in rec["events"] if ev.get("type") == "user"+ for b in ev["message"]["content"] if b.get("type") == "tool_result"}+++def test_the_app_server_turn_stores_what_the_model_saw(tmp_path):+ rec = _turn(tmp_path, [+ {"id": "call_A", "cmd": "echo A-FIRST; sleep 2; echo A-LAST", "seen_by_item": "A-LAST\n",+ "model_saw": "A-FIRST\nA-LAST\n"},+ {"id": "call_B", "cmd": "echo B-FIRST; sleep 2; echo B-LAST", "seen_by_item": "B-LAST\n",+ "model_saw": "B-FIRST\nB-LAST\n", "record": "late"}])+ res = _results(rec)+ assert rec["status"] == "done"+ assert res["call_A"]["content"] == "A-FIRST\nA-LAST\n" and "incomplete" not in res["call_A"]+ assert res["call_B"]["content"] == "B-FIRST\nB-LAST\n" and "incomplete" not in res["call_B"]+++def test_a_command_with_no_record_is_stored_marked_incomplete(tmp_path, monkeypatch, capsys):+ monkeypatch.setattr(rs, "_CODEX_RECORD_WAIT_S", 0.3)+ rec = _turn(tmp_path, [{"id": "call_A", "cmd": "echo FIRST; sleep 3; echo LAST", "seen_by_item": "LAST\n",+ "model_saw": "FIRST\nLAST\n", "record": "never"}])+ res = _results(rec)["call_A"]+ assert res["incomplete"] is True and res["content"] == "LAST\n"+ log = capsys.readouterr().out+ assert "command call_A: no record of its output within 0.3 s; stored marked incomplete" in log+ assert "1 command output(s) stored marked incomplete" in logdiff --git a/runner/tests/test_generic_step_budget.py b/runner/tests/test_generic_step_budget.pyindex c2d6d6db..220c8904 100644--- a/runner/tests/test_generic_step_budget.py+++ b/runner/tests/test_generic_step_budget.py@@ -149,9 +149,16 @@ def test_the_stop_result_reports_incomplete_at_the_gateway_layer():_FAKE_APPSERVER = '''-import json, os, sys, time+import json, os, pathlib, sys, timedef out(o):print(json.dumps(o), flush=True)+# codex's own record of the thread, which the runner reads a command's output from+rollout = pathlib.Path(os.environ["CODEX_HOME"]) / "sessions" / "rollout-2026-10-24T00-00-00-th1.jsonl"+rollout.parent.mkdir(parents=True, exist_ok=True)+def record(call_id, output):+ with open(rollout, "a") as f:+ f.write(json.dumps({"type": "response_item", "payload": {"type": "function_call_output",+ "call_id": call_id, "output": output}}) + "\\n")for line in sys.stdin:m = json.loads(line)meth, mid = m.get("method"), m.get("id")@@ -165,6 +172,7 @@ for line in sys.stdin:# the model call that asked for the command is counted before the command runsout({"method": "thread/tokenUsage/updated", "params": {"tokenUsage": {"total": {"inputTokens": 100 * (i + 1), "outputTokens": 10 * (i + 1)}}}})+ record("c%d" % i, "ok")out({"method": "item/completed", "params": {"item": {"type": "commandExecution", "id": "c%d" % i, "command": "echo %d" % i,"aggregatedOutput": "ok", "exitCode": 0}}})@@ -182,7 +190,8 @@ def _appserver_turn(tmp_path, calls: int, max_turns):fake = bindir / "codex"fake.write_text(f"#!{sys.executable}\n" + _FAKE_APPSERVER)fake.chmod(0o755)- env = {**os.environ, "PATH": f"{bindir}:{os.environ.get('PATH', '')}", "FAKE_CALLS": str(calls)}+ env = {**os.environ, "PATH": f"{bindir}:{os.environ.get('PATH', '')}", "FAKE_CALLS": str(calls),+ "CODEX_HOME": str(tmp_path / "codex-home")}turn_id = "gen-appserver-" + uuid.uuid4().hex_turns[turn_id] = {"status": "running", "events": [], "result": "", "done": False,"started": time.time(), "backend": "codex", "model": "m"}