Skip to content

The agent that grows with you

feat: expose session-scoped subagent roster and live tail RPCs

Teknium8b01df963d2e
diff --git a/tests/tui_gateway/test_subagent_snapshot.py b/tests/tui_gateway/test_subagent_snapshot.py
new file mode 100644
index 00000000000..feaf235ccb7
--- /dev/null
+++ b/tests/tui_gateway/test_subagent_snapshot.py
@@ -0,0 +1,111 @@
+"""Shared RPC contracts exercised against real registries and transcript I/O."""
+
+import json
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+
+def runtime(monkeypatch):
+ from tui_gateway import server
+ from tools import async_delegation, delegate_tool_registry
+
+ transport = SimpleNamespace(write=lambda frame: True)
+ owner = {"session_key": "parent", "history": [], "transport": transport}
+ monkeypatch.setattr(server, "_sessions", {"ui-owner": owner})
+ monkeypatch.setattr(delegate_tool_registry, "_active_subagents", {})
+ monkeypatch.setattr(delegate_tool_registry, "_recent_subagents", {})
+ monkeypatch.setattr(async_delegation, "_records", {})
+
+ def call(method, *, via=transport, **params):
+ return server.dispatch({"id": 1, "method": method,
+ "params": {"session_id": "ui-owner", **params}}, transport=via)
+
+ return server, owner, transport, call
+
+
+def test_snapshot_projects_only_this_sessions_runtime_records(runtime):
+ from tools import async_delegation as bg
+ from tools.delegate_tool_child_run import _register_child
+ from tools.delegate_tool_registry import _unregister_subagent
+
+ server, owner, transport, call = runtime
+ release = threading.Event()
+ finished = threading.Event()
+
+ def run():
+ try:
+ assert release.wait(10)
+ return {"results": []}
+ finally:
+ finished.set()
+
+ dispatch = bg.dispatch_async_delegation_batch(
+ goals=["owned task"], context="private handoff", toolsets=None, role="leaf", model="test",
+ session_key="parent", origin_ui_session_id="ui-owner", runner=run)
+ did = dispatch["delegation_id"]
+ child = SimpleNamespace(_subagent_id="child", _delegate_depth=1, _delegation_id=did, model="test")
+ _register_child(child, None, "owned task", owner_session_id="ui-owner",
+ owner_transport=transport, owner_session_record=owner)
+ foreign = SimpleNamespace(_subagent_id="foreign", _delegate_depth=1, model="test")
+ _register_child(foreign, None, "foreign secret", owner_session_id="other",
+ owner_transport=transport, owner_session_record={})
+ try:
+ snapshot = call("subagent.list")["result"]
+ assert [s["subagent_id"] for s in snapshot["subagents"]] == ["child"]
+ assert snapshot["delegations"][0]["delegation_id"] == did
+ assert snapshot["delegations"][0]["subagent_ids"] == ["child"]
+ wire = json.dumps(snapshot)
+ assert "private handoff" not in wire and "foreign secret" not in wire
+ assert "owner_transport" not in wire and "session_key" not in wire
+ assert "error" in call("subagent.list", via=SimpleNamespace(write=lambda frame: True))
+ assert "error" in call("subagent.list", session_id="missing")
+ server._sessions["ui-owner"] = {**owner}
+ assert call("subagent.list")["result"]["subagents"] == []
+ finally:
+ _unregister_subagent("child")
+ _unregister_subagent("foreign")
+ release.set()
+ assert finished.wait(10)
+
+
+def test_live_tail_and_steer_share_exact_owner_and_end_with_child(runtime):
+ from run_agent import AIAgent
+ from tools.delegate_tool_child_run import _register_child
+ from tools.delegate_tool_registry import _close_subagent_steering, _unregister_subagent
+ from tools.delegation_live_log import LiveTranscriptWriter
+
+ server, owner, transport, call = runtime
+ child = object.__new__(AIAgent)
+ child._subagent_id = "child"
+ child._delegate_depth = 1
+ child.model = "test"
+ child._pending_steer = None
+ child._pending_steer_lock = threading.Lock()
+ writer = LiveTranscriptWriter("deleg-rpc", 0, "owned task")
+ child._live_transcript_path = str(writer.path)
+ _register_child(child, None, "owned task", owner_session_id="ui-owner",
+ owner_transport=transport, owner_session_record=owner)
+ try:
+ writer.event("tool", "x" * 20000)
+ writer.tool_result("read_file", "first result")
+ tail = call("subagent.tail", subagent_id="child")["result"]
+ assert tail["available"] and tail["truncated"] and len(tail["text"].encode()) <= 16384
+ assert "first result" in tail["text"]
+ writer.tool_result("read_file", "new live output")
+ assert "new live output" in call("subagent.tail", subagent_id="child")["result"]["text"]
+ queued = call("subagent.steer", subagent_id="child", text="change course")["result"]
+ assert queued["status"] == "queued" and "delivered" not in queued
+ assert _close_subagent_steering("child", child) == "change course"
+ assert call("subagent.steer", subagent_id="child", text="too late")["result"]["status"] == "rejected"
+ assert "error" in call("subagent.tail", subagent_id="child", via=SimpleNamespace(write=lambda frame: True))
+ server._sessions["ui-owner"] = {**owner}
+ assert not call("subagent.tail", subagent_id="child")["result"]["available"]
+ server._sessions["ui-owner"] = owner
+ _unregister_subagent("child")
+ assert call("subagent.tail", subagent_id="child")["result"] == {
+ "subagent_id": "child", "available": False, "text": "", "truncated": False}
+ finally:
+ _unregister_subagent("child")
diff --git a/tui_gateway/AGENTS.md b/tui_gateway/AGENTS.md
index fe62d4df5e5..fda09b48d76 100644
--- a/tui_gateway/AGENTS.md
+++ b/tui_gateway/AGENTS.md
@@ -39,6 +39,24 @@ existing topical sibling, registered in the table — no `if method == ...` chai
| Theming | `theme.ts` + `branding.tsx` | `gateway.ready` carries skin data |
| Plugin compat notice | — | `plugins.compat_report` (see `plugins/AGENTS.md`) |
+## Shared subagent snapshots
+
+`subagent.list({session_id})` returns `{subagents, delegations}` for the calling
+transport's live session. Live child records are pinned to the exact session
+record and transport; background records use their captured `origin_ui_session_id`
+so compression does not hide ongoing work. Both lists are allowlisted projections:
+no dispatch context, results, callbacks, or routing keys are sent. Clients hydrate
+from this snapshot on their existing poll and avoid updates when unchanged.
+
+`subagent.tail({session_id, subagent_id})` returns
+`{subagent_id, available, text, truncated}`: the last 16 KiB of the live child's
+existing transcript. Poll only the selected detail. Missing/finished/foreign
+children return an unavailable empty snapshot; no client-supplied path is opened.
+This is live-only, not persisted completion history. Invalid session/transport
+returns error 4001. `subagent.steer({session_id, subagent_id, text})` remains the
+shared control: `status: queued` acknowledges acceptance, not delivery; final
+boundary races are reported by the existing runtime as `missed_steer`.
+
## Slash command flow
1. Built-in client commands (`/help`, `/quit`, `/clear`, `/resume`, `/copy`, `/paste`, ...) are
diff --git a/tui_gateway/methods_subagents.py b/tui_gateway/methods_subagents.py
new file mode 100644
index 00000000000..53547df19e4
--- /dev/null
+++ b/tui_gateway/methods_subagents.py
@@ -0,0 +1,84 @@
+"""Session-scoped roster and bounded live transcript snapshots for shared clients.
+
+Async projection adapted from JoaoMarcos44's PR #70899; controls reuse the
+existing subagent.steer RPC rather than introducing a second steering runtime.
+"""
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+method = _registry.method
+
+_SUBAGENT_SNAPSHOT_FIELDS = (
+ "subagent_id", "parent_id", "depth", "goal", "delegation_id", "model",
+ "started_at", "status", "tool_count", "current_tool", "accepting_steer",
+)
+_ASYNC_SNAPSHOT_FIELDS = (
+ "delegation_id", "goal", "role", "model", "status", "dispatched_at", "completed_at", "is_batch",
+)
+_SUBAGENT_TAIL_BYTES = 16384
+
+
+def _owned_subagent_records(session_id, transport, owner):
+ from tools.delegate_tool_registry import _active_subagents, _active_subagents_lock
+
+ with _active_subagents_lock:
+ return [dict(r) for r in _active_subagents.values()
+ if r.get("owner_session_id") == session_id
+ and r.get("owner_transport") is transport
+ and r.get("owner_session_record") is owner]
+
+
+@method("subagent.list")
+def _(rid, params):
+ session_id = _str_param(params, "session_id")
+ transport, owner = _current_session_steer_authority(session_id)
+ if transport is None or owner is None:
+ return _err(rid, 4001, "session not found or not owned by this transport")
+ from tools.async_delegation import _records, _records_lock
+
+ live = _owned_subagent_records(session_id, transport, owner)
+ # Read only projected fields, without invoking unrelated sessions' progress callbacks.
+ with _records_lock:
+ delegations = []
+ for record in _records.values():
+ if record.get("origin_ui_session_id") != session_id:
+ continue
+ item = {key: record.get(key) for key in _ASYNC_SNAPSHOT_FIELDS}
+ item["subagent_ids"] = [r["subagent_id"] for r in live
+ if r.get("delegation_id") == record.get("delegation_id")]
+ delegations.append(item)
+ return _ok(rid, {
+ "subagents": [{key: r.get(key) for key in _SUBAGENT_SNAPSHOT_FIELDS} for r in live],
+ "delegations": delegations,
+ })
+
+
+@method("subagent.tail")
+def _(rid, params):
+ session_id = _str_param(params, "session_id")
+ subagent_id = _str_param(params, "subagent_id")
+ if not subagent_id:
+ return _err(rid, 4000, "subagent_id required")
+ transport, owner = _current_session_steer_authority(session_id)
+ if transport is None or owner is None:
+ return _err(rid, 4001, "session not found or not owned by this transport")
+ result = {"subagent_id": subagent_id, "available": False, "text": "", "truncated": False}
+ record = next((r for r in _owned_subagent_records(session_id, transport, owner)
+ if r.get("subagent_id") == subagent_id), None)
+ path = getattr(record.get("agent"), "_live_transcript_path", None) if record else None
+ if not path:
+ return _ok(rid, result)
+ try:
+ with open(path, "rb") as stream:
+ size = stream.seek(0, 2)
+ stream.seek(max(0, size - _SUBAGENT_TAIL_BYTES))
+ text = stream.read(_SUBAGENT_TAIL_BYTES).decode("utf-8", errors="ignore")
+ except OSError:
+ # Creation/cleanup races are normal while a child starts or ends.
+ return _ok(rid, result)
+ return _ok(rid, {**result, "available": True, "text": text, "truncated": size > _SUBAGENT_TAIL_BYTES})
+
+
+def register(server):
+ bind_module(globals(), server)
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index d5c89e1cd2b..9973dde208c 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -3200,7 +3200,7 @@ from . import ( # noqa: E402
methods_profiles as _methods_profiles, methods_prompt as _methods_prompt, methods_session as _methods_session,
methods_tools as _methods_tools, prompt_turn as _prompt_turn, billing_view as _billing_view,
methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign,
- methods_session_control as _methods_session_control)
+ methods_session_control as _methods_session_control, methods_subagents as _methods_subagents)
for _m in (
_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
@@ -3210,6 +3210,6 @@ for _m in (
_methods_browser_control, _methods_session, _methods_prompt, _methods_config,
_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,
_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,
- _methods_session_control):
+ _methods_session_control, _methods_subagents):
_m.register(sys.modules[__name__])
del _m