gateway_mutations.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. """Prepared native controls retain their identity across ambiguous RPC replies."""
  2. import json
  3. import uuid
  4. from hermes_cli.gateway_client import COMPRESS_RPC_TIMEOUT, GatewayClientError
  5. class PreparedMutations:
  6. def __init__(self):
  7. self.pending = {}
  8. async def apply(self, client, session_id, operation, payload, *, confirm=None):
  9. """The owner's answer for this prepared mutation (retained across ambiguous replies).
  10. A guarded model target answers ``status: confirmation_required`` and writes nothing.
  11. ``confirm`` (``async (refusal) -> bool``) is the surface's prompt: yes re-sends the same
  12. retained mutation once with ``payload.confirm`` = the owner's token (under the original
  13. key, so an ambiguous reply to the confirmed send retries that exact request); no answers
  14. ``status: cancelled``. Without a prompt (non-interactive) the refusal is an error, and a
  15. confirmed send refused again (another switch or a turn landed first) is never re-asked.
  16. ``payload`` may be a function of the snapshot the CAS tuple is read from (a rewind names
  17. its target row from that same transcript); returning None means "nothing to do" and is
  18. answered ``status: nothing``. A derived payload is keyed by operation alone, so a lost-reply
  19. retry re-presents the original target instead of re-deriving one from an already-rewound
  20. transcript. Metadata edits (``rename``) carry no generation fence, as on Ink/Desktop."""
  21. key = _key(session_id, operation, payload)
  22. self.retire(session_id, keep=key)
  23. if key not in self.pending:
  24. snapshot = await client.rpc('session.resume', session_id=session_id)
  25. body = payload(snapshot) if callable(payload) else json.loads(key[2])
  26. if body is None:
  27. return {'status': 'nothing', 'session_id': session_id, 'operation': operation}
  28. fence = {} if operation in _METADATA else {'expected_generation': snapshot['execution_generation']}
  29. self.pending[key] = {'params': dict(session_id=session_id, operation=operation, payload=body,
  30. request_id=uuid.uuid4().hex, expected_revision=snapshot['revision'], **fence)}
  31. entry = self.pending[key]
  32. while 'result' not in entry:
  33. try:
  34. # A compression answers after its summary + commit; the default budget would report
  35. # a timeout while the owner (which shields the mutation) still commits it.
  36. budget = {'_timeout': COMPRESS_RPC_TIMEOUT} if operation == 'compress' else {}
  37. entry['result'] = await client.rpc('session.mutate', **budget, **entry['params'])
  38. except GatewayClientError as exc:
  39. # A disconnect is not a definitive authority refusal. Preserve
  40. # the tuple; never refresh its preconditions behind the user.
  41. if str(exc) in {'invalid_params', 'revision_conflict', 'stale_generation',
  42. 'session_busy', 'unknown_execution', 'permission_denied',
  43. 'model_resolution_failed', 'nothing_to_compress',
  44. 'unsupported_compress_options'}:
  45. self.pending.pop(key)
  46. raise
  47. refusal = entry['result']
  48. if refusal.get('status') != 'confirmation_required':
  49. break
  50. # The owner wrote nothing (no receipt): the same tuple may be re-sent with the token.
  51. del entry['result']
  52. if confirm is None or 'confirm' in entry['params']['payload']:
  53. self.pending.pop(key)
  54. raise GatewayClientError(model_refusal_text(refusal, confirmed=confirm is not None))
  55. try:
  56. accepted = await confirm(refusal)
  57. except BaseException:
  58. self.pending.pop(key)
  59. raise
  60. if not accepted:
  61. self.pending.pop(key)
  62. return {'status': 'cancelled', 'session_id': session_id, 'operation': operation}
  63. entry['params'] = {**entry['params'], 'request_id': uuid.uuid4().hex,
  64. 'payload': {**entry['params']['payload'], 'confirm': refusal['confirm']}}
  65. return entry['result']
  66. def acknowledge(self, session_id, operation, payload):
  67. self.pending.pop(_key(session_id, operation, payload), None)
  68. def retire(self, session_id, *, keep=None):
  69. """Only a session's very next control may be the retry of an ambiguous one: any other verb
  70. on the session (a different control, a prompt) retires its retained identities, so a later
  71. deliberate repeat is new work instead of replaying a stale receipt."""
  72. for key in [key for key in self.pending if key[0] == session_id and key != keep]:
  73. del self.pending[key]
  74. _METADATA = frozenset({'rename'})
  75. def _key(session_id, operation, payload):
  76. return (session_id, operation, None if callable(payload) else json.dumps(payload, sort_keys=True))
  77. def model_refusal_text(refusal, *, confirmed=False):
  78. """Why a guarded model target was not applied (the owner's guard text first)."""
  79. reason = ('the session changed before the confirmation landed; run /model again.' if confirmed else
  80. 'this target needs a confirmation; run /model in an interactive session to confirm it.')
  81. return f"{refusal['confirm_message']}\n\nModel not switched: {reason}"
  82. def confirmation_title(refusal):
  83. """The one prompt title for the owner's guard warnings (as ``combined_selection_warning``)."""
  84. warnings = refusal.get('warnings') or []
  85. return warnings[0]['title'] if len(warnings) == 1 else 'Model Selection Warning'
  86. def confirm_choice(raw, choices):
  87. """``once`` / ``cancel`` (or None) for a typed answer: the choice's number or the classic
  88. CLI's confirm aliases (y/yes/once, n/no/cancel)."""
  89. from hermes_cli.cli_modal_mixin import _CONFIRM_ALIASES
  90. answer = (raw or '').strip().lower()
  91. if answer.isdigit() and 0 < int(answer) <= len(choices):
  92. return choices[int(answer) - 1][0]
  93. allowed = {choice[0] for choice in choices}
  94. normalized = _CONFIRM_ALIASES.get(answer, answer)
  95. return normalized if normalized in allowed else None
  96. def compress_payload(arg):
  97. """Structured ``session.mutate(compress)`` payload from the raw ``/compress`` arguments.
  98. The shared parser is the one every native surface uses, so ``--preview`` stays a read-only
  99. flag and ``here [N]`` a boundary instead of becoming a focus topic; ``--aggressive`` has no
  100. canonical implementation and is refused before anything reaches the authority.
  101. """
  102. from agent.conversation_compression_manual import AGGRESSIVE_UNSUPPORTED, parse_compress_args
  103. request = parse_compress_args(arg)
  104. if request.aggressive:
  105. raise GatewayClientError(AGGRESSIVE_UNSUPPORTED)
  106. payload = {}
  107. if request.focus_topic:
  108. payload['focus'] = request.focus_topic
  109. if request.preview:
  110. payload['preview'] = True
  111. if request.partial:
  112. payload.update(partial=True, keep_last=request.keep_last)
  113. return payload
  114. def slash_mutation(command, arg):
  115. name = command.lstrip('/')
  116. if name == 'model':
  117. from hermes_cli.model_switch import parse_model_flags_detailed
  118. parsed = parse_model_flags_detailed(arg)
  119. if parsed.is_global or parsed.is_once or parsed.force_refresh or not parsed.model_input:
  120. raise GatewayClientError('unsupported_model_options')
  121. return name, {'model': parsed.model_input, **(
  122. {'provider': parsed.explicit_provider} if parsed.explicit_provider else {})}
  123. if name == 'compress':
  124. return name, compress_payload(arg)
  125. if name != 'branch':
  126. raise GatewayClientError('unsupported_command')
  127. return name, {'title': arg} if arg else {}