hermes_state_local_migration.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. """Transactional legacy binding; never a second transcript writer."""
  2. import functools
  3. import json
  4. import time
  5. from hermes_state_runtime import RuntimeStoreError, _json
  6. LEGACY_PREFIX = 'gateway.local_legacy.v1:'
  7. # Sources the pre-authority local CLI/TUI/GUI wrote. ``oneshot`` (finite ``chat -q`` / ``-z``) and ``tool``
  8. # (``chat --source tool``) are CLI runs that printed ``hermes --resume <id>``: adopted for resume like
  9. # ``cli`` and keeping their label, so human pickers still hide them (INTERNAL_LISTING_SOURCES).
  10. # ``desktop`` is the label main's Desktop stored; it is adopted as the ``gui`` creation source.
  11. # ``acp`` is main's in-process editor server (Zed, VS Code, JetBrains): adopted under its own source.
  12. LEGACY_LOCAL_SOURCES = frozenset({'cli', 'tui', 'gui', 'desktop', 'oneshot', 'tool', 'acp'})
  13. # Legacy labels that are not creation sources of their own (session_policy.SURFACES).
  14. LEGACY_CREATION_SOURCES = {'desktop': 'gui'}
  15. # Labels a routeless row can carry that never name a chat app: automation and recovery rows, a
  16. # retired platform, and a third-party WebUI that runs its own agent on this state.db (adopting its rows
  17. # would legitimise a second writer, so they stay read-only: gateway/session_history_mount.py).
  18. NOT_CLIENT_LABELS = frozenset({'cron', 'subagent', 'kanban', 'bot_room', 'a2a', 'webhook', 'api_server',
  19. 'import', 'recovered', 'curator', 'batch', 'homeassistant', 'webui',
  20. 'local', 'unknown'})
  21. @functools.lru_cache(maxsize=1)
  22. def _messaging_labels():
  23. """Every platform Hermes ships: the enum and the bundled platform plugins. A runtime-registered
  24. catalog plugin (hermes-mobile's ``mobile``) is not in it: its rows are routed, which excludes them."""
  25. from gateway.config import Platform
  26. bundled, aliases = Platform._scan_bundled_plugin_platforms()
  27. return frozenset({platform.value for platform in Platform} | set(bundled) | set(aliases))
  28. def not_client_labels():
  29. """Labels :func:`client_label` refuses, for queries that pre-filter rows."""
  30. return LEGACY_LOCAL_SOURCES | NOT_CLIENT_LABELS | _messaging_labels()
  31. def client_label(source):
  32. """Whether *source* is a client app's own label (``mobile``, ``ios``): not a local surface, a
  33. shipped messaging platform, or an automation / foreign-writer label."""
  34. return isinstance(source, str) and bool(source.strip()) and source not in not_client_labels()
  35. def client_history_row(row):
  36. """A chat a client app wrote under its own label before ``session.create`` took only surfaces.
  37. The pre-authority ``hermes serve`` stored whatever ``source`` a client sent, so phone apps signed
  38. in through the dashboard login left routeless rows labelled ``mobile``, ``ios`` and the like. They
  39. are the owner's Desktop-style chats: adopted as ``gui``. A routed row is never one, which keeps a
  40. plugin platform sharing the label (hermes-mobile registers ``mobile``) on its messaging route."""
  41. return client_label(row.get('source')) and not any(row.get(k) for k in ('session_key', 'chat_id', 'origin_json'))
  42. def legacy_history_row(row):
  43. """Whether resume adopts *row* as old local history: a local surface's label, or a client app's."""
  44. return row.get('source') in LEGACY_LOCAL_SOURCES or client_history_row(row)
  45. def legacy_creation_source(row):
  46. """The creation source an adopted legacy row resumes on (session_policy.SURFACES)."""
  47. return 'gui' if client_history_row(row) else LEGACY_CREATION_SOURCES.get(row['source'], row['source'])
  48. def legacy_account_label(row):
  49. # main's Desktop stamped the signed-in Nous account on its chats. That is a label, not a route or
  50. # an authenticated owner, so it does not block adoption of an otherwise unrouted Desktop row.
  51. user_id = row.get('user_id')
  52. return row['source'] == 'desktop' and isinstance(user_id, str) and user_id.startswith('nous:')
  53. def login_owned_by(row, subject):
  54. """Whether *subject* owns the login stamp a served dashboard put on this row.
  55. Older ``hermes serve`` builds stamped the WS-upgrade login as ``<provider>:<user id>``
  56. (tui_gateway/session_transports.py), and the gateway stored a Webapp login as its
  57. ``auth:v1:[...]`` subject. Hermes is single-user and sign-in is owner-only, so both name the
  58. machine owner: the host owner's subject adopts them (gateway.owner_identity.same_owner).
  59. """
  60. user_id = row.get('user_id')
  61. if not isinstance(user_id, str) or not subject:
  62. return False
  63. from gateway.owner_identity import same_owner
  64. return same_owner(user_id, subject)
  65. def validate_legacy_row(db, row, *, subject=None):
  66. # Unrouted old local history only. Existing identity, foreign profile,
  67. # API, messaging, delegate and canonical rows require their own authority.
  68. # ``subject``: the adopting caller, whose own login stamp is not a foreign identity. A ``user_id``
  69. # stamp equal to ``subject`` itself names that principal: it is already its history by
  70. # ``authorize_history``'s rule, so it adopts like an unstamped row.
  71. user_id = row.get('user_id')
  72. if (not legacy_history_row(row)
  73. or any(row.get(k) for k in ('session_key', 'chat_id', 'origin_json'))
  74. or (user_id and not legacy_account_label(row) and not login_owned_by(row, subject))
  75. or row.get('profile_name') not in (None, '', db._own_profile_name() or 'default')):
  76. raise RuntimeStoreError('not_found')
  77. def bind_legacy_target(db, conn, receipt):
  78. target = receipt['legacy_session_id']
  79. if target != receipt['session_id']:
  80. raise RuntimeStoreError('storage_unavailable')
  81. row = conn.execute('SELECT * FROM sessions WHERE id=?', (target,)).fetchone()
  82. if row is None:
  83. raise RuntimeStoreError('not_found')
  84. validate_legacy_row(db, dict(row), subject=receipt['principal_id'])
  85. from hermes_state_mutation_binding import BINDING_PREFIX, binding_names
  86. imported = conn.execute('SELECT value FROM state_meta WHERE key=?', (BINDING_PREFIX + target,)).fetchone()
  87. if imported and not binding_names(imported[0], receipt['profile_id'], receipt['principal_id']):
  88. raise RuntimeStoreError('permission_denied')
  89. from hermes_state_compression import _CHAIN_STEP_SQL
  90. if conn.execute(_CHAIN_STEP_SQL, (target,)).fetchone() is not None:
  91. raise RuntimeStoreError('admission_conflict')
  92. from hermes_state_mutation_guards import require_idle
  93. require_idle(db, conn, [target])
  94. root = db._session_turn_lease_key_on_conn(conn, target)
  95. if conn.execute('SELECT 1 FROM session_turn_leases WHERE conversation_id=? AND expires_at>?',
  96. (root, time.time())).fetchone():
  97. raise RuntimeStoreError('runtime_coordination_required')
  98. key = LEGACY_PREFIX + target
  99. if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (key,)).fetchone():
  100. raise RuntimeStoreError('storage_unavailable')
  101. source = receipt['entry']['origin']
  102. # Binding is a read-side claim: the row keeps main's ``source`` label and its end stamp. The first
  103. # admitted turn reopens it (``reopen_local_session``), exactly as the classic surfaces did. A client
  104. # app's own label is the exception: bound, the row has a route, so the label alone would read it as
  105. # a messaging chat; it becomes the Desktop chat it resumes as (``created_source`` keeps provenance).
  106. label = 'desktop' if client_history_row(dict(row)) else row['source']
  107. conn.execute('UPDATE sessions SET source=?,session_key=?,chat_id=?,user_id=?,chat_type=?,origin_json=? WHERE id=?',
  108. (label, receipt['route'], receipt['session_id'], receipt['principal_id'], 'dm', _json(source), target))
  109. conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, _json({
  110. 'session_id': receipt['session_id'], 'profile_id': receipt['profile_id'],
  111. 'principal_id': receipt['principal_id'], 'legacy_session_id': target})))
  112. def legacy_lineage_root(conn, receipt):
  113. root = receipt.get('legacy_session_id', receipt['session_id'])
  114. if 'legacy_session_id' in receipt:
  115. if root != receipt['session_id']:
  116. raise RuntimeStoreError('storage_unavailable')
  117. row = conn.execute('SELECT value FROM state_meta WHERE key=?', (LEGACY_PREFIX + root,)).fetchone()
  118. expected = {k: receipt[k] for k in ('session_id', 'profile_id', 'principal_id', 'legacy_session_id')}
  119. if row is None or json.loads(row[0]) != expected:
  120. raise RuntimeStoreError('storage_unavailable')
  121. return root