quick_local.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. """Reusable, non-interactive OpenViking Quick Local provisioning.
  2. User interfaces own prompts and rendering. This module owns the bounded
  3. installation, Hermes-profile-scoped configuration, and temporary validation
  4. needed to produce a ready-to-link OpenViking CLI profile.
  5. """
  6. from __future__ import annotations
  7. import importlib.util
  8. import json
  9. import os
  10. import secrets
  11. import shutil
  12. import socket
  13. import subprocess
  14. import sys
  15. import tempfile
  16. import time
  17. from dataclasses import dataclass
  18. from enum import Enum
  19. from pathlib import Path
  20. from typing import Any, Callable, Mapping, Optional
  21. from urllib.parse import urlparse
  22. from packaging.requirements import Requirement
  23. from packaging.version import InvalidVersion, Version
  24. from utils import atomic_json_write
  25. DEPLOYMENT = "quick_local"
  26. EMBEDDING_MODEL = "bge-small-zh-v1.5-f16"
  27. EMBEDDING_DIMENSION = 512
  28. # Accept new releases in the server API series; resolve only in explicit setup.
  29. OPENVIKING_REQUIREMENT = "openviking[local-embed]>=0.4.22,<0.5"
  30. # Later LiteLLM releases exclude Python 3.14. OpenViking supports this version.
  31. # This restriction applies only to the private server, never Hermes's dependencies.
  32. _OPENVIKING_REQUIREMENT = Requirement(OPENVIKING_REQUIREMENT)
  33. _OPENVIKING_VERSION_SPECIFIER = _OPENVIKING_REQUIREMENT.specifier
  34. _ROOT_DIRNAME = "openviking"
  35. _SERVER_CONFIG_FILENAME = "ov.conf"
  36. _OVCLI_CONFIG_FILENAME = "ovcli.conf"
  37. _RESTART_REQUIRED_FILENAME = ".restart-required"
  38. _WORKSPACE_DIRNAME = "data"
  39. _MODEL_CACHE_DIRNAME = "models"
  40. # Leave OpenViking's default 1933 available for independently managed servers.
  41. _DEFAULT_PORT = 1934
  42. _PORT_ATTEMPTS = 20
  43. _MODEL_DOWNLOAD_SIZE = "approximately 46 MiB"
  44. # OpenViking downloads the built-in model while its server lifespan starts.
  45. # Give a slow first download a bounded ten minutes, then leave another minute
  46. # for model loading and service initialization.
  47. _MODEL_PREPARATION_TIMEOUT_SECONDS = 600.0
  48. _HEALTH_TIMEOUT_SECONDS = _MODEL_PREPARATION_TIMEOUT_SECONDS + 60.0
  49. _HEALTH_POLL_INTERVAL_SECONDS = 0.5
  50. _PROCESS_STOP_TIMEOUT_SECONDS = 10.0
  51. class QuickLocalStage(str, Enum):
  52. PREFLIGHT = "preflight"
  53. INSTALL_OPENVIKING = "install_openviking"
  54. PREPARE_EMBEDDING = "prepare_embedding"
  55. VALIDATE = "validate"
  56. WRITE_CONFIG = "write_config"
  57. COMPLETE = "complete"
  58. @dataclass(frozen=True)
  59. class QuickLocalProgress:
  60. stage: QuickLocalStage
  61. message: str
  62. @dataclass(frozen=True)
  63. class QuickLocalPaths:
  64. root: Path
  65. runtime: Path
  66. server_config: Path
  67. ovcli_config: Path
  68. workspace: Path
  69. model_cache: Path
  70. @property
  71. def runtime_python(self) -> Path:
  72. scripts = "Scripts" if os.name == "nt" else "bin"
  73. executable = "python.exe" if os.name == "nt" else "python"
  74. if _pm_available():
  75. from pm.operations import environment_python
  76. selected = environment_python("openviking-local", root=self.runtime)
  77. else:
  78. selected = None
  79. return selected or self.runtime / scripts / executable
  80. @property
  81. def server_command(self) -> Path:
  82. scripts = "Scripts" if os.name == "nt" else "bin"
  83. executable = "openviking-server.exe" if os.name == "nt" else "openviking-server"
  84. if _pm_available():
  85. from pm.operations import python_tool
  86. selected = python_tool("openviking-local", "openviking-server", root=self.runtime)
  87. else:
  88. selected = None
  89. return selected or self.runtime / scripts / executable
  90. @property
  91. def restart_required_marker(self) -> Path:
  92. return self.root / _RESTART_REQUIRED_FILENAME
  93. @dataclass(frozen=True)
  94. class QuickLocalPreflight:
  95. paths: QuickLocalPaths
  96. reusable_endpoint: Optional[str]
  97. @dataclass(frozen=True)
  98. class QuickLocalSetupResult:
  99. paths: QuickLocalPaths
  100. endpoint: str
  101. reused: bool
  102. server_restart_required: bool = False
  103. class QuickLocalSetupError(RuntimeError):
  104. """Quick Local could not finish without partially activating it."""
  105. class SourceBuildRequired(QuickLocalSetupError):
  106. """No reviewed binary matches this platform; ask before compiling."""
  107. ProgressReporter = Callable[[QuickLocalProgress], None]
  108. HealthCheck = Callable[[str], tuple[bool, str]]
  109. def managed_paths(hermes_home: Path) -> QuickLocalPaths:
  110. root = Path(hermes_home).expanduser().absolute() / _ROOT_DIRNAME
  111. if root.is_symlink():
  112. raise QuickLocalSetupError("Quick Local directory must belong to this Hermes profile.")
  113. return QuickLocalPaths(
  114. root=root,
  115. runtime=root / "runtime",
  116. server_config=root / _SERVER_CONFIG_FILENAME,
  117. ovcli_config=root / _OVCLI_CONFIG_FILENAME,
  118. workspace=root / _WORKSPACE_DIRNAME,
  119. model_cache=root / _MODEL_CACHE_DIRNAME,
  120. )
  121. def clear_managed_settings(provider_config: dict[str, Any]) -> None:
  122. provider_config.pop("deployment", None)
  123. provider_config.pop("server_config_path", None)
  124. provider_config.pop("server_command_path", None)
  125. def clear_server_restart_required(server_config_path: Path) -> bool:
  126. """Clear the durable marker once no stale managed server remains."""
  127. marker = Path(server_config_path).with_name(_RESTART_REQUIRED_FILENAME)
  128. try:
  129. marker.unlink(missing_ok=True)
  130. return True
  131. except OSError:
  132. return False
  133. def _mark_server_restart_required(paths: QuickLocalPaths) -> None:
  134. _prepare_private_directory(paths.root)
  135. atomic_json_write(
  136. paths.restart_required_marker,
  137. {"restart_required": True},
  138. mode=0o600,
  139. )
  140. def build_server_config(
  141. paths: QuickLocalPaths,
  142. vlm: Mapping[str, Any],
  143. *,
  144. port: int = _DEFAULT_PORT,
  145. ) -> dict[str, Any]:
  146. return {
  147. "server": {
  148. "host": "127.0.0.1",
  149. "port": port,
  150. "auth_mode": "trusted",
  151. "root_api_key": _server_key(paths),
  152. },
  153. "storage": {"workspace": str(paths.workspace)},
  154. "embedding": {
  155. "dense": {
  156. "provider": "local",
  157. "model": EMBEDDING_MODEL,
  158. "dimension": EMBEDDING_DIMENSION,
  159. "cache_dir": str(paths.model_cache),
  160. }
  161. },
  162. "vlm": dict(vlm),
  163. }
  164. def resolve_hermes_vlm_config() -> dict[str, Any]:
  165. """Translate the active persisted Hermes LLM into OpenViking VLM config."""
  166. from hermes_cli.config import load_config
  167. from hermes_cli.runtime_provider import resolve_runtime_provider
  168. config = load_config()
  169. model_config = config.get("model", {}) if isinstance(config, Mapping) else {}
  170. if isinstance(model_config, str):
  171. model_config = {"default": model_config}
  172. if not isinstance(model_config, Mapping):
  173. model_config = {}
  174. default_model = model_config.get("default")
  175. requested_provider = _clean_value(model_config.get("provider")) or None
  176. if isinstance(default_model, Mapping):
  177. from hermes_cli.config import split_model_config_default
  178. nested_model, nested_provider = split_model_config_default(default_model)
  179. default_model = nested_model
  180. requested_provider = requested_provider or nested_provider or None
  181. model = _clean_value(default_model or model_config.get("model") or model_config.get("name"))
  182. if not model:
  183. raise QuickLocalSetupError("Hermes has no default LLM model configured.")
  184. runtime = resolve_runtime_provider(
  185. requested=requested_provider,
  186. target_model=model,
  187. )
  188. runtime_model = _clean_value(runtime.get("model")) or model
  189. provider = _clean_value(runtime.get("provider")).lower()
  190. api_mode = _clean_value(runtime.get("api_mode")).lower()
  191. source = _clean_value(runtime.get("source")).lower()
  192. raw_api_base = runtime.get("base_url")
  193. raw_api_key = runtime.get("api_key")
  194. api_base = _clean_value(raw_api_base)
  195. api_key = _clean_value(raw_api_key)
  196. if raw_api_base is not None and not isinstance(raw_api_base, str):
  197. raise QuickLocalSetupError("Hermes' LLM provider API base URL must be a string.")
  198. if not api_base:
  199. raise QuickLocalSetupError("Hermes' LLM provider did not resolve an API base URL.")
  200. if raw_api_key is None or (isinstance(raw_api_key, str) and not api_key):
  201. raise QuickLocalSetupError(
  202. "Hermes' LLM provider did not resolve reusable static credentials."
  203. )
  204. key_env = _clean_value(model_config.get("key_env") or model_config.get("api_key_env")).lower()
  205. local_runtime = (
  206. provider == "custom"
  207. and source == "local-runtime"
  208. and isinstance(raw_api_key, str)
  209. and bool(api_key)
  210. and urlparse(api_base).hostname in {"localhost", "127.0.0.1", "::1"}
  211. )
  212. declared_key = bool(key_env and source in {key_env, f"env:{key_env}"})
  213. # A declared env variable identifies a source, not a static credential.
  214. # Hermes owns native Anthropic OAuth authentication and token refresh.
  215. oauth_route = False
  216. if api_mode == "anthropic_messages" and isinstance(raw_api_key, str):
  217. from agent.anthropic_credentials import anthropic_route_is_oauth
  218. oauth_route = anthropic_route_is_oauth(api_base, raw_api_key, provider=provider)
  219. if oauth_route or not isinstance(raw_api_key, str) or not (
  220. local_runtime or declared_key or _has_copyable_static_credentials(provider, source, api_key)
  221. ):
  222. raise QuickLocalSetupError(
  223. "Hermes is using refreshed OAuth, cloud-native, or external-process "
  224. "credentials that cannot be copied safely into OpenViking. Configure "
  225. "a static API-key LLM for Hermes, or connect to an OpenViking server "
  226. "configured separately."
  227. )
  228. # These static-key API endpoints also provide Chat Completions. OAuth
  229. # Responses routes and third-party Responses-only endpoints stay excluded.
  230. if api_mode == "codex_responses" and urlparse(api_base).hostname in {
  231. "api.openai.com", "api.x.ai"
  232. } and provider in {"openai-api", "xai", "custom"}:
  233. api_mode = "chat_completions"
  234. if api_mode not in {"chat_completions", "anthropic_messages"}:
  235. raise QuickLocalSetupError(
  236. f"Hermes' {api_mode or 'unknown'} LLM transport is not supported by "
  237. "Quick Local. Use an OpenAI-compatible or Anthropic-compatible "
  238. "API-key provider, or connect to an OpenViking server configured "
  239. "separately."
  240. )
  241. vlm: dict[str, Any]
  242. if api_mode == "anthropic_messages":
  243. # Like Hermes's Anthropic SDK, LiteLLM appends /v1/messages itself.
  244. api_base = api_base.rstrip("/").removesuffix("/v1")
  245. from agent.anthropic_adapter import _attribution_headers, _auth_style
  246. style = _auth_style(api_key, api_base, api_base)
  247. # OV's pinned LiteLLM backend cannot reproduce Hermes's bearer/query
  248. # handling. It also treats sk-ant-oat-shaped proxy keys as native OAuth.
  249. if style == "bearer" or api_key.startswith("sk-ant-oat"):
  250. raise QuickLocalSetupError(
  251. "Quick Local cannot reproduce authentication for this Anthropic route. "
  252. "Use an OpenAI-compatible route for Hermes, or Custom setup "
  253. "with a separately configured OpenViking server."
  254. )
  255. if not runtime_model.startswith("anthropic/"):
  256. runtime_model = f"anthropic/{runtime_model}"
  257. vlm = {
  258. "provider": "litellm",
  259. "model": runtime_model,
  260. "api_key": api_key,
  261. "api_base": api_base,
  262. }
  263. if style == "kimi":
  264. vlm["extra_headers"] = _attribution_headers()
  265. else:
  266. base = urlparse(api_base)
  267. if base.hostname == "generativelanguage.googleapis.com" and not base.path.rstrip("/").endswith("/openai"):
  268. # Hermes uses Google's native client despite chat_completions in
  269. # its runtime record. OV needs Google's documented OpenAI route.
  270. api_base = base._replace(path="/v1beta/openai/").geturl()
  271. vlm = {
  272. "provider": "openai",
  273. "model": runtime_model,
  274. "api_key": api_key,
  275. "api_base": api_base,
  276. }
  277. extra_headers = runtime.get("extra_headers")
  278. if isinstance(extra_headers, dict) and extra_headers:
  279. vlm["extra_headers"] = {**vlm.get("extra_headers", {}), **extra_headers}
  280. request_overrides = runtime.get("request_overrides")
  281. if isinstance(request_overrides, dict):
  282. extra_body = request_overrides.get("extra_body")
  283. if isinstance(extra_body, dict) and extra_body:
  284. vlm["extra_request_body"] = dict(extra_body)
  285. vlm.update({"temperature": 0.0, "max_retries": 2})
  286. return vlm
  287. class QuickLocalSetup:
  288. """Provision one Hermes-home-scoped Quick Local configuration."""
  289. def __init__(
  290. self,
  291. *,
  292. health_check: HealthCheck,
  293. progress: Optional[ProgressReporter] = None,
  294. allow_source_build: bool = False,
  295. ) -> None:
  296. self._health_check = health_check
  297. self._progress = progress or (lambda _event: None)
  298. self.allow_source_build = allow_source_build
  299. def preflight(self, hermes_home: Path) -> QuickLocalPreflight:
  300. self._emit(QuickLocalStage.PREFLIGHT, "Checking local requirements...")
  301. paths = managed_paths(hermes_home)
  302. reusable_endpoint = find_reusable_endpoint(paths, self._health_check)
  303. return QuickLocalPreflight(
  304. paths=paths,
  305. reusable_endpoint=reusable_endpoint,
  306. )
  307. def provision(
  308. self,
  309. *,
  310. hermes_home: Path,
  311. preflight: Optional[QuickLocalPreflight] = None,
  312. ) -> QuickLocalSetupResult:
  313. try:
  314. return self._provision(
  315. hermes_home=Path(hermes_home),
  316. preflight=preflight,
  317. )
  318. except QuickLocalSetupError:
  319. raise
  320. except Exception as exc:
  321. raise QuickLocalSetupError(
  322. f"Could not prepare Quick Local ({type(exc).__name__}). Review the server log and retry."
  323. ) from exc
  324. def _provision(
  325. self,
  326. *,
  327. hermes_home: Path,
  328. preflight: Optional[QuickLocalPreflight],
  329. ) -> QuickLocalSetupResult:
  330. preflight = preflight or self.preflight(hermes_home)
  331. if preflight.paths != managed_paths(hermes_home):
  332. raise QuickLocalSetupError(
  333. "Quick Local preflight belongs to a different Hermes profile."
  334. )
  335. vlm = resolve_hermes_vlm_config()
  336. runtime_changed = self._ensure_openviking_installed(preflight.paths)
  337. reusable_endpoint = find_reusable_endpoint(preflight.paths, self._health_check)
  338. if reusable_endpoint:
  339. port = _endpoint_port(reusable_endpoint)
  340. if port is None:
  341. raise QuickLocalSetupError(
  342. "Quick Local's saved endpoint does not contain a valid port."
  343. )
  344. server_config = build_server_config(preflight.paths, vlm, port=port)
  345. config_changed = not _stored_server_config_matches(preflight.paths, server_config)
  346. if (
  347. runtime_changed
  348. or config_changed
  349. or preflight.paths.restart_required_marker.is_file()
  350. ):
  351. # Validate in disposable storage before changing the live service.
  352. validation_port = find_available_port()
  353. if validation_port is None:
  354. raise QuickLocalSetupError(
  355. "No free port is available to validate updated settings."
  356. )
  357. self._validate_generated_config(
  358. paths=preflight.paths,
  359. endpoint=f"http://127.0.0.1:{validation_port}",
  360. server_config=server_config,
  361. )
  362. from .local_server import LocalServer
  363. LocalServer(hermes_home).configure(server_config, runtime_changed=runtime_changed)
  364. self._emit(
  365. QuickLocalStage.WRITE_CONFIG,
  366. "Restarting Quick Local with the updated settings...",
  367. )
  368. reusable_endpoint = self._start_managed_server(preflight.paths, reusable_endpoint)
  369. self._emit(
  370. QuickLocalStage.COMPLETE,
  371. "Quick Local is ready with the updated settings."
  372. if runtime_changed or config_changed
  373. else "Existing Quick Local server is reachable; reusing it.",
  374. )
  375. return QuickLocalSetupResult(
  376. paths=preflight.paths,
  377. endpoint=reusable_endpoint,
  378. reused=True,
  379. )
  380. port = find_available_port(preferred_endpoint=_configured_endpoint(preflight.paths))
  381. if port is None:
  382. last_port = _DEFAULT_PORT + _PORT_ATTEMPTS - 1
  383. raise QuickLocalSetupError(
  384. "No available local port was found for OpenViking "
  385. f"(checked {_DEFAULT_PORT}-{last_port})."
  386. )
  387. endpoint = f"http://127.0.0.1:{port}"
  388. server_config = build_server_config(preflight.paths, vlm, port=port)
  389. self._validate_generated_config(
  390. paths=preflight.paths,
  391. endpoint=endpoint,
  392. server_config=server_config,
  393. )
  394. from .local_server import LocalServer
  395. preflight.paths.workspace.mkdir(parents=True, exist_ok=True)
  396. LocalServer(hermes_home).configure(server_config, runtime_changed=runtime_changed)
  397. endpoint = self._start_managed_server(preflight.paths, endpoint)
  398. self._emit(
  399. QuickLocalStage.WRITE_CONFIG,
  400. f"Saved Quick Local configuration to {preflight.paths.server_config}.",
  401. )
  402. self._emit(
  403. QuickLocalStage.COMPLETE,
  404. f"Quick Local is configured with {EMBEDDING_MODEL}.",
  405. )
  406. return QuickLocalSetupResult(
  407. paths=preflight.paths,
  408. endpoint=endpoint,
  409. reused=False,
  410. )
  411. def _ensure_openviking_installed(self, paths: QuickLocalPaths) -> bool:
  412. """Ensure a compatible runtime, returning whether installation was needed."""
  413. from .local_packages import (
  414. install_requirements,
  415. resolve_server_requirement,
  416. verified_requirements,
  417. )
  418. requirements = install_requirements(allow_source_build=self.allow_source_build)
  419. requirements[0] = resolve_server_requirement(allow_source_build=self.allow_source_build)
  420. receipt = paths.root / "runtime-requirements.json"
  421. try:
  422. installed_requirements = json.loads(receipt.read_text(encoding="utf-8"))
  423. except (OSError, ValueError):
  424. installed_requirements = None
  425. if (
  426. openviking_install_satisfies_requirement(paths)
  427. and installed_requirements == requirements
  428. ):
  429. return False
  430. self._emit(
  431. QuickLocalStage.INSTALL_OPENVIKING,
  432. f"Installing {OPENVIKING_REQUIREMENT}...",
  433. )
  434. _prepare_private_directory(paths.root)
  435. if self.allow_source_build:
  436. self._emit(
  437. QuickLocalStage.INSTALL_OPENVIKING,
  438. "Source builds are allowed. Native compilation can take several minutes.",
  439. )
  440. if _pm_available():
  441. from pm.client import ensure_python_tool
  442. try:
  443. verified = verified_requirements(requirements, paths.root / "wheels")
  444. ensure_python_tool(
  445. "openviking-local",
  446. verified,
  447. "openviking-server",
  448. root=paths.runtime,
  449. explicit=True,
  450. timeout=1800,
  451. )
  452. except QuickLocalSetupError:
  453. raise
  454. except Exception as exc:
  455. raise QuickLocalSetupError(
  456. "Could not install the private OpenViking runtime. Review the installer output."
  457. ) from exc
  458. else: # Genuine pre-PM Hermes only; never fall back on a broken PM import.
  459. self._install_with_uv(paths, verified_requirements(requirements, paths.root / "wheels"))
  460. if not openviking_install_satisfies_requirement(paths):
  461. raise QuickLocalSetupError(
  462. "Could not install a compatible OpenViking local embedding runtime."
  463. )
  464. atomic_json_write(receipt, requirements, mode=0o600)
  465. return True
  466. def _install_with_uv(self, paths: QuickLocalPaths, requirements: list[str]) -> None:
  467. from hermes_cli.managed_uv import resolve_uv
  468. from hermes_constants import get_default_hermes_root
  469. # ensure_uv() can replace the active Hermes environment while setup is
  470. # running. Use an existing installer without repairing the host runtime.
  471. shared_uv = get_default_hermes_root() / "bin" / ("uv.exe" if os.name == "nt" else "uv")
  472. uv = resolve_uv() or shutil.which("uv") or (str(shared_uv) if shared_uv.is_file() else None)
  473. if not uv:
  474. raise QuickLocalSetupError("Quick Local needs uv. Install uv, then retry setup.")
  475. env = _private_child_env(paths.root.parent)
  476. env.update(UV_NATIVE_TLS="true", UV_SYSTEM_CERTS="true")
  477. commands = []
  478. if not paths.runtime_python.is_file():
  479. commands.append(([uv, "venv", str(paths.runtime), "--python", sys.executable], 120))
  480. commands.append(
  481. (
  482. [
  483. uv,
  484. "pip",
  485. "install",
  486. "--upgrade-package",
  487. "openviking",
  488. "--python",
  489. str(paths.runtime_python),
  490. *requirements,
  491. ],
  492. 1800,
  493. )
  494. )
  495. for command, timeout in commands:
  496. result = subprocess.run(
  497. command,
  498. cwd=paths.root,
  499. env=env,
  500. stdin=subprocess.DEVNULL,
  501. check=False,
  502. timeout=timeout,
  503. )
  504. if result.returncode:
  505. raise QuickLocalSetupError(
  506. "Could not install the private OpenViking runtime. Review the installer output."
  507. )
  508. def _validate_generated_config(
  509. self,
  510. *,
  511. paths: QuickLocalPaths,
  512. endpoint: str,
  513. server_config: dict[str, Any],
  514. ) -> None:
  515. _prepare_private_directory(paths.root)
  516. with tempfile.TemporaryDirectory(prefix="setup-validation-", dir=paths.root) as root:
  517. validation_root = Path(root)
  518. validation_config = json.loads(json.dumps(server_config))
  519. validation_config["storage"]["workspace"] = str(validation_root / _WORKSPACE_DIRNAME)
  520. config_path = validation_root / _SERVER_CONFIG_FILENAME
  521. atomic_json_write(config_path, validation_config, mode=0o600)
  522. self._emit(QuickLocalStage.VALIDATE, "Checking the copied Hermes LLM settings...")
  523. _validate_vlm(paths, config_path)
  524. _prepare_private_directory(paths.model_cache)
  525. self._emit(
  526. QuickLocalStage.PREPARE_EMBEDDING,
  527. f"Preparing {EMBEDDING_MODEL}; its {_MODEL_DOWNLOAD_SIZE} model "
  528. "is downloaded once if needed...",
  529. )
  530. _validate_local_embedding(paths)
  531. self._emit(
  532. QuickLocalStage.VALIDATE,
  533. "Validating OpenViking with a temporary local server...",
  534. )
  535. process = _start_validation_server(
  536. endpoint,
  537. config_path,
  538. paths.root.parent,
  539. paths.server_command,
  540. )
  541. primary_error: BaseException | None = None
  542. try:
  543. def validated_health(url):
  544. healthy, message = self._health_check(url)
  545. return healthy and _server_accepts_config(validation_config, url), message
  546. if not _wait_for_health(
  547. endpoint,
  548. validated_health,
  549. process=process,
  550. ):
  551. returncode = process.poll()
  552. if returncode is not None:
  553. raise QuickLocalSetupError(
  554. "OpenViking exited before becoming reachable "
  555. f"(status {returncode}). Review the server log at "
  556. f"{_server_log_path(paths.root.parent)} and retry."
  557. )
  558. raise QuickLocalSetupError(
  559. "OpenViking did not become reachable before the local model "
  560. "preparation timeout. Review the server log at "
  561. f"{_server_log_path(paths.root.parent)} and retry."
  562. )
  563. _validate_tenant_access(endpoint, server_config["server"]["root_api_key"])
  564. except BaseException as exc:
  565. primary_error = exc
  566. raise
  567. finally:
  568. if not _stop_process(process):
  569. message = "The temporary OpenViking validation server could not be stopped."
  570. if primary_error is None:
  571. raise QuickLocalSetupError(message)
  572. primary_error.add_note(message)
  573. def _start_managed_server(self, paths: QuickLocalPaths, endpoint: str) -> str:
  574. """Leave a validated service ready for the first turn and reserve its port."""
  575. self._emit(QuickLocalStage.VALIDATE, "Starting this profile's OpenViking server...")
  576. from .local_server import LocalServer
  577. server = LocalServer(paths.root.parent)
  578. started = server.start()
  579. ready = server.wait_ready(started, self._health_check)
  580. return ready.endpoint
  581. def _emit(self, stage: QuickLocalStage, message: str) -> None:
  582. self._progress(QuickLocalProgress(stage=stage, message=message))
  583. def _validate_vlm(paths: QuickLocalPaths, config_path: Path) -> None:
  584. """Check auth and transport through the exact private OV backend before activation."""
  585. script = """
  586. import json, sys, time
  587. import httpx, openai
  588. from openviking.models.vlm import VLMFactory
  589. def failure_details(exc):
  590. # LiteLLM can replace an Anthropic HTTP/transport error with synthetic 500.
  591. # Stop at the first HTTPX error: its context may contain an older failure.
  592. error, current, seen = exc, exc, set()
  593. while isinstance(current, BaseException) and id(current) not in seen:
  594. seen.add(id(current))
  595. if isinstance(current, (httpx.HTTPError, TimeoutError)):
  596. error = current
  597. break
  598. # Suppression hides traceback text, not the structured HTTP metadata.
  599. current = current.__cause__ or current.__context__
  600. timed_out = isinstance(error, (TimeoutError, httpx.TimeoutException, openai.APITimeoutError))
  601. connection = not timed_out and isinstance(error, (httpx.TransportError, openai.APIConnectionError))
  602. status = getattr(getattr(error, "response", None), "status_code", getattr(error, "status_code", None))
  603. status = status if type(status) is int and 100 <= status <= 599 and not (timed_out or connection) else None
  604. return {"error": type(exc).__name__, "status": status,
  605. "timeout": timed_out, "connection": connection}
  606. for attempt in (1, 2):
  607. try:
  608. config = json.load(open(sys.argv[1], encoding="utf-8"))["vlm"]
  609. vlm = VLMFactory.create({**config, "timeout": 30, "max_retries": 0})
  610. reply = vlm.get_completion(prompt="Reply with OK only.")
  611. if not isinstance(reply, str) or not reply.strip():
  612. raise ValueError("Empty completion")
  613. break
  614. except Exception as exc:
  615. failure = failure_details(exc)
  616. status = failure["status"]
  617. retry = status == 429 or (status is not None and 500 <= status <= 599) or failure["timeout"]
  618. if attempt == 1 and retry:
  619. time.sleep(1)
  620. continue
  621. print(json.dumps({**failure, "attempts": attempt}))
  622. sys.exit(1)
  623. """
  624. try:
  625. result = subprocess.run(
  626. [str(paths.runtime_python), "-c", script, str(config_path)],
  627. cwd=paths.root.parent,
  628. env=_private_child_env(paths.root.parent),
  629. stdin=subprocess.DEVNULL,
  630. stdout=subprocess.PIPE,
  631. stderr=subprocess.PIPE,
  632. text=True,
  633. errors="replace",
  634. timeout=90,
  635. check=False,
  636. )
  637. if result.returncode:
  638. try:
  639. # OV may print import diagnostics before the final result.
  640. failure = json.loads(result.stdout.strip().rsplit("\n", 1)[-1])
  641. except (ValueError, TypeError):
  642. failure = {}
  643. raise _vlm_check_failure(paths, failure)
  644. except subprocess.TimeoutExpired as exc:
  645. raise _vlm_check_failure(paths, {
  646. "error": "TimeoutExpired", "timeout": True, "attempts": 0,
  647. }) from exc
  648. def _vlm_check_failure(paths: QuickLocalPaths, failure: Any) -> QuickLocalSetupError:
  649. """Report only safe error metadata, never a response body or captured stderr."""
  650. failure = failure if isinstance(failure, dict) else {}
  651. name = failure.get("error")
  652. if not isinstance(name, str) or not name.isascii() or not name.isidentifier() or len(name) > 80:
  653. name = "UnknownError"
  654. status = failure.get("status")
  655. status = status if type(status) is int and 100 <= status <= 599 else None
  656. timed_out = failure.get("timeout") is True
  657. attempts = failure.get("attempts")
  658. attempts = attempts if type(attempts) is int and 0 <= attempts <= 2 else 1
  659. detail = name + (f"; HTTP {status}" if status is not None else "")
  660. if timed_out:
  661. message = f"The Hermes LLM access check timed out ({detail}). Retry setup or check the provider's response time."
  662. else:
  663. if status in {401, 403}:
  664. guidance = "Check the API key and its permissions in Hermes."
  665. elif status == 404:
  666. guidance = "Check the model and endpoint in Hermes."
  667. elif status == 429:
  668. guidance = "The provider is rate-limiting requests. Wait, then retry setup."
  669. elif status is not None and status >= 500:
  670. guidance = "The provider reported a temporary server error. Retry setup later."
  671. elif failure.get("connection") is True or name == "APIConnectionError":
  672. guidance = "Check the endpoint and network connection, then retry setup."
  673. else:
  674. guidance = "Check the model and endpoint. The model must support Chat Completions or Anthropic Messages."
  675. message = f"The copied Hermes LLM settings failed the access check ({detail}). {guidance}"
  676. log_path = _server_log_path(paths.root.parent)
  677. _prepare_private_directory(log_path.parent)
  678. if log_path.is_symlink():
  679. raise QuickLocalSetupError("Quick Local log must belong to this profile.")
  680. if not log_path.exists():
  681. log_path.touch(mode=0o600)
  682. if os.name != "nt":
  683. log_path.chmod(0o600)
  684. with log_path.open("a", encoding="utf-8") as log:
  685. log.write(f"LLM access check failed: {detail}; timeout={timed_out}; attempts={attempts}\n")
  686. return QuickLocalSetupError(message)
  687. def openviking_install_satisfies_requirement(paths: QuickLocalPaths) -> bool:
  688. if not paths.runtime_python.is_file() or not paths.server_command.is_file():
  689. return False
  690. try:
  691. result = subprocess.run(
  692. [
  693. str(paths.runtime_python),
  694. "-c",
  695. "import importlib.metadata; import llama_cpp; "
  696. "print(importlib.metadata.version('openviking'))",
  697. ],
  698. capture_output=True,
  699. text=True,
  700. check=False,
  701. stdin=subprocess.DEVNULL,
  702. timeout=120,
  703. )
  704. if result.returncode != 0:
  705. return False
  706. version = Version(result.stdout.strip())
  707. except subprocess.TimeoutExpired as exc:
  708. # A slow cold native import is not evidence of a missing installation.
  709. raise QuickLocalSetupError(
  710. "Quick Local's runtime check timed out. Retry setup; the runtime was not reinstalled."
  711. ) from exc
  712. except (InvalidVersion, OSError, subprocess.SubprocessError):
  713. return False
  714. return version in _OPENVIKING_VERSION_SPECIFIER
  715. def _validate_local_embedding(paths: QuickLocalPaths) -> None:
  716. """Health can pass with failed embeddings; exercise the native backend."""
  717. script = (
  718. "import math; "
  719. "from openviking.models.embedder.local_embedders import LocalDenseEmbedder; "
  720. f"e=LocalDenseEmbedder(model_name={EMBEDDING_MODEL!r},cache_dir={str(paths.model_cache)!r}); "
  721. "v=e.embed('memory setup validation').dense_vector; "
  722. f"assert len(v)=={EMBEDDING_DIMENSION} and all(math.isfinite(x) for x in v) and any(v)"
  723. )
  724. log_path = _server_log_path(paths.root.parent)
  725. _prepare_private_directory(log_path.parent)
  726. if log_path.is_symlink():
  727. raise QuickLocalSetupError("Quick Local log must belong to this profile.")
  728. if not log_path.exists():
  729. log_path.touch(mode=0o600)
  730. if os.name != "nt":
  731. log_path.chmod(0o600)
  732. try:
  733. with log_path.open("ab") as log:
  734. result = subprocess.run(
  735. [str(paths.runtime_python), "-c", script],
  736. env=_private_child_env(paths.root.parent),
  737. stdin=subprocess.DEVNULL,
  738. stdout=log,
  739. stderr=subprocess.STDOUT,
  740. check=False,
  741. timeout=_HEALTH_TIMEOUT_SECONDS,
  742. )
  743. if result.returncode:
  744. raise QuickLocalSetupError(
  745. "Quick Local's embedding model could not run. "
  746. f"Review {log_path}; use Custom setup with a separate server if needed."
  747. )
  748. except subprocess.TimeoutExpired as exc:
  749. raise QuickLocalSetupError(
  750. f"Quick Local's embedding check timed out. Review {log_path} and retry setup."
  751. ) from exc
  752. def find_available_port(
  753. *,
  754. preferred_endpoint: Optional[str] = None,
  755. first_port: int = _DEFAULT_PORT,
  756. attempts: int = _PORT_ATTEMPTS,
  757. ) -> Optional[int]:
  758. preferred_port = _endpoint_port(preferred_endpoint)
  759. candidates = range(first_port, first_port + attempts)
  760. if preferred_port is not None and (
  761. preferred_port in candidates or (first_port == _DEFAULT_PORT and preferred_port == 1933)
  762. ):
  763. candidates = [
  764. preferred_port,
  765. *(port for port in candidates if port != preferred_port),
  766. ]
  767. for port in candidates:
  768. if _can_bind_local_port("127.0.0.1", port):
  769. return port
  770. return None
  771. def _can_bind_local_port(host: str, port: int) -> bool:
  772. family = socket.AF_INET6 if ":" in host else socket.AF_INET
  773. try:
  774. # Some Unix kernels allow a specific-address bind beside a wildcard
  775. # listener with SO_REUSEADDR. Never take an already reachable port.
  776. with socket.socket(family, socket.SOCK_STREAM) as probe:
  777. probe.settimeout(0.2)
  778. if probe.connect_ex((host, port)) == 0:
  779. return False
  780. with socket.socket(family, socket.SOCK_STREAM) as candidate:
  781. if os.name == "nt":
  782. candidate.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  783. else:
  784. # Match Uvicorn: permit restart after closed connections remain
  785. # in TIME_WAIT, but never bind beside a listening server.
  786. candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  787. candidate.bind((host, port))
  788. return True
  789. except OSError:
  790. return False
  791. def find_reusable_endpoint(
  792. paths: QuickLocalPaths,
  793. health_check: HealthCheck,
  794. ) -> Optional[str]:
  795. endpoint = _configured_endpoint(paths)
  796. if endpoint is None:
  797. return None
  798. healthy, _message = health_check(endpoint)
  799. return endpoint if healthy and server_belongs_to_profile(paths, endpoint) else None
  800. def _configured_endpoint(paths: QuickLocalPaths) -> Optional[str]:
  801. if not paths.server_config.is_file() or not paths.ovcli_config.is_file():
  802. return None
  803. try:
  804. server_config = json.loads(paths.server_config.read_text(encoding="utf-8"))
  805. storage = server_config.get("storage", {}) if isinstance(server_config, dict) else {}
  806. if not isinstance(storage, dict) or not _paths_equivalent(
  807. storage.get("workspace"), paths.workspace
  808. ):
  809. return None
  810. profile = json.loads(paths.ovcli_config.read_text(encoding="utf-8"))
  811. return _normalize_local_endpoint(profile.get("url") if isinstance(profile, dict) else "")
  812. except (OSError, json.JSONDecodeError, TypeError, ValueError):
  813. return None
  814. def _server_key(paths: QuickLocalPaths) -> str:
  815. try:
  816. saved = json.loads(paths.server_config.read_text(encoding="utf-8"))
  817. if _paths_equivalent(saved.get("storage", {}).get("workspace"), paths.workspace):
  818. key = _clean_value(saved.get("server", {}).get("root_api_key"))
  819. if key:
  820. return key
  821. except (OSError, ValueError, AttributeError):
  822. pass
  823. return secrets.token_urlsafe(32)
  824. def server_belongs_to_profile(paths: QuickLocalPaths, endpoint: str) -> bool:
  825. """Do not reuse an unrelated service that took the saved local port."""
  826. try:
  827. saved = json.loads(paths.server_config.read_text(encoding="utf-8"))
  828. if not _paths_equivalent(saved.get("storage", {}).get("workspace"), paths.workspace):
  829. return False
  830. return _server_accepts_config(saved, endpoint)
  831. except (OSError, ValueError, AttributeError):
  832. return False
  833. def _server_accepts_config(config: Mapping[str, Any], endpoint: str) -> bool:
  834. import httpx
  835. try:
  836. key = _clean_value(config.get("server", {}).get("root_api_key"))
  837. if not key:
  838. return False
  839. with httpx.Client(timeout=3.0, trust_env=False) as client:
  840. health = client.get(f"{endpoint}/health").json()
  841. if (
  842. health.get("auth_mode") != "trusted"
  843. or health.get("root_api_key_required") is not True
  844. ):
  845. return False
  846. response = client.get(f"{endpoint}/api/v1/admin/accounts", headers={"X-API-Key": key})
  847. return response.status_code == 200 and response.json().get("status") == "ok"
  848. except (ValueError, AttributeError, httpx.HTTPError):
  849. return False
  850. def _validate_tenant_access(endpoint: str, key: str) -> None:
  851. """Exercise a data write only in the disposable validation workspace."""
  852. import httpx
  853. try:
  854. response = httpx.post(
  855. f"{endpoint}/api/v1/sessions",
  856. json={},
  857. headers={
  858. "X-API-Key": key,
  859. "X-OpenViking-Account": "default",
  860. "X-OpenViking-User": "default",
  861. },
  862. timeout=5.0,
  863. trust_env=False,
  864. )
  865. response.raise_for_status()
  866. if response.json().get("status") != "ok":
  867. raise ValueError("session creation failed")
  868. except (ValueError, httpx.HTTPError) as exc:
  869. raise QuickLocalSetupError(
  870. "Quick Local could not validate memory data access. Review the server log and retry."
  871. ) from exc
  872. def _write_ovcli_profile(path: Path, endpoint: str, server_config: Mapping[str, Any]) -> None:
  873. atomic_json_write(
  874. path,
  875. {
  876. "url": endpoint,
  877. "root_api_key": server_config["server"]["root_api_key"],
  878. "account": "default",
  879. "user": "default",
  880. "actor_peer_id": "hermes",
  881. },
  882. mode=0o600,
  883. )
  884. def connection_config(provider_config: Mapping[str, Any], hermes_home: Path) -> dict[str, Any]:
  885. """Resolve only this profile's managed files, including after profile import."""
  886. paths = managed_paths(hermes_home)
  887. repair_private_paths(paths)
  888. endpoint = _configured_endpoint(paths)
  889. if endpoint is None:
  890. raise QuickLocalSetupError(
  891. "Quick Local configuration is missing or belongs to another profile. Run hermes memory setup openviking again."
  892. )
  893. try:
  894. profile = json.loads(paths.ovcli_config.read_text(encoding="utf-8"))
  895. saved = json.loads(paths.server_config.read_text(encoding="utf-8"))
  896. if not isinstance(profile, dict) or not isinstance(saved, dict):
  897. raise ValueError("invalid configuration")
  898. except (OSError, ValueError) as exc:
  899. raise QuickLocalSetupError(
  900. "Quick Local configuration could not be read. Run hermes memory setup openviking again."
  901. ) from exc
  902. if (
  903. not isinstance(saved.get("server"), dict)
  904. or not profile.get("root_api_key")
  905. or profile["root_api_key"] != saved["server"].get("root_api_key")
  906. ):
  907. raise QuickLocalSetupError(
  908. "Quick Local credentials are incomplete. Run hermes memory setup openviking again."
  909. )
  910. return profile
  911. def _start_validation_server(
  912. endpoint: str,
  913. config_path: Path,
  914. hermes_home: Path,
  915. server_command: Path,
  916. ) -> subprocess.Popen:
  917. if not server_command.is_file():
  918. raise QuickLocalSetupError("openviking-server was not found after installation.")
  919. command = str(server_command)
  920. host, port = _endpoint_bind(endpoint)
  921. if not _can_bind_local_port(host, port):
  922. raise QuickLocalSetupError(
  923. f"Local port {host}:{port} became unavailable before OpenViking "
  924. "could start. Retry Quick Local setup."
  925. )
  926. log_path = _server_log_path(hermes_home)
  927. log_path.parent.mkdir(parents=True, exist_ok=True)
  928. if not log_path.exists():
  929. log_path.touch(mode=0o600)
  930. log_path.chmod(0o600)
  931. child_env = _private_child_env(hermes_home)
  932. from hermes_cli._subprocess_compat import windows_detach_popen_kwargs
  933. popen_kwargs: dict[str, Any] = windows_detach_popen_kwargs()
  934. command_args = [
  935. command,
  936. "--config",
  937. str(config_path),
  938. "--host",
  939. host,
  940. "--port",
  941. str(port),
  942. ]
  943. try:
  944. with log_path.open("ab") as log_file:
  945. common_kwargs: dict[str, Any] = {
  946. "stdout": log_file,
  947. "stderr": log_file,
  948. "env": child_env,
  949. "cwd": hermes_home,
  950. }
  951. try:
  952. return subprocess.Popen(
  953. command_args,
  954. **common_kwargs,
  955. **popen_kwargs,
  956. stdin=subprocess.DEVNULL,
  957. )
  958. except OSError:
  959. if os.name != "nt":
  960. raise
  961. from hermes_cli._subprocess_compat import (
  962. windows_detach_flags_without_breakaway,
  963. )
  964. return subprocess.Popen(
  965. command_args,
  966. **common_kwargs,
  967. creationflags=windows_detach_flags_without_breakaway(),
  968. stdin=subprocess.DEVNULL,
  969. )
  970. except Exception as exc:
  971. raise QuickLocalSetupError(f"Could not start the OpenViking server: {exc}") from exc
  972. def _wait_for_health(
  973. endpoint: str,
  974. health_check: HealthCheck,
  975. *,
  976. process: Optional[subprocess.Popen] = None,
  977. timeout_seconds: float = _HEALTH_TIMEOUT_SECONDS,
  978. ) -> bool:
  979. deadline = time.monotonic() + timeout_seconds
  980. while time.monotonic() < deadline:
  981. healthy, _message = health_check(endpoint)
  982. if healthy:
  983. return True
  984. if process is not None and process.poll() is not None:
  985. return False
  986. time.sleep(_HEALTH_POLL_INTERVAL_SECONDS)
  987. return False
  988. def _stop_process(process: subprocess.Popen) -> bool:
  989. import psutil
  990. from .local_server import stop_process_tree
  991. try:
  992. if process.poll() is not None:
  993. return True
  994. stop_process_tree(psutil.Process(process.pid), timeout=_PROCESS_STOP_TIMEOUT_SECONDS)
  995. process.wait(timeout=_PROCESS_STOP_TIMEOUT_SECONDS)
  996. return True
  997. except psutil.NoSuchProcess:
  998. # The child can finish between poll() and taking its process handle.
  999. return True
  1000. except Exception:
  1001. return False
  1002. def _has_copyable_static_credentials(
  1003. provider: str,
  1004. source: str,
  1005. api_key: str,
  1006. ) -> bool:
  1007. """Return whether Hermes explicitly classifies this credential as static."""
  1008. if not api_key or api_key == "aws-sdk":
  1009. return False
  1010. if provider == "custom":
  1011. return source in {"direct-alias", "env/config"} or source.startswith(
  1012. (
  1013. "custom_provider:",
  1014. "pool:",
  1015. )
  1016. )
  1017. if provider == "openrouter":
  1018. return source == "env/config" or source.startswith(
  1019. (
  1020. "credential_pool:",
  1021. "env:",
  1022. "manual:",
  1023. "pool:",
  1024. )
  1025. )
  1026. from hermes_cli.auth import PROVIDER_REGISTRY
  1027. provider_config = PROVIDER_REGISTRY.get(provider)
  1028. if provider == "copilot" or provider_config is None or provider_config.auth_type != "api_key":
  1029. return False
  1030. if source in {"config", "default", "env", "local-offline"}:
  1031. return True
  1032. api_key_sources = {value.lower() for value in provider_config.api_key_env_vars}
  1033. if source in api_key_sources:
  1034. return True
  1035. if source.startswith("env:"):
  1036. return source.removeprefix("env:") in api_key_sources
  1037. if source.startswith("credential_pool:"):
  1038. return source.removeprefix("credential_pool:") == provider
  1039. return source.startswith("manual:")
  1040. def _stored_server_config_matches(
  1041. paths: QuickLocalPaths,
  1042. expected: Mapping[str, Any],
  1043. ) -> bool:
  1044. try:
  1045. saved = json.loads(paths.server_config.read_text(encoding="utf-8"))
  1046. except (OSError, json.JSONDecodeError, TypeError, ValueError):
  1047. return False
  1048. return saved == expected
  1049. def _prepare_private_directory(path: Path) -> None:
  1050. if path.is_symlink():
  1051. raise QuickLocalSetupError("Quick Local private directories must belong to this profile.")
  1052. path.mkdir(parents=True, exist_ok=True, mode=0o700)
  1053. if os.name != "nt":
  1054. path.chmod(0o700)
  1055. def repair_private_paths(paths: QuickLocalPaths) -> None:
  1056. """Backup/import may restore permissive modes on plugin-owned files."""
  1057. _prepare_private_directory(paths.root)
  1058. for path in (
  1059. paths.server_config,
  1060. paths.ovcli_config,
  1061. paths.restart_required_marker,
  1062. paths.root / "server-process.json",
  1063. paths.root / "server.lock",
  1064. paths.root / "runtime-requirements.json",
  1065. ):
  1066. if path.is_symlink():
  1067. raise QuickLocalSetupError("Quick Local private files must belong to this profile.")
  1068. if path.exists() and os.name != "nt":
  1069. path.chmod(0o600)
  1070. def _pm_available() -> bool:
  1071. return importlib.util.find_spec("pm") is not None
  1072. def _private_child_env(hermes_home: Path) -> dict[str, str]:
  1073. from tools.environments import local as subprocess_env
  1074. if hasattr(subprocess_env, "served_profile_child_env"):
  1075. env = subprocess_env.served_profile_child_env(target_home=hermes_home)
  1076. else:
  1077. env = subprocess_env.hermes_subprocess_env()
  1078. env["HERMES_HOME"] = str(hermes_home)
  1079. for key in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV"):
  1080. env.pop(key, None)
  1081. return env
  1082. def _server_log_path(hermes_home: Path) -> Path:
  1083. return hermes_home / "logs" / "openviking-server.log"
  1084. def _normalize_local_endpoint(value: Any) -> Optional[str]:
  1085. endpoint = _clean_value(value).rstrip("/")
  1086. if not endpoint:
  1087. return None
  1088. if "://" not in endpoint:
  1089. endpoint = f"http://{endpoint}"
  1090. parsed = urlparse(endpoint)
  1091. if parsed.scheme.lower() != "http":
  1092. return None
  1093. if (parsed.hostname or "").lower() not in {"localhost", "127.0.0.1", "::1"}:
  1094. return None
  1095. host = f"[{parsed.hostname}]" if parsed.hostname == "::1" else parsed.hostname
  1096. return f"http://{host}:{parsed.port or _DEFAULT_PORT}"
  1097. def _endpoint_bind(endpoint: str) -> tuple[str, int]:
  1098. parsed = urlparse(endpoint)
  1099. return parsed.hostname or "127.0.0.1", parsed.port or _DEFAULT_PORT
  1100. def _endpoint_port(endpoint: Optional[str]) -> Optional[int]:
  1101. if not endpoint:
  1102. return None
  1103. try:
  1104. return urlparse(endpoint).port or _DEFAULT_PORT
  1105. except ValueError:
  1106. return None
  1107. def _paths_equivalent(left: Any, right: Path) -> bool:
  1108. if not isinstance(left, (str, os.PathLike)):
  1109. return False
  1110. try:
  1111. return Path(left).expanduser().resolve() == right.expanduser().resolve()
  1112. except (OSError, RuntimeError, TypeError, ValueError):
  1113. return False
  1114. def _clean_value(value: Any) -> str:
  1115. return value.strip() if isinstance(value, str) else ""