The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(api): accept a turn author on session chat and runs; peer dm forwards it
Erosika0ac631b6c0a9
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex d93d9c1de11..7af83fb9599 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -618,6 +618,26 @@ def _session_chat_user_message(body: Dict[str, Any], *, param: str = "message")return None, _multimodal_validation_error(exc, param=param)+def _request_turn_author(body: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ """Normalized body ``author`` or None when absent or null. Raises ValueError when it is not an object.+ The value is a claim by an API-key holder: it only labels the turn for memory attribution."""+ raw = body.get("author")+ if raw is None:+ return None+ if not isinstance(raw, dict):+ raise ValueError("author must be an object")+ from agent.turn_author import parse_turn_author+ return parse_turn_author(raw)+++def _session_chat_author(body: Dict[str, Any]) -> tuple[Optional[Dict[str, Any]], Optional["web.Response"]]:+ """``_request_turn_author`` with the session-chat 400 envelope (code ``invalid_author``)."""+ try:+ return _request_turn_author(body), None+ except ValueError as exc:+ return None, _error_response(str(exc), 400, code="invalid_author")++_USAGE_TOKEN_KEYS = ("input_tokens", "output_tokens", "total_tokens")@@ -2984,6 +3004,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):if err:return None, erruser_message, err = _session_chat_user_message(body)+ if err is not None:+ return None, err+ turn_author, err = _session_chat_author(body)if err is not None:return None, errsystem_prompt = body.get("system_message") or body.get("instructions")@@ -3024,7 +3047,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):gateway_session_key=gateway_session_key, route=route, session_model=session_model,requested_runtime=runtime_request.get("requested") or {},route_source=runtime_request.get("route_source") or "global",- confirmed_runtime_lock=lock_active,+ confirmed_runtime_lock=lock_active, turn_author=turn_author,# #98619: the client addresses this session by construction — the id is in the# request path (/api/sessions/{session_id}/chat) — so a wake self-post lands where# the client will read it. The audited native-session opt-in.@@ -3626,14 +3649,15 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):route: Optional[Dict[str, Any]] = None, session_model: Optional[str] = None,requested_runtime: Optional[Dict[str, Any]] = None, route_source: str = "global",confirmed_runtime_lock: bool = False, bind_declared_conversation: bool = False,- session_history_delivery: str = "") -> tuple:+ session_history_delivery: str = "", turn_author: Optional[Dict[str, Any]] = None) -> tuple:"""Create an agent and run one turn in a thread executor -> ``(result, usage)``.``agent_ref[0]`` receives the agent so SSE writers can interrupt it; ``active_run_id``registers it in ``_active_run_agents``. Under a confirmed model lock the actualprovider/model must match or the turn fails; ``runtime`` metadata is attached.``session_history_delivery`` declares #98619 session-id provenance and default-denies: only auditedproducers whose client can address the id again pass "1" (see- ``_bind_api_server_session``)."""+ ``_bind_api_server_session``).+ ``turn_author`` only labels the turn for memory attribution; it grants nothing."""loop = asyncio.get_running_loop()# ContextVars do not follow run_in_executor threads: capture here, re-enter in _run().request_profile = _api_request_profile.get()@@ -3677,9 +3701,11 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):# two callers pass ``agent_ref``, and only /v1/runs has a run_id, so neither is a usable# hook for the rest. See #63529.self._shutdown_interruptible_agents[id(agent)] = agent+ # Passed only when set: a human turn keeps today's call shape.+ author_kwargs = {"turn_author": turn_author} if turn_author is not None else {}result = agent.run_conversation(user_message=user_message, conversation_history=conversation_history,- task_id=effective_task_id)+ task_id=effective_task_id, **author_kwargs)return self._finish_turn_result(agent, result, session_id, route=route, requested_runtime=requested_runtime,route_source=route_source, confirmed_runtime_lock=confirmed_runtime_lock)diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 2fcd0028c9d..29025ed27ed 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -327,6 +327,7 @@ class _RunLaunch:request_profile: Anybrowser_control_principal: Anybrowser_control_transport_family: Any+ turn_author: Optional[Dict[str, Any]] = None # memory-attribution label only; grants nothing@propertydef approval_session_key(self) -> str:@@ -412,6 +413,10 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Resuser_message = raw_input[-1].get("content", "") if isinstance(raw_input, list) else ""if not user_message:return _json_error(_openai_error, "No user message found in input", status=400)+ try:+ turn_author = _api_server._request_turn_author(body)+ except ValueError as exc:+ return _json_error(_openai_error, str(exc), code="invalid_author", status=400)conversation_history, instructions, stored_session_id, history_err = (_resolve_conversation_history(self, body, raw_input, _openai_error=_openai_error))if history_err is not None:@@ -488,7 +493,8 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Res**{k: agent_overrides.get(k) for k in ("requested_model", "requested_provider", "model_options")}),request_profile=_api_server._api_request_profile.get(),browser_control_principal=_api_server._api_request_browser_control_principal.get(),- browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get())+ browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get(),+ turn_author=turn_author)self._activate_admitted_request()task = self._active_run_tasks[run_id] = asyncio.create_task(_execute_run(self, launch, _api_server=_api_server))with suppress(TypeError):@@ -544,9 +550,11 @@ def _run_agent_sync(self, run: _RunLaunch, agent, approval_notify, *, _api_serve# /v1/runs owns its agent lifecycle (no TurnRunner): record process ownership# so stop/cancel reaps only the background processes this run created._api_server._publish_turn_process_ownership(agent, effective_task_id)+ # Passed only when set: a human turn keeps today's call shape.+ author_kwargs = {"turn_author": run.turn_author} if run.turn_author is not None else {}r = agent.run_conversation(user_message=run.user_message, conversation_history=run.conversation_history,- task_id=effective_task_id)+ task_id=effective_task_id, **author_kwargs)finally:# Clear ownership now so a later stop can't reap work this run left running._api_server._clear_turn_process_ownership(agent)diff --git a/hermes_cli/subcommands/peer.py b/hermes_cli/subcommands/peer.pyindex 477fa070033..5962a7218ab 100644--- a/hermes_cli/subcommands/peer.py+++ b/hermes_cli/subcommands/peer.py@@ -298,6 +298,17 @@ def _peer_run_ctl(args, action: str, peer_name: str, profile: str | None, base:return 0+def _turn_body(message: str, *, message_key: str, **extra) -> dict:+ """Request body for one turn. ``author`` is added only when a dispatcher set HERMES_TURN_AUTHOR."""+ from agent.turn_author import turn_author_from_env++ body = {message_key: message, **extra}+ author = turn_author_from_env()+ if author is not None:+ body["author"] = author+ return body++def _peer_run(args, message: str, peer_name: str, profile: str | None, base: str, key: str) -> int:idempotency_key = (getattr(args, "idempotency_key", None) or f"peer-{uuid.uuid4().hex}").strip()if (not idempotency_key or len(idempotency_key) > 255@@ -313,7 +324,7 @@ def _peer_run(args, message: str, peer_name: str, profile: str | None, base: strsession_id = _ensure_bot_chat(base, key)result = _request(f"{base}/v1/runs", key, method="POST",- body={"input": message, "session_id": session_id},+ body=_turn_body(message, message_key="input", session_id=session_id),headers={"Idempotency-Key": idempotency_key})except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:return _peer_failure(peer_name, exc)@@ -336,7 +347,7 @@ def _peer_dm(args, message: str, peer_name: str, profile: str | None, base: str,session_id = _ensure_bot_chat(base, key)result = _request(f"{base}/api/sessions/{urllib.parse.quote(session_id, safe='')}/chat", key,- method="POST", body={"message": message}, timeout=DM_TIMEOUT_S)+ method="POST", body=_turn_body(message, message_key="message"), timeout=DM_TIMEOUT_S)except RuntimeError as exc:print(f"Peer '{peer_name}': {exc}", file=sys.stderr)return 1diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.pyindex 43fdbc4a268..63da3ac15dc 100644--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@ -249,6 +249,57 @@ class TestStartRun:"runs route must bind chat_id so delegation dispatch sees a wake target")+ @staticmethod+ async def _wait_completed(cli, run_id: str) -> None:+ for _ in range(40):+ status = await (await cli.get(f"/v1/runs/{run_id}")).json()+ if status["status"] == "completed":+ return+ await asyncio.sleep(0.05)+ raise AssertionError(f"run {run_id} did not complete")++ @staticmethod+ def _capturing_agent(captured):+ agent = MagicMock()+ agent.run_conversation.side_effect = lambda **kwargs: captured.update(kwargs) or {"final_response": "done"}+ agent.session_prompt_tokens = agent.session_completion_tokens = agent.session_total_tokens = 0+ return agent++ @pytest.mark.asyncio+ @pytest.mark.parametrize("body, expected", [+ ({"input": "hello", "author": {"id": "bot:dixie", "name": " dixie ", "is_bot": True, "role": "admin"}},+ {"id": "bot:dixie", "name": "dixie", "is_bot": True}),+ ({"input": "hello"}, "absent"),+ ], ids=["author", "no author"])+ async def test_start_passes_normalized_author_to_run_conversation(self, adapter, body, expected):+ """A body ``author`` reaches ``run_conversation`` normalized; it labels memory only. Without one the+ call keeps today's shape."""+ app = _create_runs_app(adapter)+ captured = {}++ async with TestClient(TestServer(app)) as cli:+ with patch.object(adapter, "_create_agent", return_value=self._capturing_agent(captured)):+ resp = await cli.post("/v1/runs", json=body)+ assert resp.status == 202+ await self._wait_completed(cli, (await resp.json())["run_id"])++ assert captured["user_message"] == "hello"+ assert captured.get("turn_author", "absent") == expected++ @pytest.mark.asyncio+ @pytest.mark.parametrize("author", ["dixie", ["dixie"], 7])+ async def test_start_rejects_non_object_author(self, adapter, author):+ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ with patch.object(adapter, "_create_agent") as mock_create:+ resp = await cli.post("/v1/runs", json={"input": "hello", "author": author})+ assert resp.status == 400+ body = await resp.json()+ assert body["error"]["code"] == "invalid_author"+ assert body["error"]["message"] == "author must be an object"+ mock_create.assert_not_called()+ assert adapter._run_statuses == {}+@pytest.mark.asyncioasync def test_start_rejects_conflicting_route_and_request_provider(self):diff --git a/tests/gateway/test_session_api.py b/tests/gateway/test_session_api.pyindex f1db8f03c0c..0064e97e39e 100644--- a/tests/gateway/test_session_api.py+++ b/tests/gateway/test_session_api.py@@ -838,6 +838,68 @@ async def test_require_model_lock_hard_fails_when_global_default_would_be_used(amock_run.assert_not_called()+_CHAT_REPLY = ({"final_response": "ok"}, {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0})++[email protected]("body, expected", [+ ({"message": "hello", "author": {"id": " bot:dixie ", "name": "dixie", "is_bot": 1, "role": "admin"}},+ {"id": "bot:dixie", "name": "dixie", "is_bot": True}),+ ({"message": "hello"}, None),+ ({"message": "hello", "author": None}, None),+], ids=["author", "no author", "null author"])+async def test_session_chat_passes_normalized_author_to_run_agent(adapter, session_db, body, expected):+ """A body ``author`` reaches ``_run_agent`` normalized with unknown keys dropped; absent or null is None."""+ session_id = session_db.create_session("author-session", "api_server")+ app = _create_session_app(adapter)+ with patch.object(adapter, "_run_agent", AsyncMock(return_value=_CHAT_REPLY)) as mock_run:+ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(f"/api/sessions/{session_id}/chat", json=body)+ assert resp.status == 200, await resp.text()+ assert mock_run.call_args.kwargs["turn_author"] == expected++[email protected]("suffix", ["/chat", "/chat/stream"])[email protected]("author", ["dixie", ["dixie"], 7])+async def test_session_chat_rejects_non_object_author(adapter, session_db, suffix, author):+ session_id = session_db.create_session("bad-author-session", "api_server")+ app = _create_session_app(adapter)+ with patch.object(adapter, "_run_agent", new_callable=AsyncMock) as mock_run:+ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(+ f"/api/sessions/{session_id}{suffix}", json={"message": "hello", "author": author})+ assert resp.status == 400, await resp.text()+ body = await resp.json()+ assert body["error"]["code"] == "invalid_author"+ assert body["error"]["message"] == "author must be an object"+ mock_run.assert_not_called()+++async def test_run_agent_forwards_author_to_run_conversation_only_when_set(adapter, monkeypatch):+ """``turn_author`` reaches ``run_conversation`` when set; a human turn keeps today's call shape."""+ calls = []++ class FakeAgent:+ session_prompt_tokens = 0+ session_completion_tokens = 0+ session_total_tokens = 0+ session_id = "author-run"++ def run_conversation(self, user_message, conversation_history, task_id, **kwargs):+ calls.append(kwargs)+ return {"final_response": "ok", "session_id": self.session_id}++ monkeypatch.setattr(adapter, "_create_agent", lambda **kwargs: FakeAgent())+ author = {"id": "bot:dixie", "name": "dixie", "is_bot": True}+ await adapter._run_agent(+ user_message="hello", conversation_history=[], session_id="author-run", turn_author=author)+ await adapter._run_agent(user_message="hello", conversation_history=[], session_id="author-run")++ assert calls == [{"turn_author": author}, {}]++@pytest.mark.asyncioasync def test_patch_session_persists_pinned_and_archived(adapter, session_db):"""PATCH must accept the durable pin/archive flags and round-trip them.diff --git a/tests/hermes_cli/test_peer_cmd.py b/tests/hermes_cli/test_peer_cmd.pyindex 732aab2ed72..7d6816a807b 100644--- a/tests/hermes_cli/test_peer_cmd.py+++ b/tests/hermes_cli/test_peer_cmd.py@@ -7,6 +7,7 @@ from types import SimpleNamespaceimport pytest+from agent.turn_author import TURN_AUTHOR_ENVfrom hermes_cli.subcommands import peer as peer_cmd@@ -92,6 +93,7 @@ def test_dm_unknown_peer_and_missing_key(monkeypatch):class _FakePeer(BaseHTTPRequestHandler):sessions: list = []chats: list = []+ chat_bodies: list = []runs: list = []run_idempotency_keys: list = []auth_seen: list = []@@ -144,6 +146,7 @@ class _FakePeer(BaseHTTPRequestHandler):if self.path.startswith("/api/sessions/") and self.path.endswith("/chat"):type(self).chats.append(body.get("message"))+ type(self).chat_bodies.append(body)return self._json({"object": "hermes.session.chat.completion","session_id": "bc_1",@@ -176,6 +179,7 @@ class _FakePeer(BaseHTTPRequestHandler):def fake_peer_server():_FakePeer.sessions = []_FakePeer.chats = []+ _FakePeer.chat_bodies = []_FakePeer.runs = []_FakePeer.run_idempotency_keys = []_FakePeer.auth_seen = []@@ -226,6 +230,45 @@ def test_dm_reuses_existing_bot_chat(monkeypatch, capsys, fake_peer_server):assert _FakePeer.sessions == ["bc_existing"]+# ── per-turn author (HERMES_TURN_AUTHOR set by the message_agent runner) ─────+++AUTHOR = {"id": "bot:dixie", "name": "dixie", "is_bot": True}+++def _peer_spark(monkeypatch, url, author_env):+ _FakePeer.sessions = ["bc_existing"]+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": url}})+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "secret-key-123456")+ if author_env is None:+ monkeypatch.delenv(TURN_AUTHOR_ENV, raising=False)+ else:+ monkeypatch.setenv(TURN_AUTHOR_ENV, json.dumps(author_env))++[email protected]("author_env, expected_body", [+ ({**AUTHOR, "x": 1}, {"message": "ping", "author": AUTHOR}),+ (None, {"message": "ping"}),+], ids=["author from env", "no env"])+def test_dm_body_carries_author_only_from_env(monkeypatch, fake_peer_server, author_env, expected_body):+ _peer_spark(monkeypatch, fake_peer_server, author_env)++ rc = peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="spark", message="ping", json=True))++ assert rc == 0+ assert _FakePeer.chat_bodies == [expected_body]+++def test_run_body_carries_author_from_env(monkeypatch, capsys, fake_peer_server):+ _peer_spark(monkeypatch, fake_peer_server, AUTHOR)++ rc = peer_cmd.cmd_peer(SimpleNamespace(+ peer_action="run", target="spark", message="long task", idempotency_key="ticket-1", json=True))++ assert rc == 0+ assert _FakePeer.runs == [{"input": "long task", "session_id": "bc_existing", "author": AUTHOR}]++# ── hidden canonical Bot Chat (issue #91583) ─────────────────────────────────