session_local_title.py 4.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """Title-keyed local session selection, resolved read-only by the authority.
  2. ``hermes chat --resume <title>`` / ``-c <title> [--create-if-missing]`` used to open
  3. SessionDB in the client; the zero-writer client now sends the name and the owner
  4. applies the classic CLI rule (``hermes_cli.main._resolve_session_by_name_or_id``).
  5. """
  6. from __future__ import annotations
  7. from hermes_state_runtime import RuntimeStoreError
  8. def resolve_titled_session(authority, actor, name, *, missing_ok=False):
  9. """Exact session id first, then title (latest ``"<title> #N"`` continuation wins over
  10. the bare title), projected forward to the compression tip. Only a local session the
  11. actor may read is returned, or one a messaging lane took over from a local surface
  12. (``handed_off_ref``); a foreign or other non-local match is ``not_found`` so another
  13. principal's titles are never confirmed."""
  14. if not isinstance(name, str) or not name.strip():
  15. raise RuntimeStoreError('invalid_params')
  16. db = authority.db
  17. row = db.get_session(name)
  18. sid = row['id'] if row else db.resolve_session_by_title(name)
  19. tip = db.get_session(db.get_compression_tip(sid) or sid) if sid else None
  20. if tip is None:
  21. if missing_ok:
  22. return None
  23. raise RuntimeStoreError('not_found')
  24. from gateway.session_route_recovery import handed_off_ref
  25. moved = handed_off_ref(authority, tip['id'])
  26. try:
  27. if moved is not None:
  28. authority.authorize(actor, moved, 'session:read')
  29. return moved
  30. from gateway.session_local_migration import resolve_local_target
  31. ref = resolve_local_target(authority, actor, tip['id'])
  32. except RuntimeStoreError as exc:
  33. if exc.reason == 'permission_denied':
  34. raise RuntimeStoreError('not_found') from None
  35. raise
  36. return ref
  37. def resolve_latest_session(authority, actor, family, workspace=None):
  38. """The most recently active session of a surface family (``cli`` = classic CLI incl. its finite
  39. one-shot runs, ``tui``), scoped to ``workspace`` (git root / cwd) first and then global: the
  40. classic ``hermes -c`` / ``--resume latest`` rule (``hermes_cli.main._resolve_last_session``),
  41. applied by the owner so the client opens no database. Only a local session the actor may read
  42. counts; another principal's sessions are skipped, never confirmed."""
  43. from agent.session_source import CLI_FAMILY_SOURCES
  44. families = {'cli': sorted(CLI_FAMILY_SOURCES), 'tui': ['tui']}
  45. if family not in families or (workspace is not None and (not isinstance(workspace, str) or not workspace)):
  46. raise RuntimeStoreError('invalid_params')
  47. from gateway.session_local_migration import resolve_local_target
  48. # The owner's own rows are stored ``local``, with the family in ``created_source``.
  49. sources = [*families[family], 'local']
  50. for scope in ([workspace] if workspace else []) + [None]:
  51. # A launch stub (the CLI crashed or a resume failed before the first turn) is the newest row
  52. # and carries the surface from its insert. It has no messages and no admission, so it is never
  53. # "latest"; a session whose first prompt is admitted but not yet written still is.
  54. for row in authority.db.search_sessions(source=sources, local_created_sources=[family], limit=50,
  55. workspace_key=scope, skip_launch_stubs=True):
  56. tip = authority.db.get_compression_tip(row['id']) or row['id']
  57. try:
  58. return resolve_local_target(authority, actor, tip)
  59. except RuntimeStoreError as exc:
  60. if exc.reason not in {'permission_denied', 'not_found', 'profile_mismatch'}:
  61. raise
  62. raise RuntimeStoreError('not_found')
  63. def validate_title(title):
  64. from hermes_state import SessionDB
  65. try:
  66. cleaned = SessionDB.sanitize_title(title) if isinstance(title, str) else None
  67. except ValueError:
  68. cleaned = None
  69. if cleaned is None:
  70. raise RuntimeStoreError('invalid_params')
  71. return cleaned
  72. def title_new_session(authority, ref, title):
  73. """User-provenance title on a just-created local session (auto-titling never overwrites it).
  74. A concurrent creator that won the unique title is a conflict, not a silent orphan."""
  75. try:
  76. authority.db.set_session_title(ref.session_id, title)
  77. except ValueError:
  78. raise RuntimeStoreError('admission_conflict') from None