Skip to content

The agent that grows with you

refactor(openviking): move setup-only writers into _setup, dataclass _TurnUpload

Teknium1e8169a5182b
diff --git a/plugins/memory/openviking/__init__.py b/plugins/memory/openviking/__init__.py
index a81852f0ed2..eff130a1319 100644
--- a/plugins/memory/openviking/__init__.py
+++ b/plugins/memory/openviking/__init__.py
@@ -165,10 +165,8 @@ def _sanitize_openviking_error_message(message: str, status_code: Optional[int]
title_match = re.search(r"<title[^>]*>(.*?)</title>", text, flags=re.IGNORECASE | re.DOTALL)
if title_match:
title = re.sub(r"\s+", " ", title_match.group(1)).strip()
- if "|" in title:
- title = title.split("|", 1)[1].strip()
- if status_code and title.startswith(f"{status_code}:"):
- title = title.split(":", 1)[1].strip()
+ title = title.split("|", 1)[1].strip() if "|" in title else title
+ title = title.split(":", 1)[1].strip() if status_code and title.startswith(f"{status_code}:") else title
if title:
return f"{status}: {title}"
return f"{status}: OpenViking endpoint returned an HTML error page."
@@ -630,7 +628,6 @@ def _normalize_openviking_url(url: str) -> str:
candidate = f"http://[::1]:{trimmed.rsplit(':', 1)[1]}"
else:
candidate = trimmed if "://" in trimmed else f"http://{trimmed}"
-
try:
parsed = urlparse(candidate)
if parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname:
@@ -790,11 +787,6 @@ def _resolve_connection_settings(provider_config: Optional[dict] = None) -> dict
}
-def _env_writes_from_connection_values(values: dict) -> dict:
- writes = {env_key: _clean_config_value(values.get(value_key)) for env_key, value_key in zip(_OPENVIKING_ENV_KEYS, _CONNECTION_KEYS)}
- return {key: value for key, value in writes.items() if value}
-
-
def _secure_secret_file(path: Path, *, create: bool = False) -> None:
"""chmod 0600 a secret-bearing file; with ``create`` also pre-create it BEFORE writing
(write-then-chmod leaves a window where the fresh file is world-readable under the umask)."""
@@ -835,14 +827,6 @@ def _write_env_vars(env_path: Path, env_writes: dict, remove_keys: tuple[str, ..
_secure_secret_file(env_path)
-def _remember_ovcli_path(provider_config: dict, ovcli_path: Path) -> None:
- default_path = _default_ovcli_config_path().expanduser()
- if os.environ.get(_OVCLI_CONFIG_ENV, "").strip() or ovcli_path.expanduser() != default_path:
- provider_config["ovcli_config_path"] = str(ovcli_path)
- else:
- provider_config.pop("ovcli_config_path", None)
-
-
def _ovcli_data_from_connection_values(values: dict) -> dict:
data = {"url": _normalize_openviking_url(_clean_config_value(values.get("endpoint")) or _DEFAULT_ENDPOINT)}
for out_key, in_key in (("api_key", "api_key"), ("root_api_key", "root_api_key"), ("account", "account"), ("user", "user"), ("actor_peer_id", "agent")):
@@ -1164,15 +1148,17 @@ def _index_tool_calls(messages: List[Dict[str, Any]]) -> tuple[Dict[str, Dict[st
return tool_calls_by_id, completed_tool_ids, skipped_tool_ids
+@dataclass
class _TurnUpload:
"""One turn's OpenViking upload: structured batches first, falling back to plain text
on a first-batch failure, and to individual messages after a failed retry."""
- def __init__(self, provider: "OpenVikingMemoryProvider", sid: str, batch_messages: List[Dict[str, Any]],
- user_content: str, assistant_content: str):
- self.provider, self.sid, self.batch_messages = provider, sid, batch_messages
- self.user_content, self.assistant_content = user_content, assistant_content
- self.next_index = 0
+ provider: "OpenVikingMemoryProvider"
+ sid: str
+ batch_messages: List[Dict[str, Any]]
+ user_content: str
+ assistant_content: str
+ next_index: int = 0
def _trace(self, fmt: str, *args) -> None:
if env_var_enabled(_SYNC_TRACE_ENV):
@@ -1489,7 +1475,6 @@ class OpenVikingMemoryProvider(MemoryProvider):
if self._shutting_down:
self._client = None
return None
-
try:
settings = _resolve_connection_settings(_load_hermes_openviking_config())
except _OpenVikingEndpointError as exc:
@@ -2759,7 +2744,6 @@ class OpenVikingMemoryProvider(MemoryProvider):
}, ensure_ascii=False)
-
def register(ctx) -> None:
"""Register OpenViking as a memory provider plugin."""
ctx.register_memory_provider(OpenVikingMemoryProvider())
diff --git a/plugins/memory/openviking/_setup.py b/plugins/memory/openviking/_setup.py
index b1927be1bb6..523b9cebd7f 100644
--- a/plugins/memory/openviking/_setup.py
+++ b/plugins/memory/openviking/_setup.py
@@ -235,7 +235,11 @@ def _link_ovcli_profile(*, config: dict, provider_config: dict, env_path: Path,
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
- ov._remember_ovcli_path(provider_config, ovcli_path)
+ # Record the path only when it is not the default location (or the env var points elsewhere).
+ if os.environ.get(ov._OVCLI_CONFIG_ENV, "").strip() or ovcli_path.expanduser() != ov._default_ovcli_config_path().expanduser():
+ provider_config["ovcli_config_path"] = str(ovcli_path)
+ else:
+ provider_config.pop("ovcli_config_path", None)
config["memory"]["provider"] = "openviking"
config["memory"]["openviking"] = provider_config
ov._write_env_vars(env_path, {}, remove_keys=ov._OPENVIKING_ENV_KEYS)
@@ -253,7 +257,8 @@ def _save_hermes_only_config(*, config: dict, provider_config: dict, env_path: P
config["memory"]["provider"] = "openviking"
config["memory"]["openviking"] = provider_config
# Publish the file writer's cleaned values to the current process as well.
- writes = {key: ov._env_line_safe(value) for key, value in ov._env_writes_from_connection_values(values).items()}
+ writes = {env_key: ov._env_line_safe(value) for env_key, key in zip(ov._OPENVIKING_ENV_KEYS, ov._CONNECTION_KEYS)
+ if (value := ov._clean_config_value(values.get(key)))}
ov._write_env_vars(env_path, writes, remove_keys=ov._OPENVIKING_ENV_KEYS)
os.environ.update(writes)
for key in set(ov._OPENVIKING_ENV_KEYS) - set(writes):