hermes_state_mutations.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. """Closed action handlers inside the runtime mutation receipt transaction."""
  2. import time
  3. from hermes_state_runtime import RuntimeStoreError
  4. METADATA_FIELDS = {'title': str, 'archived': bool, 'hidden': bool, 'pinned': bool, 'unread': bool}
  5. def validate_action(operation, payload):
  6. if not isinstance(payload, dict) or not isinstance(operation, str):
  7. raise RuntimeStoreError('invalid_params')
  8. # ``confirm``: the owner's selection-guard token for this exact resolved target (session_mutation_model).
  9. # ``reasoning``: a level picked with the model, committed in the same selection.
  10. if (operation == 'model' and 'model' in payload and not set(payload) - {'model', 'provider', 'confirm', 'reasoning'}
  11. and all(isinstance(v, str) and v.strip() for v in payload.values())):
  12. from hermes_constants import parse_reasoning_effort
  13. if 'reasoning' not in payload or parse_reasoning_effort(payload['reasoning']) is not None:
  14. return
  15. if operation == 'branch' and _valid_branch_payload(payload):
  16. return
  17. # Session-scope ``/reasoning <level>`` and Desktop's Move to project: revision-fenced edits of
  18. # the frozen policy (gateway/session_mutation_policy.py).
  19. if operation == 'reasoning' and set(payload) == {'effort'} and payload['effort'] is None:
  20. return # ``/reasoning reset``: the session's level goes back to the profile
  21. if operation == 'reasoning' and set(payload) == {'effort'} and isinstance(payload['effort'], str):
  22. from hermes_constants import parse_reasoning_effort
  23. if parse_reasoning_effort(payload['effort']) is not None:
  24. return
  25. if operation == 'workspace' and set(payload) == {'cwd'} and isinstance(payload['cwd'], str) and payload['cwd'].strip():
  26. return
  27. # The editor's MCP servers (gateway/session_local_mcp.py): the owner keeps the list in memory and
  28. # hands the store only its fingerprint, so no transport credential reaches a receipt.
  29. if operation == 'editor_mcp' and set(payload) == {'mcp_servers'} and _valid_editor_fingerprint(payload):
  30. return
  31. # An ACP session's edit approval policy (gateway/session_mutation_policy.py prepare_edit_policy).
  32. if (operation == 'edit_policy' and set(payload) == {'policy'} and isinstance(payload['policy'], str)
  33. and payload['policy'] in {'ask', 'workspace_session', 'session'}):
  34. return
  35. if operation == 'compress' and _valid_compress_payload(payload):
  36. return
  37. if operation in {'delete', 'reset'} and not payload:
  38. return
  39. if operation == 'import' and set(payload) == {'sessions'} and isinstance(payload['sessions'], list):
  40. return
  41. if (operation == 'rewind' and 'target_message_id' in payload
  42. and not set(payload) - {'target_message_id', 'preserve_compaction_handoff'}
  43. and type(payload['target_message_id']) is int and payload['target_message_id'] > 0
  44. and type(payload.get('preserve_compaction_handoff', False)) is bool):
  45. return
  46. required = {'rename': {'title'}, 'archive': {'archived'}}
  47. if operation == 'sidebar':
  48. valid = bool(payload) and not set(payload) - METADATA_FIELDS.keys()
  49. else:
  50. valid = operation in required and set(payload) == required[operation]
  51. if not valid or any(type(value) is not METADATA_FIELDS[key] for key, value in payload.items()):
  52. raise RuntimeStoreError('invalid_params')
  53. def _valid_branch_payload(payload):
  54. # ``through_message_id``: the physical row id of the last message the branch keeps (a stable
  55. # boundary, never a visible-message count); absent means the whole active transcript.
  56. if set(payload) - {'title', 'through_message_id', 'mcp_servers'}:
  57. return False
  58. if 'mcp_servers' in payload and not _valid_editor_fingerprint(payload):
  59. return False
  60. if 'title' in payload and not isinstance(payload['title'], str):
  61. return False
  62. return 'through_message_id' not in payload or (
  63. type(payload['through_message_id']) is int and payload['through_message_id'] > 0)
  64. def _valid_editor_fingerprint(payload):
  65. servers = payload['mcp_servers']
  66. return isinstance(servers, dict) and set(servers) == {'fingerprint'} and isinstance(servers['fingerprint'], str)
  67. _COMPRESS_FIELDS = {'focus': str, 'preview': bool, 'partial': bool, 'keep_last': int}
  68. def _valid_compress_payload(payload):
  69. # ``focus`` alone may still be the raw ``/compress`` argument string (Ink/Desktop
  70. # clients); the structured flags come from the shared parser on the native CLI/ACP path.
  71. if set(payload) - _COMPRESS_FIELDS.keys():
  72. return False
  73. if any(type(value) is not _COMPRESS_FIELDS[key] for key, value in payload.items()):
  74. return False
  75. return 'keep_last' not in payload or (payload.get('partial') is True and payload['keep_last'] >= 1)
  76. def apply_action(db, conn, session_id, operation, payload, *, prepared=None):
  77. if operation == 'compress':
  78. from hermes_state_mutation_compress import compress_in_transaction
  79. return compress_in_transaction(db, conn, session_id, payload, prepared)
  80. if operation in {'model', 'reasoning', 'workspace', 'editor_mcp', 'edit_policy'}:
  81. from hermes_state_mutation_prepared import POLICY_HANDLERS
  82. return POLICY_HANDLERS[operation](db, conn, session_id, payload, prepared)
  83. if operation == 'branch':
  84. from hermes_state_mutation_branch import branch_in_transaction
  85. return branch_in_transaction(db, conn, session_id, payload, prepared)
  86. from hermes_state_mutation_reset import reset_in_transaction
  87. handlers = {'delete': _delete, 'import': _import, 'rewind': _rewind, 'reset': reset_in_transaction}
  88. if operation in handlers:
  89. return handlers[operation](db, conn, session_id, payload)
  90. affected = set()
  91. result = {}
  92. for key, value in payload.items():
  93. if key == 'title':
  94. affected.update(db._set_session_title_in_transaction(
  95. conn, session_id, value, source=db.TITLE_SOURCE_USER))
  96. result[key] = conn.execute('SELECT title FROM sessions WHERE id=?', (session_id,)).fetchone()[0]
  97. else:
  98. column = 'last_read_at' if key == 'unread' else key
  99. stored = (0.0 if value else time.time()) if key == 'unread' else int(value)
  100. affected.update(db._set_lineage_column_in_transaction(conn, column, session_id, stored))
  101. result[key] = value
  102. return affected, result
  103. def _delete(db, conn, session_id, payload):
  104. # Terminal admission/worker rows become digest tombstones so exact retries and
  105. # adoption checks still resolve after the transcript is gone.
  106. from hermes_state_mutation_retirement import delete_in_transaction
  107. return delete_in_transaction(db, conn, session_id, payload)
  108. def _rewind(db, conn, session_id, payload):
  109. from hermes_state_mutation_guards import require_idle
  110. from hermes_state_mutation_transcript import rewind_in_transaction
  111. from hermes_state_local_lineage import local_physical_target
  112. physical = local_physical_target(conn, session_id)
  113. require_idle(db, conn, list({session_id, physical}))
  114. # The client names the row: like a branch boundary it must be an active row of the physical
  115. # target. A row compaction archived (still shown, still carrying its id) would deactivate the
  116. # summary and every later turn, since both have larger ids. That refusal says so (``compacted:``
  117. # detail); a row a rewind or undo already took back, an assistant row or an unknown id does not.
  118. row = conn.execute('SELECT role FROM messages WHERE id=? AND session_id=? AND active=1',
  119. (payload['target_message_id'], physical)).fetchone()
  120. if row is None or row['role'] != 'user':
  121. if _summarized_by_compaction(conn, physical, payload['target_message_id']):
  122. raise RuntimeStoreError('invalid_params', field='target_message_id', detail=COMPACTED_TARGET_DETAIL)
  123. raise RuntimeStoreError('invalid_params', field='target_message_id',
  124. detail='target user message is no longer in session history')
  125. # A composite compaction carrier (summary + the next ask in one row) keeps its handoff, as
  126. # main's rewind does; the receipt reports the live ask, so /retry resubmits it, not the summary.
  127. live = _carrier_live_view(db, conn, physical, payload['target_message_id'])
  128. target, ids, head, replacement = rewind_in_transaction(db, conn, physical, payload['target_message_id'],
  129. preserve_compaction_handoff=live is not None or payload.get('preserve_compaction_handoff', False))
  130. # Receipts are JSON: publish the same public message shape get_messages() returns (decoded
  131. # content/tool_calls, no internal display_identity BLOB / display_order).
  132. target = db._row_to_message_dict(target, warn_context='rewind receipt', summary_flag=True)
  133. if live is not None:
  134. target['content'] = live.get('content')
  135. from agent.message_metadata import typed_prompt_content # /retry, /undo: the typed ask, not the placeholder
  136. target['content'] = typed_prompt_content(target.get('content'), target)
  137. conn.execute('UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id=?', (session_id,))
  138. return {session_id, physical}, {'rewound_count': len(ids), 'target_message': target,
  139. 'new_head_id': head, 'replacement_message_id': replacement}
  140. # The refusal's ``detail`` for a target compaction summarized: ``compacted:`` is the machine-readable
  141. # prefix clients match (Desktop's restore/edit toast); the rest is the log line.
  142. COMPACTED_TARGET_DETAIL = 'compacted: target user message was summarized when the session was compressed'
  143. def _summarized_by_compaction(conn, physical, message_id):
  144. """Whether *message_id* is a user turn compaction took out of *physical*'s live transcript, as
  145. opposed to one a rewind/undo deactivated, an assistant row, or no row at all. In-place compaction
  146. archives with ``active=0, compacted=1`` (``_ARCHIVE_ACTIVE_SQL``) while rewind, undo and replace
  147. mark ``active=0, compacted=0``; a rotating compaction leaves the turn on a compression ancestor of
  148. *physical*, still displayed (``active=1 OR compacted=1``)."""
  149. row = conn.execute('SELECT session_id, role, active, compacted FROM messages WHERE id=?',
  150. (message_id,)).fetchone()
  151. if row is None or row['role'] != 'user':
  152. return False
  153. if row['session_id'] == physical:
  154. return row['active'] == 0 and row['compacted'] == 1
  155. if not (row['active'] == 1 or row['compacted'] == 1):
  156. return False
  157. from hermes_state_sessions import _expand_compression_lineage_ids
  158. from hermes_state_compression import _CHAIN_CAP
  159. lineage, frontier = {physical}, [physical]
  160. for _ in range(_CHAIN_CAP):
  161. frontier = [sid for sid in _expand_compression_lineage_ids(conn, frontier) if sid not in lineage]
  162. if not frontier:
  163. break
  164. lineage.update(frontier)
  165. return row['session_id'] in lineage
  166. def _carrier_live_view(db, conn, session_id, message_id):
  167. from agent.context_compressor import split_user_originated_turn
  168. row = conn.execute('SELECT * FROM messages WHERE id=? AND session_id=? AND active=1',
  169. (message_id, session_id)).fetchone()
  170. message = row and db._row_to_message_dict(row, warn_context='rewind target', summary_flag=True)
  171. handoff, live = split_user_originated_turn(message) if message else (None, None)
  172. return live if handoff is not None else None
  173. def _import(db, conn, session_id, payload):
  174. rows = payload['sessions']
  175. if len(rows) > db._IMPORT_MAX_SESSIONS:
  176. raise RuntimeStoreError('invalid_params')
  177. normalized, errors = db._validate_import_payload(rows)
  178. if errors or not normalized or session_id != normalized[0]['session']['id']:
  179. raise RuntimeStoreError('invalid_params')
  180. imported, skipped, parents = [], [], []
  181. for item in normalized:
  182. raw = item['session']
  183. sid = raw['id']
  184. from hermes_state_mutation_retirement import RETIRED_PREFIX
  185. if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (RETIRED_PREFIX + sid,)).fetchone():
  186. # Refused by name at import time: a row restored beside the fence would refuse every turn.
  187. raise RuntimeStoreError('admission_conflict', field='sessions',
  188. detail=f'session {sid} was deleted here; a deleted session is not restored')
  189. if conn.execute('SELECT 1 FROM sessions WHERE id=?', (sid,)).fetchone():
  190. skipped.append(sid)
  191. continue
  192. db._import_session_row(conn, raw, item['messages'], sid)
  193. if raw.get('parent_session_id'):
  194. parents.append((sid, raw['parent_session_id']))
  195. imported.append(sid)
  196. # A parent outside this payload is kept only when it is history this importer already
  197. # controls: its import binding equals the child's (written by import_history_control in this
  198. # transaction). Linking under any other row would graft the import onto a foreign chain,
  199. # which a later chain-aware delete of the import would then remove.
  200. from hermes_state_mutation_binding import history_binding
  201. # Rows imported now, not payload ids: a payload naming an existing foreign id skips that row.
  202. fresh = set(imported)
  203. foreign = [(sid, parent) for sid, parent in parents if parent not in fresh and (
  204. history_binding(conn, parent) is None or history_binding(conn, parent) != history_binding(conn, sid))]
  205. parents = [link for link in parents if link not in foreign]
  206. detached = db._attach_import_parents(conn, parents) + len(foreign)
  207. return set(imported), {'ok': True, 'imported': len(imported), 'skipped': len(skipped),
  208. 'imported_ids': imported, 'skipped_ids': skipped, 'detached': detached, 'errors': []}