fix(delegation): harden steer lifecycle ownership
This commit is contained in:
parent
60e1f7517c
commit
a94ebf5f5e
|
|
@ -8,6 +8,9 @@ missed-steer retention race (a child that finishes before the drain) and
|
|||
the subagent.steer gateway RPC that fronts the helper.
|
||||
"""
|
||||
|
||||
import threading
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from tools.delegate_tool import (
|
||||
_register_subagent,
|
||||
_unregister_subagent,
|
||||
|
|
@ -28,7 +31,7 @@ class _StubAgent:
|
|||
return self.accept
|
||||
|
||||
|
||||
def _with_registered(sid: str, agent) -> None:
|
||||
def _with_registered(sid: str, agent, *, owner_session_id: str | None = None) -> None:
|
||||
_register_subagent(
|
||||
{
|
||||
"subagent_id": sid,
|
||||
|
|
@ -37,6 +40,7 @@ def _with_registered(sid: str, agent) -> None:
|
|||
"goal": "test goal",
|
||||
"status": "running",
|
||||
"agent": agent,
|
||||
"owner_session_id": owner_session_id,
|
||||
}
|
||||
)
|
||||
|
||||
|
|
@ -91,6 +95,47 @@ def test_exception_in_steer_degrades_to_false():
|
|||
_unregister_subagent("sid-steer-5")
|
||||
|
||||
|
||||
def test_stale_agent_teardown_cannot_unregister_recycled_id():
|
||||
old_agent = _StubAgent()
|
||||
replacement = _StubAgent()
|
||||
_with_registered("sid-recycled-teardown", old_agent, owner_session_id="old-owner")
|
||||
_with_registered("sid-recycled-teardown", replacement, owner_session_id="new-owner")
|
||||
try:
|
||||
_unregister_subagent("sid-recycled-teardown", agent=old_agent)
|
||||
assert (
|
||||
steer_subagent(
|
||||
"sid-recycled-teardown",
|
||||
"replacement remains live",
|
||||
owner_session_id="new-owner",
|
||||
)
|
||||
is True
|
||||
)
|
||||
assert old_agent.steered == []
|
||||
assert replacement.steered == ["replacement remains live"]
|
||||
finally:
|
||||
_unregister_subagent("sid-recycled-teardown", agent=replacement)
|
||||
|
||||
|
||||
def test_status_snapshot_never_leaks_owner_or_lifecycle_metadata():
|
||||
from tools.delegate_tool import list_active_subagents
|
||||
|
||||
agent = _StubAgent()
|
||||
_with_registered("sid-private-metadata", agent, owner_session_id="private-owner")
|
||||
try:
|
||||
snapshot = next(
|
||||
item
|
||||
for item in list_active_subagents()
|
||||
if item["subagent_id"] == "sid-private-metadata"
|
||||
)
|
||||
assert snapshot["status"] == "running"
|
||||
assert "agent" not in snapshot
|
||||
assert "owner_session_id" not in snapshot
|
||||
assert "accepting_steer" not in snapshot
|
||||
assert "private-owner" not in repr(snapshot)
|
||||
finally:
|
||||
_unregister_subagent("sid-private-metadata", agent=agent)
|
||||
|
||||
|
||||
class TestMissedSteerRetention:
|
||||
"""The final-answer race: a steer with no boundary left is NAMED, not lost."""
|
||||
|
||||
|
|
@ -162,6 +207,121 @@ class TestMissedSteerRetention:
|
|||
assert "missed_steer" not in entry
|
||||
assert "steer did not land" not in entry["summary"]
|
||||
|
||||
def test_accepted_steer_racing_completion_is_durably_retained(self):
|
||||
"""Acceptance wins the registry race, so completion must retain its text."""
|
||||
from tools.delegate_tool import _run_single_child
|
||||
|
||||
running = threading.Event()
|
||||
allow_return = threading.Event()
|
||||
steer_entered = threading.Event()
|
||||
allow_steer = threading.Event()
|
||||
pending: list[str] = []
|
||||
|
||||
child = MagicMock()
|
||||
child._subagent_id = "sid-linearized-accept"
|
||||
child._delegate_depth = 1
|
||||
child.model = "test-model"
|
||||
child.session_prompt_tokens = 0
|
||||
child.session_completion_tokens = 0
|
||||
|
||||
def run_conversation(**_kwargs):
|
||||
running.set()
|
||||
assert allow_return.wait(5)
|
||||
return {
|
||||
"final_response": "done",
|
||||
"completed": True,
|
||||
"interrupted": False,
|
||||
"api_calls": 1,
|
||||
"messages": [],
|
||||
}
|
||||
|
||||
def steer(text: str) -> bool:
|
||||
steer_entered.set()
|
||||
assert allow_steer.wait(5)
|
||||
pending.append(text)
|
||||
return True
|
||||
|
||||
def drain():
|
||||
if not pending:
|
||||
return None
|
||||
text = "\n".join(pending)
|
||||
pending.clear()
|
||||
return text
|
||||
|
||||
child.run_conversation.side_effect = run_conversation
|
||||
child.steer.side_effect = steer
|
||||
child._drain_pending_steer.side_effect = drain
|
||||
parent = MagicMock()
|
||||
|
||||
result_box: dict = {}
|
||||
runner = threading.Thread(
|
||||
target=lambda: result_box.setdefault(
|
||||
"result",
|
||||
_run_single_child(0, "race", child=child, parent_agent=parent),
|
||||
)
|
||||
)
|
||||
runner.start()
|
||||
assert running.wait(5)
|
||||
|
||||
accepted_box: dict = {}
|
||||
steering = threading.Thread(
|
||||
target=lambda: accepted_box.setdefault(
|
||||
"accepted", steer_subagent(child._subagent_id, "retain this exact text")
|
||||
)
|
||||
)
|
||||
steering.start()
|
||||
assert steer_entered.wait(5)
|
||||
allow_return.set()
|
||||
allow_steer.set()
|
||||
steering.join(5)
|
||||
runner.join(5)
|
||||
|
||||
assert not steering.is_alive()
|
||||
assert not runner.is_alive()
|
||||
assert accepted_box["accepted"] is True
|
||||
assert result_box["result"]["missed_steer"] == "retain this exact text"
|
||||
|
||||
def test_steer_after_run_return_is_rejected_before_completion_callback(self):
|
||||
"""Once the child returns, a blocked completion callback cannot extend acceptance."""
|
||||
from tools.delegate_tool import _run_single_child
|
||||
|
||||
callback_entered = threading.Event()
|
||||
release_callback = threading.Event()
|
||||
|
||||
def progress(_event: str, **_kwargs) -> None:
|
||||
return None
|
||||
|
||||
def flush() -> None:
|
||||
callback_entered.set()
|
||||
assert release_callback.wait(5)
|
||||
|
||||
progress._flush = flush # type: ignore[attr-defined]
|
||||
child = MagicMock()
|
||||
child._subagent_id = "sid-closed-before-callback"
|
||||
child._delegate_depth = 1
|
||||
child.model = "test-model"
|
||||
child.tool_progress_callback = progress
|
||||
child.run_conversation.return_value = {
|
||||
"final_response": "done",
|
||||
"completed": True,
|
||||
"interrupted": False,
|
||||
"api_calls": 1,
|
||||
"messages": [],
|
||||
}
|
||||
|
||||
runner = threading.Thread(
|
||||
target=lambda: _run_single_child(0, "late", child=child, parent_agent=MagicMock())
|
||||
)
|
||||
runner.start()
|
||||
assert callback_entered.wait(5)
|
||||
try:
|
||||
assert steer_subagent(child._subagent_id, "too late") is False
|
||||
child.steer.assert_not_called()
|
||||
finally:
|
||||
release_callback.set()
|
||||
runner.join(5)
|
||||
assert not runner.is_alive()
|
||||
|
||||
|
||||
class TestSubagentSteerRPC:
|
||||
"""subagent.steer gateway RPC — the programmatic caller beside subagent.interrupt."""
|
||||
|
|
@ -169,7 +329,16 @@ class TestSubagentSteerRPC:
|
|||
def _call(self, params: dict) -> dict:
|
||||
import tui_gateway.server as srv
|
||||
|
||||
return srv._methods["subagent.steer"](1, params)
|
||||
session_id = params.get("session_id")
|
||||
if session_id:
|
||||
srv._sessions[session_id] = {"session_key": session_id, "history": []}
|
||||
try:
|
||||
return srv.handle_request(
|
||||
{"id": 1, "method": "subagent.steer", "params": params}
|
||||
)
|
||||
finally:
|
||||
if session_id:
|
||||
srv._sessions.pop(session_id, None)
|
||||
|
||||
def test_missing_subagent_id_is_4000(self):
|
||||
envelope = self._call({"text": "hello"})
|
||||
|
|
@ -181,9 +350,15 @@ class TestSubagentSteerRPC:
|
|||
|
||||
def test_live_child_queues_and_receives_text(self):
|
||||
agent = _StubAgent()
|
||||
_with_registered("sid-rpc-2", agent)
|
||||
_with_registered("sid-rpc-2", agent, owner_session_id="owner-session")
|
||||
try:
|
||||
envelope = self._call({"subagent_id": "sid-rpc-2", "text": "check the edge cases"})
|
||||
envelope = self._call(
|
||||
{
|
||||
"session_id": "owner-session",
|
||||
"subagent_id": "sid-rpc-2",
|
||||
"text": "check the edge cases",
|
||||
}
|
||||
)
|
||||
assert envelope["result"] == {
|
||||
"status": "queued",
|
||||
"subagent_id": "sid-rpc-2",
|
||||
|
|
@ -193,6 +368,119 @@ class TestSubagentSteerRPC:
|
|||
finally:
|
||||
_unregister_subagent("sid-rpc-2")
|
||||
|
||||
def test_run_single_child_binds_owner_from_task_local_ui_session(self):
|
||||
from gateway.session_context import clear_session_vars, set_session_vars
|
||||
from tools.delegate_tool import _run_single_child
|
||||
|
||||
observed: dict[str, bool] = {}
|
||||
child = MagicMock()
|
||||
child._subagent_id = "sid-context-owner"
|
||||
child._delegate_depth = 1
|
||||
child.model = "test-model"
|
||||
child.steer.return_value = True
|
||||
|
||||
def run_conversation(**_kwargs):
|
||||
observed["owner"] = steer_subagent(
|
||||
child._subagent_id,
|
||||
"owned steer",
|
||||
owner_session_id="ui-owner",
|
||||
)
|
||||
observed["foreign"] = steer_subagent(
|
||||
child._subagent_id,
|
||||
"foreign steer",
|
||||
owner_session_id="ui-foreign",
|
||||
)
|
||||
return {
|
||||
"final_response": "done",
|
||||
"completed": True,
|
||||
"interrupted": False,
|
||||
"api_calls": 1,
|
||||
"messages": [],
|
||||
}
|
||||
|
||||
child.run_conversation.side_effect = run_conversation
|
||||
tokens = set_session_vars(
|
||||
session_key="durable-parent",
|
||||
session_id="durable-parent",
|
||||
ui_session_id="ui-owner",
|
||||
)
|
||||
try:
|
||||
_run_single_child(0, "owner binding", child=child, parent_agent=MagicMock())
|
||||
finally:
|
||||
clear_session_vars(tokens)
|
||||
|
||||
assert observed == {"owner": True, "foreign": False}
|
||||
child.steer.assert_called_once_with("owned steer")
|
||||
|
||||
def test_unknown_child_is_rejected_not_an_error(self):
|
||||
envelope = self._call({"subagent_id": "sid-rpc-gone", "text": "hello"})
|
||||
envelope = self._call(
|
||||
{
|
||||
"session_id": "owner-session",
|
||||
"subagent_id": "sid-rpc-gone",
|
||||
"text": "hello",
|
||||
}
|
||||
)
|
||||
assert envelope["result"]["status"] == "rejected"
|
||||
|
||||
def test_foreign_session_cannot_steer_an_owned_child(self):
|
||||
agent = _StubAgent()
|
||||
_with_registered("sid-rpc-foreign", agent, owner_session_id="owner-session")
|
||||
try:
|
||||
envelope = self._call(
|
||||
{
|
||||
"session_id": "foreign-session",
|
||||
"subagent_id": "sid-rpc-foreign",
|
||||
"text": "cross-session injection",
|
||||
}
|
||||
)
|
||||
assert envelope["result"]["status"] == "rejected"
|
||||
assert agent.steered == []
|
||||
finally:
|
||||
_unregister_subagent("sid-rpc-foreign")
|
||||
|
||||
def test_record_without_owner_cannot_be_steered_by_rpc(self):
|
||||
agent = _StubAgent()
|
||||
_with_registered("sid-rpc-owner-missing", agent)
|
||||
try:
|
||||
envelope = self._call(
|
||||
{
|
||||
"session_id": "claiming-session",
|
||||
"subagent_id": "sid-rpc-owner-missing",
|
||||
"text": "ambiguous authority",
|
||||
}
|
||||
)
|
||||
assert envelope["result"]["status"] == "rejected"
|
||||
assert agent.steered == []
|
||||
finally:
|
||||
_unregister_subagent("sid-rpc-owner-missing")
|
||||
|
||||
def test_rpc_without_invoking_session_identity_is_denied(self):
|
||||
agent = _StubAgent()
|
||||
_with_registered("sid-rpc-no-caller", agent, owner_session_id="owner-session")
|
||||
try:
|
||||
envelope = self._call(
|
||||
{"subagent_id": "sid-rpc-no-caller", "text": "identity missing"}
|
||||
)
|
||||
assert envelope["error"]["code"] == 4001
|
||||
assert agent.steered == []
|
||||
finally:
|
||||
_unregister_subagent("sid-rpc-no-caller")
|
||||
|
||||
def test_recycled_id_does_not_preserve_the_old_sessions_authority(self):
|
||||
old_agent = _StubAgent()
|
||||
new_agent = _StubAgent()
|
||||
_with_registered("sid-rpc-recycled", old_agent, owner_session_id="old-session")
|
||||
_with_registered("sid-rpc-recycled", new_agent, owner_session_id="new-session")
|
||||
try:
|
||||
envelope = self._call(
|
||||
{
|
||||
"session_id": "old-session",
|
||||
"subagent_id": "sid-rpc-recycled",
|
||||
"text": "stale generation steer",
|
||||
}
|
||||
)
|
||||
assert envelope["result"]["status"] == "rejected"
|
||||
assert old_agent.steered == []
|
||||
assert new_agent.steered == []
|
||||
finally:
|
||||
_unregister_subagent("sid-rpc-recycled")
|
||||
|
|
|
|||
|
|
@ -172,13 +172,40 @@ def _register_subagent(record: Dict[str, Any]) -> None:
|
|||
sid = record.get("subagent_id")
|
||||
if not sid:
|
||||
return
|
||||
record.setdefault("accepting_steer", True)
|
||||
with _active_subagents_lock:
|
||||
_active_subagents[sid] = record
|
||||
|
||||
|
||||
def _unregister_subagent(subagent_id: str) -> None:
|
||||
def _unregister_subagent(subagent_id: str, *, agent: Any = None) -> None:
|
||||
with _active_subagents_lock:
|
||||
_active_subagents.pop(subagent_id, None)
|
||||
record = _active_subagents.get(subagent_id)
|
||||
if record is not None and (agent is None or record.get("agent") is agent):
|
||||
_active_subagents.pop(subagent_id, None)
|
||||
|
||||
|
||||
def _close_subagent_steering(subagent_id: str, agent: Any) -> Optional[str]:
|
||||
"""Atomically close steer acceptance and drain its final durable artifact.
|
||||
|
||||
``steer_subagent`` holds the same registry lock through ``agent.steer``.
|
||||
Therefore either acceptance wins and this drain sees its exact text, or
|
||||
closure wins and the caller is rejected. Exact agent identity prevents a
|
||||
finishing child with a recycled public id from closing its replacement.
|
||||
"""
|
||||
with _active_subagents_lock:
|
||||
record = _active_subagents.get(subagent_id)
|
||||
if record is None or record.get("agent") is not agent:
|
||||
return None
|
||||
record["accepting_steer"] = False
|
||||
drain = getattr(agent, "_drain_pending_steer", None)
|
||||
if not callable(drain):
|
||||
return None
|
||||
try:
|
||||
pending = drain()
|
||||
except Exception as exc:
|
||||
logger.debug("final steer drain for %s failed: %s", subagent_id, exc)
|
||||
return None
|
||||
return pending if isinstance(pending, str) and pending.strip() else None
|
||||
|
||||
|
||||
def interrupt_subagent(subagent_id: str) -> bool:
|
||||
|
|
@ -205,36 +232,43 @@ def interrupt_subagent(subagent_id: str) -> bool:
|
|||
return True
|
||||
|
||||
|
||||
def steer_subagent(subagent_id: str, text: str) -> bool:
|
||||
def steer_subagent(
|
||||
subagent_id: str,
|
||||
text: str,
|
||||
*,
|
||||
owner_session_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""Queue steering text into a single running subagent without stopping it.
|
||||
|
||||
The redirection-side mirror of interrupt_subagent(): resolves the live
|
||||
child in the registry and calls AIAgent.steer(), which appends the text
|
||||
to the child's last tool result at its next iteration boundary — the
|
||||
current tool call is never cut. Returns True if a matching subagent
|
||||
QUEUED the text; False for an unknown id, a record with no live agent,
|
||||
or empty text.
|
||||
QUEUED the text while the child was still accepting work; False for an
|
||||
unknown/closed id, an ownership mismatch, a record with no live agent, or
|
||||
empty text. ``owner_session_id=None`` deliberately preserves the internal
|
||||
in-process helper contract; gateway callers must pass exact authority.
|
||||
|
||||
Queued is not delivered: a child already past its final tool batch has
|
||||
no boundary left to drain into. That race is surfaced, not swallowed —
|
||||
the finalizer returns the undelivered text as ``pending_steer`` and
|
||||
``_run_single_child`` retains it in the completion entry as
|
||||
``missed_steer`` with a note appended to the summary.
|
||||
Acceptance and completion are linearized by the registry lock. If
|
||||
acceptance wins but no delivery boundary remains, ``_run_single_child``
|
||||
drains the exact text into the completion entry as ``missed_steer``.
|
||||
"""
|
||||
if not text or not text.strip():
|
||||
return False
|
||||
with _active_subagents_lock:
|
||||
record = _active_subagents.get(subagent_id)
|
||||
if not record:
|
||||
return False
|
||||
agent = record.get("agent")
|
||||
if agent is None:
|
||||
return False
|
||||
try:
|
||||
return bool(agent.steer(text))
|
||||
except Exception as exc:
|
||||
logger.debug("steer_subagent(%s) failed: %s", subagent_id, exc)
|
||||
return False
|
||||
if not record or not record.get("accepting_steer", False):
|
||||
return False
|
||||
if owner_session_id is not None and record.get("owner_session_id") != owner_session_id:
|
||||
return False
|
||||
agent = record.get("agent")
|
||||
if agent is None:
|
||||
return False
|
||||
try:
|
||||
return bool(agent.steer(text))
|
||||
except Exception as exc:
|
||||
logger.debug("steer_subagent(%s) failed: %s", subagent_id, exc)
|
||||
return False
|
||||
|
||||
|
||||
def list_active_subagents() -> List[Dict[str, Any]]:
|
||||
|
|
@ -245,7 +279,11 @@ def list_active_subagents() -> List[Dict[str, Any]]:
|
|||
"""
|
||||
with _active_subagents_lock:
|
||||
return [
|
||||
{k: v for k, v in r.items() if k != "agent"}
|
||||
{
|
||||
k: v
|
||||
for k, v in r.items()
|
||||
if k not in {"agent", "owner_session_id", "accepting_steer"}
|
||||
}
|
||||
for r in _active_subagents.values()
|
||||
]
|
||||
|
||||
|
|
@ -2005,6 +2043,8 @@ def _run_single_child(
|
|||
goal: str,
|
||||
child=None,
|
||||
parent_agent=None,
|
||||
*,
|
||||
owner_session_id: Optional[str] = None,
|
||||
**_kwargs,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
|
|
@ -2139,6 +2179,13 @@ def _run_single_child(
|
|||
_raw_sid = getattr(child, "_subagent_id", None)
|
||||
_subagent_id = _raw_sid if isinstance(_raw_sid, str) else None
|
||||
if _subagent_id:
|
||||
if owner_session_id is None:
|
||||
try:
|
||||
from gateway.session_context import get_session_env
|
||||
|
||||
owner_session_id = get_session_env("HERMES_UI_SESSION_ID", "") or None
|
||||
except Exception:
|
||||
owner_session_id = None
|
||||
_raw_depth = getattr(child, "_delegate_depth", 1)
|
||||
_tui_depth = max(0, _raw_depth - 1) if isinstance(_raw_depth, int) else 0
|
||||
_parent_sid = getattr(child, "_parent_subagent_id", None)
|
||||
|
|
@ -2157,6 +2204,9 @@ def _run_single_child(
|
|||
"status": "running",
|
||||
"tool_count": 0,
|
||||
"agent": child,
|
||||
# Immutable live gateway/TUI session that commissioned this
|
||||
# child. Empty outside those hosts; RPC authority fails closed.
|
||||
"owner_session_id": owner_session_id,
|
||||
}
|
||||
)
|
||||
|
||||
|
|
@ -2244,6 +2294,12 @@ def _run_single_child(
|
|||
try:
|
||||
result = _child_future.result(timeout=child_timeout)
|
||||
except Exception as _timeout_exc:
|
||||
# No consumer boundary remains once this owner stops waiting for
|
||||
# the child. Close acceptance before any completion callback and
|
||||
# retain steer text that won the race with this failure/timeout.
|
||||
_late_pending_steer = (
|
||||
_close_subagent_steering(_subagent_id, child) if _subagent_id else None
|
||||
)
|
||||
# Signal the child to stop so its thread can exit cleanly.
|
||||
try:
|
||||
interrupted = child is not None and request_hard_interrupt(child)
|
||||
|
|
@ -2327,7 +2383,7 @@ def _run_single_child(
|
|||
else:
|
||||
_err = str(_timeout_exc)
|
||||
|
||||
return {
|
||||
_error_entry = {
|
||||
"task_index": task_index,
|
||||
"status": "timeout" if is_timeout else "error",
|
||||
"summary": None,
|
||||
|
|
@ -2345,11 +2401,33 @@ def _run_single_child(
|
|||
"_child_role": getattr(child, "_delegate_role", None),
|
||||
"diagnostic_path": diagnostic_path,
|
||||
}
|
||||
if _late_pending_steer:
|
||||
_error_entry["missed_steer"] = _late_pending_steer
|
||||
_error_entry["error"] += (
|
||||
" [steer did not land before the subagent stopped: "
|
||||
f"{_late_pending_steer}]"
|
||||
)
|
||||
return _error_entry
|
||||
finally:
|
||||
# Shut down executor without waiting — if the child thread
|
||||
# is stuck on blocking I/O, wait=True would hang forever.
|
||||
_timeout_executor.shutdown(wait=False)
|
||||
|
||||
# Linearization boundary for registry steering. From this point on the
|
||||
# child cannot consume another steer. Closing under the registry lock
|
||||
# either rejects a concurrent caller or drains every previously accepted
|
||||
# exact text into the result before callbacks/result assembly can run.
|
||||
_late_pending_steer = (
|
||||
_close_subagent_steering(_subagent_id, child) if _subagent_id else None
|
||||
)
|
||||
if _late_pending_steer:
|
||||
_existing_pending = result.get("pending_steer")
|
||||
result["pending_steer"] = (
|
||||
f"{_existing_pending}\n{_late_pending_steer}"
|
||||
if isinstance(_existing_pending, str) and _existing_pending
|
||||
else _late_pending_steer
|
||||
)
|
||||
|
||||
# Flush any remaining batched progress to gateway
|
||||
if child_progress_cb and hasattr(child_progress_cb, "_flush"):
|
||||
try:
|
||||
|
|
@ -2582,6 +2660,9 @@ def _run_single_child(
|
|||
return entry
|
||||
|
||||
except Exception as exc:
|
||||
_late_pending_steer = (
|
||||
_close_subagent_steering(_subagent_id, child) if _subagent_id else None
|
||||
)
|
||||
duration = round(time.monotonic() - child_start, 2)
|
||||
logging.exception(f"[subagent-{task_index}] failed")
|
||||
if child_progress_cb:
|
||||
|
|
@ -2595,7 +2676,7 @@ def _run_single_child(
|
|||
)
|
||||
except Exception as e:
|
||||
logger.debug("Progress callback failure relay failed: %s", e)
|
||||
return {
|
||||
_error_entry = {
|
||||
"task_index": task_index,
|
||||
"status": "error",
|
||||
"summary": None,
|
||||
|
|
@ -2604,6 +2685,13 @@ def _run_single_child(
|
|||
"duration_seconds": duration,
|
||||
"_child_role": getattr(child, "_delegate_role", None),
|
||||
}
|
||||
if _late_pending_steer:
|
||||
_error_entry["missed_steer"] = _late_pending_steer
|
||||
_error_entry["error"] += (
|
||||
" [steer did not land before the subagent stopped: "
|
||||
f"{_late_pending_steer}]"
|
||||
)
|
||||
return _error_entry
|
||||
|
||||
finally:
|
||||
# Stop the heartbeat thread so it doesn't keep touching parent activity
|
||||
|
|
@ -2618,7 +2706,7 @@ def _run_single_child(
|
|||
# Drop the TUI-facing registry entry. Safe to call even if the
|
||||
# child was never registered (e.g. ID missing on test doubles).
|
||||
if _subagent_id:
|
||||
_unregister_subagent(_subagent_id)
|
||||
_unregister_subagent(_subagent_id, agent=child)
|
||||
|
||||
if child_pool is not None and leased_cred_id is not None:
|
||||
try:
|
||||
|
|
@ -2996,6 +3084,12 @@ def delegate_task(
|
|||
from tools.async_delegation import _current_origin_session_id
|
||||
|
||||
_origin_wake_sid = _current_origin_session_id()
|
||||
try:
|
||||
from gateway.session_context import get_session_env
|
||||
|
||||
_origin_ui_session_id = get_session_env("HERMES_UI_SESSION_ID", "")
|
||||
except Exception:
|
||||
_origin_ui_session_id = ""
|
||||
|
||||
# Build all child agents on the main thread (thread-safe construction).
|
||||
# _build_child_preserving_parent_tools saves/restores the parent's
|
||||
|
|
@ -3054,7 +3148,13 @@ def delegate_task(
|
|||
if n_tasks == 1:
|
||||
# Single task -- run directly (no thread pool overhead)
|
||||
_i, _t, child = children[0]
|
||||
result = _run_single_child(_i, _t["goal"], child, parent_agent)
|
||||
result = _run_single_child(
|
||||
_i,
|
||||
_t["goal"],
|
||||
child,
|
||||
parent_agent,
|
||||
owner_session_id=_origin_ui_session_id or None,
|
||||
)
|
||||
results.append(result)
|
||||
else:
|
||||
# Batch -- run in parallel with per-task progress lines
|
||||
|
|
@ -3076,6 +3176,7 @@ def delegate_task(
|
|||
goal=t["goal"],
|
||||
child=child,
|
||||
parent_agent=parent_agent,
|
||||
owner_session_id=_origin_ui_session_id or None,
|
||||
)
|
||||
futures[future] = i
|
||||
|
||||
|
|
@ -3283,12 +3384,15 @@ def delegate_task(
|
|||
return json.dumps(_sync_result, ensure_ascii=False)
|
||||
|
||||
_session_key = get_current_session_key(default="")
|
||||
_origin_ui_session_id = ""
|
||||
try:
|
||||
from gateway.session_context import get_session_env
|
||||
|
||||
_source = get_session_env("HERMES_SESSION_SOURCE", "")
|
||||
_origin_ui_session_id = get_session_env("HERMES_UI_SESSION_ID", "")
|
||||
# Refresh from the same task-local source when available, but retain
|
||||
# the immutable value captured before child construction otherwise.
|
||||
_origin_ui_session_id = (
|
||||
get_session_env("HERMES_UI_SESSION_ID", "") or _origin_ui_session_id
|
||||
)
|
||||
# In desktop/TUI, the routable session key is the durable
|
||||
# AIAgent.session_id. Context compression can rotate that id during
|
||||
# the same turn before the TUI-side session dict is re-anchored;
|
||||
|
|
@ -3301,7 +3405,7 @@ def delegate_task(
|
|||
if _agent_session_id:
|
||||
_session_key = _agent_session_id
|
||||
except Exception:
|
||||
_origin_ui_session_id = ""
|
||||
_source = ""
|
||||
if not _session_key:
|
||||
# CLI (single-process) path: the approval contextvar is only bound
|
||||
# during gateway/TUI turns and HERMES_SESSION_KEY is not in the CLI
|
||||
|
|
|
|||
|
|
@ -2954,7 +2954,15 @@ def _(rid, params: dict) -> dict:
|
|||
text = (params.get("text") or "").strip()
|
||||
if not text:
|
||||
return _err(rid, 4002, "text is required")
|
||||
queued = steer_subagent(subagent_id, text)
|
||||
_session, err = _sess_nowait(params, rid)
|
||||
if err:
|
||||
return err
|
||||
invoking_session_id = str(params.get("session_id") or "").strip()
|
||||
queued = steer_subagent(
|
||||
subagent_id,
|
||||
text,
|
||||
owner_session_id=invoking_session_id,
|
||||
)
|
||||
return _ok(
|
||||
rid,
|
||||
{
|
||||
|
|
|
|||
|
|
@ -271,15 +271,15 @@ glance.
|
|||
|
||||
## Steering a Running Subagent
|
||||
|
||||
Interrupting a child throws away its in-flight work; often you just want to redirect it. `steer_subagent(subagent_id, text)` in `tools/delegate_tool.py` is the redirection-side mirror of `interrupt_subagent()`: it queues text into a live child through the same mechanism as [`/steer`](/reference/slash-commands) — the text is appended to the child's last tool result at its next iteration boundary, the in-flight tool call is never cut, and the child sees it as an out-of-band user message. Programmatic hosts reach it through the `subagent.steer` gateway RPC, which sits beside `subagent.interrupt`:
|
||||
Interrupting a child throws away its in-flight work; often you just want to redirect it. `steer_subagent(subagent_id, text)` in `tools/delegate_tool.py` is the redirection-side mirror of `interrupt_subagent()`: it queues text into a live child through the same mechanism as [`/steer`](/reference/slash-commands) — the text is appended to the child's last tool result at its next iteration boundary, the in-flight tool call is never cut, and the child sees it as an out-of-band user message. Programmatic hosts reach it through the session-scoped `subagent.steer` gateway RPC, which sits beside `subagent.interrupt`:
|
||||
|
||||
```json
|
||||
{"method": "subagent.steer", "params": {"subagent_id": "sa-0-1a2b3c4d", "text": "focus on pricing instead"}}
|
||||
{"method": "subagent.steer", "params": {"session_id": "owning-ui-session", "subagent_id": "sa-0-1a2b3c4d", "text": "focus on pricing instead"}}
|
||||
```
|
||||
|
||||
Subagent ids come from `delegation.status` (or `list_active_subagents()`) — the same place `subagent.interrupt` gets them.
|
||||
Subagent ids come from `delegation.status` (or `list_active_subagents()`) — the same place `subagent.interrupt` gets them. The gateway accepts steering only from the exact live UI/gateway session that spawned the child. A missing, foreign, ambiguous, or stale/recycled session identity is rejected; knowing a global subagent id is not authority. Direct in-process callers retain the unscoped helper contract deliberately.
|
||||
|
||||
**Queued is not delivered.** A `"queued"` response means the text is staged, not that the child has seen it. A child that has already produced its final answer has no tool batch left to drain the steer into. That race is surfaced instead of swallowed: the turn finalizer hands the undelivered text back as `pending_steer`, and the completion entry the parent receives retains it as `missed_steer`, with a note appended to the summary:
|
||||
**Queued is not delivered, but it is never synthetic success.** A `"queued"` response means the text was accepted before the child's completion boundary, not necessarily that the child has seen it. Acceptance and completion are synchronized: either the child can still consume the text, or its exact text is drained into the result as `pending_steer`. Calls after closure return `"rejected"`. If a child accepted the steer but had already produced its final answer, the completion entry the parent receives retains it as `missed_steer`, with a note appended to the summary:
|
||||
|
||||
```
|
||||
[steer did not land — the subagent finished before it could be delivered: focus on pricing instead]
|
||||
|
|
|
|||
Loading…
Reference in New Issue