session_viewer_automation.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """``session.automation``: the classic CLI's /goal, /subgoal, /loop and /heartbeat managers, run here.
  2. Main's HermesCLI held a ``GoalManager`` / ``LoopManager`` / ``HeartbeatManager`` in its own process:
  3. they wrote ``state_meta`` through a read-write SessionDB and called the goal judge (an auxiliary
  4. model). Over the session authority the gateway is the single writer and runs every model call, so
  5. the viewer's managers are thin proxies (``hermes_cli/gateway_automation.py``) and each mutation or
  6. judgement is one call of this verb, executed against the session's physical row under the owning
  7. profile's runtime scope and the session's own workspace (quality gates run in its cwd).
  8. The viewer keeps main's timing: it calls ``evaluate_after_turn`` / ``complete_tick`` after its turn
  9. returns and queues the continuation itself. A session whose viewer drives its automation this way is
  10. recorded in ``authority.viewer_automation``; the gateway's own post-turn goal/loop hooks skip it, so
  11. a turn is never judged twice or continued twice.
  12. """
  13. from __future__ import annotations
  14. import asyncio
  15. import dataclasses
  16. from pathlib import Path
  17. from hermes_state_runtime import RuntimeStoreError
  18. _CALLS = {
  19. "goal": frozenset({"state", "set", "pause", "resume", "clear", "mark_done", "add_subgoal", "remove_subgoal",
  20. "clear_subgoals", "add_gate", "remove_gate", "clear_gates", "wait_on", "wait_on_session",
  21. "wait_for_seconds", "stop_waiting", "is_waiting", "evaluate_after_turn", "command"}),
  22. "loop": frozenset({"state", "set", "pause", "resume", "clear", "fire_tick", "abandon_tick", "complete_tick",
  23. "goal_blocks_tick"}),
  24. "heartbeat": frozenset({"state", "set", "pause", "resume", "clear", "due_prompt", "abandon_fire"}),
  25. }
  26. _READS = frozenset({"state", "is_waiting", "goal_blocks_tick"})
  27. # /heartbeat set and resume start the CLI's watchdog when they return a state (cli_commands_mixin);
  28. # only it calls due_prompt.
  29. _WATCHDOG_CALLS = frozenset({"set", "resume", "due_prompt"})
  30. _FIELDS = frozenset({"session_id", "profile", "kind", "call", "args", "kwargs"})
  31. _ERRORS = (RuntimeError, ValueError, IndexError)
  32. def viewer_driven(authority, session_id, registry="viewer_automation") -> bool:
  33. """Whether a local viewer drives this session's goal/loop judging (see the module doc), or with
  34. ``viewer_heartbeat`` its heartbeat ticks: only while that viewer's connection still holds its
  35. subscription, so a TUI or Desktop attached after it left gets the gateway's own drivers again."""
  36. connection = getattr(authority, registry, {}).get(session_id) if authority is not None else None
  37. return bool(connection is not None and connection.subscriptions.get(session_id))
  38. def _max_turns(runner):
  39. configured = getattr(runner, "_goal_max_turns_from_config", None)
  40. if configured is not None:
  41. return configured()
  42. from hermes_cli.goals import DEFAULT_MAX_TURNS
  43. return DEFAULT_MAX_TURNS
  44. def _manager(runner, kind, target):
  45. if kind == "goal":
  46. from hermes_cli.goals import GoalManager
  47. return GoalManager(session_id=target, default_max_turns=_max_turns(runner))
  48. if kind == "loop":
  49. from hermes_cli.loops import LoopManager
  50. return LoopManager(session_id=target)
  51. from hermes_cli.heartbeat import HeartbeatManager
  52. return HeartbeatManager(session_id=target)
  53. def _wire(value):
  54. """A manager return value as JSON: states and gates keep their own serialisation."""
  55. if value is None or isinstance(value, (str, int, float, bool)):
  56. return value
  57. if hasattr(value, "to_json"):
  58. return {"__state__": value.to_json()}
  59. if hasattr(value, "to_dict"):
  60. return {"__gate__": value.to_dict()}
  61. if dataclasses.is_dataclass(value) and not isinstance(value, type):
  62. return dataclasses.asdict(value)
  63. if isinstance(value, dict):
  64. return {str(k): _wire(v) for k, v in value.items()}
  65. if isinstance(value, (list, tuple)):
  66. return [_wire(v) for v in value]
  67. return str(value)
  68. def _special(mgr, kind, target, call, args, kwargs):
  69. """Calls that are more than one manager method; ``None`` when ``call`` is a plain method."""
  70. if kind == "goal" and call == "command":
  71. # The whole /goal command (main's ``dispatch_goal_command``): ``/goal draft`` drafts its
  72. # contract with the auxiliary model, which runs here, never in the viewer.
  73. from hermes_cli.goal_command import dispatch_goal_command
  74. arg, last_user = (list(args) + ["", None])[:2]
  75. return dispatch_goal_command(mgr, str(arg or ""), authorize_gate=lambda: None, last_user_message=last_user)
  76. if kind == "goal" and call == "evaluate_after_turn":
  77. # Background processes and delegations live in this process now (the turn ran here).
  78. from hermes_cli.goals import count_active_delegations, gather_background_processes
  79. try:
  80. processes = gather_background_processes(owner_task_id=target)
  81. delegations = count_active_delegations(target)
  82. except Exception: # health: allow BLE001 -- the judge degrades to no background block, as main's hook did
  83. processes, delegations = None, 0
  84. return mgr.evaluate_after_turn(str((args or [""])[0] or ""), user_initiated=True,
  85. background_processes=processes, active_delegations=delegations)
  86. if kind == "goal" and call == "set" and isinstance(kwargs.get("contract"), dict):
  87. from hermes_cli.goals import GoalContract
  88. kwargs = {**kwargs, "contract": GoalContract.from_dict(kwargs["contract"])}
  89. return mgr.set(*args, **kwargs)
  90. if kind == "loop" and call == "goal_blocks_tick":
  91. from hermes_cli.loops import goal_blocks_loop_tick
  92. return goal_blocks_loop_tick(target)
  93. if call == "state":
  94. return None
  95. return _NOT_SPECIAL
  96. _NOT_SPECIAL = object()
  97. def invoke(runner, kind, target, call, args, kwargs) -> dict:
  98. """Run one call against ``target``'s persisted state: ``{state, value}`` or ``{state, error}``."""
  99. mgr = _manager(runner, kind, target)
  100. out: dict
  101. try:
  102. value = _special(mgr, kind, target, call, args, kwargs)
  103. if value is _NOT_SPECIAL:
  104. value = getattr(mgr, call)(*args, **kwargs)
  105. out = {"value": _wire(value)}
  106. except _ERRORS as exc:
  107. out = {"error": {"type": type(exc).__name__, "message": str(exc)}}
  108. state = mgr.state
  109. out["state"] = state.to_json() if state is not None else None
  110. return out
  111. def _parse(params):
  112. if set(params) - _FIELDS:
  113. raise RuntimeStoreError("invalid_params")
  114. kind, call = params.get("kind"), params.get("call")
  115. args, kwargs = params.get("args") or [], params.get("kwargs") or {}
  116. if (kind not in _CALLS or call not in _CALLS[kind] or not isinstance(args, list)
  117. or not isinstance(kwargs, dict) or not all(isinstance(k, str) and not k.startswith("_") for k in kwargs)):
  118. raise RuntimeStoreError("invalid_params")
  119. return kind, call, args, kwargs
  120. async def automation(connection, ref, params):
  121. kind, call, args, kwargs = _parse(params)
  122. if not isinstance(ref.session_id, str) or not ref.session_id:
  123. raise RuntimeStoreError("invalid_params")
  124. from gateway.session_busy_controls import authorize
  125. authorize(connection, ref, params, "session:control")
  126. authority = connection.authority
  127. live = authority.sessions[ref.session_id]
  128. from gateway.session_ancillary import physical_target
  129. target = physical_target(authority, ref)
  130. if not hasattr(authority, "viewer_automation"):
  131. authority.viewer_automation = {}
  132. authority.viewer_automation[ref.session_id] = connection
  133. runner = authority.runner
  134. home = Path(authority.profile_id)
  135. def run():
  136. from gateway.run import _profile_runtime_scope
  137. from gateway.session_commands import _session_workspace
  138. with _profile_runtime_scope(home), _session_workspace(runner, live.source):
  139. return invoke(runner, kind, target, call, args, kwargs)
  140. rows = lambda: tuple(authority.db.get_meta(f"{k}:{target}") for k in ("goal", "loop", "heartbeat"))
  141. # A "read" can still write: is_waiting / goal_blocks_tick clear a satisfied goal barrier.
  142. before = rows() if call in _READS else None
  143. # The judge and gates block for seconds: off the loop, with the caller's context (profile scope).
  144. result = await asyncio.to_thread(run)
  145. if kind == "heartbeat" and call in _WATCHDOG_CALLS and (call == "due_prompt" or result.get("value") is not None):
  146. # The CLI's watchdog runs from these on: from then on the gateway poller leaves the ticks to it.
  147. if not hasattr(authority, "viewer_heartbeat"):
  148. authority.viewer_heartbeat = {}
  149. authority.viewer_heartbeat[ref.session_id] = connection
  150. if before is None or rows() != before:
  151. # The classic CLI drives this session's automation: other viewers (Ink, Desktop) repaint from the event.
  152. from gateway.session_control_actions import publish
  153. publish(authority, ref.session_id)
  154. return result