Skip to content

The agent that grows with you

fix(gateway): managed-session viewers see tool arguments, output and failures

Tekniumb9fd57091462
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index bb3eb0ae58d..73a2064e467 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -223,6 +223,17 @@ def retire_agent(agent):
agent.release_clients()
+def tool_frame(call_id, name, args, *result):
+ """The callback arguments an in-process turn publishes from (executor-redacted display args,
+ the result and its failure verdict); the owner builds the shared tool event from them."""
+ frame = {'tool_call_id': str(call_id or ''), 'name': str(name or 'tool'), 'args': args if isinstance(args, dict) else {}}
+ if result:
+ from agent.display import _detect_tool_failure
+ frame['result'] = result[0] if isinstance(result[0], str) else str(result[0])
+ frame['is_error'] = bool(_detect_tool_failure(frame['name'], result[0])[0])
+ return json.loads(json.dumps(frame, default=str))
+
+
def execute(frame, channel):
# The owner RPC below imports gateway/config modules (hermes_cli.config, providers,
# hermes_cli.plugins) transitively; the policy must already be frozen when they load.
@@ -263,8 +274,9 @@ def execute(frame, channel):
skip_memory=policy.ignore_rules, skip_background_review=True, quiet_mode=True,
stream_delta_callback=lambda text: channel.send('delta', text=text) if text else None,
clarify_callback=controls.clarify,
- tool_start_callback=lambda call_id, name, args: channel.send('tool.start', tool_call_id=call_id, name=name),
- tool_complete_callback=lambda call_id, name, args, result: channel.send('tool.complete', tool_call_id=call_id, name=name))
+ tool_start_callback=lambda call_id, name, args: channel.send('tool.start', **tool_frame(call_id, name, args)),
+ tool_complete_callback=lambda call_id, name, args, result: channel.send('tool.complete',
+ **tool_frame(call_id, name, args, result)))
controls.agent = agent
if controls.stopped.is_set():
agent.interrupt()
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.py
index 18cf0f97e94..86f3be94994 100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@ -44,6 +44,39 @@ def _tool_lifecycle_payload(call_id, tool_name, args) -> dict:
return payload
+def _tool_complete_payload(call_id, tool_name, args, result, *, is_error, verbose) -> dict:
+ """``tool.complete`` as every viewer reads it: the start contract plus the executor's verdict and
+ the result (ACP renders paths/output and failure from it), and ``result_text`` under /verbose."""
+ payload = {**_tool_lifecycle_payload(call_id, tool_name, args), "is_error": bool(is_error),
+ "result": result if isinstance(result, str) else str(result)}
+ if verbose:
+ from tui_gateway.tool_progress import _tool_result_text
+ payload["result_text"] = _tool_result_text(result)
+ return payload
+
+
+def publish_worker_tool_event(authority, session_id, generation, frame) -> bool:
+ """A managed worker's tool frame, published exactly as an in-process turn publishes its own
+ (the shared viewer stream and this admission's API observers). False for any other frame."""
+ kind = frame.get("type")
+ fields = {"type", "tool_call_id", "name", "args"} | ({"result", "is_error"} if kind == "tool.complete" else set())
+ if (kind not in ("tool.start", "tool.complete") or set(frame) != fields
+ or not isinstance(frame["tool_call_id"], str) or not isinstance(frame["name"], str)
+ or not isinstance(frame["args"], dict)
+ or (kind == "tool.complete" and (not isinstance(frame["result"], str) or type(frame["is_error"]) is not bool))):
+ return False
+ call_id, name, args, result = frame["tool_call_id"], frame["name"], frame["args"], frame.get("result")
+ if kind == "tool.start":
+ payload = _tool_lifecycle_payload(call_id, name, args)
+ else:
+ verbose = getattr(authority.sessions[session_id], "tool_progress_mode", None) == "verbose"
+ payload = _tool_complete_payload(call_id, name, args, result, is_error=frame["is_error"], verbose=verbose)
+ authority.publish_execution(session_id, generation, kind, payload)
+ from gateway.session_api_turn import publish_api_tool_event
+ publish_api_tool_event(authority, session_id, generation, kind, call_id, name, args, result)
+ return True
+
+
class GatewayTurnProgressMixin:
# ── shared thread→loop plumbing ─────────────────────────────────────────────────────────
@@ -793,14 +826,11 @@ class GatewayTurnProgressMixin:
def combined_tool_complete_callback(self, call_id, tool_name, args, result):
from agent.display import _detect_tool_failure
is_error, _ = _detect_tool_failure(tool_name, result)
- payload = {**_tool_lifecycle_payload(call_id, tool_name, args), "is_error": bool(is_error),
- "result": result if isinstance(result, str) else str(result)}
owner = self._approval_owner
live = owner[0].sessions.get(owner[1]) if owner is not None else None
# A session's /verbose (gateway/session_busy_controls.py) ships the Result block text.
- if live is not None and (getattr(live, "tool_progress_mode", None) or self._ctx.progress_mode) == "verbose":
- from tui_gateway.tool_progress import _tool_result_text
- payload["result_text"] = _tool_result_text(result)
+ verbose = live is not None and (getattr(live, "tool_progress_mode", None) or self._ctx.progress_mode) == "verbose"
+ payload = _tool_complete_payload(call_id, tool_name, args, result, is_error=is_error, verbose=verbose)
self._publish_execution("tool.complete", payload)
self._publish_api_tool("tool.complete", call_id, tool_name, args, result)
if self._ctx._native_slack_task_cards:
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 9c6343c0e2a..11221500752 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -278,6 +278,7 @@ def _worker_env(authority):
async def execute_managed(authority, ref, row, policy):
+ from gateway.run_turn_progress import publish_worker_tool_event
env = await asyncio.to_thread(_worker_env, authority)
cwd = (await asyncio.to_thread(Path(__file__).resolve)).parents[1]
process = await asyncio.to_thread(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],
@@ -321,10 +322,7 @@ async def execute_managed(authority, ref, row, policy):
if kind == 'delta' and set(frame) == {'type', 'text'} and isinstance(frame['text'], str):
authority.publish_execution(ref.session_id, row['generation'], 'message.delta', {'text': frame['text']})
continue
- if (kind in {'tool.start', 'tool.complete'} and set(frame) == {'type', 'tool_call_id', 'name'}
- and isinstance(frame['tool_call_id'], str) and isinstance(frame['name'], str)):
- authority.publish_execution(ref.session_id, row['generation'], kind,
- {'tool_call_id': frame['tool_call_id'], 'name': frame['name']})
+ if publish_worker_tool_event(authority, ref.session_id, row['generation'], frame):
continue
if kind == 'result' and set(frame) == {'type', 'result'} and accepted is None:
result = frame['result']
diff --git a/tests/gateway/test_managed_worker_launch.py b/tests/gateway/test_managed_worker_launch.py
index 482bcac642d..e70b3ded532 100644
--- a/tests/gateway/test_managed_worker_launch.py
+++ b/tests/gateway/test_managed_worker_launch.py
@@ -221,7 +221,14 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_path
replay_epoch=restored['result']['replay_epoch'], last_sequence=0)
tools = [e for e in replay['result']['events'] if e['type'] in {'tool.start', 'tool.complete'}]
assert tools and tools[0]['type'] == 'tool.start' and tools[-1]['type'] == 'tool.complete', replay
- assert str(target) not in json.dumps(tools) and 'MANAGED_TOOL_EFFECT' not in json.dumps(tools), tools
+ # The ordinary turn's payload (Ink: tool_id/context; ACP: args/result/is_error); the same
+ # viewer already reads these rows through session.resume, so the stream withholds nothing.
+ start = tools[0]['payload']
+ done = next(e['payload'] for e in tools if e['type'] == 'tool.complete' and e['payload']['tool_id'] == 'managed-tool')
+ assert start['tool_id'] == 'managed-tool' and start['context'], tools
+ assert start['args']['command'] == peer.command and done['is_error'] is False, tools
+ if not peer.control_mode and worker_action != 'background':
+ assert 'MANAGED_TOOL_EFFECT' in done['result'], tools
rows = query('SELECT role,content FROM messages WHERE session_id=? ORDER BY id', (sid,))
assert sum(role == 'user' and 'DO_MANAGED_TOOL' in content for role, content in rows) == 1, rows
assert sum(role == 'assistant' and 'MANAGED_TOOL_DONE' in (content or '') for role, content in rows) == 1, rows
diff --git a/tests/gateway/test_managed_worker_tool_events.py b/tests/gateway/test_managed_worker_tool_events.py
new file mode 100644
index 00000000000..1e43275a2b5
--- /dev/null
+++ b/tests/gateway/test_managed_worker_tool_events.py
@@ -0,0 +1,56 @@
+"""A managed worker's tool events reach every viewer in the shape an in-process turn publishes.
+
+Ink reads ``tool_id``/``context``; ACP reads ``args``/``result``/``is_error`` to show paths, output and
+failures; API observers get the real arguments and result. The worker forwards its callback arguments
+and the owner builds the event with the ordinary turn's payload builder (real authority over SQLite)."""
+from types import SimpleNamespace
+
+from agent.managed_worker import encode_frame, read_frame, tool_frame
+from gateway.session_authority import LiveSession, SessionAuthority
+from hermes_state import SessionDB
+from hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input
+
+
+def _wire(frame):
+ import io
+ return read_frame(io.BytesIO(encode_frame(frame)))
+
+
+def test_worker_tool_frames_publish_the_in_process_payload(tmp_path):
+ from gateway.run_turn_progress import _tool_complete_payload, _tool_lifecycle_payload, publish_worker_tool_event
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ try:
+ db.create_session('s', source='cli')
+ epoch = begin_runtime_epoch(db, instance_id='owner')
+ runner = SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=False))
+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db, epoch=epoch)
+ live = authority.sessions['s'] = LiveSession(SimpleNamespace(platform=None, user_id='human'), 'route')
+ admit_session_input(db, epoch=epoch, principal_id='human', session_id='s', request_id='r', payload={'text': 'go'})
+ row = claim_session_input(db, epoch=epoch, session_id='s')
+ live.event_stream.execution = {'admission_id': row['admission_id']}
+ frames, observed = [], []
+ live.event_stream.observers.add(frames.append)
+ authority.api_observers = {row['admission_id']: [{
+ 'tool_start_callback': lambda *a: observed.append(('start', a)),
+ 'tool_complete_callback': lambda *a: observed.append(('complete', a))}]}
+
+ args = {'command': 'echo OUT; exit 3', 'timeout': 10}
+ result = '{"output": "OUT", "exit_code": 3, "error": null}'
+ start = _wire({'type': 'tool.start', **tool_frame('call-1', 'terminal', args)})
+ done = _wire({'type': 'tool.complete', **tool_frame('call-1', 'terminal', args, result)})
+ assert publish_worker_tool_event(authority, 's', row['generation'], start)
+ assert publish_worker_tool_event(authority, 's', row['generation'], done)
+
+ published = [(f['params']['type'], f['params']['payload']) for f in frames]
+ assert published == [
+ ('tool.start', _tool_lifecycle_payload('call-1', 'terminal', args)),
+ ('tool.complete', _tool_complete_payload('call-1', 'terminal', args, result, is_error=True, verbose=False))]
+ complete = published[1][1]
+ assert complete['tool_id'] == 'call-1' and complete['context'] and complete['is_error'] is True
+ assert complete['result'] == result and complete['args'] == args
+ assert observed == [('start', ('call-1', 'terminal', args)), ('complete', ('call-1', 'terminal', args, result))]
+ # Anything else (the retired id/name-only shape included) is not a tool frame.
+ assert not publish_worker_tool_event(authority, 's', row['generation'],
+ {'type': 'tool.start', 'tool_call_id': 'x', 'name': 'terminal'})
+ finally:
+ db.close()