sessions_adopt.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. """``hermes sessions adopt``: bring this profile's pre-gateway history under its gateway, as the host.
  2. Since #106742 the profile's gateway owns its sessions. Chats written before that (main's CLI, TUI and
  3. Desktop rows) carry no gateway receipt until one native, same-OS-user client resumes them, which
  4. adopts them (``gateway/session_local_migration.py::adopt_legacy_session``). A Webapp browser reaches
  5. the gateway through its dashboard mount as the login it authenticated, never natively, so it may not
  6. make that first claim. Run this once on the host instead: it is what opening each old chat in the
  7. native TUI or Desktop would do, and afterwards the browser continues every adopted chat through
  8. shared operator access.
  9. """
  10. from __future__ import annotations
  11. from collections import Counter
  12. import sqlite3
  13. import sys
  14. _PROGRESS_EVERY = 25
  15. def adoptable_sessions(path) -> list[dict]:
  16. """This store's unadopted pre-gateway local chats: one compression tip each, oldest first.
  17. The same eligibility the owner applies on resume (``validate_legacy_row``), read-only, so the
  18. count a dry run reports is what an adoption run attempts. A row the owner already bound is not
  19. offered again, which makes a second run a no-op."""
  20. from hermes_state import SessionDB
  21. from gateway.owner_identity import host_owner_subject
  22. from hermes_state_local import POLICY_PREFIX
  23. from hermes_state_local_migration import LEGACY_LOCAL_SOURCES, LEGACY_PREFIX, not_client_labels, validate_legacy_row
  24. from hermes_state_runtime import RuntimeStoreError
  25. db = SessionDB(db_path=path, read_only=True)
  26. try:
  27. # Local surfaces' labels, or any label a client app chose (not a platform, automation or
  28. # foreign writer): validate_legacy_row judges each row; the filter keeps cron/subagent bulk out.
  29. local = tuple(sorted(LEGACY_LOCAL_SOURCES))
  30. refused = tuple(sorted(not_client_labels()))
  31. with db._read_ctx() as conn:
  32. ids = [row[0] for row in conn.execute(
  33. f"SELECT id FROM sessions WHERE source IN ({','.join('?' * len(local))})"
  34. f" OR (source NOT IN ({','.join('?' * len(refused))}) AND ifnull(session_key,'')=''"
  35. " AND ifnull(chat_id,'')='' AND ifnull(origin_json,'')='') ORDER BY started_at, id",
  36. local + refused)]
  37. bound = {row[0] for row in conn.execute(
  38. 'SELECT key FROM state_meta WHERE key LIKE ? OR key LIKE ?', (POLICY_PREFIX + '%', LEGACY_PREFIX + '%'))}
  39. found, seen = [], set()
  40. for sid in ids:
  41. tip_id = db.get_compression_tip(sid) or sid
  42. if tip_id in seen:
  43. continue
  44. seen.add(tip_id)
  45. tip = db.get_session(tip_id)
  46. key = tip and (tip.get('chat_id') or tip_id)
  47. if tip is None or POLICY_PREFIX + key in bound or LEGACY_PREFIX + key in bound:
  48. continue
  49. try:
  50. # The host runs this command: judge each row for the owner the adoption resumes as, so a
  51. # chat a phone app stored under the dashboard login (``basic:admin``) is offered too.
  52. validate_legacy_row(db, tip, subject=host_owner_subject())
  53. except RuntimeStoreError:
  54. continue
  55. found.append(tip)
  56. return found
  57. finally:
  58. db.close()
  59. async def adopt_sessions(rows, *, report=print) -> tuple[int, Counter]:
  60. """Resume each row once over this host's native connection (the owner adopts it), then detach
  61. without ending it. ``(adopted, skipped-by-refusal)``; a row the owner refuses is skipped,
  62. never retried as another principal."""
  63. from hermes_cli.gateway_client import GatewayRPCError, connect_gateway
  64. from hermes_cli.web_server_boundary import _DESKTOP_ATTACHMENT_WS_MAX_BYTES
  65. adopted, skipped = 0, Counter()
  66. # The owner answers a resume with the session's whole history; a long chat outgrows the default frame.
  67. async with connect_gateway(max_size=_DESKTOP_ATTACHMENT_WS_MAX_BYTES) as client:
  68. for done, row in enumerate(rows, 1):
  69. try:
  70. snapshot = await client.rpc('session.resume', session_id=row['id'])
  71. except GatewayRPCError as exc:
  72. skipped[_refusal(exc)] += 1
  73. continue
  74. await client.rpc('session.detach', session_id=snapshot.get('session_id') or row['id'],
  75. subscription_id=snapshot['subscription_id'])
  76. adopted += 1
  77. if done % _PROGRESS_EVERY == 0:
  78. report(f' {done}/{len(rows)} …')
  79. return adopted, skipped
  80. _SKIP_HINTS = {
  81. 'launch_credentials_unavailable': 'its saved model route is gone; open it once and pick a model',
  82. 'not_found': 'not adoptable here (another identity or profile owns it)',
  83. }
  84. def _refusal(exc) -> str:
  85. """One owner refusal as the report prints it: the reason code, then why. A field-level refusal
  86. (a launch directory that no longer exists) names the field and the owner's bounded detail."""
  87. reason, field, detail = str(exc), exc.data.get('field'), exc.data.get('detail')
  88. why = _SKIP_HINTS.get(reason) or (f'{field}: {detail}' if field and detail else 'refused by the gateway')
  89. return f'{reason} ({why})'
  90. def _unreadable_store(exc: sqlite3.Error, store: str) -> str:
  91. """One line for a store adopt cannot read: what is wrong and what to run. Adopt opens the store
  92. read-only, so it neither upgrades a store from an older release nor waits out another writer."""
  93. from hermes_state_errors import is_sqlite_lock_error
  94. from hermes_state_repair import _schema_not_built
  95. if is_sqlite_lock_error(exc):
  96. return f'Error: {store} is locked by another program. Close that program, then run this command again.'
  97. if _schema_not_built(exc):
  98. return (f'Error: {store} is from an older Hermes and has not been upgraded ({exc}). Run '
  99. '`hermes sessions repair` to upgrade it (it makes a backup first), then run this command again.')
  100. return f'Error: could not read {store} ({exc}). Run `hermes sessions repair` to check it.'
  101. def cmd_adopt(args) -> int:
  102. import asyncio
  103. from websockets.exceptions import WebSocketException
  104. from hermes_cli.gateway_client import GatewayClientError
  105. from hermes_constants import display_hermes_home, get_hermes_home
  106. path = get_hermes_home() / 'state.db'
  107. if not path.exists():
  108. print(f'No session database at {display_hermes_home()}/state.db (nothing to adopt).')
  109. return 0
  110. try:
  111. rows = adoptable_sessions(path)
  112. except sqlite3.Error as exc:
  113. print(_unreadable_store(exc, f'{display_hermes_home()}/state.db'), file=sys.stderr)
  114. return 1
  115. if not rows:
  116. print('Nothing to adopt: every local chat in this profile already belongs to its gateway.')
  117. return 0
  118. counts = Counter(row['source'] for row in rows)
  119. print(f"{len(rows)} pre-gateway chat(s) to adopt ({', '.join(f'{n} {s}' for s, n in sorted(counts.items()))}).")
  120. if args.dry_run:
  121. print('Dry run: nothing was adopted.')
  122. return 0
  123. try:
  124. adopted, skipped = asyncio.run(adopt_sessions(rows))
  125. except (GatewayClientError, OSError, TimeoutError, WebSocketException) as exc:
  126. message = str(exc) if isinstance(exc, GatewayClientError) else 'Gateway connection/read failed'
  127. print('Error: ' + message, file=sys.stderr)
  128. return 1
  129. print(f'Adopted {adopted} chat(s).')
  130. for refusal, count in sorted(skipped.items()):
  131. print(f'Skipped {count}: {refusal}.')
  132. return 0
  133. def add_adopt_parser(sessions_subparsers) -> None:
  134. parser = sessions_subparsers.add_parser(
  135. 'adopt', help="Bring this profile's pre-gateway chats under its gateway (run on the host)",
  136. description="Chats written before the gateway owned sessions become gateway sessions the first "
  137. "time a native client on this host opens them. This adopts them all at once, so remote "
  138. "clients such as the Webapp can continue them. Run it as the gateway's OS user; use "
  139. "`hermes -p <profile> sessions adopt` for another profile.")
  140. parser.add_argument('--dry-run', action='store_true', help='Only count what would be adopted')