Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(openclaw): defer tool schemas when the inline catalog does not fit the window (#967)

Ruben Lütke9a920f5780b8
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.md
index a739326a95..4742a2c881 100644
--- a/docs/agent-runtimes.md
+++ b/docs/agent-runtimes.md
@@ -369,17 +369,26 @@ replayed during `session/load` is swallowed because the chat already shows it.
model to search, describe and call through `tool_search` / `tool_describe` /
`tool_call` and to answer greetings directly; a resumed session's pinned
eager tool catalog is invalidated first (`tool_snapshot.py`) so the deferred
- configuration takes effect. OpenClaw offers the tools directly
- (`tools.toolSearch: false`) on every route but the ChatGPT subscription: a
- 9B local model never found deferred tools there. On the subscription it uses
- OpenClaw's structured Tool Search (`tools.toolSearch: {mode: "tools"}`):
- ChatGPT's backend accepted a turn carrying the whole inline catalog (~400
- tools, ~580 KB of schemas) with HTTP 200 and then ended it as
+ configuration takes effect. OpenClaw decides per route
+ (`openclaw._tool_search`): it uses its structured Tool Search
+ (`tools.toolSearch: {mode: "tools"}`, the three controls plus a bounded
+ directory OpenClaw sizes to the window) on the ChatGPT subscription, on a
+ model server the person runs (Ollama, a local OpenAI server), on any window
+ below 128k tokens, and wherever the live catalog's inline schemas (estimated
+ from Dodaios' MCP catalog at about four characters per token) would take more
+ than a quarter of the window. Only a large cloud window whose catalog fits
+ gets the schemas directly (`tools.toolSearch: false`). Live 2026-10-27, a
+ qwen3.5:9b agent on a 64k Ollama window carried ~239 plugin tools inline
+ (`estimatedPromptTokens=225052`), overflowed before answering "ok", and its
+ compaction timed out after 180 s; deferred, the same catalog makes a 34 KB
+ request of 12 tools that Ollama counts as 8,384 prompt tokens. On the
+ subscription, ChatGPT's backend accepted a turn carrying the whole inline
+ catalog (~400 tools, ~580 KB of schemas) with HTTP 200 and then ended it as
`response.incomplete` (`max_output_tokens`, zero usage) on every retry.
- Size alone is not the trigger: 400 synthetic tools (~210k tokens) passed,
- while every failing slice of the live catalog held its only `oneOf` schemas
- (Linear's `save_*` tools), so deferring keeps third-party schema shapes off
- the backend's function list.
+ Size alone is not the trigger there: 400 synthetic tools (~210k tokens)
+ passed, while every failing slice of the live catalog held its only `oneOf`
+ schemas, so deferring keeps third-party schema shapes off the backend's
+ function list. The Claude CLI route keeps its own tool surface.
- **Subscription stream failures:** a failure the backend reports inside an
accepted stream (`error`, `response.failed`, `response.incomplete`) is logged
with its event type, code, reason and a short redacted message
diff --git a/dodaios/agent_runtimes/openclaw.py b/dodaios/agent_runtimes/openclaw.py
index 723f624d13..f57f228e91 100644
--- a/dodaios/agent_runtimes/openclaw.py
+++ b/dodaios/agent_runtimes/openclaw.py
@@ -589,7 +589,9 @@ class OpenClawRuntime:
"tools": {
"deny": denied,
"exec": {"mode": exec_mode},
- "toolSearch": _tool_search(route.transport),
+ "toolSearch": _tool_search(
+ route, _inline_catalog_tokens() if turn.mcp_url and turn.control_key else 0
+ ),
},
# The agent's log stays in its own folder, never in the shared
# temp-folder log every OpenClaw on the machine appends to.
@@ -833,7 +835,8 @@ class OpenClawRuntime:
).hexdigest()
current = self._gateways.get(key)
port = current.port if current is not None and current.alive() else _free_port()
- config = self.config_for(turn, port=port, token=token)
+ # Off the event loop: the config sizes the live tool catalog.
+ config = await asyncio.to_thread(self.config_for, turn, port=port, token=token)
changed = await asyncio.to_thread(
write_json_if_changed, home / "openclaw.json", config
)
@@ -895,11 +898,8 @@ class OpenClawRuntime:
# The port was taken before the Gateway bound it: once more on a
# fresh port.
port = _free_port()
- await asyncio.to_thread(
- write_json_if_changed,
- home / "openclaw.json",
- self.config_for(turn, port=port, token=token),
- )
+ config = await asyncio.to_thread(self.config_for, turn, port=port, token=token)
+ await asyncio.to_thread(write_json_if_changed, home / "openclaw.json", config)
gateway = await self._spawn_until_ready(
key, home, port, env_hash, launcher, env, lock, last_try=True
)
@@ -1064,23 +1064,77 @@ def _use_claude_cli(config: dict[str, Any], turn: RuntimeTurn) -> None:
tools["deny"] = [*tools["deny"], "exec", "process"]
-def _tool_search(transport: str) -> Any:
- """``tools.toolSearch``: deferred schemas on the ChatGPT subscription only.
-
- Every other route gets Jarvis' tools directly (OpenClaw turns tool search
- on by default for local models; smaller models miss deferred tools). The
- subscription's backend ends a request carrying the whole inline catalog
- (live 2026-10-27: ~400 tools, ~580 KB of schemas from the person's
- connected plugins) as ``response.incomplete`` before any output, on every
- retry. Size alone is not the trigger (400 synthetic tools at ~210k tokens
- passed); the failing slices all held the only ``oneOf`` schemas in the
- catalog, which points at a schema shape the backend refuses inline.
- Hermes on the same seat defers its tools behind ``tool_search`` and
- answers. The structured mode keeps every tool callable through
- ``tool_search`` / ``tool_describe`` / ``tool_call``, and no third-party
- schema reaches the backend as a function declaration.
+#: Windows below this always get deferred tool schemas: OpenClaw's own system
+#: prompt and native tools already take a large share of them.
+_SMALL_WINDOW: Final = 128_000
+#: The largest share of the window an inline tool catalog may take; the rest
+#: is the conversation, OpenClaw's own prompt and the reply.
+_INLINE_CATALOG_SHARE: Final = 0.25
+#: Characters per token for the catalog estimate (JSON schemas, English text).
+_CHARS_PER_TOKEN: Final = 4
+
+
+def _inline_catalog_tokens() -> int:
+ """An estimate of what Dodaios' MCP tools cost as inline schemas.
+
+ Counted from the live tool catalog (names, descriptions, input schemas),
+ so a person with many connected plugins gets the real size. ``0`` when
+ the catalog cannot be read: nothing is offered then.
"""
- return {"mode": "tools"} if transport == "responses" else False
+ try:
+ from dodaios.mcp.dodaios_tools_server import offered_tools
+
+ entries = offered_tools()
+ except Exception: # noqa: BLE001 — an unreadable catalog offers nothing
+ log.debug("agent runtimes: tool catalog size unavailable", exc_info=True)
+ return 0
+ chars = 0
+ for entry in entries:
+ try:
+ schema = json.dumps(getattr(entry, "input_schema", None) or {}, default=str)
+ except (TypeError, ValueError): # an unserializable schema only counts its name and description
+ schema = ""
+ chars += len(str(entry.name)) * 2 + len(str(entry.description or "")) + len(schema) + 32
+ return chars // _CHARS_PER_TOKEN
+
+
+def _tool_search(route: Any, catalog_tokens: int) -> Any:
+ """``tools.toolSearch``: deferred tool schemas wherever inline ones do not fit.
+
+ Deferred (``{"mode": "tools"}``) keeps every tool callable through
+ ``tool_search`` / ``tool_describe`` / ``tool_call`` behind a bounded
+ directory that OpenClaw sizes to the model's window. It is chosen when:
+
+ - the route is the ChatGPT subscription (``responses``): its backend ends
+ a request carrying the whole inline catalog (live 2026-10-27: ~400
+ tools, ~580 KB of schemas) as ``response.incomplete`` before any output;
+ the failing slices all held the catalog's only ``oneOf`` schemas;
+ - the model runs on the person's own server (Ollama, a local OpenAI
+ server): prefill of a large catalog is slow there, and live 2026-10-27
+ ~239 inline tools estimated 225k tokens against a 64k Ollama window, so
+ even "ok" overflowed and compaction timed out;
+ - the window is small (below :data:`_SMALL_WINDOW`);
+ - the inline catalog would take more than :data:`_INLINE_CATALOG_SHARE`
+ of the window.
+
+ Otherwise a large cloud window gets the schemas directly: no discovery
+ round-trips, and smaller catalogs are cheaper inline. The Claude CLI route
+ runs its own tool surface and keeps direct schemas.
+ """
+ from dodaios.agent_runtimes.model_map import is_local
+
+ transport = getattr(route, "transport", "")
+ if transport == "claude_cli":
+ return False
+ window = int(getattr(route, "context_window", 0) or 0)
+ if (
+ transport == "responses"
+ or is_local(str(getattr(route, "provider", "")))
+ or window < _SMALL_WINDOW
+ or catalog_tokens > window * _INLINE_CATALOG_SHARE
+ ):
+ return {"mode": "tools"}
+ return False
def _declared_efforts(turn: RuntimeTurn) -> dict[str, Any]:
diff --git a/tests/unit/agent_runtimes/test_runtime_configs.py b/tests/unit/agent_runtimes/test_runtime_configs.py
index 23fa014751..ba52952589 100644
--- a/tests/unit/agent_runtimes/test_runtime_configs.py
+++ b/tests/unit/agent_runtimes/test_runtime_configs.py
@@ -126,6 +126,20 @@ def test_hermes_discovers_connected_tools_with_explicit_persona_guidance(tmp_pat
assert "Search before concluding a capability is missing" in persona
[email protected]("window", [65_536, 1_000_000])
+def test_hermes_defers_connected_tools_on_every_window(tmp_path, window):
+ """Hermes never sends the catalog inline, so a 64k Ollama window holds
+ only its bounded listing, never hundreds of plugin schemas."""
+ route = ModelRoute(provider="ollama", model="qwen3.5:9b", base_url="http://127.0.0.1:11434/v1",
+ transport="chat_completions", api_key=None, context_window=window)
+ runtime = HermesRuntime()
+ runtime._write_profile(tmp_path, _turn(tmp_path, route=route))
+ config = json.loads((tmp_path / "config.yaml").read_text(encoding="utf-8"))
+ assert config["tools"]["tool_search"]["enabled"] == "on"
+ assert config["tools"]["tool_search"]["listing_max_tokens"] * 4 < window * 0.25
+ assert config["model"]["context_length"] == window
+
+
def test_hermes_profiles_share_installation_but_keep_agent_state_separate(tmp_path, monkeypatch):
from dodaios.agent_runtimes import base, hermes
@@ -230,7 +244,6 @@ def test_openclaw_never_runs_background_turns_or_persona_files(tmp_path):
assert defaults["model"]["primary"] == "jarvis/gpt-5.2" # rename-keep: a model id
assert config["session"]["reset"]["mode"] == "none"
assert "automations" in config["tools"]["deny"]
- assert config["tools"]["toolSearch"] is False
assert config["gateway"]["bind"] == "loopback"
assert config["cron"]["enabled"] is False
assert config["plugins"]["slots"]["memory"] == "none"
@@ -280,22 +293,99 @@ def test_openclaw_subscription_route_uses_the_responses_adapter(tmp_path):
assert config["models"]["providers"]["jarvis"]["api"] == "openai-responses"
+def _sized_route(
+ *, provider: str = "openai", transport: str = "chat_completions", window: int = 400_000
+) -> ModelRoute:
+ return ModelRoute(
+ provider=provider,
+ model="m1",
+ base_url="https://api.example.test/v1",
+ transport=transport, # type: ignore[arg-type]
+ api_key=_SECRET,
+ context_window=window,
+ )
+
+
+def _catalog(monkeypatch, tokens: int) -> None:
+ from dodaios.agent_runtimes import openclaw
+
+ monkeypatch.setattr(openclaw, "_inline_catalog_tokens", lambda: tokens)
+
+
@pytest.mark.parametrize(
- ("transport", "expected"),
+ ("route", "catalog_tokens", "expected"),
[
# The ChatGPT backend ends a request carrying the whole inline tool
# catalog as incomplete (live 2026-10-27), so its tools are deferred.
- ("responses", {"mode": "tools"}),
- ("chat_completions", False),
- ("anthropic_messages", False),
+ (_sized_route(provider="openai-codex", transport="responses"), 1_000, {"mode": "tools"}),
+ # Live 2026-10-27: ~239 inline tools against a 64k Ollama window.
+ (_sized_route(provider="ollama", window=65_536), 180_000, {"mode": "tools"}),
+ # A local server defers even when its window is large.
+ (_sized_route(provider="local-openai", window=262_144), 1_000, {"mode": "tools"}),
+ # A small cloud window defers whatever the catalog.
+ (_sized_route(window=32_768), 1_000, {"mode": "tools"}),
+ # A catalog above a quarter of a large window defers.
+ (_sized_route(window=200_000), 60_000, {"mode": "tools"}),
+ (_sized_route(transport="anthropic_messages", window=200_000), 60_000, {"mode": "tools"}),
+ # A large cloud window with a catalog that fits keeps direct schemas.
+ (_sized_route(window=400_000), 60_000, False),
+ (_sized_route(transport="anthropic_messages", window=200_000), 20_000, False),
],
)
-def test_openclaw_defers_tool_schemas_only_on_the_subscription(tmp_path, transport, expected):
- route = _route(transport=transport)
+def test_openclaw_defers_tool_schemas_where_inline_ones_do_not_fit(
+ tmp_path, monkeypatch, route, catalog_tokens, expected
+):
+ _catalog(monkeypatch, catalog_tokens)
config = OpenClawRuntime().config_for(_turn(tmp_path, route=route), port=1, token=_TOKEN)
assert config["tools"]["toolSearch"] == expected
+def test_openclaw_without_mcp_tools_ignores_the_catalog(tmp_path, monkeypatch):
+ _catalog(monkeypatch, 10_000_000)
+ turn = _turn(tmp_path, route=_sized_route(window=400_000), mcp_url=None, control_key=None)
+ assert OpenClawRuntime().config_for(turn, port=1, token=_TOKEN)["tools"]["toolSearch"] is False
+
+
+def test_openclaw_catalog_estimate_counts_the_live_tool_schemas(monkeypatch):
+ from dodaios.agent_runtimes import openclaw
+ from dodaios.mcp import dodaios_tools_server
+
+ schema = {"type": "object", "properties": {f"p{i}": {"type": "string",
+ "description": "x" * 100} for i in range(20)}}
+ entries = [SimpleNamespace(name=f"plugin_tool_{i}", description="d" * 400,
+ input_schema=schema) for i in range(239)]
+ monkeypatch.setattr(dodaios_tools_server, "offered_tools", lambda: entries)
+ tokens = openclaw._inline_catalog_tokens()
+ one = len(json.dumps(schema)) + 400
+ assert 239 * one // 4 <= tokens <= 239 * (one + 100) // 4
+
+ def broken():
+ raise RuntimeError("no gateway")
+
+ monkeypatch.setattr(dodaios_tools_server, "offered_tools", broken)
+ assert openclaw._inline_catalog_tokens() == 0
+
+
+def test_openclaw_on_a_64k_ollama_route_defers_the_live_sized_catalog(tmp_path, monkeypatch):
+ """The live failure: 239 plugin tools inline overflowed a 64k Ollama
+ window before the model said a word. Deferred, the request carries the
+ three controls and OpenClaw's bounded directory (at most 18,000
+ characters) instead, which leaves the window for the conversation."""
+ from dodaios.mcp import dodaios_tools_server
+
+ schema = {"type": "object", "properties": {f"p{i}": {"type": "string",
+ "description": "y" * 120} for i in range(24)}}
+ entries = [SimpleNamespace(name=f"plugin_tool_{i}", description="z" * 600,
+ input_schema=schema) for i in range(239)]
+ monkeypatch.setattr(dodaios_tools_server, "offered_tools", lambda: entries)
+ route = _sized_route(provider="ollama", window=65_536)
+ config = OpenClawRuntime().config_for(_turn(tmp_path, route=route), port=1, token=_TOKEN)
+ from dodaios.agent_runtimes.openclaw import _inline_catalog_tokens
+
+ assert _inline_catalog_tokens() > 65_536 # inline would not even fit
+ assert config["tools"]["toolSearch"] == {"mode": "tools"}
+
+
def test_openclaw_without_tools_writes_no_mcp_server(tmp_path):
config = OpenClawRuntime().config_for(
_turn(tmp_path, mcp_url=None, control_key=None), port=1, token=_TOKEN