Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(hermes): add Quick Local setup with local embeddings (#5465)
z1gon4c2a88729bab
diff --git a/.github/workflows/hermes-plugin-tests.yml b/.github/workflows/hermes-plugin-tests.ymlindex 9a55b66c0..6898dc9fa 100644--- a/.github/workflows/hermes-plugin-tests.yml+++ b/.github/workflows/hermes-plugin-tests.yml@@ -7,12 +7,14 @@ on:- 'examples/hermes-plugin/**'- '.github/workflows/hermes-plugin-tests.yml'- 'scripts/check-hermes-plugin-install.py'+ - 'scripts/check-hermes-quick-local.py'push:branches: [main, develop]paths:- 'examples/hermes-plugin/**'- '.github/workflows/hermes-plugin-tests.yml'- 'scripts/check-hermes-plugin-install.py'+ - 'scripts/check-hermes-quick-local.py'workflow_dispatch:permissions:@@ -35,7 +37,7 @@ jobs:uses: actions/checkout@v6with:repository: NousResearch/hermes-agent- ref: 58d146e961108e84f41bfed59f586121ecb3372c+ ref: 5bba024d8ddd388f56f354c1f789be825e3d8a3cpath: .ci/hermes-agentpersist-credentials: false@@ -89,3 +91,72 @@ jobs:${{ runner.temp }}/hermes-plugin-install/*.log${{ runner.temp }}/hermes-plugin-install/evidence.jsonif-no-files-found: ignore++ quick-local-platforms:+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-24.04, ubuntu-24.04-arm, macos-14, windows-2025]+ host: [main]+ include:+ - os: ubuntu-24.04+ host: release+ python: '3.13'+ hermes_ref: e3dd27ee2d8b011737a4eea8e3eb3d711ab78690 # v2026.9.24, pre-PM+ runs-on: ${{ matrix.os }}+ timeout-minutes: 30+ defaults:+ run:+ shell: bash+ working-directory: .ci/hermes-agent+ steps:+ - uses: actions/checkout@v6+ with:+ persist-credentials: false+ - uses: actions/checkout@v6+ with:+ repository: NousResearch/hermes-agent+ ref: ${{ matrix.hermes_ref || '5bba024d8ddd388f56f354c1f789be825e3d8a3c' }}+ path: .ci/hermes-agent+ persist-credentials: false+ - uses: actions/setup-python@v6+ with:+ python-version: ${{ matrix.python || '3.14' }}+ - uses: astral-sh/setup-uv@v7+ with:+ version: '0.12.3'+ enable-cache: true+ cache-dependency-glob: |+ .ci/hermes-agent/uv.lock+ examples/hermes-plugin/local_packages.py+ - name: Install the reviewed host and test dependencies+ run: |+ if [ '${{ matrix.host }}' = release ]; then+ uv sync --frozen --extra dev --no-install-project+ else+ uv sync --frozen --group dev --no-install-project+ fi+ PYTHON=$(uv run --no-sync python -c 'import sys; print(sys.executable)')+ uv pip install --python "$PYTHON" PyYAML==6.0.3+ - name: Check process ownership and installer failures+ run: |+ uv run --no-sync python -m pytest \+ "$GITHUB_WORKSPACE/examples/hermes-plugin/tests/test_local_lifecycle.py" \+ "$GITHUB_WORKSPACE/examples/hermes-plugin/tests/test_quick_local.py" \+ "$GITHUB_WORKSPACE/examples/hermes-plugin/tests/test_quick_local_routes.py" \+ "$GITHUB_WORKSPACE/examples/hermes-plugin/tests/test_quick_local_preflight.py" \+ --confcutdir="$GITHUB_WORKSPACE/examples/hermes-plugin/tests" -p no:cacheprovider -q+ - name: Install and run real Quick Local services+ run: |+ ARGS=()+ if [ '${{ matrix.host }}' = release ]; then ARGS+=(--legacy-uv); fi+ uv run --no-sync python "$GITHUB_WORKSPACE/scripts/check-hermes-quick-local.py" \+ --hermes-root "$PWD" --output-dir "$RUNNER_TEMP/quick-local" "${ARGS[@]}"+ - uses: actions/upload-artifact@v4+ if: always()+ with:+ name: quick-local-${{ matrix.os }}-${{ matrix.host }}+ path: |+ ${{ runner.temp }}/quick-local/evidence.json+ ${{ runner.temp }}/quick-local/*/logs/openviking-server.log+ if-no-files-found: ignorediff --git a/examples/hermes-plugin/DEVELOPMENT.md b/examples/hermes-plugin/DEVELOPMENT.mdindex d0d202189..c421a2228 100644--- a/examples/hermes-plugin/DEVELOPMENT.md+++ b/examples/hermes-plugin/DEVELOPMENT.md@@ -47,6 +47,31 @@ with the original author retained. This port leaves memory URI handling as itis: the original PR's UID-less `viking://user/memories/...` rewrite is notaccepted by current OpenViking servers.+Quick Local adapts [Hermes PR #94851](https://github.com/NousResearch/hermes-agent/pull/94851)+(head `d15e0e65d67a2dd6d3f3ab09a382c1f1684e2560`). Provisioning remains separate+from the setup UI. The port uses current Hermes PM, authenticated server reuse,+and paths derived from the provider's bound home. On Python 3.14, the private+server uses LiteLLM 1.83.7, within OpenViking's supported range; later LiteLLM+releases exclude that Python version. The profile server controller verifies+the PID, creation time, executable and config path before stopping a process.+It repairs permissions on plugin-owned private files after backup restoration;+no Hermes backup changes are required.++`local_packages.py` selects reviewed OpenViking and llama-cpp-python binaries+with SHA-256 verification before installation. Both PM and pre-PM installers+receive verified local wheel files. Setup records the applied requirements so+that a later pin change updates an existing private runtime. Update pins only after installation,+model and service checks pass on the listed platforms. Source builds require+explicit consent. Platform CI runs real installation, local embedding, capture,+restart and port-recovery checks. It uses a static test LLM configuration and+does not establish live memory extraction; that remains a release check.+The reviewed hashes cover the OpenViking and llama-cpp-python wheels only.+PM/uv resolve the other dependencies; this is not a fully locked server runtime.+Source builds use package version pins without reviewed binary hashes. A platform+needs a tested OpenViking/embedding-wheel pair for the prebuilt path.+Setup also checks LLM access through the installed OpenViking backend. The CI+fixture must serve an actual completion; an unreachable LLM must fail setup.+## Migration coordinationBefore the catalog cutover, submit a Hermes catalog entry with:@@ -74,8 +99,9 @@ bundled provider takes precedence while it remains present.This plugin does not add a Desktop `config_schema.py`.The wizard uses private helpers from `hermes_cli.memory_setup`; changes to-those helpers require compatibility checks. The plugin uses HTTP and does not-install or package the OpenViking server.+those helpers require compatibility checks. The plugin uses HTTP. Quick Local installs the server in a separate+profile runtime through Hermes PM, or the earlier Hermes uv installer on the+tested release baseline. It does not add server dependencies to Hermes.## Validationdiff --git a/examples/hermes-plugin/README.md b/examples/hermes-plugin/README.mdindex 558f5822c..4eb2c38b5 100644--- a/examples/hermes-plugin/README.md+++ b/examples/hermes-plugin/README.md@@ -57,12 +57,12 @@ the gateway after the upgrade. For catalog installations, use## Requirements- Python 3.11 or newer in the Hermes environment-- An OpenViking server reachable from Hermes, or OpenViking Service credentials+- A reachable OpenViking server, OpenViking Service credentials, or Quick Local setup- For a self-hosted server, OpenViking installed in its own environment or container-The plugin connects over HTTP. Do not install the OpenViking server into the-Hermes environment. For local server start from the setup wizard, make the-`openviking-server` command available on `PATH`.+The plugin connects over HTTP. Keep the server in a separate environment.+Quick Local creates that environment for you. For Custom setup to start a local+server, make `openviking-server` available on `PATH`.OpenViking 0.2.14 or newer is required. Hermes can identify older servers thatexpose the legacy status-only health response, but those releases do not provide@@ -72,7 +72,7 @@ admin credentials, and OpenViking 0.4.17 or newer for root or local development.## Setup-For a self-hosted deployment, prepare OpenViking in its server environment:+For a Custom self-hosted deployment, prepare OpenViking in its server environment:```bashopenviking-server init@@ -90,6 +90,79 @@ The setup can link to an existing `~/.openviking/ovcli.conf`, copy its currentconnection values into Hermes, or create a minimal `ovcli.conf` when one doesnot exist.+For a new connection, choose **OpenViking Service**, **Custom**, or **Quick Local**.++Quick Local installs OpenViking 0.4.22 in a private runtime. It uses+`bge-small-zh-v1.5-f16` for local embeddings and copies the configured Hermes LLM+settings for memory extraction. The LLM must use a static API key or Hermes's+local llama.cpp server, with an OpenAI-compatible or Anthropic-compatible API.+OAuth and cloud-native+credentials cannot be copied; use Custom for those deployments.+Google AI Studio uses its OpenAI-compatible endpoint. Static OpenAI and xAI+API keys use Chat Completions; the selected model must support that API.+Kimi Coding retains Hermes's client attribution. Anthropic routes that need+Bearer authentication, including MiniMax and Azure Foundry, and proxy keys+that LiteLLM would treat as OAuth require a separately configured Custom server.+Setup checks the copied LLM with one short completion before activation.+It retries once for a timeout, HTTP 429, or HTTP 5xx. Other errors fail+immediately. The message and server log identify the error without recording+credentials or the provider's response body.++Quick Local stores its runtime, data, model cache, and private configuration in+`$HERMES_HOME/openviking/`. Setup validates it, then leaves its localhost server+running so the first Hermes turn can use memory. On later starts, Hermes starts+the server in the background if it has stopped. The embedding model downloads once, about+46 MiB. The LLM can still use a remote API. Server logs are in+`$HERMES_HOME/logs/openviking-server.log`.+The first installation needs network access. It downloads prebuilt packages+with pinned hashes on macOS 14+ (Apple Silicon), Linux with glibc 2.31++(x86-64 or ARM64), and Windows x86-64. Setup asks before a source build on+other platforms. A source build needs native development tools and can take+several minutes. You can choose Custom instead and use a separate server.+Downloads require access to PyPI, GitHub and Hugging Face. The local BGE model+is trained for Chinese; use Custom for a server with a different embedding model.++Run setup again after changing the Hermes model or API key. Setup validates+the new settings and restarts this profile's server. Data and the model cache+are retained. Each profile has its own server and port; Quick Local moves to+a free port if another service takes its saved port.+New setups use ports 1934–1953, leaving OpenViking's default port 1933 free.+Existing Quick Local profiles keep their saved port when it is available.++The server stays running after Hermes exits. Use these commands in the same+Hermes profile to control it:++```bash+hermes openviking local status+hermes openviking local stop+hermes openviking local start+hermes openviking local restart+```++Stopping the server retains its data. Hermes starts it again when memory is+next used, including from a running gateway. Close those sessions or disable+OpenViking memory for it to stay stopped. While background startup or recovery+is in progress, new turns are not captured until the server is ready.+These commands and Quick Local setup require the external provider+to be active; a bundled copy still takes precedence where present.+Switching to Cloud or Custom stops this profile's managed server and retains+its data. `local start` and `local restart` require Quick Local to be selected;+`local status` and `local stop` remain available for the retained server.+The existing Cloud and Custom connection choices remain available.+Hermes backups include Quick Local files under the profile home; the plugin+adds a linked `ovcli.conf` only when it is outside that home.++Before removing the plugin, close Hermes sessions and stop the gateway for+this profile. Run `hermes openviking local stop`, then select a+different memory provider or disable OpenViking memory. Finally, run+`hermes plugins remove openviking`. The private runtime, model cache and data+remain in `$HERMES_HOME/openviking/`; they can use more than 1 GB per profile.+Plugin removal does not stop a running server.+Each running profile also uses several hundred MB of memory. Package upgrades+retain old runtime generations and wheel files, so disk use can increase.+After restoring a backup on another machine, run setup again to rebuild any+runtime excluded from the backup before using Quick Local.+Setup first asks how the Hermes instance is used:| Preset | Hermes conversation history | OpenViking long-term recall |@@ -140,6 +213,8 @@ Hermes reads provider settings from the initialized profile's `config.yaml`,profile secrets, and linked `ovcli.conf`. Connection values resolve in this order:profile environment, linked OpenViking config, Hermes YAML, then defaults. API keyscome from profile secrets or the linked OpenViking config, not Hermes YAML.+Quick Local uses its own saved connection and ignores connection environment+overrides. Recall and commit settings still accept their documented overrides.After initialization, the provider keeps that profile for connection, identity,and recall settings, including when another profile is active in the sameprocess. For the launch profile, process-level `OPENVIKING_*` values fill missing@@ -179,9 +254,10 @@ memory:Existing non-empty `OPENVIKING_AGENT`, YAML `agent`, and linked OpenViking`actor_peer_id` or legacy `agent_id` values retain their behavior. Resolution-order remains environment, linked OpenViking config, then Hermes YAML. To use-no peer, remove the peer value from each configured source and start a new-Hermes session.+order remains environment, linked OpenViking config, then Hermes YAML for Cloud+and Custom connections. Quick Local uses the `hermes` peer. To use+no peer on a Cloud or Custom connection, remove the peer value from each+configured source and start a new Hermes session.Upgrades do not move or delete existing memories. Installations that reliedon the old implicit `hermes` peer now use user memory for new writes. Withoutdiff --git a/examples/hermes-plugin/__init__.py b/examples/hermes-plugin/__init__.pyindex 6f67468c3..074cc4f16 100644--- a/examples/hermes-plugin/__init__.py+++ b/examples/hermes-plugin/__init__.py@@ -45,6 +45,8 @@ from hermes_constants import get_hermes_home, get_process_hermes_homefrom tools.registry import tool_errorfrom utils import atomic_json_write, env_var_enabled+from . import quick_local+try:import fcntlexcept ImportError: # pragma: no cover - Windows@@ -870,21 +872,36 @@ def _profile_openviking_env(hermes_home: Optional[str]) -> Optional[dict]:return {} # A failed profile read must not borrow another profile's credentials.+def _provider_ovcli_config_path(provider_config: dict, *, env: Optional[dict] = None, hermes_home=None) -> Path:+ if provider_config.get("deployment") == quick_local.DEPLOYMENT:+ return quick_local.managed_paths(Path(hermes_home or get_hermes_home())).ovcli_config+ return _resolve_ovcli_config_path(str(provider_config.get("ovcli_config_path") or ""), env=env)++def _ovcli_values_for(provider_config: dict, *, env: Optional[dict] = None) -> dict:"""Connection values from the linked ovcli profile, or {} when none is linked."""if not provider_config.get("use_ovcli_config"):return {}- ovcli_path = _resolve_ovcli_config_path(str(provider_config.get("ovcli_config_path") or ""), env=env)+ if provider_config.get("deployment") == quick_local.DEPLOYMENT:+ return _connection_values_from_ovcli(quick_local.connection_config(provider_config, get_hermes_home()))+ ovcli_path = _provider_ovcli_config_path(provider_config, env=env)return _connection_values_from_ovcli(_load_ovcli_config(ovcli_path))-def _resolve_connection_settings(provider_config: Optional[dict] = None, *, env: Optional[dict] = None) -> dict:+def _resolve_connection_settings(provider_config: Optional[dict] = None, *, env: Optional[dict] = None, hermes_home=None) -> dict:"""Layering: env -> linked ovcli profile -> config.yaml -> built-in default.An env account/user (even empty) is authoritative; the secret api_key nevercomes from config.yaml. Every env read goes through the profile secret scope:under multiplexing ``os.environ`` is the DEFAULT profile's .env, and a raw readwould spend its key and tenant on behalf of a secondary profile."""provider_config = dict(provider_config or {})+ if provider_config.get("deployment") == quick_local.DEPLOYMENT:+ try:+ profile = quick_local.connection_config(provider_config, Path(hermes_home or get_hermes_home()))+ except quick_local.QuickLocalSetupError as exc:+ raise _OpenVikingEndpointError(str(exc)) from exc+ values = _connection_values_from_ovcli(profile)+ return {key: values[key] or ("default" if key in ("account", "user") else _DEFAULT_AGENT if key == "agent" else "") for key in _CONNECTION_KEYS}ovcli_values = _ovcli_values_for(provider_config, env=env)def layered(key: str, default: str = "", *, env_authoritative: bool = False) -> str:@@ -1152,10 +1169,10 @@ def _emit_runtime(message: str, callback=None, *, kind: str = "warning") -> Nonelogger.debug("OpenViking runtime %s callback failed", kind, exc_info=True)-def _runtime_openviking_timeout_message(endpoint: str) -> str:+def _runtime_openviking_timeout_message(endpoint: str, timeout_seconds: float = _LOCAL_OPENVIKING_AUTOSTART_TIMEOUT) -> str:return (f"Local OpenViking server at {endpoint} is not reachable. Tried to start openviking-server, but it did not "- f"become reachable within {_LOCAL_OPENVIKING_AUTOSTART_TIMEOUT:.0f} seconds. {_RETRY_LATER}"+ f"become reachable within {timeout_seconds:.0f} seconds. {_RETRY_LATER}")@@ -1360,7 +1377,12 @@ class OpenVikingMemoryProvider(MemoryProvider):"""The resolved ovcli config (default ~/.openviking/ovcli.conf) so endpoint/api-keysurvive backup/import. The backup walk itself drops paths outside $HOME."""try:- return [str(_resolve_ovcli_config_path())]+ config, env = self._profile_config_and_env()+ if not config.get("use_ovcli_config"):+ return []+ home = Path(self._hermes_home or get_hermes_home()).resolve()+ path = _provider_ovcli_config_path(config, env=env, hermes_home=home)+ return [] if path.resolve().is_relative_to(home) else [str(path)]except Exception:return []@@ -1411,6 +1433,8 @@ class OpenVikingMemoryProvider(MemoryProvider):self._failed_refresh: Optional[tuple] = Noneself._runtime_start_thread: Optional[threading.Thread] = Noneself._runtime_start_pending = False+ self._runtime_status_callback = None+ self._runtime_warning_callback = Noneself._shutting_down = False # finalizers stop issuing network writes# Non-primary contexts (cron/subagent/flush) skip OpenViking writes; resolved in# initialize() from the host's agent_context.@@ -1465,7 +1489,7 @@ class OpenVikingMemoryProvider(MemoryProvider):if not provider_config.get("use_ovcli_config"):return {key: "(set)" if key in ("api_key", "root_api_key") else value for key, value in provider_config.items()}- ovcli_path = _resolve_ovcli_config_path(str(provider_config.get("ovcli_config_path") or ""))+ ovcli_path = _provider_ovcli_config_path(provider_config)display = {"use_ovcli_config": True, "ovcli_config_path": str(ovcli_path)}try:settings = _resolve_connection_settings(provider_config)@@ -1474,7 +1498,10 @@ class OpenVikingMemoryProvider(MemoryProvider):return displaydisplay["endpoint"] = settings.get("endpoint") or _DEFAULT_ENDPOINTdisplay.update({key: settings[key] for key in ("agent", "account", "user") if settings.get(key)})- if env_overrides := [key for key in _OPENVIKING_ENV_KEYS if key in os.environ]:+ if provider_config.get("deployment") == quick_local.DEPLOYMENT:+ display["deployment"] = quick_local.DEPLOYMENT+ display["server_config_path"] = str(quick_local.managed_paths(get_hermes_home()).server_config)+ elif env_overrides := [key for key in _OPENVIKING_ENV_KEYS if key in os.environ]:display["env_overrides"] = ", ".join(env_overrides)return display@@ -1490,12 +1517,12 @@ class OpenVikingMemoryProvider(MemoryProvider):# -- connection lifecycle ------------------------------------------------- def _start_runtime_openviking_waiter(self, *, endpoint: str, status_callback=None, warning_callback=None) -> None:+ def _start_runtime_openviking_waiter(self, *, endpoint: str, managed_start=None, status_callback=None, warning_callback=None) -> None:# Caller holds _runtime_start_lock and reserved ownership via _runtime_start_pending.if self._runtime_start_thread and self._runtime_start_thread.is_alive():returnself._runtime_start_thread = spawn_context_thread(- lambda: self._finish_runtime_openviking_start(endpoint=endpoint, status_callback=status_callback, warning_callback=warning_callback),+ lambda: self._finish_runtime_openviking_start(endpoint=endpoint, managed_start=managed_start, status_callback=status_callback, warning_callback=warning_callback),name="openviking-runtime-start")self._runtime_start_thread.start()@@ -1520,21 +1547,52 @@ class OpenVikingMemoryProvider(MemoryProvider):snapshot = self._conn_snapshot or self._settings_tuple()# Recovery may use only the matching endpoint and identity. Do# not persist credentials, or use the same marker after A -> B -> A.- key = hashlib.sha256(json.dumps(snapshot).encode()).hexdigest()+ recovery_snapshot = snapshot+ config, _env = self._profile_config_and_env()+ if config.get("deployment") == quick_local.DEPLOYMENT:+ # The managed workspace remains the same when a foreign+ # listener forces a port change. Keep recovery tied to that+ # workspace and tenant, while marker_id still separates+ # concurrent connection generations.+ paths = quick_local.managed_paths(Path(self._hermes_home or get_hermes_home()))+ recovery_snapshot = (quick_local.DEPLOYMENT, str(paths.workspace), *snapshot[2:])+ key = hashlib.sha256(json.dumps(recovery_snapshot).encode()).hexdigest()if self._commit_scope is not None:self._turn_count = 0self._commit_scope = _CommitScope(self._client, key)return self._commit_scope- def _finish_runtime_openviking_start(self, *, endpoint: Optional[str] = None, status_callback=None, warning_callback=None) -> None:+ def _finish_runtime_openviking_start(self, *, endpoint: Optional[str] = None, managed_start=None, status_callback=None, warning_callback=None) -> None:endpoint = endpoint or self._endpointdef stale() -> bool:return self._shutting_down or self._endpoint != endpoint- if not _wait_for_openviking_health(endpoint, timeout_seconds=_LOCAL_OPENVIKING_AUTOSTART_TIMEOUT, should_stop=stale):+ config, _env = self._profile_config_and_env()+ managed = config.get("deployment") == quick_local.DEPLOYMENT+ timeout = quick_local._HEALTH_TIMEOUT_SECONDS if managed else _LOCAL_OPENVIKING_AUTOSTART_TIMEOUT+ if managed_start is not None:+ from .local_server import LocalServer+ server = LocalServer(Path(self._hermes_home or get_hermes_home()))+ try:+ ready = server.wait_ready(managed_start,+ _validate_openviking_reachability,+ should_stop=stale, timeout=timeout)+ except Exception as exc:+ if not stale():+ _emit_runtime(f"Quick Local startup failed ({type(exc).__name__}). Review the server log; Hermes will retry on a later turn.", warning_callback)+ return+ if ready is None or stale():+ return+ if ready.endpoint != endpoint:+ with self._client_refresh_lock:+ if stale():+ return+ self._endpoint = ready.endpoint+ endpoint = ready.endpoint+ elif not _wait_for_openviking_health(endpoint, timeout_seconds=timeout, should_stop=stale):if not stale():- _emit_runtime(_runtime_openviking_timeout_message(endpoint), warning_callback)+ _emit_runtime(_runtime_openviking_timeout_message(endpoint, timeout), warning_callback)returnwith self._client_refresh_lock:@@ -1543,6 +1601,11 @@ class OpenVikingMemoryProvider(MemoryProvider):try:client = self._build_client(endpoint)healthy = client.health()+ if healthy and managed:+ paths = quick_local.managed_paths(Path(self._hermes_home or get_hermes_home()))+ healthy = quick_local.server_belongs_to_profile(paths, endpoint)+ if healthy:+ healthy = not paths.restart_required_marker.is_file()if stale():returnwarning_message = "" if healthy else f"OpenViking server at {endpoint} is still not reachable after auto-start. {_RETRY_LATER}"@@ -1573,8 +1636,23 @@ class OpenVikingMemoryProvider(MemoryProvider):if self._shutting_down or self._runtime_start_pending or (self._runtime_start_thread and self._runtime_start_thread.is_alive()):returnself._runtime_start_pending = True- start_state, start_message = _start_local_openviking_server(endpoint)- if start_state != _LOCAL_SERVER_STARTED:+ managed_start = None+ try:+ config, _env = self._profile_config_and_env()+ if config.get("deployment") == quick_local.DEPLOYMENT:+ from .local_server import LocalServer+ server = LocalServer(Path(self._hermes_home or get_hermes_home()))+ managed_start = server.start()+ settings = self._resolve_bound_connection_settings(config, _env)+ self._endpoint, self._api_key, self._account, self._user, self._agent = (settings[k] for k in _CONNECTION_KEYS)+ endpoint = self._endpoint+ start_state, start_message = _LOCAL_SERVER_STARTED, f"Starting Quick Local at {endpoint}. Logs: {server.paths.root.parent / _OPENVIKING_SERVER_LOG_RELATIVE_PATH}"+ else:+ start_state, start_message = _start_local_openviking_server(endpoint)+ except Exception as exc:+ logger.debug("OpenViking startup failed", exc_info=True)+ start_state, start_message = _LOCAL_SERVER_FAILED, f"Startup failed ({type(exc).__name__}). Review the server log."+ finally:self._runtime_start_pending = Falseif start_state != _LOCAL_SERVER_STARTED:@@ -1584,18 +1662,21 @@ class OpenVikingMemoryProvider(MemoryProvider):with self._runtime_start_lock:self._runtime_start_pending = Falseif not self._shutting_down:- self._start_runtime_openviking_waiter(endpoint=endpoint, status_callback=status_callback, warning_callback=warning_callback)+ self._start_runtime_openviking_waiter(endpoint=endpoint, managed_start=managed_start, status_callback=status_callback, warning_callback=warning_callback)def initialize(self, session_id: str, **kwargs) -> None:is_cli = kwargs.get("platform") == "cli"warning_callback = kwargs.get("warning_callback") if is_cli else Nonestatus_callback = kwargs.get("status_callback") if is_cli else None+ self._runtime_status_callback = status_callback+ self._runtime_warning_callback = warning_callbackrequested_home = str(kwargs.get("hermes_home") or "").strip()self._hermes_home = requested_home or str(get_hermes_home())self._hermes_home_bound = bool(requested_home)connection_error = ""+ config, env = self._profile_config_and_env()try:- settings = self._resolve_bound_connection_settings()+ settings = self._resolve_bound_connection_settings(config, env)except _OpenVikingEndpointError as exc:connection_error = str(exc)settings = dict.fromkeys(_CONNECTION_KEYS, "")@@ -1627,6 +1708,8 @@ class OpenVikingMemoryProvider(MemoryProvider):if connection_error:self._failed_refresh = (("invalid-endpoint", connection_error), time.monotonic())_emit_runtime(f"{connection_error} {_FIX_ENDPOINT}", warning_callback)+ elif config.get("deployment") == quick_local.DEPLOYMENT:+ self._client = self._ensure_client_locked(status_callback=status_callback, warning_callback=warning_callback)else:try:self._client = self._build_client()@@ -1660,28 +1743,33 @@ class OpenVikingMemoryProvider(MemoryProvider):if not self._env_refresh_enabled:return self._client # no baseline yet: keep whatever the caller wired upwith self._client_refresh_lock:- return self._ensure_client_locked()+ return self._ensure_client_locked(+ status_callback=self._runtime_status_callback,+ warning_callback=self._runtime_warning_callback,+ )def _profile_config_and_env(self) -> tuple[dict, Optional[dict]]:home = self._hermes_home if self._hermes_home_bound else Noneenv = _profile_openviking_env(home)return _load_hermes_openviking_config(home, env=env), env- def _resolve_bound_connection_settings(self) -> dict:- config, env = self._profile_config_and_env()- return _resolve_connection_settings(config, env=env)+ def _resolve_bound_connection_settings(self, config=None, env=None) -> dict:+ if config is None:+ config, env = self._profile_config_and_env()+ return _resolve_connection_settings(config, env=env, hermes_home=self._hermes_home or get_hermes_home())def _in_cooldown(self, failed_key) -> bool:failed = self._failed_refreshreturn failed is not None and failed[0] == failed_key and time.monotonic() - failed[1] < _FAILED_CONFIG_RETRY_COOLDOWN_SECONDS- def _ensure_client_locked(self) -> Optional["_VikingClient"]:+ def _ensure_client_locked(self, *, status_callback=None, warning_callback=None) -> Optional["_VikingClient"]:"""Resolve and publish one client/config state under the refresh lock."""if self._shutting_down:self._client = Nonereturn None+ config, env = self._profile_config_and_env()try:- settings = self._resolve_bound_connection_settings()+ settings = self._resolve_bound_connection_settings(config, env)except _OpenVikingEndpointError as exc:failed_key = ("invalid-endpoint", str(exc))if not self._in_cooldown(failed_key):@@ -1689,9 +1777,27 @@ class OpenVikingMemoryProvider(MemoryProvider):self._failed_refresh = (failed_key, time.monotonic())self._client = Nonereturn None+ managed = config.get("deployment") == quick_local.DEPLOYMENT+ if managed:+ paths = quick_local.managed_paths(Path(self._hermes_home or get_hermes_home()))+ if paths.restart_required_marker.is_file():+ self._endpoint, self._api_key, self._account, self._user, self._agent = (settings[k] for k in _CONNECTION_KEYS)+ if not self._in_cooldown(("quick-local-restart",)):+ self._handle_runtime_openviking_unreachable(status_callback=status_callback, warning_callback=warning_callback)+ self._failed_refresh = (("quick-local-restart",), time.monotonic())+ return Nonesettings_key = tuple(settings[k] for k in _CONNECTION_KEYS)if settings_key == self._settings_tuple():if self._client is not None:+ if managed:+ from .local_server import LocalServer++ server = LocalServer(Path(self._hermes_home or get_hermes_home()))+ if not server.is_running(settings_key[0]):+ self._handle_runtime_openviking_unreachable(+ status_callback=status_callback, warning_callback=warning_callback+ )+ return Nonereturn self._clientwith self._runtime_start_lock:if self._runtime_start_pending or (self._runtime_start_thread and self._runtime_start_thread.is_alive()):@@ -1711,16 +1817,24 @@ class OpenVikingMemoryProvider(MemoryProvider):health_state, health_message = _classify_runtime_openviking_health(client, settings_key[0])if health_state == "healthy":+ if managed and not quick_local.server_belongs_to_profile(paths, settings_key[0]):+ self._failed_refresh = (settings_key, time.monotonic())+ self._handle_runtime_openviking_unreachable(status_callback=status_callback, warning_callback=warning_callback)+ return None+ if managed:+ quick_local.clear_server_restart_required(paths.server_config)self._publish_client(client, settings_key[0])return self._clientself._failed_refresh = (settings_key, time.monotonic())- if health_state == "responded":+ if managed:+ self._handle_runtime_openviking_unreachable(status_callback=status_callback, warning_callback=warning_callback)+ elif health_state == "responded":logger.warning("%s OpenViking memory is temporarily unavailable; Hermes will retry on a later access (after cooldown) or when the config changes.",health_message,)else:- self._handle_runtime_openviking_unreachable()+ self._handle_runtime_openviking_unreachable(status_callback=status_callback, warning_callback=warning_callback)self._client = Nonereturn Nonediff --git a/examples/hermes-plugin/_setup.py b/examples/hermes-plugin/_setup.pyindex 83eee3a10..98cf9daa3 100644--- a/examples/hermes-plugin/_setup.py+++ b/examples/hermes-plugin/_setup.py@@ -13,6 +13,8 @@ import sysfrom pathlib import Pathfrom typing import Optional+from . import quick_local+_SETUP_CANCELLED = object()_CANCEL_OPTION = ("Cancel setup", "no changes saved")_PERSONAL_PROFILE = "personal"@@ -285,6 +287,8 @@ def _prompt_manual_connection_values(prompt, select, cancelled, *, service: booldef _link_ovcli_profile(*, config: dict, provider_config: dict, env_path: Path, ovcli_path: Path) -> None:ov = _ov()+ _stop_previous_quick_local(provider_config, env_path.parent, ovcli_path=ovcli_path)+ quick_local.clear_managed_settings(provider_config)for key in ("endpoint", "api_key", "root_api_key", "account", "user", "agent", "api_key_type"):provider_config.pop(key, None)provider_config["use_ovcli_config"] = True@@ -302,6 +306,8 @@ def _link_ovcli_profile(*, config: dict, provider_config: dict, env_path: Path,def _save_hermes_only_config(*, config: dict, provider_config: dict, env_path: Path, values: dict) -> None:ov = _ov()+ _stop_previous_quick_local(provider_config, env_path.parent)+ quick_local.clear_managed_settings(provider_config)provider_config["use_ovcli_config"] = Falseprovider_config.pop("ovcli_config_path", None)# A newly selected connection must not inherit the previous YAML peer; a@@ -318,6 +324,21 @@ def _save_hermes_only_config(*, config: dict, provider_config: dict, env_path: Pos.environ.pop(key, None)+def _stop_previous_quick_local(provider_config: dict, home: Path, *, ovcli_path=None) -> None:+ if provider_config.get("deployment") != quick_local.DEPLOYMENT:+ return+ from .local_server import LocalServer++ server = LocalServer(home)+ if ovcli_path is not None and quick_local._paths_equivalent(ovcli_path, server.paths.ovcli_config):+ return # Quick Local setup is relinking its own config.+ try:+ if server.paths.server_config.is_file() and server.stop():+ _say("Stopped this profile's Quick Local server. Its data is retained.")+ except (quick_local.QuickLocalSetupError, OSError):+ _say("The previous Quick Local server could not be stopped safely. Check it before removing the plugin.")++def _profile_display_name(profile) -> str:return {"env": _ov()._OVCLI_CONFIG_ENV, "active": "ovcli.conf"}.get(profile.source, profile.name)@@ -382,14 +403,74 @@ def _mirror_manual_config_to_openviking_store(*, prompt, select, cancelled, valureturn path+def _run_quick_local_setup(*, config: dict, provider_config: dict, env_path: Path,+ select=None, cancelled=None) -> bool:+ ov = _ov()++ def report_progress(event: quick_local.QuickLocalProgress) -> None:+ _say(event.message)++ setup = quick_local.QuickLocalSetup(+ health_check=ov._validate_openviking_reachability,+ progress=report_progress,+ )+ try:+ preflight = setup.preflight(env_path.parent)+ except quick_local.QuickLocalSetupError as exc:+ _say(f"Quick Local preflight failed: {exc}")+ return False++ try:+ result = setup.provision(hermes_home=env_path.parent, preflight=preflight)+ except quick_local.SourceBuildRequired as exc:+ _say(str(exc))+ if select is None or select(+ " Allow a source build?",+ [("Cancel", "connect to a separate OpenViking server instead"),+ ("Build locally", "requires native build tools; can take several minutes")],+ default=0, cancel_returns=cancelled,+ ) != 1:+ return False+ setup.allow_source_build = True+ try:+ result = setup.provision(hermes_home=env_path.parent, preflight=preflight)+ except quick_local.QuickLocalSetupError as retry_exc:+ _say(f"Quick Local setup failed: {retry_exc}")+ return False+ except quick_local.QuickLocalSetupError as exc:+ _say(f"Quick Local setup failed: {exc}")+ return False++ _link_ovcli_profile(+ config=config,+ provider_config=provider_config,+ env_path=env_path,+ ovcli_path=result.paths.ovcli_config,+ )+ provider_config.update(+ deployment=quick_local.DEPLOYMENT,+ )+ action = "Reused" if result.reused else "Configured"+ _print_openviking_ready(+ f"{action} Quick Local at {result.endpoint}.",+ result.paths.ovcli_config,+ )+ return True++def _run_create_profile_setup(*, prompt, select, cancelled, config: dict, provider_config: dict, env_path: Path) -> bool | object:source_choice = select(" OpenViking connection",[("OpenViking Service (VolcEngine Cloud)", "use the managed OpenViking endpoint"),- ("Custom", "use a local, VPS, or self-hosted OpenViking server")],+ ("Custom", "use a local, VPS, or self-hosted OpenViking server"),+ ("Quick Local", "install local embeddings; use the configured Hermes LLM")],default=0, cancel_returns=cancelled)if source_choice == cancelled:return _SETUP_CANCELLED+ if source_choice == 2:+ return _run_quick_local_setup(config=config, provider_config=provider_config, env_path=env_path,+ select=select, cancelled=cancelled)+values = _prompt_manual_connection_values(prompt, select, cancelled, service=(source_choice == 0))if values is _SETUP_CANCELLED:return _SETUP_CANCELLEDdiff --git a/examples/hermes-plugin/cli.py b/examples/hermes-plugin/cli.pynew file mode 100644index 000000000..f725d3117--- /dev/null+++ b/examples/hermes-plugin/cli.py@@ -0,0 +1,56 @@+"""Profile-scoped Quick Local controls, loaded without the memory provider."""++from pathlib import Path++from hermes_constants import get_hermes_home+++def _run(args):+ from .local_server import LocalServer+ from .quick_local import QuickLocalSetupError, _server_accepts_config++ server = LocalServer(Path(get_hermes_home()))+ if not server.paths.server_config.is_file():+ print("Quick Local is not configured for this profile.")+ return+ try:+ if args.local_action == "stop":+ print("Quick Local stopped." if server.stop() else "Quick Local is already stopped.")+ return+ if args.local_action in {"start", "restart"}:+ from hermes_cli.config import load_config_readonly++ from .quick_local import DEPLOYMENT++ memory = load_config_readonly().get("memory", {})+ settings = memory.get("openviking", {}) if isinstance(memory, dict) else {}+ if (+ not isinstance(memory, dict)+ or memory.get("provider") != "openviking"+ or not isinstance(settings, dict)+ or settings.get("deployment") != DEPLOYMENT+ ):+ raise QuickLocalSetupError(+ "This profile is not using Quick Local. Run "+ "hermes memory setup openviking to select Quick Local."+ )+ started = server.start(restart=args.local_action == "restart")+ print(f"Starting Quick Local at {started.endpoint}...")+ server.wait_ready(+ started, lambda url: (_server_accepts_config(server._config(), url), "")+ )+ status = server.status()+ print(f"Quick Local: {status['state']} at {status['endpoint']}")+ if status["restart_required"]:+ print("Saved settings require a restart: hermes openviking local restart")+ except QuickLocalSetupError as exc:+ print(str(exc))+ raise SystemExit(1) from exc+++def register_cli(subparser):+ commands = subparser.add_subparsers(dest="openviking_command", required=True)+ local = commands.add_parser("local", help="Control this profile's Quick Local server")+ actions = local.add_subparsers(dest="local_action", required=True)+ for name in ("status", "start", "stop", "restart"):+ actions.add_parser(name).set_defaults(func=_run)diff --git a/examples/hermes-plugin/local_packages.py b/examples/hermes-plugin/local_packages.pynew file mode 100644index 000000000..adc7df461--- /dev/null+++ b/examples/hermes-plugin/local_packages.py@@ -0,0 +1,132 @@+"""Reviewed binary packages, verified before either installer receives them."""++from __future__ import annotations++import hashlib+import os+import platform+import sys+import tempfile+from pathlib import Path+from urllib.parse import parse_qs, urldefrag, urlparse++import httpx+from packaging.requirements import Requirement+from packaging.version import Version++_OV = "https://files.pythonhosted.org/packages/"+_CPP = "https://github.com/abetlen/llama-cpp-python/releases/download/"+# macOS uses the working Metal archive. The same release's CPU macOS archive+# fails CRC validation and must not be substituted here.+_PACKAGES = {+ ("Darwin", "arm64"): (+ "5c/f4/222b2eb392a09cf2e13648d4f2f509c6043d16385ebd48a457a453816245/openviking-0.4.22-cp310-abi3-macosx_14_0_arm64.whl",+ "ddfa3d23274cbd9afcdfaf1a1542b0a9e5e8286221a96bb7e40bd63e312d5bae",+ "v0.3.30-metal/llama_cpp_python-0.3.30-py3-none-macosx_11_0_arm64.whl",+ "4f5b385f31dbda502d7118aff0c07c9e98961fa0402c025b89ff3250db843eb3",+ ),+ ("Linux", "x86_64"): (+ "aa/02/69642eddcbced2d52dc8489a0e8f618b7ae11e6caede9b02fac0f6f54528/openviking-0.4.22-cp310-abi3-manylinux_2_31_x86_64.whl",+ "fa508fc9c84a32b3206d2f719c415bad5c50e88c1838fb19349881e087da72c8",+ "v0.3.30/llama_cpp_python-0.3.30-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl",+ "591337ea31b6fea25f02da53db136041899a530eda1b2c2611f0bebe7c560a15",+ ),+ ("Linux", "aarch64"): (+ "29/ef/8bda981fae06066d2c462d051ceb6038043e776cac7b87f723fe65e34f17/openviking-0.4.22-cp310-abi3-manylinux_2_31_aarch64.whl",+ "480070405e5c64c0a7d8d1d2afba7e98a55f151a67c785e4e5d0d54320096afc",+ "v0.3.30/llama_cpp_python-0.3.30-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl",+ "0720e1d122a4d1ad46607813bd34018ff46b0f50cd0a38fb93fad650b3b98ade",+ ),+ ("Windows", "x86_64"): (+ "3f/26/e0d259f1a9fb53d02b99487f232265f79965fefb9b956563612c7acf5ae5/openviking-0.4.22-cp310-abi3-win_amd64.whl",+ "cad1f3e4ea843c47178a8d5056df733b1e3f49d4e902b6f803b9e192320bb89b",+ "v0.3.36/llama_cpp_python-0.3.36-py3-none-win_amd64.whl",+ "ae5e88a2cf464e5a2dde7c8898c2d5c71cc24d03cac6396bf7509456bde0b9fb",+ ),+}+++def install_requirements(*, allow_source_build=False):+ from .quick_local import OPENVIKING_REQUIREMENT, SourceBuildRequired++ system = platform.system()+ machine = platform.machine().lower()+ machine = {"amd64": "x86_64", "arm64": "arm64" if system == "Darwin" else "aarch64"}.get(+ machine, machine+ )+ packages = _PACKAGES.get((system, machine))+ compatible = sys.maxsize > 2**32+ if system == "Darwin":+ compatible = compatible and Version(platform.mac_ver()[0] or "0") >= Version("14")+ elif system == "Linux":+ libc, version = platform.libc_ver()+ compatible = compatible and libc == "glibc" and Version(version or "0") >= Version("2.31")+ if not packages or not compatible:+ if not allow_source_build:+ raise SourceBuildRequired(+ "No reviewed Quick Local binary is available for this platform. "+ "Use a separate OpenViking server, or explicitly allow a source build "+ "in setup. A build needs native development tools and can take several minutes."+ )+ requirements = [OPENVIKING_REQUIREMENT, "llama-cpp-python==0.3.30"]+ else:+ ov_path, ov_hash, cpp_path, cpp_hash = packages+ requirements = [+ f"openviking[local-embed] @ {_OV}{ov_path}#sha256={ov_hash}",+ f"llama-cpp-python @ {_CPP}{cpp_path}#sha256={cpp_hash}",+ ]+ # The PM resolver otherwise chooses a LiteLLM release that excludes Python+ # 3.14. This constraint belongs only to OpenViking's private environment.+ return [*requirements, 'litellm==1.83.7; python_version >= "3.14"']+++def verified_requirements(requirements: list[str], cache: Path) -> list[str]:+ """Give installers local wheels whose bytes match the reviewed pins.++ PM's project resolver does not enforce hashes in URL fragments. Checking+ before installation also protects the pre-PM path and cache reuse.+ """+ from .quick_local import QuickLocalSetupError, _prepare_private_directory++ verified = []+ for value in requirements:+ requirement = Requirement(value)+ if not requirement.url:+ verified.append(value)+ continue+ url, fragment = urldefrag(requirement.url)+ digest = parse_qs(fragment).get("sha256", [""])[0]+ if len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):+ raise QuickLocalSetupError("Quick Local's native package needs a reviewed SHA-256 pin.")+ _prepare_private_directory(cache)+ directory = cache / digest+ _prepare_private_directory(directory)+ wheel = directory / Path(urlparse(url).path).name+ if not wheel.name.endswith(".whl") or wheel.is_symlink():+ raise QuickLocalSetupError("Quick Local's native package must be a private wheel file.")+ if not wheel.is_file() or _sha256(wheel) != digest:+ fd, temporary = tempfile.mkstemp(dir=directory, suffix=".download")+ try:+ checksum = hashlib.sha256()+ with os.fdopen(fd, "wb") as output:+ with httpx.stream("GET", url, follow_redirects=True, timeout=60) as response:+ response.raise_for_status()+ for chunk in response.iter_bytes(1024 * 1024):+ checksum.update(chunk)+ output.write(chunk)+ if checksum.hexdigest() != digest:+ raise QuickLocalSetupError(+ "Quick Local's native package failed SHA-256 verification. Installation was cancelled."+ )+ os.replace(temporary, wheel)+ finally:+ Path(temporary).unlink(missing_ok=True)+ extras = f"[{','.join(sorted(requirement.extras))}]" if requirement.extras else ""+ marker = f" ; {requirement.marker}" if requirement.marker else ""+ verified.append(f"{requirement.name}{extras} @ {wheel.absolute().as_uri()}{marker}")+ return verified+++def _sha256(path: Path) -> str:+ with path.open("rb") as file:+ return hashlib.file_digest(file, "sha256").hexdigest()diff --git a/examples/hermes-plugin/local_server.py b/examples/hermes-plugin/local_server.pynew file mode 100644index 000000000..88b98191f--- /dev/null+++ b/examples/hermes-plugin/local_server.py@@ -0,0 +1,418 @@+"""Process ownership and lifecycle for one profile's Quick Local server."""++from __future__ import annotations++import hashlib+import json+import os+import time+from contextlib import contextmanager+from dataclasses import dataclass+from pathlib import Path++import psutil+from utils import atomic_json_write+++@dataclass(frozen=True)+class StartedServer:+ endpoint: str+ process: object | None+ reused: bool+ created: float | None = None+++class _RecordedProcess:+ def __init__(self, process):+ self.process = process+ self.created = process.create_time()+ self.pid = process.pid++ def poll(self):+ try:+ if self.process.create_time() != self.created:+ return -1+ return (+ None+ if self.process.is_running() and self.process.status() != psutil.STATUS_ZOMBIE+ else -1+ )+ except psutil.NoSuchProcess:+ return -1+++def _wait_stopped(processes, timeout):+ # A separate CLI cannot reap Hermes's children. A zombie has already+ # stopped; wait_procs() can otherwise keep reporting it as alive.+ deadline = time.monotonic() + timeout+ while True:+ alive = []+ for process in processes:+ try:+ if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:+ alive.append(process)+ except psutil.NoSuchProcess:+ pass+ if not alive or time.monotonic() >= deadline:+ return alive+ time.sleep(min(0.05, max(0, deadline - time.monotonic())))+ processes = alive+++def stop_process_tree(process, *, timeout=5):+ """Stop an owned parent and its existing children, including Windows launchers."""+ from .quick_local import QuickLocalSetupError++ try:+ processes = [*process.children(recursive=True), process]+ for child in processes:+ try:+ child.terminate()+ except psutil.NoSuchProcess:+ pass+ alive = _wait_stopped(processes, timeout)+ for child in alive:+ try:+ child.kill()+ except psutil.NoSuchProcess:+ pass+ alive = _wait_stopped(alive, timeout)+ if alive:+ raise QuickLocalSetupError(+ "Quick Local could not stop its server. Review the server log."+ )+ except psutil.NoSuchProcess:+ pass+++class LocalServer:+ """Never stop a process unless its identity and profile config match."""++ def __init__(self, hermes_home: Path):+ from . import quick_local as ql++ self.ql = ql+ self.paths = ql.managed_paths(hermes_home)+ self.record_path = self.paths.root / "server-process.json"++ @contextmanager+ def locked(self, timeout=10.0):+ ql = self.ql+ ql.repair_private_paths(self.paths)+ path = self.paths.root / "server.lock"+ if path.is_symlink():+ raise ql.QuickLocalSetupError("Quick Local lock must belong to this profile.")+ with path.open("a+b") as file:+ if os.name != "nt":+ path.chmod(0o600)+ file.seek(0, 2)+ if not file.tell():+ file.write(b"\0")+ file.flush()+ deadline = time.monotonic() + timeout+ while True:+ try:+ file.seek(0)+ if os.name == "nt":+ import msvcrt++ msvcrt.locking(file.fileno(), msvcrt.LK_NBLCK, 1)+ else:+ import fcntl++ fcntl.flock(file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ break+ except OSError:+ if time.monotonic() >= deadline:+ raise ql.QuickLocalSetupError(+ "Quick Local is busy in another process. Retry shortly."+ )+ time.sleep(0.05)+ try:+ yield+ finally:+ file.seek(0)+ if os.name == "nt":+ msvcrt.locking(file.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ fcntl.flock(file.fileno(), fcntl.LOCK_UN)++ def _config(self):+ self.ql.connection_config({}, self.paths.root.parent)+ return json.loads(self.paths.server_config.read_text(encoding="utf-8"))++ def _fingerprint(self, config):+ return hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest()++ def _read_record(self):+ try:+ value = json.loads(self.record_path.read_text(encoding="utf-8"))+ return value if isinstance(value, dict) else {}+ except (OSError, ValueError):+ return {}++ def _restart_stamp(self):+ try:+ return self.paths.restart_required_marker.stat().st_mtime_ns+ except FileNotFoundError:+ return None++ def _matches_desired(self, record, config):+ return (+ record.get("fingerprint") == self._fingerprint(config)+ and self.ql._paths_equivalent(record.get("command"), self.paths.server_command)+ and (+ self._restart_stamp() is None+ or record.get("restart_stamp") == self._restart_stamp()+ )+ )++ def _verified_process(self, record):+ try:+ process = psutil.Process(record["pid"])+ if (+ process.create_time() != record["created"]+ or process.status() == psutil.STATUS_ZOMBIE+ ):+ return None+ args = process.cmdline()+ config = args[args.index("--config") + 1]+ command = Path(record["command"]).absolute()+ # PM generations can change during an upgrade. The old command must+ # still be inside this profile's private runtime, never another one.+ command.relative_to(self.paths.runtime.absolute())+ if not self.ql._paths_equivalent(config, self.paths.server_config):+ return None+ if not any(self.ql._paths_equivalent(arg, command) for arg in args[:2]):+ return None+ if args[args.index("--port") + 1] != str(record["port"]):+ return None+ return process+ except (psutil.Error, KeyError, ValueError, IndexError, TypeError, OSError):+ return None++ def _adopt(self, config, endpoint):+ # Older Quick Local builds did not save a process record. Authenticated+ # ownership plus an exact executable/config match permits adoption.+ if not self.ql.server_belongs_to_profile(self.paths, endpoint):+ return None+ for process in psutil.process_iter(["pid", "create_time", "cmdline"]):+ try:+ args = process.info["cmdline"] or []+ # A runtime upgrade may select a new PM generation before+ # setup recovers the OLD server's lost record. Adopt only an+ # OpenViking entrypoint inside this profile's private runtime.+ command = next(+ (+ arg+ for arg in args[:2]+ if Path(arg).name+ in {"openviking-server", "openviking-server.exe", "openviking-server.cmd"}+ and Path(arg).absolute().is_relative_to(self.paths.runtime.absolute())+ ),+ None,+ )+ if command is None:+ continue+ record = {+ "pid": process.pid,+ "created": process.info["create_time"],+ "command": command,+ "port": self.ql._endpoint_port(endpoint),+ "fingerprint": self._fingerprint(config),+ }+ if "--config" in args and self._verified_process(record):+ atomic_json_write(self.record_path, record, mode=0o600)+ return process+ except psutil.Error:+ continue+ return None++ def _stop(self, process):+ stop_process_tree(process)++ def configure(self, config, *, runtime_changed=False):+ with self.locked():+ changed = not self.ql._stored_server_config_matches(self.paths, config)+ if (changed or runtime_changed) and self.paths.server_config.is_file():+ # Authenticate/adopt against the OLD config. Publishing a new+ # key first makes a lost process record impossible to recover.+ # Setup can repair an incomplete ovcli file; only the old+ # server config/key is needed for authenticated adoption.+ old_config = json.loads(self.paths.server_config.read_text(encoding="utf-8"))+ endpoint = self.ql._configured_endpoint(self.paths)+ process = self._verified_process(self._read_record())+ if process is None:+ process = self._adopt(old_config, endpoint)+ if process is None and self.ql.server_belongs_to_profile(self.paths, endpoint):+ raise self.ql.QuickLocalSetupError(+ "Quick Local cannot verify the server process. Existing settings were retained. "+ "Stop that server manually, then retry."+ )+ if changed or runtime_changed:+ self.ql._mark_server_restart_required(self.paths)+ atomic_json_write(self.paths.server_config, config, mode=0o600)+ self.ql._write_ovcli_profile(+ self.paths.ovcli_config, f"http://127.0.0.1:{config['server']['port']}", config+ )++ def is_running(self, endpoint):+ """Cheap owned-process check for a retained provider's cached client."""+ record = self._read_record()+ if record.get("port") == self.ql._endpoint_port(endpoint) and self._verified_process(+ record+ ):+ return True+ # A server started outside the controller may have no record. Keep+ # serving from it while its key still proves profile ownership.+ return self.ql.server_belongs_to_profile(self.paths, endpoint)++ def start(self, *, restart=False):+ ql = self.ql+ with self.locked():+ config = self._config()+ endpoint = ql._configured_endpoint(self.paths)+ record = self._read_record()+ process = self._verified_process(record)+ if process is None:+ process = self._adopt(config, endpoint)+ record = self._read_record()+ changed = (+ not self._matches_desired(record, config)+ if process is not None+ else self.paths.restart_required_marker.is_file()+ )+ if process is not None:+ if not restart and not changed:+ return StartedServer(+ endpoint, _RecordedProcess(process), True, process.create_time()+ )+ self._stop(process)+ elif ql.server_belongs_to_profile(self.paths, endpoint):+ if changed or restart:+ raise ql.QuickLocalSetupError(+ "Quick Local cannot verify the server process. Stop that server manually, then retry."+ )+ return StartedServer(endpoint, None, True)++ self.record_path.unlink(missing_ok=True)+ port = ql.find_available_port(preferred_endpoint=endpoint)+ if port is None:+ raise ql.QuickLocalSetupError("No free Quick Local port was found (1934-1953).")+ endpoint = f"http://127.0.0.1:{port}"+ config["server"]["port"] = port+ atomic_json_write(self.paths.server_config, config, mode=0o600)+ ql._write_ovcli_profile(self.paths.ovcli_config, endpoint, config)+ process = ql._start_validation_server(+ endpoint,+ self.paths.server_config,+ self.paths.root.parent,+ self.paths.server_command,+ )+ try:+ created = psutil.Process(process.pid).create_time()+ atomic_json_write(+ self.record_path,+ {+ "pid": process.pid,+ "created": created,+ "command": str(self.paths.server_command),+ "port": port,+ "restart_stamp": self._restart_stamp(),+ "fingerprint": self._fingerprint(config),+ },+ mode=0o600,+ )+ except BaseException:+ ql._stop_process(process)+ raise+ return StartedServer(endpoint, process, False, created)++ def wait_ready(self, started, health_check, *, should_stop=lambda: False, timeout=None):+ """Retry a port race after an early exit, without stopping another server."""+ ql = self.ql+ deadline = time.monotonic() + (ql._HEALTH_TIMEOUT_SECONDS if timeout is None else timeout)+ for attempt in range(3):+ while time.monotonic() < deadline and not should_stop():+ if started.process is not None and started.process.poll() is not None:+ break+ healthy, _message = health_check(started.endpoint)+ if healthy and ql.server_belongs_to_profile(self.paths, started.endpoint):+ with self.locked():+ # Do not clear a restart requested by a concurrent setup.+ record = self._read_record()+ current = self._matches_desired(record, self._config())+ if started.process is not None:+ current = (+ current+ and record.get("pid") == started.process.pid+ and record.get("created") == started.created+ )+ if current:+ ql.clear_server_restart_required(self.paths.server_config)+ elif (+ not self.paths.restart_required_marker.is_file()+ and started.process is None+ ):+ current = True+ if current:+ return started+ # Setup changed the saved config during this health probe.+ # Reconcile it before publishing a stale running server.+ started = self.start()+ continue+ time.sleep(ql._HEALTH_POLL_INTERVAL_SECONDS)+ if should_stop():+ return None+ host, port = ql._endpoint_bind(started.endpoint)+ if (+ attempt == 2+ or ql._can_bind_local_port(host, port)+ or ql.server_belongs_to_profile(self.paths, started.endpoint)+ ):+ break+ started = self.start()+ # A failed start must not leave a hung child behind. Recheck the record+ # under the lock so a newer start by another caller is never stopped.+ with self.locked():+ record = self._read_record()+ if (+ started.process is not None+ and record.get("pid") == started.process.pid+ and record.get("created") == started.created+ ):+ process = self._verified_process(record)+ if process is not None:+ self._stop(process)+ self.record_path.unlink(missing_ok=True)+ raise ql.QuickLocalSetupError(+ f"Quick Local did not become ready. Review {ql._server_log_path(self.paths.root.parent)} and retry."+ )++ def stop(self):+ with self.locked():+ config = self._config()+ endpoint = self.ql._configured_endpoint(self.paths)+ process = self._verified_process(self._read_record()) or self._adopt(config, endpoint)+ if process is None:+ if self.ql.server_belongs_to_profile(self.paths, endpoint):+ raise self.ql.QuickLocalSetupError(+ "Quick Local cannot verify the server process; it was not stopped."+ )+ return False+ self._stop(process)+ self.record_path.unlink(missing_ok=True)+ return True++ def status(self):+ with self.locked():+ config = self._config()+ endpoint = self.ql._configured_endpoint(self.paths)+ process = self._verified_process(self._read_record()) or self._adopt(config, endpoint)+ ready = self.ql.server_belongs_to_profile(self.paths, endpoint)+ return {+ "endpoint": endpoint,+ "pid": process.pid if process else None,+ "state": "ready" if ready else "starting" if process else "stopped",+ "restart_required": self.paths.restart_required_marker.is_file(),+ }diff --git a/examples/hermes-plugin/plugin.yaml b/examples/hermes-plugin/plugin.yamlindex 348d8deb1..a0f26e8c1 100644--- a/examples/hermes-plugin/plugin.yaml+++ b/examples/hermes-plugin/plugin.yaml@@ -1,5 +1,5 @@name: openviking-version: 2.0.1+version: 2.1.0description: "OpenViking context database — session-managed memory with automatic extraction, tiered retrieval, and filesystem-style knowledge browsing."pip_dependencies:- httpxdiff --git a/examples/hermes-plugin/pyproject.toml b/examples/hermes-plugin/pyproject.tomlindex 212ea2186..2d987fe48 100644--- a/examples/hermes-plugin/pyproject.toml+++ b/examples/hermes-plugin/pyproject.toml@@ -1,6 +1,6 @@[project]name = "hermes-plugin-openviking"-version = "2.0.1"+version = "2.1.0"description = "Hermes Agent memory provider plugin: openviking"requires-python = ">=3.11"license = { text = "MIT" }@@ -10,6 +10,7 @@ license = { text = "MIT" }dependencies = ["httpx>=0.27,<1","psutil>=5.9,<9",+ "packaging>=23,<27",][tool.pytest.ini_options]diff --git a/examples/hermes-plugin/quick_local.py b/examples/hermes-plugin/quick_local.pynew file mode 100644index 000000000..962efb369--- /dev/null+++ b/examples/hermes-plugin/quick_local.py@@ -0,0 +1,1235 @@+"""Reusable, non-interactive OpenViking Quick Local provisioning.++User interfaces own prompts and rendering. This module owns the bounded+installation, Hermes-profile-scoped configuration, and temporary validation+needed to produce a ready-to-link OpenViking CLI profile.+"""++from __future__ import annotations++import importlib.util+import json+import os+import secrets+import shutil+import socket+import subprocess+import sys+import tempfile+import time+from dataclasses import dataclass+from enum import Enum+from pathlib import Path+from typing import Any, Callable, Mapping, Optional+from urllib.parse import urlparse++from packaging.requirements import Requirement+from packaging.version import InvalidVersion, Version+from utils import atomic_json_write++DEPLOYMENT = "quick_local"+EMBEDDING_MODEL = "bge-small-zh-v1.5-f16"+EMBEDDING_DIMENSION = 512+OPENVIKING_REQUIREMENT = "openviking[local-embed]==0.4.22"+# Later LiteLLM releases exclude Python 3.14. OpenViking supports this version.+# This restriction applies only to the private server, never Hermes's dependencies.++_OPENVIKING_REQUIREMENT = Requirement(OPENVIKING_REQUIREMENT)+_OPENVIKING_VERSION_SPECIFIER = _OPENVIKING_REQUIREMENT.specifier+_ROOT_DIRNAME = "openviking"+_SERVER_CONFIG_FILENAME = "ov.conf"+_OVCLI_CONFIG_FILENAME = "ovcli.conf"+_RESTART_REQUIRED_FILENAME = ".restart-required"+_WORKSPACE_DIRNAME = "data"+_MODEL_CACHE_DIRNAME = "models"+# Leave OpenViking's default 1933 available for independently managed servers.+_DEFAULT_PORT = 1934+_PORT_ATTEMPTS = 20+_MODEL_DOWNLOAD_SIZE = "approximately 46 MiB"+# OpenViking downloads the built-in model while its server lifespan starts.+# Give a slow first download a bounded ten minutes, then leave another minute+# for model loading and service initialization.+_MODEL_PREPARATION_TIMEOUT_SECONDS = 600.0+_HEALTH_TIMEOUT_SECONDS = _MODEL_PREPARATION_TIMEOUT_SECONDS + 60.0+_HEALTH_POLL_INTERVAL_SECONDS = 0.5+_PROCESS_STOP_TIMEOUT_SECONDS = 10.0+++class QuickLocalStage(str, Enum):+ PREFLIGHT = "preflight"+ INSTALL_OPENVIKING = "install_openviking"+ PREPARE_EMBEDDING = "prepare_embedding"+ VALIDATE = "validate"+ WRITE_CONFIG = "write_config"+ COMPLETE = "complete"+++@dataclass(frozen=True)+class QuickLocalProgress:+ stage: QuickLocalStage+ message: str+++@dataclass(frozen=True)+class QuickLocalPaths:+ root: Path+ runtime: Path+ server_config: Path+ ovcli_config: Path+ workspace: Path+ model_cache: Path++ @property+ def runtime_python(self) -> Path:+ scripts = "Scripts" if os.name == "nt" else "bin"+ executable = "python.exe" if os.name == "nt" else "python"+ if _pm_available():+ from pm.operations import environment_python++ selected = environment_python("openviking-local", root=self.runtime)+ else:+ selected = None+ return selected or self.runtime / scripts / executable++ @property+ def server_command(self) -> Path:+ scripts = "Scripts" if os.name == "nt" else "bin"+ executable = "openviking-server.exe" if os.name == "nt" else "openviking-server"+ if _pm_available():+ from pm.operations import python_tool++ selected = python_tool("openviking-local", "openviking-server", root=self.runtime)+ else:+ selected = None+ return selected or self.runtime / scripts / executable++ @property+ def restart_required_marker(self) -> Path:+ return self.root / _RESTART_REQUIRED_FILENAME+++@dataclass(frozen=True)+class QuickLocalPreflight:+ paths: QuickLocalPaths+ reusable_endpoint: Optional[str]+++@dataclass(frozen=True)+class QuickLocalSetupResult:+ paths: QuickLocalPaths+ endpoint: str+ reused: bool+ server_restart_required: bool = False+++class QuickLocalSetupError(RuntimeError):+ """Quick Local could not finish without partially activating it."""+++class SourceBuildRequired(QuickLocalSetupError):+ """No reviewed binary matches this platform; ask before compiling."""+++ProgressReporter = Callable[[QuickLocalProgress], None]+HealthCheck = Callable[[str], tuple[bool, str]]+++def managed_paths(hermes_home: Path) -> QuickLocalPaths:+ root = Path(hermes_home).expanduser().absolute() / _ROOT_DIRNAME+ if root.is_symlink():+ raise QuickLocalSetupError("Quick Local directory must belong to this Hermes profile.")+ return QuickLocalPaths(+ root=root,+ runtime=root / "runtime",+ server_config=root / _SERVER_CONFIG_FILENAME,+ ovcli_config=root / _OVCLI_CONFIG_FILENAME,+ workspace=root / _WORKSPACE_DIRNAME,+ model_cache=root / _MODEL_CACHE_DIRNAME,+ )+++def clear_managed_settings(provider_config: dict[str, Any]) -> None:+ provider_config.pop("deployment", None)+ provider_config.pop("server_config_path", None)+ provider_config.pop("server_command_path", None)+++def clear_server_restart_required(server_config_path: Path) -> bool:+ """Clear the durable marker once no stale managed server remains."""+ marker = Path(server_config_path).with_name(_RESTART_REQUIRED_FILENAME)+ try:+ marker.unlink(missing_ok=True)+ return True+ except OSError:+ return False+++def _mark_server_restart_required(paths: QuickLocalPaths) -> None:+ _prepare_private_directory(paths.root)+ atomic_json_write(+ paths.restart_required_marker,+ {"restart_required": True},+ mode=0o600,+ )+++def build_server_config(+ paths: QuickLocalPaths,+ vlm: Mapping[str, Any],+ *,+ port: int = _DEFAULT_PORT,+) -> dict[str, Any]:+ return {+ "server": {+ "host": "127.0.0.1",+ "port": port,+ "auth_mode": "trusted",+ "root_api_key": _server_key(paths),+ },+ "storage": {"workspace": str(paths.workspace)},+ "embedding": {+ "dense": {+ "provider": "local",+ "model": EMBEDDING_MODEL,+ "dimension": EMBEDDING_DIMENSION,+ "cache_dir": str(paths.model_cache),+ }+ },+ "vlm": dict(vlm),+ }+++def resolve_hermes_vlm_config() -> dict[str, Any]:+ """Translate the active persisted Hermes LLM into OpenViking VLM config."""++ from hermes_cli.config import load_config+ from hermes_cli.runtime_provider import resolve_runtime_provider++ config = load_config()+ model_config = config.get("model", {}) if isinstance(config, Mapping) else {}+ if isinstance(model_config, str):+ model_config = {"default": model_config}+ if not isinstance(model_config, Mapping):+ model_config = {}++ default_model = model_config.get("default")+ requested_provider = _clean_value(model_config.get("provider")) or None+ if isinstance(default_model, Mapping):+ from hermes_cli.config import split_model_config_default++ nested_model, nested_provider = split_model_config_default(default_model)+ default_model = nested_model+ requested_provider = requested_provider or nested_provider or None+ model = _clean_value(default_model or model_config.get("model") or model_config.get("name"))+ if not model:+ raise QuickLocalSetupError("Hermes has no default LLM model configured.")++ runtime = resolve_runtime_provider(+ requested=requested_provider,+ target_model=model,+ )+ runtime_model = _clean_value(runtime.get("model")) or model+ provider = _clean_value(runtime.get("provider")).lower()+ api_mode = _clean_value(runtime.get("api_mode")).lower()+ source = _clean_value(runtime.get("source")).lower()+ raw_api_base = runtime.get("base_url")+ raw_api_key = runtime.get("api_key")+ api_base = _clean_value(raw_api_base)+ api_key = _clean_value(raw_api_key)++ if raw_api_base is not None and not isinstance(raw_api_base, str):+ raise QuickLocalSetupError("Hermes' LLM provider API base URL must be a string.")+ if not api_base:+ raise QuickLocalSetupError("Hermes' LLM provider did not resolve an API base URL.")+ if raw_api_key is None or (isinstance(raw_api_key, str) and not api_key):+ raise QuickLocalSetupError(+ "Hermes' LLM provider did not resolve reusable static credentials."+ )+ key_env = _clean_value(model_config.get("key_env") or model_config.get("api_key_env")).lower()+ local_runtime = (+ provider == "custom"+ and source == "local-runtime"+ and isinstance(raw_api_key, str)+ and bool(api_key)+ and urlparse(api_base).hostname in {"localhost", "127.0.0.1", "::1"}+ )+ declared_key = bool(key_env and source in {key_env, f"env:{key_env}"})+ # A declared env variable identifies a source, not a static credential.+ # Hermes owns native Anthropic OAuth authentication and token refresh.+ oauth_route = False+ if api_mode == "anthropic_messages" and isinstance(raw_api_key, str):+ from agent.anthropic_credentials import anthropic_route_is_oauth++ oauth_route = anthropic_route_is_oauth(api_base, raw_api_key, provider=provider)+ if oauth_route or not isinstance(raw_api_key, str) or not (+ local_runtime or declared_key or _has_copyable_static_credentials(provider, source, api_key)+ ):+ raise QuickLocalSetupError(+ "Hermes is using refreshed OAuth, cloud-native, or external-process "+ "credentials that cannot be copied safely into OpenViking. Configure "+ "a static API-key LLM for Hermes, or connect to an OpenViking server "+ "configured separately."+ )+ # These static-key API endpoints also provide Chat Completions. OAuth+ # Responses routes and third-party Responses-only endpoints stay excluded.+ if api_mode == "codex_responses" and urlparse(api_base).hostname in {+ "api.openai.com", "api.x.ai"+ } and provider in {"openai-api", "xai", "custom"}:+ api_mode = "chat_completions"+ if api_mode not in {"chat_completions", "anthropic_messages"}:+ raise QuickLocalSetupError(+ f"Hermes' {api_mode or 'unknown'} LLM transport is not supported by "+ "Quick Local. Use an OpenAI-compatible or Anthropic-compatible "+ "API-key provider, or connect to an OpenViking server configured "+ "separately."+ )+ vlm: dict[str, Any]+ if api_mode == "anthropic_messages":+ # Like Hermes's Anthropic SDK, LiteLLM appends /v1/messages itself.+ api_base = api_base.rstrip("/").removesuffix("/v1")+ from agent.anthropic_adapter import _attribution_headers, _auth_style++ style = _auth_style(api_key, api_base, api_base)+ # OV's pinned LiteLLM backend cannot reproduce Hermes's bearer/query+ # handling. It also treats sk-ant-oat-shaped proxy keys as native OAuth.+ if style == "bearer" or api_key.startswith("sk-ant-oat"):+ raise QuickLocalSetupError(+ "Quick Local cannot reproduce authentication for this Anthropic route. "+ "Use an OpenAI-compatible route for Hermes, or Custom setup "+ "with a separately configured OpenViking server."+ )+ if not runtime_model.startswith("anthropic/"):+ runtime_model = f"anthropic/{runtime_model}"+ vlm = {+ "provider": "litellm",+ "model": runtime_model,+ "api_key": api_key,+ "api_base": api_base,+ }+ if style == "kimi":+ vlm["extra_headers"] = _attribution_headers()+ else:+ base = urlparse(api_base)+ if base.hostname == "generativelanguage.googleapis.com" and not base.path.rstrip("/").endswith("/openai"):+ # Hermes uses Google's native client despite chat_completions in+ # its runtime record. OV needs Google's documented OpenAI route.+ api_base = base._replace(path="/v1beta/openai/").geturl()+ vlm = {+ "provider": "openai",+ "model": runtime_model,+ "api_key": api_key,+ "api_base": api_base,+ }++ extra_headers = runtime.get("extra_headers")+ if isinstance(extra_headers, dict) and extra_headers:+ vlm["extra_headers"] = {**vlm.get("extra_headers", {}), **extra_headers}+ request_overrides = runtime.get("request_overrides")+ if isinstance(request_overrides, dict):+ extra_body = request_overrides.get("extra_body")+ if isinstance(extra_body, dict) and extra_body:+ vlm["extra_request_body"] = dict(extra_body)+ vlm.update({"temperature": 0.0, "max_retries": 2})+ return vlm+++class QuickLocalSetup:+ """Provision one Hermes-home-scoped Quick Local configuration."""++ def __init__(+ self,+ *,+ health_check: HealthCheck,+ progress: Optional[ProgressReporter] = None,+ allow_source_build: bool = False,+ ) -> None:+ self._health_check = health_check+ self._progress = progress or (lambda _event: None)+ self.allow_source_build = allow_source_build++ def preflight(self, hermes_home: Path) -> QuickLocalPreflight:+ self._emit(QuickLocalStage.PREFLIGHT, "Checking local requirements...")+ paths = managed_paths(hermes_home)+ reusable_endpoint = find_reusable_endpoint(paths, self._health_check)+ return QuickLocalPreflight(+ paths=paths,+ reusable_endpoint=reusable_endpoint,+ )++ def provision(+ self,+ *,+ hermes_home: Path,+ preflight: Optional[QuickLocalPreflight] = None,+ ) -> QuickLocalSetupResult:+ try:+ return self._provision(+ hermes_home=Path(hermes_home),+ preflight=preflight,+ )+ except QuickLocalSetupError:+ raise+ except Exception as exc:+ raise QuickLocalSetupError(+ f"Could not prepare Quick Local ({type(exc).__name__}). Review the server log and retry."+ ) from exc++ def _provision(+ self,+ *,+ hermes_home: Path,+ preflight: Optional[QuickLocalPreflight],+ ) -> QuickLocalSetupResult:+ preflight = preflight or self.preflight(hermes_home)+ if preflight.paths != managed_paths(hermes_home):+ raise QuickLocalSetupError(+ "Quick Local preflight belongs to a different Hermes profile."+ )+ vlm = resolve_hermes_vlm_config()+ runtime_changed = self._ensure_openviking_installed(preflight.paths)++ reusable_endpoint = find_reusable_endpoint(preflight.paths, self._health_check)+ if reusable_endpoint:+ port = _endpoint_port(reusable_endpoint)+ if port is None:+ raise QuickLocalSetupError(+ "Quick Local's saved endpoint does not contain a valid port."+ )+ server_config = build_server_config(preflight.paths, vlm, port=port)+ config_changed = not _stored_server_config_matches(preflight.paths, server_config)+ if (+ runtime_changed+ or config_changed+ or preflight.paths.restart_required_marker.is_file()+ ):+ # Validate in disposable storage before changing the live service.+ validation_port = find_available_port()+ if validation_port is None:+ raise QuickLocalSetupError(+ "No free port is available to validate updated settings."+ )+ self._validate_generated_config(+ paths=preflight.paths,+ endpoint=f"http://127.0.0.1:{validation_port}",+ server_config=server_config,+ )+ from .local_server import LocalServer++ LocalServer(hermes_home).configure(server_config, runtime_changed=runtime_changed)+ self._emit(+ QuickLocalStage.WRITE_CONFIG,+ "Restarting Quick Local with the updated settings...",+ )+ reusable_endpoint = self._start_managed_server(preflight.paths, reusable_endpoint)+ self._emit(+ QuickLocalStage.COMPLETE,+ "Quick Local is ready with the updated settings."+ if runtime_changed or config_changed+ else "Existing Quick Local server is reachable; reusing it.",+ )+ return QuickLocalSetupResult(+ paths=preflight.paths,+ endpoint=reusable_endpoint,+ reused=True,+ )++ port = find_available_port(preferred_endpoint=_configured_endpoint(preflight.paths))+ if port is None:+ last_port = _DEFAULT_PORT + _PORT_ATTEMPTS - 1+ raise QuickLocalSetupError(+ "No available local port was found for OpenViking "+ f"(checked {_DEFAULT_PORT}-{last_port})."+ )+ endpoint = f"http://127.0.0.1:{port}"+ server_config = build_server_config(preflight.paths, vlm, port=port)++ self._validate_generated_config(+ paths=preflight.paths,+ endpoint=endpoint,+ server_config=server_config,+ )++ from .local_server import LocalServer++ preflight.paths.workspace.mkdir(parents=True, exist_ok=True)+ LocalServer(hermes_home).configure(server_config, runtime_changed=runtime_changed)+ endpoint = self._start_managed_server(preflight.paths, endpoint)+ self._emit(+ QuickLocalStage.WRITE_CONFIG,+ f"Saved Quick Local configuration to {preflight.paths.server_config}.",+ )+ self._emit(+ QuickLocalStage.COMPLETE,+ f"Quick Local is configured with {EMBEDDING_MODEL}.",+ )+ return QuickLocalSetupResult(+ paths=preflight.paths,+ endpoint=endpoint,+ reused=False,+ )++ def _ensure_openviking_installed(self, paths: QuickLocalPaths) -> bool:+ """Ensure a compatible runtime, returning whether installation was needed."""+ from .local_packages import install_requirements, verified_requirements++ requirements = install_requirements(allow_source_build=self.allow_source_build)+ receipt = paths.root / "runtime-requirements.json"+ try:+ installed_requirements = json.loads(receipt.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ installed_requirements = None+ if (+ openviking_install_satisfies_requirement(paths)+ and installed_requirements == requirements+ ):+ return False+ self._emit(+ QuickLocalStage.INSTALL_OPENVIKING,+ f"Installing {OPENVIKING_REQUIREMENT}...",+ )+ _prepare_private_directory(paths.root)+ if self.allow_source_build:+ self._emit(+ QuickLocalStage.INSTALL_OPENVIKING,+ "Source builds are allowed. Native compilation can take several minutes.",+ )+ if _pm_available():+ from pm.client import ensure_python_tool++ try:+ verified = verified_requirements(requirements, paths.root / "wheels")+ ensure_python_tool(+ "openviking-local",+ verified,+ "openviking-server",+ root=paths.runtime,+ explicit=True,+ timeout=1800,+ )+ except QuickLocalSetupError:+ raise+ except Exception as exc:+ raise QuickLocalSetupError(+ "Could not install the private OpenViking runtime. Review the installer output."+ ) from exc+ else: # Genuine pre-PM Hermes only; never fall back on a broken PM import.+ self._install_with_uv(paths, verified_requirements(requirements, paths.root / "wheels"))+ if not openviking_install_satisfies_requirement(paths):+ raise QuickLocalSetupError(+ "Could not install a compatible OpenViking local embedding runtime."+ )+ atomic_json_write(receipt, requirements, mode=0o600)+ return True++ def _install_with_uv(self, paths: QuickLocalPaths, requirements: list[str]) -> None:+ from hermes_cli.managed_uv import resolve_uv+ from hermes_constants import get_default_hermes_root++ # ensure_uv() can replace the active Hermes environment while setup is+ # running. Use an existing installer without repairing the host runtime.+ shared_uv = get_default_hermes_root() / "bin" / ("uv.exe" if os.name == "nt" else "uv")+ uv = resolve_uv() or shutil.which("uv") or (str(shared_uv) if shared_uv.is_file() else None)+ if not uv:+ raise QuickLocalSetupError("Quick Local needs uv. Install uv, then retry setup.")+ env = _private_child_env(paths.root.parent)+ env.update(UV_NATIVE_TLS="true", UV_SYSTEM_CERTS="true")+ commands = []+ if not paths.runtime_python.is_file():+ commands.append(([uv, "venv", str(paths.runtime), "--python", sys.executable], 120))+ commands.append(+ (+ [+ uv,+ "pip",+ "install",+ "--python",+ str(paths.runtime_python),+ *requirements,+ ],+ 1800,+ )+ )+ for command, timeout in commands:+ result = subprocess.run(+ command,+ cwd=paths.root,+ env=env,+ stdin=subprocess.DEVNULL,+ check=False,+ timeout=timeout,+ )+ if result.returncode:+ raise QuickLocalSetupError(+ "Could not install the private OpenViking runtime. Review the installer output."+ )++ def _validate_generated_config(+ self,+ *,+ paths: QuickLocalPaths,+ endpoint: str,+ server_config: dict[str, Any],+ ) -> None:+ _prepare_private_directory(paths.root)+ with tempfile.TemporaryDirectory(prefix="setup-validation-", dir=paths.root) as root:+ validation_root = Path(root)+ validation_config = json.loads(json.dumps(server_config))+ validation_config["storage"]["workspace"] = str(validation_root / _WORKSPACE_DIRNAME)+ config_path = validation_root / _SERVER_CONFIG_FILENAME+ atomic_json_write(config_path, validation_config, mode=0o600)++ self._emit(QuickLocalStage.VALIDATE, "Checking the copied Hermes LLM settings...")+ _validate_vlm(paths, config_path)++ _prepare_private_directory(paths.model_cache)+ self._emit(+ QuickLocalStage.PREPARE_EMBEDDING,+ f"Preparing {EMBEDDING_MODEL}; its {_MODEL_DOWNLOAD_SIZE} model "+ "is downloaded once if needed...",+ )+ _validate_local_embedding(paths)+ self._emit(+ QuickLocalStage.VALIDATE,+ "Validating OpenViking with a temporary local server...",+ )+ process = _start_validation_server(+ endpoint,+ config_path,+ paths.root.parent,+ paths.server_command,+ )+ primary_error: BaseException | None = None+ try:++ def validated_health(url):+ healthy, message = self._health_check(url)+ return healthy and _server_accepts_config(validation_config, url), message++ if not _wait_for_health(+ endpoint,+ validated_health,+ process=process,+ ):+ returncode = process.poll()+ if returncode is not None:+ raise QuickLocalSetupError(+ "OpenViking exited before becoming reachable "+ f"(status {returncode}). Review the server log at "+ f"{_server_log_path(paths.root.parent)} and retry."+ )+ raise QuickLocalSetupError(+ "OpenViking did not become reachable before the local model "+ "preparation timeout. Review the server log at "+ f"{_server_log_path(paths.root.parent)} and retry."+ )+ _validate_tenant_access(endpoint, server_config["server"]["root_api_key"])+ except BaseException as exc:+ primary_error = exc+ raise+ finally:+ if not _stop_process(process):+ message = "The temporary OpenViking validation server could not be stopped."+ if primary_error is None:+ raise QuickLocalSetupError(message)+ primary_error.add_note(message)++ def _start_managed_server(self, paths: QuickLocalPaths, endpoint: str) -> str:+ """Leave a validated service ready for the first turn and reserve its port."""+ self._emit(QuickLocalStage.VALIDATE, "Starting this profile's OpenViking server...")+ from .local_server import LocalServer++ server = LocalServer(paths.root.parent)+ started = server.start()+ ready = server.wait_ready(started, self._health_check)+ return ready.endpoint++ def _emit(self, stage: QuickLocalStage, message: str) -> None:+ self._progress(QuickLocalProgress(stage=stage, message=message))+++def _validate_vlm(paths: QuickLocalPaths, config_path: Path) -> None:+ """Check auth and transport through the exact private OV backend before activation."""+ script = """+import json, sys, time+import httpx, openai+from openviking.models.vlm import VLMFactory+for attempt in (1, 2):+ try:+ config = json.load(open(sys.argv[1], encoding="utf-8"))["vlm"]+ vlm = VLMFactory.create({**config, "timeout": 30, "max_retries": 0})+ reply = vlm.get_completion(prompt="Reply with OK only.")+ if not isinstance(reply, str) or not reply.strip():+ raise ValueError("Empty completion")+ break+ except Exception as exc:+ status = getattr(exc, "status_code", None)+ status = status if type(status) is int and 100 <= status <= 599 else None+ timed_out = isinstance(exc, (TimeoutError, httpx.TimeoutException, openai.APITimeoutError))+ retry = status == 429 or (status is not None and 500 <= status <= 599) or timed_out+ if attempt == 1 and retry:+ time.sleep(1)+ continue+ print(json.dumps({"error": type(exc).__name__, "status": status,+ "timeout": timed_out, "attempts": attempt}))+ sys.exit(1)+"""+ try:+ result = subprocess.run(+ [str(paths.runtime_python), "-c", script, str(config_path)],+ cwd=paths.root.parent,+ env=_private_child_env(paths.root.parent),+ stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ errors="replace",+ timeout=90,+ check=False,+ )+ if result.returncode:+ try:+ # OV may print import diagnostics before the final result.+ failure = json.loads(result.stdout.strip().rsplit("\n", 1)[-1])+ except (ValueError, TypeError):+ failure = {}+ raise _vlm_check_failure(paths, failure)+ except subprocess.TimeoutExpired as exc:+ raise _vlm_check_failure(paths, {+ "error": "TimeoutExpired", "timeout": True, "attempts": 0,+ }) from exc+++def _vlm_check_failure(paths: QuickLocalPaths, failure: Any) -> QuickLocalSetupError:+ """Report only safe error metadata, never a response body or captured stderr."""+ failure = failure if isinstance(failure, dict) else {}+ name = failure.get("error")+ if not isinstance(name, str) or not name.isascii() or not name.isidentifier() or len(name) > 80:+ name = "UnknownError"+ status = failure.get("status")+ status = status if type(status) is int and 100 <= status <= 599 else None+ timed_out = failure.get("timeout") is True+ attempts = failure.get("attempts")+ attempts = attempts if type(attempts) is int and 0 <= attempts <= 2 else 1+ detail = name + (f"; HTTP {status}" if status is not None else "")+ if timed_out:+ message = f"The Hermes LLM access check timed out ({detail}). Retry setup or check the provider's response time."+ else:+ if status in {401, 403}:+ guidance = "Check the API key and its permissions in Hermes."+ elif status == 404:+ guidance = "Check the model and endpoint in Hermes."+ elif status == 429:+ guidance = "The provider is rate-limiting requests. Wait, then retry setup."+ elif status is not None and status >= 500:+ guidance = "The provider reported a temporary server error. Retry setup later."+ elif name == "APIConnectionError":+ guidance = "Check the endpoint and network connection, then retry setup."+ else:+ guidance = "Check the model and endpoint. The model must support Chat Completions or Anthropic Messages."+ message = f"The copied Hermes LLM settings failed the access check ({detail}). {guidance}"+ log_path = _server_log_path(paths.root.parent)+ _prepare_private_directory(log_path.parent)+ if log_path.is_symlink():+ raise QuickLocalSetupError("Quick Local log must belong to this profile.")+ if not log_path.exists():+ log_path.touch(mode=0o600)+ if os.name != "nt":+ log_path.chmod(0o600)+ with log_path.open("a", encoding="utf-8") as log:+ log.write(f"LLM access check failed: {detail}; timeout={timed_out}; attempts={attempts}\n")+ return QuickLocalSetupError(message)+++def openviking_install_satisfies_requirement(paths: QuickLocalPaths) -> bool:+ if not paths.runtime_python.is_file() or not paths.server_command.is_file():+ return False+ try:+ result = subprocess.run(+ [+ str(paths.runtime_python),+ "-c",+ "import importlib.metadata; import llama_cpp; "+ "print(importlib.metadata.version('openviking'))",+ ],+ capture_output=True,+ text=True,+ check=False,+ stdin=subprocess.DEVNULL,+ timeout=120,+ )+ if result.returncode != 0:+ return False+ version = Version(result.stdout.strip())+ except subprocess.TimeoutExpired as exc:+ # A slow cold native import is not evidence of a missing installation.+ raise QuickLocalSetupError(+ "Quick Local's runtime check timed out. Retry setup; the runtime was not reinstalled."+ ) from exc+ except (InvalidVersion, OSError, subprocess.SubprocessError):+ return False+ return version in _OPENVIKING_VERSION_SPECIFIER+++def _validate_local_embedding(paths: QuickLocalPaths) -> None:+ """Health can pass with failed embeddings; exercise the native backend."""+ script = (+ "import math; "+ "from openviking.models.embedder.local_embedders import LocalDenseEmbedder; "+ f"e=LocalDenseEmbedder(model_name={EMBEDDING_MODEL!r},cache_dir={str(paths.model_cache)!r}); "+ "v=e.embed('memory setup validation').dense_vector; "+ f"assert len(v)=={EMBEDDING_DIMENSION} and all(math.isfinite(x) for x in v) and any(v)"+ )+ log_path = _server_log_path(paths.root.parent)+ _prepare_private_directory(log_path.parent)+ if log_path.is_symlink():+ raise QuickLocalSetupError("Quick Local log must belong to this profile.")+ if not log_path.exists():+ log_path.touch(mode=0o600)+ if os.name != "nt":+ log_path.chmod(0o600)+ try:+ with log_path.open("ab") as log:+ result = subprocess.run(+ [str(paths.runtime_python), "-c", script],+ env=_private_child_env(paths.root.parent),+ stdin=subprocess.DEVNULL,+ stdout=log,+ stderr=subprocess.STDOUT,+ check=False,+ timeout=_HEALTH_TIMEOUT_SECONDS,+ )+ if result.returncode:+ raise QuickLocalSetupError(+ "Quick Local's embedding model could not run. "+ f"Review {log_path}; use Custom setup with a separate server if needed."+ )+ except subprocess.TimeoutExpired as exc:+ raise QuickLocalSetupError(+ f"Quick Local's embedding check timed out. Review {log_path} and retry setup."+ ) from exc+++def find_available_port(+ *,+ preferred_endpoint: Optional[str] = None,+ first_port: int = _DEFAULT_PORT,+ attempts: int = _PORT_ATTEMPTS,+) -> Optional[int]:+ preferred_port = _endpoint_port(preferred_endpoint)+ candidates = range(first_port, first_port + attempts)+ if preferred_port is not None and (+ preferred_port in candidates or (first_port == _DEFAULT_PORT and preferred_port == 1933)+ ):+ candidates = [+ preferred_port,+ *(port for port in candidates if port != preferred_port),+ ]+ for port in candidates:+ if _can_bind_local_port("127.0.0.1", port):+ return port+ return None+++def _can_bind_local_port(host: str, port: int) -> bool:+ family = socket.AF_INET6 if ":" in host else socket.AF_INET+ try:+ # Some Unix kernels allow a specific-address bind beside a wildcard+ # listener with SO_REUSEADDR. Never take an already reachable port.+ with socket.socket(family, socket.SOCK_STREAM) as probe:+ probe.settimeout(0.2)+ if probe.connect_ex((host, port)) == 0:+ return False+ with socket.socket(family, socket.SOCK_STREAM) as candidate:+ if os.name == "nt":+ candidate.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)+ else:+ # Match Uvicorn: permit restart after closed connections remain+ # in TIME_WAIT, but never bind beside a listening server.+ candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ candidate.bind((host, port))+ return True+ except OSError:+ return False+++def find_reusable_endpoint(+ paths: QuickLocalPaths,+ health_check: HealthCheck,+) -> Optional[str]:+ endpoint = _configured_endpoint(paths)+ if endpoint is None:+ return None+ healthy, _message = health_check(endpoint)+ return endpoint if healthy and server_belongs_to_profile(paths, endpoint) else None+++def _configured_endpoint(paths: QuickLocalPaths) -> Optional[str]:+ if not paths.server_config.is_file() or not paths.ovcli_config.is_file():+ return None+ try:+ server_config = json.loads(paths.server_config.read_text(encoding="utf-8"))+ storage = server_config.get("storage", {}) if isinstance(server_config, dict) else {}+ if not isinstance(storage, dict) or not _paths_equivalent(+ storage.get("workspace"), paths.workspace+ ):+ return None+ profile = json.loads(paths.ovcli_config.read_text(encoding="utf-8"))+ return _normalize_local_endpoint(profile.get("url") if isinstance(profile, dict) else "")+ except (OSError, json.JSONDecodeError, TypeError, ValueError):+ return None+++def _server_key(paths: QuickLocalPaths) -> str:+ try:+ saved = json.loads(paths.server_config.read_text(encoding="utf-8"))+ if _paths_equivalent(saved.get("storage", {}).get("workspace"), paths.workspace):+ key = _clean_value(saved.get("server", {}).get("root_api_key"))+ if key:+ return key+ except (OSError, ValueError, AttributeError):+ pass+ return secrets.token_urlsafe(32)+++def server_belongs_to_profile(paths: QuickLocalPaths, endpoint: str) -> bool:+ """Do not reuse an unrelated service that took the saved local port."""+ try:+ saved = json.loads(paths.server_config.read_text(encoding="utf-8"))+ if not _paths_equivalent(saved.get("storage", {}).get("workspace"), paths.workspace):+ return False+ return _server_accepts_config(saved, endpoint)+ except (OSError, ValueError, AttributeError):+ return False+++def _server_accepts_config(config: Mapping[str, Any], endpoint: str) -> bool:+ import httpx++ try:+ key = _clean_value(config.get("server", {}).get("root_api_key"))+ if not key:+ return False+ with httpx.Client(timeout=3.0, trust_env=False) as client:+ health = client.get(f"{endpoint}/health").json()+ if (+ health.get("auth_mode") != "trusted"+ or health.get("root_api_key_required") is not True+ ):+ return False+ response = client.get(f"{endpoint}/api/v1/admin/accounts", headers={"X-API-Key": key})+ return response.status_code == 200 and response.json().get("status") == "ok"+ except (ValueError, AttributeError, httpx.HTTPError):+ return False+++def _validate_tenant_access(endpoint: str, key: str) -> None:+ """Exercise a data write only in the disposable validation workspace."""+ import httpx++ try:+ response = httpx.post(+ f"{endpoint}/api/v1/sessions",+ json={},+ headers={+ "X-API-Key": key,+ "X-OpenViking-Account": "default",+ "X-OpenViking-User": "default",+ },+ timeout=5.0,+ trust_env=False,+ )+ response.raise_for_status()+ if response.json().get("status") != "ok":+ raise ValueError("session creation failed")+ except (ValueError, httpx.HTTPError) as exc:+ raise QuickLocalSetupError(+ "Quick Local could not validate memory data access. Review the server log and retry."+ ) from exc+++def _write_ovcli_profile(path: Path, endpoint: str, server_config: Mapping[str, Any]) -> None:+ atomic_json_write(+ path,+ {+ "url": endpoint,+ "root_api_key": server_config["server"]["root_api_key"],+ "account": "default",+ "user": "default",+ "actor_peer_id": "hermes",+ },+ mode=0o600,+ )+++def connection_config(provider_config: Mapping[str, Any], hermes_home: Path) -> dict[str, Any]:+ """Resolve only this profile's managed files, including after profile import."""+ paths = managed_paths(hermes_home)+ repair_private_paths(paths)+ endpoint = _configured_endpoint(paths)+ if endpoint is None:+ raise QuickLocalSetupError(+ "Quick Local configuration is missing or belongs to another profile. Run hermes memory setup openviking again."+ )+ try:+ profile = json.loads(paths.ovcli_config.read_text(encoding="utf-8"))+ saved = json.loads(paths.server_config.read_text(encoding="utf-8"))+ if not isinstance(profile, dict) or not isinstance(saved, dict):+ raise ValueError("invalid configuration")+ except (OSError, ValueError) as exc:+ raise QuickLocalSetupError(+ "Quick Local configuration could not be read. Run hermes memory setup openviking again."+ ) from exc+ if (+ not isinstance(saved.get("server"), dict)+ or not profile.get("root_api_key")+ or profile["root_api_key"] != saved["server"].get("root_api_key")+ ):+ raise QuickLocalSetupError(+ "Quick Local credentials are incomplete. Run hermes memory setup openviking again."+ )+ return profile+++def _start_validation_server(+ endpoint: str,+ config_path: Path,+ hermes_home: Path,+ server_command: Path,+) -> subprocess.Popen:+ if not server_command.is_file():+ raise QuickLocalSetupError("openviking-server was not found after installation.")+ command = str(server_command)+ host, port = _endpoint_bind(endpoint)+ if not _can_bind_local_port(host, port):+ raise QuickLocalSetupError(+ f"Local port {host}:{port} became unavailable before OpenViking "+ "could start. Retry Quick Local setup."+ )+ log_path = _server_log_path(hermes_home)+ log_path.parent.mkdir(parents=True, exist_ok=True)+ if not log_path.exists():+ log_path.touch(mode=0o600)+ log_path.chmod(0o600)+ child_env = _private_child_env(hermes_home)+ from hermes_cli._subprocess_compat import windows_detach_popen_kwargs++ popen_kwargs: dict[str, Any] = windows_detach_popen_kwargs()+ command_args = [+ command,+ "--config",+ str(config_path),+ "--host",+ host,+ "--port",+ str(port),+ ]+ try:+ with log_path.open("ab") as log_file:+ common_kwargs: dict[str, Any] = {+ "stdout": log_file,+ "stderr": log_file,+ "env": child_env,+ "cwd": hermes_home,+ }+ try:+ return subprocess.Popen(+ command_args,+ **common_kwargs,+ **popen_kwargs,+ stdin=subprocess.DEVNULL,+ )+ except OSError:+ if os.name != "nt":+ raise+ from hermes_cli._subprocess_compat import (+ windows_detach_flags_without_breakaway,+ )++ return subprocess.Popen(+ command_args,+ **common_kwargs,+ creationflags=windows_detach_flags_without_breakaway(),+ stdin=subprocess.DEVNULL,+ )+ except Exception as exc:+ raise QuickLocalSetupError(f"Could not start the OpenViking server: {exc}") from exc+++def _wait_for_health(+ endpoint: str,+ health_check: HealthCheck,+ *,+ process: Optional[subprocess.Popen] = None,+ timeout_seconds: float = _HEALTH_TIMEOUT_SECONDS,+) -> bool:+ deadline = time.monotonic() + timeout_seconds+ while time.monotonic() < deadline:+ healthy, _message = health_check(endpoint)+ if healthy:+ return True+ if process is not None and process.poll() is not None:+ return False+ time.sleep(_HEALTH_POLL_INTERVAL_SECONDS)+ return False+++def _stop_process(process: subprocess.Popen) -> bool:+ import psutil++ from .local_server import stop_process_tree++ try:+ if process.poll() is not None:+ return True+ stop_process_tree(psutil.Process(process.pid), timeout=_PROCESS_STOP_TIMEOUT_SECONDS)+ process.wait(timeout=_PROCESS_STOP_TIMEOUT_SECONDS)+ return True+ except psutil.NoSuchProcess:+ # The child can finish between poll() and taking its process handle.+ return True+ except Exception:+ return False+++def _has_copyable_static_credentials(+ provider: str,+ source: str,+ api_key: str,+) -> bool:+ """Return whether Hermes explicitly classifies this credential as static."""++ if not api_key or api_key == "aws-sdk":+ return False++ if provider == "custom":+ return source in {"direct-alias", "env/config"} or source.startswith(+ (+ "custom_provider:",+ "pool:",+ )+ )+ if provider == "openrouter":+ return source == "env/config" or source.startswith(+ (+ "credential_pool:",+ "env:",+ "manual:",+ "pool:",+ )+ )++ from hermes_cli.auth import PROVIDER_REGISTRY++ provider_config = PROVIDER_REGISTRY.get(provider)+ if provider == "copilot" or provider_config is None or provider_config.auth_type != "api_key":+ return False++ if source in {"config", "default", "env", "local-offline"}:+ return True+ api_key_sources = {value.lower() for value in provider_config.api_key_env_vars}+ if source in api_key_sources:+ return True+ if source.startswith("env:"):+ return source.removeprefix("env:") in api_key_sources+ if source.startswith("credential_pool:"):+ return source.removeprefix("credential_pool:") == provider+ return source.startswith("manual:")+++def _stored_server_config_matches(+ paths: QuickLocalPaths,+ expected: Mapping[str, Any],+) -> bool:+ try:+ saved = json.loads(paths.server_config.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError, TypeError, ValueError):+ return False+ return saved == expected+++def _prepare_private_directory(path: Path) -> None:+ if path.is_symlink():+ raise QuickLocalSetupError("Quick Local private directories must belong to this profile.")+ path.mkdir(parents=True, exist_ok=True, mode=0o700)+ if os.name != "nt":+ path.chmod(0o700)+++def repair_private_paths(paths: QuickLocalPaths) -> None:+ """Backup/import may restore permissive modes on plugin-owned files."""+ _prepare_private_directory(paths.root)+ for path in (+ paths.server_config,+ paths.ovcli_config,+ paths.restart_required_marker,+ paths.root / "server-process.json",+ paths.root / "server.lock",+ paths.root / "runtime-requirements.json",+ ):+ if path.is_symlink():+ raise QuickLocalSetupError("Quick Local private files must belong to this profile.")+ if path.exists() and os.name != "nt":+ path.chmod(0o600)+++def _pm_available() -> bool:+ return importlib.util.find_spec("pm") is not None+++def _private_child_env(hermes_home: Path) -> dict[str, str]:+ from tools.environments import local as subprocess_env++ if hasattr(subprocess_env, "served_profile_child_env"):+ env = subprocess_env.served_profile_child_env(target_home=hermes_home)+ else:+ env = subprocess_env.hermes_subprocess_env()+ env["HERMES_HOME"] = str(hermes_home)+ for key in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV"):+ env.pop(key, None)+ return env+++def _server_log_path(hermes_home: Path) -> Path:+ return hermes_home / "logs" / "openviking-server.log"+++def _normalize_local_endpoint(value: Any) -> Optional[str]:+ endpoint = _clean_value(value).rstrip("/")+ if not endpoint:+ return None+ if "://" not in endpoint:+ endpoint = f"http://{endpoint}"+ parsed = urlparse(endpoint)+ if parsed.scheme.lower() != "http":+ return None+ if (parsed.hostname or "").lower() not in {"localhost", "127.0.0.1", "::1"}:+ return None+ host = f"[{parsed.hostname}]" if parsed.hostname == "::1" else parsed.hostname+ return f"http://{host}:{parsed.port or _DEFAULT_PORT}"+++def _endpoint_bind(endpoint: str) -> tuple[str, int]:+ parsed = urlparse(endpoint)+ return parsed.hostname or "127.0.0.1", parsed.port or _DEFAULT_PORT+++def _endpoint_port(endpoint: Optional[str]) -> Optional[int]:+ if not endpoint:+ return None+ try:+ return urlparse(endpoint).port or _DEFAULT_PORT+ except ValueError:+ return None+++def _paths_equivalent(left: Any, right: Path) -> bool:+ if not isinstance(left, (str, os.PathLike)):+ return False+ try:+ return Path(left).expanduser().resolve() == right.expanduser().resolve()+ except (OSError, RuntimeError, TypeError, ValueError):+ return False+++def _clean_value(value: Any) -> str:+ return value.strip() if isinstance(value, str) else ""diff --git a/examples/hermes-plugin/tests/test_local_lifecycle.py b/examples/hermes-plugin/tests/test_local_lifecycle.pynew file mode 100644index 000000000..455e027f1--- /dev/null+++ b/examples/hermes-plugin/tests/test_local_lifecycle.py@@ -0,0 +1,725 @@+"""Ownership, restart and installer regressions through the external package."""++import hashlib+import importlib+import os+import subprocess+import sys+from concurrent.futures import ThreadPoolExecutor+from unittest.mock import MagicMock++import pytest+++def modules(external_provider):+ home, provider, module, _settings = external_provider("lifecycle")+ ql = importlib.import_module(module.__name__ + ".quick_local")+ lifecycle = importlib.import_module(module.__name__ + ".local_server")+ packages = importlib.import_module(module.__name__ + ".local_packages")+ return home, provider, module, ql, lifecycle, packages+++def servers(modules, monkeypatch):+ home, _provider, _module, ql, lifecycle, _packages = modules+ monkeypatch.setattr(ql, "_pm_available", lambda: False)+ available = ql.find_available_port+ first_port = 20000 + int(hashlib.sha256(str(home).encode()).hexdigest()[:8], 16) % 40000+ monkeypatch.setattr(+ ql,+ "find_available_port",+ lambda **kwargs: available(first_port=first_port, attempts=20, **kwargs),+ )+ children = []++ def spawn(endpoint, config, hermes_home, command):+ host, port = ql._endpoint_bind(endpoint)+ process = subprocess.Popen(+ [+ sys.executable,+ str(command),+ "--config",+ str(config),+ "--host",+ host,+ "--port",+ str(port),+ ],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ children.append(process)+ return process++ monkeypatch.setattr(ql, "_start_validation_server", spawn)++ def create(name):+ server = lifecycle.LocalServer(home.parent / name)+ command = server.paths.server_command+ command.parent.mkdir(parents=True)+ command.write_text(+ """import argparse,json,os,subprocess,sys,time+from pathlib import Path+from http.server import BaseHTTPRequestHandler,HTTPServer+p=argparse.ArgumentParser();p.add_argument('--config');p.add_argument('--host');p.add_argument('--port',type=int);a=p.parse_args()+c=json.load(open(a.config));key=c['server']['root_api_key']+if c['vlm'].get('crash'):time.sleep(.2);raise SystemExit(9)+if c['vlm'].get('child'):+ child=subprocess.Popen([sys.executable,'-c','import time;time.sleep(120)'])+ Path(a.config+'.child').write_text(str(child.pid))+class Handler(BaseHTTPRequestHandler):+ def log_message(self,*args):pass+ def do_GET(self):+ ok=self.path=='/health' or self.headers.get('X-API-Key')==key+ self.send_response(200 if ok else 401);self.end_headers()+ self.wfile.write(json.dumps({'status':'ok','healthy':True,'version':'0.4.22','auth_mode':'trusted','root_api_key_required':True}).encode())+# Match asyncio/Uvicorn: Windows listeners do not share an active address.+HTTPServer.allow_reuse_address = os.name != 'nt'+HTTPServer((a.host,a.port),Handler).serve_forever()+""",+ encoding="utf-8",+ )+ config = ql.build_server_config(server.paths, {"model": "first"}, port=1933)+ server.configure(config)+ return server++ yield create+ for process in children:+ if process.poll() is None:+ process.terminate()+ process.wait(timeout=10)+++def ready(server):+ # Windows connection-refused probes can each take over one second.+ return server.wait_ready(server.start(), lambda _url: (True, ""), timeout=20)++[email protected]("action", ["start", "restart"])[email protected]("memory", [+ {"provider": "openviking", "openviking": {"deployment": "cloud"}},+ {"provider": "openviking", "openviking": {}},+ {"provider": "honcho", "openviking": {"deployment": "quick_local"}},+])+def test_cli_refuses_start_when_quick_local_is_not_selected(servers, modules, monkeypatch, capsys, action, memory):+ import json+ from argparse import Namespace++ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ server = servers("inactive-cli")+ home = server.paths.root.parent+ config = home / "config.yaml"+ config.write_text(json.dumps({"memory": memory}), encoding="utf-8")+ before = config.read_bytes()+ cli = importlib.import_module(modules[3].__package__ + ".cli")+ monkeypatch.setattr(cli, "get_hermes_home", lambda: home)+ token = set_hermes_home_override(home)+ try:+ with pytest.raises(SystemExit) as caught:+ cli._run(Namespace(local_action=action))+ assert caught.value.code == 1+ assert "not using Quick Local" in capsys.readouterr().out+ assert server.status()["state"] == "stopped"+ assert config.read_bytes() == before+ finally:+ reset_hermes_home_override(token)+++def test_cli_controls_selected_and_retained_server(servers, modules, monkeypatch, capsys):+ import json+ from argparse import Namespace++ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ server = servers("selected-cli")+ home = server.paths.root.parent+ config = home / "config.yaml"+ config.write_text(json.dumps({"memory": {"provider": "openviking", "openviking": {+ "deployment": "quick_local"}}}), encoding="utf-8")+ cli = importlib.import_module(modules[3].__package__ + ".cli")+ monkeypatch.setattr(cli, "get_hermes_home", lambda: home)+ token = set_hermes_home_override(home)+ try:+ cli._run(Namespace(local_action="start"))+ assert server.status()["state"] == "ready"+ old_pid = server.status()["pid"]+ cli._run(Namespace(local_action="restart"))+ assert server.status()["state"] == "ready"+ assert server.status()["pid"] != old_pid+ config.write_text(json.dumps({"memory": {"provider": "openviking", "openviking": {+ "deployment": "cloud"}}}), encoding="utf-8")+ cli._run(Namespace(local_action="status"))+ assert "Quick Local: ready" in capsys.readouterr().out+ cli._run(Namespace(local_action="stop"))+ assert server.status()["state"] == "stopped"+ finally:+ reset_hermes_home_override(token)+++def test_restart_keeps_data_and_changes_only_owned_process(servers):+ a, b = servers("a"), servers("b")+ ready(a)+ ready(b)+ old_a, old_b = a.status()["pid"], b.status()["pid"]+ a.paths.workspace.mkdir()+ marker = a.paths.workspace / "existing-memory"+ marker.write_text("keep")+ config = a._config()+ config["vlm"]["model"] = "second"+ a.configure(config)+ restarted = ready(a)+ assert not restarted.reused+ assert a.status()["pid"] != old_a+ assert b.status()["pid"] == old_b+ assert marker.read_text() == "keep"+ assert not a.paths.restart_required_marker.exists()+++def test_foreign_saved_port_moves_endpoint_without_stopping_foreign_server(servers):+ a, b = servers("a"), servers("b")+ ready(a)+ endpoint = a.status()["endpoint"]+ ready(b)+ a.stop()+ config = b._config()+ config["server"]["port"] = a.ql._endpoint_port(endpoint)+ b.configure(config)+ ready(b)+ foreign_pid = b.status()["pid"]+ moved = ready(a)+ assert moved.endpoint != endpoint+ assert a.ql.connection_config({}, a.paths.root.parent)["url"] == moved.endpoint+ assert b.status()["pid"] == foreign_pid+ assert a.status()["state"] == "ready"+++def test_concurrent_starts_of_one_profile_create_one_process(servers):+ a = servers("a")+ with ThreadPoolExecutor(max_workers=2) as executor:+ first, second = list(executor.map(lambda _: a.start(), range(2)))+ assert first.process.pid == second.process.pid+ a.wait_ready(first, lambda _url: (True, ""), timeout=20)+++def test_two_profiles_can_recover_a_concurrent_port_race(servers):+ a, b = servers("a"), servers("b")+ with ThreadPoolExecutor(max_workers=2) as executor:+ first, second = list(executor.map(ready, (a, b)))+ assert first.endpoint != second.endpoint+ assert a.status()["state"] == b.status()["state"] == "ready"++[email protected]("alter", ["pid", "created", "command", "port"])+def test_process_record_cannot_authorize_stopping_a_different_process(servers, alter):+ a, b = servers("a"), servers("b")+ ready(a)+ ready(b)+ record = a._read_record()+ foreign = b._read_record()+ record[alter] = foreign[alter] if alter != "created" else record[alter] + 1+ # Both servers can use the same port only before recovery. Ensure port differs.+ if alter == "port":+ record["port"] += 100+ assert a._verified_process(record) is None+ assert b.status()["state"] == "ready"+++def test_early_server_exit_fails_promptly_and_clears_process_record(servers):+ a = servers("a")+ config = a._config()+ config["vlm"]["crash"] = True+ a.configure(config)+ started = a.start()+ assert started.process.wait(timeout=10) == 9+ health = MagicMock()+ with pytest.raises(a.ql.QuickLocalSetupError, match="did not become ready"):+ a.wait_ready(started, health, timeout=600)+ health.assert_not_called()+ assert not a.record_path.exists()+++def test_temporary_validation_stop_also_stops_launcher_child(servers):+ import psutil++ a = servers("a")+ config = a._config()+ config["vlm"]["child"] = True+ a.configure(config)+ started = ready(a)+ child = psutil.Process(int(a.paths.server_config.with_name("ov.conf.child").read_text()))+ assert child.is_running()+ assert a.ql._stop_process(started.process)+ assert started.process.poll() is not None+ assert not child.is_running() or child.status() == psutil.STATUS_ZOMBIE+++def test_restore_repairs_private_modes_without_touching_external_paths(modules, tmp_path):+ home, _p, _m, ql, lifecycle, _packages = modules+ server = lifecycle.LocalServer(home)+ server.configure(ql.build_server_config(server.paths, {"model": "first"}))+ server.paths.root.chmod(0o755)+ server.paths.server_config.chmod(0o644)+ server.paths.ovcli_config.chmod(0o644)+ ql.connection_config({}, home)+ if os.name != "nt":+ assert server.paths.root.stat().st_mode & 0o777 == 0o700+ assert server.paths.server_config.stat().st_mode & 0o777 == 0o600+ assert server.paths.ovcli_config.stat().st_mode & 0o777 == 0o600+ outside = tmp_path / "outside"+ outside.write_text("unrelated")+ server.paths.ovcli_config.unlink()+ try:+ server.paths.ovcli_config.symlink_to(outside)+ except OSError:+ pytest.skip("symlinks unavailable")+ with pytest.raises(ql.QuickLocalSetupError, match="private files"):+ ql.connection_config({}, home)+ assert outside.read_text() == "unrelated"++[email protected]("error", [OSError("spawn"), RuntimeError("installer")])+def test_unexpected_start_failure_clears_flag_and_reaches_cli(modules, monkeypatch, error):+ home, provider, _module, ql, lifecycle, _packages = modules+ provider._hermes_home = str(home)+ provider._endpoint = "http://127.0.0.1:1933"+ monkeypatch.setattr(+ provider, "_profile_config_and_env", lambda: ({"deployment": ql.DEPLOYMENT}, {})+ )+ monkeypatch.setattr(lifecycle.LocalServer, "start", MagicMock(side_effect=error))+ warnings = []+ provider._handle_runtime_openviking_unreachable(warning_callback=warnings.append)+ assert not provider._runtime_start_pending+ assert len(warnings) == 1 and type(error).__name__ in warnings[0]+ provider._handle_runtime_openviking_unreachable(warning_callback=warnings.append)+ assert len(warnings) == 2+++def test_cold_import_timeout_does_not_trigger_reinstallation(modules, monkeypatch):+ home, _p, _m, ql, _life, _packages = modules+ paths = ql.managed_paths(home)+ monkeypatch.setattr(ql, "_pm_available", lambda: False)+ paths.runtime_python.parent.mkdir(parents=True)+ paths.runtime_python.touch()+ paths.server_command.touch()+ monkeypatch.setattr(+ ql.subprocess, "run", MagicMock(side_effect=subprocess.TimeoutExpired("probe", 120))+ )+ engine = ql.QuickLocalSetup(health_check=lambda _url: (False, ""))+ install = MagicMock()+ monkeypatch.setattr(engine, "_install_with_uv", install)+ with pytest.raises(ql.QuickLocalSetupError, match="not reinstalled"):+ engine._ensure_openviking_installed(paths)+ install.assert_not_called()++[email protected]("failure", [1, subprocess.TimeoutExpired("embedding", 660)])+def test_failed_native_embedding_does_not_activate_setup(modules, monkeypatch, failure):+ home, _p, _m, ql, _life, _packages = modules+ monkeypatch.setattr(ql, "_validate_vlm", lambda *_args: None)+ monkeypatch.setattr(ql, "_pm_available", lambda: False)+ monkeypatch.setattr(ql, "_private_child_env", lambda target: {"HERMES_HOME": str(target)})+ run = MagicMock()+ if isinstance(failure, Exception):+ run.side_effect = failure+ else:+ run.return_value.returncode = failure+ monkeypatch.setattr(ql.subprocess, "run", run)+ start = MagicMock()+ monkeypatch.setattr(ql, "_start_validation_server", start)+ paths = ql.managed_paths(home)+ engine = ql.QuickLocalSetup(health_check=lambda _url: (True, ""))+ with pytest.raises(ql.QuickLocalSetupError, match="embedding"):+ engine._validate_generated_config(+ paths=paths,+ endpoint="http://127.0.0.1:1933",+ server_config=ql.build_server_config(paths, {"model": "test"}),+ )+ start.assert_not_called()+ assert not paths.server_config.exists() and not paths.ovcli_config.exists()+ assert run.call_args.kwargs["timeout"] == ql._HEALTH_TIMEOUT_SECONDS+ assert run.call_args.kwargs["env"]["HERMES_HOME"] == str(home)+ assert "math.isfinite" in run.call_args.args[0][-1]+++def test_platform_without_reviewed_binary_requires_explicit_consent(modules, monkeypatch):+ _home, _p, _m, ql, _life, packages = modules+ monkeypatch.setattr(packages.platform, "system", lambda: "Darwin")+ monkeypatch.setattr(packages.platform, "machine", lambda: "x86_64")+ monkeypatch.setattr(packages.platform, "mac_ver", lambda: ("15.0", (), ""))+ with pytest.raises(ql.SourceBuildRequired, match="explicitly allow"):+ packages.install_requirements()+ assert "llama-cpp-python==0.3.30" in packages.install_requirements(allow_source_build=True)+++def test_broken_pm_import_never_calls_legacy_uv_shim(modules, monkeypatch):+ import builtins++ home, _p, _m, ql, _life, _packages = modules+ monkeypatch.setattr(ql, "openviking_install_satisfies_requirement", lambda _paths: False)+ monkeypatch.setattr(ql, "_pm_available", lambda: True)+ original = builtins.__import__++ def import_module(name, *args, **kwargs):+ if name == "pm.client":+ raise ImportError("broken transitive PM dependency")+ return original(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", import_module)+ engine = ql.QuickLocalSetup(health_check=lambda _url: (False, ""))+ fallback = MagicMock()+ monkeypatch.setattr(engine, "_install_with_uv", fallback)+ with pytest.raises(ImportError, match="transitive"):+ engine._ensure_openviking_installed(ql.managed_paths(home))+ fallback.assert_not_called()++[email protected]("served_profiles", [False, True])+def test_legacy_installer_uses_profile_child_environment(modules, monkeypatch, served_profiles):+ from hermes_cli import managed_uv+ from tools.environments import local as subprocess_env++ home, _p, _m, ql, _life, _packages = modules+ source_env = {+ "PATH": os.defpath,+ "HERMES_HOME": "launch-profile",+ "OPENVIKING_API_KEY": "profile-key",+ "PYTHONPATH": "host-pythonpath",+ "PYTHONHOME": "host-pythonhome",+ "VIRTUAL_ENV": "host-runtime",+ }+ child_env = MagicMock(return_value=source_env.copy())+ if served_profiles:+ source_env["HERMES_HOME"] = str(home)+ child_env.return_value = source_env.copy()+ monkeypatch.setattr(subprocess_env, "served_profile_child_env", child_env, raising=False)+ else:+ monkeypatch.delattr(subprocess_env, "served_profile_child_env", raising=False)+ monkeypatch.setattr(subprocess_env, "hermes_subprocess_env", child_env)+ monkeypatch.setattr(managed_uv, "resolve_uv", lambda: "uv")+ repair = MagicMock(side_effect=AssertionError("must not repair the Hermes runtime"))+ monkeypatch.setattr(managed_uv, "ensure_uv", repair)+ run = MagicMock(return_value=MagicMock(returncode=0))+ monkeypatch.setattr(ql.subprocess, "run", run)+ engine = ql.QuickLocalSetup(health_check=lambda _url: (False, ""))+ engine._install_with_uv(ql.managed_paths(home), ["reviewed-package"])+ if served_profiles:+ child_env.assert_called_once_with(target_home=home)+ else:+ child_env.assert_called_once_with()+ assert run.call_count == 2+ for call in run.call_args_list:+ env = call.kwargs["env"]+ assert env["HERMES_HOME"] == str(home)+ assert env["OPENVIKING_API_KEY"] == "profile-key"+ assert not any(key in env for key in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV"))+ assert source_env["PYTHONPATH"] == "host-pythonpath"+++def test_pending_recovery_identity_survives_managed_port_move(modules, monkeypatch):+ home, provider, _module, ql, _life, _packages = modules+ provider._hermes_home = str(home)+ monkeypatch.setattr(+ provider, "_profile_config_and_env", lambda: ({"deployment": ql.DEPLOYMENT}, {})+ )+ provider._client = MagicMock(+ _conn_snapshot=("http://127.0.0.1:1933", "key", "default", "default", "hermes")+ )+ first = provider._capture_commit_scope()+ provider._client = MagicMock(+ _conn_snapshot=("http://127.0.0.1:1934", "key", "default", "default", "hermes")+ )+ moved = provider._capture_commit_scope()+ assert first.connection_key == moved.connection_key+ assert first.marker_id != moved.marker_id+ provider._client = MagicMock(+ _conn_snapshot=("http://127.0.0.1:1934", "key", "default", "other", "hermes")+ )+ assert provider._capture_commit_scope().connection_key != moved.connection_key++[email protected]("consent", [False, True])+def test_source_build_prompt_defaults_to_cancel(modules, monkeypatch, consent):+ home, _provider, _module, ql, lifecycle, _packages = modules+ setup_module = importlib.import_module(ql.__package__ + "._setup")+ server = lifecycle.LocalServer(home)+ server.configure(ql.build_server_config(server.paths, {"model": "test"}))+ engine = MagicMock()+ error = ql.SourceBuildRequired("A source build needs native development tools.")+ engine.provision.side_effect = [+ error,+ ql.QuickLocalSetupResult(server.paths, "http://127.0.0.1:1933", False),+ ]+ monkeypatch.setattr(ql, "QuickLocalSetup", lambda **_kwargs: engine)+ select = MagicMock(return_value=int(consent))+ config = {"memory": {}}+ provider_config = {}+ result = setup_module._run_quick_local_setup(+ config=config,+ provider_config=provider_config,+ env_path=home / ".env",+ select=select,+ cancelled=object(),+ )+ assert result is consent+ assert select.call_args.kwargs["default"] == 0+ assert engine.provision.call_count == (2 if consent else 1)+ if consent:+ assert engine.allow_source_build is True+ assert provider_config["deployment"] == ql.DEPLOYMENT+ else:+ assert provider_config == {}+++def test_port_probe_rejects_active_listener(modules):+ import socket++ _home, _p, _m, ql, _life, _packages = modules+ with socket.socket() as listener:+ if os.name == "nt":+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)+ else:+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ listener.bind(("0.0.0.0", 0))+ port = listener.getsockname()[1]+ listener.listen()+ assert not ql._can_bind_local_port("127.0.0.1", port)+ assert ql._can_bind_local_port("127.0.0.1", port)+++ "system,machine",+ [("Darwin", "arm64"), ("Linux", "x86_64"), ("Linux", "aarch64"), ("Windows", "AMD64")],+)+def test_supported_binary_requirements_pin_both_archives_by_hash(+ modules, monkeypatch, system, machine+):+ _home, _p, _m, _ql, _life, packages = modules+ monkeypatch.setattr(packages.platform, "system", lambda: system)+ monkeypatch.setattr(packages.platform, "machine", lambda: machine)+ monkeypatch.setattr(packages.platform, "mac_ver", lambda: ("14.0", (), ""))+ monkeypatch.setattr(packages.platform, "libc_ver", lambda: ("glibc", "2.31"))+ requirements = packages.install_requirements()+ assert all("#sha256=" in requirement for requirement in requirements[:2])+ assert "metal" in requirements[1] if system == "Darwin" else "metal" not in requirements[1]++[email protected]("action", ["kill", "stop"])+def test_live_provider_recovers_a_stopped_server_in_the_same_session(servers, modules, action):+ import time++ import psutil++ _home, provider, _module, ql, _life, _packages = modules+ server = servers("live-provider")+ ready(server)+ callbacks = []+ provider._profile_config_and_env = lambda: ({"deployment": ql.DEPLOYMENT}, {})+ provider.initialize(+ "retained-session",+ hermes_home=str(server.paths.root.parent),+ platform="cli",+ status_callback=callbacks.append,+ warning_callback=callbacks.append,+ )+ old_client = provider._ensure_client()+ old_pid = server.status()["pid"]+ assert old_client is not None+ if action == "kill":+ psutil.Process(old_pid).kill()+ else:+ server.stop()+ assert provider._ensure_client() is None+ deadline = time.monotonic() + 20+ while provider._ensure_client() is None and time.monotonic() < deadline:+ time.sleep(0.05)+ assert provider._client is not None and provider._client is not old_client+ assert server.status()["pid"] != old_pid+ assert any("Starting Quick Local" in message for message in callbacks)+++def test_configure_refuses_unverifiable_server_before_changing_live_files(servers, monkeypatch):+ server = servers("unverified")+ ready(server)+ before = {+ path: path.read_bytes() for path in (server.paths.server_config, server.paths.ovcli_config)+ }+ monkeypatch.setattr(server, "_verified_process", lambda _record: None)+ monkeypatch.setattr(server, "_adopt", lambda *_args: None)+ config = server._config()+ config["server"]["root_api_key"] = "rotated-test-key"+ with pytest.raises(server.ql.QuickLocalSetupError, match="cannot verify"):+ server.configure(config)+ assert all(path.read_bytes() == value for path, value in before.items())+ assert not server.paths.restart_required_marker.exists()+ assert server.ql.server_belongs_to_profile(server.paths, server.status()["endpoint"])+++def test_configure_adopts_a_lost_record_before_changing_the_key(servers):+ import psutil++ server = servers("lost-record")+ ready(server)+ old_pid = server.status()["pid"]+ old_family = {old_pid, *(p.pid for p in psutil.Process(old_pid).children(recursive=True))}+ server.record_path.unlink()+ config = server._config()+ config["server"]["root_api_key"] = "rotated-test-key"+ server.configure(config)+ # Windows venv redirectors expose a launcher and a child with the same+ # command. Either verified member can own the recovered record.+ assert server._read_record()["pid"] in old_family+ ready(server)+ assert server.status()["pid"] not in old_family+ assert server.ql.server_belongs_to_profile(server.paths, server.status()["endpoint"])+++def test_new_managed_ports_leave_the_openviking_default_free(modules, monkeypatch):+ _home, _p, _m, ql, _life, _packages = modules+ monkeypatch.setattr(ql, "_can_bind_local_port", lambda *_args: True)+ assert ql.find_available_port() == 1934+ # Existing Quick Local profiles retain their original port.+ assert ql.find_available_port(preferred_endpoint="http://127.0.0.1:1933") == 1933+++def test_retained_provider_recovers_a_port_taken_by_another_profile(servers, modules):+ import time++ _h, provider, _module, ql, _life, _packages = modules+ a, b = servers("retained-a"), servers("retained-b")+ ready(a)+ old_endpoint = a.status()["endpoint"]+ provider._profile_config_and_env = lambda: ({"deployment": ql.DEPLOYMENT}, {})+ provider.initialize("retained-port", hermes_home=str(a.paths.root.parent), platform="cli")+ assert provider._ensure_client() is not None+ a.stop()+ config = b._config()+ config["server"]["port"] = ql._endpoint_port(old_endpoint)+ b.configure(config)+ ready(b)+ foreign_pid = b.status()["pid"]+ assert provider._ensure_client() is None+ deadline = time.monotonic() + 20+ while provider._ensure_client() is None and time.monotonic() < deadline:+ time.sleep(0.05)+ assert provider._client is not None+ assert provider._endpoint != old_endpoint+ assert provider._endpoint == ql.connection_config({}, a.paths.root.parent)["url"]+ assert b.status()["pid"] == foreign_pid+++def test_switching_away_stops_only_the_previous_managed_server(servers, modules, capsys):+ _h, _p, _m, ql, _life, _packages = modules+ setup = importlib.import_module(ql.__package__ + "._setup")+ a, b = servers("switch-a"), servers("switch-b")+ ready(a)+ ready(b)+ b_pid = b.status()["pid"]+ config = {"memory": {}}+ provider_config = {"deployment": ql.DEPLOYMENT}+ a.paths.workspace.mkdir()+ marker = a.paths.workspace / "retained-memory"+ marker.write_text("keep")+ setup._save_hermes_only_config(+ config=config,+ provider_config=provider_config,+ env_path=a.paths.root.parent / ".env",+ values={"endpoint": "https://custom.example", "api_key": "synthetic-key"},+ )+ assert a.status()["state"] == "stopped"+ assert b.status()["pid"] == b_pid+ assert marker.read_text() == "keep"+ assert "data is retained" in capsys.readouterr().out+++def test_unconfigured_status_does_not_create_managed_storage(modules, monkeypatch, capsys):+ from argparse import Namespace++ home, _p, _m, ql, _life, _packages = modules+ cli = importlib.import_module(ql.__package__ + ".cli")+ monkeypatch.setattr(cli, "get_hermes_home", lambda: home)+ cli._run(Namespace(local_action="status"))+ assert "not configured" in capsys.readouterr().out+ assert not ql.managed_paths(home).root.exists()+++def test_changed_native_pins_reinstall_an_existing_runtime(modules, monkeypatch):+ home, _p, _m, ql, _life, packages = modules+ paths = ql.managed_paths(home)+ paths.root.mkdir()+ (paths.root / "runtime-requirements.json").write_text('["older-pins"]')+ monkeypatch.setattr(ql, "openviking_install_satisfies_requirement", lambda _paths: True)+ monkeypatch.setattr(ql, "_pm_available", lambda: False)+ monkeypatch.setattr(packages, "verified_requirements", lambda values, _cache: values)+ engine = ql.QuickLocalSetup(health_check=lambda _url: (False, ""))+ install = MagicMock()+ monkeypatch.setattr(engine, "_install_with_uv", install)+ assert engine._ensure_openviking_installed(paths)+ install.assert_called_once_with(paths, packages.install_requirements())+ assert not engine._ensure_openviking_installed(paths)+ assert install.call_count == 1+++def test_legacy_install_without_uv_fails_without_repairing_hermes(modules, monkeypatch):+ import hermes_constants+ from hermes_cli import managed_uv++ home, _p, _m, ql, _life, _packages = modules+ monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: home)+ monkeypatch.setattr(managed_uv, "resolve_uv", lambda: None)+ monkeypatch.setattr(ql.shutil, "which", lambda _name: None)+ repair = MagicMock(side_effect=SystemExit("must not rebuild Hermes"))+ monkeypatch.setattr(managed_uv, "ensure_uv", repair)+ engine = ql.QuickLocalSetup(health_check=lambda _url: (False, ""))+ with pytest.raises(ql.QuickLocalSetupError, match="needs uv"):+ engine._install_with_uv(ql.managed_paths(home), ["isolated-package"])+ repair.assert_not_called()+++def test_lost_record_adoption_survives_a_selected_runtime_upgrade(servers, modules, monkeypatch):+ import psutil++ _home, _p, _m, ql, _life, _packages = modules+ server = servers("old-runtime")+ ready(server)+ old_pid = server.status()["pid"]+ old_family = {old_pid, *(p.pid for p in psutil.Process(old_pid).children(recursive=True))}+ server.record_path.unlink()+ old_command = server.paths.server_command+ new_command = server.paths.runtime / "new-generation/bin/openviking-server"+ new_command.parent.mkdir(parents=True)+ new_command.write_bytes(old_command.read_bytes())+ monkeypatch.setattr(ql.QuickLocalPaths, "server_command", property(lambda _self: new_command))+ config = server._config()+ config["server"]["root_api_key"] = "rotated-test-key"+ server.configure(config, runtime_changed=True)+ assert server._read_record()["pid"] in old_family+ assert server._read_record()["command"] == str(old_command)+ ready(server)+ assert server.status()["pid"] not in old_family+ assert server._read_record()["command"] == str(new_command)+++def test_stop_from_another_process_accepts_a_terminated_child(servers, modules):+ """A CLI cannot reap a server whose parent is a running Hermes process."""+ import json+ from pathlib import Path++ _home, _p, module, _ql, _life, _packages = modules+ server = servers("external-stop")+ ready(server)+ script = f"""+import importlib.util,sys+from pathlib import Path+sys.path[:0] = {json.dumps(sys.path)}+spec=importlib.util.spec_from_file_location("external_stop_provider", {json.dumps(module.__file__)}, submodule_search_locations=[{json.dumps(str(Path(module.__file__).parent))}])+package=importlib.util.module_from_spec(spec);sys.modules[spec.name]=package;spec.loader.exec_module(package)+from external_stop_provider.local_server import LocalServer+assert LocalServer(Path({json.dumps(str(server.paths.root.parent))})).stop()+"""+ result = subprocess.run(+ [sys.executable, "-c", script], capture_output=True, text=True, timeout=30+ )+ assert result.returncode == 0, result.stderrdiff --git a/examples/hermes-plugin/tests/test_local_packages.py b/examples/hermes-plugin/tests/test_local_packages.pynew file mode 100644index 000000000..c8fb0da22--- /dev/null+++ b/examples/hermes-plugin/tests/test_local_packages.py@@ -0,0 +1,94 @@+"""Installer-independent verification of the reviewed native package bytes."""++import hashlib+import importlib+import os+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from urllib.parse import unquote, urlparse++import pytest+++def wheel_source():+ content = b"synthetic wheel contents"+ requests = []++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_GET(self):+ requests.append(self.path)+ self.send_response(200)+ self.end_headers()+ self.wfile.write(content)++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ yield f"http://127.0.0.1:{server.server_port}/probe-1-py3-none-any.whl", content, requests+ server.shutdown()+ thread.join()+ server.server_close()+++def test_wrong_native_hash_is_rejected_before_install(external_provider, tmp_path, wheel_source):+ _h, _p, module, _s = external_provider("hashes")+ packages = importlib.import_module(module.__name__ + ".local_packages")+ ql = importlib.import_module(module.__name__ + ".quick_local")+ url, _content, requests = wheel_source+ cache = tmp_path / "wheels"+ with pytest.raises(ql.QuickLocalSetupError, match="SHA-256"):+ packages.verified_requirements([f"probe @ {url}#sha256={'0' * 64}"], cache)+ assert requests == ["/probe-1-py3-none-any.whl"]+ assert not list(cache.rglob("*.whl"))+++def test_verified_native_cache_is_rechecked_and_reused(external_provider, tmp_path, wheel_source):+ from packaging.requirements import Requirement++ _h, _p, module, _s = external_provider("hashes")+ packages = importlib.import_module(module.__name__ + ".local_packages")+ url, content, requests = wheel_source+ digest = hashlib.sha256(content).hexdigest()+ requirements = [+ f"probe[extra] @ {url}#sha256={digest}",+ 'litellm==1.83.7; python_version >= "3.14"',+ ]+ cached = packages.verified_requirements(requirements, tmp_path / "wheels")+ parsed = Requirement(cached[0])+ assert parsed.extras == {"extra"}+ local = urlparse(parsed.url)+ assert local.scheme == "file"+ wheel = Path(unquote(local.path).lstrip("/") if os.name == "nt" else unquote(local.path))+ assert wheel.read_bytes() == content and cached[1] == requirements[1]+ assert packages.verified_requirements(requirements, tmp_path / "wheels") == cached+ assert len(requests) == 1+ wheel.write_bytes(b"corrupt cache")+ assert packages.verified_requirements(requirements, tmp_path / "wheels") == cached+ assert wheel.read_bytes() == content and len(requests) == 2+++def test_bad_hash_never_reaches_pm(external_provider, tmp_path, wheel_source, monkeypatch):+ from unittest.mock import MagicMock++ pm = pytest.importorskip("pm.client")+ home, _p, module, _s = external_provider("hashes")+ packages = importlib.import_module(module.__name__ + ".local_packages")+ ql = importlib.import_module(module.__name__ + ".quick_local")+ url, _content, _requests = wheel_source+ monkeypatch.setattr(ql, "_pm_available", lambda: True)+ monkeypatch.setattr(ql, "openviking_install_satisfies_requirement", lambda _paths: False)+ monkeypatch.setattr(+ packages, "install_requirements", lambda **_kw: [f"probe @ {url}#sha256={'0' * 64}"]+ )+ install = MagicMock()+ monkeypatch.setattr(pm, "ensure_python_tool", install)+ engine = ql.QuickLocalSetup(health_check=lambda _url: (False, ""))+ with pytest.raises(ql.QuickLocalSetupError, match="SHA-256"):+ engine._ensure_openviking_installed(ql.managed_paths(home))+ install.assert_not_called()+ assert not (ql.managed_paths(home).root / "runtime-requirements.json").exists()diff --git a/examples/hermes-plugin/tests/test_quick_local.py b/examples/hermes-plugin/tests/test_quick_local.pynew file mode 100644index 000000000..c15dd2b5e--- /dev/null+++ b/examples/hermes-plugin/tests/test_quick_local.py@@ -0,0 +1,1271 @@+"""Quick Local contracts, ported from Hermes #94851 through the external loader."""++from __future__ import annotations++import importlib+import json+import os+import stat+import subprocess+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import httpx+import pytest++[email protected](autouse=True)+def plugin_modules(external_provider, monkeypatch):+ global quick_local, setup_flow, openviking_module, OpenVikingMemoryProvider+ _home, provider, openviking_module, _settings = external_provider("quick-local")+ OpenVikingMemoryProvider = type(provider)+ quick_local = importlib.import_module(openviking_module.__name__ + ".quick_local")+ setup_flow = importlib.import_module(openviking_module.__name__ + "._setup")+ monkeypatch.setattr(quick_local.secrets, "token_urlsafe", lambda _size: "local-test-key")+ monkeypatch.setattr(quick_local, "_validate_local_embedding", MagicMock())+ monkeypatch.setattr(quick_local, "_validate_vlm", MagicMock())+++def _preflight(tmp_path: Path) -> quick_local.QuickLocalPreflight:+ return quick_local.QuickLocalPreflight(+ paths=quick_local.managed_paths(tmp_path),+ reusable_endpoint=None,+ )+++def test_build_server_config_uses_profile_scoped_storage_and_local_embedding(+ tmp_path,+):+ paths = quick_local.managed_paths(tmp_path)++ config = quick_local.build_server_config(+ paths,+ {+ "provider": "openai",+ "model": "model-1",+ "api_key": "secret",+ "api_base": "https://llm.example/v1",+ },+ port=1941,+ )++ assert config == {+ "server": {+ "host": "127.0.0.1",+ "port": 1941,+ "auth_mode": "trusted",+ "root_api_key": "local-test-key",+ },+ "storage": {"workspace": str(tmp_path / "openviking" / "data")},+ "embedding": {+ "dense": {+ "provider": "local",+ "model": "bge-small-zh-v1.5-f16",+ "dimension": 512,+ "cache_dir": str(tmp_path / "openviking" / "models"),+ }+ },+ "vlm": {+ "provider": "openai",+ "model": "model-1",+ "api_key": "secret",+ "api_base": "https://llm.example/v1",+ },+ }+++def test_resolve_vlm_uses_one_persisted_hermes_model_source(monkeypatch):+ from hermes_cli import config as config_module+ from hermes_cli import runtime_provider++ monkeypatch.setattr(+ config_module,+ "load_config",+ lambda: {"model": {"provider": "custom:test", "default": "saved-model"}},+ )+ resolver = MagicMock(+ return_value={+ "provider": "custom",+ "api_mode": "chat_completions",+ "base_url": "https://llm.example/v1",+ "api_key": "secret",+ "source": "custom_provider:test",+ "extra_headers": {"X-Tenant": "tenant"},+ "request_overrides": {"extra_body": {"thinking": {"type": "disabled"}}},+ }+ )+ monkeypatch.setattr(runtime_provider, "resolve_runtime_provider", resolver)++ vlm = quick_local.resolve_hermes_vlm_config()++ resolver.assert_called_once_with(+ requested="custom:test",+ target_model="saved-model",+ )+ assert vlm == {+ "provider": "openai",+ "model": "saved-model",+ "api_key": "secret",+ "api_base": "https://llm.example/v1",+ "extra_headers": {"X-Tenant": "tenant"},+ "extra_request_body": {"thinking": {"type": "disabled"}},+ "temperature": 0.0,+ "max_retries": 2,+ }+++def test_resolve_vlm_maps_anthropic_transport(monkeypatch):+ from hermes_cli import config as config_module+ from hermes_cli import runtime_provider++ monkeypatch.setattr(+ config_module,+ "load_config",+ lambda: {"model": {"provider": "anthropic", "default": "claude-sonnet"}},+ )+ monkeypatch.setattr(+ runtime_provider,+ "resolve_runtime_provider",+ lambda **_kwargs: {+ "provider": "anthropic",+ "api_mode": "anthropic_messages",+ "base_url": "https://api.anthropic.com",+ "api_key": "secret",+ "source": "env",+ "model": "claude-sonnet",+ },+ )++ vlm = quick_local.resolve_hermes_vlm_config()++ assert vlm["provider"] == "litellm"+ assert vlm["model"] == "anthropic/claude-sonnet"+ assert vlm["api_base"] == "https://api.anthropic.com"++[email protected]("suffix", ["/anthropic", "/anthropic/v1", "/anthropic/v1/"])+def test_resolve_vlm_normalizes_only_anthropic_version_suffix(monkeypatch, suffix):+ from hermes_cli import config, runtime_provider++ monkeypatch.setattr(config, "load_config", lambda: {+ "model": {"provider": "custom:gateway", "default": "claude-test"}+ })+ runtime = {+ "provider": "custom", "api_mode": "anthropic_messages",+ "base_url": "https://gateway.example" + suffix,+ "api_key": "static-proxy-key", "source": "custom_provider:gateway",+ }+ monkeypatch.setattr(runtime_provider, "resolve_runtime_provider", lambda **_: runtime)+ assert quick_local.resolve_hermes_vlm_config()["api_base"] == "https://gateway.example/anthropic"+ runtime["api_mode"] = "chat_completions"+ assert quick_local.resolve_hermes_vlm_config()["api_base"] == runtime["base_url"]++[email protected]("credential", ["eyJ-test-only", "cc-test-only", "sk-ant-oat01-test", "sk-ant-setup-test"])[email protected]("declared", [False, True])+def test_real_resolver_rejects_native_anthropic_oauth_before_declared_key(+ external_provider, credential, declared+):+ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ home, _, _, _ = external_provider("oauth-source")+ model = {"provider": "anthropic", "default": "claude-test"}+ if declared:+ model["key_env"] = "ANTHROPIC_TOKEN"+ (home / "config.yaml").write_text(json.dumps({"model": model}))+ (home / ".env").write_text("ANTHROPIC_TOKEN=" + credential + "\n")+ home_token = set_hermes_home_override(home)+ secret_token = set_secret_scope(build_profile_secret_scope(home), profile_home=str(home))+ try:+ with pytest.raises(quick_local.QuickLocalSetupError, match="cannot be copied safely"):+ quick_local.resolve_hermes_vlm_config()+ finally:+ reset_secret_scope(secret_token)+ reset_hermes_home_override(home_token)++[email protected]("base", ["https://api.anthropic.com/v1", "https://proxy.example/anthropic/v1"])[email protected]("credential", ["eyJ-test-only", "cc-test-only", "sk-ant-api03-static-test"])+def test_anthropic_credentials_follow_route_identity_before_declared_key(monkeypatch, base, credential):+ from hermes_cli import config, runtime_provider++ monkeypatch.setattr(config, "load_config", lambda: {+ "model": {"provider": "custom:proxy", "default": "claude-test", "key_env": "PROXY_KEY"}+ })+ monkeypatch.setattr(runtime_provider, "resolve_runtime_provider", lambda **_: {+ "provider": "custom", "api_mode": "anthropic_messages", "base_url": base,+ "api_key": credential, "source": "env:PROXY_KEY",+ })+ if "api.anthropic.com" in base and not credential.startswith("sk-ant-api"):+ with pytest.raises(quick_local.QuickLocalSetupError, match="cannot be copied safely"):+ quick_local.resolve_hermes_vlm_config()+ else:+ assert quick_local.resolve_hermes_vlm_config()["api_key"] == credential+++def test_resolve_vlm_accepts_declared_model_key_env(monkeypatch):+ from hermes_cli import auth, config, runtime_provider+ saved = {"model": {"provider": "lmstudio", "default": "local-model", "key_env": "TEST_LLM_KEY"}}+ monkeypatch.setattr(config, "load_config", lambda: saved)+ monkeypatch.setattr(config, "get_env_value_prefer_dotenv", lambda name: "static-test-key" if name == "TEST_LLM_KEY" else "")+ key, source = auth._resolve_api_key_provider_secret("lmstudio", auth.PROVIDER_REGISTRY["lmstudio"])+ monkeypatch.setattr(runtime_provider, "resolve_runtime_provider", lambda **_kwargs: {+ "provider": "lmstudio", "source": source, "api_key": key,+ "base_url": "http://127.0.0.1:1234/v1", "api_mode": "chat_completions"})+ assert quick_local.resolve_hermes_vlm_config()["api_key"] == "static-test-key"++[email protected]("key", ["", "local-static-key"])+def test_resolve_vlm_accepts_hermes_local_runtime(monkeypatch, key):+ from hermes_cli import config, runtime_provider, runtime_provider_custom+ endpoint = pytest.importorskip("hermes_cli.local_runtime.endpoint")+ monkeypatch.setattr(config, "load_config", lambda: {"model": {"default": "local-model", "provider": "llamacpp"}})+ monkeypatch.setattr(endpoint, "resolve_llamacpp_endpoint", lambda **_kwargs: {+ "base_url": "http://127.0.0.1:8090/v1", "api_key": key})+ runtime = runtime_provider_custom._resolve_llamacpp_runtime("llamacpp", None)+ monkeypatch.setattr(runtime_provider, "resolve_runtime_provider", lambda **_kwargs: runtime)+ assert quick_local.resolve_hermes_vlm_config()["api_key"] == (key or "no-key-required")+++def test_resolve_vlm_accepts_structured_persisted_default(monkeypatch):+ from hermes_cli import config as config_module+ from hermes_cli import runtime_provider++ monkeypatch.setattr(+ config_module,+ "load_config",+ lambda: {"model": {"default": {"provider": "custom:corp", "model": "corp-model"}}},+ )+ resolver = MagicMock(+ return_value={+ "provider": "custom",+ "api_mode": "chat_completions",+ "base_url": "https://llm.example/v1",+ "api_key": "secret",+ "source": "custom_provider:corp",+ }+ )+ monkeypatch.setattr(runtime_provider, "resolve_runtime_provider", resolver)++ vlm = quick_local.resolve_hermes_vlm_config()++ resolver.assert_called_once_with(+ requested="custom:corp",+ target_model="corp-model",+ )+ assert vlm["model"] == "corp-model"+++ ("runtime", "message"),+ [+ (+ {+ "provider": "openai-codex",+ "api_mode": "codex_responses",+ "base_url": "https://chatgpt.com/backend-api/codex",+ "api_key": "short-lived",+ "source": "oauth",+ },+ "cannot be copied safely",+ ),+ (+ {+ "provider": "anthropic",+ "api_mode": "anthropic_messages",+ "base_url": "https://api.anthropic.com",+ "api_key": "sk-ant-oat01-short-lived",+ "source": "env",+ },+ "cannot be copied safely",+ ),+ (+ {+ "provider": "custom",+ "api_mode": "chat_completions",+ "base_url": "https://llm.example/v1",+ "api_key": lambda: pytest.fail("Setup must not execute key commands"),+ "source": "key_cmd",+ },+ "cannot be copied safely",+ ),+ (+ {+ "provider": "copilot",+ "api_mode": "chat_completions",+ "base_url": "https://api.githubcopilot.com",+ "api_key": "short-lived-exchanged-token",+ "source": "GH_TOKEN",+ },+ "cannot be copied safely",+ ),+ (+ {+ "provider": "future-oauth-provider",+ "api_mode": "chat_completions",+ "base_url": "https://llm.example/v1",+ "api_key": "short-lived",+ "source": "future-credential-store",+ },+ "cannot be copied safely",+ ),+ (+ {+ "provider": "openai-api",+ "api_mode": "codex_responses",+ "base_url": "https://responses-only.example/v1",+ "api_key": "secret",+ "source": "OPENAI_API_KEY",+ },+ "transport is not supported",+ ),+ (+ {+ "provider": "custom",+ "api_mode": "chat_completions",+ "base_url": "https://llm.example/v1",+ "api_key": False,+ "source": "env/config",+ },+ "cannot be copied safely",+ ),+ (+ {+ "provider": "custom",+ "api_mode": "chat_completions",+ "base_url": {"url": "https://llm.example/v1"},+ "api_key": "secret",+ "source": "env/config",+ },+ "API base URL must be a string",+ ),+ (+ {+ "provider": "custom",+ "api_mode": "chat_completions",+ "base_url": False,+ "api_key": "secret",+ "source": "env/config",+ },+ "API base URL must be a string",+ ),+ ],+)+def test_resolve_vlm_rejects_credentials_or_transports_openviking_cannot_reuse(+ runtime,+ message,+ monkeypatch,+):+ from hermes_cli import config as config_module+ from hermes_cli import runtime_provider++ monkeypatch.setattr(+ config_module,+ "load_config",+ lambda: {"model": {"provider": "openai", "default": "model-1"}},+ )+ monkeypatch.setattr(+ runtime_provider,+ "resolve_runtime_provider",+ lambda **_kwargs: runtime,+ )++ with pytest.raises(quick_local.QuickLocalSetupError, match=message):+ quick_local.resolve_hermes_vlm_config()+++ ("field", "message"),+ [+ ("api_key", "did not resolve reusable static credentials"),+ ("base_url", "did not resolve an API base URL"),+ ],+)[email protected]("missing_value", [None, "", " \t "])+def test_resolve_vlm_reports_missing_fields_before_classifying_credentials(+ field, message, missing_value, monkeypatch+):+ from hermes_cli import config as config_module+ from hermes_cli import runtime_provider++ monkeypatch.setattr(+ config_module,+ "load_config",+ lambda: {"model": {"provider": "custom", "default": "model-1"}},+ )+ runtime = {+ "provider": "custom",+ "api_mode": "chat_completions",+ "base_url": "https://llm.example/v1",+ "api_key": "secret",+ "source": "env/config",+ field: missing_value,+ }+ monkeypatch.setattr(runtime_provider, "resolve_runtime_provider", lambda **_kwargs: runtime)+ classify = MagicMock(wraps=quick_local._has_copyable_static_credentials)+ monkeypatch.setattr(quick_local, "_has_copyable_static_credentials", classify)++ with pytest.raises(quick_local.QuickLocalSetupError, match=message):+ quick_local.resolve_hermes_vlm_config()++ classify.assert_not_called()+++def test_existing_openviking_without_local_embedding_runtime_is_not_reused(+ tmp_path,+ monkeypatch,+):+ paths = quick_local.managed_paths(tmp_path)+ paths.runtime_python.parent.mkdir(parents=True)+ paths.runtime_python.touch()+ paths.server_command.touch()+ run = MagicMock(+ return_value=SimpleNamespace(+ returncode=1,+ stdout="",+ stderr="ModuleNotFoundError: No module named 'llama_cpp'",+ )+ )+ monkeypatch.setattr(quick_local.subprocess, "run", run)++ assert quick_local.openviking_install_satisfies_requirement(paths) is False+ assert "import llama_cpp" in run.call_args.args[0][2]+++def test_existing_openviking_with_local_embedding_runtime_is_reused(+ tmp_path,+ monkeypatch,+):+ paths = quick_local.managed_paths(tmp_path)+ paths.runtime_python.parent.mkdir(parents=True)+ paths.runtime_python.touch()+ paths.server_command.touch()+ monkeypatch.setattr(+ quick_local.subprocess,+ "run",+ lambda *_args, **_kwargs: SimpleNamespace(+ returncode=0,+ stdout="0.4.22\n",+ stderr="",+ ),+ )++ assert quick_local.openviking_install_satisfies_requirement(paths) is True+++def test_validation_server_does_not_inherit_stdin(tmp_path, monkeypatch):+ server_command = tmp_path / "openviking-server"+ server_command.write_text("", encoding="utf-8")+ config_path = tmp_path / "ov.conf"+ config_path.write_text("{}", encoding="utf-8")+ process = MagicMock()+ popen = MagicMock(return_value=process)+ monkeypatch.setattr(quick_local.subprocess, "Popen", popen)+ monkeypatch.setattr(quick_local, "_can_bind_local_port", lambda *_args: True)++ result = quick_local._start_validation_server(+ "http://127.0.0.1:1933",+ config_path,+ tmp_path,+ server_command,+ )++ assert result is process+ assert popen.call_args.kwargs["stdin"] is subprocess.DEVNULL+++def test_validation_server_rechecks_selected_port_before_start(tmp_path, monkeypatch):+ server_command = tmp_path / "openviking-server"+ server_command.write_text("", encoding="utf-8")+ config_path = tmp_path / "ov.conf"+ config_path.write_text("{}", encoding="utf-8")+ popen = MagicMock()+ monkeypatch.setattr(quick_local.subprocess, "Popen", popen)+ monkeypatch.setattr(quick_local, "_can_bind_local_port", lambda *_args: False)++ with pytest.raises(quick_local.QuickLocalSetupError, match="became unavailable"):+ quick_local._start_validation_server(+ "http://127.0.0.1:1933",+ config_path,+ tmp_path,+ server_command,+ )++ popen.assert_not_called()+++def test_reuse_rechecks_runtime_and_refreshes_saved_vlm(tmp_path, monkeypatch):+ monkeypatch.setattr(quick_local, "server_belongs_to_profile", lambda *_args: True)+ lifecycle = importlib.import_module(quick_local.__package__ + ".local_server")+ monkeypatch.setattr(lifecycle.LocalServer, "_verified_process", lambda *_args: object())+ paths = quick_local.managed_paths(tmp_path)+ paths.root.mkdir(parents=True)+ old_vlm = {+ "provider": "openai",+ "model": "old-model",+ "api_key": "old-secret",+ "api_base": "https://old.example/v1",+ }+ quick_local.atomic_json_write(+ paths.server_config,+ quick_local.build_server_config(paths, old_vlm, port=1938),+ mode=0o600,+ )+ quick_local._write_ovcli_profile(+ paths.ovcli_config, "http://127.0.0.1:1938", json.loads(paths.server_config.read_text())+ )+ new_vlm = {+ "provider": "openai",+ "model": "new-model",+ "api_key": "new-secret",+ "api_base": "https://new.example/v1",+ }+ resolve = MagicMock(return_value=new_vlm)+ monkeypatch.setattr(quick_local, "resolve_hermes_vlm_config", resolve)+ setup = quick_local.QuickLocalSetup(+ health_check=lambda _endpoint: (True, ""),+ )+ ensure_runtime = MagicMock(return_value=False)+ monkeypatch.setattr(setup, "_ensure_openviking_installed", ensure_runtime)+ monkeypatch.setattr(quick_local, "find_available_port", lambda **_kwargs: 1940)+ validate = MagicMock()+ monkeypatch.setattr(setup, "_validate_generated_config", validate)++ def restart(paths, endpoint):+ quick_local.clear_server_restart_required(paths.server_config)+ return endpoint++ restart = MagicMock(side_effect=restart)+ monkeypatch.setattr(setup, "_start_managed_server", restart)++ result = setup.provision(hermes_home=tmp_path)++ assert result.reused is True+ assert result.endpoint == "http://127.0.0.1:1938"+ assert result.server_restart_required is False+ validate.assert_called_once()+ restart.assert_called_once_with(paths, "http://127.0.0.1:1938")+ assert json.loads(paths.server_config.read_text(encoding="utf-8")) == (+ quick_local.build_server_config(paths, new_vlm, port=1938)+ )+ resolve.assert_called_once_with()+ ensure_runtime.assert_called_once_with(paths)+++def test_failed_restart_is_retried_on_next_setup(tmp_path, monkeypatch):+ monkeypatch.setattr(quick_local, "find_available_port", lambda **_kwargs: 1940)+ monkeypatch.setattr(quick_local, "server_belongs_to_profile", lambda *_args: True)+ lifecycle = importlib.import_module(quick_local.__package__ + ".local_server")+ monkeypatch.setattr(lifecycle.LocalServer, "_verified_process", lambda *_args: object())+ paths = quick_local.managed_paths(tmp_path)+ paths.root.mkdir(parents=True)+ old_vlm = {+ "provider": "openai",+ "model": "old-model",+ "api_key": "old-secret",+ "api_base": "https://llm.example/v1",+ }+ new_vlm = {**old_vlm, "api_key": "new-secret"}+ quick_local.atomic_json_write(+ paths.server_config,+ quick_local.build_server_config(paths, old_vlm, port=1938),+ mode=0o600,+ )+ quick_local._write_ovcli_profile(+ paths.ovcli_config, "http://127.0.0.1:1938", json.loads(paths.server_config.read_text())+ )+ monkeypatch.setattr(quick_local, "resolve_hermes_vlm_config", lambda: new_vlm)++ def provision_again():+ setup = quick_local.QuickLocalSetup(health_check=lambda _endpoint: (True, ""))+ monkeypatch.setattr(setup, "_ensure_openviking_installed", lambda _paths: False)+ monkeypatch.setattr(setup, "_validate_generated_config", lambda **_kwargs: None)+ monkeypatch.setattr(+ setup,+ "_start_managed_server",+ MagicMock(side_effect=quick_local.QuickLocalSetupError("restart failed")),+ )+ return setup.provision(hermes_home=tmp_path)++ with pytest.raises(quick_local.QuickLocalSetupError, match="restart failed"):+ provision_again()+ with pytest.raises(quick_local.QuickLocalSetupError, match="restart failed"):+ provision_again()+ assert paths.restart_required_marker.is_file()+++def test_fresh_provision_validates_before_writing_active_config(tmp_path, monkeypatch):+ events = []+ validation_configs = []+ process = MagicMock()+ setup = quick_local.QuickLocalSetup(+ health_check=lambda _endpoint: (True, ""),+ progress=lambda event: events.append(event.stage),+ )+ monkeypatch.setattr(+ quick_local,+ "resolve_hermes_vlm_config",+ lambda: {+ "provider": "openai",+ "model": "model-1",+ "api_key": "secret",+ "api_base": "https://llm.example/v1",+ },+ )++ def mark_ready(paths, endpoint):+ assert paths.restart_required_marker.is_file()+ quick_local.clear_server_restart_required(paths.server_config)+ return endpoint++ ready = MagicMock(side_effect=mark_ready)+ monkeypatch.setattr(setup, "_start_managed_server", ready)+ monkeypatch.setattr(setup, "_ensure_openviking_installed", lambda _paths: True)+ monkeypatch.setattr(quick_local, "find_available_port", lambda **_kwargs: 1937)+ paths = quick_local.managed_paths(tmp_path)+ paths.root.mkdir(parents=True)+ lifecycle = importlib.import_module(quick_local.__package__ + ".local_server")+ write_profile = quick_local._write_ovcli_profile++ def write_under_lock(*args):+ with pytest.raises(quick_local.QuickLocalSetupError, match="busy"):+ with lifecycle.LocalServer(tmp_path).locked(timeout=0):+ pass+ return write_profile(*args)++ monkeypatch.setattr(quick_local, "_write_ovcli_profile", write_under_lock)+ quick_local.atomic_json_write(+ paths.restart_required_marker,+ {"restart_required": True},+ mode=0o600,+ )++ def start(endpoint, config_path, hermes_home, server_command):+ assert endpoint == "http://127.0.0.1:1937"+ assert hermes_home == tmp_path+ assert server_command == paths.server_command+ assert not paths.server_config.exists()+ assert not paths.ovcli_config.exists()+ validation_configs.append(json.loads(config_path.read_text(encoding="utf-8")))+ return process++ monkeypatch.setattr(quick_local, "_start_validation_server", start)+ monkeypatch.setattr(quick_local, "_wait_for_health", lambda *args, **kwargs: True)+ monkeypatch.setattr(quick_local, "_validate_tenant_access", lambda *_args: None)+ stop = MagicMock(return_value=True)+ monkeypatch.setattr(quick_local, "_stop_process", stop)++ result = setup.provision(+ hermes_home=tmp_path,+ preflight=_preflight(tmp_path),+ )++ paths = result.paths+ assert result.endpoint == "http://127.0.0.1:1937"+ assert result.reused is False+ ready.assert_called_once_with(paths, "http://127.0.0.1:1937")+ assert result.server_restart_required is False+ assert not paths.restart_required_marker.exists()+ final_config = json.loads(paths.server_config.read_text(encoding="utf-8"))+ assert final_config["storage"]["workspace"] == str(paths.workspace)+ assert final_config["server"]["port"] == 1937+ assert final_config["embedding"]["dense"]["cache_dir"] == str(paths.model_cache)+ assert validation_configs[0]["storage"]["workspace"] != str(paths.workspace)+ assert validation_configs[0]["embedding"]["dense"]["cache_dir"] == str(paths.model_cache)+ assert json.loads(paths.ovcli_config.read_text(encoding="utf-8")) == {+ "url": "http://127.0.0.1:1937",+ "actor_peer_id": "hermes",+ "root_api_key": "local-test-key",+ "account": "default",+ "user": "default",+ }+ if os.name != "nt":+ assert stat.S_IMODE(paths.root.stat().st_mode) == 0o700+ assert stat.S_IMODE(paths.model_cache.stat().st_mode) == 0o700+ assert stat.S_IMODE(paths.server_config.stat().st_mode) == 0o600+ assert stat.S_IMODE(paths.ovcli_config.stat().st_mode) == 0o600+ stop.assert_called_once_with(process)+ assert quick_local.QuickLocalStage.PREPARE_EMBEDDING in events+ assert quick_local.QuickLocalStage.VALIDATE in events+ assert events[-2:] == [+ quick_local.QuickLocalStage.WRITE_CONFIG,+ quick_local.QuickLocalStage.COMPLETE,+ ]+++def test_fresh_provision_failed_start_keeps_restart_marker(tmp_path, monkeypatch):+ setup = quick_local.QuickLocalSetup(health_check=lambda _endpoint: (False, ""))+ monkeypatch.setattr(quick_local, "resolve_hermes_vlm_config", lambda: {"model": "test"})+ monkeypatch.setattr(quick_local, "find_available_port", lambda **_kwargs: 1937)+ monkeypatch.setattr(setup, "_ensure_openviking_installed", lambda _paths: True)+ monkeypatch.setattr(setup, "_validate_generated_config", lambda **_kwargs: None)+ monkeypatch.setattr(+ setup,+ "_start_managed_server",+ MagicMock(side_effect=quick_local.QuickLocalSetupError("startup failed")),+ )+ with pytest.raises(quick_local.QuickLocalSetupError, match="startup failed"):+ setup.provision(hermes_home=tmp_path, preflight=_preflight(tmp_path))+ paths = quick_local.managed_paths(tmp_path)+ assert paths.restart_required_marker.is_file()+ assert quick_local.connection_config({}, tmp_path)["url"] == "http://127.0.0.1:1937"+++def test_failed_validation_stops_child_and_leaves_profile_inactive(tmp_path, monkeypatch):+ process = MagicMock()+ process.poll.return_value = None+ setup = quick_local.QuickLocalSetup(health_check=lambda _endpoint: (False, "down"))+ monkeypatch.setattr(+ quick_local,+ "resolve_hermes_vlm_config",+ lambda: {+ "provider": "openai",+ "model": "model-1",+ "api_key": "secret",+ "api_base": "https://llm.example/v1",+ },+ )+ monkeypatch.setattr(setup, "_ensure_openviking_installed", lambda _paths: True)+ monkeypatch.setattr(quick_local, "find_available_port", lambda **_kwargs: 1933)+ monkeypatch.setattr(+ quick_local,+ "_start_validation_server",+ lambda *args, **kwargs: process,+ )+ monkeypatch.setattr(quick_local, "_wait_for_health", lambda *args, **kwargs: False)+ stop = MagicMock(return_value=True)+ monkeypatch.setattr(quick_local, "_stop_process", stop)++ with pytest.raises(quick_local.QuickLocalSetupError, match="did not become reachable"):+ setup.provision(+ hermes_home=tmp_path,+ preflight=_preflight(tmp_path),+ )++ paths = quick_local.managed_paths(tmp_path)+ assert not paths.server_config.exists()+ assert not paths.ovcli_config.exists()+ stop.assert_called_once_with(process)+++def test_validation_preserves_primary_error_when_cleanup_also_fails(tmp_path, monkeypatch):+ paths = quick_local.managed_paths(tmp_path)+ paths.root.mkdir(parents=True)+ process = MagicMock()+ process.poll.return_value = None+ setup = quick_local.QuickLocalSetup(health_check=lambda _endpoint: (False, "down"))+ monkeypatch.setattr(+ quick_local,+ "_start_validation_server",+ lambda *_args, **_kwargs: process,+ )+ monkeypatch.setattr(quick_local, "_wait_for_health", lambda *args, **kwargs: False)+ monkeypatch.setattr(quick_local, "_stop_process", lambda _process: False)++ with pytest.raises(+ quick_local.QuickLocalSetupError,+ match="did not become reachable",+ ) as exc_info:+ setup._validate_generated_config(+ paths=paths,+ endpoint="http://127.0.0.1:1933",+ server_config=quick_local.build_server_config(+ paths,+ {+ "provider": "openai",+ "model": "model-1",+ "api_key": "secret",+ "api_base": "https://llm.example/v1",+ },+ ),+ )++ assert any("could not be stopped" in note for note in getattr(exc_info.value, "__notes__", []))+++def test_preflight_reuses_only_healthy_profile_with_managed_workspace(tmp_path, monkeypatch):+ monkeypatch.setattr(quick_local, "server_belongs_to_profile", lambda *_args: True)+ paths = quick_local.managed_paths(tmp_path)+ paths.root.mkdir(parents=True)+ quick_local.atomic_json_write(+ paths.server_config,+ {"storage": {"workspace": str(paths.workspace)}},+ mode=0o600,+ )+ quick_local.atomic_json_write(+ paths.ovcli_config,+ {"url": "http://127.0.0.1:1938", "actor_peer_id": "hermes"},+ mode=0o600,+ )+ health = MagicMock(return_value=(True, ""))+ setup = quick_local.QuickLocalSetup(health_check=health)++ preflight = setup.preflight(tmp_path)++ assert preflight.reusable_endpoint == "http://127.0.0.1:1938"+ health.assert_called_once_with("http://127.0.0.1:1938")++ quick_local.atomic_json_write(+ paths.server_config,+ {"storage": {"workspace": str(tmp_path / "other-data")}},+ mode=0o600,+ )+ health.reset_mock()+ assert setup.preflight(tmp_path).reusable_endpoint is None+ health.assert_not_called()+++def test_preferred_configured_port_is_reused_when_available(monkeypatch):+ bound = []++ class FakeSocket:+ def settimeout(self, timeout):+ pass++ def connect_ex(self, address):+ return 1++ def setsockopt(self, *args):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def bind(self, address):+ bound.append(address)++ monkeypatch.setattr(quick_local.socket, "socket", lambda *args, **kwargs: FakeSocket())++ port = quick_local.find_available_port(+ preferred_endpoint="http://127.0.0.1:1940",+ )++ assert port == 1940+ assert bound == [("127.0.0.1", 1940)]+++def test_validation_stop_force_kills_only_after_graceful_timeout(monkeypatch):+ from itertools import count++ import psutil++ process = MagicMock()+ process.poll.return_value = None+ root, child = MagicMock(), MagicMock()+ root.children.return_value = [child]+ root.status.return_value = psutil.STATUS_RUNNING+ child.is_running.return_value = False+ root.is_running.return_value = True+ root.kill.side_effect = lambda: setattr(root.is_running, "return_value", False)+ monkeypatch.setattr(psutil, "Process", lambda _pid: root)+ lifecycle = importlib.import_module(quick_local.__package__ + ".local_server")+ clock = count(step=quick_local._PROCESS_STOP_TIMEOUT_SECONDS)+ monkeypatch.setattr(lifecycle.time, "monotonic", lambda: next(clock))++ assert quick_local._stop_process(process) is True++ root.terminate.assert_called_once_with()+ child.terminate.assert_called_once_with()+ root.kill.assert_called_once_with()+ child.kill.assert_not_called()+ process.wait.assert_called_once_with(timeout=quick_local._PROCESS_STOP_TIMEOUT_SECONDS)+++def test_health_wait_budget_covers_openviking_model_download():+ assert quick_local._HEALTH_TIMEOUT_SECONDS > quick_local._MODEL_PREPARATION_TIMEOUT_SECONDS+++def test_health_wait_stops_as_soon_as_validation_process_exits():+ process = MagicMock()+ process.poll.return_value = 1+ health = MagicMock(return_value=(False, "down"))++ assert (+ quick_local._wait_for_health(+ "http://127.0.0.1:1933",+ health,+ process=process,+ timeout_seconds=60,+ )+ is False+ )++ health.assert_called_once_with("http://127.0.0.1:1933")+++def _saved_local(home, *, port=1938):+ paths = quick_local.managed_paths(home)+ paths.root.mkdir(parents=True, exist_ok=True)+ config = quick_local.build_server_config(+ paths,+ {+ "provider": "openai",+ "model": "test-model",+ "api_key": "vlm-key",+ "api_base": "https://llm.example/v1",+ },+ port=port,+ )+ quick_local.atomic_json_write(paths.server_config, config, mode=0o600)+ quick_local._write_ovcli_profile(paths.ovcli_config, f"http://127.0.0.1:{port}", config)+ return paths, config+++ "mode,code,accepted", [("trusted", 200, True), ("trusted", 403, False), ("dev", 200, False)]+)+def test_reuse_authenticates_profile_key(tmp_path, monkeypatch, mode, code, accepted):+ paths, _cfg = _saved_local(tmp_path)+ requests = []++ def respond(request):+ requests.append(request)+ if request.url.path == "/health":+ assert "X-API-Key" not in request.headers+ return httpx.Response(+ 200, json={"status": "ok", "auth_mode": mode, "root_api_key_required": True}+ )+ assert request.url.path == "/api/v1/admin/accounts"+ assert request.headers["X-API-Key"] == "local-test-key"+ return httpx.Response(code, json={"status": "ok" if code == 200 else "error"})++ client = httpx.Client+ monkeypatch.setattr(+ httpx, "Client", lambda **kwargs: client(transport=httpx.MockTransport(respond), **kwargs)+ )+ assert quick_local.server_belongs_to_profile(paths, "http://127.0.0.1:1938") is accepted+ assert len(requests) == (1 if mode == "dev" else 2)+++def test_wrong_listener_is_not_reused(tmp_path, monkeypatch):+ paths, _cfg = _saved_local(tmp_path)+ monkeypatch.setattr(quick_local, "server_belongs_to_profile", lambda *_args: False)+ assert quick_local.find_reusable_endpoint(paths, lambda _url: (True, "")) is None+++def test_current_installer_uses_pm_and_private_root(tmp_path, monkeypatch):+ pm = pytest.importorskip("pm.client")+ install = MagicMock()+ monkeypatch.setattr(pm, "ensure_python_tool", install)+ satisfies = MagicMock(side_effect=[False, True])+ monkeypatch.setattr(quick_local, "openviking_install_satisfies_requirement", satisfies)+ paths = quick_local.managed_paths(tmp_path)+ packages = importlib.import_module(quick_local.__package__ + ".local_packages")+ monkeypatch.setattr(+ packages, "verified_requirements", lambda requirements, _cache: requirements+ )+ engine = quick_local.QuickLocalSetup(health_check=lambda _url: (False, ""))+ assert engine._ensure_openviking_installed(paths)+ install.assert_called_once_with(+ "openviking-local",+ importlib.import_module(quick_local.__package__ + ".local_packages").install_requirements(),+ "openviking-server",+ root=paths.runtime,+ explicit=True,+ timeout=1800,+ )+++def test_pm_failure_does_not_activate_profile(tmp_path, monkeypatch):+ pm = pytest.importorskip("pm.client")+ monkeypatch.setattr(+ pm, "ensure_python_tool", MagicMock(side_effect=RuntimeError("install failed"))+ )+ monkeypatch.setattr(+ quick_local, "openviking_install_satisfies_requirement", lambda _paths: False+ )+ packages = importlib.import_module(quick_local.__package__ + ".local_packages")+ monkeypatch.setattr(+ packages, "verified_requirements", lambda requirements, _cache: requirements+ )+ engine = quick_local.QuickLocalSetup(health_check=lambda _url: (False, ""))+ with pytest.raises(quick_local.QuickLocalSetupError, match="private OpenViking runtime"):+ engine._ensure_openviking_installed(quick_local.managed_paths(tmp_path))+ assert not quick_local.managed_paths(tmp_path).ovcli_config.exists()+++def test_compatible_runtime_avoids_installer(tmp_path, monkeypatch):+ monkeypatch.setattr(+ quick_local, "openviking_install_satisfies_requirement", lambda _paths: True+ )+ run = MagicMock()+ monkeypatch.setattr(quick_local.subprocess, "run", run)+ packages = importlib.import_module(quick_local.__package__ + ".local_packages")+ paths = quick_local.managed_paths(tmp_path)+ paths.root.mkdir()+ (paths.root / "runtime-requirements.json").write_text(+ json.dumps(packages.install_requirements())+ )+ engine = quick_local.QuickLocalSetup(health_check=lambda _url: (False, ""))+ assert engine._ensure_openviking_installed(quick_local.managed_paths(tmp_path)) is False+ run.assert_not_called()+++def test_managed_connection_ignores_foreign_env_and_saved_paths(tmp_path, monkeypatch):+ paths, _cfg = _saved_local(tmp_path)+ monkeypatch.setattr(openviking_module, "get_hermes_home", lambda: tmp_path)+ settings = openviking_module._resolve_connection_settings(+ {"deployment": quick_local.DEPLOYMENT, "ovcli_config_path": "/foreign/ovcli.conf"},+ env={+ "OPENVIKING_ENDPOINT": "https://foreign.example",+ "OPENVIKING_API_KEY": "foreign-key",+ "OVCLI_CONFIG": "/foreign/ovcli.conf",+ },+ )+ assert settings == {+ "endpoint": "http://127.0.0.1:1938",+ "api_key": "local-test-key",+ "account": "default",+ "user": "default",+ "agent": "hermes",+ }+ assert (+ openviking_module._provider_ovcli_config_path({"deployment": quick_local.DEPLOYMENT})+ == paths.ovcli_config+ )+++def test_copied_profile_cannot_use_source_workspace(tmp_path):+ import shutil++ home_a, home_b = tmp_path / "a", tmp_path / "b"+ paths, _cfg = _saved_local(home_a)+ shutil.copytree(paths.root, home_b / "openviking")+ with pytest.raises(quick_local.QuickLocalSetupError, match="another profile"):+ quick_local.connection_config({"deployment": quick_local.DEPLOYMENT}, home_b)+++def test_managed_symlink_is_rejected(tmp_path):+ destination = tmp_path / "other-profile"+ destination.mkdir()+ (tmp_path / "openviking").symlink_to(destination, target_is_directory=True)+ with pytest.raises(quick_local.QuickLocalSetupError, match="belong to this Hermes profile"):+ quick_local.managed_paths(tmp_path)+++def test_backup_skips_managed_profile_but_keeps_external_file(tmp_path, monkeypatch):+ provider = OpenVikingMemoryProvider()+ provider._hermes_home = str(tmp_path)+ config = {"deployment": quick_local.DEPLOYMENT, "use_ovcli_config": True}+ monkeypatch.setattr(provider, "_profile_config_and_env", lambda: (config, {}))+ assert provider.backup_paths() == []+ linked = tmp_path.parent / "outside-ovcli.conf"+ config.clear()+ config.update(use_ovcli_config=True, ovcli_config_path=str(linked))+ assert provider.backup_paths() == [str(linked)]+++def test_running_managed_server_recovers_after_config_change(tmp_path, monkeypatch):+ paths, _cfg = _saved_local(tmp_path)+ quick_local._mark_server_restart_required(paths)+ provider = OpenVikingMemoryProvider()+ provider._hermes_home = str(tmp_path)+ monkeypatch.setattr(+ provider, "_profile_config_and_env", lambda: ({"deployment": quick_local.DEPLOYMENT}, {})+ )+ monkeypatch.setattr(openviking_module, "_local_openviking_port_is_open", lambda *_args: True)+ provider._env_refresh_enabled = True+ build = MagicMock()+ monkeypatch.setattr(provider, "_build_client", build)+ restart = MagicMock()+ monkeypatch.setattr(provider, "_handle_runtime_openviking_unreachable", restart)+ assert provider._ensure_client() is None+ restart.assert_called_once()+ build.assert_not_called()+ assert paths.restart_required_marker.exists()+++def test_quick_local_wizard_links_only_after_success(tmp_path, monkeypatch, capsys):+ paths, _cfg = _saved_local(tmp_path)+ result = quick_local.QuickLocalSetupResult(paths, "http://127.0.0.1:1938", True)+ engine = MagicMock()+ engine.provision.return_value = result+ monkeypatch.setattr(quick_local, "QuickLocalSetup", lambda **_kwargs: engine)+ config = {"memory": {}}+ provider_config = {"recall_scope": "peer"}+ assert setup_flow._run_quick_local_setup(+ config=config, provider_config=provider_config, env_path=tmp_path / ".env"+ )+ assert provider_config["deployment"] == quick_local.DEPLOYMENT+ assert provider_config["ovcli_config_path"] == str(paths.ovcli_config)+ assert "server_command_path" not in provider_config+ assert "OpenViking memory is ready" in capsys.readouterr().out+ engine.provision.side_effect = quick_local.QuickLocalSetupError("bad configuration")+ previous = dict(provider_config)+ assert (+ setup_flow._run_quick_local_setup(+ config=config, provider_config=provider_config, env_path=tmp_path / ".env"+ )+ is False+ )+ assert provider_config == previous+++def test_cloud_custom_menu_positions_are_unchanged(monkeypatch):+ seen = []++ def select(_title, options, **_kwargs):+ seen.extend(options)+ return -1++ result = setup_flow._run_create_profile_setup(+ prompt=MagicMock(),+ select=select,+ cancelled=-1,+ config={},+ provider_config={},+ env_path=Path("unused"),+ )+ assert result is setup_flow._SETUP_CANCELLED+ assert [option[0] for option in seen] == [+ "OpenViking Service (VolcEngine Cloud)",+ "Custom",+ "Quick Local",+ ]+++def test_switch_to_custom_clears_managed_marker(tmp_path):+ config = {"memory": {}}+ provider_config = {+ "deployment": quick_local.DEPLOYMENT,+ "server_config_path": "old",+ "server_command_path": "old",+ }+ setup_flow._save_hermes_only_config(+ config=config,+ provider_config=provider_config,+ env_path=tmp_path / ".env",+ values={"endpoint": "https://example.com", "api_key": "new-key"},+ )+ assert not any(+ key in provider_config+ for key in ("deployment", "server_config_path", "server_command_path")+ )+ assert provider_config["use_ovcli_config"] is False++[email protected]("status,accepted", [(200, True), (403, False)])+def test_validation_checks_tenant_write_access(monkeypatch, status, accepted):+ def post(url, **kwargs):+ assert url == "http://127.0.0.1:1938/api/v1/sessions"+ assert kwargs["headers"]["X-OpenViking-Account"] == "default"+ assert kwargs["headers"]["X-OpenViking-User"] == "default"+ assert kwargs["headers"]["X-API-Key"] == "local-test-key"+ assert kwargs["json"] == {} and kwargs["trust_env"] is False+ return httpx.Response(+ status,+ json={"status": "ok" if accepted else "error"},+ request=httpx.Request("POST", url),+ )++ monkeypatch.setattr(httpx, "post", post)+ if accepted:+ quick_local._validate_tenant_access("http://127.0.0.1:1938", "local-test-key")+ else:+ with pytest.raises(quick_local.QuickLocalSetupError, match="memory data access"):+ quick_local._validate_tenant_access("http://127.0.0.1:1938", "local-test-key")+++def test_failed_data_validation_does_not_activate_configuration(tmp_path, monkeypatch):+ engine = quick_local.QuickLocalSetup(health_check=lambda _url: (True, ""))+ monkeypatch.setattr(+ quick_local,+ "resolve_hermes_vlm_config",+ lambda: {+ "provider": "openai",+ "model": "test",+ "api_key": "key",+ "api_base": "https://llm.example/v1",+ },+ )+ monkeypatch.setattr(engine, "_ensure_openviking_installed", lambda _paths: False)+ monkeypatch.setattr(quick_local, "find_available_port", lambda **_kwargs: 1938)+ process = MagicMock()+ monkeypatch.setattr(quick_local, "_start_validation_server", lambda *_args: process)+ monkeypatch.setattr(quick_local, "_wait_for_health", lambda *_args, **_kwargs: True)+ monkeypatch.setattr(+ quick_local,+ "_validate_tenant_access",+ MagicMock(side_effect=quick_local.QuickLocalSetupError("memory data access denied")),+ )+ stop = MagicMock(return_value=True)+ monkeypatch.setattr(quick_local, "_stop_process", stop)+ with pytest.raises(quick_local.QuickLocalSetupError, match="memory data access"):+ engine.provision(hermes_home=tmp_path)+ paths = quick_local.managed_paths(tmp_path)+ assert not paths.server_config.exists() and not paths.ovcli_config.exists()+ stop.assert_called_once_with(process)++[email protected]("healthy", [True, False])+def test_managed_start_keeps_only_a_ready_process(tmp_path, monkeypatch, healthy):+ paths, _cfg = _saved_local(tmp_path)+ process = MagicMock()+ lifecycle = importlib.import_module(quick_local.__package__ + ".local_server")+ server = MagicMock()+ started = lifecycle.StartedServer("http://127.0.0.1:1938", process, False)+ server.start.return_value = started+ if healthy:+ server.wait_ready.return_value = started+ else:+ server.wait_ready.side_effect = quick_local.QuickLocalSetupError("did not become ready")+ monkeypatch.setattr(lifecycle, "LocalServer", lambda _home: server)+ engine = quick_local.QuickLocalSetup(health_check=lambda _url: (True, ""))+ if healthy:+ engine._start_managed_server(paths, "http://127.0.0.1:1938")+ else:+ with pytest.raises(quick_local.QuickLocalSetupError, match="did not become ready"):+ engine._start_managed_server(paths, "http://127.0.0.1:1938")+ server.wait_ready.assert_called_once_with(started, engine._health_check)+++def test_managed_initialize_preserves_cli_startup_callbacks(tmp_path, monkeypatch):+ provider = OpenVikingMemoryProvider()+ monkeypatch.setattr(+ provider, "_profile_config_and_env", lambda: ({"deployment": quick_local.DEPLOYMENT}, {})+ )+ monkeypatch.setattr(+ provider,+ "_resolve_bound_connection_settings",+ lambda *_args: {+ "endpoint": "http://127.0.0.1:1938",+ "api_key": "key",+ "account": "default",+ "user": "default",+ "agent": "hermes",+ },+ )+ ensure = MagicMock(return_value=None)+ monkeypatch.setattr(provider, "_ensure_client_locked", ensure)+ status, warning = MagicMock(), MagicMock()+ try:+ provider.initialize(+ "sid",+ hermes_home=str(tmp_path),+ platform="cli",+ status_callback=status,+ warning_callback=warning,+ )+ ensure.assert_called_once_with(status_callback=status, warning_callback=warning)+ finally:+ provider.shutdown()+++def test_managed_start_timeout_reports_its_actual_budget(tmp_path, monkeypatch):+ provider = OpenVikingMemoryProvider()+ provider._hermes_home = str(tmp_path)+ provider._endpoint = "http://127.0.0.1:1938"+ monkeypatch.setattr(+ provider, "_profile_config_and_env", lambda: ({"deployment": quick_local.DEPLOYMENT}, {})+ )+ wait = MagicMock(return_value=False)+ monkeypatch.setattr(openviking_module, "_wait_for_openviking_health", wait)+ warning = MagicMock()+ provider._finish_runtime_openviking_start(warning_callback=warning)+ assert wait.call_args.kwargs["timeout_seconds"] == quick_local._HEALTH_TIMEOUT_SECONDS+ assert f"{quick_local._HEALTH_TIMEOUT_SECONDS:.0f} seconds" in warning.call_args.args[0]diff --git a/examples/hermes-plugin/tests/test_quick_local_preflight.py b/examples/hermes-plugin/tests/test_quick_local_preflight.pynew file mode 100644index 000000000..0543e06a4--- /dev/null+++ b/examples/hermes-plugin/tests/test_quick_local_preflight.py@@ -0,0 +1,129 @@+"""LLM preflight retries and diagnostics through the external package."""++import contextlib+import importlib+import io+import json+import os+import subprocess+import sys+import types+from unittest.mock import MagicMock++import httpx+import pytest+++def ql(external_provider):+ _home, _provider, module, _settings = external_provider("preflight")+ return importlib.import_module(module.__name__ + ".quick_local")++[email protected]("status,retries", [(401, False), (404, False), (429, True), (500, True)])+def test_preflight_script_retries_only_transient_errors(ql, tmp_path, monkeypatch, status, retries):+ import openai++ error = openai.APIStatusError(+ "secret response body", response=httpx.Response(status, request=httpx.Request("POST", "https://test")),+ body=None,+ )+ _check_script(ql, tmp_path, monkeypatch, error, retries)++[email protected]("error,retries", [+ (httpx.ReadTimeout("secret timeout text"), True),+ (TimeoutError("secret timeout text"), True),+ (ValueError("secret error text"), False),+])+def test_preflight_script_timeout_and_other_errors(ql, tmp_path, monkeypatch, error, retries):+ _check_script(ql, tmp_path, monkeypatch, error, retries)+++def test_preflight_does_not_retry_connection_errors(ql, tmp_path, monkeypatch):+ import openai++ _check_script(ql, tmp_path, monkeypatch,+ openai.APIConnectionError(request=httpx.Request("POST", "https://test")), False)+++def test_preflight_sdk_timeout_stops_after_one_retry(ql, tmp_path, monkeypatch):+ import openai++ _check_script(ql, tmp_path, monkeypatch,+ openai.APITimeoutError(request=httpx.Request("POST", "https://test")), True,+ succeeds=False)+++def _check_script(ql, tmp_path, monkeypatch, error, retries, succeeds=True):+ """Execute the shipped child script, replacing only the LLM backend."""+ paths = ql.managed_paths(tmp_path)+ config = tmp_path / "check.json"+ config.write_text(json.dumps({"vlm": {"model": "test"}}), encoding="utf-8")+ vlm = MagicMock()+ vlm.get_completion.side_effect = [error, "OK" if succeeds else error]+ factory = MagicMock()+ factory.create.return_value = vlm+ backend = types.ModuleType("openviking.models.vlm")+ backend.VLMFactory = factory+ monkeypatch.setitem(sys.modules, "openviking.models.vlm", backend)+ monkeypatch.setattr(sys, "argv", ["check", str(config)])+ import time++ sleep = MagicMock()+ monkeypatch.setattr(time, "sleep", sleep)++ def run(command, **_kwargs):+ output = io.StringIO()+ code = 0+ with contextlib.redirect_stdout(output):+ try:+ exec(compile(command[2], "<llm-preflight>", "exec"), {})+ except SystemExit as exc:+ code = exc.code+ return subprocess.CompletedProcess(command, code, stdout=output.getvalue(), stderr="secret stderr")++ monkeypatch.setattr(ql.subprocess, "run", run)+ if retries and succeeds:+ ql._validate_vlm(paths, config)+ else:+ with pytest.raises(ql.QuickLocalSetupError) as caught:+ ql._validate_vlm(paths, config)+ assert "secret" not in str(caught.value)+ assert vlm.get_completion.call_count == (2 if retries else 1)+ if retries:+ sleep.assert_called_once_with(1)+ else:+ sleep.assert_not_called()++[email protected]("failure,expected", [+ ({"error": "AuthenticationError", "status": 401}, "API key and its permissions"),+ ({"error": "NotFoundError", "status": 404}, "model and endpoint"),+ ({"error": "RateLimitError", "status": 429, "attempts": 2}, "rate-limiting"),+ ({"error": "InternalServerError", "status": 500, "attempts": 2}, "temporary server error"),+ ({"error": "APITimeoutError", "timeout": True, "attempts": 2}, "timed out"),+])+def test_failure_metadata_is_actionable_and_private(ql, tmp_path, monkeypatch, failure, expected):+ result = subprocess.CompletedProcess("check", 1,+ stdout="import notice\n" + json.dumps(failure),+ stderr="Bearer secret credential")+ monkeypatch.setattr(ql.subprocess, "run", lambda *_args, **_kwargs: result)+ with pytest.raises(ql.QuickLocalSetupError, match=expected) as caught:+ ql._validate_vlm(ql.managed_paths(tmp_path), tmp_path / "check.json")+ log = tmp_path / "logs/openviking-server.log"+ assert failure["error"] in str(caught.value) and failure["error"] in log.read_text()+ assert "secret" not in str(caught.value) and "secret" not in log.read_text()+ if failure.get("status"):+ assert f"HTTP {failure['status']}" in str(caught.value)+ if os.name != "nt":+ assert log.stat().st_mode & 0o777 == 0o600+++def test_unstructured_failure_never_exposes_child_output(ql, tmp_path, monkeypatch):+ result = subprocess.CompletedProcess("check", 1, stdout="secret credential", stderr="secret response")+ monkeypatch.setattr(ql.subprocess, "run", lambda *_args, **_kwargs: result)+ with pytest.raises(ql.QuickLocalSetupError, match="UnknownError") as caught:+ ql._validate_vlm(ql.managed_paths(tmp_path), tmp_path / "check.json")+ assert "secret" not in str(caught.value)+ assert "secret" not in (tmp_path / "logs/openviking-server.log").read_text()diff --git a/examples/hermes-plugin/tests/test_quick_local_routes.py b/examples/hermes-plugin/tests/test_quick_local_routes.pynew file mode 100644index 000000000..914c12ccd--- /dev/null+++ b/examples/hermes-plugin/tests/test_quick_local_routes.py@@ -0,0 +1,140 @@+"""Copied LLM routes must match the transport the private server can use."""++import importlib+import os+import subprocess+from unittest.mock import MagicMock++import pytest+++def ql(external_provider):+ _home, _provider, module, _settings = external_provider("routes")+ return importlib.import_module(module.__name__ + ".quick_local")+++def resolve(ql, monkeypatch, **overrides):+ from hermes_cli import config, runtime_provider++ runtime = {+ "provider": "custom", "source": "custom_provider:test", "api_key": "static-key",+ "model": "test-model", "base_url": "https://proxy.example/anthropic/v1",+ "api_mode": "anthropic_messages",+ **overrides,+ }+ monkeypatch.setattr(config, "load_config", lambda: {"model": {"default": runtime["model"]}})+ monkeypatch.setattr(runtime_provider, "resolve_runtime_provider", lambda **_kw: runtime)+ return ql.resolve_hermes_vlm_config()++[email protected]("suffix", ["", "/v1beta", "/v1beta/", "/v1", "/v1alpha"])+def test_native_gemini_uses_openai_compatible_route(ql, monkeypatch, suffix):+ vlm = resolve(ql, monkeypatch, provider="gemini", source="env:GEMINI_API_KEY",+ api_mode="chat_completions", model="gemini-test",+ base_url="https://generativelanguage.googleapis.com" + suffix)+ assert vlm["provider"] == "openai"+ assert vlm["api_base"] == "https://generativelanguage.googleapis.com/v1beta/openai/"+ assert vlm["model"] == "gemini-test"+++def test_explicit_gemini_openai_route_is_retained(ql, monkeypatch):+ base = "https://generativelanguage.googleapis.com/v1beta/openai/"+ assert resolve(ql, monkeypatch, api_mode="chat_completions", base_url=base)["api_base"] == base+ proxy = "https://proxy.example/v1beta"+ assert resolve(ql, monkeypatch, api_mode="chat_completions", base_url=proxy)["api_base"] == proxy++[email protected]("base", ["https://api.minimax.io/anthropic", "https://api.minimaxi.com/anthropic",+ "https://res.services.ai.azure.com/anthropic"])+def test_bearer_anthropic_routes_fail_before_copying(ql, monkeypatch, base):+ with pytest.raises(ql.QuickLocalSetupError, match="cannot reproduce authentication"):+ resolve(ql, monkeypatch, base_url=base)+++def test_oauth_shaped_proxy_key_is_not_reinterpreted_by_litellm(ql, monkeypatch):+ with pytest.raises(ql.QuickLocalSetupError, match="cannot reproduce authentication"):+ resolve(ql, monkeypatch, api_key="sk-ant-oat-proxy-static")+++def test_kimi_coding_uses_hermes_attribution(ql, monkeypatch):+ vlm = resolve(ql, monkeypatch, base_url="https://api.kimi.com/coding",+ extra_headers={"X-Custom": "kept"})+ assert vlm["extra_headers"]["User-Agent"].startswith("HermesAgent/")+ assert vlm["extra_headers"]["X-Custom"] == "kept"+ assert vlm["api_key"] == "static-key"++[email protected]("provider,base,key_env", [+ ("openai-api", "https://api.openai.com/v1", "OPENAI_API_KEY"),+ ("xai", "https://api.x.ai/v1", "XAI_API_KEY"),+])+def test_official_static_responses_route_can_use_chat_completions(ql, monkeypatch, provider, base, key_env):+ vlm = resolve(ql, monkeypatch, provider=provider, source="env:" + key_env,+ api_mode="codex_responses", base_url=base)+ assert vlm["provider"] == "openai" and vlm["api_base"] == base++[email protected]("source", ["direct-alias", "custom_provider:official", "pool:official"])[email protected]("base", ["https://api.openai.com/v1", "https://api.x.ai/v1"])+def test_official_custom_responses_routes_preserve_static_key_gate(ql, monkeypatch, source, base):+ vlm = resolve(ql, monkeypatch, source=source, api_mode="codex_responses", base_url=base)+ assert vlm["provider"] == "openai" and vlm["api_base"] == base+ assert vlm["api_key"] == "static-key"++[email protected]("provider,source,key", [+ ("openai-codex", "oauth", "refreshed-token"),+ ("xai", "oauth", "refreshed-token"),+ ("custom", "key_cmd", lambda: pytest.fail("Must not execute credential commands")),+ ("custom", "oauth", "refreshed-token"),+])+def test_official_host_does_not_bypass_credential_classification(ql, monkeypatch, provider, source, key):+ with pytest.raises(ql.QuickLocalSetupError, match="cannot be copied safely"):+ resolve(ql, monkeypatch, provider=provider, source=source, api_key=key,+ api_mode="codex_responses", base_url="https://api.openai.com/v1")+++def test_other_responses_routes_are_not_guessed(ql, monkeypatch):+ with pytest.raises(ql.QuickLocalSetupError, match="transport is not supported"):+ resolve(ql, monkeypatch, api_mode="codex_responses", base_url="https://proxy.example/v1")++[email protected]("failure", [1, subprocess.TimeoutExpired("llm", 90)])+def test_llm_access_failure_does_not_activate_setup(ql, tmp_path, monkeypatch, failure):+ paths = ql.managed_paths(tmp_path)+ start = MagicMock()+ monkeypatch.setattr(ql, "_start_validation_server", start)+ run = MagicMock(side_effect=failure if isinstance(failure, Exception) else None,+ return_value=MagicMock(returncode=failure))+ monkeypatch.setattr(ql.subprocess, "run", run)+ with pytest.raises(ql.QuickLocalSetupError, match="LLM.*check"):+ ql.QuickLocalSetup(health_check=lambda _url: (True, ""))._validate_generated_config(+ paths=paths, endpoint="http://127.0.0.1:1934",+ server_config=ql.build_server_config(paths, {"model": "test-model"}),+ )+ start.assert_not_called()+ assert not paths.server_config.exists() and not paths.ovcli_config.exists()+ assert not paths.restart_required_marker.exists()+++def test_named_legacy_profile_finds_root_uv_without_repair(ql, tmp_path, monkeypatch):+ from hermes_cli import managed_uv++ profile = tmp_path / "profiles/work"+ profile.mkdir(parents=True)+ uv = tmp_path / "bin" / ("uv.exe" if os.name == "nt" else "uv")+ uv.parent.mkdir()+ uv.touch()+ monkeypatch.setenv("HERMES_HOME", str(profile))+ monkeypatch.setattr(managed_uv, "resolve_uv", lambda: None)+ monkeypatch.setattr(ql.shutil, "which", lambda _name: None)+ repair = MagicMock(side_effect=AssertionError("must not repair the host"))+ monkeypatch.setattr(managed_uv, "ensure_uv", repair)+ run = MagicMock(return_value=MagicMock(returncode=0))+ monkeypatch.setattr(ql.subprocess, "run", run)+ ql.QuickLocalSetup(health_check=lambda _url: (False, ""))._install_with_uv(+ ql.managed_paths(profile), ["isolated-package"]+ )+ assert all(call.args[0][0] == str(uv) for call in run.call_args_list)+ repair.assert_not_called()diff --git a/scripts/check-hermes-plugin-install.py b/scripts/check-hermes-plugin-install.pyindex 99690fcd1..b377ea359 100644--- a/scripts/check-hermes-plugin-install.py+++ b/scripts/check-hermes-plugin-install.py@@ -94,6 +94,10 @@ def check(host, repository, root, timeout):for name in ("__init__.py","_setup.py",+ "quick_local.py",+ "local_server.py",+ "local_packages.py",+ "cli.py","native_memory_mirror.py","plugin.yaml","pyproject.toml",diff --git a/scripts/check-hermes-quick-local.py b/scripts/check-hermes-quick-local.pynew file mode 100644index 000000000..4dc2ed321--- /dev/null+++ b/scripts/check-hermes-quick-local.py@@ -0,0 +1,361 @@+#!/usr/bin/env python3+"""Run real Quick Local installation, local embeddings and profile lifecycle.++Uses a static test LLM configuration. It does not call a remote LLM; extraction+and interactive setup are separate live release checks.+"""++import argparse+import importlib+import json+import os+import shutil+import subprocess+import sys+import threading+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+++def wait_for_provider(provider, timeout=180):+ """Exercise retained-provider autostart, never the controller's start path."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if provider._ensure_client() is not None:+ return+ time.sleep(.1)+ raise AssertionError("The retained external provider did not recover its managed server")+++def check_llm_transports(home, ql, runtime_python):+ """Resolve persisted Hermes routes and observe real installed OV requests."""+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ requests = []+ request_headers = []++ class Handler(BaseHTTPRequestHandler):+ def do_POST(self):+ self.rfile.read(int(self.headers["Content-Length"]))+ requests.append(self.path)+ request_headers.append(dict(self.headers))+ print("Observed LLM request: " + self.path, flush=True)+ if self.path in {"/v1/chat/completions", "/v1beta/openai/chat/completions"}:+ body = {"id": "chat-test", "object": "chat.completion", "model": "gpt-test",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "transport-ok"},+ "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}+ elif self.path in {"/anthropic/v1/messages", "/coding/v1/messages"}:+ body = {"id": "msg-test", "type": "message", "role": "assistant", "model": "claude-test",+ "content": [{"type": "text", "text": "transport-ok"}], "stop_reason": "end_turn",+ "stop_sequence": None, "usage": {"input_tokens": 1, "output_tokens": 1}}+ else:+ self.send_error(404)+ return+ data = json.dumps(body).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def log_message(self, *_args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ worker = threading.Thread(target=server.serve_forever, daemon=True)+ worker.start()+ token = set_hermes_home_override(home)+ try:+ home.mkdir(parents=True, exist_ok=True)+ for mode, suffix, model, expected in (+ ("chat_completions", "/v1", "gpt-test", "/v1/chat/completions"),+ ("anthropic_messages", "/anthropic", "claude-test", "/anthropic/v1/messages"),+ ("anthropic_messages", "/anthropic/v1", "claude-test", "/anthropic/v1/messages"),+ ("anthropic_messages", "/anthropic/v1/", "claude-test", "/anthropic/v1/messages"),+ ("chat_completions", "/v1beta", "gemini-test", "/v1beta/openai/chat/completions"),+ ("anthropic_messages", "/coding", "claude-test", "/coding/v1/messages"),+ ):+ base = f"http://127.0.0.1:{server.server_port}{suffix}"+ if suffix == "/v1beta":+ base = "https://generativelanguage.googleapis.com/v1beta"+ elif suffix == "/coding":+ base = "https://api.kimi.com/coding"+ config = {"model": {"provider": "custom:transport", "default": model}, "custom_providers": [+ {"name": "transport", "base_url": base,+ "api_key": "static-test-key", "api_mode": mode}+ ]}+ (home / "config.yaml").write_text(json.dumps(config), encoding="utf-8")+ vlm = ql.resolve_hermes_vlm_config()+ if suffix in {"/v1beta", "/coding"}:+ from urllib.parse import urlparse++ # Resolve with the real provider host, then use the loopback+ # fixture only for observing the installed backend's request.+ vlm["api_base"] = f"http://127.0.0.1:{server.server_port}" + urlparse(vlm["api_base"]).path+ script = (+ "import json,sys; from openviking.models.vlm import VLMFactory; "+ "v=VLMFactory.create(json.load(sys.stdin)); "+ "assert v.get_completion(prompt='Reply transport-ok')=='transport-ok'"+ )+ count = len(requests)+ subprocess.run([str(runtime_python), "-c", script], input=json.dumps(vlm),+ text=True, check=True, timeout=120)+ assert requests[count:] == [expected], requests[count:]+ if suffix == "/coding":+ assert request_headers[-1]["User-Agent"].startswith("HermesAgent/")+ assert request_headers[-1]["x-api-key"] == "static-test-key"+ return requests+ finally:+ reset_hermes_home_override(token)+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--hermes-root", type=Path, required=True)+ parser.add_argument("--output-dir", type=Path, required=True)+ parser.add_argument("--legacy-uv", action="store_true")+ args = parser.parse_args()+ root = args.output_dir.resolve()+ root.mkdir(parents=True, exist_ok=True)+ host = args.hermes_root.resolve()+ sys.path.insert(0, str(host))+ for key in list(os.environ):+ if key.startswith(("OPENVIKING_", "HERMES_", "__HERMES_")):+ del os.environ[key]+ os.environ.update(+ HERMES_HOME=str(root / "a"),+ HERMES_RUNTIME_DIR=str(root / "host-runtime"),+ HERMES_ENABLE_PROJECT_PLUGINS="0",+ )+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from plugins import memory++ memory._MEMORY_PLUGINS_DIR = root / "empty-bundled"+ source = Path(__file__).resolve().parents[1] / "examples/hermes-plugin"+ servers, providers = [], []+ evidence = {"legacy_uv": args.legacy_uv, "profiles": []}+ llm_requests = []+ preflight_errors = []++ class LLMHandler(BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_POST(self):+ self.rfile.read(int(self.headers["Content-Length"]))+ if self.path != "/v1/chat/completions" or self.headers.get("Authorization") not in {+ "Bearer isolated-static-test-key", "Bearer updated-isolated-static-key"+ }:+ self.send_error(401)+ return+ llm_requests.append(self.path)+ if preflight_errors:+ self.send_error(preflight_errors.pop(0), "private provider response")+ return+ body = json.dumps({"id": "setup-test", "object": "chat.completion", "model": "test-model",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "OK"},+ "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ llm_server = ThreadingHTTPServer(("127.0.0.1", 0), LLMHandler)+ llm_worker = threading.Thread(target=llm_server.serve_forever, daemon=True)+ llm_worker.start()+ try:+ for name in ("a", "b"):+ home = root / name+ shutil.copytree(+ source,+ home / "plugins/openviking",+ dirs_exist_ok=True,+ ignore=shutil.ignore_patterns("tests", "__pycache__"),+ )+ config = {+ "model": {"provider": "custom:test", "default": "test-model"},+ "custom_providers": [+ {+ "name": "test",+ "base_url": f"http://127.0.0.1:{llm_server.server_port}/v1",+ "api_key": "isolated-static-test-key",+ "api_mode": "chat_completions",+ }+ ],+ "memory": {"provider": "openviking", "openviking": {+ "deployment": "quick_local", "use_ovcli_config": True,+ }},+ "plugins": {"enabled": ["openviking"]},+ }+ (home / "config.yaml").write_text(json.dumps(config), encoding="utf-8")+ if os.name != "nt":+ (home / "config.yaml").chmod(0o600)+ token = set_hermes_home_override(home)+ try:+ assert memory.find_provider_dir("openviking") == home / "plugins/openviking"+ provider = memory.load_memory_provider("openviking", register_skills=False)+ assert type(provider).__module__.startswith("_hermes_user_memory.")+ ql = importlib.import_module(type(provider).__module__ + ".quick_local")+ lifecycle = importlib.import_module(type(provider).__module__ + ".local_server")+ if args.legacy_uv:+ assert not ql._pm_available(), "Use a pre-PM Hermes host for the legacy test"+ server = lifecycle.LocalServer(home)+ servers.append(server)+ providers.append(provider)+ module = importlib.import_module(type(provider).__module__)+ setup = ql.QuickLocalSetup(health_check=module._validate_openviking_reachability)+ setup.provision(hermes_home=home)+ assert len(llm_requests) >= len(evidence["profiles"]) + 1+ before = {path: path.read_bytes() for path in (+ server.paths.server_config, server.paths.ovcli_config+ )}+ config["custom_providers"][0]["api_key"] = "invalid-static-test-key"+ (home / "config.yaml").write_text(json.dumps(config), encoding="utf-8")+ try:+ setup.provision(hermes_home=home)+ except ql.QuickLocalSetupError as error:+ assert "LLM settings failed the access check" in str(error), str(error)+ else:+ raise AssertionError("Invalid copied LLM key passed setup")+ finally:+ config["custom_providers"][0]["api_key"] = "isolated-static-test-key"+ (home / "config.yaml").write_text(json.dumps(config), encoding="utf-8")+ assert all(path.read_bytes() == data for path, data in before.items())+ assert not server.paths.restart_required_marker.exists()+ if name == "a":+ evidence["llm_request_paths"] = check_llm_transports(+ root / "transport-config", ql, server.paths.runtime_python+ )+ evidence["llm_preflight"] = []+ for errors in ([401], [404], [429], [500], [429, 429]):+ preflight_errors[:] = errors+ count = len(llm_requests)+ log_path = home / "logs/openviking-server.log"+ log_size = log_path.stat().st_size+ failed = False+ try:+ ql._validate_vlm(server.paths, server.paths.server_config)+ except ql.QuickLocalSetupError as error:+ failed = True+ assert f"HTTP {errors[-1]}" in str(error), str(error)+ assert "private provider response" not in str(error)+ assert failed == (errors[0] in {401, 404} or len(errors) == 2)+ expected = 1 if errors[0] in {401, 404} else 2+ assert len(llm_requests) - count == expected+ assert "private provider response" not in log_path.read_bytes()[log_size:].decode()+ evidence["llm_preflight"].append({"errors": errors, "requests": expected, "failed": failed})+ assert not preflight_errors+ provider.initialize("local-smoke-" + name, hermes_home=str(home), platform="cli")+ assert provider._client is not None+ provider.sync_turn(+ "A captured local test message",+ "Acknowledged",+ session_id="local-smoke-" + name,+ )+ assert provider._drain_writers("local-smoke-" + name, timeout=15)+ session = provider._client.get("/api/v1/sessions/local-smoke-" + name)["result"]+ assert session["pending_tokens"] > 0+ browse = json.loads(+ provider.handle_tool_call(+ "viking_browse", {"path": "viking://", "action": "list"}+ )+ )+ assert not browse.get("error")+ # Keep this provider/session alive through a crash and an+ # explicit stop. Later use must recover without a new agent.+ import psutil++ for action in ("crash", "stop"):+ old_pid = server.status()["pid"]+ assert isinstance(old_pid, int), "Managed server must have a verified PID"+ if action == "crash":+ process = psutil.Process(old_pid)+ owned = [*process.children(recursive=True), process]+ for child in owned:+ try:+ child.kill()+ except psutil.NoSuchProcess:+ pass+ psutil.wait_procs(owned, timeout=5)+ else:+ server.stop()+ assert provider._ensure_client() is None+ wait_for_provider(provider)+ assert server.status()["pid"] != old_pid+ assert provider._client.get("/api/v1/sessions/local-smoke-" + name)["result"]["pending_tokens"] > 0+ old_pid = server.status()["pid"]+ updated = server._config()+ updated["vlm"]["api_key"] = "updated-isolated-static-key"+ server.configure(updated)+ server.wait_ready(server.start(), setup._health_check, timeout=120)+ assert server.status()["pid"] != old_pid+ assert (+ provider._client.get("/api/v1/sessions/local-smoke-" + name)["result"][+ "pending_tokens"+ ]+ > 0+ )+ probe = (+ "from openviking.models.embedder.local_embedders import LocalDenseEmbedder; import math; e=LocalDenseEmbedder(model_name='bge-small-zh-v1.5-f16',cache_dir="+ + repr(str(server.paths.model_cache))+ + "); v=e.embed('local embedding validation').dense_vector; assert len(v)==512 and all(math.isfinite(x) for x in v) and any(v)"+ )+ subprocess.run(+ [str(server.paths.runtime_python), "-c", probe], check=True, timeout=120+ )+ evidence["profiles"].append(server.status())+ finally:+ reset_hermes_home_override(token)+ assert servers[0].status()["endpoint"] != servers[1].status()["endpoint"]+ # A's saved port is taken by B while A is stopped. A must move and keep+ # its captured session, without stopping or reconfiguring B.+ a, b = servers+ previous = a.status()["endpoint"]+ a.stop()+ config = b._config()+ config["server"]["port"] = b.ql._endpoint_port(previous)+ b.configure(config)+ b.wait_ready(+ b.start(), lambda url: (b.ql.server_belongs_to_profile(b.paths, url), ""), timeout=120+ )+ foreign_pid = b.status()["pid"]+ token = set_hermes_home_override(a.paths.root.parent)+ try:+ assert providers[0]._ensure_client() is None+ wait_for_provider(providers[0])+ assert providers[0]._endpoint != previous and b.status()["pid"] == foreign_pid+ assert providers[0]._client.get("/api/v1/sessions/local-smoke-a")["result"]["pending_tokens"] > 0+ finally:+ reset_hermes_home_override(token)+ evidence.update(+ external_loader=True,+ real_embeddings=True,+ captured_turns=True,+ restart_preserved_data=True,+ foreign_port_recovery=True,+ retained_provider_recovery=True,+ llm_access_validated=True,+ llm_failure_preserved_configuration=True,+ )+ print(json.dumps(evidence))+ finally:+ for provider in providers:+ provider.shutdown()+ for server in reversed(servers):+ if server.paths.server_config.exists():+ server.stop()+ llm_server.shutdown()+ llm_server.server_close()+ llm_worker.join(timeout=5)+ (root / "evidence.json").write_text(json.dumps(evidence, indent=2) + "\n")+++if __name__ == "__main__":+ main()