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: SwarmSkillHub Provider 扩展包化与 SPI 下载验签契约开放
huben2c49c5831c79
diff --git a/deploy/enterprise/templates/agentserver.template.env b/deploy/enterprise/templates/agentserver.template.envindex 9d2b5d19d1..4dbc6898e5 100644--- a/deploy/enterprise/templates/agentserver.template.env+++ b/deploy/enterprise/templates/agentserver.template.env@@ -10,6 +10,11 @@ HOME=<<AGENT_SERVER_HOME>>LOG_ROOT_PATH=<<AGENT_SERVER_HOME>>JIUWENSWARM_EDITION=enterprise+# 扩展包搜索目录(企业版 agentserver 技能源等扩展)+EXTENSION_DIRS=<<CLAW_POD_CODE_PATH>>/packages/jiuwenclaw-ee/agentserver/extensions+# pod 内代码路径(与 gateway 对齐,便于排查时核对 EXTENSION_DIRS 渲染结果)+CLAW_POD_CODE_PATH=<<CLAW_POD_CODE_PATH>>+# Skill 动态授权(默认关闭;开启后声明 skill_permissions.json 的技能加载时需审批)SKILL_AUTHORIZATION_ENABLED=<<SKILL_AUTHORIZATION_ENABLED>>diff --git a/jiuwenswarm/extensions/sdk/skill_source.py b/jiuwenswarm/extensions/sdk/skill_source.pyindex 9421d7e251..6c86816c9a 100644--- a/jiuwenswarm/extensions/sdk/skill_source.py+++ b/jiuwenswarm/extensions/sdk/skill_source.py@@ -8,10 +8,16 @@ They deliberately do not install, update, or remove workspace files.from __future__ import annotations+import hashlib+import io+import zipfilefrom abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import Any, Mapping, Sequence+from urllib.parse import urlparse++import httpxfrom jiuwenswarm.extensions.sdk.base import BaseExtension@@ -219,12 +225,36 @@ class SkillSourceProvider(ABC):display_name: strcapabilities: frozenset[str]+ # 信任策略内聚在 Provider:由扩展工厂/宿主在构造后经 set_trust_policy()+ # 注入,验签默认实现据此执行;类级默认值保证未调用 super().__init__()+ # 的子类也可安全读取。+ _trust_policy: TrustPolicy | None = None+ _secret_resolver: SecretResolver | None = None+ # Provider 显式声明的默认下载主机白名单:注册来源时并入+ # SourceConfig.download_policy(管理面显式配置的 allowed_hosts 优先);+ # 两者皆空时安装链路 fail-closed 拒绝下载。+ download_allowed_hosts: tuple[str, ...] = ()+async def start(self) -> None:return Noneasync def close(self) -> None:return None+ def set_trust_policy(+ self,+ trust_policy: TrustPolicy | None,+ secret_resolver: SecretResolver | None = None,+ ) -> None:+ """Inject the source trust policy after construction.++ Called by the extension factory or the host runtime; the default+ ``verify_artifact`` implementation verifies against it.+ """+ self._trust_policy = trust_policy+ if secret_resolver is not None:+ self._secret_resolver = secret_resolver+@abstractmethodasync def search(self,@@ -249,6 +279,81 @@ class SkillSourceProvider(ABC):) -> ArtifactDescriptor:raise NotImplementedError+ async def download_artifact(+ self,+ descriptor: ArtifactDescriptor,+ download_policy: DownloadPolicy | None = None,+ ) -> bytes:+ """Download artifact bytes under the platform's secure download policy.++ The default enforces HTTPS-only URLs, forbids redirects, applies the+ DownloadPolicy ``max_bytes``/``timeout_seconds`` limits (timeout is+ clamped to at least 30s, matching the platform's historical behavior),+ requires a ZIP payload (PK magic, intact archive) and checks the+ descriptor's ``checksum_sha256`` when present. Providers may override+ to customize the download.+ """+ download_url = str(descriptor.download_url or "").strip()+ parsed = urlparse(download_url)+ if parsed.scheme != "https" or not parsed.hostname:+ raise RuntimeError("skill 下载 URL 必须是 HTTPS 地址")+ policy = download_policy or DownloadPolicy()+ timeout = max(30.0, policy.timeout_seconds or DownloadPolicy.timeout_seconds)+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=False) as client:+ resp = await client.get(download_url)+ if resp.is_redirect:+ raise RuntimeError("skill 下载不支持自动跳转,请提供最终制品地址")+ resp.raise_for_status()+ body = resp.content or b""++ if not body:+ raise RuntimeError("下载内容为空")+ if len(body) > policy.max_bytes:+ raise RuntimeError("下载内容超过来源允许的最大大小")+ if len(body) < 4 or not body.startswith(b"PK"):+ raise RuntimeError("下载内容不是 ZIP 文件")++ expected_sha256 = str(descriptor.checksum_sha256 or "").strip().lower()+ if expected_sha256 and hashlib.sha256(body).hexdigest().lower() != expected_sha256:+ raise RuntimeError("下载文件校验失败(SHA256 不匹配)")++ try:+ with zipfile.ZipFile(io.BytesIO(body), "r") as zf:+ if zf.testzip() is not None:+ raise RuntimeError("下载 ZIP 文件已损坏")+ except zipfile.BadZipFile as exc:+ raise RuntimeError("下载内容不是有效 ZIP 文件") from exc+ return body++ async def verify_artifact(+ self,+ descriptor: ArtifactDescriptor,+ content: bytes,+ ) -> Mapping[str, Any] | None:+ """Verify downloaded artifact bytes before installation.++ Returns the verification audit mapping recorded on the installation,+ or None when the artifact carries no signature and the trust policy+ is ``if-present``; raises ArtifactVerificationError on verification+ failure. The default delegates to the platform's common SkillHub+ verification with the trust policy injected via ``set_trust_policy()``;+ Providers may override to enforce a custom verification contract.+ """+ from jiuwenswarm.server.runtime.skill.artifact_security import (+ EnvironmentSecretResolver,+ verify_skillhub_artifact,+ )++ trust_policy = self._trust_policy or TrustPolicy(verification="if-present")+ resolver = self._secret_resolver or EnvironmentSecretResolver()+ result = verify_skillhub_artifact(+ descriptor,+ content,+ trust_policy=trust_policy,+ secret_resolver=resolver,+ )+ return result.to_audit_dict() if result.verified else None+class SkillSourceExtension(BaseExtension, ABC):"""Factory registered by a trusted extension package."""@@ -259,3 +364,13 @@ class SkillSourceExtension(BaseExtension, ABC):@abstractmethoddef create_provider(self, config: SourceConfig) -> SkillSourceProvider:raise NotImplementedError++ def default_source_config(self) -> SourceConfig | None:+ """Return the default source offered by this extension, or None.++ 是否提供默认源由扩展包自行决定(例如内置参考源在企业版默认关闭)。+ 返回 None 表示该扩展不提供默认源;提供时平台在启动和管理面配置+ 重载时经 bind_extension 注册。配置来源(skill_sources)的 enabled+ 不受此钩子影响,仍由配置驱动。+ """+ return Nonediff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.pyindex ac1e04ad2b..90633bc99a 100644--- a/jiuwenswarm/server/runtime/skill/skill_manager.py+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py@@ -50,21 +50,14 @@ from jiuwenswarm.extensions.sdk.skill_source import (SkillSourceExtension,SkillSourceProvider,SourceConfig,- TrustPolicy,)from jiuwenswarm.server.runtime.skill.artifact_security import (ArtifactVerificationError,- EnvironmentSecretResolver,- verify_skillhub_artifact,)from jiuwenswarm.server.runtime.skill.source_registry import (SourceRegistry,SourceRegistryError,)-from jiuwenswarm.server.runtime.skill.sources import (- SWARM_SKILL_HUB_SOURCE_ID,- SwarmSkillHubProvider,-)def _get_ssl_verify() -> bool:@@ -508,7 +501,6 @@ class SkillManager:self._agent_id = str(agent_id or "").strip() or Noneself._state: dict[str, Any] = self._load_state()self._source_registry = SourceRegistry()- self._secret_resolver = EnvironmentSecretResolver()self._register_builtin_skill_sources()# 把手动拷入 skills 目录、未经任何安装流程登记的本地技能,自动补登记到# local_skills,使其与"导入本地技能"完全等价(可展示/卸载/查看详情/禁用)。@@ -529,48 +521,57 @@ class SkillManager:self._skillnet_install_complete_hook = hookdef _register_builtin_skill_sources(self) -> None:- """Register built-in protocol adapters; clients are started lazily."""- config = self._default_swarm_skill_hub_config()- self._source_registry.register(- config,- SwarmSkillHubProvider(- self._get_team_skills_hub_base_url(),- timeout=_TEAM_SKILLS_HUB_MARKET_TIMEOUT,- ),- )+ """Register extension-offered default sources; clients are started lazily."""+ self._register_default_sources(self._source_registry)@staticmethod- def _default_swarm_skill_hub_config() -> SourceConfig:- """Build the personal/standalone default using the common SourceConfig."""- key_id = str(os.getenv("TEAM_SKILLS_HUB_HMAC_KEY_ID") or "default").strip()- secret_env = str(- os.getenv("TEAM_SKILLS_HUB_HMAC_SECRET_ENV")- or "SKILL_DOWNLOAD_HMAC_SECRET"- ).strip()- # 默认 if-present:Hub 未下发签名时仅记 verified=false 不拦截安装;- # 需要强验签的环境通过 TEAM_SKILLS_HUB_HMAC_VERIFICATION=required 显式开启- verification = str(- os.getenv("TEAM_SKILLS_HUB_HMAC_VERIFICATION") or "if-present"- ).strip().lower()- if verification not in {"required", "if-present"}:- logger.warning(- "Invalid TEAM_SKILLS_HUB_HMAC_VERIFICATION=%s; using if-present",- verification,- )- verification = "if-present"- return SourceConfig(- source_id=SWARM_SKILL_HUB_SOURCE_ID,- provider_type="swarmskillhub",- enabled=True,- priority=100,- endpoint_ref="env://TEAM_SKILLS_HUB_BASE_URL",- capabilities=frozenset({"search", "check_updates", "get_artifact"}),- download_policy=DownloadPolicy(),- trust_policy=TrustPolicy(- verification=verification,- hmac_key_refs={key_id: f"env://{secret_env}"},- ),- )+ def _register_default_sources(+ registry: SourceRegistry, *, skip: set[str] | None = None+ ) -> None:+ """Ask each registered Skill Source factory for its default source and bind it.++ 是否提供默认源由扩展包自决(``default_source_config()`` 返回 None 即不注册)。+ 扩展系统未运行(如单测直接构造 SkillManager)时无工厂可问,直接不注册。+ """+ try:+ from jiuwenswarm.extensions.registry import ExtensionRegistry++ factories = ExtensionRegistry.get_instance().list_skill_source_extensions()+ except RuntimeError:+ factories = []+ skipped = skip or set()+ for factory in factories:+ try:+ config = factory.default_source_config()+ except Exception: # noqa: BLE001+ logger.warning(+ "skill source extension %s failed to provide default source config",+ getattr(factory, "provider_type", "?"),+ exc_info=True,+ )+ continue+ if config is None or config.source_id in skipped:+ continue+ try:+ registry.bind_extension(config, factory)+ except (SourceRegistryError, ValueError) as exc:+ logger.warning(+ "default skill source %s rejected: %s", config.source_id, exc+ )++ @staticmethod+ def _get_skill_source_extension(provider_type: str) -> SkillSourceExtension | None:+ """Look up a registered Skill Source factory.++ Returns None when the extension system is not running (e.g. unit tests+ instantiating SkillManager directly).+ """+ try:+ from jiuwenswarm.extensions.registry import ExtensionRegistry++ return ExtensionRegistry.get_instance().get_skill_source_extension(provider_type)+ except RuntimeError:+ return None@staticmethoddef _source_config_custom_payload(record: dict[str, Any]) -> dict[str, Any] | None:@@ -586,42 +587,11 @@ class SkillManager:) from excreturn raw if isinstance(raw, dict) else None- @staticmethod- def _resolve_source_endpoint(reference: str | None) -> str | None:- value = str(reference or "").strip()- if not value.startswith("env://"):- return None- variable = value[6:]- if not re.fullmatch(r"[A-Z][A-Z0-9_]{0,127}", variable):- return None- resolved = str(os.getenv(variable) or "").strip()- return resolved or None-@staticmethoddef _parse_source_config(raw: dict[str, Any]) -> SourceConfig:- trust_raw = raw.get("trust_policy")- trust_policy = None- if isinstance(trust_raw, dict):- verification = str(trust_raw.get("verification") or "if-present").strip().lower()- if verification not in {"required", "if-present"}:- raise SourceRegistryError(- "source_misconfigured", "invalid trust_policy.verification"- )- refs = trust_raw.get("hmac_key_refs") or {}- if not isinstance(refs, dict):- raise SourceRegistryError(- "source_misconfigured", "trust_policy.hmac_key_refs must be an object"- )- algorithms = trust_raw.get("allowed_algorithms") or ["HmacSHA256"]- if not isinstance(algorithms, list):- raise SourceRegistryError(- "source_misconfigured", "trust_policy.allowed_algorithms must be an array"- )- trust_policy = TrustPolicy(- verification=verification,- allowed_algorithms=frozenset(str(item) for item in algorithms),- hmac_key_refs={str(key): str(value) for key, value in refs.items()},- )+ # trust_policy 已从管理面摘除:验签信任策略内聚到 Provider(由扩展工厂+ # 注入),管理面 dict 中的 trust_policy 键一律忽略。该键自 !5611 引入,+ # 无存量使用方;SourceConfig.trust_policy 字段本身保留(SDK 模型不动)。capabilities = raw.get("capabilities") or []if not isinstance(capabilities, list):raise SourceRegistryError("source_misconfigured", "capabilities must be an array")@@ -665,7 +635,6 @@ class SkillManager:auth_ref=str(raw.get("auth_ref") or "").strip() or None,capabilities=frozenset(str(item) for item in capabilities),download_policy=download_policy,- trust_policy=trust_policy,options=dict(options),)@@ -701,48 +670,20 @@ class SkillManager:configs = [self._parse_source_config(item) for item in raw_sources]candidate = SourceRegistry()configured_ids = {config.source_id for config in configs}- if SWARM_SKILL_HUB_SOURCE_ID not in configured_ids:- default_config = self._default_swarm_skill_hub_config()- candidate.register(- default_config,- SwarmSkillHubProvider(- self._get_team_skills_hub_base_url(),- timeout=_TEAM_SKILLS_HUB_MARKET_TIMEOUT,- ),- )+ # 默认源由扩展工厂自决是否提供(含企业版门控),与配置源同表绑定。+ self._register_default_sources(candidate, skip=configured_ids)for config in configs:- if config.provider_type == "swarmskillhub":- endpoint = self._resolve_source_endpoint(config.endpoint_ref)- if not endpoint and config.source_id == SWARM_SKILL_HUB_SOURCE_ID:- endpoint = self._get_team_skills_hub_base_url()- if not endpoint:- raise SourceRegistryError(- "source_misconfigured",- f"unresolved endpoint_ref for source {config.source_id}",- )- provider = SwarmSkillHubProvider(- endpoint,- source_id=config.source_id,- display_name=str(config.options.get("display_name") or config.source_id),- timeout=_TEAM_SKILLS_HUB_MARKET_TIMEOUT,- )- candidate.register(config, provider)- continue- try:- from jiuwenswarm.extensions.registry import ExtensionRegistry-- extension = ExtensionRegistry.get_instance().get_skill_source_extension(- config.provider_type- )- except RuntimeError:- extension = None+ extension = self._get_skill_source_extension(config.provider_type)if extension is None:raise SourceRegistryError("source_misconfigured",f"provider_type is not registered: {config.provider_type}",)- candidate.bind_extension(config, extension)+ try:+ candidate.bind_extension(config, extension)+ except ValueError as exc:+ raise SourceRegistryError("source_misconfigured", str(exc)) from excprevious = self._source_registryself._source_registry = candidate@@ -2357,7 +2298,7 @@ class SkillManager:skill_id: str,version_id: str,params: dict[str, Any],- ) -> tuple[ArtifactDescriptor, bytes, dict[str, Any]]:+ ) -> tuple[ArtifactDescriptor, bytes, dict[str, Any] | None]:"""Fetch and verify one exact artifact for both install and update."""provider = await self._source_registry.get(source_id, "get_artifact")descriptor = await provider.get_artifact(@@ -2373,31 +2314,30 @@ class SkillManager:)config = self._source_registry.get_config(source_id)download_policy = config.download_policy+ allowed_hosts = tuple(download_policy.allowed_hosts) if download_policy else ()+ if not allowed_hosts:+ # SPI 来源 fail-closed:经扩展工厂/管理面注册的来源必须持有显式下载+ # 主机白名单(管理面 download_policy 或 Provider 声明的默认白名单),+ # 空白名单直接拒绝,不回退 legacy 白名单(import_local/teamskillshub+ # 内置链路行为不变)。+ raise SourceRegistryError(+ "source_misconfigured",+ f"skill source {source_id} 未配置 download_policy.allowed_hosts,拒绝下载",+ )self._assert_skill_download_url_allowed(descriptor.download_url,- allowed_hosts=(download_policy.allowed_hosts if download_policy else None),- )- body = await self._download_zip_and_verify(- descriptor.download_url,- checksum_sha256=str(descriptor.checksum_sha256 or ""),- timeout=(download_policy.timeout_seconds if download_policy else None),- max_bytes=(download_policy.max_bytes if download_policy else None),+ allowed_hosts=allowed_hosts,)+ body = await provider.download_artifact(descriptor, download_policy)if descriptor.content_length is not None and len(body) != descriptor.content_length:raise SourceRegistryError("artifact_download_failed", "artifact content length does not match")- trust_policy = config.trust_policy or TrustPolicy(verification="if-present")try:- verification = verify_skillhub_artifact(- descriptor,- body,- trust_policy=trust_policy,- secret_resolver=self._secret_resolver,- )+ verification = await provider.verify_artifact(descriptor, body)except ArtifactVerificationError as exc:raise SourceRegistryError(exc.code, str(exc)) from exc- return descriptor, body, verification.to_audit_dict()+ return descriptor, body, dict(verification) if verification is not None else Nonedef _commit_source_skill_entity(self,@@ -4330,7 +4270,11 @@ class SkillManager:breakfor plugin in self._get_installed_plugins():if plugin.get("name") == skill_name:- display_name = str(plugin.get("display_name") or "").strip()+ display_name = str(+ plugin.get("market_display_name")+ or plugin.get("display_name")+ or ""+ ).strip()if display_name:return display_namebreakdiff --git a/jiuwenswarm/server/runtime/skill/source_registry.py b/jiuwenswarm/server/runtime/skill/source_registry.pyindex c8048d8cc5..c99cc9b4c2 100644--- a/jiuwenswarm/server/runtime/skill/source_registry.py+++ b/jiuwenswarm/server/runtime/skill/source_registry.py@@ -6,9 +6,10 @@ from __future__ import annotationsimport asyncioimport re-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom jiuwenswarm.extensions.sdk.skill_source import (+ DownloadPolicy,SourceConfig,SourceDescriptor,SkillSourceExtension,@@ -63,12 +64,41 @@ class SourceRegistry:"source_misconfigured",f"provider {provider_type} does not implement {sorted(configured - declared)}",)+ config = self._merge_provider_download_hosts(config, provider)self._entries[source_id] = _ProviderEntry(config=config,provider=provider,display_name=(display_name or provider.display_name or source_id).strip(),)+ @staticmethod+ def _merge_provider_download_hosts(+ config: SourceConfig,+ provider: SkillSourceProvider,+ ) -> SourceConfig:+ """Merge the Provider-declared download allowlist into the source config.++ SPI 来源下载 fail-closed:管理面显式配置的 allowed_hosts 优先;未配置时+ 采用扩展 Provider 显式声明的默认白名单(download_allowed_hosts);两者+ 皆空则保持为空,由安装链路拒绝下载。+ """+ declared = tuple(getattr(provider, "download_allowed_hosts", ()) or ())+ if not declared:+ return config+ policy = config.download_policy+ if policy is not None and policy.allowed_hosts:+ return config+ return replace(+ config,+ download_policy=DownloadPolicy(+ allowed_hosts=declared,+ max_bytes=(policy.max_bytes if policy else DownloadPolicy.max_bytes),+ timeout_seconds=(+ policy.timeout_seconds if policy else DownloadPolicy.timeout_seconds+ ),+ ),+ )+def bind_extension(self,config: SourceConfig,diff --git a/jiuwenswarm/server/runtime/skill/sources/__init__.py b/jiuwenswarm/server/runtime/skill/sources/__init__.pydeleted file mode 100644index 2254889777..0000000000--- a/jiuwenswarm/server/runtime/skill/sources/__init__.py+++ /dev/null@@ -1,8 +0,0 @@-"""Built-in Skill Source provider adapters."""--from jiuwenswarm.server.runtime.skill.sources.swarm_skill_hub import (- SWARM_SKILL_HUB_SOURCE_ID,- SwarmSkillHubProvider,-)--__all__ = ["SWARM_SKILL_HUB_SOURCE_ID", "SwarmSkillHubProvider"]diff --git a/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/__init__.py b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/__init__.pynew file mode 100644index 0000000000..c31a333a27--- /dev/null+++ b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/__init__.py@@ -0,0 +1,7 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""SwarmSkillHub Skill Source extension package."""++from .extension import register_extensions++__all__ = ["register_extensions"]diff --git a/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/config.yaml b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/config.yamlnew file mode 100644index 0000000000..c13f4a339d--- /dev/null+++ b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/config.yaml@@ -0,0 +1,11 @@+# SwarmSkillHub 内置参考源配置(非敏感配置内聚在扩展包内)。+# 密钥不落盘:hmac_secret_ref 只放 env:// 引用,密钥值由 secret_registry 注入。+endpoint: "https://swarmskills.openjiuwen.com"+timeout: 60.0+verification: "if-present" # if-present(默认,未签名不拦截)| required(强制验签)+hmac_key_id: "default"+hmac_secret_ref: "env://SKILL_DOWNLOAD_HMAC_SECRET"+allowed_download_hosts:+ - "openjiuwen-market.obs.*.myhuaweicloud.com"+ - "127.0.0.1"+ - "localhost"diff --git a/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/extension.py b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/extension.pynew file mode 100644index 0000000000..99794444db--- /dev/null+++ b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/extension.py@@ -0,0 +1,188 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""SwarmSkillHub Skill Source extension entry.++Registers the ``swarmskillhub`` Provider factory into the ExtensionRegistry;+AgentServer binds configured sources through ``SourceRegistry.bind_extension``.++非敏感配置内聚在扩展包内 ``config.yaml``;密钥不落盘,走 ``env://`` 引用。+"""++from __future__ import annotations++import logging+import os+import re+from pathlib import Path+from typing import Any+from urllib.parse import urlparse++import yaml++from jiuwenswarm.extensions.sdk.skill_source import (+ SkillSourceExtension,+ SkillSourceProvider,+ SourceConfig,+ TrustPolicy,+)++from .provider import (+ SWARM_SKILL_HUB_SOURCE_ID,+ SwarmSkillHubProvider,+)++logger = logging.getLogger(__name__)++SWARM_SKILL_HUB_PROVIDER_TYPE = "swarmskillhub"++_CONFIG_PATH = Path(__file__).parent / "config.yaml"++_DEFAULT_BASE_URL = "https://swarmskills.openjiuwen.com"+_DEFAULT_TIMEOUT = 60.0+_ENV_REF_RE = re.compile(r"[A-Z][A-Z0-9_]{0,127}")++# 与 SkillManager legacy Team Skills Hub 白名单保持一致的内置下载主机。+_DEFAULT_ALLOWED_DOWNLOAD_HOSTS: tuple[str, ...] = (+ "openjiuwen-market.obs.*.myhuaweicloud.com",+ "127.0.0.1",+ "localhost",+)++_DEFAULTS: dict[str, Any] = {+ "endpoint": _DEFAULT_BASE_URL,+ "timeout": _DEFAULT_TIMEOUT,+ "verification": "if-present",+ "hmac_key_id": "default",+ "hmac_secret_ref": "env://SKILL_DOWNLOAD_HMAC_SECRET",+ "allowed_download_hosts": list(_DEFAULT_ALLOWED_DOWNLOAD_HOSTS),+}+++def _load_config() -> dict[str, Any]:+ """从扩展包内 config.yaml 读非敏感配置;缺失/损坏时返回空(走默认值)。"""+ if not _CONFIG_PATH.exists():+ return {}+ try:+ data = yaml.safe_load(_CONFIG_PATH.read_text(encoding="utf-8")) or {}+ return data if isinstance(data, dict) else {}+ except Exception: # noqa: BLE001+ logger.warning("读取 SwarmSkillHub config.yaml 失败,使用内置默认配置", exc_info=True)+ return {}+++def _config_value(key: str) -> Any:+ cfg = _load_config()+ return cfg[key] if key in cfg else _DEFAULTS.get(key)+++def default_source_config_from_env() -> SourceConfig:+ """内置默认源配置(endpoint 来自扩展包 config.yaml;信任策略/白名单内聚 Provider)。"""+ endpoint = str(_config_value("endpoint") or _DEFAULT_BASE_URL).strip()+ return SourceConfig(+ source_id=SWARM_SKILL_HUB_SOURCE_ID,+ provider_type=SWARM_SKILL_HUB_PROVIDER_TYPE,+ enabled=True,+ priority=100,+ endpoint_ref=endpoint,+ capabilities=frozenset({"search", "check_updates", "get_artifact"}),+ )+++def _resolve_endpoint_ref(reference: str | None) -> str | None:+ """解析 ``env://NAME`` endpoint 引用(兼容管理面下发的 env:// 配置)。"""+ value = str(reference or "").strip()+ if not value.startswith("env://"):+ return None+ variable = value[6:]+ if not _ENV_REF_RE.fullmatch(variable):+ return None+ resolved = str(os.getenv(variable) or "").strip()+ return resolved or None+++def trust_policy_from_env() -> TrustPolicy:+ """从扩展包 config.yaml 构建信任策略(密钥走 secret_ref 引用,不落盘)。"""+ key_id = str(_config_value("hmac_key_id") or "default").strip()+ secret_ref = str(+ _config_value("hmac_secret_ref") or "env://SKILL_DOWNLOAD_HMAC_SECRET"+ ).strip()+ verification = str(_config_value("verification") or "if-present").strip().lower()+ if verification not in {"required", "if-present"}:+ logger.warning("Invalid verification=%s; using if-present", verification)+ verification = "if-present"+ return TrustPolicy(+ verification=verification,+ hmac_key_refs={key_id: secret_ref},+ )+++def default_download_allowed_hosts(endpoint: str, source_id: str) -> tuple[str, ...]:+ """从扩展包 config.yaml 读下载白名单(内置默认源回落内置默认主机)。"""+ hosts: list[str] = []+ endpoint_host = (urlparse(str(endpoint or "").strip()).hostname or "").strip().lower()+ if endpoint_host:+ hosts.append(endpoint_host)+ configured = _config_value("allowed_download_hosts")+ if isinstance(configured, (list, tuple)):+ extra = [str(h).strip().lower() for h in configured if str(h).strip()]+ elif str(source_id or "").strip() == SWARM_SKILL_HUB_SOURCE_ID:+ extra = list(_DEFAULT_ALLOWED_DOWNLOAD_HOSTS)+ else:+ extra = []+ for host in extra:+ if host not in hosts:+ hosts.append(host)+ return tuple(hosts)+++class SwarmSkillHubSourceExtension(SkillSourceExtension):+ """Factory creating configured SwarmSkillHub Provider instances."""++ provider_type = SWARM_SKILL_HUB_PROVIDER_TYPE++ def default_source_config(self) -> SourceConfig | None:+ """注册内置 SwarmSkillHub 参考源(个人版/企业版统一走代码注册)。++ 开关与配置由扩展包自决:endpoint 未显式配置时 create_provider+ 回落内置默认地址,不会因缺配置注册失败。+ """+ return default_source_config_from_env()++ async def initialize(self, config) -> None:+ return None++ async def shutdown(self) -> None:+ return None++ def create_provider(self, config: SourceConfig) -> SkillSourceProvider:+ endpoint = _resolve_endpoint_ref(config.endpoint_ref)+ if not endpoint:+ # config.yaml 的 endpoint 是 URL,直接用;否则内置默认地址兜底。+ endpoint = str(config.endpoint_ref or "").strip() or _DEFAULT_BASE_URL+ display_name = (+ str(config.options.get("display_name") or "").strip() or "SwarmSkillHub"+ )+ try:+ timeout = float(_config_value("timeout") or _DEFAULT_TIMEOUT)+ except (TypeError, ValueError):+ logger.warning("Invalid timeout; using %.1f", _DEFAULT_TIMEOUT)+ timeout = _DEFAULT_TIMEOUT+ provider = SwarmSkillHubProvider(+ endpoint,+ source_id=config.source_id,+ display_name=display_name,+ timeout=timeout,+ )+ # 信任策略内聚 Provider:构造后从 config.yaml 注入验签策略,并显式声明+ # 下载主机白名单(注册时并入来源 download_policy)。+ provider.set_trust_policy(trust_policy_from_env())+ provider.download_allowed_hosts = default_download_allowed_hosts(+ endpoint, config.source_id+ )+ return provider+++async def register_extensions(registry):+ extension = SwarmSkillHubSourceExtension()+ registry.register_skill_source_extension(extension)+ return [extension]diff --git a/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/extension.yaml b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/extension.yamlnew file mode 100644index 0000000000..585e4983fe--- /dev/null+++ b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/extension.yaml@@ -0,0 +1,12 @@+id: swarm_skill_hub+name: swarm_skill_hub+version: 0.1.0+description: SwarmSkillHub Skill Source provider factory (search / check_updates / get_artifact).+author: jiuwenswarm+min_jiuwenswarm_version: "0.2.0"+roles:+ - agentserver+capabilities:+ - skill-source-v2+config_schema:+ type: objectdiff --git a/jiuwenswarm/server/runtime/skill/sources/swarm_skill_hub.py b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/provider.pysimilarity index 99%rename from jiuwenswarm/server/runtime/skill/sources/swarm_skill_hub.pyrename to packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/provider.pyindex 5ccf51bf67..45c29ae998 100644--- a/jiuwenswarm/server/runtime/skill/sources/swarm_skill_hub.py+++ b/packages/jiuwenclaw-ee/agentserver/extensions/swarm_skill_hub/provider.py@@ -1,4 +1,4 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved."""SwarmSkillHub protocol adapter for the common Skill Source SPI."""diff --git a/tests/unit_tests/agentserver/test_swarm_hub_extension.py b/tests/unit_tests/agentserver/test_swarm_hub_extension.pynew file mode 100644index 0000000000..1f9a8cb234--- /dev/null+++ b/tests/unit_tests/agentserver/test_swarm_hub_extension.py@@ -0,0 +1,90 @@+from __future__ import annotations++import pytest++from jiuwenswarm.extensions.registry import ExtensionRegistry+from jiuwenswarm.extensions.sdk.skill_source import (+ ArtifactDescriptor,+ ArtifactRef,+ DownloadPolicy,+ SkillRef,+ SkillSearchRequest,+ SkillSearchResult,+ SkillSourceProvider,+ SourceConfig,+)+from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager+from jiuwenswarm.server.runtime.skill.source_registry import SourceRegistry+++class _CustomVerifyProvider(SkillSourceProvider):+ """覆盖 download_artifact 与 verify_artifact 的客户 Provider。"""++ source_id = "hub-c"+ provider_type = "customhub"+ display_name = "CustomHub"+ capabilities = frozenset({"search", "check_updates", "get_artifact"})++ def __init__(self) -> None:+ self.download_calls: list[tuple[ArtifactDescriptor, DownloadPolicy | None]] = []+ self.verify_calls: list[tuple[ArtifactDescriptor, bytes]] = []++ async def search(self, request: SkillSearchRequest, context) -> SkillSearchResult:+ return SkillSearchResult(items=())++ async def get_artifact(self, skill_ref: SkillRef, version_id: str, context) -> ArtifactDescriptor:+ return ArtifactDescriptor(+ artifact_ref=ArtifactRef(skill_ref=skill_ref, version_id=version_id),+ download_url="https://example.com/demo.zip",+ )++ async def download_artifact(self, descriptor, download_policy=None) -> bytes:+ self.download_calls.append((descriptor, download_policy))+ return b"zip-bytes"++ async def verify_artifact(self, descriptor, content):+ self.verify_calls.append((descriptor, content))+ return {"verified": True, "artifact_sha256": "custom-sha"}+++++async def test_install_path_uses_provider_download_and_verify_overrides(tmp_path, monkeypatch):+ monkeypatch.setattr(ExtensionRegistry, "_instance", None)+ manager = SkillManager(workspace_dir=str(tmp_path))++ provider = _CustomVerifyProvider()+ registry = SourceRegistry()+ registry.register(+ SourceConfig(+ source_id="hub-c",+ provider_type="customhub",+ capabilities=frozenset({"get_artifact"}),+ download_policy=DownloadPolicy(allowed_hosts=("example.com",)),+ ),+ provider,+ )+ manager._source_registry = registry++ descriptor, body, verification = await manager._fetch_verified_source_artifact(+ source_id="hub-c",+ skill_id="demo",+ version_id="1.0.0",+ params={},+ )++ assert body == b"zip-bytes"+ assert descriptor.download_url == "https://example.com/demo.zip"+ # 下载经 Provider 覆写实现(平台默认下载被绕过),download_policy 透传+ assert len(provider.download_calls) == 1+ _, download_policy = provider.download_calls[0]+ assert download_policy is not None+ assert download_policy.allowed_hosts == ("example.com",)+ # 验签经 Provider 覆写实现:返回的审计 Mapping 直接入账(不再 to_audit_dict)+ assert verification == {"verified": True, "artifact_sha256": "custom-sha"}+ assert len(provider.verify_calls) == 1+ _, content = provider.verify_calls[0]+ assert content == b"zip-bytes"++diff --git a/tests/unit_tests/agentserver/test_tenant_sessions_write.py b/tests/unit_tests/agentserver/test_tenant_sessions_write.pyindex 945a34f662..4fc0c94f67 100644--- a/tests/unit_tests/agentserver/test_tenant_sessions_write.py+++ b/tests/unit_tests/agentserver/test_tenant_sessions_write.py@@ -18,6 +18,10 @@ from jiuwenswarm.server.runtime.session.session_metadata import (def test_resolve_tenant_sessions_dir_layout(tmp_path, monkeypatch):+ monkeypatch.setattr(+ "jiuwenswarm.common.utils.is_enterprise",+ lambda: True,+ )monkeypatch.setattr("jiuwenswarm.common.utils.get_user_workspace_dir",lambda: tmp_path,@@ -62,6 +66,10 @@ def test_sync_writes_under_tenant_sessions_root(tmp_path, monkeypatch):def test_cache_isolated_by_sessions_root(tmp_path, monkeypatch):+ monkeypatch.setattr(+ "jiuwenswarm.common.utils.is_enterprise",+ lambda: True,+ )monkeypatch.setattr("jiuwenswarm.common.utils.get_user_workspace_dir",lambda: tmp_path,diff --git a/tests/unit_tests/gateway/test_cron_tenant_registry.py b/tests/unit_tests/gateway/test_cron_tenant_registry.pyindex b00f1da284..7004222093 100644--- a/tests/unit_tests/gateway/test_cron_tenant_registry.py+++ b/tests/unit_tests/gateway/test_cron_tenant_registry.py@@ -97,6 +97,9 @@ async def test_get_controller_concurrent_same_tenant(tmp_path, monkeypatch) -> N@pytest.mark.asyncioasync def test_web_create_mirrors_to_agent_home(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.common.utils.is_enterprise", lambda: True+ )monkeypatch.setattr("jiuwenswarm.common.utils.get_user_workspace_dir", lambda: tmp_path)diff --git a/tests/unit_tests/tenant_workspace_test_helpers.py b/tests/unit_tests/tenant_workspace_test_helpers.pyindex 9355810492..24ee3a1af4 100644--- a/tests/unit_tests/tenant_workspace_test_helpers.py+++ b/tests/unit_tests/tenant_workspace_test_helpers.py@@ -47,15 +47,18 @@ def tenant_workspace_root(def patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path: Path) -> None:- def _mock(workspace_key: str) -> Path:- wk = str(workspace_key or "default").strip() or "default"- return tmp_path / f"workspace_{wk}"+ """让多租户工作区按 key 分桶并落在 ``tmp_path`` 下(企业版行为)。+ 直接 patch ``get_multi_tenant_user_workspace_dir`` 会因被测模块的+ ``from ... import get_multi_tenant_user_workspace_dir`` 引用而失效;+ 改为 patch ``is_enterprise``(走企业版按 key 分桶分支)与+ ``get_user_workspace_dir``(落在 tmp_path),对任意调用方都生效。+ """monkeypatch.setattr(- "jiuwenswarm.common.utils.get_multi_tenant_user_workspace_dir",- _mock,+ "jiuwenswarm.common.utils.is_enterprise",+ lambda: True,)monkeypatch.setattr(- "jiuwenswarm.gateway.tenant_paths.get_multi_tenant_user_workspace_dir",- _mock,+ "jiuwenswarm.common.utils.get_user_workspace_dir",+ lambda: tmp_path,)