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
优化 Skill 同步机制,降低首次会话 TTFT 并保留热加载能力
de453e86c2b0f7f
diff --git a/jiuwenswarm/server/runtime/sync_agents_configs.py b/jiuwenswarm/server/runtime/sync_agents_configs.pyindex fedcaf149a..30ee58bb1e 100644--- a/jiuwenswarm/server/runtime/sync_agents_configs.py+++ b/jiuwenswarm/server/runtime/sync_agents_configs.py@@ -8,8 +8,6 @@ import copyimport hashlibimport jsonimport logging-import os-from pathlib import Pathfrom dataclasses import asdict, dataclassfrom typing import Any@@ -212,83 +210,18 @@ def synthesize_config(return result-def _collect_shared_skill_disk_paths(env: dict[str, Any]) -> str:- """扫描 env 声明的共享 skill 目录,返回排序去重的 skill 目录完整路径清单(用于 content_hash)。-- office agent 的 ENABLED_SKILLS 被 suppress 成 ''(allow-all),其有效 skill 集- = 共享目录磁盘内容;装/卸 skill 只改目录子项、不改 env 本身,导致- compute_content_hash 算出相同 hash → sidecar 判 "unchanged" → 跳过 reload →- 运行中会话的 SkillUseRail 永不重建(interface_deep.py:8146 重建块不执行)。- 把该清单纳入 content_hash,使装/卸 skill 能让 hash 变化 → "updated" → reload- → SkillUseRail 重建。env 无 JIUWENSWARM_SHARED_SKILLS_DIRS 时返回 ""(无磁盘 I/O)。-- 记录「完整路径」而非「目录 basename」:共享目录可能多根(office-claw-skills 预置- + .office-claw/skills 用户装),若两根存在同名子目录,basename 集合会丢根维度——- 「删首根同名 skill、次根留同名」时 SkillUseRail 可见内容会变(切到次根那份),但- basename 集合不变 → 漏触发 reload。完整路径保留 (root, name) 身份,hash 精确反映- 磁盘 skill 集,对 rail 去重语义的将来变更也更稳健。-- 已知行为(resolve 穿透软链接):key 用 ``Path.resolve()`` 取真实路径,- 多个软链接若同指一个真实 skill 目录,resolve 后得到相同字符串,- 在清单里被合并为一条。故增删其中任一软链接(只要仍有至少一个链接指向- 该真实 skill)不改变 realpath 集合 → content_hash 不变 → 不触发 reload。- 此为预期:内容未变(同一份 SKILL.md 仍在)时不应 reload。若业务要求- "增删任一软链接入口即触发 reload",需改用 ``Path.absolute()`` 保留逻辑- 路径身份,但代价是同一真实 skill 会被 SkillUseRail 重复加载(两条 key、- 两份 Skill 对象、工具重复注册);且须与 SkillUseRail 内部 key 口径- (``str(item.resolve())``,skill_use_rail.py:450)同步调整,避免两层错位。- """- if not isinstance(env, dict):- return ""- # 兼容 JIUWENSWARM_* / JIUWENCLAW_* 别名(relay 可能发任一形式)- raw = ""- for key in ("JIUWENSWARM_SHARED_SKILLS_DIRS", "JIUWENCLAW_SHARED_SKILLS_DIRS"):- val = env.get(key)- if val:- raw = str(val)- break- if not raw.strip():- return ""-- from jiuwenswarm.common.utils import parse_shared_skills_dirs_raw-- dirs = parse_shared_skills_dirs_raw(raw) # 按 os.pathsep 切分,去重,绝对化- paths: set[str] = set()- for d in dirs:- try:- for entry in os.scandir(d):- if not (entry.is_dir() or entry.is_symlink()):- continue- if entry.name.startswith("_"):- continue- # 与 rail/relay 口径一致:仅算含 SKILL.md 的子目录- if not os.path.isfile(os.path.join(entry.path, "SKILL.md")):- continue- # resolve() 保留 (root, name) 身份,跨根同名目录各算一条- paths.add(str(Path(entry.path).resolve()))- except OSError:- continue- return ",".join(sorted(paths))--def compute_content_hash(*,config: dict[str, Any],env: dict[str, Any],runtime: dict[str, Any],) -> str:- """Stable SHA-256 of config + env + runtime + shared-skill disk paths JSON.-- shared_skill_disk_paths 捕获共享 skill 目录的磁盘 skill 集(office allow-all- agent 的有效 skill 集,按完整路径记录以保留根维度),使装/卸 skill 能让 hash- 变化、触发 reload+rail 重建。- """+ """Stable SHA-256 of config + env + runtime JSON."""payload = json.dumps({"config": config,"env": env,"runtime": runtime,- "shared_skill_disk_paths": _collect_shared_skill_disk_paths(env),},sort_keys=True,separators=(",", ":"),diff --git a/tests/unit_tests/agentserver/test_sync_agents_configs.py b/tests/unit_tests/agentserver/test_sync_agents_configs.pyindex 55ade7a743..3d6cc6aa9a 100644--- a/tests/unit_tests/agentserver/test_sync_agents_configs.py+++ b/tests/unit_tests/agentserver/test_sync_agents_configs.py@@ -457,6 +457,41 @@ async def test_sync_same_revision_fast_path_unchanged(mock_warmup):assert mock_warmup.await_count == warmup_calls_after_first+async def test_sync_skills_revision_forces_live_agent_update(mock_warmup):+ pool = TenantAgentPool.get_instance()++ first = await pool.sync_agents_configs(_sync_payload(revision="r1", agents=[+ {+ "agent_id": "office",+ "config": {},+ "env": _full_env(ENABLED_SKILLS="same-skill"),+ "runtime": {"skills_revision": 0},+ }+ ]))+ assert first["agents"][0]["action"] in {"added", "updated"}++ unchanged = await pool.sync_agents_configs(_sync_payload(revision="r2", agents=[+ {+ "agent_id": "office",+ "config": {},+ "env": _full_env(ENABLED_SKILLS="same-skill"),+ "runtime": {"skills_revision": 0},+ }+ ]))+ assert unchanged["agents"][0]["action"] == "unchanged"++ changed = await pool.sync_agents_configs(_sync_payload(revision="r3", agents=[+ {+ "agent_id": "office",+ "config": {},+ "env": _full_env(ENABLED_SKILLS="same-skill"),+ "runtime": {"skills_revision": 1},+ }+ ]))+ assert changed["agents"][0]["action"] == "updated"++@pytest.mark.asyncioasync def test_sync_update_model_name_replaces_tip(mock_warmup):pool = TenantAgentPool.get_instance()@@ -789,38 +824,35 @@ def test_build_agent_spec_hash_stable():assert a.content_hash == b.content_hash-def test_compute_content_hash_reflects_shared_skill_disk_changes(tmp_path):- """装/卸共享目录里的 skill 应让 content_hash 变化(office allow-all agent 的有效 skill 集 = 磁盘内容)。-- 回归根因:office 的 ENABLED_SKILLS 被 suppress 成 ''(恒定)、共享目录路径也恒定,- 故装 skill 不改 env 本身。content_hash 必须纳入磁盘 skill 名清单,否则 sidecar- 判 "unchanged" → 跳过 reload → 运行中会话的 SkillUseRail 永不重建(调不到新 skill)。- """+def test_compute_content_hash_does_not_scan_shared_skill_directories(tmp_path, monkeypatch):+ """Catalog hash must stay metadata-only; Relay already sends effective skill/config state."""shared_dir = tmp_path / "skills"shared_dir.mkdir()env = _full_env(JIUWENSWARM_SHARED_SKILLS_DIRS=str(shared_dir))- base_hash = compute_content_hash(config={}, env=env, runtime={})-- # 装一个含 SKILL.md 的子目录 → hash 应变smart = shared_dir / "smart-charts"smart.mkdir()(smart / "SKILL.md").write_text("# smart-charts")- installed_hash = compute_content_hash(config={}, env=env, runtime={})- assert installed_hash != base_hash, "安装 skill 后 content_hash 必须变化"- # 不含 SKILL.md 的杂目录(含 _ 前缀)不应影响 hash- junk = shared_dir / "_draft"- junk.mkdir()- (junk / "note.txt").write_text("noise")- assert compute_content_hash(config={}, env=env, runtime={}) == installed_hash+ def fail_if_scanned(*_args, **_kwargs):+ raise AssertionError("content hash must not scan shared skill directories")- # 卸载 smart-charts → hash 应回到装前- import shutil+ monkeypatch.setattr(os, "scandir", fail_if_scanned)+ first = compute_content_hash(config={}, env=env, runtime={})- shutil.rmtree(smart)- removed_hash = compute_content_hash(config={}, env=env, runtime={})- assert removed_hash == base_hash, "卸载 skill 后 content_hash 必须回到原值"+ another = shared_dir / "another-skill"+ another.mkdir()+ (another / "SKILL.md").write_text("# another-skill")+ second = compute_content_hash(config={}, env=env, runtime={})+ assert first == second++ assert first != compute_content_hash(config={"prompt": "changed"}, env=env, runtime={})+ assert first != compute_content_hash(+ config={}, env={**env, "ENABLED_SKILLS": "another-skill"}, runtime={}+ )+ assert first != compute_content_hash(+ config={}, env=env, runtime={"skills": ["another-skill"]}+ )def test_compute_content_hash_no_shared_dirs_is_stable():@@ -831,39 +863,6 @@ def test_compute_content_hash_no_shared_dirs_is_stable():assert a == b-def test_compute_content_hash_preserves_root_dimension_for_same_name_skill(tmp_path):- """两根目录存在同名 skill 子目录时,hash 必须保留根维度。-- 回归评审意见:basename 集合会丢根维度——root_a/shared 与 root_b/shared 都记成- "shared",删首根留次根时 basename 集合不变 → 漏触发 reload,而 SkillUseRail- 可见内容其实切到了次根那份。完整路径保留 (root, name) 身份,此场景下 hash 必变。- """- root_a = tmp_path / "root_a"- root_b = tmp_path / "root_b"- root_a.mkdir()- root_b.mkdir()- (root_a / "shared" / "SKILL.md").parent.mkdir(parents=True)- (root_a / "shared" / "SKILL.md").write_text("# from root_a")- (root_b / "shared" / "SKILL.md").parent.mkdir(parents=True)- (root_b / "shared" / "SKILL.md").write_text("# from root_b")- dirs = f"{root_a}{os.pathsep}{root_b}"- env = _full_env(JIUWENSWARM_SHARED_SKILLS_DIRS=dirs)-- both_hash = compute_content_hash(config={}, env=env, runtime={})-- # 删首根的 shared,仅留次根同名 → 可见内容切换,hash 必变(basename 集合会漏)- import shutil-- shutil.rmtree(root_a / "shared")- after_delete_hash = compute_content_hash(config={}, env=env, runtime={})- assert after_delete_hash != both_hash, "删首根同名 skill 后 hash 必须变化(完整路径保留根维度)"-- # 恢复首根 shared → 回到 both_hash- (root_a / "shared" / "SKILL.md").parent.mkdir(parents=True, exist_ok=True)- (root_a / "shared" / "SKILL.md").write_text("# from root_a")- assert compute_content_hash(config={}, env=env, runtime={}) == both_hash--# ---------------------------------------------------------------------------# 10. officeclaw guard# ---------------------------------------------------------------------------