_setup.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. """Interactive ``hermes memory setup`` wizard for the OpenViking provider.
  2. Pure UI flow: prompts, menus, and persistence of the chosen connection (Hermes
  3. ``.env`` only, or mirrored to an ``ovcli.conf.<name>`` profile that Hermes then
  4. links). Network validation and file writers live in the package ``__init__`` and
  5. are looked up there at call time so tests can monkeypatch them on the plugin module.
  6. """
  7. from __future__ import annotations
  8. import os
  9. import sys
  10. from pathlib import Path
  11. from typing import Optional
  12. from . import quick_local
  13. _SETUP_CANCELLED = object()
  14. _CANCEL_OPTION = ("Cancel setup", "no changes saved")
  15. _PERSONAL_PROFILE = "personal"
  16. _SHARED_PROFILE = "shared"
  17. def _ov():
  18. """The plugin module — resolved lazily so monkeypatched validators are honored."""
  19. return sys.modules[__package__]
  20. def _say(message: str) -> None:
  21. print(f" {message}", flush=True)
  22. def _select_usage_profile(select, cancelled, provider_config: dict) -> str | object:
  23. """Choose the original Personal/Shared preset before any connection writes."""
  24. default = 1 if provider_config.get("recall_scope") == "shared" else 0
  25. while True:
  26. choice = select(
  27. " OpenViking usage profile",
  28. [("Personal Agent", "recall common and sender memory; keep sessions"),
  29. ("Shared Agent", "share history and recall all senders")],
  30. default=default, cancel_returns=cancelled,
  31. )
  32. if choice == cancelled:
  33. return _SETUP_CANCELLED
  34. if choice == 0:
  35. return _PERSONAL_PROFILE
  36. if choice != 1:
  37. continue
  38. from hermes_cli.curses_ui import curses_radiolist
  39. from hermes_cli.memory_setup import _clear_interactive_transition
  40. description = (
  41. " Participants share conversation history within each group or thread.\n"
  42. " Different groups keep separate conversation histories.\n"
  43. " Recall includes common memory and all senders under this\n"
  44. " OpenViking user, across chats."
  45. )
  46. print(description, flush=True) # Also visible with Hermes's numbered fallback.
  47. confirm = curses_radiolist(
  48. " Confirm Shared Agent",
  49. ["Apply Shared Agent", "Go back - choose a different usage profile",
  50. "Cancel setup - no changes saved"],
  51. selected=1, cancel_returns=cancelled,
  52. description=description,
  53. )
  54. _clear_interactive_transition()
  55. if confirm == 0:
  56. return _SHARED_PROFILE
  57. if confirm != 1:
  58. return _SETUP_CANCELLED
  59. def _apply_usage_profile(config: dict, provider_config: dict, profile: str) -> None:
  60. if profile == _PERSONAL_PROFILE:
  61. provider_config["recall_scope"] = "peer"
  62. elif profile == _SHARED_PROFILE:
  63. provider_config["recall_scope"] = "shared"
  64. config["group_sessions_per_user"] = False
  65. config["thread_sessions_per_user"] = False
  66. else:
  67. raise ValueError(f"Unknown OpenViking usage profile: {profile}")
  68. def _retry_or_cancel_manual_setup(select, title: str, message: str, cancelled):
  69. """-> True (retry) or _SETUP_CANCELLED."""
  70. _say(message)
  71. choice = select(title, [("Retry", "try this step again"), _CANCEL_OPTION], default=0, cancel_returns=cancelled)
  72. return True if choice == 0 else _SETUP_CANCELLED
  73. def _handle_unreachable_endpoint(endpoint: str, message: str, select, cancelled, *, allow_local_autostart: bool = True):
  74. """-> True (reachable now) / False (re-prompt URL) / _SETUP_CANCELLED."""
  75. ov = _ov()
  76. is_local = ov._is_local_openviking_url(endpoint)
  77. if not (is_local and allow_local_autostart):
  78. title = " OpenViking server unhealthy" if is_local else " OpenViking server unreachable"
  79. return _retry_or_cancel_manual_setup(select, title, message, cancelled)
  80. _say(message)
  81. choice = select(" Local OpenViking server is down",
  82. [("Start local OpenViking", "run openviking-server and retry"), ("Retry URL", "enter the server URL again"), _CANCEL_OPTION],
  83. default=0, cancel_returns=cancelled)
  84. if choice == 1:
  85. return False
  86. if choice != 0:
  87. return _SETUP_CANCELLED
  88. start_state, start_message = ov._start_local_openviking_server(endpoint)
  89. _say(start_message)
  90. if start_state != ov._LOCAL_SERVER_STARTED:
  91. return False
  92. _say("Waiting for OpenViking server to become reachable...")
  93. if ov._wait_for_openviking_health(endpoint, timeout_seconds=ov._LOCAL_OPENVIKING_AUTOSTART_TIMEOUT):
  94. _say("OpenViking server is reachable.")
  95. return True
  96. _say("OpenViking server did not become reachable.")
  97. return False
  98. def _prompt_profile_name(prompt, select, cancelled) -> str | object:
  99. ov = _ov()
  100. while True:
  101. name = ov._clean_config_value(prompt("OpenViking profile name"))
  102. if ov._is_valid_ovcli_profile_name(name):
  103. return name
  104. if _retry_or_cancel_manual_setup(
  105. select, " Invalid OpenViking profile name",
  106. "Profile names can only contain letters, numbers, '-' and '_'.", cancelled,
  107. ) is _SETUP_CANCELLED:
  108. return _SETUP_CANCELLED
  109. def _confirm_replace_existing_profile(path: Path, values: dict, select, cancelled):
  110. """-> True (write) / False (choose another name) / _SETUP_CANCELLED."""
  111. ov = _ov()
  112. if not path.exists():
  113. return True
  114. try:
  115. existing_data = ov._load_ovcli_config(path)
  116. except Exception:
  117. existing_data = {}
  118. if existing_data == ov._ovcli_data_from_connection_values(values):
  119. return True
  120. choice = select(" OpenViking profile already exists",
  121. [("Choose another name", "leave the existing profile unchanged"), ("Replace profile", "overwrite this saved OpenViking profile"), _CANCEL_OPTION],
  122. default=0, cancel_returns=cancelled)
  123. return {1: True, 0: False}.get(choice, _SETUP_CANCELLED)
  124. def _prompt_endpoint(prompt, select, cancelled) -> str | object:
  125. """Ask for a custom server URL until it normalizes and answers /health."""
  126. ov = _ov()
  127. while True:
  128. try:
  129. endpoint = ov._normalize_openviking_url(prompt("OpenViking server URL", default=ov._DEFAULT_ENDPOINT))
  130. except ov._OpenVikingEndpointError as exc:
  131. if _retry_or_cancel_manual_setup(select, " Invalid OpenViking endpoint", str(exc), cancelled) is _SETUP_CANCELLED:
  132. return _SETUP_CANCELLED
  133. continue
  134. _say("Checking OpenViking server...")
  135. reachable, message = ov._validate_openviking_reachability(endpoint)
  136. if reachable:
  137. _say("OpenViking server is reachable.")
  138. return endpoint
  139. retry = _handle_unreachable_endpoint(endpoint, message, select, cancelled,
  140. allow_local_autostart=not (message or "").startswith(ov._OPENVIKING_RESPONDED_FAILURE_PREFIX))
  141. if retry is True:
  142. return endpoint
  143. if retry is _SETUP_CANCELLED:
  144. return _SETUP_CANCELLED
  145. # When the entered key turns out to have the other role: (note, menu title, switch option, re-enter label).
  146. _REROUTE = {
  147. "root": ("That key is valid, but it is a user API key.", " OpenViking key is a user key",
  148. ("Use as User API key", "server derives account/user automatically"), "Root API key"),
  149. "user": ("That key is valid, but it has root access.", " OpenViking user API key is root key",
  150. ("Configure as Root API key", "provide account and user IDs"), "User API key"),
  151. }
  152. class _Cancelled(Exception):
  153. """Internal unwind for the manual-connection loop (converted to _SETUP_CANCELLED at the boundary)."""
  154. def _prompt_manual_connection_values(prompt, select, cancelled, *, service: bool = False):
  155. """Loop until a validated connection dict is built, or _SETUP_CANCELLED.
  156. ``continue`` re-enters the loop with ``api_key_type`` / ``prefilled_api_key`` carried over."""
  157. ov = _ov()
  158. if service:
  159. endpoint = ov._OPENVIKING_SERVICE_ENDPOINT
  160. _say(f"OpenViking Service endpoint: {endpoint}")
  161. else:
  162. endpoint = _prompt_endpoint(prompt, select, cancelled)
  163. if endpoint is _SETUP_CANCELLED:
  164. return _SETUP_CANCELLED
  165. is_local = ov._is_local_openviking_url(endpoint)
  166. api_key_type = "user" if service else ""
  167. prefilled_api_key = ""
  168. def retry(title: str, message: str) -> None:
  169. """Retry/Cancel menu; returns to loop again, raises _Cancelled to abort."""
  170. if _retry_or_cancel_manual_setup(select, title, message, cancelled) is _SETUP_CANCELLED:
  171. raise _Cancelled
  172. def reroute(current: str) -> None:
  173. """Key has the other role: offer to use it as such (prefilled), re-enter, or cancel."""
  174. nonlocal api_key_type, prefilled_api_key
  175. note, title, switch_option, role_label = _REROUTE[current]
  176. _say(note)
  177. route_choice = select(title, [switch_option, (f"Re-enter {role_label}", f"try another {current} key"), _CANCEL_OPTION],
  178. default=0, cancel_returns=cancelled)
  179. if route_choice not in (0, 1):
  180. raise _Cancelled
  181. api_key_type = ("user" if current == "root" else "root") if route_choice == 0 else current
  182. prefilled_api_key = values["api_key"] if route_choice == 0 else ""
  183. try:
  184. while True:
  185. values = {"endpoint": endpoint, "api_key": "", "root_api_key": "", "account": "", "user": "", "agent": ""}
  186. if not api_key_type:
  187. options = [
  188. ("User API key", "recommended; server derives account/user automatically" if is_local else "server derives account/user automatically"),
  189. ("Root API key", "requires account and user IDs"),
  190. ]
  191. if is_local:
  192. options.append(("No API key", "only for explicitly unauthenticated local development"))
  193. credential_choice = select(" OpenViking credential" if is_local else " OpenViking API key type", options, default=0, cancel_returns=cancelled)
  194. if credential_choice == cancelled:
  195. raise _Cancelled
  196. if is_local and credential_choice == 2:
  197. _say("Validating OpenViking local dev access...")
  198. valid, message, _role = ov._validate_openviking_setup_values(values)
  199. if valid:
  200. _say("OpenViking local dev access validated.")
  201. return values
  202. retry(" OpenViking credential failed", message)
  203. continue
  204. api_key_type = "root" if credential_choice == 1 else "user"
  205. values["api_key_type"] = api_key_type
  206. api_key_label = "OpenViking API key" if service else f"OpenViking {api_key_type} API key"
  207. if prefilled_api_key:
  208. values["api_key"], prefilled_api_key = prefilled_api_key, ""
  209. else:
  210. values["api_key"] = ov._clean_config_value(prompt(api_key_label, secret=True))
  211. if not values["api_key"]:
  212. retry(" OpenViking API key required", f"{api_key_label} is required.")
  213. continue
  214. if api_key_type == "root":
  215. _say("Validating OpenViking root API key...")
  216. valid, message, role = ov._validate_openviking_setup_values(values, require_api_key=True)
  217. if valid and role == "user":
  218. reroute("root")
  219. continue
  220. if not (valid and role == "root"):
  221. retry(" OpenViking root API key failed", message)
  222. continue
  223. _say("OpenViking root API key validated.")
  224. values["root_api_key"] = values["api_key"]
  225. identity_errors = []
  226. for field, label in (("account", "OpenViking account"), ("user", "OpenViking user")):
  227. ok, error, values[field] = ov._validate_openviking_identity_value(prompt(label), field=field)
  228. if not ok:
  229. identity_errors.append(error)
  230. if identity_errors:
  231. retry(" OpenViking tenant identity required", identity_errors[0])
  232. prefilled_api_key = values["api_key"]
  233. continue
  234. _say("Validating OpenViking API access...")
  235. valid, message, role = ov._validate_openviking_setup_values(values, require_api_key=service or not is_local)
  236. if not valid:
  237. retry(" OpenViking API access failed", message)
  238. continue
  239. if api_key_type == "user" and role == "root":
  240. reroute("user")
  241. continue
  242. if api_key_type == "root" and role != "root":
  243. retry(" OpenViking root API key failed", "The supplied key was not accepted as a root API key.")
  244. continue
  245. _say("OpenViking API access validated.")
  246. return values
  247. except _Cancelled:
  248. return _SETUP_CANCELLED
  249. def _link_ovcli_profile(*, config: dict, provider_config: dict, env_path: Path, ovcli_path: Path) -> None:
  250. ov = _ov()
  251. _stop_previous_quick_local(provider_config, env_path.parent, ovcli_path=ovcli_path)
  252. quick_local.clear_managed_settings(provider_config)
  253. for key in ("endpoint", "api_key", "root_api_key", "account", "user", "agent", "api_key_type"):
  254. provider_config.pop(key, None)
  255. provider_config["use_ovcli_config"] = True
  256. # Record the path only when it is not the default location (or the env var points elsewhere).
  257. if os.environ.get(ov._OVCLI_CONFIG_ENV, "").strip() or ovcli_path.expanduser() != ov._default_ovcli_config_path().expanduser():
  258. provider_config["ovcli_config_path"] = str(ovcli_path)
  259. else:
  260. provider_config.pop("ovcli_config_path", None)
  261. config["memory"]["provider"] = "openviking"
  262. config["memory"]["openviking"] = provider_config
  263. ov._write_env_vars(env_path, {}, remove_keys=ov._OPENVIKING_ENV_KEYS)
  264. for key in ov._OPENVIKING_ENV_KEYS:
  265. os.environ.pop(key, None)
  266. def _save_hermes_only_config(*, config: dict, provider_config: dict, env_path: Path, values: dict) -> None:
  267. ov = _ov()
  268. _stop_previous_quick_local(provider_config, env_path.parent)
  269. quick_local.clear_managed_settings(provider_config)
  270. provider_config["use_ovcli_config"] = False
  271. provider_config.pop("ovcli_config_path", None)
  272. # A newly selected connection must not inherit the previous YAML peer; a
  273. # non-empty peer, if supplied, is saved with the connection below.
  274. provider_config.pop("agent", None)
  275. config["memory"]["provider"] = "openviking"
  276. config["memory"]["openviking"] = provider_config
  277. # Publish the file writer's cleaned values to the current process as well.
  278. writes = {env_key: ov._env_line_safe(value) for env_key, key in zip(ov._OPENVIKING_ENV_KEYS, ov._CONNECTION_KEYS)
  279. if (value := ov._clean_config_value(values.get(key)))}
  280. ov._write_env_vars(env_path, writes, remove_keys=ov._OPENVIKING_ENV_KEYS)
  281. os.environ.update(writes)
  282. for key in set(ov._OPENVIKING_ENV_KEYS) - set(writes):
  283. os.environ.pop(key, None)
  284. def _stop_previous_quick_local(provider_config: dict, home: Path, *, ovcli_path=None) -> None:
  285. if provider_config.get("deployment") != quick_local.DEPLOYMENT:
  286. return
  287. from .local_server import LocalServer
  288. server = LocalServer(home)
  289. if ovcli_path is not None and quick_local._paths_equivalent(ovcli_path, server.paths.ovcli_config):
  290. return # Quick Local setup is relinking its own config.
  291. try:
  292. if server.paths.server_config.is_file() and server.stop():
  293. _say("Stopped this profile's Quick Local server. Its data is retained.")
  294. except (quick_local.QuickLocalSetupError, OSError):
  295. _say("The previous Quick Local server could not be stopped safely. Check it before removing the plugin.")
  296. def _profile_display_name(profile) -> str:
  297. return {"env": _ov()._OVCLI_CONFIG_ENV, "active": "ovcli.conf"}.get(profile.source, profile.name)
  298. def _print_openviking_ready(message: str, path: Optional[Path] = None) -> None:
  299. print("\n OpenViking memory is ready")
  300. _say(message)
  301. if path is not None:
  302. _say(f"Config file: {path}")
  303. print(" Start a new Hermes session to activate.\n")
  304. def _run_existing_profile_setup(*, profiles: list, select, cancelled, config: dict, provider_config: dict, env_path: Path) -> bool | object:
  305. ov = _ov()
  306. while True:
  307. choice = select(
  308. " OpenViking profile",
  309. [(_profile_display_name(p), f"{ov._clean_config_value(p.values.get('endpoint')) or ov._DEFAULT_ENDPOINT} ({p.path})") for p in profiles],
  310. default=0, cancel_returns=cancelled,
  311. )
  312. if choice == cancelled or choice < 0 or choice >= len(profiles):
  313. return _SETUP_CANCELLED
  314. profile = profiles[choice]
  315. for attempt in (0, 1):
  316. _say("Validating OpenViking profile...")
  317. require_api_key = not ov._is_local_openviking_url(profile.values.get("endpoint", ""))
  318. ok, message, _role = ov._validate_openviking_setup_values(profile.values, require_api_key=require_api_key)
  319. if ok:
  320. _link_ovcli_profile(config=config, provider_config=provider_config, env_path=env_path, ovcli_path=profile.path)
  321. _print_openviking_ready(f"Linked profile: {_profile_display_name(profile)}", profile.path)
  322. return True
  323. _say(message)
  324. if attempt == 1:
  325. break # second failure returns to the profile picker
  326. retry = select(" OpenViking profile validation failed",
  327. [("Choose another profile", "select a different OpenViking profile"), ("Retry validation", "try this profile again"), _CANCEL_OPTION],
  328. default=0, cancel_returns=cancelled)
  329. if retry == 0:
  330. break
  331. if retry != 1:
  332. return _SETUP_CANCELLED
  333. def _mirror_manual_config_to_openviking_store(*, prompt, select, cancelled, values: dict) -> Path | object:
  334. ov = _ov()
  335. while True:
  336. name = _prompt_profile_name(prompt, select, cancelled)
  337. if name is _SETUP_CANCELLED:
  338. return _SETUP_CANCELLED
  339. path = ov._default_ovcli_config_path().parent / f"{ov._OVCLI_SAVED_PREFIX}{name}"
  340. replace = _confirm_replace_existing_profile(path, values, select, cancelled)
  341. if replace is _SETUP_CANCELLED:
  342. return _SETUP_CANCELLED
  343. if replace is False:
  344. continue
  345. from hermes_constants import mkdir_under_hermes_home
  346. mkdir_under_hermes_home(path.parent)
  347. # atomic_json_write creates the temp file 0600 and os.replace()s it: no
  348. # half-written config on crash, no chmod-after-write window for the keys.
  349. ov.atomic_json_write(path, ov._ovcli_data_from_connection_values(values), mode=0o600)
  350. return path
  351. def _run_quick_local_setup(*, config: dict, provider_config: dict, env_path: Path,
  352. select=None, cancelled=None) -> bool:
  353. ov = _ov()
  354. def report_progress(event: quick_local.QuickLocalProgress) -> None:
  355. _say(event.message)
  356. setup = quick_local.QuickLocalSetup(
  357. health_check=ov._validate_openviking_reachability,
  358. progress=report_progress,
  359. )
  360. try:
  361. preflight = setup.preflight(env_path.parent)
  362. except quick_local.QuickLocalSetupError as exc:
  363. _say(f"Quick Local preflight failed: {exc}")
  364. return False
  365. try:
  366. result = setup.provision(hermes_home=env_path.parent, preflight=preflight)
  367. except quick_local.SourceBuildRequired as exc:
  368. _say(str(exc))
  369. if select is None or select(
  370. " Allow a source build?",
  371. [("Cancel", "connect to a separate OpenViking server instead"),
  372. ("Build locally", "requires native build tools; can take several minutes")],
  373. default=0, cancel_returns=cancelled,
  374. ) != 1:
  375. return False
  376. setup.allow_source_build = True
  377. try:
  378. result = setup.provision(hermes_home=env_path.parent, preflight=preflight)
  379. except quick_local.QuickLocalSetupError as retry_exc:
  380. _say(f"Quick Local setup failed: {retry_exc}")
  381. return False
  382. except quick_local.QuickLocalSetupError as exc:
  383. _say(f"Quick Local setup failed: {exc}")
  384. return False
  385. _link_ovcli_profile(
  386. config=config,
  387. provider_config=provider_config,
  388. env_path=env_path,
  389. ovcli_path=result.paths.ovcli_config,
  390. )
  391. provider_config.update(
  392. deployment=quick_local.DEPLOYMENT,
  393. )
  394. action = "Reused" if result.reused else "Configured"
  395. _print_openviking_ready(
  396. f"{action} Quick Local at {result.endpoint}.",
  397. result.paths.ovcli_config,
  398. )
  399. return True
  400. def _run_create_profile_setup(*, prompt, select, cancelled, config: dict, provider_config: dict, env_path: Path) -> bool | object:
  401. source_choice = select(" OpenViking connection",
  402. [("OpenViking Service (VolcEngine Cloud)", "use the managed OpenViking endpoint"),
  403. ("Custom", "use a local, VPS, or self-hosted OpenViking server"),
  404. ("Quick Local", "install local embeddings; use the configured Hermes LLM")],
  405. default=0, cancel_returns=cancelled)
  406. if source_choice == cancelled:
  407. return _SETUP_CANCELLED
  408. if source_choice == 2:
  409. return _run_quick_local_setup(config=config, provider_config=provider_config, env_path=env_path,
  410. select=select, cancelled=cancelled)
  411. values = _prompt_manual_connection_values(prompt, select, cancelled, service=(source_choice == 0))
  412. if values is _SETUP_CANCELLED:
  413. return _SETUP_CANCELLED
  414. if values is None:
  415. return False
  416. save_choice = select(" Save OpenViking config",
  417. [("Keep in Hermes only", "write values only to Hermes .env"),
  418. ("Mirror to OpenViking store", "write ~/.openviking/ovcli.conf.<name> and link it")],
  419. default=1, cancel_returns=cancelled)
  420. if save_choice == cancelled:
  421. return _SETUP_CANCELLED
  422. if save_choice == 1:
  423. ovcli_path = _mirror_manual_config_to_openviking_store(prompt=prompt, select=select, cancelled=cancelled, values=values)
  424. if ovcli_path is _SETUP_CANCELLED:
  425. return _SETUP_CANCELLED
  426. _link_ovcli_profile(config=config, provider_config=provider_config, env_path=env_path, ovcli_path=ovcli_path)
  427. _print_openviking_ready("Created and linked OpenViking profile.", ovcli_path)
  428. return True
  429. _save_hermes_only_config(config=config, provider_config=provider_config, env_path=env_path, values=values)
  430. _print_openviking_ready("Connection saved to Hermes .env.")
  431. return True
  432. def run_setup(hermes_home: str, config: dict) -> None:
  433. """Entry point for ``OpenVikingMemoryProvider.post_setup``."""
  434. from hermes_cli.config import save_config
  435. from hermes_cli.memory_setup import _CANCELLED, _curses_select, _print_cancelled_setup, _prompt
  436. env_path = Path(hermes_home) / ".env"
  437. memory_config = config.get("memory")
  438. provider_config = memory_config.get("openviking", {}) if isinstance(memory_config, dict) else {}
  439. provider_config = provider_config if isinstance(provider_config, dict) else {}
  440. print("\n OpenViking memory setup\n")
  441. usage_profile = _select_usage_profile(_curses_select, _CANCELLED, provider_config)
  442. if usage_profile is _SETUP_CANCELLED:
  443. _print_cancelled_setup()
  444. return
  445. if not isinstance(config.get("memory"), dict):
  446. config["memory"] = {}
  447. common = dict(select=_curses_select, cancelled=_CANCELLED, config=config, provider_config=provider_config, env_path=env_path)
  448. profiles = _ov()._discover_ovcli_profiles()
  449. if profiles:
  450. choice = _curses_select(" OpenViking config source",
  451. [("Use existing OpenViking profile", "choose from detected ovcli.conf profiles"),
  452. ("Create new OpenViking profile", "enter a new URL/API key")],
  453. default=0, cancel_returns=_CANCELLED)
  454. if choice == _CANCELLED:
  455. _print_cancelled_setup()
  456. return
  457. if choice == 0:
  458. result = _run_existing_profile_setup(profiles=profiles, **common)
  459. else:
  460. result = _run_create_profile_setup(prompt=_prompt, **common)
  461. else:
  462. _say("No existing OpenViking CLI profiles found. Creating a new config.")
  463. result = _run_create_profile_setup(prompt=_prompt, **common)
  464. if result is _SETUP_CANCELLED:
  465. _print_cancelled_setup()
  466. elif result:
  467. _apply_usage_profile(config, provider_config, usage_profile)
  468. # A saved environment override must not silently defeat the chosen preset.
  469. _ov()._write_env_vars(env_path, {}, remove_keys=("OPENVIKING_RECALL_SCOPE",))
  470. os.environ.pop("OPENVIKING_RECALL_SCOPE", None)
  471. save_config(config)
  472. if usage_profile == _SHARED_PROFILE:
  473. _say("Restart the Hermes gateway to apply the shared session settings.")
  474. else:
  475. _say("Personal recall enabled. Conversation-sharing settings are unchanged.")