Skip to content

The agent that grows with you

fix(plugins): subagent lifecycle facade works under plugin-host isolation; add steer

Eva5a7151266268
diff --git a/agent/subagent_lifecycle.py b/agent/subagent_lifecycle.py
index 3aca72ee77b..8dd639c92ef 100644
--- a/agent/subagent_lifecycle.py
+++ b/agent/subagent_lifecycle.py
@@ -234,6 +234,35 @@ def _handle_is_well_formed(handle: Any) -> bool:
return isinstance(handle, SubagentHandle) and all(check(getattr(handle, field)) for field, check in _HANDLE_FIELD_CHECKS)
+def _coerce_request(request: Any) -> SubagentLaunchRequest:
+ if isinstance(request, SubagentLaunchRequest):
+ return request
+ if not isinstance(request, Mapping):
+ raise SubagentLifecycleError("request must be a SubagentLaunchRequest or a mapping of its fields.")
+ values = dict(request)
+ unknown = set(values) - {field.name for field in dataclasses.fields(SubagentLaunchRequest)}
+ if unknown:
+ raise SubagentLifecycleError(f"Unknown request fields: {', '.join(sorted(map(str, unknown)))}.")
+ for name in ("allowed_toolsets", "blocked_tools"):
+ if isinstance(values.get(name), list):
+ values[name] = tuple(values[name])
+ try:
+ return SubagentLaunchRequest(**values)
+ except TypeError as exc:
+ raise SubagentLifecycleError(f"Malformed subagent launch request: {exc}") from exc
+
+
+def _coerce_handle(handle: Any) -> Optional[SubagentHandle]:
+ if isinstance(handle, SubagentHandle):
+ return handle
+ if isinstance(handle, Mapping):
+ try:
+ return SubagentHandle.from_dict(handle)
+ except SubagentLifecycleError:
+ return None
+ return None
+
+
class SubagentLifecycleService:
"""Stable public service behind :attr:`PluginContext.subagent_lifecycle`. Children run in-process only;
completed results stay until process exit; ``reconnect`` reports that a serialized handle cannot
@@ -242,10 +271,11 @@ class SubagentLifecycleService:
def __init__(self, parent_agent_resolver: Callable[[], Any]) -> None:
self._parent_agent_resolver = parent_agent_resolver
- def launch(self, request: SubagentLaunchRequest) -> SubagentHandle:
+ def launch(self, request: SubagentLaunchRequest | Mapping[str, Any]) -> SubagentHandle:
parent = self._parent_agent_resolver()
if parent is None:
raise SubagentLifecycleError("No active Hermes parent session is available.")
+ request = _coerce_request(request)
self._validate_request(request, parent)
parent_session_id = _session_id_of(parent)
if request.parent_session_id and request.parent_session_id != parent_session_id:
@@ -279,14 +309,14 @@ class SubagentLifecycleService:
record.future = _EXECUTOR.submit(self._run, record, request.goal, parent)
return handle
- def status(self, handle: SubagentHandle) -> SubagentStatus:
+ def status(self, handle: SubagentHandle | Mapping[str, Any]) -> SubagentStatus:
record = self._record(handle)
if record is None:
return SubagentStatus(handle, SubagentState.UNKNOWN, time.time(), "UNKNOWN_HANDLE")
with _REGISTRY.lock:
return SubagentStatus(record.handle, record.state, record.updated_at)
- def wait(self, handle: SubagentHandle, *, timeout_seconds: Optional[float] = None) -> SubagentTerminalState:
+ def wait(self, handle: SubagentHandle | Mapping[str, Any], *, timeout_seconds: Optional[float] = None) -> SubagentTerminalState:
record = self._record(handle)
if record is None:
return SubagentTerminalState(handle, SubagentState.UNKNOWN, True, diagnostic="UNKNOWN_HANDLE")
@@ -300,7 +330,7 @@ class SubagentLifecycleService:
with _REGISTRY.lock:
return SubagentTerminalState(record.handle, record.state, record.result is not None)
- def cancel(self, handle: SubagentHandle, *, reason: str) -> SubagentCancelResult:
+ def cancel(self, handle: SubagentHandle | Mapping[str, Any], *, reason: str) -> SubagentCancelResult:
record = self._record(handle)
if record is None:
return SubagentCancelResult(False, unknown_handle=True)
@@ -318,22 +348,34 @@ class SubagentLifecycleService:
)
return SubagentCancelResult(bool(accepted), unsupported=not accepted, state=SubagentState.CANCEL_REQUESTED)
- def result(self, handle: SubagentHandle) -> SubagentResult:
+ def result(self, handle: SubagentHandle | Mapping[str, Any]) -> SubagentResult:
record = self._record(handle)
if record is None:
return SubagentResult(handle, SubagentState.UNKNOWN, False, error_classification="UNKNOWN_HANDLE")
with _REGISTRY.lock:
return record.result or SubagentResult(record.handle, record.state, False, error_classification="NOT_READY")
- def reconnect(self, handle: SubagentHandle) -> SubagentReconnectResult:
+ def reconnect(self, handle: SubagentHandle | Mapping[str, Any]) -> SubagentReconnectResult:
record = self._record(handle)
if record is None:
return SubagentReconnectResult(False, SubagentState.UNKNOWN, "RECONNECT_UNAVAILABLE")
with _REGISTRY.lock:
return SubagentReconnectResult(True, record.state)
- def _record(self, handle: SubagentHandle) -> Optional[_Record]:
+ def steer(self, handle: SubagentHandle | Mapping[str, Any], text: str) -> bool:
+ """Queue text for the child's next iteration boundary while it accepts steering."""
+ record = self._record(handle)
+ if record is None or not isinstance(text, str) or not text.strip():
+ return False
+ with _REGISTRY.lock:
+ if record.result is not None:
+ return False
+ from tools.delegate_tool_registry import steer_subagent
+ return steer_subagent(record.handle.subagent_id, text.strip())
+
+ def _record(self, handle: SubagentHandle | Mapping[str, Any]) -> Optional[_Record]:
"""Registry record for a well-formed, capability-verified handle owned by the active parent."""
+ handle = _coerce_handle(handle)
if not _handle_is_well_formed(handle):
return None
expected = self._capability(handle.subagent_id, handle.parent_session_id, handle.created_at)
diff --git a/tests/agent/test_subagent_lifecycle.py b/tests/agent/test_subagent_lifecycle.py
index 262e0517baf..aad844e43b2 100644
--- a/tests/agent/test_subagent_lifecycle.py
+++ b/tests/agent/test_subagent_lifecycle.py
@@ -1,5 +1,6 @@
"""Contract tests for the public plugin subagent lifecycle API."""
+import threading
import time
from types import SimpleNamespace
from unittest.mock import Mock
@@ -27,6 +28,11 @@ class FakeChild:
self.interrupt_kind = None
self.interrupt_message = None
self.tool_reason = None
+ self.steering = []
+
+ def steer(self, text):
+ self.steering.append(text)
+ return True
def interrupt(self, _reason):
self.interrupted = True
@@ -178,3 +184,87 @@ def test_agent_turn_binds_and_clears_lifecycle_parent(monkeypatch):
assert agent.run_conversation("hello") == {"final_response": "ok"}
assert observed == [agent]
assert get_active_subagent_parent() is None
+
+
+def steer_lifecycle(monkeypatch):
+ from agent.subagent_lifecycle import _REGISTRY
+ from tools.delegate_tool_registry import _register_subagent, _unregister_subagent
+
+ child = FakeChild("sa-steer-contract")
+ started, finish = threading.Event(), threading.Event()
+ service = SubagentLifecycleService(lambda: SimpleNamespace(session_id="parent-steer", enabled_toolsets=["file"]))
+
+ def run(_index, _goal, child, _parent):
+ _register_subagent({"subagent_id": child._subagent_id, "agent": child})
+ try:
+ started.set()
+ assert finish.wait(5)
+ return {"status": "interrupted" if child.interrupted else "completed", "summary": "done"}
+ finally:
+ _unregister_subagent(child._subagent_id, agent=child)
+
+ monkeypatch.setattr("tools.delegate_tool._build_child_agent", lambda **_kwargs: child)
+ monkeypatch.setattr("tools.delegate_tool._run_single_child", run)
+ yield service, child, started, finish
+ finish.set()
+ record = _REGISTRY.records.get(child._subagent_id)
+ if record is not None:
+ record.future.result(timeout=5)
+
+
[email protected]("wire", [False, True])
+def test_steer_queues_to_running_child_and_rejects_invalid_calls(steer_lifecycle, wire):
+ from hermes_cli.plugin_host_wire import decode, encode
+
+ service, child, started, finish = steer_lifecycle
+ request = SubagentLaunchRequest(goal="review", allowed_toolsets=("file",))
+ handle = service.launch(decode(encode(request)) if wire else request)
+ assert started.wait(2)
+ handle = decode(encode(handle)) if wire else handle
+ assert service.status(handle).state is SubagentState.RUNNING
+ assert service.reconnect(handle).connected
+ assert service.steer(handle, "focus on correctness") is True
+ assert child.steering == ["focus on correctness"]
+ assert service.steer(handle, "") is False
+ assert service.steer(handle, " ") is False
+ other = SubagentLifecycleService(lambda: SimpleNamespace(session_id="foreign"))
+ assert other.steer(handle, "foreign") is False
+ forged = {**(dict(handle) if wire else handle.to_dict()), "capability": "forged"}
+ assert service.steer(forged, "forged") is False
+ finish.set()
+ assert service.wait(handle, timeout_seconds=2).state is SubagentState.SUCCEEDED
+ assert service.result(handle).summary == "done"
+ assert service.steer(handle, "too late") is False
+ assert child.steering == ["focus on correctness"]
+
+
+def test_wire_handle_can_cancel_a_running_child(steer_lifecycle):
+ from hermes_cli.plugin_host_wire import decode, encode
+
+ service, child, started, finish = steer_lifecycle
+ handle = decode(encode(service.launch(SubagentLaunchRequest(goal="cancel"))))
+ assert started.wait(2)
+ assert service.cancel(handle, reason="cancel wire child").accepted
+ assert child.interrupted
+ finish.set()
+ assert service.wait(handle, timeout_seconds=2).state is SubagentState.CANCELLED
+
+
[email protected]("handle", [{}, {"subagent_id": "unknown"}, 42])
+def test_malformed_handles_keep_unknown_results(lifecycle, handle):
+ assert lifecycle.status(handle).diagnostic == "UNKNOWN_HANDLE"
+ assert lifecycle.wait(handle).diagnostic == "UNKNOWN_HANDLE"
+ assert lifecycle.cancel(handle, reason="test").unknown_handle
+ assert lifecycle.result(handle).error_classification == "UNKNOWN_HANDLE"
+ assert lifecycle.reconnect(handle).diagnostic == "RECONNECT_UNAVAILABLE"
+ assert lifecycle.steer(handle, "test") is False
+
+
[email protected]("launch_request, message", [
+ ({"goal": "review", "future_field": True}, "future_field"),
+ (42, "request must be a SubagentLaunchRequest"),
+])
+def test_mapping_request_errors_are_explicit(lifecycle, launch_request, message):
+ with pytest.raises(SubagentLifecycleError, match=message):
+ lifecycle.launch(launch_request)
diff --git a/tests/hermes_cli/test_plugin_host.py b/tests/hermes_cli/test_plugin_host.py
index 326379a87cb..0cda2cbd7e1 100644
--- a/tests/hermes_cli/test_plugin_host.py
+++ b/tests/hermes_cli/test_plugin_host.py
@@ -279,3 +279,65 @@ def test_hosted_memory_provider_stays_live_across_a_host_crash(tmp_path, monkeyp
assert provider.whoami() not in {first_pid, os.getpid()}
finally:
host.shutdown()
+
+
+def test_host_plugin_can_launch_status_and_steer_subagent(tmp_path, monkeypatch):
+ import threading
+ from types import SimpleNamespace
+ from agent.subagent_lifecycle import bind_subagent_parent, SubagentLifecycleService
+ from tools.delegate_tool_registry import _register_subagent, _unregister_subagent
+ from tools.registry import registry
+
+ body = '''
+import json, os
+from agent.subagent_lifecycle import SubagentLaunchRequest
+def register(ctx):
+ def run(args, **kw):
+ service = ctx.subagent_lifecycle
+ handle = service.launch(SubagentLaunchRequest(goal="review from host"))
+ return json.dumps({"pid": os.getpid(), "state": service.status(handle).state,
+ "accepted": service.steer(handle, "check correctness"), "handle": handle})
+ ctx.register_tool(name="host_lifecycle", toolset="hostlife",
+ schema={"name": "host_lifecycle", "description": "d",
+ "parameters": {"type": "object", "properties": {}}}, handler=run)
+'''
+ finish, steering = threading.Event(), []
+ child = SimpleNamespace(_subagent_id="sa-host-lifecycle", provider="test", model="test-model",
+ steer=lambda text: steering.append(text) is None)
+ parent = SimpleNamespace(session_id="parent-host-lifecycle")
+
+ def build(**kwargs):
+ assert kwargs["parent_agent"] is parent
+ assert kwargs["goal"] == "review from host"
+ _register_subagent({"subagent_id": child._subagent_id, "agent": child})
+ return child
+
+ def run(*_args):
+ assert finish.wait(5)
+ return {"status": "completed", "summary": "host child done"}
+
+ monkeypatch.setattr("tools.delegate_tool._build_child_agent", build)
+ monkeypatch.setattr("tools.delegate_tool._run_single_child", run)
+ _home_with_plugins(tmp_path, monkeypatch, {"hostlife": body})
+ manager = PluginManager()
+ manager.discover_and_load()
+ service = SubagentLifecycleService(lambda: parent)
+ result = None
+ try:
+ with bind_subagent_parent(parent):
+ result = json.loads(registry.dispatch("host_lifecycle", {}, scope=manager.scope_key))
+ assert result["pid"] != os.getpid()
+ assert result["state"] in {"PENDING", "RUNNING"}
+ assert result["accepted"] is True
+ assert steering == ["check correctness"]
+ finally:
+ finish.set()
+ from agent.subagent_lifecycle import _REGISTRY
+ record = _REGISTRY.records.get(child._subagent_id)
+ if record is not None:
+ record.future.result(timeout=5)
+ _unregister_subagent(child._subagent_id, agent=child)
+ manager.unload()
+ manager._plugin_host().shutdown()
+ assert service.result(result["handle"]).summary == "host child done"
diff --git a/website/docs/developer-guide/subagent-lifecycle-api.md b/website/docs/developer-guide/subagent-lifecycle-api.md
index 7054afcdb73..d5ce8789a52 100644
--- a/website/docs/developer-guide/subagent-lifecycle-api.md
+++ b/website/docs/developer-guide/subagent-lifecycle-api.md
@@ -10,6 +10,7 @@ Plugins can launch and supervise fresh Hermes child sessions without importing
The service resolves its parent from the current agent turn, so it works in
CLI, gateway, non-interactive, and kanban-worker sessions. Launching outside an
active agent turn fails closed with `No active Hermes parent session`.
+The facade also works when a plugin runs under `plugins.isolation: host`.
```python
from agent.subagent_lifecycle import SubagentLaunchRequest
@@ -31,9 +32,15 @@ def launch_review(ctx):
```
`SubagentHandle` is serializable and carries a versioned, opaque capability.
-Pass it back to `status`, `wait`, `cancel`, `result`, or `reconnect`; malformed
+Requests and handles may also arrive as mappings, including plugin-host wire records.
+Pass a handle back to `status`, `wait`, `cancel`, `steer`, `result`, or `reconnect`; malformed
or forged handles return `UNKNOWN`/`UNKNOWN_HANDLE` and cannot access a child.
+`steer(handle, text)` queues text for the child's next iteration boundary and
+returns `True` while the child accepts steering. It returns `False` for empty
+text, unknown or forged handles, handles owned by another parent session, or a
+child that has finished or stopped accepting steering.
+
The stable states are `PENDING`, `STARTING`, `RUNNING`, `SUCCEEDED`, `FAILED`,
`INTERRUPTED`, `CANCEL_REQUESTED`, `CANCELLED`, and `UNKNOWN`.