The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): session.automation runs the classic CLI's /goal, /loop, /heartbeat managers
Teknium83960b47df32
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex b316066aa62..21c7429a380 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4585,6 +4585,19 @@ export interface SessionStats {provider: stringfallback_model?: string | null}+export interface SessionAutomationParams {+ session_id: string+ kind: 'goal' | 'loop' | 'heartbeat'+ call: string+ args?: unknown[] | null+ kwargs?: Record<string, unknown> | null+}+/** ``gateway/session_viewer_automation.py``: the manager's persisted state after the call (its own JSON, ``null`` when none) and the call's value, or the refusal main's manager raised. */+export interface SessionAutomationResult {+ state: string | null+ value?: unknown | null+ error?: Record<string, string> | null+}export interface SessionDetachParams {session_id: stringsubscription_id: string@@ -6544,6 +6557,8 @@ export interface CanonicalRpcMethods {'prompt.submit': { params: CanonicalSubmitParams; result: AdmissionStatus }/** Owner identity and the canonical capabilities a client may rely on. */'runtime.describe': { params: RuntimeDescribeParams; result: RuntimeDescribeResult }+ /** The classic CLI's /goal, /subgoal, /loop, /heartbeat manager calls (state writes, the goal judge, quality gates), run by the owner on the session's row. */+ 'session.automation': { params: SessionAutomationParams; result: SessionAutomationResult }'session.create': { params: CanonicalCreateParams; result: CanonicalSnapshot }/** Drop this connection's subscription; a stale subscription id answers detached=false. end_reason (snake_case): the viewer is closing the conversation; the last viewer leaving an idle local session ends its row with that reason. */'session.detach': { params: SessionDetachParams; result: SessionDetachResult }@@ -6596,6 +6611,7 @@ export const CANONICAL_RPC_METHODS = ['prompt.resolve_unknown','prompt.submit','runtime.describe',+ 'session.automation','session.create','session.detach','session.events.since',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 5aaf0ab0e9c..a4bdfc26fbb 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -33656,6 +33656,108 @@"title": "SessionArchiveResult","type": "object"},+ "SessionAutomationParams": {+ "additionalProperties": false,+ "properties": {+ "session_id": {+ "title": "Session Id",+ "type": "string"+ },+ "kind": {+ "enum": [+ "goal",+ "loop",+ "heartbeat"+ ],+ "title": "Kind",+ "type": "string"+ },+ "call": {+ "title": "Call",+ "type": "string"+ },+ "args": {+ "anyOf": [+ {+ "items": {},+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Args"+ },+ "kwargs": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Kwargs"+ }+ },+ "required": [+ "session_id",+ "kind",+ "call"+ ],+ "title": "SessionAutomationParams",+ "type": "object"+ },+ "SessionAutomationResult": {+ "additionalProperties": false,+ "description": "``gateway/session_viewer_automation.py``: the manager's persisted state after the call (its own\nJSON, ``null`` when none) and the call's value, or the refusal main's manager raised.",+ "properties": {+ "state": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "State"+ },+ "value": {+ "anyOf": [+ {},+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Value"+ },+ "error": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Error"+ }+ },+ "required": [+ "state"+ ],+ "title": "SessionAutomationResult",+ "type": "object"+ },"SessionBranchParams": {"additionalProperties": false,"properties": {@@ -45870,6 +45972,24 @@}}},+ {+ "name": "session.automation",+ "summary": "The classic CLI's /goal, /subgoal, /loop, /heartbeat manager calls (state writes, the goal judge, quality gates), run by the owner on the session's row.",+ "params": [+ {+ "name": "params",+ "schema": {+ "$ref": "#/components/schemas/SessionAutomationParams"+ }+ }+ ],+ "result": {+ "name": "result",+ "schema": {+ "$ref": "#/components/schemas/SessionAutomationResult"+ }+ }+ },{"name": "session.create","summary": "",diff --git a/gateway/run_goals.py b/gateway/run_goals.pyindex 4ef9c486bac..335d0000403 100644--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@ -327,6 +327,10 @@ class GatewayGoalsMixin:self, *, agent_result: Any, source: Any, is_internal: bool, event: Any = None,) -> None:"""Run goal and loop bookkeeping after an agent turn returns."""+ from gateway.session_authorities import active_authority+ from gateway.session_viewer_automation import viewer_driven+ if viewer_driven(active_authority(self), getattr(source, "chat_id", None)):+ return # the classic CLI viewer judges and continues through ``session.automation``final_text = self._final_text_for_post_turn_hooks(agent_result, event)try:session_entry = await self.async_session_store.get_or_create_session(diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 701575a26e6..29686a71f95 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -109,6 +109,8 @@ class AuthorityConnection:handlers['session.prune'] = partial(prune, self)from gateway.session_usage import statshandlers['session.stats'] = partial(stats, self)+ from gateway.session_viewer_automation import automation+ handlers['session.automation'] = partial(automation, self)return handlersasync def dispatch(self, request):diff --git a/gateway/session_viewer_automation.py b/gateway/session_viewer_automation.pynew file mode 100644index 00000000000..945a8e2b549--- /dev/null+++ b/gateway/session_viewer_automation.py@@ -0,0 +1,161 @@+"""``session.automation``: the classic CLI's /goal, /subgoal, /loop and /heartbeat managers, run here.++Main's HermesCLI held a ``GoalManager`` / ``LoopManager`` / ``HeartbeatManager`` in its own process:+they wrote ``state_meta`` through a read-write SessionDB and called the goal judge (an auxiliary+model). Over the session authority the gateway is the single writer and runs every model call, so+the viewer's managers are thin proxies (``hermes_cli/gateway_automation.py``) and each mutation or+judgement is one call of this verb, executed against the session's physical row under the owning+profile's runtime scope and the session's own workspace (quality gates run in its cwd).++The viewer keeps main's timing: it calls ``evaluate_after_turn`` / ``complete_tick`` after its turn+returns and queues the continuation itself. A session whose viewer drives its automation this way is+recorded in ``authority.viewer_automation``; the gateway's own post-turn goal/loop hooks skip it, so+a turn is never judged twice or continued twice.+"""+from __future__ import annotations++import asyncio+import dataclasses+from pathlib import Path++from hermes_state_runtime import RuntimeStoreError++_CALLS = {+ "goal": frozenset({"state", "set", "pause", "resume", "clear", "mark_done", "add_subgoal", "remove_subgoal",+ "clear_subgoals", "add_gate", "remove_gate", "clear_gates", "wait_on", "wait_on_session",+ "wait_for_seconds", "stop_waiting", "is_waiting", "evaluate_after_turn", "command"}),+ "loop": frozenset({"state", "set", "pause", "resume", "clear", "fire_tick", "abandon_tick", "complete_tick",+ "goal_blocks_tick"}),+ "heartbeat": frozenset({"state", "set", "pause", "resume", "clear", "due_prompt", "abandon_fire"}),+}+_FIELDS = frozenset({"session_id", "profile", "kind", "call", "args", "kwargs"})+_ERRORS = (RuntimeError, ValueError, IndexError)+++def viewer_driven(authority, session_id) -> bool:+ """Whether a local viewer drives this session's goal/loop judging (see the module doc): only while+ that viewer's connection still holds its subscription, so a TUI or Desktop attached after it left+ gets the gateway's own post-turn hooks again."""+ connection = getattr(authority, "viewer_automation", {}).get(session_id) if authority is not None else None+ return bool(connection is not None and connection.subscriptions.get(session_id))+++def _max_turns(runner):+ configured = getattr(runner, "_goal_max_turns_from_config", None)+ if configured is not None:+ return configured()+ from hermes_cli.goals import DEFAULT_MAX_TURNS+ return DEFAULT_MAX_TURNS+++def _manager(runner, kind, target):+ if kind == "goal":+ from hermes_cli.goals import GoalManager+ return GoalManager(session_id=target, default_max_turns=_max_turns(runner))+ if kind == "loop":+ from hermes_cli.loops import LoopManager+ return LoopManager(session_id=target)+ from hermes_cli.heartbeat import HeartbeatManager+ return HeartbeatManager(session_id=target)+++def _wire(value):+ """A manager return value as JSON: states and gates keep their own serialisation."""+ if value is None or isinstance(value, (str, int, float, bool)):+ return value+ if hasattr(value, "to_json"):+ return {"__state__": value.to_json()}+ if hasattr(value, "to_dict"):+ return {"__gate__": value.to_dict()}+ if dataclasses.is_dataclass(value) and not isinstance(value, type):+ return dataclasses.asdict(value)+ if isinstance(value, dict):+ return {str(k): _wire(v) for k, v in value.items()}+ if isinstance(value, (list, tuple)):+ return [_wire(v) for v in value]+ return str(value)+++def _special(mgr, kind, target, call, args, kwargs):+ """Calls that are more than one manager method; ``None`` when ``call`` is a plain method."""+ if kind == "goal" and call == "command":+ # The whole /goal command (main's ``dispatch_goal_command``): ``/goal draft`` drafts its+ # contract with the auxiliary model, which runs here, never in the viewer.+ from hermes_cli.goal_command import dispatch_goal_command+ arg, last_user = (list(args) + ["", None])[:2]+ return dispatch_goal_command(mgr, str(arg or ""), authorize_gate=lambda: None, last_user_message=last_user)+ if kind == "goal" and call == "evaluate_after_turn":+ # Background processes and delegations live in this process now (the turn ran here).+ from hermes_cli.goals import count_active_delegations, gather_background_processes+ try:+ processes = gather_background_processes(owner_task_id=target)+ delegations = count_active_delegations(target)+ except Exception: # health: allow BLE001 -- the judge degrades to no background block, as main's hook did+ processes, delegations = None, 0+ return mgr.evaluate_after_turn(str((args or [""])[0] or ""), user_initiated=True,+ background_processes=processes, active_delegations=delegations)+ if kind == "goal" and call == "set" and isinstance(kwargs.get("contract"), dict):+ from hermes_cli.goals import GoalContract+ kwargs = {**kwargs, "contract": GoalContract.from_dict(kwargs["contract"])}+ return mgr.set(*args, **kwargs)+ if kind == "loop" and call == "goal_blocks_tick":+ from hermes_cli.loops import goal_blocks_loop_tick+ return goal_blocks_loop_tick(target)+ if call == "state":+ return None+ return _NOT_SPECIAL+++_NOT_SPECIAL = object()+++def invoke(runner, kind, target, call, args, kwargs) -> dict:+ """Run one call against ``target``'s persisted state: ``{state, value}`` or ``{state, error}``."""+ mgr = _manager(runner, kind, target)+ out: dict+ try:+ value = _special(mgr, kind, target, call, args, kwargs)+ if value is _NOT_SPECIAL:+ value = getattr(mgr, call)(*args, **kwargs)+ out = {"value": _wire(value)}+ except _ERRORS as exc:+ out = {"error": {"type": type(exc).__name__, "message": str(exc)}}+ state = mgr.state+ out["state"] = state.to_json() if state is not None else None+ return out+++def _parse(params):+ if set(params) - _FIELDS:+ raise RuntimeStoreError("invalid_params")+ kind, call = params.get("kind"), params.get("call")+ args, kwargs = params.get("args") or [], params.get("kwargs") or {}+ if (kind not in _CALLS or call not in _CALLS[kind] or not isinstance(args, list)+ or not isinstance(kwargs, dict) or not all(isinstance(k, str) and not k.startswith("_") for k in kwargs)):+ raise RuntimeStoreError("invalid_params")+ return kind, call, args, kwargs+++async def automation(connection, ref, params):+ kind, call, args, kwargs = _parse(params)+ if not isinstance(ref.session_id, str) or not ref.session_id:+ raise RuntimeStoreError("invalid_params")+ from gateway.session_busy_controls import authorize+ authorize(connection, ref, params, "session:control")+ authority = connection.authority+ live = authority.sessions[ref.session_id]+ from gateway.session_ancillary import physical_target+ target = physical_target(authority, ref)+ if not hasattr(authority, "viewer_automation"):+ authority.viewer_automation = {}+ authority.viewer_automation[ref.session_id] = connection+ runner = authority.runner+ home = Path(authority.profile_id)++ def run():+ from gateway.run import _profile_runtime_scope+ from gateway.session_commands import _session_workspace+ with _profile_runtime_scope(home), _session_workspace(runner, live.source):+ return invoke(runner, kind, target, call, args, kwargs)+ # The judge and gates block for seconds: off the loop, with the caller's context (profile scope).+ return await asyncio.to_thread(run)diff --git a/tests/gateway/test_session_viewer_automation.py b/tests/gateway/test_session_viewer_automation.pynew file mode 100644index 00000000000..4880a728a6f--- /dev/null+++ b/tests/gateway/test_session_viewer_automation.py@@ -0,0 +1,105 @@+"""``session.automation``: the classic CLI's /goal, /subgoal, /loop, /heartbeat managers run by the owner.++Real authority + SQLite: every mutation lands in the owner's ``state_meta`` row for the session's physical+target, the goal judge runs here (patched), a manager refusal comes back as main's exception text, and a+session driven this way is skipped by the gateway's own post-turn goal hook (never judged twice).+"""+import json+from types import SimpleNamespace++import pytest+import pytest_asyncio+++@pytest_asyncio.fixture+async def owner(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import create_local_session+ from hermes_state_local import local_receipt+ from hermes_cli import goals++ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path / 'fixture'), instance_id='owner')+ monkeypatch.setattr(goals, '_get_session_db', lambda: authority.db) # the owner's own store+ viewer = AuthorityConnection(authority, object(), {'user_id': 'human', 'profile_id': str(tmp_path / 'fixture')})+ ref = create_local_session(authority, viewer.actor, {'request_id': 'r', 'source': 'cli',+ 'cwd': str(tmp_path), 'model': 'm', 'toolsets': []})+ target = local_receipt(authority.db, ref.session_id)['entry']['session_id']++ async def call(kind, name, *args, **kwargs):+ reply = await viewer.dispatch({'id': 1, 'method': 'session.automation', 'params': {+ 'session_id': ref.session_id, 'kind': kind, 'call': name, 'args': list(args), 'kwargs': kwargs}})+ return reply.get('result', reply.get('error'))+ try:+ yield SimpleNamespace(call=call, db=authority.db, target=target, authority=authority, ref=ref, viewer=viewer)+ finally:+ store.close_all_db_handles()+++async def test_goal_mutations_land_in_the_owners_row(owner):+ reply = await owner.call('goal', 'set', 'ship it', max_turns=5)+ state = json.loads(reply['state'])+ assert (state['goal'], state['status'], state['max_turns']) == ('ship it', 'active', 5)+ assert json.loads(owner.db.get_meta('goal:' + owner.target))['goal'] == 'ship it'+ reply = await owner.call('goal', 'add_subgoal', 'and test it')+ assert reply['value'] == 'and test it'+ assert json.loads(owner.db.get_meta('goal:' + owner.target))['subgoals'] == ['and test it']+ reply = await owner.call('goal', 'remove_subgoal', 9)+ assert reply['error'] == {'type': 'IndexError', 'message': 'index out of range (1..1)'}+ await owner.call('goal', 'pause', reason='user-paused')+ assert json.loads(owner.db.get_meta('goal:' + owner.target))['status'] == 'paused'+ await owner.call('goal', 'clear')+ assert json.loads(owner.db.get_meta('goal:' + owner.target))['status'] == 'cleared'+++async def test_the_goal_judge_runs_on_the_owner(owner, monkeypatch):+ from hermes_cli import goals+ seen = []++ def judge(goal, response, **kw):+ seen.append((goal, response))+ return 'continue', 'only the outline exists', False, None, False+ monkeypatch.setattr(goals, 'judge_goal', judge)+ await owner.call('goal', 'set', 'write the report')+ reply = await owner.call('goal', 'evaluate_after_turn', 'drafted the outline')+ decision = reply['value']+ assert seen == [('write the report', 'drafted the outline')]+ assert decision['should_continue'] is True+ assert decision['message'] == '↻ Continuing toward goal (1/20): only the outline exists'+ assert decision['continuation_prompt'].startswith('[Continuing toward your standing goal]')+ assert json.loads(owner.db.get_meta('goal:' + owner.target))['turns_used'] == 1++ from gateway.session_viewer_automation import viewer_driven+ assert not viewer_driven(owner.authority, owner.ref.session_id), 'no subscription: the gateway hooks run'+ owner.viewer.subscriptions[owner.ref.session_id] = 'sub-1'+ assert viewer_driven(owner.authority, owner.ref.session_id), 'the attached CLI judges; the gateway hook skips'+++async def test_loop_and_heartbeat_ticks_are_claimed_on_the_owner(owner):+ await owner.call('loop', 'set', 'check the queue', interval_seconds=60, times=1)+ wake = (await owner.call('loop', 'fire_tick'))['value']+ assert wake.startswith('[/loop wakeup #1')+ reply = await owner.call('loop', 'complete_tick', 'nothing new')+ assert reply['value']['message'] == '✓ Loop finished — ran 1/1 times.'+ assert json.loads(owner.db.get_meta('loop:' + owner.target))['status'] == 'done'+ reply = await owner.call('heartbeat', 'set', 'pulse', 60)+ assert json.loads(reply['state'])['interval_seconds'] == 60+ assert (await owner.call('heartbeat', 'clear'))['value'] is True+ assert json.loads(owner.db.get_meta('heartbeat:' + owner.target))['status'] == 'cleared'+++async def test_unknown_calls_are_refused(owner):+ assert (await owner.call('goal', '_save'))['message'] == 'invalid_params'+ assert (await owner.call('cron', 'state'))['message'] == 'invalid_params'diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.pyindex 69bc5325e01..5369d109859 100644--- a/tui_gateway/contracts/canonical.py+++ b/tui_gateway/contracts/canonical.py@@ -219,6 +219,28 @@ canonical_method("session.stats", params=SessionStatsParams, result=SessionStatsdoc="The session.usage dict on demand: what main's classic CLI read off its agent.")+class SessionAutomationParams(Params):+ session_id: str+ kind: Literal["goal", "loop", "heartbeat"]+ call: str+ args: list[JsonValue] | None = None+ kwargs: dict[str, JsonValue] | None = None+++class SessionAutomationResult(Result):+ """``gateway/session_viewer_automation.py``: the manager's persisted state after the call (its own+ JSON, ``null`` when none) and the call's value, or the refusal main's manager raised."""++ state: str | None+ value: JsonValue | None = None+ error: dict[str, str] | None = None+++canonical_method("session.automation", params=SessionAutomationParams, result=SessionAutomationResult,+ doc="The classic CLI's /goal, /subgoal, /loop, /heartbeat manager calls (state writes, the "+ "goal judge, quality gates), run by the owner on the session's row.")++class SessionDetachParams(Params):session_id: strsubscription_id: str