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(bot): Change bot api_key to user mode, support ov's peers, eval support peers (#2527)
DuTaoa702d38a8bff
diff --git a/benchmark/locomo/vikingbot/import_to_ov.py b/benchmark/locomo/vikingbot/import_to_ov.pyindex 4f925c50b..7b8879dc4 100644--- a/benchmark/locomo/vikingbot/import_to_ov.py+++ b/benchmark/locomo/vikingbot/import_to_ov.py@@ -31,10 +31,18 @@ def _get_session_number(session_key: str) -> int:def build_memory_policy(group_chat: bool) -> Dict[str, Dict[str, bool]]:- """Build session memory policy for benchmark ingest."""+ """Build session/commit memory policy for benchmark ingest.++ LoCoMo eval isolates samples through peer memory. In non-group mode the+ peer is the sample_id (for example conv-26); in group mode the peer is the+ speaker. Do not write benchmark memories into the current User self memory,+ otherwise all samples imported by the same User API key become visible to+ every question.+ """+ del group_chatreturn {- "self": {"enabled": True},- "peer": {"enabled": bool(group_chat)},+ "self": {"enabled": False},+ "peer": {"enabled": True},}@@ -92,10 +100,11 @@ def build_session_messages(Each dict represents a session with multiple messages (user/assistant role).Args:- group_chat: If True (default), group-chat mode — peer_id=speaker.- If False, single-chat mode — no peer_id/speaker on messages.+ group_chat: If True, use speaker names as peer_id.+ If False, use sample_id as peer_id and prefix speaker in text."""conv = item["conversation"]+ sample_peer_id = item["sample_id"]speakers = f"{conv['speaker_a']} & {conv['speaker_b']}"session_keys = sorted(@@ -119,11 +128,27 @@ def build_session_messages(speaker = msg.get("speaker", "unknown")text = msg.get("text", "")if group_chat:- messages.append({"role": "user", "text": text, "speaker": speaker, "index": idx})+ messages.append(+ {+ "role": "user",+ "text": text,+ "speaker": speaker,+ "peer_id": speaker,+ "index": idx,+ }+ )else:- # single-chat 模式下所有消息用统一 user_id 上传,- # speaker 信息需要嵌入文本以保留说话人身份- messages.append({"role": "user", "text": f"{speaker}: {text}", "index": idx})+ # single-chat 模式下按 sample_id 聚合 peer,+ # speaker 信息嵌入文本以保留说话人身份+ messages.append(+ {+ "role": "user",+ "text": f"{speaker}: {text}",+ "speaker": speaker,+ "peer_id": sample_peer_id,+ "index": idx,+ }+ )sessions.append({@@ -361,7 +386,7 @@ async def viking_ingest(role=msg["role"],parts=[{"type": "text", "text": msg["text"]}],created_at=msg_created_at,- peer_id=msg.get("speaker"),+ peer_id=msg.get("peer_id"),)# Commit@@ -425,8 +450,14 @@ async def process_single_session(source_sample_id = str(sample_id)try:started_at = time.perf_counter()- user_id = str(sample_id) if args.separate_user_by_sample else ""- account = args.account if args.separate_user_by_sample else ""+ if args.api_key:+ # User API keys already pin account/user on the server side. Passing+ # account/user headers would be rejected in api_key auth mode.+ user_id = ""+ account = ""+ else:+ user_id = str(sample_id) if args.separate_user_by_sample else ""+ account = args.account if args.separate_user_by_sample else ""result = await viking_ingest(messages,args.openviking_url,@@ -754,7 +785,13 @@ async def run_import(args: argparse.Namespace) -> None:messages = []for i, text in enumerate(session["messages"]):messages.append(- {"role": "user", "text": text.strip(), "speaker": "user", "index": i}+ {+ "role": "user",+ "text": text.strip(),+ "speaker": "user",+ "peer_id": "user",+ "index": i,+ })preview = " | ".join([f"{msg['role']}: {msg['text'][:30]}..." for msg in messages[:3]])@@ -894,7 +931,7 @@ def main():"--separate-user-by-sample",action=argparse.BooleanOptionalAction,default=True,- help="Whether to isolate OpenViking users by sample (default: true). Use --no-separate-user-by-sample to use an empty user while keeping --account unchanged.",+ help="Whether to isolate OpenViking users by sample (default: true). Ignored when --api-key is provided because User keys pin account/user identity.",)parser.add_argument("--parallel-samples",@@ -910,9 +947,9 @@ def main():)parser.add_argument("--group-chat",- action="store_true",+ action=argparse.BooleanOptionalAction,default=False,- help="Group-chat mode: set peer_id/speaker on messages. Default is group-chat mode.",+ help="Group-chat mode: use speaker names as peer_id (default: false).",)parser.add_argument("--clear-ingest-record",diff --git a/benchmark/locomo/vikingbot/preflight_eval_config.py b/benchmark/locomo/vikingbot/preflight_eval_config.pyindex 10cc52213..d8c0236e2 100644--- a/benchmark/locomo/vikingbot/preflight_eval_config.py+++ b/benchmark/locomo/vikingbot/preflight_eval_config.py@@ -7,9 +7,7 @@ from pathlib import Pathfrom openviking_cli.utils.config.config_loader import resolve_config_pathfrom openviking_cli.utils.config.consts import (- DEFAULT_OVCLI_CONF,DEFAULT_OV_CONF,- OPENVIKING_CLI_CONFIG_ENV,OPENVIKING_CONFIG_ENV,)@@ -54,33 +52,12 @@ def _prompt_text(prompt: str, default: str | None = None) -> str:return raw-def _prompt_confirm(prompt: str, default: bool = True) -> bool:- hint = "Y/n" if default else "y/N"- raw = input(f"{_prefix()} {prompt} [{hint}]: ").strip().lower()- if not raw:- return default- return raw in {"y", "yes"}--def _load_json(path: Path) -> dict:with open(path, "r", encoding="utf-8-sig") as f:raw = f.read()return json.loads(raw)-def _backup_and_write_json(path: Path, data: dict) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- if path.exists():- backup = path.with_suffix(path.suffix + ".bak")- with open(path, "r", encoding="utf-8") as src:- original = src.read()- with open(backup, "w", encoding="utf-8") as bak:- bak.write(original)- with open(path, "w", encoding="utf-8") as f:- json.dump(data, f, indent=2, ensure_ascii=False)- f.write("\n")--def _resolve_ov_conf_path() -> Path:configured_path = os.environ.get(OPENVIKING_CONFIG_ENV, "").strip()if configured_path:@@ -97,161 +74,13 @@ def _resolve_ov_conf_path() -> Path:return Path(chosen).expanduser()-def _ensure_server_root_api_key(ov_data: dict) -> tuple[bool, bool]:- server = ov_data.setdefault("server", {})- root_key = str(server.get("root_api_key") or "").strip()- if root_key:- return True, False-- _log_warn("server.root_api_key 未配置。")- if not _is_interactive():- _log_error("非交互模式下无法录入 root_api_key,请先配置后重试。")- return False, False-- while True:- key = _prompt_text("请输入 OpenViking root_api_key")- if key:- server["root_api_key"] = key- return True, True- _log_warn("root_api_key 不能为空,请重新输入。")---def _check_bot_root_key(ov_data: dict) -> tuple[bool, bool]:- server_root_key = str(ov_data.get("server", {}).get("root_api_key") or "").strip()- bot = ov_data.setdefault("bot", {})- ov_server = bot.setdefault("ov_server", {})- bot_root_key = str(ov_server.get("root_api_key") or "").strip()-- if not bot_root_key or bot_root_key == server_root_key:- return True, False-- _log_warn("bot.ov_server.root_api_key 与 server.root_api_key 不一致。")- _log_warn("vikingbot 必须使用 OpenViking 的 root 级 API key。")-- if not _is_interactive():- _log_error("非交互模式下不会自动修改,请先修复配置后重试。")- return False, False-- if _prompt_confirm("是否自动调整为 server.root_api_key", default=True):- ov_server["root_api_key"] = server_root_key- return True, True-- _log_error("已取消自动调整。")- return False, False---def _resolve_ovcli_path() -> Path:- resolved = resolve_config_path(None, OPENVIKING_CLI_CONFIG_ENV, DEFAULT_OVCLI_CONF)- if resolved is not None:- return resolved- return Path.home() / ".openviking" / "ovcli.conf"---def _set_bot_account_id(ov_data: dict, account_id: str) -> bool:- bot = ov_data.setdefault("bot", {})- ov_server = bot.setdefault("ov_server", {})- current = str(ov_server.get("account_id") or "").strip()- if current == account_id:- return False- ov_server["account_id"] = account_id- return True---def _check_ovcli_keys_and_account(server_root_key: str, ov_data: dict) -> tuple[bool, bool, str]:- ovcli_path = _resolve_ovcli_path()-- changed_ovcli = False- changed_ov = False-- if not ovcli_path.exists():- _log_warn(f"未找到 ovcli.conf: {ovcli_path}")- if not _is_interactive():- _log_error("非交互模式下不会创建 ovcli.conf。")- return False, False, "default"- if not _prompt_confirm("是否创建并写入 root key", default=True):- _log_error("已取消创建 ovcli.conf。")- return False, False, "default"- ovcli_data = {- "url": "http://localhost:1933",- "api_key": server_root_key,- "root_api_key": server_root_key,- "account": "",- "timeout": 60.0,- }- changed_ovcli = True- else:- try:- ovcli_data = _load_json(ovcli_path)- except Exception as exc:- _log_error(f"读取 ovcli.conf 失败: {exc}")- return False, False, "default"-- needs_key_update = False- api_key = str(ovcli_data.get("api_key") or "").strip()- if api_key != server_root_key:- needs_key_update = True-- has_root_key_field = "root_api_key" in ovcli_data- root_api_key = str(ovcli_data.get("root_api_key") or "").strip() if has_root_key_field else ""- if has_root_key_field and root_api_key != server_root_key:- needs_key_update = True-- if needs_key_update:- _log_warn("ovcli.conf 的 key 与 server.root_api_key 不一致。")- if not _is_interactive():- _log_error("非交互模式下不会自动修改 ovcli.conf。")- return False, False, "default"- if not _prompt_confirm("是否自动更改为 server.root_api_key", default=True):- _log_error("已取消自动更改 ovcli.conf。")- return False, False, "default"- ovcli_data["api_key"] = server_root_key- if has_root_key_field:- ovcli_data["root_api_key"] = server_root_key- changed_ovcli = True- _log_ok("ovcli.conf key 已同步为 server.root_api_key")-- selected_account = str(ovcli_data.get("account") or "").strip()- if selected_account:- if _is_interactive():- use_current = _prompt_confirm(- f"检测到 ovcli.conf.account={selected_account},是否使用该 account",- default=True,- )- if not use_current:- candidate = _prompt_text("请输入新的 account", default=selected_account).strip()- if candidate:- selected_account = candidate- ovcli_data["account"] = selected_account- changed_ovcli = True- _log_ok(f"ovcli.conf account 已更新为: {selected_account}")- _log_info(f"导入与评测将使用 account: {selected_account}")- else:- _log_warn("ovcli.conf 的 account 为空。")- if _is_interactive():- selected_account = _prompt_text(- "将使用默认 Account=default;回车确认,或输入新 account",- default="default",- ).strip()- if not selected_account:- selected_account = "default"- else:- selected_account = "default"- _log_info("将使用默认 Account=default 导入 OpenViking 数据和 Vikingbot 评测。")-- if selected_account != "default":- ovcli_data["account"] = selected_account- changed_ovcli = True- _log_ok(f"ovcli.conf account 已更新为: {selected_account}")-- if _set_bot_account_id(ov_data, selected_account):- changed_ov = True- _log_ok(f"bot.ov_server.account_id 已同步为: {selected_account}")-- if changed_ovcli:- _backup_and_write_json(ovcli_path, ovcli_data)- _log_ok(f"已更新 {ovcli_path}")-- return True, changed_ov, selected_account+def _warn_deprecated_or_conflicting_fields(ov_data: dict) -> None:+ ov_server = (ov_data.get("bot") or {}).get("ov_server") or {}+ if str(ov_server.get("root_api_key") or "").strip():+ _log_warn("bot.ov_server.root_api_key 已废弃,评测不会再把它当作认证 key 使用。")+ api_key_type = str(ov_server.get("api_key_type") or "").strip().lower()+ if api_key_type and api_key_type != "user":+ _log_warn("bot.ov_server.api_key_type 不是 user;后续会在 User key 校验通过后同步为 user。")def main() -> int:@@ -267,33 +96,8 @@ def main() -> int:_log_error(f"读取 ov.conf 失败: {exc}")return 1- ok, changed_server = _ensure_server_root_api_key(ov_data)- if not ok:- return 1-- ok, changed_bot = _check_bot_root_key(ov_data)- if not ok:- return 1-- if changed_server or changed_bot:- _backup_and_write_json(ov_conf_path, ov_data)- _log_ok(f"已更新 {ov_conf_path}")-- if changed_server:- _log_warn("检测到 server.root_api_key 刚完成配置,请先重启 openviking-server。")- _log_info("重启完成后请重新执行一键评测脚本。")- return 2-- server_root_key = str(ov_data.get("server", {}).get("root_api_key") or "").strip()- ok, changed_ov_account, _ = _check_ovcli_keys_and_account(server_root_key, ov_data)- if not ok:- return 1-- if changed_ov_account:- _backup_and_write_json(ov_conf_path, ov_data)- _log_ok(f"已更新 {ov_conf_path}")-- _log_ok("配置检查通过。")+ _warn_deprecated_or_conflicting_fields(ov_data)+ _log_ok("本地配置可读取;将继续连接 OpenViking 校验 User API key。")return 0except KeyboardInterrupt:_log_error("用户取消。")diff --git a/benchmark/locomo/vikingbot/preflight_eval_runtime.py b/benchmark/locomo/vikingbot/preflight_eval_runtime.pyindex cdf2516b8..72b515998 100644--- a/benchmark/locomo/vikingbot/preflight_eval_runtime.py+++ b/benchmark/locomo/vikingbot/preflight_eval_runtime.py@@ -31,7 +31,24 @@ def _load_json(path: Path) -> dict:return json.load(f)-def _resolve_account() -> str:+def _is_interactive() -> bool:+ interactive_env = os.environ.get("INTERACTIVE", "").strip()+ if interactive_env:+ return interactive_env == "1"+ return sys.stdin.isatty() and sys.stdout.isatty()+++def _prompt_api_key() -> str:+ prompt = "[preflight] 请输入 OpenViking User API key: "+ try:+ with open("/dev/tty", "r", encoding="utf-8") as tty_in:+ print(prompt, end="", flush=True)+ return tty_in.readline().strip()+ except Exception:+ return input(prompt).strip()+++def _resolve_configured_account_hint() -> str:path = resolve_config_path(None, OPENVIKING_CLI_CONFIG_ENV, DEFAULT_OVCLI_CONF)if path is None:return "default"@@ -51,6 +68,12 @@ def _resolve_openviking_url() -> str:if path is not None:try:data = _load_json(Path(path))+ bot_server_url = str(+ ((data.get("bot") or {}).get("ov_server") or {}).get("server_url") or ""+ ).strip()+ if bot_server_url:+ return bot_server_url.rstrip("/")+server = data.get("server") or {}parsed_host = str(server.get("host") or "").strip()parsed_port = server.get("port")@@ -69,7 +92,7 @@ def _resolve_openviking_url() -> str:def _load_ov_conf() -> dict:ov_conf_path = resolve_config_path(None, OPENVIKING_CONFIG_ENV, DEFAULT_OV_CONF)if ov_conf_path is None:- _error("未找到 ov.conf,无法读取 root_api_key。")+ _error("未找到 ov.conf,无法读取 OpenViking User API key。")raise SystemExit(1)try:@@ -79,59 +102,89 @@ def _load_ov_conf() -> dict:raise SystemExit(1)-def _parse_accounts(body: str) -> list:- try:- payload = json.loads(body)- except Exception as exc:- _error(f"/api/v1/admin/accounts 返回非 JSON: {exc}")- raise SystemExit(1)+def _write_json_with_backup(path: Path, data: dict) -> None:+ if path.exists():+ backup = path.with_suffix(path.suffix + ".bak")+ with open(path, "r", encoding="utf-8") as src:+ original = src.read()+ with open(backup, "w", encoding="utf-8") as bak:+ bak.write(original)+ with open(path, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ f.write("\n")- accounts = payload.get("result", payload)- if not isinstance(accounts, list):- _error("/api/v1/admin/accounts 返回格式异常。")- raise SystemExit(1)- return accounts+def _sync_bot_identity(account_id: str, user_id: str, api_key: str) -> None:+ ov_conf_path = resolve_config_path(None, OPENVIKING_CONFIG_ENV, DEFAULT_OV_CONF)+ if ov_conf_path is None:+ return+ path = Path(ov_conf_path)+ ov_data = _load_ov_conf()+ ov_server = ov_data.setdefault("bot", {}).setdefault("ov_server", {})+ changed = False+ desired = {+ "api_key_type": "user",+ "api_key": api_key,+ "account_id": account_id,+ "admin_user_id": user_id,+ }+ for key, value in desired.items():+ if str(ov_server.get(key) or "").strip() != value:+ ov_server[key] = value+ changed = True+ if changed:+ _write_json_with_backup(path, ov_data)+ _log(f"已同步 bot.ov_server: api_key_type=user, account_id={account_id}, admin_user_id={user_id}")+++def _resolve_openviking_api_key() -> tuple[str, str]:+ ov_data = _load_ov_conf()+ bot_key = str(((ov_data.get("bot") or {}).get("ov_server") or {}).get("api_key") or "").strip()+ if bot_key:+ return bot_key, "bot.ov_server.api_key"++ path = resolve_config_path(None, OPENVIKING_CLI_CONFIG_ENV, DEFAULT_OVCLI_CONF)+ if path is not None:+ try:+ data = _load_json(Path(path))+ except Exception:+ data = {}+ cli_key = str(data.get("api_key") or "").strip()+ if cli_key:+ return cli_key, "ovcli.conf.api_key"++ if _is_interactive():+ key = _prompt_api_key()+ if key:+ return key, "interactive input"-def _account_exists(accounts: list, account: str) -> bool:- for item in accounts:- if isinstance(item, dict):- account_id = str(item.get("account_id") or item.get("id") or "").strip()- if account_id == account:- return True- elif isinstance(item, str) and item == account:- return True- return False+ _error("未配置 OpenViking User API key,请设置 bot.ov_server.api_key 或 ovcli.conf.api_key 后重试。")+ raise SystemExit(1)-def _prompt_confirm_create(account: str) -> bool:- prompt = f"[preflight] account '{account}' 不存在,是否自动创建该 account? [Y/n]: "+def _parse_health_identity(body: str) -> tuple[str, str, str]:try:- with open("/dev/tty", "r", encoding="utf-8") as tty_in:- print(prompt, end="", flush=True)- answer = tty_in.readline().strip().lower()+ payload = json.loads(body)except Exception as exc:- _error(f"无法读取终端输入: {exc}")+ _error(f"/health 返回非 JSON: {exc}")raise SystemExit(1)- return answer in ("", "y", "yes")--def _ensure_server_and_account_ready(url: str, account: str, interactive: bool) -> None:- ov_data = _load_ov_conf()-- root_key = str((ov_data.get("server") or {}).get("root_api_key") or "").strip()- if not root_key:- _error("server.root_api_key 为空,无法执行服务连通性检查。")+ account_id = str(payload.get("account_id") or "").strip()+ user_id = str(payload.get("user_id") or "").strip()+ role = str(payload.get("role") or "").strip().lower()+ if not account_id or not user_id or not role:+ _error(f"API key 未解析出有效身份,请检查 key 是否正确。/health 返回: {payload}")raise SystemExit(1)+ return account_id, user_id, role- admin_user_id = str(- ((ov_data.get("bot") or {}).get("ov_server") or {}).get("admin_user_id") or "default"- ).strip() or "default"+def _ensure_server_and_user_key_ready(+ url: str, selected_account: str, api_key: str+) -> tuple[str, str]:req = urllib.request.Request(- f"{url}/api/v1/admin/accounts",+ f"{url}/health",headers={- "X-API-Key": root_key,+ "X-API-Key": api_key,"Content-Type": "application/json",},method="GET",@@ -148,57 +201,29 @@ def _ensure_server_and_account_ready(url: str, account: str, interactive: bool)_error(f"OpenViking server 不可用: {exc}")raise SystemExit(1)- accounts = _parse_accounts(body)- if _account_exists(accounts, account):- _log(f"OpenViking server 可用,account '{account}' 已就绪。")- return-- if not interactive:- _error(f"account '{account}' 不存在,非交互模式下不会自动创建。")+ account_id, user_id, role = _parse_health_identity(body)+ if role != "user":+ _error(f"当前 API key 解析为 role={role}。评测需要普通 User key,请更换后重试。")raise SystemExit(1)- if not _prompt_confirm_create(account):- _error("已取消自动创建 account。")- raise SystemExit(1)+ if selected_account and selected_account != "default" and selected_account != account_id:+ _log(+ f"ovcli.conf.account={selected_account} 与 API key 归属 account={account_id} 不一致;"+ "本次评测使用 API key 归属 account。"+ )- create_req = urllib.request.Request(- f"{url}/api/v1/admin/accounts",- headers={- "X-API-Key": root_key,- "Content-Type": "application/json",- },- data=json.dumps({"account_id": account, "admin_user_id": admin_user_id}).encode("utf-8"),- method="POST",- )+ _log(f"OpenViking server 可用,User key 身份: account={account_id}, user={user_id}, role={role}。")+ return account_id, user_id- try:- with urllib.request.urlopen(create_req, timeout=10) as create_resp:- create_body = create_resp.read().decode("utf-8", errors="replace")- except urllib.error.HTTPError as e:- detail = e.read().decode("utf-8", errors="replace")- _error(f"创建 account 失败(HTTP {e.code}): {detail}")- raise SystemExit(1)- except Exception as exc:- _error(f"创建 account 失败: {exc}")- raise SystemExit(1)-- try:- create_payload = json.loads(create_body)- except Exception:- create_payload = {}- if isinstance(create_payload, dict) and create_payload.get("status") == "error":- _error(f"创建 account 失败: {create_payload}")- raise SystemExit(1)-- _log(f"已创建 account '{account}'(admin_user_id={admin_user_id})。")- _log(f"OpenViking server 可用,account '{account}' 已就绪。")---def _write_env_file(path: Path, account: str, openviking_url: str) -> None:+def _write_env_file(+ path: Path, account: str, openviking_url: str, api_key: str, user_id: str+) -> None:with open(path, "w", encoding="utf-8") as f:f.write(f"ACCOUNT={shlex.quote(account)}\n")f.write(f"OPENVIKING_URL={shlex.quote(openviking_url)}\n")+ f.write(f"OPENVIKING_API_KEY={shlex.quote(api_key)}\n")+ f.write(f"OPENVIKING_USER={shlex.quote(user_id)}\n")def main() -> int:@@ -206,20 +231,16 @@ def main() -> int:parser.add_argument("--output-env-file", required=True, help="File path to write ACCOUNT/OPENVIKING_URL exports")args = parser.parse_args()- interactive_env = os.environ.get("INTERACTIVE", "").strip()- if interactive_env:- interactive = interactive_env == "1"- else:- interactive = sys.stdin.isatty() and sys.stdout.isatty()-- account = _resolve_account()+ selected_account = _resolve_configured_account_hint()openviking_url = _resolve_openviking_url()+ api_key, key_source = _resolve_openviking_api_key()- _log(f"本次导入与评测使用 account: {account}")+ _log(f"使用 {key_source} 校验 OpenViking User key")_log(f"本次导入使用 OpenViking URL: {openviking_url}")- _ensure_server_and_account_ready(openviking_url, account, interactive)- _write_env_file(Path(args.output_env_file), account, openviking_url)+ account, user_id = _ensure_server_and_user_key_ready(openviking_url, selected_account, api_key)+ _sync_bot_identity(account, user_id, api_key)+ _write_env_file(Path(args.output_env_file), account, openviking_url, api_key, user_id)return 0diff --git a/benchmark/locomo/vikingbot/run_eval.py b/benchmark/locomo/vikingbot/run_eval.pyindex ef379b511..45129f173 100644--- a/benchmark/locomo/vikingbot/run_eval.py+++ b/benchmark/locomo/vikingbot/run_eval.py@@ -153,16 +153,20 @@ def load_locomo_qa(samples = datafor sample in samples:- original_id = sample.get("sample_id", "")+ original_sample_id = sample.get("sample_id", "")# Find the sample's index in the full datasetif sample_index is not None:try:data_idx = int(sample_index)except ValueError:- data_idx = next(i for i, s in enumerate(data) if s.get("sample_id") == original_id)+ data_idx = next(+ i for i, s in enumerate(data) if s.get("sample_id") == original_sample_id+ )else:- data_idx = next(i for i, s in enumerate(data) if s.get("sample_id") == original_id)- sample_id = f"sample_{data_idx}"+ data_idx = next(+ i for i, s in enumerate(data) if s.get("sample_id") == original_sample_id+ )+ benchmark_sample_id = f"sample_{data_idx}"question_time = get_sample_question_time(sample)qa_items = sample.get("qa", [])@@ -182,10 +186,10 @@ def load_locomo_qa()qa = qa_items[question_index]evidence_list = qa.get("evidence", [])- question_id = f"{sample_id}_qa{question_index}"+ question_id = f"{benchmark_sample_id}_qa{question_index}"qa_list.append({- "sample_id": sample_id,+ "sample_id": benchmark_sample_id,"question_id": question_id,"question_index": question_index,"question": qa["question"],@@ -195,7 +199,7 @@ def load_locomo_qa("evidence_text": get_evidence_text(evidence_list, sample),"question_time": question_time,"speakers": speakers,- "original_sample_id": original_id,+ "original_sample_id": original_sample_id,"is_invalid": qa["question"] in invalid_questionsif invalid_questionselse False,@@ -204,10 +208,10 @@ def load_locomo_qa(else:for q_idx, qa in enumerate(qa_items):evidence_list = qa.get("evidence", [])- question_id = f"{sample_id}_qa{q_idx}"+ question_id = f"{benchmark_sample_id}_qa{q_idx}"qa_list.append({- "sample_id": sample_id,+ "sample_id": benchmark_sample_id,"question_id": question_id,"question_index": q_idx,"question": qa["question"],@@ -217,7 +221,7 @@ def load_locomo_qa("evidence_text": get_evidence_text(evidence_list, sample),"question_time": question_time,"speakers": speakers,- "original_sample_id": original_id,+ "original_sample_id": original_sample_id,"is_invalid": qa["question"] in invalid_questionsif invalid_questionselse False,@@ -232,14 +236,14 @@ def load_locomo_qa(def run_vikingbot_chat(question: str,question_time: str | None = None,- sample_id: str | None = None,+ sender_peer_id: str | None = None,question_id: str | None = None,config: str | None = None,- memory_users: list[str] | None = None,+ memory_peer_ids: list[str] | None = None,) -> tuple[str, dict, float, int, list]:"""执行vikingbot chat命令,返回回答、token使用情况、耗时(秒)、迭代次数、使用的工具列表"""# 先执行 /new 命令清除会话- if sample_id:+ if sender_peer_id:new_cmd = ["vikingbot", "chat"]if config:new_cmd.extend(["--config", config])@@ -249,14 +253,14 @@ def run_vikingbot_chat("/new","-e","--sender",- sample_id,+ sender_peer_id,"--session",question_id,])- if memory_users:- for user in memory_users:- new_cmd.extend(["--memory-user", user])+ if memory_peer_ids:+ for peer_id in memory_peer_ids:+ new_cmd.extend(["--memory-peer", peer_id])try:# print(f'new_cmd={new_cmd}')subprocess.run(new_cmd, capture_output=True, text=True, timeout=300)@@ -274,13 +278,13 @@ def run_vikingbot_chat(if config:cmd.extend(["--config", config])cmd.extend(["-m", input, "-e"])- # 添加 --sender 作为 user_id,--session 作为会话隔离标识- if sample_id:- cmd.extend(["--sender", sample_id, "--session", question_id])- # 添加 --memory-user 参数,指定检索哪些用户的记忆- if memory_users:- for user in memory_users:- cmd.extend(["--memory-user", user])+ # 添加 --sender 作为当前 peer,--session 作为会话隔离标识+ if sender_peer_id:+ cmd.extend(["--sender", sender_peer_id, "--session", question_id])+ # 添加 --memory-peer 参数,指定当前 User 下需要一并检索的额外 peer 记忆+ if memory_peer_ids:+ for peer_id in memory_peer_ids:+ cmd.extend(["--memory-peer", peer_id])start_time = time.time()try:# print(f'cmd={cmd}')@@ -402,9 +406,9 @@ def main():)parser.add_argument("--group-chat",- action="store_true",+ action=argparse.BooleanOptionalAction,default=False,- help="Group-chat mode: pass --memory-peer to vikingbot chat. Default is group-chat mode.",+ help="Group-chat mode: use speaker peers for sender/memory-peer (default: false).",)parser.add_argument("--retry-wrong",@@ -529,19 +533,31 @@ def main():# 使用 question_id 作为 session_id,实现完全独立并行question_id = qa_item.get("question_id")speakers = qa_item.get("speakers", [])+ source_sample_id = qa_item.get("original_sample_id")+ sender_peer_id = source_sample_id+ memory_peer_ids = None+ if args.group_chat:+ sender_peer_id = speakers[0] if speakers else source_sample_id+ memory_peer_ids = speakers[1:] if len(speakers) > 1 else Noneprint(f"Processing {idx}/{total_count}: {question[:60]}...")if question_time:print(f" [time context: {question_time}]")+ if source_sample_id:+ print(f" [sample peer: {source_sample_id}]")if speakers:- print(f" [memory users: {speakers}]")+ print(f" [speakers: {speakers}]")+ if sender_peer_id:+ print(f" [sender peer: {sender_peer_id}]")+ if memory_peer_ids:+ print(f" [memory peers: {memory_peer_ids}]")response, token_usage, time_cost, iteration, tools_used_names = run_vikingbot_chat(question,question_time,- qa_item.get("original_sample_id"),+ sender_peer_id,question_id,args.config,- None if not args.group_chat else speakers,+ memory_peer_ids,)row = {diff --git a/benchmark/locomo/vikingbot/run_full_eval.sh b/benchmark/locomo/vikingbot/run_full_eval.shindex b3efc13d6..4cb1f97b8 100755--- a/benchmark/locomo/vikingbot/run_full_eval.sh+++ b/benchmark/locomo/vikingbot/run_full_eval.sh@@ -7,7 +7,8 @@# ./run_full_eval.sh conv-26 # 评测 sample_id conv-26 所有问题# ./run_full_eval.sh 0 2 # 评测 sample 0 的第 2 题# ./run_full_eval.sh 0 --skip-import # 跳过导入,批量评测-# ./run_full_eval.sh 0 2 --skip-import --group-chat # 跳过导入,单题群聊模式+# ./run_full_eval.sh 0 2 --skip-import # 跳过导入,单题非群聊模式(默认)+# ./run_full_eval.sh 0 2 --group-chat # 单题群聊模式# ./run_full_eval.sh --skip-import --auto-commit # 评测全部,跳过导入,自动提交# ./run_full_eval.sh --retry-wrong result/locomo_result_xxx.csv # 只重跑错题@@ -25,7 +26,8 @@ for arg in "$@"; doecho ""echo "开关参数:"echo " --skip-import 跳过导入步骤,直接使用已导入的数据进行评测"- echo " --group-chat 群聊模式,设置 peer_id/speaker,传 --memory-user"+ echo " --group-chat 群聊模式,使用 speaker 作为 Peer,并传 --memory-peer"+ echo " --no-group-chat 非群聊模式(默认),使用 sample_id 作为 Peer"echo " --auto-commit 自动提交未提交的代码变更,结果文件名带 commit id 和时间戳"echo " --retry-wrong CSV 只重跑指定结果文件中的有效错题(导入相关对话+重新问答)"exit 0@@ -85,7 +87,7 @@ PRECHECK_STATUS=0"$PYTHON_BIN" "$SCRIPT_DIR/preflight_eval_config.py" || PRECHECK_STATUS=$?if [ "$PRECHECK_STATUS" -ne 0 ]; thenif [ "$PRECHECK_STATUS" -eq 2 ]; then- echo "[preflight] 已完成 root_api_key 初始化,请先重启 openviking-server,再重新执行评测脚本。" >&2+ echo "[preflight] 已完成 OpenViking API key 初始化,请重新执行评测脚本。" >&2fiexit "$PRECHECK_STATUS"fi@@ -115,6 +117,8 @@ for arg in "$@"; doSKIP_IMPORT=trueelif [ "$arg" = "--group-chat" ]; thenGROUP_CHAT=true+ elif [ "$arg" = "--no-group-chat" ]; then+ GROUP_CHAT=falseelif [ "$arg" = "--auto-commit" ]; thenAUTO_COMMIT=trueelif [ "$arg" = "--retry-wrong" ]; then@@ -136,7 +140,7 @@ for arg in "$@"; doSKIP_NEXT=truecontinuefi- if [ "$arg" != "--skip-import" ] && [ "$arg" != "--group-chat" ] && [ "$arg" != "--auto-commit" ]; then+ if [ "$arg" != "--skip-import" ] && [ "$arg" != "--group-chat" ] && [ "$arg" != "--no-group-chat" ] && [ "$arg" != "--auto-commit" ]; thenARGS+=("$arg")fidone@@ -145,6 +149,12 @@ doneCOMMON_OPTS=()if [ "$GROUP_CHAT" = "true" ]; thenCOMMON_OPTS+=("--group-chat")+else+ COMMON_OPTS+=("--no-group-chat")+fi+IMPORT_OPTS=()+if [ -n "${OPENVIKING_API_KEY:-}" ]; then+ IMPORT_OPTS+=("--api-key" "$OPENVIKING_API_KEY" "--no-separate-user-by-sample")fiSAMPLE=${ARGS[0]}@@ -152,7 +162,7 @@ QUESTION_INDEX=${ARGS[1]}INPUT_FILE="$SCRIPT_DIR/../data/locomo10.json"# Export for inline Python usage-export SCRIPT_DIR INPUT_FILE RETRY_WRONG ACCOUNT OPENVIKING_URL GROUP_CHAT+export SCRIPT_DIR INPUT_FILE RETRY_WRONG ACCOUNT OPENVIKING_URL OPENVIKING_API_KEY GROUP_CHAT# auto-commit 逻辑if [ "$AUTO_COMMIT" = "true" ]; then@@ -312,6 +322,7 @@ if [ -n "$RETRY_WRONG" ]; then--force-ingest \--account "$ACCOUNT" \--openviking-url "$OPENVIKING_URL" \+ "${IMPORT_OPTS[@]}" \"${COMMON_OPTS[@]}"IMPORT_PERFORMED=true@@ -358,7 +369,7 @@ if [ -z "$SAMPLE" ]; thenelseecho "[1/4] 导入数据..."capture_import_row_start- "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" --input "$INPUT_FILE" --force-ingest --account "$ACCOUNT" --openviking-url "$OPENVIKING_URL" "${COMMON_OPTS[@]}"+ "$PYTHON_BIN" "$SCRIPT_DIR/import_to_ov.py" --input "$INPUT_FILE" --force-ingest --account "$ACCOUNT" --openviking-url "$OPENVIKING_URL" "${IMPORT_OPTS[@]}" "${COMMON_OPTS[@]}"IMPORT_PERFORMED=trueecho "等待 1 分钟..."sleep 60@@ -434,6 +445,7 @@ if [ -n "$QUESTION_INDEX" ]; then--force-ingest \--account "$ACCOUNT" \--openviking-url "$OPENVIKING_URL" \+ "${IMPORT_OPTS[@]}" \"${COMMON_OPTS[@]}"IMPORT_PERFORMED=true@@ -538,6 +550,7 @@ PY--force-ingest \--account "$ACCOUNT" \--openviking-url "$OPENVIKING_URL" \+ "${IMPORT_OPTS[@]}" \"${COMMON_OPTS[@]}"IMPORT_PERFORMED=true@@ -570,7 +583,7 @@ PYelseecho "[3/4] Running judge..."fi- "$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$OUTPUT_FILE" --parallel 5+ "$PYTHON_BIN" "$SCRIPT_DIR/judge.py" --input "$OUTPUT_FILE" --parallel 40# 输出统计结果if [ "$SKIP_IMPORT" = "true" ]; thendiff --git a/bot/README.md b/bot/README.mdindex e79bc7048..7406084a2 100644--- a/bot/README.md+++ b/bot/README.md@@ -145,14 +145,19 @@ Config file: `~/.openviking/ov.conf` (custom path can be set via environment var### OpenViking Server ConfigurationThe bot will connect to the remote OpenViking server. Please start the OpenViking Server before use. By default, the OpenViking server information configured in `ov.conf` is used- OpenViking default startup address is 127.0.0.1:1933-- If `root_api_key` is configured, multi-tenant mode is enabled. For details, see [Multi-tenant](https://github.com/volcengine/OpenViking/blob/main/examples/multi_tenant/README.md)+- New bot deployments should use an OpenViking User API key. `root_api_key` is kept only as a deprecated compatibility field for legacy root-key setups.- OpenViking Server configuration example```json{"server": {"host": "127.0.0.1",- "port": 1933,- "root_api_key": "test"+ "port": 1933+ },+ "bot": {+ "ov_server": {+ "api_key": "<your-openviking-user-api-key>",+ "api_key_type": "user"+ }}}```@@ -178,9 +183,11 @@ All configurations are under the `bot` field in `ov.conf`, with default values f- If not configured, the OpenViking server information configured in `ov.conf` is used by default- If you use a remote OpenViking Server, configure the target service URL and API key here- `server_url`: OpenViking server base URL, for example `https://api.vikingdb.cn-beijing.volces.com/openviking` or `http://localhost:1933`.- - `root_api_key`: API key used by the bot when calling the OpenViking server. Despite the historical field name, this field is also used in the `user` key flow.+ - `api_key`: API key used by the bot when calling the OpenViking server. New configs should set this to an OpenViking User key.+ - `root_api_key`: Deprecated compatibility field for legacy root-key deployments; do not use it for new configs.- `account_id`: Defaults to `default`, which is the OpenViking account ID. All users under the same OpenViking account share resources.- - `api_key_type`: Optional `root` or `user`, default `root`. `root` keeps the original root-key fanout behavior; `user` switches the bot to the user-key flow for OpenViking client calls. For a hosted remote OpenViking service, `user` is usually the recommended choice.+ - `api_key_type`: Optional `root` or `user`, default `user`. `user` uses the OpenViking User-key flow and maps the bot sender to a peer under that User. `root` is only for legacy root-key fanout behavior and should be configured explicitly if still needed.+ Legacy configs that put a root key in `api_key` must add `api_key_type: "root"` or move the key to `root_api_key`; otherwise `api_key` is interpreted as a User key.- exp_write_tools: Optional list of tool names that trigger experience-memory injection before the call (self-evolving agent memory loop, see #2007). Defaults to `["write_file", "edit_file"]`. This only controls the bot-side injection trigger; stored experience generation is governed by OpenViking memory extraction and the active session `memory_policy.memory_types` whitelist.- `recall_exp_first_round_only`: Optional. When `true`, `ContextBuilder._build_user_memory` skips per-turn user/agent experience recall and injects experiences only once on the first user turn. Defaults to `false`.- `exp_recall_limit`: Optional. Number of experiences to retrieve per task during recall. Defaults to `5`.@@ -208,7 +215,7 @@ All configurations are under the `bot` field in `ov.conf`, with default values f},"ov_server": {"server_url": "https://api.vikingdb.cn-beijing.volces.com/openviking",- "root_api_key": "<your-openviking-user-api-key>",+ "api_key": "<your-openviking-user-api-key>","account_id": "default","api_key_type": "user"},diff --git a/bot/README_CN.md b/bot/README_CN.mdindex 313654e4b..6be91fffe 100644--- a/bot/README_CN.md+++ b/bot/README_CN.md@@ -147,15 +147,19 @@ ov chat --no-format### OpenViking Server 配置bot 将连接到远程 OpenViking Server,使用前请先启动 OpenViking Server。默认使用 `ov.conf` 中配置的 OpenViking Server 信息。- OpenViking 默认启动地址为 `127.0.0.1:1933`-- 如果配置了 `root_api_key`,则开启多租户模式。详见 [多租户](https://github.com/volcengine/OpenViking/blob/main/examples/multi_tenant/README.md)+- 新部署的 bot 默认应使用 OpenViking User API key。`root_api_key` 仅作为旧 root-key 部署的废弃兼容字段保留。- OpenViking Server 配置示例```json{"server": {-"host": "127.0.0.1",- "port": 1933,- "root_api_key": "test"+ "port": 1933+ },+ "bot": {+ "ov_server": {+ "api_key": "<your-openviking-user-api-key>",+ "api_key_type": "user"+ }}}```@@ -181,9 +185,11 @@ bot 将连接到远程 OpenViking Server,使用前请先启动 OpenViking Serv- 若不配置,默认使用 `ov.conf` 中配置的 OpenViking Server 信息。- 如果你使用远端 OpenViking Server,可以在这里配置目标服务地址和 API Key。- `server_url`:OpenViking Server 基础地址,例如 `https://api.vikingdb.cn-beijing.volces.com/openviking` 或 `http://localhost:1933`。- - `root_api_key`:bot 调用 OpenViking Server 时使用的 API Key。尽管字段名保留为 `root_api_key`,但在 `user` key 流程下该字段同样会被使用。+ - `api_key`:bot 调用 OpenViking Server 时使用的 API Key。新配置应填写 OpenViking User key。+ - `root_api_key`:旧 root-key 部署的废弃兼容字段;新配置不要再使用。- `account_id`:默认值为 `default`,即 OpenViking 的账号 ID。同一 OpenViking account 下的所有 user 共享 resources。- - `api_key_type`:可选 `root` 或 `user`,默认 `root`。`root` 保留原有的 root-key fanout 行为;`user` 切换 bot 走 user-key 流程调用 OpenViking 客户端。对于托管型远端 OpenViking 服务,通常推荐使用 `user`。+ - `api_key_type`:可选 `root` 或 `user`,默认 `user`。`user` 使用 OpenViking User-key 流程,并将 bot sender 映射为该 User 下的 peer。`root` 仅用于旧 root-key fanout 行为,如仍需使用必须显式配置。+ 旧配置如果把 root key 填在 `api_key`,需要补充 `api_key_type: "root"`,或迁移到 `root_api_key`;否则 `api_key` 会按 User key 解释。- `exp_write_tools`:可选,触发经验记忆注入的工具名列表(自演化 agent memory 循环,详见 #2007)。默认 `["write_file", "edit_file"]`。该配置只控制 bot 侧注入触发时机;已存储 experience 的生成由 OpenViking 记忆抽取和当前 session 的 `memory_policy.memory_types` 白名单控制。- `recall_exp_first_round_only`:可选。为 `true` 时,`ContextBuilder._build_user_memory` 跳过每轮 user/agent 经验召回,仅在首个 user turn 注入一次经验。默认 `false`。- `exp_recall_limit`:可选。召回时每个任务检索的经验条数。默认 `5`。@@ -211,7 +217,7 @@ bot 将连接到远程 OpenViking Server,使用前请先启动 OpenViking Serv},"ov_server": {"server_url": "https://api.vikingdb.cn-beijing.volces.com/openviking",- "root_api_key": "<your-openviking-user-api-key>",+ "api_key": "<your-openviking-user-api-key>","account_id": "default","api_key_type": "user"},diff --git a/bot/tests/test_agent_loop_outcome.py b/bot/tests/test_agent_loop_outcome.pyindex 6588bb38c..6ff1cbcaf 100644--- a/bot/tests/test_agent_loop_outcome.py+++ b/bot/tests/test_agent_loop_outcome.py@@ -257,8 +257,8 @@ async def test_agent_loop_build_prompt_history_uses_ov_context_plus_unsynced_tai})- async def fake_get_ov_client(self, session_key):- del session_key+ async def fake_get_ov_client(self, session_key, openviking_connection=None):+ del session_key, openviking_connectionreturn fake_ov_clientmonkeypatch.setattr(AgentLoop, "_get_ov_client", fake_get_ov_client)@@ -310,8 +310,8 @@ async def test_agent_loop_build_prompt_history_skips_tail_when_sync_cursor_is_pacontext_payload={"messages": [{"role": "user", "content": "OV user turn"}]})- async def fake_get_ov_client(self, session_key):- del self, session_key+ async def fake_get_ov_client(self, session_key, openviking_connection=None):+ del self, session_key, openviking_connectionreturn fake_ov_clientmonkeypatch.setattr(AgentLoop, "_get_ov_client", fake_get_ov_client)@@ -415,8 +415,8 @@ async def test_agent_loop_commits_openviking_before_model_when_pending_tokens_restate["last_synced_local_index"] = len(session.messages) - 1return kwargs- async def fake_get_ov_client(self, session_key):- del self, session_key+ async def fake_get_ov_client(self, session_key, openviking_connection=None):+ del self, session_key, openviking_connectionclass _Client:async def get_session_context(self, session_id, token_budget):@@ -515,8 +515,8 @@ async def test_agent_loop_commits_openviking_before_model_when_memory_window_reasession.metadata["openviking"]["last_commit_performed"] = bool(kwargs["force_commit"])return kwargs- async def fake_get_ov_client(self, session_key):- del self, session_key+ async def fake_get_ov_client(self, session_key, openviking_connection=None):+ del self, session_key, openviking_connectionclass _Client:async def get_session_context(self, session_id, token_budget):@@ -775,6 +775,14 @@ async def test_agent_loop_emits_normalized_response_completed_payload(temp_dir:3,)+ class FakeContextBuilder:+ def __init__(self, *args, **kwargs):+ self.latest_relevant_memories = None++ async def build_messages(self, **kwargs):+ return [{"role": "user", "content": kwargs["current_message"]}]++ monkeypatch.setattr("vikingbot.agent.context.ContextBuilder", FakeContextBuilder)monkeypatch.setattr(AgentLoop, "_run_agent_loop", fake_run_agent_loop)bus = MessageBus()@@ -824,3 +832,67 @@ async def test_agent_loop_emits_normalized_response_completed_payload(temp_dir:session_path = temp_dir / "bot" / "sessions" / "cli__default__session-1.jsonl"metadata = json.loads(session_path.read_text().splitlines()[0])assert metadata["metadata"]["response_facts"][response.response_id] == payload+++async def test_auto_openviking_memory_uses_distinct_tool_name(temp_dir: Path, monkeypatch):+ monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)+ monkeypatch.setattr(AgentLoop, "_register_default_tools", lambda self: None)+ monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", _FakeSubagentManager)++ fake_langfuse = _FakeLangfuseClient()+ monkeypatch.setattr(+ "vikingbot.agent.loop.LangfuseClient.get_instance",+ staticmethod(lambda: fake_langfuse),+ )++ class FakeContextBuilder:+ def __init__(self, *args, **kwargs):+ self.latest_relevant_memories = "remembered fact"++ async def build_messages(self, **kwargs):+ return [{"role": "user", "content": kwargs["current_message"]}]++ async def fake_run_agent_loop(self, **kwargs):+ return (+ "final answer",+ None,+ [],+ {"prompt_tokens": 12, "completion_tokens": 8},+ 1,+ )++ monkeypatch.setattr("vikingbot.agent.context.ContextBuilder", FakeContextBuilder)+ monkeypatch.setattr(AgentLoop, "_run_agent_loop", fake_run_agent_loop)++ bus = MessageBus()+ config = Config(storage_workspace=str(temp_dir))+ loop = AgentLoop(+ bus=bus,+ provider=_FakeProvider(),+ workspace=temp_dir / "workspace",+ config=config,+ )++ session_key = SessionKey(type="cli", channel_id="default", chat_id="session-1")+ response = await loop._process_message(+ InboundMessage(+ session_key=session_key,+ sender_id="user-1",+ content="please help",+ timestamp=datetime.fromisoformat("2026-04-30T00:05:00"),+ )+ )++ assert response is not None+ assert response.tools_used_names == ["auto_memory_search"]++ completed_payload = None+ while bus.outbound_size:+ event = await bus.consume_outbound()+ if event.event_type == OutboundEventType.RESPONSE_COMPLETED:+ completed_payload = event.metadata["response_completed"]++ assert completed_payload is not None+ assert completed_payload["tool_count"] == 1+ assert completed_payload["tools_used_names"] == ["auto_memory_search"]diff --git a/bot/tests/test_gateway_startup_security.py b/bot/tests/test_gateway_startup_security.pyindex 9d5ee7656..89fbca03e 100644--- a/bot/tests/test_gateway_startup_security.py+++ b/bot/tests/test_gateway_startup_security.py@@ -17,6 +17,7 @@ def test_gateway_rejects_non_localhost_without_token(monkeypatch):)monkeypatch.setattr(commands, "ensure_config", lambda _: config)+ monkeypatch.setattr(commands, "validate_openviking_auth", lambda _config: None)def _abort(*args, **kwargs):raise AssertionError("_abort_if_port_in_use should not be reached")@@ -33,6 +34,7 @@ def test_gateway_allows_non_localhost_with_token(monkeypatch):)monkeypatch.setattr(commands, "ensure_config", lambda _: config)+ monkeypatch.setattr(commands, "validate_openviking_auth", lambda _config: None)def _abort(*args, **kwargs):raise _AbortCalleddiff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.pyindex 763ca20a4..522b1fe37 100644--- a/bot/tests/test_openviking_api_key_type.py+++ b/bot/tests/test_openviking_api_key_type.py@@ -5,9 +5,21 @@ from types import SimpleNamespaceimport pytestfrom vikingbot.agent.context import ContextBuilderfrom vikingbot.agent.loop import _is_tool_result_success-from vikingbot.agent.tools.ov_file import VikingGrepTool, VikingMemoryCommitTool, VikingSearchTool-from vikingbot.config.schema import SessionKey+from vikingbot.agent.memory import MemoryStore+from vikingbot.agent.tools.base import ToolContext+from vikingbot.agent.tools.ov_file import (+ VikingGlobTool,+ VikingGrepTool,+ VikingListTool,+ VikingMemoryCommitTool,+ VikingSearchTool,+)+from vikingbot.agent.tools import ov_file as ov_file_module+from vikingbot.cli import commands as commands_module+from vikingbot.config import loader as config_loader_module+from vikingbot.config.schema import OpenVikingConfig, SessionKeyfrom vikingbot.hooks.base import HookContext+from vikingbot.hooks.builtins import openviking_hooks as openviking_hooks_modulefrom vikingbot.hooks.builtins.openviking_hooks import OpenVikingCompactHookfrom vikingbot.openviking_mount import ov_server as ov_server_modulefrom vikingbot.openviking_mount.ov_server import VikingClient@@ -48,11 +60,14 @@ class _DummyHTTPClient:async def batch_add_messages(self, session_id, messages):return {"session_id": session_id, "added": len(messages), "message_count": len(messages)}- async def commit_session(self, session_id, keep_recent_count=0, telemetry=False):+ async def commit_session(+ self, session_id, keep_recent_count=0, telemetry=False, memory_policy=None+ ):return {"session_id": session_id,"status": "committed","keep_recent_count": keep_recent_count,+ "memory_policy": memory_policy,}def session(self, _session_id):@@ -105,6 +120,7 @@ def _make_config(api_key_type: str, mode: str = "remote", **ov_overrides):mode=mode,api_key_type=api_key_type,server_url="http://ov.local",+ api_key="user-key",root_api_key="root-key",account_id="acct",admin_user_id="admin",@@ -130,6 +146,8 @@ def test_viking_client_init_root_mode_sets_account_and_user(monkeypatch):assert client.api_key_type == "root"assert first.kwargs["account"] == "acct"assert first.kwargs["user"] == "admin"+ assert first.kwargs["profile_enabled"] is False+ assert "agent_id" not in first.kwargsdef test_tool_result_success_only_treats_standard_error_prefix_as_failure():@@ -145,8 +163,137 @@ def test_viking_client_init_user_mode_does_not_set_user_or_account(monkeypatch):first = _DummyHTTPClient.instances[0]assert client.api_key_type == "user"+ assert first.kwargs["profile_enabled"] is Falseassert "user" not in first.kwargsassert "account" not in first.kwargs+ assert "agent_id" not in first.kwargs+++def test_openviking_config_api_key_type_empty_values_are_inferred():+ assert OpenVikingConfig(api_key_type=None, api_key="user-key").api_key_type == "user"+ assert OpenVikingConfig(api_key_type="", api_key="user-key").api_key_type == "user"+ assert OpenVikingConfig(api_key_type=None, root_api_key="root-key").api_key_type == "root"+ assert OpenVikingConfig(api_key_type="", root_api_key="root-key").api_key_type == "root"+++def test_user_key_current_memory_targets_use_current_user_shorthand(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))++ client = VikingClient()++ assert client.build_current_memory_target_uris(peer_ids=["sender-1"]) == [+ "viking://user/memories/",+ "viking://user/peers/sender-1/memories/",+ ]+++def test_ov_server_legacy_root_api_key_takes_precedence_over_ovcli(monkeypatch):+ bot_data = {"root_api_key": "bot-user-key"}+ ov_data = {"root_api_key": "server-root-key"}+ monkeypatch.setattr(+ config_loader_module,+ "load_ovcli_config",+ lambda: SimpleNamespace(api_key="stale-ovcli-key"),+ )++ config_loader_module._merge_ov_server_config(bot_data, ov_data)++ assert bot_data["mode"] == "remote"+ assert bot_data["api_key"] == "bot-user-key"+ assert bot_data["api_key_type"] == "root"+++def test_ov_server_top_level_root_api_key_backfills_legacy_root_mode(monkeypatch):+ bot_data = {}+ ov_data = {"root_api_key": "server-root-key"}+ monkeypatch.setattr(+ config_loader_module,+ "load_ovcli_config",+ lambda: SimpleNamespace(api_key="stale-ovcli-key"),+ )++ config_loader_module._merge_ov_server_config(bot_data, ov_data)++ assert bot_data["mode"] == "remote"+ assert bot_data["api_key"] == "server-root-key"+ assert bot_data["root_api_key"] == "server-root-key"+ assert bot_data["api_key_type"] == "root"+++def test_ov_server_api_key_implies_remote_mode(monkeypatch):+ bot_data = {"api_key": "bot-user-key"}+ monkeypatch.setattr(+ config_loader_module,+ "load_ovcli_config",+ lambda: SimpleNamespace(api_key="stale-ovcli-key"),+ )++ config_loader_module._merge_ov_server_config(bot_data, {})++ assert bot_data["mode"] == "remote"+ assert bot_data["api_key"] == "bot-user-key"+++def test_validate_openviking_auth_allows_local_mode():+ config = SimpleNamespace(ov_server=SimpleNamespace(mode="local", api_key="", root_api_key=""))++ config_loader_module.validate_openviking_auth(config)+++def test_validate_openviking_auth_allows_api_key():+ config = SimpleNamespace(+ ov_server=SimpleNamespace(mode="remote", api_key="user-key", root_api_key="")+ )++ config_loader_module.validate_openviking_auth(config)+++def test_validate_openviking_auth_allows_legacy_root_api_key():+ config = SimpleNamespace(+ ov_server=SimpleNamespace(mode="remote", api_key="", root_api_key="root-key")+ )++ config_loader_module.validate_openviking_auth(config)+++def test_validate_openviking_auth_exits_with_migration_hint(capsys):+ config = SimpleNamespace(ov_server=SimpleNamespace(mode="remote", api_key="", root_api_key=""))++ with pytest.raises(SystemExit):+ config_loader_module.validate_openviking_auth(config)++ captured = capsys.readouterr()+ assert "bot.ov_server.api_key" in captured.err+ assert "User API key" in captured.err+ assert "root_api_key is deprecated" in captured.err+++def test_memory_user_cli_option_warns_at_runtime(capsys):+ commands_module._warn_deprecated_memory_user(["legacy-user"])++ captured = capsys.readouterr()+ assert "--memory-user is deprecated" in captured.err+ assert "--memory-peer" in captured.err+++async def test_user_key_mode_skips_admin_namespace_policy_lookup(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))++ client = VikingClient()++ async def _must_not_call_admin_api():+ raise AssertionError("user key mode must not call admin namespace policy API")++ monkeypatch.setattr(client.client, "admin_list_accounts", _must_not_call_admin_api)++ await client._load_namespace_policy()++ assert client._namespace_policy_loaded is True+ assert client._namespace_policy == {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+ }def test_viking_client_request_connection_uses_active_identity(monkeypatch):@@ -176,9 +323,7 @@ def test_viking_client_request_connection_uses_active_identity(monkeypatch):assert client._apikey_manager is Noneassert client._namespace_policy_loaded is Trueassert client.should_sender_fanout() is False- assert (- client._memory_target_uri(None) == "viking://user/anonymous/agent/web-playground/memories/"- )+ assert client._memory_target_uri(None) == "viking://user/memories/"assert first.kwargs == {"url": "http://studio.local","api_key": "anonymous-key",@@ -298,7 +443,7 @@ async def test_request_connection_search_memory_uses_request_client_only(monkeypassert result == {"user_memory": [], "agent_memory": []}first = _DummyHTTPClient.instances[0]assert len(first.find_calls) == 2- assert first.find_calls[0][1]["target_uri"] == "viking://user/anonymous/memories/"+ assert first.find_calls[0][1]["target_uri"] == "viking://user/memories/"assert first.find_calls[1][1]["target_uri"] == "viking://agent/web-playground/memories/"@@ -340,6 +485,9 @@ async def test_compact_hook_user_mode_commits_once(monkeypatch):def should_sender_fanout(self):return False+ def session_owner_user_id(self):+ return None+async def commit(self, session_id, messages, user_id=None):self.calls.append((session_id, user_id, len(messages)))return {"success": "committed"}@@ -375,7 +523,7 @@ async def test_compact_hook_user_mode_commits_once(monkeypatch):@pytest.mark.asyncio-async def test_compact_hook_session_context_commits_admin_and_sender_sessions(monkeypatch):+async def test_compact_hook_session_context_commits_single_session_with_peer_messages(monkeypatch):from vikingbot.hooks.builtins import openviking_hooks as hooks_modulemonkeypatch.setattr(@@ -396,6 +544,9 @@ async def test_compact_hook_session_context_commits_admin_and_sender_sessions(moself.session_calls = []self.commit_calls = []+ def session_owner_user_id(self):+ return "admin"+async def append_messages(self,session_id,@@ -449,23 +600,16 @@ async def test_compact_hook_session_context_commits_admin_and_sender_sessions(moassert result["success"] is Trueassert result["admin_result"]["committed"] is True- assert result["users_count"] == 2- assert fake_client.append_calls[-1] == (- "cli__default__chat-1",- ["admin answer", "u1 asks", "u1 reply", "u2 asks"],- "admin",- "admin",- )- assert (- "cli__default__chat-1_u1",- ["u1 asks", "u1 reply"],- "u1",- "u1",- ) in fake_client.append_calls- assert ("cli__default__chat-1_u2", ["u2 asks"], "u2", "u2") in fake_client.append_calls- assert ("cli__default__chat-1", 2, "admin") in fake_client.commit_calls- assert ("cli__default__chat-1_u1", 2, "u1") in fake_client.commit_calls- assert ("cli__default__chat-1_u2", 2, "u2") in fake_client.commit_calls+ assert result["users_count"] == 0+ assert fake_client.append_calls == [+ (+ "cli__default__chat-1",+ ["admin answer", "u1 asks", "u1 reply", "u2 asks"],+ None,+ "admin",+ )+ ]+ assert fake_client.commit_calls == [("cli__default__chat-1", 2, "admin")]state = session.metadata["openviking"]assert state["session_id"] == "cli__default__chat-1"@@ -530,6 +674,9 @@ async def test_compact_hook_force_commit_does_not_resync_already_synced_messagesself.append_calls = []self.commit_calls = []+ def session_owner_user_id(self):+ return "admin"+async def append_messages(self,session_id,@@ -577,18 +724,14 @@ async def test_compact_hook_force_commit_does_not_resync_already_synced_messagesresult = await hook.execute(context, session=session, force_commit=True)assert result["success"] is True- assert fake_client.append_calls == [- ("cli__default__chat-1_u1", ["new reply"]),- ("cli__default__chat-1", ["new reply"]),- ]- assert ("cli__default__chat-1", 2, "admin") in fake_client.commit_calls- assert ("cli__default__chat-1_u1", 2, "u1") in fake_client.commit_calls+ assert fake_client.append_calls == [("cli__default__chat-1", ["new reply"])]+ assert fake_client.commit_calls == [("cli__default__chat-1", 2, "admin")]assert session.metadata["openviking"]["last_synced_local_index"] == 1assert session.metadata["openviking"]["last_commit_local_index"] == 1@pytest.mark.asyncio-async def test_compact_hook_force_commit_commits_sender_sessions_without_unsynced_messages(+async def test_compact_hook_force_commit_commits_current_session_without_unsynced_messages(monkeypatch,):from vikingbot.hooks.builtins import openviking_hooks as hooks_module@@ -609,6 +752,9 @@ async def test_compact_hook_force_commit_commits_sender_sessions_without_unsynceself.append_calls = []self.commit_calls = []+ def session_owner_user_id(self):+ return "admin"+async def append_messages(self,session_id,@@ -657,14 +803,12 @@ async def test_compact_hook_force_commit_commits_sender_sessions_without_unsynceassert result["success"] is Trueassert fake_client.append_calls == []- assert ("cli__default__chat-1", 2, "admin") in fake_client.commit_calls- assert ("cli__default__chat-1_u1", 2, "u1") in fake_client.commit_calls- assert ("cli__default__chat-1_u2", 2, "u2") in fake_client.commit_calls+ assert fake_client.commit_calls == [("cli__default__chat-1", 2, "admin")]assert session.metadata["openviking"]["last_commit_performed"] is True@pytest.mark.asyncio-async def test_compact_hook_session_context_sender_failure_does_not_advance_sync_cursor(+async def test_compact_hook_session_context_append_failure_does_not_advance_sync_cursor(monkeypatch,):from vikingbot.hooks.builtins import openviking_hooks as hooks_module@@ -685,6 +829,9 @@ async def test_compact_hook_session_context_sender_failure_does_not_advance_syncself.append_calls = []self.commit_calls = []+ def session_owner_user_id(self):+ return "admin"+async def append_messages(self,session_id,@@ -693,8 +840,8 @@ async def test_compact_hook_session_context_sender_failure_does_not_advance_syncsession_user_id=None,):self.append_calls.append((session_id, [message["content"] for message in messages]))- if session_id.endswith("_u1"):- raise RuntimeError("sender append failed")+ if session_id == "cli__default__chat-1":+ raise RuntimeError("session append failed")return {"session_id": session_id, "added": len(messages)}async def get_session(self, session_id, user_id=None):@@ -730,14 +877,14 @@ async def test_compact_hook_session_context_sender_failure_does_not_advance_syncresult = await hook.execute(context, session=session)assert result["success"] is False- assert "sender append failed" in result["error"]- assert fake_client.append_calls == [("cli__default__chat-1_u1", ["u1 asks", "u1 reply"])]+ assert "session append failed" in result["error"]+ assert fake_client.append_calls == [("cli__default__chat-1", ["u1 asks", "u1 reply"])]assert fake_client.commit_calls == []state = session.metadata["openviking"]assert state["last_sync_status"] == "error"- assert "sender append failed" in state["last_sync_error"]+ assert "session append failed" in state["last_sync_error"]assert state["last_synced_local_index"] == -1- assert state["last_commit_performed"] is False+ assert state.get("last_commit_performed") is not True@pytest.mark.asyncio@@ -762,6 +909,9 @@ async def test_compact_hook_session_context_commits_when_message_threshold_reachself.append_calls = []self.commit_calls = []+ def session_owner_user_id(self):+ return "admin"+async def append_messages(self,session_id,@@ -812,17 +962,13 @@ async def test_compact_hook_session_context_commits_when_message_threshold_reachassert result["success"] is Trueassert result["admin_result"]["committed"] is True- assert fake_client.append_calls == [- ("cli__default__chat-1_u1", ["m3"]),- ("cli__default__chat-1", ["m3"]),- ]- assert ("cli__default__chat-1", 2, "admin") in fake_client.commit_calls- assert ("cli__default__chat-1_u1", 2, "u1") in fake_client.commit_calls+ assert fake_client.append_calls == [("cli__default__chat-1", ["m3"])]+ assert fake_client.commit_calls == [("cli__default__chat-1", 2, "admin")]assert session.metadata["openviking"]["last_commit_local_index"] == 2@pytest.mark.asyncio-async def test_compact_hook_sender_commit_failure_does_not_commit_admin_and_retry_dedupes(+async def test_compact_hook_session_commit_failure_retries_without_resyncing_messages(monkeypatch,):from vikingbot.hooks.builtins import openviking_hooks as hooks_module@@ -842,7 +988,10 @@ async def test_compact_hook_sender_commit_failure_does_not_commit_admin_and_retrdef __init__(self):self.append_calls = []self.commit_calls = []- self.fail_sender_commit = True+ self.fail_session_commit = True++ def session_owner_user_id(self):+ return "admin"async def append_messages(self,@@ -859,8 +1008,8 @@ async def test_compact_hook_sender_commit_failure_does_not_commit_admin_and_retrasync def commit_session(self, session_id, keep_recent_count=0, user_id=None):self.commit_calls.append((session_id, keep_recent_count, user_id))- if session_id.endswith("_u1") and self.fail_sender_commit:- raise RuntimeError("sender commit failed")+ if session_id == "cli__default__chat-1" and self.fail_session_commit:+ raise RuntimeError("session commit failed")return {"session_id": session_id, "status": "accepted"}fake_client = _FakeClient()@@ -887,19 +1036,15 @@ async def test_compact_hook_sender_commit_failure_does_not_commit_admin_and_retrfirst = await hook.execute(context, session=session)assert first["success"] is False- assert "sender commit failed" in first["error"]- assert fake_client.append_calls == [- ("cli__default__chat-1_u1", ["u1 asks", "u1 reply"]),- ("cli__default__chat-1", ["u1 asks", "u1 reply"]),- ]- assert fake_client.commit_calls == [("cli__default__chat-1_u1", 2, "u1")]+ assert "session commit failed" in first["error"]+ assert fake_client.append_calls == [("cli__default__chat-1", ["u1 asks", "u1 reply"])]+ assert fake_client.commit_calls == [("cli__default__chat-1", 2, "admin")]state = session.metadata["openviking"]assert state["last_sync_status"] == "error"assert state["last_synced_local_index"] == 1- assert state["last_sender_synced_local_indexes"] == {"u1": 1}- assert state["last_commit_performed"] is False+ assert state.get("last_commit_performed") is not True- fake_client.fail_sender_commit = False+ fake_client.fail_session_commit = Falsefake_client.append_calls.clear()fake_client.commit_calls.clear()@@ -907,10 +1052,7 @@ async def test_compact_hook_sender_commit_failure_does_not_commit_admin_and_retrassert second["success"] is Trueassert fake_client.append_calls == []- assert fake_client.commit_calls == [- ("cli__default__chat-1_u1", 2, "u1"),- ("cli__default__chat-1", 2, "admin"),- ]+ assert fake_client.commit_calls == [("cli__default__chat-1", 2, "admin")]assert session.metadata["openviking"]["last_commit_performed"] is True@@ -936,6 +1078,9 @@ async def test_compact_hook_session_context_skips_message_threshold_after_recentself.append_calls = []self.commit_calls = []+ def session_owner_user_id(self):+ return "admin"+async def append_messages(self,session_id,@@ -986,10 +1131,7 @@ async def test_compact_hook_session_context_skips_message_threshold_after_recentassert result["success"] is Trueassert result["admin_result"]["committed"] is False- assert fake_client.append_calls == [- ("cli__default__chat-1_u1", ["m3"]),- ("cli__default__chat-1", ["m3"]),- ]+ assert fake_client.append_calls == [("cli__default__chat-1", ["m3"])]assert fake_client.commit_calls == []@@ -1031,11 +1173,7 @@ async def test_viking_client_normalizes_system_tool_and_tool_result_messages(mon"assistant","assistant",]- assert [message["peer_id"] for message in normalized] == [- "admin",- "admin",- "admin",- ]+ assert all("peer_id" not in message for message in normalized)assert normalized[0]["content"] == "system context"assert normalized[1]["content"] == "tool response"assert normalized[2]["content"] == "assistant answer"@@ -1142,7 +1280,7 @@ def test_openviking_grep_schema_requires_single_string_pattern():@pytest.mark.asyncio-async def test_openviking_grep_passes_admin_user_id(monkeypatch):+async def test_openviking_grep_keeps_explicit_resource_uri(monkeypatch):tool = VikingGrepTool()calls = []@@ -1173,11 +1311,73 @@ async def test_openviking_grep_passes_admin_user_id(monkeypatch):case_insensitive=True,)- assert calls == [("viking://resources/", "hello", True, "admin")]+ assert calls == [("viking://resources/", "hello", True, None)]assert "Found 1 match for pattern 'hello':" in resultassert "viking://resources/doc.md" in result+def test_openviking_tool_memory_peer_ids_exclude_legacy_memory_users():+ tool = VikingSearchTool()++ peer_ids = tool._memory_peer_ids(+ SimpleNamespace(+ sender_id="sender-1",+ memory_peer_ids=["speaker-a"],+ memory_user_ids=["legacy-user"],+ )+ )++ assert peer_ids == ["sender-1", "speaker-a"]+++def test_tool_context_syncs_legacy_memory_user_alias():+ from_legacy = ToolContext(memory_user_ids=["legacy-user"])+ from_owner = ToolContext(memory_owner_user_ids=["owner-user"])++ assert from_legacy.memory_owner_user_ids == ["legacy-user"]+ assert from_owner.memory_user_ids == ["owner-user"]+++async def test_viking_memory_context_keeps_legacy_users_separate_from_peers(+ monkeypatch, tmp_path+):+ calls = []++ class _FakeClient:+ async def search_memory(self, **kwargs):+ calls.append(kwargs)+ return []++ async def close(self):+ return None++ async def _fake_create(**_kwargs):+ return _FakeClient()++ monkeypatch.setattr("vikingbot.agent.memory.load_config", lambda: _make_config("root"))+ monkeypatch.setattr("vikingbot.agent.memory.VikingClient.create", _fake_create)++ store = MemoryStore(tmp_path)++ await store.get_viking_memory_context(+ current_message="hello",+ workspace_id="workspace",+ sender_id="sender-1",+ peer_ids=["speaker-a"],+ user_ids=["legacy-user"],+ )++ assert calls == [+ {+ "query": "hello",+ "user_ids": ["legacy-user"],+ "peer_ids": ["sender-1", "speaker-a"],+ "limit": 10,+ }+ ]++@pytest.mark.asyncioasync def test_openviking_search_uses_user_namespace(monkeypatch):monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("root"))@@ -1186,8 +1386,8 @@ async def test_openviking_search_uses_user_namespace(monkeypatch):calls = []- async def _search(query, target_uri=None, limit=20, user_id=None):- calls.append((target_uri, user_id))+ async def _search(query, target_uri=None, limit=20, user_id=None, peer_id=None):+ calls.append((target_uri, user_id, peer_id))return {"memories": [{"uri": target_uri, "abstract": "a", "score": 0.9, "is_leaf": True}]}async def _fake_get_client(_tool_context):@@ -1196,11 +1396,15 @@ async def test_openviking_search_uses_user_namespace(monkeypatch):monkeypatch.setattr(client, "search", _search)monkeypatch.setattr(tool, "_get_client", _fake_get_client)- tool_context = SimpleNamespace(workspace_id="workspace", memory_user_ids=["sender-1"])+ tool_context = SimpleNamespace(workspace_id="workspace", memory_owner_user_ids=["sender-1"])result = await tool.execute(tool_context, query="hello")assert "sender-1/memories" in result- assert calls == [("viking://user/sender-1/memories/", "admin")]+ assert calls == [+ ("viking://resources/", None, None),+ ("viking://user/sender-1/memories/", None, None),+ ("viking://user/sender-1/skills/", None, None),+ ]@pytest.mark.asyncio@@ -1211,8 +1415,8 @@ async def test_openviking_search_user_key_mode_uses_current_user_namespace(monkecalls = []- async def _search(query, target_uri=None, limit=20, user_id=None):- calls.append((target_uri, user_id))+ async def _search(query, target_uri=None, limit=20, user_id=None, peer_id=None):+ calls.append((target_uri, user_id, peer_id))return {"memories": [{"uri": target_uri, "abstract": "a", "score": 0.9, "is_leaf": True}]}async def _fake_get_client(_tool_context):@@ -1222,12 +1426,162 @@ async def test_openviking_search_user_key_mode_uses_current_user_namespace(monkemonkeypatch.setattr(tool, "_get_client", _fake_get_client)tool_context = SimpleNamespace(- workspace_id="workspace", memory_user_ids=["sender-1", "sender-2"]+ workspace_id="workspace",+ sender_id="sender-0",+ memory_peer_ids=["sender-1", "sender-2"],)result = await tool.execute(tool_context, query="hello")- assert "viking://user/memories/" in result- assert calls == [("viking://user/memories/", "admin")]+ assert "sender-1/memories" in result+ assert calls == [+ ("", None, "sender-0"),+ ("viking://user/peers/sender-1/memories/", None, None),+ ("viking://user/peers/sender-2/memories/", None, None),+ ]+++async def test_openviking_grep_default_memory_expands_current_peer(monkeypatch):+ tool = VikingGrepTool()+ calls = []++ class _FakeClient:+ def _memory_target_uri(self, _user_id=None):+ return "viking://user/memories/"++ def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):+ uris = ["viking://user/memories/"] if include_self else []+ uris.extend(f"viking://user/default/peers/{peer_id}/memories/" for peer_id in peer_ids or [])+ return uris++ async def grep(self, uri, pattern, case_insensitive=False, user_id=None):+ calls.append((uri, pattern, case_insensitive, user_id))+ return {"matches": []}++ async def _fake_get_client(_tool_context):+ return _FakeClient()++ monkeypatch.setattr(tool, "_get_client", _fake_get_client)++ await tool.execute(+ SimpleNamespace(workspace_id="workspace", sender_id="sender-0"),+ uri="viking://user/memories/",+ pattern="hello",+ )++ assert calls == [+ ("viking://user/memories/", "hello", False, None),+ ("viking://user/default/peers/sender-0/memories/", "hello", False, None),+ ]+++async def test_openviking_list_default_memory_expands_current_peer(monkeypatch):+ tool = VikingListTool()+ calls = []++ class _FakeClient:+ def _memory_target_uri(self, _user_id=None):+ return "viking://user/memories/"++ def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):+ uris = ["viking://user/memories/"] if include_self else []+ uris.extend(f"viking://user/default/peers/{peer_id}/memories/" for peer_id in peer_ids or [])+ return uris++ async def list_resources(self, path=None, recursive=False):+ calls.append((path, recursive))+ return []++ async def _fake_get_client(_tool_context):+ return _FakeClient()++ monkeypatch.setattr(tool, "_get_client", _fake_get_client)++ await tool.execute(+ SimpleNamespace(workspace_id="workspace", sender_id="sender-0"),+ uri="viking://user/memories/",+ )++ assert calls == [+ ("viking://user/memories/", False),+ ("viking://user/default/peers/sender-0/memories/", False),+ ]+++async def test_openviking_glob_root_adds_current_peer_memory(monkeypatch):+ tool = VikingGlobTool()+ calls = []++ class _FakeClient:+ def _memory_target_uri(self, _user_id=None):+ return "viking://user/memories/"++ def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):+ uris = ["viking://user/memories/"] if include_self else []+ uris.extend(f"viking://user/default/peers/{peer_id}/memories/" for peer_id in peer_ids or [])+ return uris++ async def glob(self, pattern, uri="viking://"):+ calls.append((pattern, uri))+ return {"matches": [], "count": 0}++ async def _fake_get_client(_tool_context):+ return _FakeClient()++ monkeypatch.setattr(tool, "_get_client", _fake_get_client)++ await tool.execute(+ SimpleNamespace(workspace_id="workspace", sender_id="sender-0"),+ pattern="*.md",+ )++ assert calls == [+ ("*.md", "viking://resources/"),+ ("*.md", "viking://user/memories/"),+ ("*.md", "viking://user/skills/"),+ ("*.md", "viking://user/default/peers/sender-0/memories/"),+ ]+++async def test_openviking_glob_root_uses_namespaced_self_targets_for_root_key(monkeypatch):+ tool = VikingGlobTool()+ calls = []++ class _FakeClient:+ def _memory_target_uri(self, _user_id=None):+ return "viking://user/admin/memories/"++ def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):+ uris = ["viking://user/admin/memories/"] if include_self else []+ uris.extend(+ f"viking://user/admin/peers/{peer_id}/memories/"+ for peer_id in peer_ids or []+ )+ return uris++ async def glob(self, pattern, uri="viking://"):+ calls.append((pattern, uri))+ return {"matches": [], "count": 0}++ async def _fake_get_client(_tool_context):+ return _FakeClient()++ monkeypatch.setattr(tool, "_get_client", _fake_get_client)++ await tool.execute(+ SimpleNamespace(workspace_id="workspace", sender_id="sender-0"),+ pattern="*.md",+ )++ assert calls == [+ ("*.md", "viking://resources/"),+ ("*.md", "viking://user/admin/memories/"),+ ("*.md", "viking://user/admin/skills/"),+ ("*.md", "viking://user/admin/peers/sender-0/memories/"),+ ]def test_openviking_search_description_allows_follow_up_memory_queries():@@ -1261,6 +1615,36 @@ async def test_context_reminds_agent_to_search_current_memory_question(tmp_path)assert "A previous empty search result does not prove" in user_info+async def test_context_loads_profiles_for_memory_peers(tmp_path):+ calls = {"sender": [], "peers": []}++ class _ProfileMemory:+ async def get_viking_peer_profile(self, **kwargs):+ calls["sender"].append(kwargs["peer_id"])+ return "sender profile"++ async def get_viking_peer_profiles(self, **kwargs):+ calls["peers"].append(kwargs["peer_ids"])+ return "\n".join(f"profile for {peer_id}" for peer_id in kwargs["peer_ids"])++ context = ContextBuilder(workspace=tmp_path, sender_id="sender-1")+ context._memory = _ProfileMemory()++ system_prompt = await context.build_system_prompt(+ session_key=SessionKey(type="cli", channel_id="default", chat_id="chat-1"),+ ov_tools_enable=True,+ profile_user_list=["speaker-a"],+ memory_peer_ids=["sender-1", "speaker-a", "speaker-b"],+ )++ assert calls["sender"] == ["sender-1"]+ assert calls["peers"] == [["speaker-a", "speaker-b"]]+ assert "sender profile" in system_prompt+ assert "profile for speaker-a" in system_prompt+ assert "profile for speaker-b" in system_prompt++@pytest.mark.asyncioasync def test_openviking_memory_commit_prefers_sender_in_static_multi_user_bot(monkeypatch):tool = VikingMemoryCommitTool()@@ -1269,8 +1653,8 @@ async def test_openviking_memory_commit_prefers_sender_in_static_multi_user_bot(class _FakeClient:admin_user_id = "default"- async def commit(self, session_id, messages, user_id):- calls.append((session_id, messages, user_id))+ async def commit(self, session_id, messages, peer_id=None):+ calls.append((session_id, messages, peer_id))return {"commit": {"archived": False}}async def _fake_get_client(_tool_context):@@ -1278,24 +1662,92 @@ async def test_openviking_memory_commit_prefers_sender_in_static_multi_user_bot(monkeypatch.setattr(tool, "_get_client", _fake_get_client)+ tool_context = SimpleNamespace(+ workspace_id="workspace",+ sender_id="alice",+ session_key=SimpleNamespace(safe_name=lambda: "session-1"),+ openviking_connection=None,+ )result = await tool.execute(- SimpleNamespace(- workspace_id="workspace",- sender_id="alice",- session_key=SimpleNamespace(safe_name=lambda: "session-1"),- openviking_connection=None,- ),+ tool_context,messages=[{"role": "user", "content": "remember this"}],)+ second_result = await tool.execute(+ tool_context,+ messages=[{"role": "user", "content": "remember this again"}],+ )- assert json.loads(result)["status"] == "success"- assert calls == [- (- "session-1",- [{"role": "user", "content": "remember this"}],- "alice",- )- ]+ payload = json.loads(result)+ second_payload = json.loads(second_result)+ assert payload["status"] == "success"+ assert second_payload["status"] == "success"+ assert calls[0] == (+ payload["memory_commit_session_id"],+ [{"role": "user", "content": "remember this"}],+ "alice",+ )+ assert calls[1] == (+ second_payload["memory_commit_session_id"],+ [{"role": "user", "content": "remember this again"}],+ "alice",+ )+ assert payload["session_id"] == payload["memory_commit_session_id"]+ assert payload["source_session_id"] == "session-1"+ assert payload["memory_commit_session_id"].startswith("session-1__memory_commit__")+ assert second_payload["source_session_id"] == "session-1"+ assert second_payload["memory_commit_session_id"].startswith("session-1__memory_commit__")+ assert second_payload["memory_commit_session_id"] != payload["memory_commit_session_id"]+++async def test_openviking_hook_clients_are_cached_by_workspace(monkeypatch):+ openviking_hooks_module._global_clients.clear()+ created_workspace_ids = []++ class _FakeVikingClient:+ @classmethod+ async def create(cls, workspace_id=None):+ created_workspace_ids.append(workspace_id)+ return SimpleNamespace(workspace_id=workspace_id)++ monkeypatch.setattr(openviking_hooks_module, "VikingClient", _FakeVikingClient)++ ws_a_first = await openviking_hooks_module.get_global_client("workspace-a")+ ws_a_second = await openviking_hooks_module.get_global_client("workspace-a")+ ws_b = await openviking_hooks_module.get_global_client("workspace-b")++ assert ws_a_first is ws_a_second+ assert ws_a_first is not ws_b+ assert created_workspace_ids == ["workspace-a", "workspace-b"]+ openviking_hooks_module._global_clients.clear()+++async def test_openviking_tool_clients_are_cached_by_workspace(monkeypatch):+ created_workspace_ids = []++ class _FakeVikingClient:+ @classmethod+ async def create(cls, workspace_id=None, **kwargs):+ created_workspace_ids.append(workspace_id)+ return SimpleNamespace(workspace_id=workspace_id)++ monkeypatch.setattr(ov_file_module, "VikingClient", _FakeVikingClient)+ tool = VikingSearchTool()++ ws_a_first = await tool._get_client(+ SimpleNamespace(workspace_id="workspace-a", openviking_connection=None)+ )+ ws_a_second = await tool._get_client(+ SimpleNamespace(workspace_id="workspace-a", openviking_connection=None)+ )+ ws_b = await tool._get_client(+ SimpleNamespace(workspace_id="workspace-b", openviking_connection=None)+ )++ assert ws_a_first is ws_a_second+ assert ws_a_first is not ws_b+ assert created_workspace_ids == ["workspace-a", "workspace-b"]@pytest.mark.asyncio@@ -1306,7 +1758,7 @@ async def test_openviking_request_connection_client_is_closed_after_tool_call(moresult = await tool.execute(SimpleNamespace(workspace_id="workspace",- memory_user_ids=None,+ memory_peer_ids=None,openviking_connection={"server_url": "http://studio.local","api_key": "user-key",diff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.pyindex 615aa702b..865cf2e1b 100644--- a/bot/vikingbot/agent/context.py+++ b/bot/vikingbot/agent/context.py@@ -78,11 +78,23 @@ class ContextBuilder:return self.sandbox_manager.to_workspace_id(session_key)return session_key.safe_name()+ @staticmethod+ def _dedupe_ids(values: list[str] | None, *, exclude: set[str] | None = None) -> list[str]:+ exclude = exclude or set()+ normalized: list[str] = []+ for value in values or []:+ value_str = str(value).strip()+ if value_str and value_str not in exclude and value_str not in normalized:+ normalized.append(value_str)+ return normalized+async def build_system_prompt(self,session_key: SessionKey,ov_tools_enable: bool = True,profile_user_list: list[str] | None = None,+ memory_peer_ids: list[str] | None = None,+ memory_owner_user_ids: list[str] | None = None,) -> str:"""Build the system prompt from bootstrap files, memory, and skills.@@ -90,7 +102,9 @@ class ContextBuilder:Args:session_key: Session key for the context.ov_tools_enable: Whether to enable OpenViking tools and memory.- profile_user_list: List of additional user IDs to fetch profiles for.+ profile_user_list: Deprecated list of additional peer IDs to fetch profiles for.+ memory_peer_ids: Peer IDs used for memory retrieval; profiles are fetched too.+ memory_owner_user_ids: Deprecated legacy owner-user IDs used for root-key fanout.Returns:Complete system prompt.@@ -139,27 +153,35 @@ Skills with available="false" need dependencies installed first - you can try in{skills_summary}""")- # Viking user profile (only if ov tools are enabled)+ # Viking peer profile (only if ov tools are enabled). In the current+ # OpenViking identity model, the bot API key owns the User, and the+ # message sender is represented as a peer under that User.if ov_tools_enable:- # Fetch current user's profile+ # Fetch current sender's peer profilestart = _time.time()- profile = await self.memory.get_viking_user_profile(+ profile = await self.memory.get_viking_peer_profile(workspace_id=workspace_id,- user_id=self._sender_id,+ peer_id=self._sender_id,openviking_connection=self._openviking_connection,)cost = round(_time.time() - start, 2)logger.info(- f"[READ_USER_PROFILE]: cost {cost}s, profile={profile[:50] if profile else 'None'}"+ f"[READ_PEER_PROFILE]: cost {cost}s, profile={profile[:50] if profile else 'None'}")if profile:- parts.append(f"## Current user's information\n{profile}")-- # Fetch additional profiles from profile_user_list- if profile_user_list:- profiles = await self.memory.get_viking_user_profiles(+ parts.append(f"## Current sender's information\n{profile}")++ # Fetch additional peer profiles from profile_user_list and from the+ # peers used for memory retrieval. The profile_user_list config name+ # is retained for compatibility with older deployments.+ additional_peer_ids = self._dedupe_ids(+ [*(profile_user_list or []), *(memory_peer_ids or [])],+ exclude={self._sender_id} if self._sender_id else set(),+ )+ if additional_peer_ids:+ profiles = await self.memory.get_viking_peer_profiles(workspace_id=workspace_id,- user_ids=profile_user_list,+ peer_ids=additional_peer_ids,openviking_connection=self._openviking_connection,)if profiles:@@ -172,7 +194,8 @@ Skills with available="false" need dependencies installed first - you can try insession_key: SessionKey,current_message: str,sender_id: str,- memory_users: list[str] | None = None,+ memory_peer_ids: list[str] | None = None,+ memory_owner_user_ids: list[str] | None = None,ov_tools_enable: bool = True,is_first_round: bool = True,) -> str:@@ -235,13 +258,15 @@ Skills with available="false" need dependencies installed first - you can try inparts.append(f"## Relevant Agent Experience\n{exp_memory}")else:start = _time.time()- # Use provided memory_users or fall back to [sender_id]- search_user_ids = memory_users if memory_users else [sender_id]+ # Default recall runs under the configured/request OpenViking user.+ # sender_id is passed separately as peer identity.+ search_peer_ids = memory_peer_ids if memory_peer_ids else Noneviking_memory = await self.memory.get_viking_memory_context(current_message=current_message,workspace_id=workspace_id,sender_id=sender_id,- user_ids=search_user_ids,+ peer_ids=search_peer_ids,+ user_ids=memory_owner_user_ids if memory_owner_user_ids else None,openviking_connection=self._openviking_connection,)logger.info(f"viking_memory={viking_memory}")@@ -324,7 +349,8 @@ IMPORTANT:session_key: SessionKey | None = None,ov_tools_enable: bool = True,profile_user_list: list[str] | None = None,- memory_users: list[str] | None = None,+ memory_peer_ids: list[str] | None = None,+ memory_owner_user_ids: list[str] | None = None,) -> list[dict[str, Any]]:"""Build the complete message list for an LLM call.@@ -335,8 +361,9 @@ IMPORTANT:media: Optional list of local file paths for images/media.session_key: Optional session key.ov_tools_enable: Whether to enable OpenViking tools and memory.- profile_user_list: List of additional user IDs to fetch profiles for.- memory_users: Optional list of user IDs to fetch memory for.+ profile_user_list: Deprecated list of additional peer IDs to fetch profiles for.+ memory_peer_ids: Optional list of peer IDs to fetch memory for.+ memory_owner_user_ids: Deprecated legacy owner-user IDs used for root-key fanout.Returns:List of messages including system prompt.@@ -345,7 +372,11 @@ IMPORTANT:# System promptsystem_prompt = await self.build_system_prompt(- session_key, ov_tools_enable=ov_tools_enable, profile_user_list=profile_user_list+ session_key,+ ov_tools_enable=ov_tools_enable,+ profile_user_list=profile_user_list,+ memory_peer_ids=memory_peer_ids,+ memory_owner_user_ids=memory_owner_user_ids,)messages.append({"role": "system", "content": system_prompt})# logger.debug(f"system_prompt: {system_prompt}")@@ -359,7 +390,8 @@ IMPORTANT:session_key,current_message,self._sender_id,- memory_users,+ memory_peer_ids,+ memory_owner_user_ids,ov_tools_enable=ov_tools_enable,is_first_round=not history,)diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 080a9b5b1..2cd662a3e 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -243,7 +243,7 @@ class AgentLoop:await self.bus.publish_outbound(OutboundMessage(session_key=session_key,- content=f"openviking_search({args_str})",+ content=f"auto_memory_search({args_str})",event_type=OutboundEventType.TOOL_CALL,))@@ -255,7 +255,7 @@ class AgentLoop:))return {- "tool_name": "openviking_search",+ "tool_name": "auto_memory_search","args": args_str,"result": result,"duration": 0,@@ -640,7 +640,8 @@ class AgentLoop:publish_events: bool = True,sender_id: str | None = None,ov_tools_enable: bool = True,- memory_user_ids: list[str] | None = None,+ memory_peer_ids: list[str] | None = None,+ memory_owner_user_ids: list[str] | None = None,disabled_tools: list[str] | None = None,openviking_connection: dict[str, Any] | None = None,) -> tuple[str | None, str | None, list[dict], dict[str, int], int]:@@ -652,7 +653,9 @@ class AgentLoop:session_key: Session key for tool execution contextpublish_events: Whether to publish ITERATION/REASONING/TOOL_CALL events to the busov_tools_enable: Whether to enable OpenViking tools for this session- memory_user_ids: List of user IDs for memory retrieval+ memory_peer_ids: List of peer IDs for memory retrieval+ memory_owner_user_ids: List of explicit OpenViking user IDs for+ legacy root-key fanout searchesdisabled_tools: Tool names to hide from the model for this requestopenviking_connection: Request-scoped OpenViking identity for tools@@ -776,7 +779,8 @@ class AgentLoop:session_key=session_key,sandbox_manager=self.sandbox_manager,sender_id=sender_id,- memory_user_ids=memory_user_ids,+ memory_peer_ids=memory_peer_ids,+ memory_owner_user_ids=memory_owner_user_ids,openviking_connection=openviking_connection,)tool_execute_duration = (time.time() - tool_execute_start_time) * 1000@@ -920,17 +924,17 @@ class AgentLoop:if not isinstance(openviking_connection, dict):openviking_connection = Nonemsg.openviking_connection = openviking_connection- # Get profile_user_list from channel configprofile_user_list = []- # Try to get memory_users from message metadata first (CLI mode), then from channel config- memory_user = msg.metadata.get("memory_users", []) if msg.metadata else []+ memory_peer_ids = self._metadata_memory_peer_ids(msg.metadata)+ memory_owner_user_ids = self._metadata_memory_owner_user_ids(msg.metadata)channel_config = self._get_channel_config(session_key)if channel_config and ov_tools_enable:profile_user_list = getattr(channel_config, "profile_user_list", [])- # Only override if not already set from metadata- if not memory_user:- memory_user = getattr(channel_config, "memory_user", None) or []+ if not memory_peer_ids:+ memory_peer_ids = self._channel_memory_peer_ids(channel_config)+ if not memory_owner_user_ids:+ memory_owner_user_ids = self._channel_memory_owner_user_ids(channel_config)# Handle slash commandsis_group_chat = msg.metadata.get("chat_type") == "group" if msg.metadata else False@@ -1045,9 +1049,9 @@ class AgentLoop:await self._evaluate_previous_response_outcome(session, msg)# Consolidate memory before processing if session is too large- if self._ov_session_context_enabled():+ if self._ov_session_context_enabled() and not self._eval:await self._maybe_commit_openviking_before_turn(session, msg)- elif len(session.messages) > self.memory_window:+ elif len(session.messages) > self.memory_window and not self._eval:# Clone session for async consolidation, then immediately trim originalsession_clone = session.clone()keep_count = min(10, max(2, self.memory_window // 2))@@ -1087,7 +1091,8 @@ class AgentLoop:session_key=msg.session_key,ov_tools_enable=ov_tools_enable,profile_user_list=profile_user_list,- memory_users=memory_user,+ memory_peer_ids=memory_peer_ids,+ memory_owner_user_ids=memory_owner_user_ids,)relevant_memories = message_context.latest_relevant_memoriesauto_memory_tool = None@@ -1114,7 +1119,8 @@ class AgentLoop:publish_events=True,sender_id=msg.sender_id,ov_tools_enable=ov_tools_enable,- memory_user_ids=memory_user,+ memory_peer_ids=memory_peer_ids,+ memory_owner_user_ids=memory_owner_user_ids,disabled_tools=disabled_tools,openviking_connection=openviking_connection,)@@ -1151,7 +1157,7 @@ class AgentLoop:)session.metadata.setdefault("response_facts", {})[response_id] = response_completedawait self.sessions.save(session)- if self._ov_session_context_enabled():+ if self._ov_session_context_enabled() and not self._eval:await self._submit_openviking_session_and_clear_if_committed(session,commit_message_threshold=self.memory_window,@@ -1290,6 +1296,37 @@ class AgentLoop:"""return self.config.channels_config.get_channel_by_key(session_key.channel_key())+ @staticmethod+ def _normalize_id_list(value: Any) -> list[str]:+ if value is None:+ return []+ if isinstance(value, str):+ value = [value]+ if not isinstance(value, list):+ return []+ normalized: list[str] = []+ for item in value:+ item_str = str(item).strip()+ if item_str and item_str not in normalized:+ normalized.append(item_str)+ return normalized++ def _metadata_memory_peer_ids(self, metadata: dict[str, Any] | None) -> list[str]:+ if not isinstance(metadata, dict):+ return []+ return self._normalize_id_list(metadata.get("memory_peers"))++ def _metadata_memory_owner_user_ids(self, metadata: dict[str, Any] | None) -> list[str]:+ if not isinstance(metadata, dict):+ return []+ return self._normalize_id_list(metadata.get("memory_users"))++ def _channel_memory_peer_ids(self, channel_config: Any) -> list[str]:+ return self._normalize_id_list(getattr(channel_config, "memory_peer", None))++ def _channel_memory_owner_user_ids(self, channel_config: Any) -> list[str]:+ return self._normalize_id_list(getattr(channel_config, "memory_user", None))+def _get_ov_tools_enable(self, session_key: SessionKey) -> bool:"""Get ov_tools_enable setting from channel config.@@ -1343,7 +1380,7 @@ class AgentLoop:session_key=msg.session_key,publish_events=False,ov_tools_enable=ov_tools_enable,- memory_user_ids=None,+ memory_peer_ids=None,)if final_content is None or (isinstance(final_content, str) and not final_content.strip()):diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.pyindex e2522e160..006fd472d 100644--- a/bot/vikingbot/agent/memory.py+++ b/bot/vikingbot/agent/memory.py@@ -150,6 +150,7 @@ class MemoryStore:current_message: str,workspace_id: str,sender_id: str,+ peer_ids: list[str] | None = None,user_ids: list[str] | None = None,openviking_connection: dict[str, Any] | None = None,) -> str:@@ -163,6 +164,7 @@ class MemoryStore:)logger.info(f"workspace_id={workspace_id}")logger.info(f"sender_id={sender_id}")+ logger.info(f"peer_ids={peer_ids}")logger.info(f"user_ids={user_ids}")logger.info(f"admin_user_id={admin_user_id}")@@ -170,11 +172,12 @@ class MemoryStore:agent_id=workspace_id,connection=openviking_connection,)+ search_peer_ids = [sender_id, *(peer_ids or [])] if sender_id else (peer_ids or None)result = await client.search_memory(query=current_message,- owner_user_id=sender_id,- peer_ids=user_ids,- limit=30,+ user_ids=user_ids,+ peer_ids=search_peer_ids,+ limit=10,)if not result:return ""@@ -244,7 +247,7 @@ class MemoryStore:async def get_viking_user_profile(self,workspace_id: str,- user_id: str,+ user_id: str | None,openviking_connection: dict[str, Any] | None = None,) -> str:client = None@@ -265,6 +268,85 @@ class MemoryStore:except Exception as e:logger.warning(f"Error closing VikingClient: {e}")+ async def get_viking_peer_profile(+ self,+ workspace_id: str,+ peer_id: str | None,+ openviking_connection: dict[str, Any] | None = None,+ ) -> str:+ if not peer_id:+ return ""++ client = None+ try:+ client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ )+ result = await client.read_peer_profile(peer_id)+ return result or ""+ except Exception as e:+ logger.error(f"[READ_PEER_PROFILE]: peer_id={peer_id}, error. {e}")+ return ""+ finally:+ if client:+ try:+ await client.close()+ except Exception as e:+ logger.warning(f"Error closing VikingClient: {e}")++ async def get_viking_peer_profiles(+ self,+ workspace_id: str,+ peer_ids: list[str],+ openviking_connection: dict[str, Any] | None = None,+ ) -> str:+ if not peer_ids:+ return ""++ client = None+ try:+ client = await VikingClient.create(+ agent_id=workspace_id,+ connection=openviking_connection,+ )++ async def fetch_profile(peer_id: str) -> tuple[str, str]:+ try:+ start_time = time.time()+ profile = await client.read_peer_profile(peer_id)+ cost = round(time.time() - start_time, 2)+ logger.info(+ f"[READ_PEER_PROFILE]: peer_id={peer_id}, cost {cost}s, "+ f"profile={profile[:50] if profile else 'None'}"+ )+ return (peer_id, profile or "")+ except Exception as e:+ logger.error(f"[READ_PEER_PROFILE]: peer_id={peer_id}, error. {e}")+ return (peer_id, "")++ tasks = [fetch_profile(peer_id) for peer_id in peer_ids]+ results = await asyncio.gather(*tasks, return_exceptions=True)++ parts = []+ for result in results:+ if isinstance(result, Exception):+ continue+ peer_id, profile = result+ if profile:+ parts.append(f"## Peer profile for {peer_id}: \n{profile}")++ return "\n\n".join(parts) if parts else ""+ except Exception as e:+ logger.error(f"[READ_PEER_PROFILES]: error. {e}")+ return ""+ finally:+ if client:+ try:+ await client.close()+ except Exception as e:+ logger.warning(f"Error closing VikingClient: {e}")+async def get_viking_user_profiles(self,workspace_id: str,diff --git a/bot/vikingbot/agent/tools/base.py b/bot/vikingbot/agent/tools/base.pyindex f76b65676..b3e415faa 100644--- a/bot/vikingbot/agent/tools/base.py+++ b/bot/vikingbot/agent/tools/base.py@@ -24,8 +24,10 @@ class ToolContext:and session_key. This determines the sandbox directory for the session.sender_id: Optional identifier for the message sender, used for trackingand permission checks.- memory_user_ids: Optional list of user IDs for memory retrieval. Used by- openviking_search tool to search specific users' memory spaces.+ memory_peer_ids: Optional list of peer IDs for memory retrieval inside+ the current OpenViking user scope.+ memory_owner_user_ids: Optional list of explicit OpenViking user IDs+ for legacy root-key fanout searches.openviking_connection: Optional request-scoped OpenViking identity. Studiorequests use this so tools call OpenViking with the same connectionselected in the browser.@@ -42,9 +44,17 @@ class ToolContext:sandbox_manager: SandboxManager | None = Noneworkspace_id: str = sandbox_manager.to_workspace_id(session_key) if sandbox_manager else Nonesender_id: str | None = None- memory_user_ids: list[str] | None = None+ memory_peer_ids: list[str] | None = None+ memory_owner_user_ids: list[str] | None = None+ memory_user_ids: list[str] | None = None # Deprecated alias for memory_owner_user_ids.openviking_connection: dict[str, Any] | None = None+ def __post_init__(self) -> None:+ if self.memory_owner_user_ids is None and self.memory_user_ids is not None:+ self.memory_owner_user_ids = self.memory_user_ids+ elif self.memory_user_ids is None and self.memory_owner_user_ids is not None:+ self.memory_user_ids = self.memory_owner_user_ids+class Tool(ABC):"""diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex e658919e4..78dc75c56 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -1,7 +1,9 @@"""OpenViking file system tools: read, write, list, search resources."""import asyncio+import itertoolsimport json+import timefrom abc import ABCfrom pathlib import Pathfrom typing import Any, Optional@@ -14,6 +16,8 @@ from vikingbot.openviking_mount.ov_server import VikingClientclass OVFileTool(Tool, ABC):+ _memory_commit_counter = itertools.count(1)+def __init__(self):super().__init__()self._clients = {}@@ -28,7 +32,7 @@ class OVFileTool(Tool, ABC):tool_context.workspace_id,connection=tool_context.openviking_connection,)- cache_key = "__default__"+ cache_key = str(tool_context.workspace_id or "__default__")client = self._clients.get(cache_key)if client is None:client = await VikingClient.create(tool_context.workspace_id)@@ -39,6 +43,95 @@ class OVFileTool(Tool, ABC):if client is not None and self._has_request_connection(tool_context):await client.close()+ @staticmethod+ def _normalize_uri(uri: str | None) -> str:+ normalized = (uri or "").strip()+ if normalized == "viking://":+ return normalized+ return normalized.rstrip("/")++ @staticmethod+ def _dedupe_strings(values: list[str | None]) -> list[str]:+ deduped: list[str] = []+ seen: set[str] = set()+ for value in values:+ if not value:+ continue+ value = str(value).strip()+ if not value or value in seen:+ continue+ seen.add(value)+ deduped.append(value)+ return deduped++ def _memory_peer_ids(self, tool_context: ToolContext) -> list[str]:+ return self._dedupe_strings(+ [+ getattr(tool_context, "sender_id", None),+ *(getattr(tool_context, "memory_peer_ids", None) or []),+ ]+ )++ def _is_default_memory_uri(self, client: VikingClient, uri: str | None) -> bool:+ normalized = self._normalize_uri(uri)+ if normalized in {"", "viking://user/memories"}:+ return True+ try:+ return normalized == self._normalize_uri(client._memory_target_uri(None))+ except Exception:+ return False++ def _is_default_root_uri(self, uri: str | None) -> bool:+ return self._normalize_uri(uri) in {"", "viking://", "viking://user"}++ def _peer_memory_uris(+ self,+ client: VikingClient,+ tool_context: ToolContext,+ peer_ids: list[str] | None = None,+ ) -> list[str]:+ builder = getattr(client, "build_current_memory_target_uris", None)+ if not callable(builder):+ return []+ return builder(+ peer_ids=peer_ids if peer_ids is not None else self._memory_peer_ids(tool_context),+ include_self=False,+ )++ def _current_memory_uri(self, client: VikingClient) -> str:+ return client._memory_target_uri(None)++ def _current_skill_uri(self, client: VikingClient) -> str:+ memory_uri = self._current_memory_uri(client).rstrip("/")+ if memory_uri.endswith("/memories"):+ return f"{memory_uri[: -len('/memories')]}/skills/"+ return "viking://user/skills/"++ def _fs_retrieval_uris(+ self,+ client: VikingClient,+ tool_context: ToolContext,+ uri: str | None,+ ) -> list[str]:+ if not self._is_default_memory_uri(client, uri):+ if not self._is_default_root_uri(uri):+ return [uri or ""]++ target_uris = [+ "viking://resources/",+ self._current_memory_uri(client),+ self._current_skill_uri(client),+ *self._peer_memory_uris(client, tool_context),+ ]+ return self._dedupe_strings(target_uris)++ builder = getattr(client, "build_current_memory_target_uris", None)+ if callable(builder):+ uris = builder(peer_ids=self._memory_peer_ids(tool_context))+ if uris:+ return uris+ return [uri or "viking://user/memories/"]+class VikingListTool(OVFileTool):"""Tool to list Viking resources."""@@ -58,7 +151,8 @@ class VikingListTool(OVFileTool):"properties": {"uri": {"type": "string",- "description": "The parent Viking uri to list (e.g., viking://resources/)",+ "description": "Optional parent Viking URI to list. Defaults to all visible OpenViking roots plus current peer memory.",+ "default": "viking://",},"recursive": {"type": "boolean",@@ -66,16 +160,27 @@ class VikingListTool(OVFileTool):"default": False,},},- "required": ["uri"],+ "required": [],}async def execute(- self, tool_context: "ToolContext", uri: str, recursive: bool = False, **kwargs: Any+ self, tool_context: "ToolContext", uri: str = "viking://", recursive: bool = False, **kwargs: Any) -> str:client = Nonetry:client = await self._get_client(tool_context)- entries = await client.list_resources(path=uri, recursive=recursive)+ entries = []+ target_uris = self._fs_retrieval_uris(client, tool_context, uri)+ for target_uri in target_uris:+ try:+ entries.extend(+ await client.list_resources(path=target_uri, recursive=recursive)+ )+ except Exception as exc:+ if len(target_uris) == 1:+ raise+ logger.debug(f"Skip OpenViking list target {target_uri}: {exc}")+ continueif not entries:return f"No resources found at {uri}"@@ -271,72 +376,87 @@ class VikingSearchTool(OVFileTool):client = Nonetry:client = await self._get_client(tool_context)- admin_user_id = client.admin_user_id- memory_user_ids = getattr(tool_context, "memory_user_ids", None)- memory_peer_ids = getattr(tool_context, "memory_peer_ids", None)-- if not target_uri and (memory_user_ids or memory_peer_ids):- grouped_items = {- "memory": [],- "resource": [],- "skill": [],- }-- if memory_user_ids:- user_ids = memory_user_ids if client.should_sender_fanout() else [None]- deduped_user_ids: list[str | None] = []- for user_id in user_ids or []:- if user_id in deduped_user_ids:- continue- deduped_user_ids.append(user_id)+ memory_owner_user_ids = getattr(tool_context, "memory_owner_user_ids", None)+ legacy_memory_user_ids = getattr(tool_context, "memory_user_ids", None)++ grouped_items = {+ "memory": [],+ "resource": [],+ "skill": [],+ }++ if (+ not target_uri+ and client.should_sender_fanout()+ and (memory_owner_user_ids or legacy_memory_user_ids)+ ):+ user_ids = memory_owner_user_ids or legacy_memory_user_ids+ search_requests = [{"target_uri": "viking://resources/", "peer_id": None}]+ for user_id in self._dedupe_strings(list(user_ids or [])):+ memory_uri = client._memory_target_uri(user_id)+ skill_uri = (+ f"{memory_uri.rstrip('/')[: -len('/memories')]}/skills/"+ if memory_uri.rstrip("/").endswith("/memories")+ else "viking://user/skills/"+ )+ search_requests.extend(+ [+ {"target_uri": memory_uri, "peer_id": None},+ {"target_uri": skill_uri, "peer_id": None},+ ]+ )+ else:+ peer_ids = self._memory_peer_ids(tool_context)+ if not target_uri:+ search_requests = (+ [{"target_uri": "", "peer_id": peer_ids[0]}]+ if peer_ids+ else [{"target_uri": "", "peer_id": None}]+ )+ peer_memory_uris = self._peer_memory_uris(+ client, tool_context, peer_ids=peer_ids[1:]+ )+ if peer_memory_uris:+ search_requests.extend(+ {"target_uri": peer_uri, "peer_id": None}+ for peer_uri in peer_memory_uris+ )+ else:+ search_requests.extend(+ {"target_uri": "viking://user/memories/", "peer_id": peer_id}+ for peer_id in peer_ids[1:]+ )+ elif self._is_default_memory_uri(client, target_uri) and peer_ids:+ memory_uris = self._dedupe_strings(+ [+ "viking://user/memories/",+ *self._peer_memory_uris(client, tool_context, peer_ids=peer_ids),+ ]+ )search_requests = [- {"target_uri": client._memory_target_uri(user_id), "peer_id": None}- for user_id in deduped_user_ids+ {"target_uri": memory_uri, "peer_id": None}+ for memory_uri in memory_uris]else:- search_requests = client.build_memory_search_requests(- owner_user_id=tool_context.sender_id if client.should_sender_fanout() else None,- peer_ids=memory_peer_ids,- )-- for request in search_requests:- search_kwargs = {- "target_uri": request["target_uri"],- "limit": 10,- "user_id": admin_user_id,- }- if request.get("peer_id") is not None:- search_kwargs["peer_id"] = request.get("peer_id")- results = await client.search(- query,- **search_kwargs,- )- filtered_items = self._filter_search_items(results, min_score=min_score)- for item_type, items in filtered_items.items():- grouped_items[item_type].extend(items)-- total = sum(len(items) for items in grouped_items.values())- if total == 0:- return f"No results found for query: {query}"- return self._format_search_items_json(grouped_items, min_score=min_score)-- results = await client.search(- query,- target_uri=target_uri,- limit=10,- user_id=admin_user_id,- )+ search_requests = [{"target_uri": target_uri, "peer_id": None}]- if not results:- return f"No results found for query: {query}"+ for request in search_requests:+ search_kwargs = {+ "target_uri": request["target_uri"],+ "limit": 10,+ }+ if request.get("peer_id") is not None:+ search_kwargs["peer_id"] = request.get("peer_id")+ results = await client.search(query, **search_kwargs)+ filtered_items = self._filter_search_items(results, min_score=min_score)+ for item_type, items in filtered_items.items():+ grouped_items[item_type].extend(items)- grouped_items = self._filter_search_items(results, min_score=min_score)total = sum(len(items) for items in grouped_items.values())if total == 0:return f"No results found for query: {query}"- content = self._format_search_items_json(grouped_items, min_score=min_score)- return content+ return self._format_search_items_json(grouped_items, min_score=min_score)except Exception as e:return f"Error searching Viking: {str(e)}"finally:@@ -420,7 +540,8 @@ class VikingGrepTool(OVFileTool):"properties": {"uri": {"type": "string",- "description": "The whole Viking URI to search within (e.g., viking://resources/)",+ "description": "Optional Viking URI to search within. Defaults to all visible OpenViking roots plus current peer memory.",+ "default": "viking://",},"pattern": {"type": "string",@@ -432,30 +553,38 @@ class VikingGrepTool(OVFileTool):"default": False,},},- "required": ["uri", "pattern"],+ "required": ["pattern"],}async def execute(self,tool_context: "ToolContext",- uri: str,pattern: str,+ uri: str = "viking://",case_insensitive: bool = False,**kwargs: Any,) -> str:client = Nonetry:client = await self._get_client(tool_context)- result = await client.grep(- uri,- pattern,- case_insensitive=case_insensitive,- user_id=client.admin_user_id,- )- if isinstance(result, dict):- matches = result.get("matches", [])- else:- matches = getattr(result, "matches", [])+ matches = []+ target_uris = self._fs_retrieval_uris(client, tool_context, uri)+ for target_uri in target_uris:+ try:+ result = await client.grep(+ target_uri,+ pattern,+ case_insensitive=case_insensitive,+ )+ except Exception as exc:+ if len(target_uris) == 1:+ raise+ logger.debug(f"Skip OpenViking grep target {target_uri}: {exc}")+ continue+ if isinstance(result, dict):+ matches.extend(result.get("matches", []))+ else:+ matches.extend(getattr(result, "matches", []))if not matches:return f"No matches found for pattern: '{pattern}'"@@ -532,14 +661,26 @@ class VikingGlobTool(OVFileTool):client = Nonetry:client = await self._get_client(tool_context)- result = await client.glob(pattern, uri=uri or None, user_id=client.admin_user_id)+ matches = []+ count = 0+ target_uris = self._fs_retrieval_uris(client, tool_context, uri or "viking://")+ for target_uri in target_uris:+ try:+ result = await client.glob(pattern, uri=target_uri or "viking://")+ except Exception as exc:+ if len(target_uris) == 1:+ raise+ logger.debug(f"Skip OpenViking glob target {target_uri}: {exc}")+ continue- if isinstance(result, dict):- matches = result.get("matches", [])- count = result.get("count", 0)- else:- matches = getattr(result, "matches", [])- count = getattr(result, "count", 0)+ if isinstance(result, dict):+ batch_matches = result.get("matches", [])+ batch_count = result.get("count", len(batch_matches))+ else:+ batch_matches = getattr(result, "matches", [])+ batch_count = getattr(result, "count", len(batch_matches))+ matches.extend(batch_matches)+ count += int(batch_count or 0)if not matches:return f"No files found for pattern: {pattern}"@@ -647,14 +788,14 @@ class VikingMemoryCommitTool(OVFileTool):client = Nonetry:client = await self._get_client(tool_context)- if self._has_request_connection(tool_context):- commit_user_id = client.admin_user_id or tool_context.sender_id- else:- commit_user_id = tool_context.sender_id or client.admin_user_id- if not commit_user_id:- return "Error: user id is required for OpenViking memory commit."- session_id = tool_context.session_key.safe_name()- result = await client.commit(session_id, messages, commit_user_id)+ if not tool_context.sender_id:+ return "Error: peer id is required for OpenViking memory commit."+ source_session_id = tool_context.session_key.safe_name()+ commit_seq = next(self._memory_commit_counter)+ timestamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())+ session_id = f"{source_session_id}__memory_commit__{timestamp}__{commit_seq:04d}"+ result = await client.commit(session_id, messages, peer_id=tool_context.sender_id)+ session_id = result.get("session_id", session_id) if isinstance(result, dict) else session_idcommit_result = result.get("commit", {}) if isinstance(result, dict) else {}archive_uri = commit_result.get("archive_uri")memory_diff_uri = f"{archive_uri}/memory_diff.json" if archive_uri else None@@ -674,6 +815,8 @@ class VikingMemoryCommitTool(OVFileTool):{"status": "success","session_id": session_id,+ "memory_commit_session_id": session_id,+ "source_session_id": source_session_id,"message_count": len(messages),"archived": commit_result.get("archived"),**changed_uris,diff --git a/bot/vikingbot/agent/tools/registry.py b/bot/vikingbot/agent/tools/registry.pyindex d2c34c204..4a485e0ec 100644--- a/bot/vikingbot/agent/tools/registry.py+++ b/bot/vikingbot/agent/tools/registry.py@@ -140,6 +140,8 @@ class ToolRegistry:session_key: SessionKey,sandbox_manager: SandboxManager | None = None,sender_id: str | None = None,+ memory_peer_ids: list[str] | None = None,+ memory_owner_user_ids: list[str] | None = None,memory_user_ids: list[str] | None = None,openviking_connection: dict[str, Any] | None = None,) -> str:@@ -152,7 +154,10 @@ class ToolRegistry:session_key: Session key for the current session.sandbox_manager: Sandbox manager for file/shell operations.sender_id: Sender id for the current session.- memory_user_ids: List of user IDs for memory retrieval.+ memory_peer_ids: List of peer IDs for memory retrieval.+ memory_owner_user_ids: List of explicit OpenViking user IDs for+ legacy root-key fanout searches.+ memory_user_ids: Deprecated alias for memory_owner_user_ids.openviking_connection: Request-scoped OpenViking identity.Returns:@@ -169,6 +174,8 @@ class ToolRegistry:session_key=session_key,sandbox_manager=sandbox_manager,sender_id=sender_id,+ memory_peer_ids=memory_peer_ids,+ memory_owner_user_ids=memory_owner_user_ids,memory_user_ids=memory_user_ids,openviking_connection=openviking_connection,)diff --git a/bot/vikingbot/channels/chat.py b/bot/vikingbot/channels/chat.pyindex 80d50b32a..4989f006a 100644--- a/bot/vikingbot/channels/chat.py+++ b/bot/vikingbot/channels/chat.py@@ -156,6 +156,13 @@ class ChatChannel(BaseChannel):self._last_response = Nonesender_id = self.sender or "user"+ metadata = {}+ memory_peers = getattr(self.config, "memory_peer", None)+ if memory_peers:+ metadata["memory_peers"] = memory_peers+ memory_users = getattr(self.config, "memory_user", None)+ if memory_users:+ metadata["memory_users"] = memory_usersmsg = InboundMessage(session_key=SessionKey(type="cli",@@ -164,6 +171,7 @@ class ChatChannel(BaseChannel):),sender_id=sender_id,content=user_input,+ metadata=metadata,)await self.bus.publish_inbound(msg)diff --git a/bot/vikingbot/channels/single_turn.py b/bot/vikingbot/channels/single_turn.pyindex 6d437b9d1..129b09451 100644--- a/bot/vikingbot/channels/single_turn.py+++ b/bot/vikingbot/channels/single_turn.py@@ -62,10 +62,13 @@ class SingleTurnChannel(BaseChannel):# Send the messagesender_id = self.sender or "user"- # Pass memory_user through metadatametadata = {}- if self.config.memory_user:- metadata["memory_users"] = self.config.memory_user+ memory_peers = getattr(self.config, "memory_peer", None)+ if memory_peers:+ metadata["memory_peers"] = memory_peers+ memory_users = getattr(self.config, "memory_user", None)+ if memory_users:+ metadata["memory_users"] = memory_usersmsg = InboundMessage(session_key=SessionKey(type="cli",diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.pyindex 8cb803425..db596e241 100644--- a/bot/vikingbot/cli/commands.py+++ b/bot/vikingbot/cli/commands.py@@ -26,7 +26,13 @@ from vikingbot import __logo__, __version__from vikingbot.agent.loop import AgentLoopfrom vikingbot.bus.queue import MessageBusfrom vikingbot.channels.manager import ChannelManager-from vikingbot.config.loader import ensure_config, get_config_path, get_data_dir, load_config+from vikingbot.config.loader import (+ ensure_config,+ get_config_path,+ get_data_dir,+ load_config,+ validate_openviking_auth,+)from vikingbot.config.schema import SessionKey, requires_gateway_tokenfrom vikingbot.cron.service import CronServicefrom vikingbot.cron.types import CronJob@@ -67,6 +73,17 @@ console = Console()EXIT_COMMANDS = {"exit", "quit", "/exit", "/quit", ":q"}+def _warn_deprecated_memory_user(memory_user: list[str] | None) -> None:+ if not memory_user:+ return+ typer.secho(+ "Warning: --memory-user is deprecated and only kept for legacy root-key fanout. "+ "Use --memory-peer for the current OpenViking User/Peer model.",+ fg=typer.colors.YELLOW,+ err=True,+ )++def get_or_create_machine_id() -> str:"""Get a unique machine ID using py-machineid.@@ -324,6 +341,7 @@ def gateway(bus = MessageBus()path = Path(config_path).expanduser() if config_path is not None else Noneconfig = ensure_config(path)+ validate_openviking_auth(config)effective_host = host if host is not None else config.gateway.hosteffective_port = port if port is not None else config.gateway.portgateway_token = _get_gateway_token(config)@@ -613,6 +631,7 @@ def prepare_agent_channel(logs: bool,eval: bool = False,sender: str | None = None,+ memory_peer: list[str] | None = None,memory_user: list[str] | None = None,):"""Prepare channel for agent command."""@@ -622,7 +641,10 @@ def prepare_agent_channel(channels = ChannelManager(bus)if message is not None:# Single message mode - use SingleTurnChannel for clean output- channel_config = SingleTurnChannelConfig(memory_user=memory_user)+ channel_config = SingleTurnChannelConfig(+ memory_peer=memory_peer,+ memory_user=memory_user,+ )channel = SingleTurnChannel(channel_config,bus,@@ -636,7 +658,10 @@ def prepare_agent_channel(channels.add_channel(channel)else:# Interactive mode - use ChatChannel with thinking display- channel_config = ChatChannelConfig(memory_user=memory_user)+ channel_config = ChatChannelConfig(+ memory_peer=memory_peer,+ memory_user=memory_user,+ )channel = ChatChannel(channel_config,bus,@@ -670,8 +695,13 @@ def chat(sender: str = typer.Option(None, "--sender", help="Sender ID, same usage as feishu channel sender"),+ memory_peer: list[str] = typer.Option(+ None, "--memory-peer", help="Peer ID for memory retrieval (can be repeated)"+ ),memory_user: list[str] = typer.Option(- None, "--memory-user", help="User ID for memory retrieval (can be repeated)"+ None,+ "--memory-user",+ help="Deprecated legacy OpenViking user ID for root-key memory fanout",),):"""Interact with the agent directly."""@@ -679,6 +709,8 @@ def chat(bus = MessageBus()config = ensure_config(path)+ validate_openviking_auth(config)+ _warn_deprecated_memory_user(memory_user)_init_bot_data(config)logger.remove()@@ -706,7 +738,16 @@ def chat(session_id = get_or_create_machine_id()cron = prepare_cron(bus, quiet=is_single_turn)channels = prepare_agent_channel(- config, bus, message, session_id, markdown, logs, eval, sender, memory_user+ config,+ bus,+ message,+ session_id,+ markdown,+ logs,+ eval,+ sender,+ memory_peer,+ memory_user,)agent_loop = prepare_agent_loop(config, bus, session_manager, cron, quiet=is_single_turn, eval=evaldiff --git a/bot/vikingbot/config/loader.py b/bot/vikingbot/config/loader.pyindex 3b824536c..cecfbbd5a 100644--- a/bot/vikingbot/config/loader.py+++ b/bot/vikingbot/config/loader.py@@ -2,10 +2,12 @@import jsonimport os+import sysfrom pathlib import Pathfrom typing import Anyfrom loguru import logger+from openviking_cli.utils.config.ovcli_config import load_ovcli_configfrom vikingbot.config.schema import Config@@ -147,12 +149,45 @@ def _merge_ov_server_config(bot_data: dict, ov_data: dict) -> None:host = ov_data.get("host", "127.0.0.1")port = ov_data.get("port", "1933")bot_data["server_url"] = f"http://{host}:{port}"- if "root_api_key" not in bot_data or not bot_data["root_api_key"]:- bot_data["root_api_key"] = ov_data.get("root_api_key", "")- if "root_api_key" in bot_data and bot_data["root_api_key"]:- bot_data["mode"] = "remote"- else:- bot_data["mode"] = "local"+ api_key = bot_data.get("api_key") or ""+ legacy_bot_api_key = bot_data.get("root_api_key") or ""+ server_root_api_key = ov_data.get("root_api_key", "")+ if not api_key and legacy_bot_api_key:+ bot_data["api_key"] = legacy_bot_api_key+ bot_data["api_key_type"] = "root"+ api_key = legacy_bot_api_key+ elif not api_key and server_root_api_key:+ bot_data["root_api_key"] = server_root_api_key+ bot_data["api_key"] = server_root_api_key+ bot_data["api_key_type"] = "root"+ api_key = server_root_api_key+ mode = bot_data["mode"] if "mode" in bot_data and bot_data["mode"] else ""+ if not mode:+ mode = "remote" if api_key or server_root_api_key else "local"+ bot_data["mode"] = mode+ if not api_key and mode == "remote":+ try:+ cli_config = load_ovcli_config()+ except ValueError as e:+ print(str(e), file=sys.stderr)+ raise+ if cli_config and cli_config.api_key:+ bot_data["api_key"] = cli_config.api_key++def validate_openviking_auth(config: Config) -> None:+ ov_server = config.ov_server+ if ov_server.mode == "local":+ return+ if ov_server.api_key or ov_server.root_api_key:+ return++ print(+ "Error: missing OpenViking API key for remote mode. "+ "New VikingBot deployments should configure bot.ov_server.api_key with a User API key. "+ "Legacy root-key deployments may still use bot.ov_server.root_api_key, but root_api_key is deprecated.",+ file=sys.stderr,+ )+ raise SystemExit(1)def save_config(diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.pyindex 933e12190..63c4837a2 100644--- a/bot/vikingbot/config/schema.py+++ b/bot/vikingbot/config/schema.py@@ -4,7 +4,7 @@ from enum import Enumfrom pathlib import Pathfrom typing import Any, Dict, Literal, Optional-from pydantic import BaseModel, ConfigDict, Field, field_validator+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict@@ -64,7 +64,8 @@ class BaseChannelConfig(BaseModel):type: Any = ChannelType.TELEGRAM # Default for backwards compatibilityenabled: bool = Trueov_tools_enable: bool = True- memory_user: list[str] | None = None+ memory_peer: list[str] | None = None+ memory_user: list[str] | None = None # Deprecated legacy owner-user memory lookup.def channel_id(self) -> str:return "default"@@ -291,7 +292,8 @@ class BotChannelConfig(BaseChannelConfig):max_concurrent_requests: int = 100need_mention: bool = Falseprofile_user_list: list[str] = Field(default_factory=list)- memory_user: str = ""+ memory_peer: list[str] | str | None = None+ memory_user: list[str] | str | None = None # Deprecated legacy owner-user memory lookup.id: str = "default" # Channel identifier for multi-channel supportdef channel_id(self) -> str:@@ -514,8 +516,10 @@ class OpenVikingConfig(BaseModel):"""Viking tools configuration."""mode: str = "remote" # local or remote- api_key_type: Literal["root", "user"] = "root"+ api_key_type: Literal["root", "user"] | None = Noneserver_url: str = ""+ api_key: str = ""+ # 废弃,后续使用api_keyroot_api_key: str = ""account_id: str = "default"admin_user_id: str = "default"@@ -535,10 +539,19 @@ class OpenVikingConfig(BaseModel):@field_validator("api_key_type", mode="before")@classmethod- def normalize_api_key_type(cls, value: Any) -> str:+ def normalize_api_key_type(cls, value: Any) -> str | None:if value is None:- return "root"- return str(value).strip().lower()+ return None+ normalized = str(value).strip().lower()+ return normalized or None++ @model_validator(mode="after")+ def apply_api_key_compatibility(self):+ if not self.api_key_type:+ self.api_key_type = "user" if not self.root_api_key or self.api_key else "root"+ if self.root_api_key and not self.api_key:+ self.api_key = self.root_api_key+ return selfclass WebToolsConfig(BaseModel):diff --git a/bot/vikingbot/hooks/builtins/openviking_hooks.py b/bot/vikingbot/hooks/builtins/openviking_hooks.pyindex ba4555459..d4362aa81 100644--- a/bot/vikingbot/hooks/builtins/openviking_hooks.py+++ b/bot/vikingbot/hooks/builtins/openviking_hooks.py@@ -1,6 +1,4 @@-import asyncioimport re-from collections import defaultdictfrom datetime import datetimefrom typing import Any@@ -11,9 +9,7 @@ from vikingbot.openviking_mount.session_state import (get_openviking_session_id,get_openviking_state,get_unsynced_messages,- get_unsynced_messages_for_sender,parse_local_index,- set_sender_synced_local_index,)from vikingbot.utils.helpers import cal_str_tokens@@ -30,16 +26,17 @@ except Exception:VikingClient = Noneov = None-_global_client: Any = None+_global_clients: dict[str, Any] = {}async def get_global_client(workspace_id: str | None) -> VikingClient:"""Get or create the shared VikingClient."""- del workspace_id- global _global_client- if _global_client is None:- _global_client = await VikingClient.create()- return _global_client+ cache_key = str(workspace_id or "__default__")+ client = _global_clients.get(cache_key)+ if client is None:+ client = await VikingClient.create(workspace_id)+ _global_clients[cache_key] = client+ return clientclass OpenVikingCompactHook(Hook):@@ -91,8 +88,6 @@ class OpenVikingCompactHook(Hook):admin_append_result = Noneadmin_commit_result = None- user_results = []- pending_tokens_before_sync = pending_tokensunsynced_tokens = sum(cal_str_tokens(str(msg.get("content") or ""))@@ -100,176 +95,40 @@ class OpenVikingCompactHook(Hook):if msg.get("content") is not None)- all_sender_ids = sorted(- {- str(msg.get("sender_id"))- for msg in session.messages- if msg.get("sender_id") and msg.get("sender_id") != admin_user_id- }- )- unsynced_messages_by_sender = {}- sender_latest_indexes: dict[str, int] = {}- for sender_id in all_sender_ids:- user_messages = get_unsynced_messages_for_sender(- session,- sender_id,- admin_user_id=admin_user_id,- )- if user_messages:- unsynced_messages_by_sender[sender_id] = user_messages- sender_latest_indexes[sender_id] = max(- index- for index, msg in enumerate(session.messages)- if msg.get("sender_id") == sender_id- )-should_commit = bool(force_commitor pending_tokens + unsynced_tokens >= commit_token_thresholdor reached_message_threshold)- sender_ids_to_sync = (- all_sender_ids if should_commit else sorted(unsynced_messages_by_sender)- )- user_results_by_id: dict[str, dict[str, Any]] = {}-- if sender_ids_to_sync:- semaphore = asyncio.Semaphore(5)-- async def sync_sender(user_id: str):- user_messages = unsynced_messages_by_sender.get(user_id, [])- async with semaphore:- sender_session_id = f"{session_id}_{user_id}"- append_result = None- if user_messages:- append_result = await client.append_messages(- session_id=sender_session_id,- messages=user_messages,- default_user_peer_id=user_id,- session_user_id=user_id,- )- return {- "session_id": sender_session_id,- "user_id": user_id,- "append": append_result,- }-- user_results = await asyncio.gather(- *(sync_sender(user_id) for user_id in sender_ids_to_sync),- return_exceptions=True,- )- for result in user_results:- if isinstance(result, dict):- user_id = result["user_id"]- user_results_by_id[user_id] = result- if result.get("append") is not None and user_id in sender_latest_indexes:- set_sender_synced_local_index(- session, user_id, sender_latest_indexes[user_id]- )-- fanout_errors = [result for result in user_results if isinstance(result, Exception)]- if fanout_errors:- error_message = "; ".join(str(error) for error in fanout_errors)- state["last_pending_tokens"] = pending_tokens_before_sync- state["last_commit_performed"] = False- state["last_sync_status"] = "error"- state["last_sync_error"] = error_message- return {- "success": False,- "session_id": session_id,- "admin_result": {- "append": admin_append_result,- "commit": admin_commit_result,- "committed": False,- },- "user_results": user_results,- "users_count": len(sender_ids_to_sync),- "pending_tokens": pending_tokens_before_sync,- "error": error_message,- }+ session_user_id = client.session_owner_user_id()if messages_to_sync:admin_append_result = await client.append_messages(session_id=session_id,messages=messages_to_sync,- default_user_peer_id=admin_user_id,- session_user_id=admin_user_id,+ default_user_peer_id=None,+ session_user_id=session_user_id,)state["last_synced_local_index"] = len(session.messages) - 1- admin_session_state = await client.get_session(session_id, user_id=admin_user_id)+ admin_session_state = await client.get_session(session_id, user_id=session_user_id)pending_tokens = int(admin_session_state.get("pending_tokens", 0) or 0)elif force_commit:- admin_session_state = await client.get_session(session_id, user_id=admin_user_id)+ admin_session_state = await client.get_session(session_id, user_id=session_user_id)pending_tokens = int(admin_session_state.get("pending_tokens", 0) or 0)should_commit = (force_commit or pending_tokens >= commit_token_threshold or reached_message_threshold)if should_commit:- sender_ids_to_commit = all_sender_ids- for user_id in sender_ids_to_commit:- user_results_by_id.setdefault(- user_id,- {- "session_id": f"{session_id}_{user_id}",- "user_id": user_id,- "append": None,- },- )-- if sender_ids_to_commit:- semaphore = asyncio.Semaphore(5)-- async def commit_sender(user_id: str):- async with semaphore:- sender_session_id = f"{session_id}_{user_id}"- logger.info(- f"[HOOK] Committed session {sender_session_id} for user {user_id}"- )- return await client.commit_session(- session_id=sender_session_id,- keep_recent_count=keep_recent_count,- user_id=user_id,- )-- commit_results = await asyncio.gather(- *(commit_sender(user_id) for user_id in sender_ids_to_commit),- return_exceptions=True,- )- for user_id, commit_result in zip(- sender_ids_to_commit, commit_results, strict=True- ):- user_results_by_id[user_id]["commit"] = commit_result- fanout_errors = [- result for result in commit_results if isinstance(result, Exception)- ]- if fanout_errors:- error_message = "; ".join(str(error) for error in fanout_errors)- state["last_pending_tokens"] = pending_tokens- state["last_commit_performed"] = False- state["last_sync_status"] = "error"- state["last_sync_error"] = error_message- return {- "success": False,- "session_id": session_id,- "admin_result": {- "append": admin_append_result,- "commit": admin_commit_result,- "committed": False,- },- "user_results": list(user_results_by_id.values()),- "users_count": len(user_results_by_id),- "pending_tokens": pending_tokens,- "error": error_message,- }-admin_commit_result = await client.commit_session(session_id=session_id,keep_recent_count=keep_recent_count,- user_id=admin_user_id,+ user_id=session_user_id,+ )+ logger.info(+ f"[HOOK] Committed session {session_id} for user {session_user_id or 'current'}")- logger.info(f"[HOOK] Committed session {session_id} for user {admin_user_id}")- admin_session_state = await client.get_session(session_id, user_id=admin_user_id)+ admin_session_state = await client.get_session(session_id, user_id=session_user_id)pending_tokens = int(admin_session_state.get("pending_tokens", 0) or 0)if should_commit:@@ -288,8 +147,8 @@ class OpenVikingCompactHook(Hook):"commit": admin_commit_result,"committed": should_commit,},- "user_results": list(user_results_by_id.values()),- "users_count": len(user_results_by_id),+ "user_results": [],+ "users_count": 0,"pending_tokens": pending_tokens,}@@ -342,47 +201,16 @@ class OpenVikingCompactHook(Hook):commit_message_threshold=commit_message_threshold,)- if not client.should_sender_fanout():- single_result = await client.commit(session_id, vikingbot_session.messages, None)- return {- "success": True,- "admin_result": single_result,- "user_results": [],- "users_count": 0,- }-admin_result = await client.commit(- session_id, vikingbot_session.messages, admin_user_id+ session_id,+ vikingbot_session.messages,+ user_id=client.session_owner_user_id(),)-- messages_by_sender = defaultdict(list)- for msg in vikingbot_session.messages:- sender_id = msg.get("sender_id")- if sender_id and sender_id != admin_user_id:- messages_by_sender[sender_id].append(msg)-- user_results = []- if messages_by_sender:- semaphore = asyncio.Semaphore(5)-- async def commit_with_semaphore(user_id: str, user_messages: list):- async with semaphore:- return await client.commit(- f"{session_id}_{user_id}", user_messages, user_id- )-- user_tasks = []- for user_id, user_messages in messages_by_sender.items():- task = commit_with_semaphore(user_id, user_messages)- user_tasks.append(task)-- user_results = await asyncio.gather(*user_tasks, return_exceptions=True)-return {"success": True,"admin_result": admin_result,- "user_results": user_results,- "users_count": len(messages_by_sender),+ "user_results": [],+ "users_count": 0,}except Exception as e:state = Nonediff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex ef8e08d63..5f9eb3e80 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -17,6 +17,14 @@ def _is_session_key(agent_id: Optional[str]) -> bool:return agent_id is not None and "__" in agent_id+def _safe_peer_id(peer_id: Optional[str]) -> Optional[str]:+ if not peer_id:+ return None+ if "/" in peer_id or "\\" in peer_id:+ return None+ return peer_id++class VikingClient:def __init__(self,@@ -37,7 +45,7 @@ class VikingClient:self.agent_id = agent_idself.ov_path = config.ov_data_pathself.mode = openviking_config.mode- self.api_key_type = (openviking_config.api_key_type or "root").strip().lower()+ self.api_key_type = (openviking_config.api_key_type or "user").strip().lower()if self.api_key_type not in {"root", "user"}:raise ValueError(f"Invalid ov_server.api_key_type: {self.api_key_type}")@@ -70,9 +78,11 @@ class VikingClient:self.account_id = openviking_config.account_idself.admin_user_id = openviking_config.admin_user_id+ api_key = openviking_config.api_key or openviking_config.root_api_keyremote_client_kwargs = {"url": openviking_config.server_url,- "api_key": openviking_config.root_api_key,+ "api_key": api_key,+ "profile_enabled": False,}if self._is_root_key_mode():remote_client_kwargs["account"] = openviking_config.account_id@@ -205,16 +215,32 @@ class VikingClient:def _effective_user_id(self, user_id: Optional[str]) -> str:if self._has_request_connection():- return user_id or self.admin_user_id+ return ""if self._is_user_key_mode():return ""return user_id or self.admin_user_iddef _effective_session_user_id(self, user_id: Optional[str] = None) -> Optional[str]:- if self._has_request_connection():- return self.admin_user_id or user_id+ if self._has_request_connection() or self.mode == "local" or self._is_user_key_mode():+ return Nonereturn user_id or self.admin_user_id+ def session_owner_user_id(self) -> Optional[str]:+ """Return the explicit OpenViking user for session operations, when needed."""+ return self._effective_session_user_id()++ @staticmethod+ def default_memory_policy() -> Dict[str, Dict[str, bool]]:+ """Write extracted conversation memories to peers by default for bot sessions."""+ return {+ "self": {"enabled": False},+ "peer": {"enabled": True},+ }++ @staticmethod+ def _peer_id(value: Optional[str]) -> Optional[str]:+ return _safe_peer_id(str(value)) if value is not None else None+async def _load_namespace_policy(self) -> None:if self._namespace_policy_loaded:return@@ -223,12 +249,12 @@ class VikingClient:"isolate_user_scope_by_agent": False,"isolate_agent_scope_by_user": False,}- if self._has_request_connection():+ if self._has_request_connection() or self.mode == "local" or self._is_user_key_mode():self._namespace_policy = policyself._namespace_policy_loaded = Truereturn- if self.mode == "remote" and self.account_id:+ if self._is_root_key_mode() and self.account_id:try:accounts = await self.client.admin_list_accounts()for account in accounts or []:@@ -266,13 +292,58 @@ class VikingClient:def _peer_memory_target_uri(self, user_id: Optional[str], peer_id: str) -> str:user_space = self._user_space_fragment(user_id)- normalized_peer_id = str(peer_id or "").strip()+ normalized_peer_id = self._peer_id(peer_id)if not normalized_peer_id:raise ValueError("peer_id is required for peer memory target")if not user_space:raise ValueError("peer memory target requires explicit user_id")return f"viking://user/{user_space}/peers/{normalized_peer_id}/memories/"+ def _current_user_space_fragment(self) -> str:+ current_user_id = getattr(self, "admin_user_id", None) or getattr(self, "user_id", None)+ if not current_user_id:+ return ""+ return current_user_id++ def _current_peer_memory_target_uri(self, peer_id: str) -> str:+ normalized_peer_id = self._peer_id(peer_id)+ if not normalized_peer_id:+ raise ValueError("peer_id is required for peer memory target")+ if self._is_user_key_mode() or self._has_request_connection():+ return f"viking://user/peers/{normalized_peer_id}/memories/"+ user_space = self._current_user_space_fragment()+ if not user_space:+ raise ValueError("peer memory target requires current user_id")+ return f"viking://user/{user_space}/peers/{normalized_peer_id}/memories/"++ def _current_peer_profile_uri(self, peer_id: str) -> str:+ return f"{self._current_peer_memory_target_uri(peer_id).rstrip('/')}/profile.md"++ def build_current_memory_target_uris(+ self,+ *,+ peer_ids: Optional[List[str]] = None,+ include_self: bool = True,+ ) -> List[str]:+ uris: List[str] = []+ if include_self:+ uris.append(self._memory_target_uri(None))++ normalized_peer_ids = self._dedupe_strings(+ [+ safe_peer_id+ for safe_peer_id in (self._peer_id(peer_id) for peer_id in (peer_ids or []))+ if safe_peer_id+ ]+ )+ for peer_id in normalized_peer_ids:+ try:+ uris.append(self._current_peer_memory_target_uri(peer_id))+ except ValueError as exc:+ logger.warning(f"Skip invalid current peer memory target peer_id={peer_id}: {exc}")++ return self._dedupe_strings(uris)+@staticmethoddef _dedupe_strings(values: List[str]) -> List[str]:deduped: List[str] = []@@ -296,7 +367,11 @@ class VikingClient:[str(user_id).strip() for user_id in (user_ids or []) if str(user_id).strip()])normalized_peer_ids = self._dedupe_strings(- [str(peer_id).strip() for peer_id in (peer_ids or []) if str(peer_id).strip()]+ [+ safe_peer_id+ for safe_peer_id in (self._peer_id(peer_id) for peer_id in (peer_ids or []))+ if safe_peer_id+ ])effective_owner_user_id = self._effective_user_id(owner_user_id) if owner_user_id else None@@ -401,6 +476,9 @@ class VikingClient:async def read_user_profile(self, user_id: str) -> str:"""读取用户 profile。"""effective_user_id = self._effective_user_id(user_id)+ if not effective_user_id:+ return await self.read_content(uri="viking://user/memories/profile.md", level="read")+user_exists = await self._check_user_exists(effective_user_id)if not user_exists:@@ -411,6 +489,14 @@ class VikingClient:result = await self.read_content(uri=uri, level="read")return result+ async def read_peer_profile(self, peer_id: str) -> str:+ """读取当前 User 下指定 peer 的 profile。"""+ try:+ uri = self._current_peer_profile_uri(peer_id)+ except ValueError:+ return ""+ return await self.read_content(uri=uri, level="read")+async def search(self,query: str,@@ -429,7 +515,7 @@ class VikingClient:query,target_uri=target_uri,limit=limit,- peer_id=peer_id,+ peer_id=self._peer_id(peer_id),)finally:if should_close:@@ -579,6 +665,7 @@ class VikingClient:*,owner_user_id: Optional[str] = None,peer_ids: Optional[list[str]] = None,+ peer_id: Optional[str] = None,) -> list[Any] | dict[str, list[Any]]:"""通过上下文消息检索用户 memory。"""@@ -593,11 +680,26 @@ class VikingClient:memories = getattr(result, "memories", None)return memories if isinstance(memories, list) else []- if isinstance(user_ids, str):- user_ids = [user_ids]-- normalized_user_ids = [str(user_id).strip() for user_id in (user_ids or []) if user_id]- normalized_peer_ids = [str(peer_id).strip() for peer_id in (peer_ids or []) if peer_id]+ if user_ids is None:+ normalized_user_ids: list[str] = []+ elif isinstance(user_ids, str):+ normalized_user_ids = [user_ids]+ else:+ normalized_user_ids = list(user_ids)+ normalized_user_ids = [+ str(user_id).strip() for user_id in normalized_user_ids if str(user_id).strip()+ ]++ peer_values = [*(peer_ids or [])]+ if peer_id:+ peer_values.append(peer_id)+ normalized_peer_ids = self._dedupe_strings(+ [+ safe_peer_id+ for safe_peer_id in (self._peer_id(peer_value) for peer_value in peer_values)+ if safe_peer_id+ ]+ )effective_owner_user_id = self._effective_user_id(owner_user_id) if owner_user_id else Noneuser_ids_to_check = self._dedupe_strings(@@ -631,7 +733,7 @@ class VikingClient:"limit": limit,}if request.get("peer_id") is not None:- find_kwargs["peer_id"] = request.get("peer_id")+ find_kwargs["peer_id"] = self._peer_id(request.get("peer_id"))user_memory = await self.client.find(**find_kwargs)all_user_memories.extend(_extract_memories(user_memory))@@ -732,8 +834,6 @@ class VikingClient:return clientdef _assistant_peer_id(self) -> Optional[str]:- if self.admin_user_id:- return self.admin_user_idreturn Nonedef _normalize_session_messages(@@ -784,7 +884,7 @@ class VikingClient:)if match:skill_name = match.group(1).strip()- skill_uri = self._skill_memory_uri(skill_name, default_user_peer_id)+ skill_uri = self._skill_memory_uri(skill_name)tool_id = f"{tool_name}_{uuid.uuid4().hex[:8]}"parts.append(@@ -824,8 +924,9 @@ class VikingClient:elif not peer_id and ov_role == "assistant":peer_id = assistant_peer_id- if peer_id:- payload["peer_id"] = peer_id+ safe_message_peer_id = self._peer_id(peer_id)+ if safe_message_peer_id:+ payload["peer_id"] = safe_message_peer_idnormalized.append(payload)@@ -892,12 +993,16 @@ class VikingClient:session_id: str,keep_recent_count: int = 0,user_id: Optional[str] = None,+ memory_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:await self.ensure_session(session_id, user_id=user_id)client = await self._session_client_for_user(user_id)return await client.commit_session(session_id,keep_recent_count=keep_recent_count,+ memory_policy=memory_policy+ if memory_policy is not None+ else self.default_memory_policy(),)async def commit(@@ -906,19 +1011,22 @@ class VikingClient:messages: list[dict[str, Any]],user_id: str = None,keep_recent_count: int = 0,+ peer_id: Optional[str] = None,+ memory_policy: Optional[Dict[str, Any]] = None,):"""Append messages to a stable session and commit it."""session_user_id = self._effective_session_user_id(user_id)appended = await self.append_messages(session_id,messages,- default_user_peer_id=session_user_id,+ default_user_peer_id=peer_id,session_user_id=session_user_id,)commit_result = await self.commit_session(session_id,keep_recent_count=keep_recent_count,user_id=session_user_id,+ memory_policy=memory_policy,)logger.debug(f"Committed OpenViking session {session_id}, "diff --git a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py b/bot/vikingbot/tests/unit/test_openviking_peer_identity.pynew file mode 100644index 000000000..49f340aac--- /dev/null+++ b/bot/vikingbot/tests/unit/test_openviking_peer_identity.py@@ -0,0 +1,223 @@+import sys+import types+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[4]))++config_module = types.ModuleType("vikingbot.config")+loader_module = types.ModuleType("vikingbot.config.loader")+loader_module.load_config = lambda: None+config_module.load_config = loader_module.load_config+sys.modules.setdefault("vikingbot.config", config_module)+sys.modules.setdefault("vikingbot.config.loader", loader_module)++from vikingbot.openviking_mount.ov_server import VikingClient+++def _client(api_key_type: str = "user") -> VikingClient:+ client = VikingClient.__new__(VikingClient)+ client.mode = "remote"+ client.api_key_type = api_key_type+ client.admin_user_id = "bot-user"+ client.agent_id = "agent-1"+ client._request_connection = None+ client._namespace_policy = {+ "isolate_user_scope_by_agent": False,+ "isolate_agent_scope_by_user": False,+ }+ return client+++def test_normalize_session_messages_maps_sender_to_peer_only_for_user_messages():+ client = _client()++ messages = [+ {"role": "user", "content": "hello", "sender_id": "telegram:alice"},+ {"role": "assistant", "content": "hi", "sender_id": "telegram:alice"},+ ]++ normalized = client._normalize_session_messages(messages)++ assert normalized[0]["peer_id"] == "telegram:alice"+ assert "peer_id" not in normalized[1]+++def test_normalize_session_messages_skips_path_like_peer_ids():+ client = _client()++ normalized = client._normalize_session_messages(+ [{"role": "user", "content": "hello", "sender_id": "bad/peer"}]+ )++ assert "peer_id" not in normalized[0]+++async def test_read_peer_profile_uses_current_user_peer_alias(monkeypatch):+ client = _client(api_key_type="user")+ calls = []++ async def fake_read_content(uri, level="read"):+ calls.append((uri, level))+ return "Alice profile"++ monkeypatch.setattr(client, "read_content", fake_read_content)++ profile = await client.read_peer_profile("telegram:alice")++ assert profile == "Alice profile"+ assert calls == [("viking://user/peers/telegram:alice/memories/profile.md", "read")]+++async def test_read_peer_profile_uses_explicit_user_namespace_for_root_key(monkeypatch):+ client = _client(api_key_type="root")+ calls = []++ async def fake_read_content(uri, level="read"):+ calls.append((uri, level))+ return "Alice profile"++ monkeypatch.setattr(client, "read_content", fake_read_content)++ profile = await client.read_peer_profile("telegram:alice")++ assert profile == "Alice profile"+ assert calls == [+ ("viking://user/bot-user/peers/telegram:alice/memories/profile.md", "read")+ ]+++async def test_read_user_profile_uses_current_user_self_alias_for_user_key(monkeypatch):+ client = _client(api_key_type="user")+ calls = []++ async def fake_read_content(uri, level="read"):+ calls.append((uri, level))+ return "Self profile"++ monkeypatch.setattr(client, "read_content", fake_read_content)++ profile = await client.read_user_profile("sender-is-peer")++ assert profile == "Self profile"+ assert calls == [("viking://user/memories/profile.md", "read")]+++async def test_commit_uses_current_user_key_session_and_sender_peer(monkeypatch):+ client = _client(api_key_type="user")+ calls = {}++ async def fake_append_messages(+ session_id,+ messages,+ default_user_peer_id=None,+ session_user_id=None,+ ):+ calls["append"] = {+ "session_id": session_id,+ "messages": messages,+ "default_user_peer_id": default_user_peer_id,+ "session_user_id": session_user_id,+ }+ return {"added": len(messages)}++ async def fake_commit_session(+ session_id, keep_recent_count=0, user_id=None, memory_policy=None+ ):+ calls["commit"] = {+ "session_id": session_id,+ "keep_recent_count": keep_recent_count,+ "user_id": user_id,+ "memory_policy": memory_policy,+ }+ return {"archived": True}++ monkeypatch.setattr(client, "append_messages", fake_append_messages)+ monkeypatch.setattr(client, "commit_session", fake_commit_session)++ await client.commit(+ "session-1",+ [{"role": "user", "content": "remember this"}],+ peer_id="telegram:alice",+ )++ assert calls["append"]["session_user_id"] is None+ assert calls["append"]["default_user_peer_id"] == "telegram:alice"+ assert calls["commit"]["user_id"] is None+ assert calls["commit"]["memory_policy"] is None+++async def test_commit_keeps_root_owner_user_explicit(monkeypatch):+ client = _client(api_key_type="root")+ calls = {}++ async def fake_append_messages(+ session_id,+ messages,+ default_user_peer_id=None,+ session_user_id=None,+ ):+ calls["append"] = {+ "default_user_peer_id": default_user_peer_id,+ "session_user_id": session_user_id,+ }+ return {"added": len(messages)}++ async def fake_commit_session(+ session_id, keep_recent_count=0, user_id=None, memory_policy=None+ ):+ calls["commit"] = {"user_id": user_id, "memory_policy": memory_policy}+ return {"archived": True}++ monkeypatch.setattr(client, "append_messages", fake_append_messages)+ monkeypatch.setattr(client, "commit_session", fake_commit_session)++ await client.commit(+ "session-1",+ [{"role": "user", "content": "remember this"}],+ peer_id="telegram:alice",+ )++ assert calls["append"]["session_user_id"] == "bot-user"+ assert calls["append"]["default_user_peer_id"] == "telegram:alice"+ assert calls["commit"]["user_id"] == "bot-user"+ assert calls["commit"]["memory_policy"] is None+++async def test_commit_session_defaults_to_peer_only_memory(monkeypatch):+ client = _client(api_key_type="user")+ calls = {}++ async def fake_ensure_session(session_id, user_id=None):+ calls["ensure"] = {"session_id": session_id, "user_id": user_id}+ return {"session_id": session_id}++ class FakeSessionClient:+ async def commit_session(self, session_id, keep_recent_count=0, memory_policy=None):+ calls["commit"] = {+ "session_id": session_id,+ "keep_recent_count": keep_recent_count,+ "memory_policy": memory_policy,+ }+ return {"archived": True}++ async def fake_session_client_for_user(user_id=None):+ calls["session_user_id"] = user_id+ return FakeSessionClient()++ monkeypatch.setattr(client, "ensure_session", fake_ensure_session)+ monkeypatch.setattr(client, "_session_client_for_user", fake_session_client_for_user)++ await client.commit_session("session-1", keep_recent_count=2)++ assert calls["commit"]["memory_policy"] == {+ "self": {"enabled": False},+ "peer": {"enabled": True},+ }diff --git a/bot/workspace/TOOLS.md b/bot/workspace/TOOLS.mdindex 9e5f2ae5f..1677c98a4 100644--- a/bot/workspace/TOOLS.md+++ b/bot/workspace/TOOLS.md@@ -27,9 +27,10 @@ List all resources at a specified path.### ⚠️ CRITICAL: Commit Memories and Events```-openviking_memory_commit(session_id: str, messages: list) -> str+openviking_memory_commit(messages: list[{"role": "user" | "assistant", "content": str}]) -> str```**All user's important conversations, information, and memories MUST be committed to OpenViking** for future retrieval and context understanding.+Do not pass a session_id; the tool creates a separate memory-commit session automatically. The returned string is JSON containing fields such as `status`, `memory_commit_session_id`, `source_session_id`, changed memory URIs, and commit task status.---diff --git a/tests/unit/test_locomo_peer_wiring.py b/tests/unit/test_locomo_peer_wiring.pynew file mode 100644index 000000000..d70c86a05--- /dev/null+++ b/tests/unit/test_locomo_peer_wiring.py@@ -0,0 +1,282 @@+import importlib.util+import json+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest+++def _load_module(module_name: str, relative_path: str):+ repo_root = Path(__file__).resolve().parents[2]+ module_path = repo_root / relative_path+ spec = importlib.util.spec_from_file_location(module_name, module_path)+ module = importlib.util.module_from_spec(spec)+ assert spec is not None and spec.loader is not None+ spec.loader.exec_module(module)+ return module+++IMPORT_TO_OV = _load_module(+ "test_import_to_ov_module", "benchmark/locomo/vikingbot/import_to_ov.py"+)+RUN_EVAL = _load_module("test_run_eval_module", "benchmark/locomo/vikingbot/run_eval.py")+++def _sample_payload():+ return {+ "sample_id": "conv-26",+ "conversation": {+ "speaker_a": "Alice",+ "speaker_b": "Bob",+ "session_1": [+ {"speaker": "Alice", "text": "Hi Bob"},+ {"speaker": "Bob", "text": "Hello Alice"},+ ],+ "session_1_date_time": "1:56 pm on 8 May, 2023",+ },+ "qa": [+ {+ "question": "Who said hello?",+ "answer": "Bob",+ "category": "1",+ "evidence": ["D1:2"],+ }+ ],+ }+++def test_build_memory_policy_writes_peer_only():+ assert IMPORT_TO_OV.build_memory_policy(False) == {+ "self": {"enabled": False},+ "peer": {"enabled": True},+ }+ assert IMPORT_TO_OV.build_memory_policy(True) == {+ "self": {"enabled": False},+ "peer": {"enabled": True},+ }+++def test_build_session_messages_non_group_uses_sample_peer_and_prefixes_speaker():+ sessions = IMPORT_TO_OV.build_session_messages(_sample_payload(), group_chat=False)++ assert len(sessions) == 1+ messages = sessions[0]["messages"]+ assert [msg["peer_id"] for msg in messages] == ["conv-26", "conv-26"]+ assert messages[0]["text"] == "Alice: Hi Bob"+ assert messages[1]["text"] == "Bob: Hello Alice"+++++async def test_viking_ingest_uses_message_peer_id(monkeypatch):+ calls = []++ class FakeClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ async def initialize(self):+ return None++ async def create_session(self, memory_policy=None):+ calls.append(("create_session", memory_policy))+ return {"session_id": "sess-1"}++ async def add_message(+ self, session_id=None, role=None, parts=None, created_at=None, peer_id=None+ ):+ calls.append(+ (+ "add_message",+ {+ "session_id": session_id,+ "role": role,+ "parts": parts,+ "created_at": created_at,+ "peer_id": peer_id,+ },+ )+ )++ async def commit_session(self, session_id, telemetry=True, memory_policy=None):+ calls.append(("commit_session", memory_policy))+ return {"status": "accepted", "task_id": None, "trace_id": "trace-1"}++ async def close(self):+ return None++ monkeypatch.setattr(IMPORT_TO_OV.ov, "AsyncHTTPClient", lambda **kwargs: FakeClient(**kwargs))++ result = await IMPORT_TO_OV.viking_ingest(+ messages=[{"role": "user", "text": "Alice: Hi Bob", "peer_id": "conv-26"}],+ openviking_url="http://localhost:1933",+ session_time=None,+ user_id="",+ account="",+ api_key="user-key",+ group_chat=False,+ )++ assert result["trace_id"] == "trace-1"+ add_calls = [entry for entry in calls if entry[0] == "add_message"]+ assert len(add_calls) == 1+ assert add_calls[0][1]["peer_id"] == "conv-26"+++def test_load_locomo_qa_keeps_internal_and_original_sample_ids(tmp_path):+ input_path = tmp_path / "locomo.json"+ input_path.write_text(json.dumps([_sample_payload()]), encoding="utf-8")++ qa_list = RUN_EVAL.load_locomo_qa(str(input_path))++ assert len(qa_list) == 1+ assert qa_list[0]["sample_id"] == "sample_0"+ assert qa_list[0]["original_sample_id"] == "conv-26"+ assert qa_list[0]["speakers"] == ["Alice", "Bob"]+++def test_run_vikingbot_chat_non_group_builds_sender_without_memory_peers(monkeypatch):+ calls = []++ def fake_run(cmd, capture_output, text, timeout=None, check=False):+ calls.append(cmd)+ return SimpleNamespace(+ stdout=json.dumps(+ {+ "text": "ok",+ "token_usage": {"total_tokens": 3},+ "time_cost": 0.1,+ "iteration": 1,+ "tools_used_names": [],+ }+ ),+ stderr="",+ )++ monkeypatch.setattr(RUN_EVAL.subprocess, "run", fake_run)++ response, token_usage, _time_cost, iteration, tools_used_names = RUN_EVAL.run_vikingbot_chat(+ question="Who said hello?",+ question_time="2023-05-08",+ sender_peer_id="conv-26",+ question_id="sample_0_qa0",+ config="/tmp/ov.conf",+ memory_peer_ids=None,+ )++ assert response == "ok"+ assert token_usage == {"total_tokens": 3}+ assert iteration == 1+ assert tools_used_names == []+ assert len(calls) == 2+ assert calls[0].count("--memory-peer") == 0+ assert calls[1].count("--memory-peer") == 0+ assert calls[0][calls[0].index("--sender") + 1] == "conv-26"+ assert calls[1][calls[1].index("--sender") + 1] == "conv-26"+++def test_run_eval_main_default_mode_uses_original_sample_id_as_sender_peer(monkeypatch, tmp_path):+ input_path = tmp_path / "locomo.json"+ output_path = tmp_path / "result.csv"+ errors_path = tmp_path / "errors.json"+ input_path.write_text(json.dumps([_sample_payload()]), encoding="utf-8")+ errors_path.write_text("[]", encoding="utf-8")++ captured = []++ def fake_run_vikingbot_chat(+ question,+ question_time=None,+ sender_peer_id=None,+ question_id=None,+ config=None,+ memory_peer_ids=None,+ ):+ captured.append(+ {+ "question": question,+ "question_time": question_time,+ "sender_peer_id": sender_peer_id,+ "question_id": question_id,+ "memory_peer_ids": memory_peer_ids,+ }+ )+ return ("ok", {"total_tokens": 1}, 0.1, 1, [])++ monkeypatch.setattr(RUN_EVAL, "run_vikingbot_chat", fake_run_vikingbot_chat)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "run_eval.py",+ str(input_path),+ "--output",+ str(output_path),+ "--errors",+ str(errors_path),+ "--threads",+ "1",+ ],+ )++ RUN_EVAL.main()++ assert len(captured) == 1+ assert captured[0]["sender_peer_id"] == "conv-26"+ assert captured[0]["memory_peer_ids"] is None+ assert captured[0]["question_id"] == "sample_0_qa0"+++def test_run_eval_main_group_chat_uses_speaker_peers(monkeypatch, tmp_path):+ input_path = tmp_path / "locomo.json"+ output_path = tmp_path / "result.csv"+ errors_path = tmp_path / "errors.json"+ input_path.write_text(json.dumps([_sample_payload()]), encoding="utf-8")+ errors_path.write_text("[]", encoding="utf-8")++ captured = []++ def fake_run_vikingbot_chat(+ question,+ question_time=None,+ sender_peer_id=None,+ question_id=None,+ config=None,+ memory_peer_ids=None,+ ):+ captured.append(+ {+ "question": question,+ "question_time": question_time,+ "sender_peer_id": sender_peer_id,+ "question_id": question_id,+ "memory_peer_ids": memory_peer_ids,+ }+ )+ return ("ok", {"total_tokens": 1}, 0.1, 1, [])++ monkeypatch.setattr(RUN_EVAL, "run_vikingbot_chat", fake_run_vikingbot_chat)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "run_eval.py",+ str(input_path),+ "--output",+ str(output_path),+ "--errors",+ str(errors_path),+ "--threads",+ "1",+ "--group-chat",+ ],+ )++ RUN_EVAL.main()++ assert len(captured) == 1+ assert captured[0]["sender_peer_id"] == "Alice"+ assert captured[0]["memory_peer_ids"] == ["Bob"]+ assert captured[0]["question_id"] == "sample_0_qa0"