JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(memory): 用户画像改按需拉取,去掉进程级后台周期任务
zhouguohao6fc1af4b92eb
diff --git a/jiuwenswarm/agents/harness/common/memory/external_memory_config.py b/jiuwenswarm/agents/harness/common/memory/external_memory_config.pyindex 432e9a60c9..1c9a0eb8aa 100644--- a/jiuwenswarm/agents/harness/common/memory/external_memory_config.py+++ b/jiuwenswarm/agents/harness/common/memory/external_memory_config.py@@ -99,7 +99,7 @@ def _is_cloud_deployment() -> bool:未设置或其他值视为 PC 端(向后兼容)。"""- return os.environ.get("OFFICE_ACE_DEPLOYMENT", "").strip().lower() == "cloud"+ return os.environ.get("OFFICE_ACE_DEPLOYMENT", "pc").strip().lower() == "cloud"def get_office_ace_user_profile_config(diff --git a/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/__init__.py b/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/__init__.pyindex 5dfa7af1fd..33f9517039 100644--- a/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/__init__.py+++ b/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/__init__.py@@ -11,10 +11,12 @@凭据/endpoint/user_id 由 config.yaml ``memory.office_ace_user_profile`` 段提供,relay-claw 经 env 覆盖占位符下发(配置替换,同 agentarts memory 模式)。++画像按需拉取:rail 的 ``before_model_call`` 在本地缓存失效时才 fetch,+无进程级后台周期任务。"""from __future__ import annotations-from .background import user_profile_background_managerfrom .fetcher import UserProfileConfig, UserProfileFetcherfrom .office_ace_user_profile_rail import OfficeAceUserProfileRailfrom .section import SECTION_NAME, build_office_ace_user_profile_section@@ -25,5 +27,4 @@ __all__ = ["UserProfileConfig","UserProfileFetcher","build_office_ace_user_profile_section",- "user_profile_background_manager",]diff --git a/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/background.py b/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/background.pydeleted file mode 100644index 802711d0d6..0000000000--- a/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/background.py+++ /dev/null@@ -1,112 +0,0 @@-# coding: utf-8-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""进程级后台拉取管理器 — 周期拉取云端用户画像概览,生命周期挂在 AgentWebSocketServer。--与 rail 实例解耦:rail 卸载只影响 prompt 注入,后台拉取不中断。-每 tick 先重读 config(``get_office_ace_user_profile_config``),配置热修改即时生效:-* enabled & endpoint/api_key/user_id 齐全 → fetch-* 否则 skip(配置关了/不全就停拉,但不杀任务,等下次 tick 再判)-"""-from __future__ import annotations--import asyncio-from typing import Any, Optional--from jiuwenswarm.agents.harness.common.memory.external_memory_config import (- get_office_ace_user_profile_config,-)-from jiuwenswarm.agents.harness.common.rails.office_ace_user_profile.fetcher import (- UserProfileConfig,- UserProfileFetcher,-)-from jiuwenswarm.common.utils import logger--# tick 之间最小 sleep 上限(秒),避免 interval 配 0/负值导致 busy-loop-_MIN_TICK_SLEEP_SECONDS = 60---class _UserProfileBackgroundManager:- """进程级单例后台拉取管理器。-- 生命周期由 :meth:`start` / :meth:`stop` 驱动(挂在 ws_server 进程级)。- rail 不再启动/取消后台任务——``init``/``uninit`` 只管 prompt 段注入。- """-- def __init__(self) -> None:- self._task: Optional[asyncio.Task[Any]] = None- self._stopping = False-- @classmethod- def get(cls) -> "_UserProfileBackgroundManager":- """懒单例。"""- global _manager_instance- if _manager_instance is None:- _manager_instance = cls()- return _manager_instance-- async def start(self) -> None:- """启动后台周期拉取(幂等:已运行则直接返回)。"""- if self._task is not None and not self._task.done():- return- self._stopping = False- try:- self._task = asyncio.create_task(self._loop(), name="user-profile-bg")- logger.info("[UserProfileBackgroundManager] background task started")- except RuntimeError:- # 无事件循环(非 async 上下文)——跳过,不影响主流程- logger.warning(- "[UserProfileBackgroundManager] no event loop; task not started",- )-- async def stop(self) -> None:- """停止后台任务(幂等)。"""- self._stopping = True- task = self._task- self._task = None- if task is not None and not task.done():- task.cancel()- try:- await task- except asyncio.CancelledError:- pass- except Exception as exc: # noqa: BLE001- logger.warning(- "[UserProfileBackgroundManager] task cancel failed: %s", exc- )-- async def _loop(self) -> None:- """周期拉取主循环。每 tick 重读 config,配置热修改即时生效。"""- from jiuwenswarm.common.config import get_config-- while not self._stopping:- try:- cfg = get_office_ace_user_profile_config(get_config())- interval = max(1, int(cfg.get("fetch_interval_minutes", 10) or 10))- # enabled 已综合:external memory 开关 + provider=officeace_cloud + 凭证齐全- if cfg.get("enabled"):- fetcher = UserProfileFetcher(UserProfileConfig(**cfg))- await fetcher.fetch_once()- else:- logger.debug(- "[UserProfileBackgroundManager] skip tick "- "(external memory off / provider not officeace_cloud / "- "credentials incomplete)",- )- except Exception as exc: # noqa: BLE001- logger.debug(- "[UserProfileBackgroundManager] tick error: %s", exc- )- if self._stopping:- break- await asyncio.sleep(max(_MIN_TICK_SLEEP_SECONDS, interval * 60))---_manager_instance: Optional[_UserProfileBackgroundManager] = None---def user_profile_background_manager() -> _UserProfileBackgroundManager:- """返回进程级单例。"""- return _UserProfileBackgroundManager.get()---__all__ = ["user_profile_background_manager"]diff --git a/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/fetcher.py b/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/fetcher.pyindex 0f91977c8b..4e9681d7e6 100644--- a/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/fetcher.py+++ b/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/fetcher.py@@ -18,13 +18,13 @@from __future__ import annotationsimport asyncio-import jsonimport loggingimport osimport tempfile+import timefrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Optional+from typing import Optionalimport httpx@@ -48,19 +48,31 @@ class UserProfileConfig:space_id: str = ""-def _default_cache_dir() -> Path:- """``~/.jiuwenswarm/memory``(受 ``JIUWENSWARM_DATA_DIR`` 覆盖)。"""- from jiuwenswarm.common.utils import get_user_workspace_dir+def _default_cache_dir(user_id: str) -> Path:+ """``~/.office-claw/users/<userId>/``(与 relay-claw resolveUserConfigDir 对齐)。- return get_user_workspace_dir() / "memory"+ global root 取 ``OFFICE_CLAW_GLOBAL_CONFIG_ROOT``,否则 ``Path.home()``。+ userId 段经 ``urllib.parse.quote`` 编码(对齐 relay-claw encodeUserIdPathSegment)。+ 无 userId 时回落到 ``~/.office-claw/`` 全局目录。+ """+ from urllib.parse import quote++ global_root = (os.getenv("OFFICE_CLAW_GLOBAL_CONFIG_ROOT") or "").strip()+ base = Path(global_root) if global_root else Path.home()+ office_claw_dir = base / ".office-claw"+ normalized_uid = (user_id or "").strip()+ if not normalized_uid:+ return office_claw_dir+ return office_claw_dir / "users" / quote(normalized_uid, safe="")class UserProfileFetcher:"""周期拉取云端用户画像概览,原子写本地缓存。- 缓存文件:- * ``{cache_dir}/user_profile_{user_id}.md`` — 概览正文- * ``{cache_dir}/user_profile_{user_id}.meta.json`` — version/updatedAt/lastSyncAt+ 缓存文件(默认):+ * ``~/.office-claw/users/<userId>/user-profile.md`` — 概览正文++ 新鲜度判定读缓存文件 mtime(距上次写 < fetch_interval 即新鲜),无需 meta 边车文件。线程安全:``read_cache`` 同步读,``fetch_once`` 异步写。后台周期任务与 ``before_model_call`` 的同步拉取可能并发写同一文件;原子写(tmp→rename)@@ -73,7 +85,7 @@ class UserProfileFetcher:cache_dir: Optional[Path] = None,) -> None:self._config = config- self._cache_dir = cache_dir or _default_cache_dir()+ self._cache_dir = cache_dir or _default_cache_dir(config.user_id)# ------------------------------------------------------------------# Paths@@ -85,11 +97,7 @@ class UserProfileFetcher:@propertydef cache_path(self) -> Path:- return self._cache_dir / f"user_profile_{self._config.user_id}.md"-- @property- def meta_path(self) -> Path:- return self._cache_dir / f"user_profile_{self._config.user_id}.meta.json"+ return self._cache_dir / "user-profile.md"# ------------------------------------------------------------------# Public API@@ -172,33 +180,22 @@ class UserProfileFetcher:return Nonedef _is_cache_fresh(self) -> bool:- """本地缓存是否新鲜(距上次拉取 < fetch_interval)。+ """本地缓存是否新鲜(距上次写入 < fetch_interval)。- meta.json 的 ``lastSyncAt``(ISO 8601)+ ``fetch_interval_minutes`` 判断。- 缓存文件不存在、meta 缺失/解析失败/时间已过 → False。+ 读缓存文件 mtime(``cache_path.stat().st_mtime``)+ ``fetch_interval_minutes`` 判断。+ 缓存文件不存在或 mtime 已过 fetch_interval → False。无需 meta 边车文件。"""- if not self.cache_path.exists():- return False- meta = self._read_meta()- last_sync = meta.get("lastSyncAt")- if not last_sync:- return Falsetry:- from datetime import datetime, timezone-- # 兼容带/不带时区的 ISO 串(如 "...Z" 或 "...+00:00")- dt = datetime.fromisoformat(last_sync.replace("Z", "+00:00"))- if dt.tzinfo is None:- dt = dt.replace(tzinfo=timezone.utc)- elapsed = (datetime.now(timezone.utc) - dt).total_seconds()- return elapsed < self._config.fetch_interval_minutes * 60- except (ValueError, TypeError) as exc:+ mtime = self.cache_path.stat().st_mtime+ except OSError as exc:logger.debug(- "[UserProfileFetcher] parse lastSyncAt failed (user=%s): %s",+ "[UserProfileFetcher] stat cache failed (user=%s): %s",self._config.user_id,exc,)return False+ elapsed = time.time() - mtime+ return elapsed < self._config.fetch_interval_minutes * 60# ------------------------------------------------------------------# Internal@@ -222,7 +219,7 @@ class UserProfileFetcher:@staticmethoddef _is_cloud() -> bool:"""True iff OFFICE_ACE_DEPLOYMENT=cloud。"""- return os.environ.get("OFFICE_ACE_DEPLOYMENT", "").strip().lower() == "cloud"+ return os.environ.get("OFFICE_ACE_DEPLOYMENT", "pc").strip().lower() == "cloud"def _build_url(self) -> str:base = self._config.endpoint.rstrip("/")@@ -237,14 +234,6 @@ class UserProfileFetcher:# chat-service-app-api-memory.yaml:GET /v1/appapi/memory/user-profilereturn f"{base}/v1/appapi/memory/user-profile"- def _read_meta(self) -> dict[str, Any]:- try:- if not self.meta_path.exists():- return {}- return json.loads(self.meta_path.read_text(encoding="utf-8"))- except (OSError, ValueError):- return {}-def _handle_response(self,resp: httpx.Response,@@ -287,7 +276,7 @@ class UserProfileFetcher:)return None- self._write_cache_atomic(body, resp)+ self._write_cache_atomic(body)logger.info("[UserProfileFetcher] fetched ok (user=%s, %d chars)",self._config.user_id,@@ -321,27 +310,10 @@ class UserProfileFetcher:return Nonereturn content- def _write_cache_atomic(- self,- body: str,- resp: httpx.Response,- ) -> None:- """tmp→rename 原子写 md + meta.json。"""+ def _write_cache_atomic(self, body: str) -> None:+ """tmp→rename 原子写 md。新鲜度由文件 mtime 判定,无需 meta 边车文件。"""try:self._cache_dir.mkdir(parents=True, exist_ok=True)- # 先写 meta.json(失败不影响 md)- meta: dict[str, Any] = {}- try:- data = resp.json()- if isinstance(data, dict):- # 新契约字段:revision(版本号)、updated_at(更新时间)- meta["version"] = data.get("revision")- meta["updatedAt"] = data.get("updated_at")- except ValueError:- pass- meta["lastSyncAt"] = self._now_iso()-- self._atomic_write_text(self.meta_path, json.dumps(meta, ensure_ascii=False))self._atomic_write_text(self.cache_path, body)except OSError as exc:logger.warning(@@ -379,11 +351,5 @@ class UserProfileFetcher:except Exception: # noqa: BLE001return "<unreadable>"- @staticmethod- def _now_iso() -> str:- from datetime import datetime, timezone-- return datetime.now(timezone.utc).isoformat()-__all__ = ["UserProfileConfig", "UserProfileFetcher"]diff --git a/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/office_ace_user_profile_rail.py b/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/office_ace_user_profile_rail.pyindex 48b3ba39ab..3314015115 100644--- a/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/office_ace_user_profile_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/office_ace_user_profile/office_ace_user_profile_rail.py@@ -38,8 +38,9 @@ if TYPE_CHECKING:class OfficeAceUserProfileRail(DeepAgentRail):"""Inject the cloud-side user profile (memory overview) into the system prompt.- Loaded source: ``~/.jiuwenswarm/memory/user_profile_{userId}.md``, written- by :class:`UserProfileFetcher` (background periodic + on-missing sync fetch).+ Loaded source: ``~/.office-claw/users/<userId>/user-profile.md``, written+ by :class:`UserProfileFetcher` (on-demand sync fetch in ``before_model_call``+ when the local cache is missing or stale).Priority 130 — higher than ProjectMemoryRail (120), lower than runtime promptrails, so the user profile sits close to the agent's runtime identity.@@ -71,7 +72,7 @@ class OfficeAceUserProfileRail(DeepAgentRail):)def uninit(self, agent: "DeepAgent") -> None:- """清段。后台周期拉取由进程级 manager 负责,不在此取消。"""+ """清段。无后台周期任务,仅需移除注入的 prompt 段。"""if self._system_prompt_builder is not None:try:self._system_prompt_builder.remove_section(SECTION_NAME)diff --git a/jiuwenswarm/common/local_env_config.py b/jiuwenswarm/common/local_env_config.pyindex 3035826497..b0763114c1 100644--- a/jiuwenswarm/common/local_env_config.py+++ b/jiuwenswarm/common/local_env_config.py@@ -93,18 +93,6 @@ SPAWN_ENV_KEYS: frozenset[str] = frozenset("EXTENSION_DIRS",# Comma-separated source basenames loaded from EXTENSION_DIRS/model_clients at startup."AGENT_EXTRA_MODEL_CLIENTS",- "MEMORY_ENGINE",- "MEMORY_USER_ID",- "MEMORY_EXTERNAL_PROVIDER",- "AGENTARTS_MEMORY_BASE_URL",- "AGENTARTS_MEMORY_API_KEY",- "OFFICE_ACE_USER_PROFILE_ENABLED",- "OFFICE_ACE_USER_PROFILE_ENDPOINT",- "OFFICE_ACE_USER_PROFILE_API_KEY",- "OFFICE_ACE_USER_PROFILE_FETCH_INTERVAL",- "OFFICE_ACE_USER_PROFILE_MAX_CHARS",- "OFFICE_ACE_USER_PROFILE_TIMEOUT",- "OFFICE_ACE_DEPLOYMENT",})@@ -120,6 +108,18 @@ BUSINESS_MIRROR_KEYS: frozenset[str] = frozenset("API_KEY","API_BASE","MEMORY_ENGINE",+ "MEMORY_EXTERNAL_PROVIDER",+ "MEMORY_USER_ID",+ "AGENTARTS_MEMORY_BASE_URL",+ "AGENTARTS_MEMORY_API_KEY",+ "AGENTARTS_MEMORY_SPACE_ID",+ "OFFICE_ACE_DEPLOYMENT",+ "OFFICE_ACE_USER_PROFILE_ENABLED",+ "OFFICE_ACE_USER_PROFILE_ENDPOINT",+ "OFFICE_ACE_USER_PROFILE_API_KEY",+ "OFFICE_ACE_USER_PROFILE_FETCH_INTERVAL",+ "OFFICE_ACE_USER_PROFILE_MAX_CHARS",+ "OFFICE_ACE_USER_PROFILE_TIMEOUT","EVOLUTION_ENABLED","EMBED_API_KEY","EMBED_API_BASE",diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 2239f1a8c6..e1d450f3b6 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -533,19 +533,6 @@ class AgentWebSocketServer:# 启动 (用户依然可以在 TUI 里跑 /sandbox enable 重试)。await self._bootstrap_internal_jiuwenbox()await self._start_loop_lag_monitor()- # OfficeAce 用户画像后台周期拉取(进程级单例,与 rail 实例解耦;- # rail 卸载只影响 prompt 注入,后台拉取不中断。config 每 tick 重读。)- try:- from jiuwenswarm.agents.harness.common.rails.office_ace_user_profile.background import (- user_profile_background_manager,- )-- await user_profile_background_manager().start()- except Exception as exc: # noqa: BLE001- logger.warning(- "[AgentWebSocketServer] user profile background manager start failed: %s",- exc,- )async def _start_loop_lag_monitor(self) -> None:"""启动事件循环 lag 观测 task 与停摆探针(验收用,不主动断连/不发应用心跳)。"""@@ -965,18 +952,6 @@ class AgentWebSocketServer:lag_task = self._loop_lag_taskself._loop_lag_task = Noneawait _cancel_warmup_task(lag_task, "loop lag monitor")- # OfficeAce 用户画像后台拉取(进程级单例,随 server 退出停止)- try:- from jiuwenswarm.agents.harness.common.rails.office_ace_user_profile.background import (- user_profile_background_manager,- )-- await user_profile_background_manager().stop()- except Exception as exc: # noqa: BLE001- logger.warning(- "[AgentWebSocketServer] user profile background manager stop failed: %s",- exc,- )had_server = self._server is not Noneif had_server:self._server.close()diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 31fdbea12d..d16e8aa84e 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -21187,10 +21187,8 @@ class JiuWenSwarmDeepAdapter:"""Register / unregister OfficeAceUserProfileRail based on config.Mode-independent(同 ExternalMemoryRail),不随 config 热重载销毁。- 后台周期拉取由进程级 ``user_profile_background_manager`` 管理- (挂在 AgentWebSocketServer 生命周期),与此处 rail 注册/卸载解耦——- rail 卸载只影响 prompt 注入,后台拉取不中断;config 每 tick 重读,- endpoint/interval/enabled 热修改即时生效。+ 画像按需拉取:rail 的 before_model_call 在本地缓存失效时才 fetch+ (per-agent user_id)。"""from jiuwenswarm.agents.harness.common.memory.external_memory_config import (is_office_ace_user_profile_enabled,