session_pending_controls.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """Generation-bound projection/control of the existing blocking approval queue.
  2. Ordinary approvals and clarify prompts share the existing native waiters.
  3. Secret/sudo prompts remain native; no response is published or journaled here.
  4. """
  5. from copy import deepcopy
  6. from hermes_state_runtime import RuntimeStoreError
  7. from tools.approval import list_gateway_approvals, resolve_gateway_approval
  8. class PendingControls:
  9. def __init__(self, events):
  10. self.events = events
  11. self.pending = {}
  12. self.remote_responders = {}
  13. def register(self, session_id, route, generation, data, *, timeout_s=None):
  14. from gateway.run import _redact_approval_command
  15. with self.events.lock:
  16. prompt_id = data['request_id']
  17. choices = ['once', 'deny']
  18. if data.get('allow_session', True) and not data.get('smart_denied', False):
  19. choices.append('session')
  20. if data.get('allow_permanent', True) and not data.get('smart_denied', False):
  21. choices.append('always')
  22. prompt = {'kind': 'approval', 'prompt_id': prompt_id,
  23. 'execution_generation': generation,
  24. 'command': _redact_approval_command(data.get('command', '')),
  25. 'description': _redact_approval_command(data.get('description', '')),
  26. 'choices': choices}
  27. if 'edit' in data:
  28. prompt['edit'] = deepcopy(data['edit'])
  29. prompt['choices'] = ['once', 'deny']
  30. if timeout_s is not None:
  31. prompt['timeout_s'] = timeout_s
  32. self.pending[prompt_id] = (route, prompt)
  33. self.events.publish(session_id, prompt, event_type='approval.request')
  34. def register_clarify(self, session_id, generation, entry, *, timeout_s=None):
  35. from gateway.run import _redact_approval_command
  36. with self.events.lock:
  37. prompt = {"kind": "clarify", "prompt_id": entry.clarify_id,
  38. "execution_generation": generation,
  39. "question": _redact_approval_command(entry.question),
  40. "choices": [_redact_approval_command(c) for c in entry.choices or []],
  41. "multi_select": entry.multi_select}
  42. if timeout_s is not None:
  43. prompt["timeout_s"] = timeout_s
  44. self.pending[entry.clarify_id] = (entry, prompt)
  45. self.events.publish(session_id, prompt, event_type="clarify.request")
  46. def snapshot(self, session_id, generation):
  47. with self.events.lock:
  48. for prompt_id, (route, prompt) in list(self.pending.items()):
  49. active = (prompt_id in self.remote_responders or
  50. (not route.event.is_set() if prompt['kind'] == 'clarify' else
  51. any(p['request_id'] == prompt_id for p in list_gateway_approvals(route))))
  52. if prompt['execution_generation'] != generation or not active:
  53. del self.pending[prompt_id]
  54. self.remote_responders.pop(prompt_id, None)
  55. self.events.publish(session_id, {'prompt_id': prompt_id,
  56. 'execution_generation': prompt['execution_generation']}, event_type=prompt['kind'] + '.settled')
  57. return tuple(deepcopy(prompt) for _, prompt in self.pending.values())
  58. def respond(self, session_id, generation, prompt_id, response, *, kind="approval"):
  59. with self.events.lock:
  60. self.snapshot(session_id, generation)
  61. entry = self.pending.get(prompt_id)
  62. if entry is None:
  63. return {'status': 'already_resolved', 'prompt_id': prompt_id}
  64. route, prompt = entry
  65. if prompt['kind'] != kind:
  66. raise RuntimeStoreError('invalid_params')
  67. if prompt_id in self.remote_responders:
  68. field = 'answer' if kind == 'clarify' else 'choice'
  69. if (not isinstance(response, dict) or set(response) != {field}
  70. or not isinstance(response[field], str) or len(response[field]) > 16384
  71. or (kind == 'approval' and response[field] not in prompt['choices'])):
  72. raise RuntimeStoreError('invalid_params')
  73. self.remote_responders[prompt_id](kind, prompt_id, response[field])
  74. del self.remote_responders[prompt_id]
  75. del self.pending[prompt_id]
  76. self.events.publish(session_id, {'prompt_id': prompt_id, 'execution_generation': generation},
  77. event_type=kind + '.settled')
  78. return {'status': 'resolved', 'prompt_id': prompt_id}
  79. if kind == 'clarify':
  80. from tools.clarify_gateway import resolve_gateway_clarify
  81. if (not isinstance(response, dict) or set(response) != {'answer'}
  82. or not isinstance(response['answer'], str)):
  83. raise RuntimeStoreError('invalid_params')
  84. resolved = resolve_gateway_clarify(prompt_id, response['answer'])
  85. self.snapshot(session_id, generation)
  86. return {'status': 'resolved' if resolved else 'already_resolved', 'prompt_id': prompt_id}
  87. if not isinstance(response, dict) or set(response) != {'choice'} or response['choice'] not in prompt['choices']:
  88. raise RuntimeStoreError('invalid_params')
  89. # The tools lock arbitrates native taps versus attached responders;
  90. # an exact request ID can never consume the next FIFO approval.
  91. resolved = resolve_gateway_approval(route, response['choice'], request_id=prompt_id)
  92. self.snapshot(session_id, generation)
  93. return {'status': 'resolved' if resolved else 'already_resolved', 'prompt_id': prompt_id}