Skip to content

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: 企业技能管理——技能源 Provider + HMAC 验签 + 搜索/安装/更新

huben6dcab13b1e16
diff --git a/.gitignore b/.gitignore
index 962a484082..dba360ab80 100644
--- a/.gitignore
+++ b/.gitignore
@@ -98,3 +98,7 @@ packages/jiuwenswarm-tui/jiuwenswarm_tui/resources/tui-bin/
# Build-time Node runtime cache used by packaging scripts.
vendor/node/
+
+# Local smoke / verification scratch scripts (not part of the PR).
+_smoke_*.py
+_verify_*.py
diff --git a/jiuwenswarm/agents/harness/common/tools/skill_toolkits.py b/jiuwenswarm/agents/harness/common/tools/skill_toolkits.py
index 52f7871a2d..5057e2fb1f 100644
--- a/jiuwenswarm/agents/harness/common/tools/skill_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/skill_toolkits.py
@@ -11,7 +11,7 @@ from typing import Any, Callable
from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
-from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager, SkillNameConflictError
from jiuwenswarm.server.runtime.skill.skill_whitelist import is_skill_whitelist_tenant
logger = logging.getLogger(__name__)
@@ -79,27 +79,6 @@ class SkillToolkit:
def _is_enterprise(self) -> bool:
return is_skill_whitelist_tenant(self._agent_id, self._service_id)
- @staticmethod
- def _enterprise_user_id() -> str | None:
- from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple
- from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
- get_runtime_tool_metadata,
- )
-
- meta = get_runtime_tool_metadata() or {}
- _g, _b, user_id = extract_routing_triple(meta)
- return str(user_id).strip() if user_id else None
-
- @staticmethod
- def _enterprise_routing() -> tuple[str | None, str | None, str | None]:
- from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple
- from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
- get_runtime_tool_metadata,
- )
-
- meta = get_runtime_tool_metadata() or {}
- return extract_routing_triple(meta)
-
async def _notify_installed_skills_changed(self) -> None:
if self._on_installed_skills_changed is None:
return
@@ -590,53 +569,6 @@ class SkillToolkit:
resolved_source = normalized_source
wait_timeout = self._safe_int(timeout_sec, 60)
- if self._is_enterprise():
- from jiuwenswarm.agents.harness.common.installed_skill_ops import (
- install_from_channel,
- )
-
- group_id, bot_id, user_id = self._enterprise_routing()
-
- async def _do_channel_install(
- tgt: str, src: str, timeout: int, *, force: bool
- ) -> dict[str, Any]:
- return await self._channel_install(tgt, src, timeout, force=force)
-
- result = await install_from_channel(
- service_id=str(self._service_id or ""),
- agent_id=str(self._agent_id or ""),
- target=target,
- source=resolved_source,
- timeout_sec=wait_timeout,
- channel_install=_do_channel_install,
- get_skill_meta=self._get_skill_meta,
- remove_skill_dir=self._manager.remove_skill_directory,
- group_id=group_id,
- bot_id=bot_id,
- user_id=user_id or self._enterprise_user_id(),
- )
- if not result.get("success"):
- return result
- await self._notify_installed_skills_changed()
- name = str(result.get("name") or "").strip()
- installed_item = self._build_installed_item(name, resolved_source)
- detail = (
- f"Skill installed successfully. Available now: - `{installed_item['name']}`: "
- f"{installed_item['description'].strip() or 'No description provided.'}"
- )
- if installed_item["skill_file"]:
- detail = f"{detail} Read SKILL.md before use."
- return {
- "success": True,
- "source": resolved_source,
- "installed": True,
- "name": installed_item["name"],
- "description": installed_item["description"],
- "identifier": installed_item["identifier"],
- "skill_file": installed_item["skill_file"],
- "detail": detail,
- }
-
if resolved_source == "skillnet":
r = self._check_already_installed(target, resolved_source)
if r is not None:
@@ -688,6 +620,43 @@ class SkillToolkit:
# 底层未显式返回名称时,尽量从 identifier 推断一个稳定值。
name = Path(target).name if resolved_source == "skillnet" else target
+ if self._is_enterprise():
+ record_origin = ""
+ for record in self._manager.get_local_skills():
+ if str(record.get("name") or "").strip() == name:
+ record_origin = str(record.get("origin") or "").strip()
+ break
+ if not record_origin:
+ record_origin = str(target or "").strip() or resolved_source
+ meta = self._get_skill_meta(name) or {}
+ try:
+ self._manager.record_skill_installation(
+ name=name,
+ source_type="user",
+ source=resolved_source,
+ origin=record_origin,
+ version=str(meta.get("version") or "").strip(),
+ )
+ except SkillNameConflictError as exc:
+ self._manager.remove_skill_directory(name)
+ return {
+ "success": False,
+ "source": resolved_source,
+ "installed": False,
+ "error_code": "skill_name_conflict",
+ "detail": str(exc),
+ }
+ except Exception as exc: # noqa: BLE001
+ self._manager.remove_skill_directory(name)
+ return {
+ "success": False,
+ "source": resolved_source,
+ "installed": False,
+ "error_code": "state_write_failed",
+ "detail": str(exc),
+ }
+ await self._notify_installed_skills_changed()
+
installed_item = self._build_installed_item(name, resolved_source)
detail = (
f"Skill installed successfully. Available now: - `{installed_item['name']}`: "
@@ -728,20 +697,53 @@ class SkillToolkit:
}
if self._is_enterprise():
- from jiuwenswarm.agents.harness.common.installed_skill_ops import uninstall
-
- async def _remove_disk(n: str) -> dict[str, Any]:
- return await self._manager.handle_skills_uninstall({"name": n})
-
- result = await uninstall(
- service_id=str(self._service_id or ""),
- agent_id=str(self._agent_id or ""),
- skill_name=skill_name,
- remove_from_disk=_remove_disk,
+ installation = None
+ for record in self._manager.list_skill_installations():
+ if (
+ str(record.get("name") or "").strip() == skill_name
+ and str(record.get("source_type") or "").strip()
+ in {"prebuilt", "user"}
+ ):
+ installation = record
+ break
+ if installation is None:
+ return {
+ "success": False,
+ "removed": False,
+ "name": skill_name,
+ "error_code": "not_found",
+ "detail": f"Skill `{skill_name}` is not installed.",
+ }
+ if str(installation.get("source_type") or "").strip() == "prebuilt":
+ return {
+ "success": False,
+ "removed": False,
+ "name": skill_name,
+ "error_code": "prebuilt_not_removable",
+ "detail": f"Skill `{skill_name}` is prebuilt and cannot be uninstalled.",
+ }
+ result = await self._manager.handle_skills_uninstall(
+ {
+ "name": skill_name,
+ "origin": str(installation.get("origin") or ""),
+ }
)
if result.get("success"):
await self._notify_installed_skills_changed()
- return result
+ return {
+ "success": True,
+ "removed": True,
+ "name": skill_name,
+ "source": "user",
+ "detail": f"Skill `{skill_name}` uninstalled successfully.",
+ }
+ return {
+ "success": False,
+ "removed": False,
+ "name": skill_name,
+ "error_code": str(result.get("error_code") or "uninstall_failed"),
+ "detail": str(result.get("detail") or "uninstall failed"),
+ }
installed_payload = await self._list_installed_skills()
if not installed_payload.get("success"):
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
index d1ecddb2ce..792d2e7d7b 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
@@ -2090,23 +2090,21 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
</button>
)}
</div>
- {(marketplaceSubTab !== "swarmskills" || !readOnly) && (
- <div className="flex-1">
- <input
- type="text"
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder={
- marketplaceSubTab === "builtin"
- ? t("skills.searchPlaceholder")
- : marketplaceSubTab === "swarmskills"
- ? t("skills.swarmskills.searchPlaceholder")
- : t("skills.onlineSearch.searchPlaceholder")
- }
- className="w-full px-3 py-1.5 rounded-lg text-sm bg-secondary border border-border text-text placeholder:text-text-muted"
- />
- </div>
- )}
+ <div className="flex-1">
+ <input
+ type="text"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={
+ marketplaceSubTab === "builtin"
+ ? t("skills.searchPlaceholder")
+ : marketplaceSubTab === "swarmskills"
+ ? t("skills.swarmskills.searchPlaceholder")
+ : t("skills.onlineSearch.searchPlaceholder")
+ }
+ className="w-full px-3 py-1.5 rounded-lg text-sm bg-secondary border border-border text-text placeholder:text-text-muted"
+ />
+ </div>
</div>
<div className={`mt-4 flex-1 min-h-0 overflow-y-auto ${viewMode === "grid" && marketplaceSubTab === "builtin" ? "flex flex-wrap gap-4 content-start" : "space-y-3"}`}>
@@ -2215,6 +2213,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
<EnterpriseSkillSourcePanel
sessionId={sessionId}
viewMode={viewMode}
+ externalSearchQuery={debouncedSearch}
onInstalled={() => {
void fetchSkills();
}}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx
index 7b1d9fbbfb..cee8847c3d 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/features/EnterpriseSkillSourcePanel/index.tsx
@@ -60,6 +60,8 @@ type UpdateStatus = {
interface EnterpriseSkillSourcePanelProps {
sessionId: string;
viewMode?: 'list' | 'grid';
+ /** 外层搜索框传入的关键词;提供时隐藏面板内置搜索框,关键词变化自动搜索 */
+ externalSearchQuery?: string;
onInstalled?: (skillName: string) => void | Promise<void>;
}
@@ -80,7 +82,7 @@ function labelText(label: { name?: string } | string | undefined): string {
return label.name || '';
}
-export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', onInstalled }: EnterpriseSkillSourcePanelProps) {
+export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', externalSearchQuery, onInstalled }: EnterpriseSkillSourcePanelProps) {
const { t } = useTranslation();
const [sources, setSources] = useState<SourceDescriptor[]>([]);
const [sourceId, setSourceId] = useState('');
@@ -188,10 +190,25 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', onIns
setPage(1);
void runSearch(1);
}
- // 仅 sourceId 变化时触发;query 变化由搜索按钮/回车触发
+ // sourceId 变化时触发;内部模式 query 变化由搜索按钮/回车触发,外部模式由下面 query effect 触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sourceId]);
+ const isExternalQuery = externalSearchQuery !== undefined;
+
+ // 外层搜索框驱动:同步关键词(与个人版 TeamSkillsHubModal 嵌入模式一致)
+ useEffect(() => {
+ if (isExternalQuery) setQuery(externalSearchQuery);
+ }, [externalSearchQuery, isExternalQuery]);
+
+ // 外部模式下关键词变化自动搜索(外层输入已做防抖)
+ useEffect(() => {
+ if (!isExternalQuery || !sourceId) return;
+ setPage(1);
+ void runSearch(1);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [query, isExternalQuery]);
+
const handleInstall = useCallback(
async (item: SkillCandidate, force = false) => {
if (installingId) return;
@@ -398,38 +415,44 @@ export function EnterpriseSkillSourcePanel({ sessionId, viewMode = 'list', onIns
</div>
)}
- <div className="flex items-center gap-2">
- {sources.length > 1 && (
- <select
- value={sourceId}
- onChange={e => setSourceId(e.target.value)}
- className="px-2 py-1.5 rounded-lg text-sm bg-secondary border border-border text-text"
- >
- {sources.map(s => (
- <option key={s.source_id} value={s.source_id}>
- {s.display_name || s.source_id}
- </option>
- ))}
- </select>
- )}
- <input
- value={query}
- onChange={e => setQuery(e.target.value)}
- onKeyDown={e => e.key === 'Enter' && void runSearch(1)}
- placeholder={t('skills.source.searchPlaceholder')}
- className="flex-1 min-w-0 px-3 py-1.5 rounded-lg text-sm bg-secondary border border-border text-text placeholder:text-text-muted"
- />
- <button
- type="button"
- onClick={() => void runSearch(1)}
- disabled={loadState === 'loading' || !sourceId}
- className={`px-4 py-1.5 rounded-2xl text-sm border border-gray-400 hover:border-gray-600 hover:bg-secondary/50 ${
- loadState === 'loading' || !sourceId ? 'text-text-muted cursor-not-allowed' : 'text-text'
- }`}
- >
- {loadState === 'loading' ? t('common.loading') : t('skills.teamskillshub.search')}
- </button>
- </div>
+ {(sources.length > 1 || !isExternalQuery) && (
+ <div className="flex items-center gap-2">
+ {sources.length > 1 && (
+ <select
+ value={sourceId}
+ onChange={e => setSourceId(e.target.value)}
+ className="px-2 py-1.5 rounded-lg text-sm bg-secondary border border-border text-text"
+ >
+ {sources.map(s => (
+ <option key={s.source_id} value={s.source_id}>
+ {s.display_name || s.source_id}
+ </option>
+ ))}
+ </select>
+ )}
+ {!isExternalQuery && (
+ <>
+ <input
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ onKeyDown={e => e.key === 'Enter' && void runSearch(1)}
+ placeholder={t('skills.source.searchPlaceholder')}
+ className="flex-1 min-w-0 px-3 py-1.5 rounded-lg text-sm bg-secondary border border-border text-text placeholder:text-text-muted"
+ />
+ <button
+ type="button"
+ onClick={() => void runSearch(1)}
+ disabled={loadState === 'loading' || !sourceId}
+ className={`px-4 py-1.5 rounded-2xl text-sm border border-gray-400 hover:border-gray-600 hover:bg-secondary/50 ${
+ loadState === 'loading' || !sourceId ? 'text-text-muted cursor-not-allowed' : 'text-text'
+ }`}
+ >
+ {loadState === 'loading' ? t('common.loading') : t('skills.teamskillshub.search')}
+ </button>
+ </>
+ )}
+ </div>
+ )}
{loadState === 'loading' && <div className="flex items-center justify-center flex-1 text-text-muted">{t('common.loading')}</div>}
{loadState === 'error' && <div className="mt-4 text-sm text-text-muted">{t('skills.source.errors.searchFailed')}</div>}
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 712423829a..b63687abf1 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -1910,6 +1910,7 @@
"install": "Install",
"replaceConfirm": "A skill named \"{{name}}\" is already installed. Continuing will uninstall the current version and replace it with the selected one. Continue?",
"installing": "Installing…",
+ "updating": "Updating…",
"updatedAt": "Updated {{date}}",
"configTitle": "Configure",
"configDescription": "Enter the CLI Token from the ClawHub platform to access the ClawHub skill library.",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 8ac60e44ec..79c240ce64 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -1911,6 +1911,7 @@
"install": "安装",
"replaceConfirm": "已安装同名技能「{{name}}」,继续安装将卸载已安装的版本并替换为当前选择的版本。是否继续?",
"installing": "安装中…",
+ "updating": "更新中…",
"updatedAt": "更新于 {{date}}",
"configTitle": "配置",
"configDescription": "请输入从 ClawHub 平台获取的 CLI Token,用于访问 ClawHub 技能库。",
diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
index bc525807e7..573c54cf15 100644
--- a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts
@@ -93,7 +93,7 @@ const ROUTES: Record<string, RouteRow> = {
'skills.import_local': { verb: 'POST', path: '/skills/actions/import-local', kind: 'unary' },
'skills.source.providers': { verb: 'GET', path: '/skills/sources', kind: 'unary' },
'skills.source.search': { verb: 'GET', path: '/skills/sources/search', kind: 'unary' },
- 'skills.source.install': { verb: 'POST', path: '/skills/sources/install', kind: 'unary' },
+ 'skills.source.install': { verb: 'POST', path: '/skills/sources/actions/install', kind: 'unary' },
'skills.updates.check': { verb: 'GET', path: '/skills/updates', kind: 'unary' },
'skills.update': { verb: 'POST', path: '/skills/actions/update', kind: 'unary' },
'skills.teamskillshub.info': { verb: 'GET', path: '/skills/teamskillshub', kind: 'unary' },
@@ -102,7 +102,7 @@ const ROUTES: Record<string, RouteRow> = {
'skills.retrieval.index_build': { verb: 'POST', path: '/skills/retrieval/actions/index-build', kind: 'unary' },
'skills.retrieval.index_cancel': { verb: 'POST', path: '/skills/retrieval/actions/index-cancel', kind: 'unary' },
'skills.enterprise.list': { verb: 'GET', path: '/skills/enterprise', kind: 'unary' },
- 'skills.enterprise.install': { verb: 'POST', path: '/skills/enterprise/install', kind: 'unary' },
+ 'skills.enterprise.install': { verb: 'POST', path: '/skills/enterprise/actions/install', kind: 'unary' },
'skills.enterprise.uninstall': { verb: 'POST', path: '/skills/enterprise/actions/uninstall', kind: 'unary' },
'skills.marketplace.list': { verb: 'GET', path: '/skills/marketplace', kind: 'unary' },
'skills.marketplace.add': { verb: 'POST', path: '/skills/marketplace', kind: 'unary' },
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index d838da9cb2..74f5bcd1ec 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -119,6 +119,11 @@ class ReqMethod(Enum):
SKILLS_TEAMSKILLS_HUB_INSTALL = "skills.teamskillshub.install"
SKILLS_TEAMSKILLS_HUB_PUBLISH = "skills.teamskillshub.publish"
SKILLS_TEAMSKILLS_HUB_DELETE = "skills.teamskillshub.delete"
+ SKILLS_SOURCE_PROVIDERS = "skills.source.providers"
+ SKILLS_SOURCE_SEARCH = "skills.source.search"
+ SKILLS_SOURCE_INSTALL = "skills.source.install"
+ SKILLS_UPDATES_CHECK = "skills.updates.check"
+ SKILLS_UPDATE = "skills.update"
SKILLS_RETRIEVAL_STATUS = "skills.retrieval.status"
SKILLS_RETRIEVAL_INDEX_BUILD = "skills.retrieval.index_build"
SKILLS_RETRIEVAL_INDEX_CANCEL = "skills.retrieval.index_cancel"
@@ -133,6 +138,8 @@ class ReqMethod(Enum):
SKILLS_ENTERPRISE_LIST = "skills.enterprise.list"
SKILLS_ENTERPRISE_INSTALL = "skills.enterprise.install"
SKILLS_ENTERPRISE_UNINSTALL = "skills.enterprise.uninstall"
+ SKILLS_ENTERPRISE_SOURCE_PROVIDERS = "skills.enterprise.source.providers"
+ SKILLS_ENTERPRISE_SOURCE_SEARCH = "skills.enterprise.source.search"
SYMPHONY_BUILD_SCORE = "symphony.build_score"
SYMPHONY_PAUSE_BUILD = "symphony.pause_build"
diff --git a/jiuwenswarm/extensions/registry.py b/jiuwenswarm/extensions/registry.py
index 6982e67e9a..850e473587 100644
--- a/jiuwenswarm/extensions/registry.py
+++ b/jiuwenswarm/extensions/registry.py
@@ -9,6 +9,7 @@ from jiuwenswarm.extensions.sdk.agent_server_client import AgentServerClientExte
from jiuwenswarm.extensions.sdk.crypto_utility import CryptoUtility
from jiuwenswarm.extensions.sdk.telemetry_provider import TelemetryProviderExtension
from jiuwenswarm.extensions.sdk.third_agent import ThirdAgentExtension
+from jiuwenswarm.extensions.sdk.skill_source import SkillSourceExtension
from jiuwenswarm.extensions.types import ExtensionConfig
from jiuwenswarm.common.security.base_crypto import CryptoProvider
from jiuwenswarm.gateway.routing.third_agent import ThirdAgent
@@ -27,6 +28,7 @@ class ExtensionRegistry:
self._crypto_tool: CryptoUtility | None = None
self._third_agent: ThirdAgentExtension | None = None
self._telemetry_provider: TelemetryProviderExtension | None = None
+ self._skill_source_extensions: dict[str, SkillSourceExtension] = {}
self._rpc_handlers: dict[str, Callable] = {}
self.callback_framework = callback_framework
self._config = ExtensionConfig(config=config, logger=logger)
@@ -76,6 +78,25 @@ class ExtensionRegistry:
) -> None:
self._telemetry_provider = extension
+ def register_skill_source_extension(self, extension: SkillSourceExtension) -> None:
+ """Register one trusted Skill Source provider factory.
+
+ A configured ``source_id`` is bound to this factory later by AgentServer;
+ extensions must not register tenant-specific provider instances here.
+ """
+ provider_type = str(extension.provider_type or "").strip()
+ if not provider_type:
+ raise ValueError("skill source provider_type is required")
+ if provider_type in self._skill_source_extensions:
+ raise ValueError(f"duplicate skill source provider_type: {provider_type}")
+ self._skill_source_extensions[provider_type] = extension
+
+ def get_skill_source_extension(self, provider_type: str) -> SkillSourceExtension | None:
+ return self._skill_source_extensions.get(str(provider_type or "").strip())
+
+ def list_skill_source_extensions(self) -> list[SkillSourceExtension]:
+ return [self._skill_source_extensions[key] for key in sorted(self._skill_source_extensions)]
+
def register_rpc_handler(self, method: str, handler: Callable) -> None:
method_name = str(method or "").strip()
if not method_name:
diff --git a/jiuwenswarm/extensions/sdk/__init__.py b/jiuwenswarm/extensions/sdk/__init__.py
index 1f76797262..4e1ebe198c 100644
--- a/jiuwenswarm/extensions/sdk/__init__.py
+++ b/jiuwenswarm/extensions/sdk/__init__.py
@@ -2,10 +2,44 @@ from jiuwenswarm.extensions.sdk.agent_server_client import AgentServerClientExte
from jiuwenswarm.extensions.sdk.base import BaseExtension
from jiuwenswarm.extensions.sdk.crypto_utility import CryptoUtility
from jiuwenswarm.extensions.sdk.third_agent import ThirdAgentExtension
+from jiuwenswarm.extensions.sdk.skill_source import (
+ ArtifactDescriptor,
+ ArtifactRef,
+ DownloadPolicy,
+ ProviderInvocationContext,
+ InstalledArtifact,
+ SkillCandidate,
+ SkillRef,
+ SkillSearchRequest,
+ SkillSearchResult,
+ SkillUpdateStatus,
+ SkillSourceExtension,
+ SkillSourceProvider,
+ SourceConfig,
+ SourceDescriptor,
+ SecretResolver,
+ TrustPolicy,
+)
__all__ = [
"BaseExtension",
"AgentServerClientExtension",
"CryptoUtility",
"ThirdAgentExtension",
+ "ArtifactDescriptor",
+ "ArtifactRef",
+ "DownloadPolicy",
+ "ProviderInvocationContext",
+ "InstalledArtifact",
+ "SkillCandidate",
+ "SkillRef",
+ "SkillSearchRequest",
+ "SkillSearchResult",
+ "SkillUpdateStatus",
+ "SkillSourceExtension",
+ "SkillSourceProvider",
+ "SourceConfig",
+ "SourceDescriptor",
+ "SecretResolver",
+ "TrustPolicy",
]
diff --git a/jiuwenswarm/extensions/sdk/skill_source.py b/jiuwenswarm/extensions/sdk/skill_source.py
new file mode 100644
index 0000000000..9421d7e251
--- /dev/null
+++ b/jiuwenswarm/extensions/sdk/skill_source.py
@@ -0,0 +1,261 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.
+
+"""Public Skill Source SPI used by AgentServer extensions.
+
+Providers translate a remote catalogue protocol into the common models below.
+They deliberately do not install, update, or remove workspace files.
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Mapping, Sequence
+
+from jiuwenswarm.extensions.sdk.base import BaseExtension
+
+
+@dataclass(frozen=True)
+class SkillRef:
+ source_id: str
+ skill_id: str
+
+
+@dataclass(frozen=True)
+class ArtifactRef:
+ skill_ref: SkillRef
+ version_id: str
+
+
+@dataclass(frozen=True)
+class TrustPolicy:
+ verification: str = "if-present"
+ allowed_algorithms: frozenset[str] = frozenset({"HmacSHA256"})
+ hmac_key_refs: Mapping[str, str] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class DownloadPolicy:
+ allowed_hosts: tuple[str, ...] = ()
+ max_bytes: int = 64 * 1024 * 1024
+ timeout_seconds: float = 60.0
+
+
+class SecretResolver(ABC):
+ """Resolve an approved secret reference without exposing it to Providers."""
+
+ @abstractmethod
+ def resolve(self, reference: str) -> str | None:
+ raise NotImplementedError
+
+
+@dataclass(frozen=True)
+class SourceConfig:
+ source_id: str
+ provider_type: str
+ enabled: bool = True
+ priority: int = 0
+ endpoint_ref: str | None = None
+ auth_ref: str | None = None
+ capabilities: frozenset[str] = frozenset()
+ download_policy: DownloadPolicy | None = None
+ trust_policy: TrustPolicy | None = None
+ options: Mapping[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class SourceDescriptor:
+ source_id: str
+ provider_type: str
+ display_name: str
+ enabled: bool
+ priority: int
+ capabilities: frozenset[str]
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "source": self.source_id,
+ "source_id": self.source_id,
+ "provider_type": self.provider_type,
+ "display_name": self.display_name,
+ "enabled": self.enabled,
+ "priority": self.priority,
+ "capabilities": sorted(self.capabilities),
+ }
+
+
+@dataclass(frozen=True)
+class SkillSearchRequest:
+ q: str = ""
+ page: int = 1
+ page_size: int = 20
+ filters: Mapping[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class SkillCandidate:
+ source_id: str
+ skill_id: str
+ version_id: str
+ name: str
+ display_name: str | None = None
+ summary: str | None = None
+ version: str | None = None
+ fingerprint: str | None = None
+ namespace: str | None = None
+ slug: str | None = None
+ canonical_slug: str | None = None
+ owner_display_name: str | None = None
+ labels: tuple[Mapping[str, Any], ...] = ()
+ homepage: str | None = None
+ rating_avg: float | None = None
+ rating_count: int | None = None
+ download_count: int | None = None
+ updated_at: datetime | str | int | None = None
+ versions: tuple[Mapping[str, Any], ...] = ()
+ previous_version: str | None = None
+ accessible: bool | None = None
+ downloadable: bool | None = None
+ metadata: Mapping[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ updated_at: str | int | None = self.updated_at
+ if isinstance(updated_at, datetime):
+ updated_at = updated_at.isoformat()
+ raw: dict[str, Any] = {
+ "source_id": self.source_id,
+ "skill_id": self.skill_id,
+ "version_id": self.version_id,
+ "name": self.name,
+ "display_name": self.display_name,
+ "summary": self.summary,
+ "version": self.version,
+ "fingerprint": self.fingerprint,
+ "namespace": self.namespace,
+ "slug": self.slug,
+ "canonical_slug": self.canonical_slug,
+ "owner_display_name": self.owner_display_name,
+ "labels": list(self.labels),
+ "homepage": self.homepage,
+ "rating_avg": self.rating_avg,
+ "rating_count": self.rating_count,
+ "download_count": self.download_count,
+ "updated_at": updated_at,
+ "versions": list(self.versions),
+ "previous_version": self.previous_version,
+ "accessible": self.accessible,
+ "downloadable": self.downloadable,
+ "metadata": dict(self.metadata),
+ }
+ result: dict[str, Any] = {}
+ for key, value in raw.items():
+ if value is None or value in ((), [], {}):
+ continue
+ result[key] = value
+ return result
+
+
+@dataclass(frozen=True)
+class SkillSearchResult:
+ items: tuple[SkillCandidate, ...]
+ total: int | None = None
+ next_page: int | None = None
+
+
+@dataclass(frozen=True)
+class InstalledArtifact:
+ source_id: str
+ skill_id: str
+ version_id: str
+ version: str | None = None
+ fingerprint: str | None = None
+
+
+@dataclass(frozen=True)
+class SkillUpdateStatus:
+ skill_ref: SkillRef
+ current_version_id: str
+ latest_version_id: str | None
+ has_update: bool
+ latest_version: str | None = None
+ fingerprint_matched: bool | None = None
+ accessible: bool | None = None
+ downloadable: bool | None = None
+ remote_status: str = "unknown"
+ error_code: str | None = None
+
+
+@dataclass(frozen=True)
+class ArtifactDescriptor:
+ artifact_ref: ArtifactRef
+ download_url: str
+ expires_at: datetime | None = None
+ checksum_sha256: str | None = None
+ artifact_sha256: str | None = None
+ signature: str | None = None
+ signature_algorithm: str | None = None
+ signature_encoding: str | None = None
+ signature_scope: str | None = None
+ key_id: str | None = None
+ fingerprint: str | None = None
+ content_length: int | None = None
+ metadata: Mapping[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class ProviderInvocationContext:
+ request_id: str
+ trace_id: str | None = None
+ authorization_scope: str | None = None
+ credential_ref: str | None = None
+
+
+class SkillSourceProvider(ABC):
+ """Remote catalogue adapter. Workspace mutation is intentionally absent."""
+
+ source_id: str
+ provider_type: str
+ display_name: str
+ capabilities: frozenset[str]
+
+ async def start(self) -> None:
+ return None
+
+ async def close(self) -> None:
+ return None
+
+ @abstractmethod
+ async def search(
+ self,
+ request: SkillSearchRequest,
+ context: ProviderInvocationContext,
+ ) -> SkillSearchResult:
+ raise NotImplementedError
+
+ async def check_updates(
+ self,
+ installed: Sequence[InstalledArtifact],
+ context: ProviderInvocationContext,
+ ) -> Sequence[SkillUpdateStatus]:
+ raise NotImplementedError
+
+ @abstractmethod
+ async def get_artifact(
+ self,
+ skill_ref: SkillRef,
+ version_id: str,
+ context: ProviderInvocationContext,
+ ) -> ArtifactDescriptor:
+ raise NotImplementedError
+
+
+class SkillSourceExtension(BaseExtension, ABC):
+ """Factory registered by a trusted extension package."""
+
+ provider_type: str
+ api_version: str = "2"
+
+ @abstractmethod
+ def create_provider(self, config: SourceConfig) -> SkillSourceProvider:
+ raise NotImplementedError
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index f06be007b3..da3f3fd963 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -249,6 +249,11 @@ CLI_FORWARD_REQ_METHODS = frozenset(
"skills.teamskillshub.install",
"skills.teamskillshub.publish",
"skills.teamskillshub.delete",
+ "skills.source.providers",
+ "skills.source.search",
+ "skills.source.install",
+ "skills.updates.check",
+ "skills.update",
"skills.evolution.status",
"skills.evolution.get",
"skills.evolution.save",
@@ -356,6 +361,11 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset(
"skills.teamskillshub.install",
"skills.teamskillshub.publish",
"skills.teamskillshub.delete",
+ "skills.source.providers",
+ "skills.source.search",
+ "skills.source.install",
+ "skills.updates.check",
+ "skills.update",
"skills.evolution.status",
"skills.evolution.get",
"skills.evolution.save",
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index a14fdbbb3b..8793911d4e 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -671,6 +671,11 @@ _FORWARD_REQ_METHODS = frozenset({
"skills.teamskillshub.install",
"skills.teamskillshub.publish",
"skills.teamskillshub.delete",
+ "skills.source.providers",
+ "skills.source.search",
+ "skills.source.install",
+ "skills.updates.check",
+ "skills.update",
"skills.retrieval.status",
"skills.retrieval.index_build",
"skills.retrieval.index_cancel",
@@ -682,8 +687,11 @@ _FORWARD_REQ_METHODS = frozenset({
"skills.evolution.archives",
"skills.evolution.rollback",
"skills.evolution.rebuild",
+ "skills.enterprise.list",
"skills.enterprise.install",
"skills.enterprise.uninstall",
+ "skills.enterprise.source.providers",
+ "skills.enterprise.source.search",
"symphony.build_score",
"symphony.pause_build",
"symphony.score_status",
@@ -775,6 +783,11 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
"skills.teamskillshub.install",
"skills.teamskillshub.publish",
"skills.teamskillshub.delete",
+ "skills.source.providers",
+ "skills.source.search",
+ "skills.source.install",
+ "skills.updates.check",
+ "skills.update",
"skills.retrieval.status",
"skills.retrieval.index_build",
"skills.retrieval.index_cancel",
@@ -786,8 +799,11 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
"skills.evolution.archives",
"skills.evolution.rollback",
"skills.evolution.rebuild",
+ "skills.enterprise.list",
"skills.enterprise.install",
"skills.enterprise.uninstall",
+ "skills.enterprise.source.providers",
+ "skills.enterprise.source.search",
"symphony.build_score",
"symphony.pause_build",
"symphony.score_status",
@@ -6903,46 +6919,6 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
channel.register_method("cron.job.preview", _cron_job_preview)
channel.register_method("cron.job.run_now", _cron_job_run_now)
- async def _skills_enterprise_list(ws, req_id, params, session_id):
- """Gateway 只读 DB:按最终 service_id+agent_id 列出已装成功行."""
- from jiuwenswarm.agents.harness.common.installed_skill import (
- list_installed_skills_for_gateway,
- resolve_final_tenant_ids,
- )
- from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple
-
- if not isinstance(params, dict):
- await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
- return
- g, b, u = extract_routing_triple(params)
- try:
- service_id, agent_id = resolve_final_tenant_ids(
- group_id=g,
- bot_id=b,
- user_id=u,
- service_id=params.get("service_id"),
- agent_id=params.get("agent_id"),
- )
- skills = await list_installed_skills_for_gateway(
- service_id=service_id,
- agent_id=agent_id,
- )
- await channel.send_response(
- ws,
- req_id,
- ok=True,
- payload={
- "skills": skills,
- "service_id": service_id,
- "agent_id": agent_id,
- },
- )
- except Exception as e: # noqa: BLE001
- logger.exception("[skills.enterprise.list] %s", e)
- await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
-
- channel.register_method("skills.enterprise.list", _skills_enterprise_list)
-
# 数字分身 — permissions.owner_scopes:仅 Web 网关直连 config(不经 E2A / config_rpc)。
# 其余 permissions.*(tools / rules / approval_overrides)走 _forward_permissions_to_agent。
diff --git a/jiuwenswarm/gateway/channel_manager/web/invoke.py b/jiuwenswarm/gateway/channel_manager/web/invoke.py
index 5080fb068b..a8200c0ef1 100644
--- a/jiuwenswarm/gateway/channel_manager/web/invoke.py
+++ b/jiuwenswarm/gateway/channel_manager/web/invoke.py
@@ -28,7 +28,21 @@ _ENTERPRISE_BLOCKED_EXACT = frozenset({
"updater.upgrade", "updater.reset_source", "updater.set_conf",
})
_ENTERPRISE_BLOCKED_PREFIXES = ("agents.", "teams.", "extensions.", "plugins.")
-_ENTERPRISE_SKILL_ALLOWED = frozenset({"skills.list", "skills.get", "skills.enterprise.list"})
+_ENTERPRISE_SKILL_ALLOWED = frozenset({
+ "skills.list",
+ "skills.get",
+ "skills.toggle",
+ "skills.source.providers",
+ "skills.source.search",
+ "skills.source.install",
+ "skills.updates.check",
+ "skills.update",
+ "skills.enterprise.list",
+ "skills.enterprise.install",
+ "skills.enterprise.uninstall",
+ "skills.enterprise.source.providers",
+ "skills.enterprise.source.search",
+})
def is_enterprise_write_forbidden(method: str) -> bool:
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
index 207251953c..349123724d 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
@@ -1027,9 +1027,11 @@ async def _stream(
def _coerce_query_value(raw: str) -> Any:
text = str(raw).strip()
lowered = text.lower()
- if lowered in {"true", "1", "yes"}:
+ # 布尔只认显式字面量;``1``/``0`` 不归入布尔——它们更可能是页码/数量等数值
+ # (如 ``page=1``),交给下面 isdigit() 转 int,避免被截胡成 True/False。
+ if lowered in {"true", "yes"}:
return True
- if lowered in {"false", "0", "no"}:
+ if lowered in {"false", "no"}:
return False
try:
if text.isdigit() or (text.startswith("-") and text[1:].isdigit()):
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py
index 3bf0882d0a..ce27ee3bc3 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py
@@ -445,6 +445,64 @@ _SKILLS_ROUTES: tuple[WebHttpMappedRoute, ...] = (
accept_body=True,
bind_session_param=True,
),
+ WebHttpMappedRoute(
+ "GET", "/skills/sources", "skills.source.providers",
+ "skills", "列出已配置技能源",
+ query_keys=_TENANT_QUERY + _SKILL_SESSION_QUERY,
+ bind_session_param=True,
+ ),
+ WebHttpMappedRoute(
+ "GET", "/skills/sources/search", "skills.source.search",
+ "skills", "搜索技能源",
+ query_keys=("source_id", "q", "page", "page_size") + _TENANT_QUERY + _SKILL_SESSION_QUERY,
+ bind_session_param=True,
+ ),
+ WebHttpMappedRoute(
+ "POST", "/skills/sources/actions/search", "skills.source.search",
+ "skills", "搜索技能源(含扩展筛选)",
+ query_keys=_TENANT_QUERY,
+ accept_body=True,
+ bind_session_param=True,
+ ),
+ WebHttpMappedRoute(
+ "POST", "/skills/sources/actions/install", "skills.source.install",
+ "skills", "从技能源安装精确版本",
+ query_keys=_TENANT_QUERY,
+ accept_body=True,
+ bind_session_param=True,
+ ),
+ WebHttpMappedRoute(
+ "GET", "/skills/updates", "skills.updates.check",
+ "skills", "检查已安装技能更新",
+ query_keys=("source_id",) + _TENANT_QUERY + _SKILL_SESSION_QUERY,
+ bind_session_param=True,
+ ),
+ WebHttpMappedRoute(
+ "POST", "/skills/actions/update", "skills.update",
+ "skills", "更新已安装技能",
+ query_keys=_TENANT_QUERY,
+ accept_body=True,
+ bind_session_param=True,
+ ),
+ WebHttpMappedRoute(
+ "GET", "/skills/enterprise/sources", "skills.enterprise.source.providers",
+ "skills", "列出企业技能源",
+ query_keys=_TENANT_QUERY + _SKILL_SESSION_QUERY,
+ bind_session_param=True,
+ ),
+ WebHttpMappedRoute(
+ "GET", "/skills/enterprise/sources/search", "skills.enterprise.source.search",
+ "skills", "搜索企业技能源",
+ query_keys=("source_id", "q", "page", "page_size") + _TENANT_QUERY + _SKILL_SESSION_QUERY,
+ bind_session_param=True,
+ ),
+ WebHttpMappedRoute(
+ "POST", "/skills/enterprise/sources/actions/search", "skills.enterprise.source.search",
+ "skills", "搜索企业技能源(含扩展筛选)",
+ query_keys=_TENANT_QUERY,
+ accept_body=True,
+ bind_session_param=True,
+ ),
WebHttpMappedRoute(
"GET", "/skills/retrieval/status", "skills.retrieval.status",
"skills", "技能检索索引状态",
diff --git a/jiuwenswarm/gateway/routing/agent_rest_map.py b/jiuwenswarm/gateway/routing/agent_rest_map.py
index 667129d6a9..1ed05801b8 100644
--- a/jiuwenswarm/gateway/routing/agent_rest_map.py
+++ b/jiuwenswarm/gateway/routing/agent_rest_map.py
@@ -118,8 +118,16 @@ _ROUTE_ROWS: tuple[tuple[str, str, str], ...] = (
("skills.teamskillshub.pack", "POST", "/skills/teamskillshub/actions/pack"),
("skills.teamskillshub.publish", "POST", "/skills/teamskillshub/actions/publish"),
("skills.teamskillshub.delete", "POST", "/skills/teamskillshub/actions/delete"),
+ ("skills.source.providers", "GET", "/skills/sources"),
+ ("skills.source.search", "GET", "/skills/sources/search"),
+ ("skills.source.install", "POST", "/skills/sources/install"),
+ ("skills.updates.check", "GET", "/skills/updates"),
+ ("skills.update", "POST", "/skills/actions/update"),
+ ("skills.enterprise.list", "GET", "/skills/enterprise"),
("skills.enterprise.install", "POST", "/skills/enterprise/install"),
("skills.enterprise.uninstall", "POST", "/skills/enterprise/actions/uninstall"),
+ ("skills.enterprise.source.providers", "GET", "/skills/enterprise/sources"),
+ ("skills.enterprise.source.search", "GET", "/skills/enterprise/sources/search"),
("skills.get", "GET", "/skills/{name}"),
("skills.uninstall", "DELETE", "/skills/{name}"),
("skills.toggle", "POST", "/skills/{name}/actions/toggle"),
diff --git a/jiuwenswarm/server/agent_http_routes.py b/jiuwenswarm/server/agent_http_routes.py
index 7ee2ed53db..440e3e8017 100644
--- a/jiuwenswarm/server/agent_http_routes.py
+++ b/jiuwenswarm/server/agent_http_routes.py
@@ -268,6 +268,24 @@ ROUTES: list[RouteSpec] = [
"/skills/teamskillshub/actions/delete",
ReqMethod.SKILLS_TEAMSKILLS_HUB_DELETE.value,
),
+ RouteSpec(
+ "GET", "/skills/sources", ReqMethod.SKILLS_SOURCE_PROVIDERS.value
+ ),
+ RouteSpec(
+ "GET", "/skills/sources/search", ReqMethod.SKILLS_SOURCE_SEARCH.value
+ ),
+ RouteSpec(
+ "POST", "/skills/sources/install", ReqMethod.SKILLS_SOURCE_INSTALL.value, 201
+ ),
+ RouteSpec(
+ "GET", "/skills/updates", ReqMethod.SKILLS_UPDATES_CHECK.value
+ ),
+ RouteSpec(
+ "POST", "/skills/actions/update", ReqMethod.SKILLS_UPDATE.value
+ ),
+ RouteSpec(
+ "GET", "/skills/enterprise", ReqMethod.SKILLS_ENTERPRISE_LIST.value
+ ),
RouteSpec(
"POST", "/skills/enterprise/install", ReqMethod.SKILLS_ENTERPRISE_INSTALL.value, 201
),
@@ -276,6 +294,16 @@ ROUTES: list[RouteSpec] = [
"/skills/enterprise/actions/uninstall",
ReqMethod.SKILLS_ENTERPRISE_UNINSTALL.value,
),
+ RouteSpec(
+ "GET",
+ "/skills/enterprise/sources",
+ ReqMethod.SKILLS_ENTERPRISE_SOURCE_PROVIDERS.value,
+ ),
+ RouteSpec(
+ "GET",
+ "/skills/enterprise/sources/search",
+ ReqMethod.SKILLS_ENTERPRISE_SOURCE_SEARCH.value,
+ ),
RouteSpec("GET", "/skills/{name}", ReqMethod.SKILLS_GET.value),
RouteSpec("DELETE", "/skills/{name}", ReqMethod.SKILLS_UNINSTALL.value),
RouteSpec("POST", "/skills/{name}/actions/toggle", ReqMethod.SKILLS_TOGGLE.value),
diff --git a/jiuwenswarm/server/agent_http_server.py b/jiuwenswarm/server/agent_http_server.py
index ece72d6423..10771bb62b 100644
--- a/jiuwenswarm/server/agent_http_server.py
+++ b/jiuwenswarm/server/agent_http_server.py
@@ -25,10 +25,24 @@ API_PREFIX = "/api/v1"
PORT_SCAN_RANGE = 10
PORT_SCAN_STEP = 1000
-#: 企业版北向允许的 Skill 方法白名单(与 Gateway ``invoke.py`` 的
-#: ``_ENTERPRISE_SKILL_ALLOWED`` 保持一致)。企业版暂不开放 skills.toggle /
-#: install / uninstall 等写操作,仅只读列表/详情开放。
-_ENTERPRISE_SKILL_ALLOWED = frozenset({"skills.list", "skills.get", "skills.enterprise.list"})
+#: 企业版北向允许的 Skill 方法白名单(必须与 Gateway ``invoke.py`` 的
+#: ``_ENTERPRISE_SKILL_ALLOWED`` 保持一致)。企业版经 SPI 开放只读列表/详情
+#: 与用户自装/卸载/更新写操作;技能卸载走 ``skills.enterprise.uninstall``。
+_ENTERPRISE_SKILL_ALLOWED = frozenset({
+ "skills.list",
+ "skills.get",
+ "skills.toggle",
+ "skills.source.providers",
+ "skills.source.search",
+ "skills.source.install",
+ "skills.updates.check",
+ "skills.update",
+ "skills.enterprise.list",
+ "skills.enterprise.install",
+ "skills.enterprise.uninstall",
+ "skills.enterprise.source.providers",
+ "skills.enterprise.source.search",
+})
def _is_enterprise_skill_forbidden(method: str) -> bool:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 5f73d63f20..6f58ba04f5 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -593,6 +593,11 @@ _SKILL_ROUTES: dict[ReqMethod, str] = {
ReqMethod.SKILLS_TEAMSKILLS_HUB_INSTALL: "handle_skills_team_skills_hub_install",
ReqMethod.SKILLS_TEAMSKILLS_HUB_PUBLISH: "handle_skills_team_skills_hub_publish",
ReqMethod.SKILLS_TEAMSKILLS_HUB_DELETE: "handle_skills_team_skills_hub_delete",
+ ReqMethod.SKILLS_SOURCE_PROVIDERS: "handle_skills_source_providers",
+ ReqMethod.SKILLS_SOURCE_SEARCH: "handle_skills_source_search",
+ ReqMethod.SKILLS_SOURCE_INSTALL: "handle_skills_source_install",
+ ReqMethod.SKILLS_UPDATES_CHECK: "handle_skills_updates_check",
+ ReqMethod.SKILLS_UPDATE: "handle_skills_update",
ReqMethod.SKILLS_RETRIEVAL_STATUS: "handle_skills_retrieval_status",
ReqMethod.SKILLS_RETRIEVAL_INDEX_BUILD: "handle_skills_retrieval_index_build",
ReqMethod.SKILLS_RETRIEVAL_INDEX_CANCEL: "handle_skills_retrieval_index_cancel",
@@ -604,6 +609,8 @@ _SKILL_ROUTES: dict[ReqMethod, str] = {
ReqMethod.SKILLS_ENTERPRISE_LIST: "handle_skills_enterprise_list",
ReqMethod.SKILLS_ENTERPRISE_INSTALL: "handle_skills_web_install",
ReqMethod.SKILLS_ENTERPRISE_UNINSTALL: "handle_skills_web_uninstall",
+ ReqMethod.SKILLS_ENTERPRISE_SOURCE_PROVIDERS: "handle_skills_source_providers",
+ ReqMethod.SKILLS_ENTERPRISE_SOURCE_SEARCH: "handle_skills_source_search",
}
# Evolution version RPCs (archives/rollback/rebuild) are handled by DeepAdapter.
@@ -623,6 +630,18 @@ _SKILLS_WEB_HANDLERS: frozenset[str] = frozenset(
}
)
+_SKILL_SOURCE_POLICY_ROUTES: frozenset[ReqMethod] = frozenset(
+ {
+ ReqMethod.SKILLS_SOURCE_PROVIDERS,
+ ReqMethod.SKILLS_SOURCE_SEARCH,
+ ReqMethod.SKILLS_SOURCE_INSTALL,
+ ReqMethod.SKILLS_UPDATES_CHECK,
+ ReqMethod.SKILLS_UPDATE,
+ ReqMethod.SKILLS_ENTERPRISE_SOURCE_PROVIDERS,
+ ReqMethod.SKILLS_ENTERPRISE_SOURCE_SEARCH,
+ }
+)
+
# Preserve cross-service context-size hints if they are present in request.params.
_CONTEXT_SIZE_HINT_KEYS: tuple[str, ...] = (
"context_size",
@@ -1952,6 +1971,11 @@ class JiuWenSwarm:
handler_name = _SKILL_ROUTES[request.req_method]
handler = getattr(self._skill_manager, handler_name)
try:
+ if is_enterprise() and request.req_method in _SKILL_SOURCE_POLICY_ROUTES:
+ adapter = self._ensure_adapter(mode=self._adapter_mode_for_request(request))
+ prepare_sources = getattr(adapter, "prepare_skill_source_config", None)
+ if callable(prepare_sources):
+ await prepare_sources(request)
params = dict(request.params) if isinstance(request.params, dict) else {}
if handler_name in _SKILLS_WEB_HANDLERS and is_enterprise():
if self._service_id and not str(params.get("service_id") or "").strip():
@@ -1966,6 +1990,8 @@ class JiuWenSwarm:
"handle_skills_skillnet_install",
"handle_skills_clawhub_download",
"handle_skills_team_skills_hub_install",
+ "handle_skills_source_install",
+ "handle_skills_update",
]
_enterprise_web_handler = handler_name in _SKILLS_WEB_HANDLERS
if handler_name == "handle_skills_skillnet_install" and payload.get("pending"):
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index d71d1d34d0..9ae4e14a23 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -4477,6 +4477,18 @@ class JiuWenSwarmDeepAdapter:
DEFAULT_AGENT_LOAD_SLOTS,
)
self._enterprise_config = loaded
+ if loaded is not None and self._skill_manager is not None:
+ try:
+ await self._skill_manager.apply_skill_source_configs(
+ getattr(loaded, "extension_config", None)
+ )
+ except Exception as exc: # noqa: BLE001
+ # SourceManager applies revisions atomically; a bad revision leaves
+ # the last valid registry active for existing requests.
+ logger.error(
+ "[JiuWenSwarmDeepAdapter] skill source config rejected: %s",
+ exc,
+ )
if loaded is None:
from jiuwenswarm.common.request_identity import web_routing_identity
@@ -4491,6 +4503,10 @@ class JiuWenSwarmDeepAdapter:
identity.get("user_id"),
)
+ async def prepare_skill_source_config(self, request: AgentRequest) -> None:
+ """Load the effective policy before a source RPC, even before chat startup."""
+ await self._load_enterprise_config(request)
+
def _inject_extension_config_into_inputs(self, inputs: dict[str, Any]) -> None:
"""将企业策略中的 extension_config 注入 inputs(替代 ee gateway channel_context 透传)。"""
if not is_enterprise():
@@ -6466,7 +6482,7 @@ class JiuWenSwarmDeepAdapter:
)
async def refresh_enabled_skills_from_db(self) -> None:
- """Refresh enabled skills from the current tenant workspace state."""
+ """workspace Skill 状态变更后刷新启用集并热替换 ``SkillUseRail``。"""
if not is_skill_whitelist_tenant(self._agent_id, self._service_id):
return
if self._instance is None:
diff --git a/jiuwenswarm/server/runtime/skill/artifact_security.py b/jiuwenswarm/server/runtime/skill/artifact_security.py
new file mode 100644
index 0000000000..95dbb97c6e
--- /dev/null
+++ b/jiuwenswarm/server/runtime/skill/artifact_security.py
@@ -0,0 +1,157 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.
+
+"""Common artifact integrity and SkillHub HMAC verification."""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import os
+import re
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Mapping
+
+from jiuwenswarm.extensions.sdk.skill_source import (
+ ArtifactDescriptor,
+ SecretResolver,
+ TrustPolicy,
+)
+
+_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
+_HMAC_ALGORITHM = "HmacSHA256"
+_HMAC_ENCODING = "hex-lower"
+_HMAC_SCOPE = "skillhub-artifact-v1"
+
+
+class ArtifactVerificationError(RuntimeError):
+ def __init__(self, code: str, message: str):
+ super().__init__(message)
+ self.code = code
+
+
+class MappingSecretResolver(SecretResolver):
+ def __init__(self, secrets: Mapping[str, str]):
+ self._secrets = {str(key): str(value) for key, value in secrets.items()}
+
+ def resolve(self, reference: str) -> str | None:
+ return self._secrets.get(str(reference or "").strip())
+
+
+class EnvironmentSecretResolver(SecretResolver):
+ """Resolve only explicit ``env://NAME`` references."""
+
+ def resolve(self, reference: str) -> 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
+ secret = os.getenv(variable)
+ return secret if secret else None
+
+
+@dataclass(frozen=True)
+class VerificationResult:
+ verified: bool
+ artifact_sha256: str
+ algorithm: str | None = None
+ scope: str | None = None
+ key_id: str | None = None
+ verified_at: str | None = None
+
+ def to_audit_dict(self) -> dict[str, str | bool]:
+ raw: dict[str, str | bool | None] = {
+ "verified": self.verified,
+ "artifact_sha256": self.artifact_sha256,
+ "algorithm": self.algorithm,
+ "scope": self.scope,
+ "key_id": self.key_id,
+ "verified_at": self.verified_at,
+ }
+ result: dict[str, str | bool] = {}
+ for key, value in raw.items():
+ if value is not None:
+ result[key] = value
+ return result
+
+
+def verify_skillhub_artifact(
+ descriptor: ArtifactDescriptor,
+ body: bytes,
+ *,
+ trust_policy: TrustPolicy,
+ secret_resolver: SecretResolver,
+) -> VerificationResult:
+ """Verify raw ZIP bytes using the frozen ``skillhub-artifact-v1`` contract."""
+ actual_sha256 = hashlib.sha256(body).hexdigest().lower()
+ declared_sha256 = str(descriptor.artifact_sha256 or "").strip()
+ if declared_sha256 and not _SHA256_RE.fullmatch(declared_sha256):
+ raise ArtifactVerificationError(
+ "artifact_descriptor_invalid", "artifactSha256 must be lower-case SHA-256 hex"
+ )
+ if declared_sha256 and not hmac.compare_digest(actual_sha256, declared_sha256):
+ raise ArtifactVerificationError(
+ "artifact_checksum_mismatch", "artifact SHA-256 does not match"
+ )
+
+ signature = str(descriptor.signature or "").strip()
+ required = trust_policy.verification == "required"
+ if not signature:
+ if required:
+ raise ArtifactVerificationError(
+ "artifact_signature_invalid", "artifact signature is required"
+ )
+ return VerificationResult(verified=False, artifact_sha256=actual_sha256)
+
+ if not declared_sha256:
+ raise ArtifactVerificationError(
+ "artifact_signature_invalid", "signed artifact is missing artifactSha256"
+ )
+ algorithm = str(descriptor.signature_algorithm or "").strip()
+ encoding = str(descriptor.signature_encoding or "").strip()
+ scope = str(descriptor.signature_scope or "").strip()
+ key_id = str(descriptor.key_id or "").strip()
+ if algorithm != _HMAC_ALGORITHM or algorithm not in trust_policy.allowed_algorithms:
+ raise ArtifactVerificationError(
+ "artifact_signature_invalid", "artifact signature algorithm is not allowed"
+ )
+ if encoding != _HMAC_ENCODING or scope != _HMAC_SCOPE:
+ raise ArtifactVerificationError(
+ "artifact_signature_invalid", "artifact signature encoding or scope is invalid"
+ )
+ if not _SHA256_RE.fullmatch(signature):
+ raise ArtifactVerificationError(
+ "artifact_signature_invalid", "artifact signature must be lower-case HMAC hex"
+ )
+ secret_ref = trust_policy.hmac_key_refs.get(key_id)
+ if not key_id or not secret_ref:
+ raise ArtifactVerificationError(
+ "artifact_signature_invalid", "artifact HMAC key is unavailable"
+ )
+ secret = secret_resolver.resolve(secret_ref)
+ if not secret:
+ raise ArtifactVerificationError(
+ "artifact_signature_invalid", "artifact HMAC key is unavailable"
+ )
+ skill_ref = descriptor.artifact_ref.skill_ref
+ signing_input = (
+ f"{_HMAC_SCOPE}\n{skill_ref.skill_id}\n"
+ f"{descriptor.artifact_ref.version_id}\n{declared_sha256}"
+ )
+ expected = hmac.new(
+ secret.encode("utf-8"), signing_input.encode("utf-8"), hashlib.sha256
+ ).hexdigest()
+ if not hmac.compare_digest(expected, signature):
+ raise ArtifactVerificationError(
+ "artifact_signature_invalid", "artifact HMAC verification failed"
+ )
+ return VerificationResult(
+ verified=True,
+ artifact_sha256=actual_sha256,
+ algorithm=algorithm,
+ scope=scope,
+ key_id=key_id,
+ verified_at=datetime.now(timezone.utc).isoformat(),
+ )
diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.py
index 4258a2e0a7..d78a35fca6 100644
--- a/jiuwenswarm/server/runtime/skill/skill_manager.py
+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py
@@ -40,6 +40,31 @@ from jiuwenswarm.common.utils import (
get_builtin_skills_dir,
is_package_installation,
)
+from jiuwenswarm.extensions.sdk.skill_source import (
+ ArtifactDescriptor,
+ DownloadPolicy,
+ InstalledArtifact,
+ ProviderInvocationContext,
+ SkillRef,
+ SkillSearchRequest,
+ 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:
@@ -281,7 +306,7 @@ def _skillnet_network_context():
class SkillNameConflictError(ValueError):
- """Raised when the same skill name is owned by a different installation."""
+ """同名但不同来源的 Skill 安装冲突(映射为稳定错误码 skill_name_conflict)。"""
def _safe_path_name(value: Any, label: str) -> str:
@@ -482,6 +507,9 @@ class SkillManager:
self._service_id = str(service_id or "").strip() or None
self._agent_id = str(agent_id or "").strip() or None
self._state: dict[str, Any] = self._load_state()
+ self._source_registry = SourceRegistry()
+ self._secret_resolver = EnvironmentSecretResolver()
+ self._register_builtin_skill_sources()
# 把手动拷入 skills 目录、未经任何安装流程登记的本地技能,自动补登记到
# local_skills,使其与"导入本地技能"完全等价(可展示/卸载/查看详情/禁用)。
self._register_unmanaged_local_skills()
@@ -500,6 +528,249 @@ class SkillManager:
"""安装成功落盘后回调(通常为重载 Agent 实例)."""
self._skillnet_install_complete_hook = hook
+ def _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,
+ ),
+ )
+
+ @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()
+ verification = str(
+ os.getenv("TEAM_SKILLS_HUB_HMAC_VERIFICATION") or "required"
+ ).strip().lower()
+ if verification not in {"required", "if-present"}:
+ logger.warning(
+ "Invalid TEAM_SKILLS_HUB_HMAC_VERIFICATION=%s; using required",
+ verification,
+ )
+ verification = "required"
+ 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}"},
+ ),
+ )
+
+ @staticmethod
+ def _source_config_custom_payload(record: dict[str, Any]) -> dict[str, Any] | None:
+ raw = record.get("custom_config")
+ if raw is None:
+ raw = record.get("data")
+ if isinstance(raw, str):
+ try:
+ raw = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise SourceRegistryError(
+ "source_misconfigured", "extension custom_config is not valid JSON"
+ ) from exc
+ return 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
+
+ @staticmethod
+ def _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()},
+ )
+ capabilities = raw.get("capabilities") or []
+ if not isinstance(capabilities, list):
+ raise SourceRegistryError("source_misconfigured", "capabilities must be an array")
+ options = raw.get("options") or {}
+ if not isinstance(options, dict):
+ raise SourceRegistryError("source_misconfigured", "options must be an object")
+ try:
+ priority = int(raw.get("priority", 0))
+ except (TypeError, ValueError) as exc:
+ raise SourceRegistryError("source_misconfigured", "priority must be an integer") from exc
+ download_raw = raw.get("download_policy")
+ download_policy = DownloadPolicy()
+ if isinstance(download_raw, dict):
+ allowed_hosts = download_raw.get("allowed_hosts") or []
+ if not isinstance(allowed_hosts, list):
+ raise SourceRegistryError(
+ "source_misconfigured", "download_policy.allowed_hosts must be an array"
+ )
+ try:
+ max_bytes = int(download_raw.get("max_bytes", 64 * 1024 * 1024))
+ timeout_seconds = float(download_raw.get("timeout_seconds", 60.0))
+ except (TypeError, ValueError) as exc:
+ raise SourceRegistryError(
+ "source_misconfigured", "download policy limits must be numeric"
+ ) from exc
+ if max_bytes <= 0 or timeout_seconds <= 0:
+ raise SourceRegistryError(
+ "source_misconfigured", "download policy limits must be positive"
+ )
+ download_policy = DownloadPolicy(
+ allowed_hosts=tuple(str(item).strip().lower() for item in allowed_hosts if str(item).strip()),
+ max_bytes=max_bytes,
+ timeout_seconds=timeout_seconds,
+ )
+ return SourceConfig(
+ source_id=str(raw.get("source_id") or "").strip(),
+ provider_type=str(raw.get("provider_type") or "").strip(),
+ enabled=bool(raw.get("enabled", True)),
+ priority=priority,
+ endpoint_ref=str(raw.get("endpoint_ref") or "").strip() or None,
+ 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),
+ )
+
+ async def apply_skill_source_configs(
+ self,
+ extension_config: list[dict[str, Any]] | None,
+ ) -> dict[str, Any]:
+ """Atomically apply ``custom_config.skill_sources`` from effective policy."""
+ raw_sources: list[dict[str, Any]] = []
+ for record in extension_config or []:
+ if not isinstance(record, dict):
+ continue
+ custom = self._source_config_custom_payload(record)
+ if custom is None or "skill_sources" not in custom:
+ continue
+ configured = custom.get("skill_sources")
+ if not isinstance(configured, list):
+ raise SourceRegistryError(
+ "source_misconfigured", "custom_config.skill_sources must be an array"
+ )
+ for item in configured:
+ if not isinstance(item, dict):
+ raise SourceRegistryError(
+ "source_misconfigured", "skill_sources entries must be objects"
+ )
+ raw_sources.append(item)
+ if not raw_sources:
+ return {
+ "applied": False,
+ "source_count": len(self._source_registry.list()),
+ }
+
+ 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,
+ ),
+ )
+
+ 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
+ if extension is None:
+ raise SourceRegistryError(
+ "source_misconfigured",
+ f"provider_type is not registered: {config.provider_type}",
+ )
+ candidate.bind_extension(config, extension)
+
+ previous = self._source_registry
+ self._source_registry = candidate
+ await previous.close()
+ return {"applied": True, "source_count": len(candidate.list())}
+
+ def register_skill_source_provider(
+ self,
+ config: SourceConfig,
+ provider: SkillSourceProvider,
+ *,
+ display_name: str | None = None,
+ ) -> None:
+ """Bind an extension-created Provider to this AgentServer runtime."""
+ self._source_registry.register(config, provider, display_name=display_name)
+
+ def bind_skill_source_extension(
+ self,
+ config: SourceConfig,
+ extension: SkillSourceExtension,
+ *,
+ display_name: str | None = None,
+ ) -> SkillSourceProvider:
+ """Instantiate one configured source through a registered SPI factory."""
+ return self._source_registry.bind_extension(
+ config,
+ extension,
+ display_name=display_name,
+ )
+
# -----------------------------------------------------------------------
# 公开 handler
# -----------------------------------------------------------------------
@@ -563,10 +834,14 @@ class SkillManager:
return {"plugins": plugins, "skills": skills}
async def handle_skills_enterprise_list(self, params: dict) -> dict:
- """Return workspace-backed enterprise installations."""
+ """企业兼容列表:复用 workspace 安装 DTO,并保留租户标识字段。"""
payload = await self.handle_skills_installed(params)
- service_id = str(params.get("service_id") or self._service_id or "").strip()
- agent_id = str(params.get("agent_id") or self._agent_id or "").strip()
+ service_id = str(
+ params.get("service_id") or self._service_id or ""
+ ).strip()
+ agent_id = str(
+ params.get("agent_id") or self._agent_id or ""
+ ).strip()
for skill in payload.get("skills", []):
if not isinstance(skill, dict):
continue
@@ -1939,6 +2214,482 @@ class SkillManager:
logger.error("Team Skills Hub pack 失败: %s", exc)
return {"success": False, "detail": str(exc)[:500]}
+ @staticmethod
+ def _source_error(code: str, message: str) -> dict[str, Any]:
+ return {
+ "success": False,
+ "error_code": code,
+ "error_message": str(message)[:500],
+ }
+
+ @staticmethod
+ def _source_context(params: dict[str, Any]) -> ProviderInvocationContext:
+ metadata = params.get("metadata")
+ metadata = metadata if isinstance(metadata, dict) else {}
+ return ProviderInvocationContext(
+ request_id=str(params.get("request_id") or uuid.uuid4()),
+ trace_id=str(metadata.get("trace_id") or "").strip() or None,
+ )
+
+ async def handle_skills_source_providers(self, params: dict) -> dict:
+ """List configured sources without exposing endpoint or credentials."""
+ del params
+ return {
+ "success": True,
+ "providers": [item.to_dict() for item in self._source_registry.list()],
+ }
+
+ async def handle_skills_source_search(self, params: dict) -> dict:
+ """Dispatch a normalized search request to one Skill Source Provider."""
+ source_id = str(params.get("source_id") or "").strip()
+ if not source_id:
+ return self._source_error("missing_params", "source_id is required")
+ try:
+ page = int(params.get("page", 1))
+ page_size = int(params.get("page_size", 20))
+ except (TypeError, ValueError):
+ return self._source_error("invalid_params", "page and page_size must be integers")
+ if page < 1 or not 1 <= page_size <= 100:
+ return self._source_error("invalid_params", "page must be >= 1 and page_size must be 1..100")
+ filters = params.get("filter", {})
+ if filters is None:
+ filters = {}
+ if not isinstance(filters, dict):
+ return self._source_error("invalid_params", "filter must be an object")
+ blocked_filter_keys = {
+ "token", "authorization", "password", "secret", "signature",
+ "download_url", "user_id", "group_id", "bot_id", "service_id", "agent_id",
+ }
+ if any(str(key).strip().lower() in blocked_filter_keys for key in filters):
+ return self._source_error("invalid_params", "filter contains a protected field")
+
+ try:
+ provider = await self._source_registry.get(source_id, "search")
+ result = await provider.search(
+ SkillSearchRequest(
+ q=str(params.get("q") or "").strip(),
+ page=page,
+ page_size=page_size,
+ filters=filters,
+ ),
+ self._source_context(params),
+ )
+ items: list[dict[str, Any]] = []
+ seen: set[tuple[str, str]] = set()
+ for candidate in result.items:
+ if candidate.source_id != source_id:
+ raise SourceRegistryError(
+ "source_response_invalid", "provider returned a different source_id"
+ )
+ if not candidate.skill_id or not candidate.version_id or not candidate.name:
+ raise SourceRegistryError(
+ "source_response_invalid", "provider returned an incomplete SkillCandidate"
+ )
+ identity = (candidate.skill_id, candidate.version_id)
+ if identity in seen:
+ raise SourceRegistryError(
+ "source_response_invalid", "provider returned a duplicate artifact"
+ )
+ seen.add(identity)
+ items.append(candidate.to_dict())
+ return {
+ "success": True,
+ "source": source_id,
+ "source_id": source_id,
+ "items": items,
+ "skills": items,
+ "total": result.total,
+ "page": page,
+ "page_size": page_size,
+ "count": len(items),
+ "next_page": result.next_page,
+ }
+ except SourceRegistryError as exc:
+ return self._source_error(exc.code, str(exc))
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Skill Source search failed: source_id=%s error=%s", source_id, exc)
+ return self._source_error("source_unavailable", str(exc))
+
+ def _find_installation_by_skill_ref(
+ self,
+ source_id: str,
+ skill_id: str,
+ ) -> dict[str, Any] | None:
+ for record in self._get_installed_plugins():
+ if not isinstance(record, dict):
+ continue
+ if (
+ str(record.get("source_id") or "").strip() == source_id
+ and str(record.get("skill_id") or "").strip() == skill_id
+ ):
+ return record
+ return None
+
+ @staticmethod
+ def _validate_source_artifact(
+ descriptor: ArtifactDescriptor,
+ *,
+ source_id: str,
+ skill_id: str,
+ version_id: str,
+ ) -> None:
+ artifact_ref = descriptor.artifact_ref
+ if (
+ artifact_ref.skill_ref.source_id != source_id
+ or artifact_ref.skill_ref.skill_id != skill_id
+ or artifact_ref.version_id != version_id
+ ):
+ raise SourceRegistryError(
+ "source_response_invalid", "provider returned a different ArtifactRef"
+ )
+ checksum = str(descriptor.checksum_sha256 or "").strip().lower()
+ artifact_sha = str(descriptor.artifact_sha256 or "").strip().lower()
+ for value in (checksum, artifact_sha):
+ if value and not re.fullmatch(r"[0-9a-f]{64}", value):
+ raise SourceRegistryError("source_response_invalid", "invalid artifact SHA-256")
+
+ async def _fetch_verified_source_artifact(
+ self,
+ *,
+ source_id: str,
+ skill_id: str,
+ version_id: str,
+ params: dict[str, Any],
+ ) -> tuple[ArtifactDescriptor, bytes, dict[str, Any]]:
+ """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(
+ SkillRef(source_id=source_id, skill_id=skill_id),
+ version_id,
+ self._source_context(params),
+ )
+ self._validate_source_artifact(
+ descriptor,
+ source_id=source_id,
+ skill_id=skill_id,
+ version_id=version_id,
+ )
+ config = self._source_registry.get_config(source_id)
+ download_policy = config.download_policy
+ 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),
+ )
+ 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,
+ )
+ except ArtifactVerificationError as exc:
+ raise SourceRegistryError(exc.code, str(exc)) from exc
+ return descriptor, body, verification.to_audit_dict()
+
+ def _commit_source_skill_entity(
+ self,
+ skill_dir: Path,
+ *,
+ skill_name: str,
+ source_id: str,
+ skill_id: str,
+ version_id: str,
+ version: str,
+ force: bool,
+ fingerprint: str | None = None,
+ verification: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Atomically replace the entity, then commit the JSON installation record."""
+ existing_ref = self._find_installation_by_skill_ref(source_id, skill_id)
+ existing_name = str((existing_ref or {}).get("name") or "").strip()
+ if existing_ref is not None and not force:
+ raise SourceRegistryError(
+ "skill_already_installed",
+ f"skill {existing_name or skill_name} is already installed from {source_id}",
+ )
+ name_conflict = self._find_skill_installation(name=skill_name)
+ if name_conflict is not None and name_conflict is not existing_ref:
+ raise SourceRegistryError(
+ "skill_name_conflict", f"skill name already installed: {skill_name}"
+ )
+ entity_dir = str((existing_ref or {}).get("entity_dir") or existing_name or skill_name).strip()
+ dest = _safe_child_path(self._skills_dir, entity_dir, "skill")
+ if dest.exists() and existing_ref is None:
+ raise SourceRegistryError(
+ "skill_name_conflict", f"skill directory already exists: {skill_name}"
+ )
+ staging = _safe_child_path(
+ self._skills_dir,
+ f"_source_staging_{uuid.uuid4().hex}",
+ "skill staging",
+ )
+ backup = _safe_child_path(
+ self._skills_dir,
+ f"_source_backup_{uuid.uuid4().hex}",
+ "skill backup",
+ )
+ shutil.copytree(skill_dir, staging)
+ moved_old = False
+ try:
+ if dest.exists():
+ dest.rename(backup)
+ moved_old = True
+ staging.rename(dest)
+ record = self.record_skill_installation(
+ name=skill_name,
+ source_type="user",
+ source=source_id,
+ origin=f"{source_id}:{skill_id}",
+ version=version,
+ source_id=source_id,
+ skill_id=skill_id,
+ version_id=version_id,
+ fingerprint=fingerprint,
+ verification=verification,
+ entity_dir=entity_dir,
+ )
+ except Exception:
+ if dest.exists():
+ _safe_rmtree(dest)
+ if moved_old and backup.exists():
+ backup.rename(dest)
+ raise
+ finally:
+ if staging.exists():
+ _safe_rmtree(staging)
+ if backup.exists():
+ _safe_rmtree(backup)
+ self._refresh_agent_data_indexes()
+ return self._skill_installation_dto(record)
+
+ async def handle_skills_source_install(self, params: dict) -> dict:
+ """Install one exact Provider artifact through the common transaction."""
+ source_id = str(params.get("source_id") or "").strip()
+ skill_id = str(params.get("skill_id") or "").strip()
+ version_id = str(params.get("version_id") or "").strip()
+ if not source_id or not skill_id or not version_id:
+ return self._source_error(
+ "missing_params", "source_id, skill_id and version_id are required"
+ )
+ force = bool(params.get("force", False))
+ try:
+ descriptor, body, verification = await self._fetch_verified_source_artifact(
+ source_id=source_id,
+ skill_id=skill_id,
+ version_id=version_id,
+ params=params,
+ )
+ with tempfile.TemporaryDirectory(prefix="jiuwenswarm_source_install_") as tmpdir:
+ tmp_path = Path(tmpdir)
+ self._safe_extract_zip_bytes_to_dir(body, tmp_path)
+ skill_dir = self._locate_skill_dir(tmp_path)
+ if skill_dir is None:
+ raise SourceRegistryError(
+ "invalid_package", "downloaded content is missing SKILL.md"
+ )
+ skill_md = self._try_find_skill_file(skill_dir)
+ metadata = self._parse_skill_md(skill_md) if skill_md is not None else None
+ if not isinstance(metadata, dict):
+ raise SourceRegistryError("invalid_package", "SKILL.md cannot be parsed")
+ skill_name = _safe_path_name(
+ str(metadata.get("name") or skill_dir.name), "skill"
+ )
+ version = str(
+ metadata.get("version")
+ or descriptor.metadata.get("version")
+ or version_id
+ ).strip()
+ record = self._commit_source_skill_entity(
+ skill_dir,
+ skill_name=skill_name,
+ source_id=source_id,
+ skill_id=skill_id,
+ version_id=version_id,
+ version=version,
+ force=force,
+ fingerprint=descriptor.fingerprint,
+ verification=verification,
+ )
+ skill_payload: dict[str, Any] = {}
+ for key in (
+ "installation_id", "name", "declared_name", "source_type",
+ "source_id", "skill_id", "version_id", "version", "enabled",
+ "installed", "removable", "consistency",
+ ):
+ value = record.get(key)
+ if value is not None:
+ skill_payload[key] = value
+ return {"success": True, "skill": skill_payload}
+ except SourceRegistryError as exc:
+ return self._source_error(exc.code, str(exc))
+ except ValueError as exc:
+ return self._source_error("invalid_package", str(exc))
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "Skill Source install failed: source_id=%s skill_id=%s version_id=%s error=%s",
+ source_id,
+ skill_id,
+ version_id,
+ exc,
+ )
+ return self._source_error("source_install_failed", str(exc))
+
+ async def handle_skills_update(self, params: dict) -> dict:
+ """Update an installed SkillRef through the same verified install transaction."""
+ source_id = str(params.get("source_id") or "").strip()
+ skill_id = str(params.get("skill_id") or "").strip()
+ target_version_id = str(
+ params.get("target_version_id") or params.get("version_id") or ""
+ ).strip()
+ if not source_id or not skill_id or not target_version_id:
+ return self._source_error(
+ "missing_params",
+ "source_id, skill_id and target_version_id are required",
+ )
+ existing = self._find_installation_by_skill_ref(source_id, skill_id)
+ if existing is None:
+ return self._source_error("skill_not_found", "installed SkillRef was not found")
+ current_version_id = str(existing.get("version_id") or "").strip()
+ expected = str(params.get("expected_current_version_id") or "").strip()
+ if expected and expected != current_version_id:
+ return self._source_error(
+ "skill_version_conflict",
+ f"expected {expected}, current version is {current_version_id}",
+ )
+ if target_version_id == current_version_id:
+ return {"success": True, "skill": self._skill_installation_dto(existing)}
+ install_params = dict(params)
+ install_params.update(
+ {
+ "source_id": source_id,
+ "skill_id": skill_id,
+ "version_id": target_version_id,
+ "force": True,
+ }
+ )
+ return await self.handle_skills_source_install(install_params)
+
+ async def handle_skills_updates_check(self, params: dict) -> dict:
+ """Check configured Providers and cache only non-sensitive update status."""
+ raw_source_ids = params.get("source_ids")
+ if raw_source_ids is not None and not isinstance(raw_source_ids, list):
+ return self._source_error("invalid_params", "source_ids must be an array")
+ requested_sources = {
+ str(value).strip()
+ for value in (raw_source_ids or [])
+ if str(value or "").strip()
+ }
+ legacy_source_id = str(params.get("source_id") or "").strip()
+ if legacy_source_id:
+ requested_sources.add(legacy_source_id)
+ grouped: dict[str, list[dict[str, Any]]] = {}
+ for record in self._get_installed_plugins():
+ if not isinstance(record, dict):
+ continue
+ source_id = str(record.get("source_id") or "").strip()
+ skill_id = str(record.get("skill_id") or "").strip()
+ version_id = str(record.get("version_id") or "").strip()
+ if not source_id or not skill_id or not version_id:
+ continue
+ if requested_sources and source_id not in requested_sources:
+ continue
+ grouped.setdefault(source_id, []).append(record)
+
+ items: list[dict[str, Any]] = []
+ checked_at = datetime.now(timezone.utc).isoformat()
+ for source_id, records in grouped.items():
+ try:
+ provider = await self._source_registry.get(source_id, "check_updates")
+ installed = tuple(
+ InstalledArtifact(
+ source_id=source_id,
+ skill_id=str(record.get("skill_id")),
+ version_id=str(record.get("version_id")),
+ version=str(record.get("version") or "") or None,
+ fingerprint=str(record.get("fingerprint") or "") or None,
+ )
+ for record in records
+ )
+ statuses = await provider.check_updates(
+ installed,
+ self._source_context(params),
+ )
+ by_ref = {
+ (status.skill_ref.source_id, status.skill_ref.skill_id): status
+ for status in statuses
+ }
+ for record in records:
+ identity = (source_id, str(record.get("skill_id")))
+ status = by_ref.get(identity)
+ if status is None:
+ raise SourceRegistryError(
+ "source_response_invalid",
+ "provider omitted an installed SkillRef",
+ )
+ public_status = {
+ "installation_id": record.get("installation_id"),
+ "name": record.get("name"),
+ "source_id": source_id,
+ "skill_id": status.skill_ref.skill_id,
+ "current_version_id": status.current_version_id,
+ "current_version": record.get("version"),
+ "latest_version_id": status.latest_version_id,
+ "latest_version": status.latest_version,
+ "has_update": bool(status.has_update),
+ "fingerprint_matched": status.fingerprint_matched,
+ "accessible": status.accessible,
+ "downloadable": status.downloadable,
+ "remote_status": status.remote_status,
+ "error_code": status.error_code,
+ "checked_at": checked_at,
+ }
+ items.append(
+ {key: value for key, value in public_status.items() if value is not None}
+ )
+ record.update(
+ {
+ "updatable": bool(status.has_update),
+ "latest_version_id": status.latest_version_id,
+ "latest_version": status.latest_version,
+ "fingerprint_matched": status.fingerprint_matched,
+ "accessible": status.accessible,
+ "downloadable": status.downloadable,
+ "remote_status": status.remote_status,
+ "update_checked_at": checked_at,
+ }
+ )
+ except Exception as exc: # noqa: BLE001
+ code = exc.code if isinstance(exc, SourceRegistryError) else "update_check_failed"
+ logger.warning("Skill update check failed: source_id=%s error=%s", source_id, exc)
+ for record in records:
+ items.append(
+ {
+ "installation_id": record.get("installation_id"),
+ "name": record.get("name"),
+ "source_id": source_id,
+ "skill_id": record.get("skill_id"),
+ "current_version_id": record.get("version_id"),
+ "has_update": False,
+ "remote_status": "unknown",
+ "error_code": code,
+ "checked_at": checked_at,
+ }
+ )
+ if grouped:
+ self._save_state()
+ return {"success": True, "items": items, "count": len(items)}
+
async def handle_skills_team_skills_hub_info(self, params: dict) -> dict:
"""查询 Team Skills Hub 技能版本详情(/api/v1/artifacts/{asset_id})。"""
asset_id = str(params.get("asset_id", "")).strip()
@@ -2749,7 +3500,7 @@ class SkillManager:
return body
def _install_web_skill_dir(self, skill_dir: Path, *, skill_name: str) -> dict[str, Any]:
- """Copy an enterprise web installation into the workspace skills dir."""
+ """企业 Web 安装专用:先完成实体落盘,再由调用方提交 workspace 状态。"""
name = str(skill_name or "").strip()
if not name:
return {"success": False, "detail": "skill name is required"}
@@ -2783,7 +3534,7 @@ class SkillManager:
_safe_rmtree(dest)
async def handle_skills_web_install(self, params: dict) -> dict:
- """Install an enterprise user skill and persist it in workspace state."""
+ """企业 Web 安装兼容入口:下载、校验、落盘并提交 workspace JSON。"""
from jiuwenswarm.agents.harness.common.installed_skill import (
verify_skill_download_hmac,
)
@@ -2924,7 +3675,7 @@ class SkillManager:
return {"success": True, "skill": {"name": skill_name, "version": skill_version}}
async def handle_skills_web_uninstall(self, params: dict) -> dict:
- """Remove only user-managed enterprise skills from workspace state."""
+ """企业 Web 卸载兼容入口:仅允许删除 workspace 中的 user 安装。"""
name = str(params.get("name") or "").strip()
if not name:
@@ -4099,8 +4850,31 @@ class SkillManager:
path = (parsed.path or "").lower()
return "/tree/" in path or "/blob/" in path
- def _assert_skill_download_url_allowed(self, download_url: str) -> None:
+ def _assert_skill_download_url_allowed(
+ self,
+ download_url: str,
+ *,
+ allowed_hosts: tuple[str, ...] | None = None,
+ ) -> None:
"""SkillHub / 远程归档下载主机白名单(import_local 与 Team Skills Hub 并集)。"""
+ if allowed_hosts:
+ parsed = urlparse(str(download_url or "").strip())
+ host = (parsed.hostname or "").strip().lower()
+ if parsed.scheme != "https":
+ raise RuntimeError("skill 下载 URL 必须使用 HTTPS")
+ if not host:
+ raise RuntimeError("skill 下载 URL 缺少主机名")
+ if parsed.username or parsed.password:
+ raise RuntimeError("skill 下载 URL 不能包含用户信息")
+ if not any(
+ SkillManager._team_skills_hub_host_matches_rule(host, rule)
+ for rule in allowed_hosts
+ ):
+ raise RuntimeError(
+ f"skill 下载 URL 主机不在来源白名单: {host}"
+ ",请在来源 download_policy.allowed_hosts 中配置该主机"
+ )
+ return
errors: list[str] = []
for checker in (
self._assert_import_local_download_url_allowed,
@@ -4115,6 +4889,7 @@ class SkillManager:
raise RuntimeError(
f"skill 下载 URL 主机不在白名单: {host}"
+ (f" ({errors[0]})" if errors else "")
+ + ",请在来源 download_policy.allowed_hosts 中配置该主机"
)
def _download_http_archive_bytes_sync(self, download_url: str) -> bytes:
@@ -4338,15 +5113,23 @@ class SkillManager:
*,
checksum_sha256: str = "",
timeout: float | None = None,
+ max_bytes: int | None = None,
) -> bytes:
+ parsed = urlparse(str(download_url or "").strip())
+ if parsed.scheme != "https" or not parsed.hostname:
+ raise RuntimeError("skill 下载 URL 必须是 HTTPS 地址")
timeout = max(30.0, timeout or _TEAM_SKILLS_HUB_MARKET_TIMEOUT)
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 max_bytes is not None and len(body) > max_bytes:
+ raise RuntimeError("下载内容超过来源允许的最大大小")
if len(body) < 4 or not body.startswith(b"PK"):
raise RuntimeError("下载内容不是 ZIP 文件")
diff --git a/jiuwenswarm/server/runtime/skill/source_registry.py b/jiuwenswarm/server/runtime/skill/source_registry.py
new file mode 100644
index 0000000000..c8048d8cc5
--- /dev/null
+++ b/jiuwenswarm/server/runtime/skill/source_registry.py
@@ -0,0 +1,139 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.
+
+"""In-process registry for configured Skill Source providers."""
+
+from __future__ import annotations
+
+import asyncio
+import re
+from dataclasses import dataclass
+
+from jiuwenswarm.extensions.sdk.skill_source import (
+ SourceConfig,
+ SourceDescriptor,
+ SkillSourceExtension,
+ SkillSourceProvider,
+)
+
+_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
+
+
+class SourceRegistryError(RuntimeError):
+ def __init__(self, code: str, message: str):
+ super().__init__(message)
+ self.code = code
+
+
+@dataclass
+class _ProviderEntry:
+ config: SourceConfig
+ provider: SkillSourceProvider
+ display_name: str
+ started: bool = False
+ start_lock: asyncio.Lock | None = None
+
+
+class SourceRegistry:
+ """Keeps runtime provider instances only; it never stores workspace state."""
+
+ def __init__(self) -> None:
+ self._entries: dict[str, _ProviderEntry] = {}
+
+ def register(
+ self,
+ config: SourceConfig,
+ provider: SkillSourceProvider,
+ *,
+ display_name: str | None = None,
+ ) -> None:
+ source_id = str(config.source_id or "").strip()
+ provider_type = str(config.provider_type or "").strip()
+ if not _ID_RE.fullmatch(source_id):
+ raise SourceRegistryError("source_misconfigured", f"invalid source_id: {source_id}")
+ if not _ID_RE.fullmatch(provider_type):
+ raise SourceRegistryError("source_misconfigured", f"invalid provider_type: {provider_type}")
+ if source_id in self._entries:
+ raise SourceRegistryError("source_misconfigured", f"duplicate source_id: {source_id}")
+ if str(provider.source_id or "").strip() != source_id:
+ raise SourceRegistryError("source_misconfigured", "provider source_id does not match config")
+ declared = frozenset(provider.capabilities)
+ configured = frozenset(config.capabilities)
+ if configured and not configured.issubset(declared):
+ raise SourceRegistryError(
+ "source_misconfigured",
+ f"provider {provider_type} does not implement {sorted(configured - declared)}",
+ )
+ self._entries[source_id] = _ProviderEntry(
+ config=config,
+ provider=provider,
+ display_name=(display_name or provider.display_name or source_id).strip(),
+ )
+
+ def bind_extension(
+ self,
+ config: SourceConfig,
+ extension: SkillSourceExtension,
+ *,
+ display_name: str | None = None,
+ ) -> SkillSourceProvider:
+ """Create and bind a configured Provider through an extension factory."""
+ if str(extension.provider_type or "").strip() != config.provider_type:
+ raise SourceRegistryError(
+ "source_misconfigured", "extension provider_type does not match config"
+ )
+ provider = extension.create_provider(config)
+ self.register(config, provider, display_name=display_name)
+ return provider
+
+ def list(self) -> list[SourceDescriptor]:
+ descriptors = [
+ SourceDescriptor(
+ source_id=entry.config.source_id,
+ provider_type=entry.config.provider_type,
+ display_name=entry.display_name,
+ enabled=entry.config.enabled,
+ priority=entry.config.priority,
+ capabilities=frozenset(entry.config.capabilities or entry.provider.capabilities),
+ )
+ for entry in self._entries.values()
+ ]
+ return sorted(descriptors, key=lambda item: (-item.priority, item.source_id))
+
+ def get_config(self, source_id: str) -> SourceConfig:
+ """Return the trusted runtime configuration for one source."""
+ entry = self._entries.get(str(source_id or "").strip())
+ if entry is None:
+ raise SourceRegistryError("source_not_found", f"skill source not found: {source_id}")
+ return entry.config
+
+ async def get(self, source_id: str, capability: str) -> SkillSourceProvider:
+ entry = self._entries.get(str(source_id or "").strip())
+ if entry is None:
+ raise SourceRegistryError("source_not_found", f"skill source not found: {source_id}")
+ if not entry.config.enabled:
+ raise SourceRegistryError("source_disabled", f"skill source is disabled: {source_id}")
+ capabilities = frozenset(entry.config.capabilities or entry.provider.capabilities)
+ if capability not in capabilities:
+ raise SourceRegistryError(
+ "source_capability_unsupported",
+ f"skill source {source_id} does not support {capability}",
+ )
+ if not entry.started:
+ if entry.start_lock is None:
+ entry.start_lock = asyncio.Lock()
+ async with entry.start_lock:
+ if not entry.started:
+ try:
+ await entry.provider.start()
+ except Exception as exc:
+ raise SourceRegistryError(
+ "source_unavailable", f"skill source {source_id} failed to start: {exc}"
+ ) from exc
+ entry.started = True
+ return entry.provider
+
+ async def close(self) -> None:
+ for entry in self._entries.values():
+ if entry.started:
+ await entry.provider.close()
+ entry.started = False
diff --git a/jiuwenswarm/server/runtime/skill/sources/__init__.py b/jiuwenswarm/server/runtime/skill/sources/__init__.py
new file mode 100644
index 0000000000..2254889777
--- /dev/null
+++ b/jiuwenswarm/server/runtime/skill/sources/__init__.py
@@ -0,0 +1,8 @@
+"""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/jiuwenswarm/server/runtime/skill/sources/swarm_skill_hub.py b/jiuwenswarm/server/runtime/skill/sources/swarm_skill_hub.py
new file mode 100644
index 0000000000..5ccf51bf67
--- /dev/null
+++ b/jiuwenswarm/server/runtime/skill/sources/swarm_skill_hub.py
@@ -0,0 +1,308 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.
+
+"""SwarmSkillHub protocol adapter for the common Skill Source SPI."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from typing import Any, Mapping
+
+import httpx
+
+from jiuwenswarm.extensions.sdk.skill_source import (
+ ArtifactDescriptor,
+ ArtifactRef,
+ InstalledArtifact,
+ ProviderInvocationContext,
+ SkillCandidate,
+ SkillRef,
+ SkillSearchRequest,
+ SkillSearchResult,
+ SkillSourceProvider,
+ SkillUpdateStatus,
+)
+
+SWARM_SKILL_HUB_SOURCE_ID = "swarmskillhub"
+
+
+def _text(value: Any) -> str:
+ return str(value or "").strip()
+
+
+def _int_or_none(value: Any) -> int | None:
+ try:
+ return int(value) if value is not None and str(value).strip() else None
+ except (TypeError, ValueError):
+ return None
+
+
+def _float_or_none(value: Any) -> float | None:
+ try:
+ return float(value) if value is not None and str(value).strip() else None
+ except (TypeError, ValueError):
+ return None
+
+
+def _bool_value(value: Any, default: bool = False) -> bool:
+ if value is None:
+ return default
+ if isinstance(value, bool):
+ return value
+ return _text(value).lower() in {"1", "true", "yes", "on"}
+
+
+def _timestamp(value: Any) -> datetime | str | int | None:
+ if value is None or value == "":
+ return None
+ if isinstance(value, (int, float)):
+ number = float(value)
+ if number > 10_000_000_000:
+ number /= 1000
+ try:
+ return datetime.fromtimestamp(number, tz=timezone.utc)
+ except (OverflowError, OSError, ValueError):
+ return int(value)
+ return _text(value)
+
+
+class SwarmSkillHubProvider(SkillSourceProvider):
+ """Maps `/api/v1/plugins` and `/api/v1/artifacts` to the v2 SPI."""
+
+ source_id = SWARM_SKILL_HUB_SOURCE_ID
+ provider_type = "swarmskillhub"
+ display_name = "SwarmSkillHub"
+ capabilities = frozenset({"search", "check_updates", "get_artifact"})
+
+ def __init__(
+ self,
+ base_url: str,
+ *,
+ source_id: str = SWARM_SKILL_HUB_SOURCE_ID,
+ display_name: str = "SwarmSkillHub",
+ timeout: float = 60.0,
+ ) -> None:
+ self.source_id = _text(source_id)
+ self.display_name = _text(display_name) or self.source_id
+ self._base_url = str(base_url or "").strip().rstrip("/")
+ if not self._base_url:
+ raise ValueError("SwarmSkillHub base_url is required")
+ self._timeout = timeout
+ self._client: httpx.AsyncClient | None = None
+
+ async def start(self) -> None:
+ if self._client is None:
+ self._client = httpx.AsyncClient(timeout=self._timeout, follow_redirects=False)
+
+ async def close(self) -> None:
+ client, self._client = self._client, None
+ if client is not None:
+ await client.aclose()
+
+ async def _get_data(self, path: str, params: Mapping[str, Any] | None = None) -> dict[str, Any]:
+ if self._client is None:
+ await self.start()
+ client = self._client
+ if client is None:
+ raise RuntimeError("SwarmSkillHub 客户端未初始化")
+ try:
+ response = await client.get(f"{self._base_url}{path}", params=params)
+ except Exception as exc:
+ raise RuntimeError(f"无法连接 SwarmSkillHub: {exc}") from exc
+ if not response.is_success:
+ detail = (response.text or "").strip()[:300]
+ raise RuntimeError(f"SwarmSkillHub API 错误 HTTP {response.status_code}: {detail}")
+ try:
+ payload = response.json()
+ except Exception as exc:
+ raise RuntimeError(f"SwarmSkillHub API 响应不是合法 JSON: {exc}") from exc
+ if not isinstance(payload, dict):
+ raise RuntimeError("SwarmSkillHub API 响应格式错误")
+ try:
+ code = int(payload.get("code", 200))
+ except (TypeError, ValueError) as exc:
+ raise RuntimeError("SwarmSkillHub API code 格式错误") from exc
+ if code != 200:
+ raise RuntimeError(_text(payload.get("message")) or "SwarmSkillHub API 返回失败")
+ data = payload.get("data")
+ if not isinstance(data, dict):
+ raise RuntimeError("SwarmSkillHub API data 格式错误")
+ return data
+
+ async def search(
+ self,
+ request: SkillSearchRequest,
+ context: ProviderInvocationContext,
+ ) -> SkillSearchResult:
+ del context
+ filters = dict(request.filters)
+ query: dict[str, Any] = {
+ "page": request.page,
+ "page_size": request.page_size,
+ "order_by": _text(filters.get("order_by")) or "install_count",
+ "desc": str(_bool_value(filters.get("desc"), True)).lower(),
+ }
+ if request.q:
+ query["search_keyword"] = request.q
+ for public_name, remote_name in (
+ ("skill_type", "plugin_type"),
+ ("author", "publisher_name"),
+ ("asset_id", "asset_id"),
+ ("asset_type", "asset_type"),
+ ("publisher_id", "publisher_id"),
+ ):
+ value = _text(filters.get(public_name))
+ if value:
+ query[remote_name] = value
+
+ data = await self._get_data("/api/v1/plugins", query)
+ raw_items = data.get("items")
+ if not isinstance(raw_items, list):
+ raise RuntimeError("SwarmSkillHub items 格式错误")
+ items: list[SkillCandidate] = []
+ for raw in raw_items:
+ if not isinstance(raw, dict):
+ raise RuntimeError("SwarmSkillHub item 格式错误")
+ skill_id = _text(raw.get("asset_id") or raw.get("skill_id") or raw.get("id"))
+ name = _text(raw.get("name")) or skill_id
+ version_id = _text(raw.get("latest_version_id") or raw.get("version_id") or raw.get("latest_version"))
+ if not skill_id or not version_id or not name:
+ raise RuntimeError("SwarmSkillHub item 缺少 asset_id/latest_version/name")
+ tags = raw.get("labels", raw.get("tags", []))
+ labels: tuple[Mapping[str, Any], ...] = tuple(
+ item if isinstance(item, dict) else {"name": _text(item)}
+ for item in (tags if isinstance(tags, list) else [])
+ if isinstance(item, dict) or _text(item)
+ )
+ versions = raw.get("versions", [])
+ items.append(
+ SkillCandidate(
+ source_id=self.source_id,
+ skill_id=skill_id,
+ version_id=version_id,
+ name=name,
+ display_name=_text(raw.get("display_name")) or name,
+ summary=_text(raw.get("short_desc") or raw.get("summary") or raw.get("description")) or None,
+ version=_text(raw.get("latest_version") or raw.get("version")) or None,
+ fingerprint=_text(raw.get("fingerprint")) or None,
+ namespace=_text(raw.get("namespace") or raw.get("space_name")) or None,
+ slug=_text(raw.get("slug")) or None,
+ canonical_slug=_text(raw.get("canonical_slug")) or None,
+ owner_display_name=_text(raw.get("publisher_name") or raw.get("author")) or None,
+ labels=labels,
+ homepage=_text(raw.get("homepage") or raw.get("detail_url")) or None,
+ rating_avg=_float_or_none(raw.get("rating_avg", raw.get("rating"))),
+ rating_count=_int_or_none(raw.get("rating_count")),
+ download_count=_int_or_none(raw.get("download_count", raw.get("install_count"))),
+ updated_at=_timestamp(raw.get("updated_at", raw.get("update_time"))),
+ versions=tuple(v for v in versions if isinstance(v, dict)) if isinstance(versions, list) else (),
+ previous_version=_text(raw.get("previous_version")) or None,
+ accessible=_bool_value(raw["accessible"]) if "accessible" in raw else None,
+ downloadable=_bool_value(raw.get("downloadable"), True),
+ metadata={"asset_type": raw.get("asset_type")} if raw.get("asset_type") is not None else {},
+ )
+ )
+ total = _int_or_none(data.get("total", data.get("total_count")))
+ next_page = request.page + 1 if total is not None and request.page * request.page_size < total else None
+ return SkillSearchResult(items=tuple(items), total=total, next_page=next_page)
+
+ async def check_updates(
+ self,
+ installed: list[InstalledArtifact] | tuple[InstalledArtifact, ...],
+ context: ProviderInvocationContext,
+ ) -> tuple[SkillUpdateStatus, ...]:
+ statuses: list[SkillUpdateStatus] = []
+ for current in installed:
+ if current.source_id != self.source_id:
+ raise RuntimeError("InstalledArtifact source_id 与 Provider 不一致")
+ result = await self.search(
+ SkillSearchRequest(
+ page=1,
+ page_size=2,
+ filters={"asset_id": current.skill_id},
+ ),
+ context,
+ )
+ candidate = next(
+ (item for item in result.items if item.skill_id == current.skill_id),
+ None,
+ )
+ if candidate is None:
+ statuses.append(
+ SkillUpdateStatus(
+ skill_ref=SkillRef(self.source_id, current.skill_id),
+ current_version_id=current.version_id,
+ latest_version_id=None,
+ has_update=False,
+ accessible=False,
+ downloadable=False,
+ remote_status="removed",
+ )
+ )
+ continue
+ accessible = candidate.accessible
+ downloadable = candidate.downloadable
+ remote_status = "available"
+ if accessible is False:
+ remote_status = "no_access"
+ fingerprint_matched = None
+ if current.fingerprint and candidate.fingerprint:
+ fingerprint_matched = current.fingerprint == candidate.fingerprint
+ statuses.append(
+ SkillUpdateStatus(
+ skill_ref=SkillRef(self.source_id, current.skill_id),
+ current_version_id=current.version_id,
+ latest_version_id=candidate.version_id,
+ has_update=(
+ remote_status == "available"
+ and candidate.version_id != current.version_id
+ and fingerprint_matched is not True
+ ),
+ latest_version=candidate.version,
+ fingerprint_matched=fingerprint_matched,
+ accessible=accessible,
+ downloadable=downloadable,
+ remote_status=remote_status,
+ )
+ )
+ return tuple(statuses)
+
+ async def get_artifact(
+ self,
+ skill_ref: SkillRef,
+ version_id: str,
+ context: ProviderInvocationContext,
+ ) -> ArtifactDescriptor:
+ del context
+ if skill_ref.source_id != self.source_id:
+ raise RuntimeError("SkillRef source_id 与 Provider 不一致")
+ data = await self._get_data(
+ f"/api/v1/artifacts/{skill_ref.skill_id}",
+ {"version": version_id},
+ )
+ download_url = _text(data.get("download_url"))
+ if not download_url:
+ raise RuntimeError("SwarmSkillHub 未返回 download_url")
+ return ArtifactDescriptor(
+ artifact_ref=ArtifactRef(skill_ref=skill_ref, version_id=version_id),
+ download_url=download_url,
+ checksum_sha256=_text(data.get("checksum_sha256")) or None,
+ artifact_sha256=_text(data.get("artifact_sha256")) or None,
+ signature=_text(data.get("signature")) or None,
+ signature_algorithm=_text(
+ data.get("signature_algorithm") or data.get("signatureAlgorithm")
+ ) or None,
+ signature_encoding=_text(
+ data.get("signature_encoding") or data.get("signatureEncoding")
+ ) or None,
+ signature_scope=_text(
+ data.get("signature_scope") or data.get("signatureScope")
+ ) or None,
+ key_id=_text(data.get("key_id") or data.get("keyId")) or None,
+ fingerprint=_text(data.get("fingerprint")) or None,
+ content_length=_int_or_none(data.get("content_length")),
+ metadata={
+ key: data[key]
+ for key in ("display_name", "short_desc", "version")
+ if key in data and data[key] is not None
+ },
+ )
diff --git a/tests/unit_tests/gateway/test_agent_rest_map.py b/tests/unit_tests/gateway/test_agent_rest_map.py
deleted file mode 100644
index a20a8049fa..0000000000
--- a/tests/unit_tests/gateway/test_agent_rest_map.py
+++ /dev/null
@@ -1,390 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-
-"""Gateway → Agent HTTP:method 查表、填路径、body/query、身份头、表外 RPC。"""
-
-from __future__ import annotations
-
-import json
-from urllib.parse import quote, urlparse
-
-import pytest
-
-from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields
-from jiuwenswarm.common.schema.message import ReqMethod
-from jiuwenswarm.gateway.routing.agent_rest_map import (
- API_PREFIX,
- REST_ROUTES,
- RestAssemblyError,
- _METHODS_WITHOUT_PARAM_SESSION_ID,
- _PATH_PLACEHOLDER,
- assemble_rest_request,
- normalize_agent_http_base,
-)
-
-BASE = "http://127.0.0.1:8766"
-
-PATH_SAMPLES: dict[str, str] = {
- "session_id": "sess_1",
- "name": "agent_a",
- "team_name": "team_a",
- "task_id": "task_1",
- "issue_id": "issue_1",
- "rule_id": "rule_1",
- "override_id": "ovr_1",
-}
-
-# 本仓 ReqMethod 有、REST 表没有:只允许走 POST /rpc/{method},禁止猜路径。
-_RPC_ALLOWLIST = frozenset(
- {
- "chat.swarmflow_reply",
- "ssh.relay",
- "config.get",
- "config.set",
- "channel.get",
- "team.session.reset",
- "team.runtime.dissolve",
- "path.get",
- "path.set",
- "logging.set",
- "memory.compute",
- "tts.synthesize",
- "3rdagent.switch",
- "3rdagent.list",
- "skills.enterprise.list",
- # 下面全仓无任何实现(只有ReqMethod枚举),与logging.set同类遗留
- "files.list",
- "files.get",
- "harness.packages.import",
- "harness.packages.export",
- }
-)
-
-_SPECIAL_METHODS = frozenset({"chat.send", "chat.resume"})
-
-
-def _env(
- method: str | ReqMethod,
- *,
- params: dict | None = None,
- session_id: str | None = "sess_1",
- is_stream: bool = False,
- user_id: str | None = "u1",
- request_id: str = "r1",
- channel_id: str = "web",
-):
- return e2a_from_agent_fields(
- request_id=request_id,
- channel_id=channel_id,
- session_id=session_id,
- req_method=method,
- params=params,
- is_stream=is_stream,
- user_id=user_id,
- )
-
-
-def _params_for(path: str) -> dict:
- params = {key: PATH_SAMPLES[key] for key in _PATH_PLACEHOLDER.findall(path)}
- params["limit"] = 3
- return params
-
-
- ("method", "verb", "path"),
- [(method, verb, path) for method, (verb, path) in REST_ROUTES.items()],
- ids=list(REST_ROUTES),
-)
-def test_every_rest_route_assembles(method: str, verb: str, path: str):
- assembled = assemble_rest_request(
- _env(method, params=_params_for(path)),
- base_url=BASE,
- )
- assert assembled.used_rpc_fallback is False
- assert assembled.verb == verb
- expected = f"{BASE}{API_PREFIX}" + path.format(
- **{k: quote(v, safe="") for k, v in PATH_SAMPLES.items() if f"{{{k}}}" in path}
- )
- assert assembled.url == expected
- used = set(_PATH_PLACEHOLDER.findall(path))
- remaining: dict = {"limit": 3}
- if "session_id" not in used and method not in _METHODS_WITHOUT_PARAM_SESSION_ID:
- remaining["session_id"] = "sess_1"
- if verb == "GET":
- assert assembled.json_body is None
- assert assembled.query == {k: str(v) for k, v in remaining.items()}
- assert assembled.headers["Accept"] == "application/json"
- assert "Content-Type" not in assembled.headers
- else:
- assert assembled.query is None
- assert assembled.json_body == remaining
- assert assembled.headers["Content-Type"] == "application/json"
- for key in used:
- assert key not in assembled.json_body
- assert assembled.headers["X-Request-Id"] == "r1"
- assert assembled.headers["X-Channel-Id"] == "web"
- assert assembled.headers["X-Session-Id"] == "sess_1"
- assert assembled.headers["X-User-Id"] == "u1"
- if assembled.json_body is not None:
- assert "method" not in assembled.json_body
- assert "request_id" not in assembled.json_body
- assert "channel" not in assembled.json_body
-
-
[email protected]("req_method", list(ReqMethod), ids=lambda m: m.value)
-def test_every_reqmethod_is_rest_or_documented_rpc(req_method: ReqMethod):
- method = req_method.value
- placeholders = REST_ROUTES.get(method, ("POST", ""))[1]
- assembled = assemble_rest_request(
- _env(method, params=_params_for(placeholders) if placeholders else dict(PATH_SAMPLES)),
- base_url=BASE,
- )
- if method in REST_ROUTES or method in _SPECIAL_METHODS:
- assert assembled.used_rpc_fallback is False, method
- return
- assert method in _RPC_ALLOWLIST, f"新增 method {method}:补 REST 表或写入 _RPC_ALLOWLIST"
- assert assembled.used_rpc_fallback is True
- assert assembled.verb == "POST"
- assert assembled.url.endswith(f"/rpc/{method}")
-
-
-def test_chat_send_and_resume_ignore_stream_flag_for_path():
- send_stream = assemble_rest_request(
- _env(ReqMethod.CHAT_SEND, params={"query": "hi"}, is_stream=True),
- base_url=BASE,
- )
- send_unary = assemble_rest_request(
- _env(ReqMethod.CHAT_SEND, params={"query": "hi"}, is_stream=False),
- base_url=BASE,
- )
- resume = assemble_rest_request(
- _env(ReqMethod.CHAT_RESUME, params={"query": "hi"}, is_stream=True),
- base_url=BASE,
- )
- assert send_stream.url.endswith("/chat/completions")
- assert send_unary.url.endswith("/chat/completions")
- assert send_stream.headers["Accept"] == "text/event-stream"
- assert send_unary.headers["Accept"] == "application/json"
- assert resume.url.endswith("/chat/resume")
- assert send_stream.used_rpc_fallback is False
-
-
-def test_history_get_stream_switches_path_unary_keeps_history():
- stream = assemble_rest_request(
- _env(ReqMethod.HISTORY_GET, params={"limit": 20}, is_stream=True),
- base_url=BASE,
- )
- unary = assemble_rest_request(
- _env(ReqMethod.HISTORY_GET, params={"limit": 20}, is_stream=False),
- base_url=BASE,
- )
- assert stream.verb == "GET"
- assert stream.url.endswith("/sessions/sess_1/history/stream")
- assert stream.query == {"limit": "20"}
- assert stream.json_body is None
- assert unary.url.endswith("/sessions/sess_1/history")
- assert "/stream" not in unary.url
-
-
- ("alias", "canonical"),
- [
- ("agents.tools_list", "agents.tools.list"),
- ("agent.prewarm_sync", "agent.prewarm.sync"),
- ("issue.state_list", "issue.state.list"),
- ("skills.online.search", "skills.online_search.search"),
- ],
-)
-def test_method_aliases_share_path(alias: str, canonical: str):
- params = _params_for(REST_ROUTES[canonical][1])
- left = assemble_rest_request(_env(alias, params=params), base_url=BASE)
- right = assemble_rest_request(_env(canonical, params=params), base_url=BASE)
- assert left.verb == right.verb
- assert left.url == right.url
- assert left.used_rpc_fallback is False
- assert right.used_rpc_fallback is False
-
-
-def test_skills_static_names_are_not_skills_get():
- clawhub = assemble_rest_request(_env("skills.clawhub.get_token", params={}), base_url=BASE)
- get_named = assemble_rest_request(
- _env("skills.get", params={"name": "clawhub"}),
- base_url=BASE,
- )
- assert clawhub.url.endswith("/skills/clawhub/token")
- assert get_named.url.endswith("/skills/clawhub")
- assert clawhub.url != get_named.url
-
-
-def test_session_id_from_envelope_when_params_omit_it():
- assembled = assemble_rest_request(
- _env(ReqMethod.SESSION_RENAME, params={"title": "n"}, session_id="from-env"),
- base_url=BASE,
- )
- assert assembled.url.endswith("/sessions/from-env")
- assert assembled.json_body == {"title": "n"}
-
-
-def test_params_session_id_wins_over_envelope():
- assembled = assemble_rest_request(
- _env(
- ReqMethod.SESSION_RENAME,
- params={"session_id": "from-params", "title": "n"},
- session_id="from-env",
- ),
- base_url=BASE,
- )
- assert assembled.url.endswith("/sessions/from-params")
-
-
-def test_path_placeholder_is_percent_encoded():
- assembled = assemble_rest_request(
- _env(ReqMethod.SESSION_DELETE, params={}, session_id="sess/a b"),
- base_url=BASE,
- )
- assert assembled.url.endswith("/sessions/sess%2Fa%20b")
-
-
-def test_missing_path_placeholder_raises_and_does_not_emit_half_url():
- with pytest.raises(RestAssemblyError, match="session_id"):
- assemble_rest_request(
- _env(ReqMethod.SESSION_DELETE, params={}, session_id=None),
- base_url=BASE,
- )
-
-
-def test_team_bind_missing_one_of_two_placeholders_raises():
- with pytest.raises(RestAssemblyError, match="team_name"):
- assemble_rest_request(
- _env(
- ReqMethod.TEAM_SESSION_BIND,
- params={"session_id": "s1"},
- session_id="s1",
- ),
- base_url=BASE,
- )
-
-
-def test_empty_method_raises():
- env = e2a_from_agent_fields(
- request_id="r1",
- channel_id="web",
- req_method=None,
- params={},
- )
- with pytest.raises(RestAssemblyError, match="method"):
- assemble_rest_request(env, base_url=BASE)
-
-
-def test_unknown_method_rpc_keeps_dots_and_puts_remaining_in_body():
- assembled = assemble_rest_request(
- _env("file.transfer.start", params={"chunk": 1}, session_id="s1"),
- base_url=BASE,
- )
- assert assembled.used_rpc_fallback is True
- assert assembled.url.endswith("/rpc/file.transfer.start")
- assert assembled.json_body == {"chunk": 1, "session_id": "s1"}
-
-
-def test_get_nested_params_are_json_in_query():
- assembled = assemble_rest_request(
- _env(ReqMethod.SESSION_LIST, params={"filter": {"a": 1}, "tags": ["x"]}, session_id=None),
- base_url=BASE,
- )
- assert assembled.query is not None
- assert json.loads(assembled.query["filter"]) == {"a": 1}
- assert json.loads(assembled.query["tags"]) == ["x"]
-
-
-def test_none_params_are_dropped():
- assembled = assemble_rest_request(
- _env(ReqMethod.SESSION_CREATE, params={"title": "t", "hint": None}),
- base_url=BASE,
- )
- # session.create 不把信封 session_id 写入 body;None 字段仍丢弃。
- assert assembled.json_body == {"title": "t"}
-
-
-def test_identity_headers_omit_optional_ids():
- assembled = assemble_rest_request(
- _env(ReqMethod.SESSION_LIST, params={}, session_id=None, user_id=None, channel_id=""),
- base_url=BASE,
- )
- assert assembled.headers["X-Channel-Id"] == "web"
- assert "X-Session-Id" not in assembled.headers
- assert "X-User-Id" not in assembled.headers
- assert "X-Bot-Id" not in assembled.headers
- assert "X-Group-Id" not in assembled.headers
- assert "X-Gateway-Id" not in assembled.headers
- assert "X-Service-Id" not in assembled.headers
- assert "X-Agent-Id" not in assembled.headers
- assert "X-Workspace-Key" not in assembled.headers
-
-
-def test_identity_headers_carry_routing_from_channel_context():
- """REST body 不含 E2A;routing 必须经 X-* 头传到 Agent。"""
- env = _env(
- ReqMethod.COMMAND_GOAL,
- params={"session_id": "sess_1", "action": "get", "mode": "agent"},
- user_id="user1",
- )
- env.channel_context = {
- "user_id": "user1",
- "routing": {
- "group_id": "__none__",
- "bot_id": "d64efe50-3b44-4895-b040-df922e1df242",
- "gateway_id": "4e3a795a-2339-4efd-895f-bc796943f57c",
- },
- "method": "command.goal",
- }
- assembled = assemble_rest_request(env, base_url=BASE)
- assert assembled.url.endswith("/sessions/sess_1/commands/goal")
- assert assembled.json_body == {
- "action": "get",
- "mode": "agent",
- }
- assert assembled.headers["X-User-Id"] == "user1"
- assert assembled.headers["X-Group-Id"] == "__none__"
- assert assembled.headers["X-Bot-Id"] == "d64efe50-3b44-4895-b040-df922e1df242"
- assert assembled.headers["X-Gateway-Id"] == "4e3a795a-2339-4efd-895f-bc796943f57c"
-
-
-def test_identity_headers_carry_tenant_ids():
- """企业租户顶层字段经 X-Service/Agent/Workspace-Key 透传,不进 REST body。"""
- env = _env(
- ReqMethod.CHAT_SEND,
- params={"session_id": "sess_1", "query": "hi"},
- user_id="user1",
- )
- env.service_id = "svc-hash"
- env.agent_id = "ag-hash"
- env.workspace_key = "wk-hash"
- assembled = assemble_rest_request(env, base_url=BASE)
- assert assembled.json_body == {"session_id": "sess_1", "query": "hi"}
- assert assembled.headers["X-Service-Id"] == "svc-hash"
- assert assembled.headers["X-Agent-Id"] == "ag-hash"
- assert assembled.headers["X-Workspace-Key"] == "wk-hash"
-
-
-def test_normalize_base_empty_raises():
- with pytest.raises(RestAssemblyError, match="空"):
- normalize_agent_http_base(" ")
-
-
- ("raw", "expected"),
- [
- ("http://h:8766", "http://h:8766/api/v1"),
- ("http://h:8766/", "http://h:8766/api/v1"),
- ("http://h:8766/api/v1", "http://h:8766/api/v1"),
- ("http://h:8766/api/v1/", "http://h:8766/api/v1"),
- ("https://h:443/api/v1", "https://h:443/api/v1"),
- ],
-)
-def test_normalize_agent_http_base(raw: str, expected: str):
- assert normalize_agent_http_base(raw) == expected
-
-
-def test_assembled_url_keeps_api_prefix_segment():
- assembled = assemble_rest_request(_env(ReqMethod.SESSION_LIST, params={}), base_url=BASE)
- parsed = urlparse(assembled.url)
- assert parsed.path.startswith("/api/v1/")