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(agents): OpenClaw file tools ask, the ask tool is reachable, replies stay whole (#1039)

Ruben Lütkeab6646fd588f
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.md
index 8db8a3dc53..762c0b52a0 100644
--- a/docs/agent-runtimes.md
+++ b/docs/agent-runtimes.md
@@ -261,8 +261,31 @@ replayed during `session/load` is swallowed because the chat already shows it.
| Dodaios runtime (brain) | yes | yes | The Dodaios tool gate (`society/approvals.decide`): reads run, everything else shows the card; Always ask shows it for every call. |
| Claude Code seat (`claude-cli`, `glm-cli`) | yes | no | `--permission-mode default`, prompts answered on the chat card (`--permission-prompt-tool stdio`), plus ask rules for this process only (`--settings`, `runner_cli.claude_ask_settings`) for `Edit`, `Write`, `MultiEdit`, `NotebookEdit`, `Bash` and `PowerShell`. Claude Code checks deny, then ask, then allow rules across all settings sources, so the allow list in the person's own `~/.claude/settings.json` can no longer skip the card (checked on Claude Code 2.1.310 against a local mock endpoint: without the ask rules `Write`, `PowerShell` and `Bash` ran with no prompt, with them each one asked); their deny rules still apply and their files are never edited. Reads of Dodaios' own tools (`readOnlyHint`) are answered without a card (`runner_cli.dodaios_read_free`), and a call that an earlier "Always allow" in the same process covers is answered by the runner (a shell prefix rule never covers a chained, piped or redirected command line). Bypass is unchanged. |
| Codex seat (`codex-cli`) | yes | yes | The seat runs with `--ignore-user-config --ignore-rules`, a read-only sandbox, `approval_policy="never"` and its shell, plugins, apps and browser disabled, so the person's `~/.codex/config.toml` cannot widen it and its only hands are the Dodaios tools, gated like the Dodaios runtime. |
- | Hermes, OpenClaw | yes | no | The runtime's config is written per turn (`approvals.mode: manual`, `tools.exec.mode: ask`) and every request comes over ACP to the chat card. |
+ | Hermes | yes | no | The runtime's config is written per turn (`approvals.mode: manual`) and every request comes over ACP to the chat card. |
+ | OpenClaw | yes | yes | Exec asks over ACP (`tools.exec.mode: ask`). OpenClaw relays no other approval, so Dodaios' gate plugin (`agent_runtimes/openclaw_gate.py`, loaded from the agent's folder) holds every `write`, `edit` and `apply_patch` call in a `before_tool_call` hook and asks Dodaios (`POST /api/control/runtime/native-approval`, `native_gate.py`); the chat's running turn answers from its stance like an ACP request. Typing into a running command (`process` with `write`, `send-keys`, `submit` or `paste`) asks the same way, since an allowed interactive shell would otherwise run every later command unasked; its other actions run freely. In Always ask the hook asks for `read`, `ls`, `grep`, `find`, `web_search` and `web_fetch` too, and "allow always" allows one call. The plugin's config never depends on the stance, so a stance change never restarts the Gateway. Tools that would wait for an answer only OpenClaw's own UI can give (`ask_user`, `openclaw`) or drive this desktop (`computer`, `terminal`) are denied. |
| Other CLI seats | no | no | No relay for their own prompts: Ask and Always ask are refused when the chat binds. |
+- **The ask tool on OpenClaw** is offered by the gate plugin under its plain
+ name, `society_ask_user`, as a direct tool next to the deferred tool search
+ (the MCP copy, `dodaios__society_ask_user`, is denied), and calls Dodaios'
+ own MCP tool. Question ids a model adds (`color-pref`) are normalized, never
+ refused.
+- **OpenClaw's stream is repaired from the model gateway.** Its ACP bridge
+ sends each message of a turn as the part beyond the length of the text it
+ sent before, so a later message (after a tool call or its "isolated
+ finalization" pass) arrives without its first characters, or not at all.
+ The model gateway records each answer of the watched turn
+ (`gateway.turn_replies`); `AcpTurn` replaces a streamed text that is the end
+ of a longer answer with that answer and shows a final answer the stream
+ dropped.
+- **A prompt the runtime answered never restarts it.** A turn whose
+ `session/prompt` got a result (also a run OpenClaw ended itself as
+ `cancelled`, or a stop) keeps its process and Gateway
+ (`runner_acp.poisons_runtime`); a restart then cost a minute and OpenClaw's
+ restarted Gateway could not resume the run (`delegated_authority_unavailable`).
+ A failure the model gateway saw still restarts it.
+- **Retiring an agent stops its processes.** Archiving a Hermes or OpenClaw
+ agent stops its warm processes, its OpenClaw Gateways and its Hermes gateway
+ daemons at once; idle ones still stop after 30 minutes.
- **Warm processes** (`warm.py`). An agent's runtime process stays up
between its turns, initialized and with its conversation open, so a message
only costs `session/prompt` (Hermes: first answer text 0.03 s instead of
diff --git a/dodaios/agent_chat/permissions.py b/dodaios/agent_chat/permissions.py
index 722a5294fb..98d077b865 100644
--- a/dodaios/agent_chat/permissions.py
+++ b/dodaios/agent_chat/permissions.py
@@ -404,7 +404,9 @@ def society_mode_supported(runner: str, mode: str) -> bool:
"openclaw-cli",
}
if mode == "always_ask":
- return runner in {"brain", "codex-cli"}
+ # OpenClaw: Dodaios' gate plugin asks before every native file call
+ # (reads too), exec asks over ACP, Dodaios' tools ask on their own.
+ return runner in {"brain", "codex-cli", "openclaw-cli"}
return False
diff --git a/dodaios/agent_chat/runner_acp.py b/dodaios/agent_chat/runner_acp.py
index 15b719dcd8..52f5e6c6be 100644
--- a/dodaios/agent_chat/runner_acp.py
+++ b/dodaios/agent_chat/runner_acp.py
@@ -319,14 +319,10 @@ async def plan_runtime_turn(
if route.api_key:
gateway.unwatch_failure(route.api_key, failure)
acp = plan.acp if plan is not None else None
- # A runtime still finishing its start keeps its process: a restart
- # would only begin that start again (the turn sends once more).
- starting = acp is not None and not_ready_kind(acp.error) == "starting"
- if launch.invalidate is not None and (
- handle.cancel.is_set()
- or (failure.done() and not failure.cancelled())
- or acp is None
- or ((not acp.saw_result or acp.status != "done") and not starting)
+ if launch.invalidate is not None and poisons_runtime(
+ acp,
+ cancelled=handle.cancel.is_set(),
+ provider_failed=failure.done() and not failure.cancelled(),
):
launch.invalidate()
release_launch()
@@ -346,6 +342,31 @@ async def plan_runtime_turn(
raise
+def poisons_runtime(acp: AcpTurn | None, *, cancelled: bool, provider_failed: bool) -> bool:
+ """Whether a finished turn leaves its runtime process (OpenClaw: its
+ Gateway) to be restarted before the next one.
+
+ A prompt the runtime answered (also a run it ended itself, or a stop)
+ proves the process and its Gateway work: a restart then only costs a
+ minute and cuts off the runtime's own recovery of the conversation (live
+ 2026-10-28: OpenClaw ended a failed run as ``cancelled``; its restarted
+ Gateway could not resume the run, ``delegated_authority_unavailable``).
+ A failure the model gateway saw still restarts it: the runtime may keep
+ the failed provider state. A runtime still finishing its start keeps its
+ process too: a restart would only begin that start again.
+ """
+ if acp is None:
+ return True
+ if acp.prompt_answered:
+ return provider_failed
+ starting = not_ready_kind(acp.error) == "starting"
+ return (
+ cancelled
+ or provider_failed
+ or ((not acp.saw_result or acp.status != "done") and not starting)
+ )
+
+
def _plan(
handle: Any,
launch: Any,
@@ -360,6 +381,7 @@ def _plan(
client_version: str,
) -> Any:
from dodaios.agent_chat.runner_cli import _PLAN_PREAMBLE, CliPlan, _with_identity
+ from dodaios.agent_runtimes import native_gate
text = _PLAN_PREAMBLE + prompt if plan_mode else prompt
acp = AcpTurn(
@@ -370,6 +392,10 @@ def _plan(
mcp_servers=launch.mcp_servers,
auto_allow=turn.auto_approve,
auto_deny=plan_mode,
+ always_ask=handle.session.permission_mode == "always_ask",
+ native_always=native_gate.always_for(handle.session.session_id),
+ # The whole answers, for the text OpenClaw's stream cut short.
+ reply_texts=lambda: gateway.turn_replies(failure),
client_version=client_version,
report_session=launch.vendor_session,
session_meta=launch.session_meta,
diff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.py
index 6b9f0b05be..797321291d 100644
--- a/dodaios/agent_chat/runner_cli.py
+++ b/dodaios/agent_chat/runner_cli.py
@@ -4502,6 +4502,22 @@ async def _drive_cli(
return str(decision)
acp_io = _AcpIO()
+ gate_decider = None
+ if plan.acp is not None:
+ from dodaios.agent_runtimes import native_gate
+
+ acp_turn = plan.acp
+
+ async def gate_decider(
+ call_id: str, tool: str, args: dict[str, Any], title: str, read_only: bool
+ ) -> str:
+ # A native tool the runtime cannot ask about (OpenClaw's file
+ # tools, through Dodaios' gate plugin): this turn's card decides.
+ return await acp_turn.native_permission(
+ acp_io, call_id, tool, args, title, read_only=read_only
+ )
+
+ native_gate.register(handle.session.session_id, gate_decider)
grace_kill: asyncio.TimerHandle | None = None
# Stall watchdog state: the last stdout frame, and an open approval card.
activity = [time.monotonic()]
@@ -4551,6 +4567,8 @@ async def _drive_cli(
_kill(proc)
raise
finally:
+ if gate_decider is not None:
+ native_gate.unregister(handle.session.session_id, gate_decider)
watcher.cancel()
provider_watcher.cancel()
stall_watcher.cancel()
diff --git a/dodaios/agent_runtimes/acp.py b/dodaios/agent_runtimes/acp.py
index 56b76ed772..9db6e5b5b8 100644
--- a/dodaios/agent_runtimes/acp.py
+++ b/dodaios/agent_runtimes/acp.py
@@ -33,6 +33,7 @@ import logging
import re
import time
import uuid
+from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Final, Protocol
@@ -75,6 +76,14 @@ _OWN_TOOL_PREFIXES: Final[tuple[tuple[str, str], ...]] = tuple(
)
_IDENTIFIER: Final[re.Pattern[str]] = re.compile(r"^[A-Za-z_][\w.:-]{0,120}$")
+#: What a ``cancelled`` stop reason means when this client never sent
+#: ``session/cancel``: the runtime ended the run on its own (OpenClaw does so
+#: for a run that failed before its reply).
+_ENDED_BY_RUNTIME: Final[str] = "The runtime ended the run before it finished."
+
+#: Replies a runtime keeps out of the chat on purpose (OpenClaw's silent tokens).
+_SILENT_REPLY: Final[re.Pattern[str]] = re.compile(r"^\W*(NO_REPLY|HEARTBEAT_OK)\W*$")
+
class AcpIO(Protocol):
"""What a turn needs from its host."""
@@ -163,6 +172,17 @@ class AcpTurn:
auto_allow: bool = False
#: Refuse every permission request without asking (Plan mode: read only).
auto_deny: bool = False
+ #: "Always ask": an "allow always" answer allows this one call only.
+ always_ask: bool = False
+ #: Native tools the person allowed for the rest of the chat ("allow
+ #: always" on a native tool's card, :meth:`native_permission`). Shared
+ #: with the chat, which owns the set.
+ native_always: set[str] = field(default_factory=set)
+ #: The answers the model gateway gave this turn, ``(text, tool calls)``
+ #: oldest first (``gateway.turn_replies``). OpenClaw's bridge streams a
+ #: turn's later messages as offsets into the previous one, cutting their
+ #: start off; the shown text is repaired from these.
+ reply_texts: Callable[[], list[tuple[str, int]]] | None = None
client_name: str = "dodaios"
client_version: str = ""
#: What the chat stores as its vendor session instead of the ACP session
@@ -196,6 +216,9 @@ class AcpTurn:
saw_result: bool = False
stop_reason: str = ""
emitted_tool_ids: set[str] = field(default_factory=set)
+ #: The runtime answered ``session/prompt`` with a result: its process and
+ #: the Gateway behind it work, whatever the turn's own outcome.
+ prompt_answered: bool = False
# --- what the agent announced in ``initialize`` ---
agent_name: str = ""
@@ -212,6 +235,9 @@ class AcpTurn:
_tool_started: dict[str, float] = field(default_factory=dict, init=False)
_finished_tools: set[str] = field(default_factory=set, init=False)
_failure_reply: str = field(default="", init=False)
+ _cancel_sent: bool = field(default=False, init=False)
+ #: Text was shown after the last tool call (``_flush_text``).
+ _text_since_tool: bool = field(default=False, init=False)
# ------------------------------------------------------------------ frames
@@ -245,6 +271,7 @@ class AcpTurn:
``stopReason: cancelled`` once its turn has wound down."""
if not self._acp_session or self.saw_result:
return None
+ self._cancel_sent = True
return {
"jsonrpc": "2.0",
"method": "session/cancel",
@@ -351,17 +378,22 @@ class AcpTurn:
self._fail(_error_text(error))
return
res = result if isinstance(result, dict) else {}
+ self.prompt_answered = True
self.stop_reason = str(res.get("stopReason") or "")
self._take_usage(res.get("usage"))
if self._failure_reply:
self._fail(self._failure_reply.strip())
return
+ await self._show_lost_final(io)
+ early = _STOPPED_EARLY.get(self.stop_reason, "")
+ if self.stop_reason == "cancelled" and not self._cancel_sent:
+ early = _ENDED_BY_RUNTIME
if self.stop_reason == "refusal" and not self.emitted_text:
self._fail("The model refused this request.")
- elif self.stop_reason in _STOPPED_EARLY and not self.emitted_text:
- self._fail(_STOPPED_EARLY[self.stop_reason])
- elif self.stop_reason in _STOPPED_EARLY:
- self._fail(f"{_STOPPED_EARLY[self.stop_reason]} ({self.stop_reason})")
+ elif early and not self.emitted_text:
+ self._fail(early)
+ elif early:
+ self._fail(f"{early} ({self.stop_reason})")
# Retain the partial answer while reporting that the turn is incomplete.
await io.emit(
make_event(
@@ -370,7 +402,7 @@ class AcpTurn:
"kind": "stop_reason",
"turn_id": self.turn_id,
"stop_reason": self.stop_reason,
- "text": _STOPPED_EARLY[self.stop_reason],
+ "text": early,
},
)
)
@@ -379,6 +411,7 @@ class AcpTurn:
async def cancel(self, io: AcpIO) -> None:
"""Abort the upstream session before its stdio bridge is terminated."""
if self._acp_session and not self.saw_result:
+ self._cancel_sent = True
await io.write({
"jsonrpc": "2.0", "method": "session/cancel",
"params": {"sessionId": self._acp_session},
@@ -423,6 +456,8 @@ class AcpTurn:
else:
await self._flush_text(io)
decision = await io.ask(call_id, name, args, summary)
+ if decision == "allow_always" and self.always_ask:
+ decision = "allow"
wanted: tuple[str, ...]
if decision == "allow_always":
wanted = ("allow_always", "allow_once")
@@ -437,6 +472,51 @@ class AcpTurn:
return {"outcome": "selected", "optionId": by_kind[kind]}
return {"outcome": "cancelled"}
+ async def native_permission(
+ self,
+ io: AcpIO,
+ call_id: str,
+ name: str,
+ args: dict[str, Any],
+ title: str = "",
+ *,
+ read_only: bool = False,
+ ) -> str:
+ """Decide one native tool call the runtime cannot ask about itself.
+
+ OpenClaw relays only exec approvals over ACP; its file tools (write,
+ edit, apply_patch) are asked about here instead, by Dodaios' gate
+ plugin in the Gateway (``openclaw_gate``). The chat's stance decides
+ as for ``session/request_permission``: Bypass allows, Plan refuses,
+ anything else shows the approval card on the tool's row. A reading
+ tool (``read_only``) runs freely, also in Plan, and asks in "Always
+ ask" only. Returns ``allow`` / ``allow_always`` / ``deny`` / ``cancel``.
+ """
+ if read_only and (self.auto_allow or not self.always_ask):
+ return "allow"
+ if self.auto_deny:
+ return "deny"
+ if self.auto_allow:
+ return "allow"
+ if name in self.native_always and not self.always_ask:
+ return "allow"
+ call_id = call_id or uuid.uuid4().hex
+ await self._flush_text(io)
+ if call_id not in self.emitted_tool_ids:
+ # The approval card sits on a tool row; give it one.
+ await self._tool_start(
+ {"toolCallId": call_id, "title": title or name, "rawInput": args,
+ "_meta": {"toolName": name}},
+ io,
+ )
+ summary = str(title or name)[:200]
+ decision = await io.ask(call_id, self._tool_names.get(call_id) or name, args, summary)
+ if decision == "allow_always":
+ if self.always_ask:
+ return "allow"
+ self.native_always.add(name)
+ return decision
+
# ----------------------------------------------------------------- updates
async def _on_update(self, params: dict[str, Any], io: AcpIO) -> None:
@@ -514,6 +594,7 @@ class AcpTurn:
# Hermes sends no input for its own file tools, only where they act.
args = {"path": path}
self.emitted_tool_ids.add(call_id)
+ self._text_since_tool = False
self._tool_names[call_id] = name
self._tool_started[call_id] = time.perf_counter()
await io.emit(
@@ -563,7 +644,9 @@ class AcpTurn:
self._text_id = ""
if not text.strip():
return
+ text = self._repaired(text)
self.emitted_text = True
+ self._text_since_tool = True
self.result_text = text
await io.emit(
make_event(
@@ -572,6 +655,63 @@ class AcpTurn:
)
)
+ def _replies(self) -> list[tuple[str, int]]:
+ if self.reply_texts is None:
+ return []
+ try:
+ return list(self.reply_texts())
+ except Exception: # noqa: BLE001 — a repair never decides more than the shown text
+ log.debug("acp: model replies unreadable", exc_info=True)
+ return []
+
+ def _repaired(self, streamed: str) -> str:
+ """``streamed`` with a start the runtime's stream cut off put back.
+
+ OpenClaw's bridge sends each message of a turn as the part beyond the
+ length of the text it sent before, so a later message (after a tool
+ call, or its own "isolated finalization" pass) arrives without its
+ first characters. The model gateway saw the whole answer: a streamed
+ text that is the end of a longer answer of this turn is that answer.
+ """
+ shown = streamed.strip()
+ for text, _calls in reversed(self._replies()):
+ whole = text.strip()
+ if whole == shown:
+ return streamed
+ if len(whole) > len(shown) and whole.endswith(shown):
+ return whole
+ return streamed
+
+ async def _show_lost_final(self, io: AcpIO) -> None:
+ """The turn's final answer when the runtime's stream dropped it whole.
+
+ A final message no longer than the text streamed before it arrives as
+ nothing at all (the same offset fault as :meth:`_repaired`). When the
+ turn's last answer came after the last tool call and nothing was shown
+ since, it is shown here.
+ """
+ if self._text_since_tool or not self.emitted_tool_ids:
+ return
+ final = ""
+ for text, calls in reversed(self._replies()):
+ if calls:
+ return # the last model call asked for a tool: no answer followed
+ if text.strip():
+ final = text.strip()
+ break
+ if not final or _SILENT_REPLY.match(final):
+ return
+ message_id = f"acp-{self.turn_id}-{uuid.uuid4().hex[:8]}"
+ self.emitted_text = True
+ self._text_since_tool = True
+ self.result_text = final
+ await io.emit(
+ make_event(
+ "assistant_text",
+ {"turn_id": self.turn_id, "message_id": message_id, "text": final},
+ )
+ )
+
async def _flush_thought(self, io: AcpIO) -> None:
if self._thought_started is None:
return
diff --git a/dodaios/agent_runtimes/gateway.py b/dodaios/agent_runtimes/gateway.py
index 8e9c87057f..037188ee29 100644
--- a/dodaios/agent_runtimes/gateway.py
+++ b/dodaios/agent_runtimes/gateway.py
@@ -118,6 +118,15 @@ _TURN_EFFORTS: dict[Grant, str] = {}
#: runtime; the runner's stall watchdog asks here before it calls that a hang
#: (issue #978). The gateway's own read timeout still ends a dead model call.
_OPEN_CALLS: weakref.WeakKeyDictionary[Future[str], int] = weakref.WeakKeyDictionary()
+#: The answers the gateway gave each watched turn, in order: ``(text, tool
+#: calls)``. OpenClaw's ACP bridge streams a turn's later messages as offsets
+#: into the first one, so the runner reads the real text back from here
+#: (``acp.AcpTurn.reply_texts``).
+_REPLIES: weakref.WeakKeyDictionary[Future[str], list[tuple[str, int]]] = (
+ weakref.WeakKeyDictionary()
+)
+#: Answers kept per turn; a turn with more model calls keeps the latest.
+_MAX_REPLIES: Final = 64
#: Per (provider, account, model): until when calls are refused, why
#: (``rate_limited`` / ``usage_limit``) and whether the provider named that
#: time (a usage limit's reset is only told when it did).
@@ -473,6 +482,23 @@ def _answered(signal: Future[str] | None) -> None:
_LAST_FAILURES.pop(signal, None)
+def _record_reply(signal: Future[str] | None, text: str, calls: int) -> None:
+ if signal is None:
+ return
+ with _LOCK:
+ replies = _REPLIES.setdefault(signal, [])
+ replies.append((text, calls))
+ del replies[:-_MAX_REPLIES]
+
+
+def turn_replies(signal: Future[str] | None) -> list[tuple[str, int]]:
+ """``(text, tool calls)`` of every answer this turn got, oldest first."""
+ if signal is None:
+ return []
+ with _LOCK:
+ return list(_REPLIES.get(signal, ()))
+
+
def unwatch_failure(token: str, signal: Future[str]) -> None:
with _LOCK:
grant = _GRANTS.get(token)
@@ -768,6 +794,8 @@ async def stream_response(
args = {**args, "reasoning_effort": effort}
started = False
completed = False
+ texts: list[str] = []
+ calls = 0
try:
_require_turn(grant, signal)
check_cooldown(grant.provider, model, grant.account_id)
@@ -777,10 +805,16 @@ async def stream_response(
async for event in upstream:
started = True
completed = completed or event.get("type") == "response.completed"
+ kind = event.get("type")
+ if kind == "response.output_text.done":
+ texts.append(str(event.get("text") or ""))
+ elif kind == "response.output_item.done" and isinstance(event.get("item"), dict):
+ calls += event["item"].get("type") == "function_call"
yield _sse(event)
if not completed:
raise GatewayError("ChatGPT ended before completion.", status=502, code="incomplete")
_answered(signal)
+ _record_reply(signal, "\n".join(texts), calls)
except (SubscriptionReasoningError, SubscriptionAuthError, GatewayError) as exc:
log.info("runtime gateway: %s turn failed (%s)", grant.agent_id, type(exc).__name__)
failure = _report_failure(grant, model, _subscription_failure(grant, exc), signal)
@@ -1515,10 +1549,12 @@ async def _chat_chunks(
calls = 0
finish: str | None = None
delta = first
+ text: list[str] = []
try:
yield _chunk(chat_id, model, {"role": "assistant", "content": ""})
while delta is not None:
if delta.content:
+ text.append(delta.content)
yield _chunk(chat_id, model, {"content": delta.content})
if delta.tool_call:
yield _chunk(chat_id, model, {"tool_calls": [_tool_call(calls, delta.tool_call)]})
@@ -1539,6 +1575,7 @@ async def _chat_chunks(
return
else:
_answered(signal)
+ _record_reply(signal, "".join(text), calls)
finally:
# The runner stops on a provider failure; a closed HTTP client must
# also release the plugin task if it was suspended between deltas.
@@ -1602,6 +1639,7 @@ async def complete_chat(
except Exception as exc: # noqa: BLE001 — becomes the runtime's HTTP error; _failure logs it
raise _report_failure(grant, model, _failure(grant.provider, exc, model), signal) from exc
_answered(signal)
+ _record_reply(signal, "".join(text), len(calls))
message: dict[str, Any] = {"role": "assistant", "content": "".join(text) or None}
if calls:
message["tool_calls"] = [{k: v for k, v in call.items() if k != "index"} for call in calls]
@@ -1692,6 +1730,7 @@ def reset() -> None:
_SIGNATURES.clear()
_MODEL_LIMITS.clear()
_FAILURES.clear()
+ _REPLIES.clear()
_TURN_EFFORTS.clear()
_COOLDOWNS.clear()
_WARMING.clear()
diff --git a/dodaios/agent_runtimes/hermes.py b/dodaios/agent_runtimes/hermes.py
index 889be0cd2c..269cb5d26a 100644
--- a/dodaios/agent_runtimes/hermes.py
+++ b/dodaios/agent_runtimes/hermes.py
@@ -445,8 +445,11 @@ class HermesRuntime:
gateway daemons they ran on."""
keys = None if agent_id is None else {agent_id, f"{agent_id}~runs"}
await self._warm.stop(keys)
- for key in [key for key in self._daemons if keys is None or key in keys]:
- del self._daemons[key]
+ # A named agent's daemons go even when this app run never started
+ # them (one left by an earlier run lives on its own for minutes).
+ doomed = set(self._daemons) if keys is None else keys
+ for key in doomed:
+ self._daemons.pop(key, None)
home = hermes_root() / "profiles" / profile_name(key)
await asyncio.to_thread(_stop_profile_gateway, home)
diff --git a/dodaios/agent_runtimes/native_gate.py b/dodaios/agent_runtimes/native_gate.py
new file mode 100644
index 0000000000..434f94e866
--- /dev/null
+++ b/dodaios/agent_runtimes/native_gate.py
@@ -0,0 +1,99 @@
+"""Approval cards for a runtime's native tools that cannot ask over ACP.
+
+OpenClaw relays only its exec approvals to the ACP client
+(``session/request_permission``); its file tools (``write``, ``edit``,
+``apply_patch``) run without asking anyone. Dodaios' gate plugin in the
+agent's Gateway (``openclaw_gate``) holds each such call and asks here, over
+the Control API (``POST /api/control/runtime/native-approval``), and the
+running turn of that chat decides it like any other approval: Bypass allows,
+Plan refuses, Ask and Always ask show the card on the tool's row.
+
+The running ACP turn registers its decider for its chat while it runs
+(``runner_cli``); a call that arrives while no turn of the chat runs is
+refused, never run unasked.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Awaitable, Callable
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+#: ``decider(call_id, tool, args, title, read_only) -> allow | allow_always |
+#: deny | cancel``. ``read_only``: the tool only reads (asked in "Always ask").
+Decider = Callable[[str, str, dict[str, Any], str, bool], Awaitable[str]]
+
+#: A decision must reach the plugin before its hook budget runs out
+#: (``openclaw_gate.HOOK_TIMEOUT_MS``); an unanswered card is refused then.
+DECISION_TIMEOUT_S: Final[float] = 570.0
+
+#: The tool sees this as the reason its call did not run.
+NO_TURN: Final[str] = "No Dodaios turn is running for this chat, so the action was not run."
+DECLINED: Final[str] = "The person declined this action. Do not try to work around it."
+STOPPED: Final[str] = "The turn was stopped before the person decided. Do not continue."
+NO_ANSWER: Final[str] = "Nobody answered the approval card in time, so the action was not run."
+
+_DECIDERS: dict[str, Decider] = {}
+#: Per chat: the native tools the person allowed with "allow always".
+_ALWAYS: dict[str, set[str]] = {}
+
+
+def register(session_id: str, decider: Decider) -> None:
+ """The running turn of ``session_id`` decides its native tool calls."""
+ _DECIDERS[session_id] = decider
+
+
+def unregister(session_id: str, decider: Decider) -> None:
+ if _DECIDERS.get(session_id) is decider:
+ del _DECIDERS[session_id]
+
+
+def always_for(session_id: str) -> set[str]:
+ """The chat's "allow always" set for native tools (shared, mutable)."""
+ return _ALWAYS.setdefault(session_id, set())
+
+
+def forget(session_id: str) -> None:
+ """Drop the chat's remembered answers (a cleared or deleted chat)."""
+ _ALWAYS.pop(session_id, None)
+
+
+async def decide(
+ session_id: str,
+ tool: str,
+ args: dict[str, Any],
+ *,
+ call_id: str = "",
+ title: str = "",
+ read_only: bool = False,
+) -> tuple[str, str]:
+ """``("allow", "")`` or ``("deny", reason)`` for one native tool call."""
+ decider = _DECIDERS.get(session_id)
+ if decider is None:
+ log.info("native gate: %s for %s refused, no turn running", tool, session_id)
+ return "deny", NO_TURN
+ try:
+ decision = await asyncio.wait_for(
+ decider(call_id, tool, dict(args or {}), title, read_only),
+ timeout=DECISION_TIMEOUT_S,
+ )
+ except TimeoutError:
+ log.info("native gate: nobody answered %s for %s in time; refusing", tool, session_id)
+ return "deny", NO_ANSWER
+ except Exception: # noqa: BLE001 — a broken card refuses, it never allows
+ log.warning("native gate: deciding %s failed; refusing", tool, exc_info=True)
+ return "deny", DECLINED
+ if decision in ("allow", "allow_always"):
+ return "allow", ""
+ if decision == "cancel":
+ return "deny", STOPPED
+ return "deny", DECLINED
+
+
+def reset() -> None:
+ """Forget every decider and answer (tests)."""
+ _DECIDERS.clear()
+ _ALWAYS.clear()
diff --git a/dodaios/agent_runtimes/openclaw.py b/dodaios/agent_runtimes/openclaw.py
index c56ad2e20d..f64ee747ac 100644
--- a/dodaios/agent_runtimes/openclaw.py
+++ b/dodaios/agent_runtimes/openclaw.py
@@ -40,7 +40,7 @@ from pathlib import Path
from typing import Any, Final
from dodaios.agent_chat.effort import ORDER, snap_to_ladder
-from dodaios.agent_runtimes import base, versions
+from dodaios.agent_runtimes import base, openclaw_gate, versions
from dodaios.agent_runtimes.base import (
DetectCache,
HomeFileLock,
@@ -139,9 +139,13 @@ _EMBED_ENV: Final[dict[str, str]] = {
}
#: Native tools that duplicate a Jarvis feature (routines, messaging, other
-#: devices, the visible browser) and would bypass Jarvis' own approvals and
-#: budgets, and tools for OpenClaw's own apps and dashboards no Dodaios agent
-#: has (their schemas were about a quarter of every request).
+#: devices, the visible browser, desktop control, asking the person) and
+#: would bypass Jarvis' own approvals and budgets, and tools for OpenClaw's
+#: own apps and dashboards no Dodaios agent has (their schemas were about a
+#: quarter of every request). ``computer`` drives this desktop and
+#: ``terminal`` the operator's shared terminals; ``openclaw`` changes
+#: OpenClaw's own setup and ``ask_user`` asks in OpenClaw's own UI, both
+#: waiting for an approval or answer no Dodaios surface can give.
_ALWAYS_DENIED: Final[tuple[str, ...]] = (
"automations",
"message",
@@ -149,6 +153,10 @@ _ALWAYS_DENIED: Final[tuple[str, ...]] = (
"conversations_turn",
"gateway",
"nodes",
+ "computer",
+ "terminal",
+ "openclaw",
+ "ask_user",
"browser",
"skill_workshop",
"theme",
@@ -643,8 +651,17 @@ class OpenClawRuntime:
denied += ["web_search", "web_fetch"]
# "ask" relays every exec approval over ACP; Jarvis answers it from the
# chat's stance (Bypass allows without a card), so the file does not
- # change with the stance of whichever turn wrote it.
+ # change with the stance of whichever turn wrote it. The file tools
+ # ask through Dodaios' gate plugin the same way (``openclaw_gate``).
exec_mode = "deny" if "shell" in turn.denied_native else "ask"
+ gate = _gate_plugin(turn, home) if route.transport != "claude_cli" else None
+ if gate is None and not turn.auto_approve:
+ # Nothing could ask about a file change: outside Bypass it does
+ # not run at all (exec still asks over ACP).
+ denied += list(openclaw_gate.GATED_TOOLS)
+ if gate is not None and gate.get("config", {}).get("ask"):
+ # One ask tool, under the name the agent's instructions use.
+ denied.append(gate["config"]["ask"]["catalogName"])
config: dict[str, Any] = {
"gateway": {
"mode": "local",
@@ -696,6 +713,10 @@ class OpenClawRuntime:
# temp-folder log every OpenClaw on the machine appends to.
"logging": {"file": str(home / "state" / "logs" / "openclaw.log")},
}
+ if gate is not None:
+ plugins = config["plugins"]
+ plugins["load"] = {"paths": [gate["path"]]}
+ plugins["entries"][openclaw_gate.PLUGIN_ID] = gate["entry"]
if route.transport == "claude_cli":
_use_claude_cli(config, turn)
if turn.mcp_url and turn.control_key:
@@ -1202,6 +1223,41 @@ class OpenClawRuntime:
await self._stop_gateway(gateway)
+def _gate_plugin(turn: RuntimeTurn, home: Path) -> dict[str, Any] | None:
+ """Dodaios' gate plugin for this agent's Gateway, or ``None`` without tools.
+
+ The plugin asks Dodaios before every native file change and offers the
+ ask tool by its plain name (``openclaw_gate``). It needs the agent's
+ Dodaios tools (the control key and the MCP endpoint): a turn without them
+ has nothing to ask with.
+ """
+ if not (turn.mcp_url and turn.control_key):
+ return None
+ from dodaios.core.branding import MCP_TOOLS_SERVER_NAME
+ from dodaios.society.routine_runner import is_routine_session
+
+ installed = openclaw_gate.install(home)
+ plugin_config: dict[str, Any] = {
+ "gateUrl": openclaw_gate.approval_url(turn.mcp_url),
+ "session": turn.session_id,
+ # A new plugin build is a config change: the Gateway restarts on it.
+ "build": installed.digest,
+ }
+ if not is_routine_session(turn.session_id):
+ # A routine runs unattended: nobody could answer a question there.
+ plugin_config["mcpUrl"] = turn.mcp_url
+ plugin_config["ask"] = openclaw_gate.ask_spec(MCP_TOOLS_SERVER_NAME)
+ return {
+ "path": str(installed.path),
+ "config": plugin_config,
+ "entry": {
+ "enabled": True,
+ "hooks": {"timeouts": {"before_tool_call": openclaw_gate.HOOK_TIMEOUT_MS}},
+ "config": plugin_config,
+ },
+ }
+
+
def _use_claude_cli(config: dict[str, Any], turn: RuntimeTurn) -> None:
"""Run the agent on the Claude subscription through OpenClaw's bundled
``claude-cli`` backend (``docs/gateway/cli-backends.md`` of OpenClaw).
@@ -1256,7 +1312,7 @@ def _inline_catalog_tokens() -> int:
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
+ except (TypeError, ValueError): # an unserializable schema counts name and description
schema = ""
chars += len(str(entry.name)) * 2 + len(str(entry.description or "")) + len(schema) + 32
return chars // _CHARS_PER_TOKEN
diff --git a/dodaios/agent_runtimes/openclaw_gate.py b/dodaios/agent_runtimes/openclaw_gate.py
new file mode 100644
index 0000000000..9764b14aba
--- /dev/null
+++ b/dodaios/agent_runtimes/openclaw_gate.py
@@ -0,0 +1,292 @@
+"""Dodaios' gate plugin for an agent's OpenClaw Gateway.
+
+OpenClaw relays only exec approvals over ACP. Its file tools (``write``,
+``edit``, ``apply_patch``) have no approval of their own, so in Ask they ran
+without a card. This small plugin, written into each agent's state folder and
+loaded through ``plugins.load.paths``, closes that gap with OpenClaw's own
+``before_tool_call`` hook: every such call waits for Dodaios' answer
+(``native_gate``), which follows the chat's stance. Bypass answers at once,
+so the plugin's config never depends on the stance and a stance change never
+restarts the Gateway.
+
+It also registers the agent's ask tool under its plain name
+(``society_ask_user``) as a direct tool, outside OpenClaw's deferred tool
+search: a small model calls the name its instructions use, which the MCP
+catalog only knows as ``dodaios__society_ask_user`` behind ``tool_search``.
+The call goes to Dodaios' own MCP tool, with its card and limits.
+
+The plugin talks to Dodaios with the control key the Gateway already has in
+its environment (``JARVIS_CONTROL_API_KEY``); nothing secret is written.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Final
+
+from dodaios.agent_runtimes.base import write_if_changed
+
+#: The plugin's id (its folder name and ``plugins.entries`` key).
+PLUGIN_ID: Final[str] = "dodaios-gate"
+
+#: OpenClaw's own tools that change files and have no approval to relay.
+GATED_TOOLS: Final[tuple[str, ...]] = ("write", "edit", "apply_patch")
+
+#: OpenClaw's own reading tools: asked about in "Always ask" only, answered
+#: at once otherwise (``native_gate``), so the config stays the same.
+READ_TOOLS: Final[tuple[str, ...]] = (
+ "read", "ls", "grep", "find", "web_search", "web_fetch"
+)
+
+#: OpenClaw's ``process`` tool drives a command ``exec`` started. Its input
+#: actions type into that process: once an interactive shell or REPL was
+#: allowed, they would run any further command without a card. They ask like
+#: a file change; its other actions (list, poll, log, kill, ...) run freely.
+PROCESS_TOOL: Final[str] = "process"
+PROCESS_INPUT_ACTIONS: Final[frozenset[str]] = frozenset({"write", "send-keys", "submit", "paste"})
+
+#: The hook waits this long for the person (OpenClaw's ceiling for an
+#: operator-set hook budget); ``native_gate`` answers before it.
+HOOK_TIMEOUT_MS: Final[int] = 600_000
+
+#: Where the gate asks (the Control API, same origin as the MCP endpoint).
+APPROVAL_PATH: Final[str] = "/api/control/runtime/native-approval"
+
+_MANIFEST: Final[dict[str, Any]] = {
+ "id": PLUGIN_ID,
+ "name": "Dodaios gate",
+ "description": "Asks Dodaios before file changes and offers the agent's ask tool.",
+ "contracts": {"tools": ["society_ask_user"]},
+ "activation": {"onStartup": True},
+ "configSchema": {"type": "object", "additionalProperties": True},
+}
+
+_PACKAGE: Final[dict[str, Any]] = {
+ "name": PLUGIN_ID,
+ "version": "1.0.0",
+ "private": True,
+ "type": "module",
+ "openclaw": {"extensions": ["./index.mjs"]},
+}
+
+_SOURCE: Final[str] = r"""// Written by Dodaios (agent_runtimes/openclaw_gate.py). Do not edit.
+const GATED = __GATED__;
+const HOOK_TIMEOUT_MS = __TIMEOUT__;
+
+function headers(cfg, extra) {
+ return {
+ "content-type": "application/json",
+ authorization: `Bearer ${process.env.JARVIS_CONTROL_API_KEY || ""}`,
+ "x-jarvis-chat-session": String(cfg.session || ""),
+ ...(extra || {}),
+ };
+}
+
+function title(tool, params) {
+ const path = params && (params.path || params.file_path || params.filePath);
+ if (typeof path === "string" && path) return `${tool}: ${path}`;
+ const action = params && params.action;
+ return typeof action === "string" && action ? `${tool}: ${action}` : tool;
+}
+
+function parsed(value) {
+ if (typeof value !== "string") return value;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+}
+
+// Small models send question ids such as "color-pref" and options as plain
+// strings; the card takes any of it.
+function normalizeAsk(raw) {
+ const args = parsed(raw);
+ if (!args || typeof args !== "object") return args;
+ const out = { ...args };
+ const questions = parsed(out.questions);
+ if (Array.isArray(questions)) {
+ out.questions = questions.map((item, index) => {
+ const q = parsed(item);
+ if (!q || typeof q !== "object") return q;
+ const next = { ...q };
+ if (next.id !== undefined) {
+ const id = String(next.id)
+ .toLowerCase()
+ .replace(/[^a-z0-9_]+/g, "_")
+ .replace(/^[^a-z]+/, "");
+ next.id = id || `question_${index + 1}`;
+ }
+ // Dodaios' MCP schema requires the reason; a model that left it out
+ // still gets its card (the recommendation simply goes unexplained).
+ if (typeof next.recommendation_reason !== "string") next.recommendation_reason = "";
+ const options = parsed(next.options);
+ if (Array.isArray(options)) {
+ next.options = options.map((o) => (typeof o === "string" ? { label: o } : o));
+ }
+ return next;
+ });
+ }
+ return out;
+}
+
+export default {
+ id: "dodaios-gate",
+ name: "Dodaios gate",
+ description: "Asks Dodaios before file changes and offers the agent's ask tool.",
+ register(api) {
+ const cfg = api.pluginConfig || {};
+ api.on(
+ "before_tool_call",
+ async (event, ctx) => {
+ const refuse = (reason) => ({ block: true, blockReason: reason });
+ if (!cfg.gateUrl) {
+ return refuse("Dodaios cannot ask for approval here, so the action was not run.");
+ }
+ try {
+ const params = event.params || {};
+ const res = await fetch(cfg.gateUrl, {
+ method: "POST",
+ headers: headers(cfg),
+ body: JSON.stringify({
+ tool: event.toolName,
+ params,
+ tool_call_id: event.toolCallId || "",
+ title: title(event.toolName, params),
+ }),
+ signal: ctx && ctx.abortSignal,
+ });
+ if (!res.ok) {
+ return refuse(
+ `Dodaios could not ask for approval (HTTP ${res.status}), so the action was not run.`,
+ );
+ }
+ const body = await res.json();
+ if (body && body.decision === "allow") return undefined;
+ return refuse(String((body && body.reason) || "The person declined this action."));
+ } catch {
+ return refuse("Dodaios could not ask for approval, so the action was not run.");
+ }
+ },
+ { matcher: GATED, priority: 1000, timeoutMs: HOOK_TIMEOUT_MS },
+ );
+ const ask = cfg.ask;
+ if (cfg.mcpUrl && ask && ask.name) {
+ api.registerTool({
+ name: ask.name,
+ label: "Ask the user",
+ description: String(ask.description || ""),
+ catalogMode: "direct-only",
+ parameters: ask.schema || { type: "object", properties: {} },
+ prepareArguments: normalizeAsk,
+ async execute(_toolCallId, params, signal) {
+ const res = await fetch(cfg.mcpUrl, {
+ method: "POST",
+ headers: headers(cfg, { accept: "application/json, text/event-stream" }),
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: { name: ask.wire || ask.name, arguments: normalizeAsk(params) || {} },
+ }),
+ signal,
+ });
+ if (!res.ok) throw new Error(`Dodaios did not take the question (HTTP ${res.status}).`);
+ const body = await res.json();
+ if (body.error) {
+ throw new Error(String(body.error.message || "The question could not be shown."));
+ }
+ const result = body.result || {};
+ const text = (result.content || [])
+ .filter((part) => part && part.type === "text")
+ .map((part) => part.text)
+ .join("\n");
+ if (result.isError) throw new Error(text || "The question could not be shown.");
+ return { content: [{ type: "text", text }], details: { text } };
+ },
+ });
+ }
+ },
+};
+"""
+
+
+def kind(tool: str, params: dict[str, Any] | None) -> str:
+ """How Dodaios treats one call the plugin holds: ``free`` (runs at once),
+ ``read`` (asks in "Always ask" only) or ``change`` (asks outside Bypass)."""
+ if tool == PROCESS_TOOL:
+ action = str((params or {}).get("action") or "").strip().lower()
+ return "change" if action in PROCESS_INPUT_ACTIONS else "free"
+ return "read" if tool in READ_TOOLS else "change"
+
+
+def source() -> str:
+ """The plugin's entry module."""
+ matched = [*GATED_TOOLS, *READ_TOOLS, PROCESS_TOOL]
+ return _SOURCE.replace("__GATED__", json.dumps(matched)).replace(
+ "__TIMEOUT__", str(HOOK_TIMEOUT_MS)
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class Installed:
+ """Where the plugin lives in an agent's folder, and which build it is."""
+
+ path: Path
+ digest: str
+
+
+def install(home: Path) -> Installed:
+ """Write the plugin into ``home/plugins/dodaios-gate`` (only what changed).
+
+ The digest goes into the Gateway's config, so a new build of the plugin
+ restarts the Gateway like any other config change.
+ """
+ folder = home / "plugins" / PLUGIN_ID
+ files = {
+ "index.mjs": source(),
+ "openclaw.plugin.json": json.dumps(_MANIFEST, indent=2) + "\n",
+ "package.json": json.dumps(_PACKAGE, indent=2) + "\n",
+ }
+ digest = hashlib.sha256()
+ for name, text in sorted(files.items()):
+ write_if_changed(folder / name, text)
+ digest.update(name.encode("utf-8") + b"\0" + text.encode("utf-8"))
+ return Installed(folder, digest.hexdigest()[:16])
+
+
+def ask_spec(mcp_server: str) -> dict[str, Any]:
+ """The ask tool as the plugin offers it: Dodaios' own description and schema."""
+ from dodaios.society.ask_tool import ASK_USER_TOOL_NAME, AskUserTool
+
+ return {
+ "name": ASK_USER_TOOL_NAME,
+ "wire": ASK_USER_TOOL_NAME,
+ "description": AskUserTool.description,
+ "schema": _lenient(AskUserTool.schema),
+ "catalogName": f"{mcp_server}__{ASK_USER_TOOL_NAME}",
+ }
+
+
+def _lenient(schema: dict[str, Any]) -> dict[str, Any]:
+ """The ask schema as OpenClaw validates a plugin tool's input: only the
+ question text is required. OpenClaw refuses a call that misses any other
+ required field before Dodaios sees it (live: a small model left out
+ ``recommendation_reason``); Dodaios' own parser decides the rest."""
+ copy = json.loads(json.dumps(schema))
+ questions = copy.get("properties", {}).get("questions", {})
+ items = questions.get("items")
+ if isinstance(items, dict):
+ items["required"] = ["question"]
+ return copy
+
+
+def approval_url(mcp_url: str) -> str:
+ """The gate's endpoint on the same Dodaios server as ``mcp_url``."""
+ from urllib.parse import urlsplit, urlunsplit
+
+ parts = urlsplit(mcp_url)
+ return urlunsplit((parts.scheme, parts.netloc, APPROVAL_PATH, "", ""))
diff --git a/dodaios/society/roster.py b/dodaios/society/roster.py
index 4ceb3fd94b..4d236a73fa 100644
--- a/dodaios/society/roster.py
+++ b/dodaios/society/roster.py
@@ -437,6 +437,45 @@ def _revoke_runtime_grants(agent_id: str) -> None:
log.info("society: revoked %s runtime gateway grant(s) of %s", revoked, agent_id)
+def _runtime_left(before: dict[str, Any], after: dict[str, Any]) -> str:
+ """The runtime whose background processes an agent no longer needs ("" = none).
+
+ An archived Hermes / OpenClaw agent keeps no warm process or OpenClaw
+ Gateway (about 1.3 GB each) running. (An agent's runtime never changes.)
+ """
+ runtime = str(before.get("runtime") or "jarvis")
+ if runtime == "jarvis":
+ return ""
+ archived = str(after.get("state") or "") == str(AgentState.ARCHIVED)
+ was_archived = str(before.get("state") or "") == str(AgentState.ARCHIVED)
+ return runtime if archived and not was_archived else ""
+
+
+#: Runtime stops still running (kept so they are not collected mid-way).
+_STOPPING: set[asyncio.Task[None]] = set()
+
+
+async def _stop_runtime_processes(runtime: str, agent_id: str) -> None:
+ """Stop ``agent_id``'s processes of ``runtime`` if its driver ever started."""
+ from dodaios.agent_runtimes import started_drivers
+
+ for found in started_drivers():
+ if getattr(found, "name", "") != runtime:
+ continue
+ try:
+ await found.stop(agent_id)
+ log.info("society: stopped the %s processes of %s", runtime, agent_id)
+ except Exception: # noqa: BLE001 — the roster change stands; idle reaping still applies
+ log.warning("society: %s processes of %s not stopped", runtime, agent_id,
+ exc_info=True)
+
+
+def _schedule_runtime_stop(runtime: str, agent_id: str) -> None:
+ task = asyncio.get_running_loop().create_task(_stop_runtime_processes(runtime, agent_id))
+ _STOPPING.add(task)
+ task.add_done_callback(_STOPPING.discard)
+
+
def _check_sandbox_placement(row: dict[str, Any]) -> None:
if row.get("execution_environment", "local") != "sandbox":
return
@@ -817,6 +856,9 @@ class Roster:
await self.refresh()
if _seat_left(current, row):
_revoke_runtime_grants(agent_id)
+ if left := _runtime_left(current, row):
+ # Off the request: a Gateway may take seconds to stop.
+ _schedule_runtime_stop(left, agent_id)
return record
async def archive(self, agent_id: str) -> AgentRecord:
diff --git a/dodaios/ui/web/control_routes.py b/dodaios/ui/web/control_routes.py
index 63bad46615..c8052c3851 100644
--- a/dodaios/ui/web/control_routes.py
+++ b/dodaios/ui/web/control_routes.py
@@ -501,3 +501,47 @@ def set_api_key(body: SetKeyBody, request: Request) -> dict[str, Any]:
getattr(client, "host", "unknown"),
)
return {"ok": True, "masked": control_key.mask_control_key(key)}
+
+
+# ----------------------------------------------------------------------
+# Native tool approvals of an agent runtime (OpenClaw's gate plugin)
+# ----------------------------------------------------------------------
+
+
+class _NativeApproval(BaseModel):
+ tool: str = Field(min_length=1, max_length=200)
+ params: dict[str, Any] = Field(default_factory=dict)
+ tool_call_id: str = Field(default="", max_length=200)
+ title: str = Field(default="", max_length=400)
+
+
+ "/runtime/native-approval",
+ dependencies=[Depends(require_control_key)],
+ include_in_schema=False,
+)
+async def runtime_native_approval(body: _NativeApproval, request: Request) -> dict[str, Any]:
+ """Decide one native tool call an agent runtime cannot ask about itself.
+
+ Dodaios' gate plugin in an agent's OpenClaw Gateway holds each file
+ change here until the chat's running turn decides it (its card, or the
+ stance at once). The chat travels in the same header as on the MCP
+ endpoint; without a running turn of that chat the call is refused.
+ """
+ from dodaios.agent_runtimes import native_gate, openclaw_gate
+
+ session_id = (request.headers.get("x-jarvis-chat-session") or "").strip()
+ if not session_id:
+ return {"decision": "deny", "reason": native_gate.NO_TURN}
+ kind = openclaw_gate.kind(body.tool, body.params)
+ if kind == "free":
+ return {"decision": "allow", "reason": ""}
+ decision, reason = await native_gate.decide(
+ session_id,
+ body.tool,
+ body.params,
+ call_id=body.tool_call_id,
+ title=body.title,
+ read_only=kind == "read",
+ )
+ return {"decision": decision, "reason": reason}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/reduce.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/reduce.test.ts
index f47e6f5659..523bc4a043 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/reduce.test.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/reduce.test.ts
@@ -81,6 +81,22 @@ describe("agent-chat reduce", () => {
expect(runningTurn(tl)).toBeNull();
});
+ it("a later message's repaired text replaces the start its stream lost", () => {
+ // OpenClaw's bridge streams a later message from the previous bubble's
+ // length on; the runner then sends the whole answer under the same id.
+ const tl = reduceEvents(EMPTY_TIMELINE, [
+ ev("turn_started", { turn_id: "oc", provider: "ollama", model: "qwen", effort: "", runner: "openclaw-cli" }),
+ ev("assistant_text", { turn_id: "oc", message_id: "a", text: "I create the file." }),
+ ev("tool_call", { turn_id: "oc", call_id: "w", name: "write", input: { path: "a.txt" } }),
+ ev("text_delta", { turn_id: "oc", message_id: "b", text: "a.txt now holds hello." }, false),
+ ev("assistant_text", { turn_id: "oc", message_id: "b", text: "Done! The file a.txt now holds hello." }),
+ ev("turn_finished", { turn_id: "oc", status: "done", duration_ms: 10 }),
+ ]);
+ const turn = tl.items[0] as TurnItem;
+ const texts = turn.blocks.filter((b) => b.kind === "text").map((b) => (b.kind === "text" ? b.text : ""));
+ expect(texts).toEqual(["I create the file.", "Done! The file a.txt now holds hello."]);
+ });
+
it("tracks approvals: pending until resolved, and the tool row carries the decision", () => {
let tl = reduceEvents(EMPTY_TIMELINE, [
ev("turn_started", { turn_id: "t2", provider: "openai", model: "", effort: "", runner: "api" }),
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.test.tsx
index 06a6e40708..e8f3d52bd8 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.test.tsx
@@ -83,6 +83,9 @@ describe("approval mode support", () => {
expect(modeSupported("claude-cli", "ask")).toBe(true);
expect(modeSupported("hermes-cli", "ask")).toBe(true);
expect(modeSupported("openclaw-cli", "ask")).toBe(true);
+ // OpenClaw asks before every native call through Dodaios' gate plugin.
+ expect(modeSupported("openclaw-cli", "always_ask")).toBe(true);
+ expect(modeSupported("hermes-cli", "always_ask")).toBe(false);
expect(modeSupported("opencode-cli", "ask")).toBe(false);
expect(modeSupported(null, "ask")).toBe(false);
expect(modeSupported(null, "bypass")).toBe(true);
@@ -128,6 +131,12 @@ describe("AgentHeader and the approval picker", () => {
expect((screen.getByTestId("approval-mode-always_ask") as HTMLButtonElement).disabled).toBe(true);
});
+ it("lets an OpenClaw agent always ask", async () => {
+ mount(agent({ provider: "codex", runtime: "openclaw", approvalMode: "ask" }));
+ fireEvent.click(screen.getByTestId("agent-approval-mode"));
+ await waitFor(() => expect((screen.getByTestId("approval-mode-always_ask") as HTMLButtonElement).disabled).toBe(false));
+ });
+
it("tightens at once but asks once more before loosening", async () => {
const fetcher = vi.fn(async (url: string, init?: RequestInit) => {
if (String(url).endsWith("/providers")) return json({ providers });
diff --git a/dodaios/ui/web/frontend/src/components/society/card/approvalModes.ts b/dodaios/ui/web/frontend/src/components/society/card/approvalModes.ts
index 0ac261c812..e7a490cf61 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/approvalModes.ts
+++ b/dodaios/ui/web/frontend/src/components/society/card/approvalModes.ts
@@ -26,7 +26,8 @@ const ASK_RUNNERS: ReadonlySet<string> = new Set([
"hermes-cli",
"openclaw-cli",
]);
-const ALWAYS_ASK_RUNNERS: ReadonlySet<string> = new Set(["brain", "codex-cli"]);
+// OpenClaw asks before every native call through Dodaios' gate plugin.
+const ALWAYS_ASK_RUNNERS: ReadonlySet<string> = new Set(["brain", "codex-cli", "openclaw-cli"]);
/**
* The runner that answers this agent's turns, or null while it is not known
diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/ToolsTab.tsx b/dodaios/ui/web/frontend/src/components/society/card/pane/ToolsTab.tsx
index e360d3d437..d08f1d2c95 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/pane/ToolsTab.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/ToolsTab.tsx
@@ -33,6 +33,7 @@ import {
type SocietyAgent,
} from "../../data";
import { AgentSandboxSection } from "../AgentSandboxSection";
+import { modeSupported, runnerFor } from "../approvalModes";
import {
draftFromAgent,
isDirty,
@@ -51,16 +52,6 @@ import { ChipList, ChoicePill, PaneHint, PaneSection, Segmented, type SegmentOpt
/** Rows shown before "Show all": enough for the tools an agent really uses. */
const TOOL_PREVIEW = 8;
-/** Runners that can show an actionable approval card, per mode (mirrors the PATCH validator). */
-function modeUnavailable(mode: AgentApprovalMode, provider: string, runner: string | undefined): boolean {
- const unknownRunner = Boolean(provider) && runner == null;
- if (mode === "always_ask") return unknownRunner || (runner != null && runner !== "codex-cli" && runner !== "brain");
- if (mode === "ask") {
- return unknownRunner || (runner != null && !["codex-cli", "claude-cli", "glm-cli", "brain"].includes(runner));
- }
- return false;
-}
-
export function ToolsTab({ agent, sample }: { agent: SocietyAgent; sample: boolean }) {
const t = useT();
useLocaleChunk("society");
@@ -69,7 +60,8 @@ export function ToolsTab({ agent, sample }: { agent: SocietyAgent; sample: boole
const assistantName = useEventStore((s) => s.assistantName);
const capabilities = useSocietyCapabilities(!sample);
const providers = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders, enabled: !lead && !sample, retry: false });
- const runner = providers.data?.find((row) => row.id === agent.provider)?.runner;
+ // The runner that answers this agent (Hermes and OpenClaw run their own).
+ const runner = runnerFor(agent, providers.data);
const base = useMemo(() => draftFromAgent(agent), [agent]);
const [draft, setDraft] = useState<AccessDraft>(base);
@@ -174,7 +166,7 @@ export function ToolsTab({ agent, sample }: { agent: SocietyAgent; sample: boole
disabled={disabled}
testId="agent-pane-approval-mode"
options={AGENT_APPROVAL_MODES.map((mode) => {
- const off = modeUnavailable(mode, agent.provider, runner);
+ const off = !modeSupported(runner, mode);
return {
value: mode,
label: t(`society.approval_mode.${mode}`),
diff --git a/tests/unit/agent_runtimes/test_hermes_gateway_daemon.py b/tests/unit/agent_runtimes/test_hermes_gateway_daemon.py
index 3587f615c6..7521b2bc43 100644
--- a/tests/unit/agent_runtimes/test_hermes_gateway_daemon.py
+++ b/tests/unit/agent_runtimes/test_hermes_gateway_daemon.py
@@ -96,11 +96,14 @@ def test_stopping_an_agent_stops_only_its_daemons(roots, stopped):
bob = Path(_launch(runtime, _turn(roots, agent="bob")).env["HERMES_HOME"])
stopped.clear()
asyncio.run(runtime.stop("ada"))
- assert stopped == [ada]
+ # Both of ada's profiles (chat and routine runs), started this run or not.
+ assert ada in stopped and bob not in stopped
+ assert all(path.name.startswith("ada") for path in stopped)
+ stopped.clear()
asyncio.run(runtime.stop())
- assert stopped == [ada, bob]
+ assert stopped == [bob]
asyncio.run(runtime.stop()) # nothing left to stop
- assert stopped == [ada, bob]
+ assert stopped == [bob]
def _sleeper(*argv: str) -> subprocess.Popen:
diff --git a/tests/unit/agent_runtimes/test_openclaw_gates.py b/tests/unit/agent_runtimes/test_openclaw_gates.py
new file mode 100644
index 0000000000..9a7deeef42
--- /dev/null
+++ b/tests/unit/agent_runtimes/test_openclaw_gates.py
@@ -0,0 +1,576 @@
+"""OpenClaw agents: native tool approvals, the plain-named ask tool, stream
+repair, Gateway restarts and retired agents.
+
+Live 2026-10-28 (a local Ollama agent on OpenClaw 2026.10.8):
+
+- with Permissions = Ask, OpenClaw's own ``write`` ran without a card: only
+ exec approvals reach the ACP client;
+- the model called ``society_ask_user`` and got "Tool society_ask_user not
+ found" (the MCP catalog has ``dodaios__society_ask_user`` behind tool
+ search), then OpenClaw's own ``ask_user`` rejected the id ``color-pref``;
+- after OpenClaw's "isolated finalization" pass the chat lost the first N
+ characters of the reply (N = the previous bubble's length);
+- a run OpenClaw itself ended as ``cancelled`` poisoned the Gateway, whose
+ restart then could not resume the run (``delegated_authority_unavailable``);
+- archiving the agent left its Gateway (about 1.3 GB) running.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from concurrent.futures import Future
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from dodaios.agent_runtimes import base, gateway, native_gate, openclaw_gate
+from dodaios.agent_runtimes.acp import AcpTurn
+from dodaios.agent_runtimes.base import RuntimeTurn
+from dodaios.agent_runtimes.model_map import ModelRoute
+from dodaios.agent_runtimes.openclaw import OpenClawRuntime
+
+_MCP = "http://127.0.0.1:47821/api/control/mcp/"
+
+
[email protected](autouse=True)
+def _clean(monkeypatch, tmp_path):
+ monkeypatch.setattr(base, "runtimes_root", lambda: tmp_path / "rt")
+ monkeypatch.setattr(base, "legacy_runtimes_root", lambda: tmp_path / "legacy")
+ native_gate.reset()
+ gateway.reset()
+ yield
+ native_gate.reset()
+ gateway.reset()
+
+
+def _turn(tmp_path: Path, **overrides: Any) -> RuntimeTurn:
+ values: dict[str, Any] = {
+ "agent_id": "ada",
+ "agent_name": "Ada",
+ "session_id": "society:ada",
+ "workspace": tmp_path,
+ "route": ModelRoute(
+ provider="ollama",
+ model="qwen3.5:9b",
+ base_url="http://127.0.0.1:47821/api/runtime-gateway/v1",
+ transport="chat_completions",
+ api_key="gw-token",
+ context_window=65536,
+ ),
+ "resume": None,
+ "auto_approve": False,
+ "mcp_url": _MCP,
+ "control_key": "control-key",
+ }
+ values.update(overrides)
+ return RuntimeTurn(**values)
+
+
+def _config(tmp_path: Path, **overrides: Any) -> dict[str, Any]:
+ token = "t" # noqa: S105 — the loopback Gateway token: any value
+ return OpenClawRuntime().config_for(_turn(tmp_path, **overrides), port=1, token=token)
+
+
+# ------------------------------------------------------------ the config
+
+
+def test_the_gate_plugin_is_loaded_and_the_config_ignores_the_stance(tmp_path):
+ ask = _config(tmp_path)
+ bypass = _config(tmp_path, auto_approve=True)
+ # A stance change never rewrites the file, so it never restarts the Gateway.
+ assert ask == bypass
+ plugins = ask["plugins"]
+ folder = Path(plugins["load"]["paths"][0])
+ assert folder.name == openclaw_gate.PLUGIN_ID
+ assert (folder / "index.mjs").is_file()
+ assert (folder / "openclaw.plugin.json").is_file()
+ entry = plugins["entries"][openclaw_gate.PLUGIN_ID]
+ assert entry["enabled"] is True
+ assert entry["hooks"]["timeouts"]["before_tool_call"] == openclaw_gate.HOOK_TIMEOUT_MS
+ settings = entry["config"]
+ assert settings["gateUrl"] == "http://127.0.0.1:47821/api/control/runtime/native-approval"
+ assert settings["session"] == "society:ada"
+ assert settings["ask"]["name"] == "society_ask_user"
+ # Nothing secret in the file: the plugin reads the key from its environment.
+ assert "control-key" not in json.dumps(ask)
+
+
+def test_the_file_tools_stay_and_unanswerable_native_tools_go(tmp_path):
+ denied = set(_config(tmp_path)["tools"]["deny"])
+ assert not denied & set(openclaw_gate.GATED_TOOLS) # they ask through the gate
+ assert {"computer", "terminal", "openclaw", "ask_user"} <= denied
+ # One ask tool: the plain one, never the deferred MCP copy as well.
+ assert "dodaios__society_ask_user" in denied
+ assert _config(tmp_path)["tools"]["exec"]["mode"] == "ask"
+
+
+def test_without_dodaios_tools_file_changes_do_not_run_outside_bypass(tmp_path):
+ ask = _config(tmp_path, mcp_url=None, control_key=None)
+ assert "load" not in ask["plugins"]
+ assert set(openclaw_gate.GATED_TOOLS) <= set(ask["tools"]["deny"])
+ bypass = _config(tmp_path, mcp_url=None, control_key=None, auto_approve=True)
+ assert not set(openclaw_gate.GATED_TOOLS) & set(bypass["tools"]["deny"])
+
+
+def test_a_routine_gateway_gates_files_but_offers_no_question(tmp_path):
+ entry = _config(tmp_path, session_id="society:ada:routine:7")["plugins"]["entries"][
+ openclaw_gate.PLUGIN_ID
+ ]
+ assert entry["config"]["gateUrl"]
+ assert "ask" not in entry["config"]
+ assert "mcpUrl" not in entry["config"]
+
+
+def test_the_plugin_build_is_part_of_the_config(tmp_path):
+ first = openclaw_gate.install(tmp_path)
+ again = openclaw_gate.install(tmp_path)
+ assert first == again
+ source = (first.path / "index.mjs").read_text(encoding="utf-8")
+ for tool in (*openclaw_gate.GATED_TOOLS, *openclaw_gate.READ_TOOLS, "process"):
+ assert f'"{tool}"' in source
+ assert "JARVIS_CONTROL_API_KEY" in source
+ assert 'catalogMode: "direct-only"' in source
+ manifest = json.loads((first.path / "openclaw.plugin.json").read_text(encoding="utf-8"))
+ assert manifest["contracts"]["tools"] == ["society_ask_user"]
+ entry = _config(tmp_path)["plugins"]["entries"][openclaw_gate.PLUGIN_ID]
+ assert entry["config"]["build"] == first.digest
+
+
+def test_the_plain_ask_tool_only_requires_the_question():
+ """OpenClaw validates a plugin tool's input before Dodaios sees it: a
+ small model that leaves out ``recommendation_reason`` (or sends an id
+ like ``color-pref``) still reaches the card."""
+ from dodaios.agent_chat.questions import parse_questions
+ from dodaios.society.ask_tool import AskUserTool
+
+ spec = openclaw_gate.ask_spec("dodaios")
+ items = spec["schema"]["properties"]["questions"]["items"]
+ assert items["required"] == ["question"]
+ assert AskUserTool.schema["properties"]["questions"]["items"]["required"] == [
+ "question", "recommendation_reason",
+ ] # Dodaios' own schema is untouched
+ asked = {"questions": [{"id": "color-pref", "header": "Colour", "question": "Which colour?",
+ "options": [{"label": "red"}, {"label": "green"}],
+ "multiSelect": False}]}
+ (question,) = parse_questions(asked)
+ assert question.question == "Which colour?"
+ assert [o.label for o in question.options] == ["red", "green"]
+
+
+# ------------------------------------------------------- the native gate
+
+
+class _IO:
+ def __init__(self, answer: str = "allow") -> None:
+ self.answer = answer
+ self.events: list[dict[str, Any]] = []
+ self.asked: list[tuple[str, str]] = []
+
+ async def write(self, frame: dict[str, Any]) -> None:
+ pass
+
+ async def emit(self, event: dict[str, Any]) -> None:
+ self.events.append(event)
+
+ async def ask(self, call_id: str, name: str, args: dict[str, Any], summary: str) -> str:
+ self.asked.append((call_id, name))
+ return self.answer
+
+
+def _kinds(io: _IO) -> list[str]:
+ return [event["kind"] for event in io.events]
+
+
+def _gate(turn: AcpTurn, io: _IO, tool: str = "write", *, read_only: bool = False) -> str:
+ return asyncio.run(
+ turn.native_permission(
+ io, "call_w1", tool, {"path": "a.txt", "content": "x"}, f"{tool}: a.txt",
+ read_only=read_only,
+ )
+ )
+
+
+def test_ask_shows_a_card_on_the_tool_row():
+ io = _IO("allow")
+ turn = AcpTurn(turn_id="t", cwd=".", prompt_text="hi")
+ assert _gate(turn, io) == "allow"
+ assert io.asked == [("call_w1", "write")]
+ assert _kinds(io) == ["tool_call"]
+ # The ACP tool_call of the same call that follows adds no second row.
+ assert "call_w1" in turn.emitted_tool_ids
+
+
+def test_bypass_allows_and_plan_refuses_without_a_card():
+ io = _IO()
+ assert _gate(AcpTurn(turn_id="t", cwd=".", prompt_text="hi", auto_allow=True), io) == "allow"
+ assert _gate(AcpTurn(turn_id="t", cwd=".", prompt_text="hi", auto_deny=True), io) == "deny"
+ assert io.asked == []
+
+
+def test_reads_ask_in_always_ask_only():
+ io = _IO()
+ for turn in (
+ AcpTurn(turn_id="t", cwd=".", prompt_text="hi"),
+ AcpTurn(turn_id="t", cwd=".", prompt_text="hi", auto_deny=True), # Plan reads freely
+ ):
+ assert _gate(turn, io, "read", read_only=True) == "allow"
+ assert io.asked == []
+ strict = AcpTurn(turn_id="t", cwd=".", prompt_text="hi", always_ask=True)
+ assert _gate(strict, io, "read", read_only=True) == "allow"
+ assert io.asked == [("call_w1", "read")]
+
+
+def test_allow_always_is_remembered_except_in_always_ask():
+ remembered: set[str] = set()
+ io = _IO("allow_always")
+ turn = AcpTurn(turn_id="t", cwd=".", prompt_text="hi", native_always=remembered)
+ assert _gate(turn, io) == "allow_always"
+ assert remembered == {"write"}
+ later = AcpTurn(turn_id="t2", cwd=".", prompt_text="hi", native_always=remembered)
+ assert _gate(later, _IO("deny")) == "allow" # no second card
+ strict_set: set[str] = set()
+ strict = AcpTurn(
+ turn_id="t3", cwd=".", prompt_text="hi", always_ask=True, native_always=strict_set
+ )
+ assert _gate(strict, _IO("allow_always")) == "allow"
+ assert strict_set == set()
+
+
+def test_decide_refuses_without_a_running_turn_and_follows_the_card():
+ async def go() -> list[tuple[str, str]]:
+ results = [await native_gate.decide("society:ada", "write", {})]
+ answers = iter(["allow", "deny", "cancel"])
+
+ async def decider(call_id, tool, args, title, read_only):
+ return next(answers)
+
+ native_gate.register("society:ada", decider)
+ for _ in range(3):
+ results.append(await native_gate.decide("society:ada", "write", {}))
+ native_gate.unregister("society:ada", decider)
+ results.append(await native_gate.decide("society:ada", "write", {}))
+ return results
+
+ assert asyncio.run(go()) == [
+ ("deny", native_gate.NO_TURN),
+ ("allow", ""),
+ ("deny", native_gate.DECLINED),
+ ("deny", native_gate.STOPPED),
+ ("deny", native_gate.NO_TURN),
+ ]
+
+
+def test_a_card_nobody_answers_is_refused_in_time(monkeypatch):
+ monkeypatch.setattr(native_gate, "DECISION_TIMEOUT_S", 0.05)
+
+ async def never(*_args):
+ await asyncio.sleep(10)
+ return "allow"
+
+ async def go() -> tuple[str, str]:
+ native_gate.register("s", never)
+ return await native_gate.decide("s", "edit", {})
+
+ assert asyncio.run(go()) == ("deny", native_gate.NO_ANSWER)
+ assert native_gate.DECISION_TIMEOUT_S * 1000 < openclaw_gate.HOOK_TIMEOUT_MS
+
+
+def test_the_control_route_asks_the_running_turn(monkeypatch):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from dodaios.ui.web import control_routes
+
+ app = FastAPI()
+ app.include_router(control_routes.router)
+ app.dependency_overrides[control_routes.require_control_key] = lambda: None
+ seen: list[tuple[str, str, bool]] = []
+
+ async def decider(call_id, tool, args, title, read_only):
+ seen.append((call_id, tool, read_only))
+ return "allow"
+
+ native_gate.register("society:ada", decider)
+ client = TestClient(app)
+ url = "/api/control/runtime/native-approval"
+ body = {"tool": "write", "params": {"path": "a"}, "tool_call_id": "c1", "title": "write: a"}
+ ok = client.post(url, json=body, headers={"x-jarvis-chat-session": "society:ada"})
+ assert ok.json() == {"decision": "allow", "reason": ""}
+ read = client.post(
+ url, json={**body, "tool": "read"}, headers={"x-jarvis-chat-session": "society:ada"}
+ )
+ assert read.json()["decision"] == "allow"
+ assert seen == [("c1", "write", False), ("c1", "read", True)]
+ other = client.post(url, json=body, headers={"x-jarvis-chat-session": "society:bob"})
+ assert other.json() == {"decision": "deny", "reason": native_gate.NO_TURN}
+ nobody = client.post(url, json=body)
+ assert nobody.json()["decision"] == "deny"
+
+
+def test_typing_into_a_running_process_asks_and_watching_it_does_not():
+ # An allowed interactive shell would otherwise run every later command
+ # typed into it without a card.
+ assert openclaw_gate.kind("process", {"action": "submit", "data": "rm -rf x"}) == "change"
+ assert openclaw_gate.kind("process", {"action": "send-keys"}) == "change"
+ for action in ("list", "poll", "log", "kill"):
+ assert openclaw_gate.kind("process", {"action": action}) == "free"
+ assert openclaw_gate.kind("grep", {"pattern": "x"}) == "read"
+ assert openclaw_gate.kind("write", {"path": "a"}) == "change"
+
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from dodaios.ui.web import control_routes
+
+ app = FastAPI()
+ app.include_router(control_routes.router)
+ app.dependency_overrides[control_routes.require_control_key] = lambda: None
+ seen: list[tuple[str, bool]] = []
+
+ async def decider(call_id, tool, args, title, read_only):
+ seen.append((tool, read_only))
+ return "deny"
+
+ native_gate.register("society:ada", decider)
+ client = TestClient(app)
+ url = "/api/control/runtime/native-approval"
+ headers = {"x-jarvis-chat-session": "society:ada"}
+ poll = client.post(url, json={"tool": "process", "params": {"action": "poll"}}, headers=headers)
+ assert poll.json()["decision"] == "allow"
+ typed = client.post(
+ url, json={"tool": "process", "params": {"action": "submit"}}, headers=headers
+ )
+ assert typed.json()["decision"] == "deny"
+ assert seen == [("process", False)]
+
+
+# ------------------------------------------------------ stream repair
+
+
+def _update(kind: str, **fields: Any) -> dict[str, Any]:
+ return {
+ "jsonrpc": "2.0",
+ "method": "session/update",
+ "params": {"sessionId": "s", "update": {"sessionUpdate": kind, **fields}},
+ }
+
+
+def _chunk(text: str) -> dict[str, Any]:
+ return _update("agent_message_chunk", content={"type": "text", "text": text})
+
+
+def _tool(call_id: str) -> dict[str, Any]:
+ return _update("tool_call", toolCallId=call_id, title="write: a.txt", status="in_progress")
+
+
+def _done(call_id: str) -> dict[str, Any]:
+ return _update("tool_call_update", toolCallId=call_id, status="completed")
+
+
+def _result(stop: str = "end_turn") -> dict[str, Any]:
+ return {"jsonrpc": "2.0", "id": 3, "result": {"stopReason": stop}}
+
+
+def _texts(io: _IO) -> list[str]:
+ return [e["payload"]["text"] for e in io.events if e["kind"] == "assistant_text"]
+
+
+def _run(frames: list[dict[str, Any]], replies: list[tuple[str, int]], **kw: Any):
+ turn = AcpTurn(
+ turn_id="t", cwd=".", prompt_text="hi", reply_texts=lambda: list(replies), **kw
+ )
+ turn._acp_session = "s"
+ io = _IO()
+
+ async def go() -> None:
+ for frame in frames:
+ await turn.on_message(frame, io)
+
+ asyncio.run(go())
+ return turn, io
+
+
+def test_a_reply_cut_by_the_previous_bubble_is_shown_whole():
+ first = "I create the file qa_local.txt."
+ final = "Done! The file qa_local.txt now holds: hello from QA (13 bytes)."
+ # OpenClaw's bridge sends the final message from offset len(first) on.
+ cut = final[len(first):]
+ turn, io = _run(
+ [_chunk(first), _tool("w"), _done("w"), _chunk(cut), _result()],
+ [(first, 1), ("", 0), (final, 0)],
+ )
+ assert _texts(io) == [first, final]
+ assert turn.result_text == final and turn.status == "done"
+
+
+def test_a_final_reply_shorter_than_the_last_bubble_is_not_lost():
+ first = "Let me look at the whole repository before I answer the question."
+ final = "Red or green?"
+ turn, io = _run(
+ [_chunk(first), _tool("w"), _done("w"), _result()],
+ [(first, 1), (final, 0)],
+ )
+ assert _texts(io) == [first, final]
+ assert turn.result_text == final
+
+
+def test_intact_streams_and_silent_replies_stay_as_they_are():
+ _, io = _run([_chunk("Hello there."), _result()], [("Hello there.", 0)])
+ assert _texts(io) == ["Hello there."]
+ _, io = _run([_tool("w"), _done("w"), _result()], [("", 1), ("NO_REPLY", 0)])
+ assert _texts(io) == []
+ # The last model call asked for a tool: no answer was dropped.
+ _, io = _run([_chunk("Working."), _tool("w"), _result()], [("Working.", 1)])
+ assert _texts(io) == ["Working."]
+
+
+def test_the_gateway_keeps_each_turns_answers():
+ signal: Future[str] = Future()
+ other: Future[str] = Future()
+ gateway._record_reply(signal, "first", 1)
+ gateway._record_reply(signal, "second", 0)
+ gateway._record_reply(None, "nobody", 0)
+ assert gateway.turn_replies(signal) == [("first", 1), ("second", 0)]
+ assert gateway.turn_replies(other) == []
+ for i in range(100):
+ gateway._record_reply(signal, str(i), 0)
+ assert len(gateway.turn_replies(signal)) == gateway._MAX_REPLIES
+ assert gateway.turn_replies(signal)[-1] == ("99", 0)
+
+
+# ----------------------------------------- runtime-ended runs and restarts
+
+
+def test_a_run_the_runtime_cancelled_itself_says_so():
+ turn, _ = _run([_chunk("Red or green?"), _result("cancelled")], [])
+ assert turn.prompt_answered
+ assert turn.error and turn.error.startswith("The runtime ended the run")
+ stopped = AcpTurn(turn_id="t", cwd=".", prompt_text="hi")
+ stopped._acp_session = "s"
+ assert stopped.cancel_frame() is not None
+ io = _IO()
+ asyncio.run(stopped.on_message(_result("cancelled"), io))
+ assert stopped.error == "The turn was cancelled before it finished."
+
+
+def test_an_answered_prompt_never_restarts_the_gateway():
+ from dodaios.agent_chat.runner_acp import poisons_runtime
+
+ ended, _ = _run([_chunk("x"), _result("cancelled")], [])
+ for cancelled in (False, True):
+ assert not poisons_runtime(ended, cancelled=cancelled, provider_failed=False)
+ # A failure the model gateway saw still starts the runtime afresh.
+ assert poisons_runtime(ended, cancelled=False, provider_failed=True)
+ silent = AcpTurn(turn_id="t", cwd=".", prompt_text="hi")
+ assert poisons_runtime(silent, cancelled=False, provider_failed=False)
+ assert poisons_runtime(None, cancelled=False, provider_failed=False)
+ starting = AcpTurn(turn_id="t", cwd=".", prompt_text="hi")
+ starting._fail("Agent main has not completed startup inspection and preparation.")
+ assert not poisons_runtime(starting, cancelled=False, provider_failed=False)
+
+
+# ------------------------------------------------------ retired agents
+
+
+async def test_archiving_a_runtime_agent_stops_its_processes(tmp_path, monkeypatch):
+ from dodaios import agent_runtimes
+ from dodaios.society import roster as roster_mod
+ from dodaios.society import runtime as runtime_mod
+ from dodaios.society.runtime import SocietyRuntime
+
+ stopped: list[tuple[str, str]] = []
+
+ class Fake:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+ async def stop(self, agent_id=None):
+ stopped.append((self.name, agent_id))
+
+ drivers = [Fake("hermes"), Fake("openclaw")]
+ monkeypatch.setattr(agent_runtimes, "started_drivers", lambda: drivers)
+ rt = SocietyRuntime(tmp_path / "society", seed_starter_team=False)
+ await rt.ensure_started()
+ try:
+ claw, _ = await rt.roster.create(name="Claw", runtime="openclaw")
+ plain, _ = await rt.roster.create(name="Plain")
+ await rt.roster.archive(plain.agent_id)
+ await rt.roster.archive(claw.agent_id)
+ await asyncio.gather(*list(roster_mod._STOPPING))
+ assert stopped == [("openclaw", claw.agent_id)]
+ hermit, _ = await rt.roster.create(name="Hermit", runtime="hermes")
+ await rt.roster.update(hermit.agent_id, {"title": "Researcher"})
+ await asyncio.gather(*list(roster_mod._STOPPING))
+ assert len(stopped) == 1 # an ordinary edit stops nothing
+ await rt.roster.archive(hermit.agent_id)
+ await asyncio.gather(*list(roster_mod._STOPPING))
+ assert stopped[-1] == ("hermes", hermit.agent_id)
+ finally:
+ runtime_mod.set_current_runtime(None)
+ await rt.close()
+
+
+def test_openclaw_offers_always_ask_and_hermes_does_not():
+ from dodaios.agent_chat.permissions import society_mode_supported
+
+ assert society_mode_supported("openclaw-cli", "always_ask")
+ assert society_mode_supported("openclaw-cli", "ask")
+ assert not society_mode_supported("hermes-cli", "always_ask")
+
+
+def test_the_plugins_ask_call_passes_dodaios_mcp_endpoint(monkeypatch):
+ """The plugin calls Dodaios' MCP tool with one stateless ``tools/call``;
+ the endpoint checks the call against the listed schema, which requires
+ ``recommendation_reason`` (the plugin fills an empty one in)."""
+ from types import SimpleNamespace
+
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from dodaios.core import runtime_refs
+ from dodaios.core.protocols import ToolResult
+ from dodaios.society.ask_tool import AskUserTool
+ from dodaios.ui.web import mcp_server_routes
+
+ seen: list[dict[str, Any]] = []
+
+ class Gateway:
+ def catalog(self):
+ return [SimpleNamespace(
+ name="society_ask_user", description="ask", input_schema=AskUserTool.schema,
+ read_only=False,
+ )]
+
+ async def execute(self, name, args, request):
+ seen.append(args)
+ return ToolResult(success=True, output={"answers": [{"answer": "red"}]})
+
+ monkeypatch.setattr(runtime_refs, "get_supervisor_tool_gateway", lambda: Gateway())
+ monkeypatch.setattr(mcp_server_routes, "_authorized", lambda scope, surface: True)
+ app = FastAPI()
+ app.mount("/api/control/mcp", mcp_server_routes.build_mcp_asgi_app())
+ headers = {
+ "accept": "application/json, text/event-stream",
+ "content-type": "application/json",
+ "x-jarvis-chat-session": "society:ada",
+ }
+
+ def call(method: str, params: dict[str, Any]) -> dict[str, Any]:
+ body = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
+ return client.post("/api/control/mcp/", headers=headers, json=body).json()
+
+ question = {"id": "color_pref", "header": "Colour", "question": "Which colour?",
+ "options": [{"label": "red"}, {"label": "green"}]}
+ with TestClient(app) as client:
+ assert call("tools/list", {})["result"]["tools"][0]["name"] == "society_ask_user"
+ filled = call("tools/call", {"name": "society_ask_user", "arguments": {
+ "questions": [{**question, "recommendation_reason": ""}]}})
+ assert filled["result"]["isError"] is False, filled
+ assert seen and seen[0]["questions"][0]["question"] == "Which colour?"
+ bare = call("tools/call", {"name": "society_ask_user",
+ "arguments": {"questions": [question]}})
+ assert bare["result"]["isError"] is True # why the plugin fills the reason in
+ source = openclaw_gate.source()
+ assert 'next.recommendation_reason = ""' in source