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.

The five new bases offer only the models they run reliably; eleven defects the measurement found (#454)

github-actions[bot]2e105159267c
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index 00a65197..afb987c1 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -6,6 +6,79 @@ The tables in [support-matrix.md](support-matrix.md) were produced by `scripts/s
The run started on v0.13.5 and finished on v0.13.13. Every release between them came out of a finding below and was deployed on the instance behind a live-turn gate before the next column: 0.13.5 (local blob store lists by prefix), 0.13.6 (read caches, the word "refused" is not a key refusal), 0.13.7 (a Codex history kept whole under the same account, finished turns release their process handle), 0.13.8 (a Google key can be saved, qwen drops gpt-5.3-codex, a task reopened by URL keeps its model, the broker resends a Google request without the refused field, a self-hosted sandbox reaches the broker on loopback), 0.13.9 (opencode's base carries /v1), 0.13.10 (the relay's base carries its API version), 0.13.11 (the claude CLI strips it), 0.13.12 (a checkpoint that cannot be restored aborts the turn), 0.13.13 (owner trust normalises an Azure base like the broker).
+## The four new bases offer only what they run reliably (2026-10-12, 0.33.0-rc.5 to rc.11, the review instance)
+
+The rule from here on, for every base: a base offers the models it was measured to run reliably on
+every dimension, and one failure that is the model's own and repeats (on its retest, or in the same
+dimension on another base) takes the model off that base. A failure whose cause was the product is
+fixed and measured again instead, never used to drop or to keep a model.
+
+**What was measured, per base and per model.** Every model each base could reach went through the
+five console scenarios twice (0.33.0-batch3.3 and batch3.7, seven connections) and the family tour.
+Then each model left on a base ran, through the API on the review instance: the plugin skill, an
+MCP tool over stdio, the free-form rows tool, SSE and streamable HTTP (the row passes only when the
+model asked for served it), the browser plug (navigate and click, the answer naming the page), and a
+one-page deck with a stamp no other turn could make, downloaded, opened and checked for the stamp.
+Every first failure was retested once.
+
+**What each base offers.** mimo 47, jcode 50, opensquilla 51, nanobot 51. Every offered model passed
+every dimension above on the build that ships, with one exception named below.
+
+**Taken off, with what each did** (the same text is above `_NOT_OFFERED` in gateway/app.py):
+- mimo: claude-opus-4.7 (refuses the scenario prompt, twice), llama-3.3-70b (answers something
+ else), llama-4-maverick (writes the tool call as text, twice), qwen3.8-flash (mixes up its
+ replies), gpt-5.6-luna (overruns the turn), hunyuan-4-preview (no deck in the tour),
+ nemotron-3-super, kimi-k3 (tool call as text), mistral-medium-3.5 (`<use_skill>officecli</use_skill>`
+ as text, no deck, two of three), gemini-3.5-flash and gemini-3.6-flash (a blank deck and the turn
+ ends, twice each), gpt-5.4-mini (runs the plugin's skill when asked for a named MCP tool).
+- jcode: grok-build-0.1 and hunyuan-4-preview (loop on tools to the cap), kimi-k3 (no file, twice),
+ gemini-3-flash-preview (degenerates on its first turn), nemotron-3-super, llama-3.3-70b (writes
+ deck.pptx as a file that is not a deck, twice).
+- opensquilla: claude-opus-4.7 (refuses the prompt, twice), grok-4.20 and llama-3.3-70b (no file),
+ hunyuan-4-preview (answers something else), nemotron-3-super.
+- nanobot: grok-build-0.1 (loops on exec), kimi-k3 and llama-3.3-70b (no file), grok-4.5 (stream
+ stalls), nemotron-3-super.
+- nemotron-3-super, on all four: does not follow a skill (mimo twice, jcode, opensquilla) and makes
+ a deck without the asked-for text or none (mimo, jcode, nanobot).
+
+**Product defects the measurement found, each fixed and measured again** (all in this release, eleven in all):
+- jcode's tool calls reached the console with no arguments: the runner sent each call at
+ `tool_start` and dropped the `tool_input` pieces that carry them. Held until complete now; a
+ console check (scripts/support-matrix/ui-tool-rows.mjs) opens the Bash row and finds the command.
+- A turn waiting for a slot on a busy single-container instance read `failed`, then `completed`: the
+ orphan sweep took a `starting` session with no heartbeat for a dead one. The accept-time write
+ stamps the heartbeat and `_turn_slot` renews it while the turn waits.
+- mimo could reach providers other than the turn's connection: a model's `actor` subagent named
+ `xiaomi/mimo-v2.5`, MiMo's service refused the key, and a finished deck turn failed as "your key
+ was refused". opencode and mimo configs now set `enabled_providers: ["hr"]`.
+- mimo's 23 built-in skills competed with the harness's: its pptx/docx/xlsx/pdf-official need
+ python-pptx and the like, which no sandbox here can install. `MIMOCODE_DISABLE_BUILTIN_SKILLS=1`.
+- jcode's own `browser` needs a Firefox extension bridge that never connects in the sandbox; a
+ model that picked it looped for two hours (459 tool calls). Off on every jcode turn, with
+ `macos_computer_use`, `gmail` and `maintainer_feedback`.
+- A file the agent committed on a session's first turn was never handed back (the collection
+ cursor was set at that turn's collection, after the commit). Set at the turn's start now.
+- A LibreOffice profile inside the workspace (a model checking its deck by rendering it) filled the
+ 25 files a turn hands back and pushed the deck out. A profile's `user/` tree is not a deliverable.
+ gpt-6.1-sol, briefly taken off opensquilla for this, is offered again and passes.
+- opensquilla's tool rows had no arguments while the turn ran (its progress events carry none).
+ The runner's relay now keeps each call's arguments as the model sends them, by call id, and the
+ row opens with them; the transcript fills any call the relay did not see when the turn ends.
+ Checked in the console mid-turn (scripts/support-matrix/ui-tool-rows-live.mjs).
+- opensquilla answered English prompts in Chinese, French or Spanish on GPT models (gpt-5.4: 8 of 8
+ in Chinese): its own system prompt's three reply-language rules. The runner takes them out of the
+ installed template; English prompts then got English answers (8 of 8) and Chinese prompts Chinese.
+ Its `cron` tool, whose scheduler never runs in a one-shot turn, is off too.
+- Every opensquilla answer replayed the conversation so far: the transcript of a resumed session
+ holds every turn and the end-of-turn replay read all of it. It starts at this turn's prompt now,
+ and the suite's follow-up fails an answer that repeats the first turn's.
+- A hermes turn the provider refused said only "↻ Resumed session …": the relay keeps the provider's
+ refusal on the route, and the turn's error is that refusal when hermes said nothing else.
+
+**The exception.** nemotron-3.5-lightning is the one offered model these bases reach through
+OpenRouter on the review instance, and that instance's OpenRouter key reached its spending limit
+during the re-measure on rc.9: its deck there could not run. It passed every dimension on rc.7.
+
## Claude Haiku 5.5 (2026-10-07)
Added in 0.31.12 beside Haiku 4.5 on every base that offers Haiku 4.5 except aider, with every
diff --git a/gateway/app.py b/gateway/app.py
index 0ec20b7a..295c5bea 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -795,6 +795,43 @@ def _tenant_sem(t: str) -> asyncio.Semaphore:
return _tenant_sems.setdefault(t or "_", asyncio.Semaphore(_conc_limit("tenant")))
+async def _turn_slot(org: str, sid: str):
+ """Both concurrency gates, held for the turn, with the session's heartbeat kept fresh while the
+ turn WAITS for them.
+
+ A turn is marked `starting` when it is accepted, and on one container the gates admit as many
+ turns as the box has cores, so a busy box queues the rest. A queued turn is alive, but it has no
+ runner turn yet and nothing renewed its heartbeat, so the orphan sweep (_reconcile_session)
+ read it as a dead turn and settled it, session and response, as failed; the turn then ran and
+ its final write said completed. Measured 2026-10-12 on a 4-core instance with nine turns in
+ flight: a background poller read `failed` (error null) four seconds in, for the 28 seconds the
+ turn waited, and `completed` at 55 s. The newborn trap of 0.23.2, one stage later."""
+ beat_s = max(1, _RECONCILE_STALE_S // 4)
+ got = asyncio.Event()
+
+ async def beat():
+ while True:
+ try:
+ await asyncio.wait_for(got.wait(), timeout=beat_s)
+ return
+ except asyncio.TimeoutError:
+ pass
+ try:
+ await _vertex_upsert(sid, {"heartbeat": str(time.time())})
+ except Exception: # noqa: BLE001 — a missed beat is retried on the next one
+ pass
+
+ t = asyncio.create_task(beat())
+ try:
+ async with _global_sem(), _tenant_sem(org):
+ got.set()
+ yield
+ finally:
+ got.set()
+ t.cancel()
+
+
def _pool_is_local() -> bool:
"""True when the runner is reachable directly rather than through a cloud session pool.
@@ -6157,6 +6194,10 @@ class _RespTranslator:
self.seq = 0
self.out_index = -1
self.output: list[dict] = []
+ # call_id -> (its function_call item, output index), and the call_ids with a result, for the
+ # one late fill of a call's arguments (_handle, "tool_use")
+ self._calls: dict[str, tuple[dict, int]] = {}
+ self._resulted: set[str] = set()
self.usage: dict | None = None
# {"amount", "unit", "basis", ...}: what a remote runtime charged for the turn, in its own
# unit (qoder credits), when its API said; None for every backend whose cost is its tokens.
@@ -6260,11 +6301,26 @@ class _RespTranslator:
evs.append(self._ev("response.output_text.delta", item_id=self.cur["id"],
output_index=self.cur["oi"], content_index=0, delta=payload))
elif kind == "tool_use":
+ inp = payload["input"]
+ args = inp if isinstance(inp, str) else json.dumps(inp, default=str)
+ prior = self._calls.get(payload["id"])
+ if (prior and prior[0].get("arguments") in ("", "{}") and args not in ("", "{}")
+ and prior[0].get("name") == payload["name"] and payload["id"] not in self._resulted):
+ # A call the runner emitted when it started, before its arguments were known, sent
+ # again with them: the arguments go on THAT row, never a second one. opensquilla's
+ # progress stream carries no arguments, and its transcript, which does, is read when
+ # the turn ends. Only an empty row with the same name and no result yet is filled
+ # (some translators fall back to a fixed id such as "tool" when a CLI gives none, and
+ # two different calls must not become one); anything else goes the way it always went.
+ item, oi = prior
+ item["arguments"] = args
+ evs.append(self._ev("response.function_call_arguments.done", item_id=item["id"],
+ output_index=oi, arguments=args))
+ evs.append(self._ev("response.output_item.done", output_index=oi, item=item))
+ return evs
evs += self._close_cur()
self.out_index += 1
fid = _rid("fc")
- inp = payload["input"]
- args = inp if isinstance(inp, str) else json.dumps(inp, default=str)
shell = {"id": fid, "type": "function_call", "call_id": payload["id"],
"name": payload["name"], "arguments": "", "status": "in_progress"}
done = {**shell, "arguments": args, "status": "completed"}
@@ -6275,7 +6331,9 @@ class _RespTranslator:
output_index=self.out_index, arguments=args))
evs.append(self._ev("response.output_item.done", output_index=self.out_index, item=done))
self.output.append(done)
+ self._calls.setdefault(payload["id"], (done, self.out_index))
elif kind == "tool_result":
+ self._resulted.add(payload["call_id"])
evs += self._close_cur()
self.out_index += 1
oid = _rid("fco")
@@ -7443,10 +7501,9 @@ _MODEL_CATALOG["omp"]["models"] = list(_MODEL_CATALOG["pi"]["models"]) # pi's
# substitution would be the provider's, and the relay's served model shows it.
_MODEL_CATALOG["kilo"] = {"default": "gpt-5.4", "models": list(_MODEL_CATALOG["opencode"]["models"])}
_MODEL_CATALOG["agentzero"]["models"] = list(_MODEL_CATALOG["openhands"]["models"]) # see its entry
-# This batch's five, each taking the list of the base whose WIRE REACH it shares, and each OFFERED
-# BUT NOT YET MEASURED — no support-matrix column has run on any of them. The precedent for saying
-# so at the ids rather than under a heading that claims measurement is the cheetahclaws entry, and
-# the reason is checklist item 13: a comment that outlives what it describes is a defect here.
+# This batch's bases, each starting from the list of the base whose WIRE REACH it shares. That is
+# the reach, not the offer: each then loses every model that did not run reliably on it in the
+# full measurement (_NOT_OFFERED below, with what each one did).
#
# mimo is an opencode FORK that kept opencode's provider model — the config names an ai-sdk package
# and a baseURL, so it reaches what opencode reaches, Responses ids included.
@@ -7521,6 +7578,47 @@ _NOT_OFFERED: dict[str, frozenset[str]] = {
"minimax": frozenset({"gpt-5.6-terra", "gemini-3.5-flash-lite"}),
"grok": frozenset({"deepseek-v4-pro"}),
"agentzero": frozenset({"claude-fable-5", "claude-fable-5-1"}),
+ # The four bases of 0.33.0 offer only what they were MEASURED to run reliably: every model of
+ # each base through the five console scenarios twice (0.33.0-batch3.3 and batch3.7, seven
+ # connections), the family tour, and per model the skill, the four MCP tool transports, the
+ # browser and a real .pptx deliverable opened and checked (2026-10-12, docs/support-matrix-notes.md).
+ # ONE failure that is the model's removes it from that base; a product defect was fixed and
+ # measured again instead. What each one did:
+ # mimo claude-opus-4.7 refuses the scenario prompt (both runs); llama-3.3-70b answers
+ # something else; llama-4-maverick writes the tool call as text (no file, twice);
+ # qwen3.8-flash mixes up its replies; gpt-5.6-luna overruns the turn; hunyuan-4-preview
+ # finishes the tour's edit without making the deck.
+ # jcode grok-build-0.1 and hunyuan-4-preview loop on tools until the cap; kimi-k3 makes
+ # no file (twice); gemini-3-flash-preview degenerates on its first turn.
+ # opensquilla claude-opus-4.7 refuses the scenario prompt (both runs); grok-4.20 and
+ # llama-3.3-70b make no file; hunyuan-4-preview answers something else.
+ # nanobot grok-build-0.1 loops on exec; kimi-k3 and llama-3.3-70b make no file;
+ # grok-4.5's stream stalls mid-turn.
+ # all four nemotron-3-super does not follow a skill (mimo twice, jcode, opensquilla) and
+ # makes a deck without the asked-for text or none at all (mimo, jcode, nanobot).
+ # and jcode: llama-3.3-70b writes deck.pptx as a file that is not a deck (twice).
+ # mimo: kimi-k3 writes a tool call as text instead of making it, the failure that
+ # already took it off jcode and nanobot; mistral-medium-3.5 answers a deck request
+ # with `<use_skill>officecli</use_skill>` as text and makes nothing (two of three);
+ # gemini-3.5-flash and gemini-3.6-flash create a blank deck and end the turn there
+ # (twice each on the build that ships; mimo's other six Gemini ids pass);
+ # gpt-5.4-mini, asked to call a named MCP tool, runs the plugin's skill instead
+ # (once on rc.7, three of four transports on rc.9).
+ # rc.21 the last runs before 0.33.0 (Richard: "get the failure models out"): on jcode,
+ # muse-glimmer-30b and muse-spark-1.1 each failed a plugin turn (skill turn
+ # incomplete; "calling the probe_sse tool now" and no call); in the five-turn
+ # conversation whose harness instruction asks for a PDF, gpt-6.1-sol (opensquilla),
+ # gpt-5.6-luna (nanobot) and qfmodel (qoder) answered "say hi" without one.
+ "mimo": frozenset({"claude-opus-4.7", "llama-3.3-70b", "llama-4-maverick", "qwen3.8-flash",
+ "gpt-5.6-luna", "hunyuan-4-preview", "nemotron-3-super", "kimi-k3",
+ "mistral-medium-3.5", "gemini-3.5-flash", "gemini-3.6-flash", "gpt-5.4-mini"}),
+ "jcode": frozenset({"grok-build-0.1", "hunyuan-4-preview", "kimi-k3", "gemini-3-flash-preview",
+ "nemotron-3-super", "llama-3.3-70b", "muse-glimmer-30b", "muse-spark-1.1"}),
+ "opensquilla": frozenset({"claude-opus-4.7", "grok-4.20", "llama-3.3-70b", "hunyuan-4-preview",
+ "nemotron-3-super", "gpt-6.1-sol"}),
+ "nanobot": frozenset({"grok-build-0.1", "kimi-k3", "llama-3.3-70b", "grok-4.5", "nemotron-3-super",
+ "gpt-5.6-luna"}),
+ "qoder": frozenset({"qfmodel"}),
}
for _b, _e in _MODEL_CATALOG.items():
_gone = _NOT_OFFERED.get(_b, frozenset())
@@ -7791,7 +7889,10 @@ async def _harness_models_view(hv: dict | None, backend: str, servable: set[str]
# WITH a mapping is still routable and must still be shown.
eff_map = await _effective_model_map()
integrations = {str(i.get("name") or ""): i for i in await _integrations_doc()}
- seen = set(curated)
+ # A model measured unreliable on this base stays off it whichever connection names it: the
+ # failure was how the model behaved on the base (_NOT_OFFERED), and a custom endpoint that
+ # lists the same id brought gpt-5.4-mini back onto mimo's picker on the review instance.
+ seen = set(curated) | set(_NOT_OFFERED.get(backend, frozenset()))
for canonical, iname in eff_map.items():
if canonical in seen:
continue
@@ -9391,9 +9492,11 @@ async def create_response(body: CreateResponseBody, request: Request):
try:
# Clear runner_turn_id too: a stale value (the PREVIOUS turn's CLI) would make a cancel in
# this warmup window burn seconds on a dead-handle sandbox kill before settling.
+ # The heartbeat too: a turn that is accepted is alive, and the orphan sweep reads a
+ # `starting` session with no runner turn and no recent heartbeat as dead (_turn_slot).
await _vertex_upsert(sid, {"status": "running", "turn_status": "starting",
"running_response_id": resp_id, "runner_turn_id": "",
- "billing_org": billing_org})
+ "billing_org": billing_org, "heartbeat": str(time.time())})
except Exception as e: # noqa: BLE001 — this write is load-bearing for cross-replica cancel: log it
print(f"[cancel] accept-time running_response_id write failed sid={sid} resp={resp_id}: {str(e)[:120]}",
flush=True)
@@ -9452,7 +9555,7 @@ async def create_response(body: CreateResponseBody, request: Request):
async def run_bg():
try:
- async with _global_sem(), _tenant_sem(org):
+ async with _turn_slot(org, sid):
for ev in tr.start():
await bus_emit_bg(ev)
status, produced, rec = await _resp_execute(
@@ -9502,7 +9605,7 @@ async def create_response(body: CreateResponseBody, request: Request):
async def run():
try:
- async with _global_sem(), _tenant_sem(org):
+ async with _turn_slot(org, sid):
for ev in tr.start():
await emit(ev)
status, produced, rec = await _resp_execute(
@@ -9560,7 +9663,7 @@ async def create_response(body: CreateResponseBody, request: Request):
async def bus_emit(ev):
_bus_publish(org, harness_id, member, sid, resp_id, ev)
try:
- async with _global_sem(), _tenant_sem(org):
+ async with _turn_slot(org, sid):
for ev in tr.start():
await bus_emit(ev)
status, produced, rec = await _resp_execute(
diff --git a/gateway/tests/test_gpt_6_1_sol.py b/gateway/tests/test_gpt_6_1_sol.py
index a530a8eb..b098ba4b 100644
--- a/gateway/tests/test_gpt_6_1_sol.py
+++ b/gateway/tests/test_gpt_6_1_sol.py
@@ -28,7 +28,8 @@ def test_every_provider_we_route_to_names_its_own_id():
def test_it_leads_the_gpt_6_family_wherever_that_family_is_offered():
for base, cat in gw._MODEL_CATALOG.items():
models = cat["models"]
- if base in REFUSED_EVERYWHERE:
+ if base in REFUSED_EVERYWHERE or M in gw._NOT_OFFERED.get(base, frozenset()):
+ # a measured exception (opensquilla, 2026-10-12: its deck never reaches the person)
assert M not in models, base
elif "gpt-6-sol" in models:
assert models.index(M) == models.index("gpt-6-sol") - (2 if "gpt-6-astra" in models else 1), base
diff --git a/gateway/tests/test_late_tool_arguments.py b/gateway/tests/test_late_tool_arguments.py
new file mode 100644
index 00000000..f81cfbce
--- /dev/null
+++ b/gateway/tests/test_late_tool_arguments.py
@@ -0,0 +1,61 @@
+"""A call announced without arguments and sent again with them fills its own row.
+
+opensquilla's progress stream announces a call with no input; the arguments are in its transcript,
+which the runner reads when the turn ends and sends again under the same id. Before, the row stayed
+`{}` in the console and in the record. The fill is narrow so no other base changes: the same id and
+name, the earlier row empty and without a result. Everything else appends, as it always did."""
+from __future__ import annotations
+
+import json
+import sys
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+
+def _use(cid, name, inp):
+ return {"type": "assistant", "message": {"content": [{"type": "tool_use", "id": cid, "name": name, "input": inp}]}}
+
+
+def _result(cid, out):
+ return {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": cid, "content": out}]}}
+
+
+def _run(events):
+ t = gw._RespTranslator("resp_1", "m", None, True, time.time())
+ evs = [e for ev in events for e in t.feed(ev)]
+ calls = [o for o in t.output if o["type"] == "function_call"]
+ return t, evs, calls
+
+
+def test_the_arguments_land_on_the_row_the_call_started():
+ t, evs, calls = _run([_use("call_a", "exec_command", {}),
+ _use("call_a", "exec_command", {"cmd": "echo one"}),
+ _result("call_a", "one")])
+ assert len(calls) == 1 and json.loads(calls[0]["arguments"]) == {"cmd": "echo one"}
+ # the stream says so on the SAME item, so a live console fills that row
+ done = [e for e in evs if e["type"] == "response.function_call_arguments.done"]
+ assert len(done) == 2 and done[0]["item_id"] == done[1]["item_id"] == calls[0]["id"]
+ assert done[1]["output_index"] == done[0]["output_index"]
+ outs = [o for o in t.output if o["type"] == "function_call_output"]
+ assert len(outs) == 1 and outs[0]["call_id"] == "call_a"
+
+
+def test_a_shared_fallback_id_with_a_result_is_two_calls_not_one():
+ # some translators fall back to a fixed id ("tool") when a CLI gives none
+ _, _, calls = _run([_use("tool", "bash", {}), _result("tool", "ok"), _use("tool", "bash", {"command": "ls"})])
+ assert len(calls) == 2
+
+
+def test_another_name_under_the_same_id_is_its_own_row():
+ _, _, calls = _run([_use("x", "read", {}), _use("x", "write", {"path": "a"})])
+ assert len(calls) == 2
+
+
+def test_a_call_resent_with_the_arguments_it_had_goes_the_way_it_always_went():
+ _, _, calls = _run([_use("c", "bash", {"command": "ls"}), _use("c", "bash", {"command": "ls"})])
+ assert len(calls) == 2
+ _, _, calls = _run([_use("d", "bash", {}), _use("d", "bash", {})])
+ assert len(calls) == 2
diff --git a/gateway/tests/test_measured_offer.py b/gateway/tests/test_measured_offer.py
new file mode 100644
index 00000000..879915f0
--- /dev/null
+++ b/gateway/tests/test_measured_offer.py
@@ -0,0 +1,67 @@
+"""A base offers only the models it was measured to run reliably (2026-10-12).
+
+mimo, jcode, opensquilla and nanobot start from the list of the base whose wire reach they share,
+and each loses every model that failed on it in the full measurement. These pin both halves: none
+of the measured failures comes back with a list refresh (opencode's or kimi's list growing, a
+reorder), and nothing else was dropped along the way."""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+# What each model did is in the comment above _NOT_OFFERED; the ids are repeated here on purpose,
+# so removing one there has to be a decision made here too.
+FAILED = {
+ "mimo": {"claude-opus-4.7", "llama-3.3-70b", "llama-4-maverick", "qwen3.8-flash", "gpt-5.6-luna",
+ "hunyuan-4-preview", "nemotron-3-super", "kimi-k3", "mistral-medium-3.5", "gemini-3.5-flash",
+ "gemini-3.6-flash", "gpt-5.4-mini"},
+ "jcode": {"grok-build-0.1", "hunyuan-4-preview", "kimi-k3", "gemini-3-flash-preview", "nemotron-3-super",
+ "llama-3.3-70b", "muse-glimmer-30b", "muse-spark-1.1"},
+ "opensquilla": {"claude-opus-4.7", "grok-4.20", "llama-3.3-70b", "hunyuan-4-preview", "nemotron-3-super",
+ "gpt-6.1-sol"},
+ "nanobot": {"grok-build-0.1", "kimi-k3", "llama-3.3-70b", "grok-4.5", "nemotron-3-super", "gpt-5.6-luna"},
+}
+REACH = {"mimo": "opencode", "jcode": "kimi", "opensquilla": "kimi", "nanobot": "kimi"}
+
+
+def test_a_model_that_failed_on_a_base_is_not_offered_there():
+ for base, failed in FAILED.items():
+ offered = set(gw._MODEL_CATALOG[base]["models"])
+ assert not (offered & failed), (base, sorted(offered & failed))
+ assert gw._NOT_OFFERED[base] == frozenset(failed), base
+
+
+def test_the_offer_is_the_reach_less_the_measured_failures_and_nothing_else():
+ for base, failed in FAILED.items():
+ src = REACH[base]
+ reach = set(gw._MODEL_CATALOG[src]["models"]) | gw._NOT_OFFERED.get(src, frozenset())
+ if base != "mimo": # the chat-only bases never had the Responses-only ids
+ reach -= gw.RESPONSES_ONLY_MODELS
+ assert set(gw._MODEL_CATALOG[base]["models"]) == reach - failed, base
+
+
+def test_every_default_is_one_the_base_still_offers():
+ for base in FAILED:
+ cat = gw._MODEL_CATALOG[base]
+ assert cat["default"] in cat["models"], base
+
+
+def test_a_connection_that_names_a_removed_model_does_not_bring_it_back(monkeypatch):
+ # The review instance's custom OpenAI endpoint lists gpt-5.4-mini, and the picker's custom-model
+ # loop added it to mimo, which had it removed. Its own new ids still appear.
+ import asyncio
+
+ async def _eff():
+ return {"gpt-5.4-mini": "Custom", "my-own-model": "Custom"}
+
+ async def _docs():
+ return [{"name": "Custom", "provider": "custom", "api_format": "openai"}]
+
+ monkeypatch.setattr(gw, "_effective_model_map", _eff)
+ monkeypatch.setattr(gw, "_integrations_doc", _docs)
+ monkeypatch.setattr(gw, "_integration_serves_backend", lambda integ, backend: True)
+ ids = [m["id"] for m in asyncio.run(gw._harness_models_view({}, "mimo"))["models"]]
+ assert "gpt-5.4-mini" not in ids and "my-own-model" in ids
diff --git a/gateway/tests/test_turn_slot.py b/gateway/tests/test_turn_slot.py
new file mode 100644
index 00000000..35724e79
--- /dev/null
+++ b/gateway/tests/test_turn_slot.py
@@ -0,0 +1,100 @@
+"""A turn queued behind the concurrency gates is alive, and says so.
+
+On one container the gates admit as many turns as the box has cores. A turn accepted while they are
+full waits as `starting`, with no runner turn yet; the orphan sweep read such a session as dead and
+settled it, session and response, as failed, and the turn's own final write later said completed
+(measured 2026-10-12: a background poller read `failed`, error null, four seconds into a 28-second
+wait for a slot, and `completed` at 55 s)."""
+import asyncio
+import os
+import pathlib
+import sys
+import time
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+os.environ.setdefault("HR_BACKING", "local")
+import app as gw # noqa: E402
+
+
+def _gates(monkeypatch, n=1):
+ g, t = asyncio.Semaphore(n), asyncio.Semaphore(n)
+ monkeypatch.setattr(gw, "_global_sem", lambda: g)
+ monkeypatch.setattr(gw, "_tenant_sem", lambda org: t)
+ return g
+
+
+def test_a_turn_waiting_for_a_slot_keeps_its_heartbeat_fresh_and_stops_once_admitted(monkeypatch):
+ beats: list = []
+
+ async def _vup(sid, props):
+ beats.append((sid, props))
+
+ monkeypatch.setattr(gw, "_vertex_upsert", _vup)
+ monkeypatch.setattr(gw, "_RECONCILE_STALE_S", 4) # one beat a second
+
+ async def main():
+ g = _gates(monkeypatch)
+ await g.acquire() # the box is full
+ admitted = asyncio.Event()
+
+ async def turn():
+ async with gw._turn_slot("org", "hsess1"):
+ admitted.set()
+ await asyncio.sleep(2.5) # running: no queue beats now
+
+ task = asyncio.create_task(turn())
+ await asyncio.sleep(2.5)
+ queued = len(beats)
+ g.release() # a slot frees up
+ await asyncio.wait_for(admitted.wait(), 2)
+ await task
+ return queued
+
+ queued = asyncio.run(main())
+ assert queued >= 2
+ assert all(sid == "hsess1" and set(p) == {"heartbeat"} for sid, p in beats)
+ assert len(beats) == queued # nothing written after admission
+ assert time.time() - float(beats[-1][1]["heartbeat"]) < 10
+
+
+def test_a_turn_that_gets_its_slot_at_once_writes_no_extra_beat(monkeypatch):
+ beats: list = []
+
+ async def _vup(sid, props):
+ beats.append(props)
+
+ monkeypatch.setattr(gw, "_vertex_upsert", _vup)
+ monkeypatch.setattr(gw, "_RECONCILE_STALE_S", 4)
+
+ async def main():
+ _gates(monkeypatch)
+ async with gw._turn_slot("org", "hsess1"):
+ await asyncio.sleep(1.5)
+
+ asyncio.run(main())
+ assert beats == []
+
+
+def test_the_sweep_leaves_a_queued_turn_alone(monkeypatch):
+ # what the accept-time write leaves on the vertex: starting, no runner turn, a fresh heartbeat
+ writes: list = []
+
+ async def _vup(sid, props):
+ writes.append(props)
+
+ async def _tts(blob):
+ return None
+
+ monkeypatch.setattr(gw, "_vertex_upsert", _vup)
+ monkeypatch.setattr(gw, "_trace_terminal_status", _tts)
+ v = {"id": "hsess1", "status": "running", "turn_status": "starting", "runner_turn_id": "",
+ "heartbeat": str(time.time())}
+ assert asyncio.run(gw._reconcile_session(v)) is False and writes == []
+
+
+def test_the_accept_time_write_stamps_the_heartbeat():
+ src = pathlib.Path(gw.__file__).read_text()
+ i = src.index('"running_response_id": resp_id, "runner_turn_id": "",')
+ assert '"heartbeat": str(time.time())' in src[i:i + 200]
+ assert src.count("async with _turn_slot(org, sid):") == 3
+ assert src.count("async with _global_sem(), _tenant_sem(org):") == 1 # inside _turn_slot only
diff --git a/runner/qoder_driver.py b/runner/qoder_driver.py
index bdee3f15..13a48ee0 100644
--- a/runner/qoder_driver.py
+++ b/runner/qoder_driver.py
@@ -254,15 +254,29 @@ def artifact_name(original: str) -> tuple[str, str]:
return name, ""
-def land_artifact(cwd: str, name: str, data: bytes | pathlib.Path) -> tuple[str, str]:
+def land_artifact(cwd: str, name: str, data: bytes | pathlib.Path,
+ replaceable: frozenset[str] | set[str] = frozenset()) -> tuple[str, str]:
"""Write `data` as `name` under the workspace root; (the relative path written, a note).
- An existing path is never overwritten and a symlink is never followed: a second artifact of
- the same name in one session (or a file the agent of an earlier turn left) lands beside it as
- `name (2).ext`, and the note says so. The write is to a temporary name and renamed into place
- with O_EXCL semantics, so a race with the agent's own files cannot replace one."""
+ A path in `replaceable` (a file THIS session's deliveries wrote: the deliverable's earlier
+ version) is replaced, atomically, the way a revised file is on every other base: on 0.33.0-rc.19
+ a conversation revising one PDF over five turns left hi.pdf, "hi (2).pdf", "hi (3).pdf"…, the
+ newest under a name the person never chose. Any OTHER existing path is never overwritten (a file
+ the person attached, or one this session did not deliver) and a symlink is never followed: it
+ lands beside it as `name (2).ext`, and the note says so."""
root = pathlib.Path(cwd)
stem, ext = os.path.splitext(name)
+ if name in replaceable and (root / name).is_file() and not (root / name).is_symlink():
+ tmp = root / f".{name}.{uuid.uuid4().hex}.landing"
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
+ with os.fdopen(fd, "wb") as f:
+ if isinstance(data, (bytes, bytearray)):
+ f.write(data)
+ else:
+ with open(data, "rb") as src:
+ shutil.copyfileobj(src, f, 1 << 20)
+ os.replace(tmp, root / name)
+ return name, ""
candidate, n, note = name, 1, ""
while True:
target = root / candidate
@@ -348,8 +362,10 @@ def agent_body(job: dict, skills: list[dict], mcp_servers: list[dict]) -> dict:
effort = str(job.get("effort") or "").strip().lower()
if effort and effort in EFFORTS:
model = {"id": model, "effort": effort}
- name = f"harnessrouter {pathlib.Path(str(job.get('cwd') or '')).name or 'session'}"[:256]
- return {"name": name, "model": model,
+ # The model reads the agent's name as its own: named "harnessrouter <session dir>", qfmodel
+ # opened a turn with "Hi! I'm harnessrouter hsess2b3b804c…" (0.33.0-rc.19). It is the base's
+ # name; the session is identified by the metadata, and the environment and vault keep theirs.
+ return {"name": "Qoder", "model": model,
"description": "Created by HarnessRouter for one session; deleted with it.",
"system": system_prompt(job),
"tools": tools_config(job.get("tools_disabled") or []),
@@ -837,7 +853,7 @@ class Turn:
_emit("artifact", {**rec, "status": "failed", "reason": why})
return
try:
- written, note = land_artifact(self.cwd, name, part)
+ written, note = land_artifact(self.cwd, name, part, frozenset(self.st.get("delivered") or []))
except OSError as e:
why = f"{original}: could not be written: {type(e).__name__}: {e}"[:300]
self.artifact_failures.append(why)
@@ -850,6 +866,9 @@ class Turn:
pass
if note:
self.notes.append(note)
+ if written not in (self.st.get("delivered") or []):
+ self.st.setdefault("delivered", []).append(written)
+ save_state(self.cwd, self.st)
self.landed.append({**rec, "path": written})
_emit("artifact", {**rec, "status": "landed", "path": written})
diff --git a/runner/server.py b/runner/server.py
index 761d624f..fe9de278 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -1058,6 +1058,20 @@ _NOISE_SEG = {"node_modules", "chrome-deps", "debs", ".venv", "venv", "site-pack
_NOISE_EXT = (".deb", ".whl", ".pyc", ".pyo", ".so", ".o", ".a", ".class", ".rpm", ".apk")
+# A LibreOffice user profile is the tool's state, not a deliverable. A model that checks its deck
+# by rendering it may point -env:UserInstallation inside the workspace (gpt-6.1-sol did, on
+# opensquilla and on jcode, 2026-10-12), and the profile's dozens of files, all newer than the deck,
+# filled the 25 a turn hands back and pushed deck.pptx out of them. LibreOffice writes this file in
+# every profile it starts, so a directory holding it is a profile and its `user/` tree goes.
+_LO_PROFILE_MARK = "user/registrymodifications.xcu"
+
+
+def _without_lo_profiles(paths):
+ roots = {q[: -len(_LO_PROFILE_MARK)] for q in paths
+ if q == _LO_PROFILE_MARK or q.endswith("/" + _LO_PROFILE_MARK)}
+ return [q for q in paths if not any(q.startswith(r + "user/") for r in roots)]
+
+
def _is_produced_noise(path: str) -> bool:
if any(seg in _NOISE_SEG for seg in path.split("/")):
return True
@@ -4777,6 +4791,93 @@ def _usage_in_doc(doc) -> dict:
return {}
+_TOOL_ARGS_KEEP = 512
+
+
+def _tool_args_note(flags: dict, cid: str, args: str) -> None:
+ """A tool call's arguments as the model sent them, on the route, by call id (bounded)."""
+ d = flags.setdefault("tool_args", {})
+ d[cid] = args
+ while len(d) > _TOOL_ARGS_KEEP:
+ d.pop(next(iter(d)))
+
+
+def _tool_args_in_sse_line(line: bytes, flags: dict, st: dict) -> None:
+ """Tool calls as a model streams them through the relay, assembled by call id: OpenAI
+ chat/completions `delta.tool_calls[]` pieces, and Anthropic `tool_use` blocks with their
+ `input_json_delta`. `st` is this response's own state (indices are per response).
+
+ For a harness that announces a call without its arguments: opensquilla's progress event names
+ the call and nothing else, so its console row had nothing to open while the turn ran; the call
+ id is the provider's, and the model sent the arguments before the tool ran."""
+ if not line.startswith(b"data:"):
+ return
+ raw = line[5:].strip()
+ if not (b"tool_calls" in raw or b"tool_use" in raw or b"input_json_delta" in raw):
+ return
+ try:
+ j = json.loads(raw)
+ except ValueError:
+ return
+ if not isinstance(j, dict):
+ return
+ for ch in j.get("choices") or []:
+ for tc in ((ch.get("delta") or {}) if isinstance(ch, dict) else {}).get("tool_calls") or []:
+ if not isinstance(tc, dict):
+ continue
+ cur = st.setdefault("oa", {}).setdefault(tc.get("index", 0), {"id": "", "args": ""})
+ if tc.get("id"):
+ cur["id"] = str(tc["id"])
+ piece = (tc.get("function") or {}).get("arguments")
+ if isinstance(piece, str):
+ cur["args"] += piece
+ if cur["id"]:
+ _tool_args_note(flags, cur["id"], cur["args"])
+ t = j.get("type")
+ if t == "content_block_start" and (j.get("content_block") or {}).get("type") == "tool_use":
+ cb = j["content_block"]
+ st.setdefault("an", {})[j.get("index", 0)] = {"id": str(cb.get("id") or ""), "args": ""}
+ elif t == "content_block_delta" and (j.get("delta") or {}).get("type") == "input_json_delta":
+ cur = (st.get("an") or {}).get(j.get("index", 0))
+ if cur and cur["id"]:
+ cur["args"] += j["delta"].get("partial_json") or ""
+ _tool_args_note(flags, cur["id"], cur["args"])
+
+
+def _tool_args_in_body(data: bytes, flags: dict) -> None:
+ """The same, from a whole (non-streamed) response."""
+ if b"tool_calls" not in data and b"tool_use" not in data:
+ return
+ try:
+ j = json.loads(data)
+ except ValueError:
+ return
+ if not isinstance(j, dict):
+ return
+ for ch in j.get("choices") or []:
+ for tc in ((ch.get("message") or {}) if isinstance(ch, dict) else {}).get("tool_calls") or []:
+ if isinstance(tc, dict) and tc.get("id"):
+ _tool_args_note(flags, str(tc["id"]), str((tc.get("function") or {}).get("arguments") or ""))
+ for c in j.get("content") or []:
+ if isinstance(c, dict) and c.get("type") == "tool_use" and c.get("id"):
+ _tool_args_note(flags, str(c["id"]), json.dumps(c.get("input") or {}))
+
+
+def _relay_tool_args(routes, cid: str) -> dict | None:
+ """The arguments the relay saw for this call id on any of the turn's routes, parsed; None when
+ it saw none, or they do not parse as a JSON object yet."""
+ for f in reversed(routes or []):
+ raw = ((f.get("tool_args") or {}) if isinstance(f, dict) else {}).get(cid)
+ if raw is None:
+ continue
+ try:
+ v = json.loads(raw) if raw.strip() else {}
+ except ValueError:
+ return None
+ return v if isinstance(v, dict) and v else None
+ return None
+
+
def _usage_in_sse_line(line: bytes) -> dict:
"""One SSE line as it passes the relay → the usage it carries, {} for anything else."""
if not line.startswith(b"data:") or b"sage" not in line:
@@ -5251,6 +5352,10 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
# at 429 or 503 this did not print them.
print(f"[relay] {'google' if google else 'provider'} refused {tail} model={_body_model} "
f"status={e.code}: {data[:300]!r}", flush=True)
+ # ...and on the route, for a harness that does not say why its turn failed: hermes
+ # printed only its own "↻ Resumed session" line when Vercel refused gpt-6.1-sol for
+ # a spent budget (2026-10-13), and that line was the turn's whole error.
+ flags["last_refusal"] = _refusal_words(e.code, data)
if (attempt < 2 and e.code == 400 and b"thought_signature" in data
and not flags.get("thought_signature") and body is not None):
# a Gemini 3 endpoint this relay did not recognise as Google names the need itself
@@ -5354,6 +5459,7 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
self.end_headers()
pending = b""
line_state: dict = {} # what the per-line rewrite has seen of this stream so far
+ tool_state: dict = {} # this response's tool calls, by index (_tool_args_in_sse_line)
carry = b"" # tail of the previous chunk, so a split "model":"…" is still seen
fcarry = b"" # tail of the previous chunk, for the finish_reason field
call_usage: dict = {} # what this call's events said about tokens, unioned
@@ -5440,6 +5546,7 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
last_event = time.monotonic() # an event's line; a comment is not one
flags["last_data"] = time.time() # ...and the route's own note of it (_hermes_startup_hung)
call_usage.update(_usage_in_sse_line(line))
+ _tool_args_in_sse_line(line, flags, tool_state)
seen_thinking = _thinking_in_sse_line(line)
if seen_thinking is not None:
call_thinking = seen_thinking
@@ -5495,6 +5602,7 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
fr = _finish_reason_in(data[-65536:])
if fr:
flags["last_finish"] = fr
+ _tool_args_in_body(data, flags)
if body is not None and b"sage" in data:
try:
whole = json.loads(data)
@@ -7542,6 +7650,14 @@ def _opencode_config(auth: Auth, model: str, cwd: str, mcp_servers: list[dict] |
"models": {model: {}},
}
},
+ # The turn's connection and NOTHING ELSE. Both binaries carry built-in providers besides the
+ # ones a config defines, and a model may name one: mimo's `actor` tool takes a model, and on
+ # 0.33.0-rc.6 gpt-6-sol spawned a visual-QA subagent on `xiaomi/mimo-v2.5`, which MiMo's own
+ # service refused ("Invalid API Key"); the deck was made, the turn failed on the subagent's
+ # error, and the gateway read it as the user's key refused. Measured on @mimo-ai/cli 0.1.15:
+ # `mimo models` lists hr, mimo and six xiaomi ids without this, and hr alone with it. A
+ # request off the connection is also a request the person never sent anywhere.
+ "enabled_providers": ["hr"],
# opencode's filesystem snapshots back the TUI's undo/revert; a fresh `run` per turn has
# no one to undo for, and HarnessRouter's checkpoint is the rollback here. Left on, it is
# a git repo of the workspace under $HOME — 699 MB of the 1.4 GB tarball in #193.
@@ -7723,6 +7839,14 @@ def _build_mimo(provider: str, auth: Auth, model: str, prompt: str, cwd: str, en
qualified = _opencode_config(auth, model, cwd, mcp_servers, skills_dir, tools_disabled, pr,
backend="mimo", key_env=_MIMO_KEY_ENV, npm=npm)
env["MIMOCODE_CONFIG"] = os.path.join(cwd, ".harness", "mimo.json")
+ # mimo's own 23 built-in skills off: several are dead ends here that compete with the skills the
+ # harness mounts. Its pptx/docx/xlsx/pdf-official run on python-pptx and the like, which this
+ # image does not ship and a sandbox cannot pip-install (no route to PyPI): gpt-5.4-mini picked
+ # pptx-official and gave up on the deck three times out of three while officecli, the skill
+ # every other base uses, sat beside it. Its `playwright` competes with the browser plug.
+ # Measured on 0.1.15 with `mimo debug skill`: 37 skills without this, 15 with it, and the
+ # skill from the harness's own skills path present both times.
+ env["MIMOCODE_DISABLE_BUILTIN_SKILLS"] = "1"
cmd = ["mimo", "run", "--format", "json", "--model", qualified,
# The sandbox is the trust boundary and nobody is attached to answer a prompt — the
# same grant claude gets with --dangerously-skip-permissions and pi with --approve.
@@ -8897,6 +9021,17 @@ def _build_qoder(provider: str, auth: Auth, model: str, prompt: str, cwd: str, e
return [QODER_PYTHON, QODER_DRIVER, json.dumps(job)]
+# A reasoning model behind a Qoder id can leave its thinking markers in the text Qoder streams: on
+# 0.33.0-rc.19 the `performance` id's answer began "</think> Rendered — full-bleed purple…". Neither
+# marker is the answer: a whole <think>…</think> block goes, and a stray tag of either kind with it.
+_THINK_BLOCK = re.compile(r"<think>.*?</think>\s*", re.S)
+_THINK_TAG = re.compile(r"\s*</?think>\s*")
+
+
+def _without_think(text: str) -> str:
+ return _THINK_TAG.sub(" ", _THINK_BLOCK.sub("", text)).strip() if "think>" in text else text
+
+
def _qoder_to_claude(obj: dict, state: dict) -> list[dict]:
"""Map ONE driver NDJSON line to canonical claude stream-json events.
@@ -8923,10 +9058,12 @@ def _qoder_to_claude(obj: dict, state: dict) -> list[dict]:
"requested_session_id": str(p.get("requested_session_id") or "")}]
if m == "text":
txt = str(p.get("text") or "")
+ if "think>" in txt:
+ txt = _THINK_TAG.sub(" ", txt).lstrip()
if not txt:
return []
state["_qoder_text"] = state.get("_qoder_text", "") + txt
- state["final"] = state["_qoder_text"]
+ state["final"] = _without_think(state["_qoder_text"])
return [{"type": "assistant", "message": {"content": [{"type": "text", "text": txt}]}}]
if m == "tool_use":
if state.get("_qoder_text") and not state["_qoder_text"].endswith("\n"):
@@ -8947,7 +9084,7 @@ def _qoder_to_claude(obj: dict, state: dict) -> list[dict]:
return []
if m == "__hr_result":
status = str(p.get("status") or "")
- final = str(p.get("final") or "") or state.get("_qoder_text", "")
+ final = _without_think(str(p.get("final") or "") or state.get("_qoder_text", ""))
reason = str(p.get("reason") or "")
ev: dict = {"type": "result", "usage": {}}
if p.get("charge"):
@@ -9452,6 +9589,23 @@ ALL_JCODE_TOOLS = {
"panel", "read", "replace", "schedule", "session_search", "side_panel", "skill_manage",
"swarm", "todo", "webfetch", "websearch", "write",
}
+# Off on every turn, whatever the harness asks: jcode tools that cannot work in a headless Linux
+# sandbox, or that leave it on their own. `browser` drives Firefox through an extension bridge that
+# never connects here, and a model that picks it over the browser plug tries to set it up until the
+# turn's cap: gpt-5.4-mini ran 459 tool calls for two hours on 0.33.0-rc.7, "the browser bridge is
+# not connected", on a task the plug does in a minute. `macos_computer_use` is macOS's,
+# `gmail` signs in through jcode's own Google login rather than the person's plugs, and
+# `maintainer_feedback` writes to jcode's maintainer.
+# `todo` and `memory` are the way into jcode's runaway turns. Its todo tool carries per-item
+# "confidence" and a "closed feedback loop" plan, and a model can keep re-validating against it:
+# grok-4.20 on a three-turn PDF edit made 84 calls in five minutes, 47 of them `todo`, ending "the
+# validation has transcended into the null-eternal"; a person's grok-4.6 turn re-verified "All 11…
+# 12… 13 items" through `todo` and `memory` until stopped (0.33.0-rc.18). With both off, grok-4.20
+# finished all three turns in three runs of three (4 to 12 calls a turn), and claude-sonnet-5.5,
+# gpt-5.4 and grok-4.6 finished faster than with them. No release after the pinned v0.90.0, through
+# v0.95.0, changes either. `memory` is jcode's own store under its home, not this product's memory.
+_JCODE_SANDBOX_OFF = frozenset({"browser", "macos_computer_use", "gmail", "maintainer_feedback",
+ "todo", "memory"})
def _jcode_usage_add(state: dict, ev: dict) -> None:
@@ -9486,14 +9640,42 @@ def _jcode_usage(state: dict) -> dict:
return {k: v for k, v in (state.get("_jc_usage") or {}).items() if v}
+def _jcode_held_calls(state: dict, upto: str | None = None) -> list[dict]:
+ """Emit the held tool calls, oldest first, with the arguments their `tool_input` pieces built:
+ every one when `upto` is None, else up to and including the call with that id.
+
+ A call is held from `tool_start` because jcode streams its arguments AFTER it, as `tool_input`
+ pieces that carry no id (they belong to the call started last), and a tool_use is final once
+ the gateway has it. Emitting it at tool_start sent every jcode call with `{}`: the console
+ showed a bare "Bash" with nothing to open, and the record kept no command. Measured on v0.90.0
+ against a stub endpoint: tool_start{id,name}, tool_input{delta} x3, tool_exec{id,name},
+ message_end, tool_done{id,output}."""
+ held = state.get("_jc_calls") or []
+ if upto is not None and not any(c["id"] == upto for c in held):
+ return []
+ out = []
+ while held:
+ c = held.pop(0)
+ raw = c["args"].strip()
+ try:
+ inp = json.loads(raw) if raw else {}
+ except ValueError:
+ inp = {"arguments": raw} # cut short (a killed turn): shown as it arrived, never dropped
+ out.append({"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": c["id"], "name": c["name"],
+ "input": inp if isinstance(inp, dict) else {"arguments": inp}}]}})
+ if c["id"] == upto:
+ break
+ return out
+
+
def _jcode_to_claude(obj: dict, state: dict) -> list[dict]:
"""Map ONE `jcode run --ndjson` line to zero+ canonical claude stream-json events.
Text streams from text_delta; `text_replace` is jcode's revision event and replaces what was
streamed, so it is not re-emitted (the user already has the old text on screen — the same
decision _pi_to_claude makes for a non-prefix revision) but it does become the candidate final.
- `tool_input` carries argument deltas for a call whose tool_use was already emitted at
- tool_start, so it is dropped rather than painted twice."""
+ A tool call is held from `tool_start` until its arguments are complete (_jcode_held_calls)."""
t = obj.get("type")
if t == "start":
state["_jc_session"] = obj.get("session_id") or ""
@@ -9515,37 +9697,58 @@ def _jcode_to_claude(obj: dict, state: dict) -> list[dict]:
state["final"] = txt
return []
if t == "tool_start":
- return [{"type": "assistant", "message": {"content": [
- {"type": "tool_use", "id": obj.get("id") or "tool",
- "name": obj.get("name") or "tool", "input": {}}]}}]
+ # jcode has no step limit of its own (no flag for one), so the turn's budget is counted
+ # here: past it the turn ends incomplete at its budget and the run loop stops the process.
+ # Without it a model that would not stop ran to the turn's wall-clock cap: grok-4.20 made
+ # 84 calls in five minutes on 0.33.0-rc.18, 47 of them `todo`, "the validation has
+ # transcended into the null-eternal", and a person stopped it by hand.
+ n = state["_jc_tool_n"] = state.get("_jc_tool_n", 0) + 1
+ cap = state.get("max_turns")
+ if cap and n > int(cap) and not state.get("_stop"):
+ state["_stop"] = "max_turns"
+ return _jcode_held_calls(state) + [{
+ "type": "result", "subtype": "error_max_turns", "is_error": False,
+ "result": state.get("final", "") or state.get("_jc_text", ""),
+ "usage": _jcode_usage(state)}]
+ state.setdefault("_jc_calls", []).append(
+ {"id": obj.get("id") or "tool", "name": obj.get("name") or "tool", "args": ""})
+ return []
+ if t == "tool_input":
+ held = state.get("_jc_calls")
+ if held:
+ held[-1]["args"] += str(obj.get("delta") or "")
+ return []
+ if t == "tool_exec":
+ return _jcode_held_calls(state, obj.get("id") or "tool")
if t == "tool_done":
err = obj.get("error")
content = str(obj.get("output") or err or "")
- return [{"type": "user", "message": {"content": [
- {"type": "tool_result", "tool_use_id": obj.get("id") or "tool",
- "is_error": bool(err), "content": content[:8000]}]}}]
+ return _jcode_held_calls(state, obj.get("id") or "tool") + [
+ {"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": obj.get("id") or "tool",
+ "is_error": bool(err), "content": content[:8000]}]}}]
if t == "tokens":
_jcode_usage_add(state, obj)
return []
if t == "message_end":
# One assistant message ended; the next may follow in the same turn (a tool round trip).
# `final` is the LAST message's text, so the buffer resets rather than accumulating a
- # mid-run aside into the answer.
+ # mid-run aside into the answer. Every call the message made has its arguments by now.
state["_jc_text"] = ""
- return []
+ return _jcode_held_calls(state)
if t == "error":
# A REAL error event, which is more than several of these CLIs have: the message names the
# endpoint, the model, the auth variable's NAME (never its value), the status and the
# provider's own body. No `done` follows it, and the process exits 1.
state["_jc_error"] = str(obj.get("message") or "jcode run failed")[:1000]
- return [{"type": "result", "subtype": "error", "is_error": True,
- "result": state["_jc_error"], "usage": _jcode_usage(state)}]
+ return _jcode_held_calls(state) + [{"type": "result", "subtype": "error", "is_error": True,
+ "result": state["_jc_error"], "usage": _jcode_usage(state)}]
if t == "done":
# `done.text` is the whole final answer, authoritative over what the deltas assembled.
final = obj.get("text")
if isinstance(final, str) and final:
state["final"] = final
- return [{"type": "result", "subtype": "success", "is_error": False,
+ return _jcode_held_calls(state) + [{"type": "result", "subtype": "success", "is_error": False,
"result": state.get("final", ""), "usage": _jcode_usage(state),
# The CLI echoes the REQUESTED id here, never what the provider answered, so this
# is deliberately NOT set as the served model: the relay's tap is the only honest
@@ -9559,13 +9762,14 @@ def _jcode_eof(state: dict, rc: int) -> list[dict]:
emitter ran. The exit code decides, and a failure returns an EMPTY result so the run loop's
collected stderr tail — which carries jcode's own `Error: …` block — is the reason rather than
a placeholder written here."""
+ held = _jcode_held_calls(state) # a call the kill cut off still shows what it was running
if state.get("_jc_error"):
- return []
+ return held
usage = _jcode_usage(state)
if rc == 0:
- return [{"type": "result", "subtype": "success", "is_error": False,
- "result": state.get("final", ""), "usage": usage}]
- return [{"type": "result", "subtype": "error", "is_error": True, "result": "", "usage": usage}]
+ return held + [{"type": "result", "subtype": "success", "is_error": False,
+ "result": state.get("final", ""), "usage": usage}]
+ return held + [{"type": "result", "subtype": "error", "is_error": True, "result": "", "usage": usage}]
_jcode_to_claude.eof = _jcode_eof # type: ignore[attr-defined]
@@ -9678,21 +9882,36 @@ def _opensquilla_transcript(state: dict) -> list[dict]:
cwd = state.get("cwd") or ""
if not cwd:
return []
- _, transcript, _ = _opensquilla_paths(cwd)
+ state_dir, transcript, _ = _opensquilla_paths(cwd)
try:
lines = transcript.read_text(errors="replace").splitlines()
except OSError:
return []
- out: list[dict] = []
- final = ""
+ msgs: list[dict] = []
for raw in lines:
raw = raw.strip()
if not raw.startswith("{"):
continue
try:
- msg = (json.loads(raw) or {}).get("message") or {}
+ msgs.append((json.loads(raw) or {}).get("message") or {})
except Exception: # noqa: BLE001 — one unparseable line in a transcript the CLI is still
continue # appending to is a line, not a turn: skip it and read the rest.
+ # THIS turn only. A resumed session's transcript is the whole conversation, rewritten each turn,
+ # and replaying it all put every earlier answer in front of this one and every earlier tool call
+ # and result into its trace (2026-10-13: a sixth turn answered "Hello! How can I help you
+ # today?…" from the first and listed 31 tools). The turn begins after the LAST user message that
+ # carries its prompt (the run loop's state holds it); without it, after the last user message.
+ prompt = str(state.get("prompt") or "").strip()
+ def _user_text(m: dict) -> str:
+ c = m.get("content")
+ return c if isinstance(c, str) else "\n".join(
+ x.get("text") or "" for x in (c or []) if isinstance(x, dict) and x.get("type") == "text")
+ users = [i for i, m in enumerate(msgs) if m.get("role") == "user"]
+ mine = [i for i in users if prompt and prompt in _user_text(msgs[i])]
+ start = (mine or users or [-1])[-1] + 1
+ out: list[dict] = []
+ final = ""
+ for msg in msgs[start:]:
role = msg.get("role")
content = msg.get("content") if isinstance(msg.get("content"), list) else []
if role == "assistant":
@@ -9706,6 +9925,28 @@ def _opensquilla_transcript(state: dict) -> list[dict]:
# assistant message was exactly "DONE".
final = text
out.append({"type": "assistant", "message": {"content": [{"type": "text", "text": text}]}})
+ # Each call again, now WITH its arguments: the progress stream announced it with none
+ # (tool_use_start carries no input), so its row had nothing to show. The gateway fills
+ # that row in place (same id, same name, no result yet) rather than adding one; the name
+ # is the one the row was given, so the two can never disagree.
+ live = state.get("_sq_calls") or {}
+ filled = state.get("_sq_filled") or set()
+ for c in content:
+ if not (isinstance(c, dict) and c.get("type") == "toolCall" and c.get("id")):
+ continue
+ if c["id"] in filled:
+ continue # its row has had its arguments since it started; a second would duplicate it
+ args = c.get("arguments")
+ if isinstance(args, str):
+ try:
+ args = json.loads(args) if args.strip() else {}
+ except ValueError:
+ args = {"arguments": args}
+ if not args:
+ continue
+ out.append({"type": "assistant", "message": {"content": [
+ {"type": "tool_use", "id": c["id"], "name": live.get(c["id"]) or c.get("name") or "tool",
+ "input": args if isinstance(args, dict) else {"arguments": args}}]}})
elif role == "toolResult":
body = "\n".join(c.get("text") or "" for c in content
if isinstance(c, dict) and c.get("type") == "text")
@@ -9727,12 +9968,18 @@ def _opensquilla_to_claude(obj: dict, state: dict) -> list[dict]:
if obj.get("_event") is True:
kind = obj.get("kind")
if kind == "tool_use_start":
+ tid = obj.get("tool_use_id") or "tool"
+ state.setdefault("_sq_calls", {})[tid] = obj.get("tool_name") or "tool"
+ # The progress stream carries no arguments, by design; the model sent them through the
+ # relay before the tool ran, under this same call id, so the row has them from the start.
+ # When the relay saw none (a route that is not relayed), the row starts empty and the
+ # transcript fills it when the turn ends (_opensquilla_transcript).
+ args = _relay_tool_args(state.get("routes"), tid)
+ if args:
+ state.setdefault("_sq_filled", set()).add(tid)
return [{"type": "assistant", "message": {"content": [
- {"type": "tool_use", "id": obj.get("tool_use_id") or "tool",
- "name": obj.get("tool_name") or "tool",
- # The progress stream carries no arguments, by design. An empty object is the
- # honest rendering: a card with no arguments, rather than invented ones.
- "input": {}}]}}]
+ {"type": "tool_use", "id": tid, "name": obj.get("tool_name") or "tool",
+ "input": args or {}}]}}]
if kind == "router_decision":
# The router is turned OFF by the config this builder writes, so this event should
# never arrive. If it does, the turn ran on a model nobody asked for: recorded so the
@@ -9843,6 +10090,14 @@ def _opensquilla_config(auth: Auth, model: str, state_dir: pathlib.Path, anthrop
"# ensure_agent_workspace writes those whatever this says; _git_exclude is what covers them.",
'source = "state"',
"",
+ "[tools]",
+ "# `cron` schedules jobs for opensquilla's own scheduler, which a one-shot `opensquilla agent`",
+ "# turn never runs, so a job made with it never fires. Its description is also the only text in",
+ "# the whole request that is not English (three Chinese example requests), and on 0.33.0-rc.15",
+ "# gpt-5.5 and gpt-5.4 answered English prompts with a Chinese opening line. The global policy's",
+ "# deny list wins over every later layer (tools/policy_helpers.py).",
+ 'deny = ["cron"]',
+ "",
]
entries = []
for i, sv in enumerate(mcp_servers or []):
@@ -9876,10 +10131,53 @@ def _opensquilla_config(auth: Auth, model: str, state_dir: pathlib.Path, anthrop
(state_dir / "config.toml").write_text("\n".join(lines))
+# opensquilla's own reply-language rules, in its system prompt template. Measured on 0.33.0-rc.16
+# against gpt-5.4 with plain English prompts: with them, 8 of 8 answers in Chinese, and with the
+# Chinese line alone removed, 4 of 4 in French; with all three removed, 4 of 4 in English (gpt-5.5
+# drifted too, gemini and claude did not). Without them a model answers in the person's language,
+# as on every other base. The template has no override hook (identity/prompt.py loads it from the
+# package directory), so the lines are taken out of the installed file before a turn runs, once per
+# runner, idempotently; installs made before this fix get it too.
+_OPENSQUILLA_LANGUAGE_RULES = re.compile(
+ r"^- (?:Write tool preambles in the same language as the user's current conversation\."
+ r"|Use the conversation's language for all user-visible replies[^\n]*"
+ r"|If the user writes in Chinese, keep replying in Chinese[^\n]*)\n", re.M)
+_OPENSQUILLA_LANGUAGE_DONE: list[bool] = []
+
+
+def _opensquilla_reply_language_fix(venv: pathlib.Path | None = None) -> str:
+ """Remove the three rules from the installed template; what was done, for the log."""
+ if _OPENSQUILLA_LANGUAGE_DONE:
+ return "done"
+ venv = venv or pathlib.Path(OPENSQUILLA_BIN).parent.parent
+ found = sorted(venv.glob("lib/python*/site-packages/opensquilla/identity/templates/system_prompt.j2"))
+ if not found:
+ return "no template"
+ t = found[0]
+ s = t.read_text(encoding="utf-8")
+ new = _OPENSQUILLA_LANGUAGE_RULES.sub("", s)
+ if new != s:
+ t.write_text(new, encoding="utf-8")
+ what = "removed"
+ elif "conversation's language" in s or "replying in Chinese" in s:
+ # a release that reworded them: say so rather than leave the drift unexplained
+ print("[opensquilla] WARNING: its reply-language rules are in a form this runner does not "
+ "know; English prompts may get answers in another language", flush=True)
+ what = "unknown form"
+ else:
+ what = "absent"
+ _OPENSQUILLA_LANGUAGE_DONE.append(True)
+ return what
+
+
def _build_opensquilla(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,
resume_session_id: str | None = None, mcp_servers: list[dict] | None = None,
tools_disabled: list[str] | None = None,
max_turns: int | None = None) -> list[str]:
+ try:
+ _opensquilla_reply_language_fix()
+ except OSError as e: # never fails a turn; the turn just keeps opensquilla's own wording
+ print(f"[opensquilla] reply-language rules not changed: {e}", flush=True)
pr = provider or "openai-api"
if pr not in OPENSQUILLA_PROVIDERS:
raise HTTPException(400, f"unknown opensquilla provider '{pr}' "
@@ -10385,14 +10683,12 @@ def _build_jcode(provider: str, auth: Auth, model: str, prompt: str, cwd: str, e
elif resume_session_id:
print(f"[resume] jcode: session {resume_session_id} not in this workspace — starting fresh",
flush=True)
- if tools_disabled:
- # A real per-tool switch, applied AFTER the tool profile, so it is enforcement rather than
- # instruction: the model's own list came back without the disabled name. Names outside this
- # runtime's set are dropped, so a label from another backend narrows nothing.
- names = sorted({x.split(" (")[0].strip().lower() for x in tools_disabled if x and x.strip()}
- & ALL_JCODE_TOOLS)
- if names:
- cmd += ["--disabled-tools", ",".join(names)]
+ # A real per-tool switch, applied AFTER the tool profile, so it is enforcement rather than
+ # instruction: the model's own list came back without the disabled name. Names outside this
+ # runtime's set are dropped, so a label from another backend narrows nothing.
+ names = sorted(({x.split(" (")[0].strip().lower() for x in (tools_disabled or []) if x and x.strip()}
+ & ALL_JCODE_TOOLS) | _JCODE_SANDBOX_OFF)
+ cmd += ["--disabled-tools", ",".join(names)]
if not _jcode_write_mcp(home, mcp_servers) and mcp_servers:
print("[jcode] every configured MCP server was remote and could not be bridged — "
"this turn runs without them", flush=True)
@@ -11008,10 +11304,18 @@ def _kill_capped(proc: subprocess.Popen, rec: dict) -> None:
def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, model: str,
- timeout_seconds: int | None = None, partial: bool = False) -> None:
+ timeout_seconds: int | None = None, partial: bool = False,
+ max_turns: int | None = None, prompt: str = "") -> None:
rec = _turns[turn_id]
rec["turn_id"] = turn_id
- state = {"model": model, "final": "", "partial": partial, "cwd": cwd, "started": time.time()}
+ state = {"model": model, "final": "", "partial": partial, "cwd": cwd, "started": time.time(),
+ # the relay's notes on this turn's routes (a translator may read what the model sent)
+ "routes": rec.get("routes"),
+ # the turn's step budget, for a CLI that has no limit of its own (_jcode_to_claude)
+ "max_turns": max_turns,
+ # the turn's own prompt, where a transcript of the whole conversation begins this turn
+ # (_opensquilla_transcript)
+ "prompt": prompt}
result_ev = None
env = {**env, _TURN_MARK: turn_id}
try:
@@ -11080,6 +11384,12 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m
# Claude's stream-json carries the final assistant text on the result event;
# the codex normalizer already fills state['final'], so prefer that.
state["final"] = state.get("final") or ev.get("result") or ""
+ if state.get("_stop") and not state.get("_stopped") and proc.poll() is None:
+ # A translator ended the turn itself (a CLI with no step limit of its own went past
+ # the turn's budget): the process is stopped here, and the result event it emitted
+ # says why, so the turn is incomplete at its budget rather than running to the cap.
+ state["_stopped"] = True
+ _kill_proc_tree(proc, turn_id)
rc = proc.wait()
finally:
killer.cancel()
@@ -11465,16 +11775,37 @@ _HERMES_POLL_S = 0.8
_HERMES_STARTUP_TIMEOUT_S = float(os.environ.get("HERMES_STARTUP_TIMEOUT_S", "90"))
-_HERMES_SID_LINE = re.compile(r"^session_id:\s*\S+$")
+# hermes's own status lines, never a reason: the `session_id:` it closes every run with, and the
+# "↻ Resumed session <id> (N user messages, M total messages)" it prints when a turn resumes.
+_HERMES_SID_LINE = re.compile(r"^(session_id:\s*\S+|↻ Resumed session \S+.*)$")
-def _hermes_error_text(err_lines: list[str], rc: int | None, silent_s: float) -> str:
+def _refusal_words(status: int, body: bytes) -> str:
+ """A provider's refusal in its own words: the JSON error's message when there is one, else the
+ body's start, after the status."""
+ text = body.decode("utf-8", "replace").strip()
+ try:
+ j = json.loads(text)
+ err = j.get("error") if isinstance(j, dict) else None
+ msg = (err.get("message") if isinstance(err, dict) else err) or (j.get("message") if isinstance(j, dict) else "")
+ if isinstance(msg, str) and msg.strip():
+ text = msg.strip()
+ except ValueError:
+ pass
+ return f"{status}: {text[:500]}"
+
+
+def _hermes_error_text(err_lines: list[str], rc: int | None, silent_s: float, refusal: str = "") -> str:
"""Why a hermes run failed, from its last stderr lines. The CLI closes every run with a
`session_id: <id>` line, a failed one too; taken as the reason, it told a person "The last one
- said: session_id: 20261005_135032_0fb4fd" (the hosted service, 2026-10-05). When the CLI said
- nothing else, the reason is what is known: it stopped with no final answer, its exit code, and
- how long it had been silent by then."""
+ said: session_id: 20261005_135032_0fb4fd" (the hosted service, 2026-10-05), and a resumed turn
+ whose provider refused it said only "↻ Resumed session …" (2026-10-13). Neither is a reason.
+ When the CLI said nothing else, the reason is the provider's refusal the relay saw on this
+ turn, if there was one; else what is known: no final answer, the exit code, and how long it had
+ been silent by then."""
said = "\n".join(x for x in err_lines[-30:] if not _HERMES_SID_LINE.match(x.strip())).strip()
+ if not said and refusal:
+ said = f"The model provider refused the request ({refusal})"
return (said or f"Hermes ended the turn without a final answer and gave no reason "
f"(exit code {rc}, {silent_s:.0f} s after its last message).")[:2000]
@@ -11739,7 +12070,9 @@ def _run_hermes_bg(turn_id: str, cwd: str, env: dict, model: str, provider: str,
if not use_chat:
final = "\n".join(out_buf).strip() or final
ok = rc == 0 and not run_failed and not rec.get("cancelled") and not rec.get("capped") and bool(final.strip())
- err_txt = _hermes_error_text(err_buf, rc, time.time() - last_msg)
+ refusal = next((str(f.get("last_refusal")) for f in reversed(rec.get("routes") or [])
+ if isinstance(f, dict) and f.get("last_refusal")), "")
+ err_txt = _hermes_error_text(err_buf, rc, time.time() - last_msg, refusal)
if rec.get("startup_timeout"):
# The generic exit_code/stderr text is useless here (the process was killed by US, not a
# normal failure) — say what actually happened instead of leaving a cryptic "exit_code=-9".
@@ -11980,6 +12313,21 @@ def _collected_init(ws: str) -> None:
_git(ws, "update-ref", _COLLECTED_REF, head.stdout.strip())
+def _collected_at_turn_start(ws: str) -> None:
+ """Set the cursor BEFORE the agent runs, so a turn's own commits are past it.
+
+ It used to be set at the first collection, to the HEAD of that moment: an agent that committed
+ its work during a session's first turn (`git add deck.pptx && git commit`, which jcode's models
+ do) had its commit under the cursor, and /produced listed nothing. Measured on 0.33.0-rc.7:
+ gpt-6-sol and gpt-6.1-sol on jcode made the deck every time and handed back no file, on both
+ runs. A repo with no commit yet gets an empty one to point at; later turns already have a
+ cursor, left where the last collection put it."""
+ _git_ensure(ws)
+ if _git(ws, "rev-parse", "-q", "--verify", "HEAD").returncode != 0:
+ _git(ws, "commit", "-q", "--allow-empty", "-m", "harness: session start")
+ _collected_init(ws)
+
+
def _produced_keep(status: str, path: str) -> bool:
if not path or path.endswith("/") or status.startswith("D"):
return False
@@ -12013,6 +12361,8 @@ def _produced_list(ws: str) -> list[dict]:
path = path.strip().strip('"')
if _produced_keep(status, path):
seen.setdefault(path, status.strip() or "?")
+ keep = set(_without_lo_profiles(list(seen)))
+ seen = {k: v for k, v in seen.items() if k in keep}
# mtime rides on each item so a reader can put the newest first: a response carries at most
# HARNESS_RESP_MAX_FILES of them, and git's path order handed a Mario run its first 24 frames
# of 1,400 (hosted, 2026-09-25). 0 when the file is gone (a deletion) or cannot be stat'ed.
@@ -12206,6 +12556,10 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
raise HTTPException(400, "cwd is decided by the session identifier")
os.makedirs(cwd, exist_ok=True)
input_files = _write_input_files(cwd, req.files) # land caller-attached files in the workspace pre-run
+ try:
+ _collected_at_turn_start(_ws(identifier))
+ except Exception as e: # noqa: BLE001 — the cursor is collection's; a turn never waits on it
+ print(f"[produced] cursor not set at turn start: {str(e)[:160]}", flush=True)
# Built-in skills the harness disabled must NOT be mounted. On BusinessOS built-ins aren't
# image-mounted (there is no _mount_builtin_skills), and the gateway already drops suppress markers
# from req.skills, so this filter is a parity guard: never write a skill whose name is suppressed.
@@ -12549,6 +12903,7 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
threading.Thread(target=_run_turn_bg,
args=(turn_id, cmd, env, cwd, spec["normalize"], model, req.timeout_seconds,
bool(req.partial_messages)), # claude: CLI flag added above
+ kwargs={"max_turns": req.max_turns, "prompt": req.prompt or ""},
daemon=True).start()
cap = min(req.timeout_seconds, MAX_TURN_SECONDS) if req.timeout_seconds else MAX_TURN_SECONDS
return {"turn_id": turn_id, "status": "running", "backend": backend, "model": model,
diff --git a/runner/tests/test_batch3_backends.py b/runner/tests/test_batch3_backends.py
index b79ba355..cea73d6c 100644
--- a/runner/tests/test_batch3_backends.py
+++ b/runner/tests/test_batch3_backends.py
@@ -25,7 +25,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from server import (ALL_GAJAE_TOOLS, ALL_JCODE_TOOLS, ALL_NANOBOT_TOOLS, # noqa: E402
Auth, BACKENDS, CHECKPOINT_EXCLUDE, _agent_doc_path, _build_gajae,
_build_jcode, _build_mimo, _build_nanobot, _build_opensquilla,
- _BRIDGED_TRANSPORTS, _gajae_to_claude, _jcode_eof, _jcode_to_claude,
+ _BRIDGED_TRANSPORTS, _JCODE_SANDBOX_OFF, _gajae_to_claude, _jcode_eof, _jcode_to_claude,
_opencode_to_claude, _opensquilla_eof, _opensquilla_to_claude,
_opensquilla_transcript,
_jcode_session_model, _mcp_url_is_loopback, _opensquilla_usage,
@@ -120,6 +120,20 @@ def test_mimo_config_is_the_opencode_schema_with_the_key_named_not_written():
# opencode's snapshot repo is a git repo of the workspace under $HOME; left on it reached
# 699 MB in twenty turns (#193). The fork inherited it, so it is turned off here too.
assert cfg["snapshot"] is False
+ # The turn's connection and nothing else: mimo's built-in xiaomi provider is what a model's
+ # `actor` subagent reached on rc.6, refused with "Invalid API Key", failing a finished turn.
+ assert cfg["enabled_providers"] == ["hr"] and list(cfg["provider"]) == ["hr"]
+ # mimo's own built-in skills off (pptx-official on python-pptx, which no sandbox here can get);
+ # the harness's skills come through skills.paths and stay
+ assert env["MIMOCODE_DISABLE_BUILTIN_SKILLS"] == "1"
+
+
+def test_opencode_too_reaches_only_the_turns_connection():
+ d, env = _ws(), {}
+ from server import _build_opencode
+ _build_opencode("openai-api", Auth(api_key="k", base_url=UP), "deepseek-v4-pro", "hi", d, env)
+ cfg = json.loads((pathlib.Path(d) / ".harness" / "opencode.json").read_text())
+ assert cfg["enabled_providers"] == ["hr"] and list(cfg["provider"]) == ["hr"]
def test_mimo_shares_opencodes_normaliser():
@@ -301,10 +315,22 @@ def test_jcode_disabled_tools_are_filtered_to_names_this_runtime_has():
d, env = _ws(), {"HOME": str(pathlib.Path(_ws()) / "h")}
cmd = _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
tools_disabled=["write (File Write)", "NotATool"])
- assert cmd[cmd.index("--disabled-tools") + 1] == "write"
+ assert cmd[cmd.index("--disabled-tools") + 1].split(",") == sorted({"write"} | _JCODE_SANDBOX_OFF)
assert "write" in ALL_JCODE_TOOLS and "notatool" not in ALL_JCODE_TOOLS
+def test_jcode_tools_that_cannot_work_in_the_sandbox_are_off_on_every_turn():
+ # rc.7: gpt-5.4-mini picked jcode's own Firefox-bridge `browser` over the browser plug and ran
+ # 459 tool calls for two hours trying to connect it. Off whatever the harness asks for.
+ d, env = _ws(), {"HOME": str(pathlib.Path(_ws()) / "h")}
+ cmd = _build_jcode("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ off = set(cmd[cmd.index("--disabled-tools") + 1].split(","))
+ assert off == set(_JCODE_SANDBOX_OFF) and {"browser", "macos_computer_use", "gmail", "maintainer_feedback"} <= off
+ # the way into its runaway turns (grok-4.20: 84 calls, 47 of them todo; with both off, 3 of 3 runs finished)
+ assert {"todo", "memory"} <= off
+ assert _JCODE_SANDBOX_OFF <= ALL_JCODE_TOOLS and "bash" not in off and "webfetch" not in off
+
+
def test_jcode_usage_is_summed_across_requests_and_netted_of_both_caches():
# The two facts: `done.usage` holds only the LAST request's numbers (NdjsonRunState.usage is
# assigned, never accumulated), and `input` is GROSS — jcode's own OpenAI client says
@@ -350,6 +376,75 @@ def test_jcode_eof_fails_a_stream_that_ended_with_neither_terminal_event():
assert out[0]["is_error"] is False and out[0]["result"] == "an answer"
+def _tool_uses(evs):
+ return [b for e in evs if e.get("type") == "assistant"
+ for b in e["message"]["content"] if b.get("type") == "tool_use"]
+
+
+def test_jcode_tool_call_carries_the_arguments_its_input_pieces_built():
+ # Captured from jcode v0.90.0 against a stub endpoint that streamed one bash call in three
+ # pieces (2026-10-12). The arguments arrive AFTER tool_start, as tool_input pieces with no id;
+ # emitting the call at tool_start sent it with {} and the console row had nothing to open.
+ evs, _ = _norm(_jcode_to_claude, [
+ {"type": "start", "session_id": "s", "model": "stub-model"},
+ {"id": "call_stub1", "name": "bash", "type": "tool_start"},
+ {"delta": "{\"comm", "type": "tool_input"},
+ {"delta": "and\": \"echo stub-", "type": "tool_input"},
+ {"delta": "ok\"}", "type": "tool_input"},
+ {"id": "call_stub1", "name": "bash", "type": "tool_exec"},
+ {"stop_reason": "tool_calls", "type": "message_end"},
+ {"error": None, "id": "call_stub1", "name": "bash", "type": "tool_done",
+ "output": "stub-ok\n\n--- Command finished with exit code: 0 ---\n"},
+ {"stop_reason": "stop", "type": "message_end"},
+ {"type": "done", "text": "finished", "model": "stub-model", "session_id": "s"},
+ ])
+ uses = _tool_uses(evs)
+ assert [(u["id"], u["name"], u["input"]) for u in uses] == [("call_stub1", "bash", {"command": "echo stub-ok"})]
+ kinds = [e["type"] for e in evs]
+ assert kinds.index("user") > kinds.index("assistant") # the call before its result
+
+
+def test_jcode_stops_at_the_turns_step_budget():
+ # jcode has no step limit; grok-4.20 looped 84 calls in five minutes on its todo tool (rc.18).
+ from server import _status_from_result
+ state = {"model": "m", "max_turns": 3}
+ out = []
+ for i in range(5):
+ out += _jcode_to_claude({"id": f"c{i}", "name": "todo", "type": "tool_start"}, state)
+ results = [e for e in out if e.get("type") == "result"]
+ assert len(results) == 1 and results[0]["subtype"] == "error_max_turns"
+ assert state["_stop"] == "max_turns"
+ assert _status_from_result(results[0], -9) == "max_turns"
+ # no budget on record: never stopped by this
+ free = {"model": "m"}
+ assert not [e for i in range(50) for e in _jcode_to_claude({"id": f"c{i}", "name": "bash", "type": "tool_start"}, free)
+ if e.get("type") == "result"]
+
+
+def test_jcode_two_calls_in_one_message_keep_their_own_arguments_and_order():
+ evs, _ = _norm(_jcode_to_claude, [
+ {"type": "start", "session_id": "s", "model": "m"},
+ {"id": "a", "name": "read", "type": "tool_start"}, {"delta": "{\"path\": \"x\"}", "type": "tool_input"},
+ {"id": "b", "name": "bash", "type": "tool_start"}, {"delta": "{\"command\": \"ls\"}", "type": "tool_input"},
+ {"id": "a", "name": "read", "type": "tool_exec"},
+ {"id": "b", "name": "bash", "type": "tool_exec"},
+ {"type": "message_end", "stop_reason": "tool_calls"},
+ {"type": "done", "text": "ok"},
+ ])
+ assert [(u["id"], u["input"]) for u in _tool_uses(evs)] == [("a", {"path": "x"}), ("b", {"command": "ls"})]
+
+
+def test_jcode_call_cut_off_by_a_kill_still_shows_what_had_arrived():
+ state = {"model": "m"}
+ for o in ({"type": "start", "session_id": "s"}, {"id": "c", "name": "bash", "type": "tool_start"},
+ {"delta": "{\"command\": \"sleep", "type": "tool_input"}):
+ assert _jcode_to_claude(o, state) in ([], [{"type": "system", "subtype": "init", "session_id": "s", "model": "m"}])
+ out = _jcode_eof(state, 1)
+ assert _tool_uses(out) == [{"type": "tool_use", "id": "c", "name": "bash",
+ "input": {"arguments": "{\"command\": \"sleep"}}]
+ assert out[-1]["type"] == "result" and out[-1]["is_error"] is True
+
+
def test_jcode_bridges_remote_mcp_because_it_has_no_client_for_one():
# "jcode currently supports stdio (command-based) servers only; HTTP/SSE entries are recognized
# and skipped with a log line" — so without the bridge every remote server a harness declares is
@@ -379,6 +474,39 @@ def test_opensquilla_config_turns_the_router_off_and_declares_the_window():
assert 'provider = "custom"' in cfg
+def test_opensquilla_denies_cron_which_a_one_shot_turn_never_runs():
+ # Its scheduler never runs under `opensquilla agent`, and its description was the only non-English
+ # text in the request (Chinese examples); gpt-5.5 opened English answers in Chinese on rc.15.
+ # Measured with the request captured at a stub: 26 tools with cron, 25 and no Chinese without.
+ import tomllib
+ d, env = _ws(), {}
+ _build_opensquilla("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env)
+ cfg = tomllib.loads(pathlib.Path(d, ".harness", "opensquilla", "config.toml").read_text())
+ assert cfg["tools"]["deny"] == ["cron"]
+
+
+def test_opensquilla_reply_language_rules_come_out_of_its_template(tmp_path, monkeypatch):
+ # gpt-5.4 answered English prompts in Chinese (8 of 8) under these rules, in French without the
+ # Chinese one, and in English (4 of 4) without all three, rc.16.
+ import server
+ t = tmp_path / "lib" / "python3.12" / "site-packages" / "opensquilla" / "identity" / "templates"
+ t.mkdir(parents=True)
+ body = ("## Reply Guidelines\n\n"
+ "- Use the conversation's language for all user-visible replies, including progress notes, tables, and final answers.\n"
+ "- If the user writes in Chinese, keep replying in Chinese unless they explicitly ask for another language.\n"
+ "- Lead final answers with the result and a usable reference when relevant.\n"
+ "## Tools\n- Write tool preambles in the same language as the user's current conversation.\n- Keep it short.\n")
+ (t / "system_prompt.j2").write_text(body)
+ monkeypatch.setattr(server, "_OPENSQUILLA_LANGUAGE_DONE", [])
+ assert server._opensquilla_reply_language_fix(tmp_path) == "removed"
+ out = (t / "system_prompt.j2").read_text()
+ assert "language" not in out and "Chinese" not in out
+ assert "- Lead final answers with the result" in out and "- Keep it short." in out
+ monkeypatch.setattr(server, "_OPENSQUILLA_LANGUAGE_DONE", [])
+ assert server._opensquilla_reply_language_fix(tmp_path) == "absent" # idempotent
+ assert server._opensquilla_reply_language_fix(tmp_path) == "done" # once per runner
+
+
def test_opensquilla_argv_bounds_retries_and_keeps_a_session_db():
d, env = _ws(), {}
cmd = _build_opensquilla("openai-api", Auth(api_key="k", base_url=UP), "gpt-5.4", "hi", d, env,
@@ -643,6 +771,113 @@ def test_opensquilla_channel_routing_directives_are_not_part_of_the_answer():
assert _opensquilla_text("see [[notes]] here") == "see [[notes]] here"
+def test_opensquilla_calls_come_back_with_their_arguments_under_the_live_rows_name():
+ # The progress stream announces a call with no input; its row read `{}` in the console and the
+ # record. The transcript has the arguments, and the end-of-turn replay now sends each call again
+ # under the same id and the name the live row was given, so the gateway fills that row in place.
+ d = _ws()
+ base = pathlib.Path(d, ".harness", "opensquilla"); base.mkdir(parents=True)
+ (base / "transcript.jsonl").write_text("\n".join(json.dumps(x) for x in [
+ {"type": "message", "message": {"role": "assistant", "content": [
+ {"type": "toolCall", "name": "exec", "id": "call_1", "arguments": {"cmd": "echo one"}},
+ {"type": "toolCall", "name": "exec", "id": "call_2", "arguments": "{\"cmd\": \"echo two\"}"},
+ {"type": "toolCall", "name": "noop", "id": "call_3", "arguments": {}}]}},
+ {"type": "message", "message": {"role": "toolResult", "toolCallId": "call_1", "isError": False,
+ "content": [{"type": "text", "text": "one"}]}},
+ {"type": "message", "message": {"role": "assistant", "content": [{"type": "text", "text": "DONE"}]}},
+ ]))
+ evs, state = _norm(_opensquilla_to_claude, [
+ {"_event": True, "schema_version": 1, "kind": "tool_use_start", "tool_use_id": "call_1", "tool_name": "exec_command"},
+ {"_event": True, "schema_version": 1, "kind": "tool_use_start", "tool_use_id": "call_2", "tool_name": "exec_command"},
+ ], cwd=d)
+ live = [b for e in evs for b in e["message"]["content"] if b.get("type") == "tool_use"]
+ assert [(u["id"], u["input"]) for u in live] == [("call_1", {}), ("call_2", {})]
+ late = [b for e in _opensquilla_transcript(state) if e.get("type") == "assistant"
+ for b in e["message"]["content"] if b.get("type") == "tool_use"]
+ # each call once more, WITH its arguments (a JSON string parsed), named as the live row was; a
+ # call with no arguments is not sent again (there is nothing to fill)
+ assert [(u["id"], u["name"], u["input"]) for u in late] == [
+ ("call_1", "exec_command", {"cmd": "echo one"}), ("call_2", "exec_command", {"cmd": "echo two"})]
+
+
+def test_the_relay_assembles_a_tool_calls_arguments_from_the_models_stream():
+ from server import _relay_tool_args, _tool_args_in_body, _tool_args_in_sse_line
+ flags, st = {}, {}
+ for piece in ({"index": 0, "id": "call_a", "function": {"name": "exec_command", "arguments": ""}},
+ {"index": 0, "function": {"arguments": "{\"cmd\": \"echo "}},
+ {"index": 0, "function": {"arguments": "one\"}"}},
+ {"index": 1, "id": "call_b", "function": {"name": "read", "arguments": "{\"path\": \"a\"}"}}):
+ line = b"data: " + json.dumps({"choices": [{"index": 0, "delta": {"tool_calls": [piece]}}]}).encode()
+ _tool_args_in_sse_line(line, flags, st)
+ assert _relay_tool_args([flags], "call_a") == {"cmd": "echo one"}
+ assert _relay_tool_args([flags], "call_b") == {"path": "a"}
+ # Anthropic Messages: a tool_use block and its input_json_delta pieces
+ fa, sa = {}, {}
+ for ev in ({"type": "content_block_start", "index": 1, "content_block": {"type": "tool_use", "id": "toolu_1", "name": "bash", "input": {}}},
+ {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": "}},
+ {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "\"ls\"}"}}):
+ _tool_args_in_sse_line(b"data: " + json.dumps(ev).encode(), fa, sa)
+ assert _relay_tool_args([fa], "toolu_1") == {"command": "ls"}
+ # a whole response, both shapes
+ fb = {}
+ _tool_args_in_body(json.dumps({"choices": [{"message": {"tool_calls": [
+ {"id": "call_c", "function": {"name": "x", "arguments": "{\"k\": 1}"}}]}}]}).encode(), fb)
+ _tool_args_in_body(json.dumps({"content": [{"type": "tool_use", "id": "toolu_2", "name": "y", "input": {"q": "z"}}]}).encode(), fb)
+ assert _relay_tool_args([fb], "call_c") == {"k": 1} and _relay_tool_args([fb], "toolu_2") == {"q": "z"}
+ # nothing seen, or not yet a whole object: no arguments rather than a wrong one
+ assert _relay_tool_args([flags], "call_zzz") is None and _relay_tool_args(None, "call_a") is None
+ _tool_args_note_half = {"tool_args": {"call_h": "{\"cmd\": \"ec"}}
+ assert _relay_tool_args([_tool_args_note_half], "call_h") is None
+
+
+def test_opensquilla_rows_have_their_arguments_while_the_turn_runs():
+ # The live fix: the relay saw the model send call_1's arguments before opensquilla ran the tool,
+ # so the row the progress event opens carries them, and the transcript does not add a second.
+ d = _ws()
+ base = pathlib.Path(d, ".harness", "opensquilla"); base.mkdir(parents=True)
+ (base / "transcript.jsonl").write_text(json.dumps({"type": "message", "message": {"role": "assistant", "content": [
+ {"type": "toolCall", "name": "exec", "id": "call_1", "arguments": {"cmd": "echo one"}}]}}))
+ route = {"tool_args": {"call_1": "{\"cmd\": \"echo one\"}"}}
+ state = {"model": "gpt-5.4", "final": "", "cwd": d, "routes": [route]}
+ evs = _opensquilla_to_claude({"_event": True, "schema_version": 1, "kind": "tool_use_start",
+ "tool_use_id": "call_1", "tool_name": "exec_command"}, state)
+ assert evs[0]["message"]["content"][0]["input"] == {"cmd": "echo one"}
+ late = [b for e in _opensquilla_transcript(state) if e.get("type") == "assistant"
+ for b in e["message"]["content"] if b.get("type") == "tool_use"]
+ assert late == []
+
+
+def test_opensquilla_replays_only_this_turn_of_a_resumed_sessions_transcript():
+ # A resumed session's transcript holds the whole conversation; replaying it all put the first
+ # turn's answer in front of the sixth's and every earlier call into its trace (2026-10-13).
+ d = _ws()
+ base = pathlib.Path(d, ".harness", "opensquilla"); base.mkdir(parents=True)
+ msgs = [
+ {"role": "user", "content": [{"type": "text", "text": "[2026-10-13T04:51+00:00 Tue UTC]\nfollow instruction: hello"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "Hello! How can I help you today?"}]},
+ {"role": "user", "content": [{"type": "text", "text": "[2026-10-13T04:53+00:00 Tue UTC]\nmake a pdf"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "Writing it."},
+ {"type": "toolCall", "name": "write_file", "id": "call_old", "arguments": {"path": "a.pdf"}}]},
+ {"role": "toolResult", "toolCallId": "call_old", "content": [{"type": "text", "text": "Written"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "Made a.pdf"}]},
+ {"role": "user", "content": [{"type": "text", "text": "[2026-10-13T07:30+00:00 Tue UTC]\nchange to red"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "Recolouring."},
+ {"type": "toolCall", "name": "edit_file", "id": "call_new", "arguments": {"color": "red"}}]},
+ {"role": "toolResult", "toolCallId": "call_new", "content": [{"type": "text", "text": "Edited"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "It is red now."}]},
+ ]
+ (base / "transcript.jsonl").write_text("\n".join(json.dumps({"type": "message", "message": m}) for m in msgs))
+ state = {"model": "gpt-5.4", "final": "", "cwd": d, "prompt": "change to red"}
+ evs = _opensquilla_transcript(state)
+ blob = json.dumps(evs)
+ assert "Hello! How can I help" not in blob and "Made a.pdf" not in blob and "call_old" not in blob
+ assert "Recolouring." in blob and "call_new" in blob and "Edited" in blob
+ assert state["final"] == "It is red now."
+ # the prompt not on record: after the last user message, the same turn
+ state = {"model": "gpt-5.4", "final": "", "cwd": d}
+ assert "Made a.pdf" not in json.dumps(_opensquilla_transcript(state)) and state["final"] == "It is red now."
+
+
def test_opensquilla_transcript_answer_has_the_directive_removed():
d = _ws()
base = pathlib.Path(d, ".harness", "opensquilla"); base.mkdir(parents=True)
diff --git a/runner/tests/test_produced_cursor.py b/runner/tests/test_produced_cursor.py
index 3740d856..d5d098b6 100644
--- a/runner/tests/test_produced_cursor.py
+++ b/runner/tests/test_produced_cursor.py
@@ -12,7 +12,7 @@ import tempfile
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
-from server import _git, _git_ensure, _produced_ack, _produced_list # noqa: E402
+from server import _collected_at_turn_start, _without_lo_profiles, _git, _git_ensure, _produced_ack, _produced_list # noqa: E402
def _ws():
@@ -82,3 +82,41 @@ def test_each_produced_item_says_when_it_was_written():
_git(d, "add", "-A")
_git(d, "commit", "-q", "-m", "checkpoint")
assert {f["path"]: f["mtime"] for f in _produced_list(d)}["old.txt"] == 1_700_000_000.0
+
+
+def test_a_first_turn_that_commits_its_own_work_still_hands_it_back():
+ # 0.33.0-rc.7: jcode's gpt-6 models ended a first turn with `git add deck.pptx && git commit`.
+ # The cursor was set at that turn's collection, to a HEAD that already held the commit, and
+ # /produced listed nothing. Set at the turn's start, the agent's commit is past it.
+ d = tempfile.mkdtemp() # a brand-new session: no repo, no commit
+ _collected_at_turn_start(d)
+ (pathlib.Path(d) / "deck.pptx").write_text("deck")
+ _git(d, "add", "deck.pptx")
+ _git(d, "commit", "-q", "-m", "Create deck") # what the agent ran
+ assert {f["path"] for f in _produced_list(d)} == {"deck.pptx"}
+
+
+def test_the_turn_start_cursor_leaves_a_later_turns_cursor_where_collection_put_it():
+ d = _ws() # a session whose last turn was collected
+ (pathlib.Path(d) / "old.txt").write_text("from an earlier turn")
+ _produced_ack(d)
+ _collected_at_turn_start(d)
+ (pathlib.Path(d) / "new.txt").write_text("this turn")
+ _git(d, "add", "-A")
+ _git(d, "commit", "-q", "-m", "agent commit")
+ assert {f["path"] for f in _produced_list(d)} == {"new.txt"}
+
+
+def test_a_libreoffice_profile_in_the_workspace_is_not_a_deliverable():
+ # gpt-6.1-sol checked its deck with -env:UserInstallation inside the workspace (opensquilla and
+ # jcode, 2026-10-12); the profile's files, newer than the deck, filled the 25 a turn hands back.
+ d = _ws()
+ for rel in ("deck.pptx", "preview/deck.png", "preview/lo-profile/user/registrymodifications.xcu",
+ "preview/lo-profile/user/pack/ExtensionInfo.pack", "notes/user/todo.md"):
+ f = pathlib.Path(d) / rel
+ f.parent.mkdir(parents=True, exist_ok=True)
+ f.write_text("x")
+ assert {f["path"] for f in _produced_list(d)} == {"deck.pptx", "preview/deck.png", "notes/user/todo.md"}
+ # a profile at the workspace root, and a folder named user/ that is not a profile, both read right
+ assert _without_lo_profiles(["user/registrymodifications.xcu", "user/pack/a", "out.pdf"]) == ["out.pdf"]
+ assert _without_lo_profiles(["user/readme.md", "out.pdf"]) == ["user/readme.md", "out.pdf"]
diff --git a/runner/tests/test_qoder_backend.py b/runner/tests/test_qoder_backend.py
index c767e352..1b982d4c 100644
--- a/runner/tests/test_qoder_backend.py
+++ b/runner/tests/test_qoder_backend.py
@@ -1084,3 +1084,36 @@ def test_an_artifact_over_the_limit_or_unwritable_fails_with_its_reason(tmp_path
def test_a_long_artifact_name_is_cut_by_bytes_keeping_its_extension():
name, why = drv.artifact_name("é" * 200 + ".pdf")
assert not why and name.endswith(".pdf") and len(name.encode("utf-8")) <= 240
+
+
+def test_a_reasoning_models_think_markers_are_not_the_answer():
+ # rc.19: the `performance` id's answer began "</think> Rendered — full-bleed purple…".
+ from server import _qoder_to_claude
+ state = {"model": "performance"}
+ out = []
+ for o in ({"m": "text", "p": {"text": "</think> Rendered"}}, {"m": "text", "p": {"text": " — full-bleed purple."}},
+ {"m": "__hr_result", "p": {"status": "completed", "final": "<think>plan the colours</think>Rendered — full-bleed purple."}}):
+ out += _qoder_to_claude(o, state)
+ texts = [b["text"] for e in out if e.get("type") == "assistant" for b in e["message"]["content"] if b.get("type") == "text"]
+ assert "think>" not in "".join(texts) and texts[0] == "Rendered"
+ res = [e for e in out if e.get("type") == "result"][0]
+ assert res["result"] == "Rendered — full-bleed purple." and state["final"] == res["result"]
+
+
+
+def test_a_revised_deliverable_replaces_its_earlier_version_but_nothing_else(tmp_path):
+ # rc.19: one PDF revised over five turns landed as hi.pdf, "hi (2).pdf", "hi (3).pdf"...
+ written, _ = drv.land_artifact(str(tmp_path), "hi.pdf", b"v1")
+ written, note = drv.land_artifact(str(tmp_path), "hi.pdf", b"v2", frozenset({written}))
+ assert written == "hi.pdf" and not note and (tmp_path / "hi.pdf").read_bytes() == b"v2"
+ assert not list(tmp_path.glob("hi (*")) and not list(tmp_path.glob(".hi.pdf.*"))
+ # a file this session did not deliver (the person's own) is still never overwritten
+ (tmp_path / "mine.pdf").write_bytes(b"theirs")
+ written, note = drv.land_artifact(str(tmp_path), "mine.pdf", b"x", frozenset({"hi.pdf"}))
+ assert written == "mine (2).pdf" and (tmp_path / "mine.pdf").read_bytes() == b"theirs"
+
+
+def test_the_agent_is_named_for_the_base_never_for_the_session():
+ # qfmodel introduced itself as "harnessrouter hsess2b3b804c…" from the agent's name (rc.19)
+ body = drv.agent_body({"cwd": "/data/workspaces/hsess2b3b804ca4d14025b33a69316c6f350a", "model": "qfmodel"}, [], [])
+ assert body["name"] == "Qoder" and "hsess" not in json.dumps({k: v for k, v in body.items() if k != "metadata"})
diff --git a/runner/tests/test_turn_hold.py b/runner/tests/test_turn_hold.py
index 06fc9365..5b0bed45 100644
--- a/runner/tests/test_turn_hold.py
+++ b/runner/tests/test_turn_hold.py
@@ -153,3 +153,22 @@ def test_the_cli_home_is_out_of_the_workspaces_own_history_so_the_tar_is_the_onl
subprocess.run(["git", "-C", ws, "add", "-A"], check=True, env={**os.environ, **server._GIT_ENV})
tracked = subprocess.run(["git", "-C", ws, "ls-files"], capture_output=True, check=True).stdout.decode()
assert "notes.md" in tracked and ".harness/home" not in tracked
+
+
+def test_a_resumed_turn_the_provider_refused_says_why_not_that_it_resumed():
+ # 2026-10-13: Vercel refused gpt-6.1-sol on a spent budget; hermes printed only its resume line
+ # and its session id, and "↻ Resumed session …" was the turn's whole error.
+ from server import _refusal_words
+ lines = ["↻ Resumed session 20261013_042621_26ef17 (2 user messages, 4 total messages)",
+ "session_id: 20261013_042621_26ef17"]
+ refusal = _refusal_words(429, b'{"error":{"message":"API key budget exceeded. Current spend: $500.31, limit: $500.00.","type":"rate_limit"}}')
+ assert refusal == "429: API key budget exceeded. Current spend: $500.31, limit: $500.00."
+ text = _hermes_error_text(lines, 1, 2.0, refusal)
+ assert text == "The model provider refused the request (429: API key budget exceeded. Current spend: $500.31, limit: $500.00.)"
+ assert "Resumed session" not in text
+ # hermes's own words still win when it gave any
+ assert _hermes_error_text(lines + ["Error: provider returned 400: context length exceeded"], 1, 2.0, refusal) \
+ == "Error: provider returned 400: context length exceeded"
+ # no refusal on the turn: the known facts, as before
+ assert "without a final answer" in _hermes_error_text(lines, 1, 2.0)
+ assert _refusal_words(503, b"upstream unavailable") == "503: upstream unavailable"
diff --git a/scripts/support-matrix/plugins/run-matrix.py b/scripts/support-matrix/plugins/run-matrix.py
index 507755b8..eb66cfbe 100755
--- a/scripts/support-matrix/plugins/run-matrix.py
+++ b/scripts/support-matrix/plugins/run-matrix.py
@@ -176,8 +176,16 @@ def run_one(api: Api, base: str, mode: str, model: str, keep: bool, task_timeout
"input": prompt, "metadata": {"harness_id": created["id"]}, "stream": False,
"max_step": 12}, timeout=task_timeout)
answer = text_of(resp) if status == 200 else ""
+ # With --model the row measures THAT model: a turn the gateway served with another one (a
+ # fallback, or the base's default) is not a pass for it, whatever the answer says.
+ meta = (resp.get("metadata") or {}) if isinstance(resp, dict) else {}
+ row["served"] = str(resp.get("model") or "") if isinstance(resp, dict) else ""
+ swapped = model and (row["served"] != model or meta.get("requested_model") or meta.get("model_fallback"))
if status != 200:
row["outcome"], row["detail"] = "task failed", f"HTTP {status} {str(resp)[:200]}"
+ elif swapped:
+ row["outcome"] = "other model"
+ row["detail"] = f"asked {model}, served {row['served']!r} {meta.get('requested_model') or ''}".strip()
elif token in answer:
row["outcome"] = "pass"
row["detail"] = answer.strip().splitlines()[-1][:200]
diff --git a/scripts/support-matrix/plugs/browser.py b/scripts/support-matrix/plugs/browser.py
index cad61e35..775bfb62 100644
--- a/scripts/support-matrix/plugs/browser.py
+++ b/scripts/support-matrix/plugs/browser.py
@@ -97,6 +97,10 @@ def run_base(call, base: str, model: str, keep: bool, log) -> dict:
if status in ("completed", "failed", "incomplete", "cancelled"):
break
time.sleep(6)
+ if status not in ("completed", "failed", "incomplete", "cancelled"):
+ # Given up on: stop it, as the family tour does. Left running, a jcode turn looping on
+ # a browser it could not connect went on for two hours past this point (rc.7).
+ call("POST", f"/v1/responses/{rid}/cancel", {})
out["status"] = status
out["model"] = model or (str(d.get("model") or "") if isinstance(d, dict) else "") # the turn's own model: the base's default
text = "".join(p.get("text") or "" for it in (d.get("output") or []) for p in (it.get("content") or [])
diff --git a/scripts/support-matrix/run.mjs b/scripts/support-matrix/run.mjs
index bd6b361d..b630a13f 100644
--- a/scripts/support-matrix/run.mjs
+++ b/scripts/support-matrix/run.mjs
@@ -186,12 +186,20 @@ try {
log(`FIRST ${k} ${rec.first.ok ? 'ok' : 'FAIL'} ${rec.first.s}s ${rec.first.why}`);
if (rec.first.ok) {
rec.followup = expectWord(await turn(`Reply with exactly: M2-${m}`), `M2-${m}`);
+ // This turn's OWN answer must not carry the first turn's: a base that replayed its whole
+ // transcript at the end of each turn answered "M1-…M2-…" and passed on the M2 alone
+ // (opensquilla, found by hand on 2026-10-13: a sixth answer opened with the first).
+ if (rec.followup.ok && (rec.followup.answer || '').includes(`M1-${m}`)) {
+ rec.followup = { ...rec.followup, ok: false, why: `the follow-up repeats the first turn's answer: ${rec.followup.answer.slice(-200)}` };
+ }
log(`FOLLOWUP ${k} ${rec.followup.ok ? 'ok' : 'FAIL'} ${rec.followup.s}s ${rec.followup.why}`);
// the partner must be one Codex can carry on with: gpt-5.3-codex and the gpt-5.6 line refuse each
// other's threads by design (#73), and that rule is not what the switch row measures
// Codex refuses gpt-5.3-codex after any other model (measured after gpt-5.5 and after the gpt-5.6
- // line), so a switch away and back can only fail by design: that row is n/a, not a measurement
- const conflicts = (a, c) => a === 'gpt-5.3-codex' || c === 'gpt-5.3-codex';
+ // line), so a switch away and back can only fail by design: that row is n/a, not a measurement.
+ // Codex's rule alone: mimo switches into and out of gpt-5.3-codex (measured 2026-10-12), and
+ // applying it to every base left that switch unmeasured on every other base offering the id
+ const conflicts = (a, c) => h === 'codex' && (a === 'gpt-5.3-codex' || c === 'gpt-5.3-codex');
const other = runnableAll.find((x) => x !== m && !conflicts(m, x)) || null;
if (other) { await pickModel(other); rec.switch = { to: other, ...expectWord(await turn(`Reply with exactly: M3-${other}`), `M3-${other}`) }; }
else rec.switch = { to: null, ok: null, why: 'only one model' };
diff --git a/scripts/support-matrix/ui-conversation-switch.mjs b/scripts/support-matrix/ui-conversation-switch.mjs
new file mode 100644
index 00000000..fc816ebf
--- /dev/null
+++ b/scripts/support-matrix/ui-conversation-switch.mjs
@@ -0,0 +1,83 @@
+// ui-conversation-switch.mjs: the conversation a person ran by hand, through the console. A custom
+// harness on HBASE whose instruction makes a PDF; five turns in ONE conversation, each on the next
+// model in MODELS, chosen on the model chip: "say hi", "improve the style", then three colour
+// changes. Every turn must complete inside CAP_S (else it is stopped and called a loop), be served
+// by the model asked for, hand back a PDF that differs from the turn before's, and answer for itself
+// (no earlier answer replayed in front of it).
+// Env BASE, HR_PASS, HBASE, MODELS (comma list, one per turn), CAP_S (default 480), SHOT, RESULTS.
+import fs from 'node:fs';
+import { chromium } from 'playwright';
+const BASE = process.env.BASE, HB = process.env.HBASE, MODELS = (process.env.MODELS || '').split(',').filter(Boolean);
+const CAP_S = Number(process.env.CAP_S || 480);
+const INSTR = 'Use pdf gen skill to generate a pdf with your desired output text';
+// the first turn asks for the instruction outright: "say hi" alone leaves a PDF to the model's
+// judgement, and gpt-5.6-luna (nanobot) and qfmodel (qoder) answered "Hi!" without one although the
+// instruction reached them (a marker it asked for came back, 2026-10-13)
+const PROMPTS = ['follow your instruction: say hi', 'improve the style', 'change background to purple', 'change to red', 'change to green'];
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
+const b = await chromium.launch(); const page = await (await b.newContext({ viewport: { width: 1440, height: 900 } })).newPage();
+const rt = (sel, v) => page.$eval(sel, (el, x) => { Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, x); el.dispatchEvent(new Event('input', { bubbles: true })); }, v);
+const dismissWelcome = async () => { for (let i = 0; i < 4 && (await page.locator('.welcome-overlay').count()); i++) { await page.locator('.welcome-overlay .welcome-wide-close').click().catch(() => {}); await sleep(600); } };
+const api = (method, path, body) => page.evaluate(async ([m, p, bd]) => { const r = await fetch('/api/harness' + p, { method: m, headers: { 'content-type': 'application/json' }, body: bd ? JSON.stringify(bd) : undefined }); let j = null; try { j = await r.json(); } catch {} return { s: r.status, j }; }, [method, path, body]);
+const sha = (url) => page.evaluate(async (u) => { const r = await fetch('/api/harness' + u); if (!r.ok) return ''; const d = await crypto.subtle.digest('SHA-256', await r.arrayBuffer()); return [...new Uint8Array(d)].map((x) => x.toString(16).padStart(2, '0')).join('').slice(0, 16); }, url);
+const pickModel = async (id) => {
+ await page.click('.ar2-chip'); await sleep(500);
+ const opt = page.locator('.wbx-model-opt', { hasText: new RegExp('^' + id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(\\s|$)') }).first();
+ await opt.waitFor({ timeout: 15000 }); await opt.click(); await sleep(400);
+};
+const rows = []; let fails = 0;
+try {
+ await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' }); await sleep(2500);
+ if (page.url().includes('/login')) { await rt('#sh-user', 'harnessrouter'); await rt('#sh-pass', process.env.HR_PASS); await page.click('button[type=submit]'); await page.waitForURL((u) => !u.pathname.includes('/login'), { timeout: 60000, waitUntil: 'commit' }); }
+ await sleep(1500); await dismissWelcome();
+ const made = await api('POST', '/v1/harnesses', { name: `overnight-${HB}-conversation`, base: HB, system_prompt: INSTR, default_model: MODELS[0] });
+ if (made.s !== 200) throw new Error(`harness create ${made.s} ${JSON.stringify(made.j).slice(0, 200)}`);
+ const hid = made.j.id;
+ await page.goto(`${BASE}/harnesses?h=${hid}`, { waitUntil: 'domcontentloaded' }); await sleep(3500); await dismissWelcome();
+ for (let i = 0; i < 10 && !(await page.locator('.wbx-conv-main.is-hero').count()); i++) { await page.click('button:has-text("New task")').catch(() => {}); await sleep(800); }
+ let sid = '', prevSha = '', prevAnswers = [];
+ for (let k = 0; k < PROMPTS.length; k++) {
+ const model = MODELS[k % MODELS.length];
+ await page.locator('textarea.wbx-composer-input:not([disabled])').waitFor({ timeout: 120000 });
+ await pickModel(model);
+ await page.fill('textarea.wbx-composer-input', PROMPTS[k]); await page.locator('button.wbx-send').click();
+ if (!sid) { await page.waitForURL((u) => u.searchParams.get('sid'), { timeout: 30000, waitUntil: 'commit' }); sid = new URL(page.url()).searchParams.get('sid'); }
+ const t0 = Date.now(); let last = null, loop = false;
+ while (true) {
+ const t = (await api('GET', `/v1/sessions/${sid}/turns`)).j?.turns || [];
+ if (t.length === k + 1 && ['completed', 'failed', 'incomplete', 'cancelled'].includes(t[k].status)) { last = t[k]; break; }
+ if ((Date.now() - t0) / 1000 > CAP_S) {
+ loop = true;
+ const stop = page.locator('button.wbx-stop, button:has-text("Stop")').first();
+ if (await stop.count()) await stop.click().catch(() => {}); else await api('POST', `/v1/sessions/${sid}/cancel`, {});
+ await sleep(8000); last = ((await api('GET', `/v1/sessions/${sid}/turns`)).j?.turns || [])[k] || null; break;
+ }
+ await sleep(4000);
+ }
+ const secs = Math.round((Date.now() - t0) / 1000);
+ const ans = String(last?.assistant || '');
+ const pdfs = (last?.files || []).filter((f) => /\.pdf$/i.test(f.filename || f.name || ''));
+ const h = pdfs.length ? await sha(pdfs[pdfs.length - 1].download_url) : '';
+ const served = String(last?.served_model || '');
+ const servedOk = last?.model === model && (!served || served.toLowerCase().replace(/^[a-z-]+\//, '').replace(/[._-]/g, '').includes(model.toLowerCase().replace(/[._-]/g, '').slice(0, 6)));
+ const replay = prevAnswers.some((p) => p.length > 12 && ans.startsWith(p.slice(0, 40)));
+ const changed = k === 0 ? !!h : (!!h && h !== prevSha);
+ const ok = !loop && last?.status === 'completed' && changed && servedOk && !replay;
+ if (!ok) fails++;
+ const row = { turn: k + 1, prompt: PROMPTS[k], model, served, status: loop ? `stopped after ${CAP_S}s (loop)` : last?.status, seconds: secs,
+ tools: (last?.tools || []).length, pdf: pdfs.map((f) => f.filename || f.name), pdf_changed: changed, replay, ok, answer: ans.replace(/\s+/g, ' ').slice(0, 160) };
+ rows.push(row);
+ log(ok ? 'PASS' : 'FAIL', HB, `turn ${k + 1}`, model, `served ${served || '-'}`, row.status, `${secs}s`, `tools ${row.tools}`, `pdf ${row.pdf.join(',') || 'none'}${changed ? '' : ' (unchanged)'}`, replay ? 'REPLAY' : '', '|', row.answer.slice(0, 80));
+ if (h) prevSha = h; prevAnswers.push(ans);
+ if (loop) break;
+ }
+ await sleep(2000);
+ await page.screenshot({ path: process.env.SHOT || `conv-${HB}.png`, fullPage: false });
+ log(fails ? 'FAIL' : 'PASS', HB, `${rows.filter((r) => r.ok).length} of ${PROMPTS.length} turns`, `session ${sid}`);
+} catch (e) {
+ fails++; log('FAIL', HB, 'driver error', String(e).slice(0, 300));
+} finally {
+ if (process.env.RESULTS) fs.writeFileSync(process.env.RESULTS, JSON.stringify({ base: HB, models: MODELS, rows, fails }, null, 1));
+ await b.close();
+}
diff --git a/scripts/support-matrix/ui-tool-rows-live.mjs b/scripts/support-matrix/ui-tool-rows-live.mjs
new file mode 100644
index 00000000..bab7d5de
--- /dev/null
+++ b/scripts/support-matrix/ui-tool-rows-live.mjs
@@ -0,0 +1,34 @@
+// ui-tool-rows-live.mjs: the tool row opens WHILE the turn runs. One console task on HARNESS (model
+// MODEL, optional) runs a command that sleeps; while the turn still shows Working…, the shell row
+// (ROW, a regex) must be openable and show the command. Env BASE, HR_PASS, HARNESS, MODEL, ROW, SHOT.
+import { chromium } from 'playwright';
+const BASE = process.env.BASE, H = process.env.HARNESS || 'opensquilla', WORD = `live-row-${Date.now() % 100000}`;
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const b = await chromium.launch(); const page = await (await b.newContext({ viewport: { width: 1440, height: 900 } })).newPage();
+const rt = (sel, v) => page.$eval(sel, (el, x) => { Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, x); el.dispatchEvent(new Event('input', { bubbles: true })); }, v);
+const dismissWelcome = async () => { for (let i = 0; i < 4 && (await page.locator('.welcome-overlay').count()); i++) { await page.locator('.welcome-overlay .welcome-wide-close').click().catch(() => {}); await sleep(600); } };
+try {
+ await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' }); await sleep(2500);
+ if (page.url().includes('/login')) { await rt('#sh-user', 'harnessrouter'); await rt('#sh-pass', process.env.HR_PASS); await page.click('button[type=submit]'); await page.waitForURL((u) => !u.pathname.includes('/login'), { timeout: 60000, waitUntil: 'commit' }); }
+ await sleep(1500); await dismissWelcome();
+ await page.goto(`${BASE}/harnesses?h=${H}`, { waitUntil: 'domcontentloaded' }); await sleep(3500); await dismissWelcome();
+ for (let i = 0; i < 10 && !(await page.locator('.wbx-conv-main.is-hero').count()); i++) { await page.click('button:has-text("New task")').catch(() => {}); await sleep(800); }
+ if (process.env.MODEL) {
+ await page.click('.ar2-chip'); await sleep(500);
+ await page.locator('.wbx-model-opt', { hasText: new RegExp('^' + process.env.MODEL.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(\\s|$)') }).first().click(); await sleep(300);
+ }
+ await page.fill('textarea.wbx-composer-input', `Run exactly this one shell command and nothing else: sleep 30; echo ${WORD} Then reply with its output.`);
+ await page.locator('button.wbx-send').click();
+ const row = page.locator('button.wbx-act-row', { hasText: new RegExp(process.env.ROW || 'exec', 'i') }).first();
+ let shown = '', running = false, t0 = Date.now();
+ for (let i = 0; i < 90; i++) {
+ running = (await page.getByText('Working…').count()) > 0;
+ if (await row.count()) {
+ if (!(await row.isDisabled())) { await row.click(); await sleep(600); shown = await row.evaluate((x) => (x.parentElement?.textContent || '').replace(/\s+/g, ' ').slice(0, 400)); running = (await page.getByText('Working…').count()) > 0; break; }
+ }
+ await sleep(1000);
+ }
+ await page.screenshot({ path: process.env.SHOT || 'ui-tool-rows-live.png', fullPage: false });
+ const ok = running && shown.includes(`echo ${WORD}`);
+ console.log(ok ? 'PASS' : 'FAIL', H, `${Math.round((Date.now() - t0) / 1000)}s`, 'turn still running:', running, '| row shows:', shown.slice(0, 220));
+} finally { await b.close(); }
diff --git a/scripts/support-matrix/ui-tool-rows.mjs b/scripts/support-matrix/ui-tool-rows.mjs
new file mode 100644
index 00000000..292d989c
--- /dev/null
+++ b/scripts/support-matrix/ui-tool-rows.mjs
@@ -0,0 +1,37 @@
+// ui-tool-rows.mjs: one console task on HARNESS that runs a shell command; then every tool row of the
+// answer must open, and the shell row must show the command it ran. Env BASE, HR_PASS, HARNESS, SHOT,
+// ROW (the shell row's label as a regex: bash on jcode, exec_command on opensquilla; default bash).
+import { chromium } from 'playwright';
+const BASE = process.env.BASE, H = process.env.HARNESS || 'jcode', WORD = `ui-row-${Date.now() % 100000}`;
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const b = await chromium.launch(); const page = await (await b.newContext({ viewport: { width: 1440, height: 900 } })).newPage();
+try {
+ // run.mjs's login: the native value setter plus an input event (React reads the event, not fill's keystrokes)
+ const rt = (sel, v) => page.$eval(sel, (el, x) => { Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, x); el.dispatchEvent(new Event('input', { bubbles: true })); }, v);
+ const dismissWelcome = async () => { for (let i = 0; i < 4 && (await page.locator('.welcome-overlay').count()); i++) { await page.locator('.welcome-overlay .welcome-wide-close').click().catch(() => {}); await sleep(600); } };
+ await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' }); await sleep(2500);
+ if (page.url().includes('/login')) { await rt('#sh-user', 'harnessrouter'); await rt('#sh-pass', process.env.HR_PASS); await page.click('button[type=submit]'); await page.waitForURL((u) => !u.pathname.includes('/login'), { timeout: 60000, waitUntil: 'commit' }); }
+ await sleep(1500); await dismissWelcome();
+ await page.goto(`${BASE}/harnesses?h=${H}`, { waitUntil: 'domcontentloaded' }); await sleep(3500); await dismissWelcome();
+ for (let i = 0; i < 10 && !(await page.locator('.wbx-conv-main.is-hero').count()); i++) { await page.click('button:has-text("New task")').catch(() => {}); await sleep(800); }
+ await page.fill('textarea.wbx-composer-input', `Run the shell command \`echo ${WORD}\` and reply with its output.`);
+ await page.locator('button.wbx-send').click();
+ await page.waitForURL((u) => u.searchParams.get('sid'), { timeout: 30000, waitUntil: 'commit' });
+ const sid = new URL(page.url()).searchParams.get('sid');
+ for (let i = 0; i < 100; i++) {
+ const st = await page.evaluate(async (s) => { const r = await fetch(`/api/harness/v1/sessions/${s}/turns`); const j = await r.json(); const t = (j.turns || []).slice(-1)[0] || {}; return t.status || ''; }, sid);
+ if (['completed', 'failed', 'incomplete', 'cancelled'].includes(st)) break; await sleep(3000);
+ }
+ await sleep(3000);
+ // a finished turn folds its tools under "Used N tools": open the group first, as a person would
+ const group = page.getByText(/^Used (a|\d+) tools?$/).first(); // "Used a tool" for one
+ if (await group.count()) { await group.click(); await sleep(800); }
+ const rows = await page.evaluate(() => [...document.querySelectorAll('button.wbx-act-row')].map((x) => ({ label: x.textContent.trim().slice(0, 40), disabled: x.disabled })));
+ console.log('ROWS', JSON.stringify(rows));
+ const bash = page.locator('button.wbx-act-row', { hasText: new RegExp(process.env.ROW || 'bash', 'i') }).first();
+ let shown = '';
+ if (await bash.count()) { await bash.click(); await sleep(800); shown = await bash.evaluate((x) => (x.parentElement?.textContent || '').replace(/\s+/g, ' ').slice(0, 400)); }
+ await page.screenshot({ path: process.env.SHOT || 'ui-tool-rows.png', fullPage: false });
+ const ok = rows.length > 0 && rows.every((r) => !r.disabled) && shown.includes(`echo ${WORD}`);
+ console.log(ok ? 'PASS' : 'FAIL', H, 'shell row shows:', shown.slice(0, 200));
+} finally { await b.close(); }
diff --git a/scripts/support-matrix/ui-turns-own.mjs b/scripts/support-matrix/ui-turns-own.mjs
new file mode 100644
index 00000000..3730ffb4
--- /dev/null
+++ b/scripts/support-matrix/ui-turns-own.mjs
@@ -0,0 +1,41 @@
+// ui-turns-own.mjs: several turns in ONE console conversation on HARNESS (model MODEL); each turn's
+// stored answer and tool count must be that turn's alone, never the conversation so far replayed.
+// Env BASE, HR_PASS, HARNESS, MODEL, SHOT.
+import { chromium } from 'playwright';
+const BASE = process.env.BASE, H = process.env.HARNESS || 'opensquilla', N = Date.now() % 100000;
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const b = await chromium.launch(); const page = await (await b.newContext({ viewport: { width: 1440, height: 900 } })).newPage();
+const rt = (sel, v) => page.$eval(sel, (el, x) => { Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, x); el.dispatchEvent(new Event('input', { bubbles: true })); }, v);
+const dismissWelcome = async () => { for (let i = 0; i < 4 && (await page.locator('.welcome-overlay').count()); i++) { await page.locator('.welcome-overlay .welcome-wide-close').click().catch(() => {}); await sleep(600); } };
+const steps = [`Reply with exactly: ONE-${N}`, `Run the shell command \`echo TWO-${N}\` and reply with its output only.`,
+ `Reply with exactly: THREE-${N}`, `Run the shell command \`echo FOUR-${N}\` and reply with its output only.`];
+let fails = 0;
+try {
+ await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' }); await sleep(2500);
+ if (page.url().includes('/login')) { await rt('#sh-user', 'harnessrouter'); await rt('#sh-pass', process.env.HR_PASS); await page.click('button[type=submit]'); await page.waitForURL((u) => !u.pathname.includes('/login'), { timeout: 60000, waitUntil: 'commit' }); }
+ await sleep(1500); await dismissWelcome();
+ await page.goto(`${BASE}/harnesses?h=${H}`, { waitUntil: 'domcontentloaded' }); await sleep(3500); await dismissWelcome();
+ for (let i = 0; i < 10 && !(await page.locator('.wbx-conv-main.is-hero').count()); i++) { await page.click('button:has-text("New task")').catch(() => {}); await sleep(800); }
+ if (process.env.MODEL) { await page.click('.ar2-chip'); await sleep(500); await page.locator('.wbx-model-opt', { hasText: new RegExp('^' + process.env.MODEL.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(\\s|$)') }).first().click(); await sleep(300); }
+ let sid = '';
+ for (let k = 0; k < steps.length; k++) {
+ await page.locator('textarea.wbx-composer-input:not([disabled])').waitFor({ timeout: 120000 });
+ await page.fill('textarea.wbx-composer-input', steps[k]); await page.locator('button.wbx-send').click();
+ if (!sid) { await page.waitForURL((u) => u.searchParams.get('sid'), { timeout: 30000, waitUntil: 'commit' }); sid = new URL(page.url()).searchParams.get('sid'); }
+ let last = null;
+ for (let i = 0; i < 100; i++) {
+ const t = await page.evaluate(async (s) => (await (await fetch(`/api/harness/v1/sessions/${s}/turns`)).json()).turns || [], sid);
+ if (t.length === k + 1 && ['completed', 'failed', 'incomplete', 'cancelled'].includes(t[k].status)) { last = t[k]; break; }
+ await sleep(3000);
+ }
+ const ans = String(last?.assistant || ''); const tools = (last?.tools || []).length;
+ const earlier = ['ONE', 'TWO', 'THREE', 'FOUR'].slice(0, k).map((w) => `${w}-${N}`).filter((w) => ans.includes(w));
+ const own = ans.includes(['ONE', 'TWO', 'THREE', 'FOUR'][k] + `-${N}`);
+ const ok = last?.status === 'completed' && own && earlier.length === 0;
+ if (!ok) fails++;
+ console.log(ok ? 'PASS' : 'FAIL', `turn ${k + 1}`, `tools ${tools}`, earlier.length ? `repeats ${earlier.join(',')}` : '', '|', ans.replace(/\s+/g, ' ').slice(0, 90));
+ }
+ await sleep(2500);
+ await page.screenshot({ path: process.env.SHOT || 'ui-turns-own.png', fullPage: false });
+ console.log(fails ? 'FAIL' : 'PASS', H, `${steps.length} turns, each its own answer`);
+} finally { await b.close(); }
diff --git a/ui/src/lib/conversation.ts b/ui/src/lib/conversation.ts
index 63f2c765..663f2944 100644
--- a/ui/src/lib/conversation.ts
+++ b/ui/src/lib/conversation.ts
@@ -17,6 +17,7 @@ import { getCurrentWorkspaceRef } from '@/lib/workspace';
import { track } from '@/lib/analytics';
import { billing } from '@/app/(app)/billing/lib';
import { oobById } from '@/lib/harness';
+import { fillStep } from '@/lib/tool-steps';
import { withText, withReasoning, withStep, withResult } from 'reifyui';
import { createConversationStore } from 'reifyui';
@@ -52,7 +53,8 @@ function beforeError(blocks: Block[], apply: (rest: Block[]) => Block[]): Block[
}
const addText = (blocks: Block[], d: string): Block[] => beforeError(blocks, (r) => withText(r, d));
const addReasoning = (blocks: Block[], d: string): Block[] => beforeError(blocks, (r) => withReasoning(r, d));
-const addStep = (blocks: Block[], step: ToolStep): Block[] => beforeError(blocks, (r) => withStep(r, step));
+const addStep = (blocks: Block[], step: ToolStep): Block[] =>
+ fillStep(blocks, step) ?? beforeError(blocks, (r) => withStep(r, step));
const addResult = (blocks: Block[], callId: string, output: string): Block[] => beforeError(blocks, (r) => withResult(r, callId, output));
function errorBlock(blocks: Block[], msg: string): Block {
return { kind: 'text', text: (blocks.length ? '\n\n' : '') + 'Error: ' + msg, error: true };
diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.ts
index 5322fa0a..766faef4 100644
--- a/ui/src/lib/harness.ts
+++ b/ui/src/lib/harness.ts
@@ -219,29 +219,29 @@ export const OOB: OobHarness[] = [
// Placeholder only: the gateway's catalog wins once fetched. Qoder's own model ids, as its
// GET /models lists them for the tenant; the runtime is Qoder's cloud, not a process on this
// box, and Qoder picks and bills the model behind an id.
- models: ['auto', 'ultimate', 'performance', 'efficient', 'smodel', 'qmodel_38max', 'qfmodel', 'qmodel_latest', 'qmodel', 'kmodel_latest', 'kmodel', 'gmodel', 'gfmodel', 'dmodel', 'dfmodel', 'mmodel'], defaultModel: 'ultimate', moreModels: 0,
+ models: ['auto', 'ultimate', 'performance', 'efficient', 'smodel', 'qmodel_38max', 'qmodel_latest', 'qmodel', 'kmodel_latest', 'kmodel', 'gmodel', 'gfmodel', 'dmodel', 'dfmodel', 'mmodel'], defaultModel: 'ultimate', moreModels: 0,
systemPrompt: 'You are Qoder, an autonomous coding agent running in a cloud sandbox with shell and file access. Read, edit and run what the task needs, and deliver every file the user should receive with DeliverArtifacts.',
tools: ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'WebFetch', 'WebSearch', 'ImageSearch', 'ImageGen', 'DeliverArtifacts'], skills: [] },
{ id: 'mimo', name: 'MiMo Code', version: 'v0.1.15', backend: 'mimo', status: 'ready',
// Placeholder only, like every list above: the gateway's catalog wins once fetched. MiMo Code is
// an opencode fork and reaches what opencode reaches, so the list is opencode's.
- models: ['gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.3-codex', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-4-maverick', 'llama-3.3-70b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning', 'nemotron-3-super'], defaultModel: 'gpt-5.4', moreModels: 0,
+ models: ['gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.5', 'gpt-5.4', 'gpt-5.3-codex', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-sonnet-4.6', 'claude-haiku-5.5', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'step-3.7-flash', 'nemotron-3.5-lightning'], defaultModel: 'gpt-5.4', moreModels: 0,
systemPrompt: 'You are MiMo 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: [] },
{ id: 'jcode', name: 'jcode', version: 'v0.90.0', backend: 'jcode', status: 'ready',
// Placeholder only. jcode speaks one OpenAI shape, chat/completions, through the relay, so the
// list is the other chat-completions bases' and the two Responses-only ids are not on it.
- models: ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', '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', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-3.3-70b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning', 'nemotron-3-super'], defaultModel: 'gpt-5.4', moreModels: 0,
+ models: ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', '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', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'muse-spark-1.3', 'muse-spark-1.2', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'nemotron-3.5-lightning'], defaultModel: 'gpt-5.4', moreModels: 0,
systemPrompt: 'You are jcode, 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: 'opensquilla', name: 'OpenSquilla', version: 'v0.5.6', backend: 'opensquilla', status: 'ready',
// Placeholder only; the chat-completions list, for jcode's reason.
- models: ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', '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', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-3.3-70b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning', 'nemotron-3-super'], defaultModel: 'gpt-5.4', moreModels: 0,
+ models: ['gpt-6-sol', 'gpt-6-luna', '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', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-sonnet-4.6', 'claude-haiku-5.5', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'nemotron-3.5-lightning'], defaultModel: 'gpt-5.4', moreModels: 0,
systemPrompt: 'You are OpenSquilla, an autonomous 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: 'nanobot', name: 'nanobot', version: 'v0.3.5', backend: 'nanobot', status: 'ready',
// Placeholder only; the chat-completions list, for jcode's reason.
- models: ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', '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', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-3.3-70b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning', 'nemotron-3-super'], defaultModel: 'gpt-5.4', moreModels: 0,
+ models: ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5.5', 'claude-opus-5', 'claude-sonnet-5.5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-5.5', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.3', 'grok-4.20', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning'], defaultModel: 'gpt-5.4', moreModels: 0,
systemPrompt: 'You are nanobot, an autonomous 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: [] },
];
diff --git a/ui/src/lib/tool-steps.test.ts b/ui/src/lib/tool-steps.test.ts
new file mode 100644
index 00000000..54f88100
--- /dev/null
+++ b/ui/src/lib/tool-steps.test.ts
@@ -0,0 +1,27 @@
+import { fillStep } from './tool-steps';
+
+type Blk = { kind: 'text'; text: string } | { kind: 'tools'; reasoning: string; steps: { name: string; args: string; result?: string; callId?: string }[] };
+const tools = (steps: { name: string; args: string; result?: string; callId?: string }[]): Blk => ({ kind: 'tools', reasoning: '', steps });
+
+describe('fillStep', () => {
+ it('puts late arguments on the row the call started, not a new row', () => {
+ const blocks: Blk[] = [tools([{ name: 'exec_command', args: '{}', callId: 'call_1' }]), { kind: 'text', text: 'working' }];
+ const out = fillStep(blocks, { name: 'exec_command', args: '{"cmd":"echo one"}', callId: 'call_1' });
+ expect(out).not.toBeNull();
+ const t = out![0] as Extract<Blk, { kind: 'tools' }>;
+ expect(t.steps).toHaveLength(1);
+ expect(t.steps[0].args).toBe('{"cmd":"echo one"}');
+ expect(blocks[0]).toEqual(tools([{ name: 'exec_command', args: '{}', callId: 'call_1' }])); // not mutated
+ });
+
+ it('leaves everything else to append, as before', () => {
+ const answered: Blk[] = [tools([{ name: 'bash', args: '{}', callId: 'tool', result: 'ok' }])];
+ expect(fillStep(answered, { name: 'bash', args: '{"command":"ls"}', callId: 'tool' })).toBeNull();
+ const other: Blk[] = [tools([{ name: 'read', args: '{}', callId: 'x' }])];
+ expect(fillStep(other, { name: 'write', args: '{"path":"a"}', callId: 'x' })).toBeNull();
+ const full: Blk[] = [tools([{ name: 'bash', args: '{"command":"ls"}', callId: 'c' }])];
+ expect(fillStep(full, { name: 'bash', args: '{"command":"ls"}', callId: 'c' })).toBeNull();
+ expect(fillStep(other, { name: 'read', args: '{}', callId: 'x' })).toBeNull();
+ expect(fillStep(other, { name: 'read', args: '{"p":1}' })).toBeNull();
+ });
+});
diff --git a/ui/src/lib/tool-steps.ts b/ui/src/lib/tool-steps.ts
new file mode 100644
index 00000000..283688b3
--- /dev/null
+++ b/ui/src/lib/tool-steps.ts
@@ -0,0 +1,23 @@
+// A call sent again with its arguments after it started without any fills its own row: opensquilla
+// announces a call with none and its arguments arrive when the turn ends. Only a row with the same
+// call id and name, no arguments yet and no result is filled; anything else adds a row, as before
+// (null tells the caller to append).
+interface Step { name: string; args: string; result?: string; callId?: string }
+type Blk = { kind: 'text'; text: string; error?: true } | { kind: 'tools'; reasoning: string; steps: Step[] };
+
+export function fillStep<B extends Blk>(blocks: B[], step: Step): B[] | null {
+ if (!step.callId || !step.args || step.args === '{}') return null;
+ for (let i = blocks.length - 1; i >= 0; i--) {
+ const b = blocks[i];
+ if (b.kind !== 'tools') continue;
+ const j = b.steps.findIndex((s) => s.callId === step.callId && s.name === step.name
+ && (!s.args || s.args === '{}') && s.result === undefined);
+ if (j < 0) continue;
+ const steps = b.steps.slice();
+ steps[j] = { ...steps[j], args: step.args };
+ const out = blocks.slice();
+ out[i] = { ...b, steps };
+ return out;
+ }
+ return null;
+}