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(a2a): add enterprise outbound auth, reverse RPC, and ingress gate
NickFuryXXX9882a05053d4
diff --git a/jiuwenswarm/agents/harness/common/rails/a2a_outbound_toolkit_rail.py b/jiuwenswarm/agents/harness/common/rails/a2a_outbound_toolkit_rail.pyindex 1369f9e9d4..b45e48b721 100644--- a/jiuwenswarm/agents/harness/common/rails/a2a_outbound_toolkit_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/a2a_outbound_toolkit_rail.py@@ -27,10 +27,12 @@ class A2AOutboundToolkitRail(DeepAgentRail):*,backend_provider: Callable[[], A2AOutboundToolBackend | None] | None = None,runtime_route: Callable[[], tuple[str, str]] | None = None,+ runtime_resource_id: Callable[[], str] | None = None,) -> None:super().__init__()self._backend_provider = backend_provider or GatewayA2AOutboundToolBackendself._runtime_route = runtime_route+ self._runtime_resource_id = runtime_resource_idself._registered: list[str] = []self._prompt_builder: Any = Noneself._agent: Any = None@@ -50,11 +52,12 @@ class A2AOutboundToolkitRail(DeepAgentRail):ability_manager = getattr(agent, "ability_manager", None)if ability_manager is None:return- toolkit = (- A2AOutboundToolkit(backend, runtime_route=self._runtime_route)- if self._runtime_route is not None- else A2AOutboundToolkit(backend)- )+ toolkit_kwargs: dict[str, Any] = {}+ if self._runtime_route is not None:+ toolkit_kwargs["runtime_route"] = self._runtime_route+ if self._runtime_resource_id is not None:+ toolkit_kwargs["runtime_resource_id"] = self._runtime_resource_id+ toolkit = A2AOutboundToolkit(backend, **toolkit_kwargs)tools = toolkit.get_tools()for tool in tools:ability_manager.add_ability(tool.card, tool)diff --git a/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py b/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.pyindex 09146c761f..2abe354617 100644--- a/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py@@ -105,15 +105,25 @@ def _runtime_route() -> tuple[str, str]:)+def _runtime_resource_id() -> str:+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ get_runtime_tool_resource_id,+ )++ return str(get_runtime_tool_resource_id() or "").strip()++class A2AOutboundToolkit:def __init__(self,backend: A2AOutboundToolBackend,*,runtime_route: Callable[[], tuple[str, str]] = _runtime_route,+ runtime_resource_id: Callable[[], str] = _runtime_resource_id,) -> None:self._backend = backendself._runtime_route = runtime_route+ self._runtime_resource_id = runtime_resource_idasync def find_agents(self,@@ -152,7 +162,7 @@ class A2AOutboundToolkit:return _error(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)return await self._backend.call(method,- params,+ {**params, "resource_id": self._runtime_resource_id()},session_id=session_id,channel_id=channel_id,)diff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.pyindex 0324b1e77d..79d3eea1d6 100644--- a/jiuwenswarm/agents/swarm/providers/member_rails.py+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py@@ -48,7 +48,6 @@ from jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail importfrom jiuwenswarm.agents.harness.common.rails.symphony import (SymphonyOrchestrationRail,)-from jiuwenswarm.edition import is_enterprisefrom jiuwenswarm.agents.harness.team.rails.team_skill_storage_policy_rail import (TeamSkillStoragePolicyRail,)@@ -181,11 +180,12 @@ def _build_a2a_outbound_toolkit_rail(context: SwarmBuildContext,) -> A2AOutboundToolkitRail | None:"""Build the shared A2A rail with a route stable across member tasks."""- if is_enterprise():- return Noneinp = A2AOutboundToolkitInput.resolve(params, context)session_id = str(inp.session_id or "").strip()channel = str(inp.channel or "default").strip() or "default"+ from jiuwenswarm.common.request_identity import web_routing_identity++ resource_id = str(web_routing_identity(context.request_metadata).get("bot_id") or "").strip()def _runtime_route() -> tuple[str, str]:from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (@@ -199,7 +199,19 @@ def _build_a2a_outbound_toolkit_rail(return live_session, live_channel or channelreturn session_id, channel- return A2AOutboundToolkitRail(runtime_route=_runtime_route)+ def _runtime_resource_id() -> str:+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ get_runtime_tool_resource_id,+ get_runtime_tool_session_id,+ )++ if str(get_runtime_tool_session_id() or "").strip():+ return str(get_runtime_tool_resource_id() or "").strip()+ return resource_id++ return A2AOutboundToolkitRail(+ runtime_route=_runtime_route, runtime_resource_id=_runtime_resource_id+ )class DisabledToolsInput(ConstructionInput):diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 1be41d41d7..41b72261ce 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -2341,7 +2341,7 @@ function AppContent() {) : null}{/* Main Content */}- <main className={`content ${activeNav === 'chat' ? 'content--chat' : ''} ${isTeamAreaExpanded ? 'content--team-expanded' : ''}`}>+ <main className={`content ${activeNav === 'chat' ? 'content--chat' : ''} ${activeNav === 'a2aingress' ? 'content--a2a' : ''} ${isTeamAreaExpanded ? 'content--team-expanded' : ''}`}>{configError && (<div className="card mb-4"><div className="text-sm text-text-muted">@@ -2538,7 +2538,7 @@ function AppContent() {</div>)}{activeNav === 'a2aingress' && (- <div className="app-section">+ <div className="app-section min-h-0"><A2AIngressPanel isConnected={isConnected} request={request} /></div>)}diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsxindex cc800f71f1..b512080c9f 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx@@ -488,7 +488,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer{t(enterpriseMode ? 'a2aIngress.outbound.list.enterpriseEmpty' : 'a2aIngress.outbound.list.empty')}</div>) : (- <div className="grid min-h-0 flex-1 content-start gap-3 overflow-auto p-4">+ <div className="grid min-h-0 flex-1 auto-rows-max content-start gap-3 overflow-auto p-4">{agents.map(agent => {const isEditing = editing?.agentId === agent.agent_id;const settingsPanelId = `a2a-agent-settings-${agent.agent_id}`;diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsxindex 8c65fc6cfe..f8e1ddf817 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx@@ -122,7 +122,7 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)const responseGeneration = ++historyResponseGenerationRef.current;if (showLoading) setHistoryLoading(true);try {- const payload = await request('a2a.ingress.history', { limit: 200 });+ const payload = await request('a2a.ingress.history', { limit: 100 });if (!shouldAcceptA2AIngressResponse(responseGeneration, historyResponseGenerationRef.current)) return;const next = normalizeA2AIngressHistory(payload);if (!next) throw new Error(t('a2aIngress.errors.invalidHistoryResponse'));@@ -144,7 +144,7 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)const responseGeneration = ++outboundHistoryResponseGenerationRef.current;if (showLoading) setOutboundHistoryLoading(true);try {- const payload = await request('a2a.outbound.dispatch.list', { limit: 200 });+ const payload = await request('a2a.outbound.dispatch.list', { limit: 100 });if (!shouldAcceptA2AIngressResponse(responseGeneration, outboundHistoryResponseGenerationRef.current)) return;const next = normalizeA2AOutboundDispatchHistory(payload);if (!next) throw new Error(t('a2aIngress.errors.invalidHistoryResponse'));diff --git a/jiuwenswarm/channels/web/frontend/src/index.css b/jiuwenswarm/channels/web/frontend/src/index.cssindex 1397234e97..ed70ed55a1 100644--- a/jiuwenswarm/channels/web/frontend/src/index.css+++ b/jiuwenswarm/channels/web/frontend/src/index.css@@ -383,6 +383,10 @@ select {background: var(--effect-content-background);}+ .content.content--a2a {+ overflow-y: hidden;+ }+/* Cards */.card {background: var(--color-surface-card);diff --git a/jiuwenswarm/gateway/a2a_manager/manager.py b/jiuwenswarm/gateway/a2a_manager/manager.pyindex cd6d16f94f..f174fe2340 100644--- a/jiuwenswarm/gateway/a2a_manager/manager.py+++ b/jiuwenswarm/gateway/a2a_manager/manager.py@@ -10,6 +10,7 @@ from collections import dequefrom collections.abc import Callablefrom typing import Any, Protocol+from jiuwenswarm.edition import is_enterprisefrom jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import (A2AChannel,A2ADependencyMissingError,@@ -161,15 +162,34 @@ class A2AManager:async def outbound_register(self, params: dict[str, Any]) -> dict[str, Any]:return await self._require_outbound().register(params)- async def outbound_list(self) -> dict[str, Any]:- return await self._require_outbound().list_agents()+ async def outbound_list(+ self, *, source_resource_id: str | None = None+ ) -> dict[str, Any]:+ outbound = self._require_outbound()+ result = await outbound.list_agents()+ allowed = await self._resolve_authorized_a2a_agent_ids(source_resource_id)+ if allowed is None:+ return result+ items = [+ item+ for item in result.get("items", [])+ if str(item.get("agent_id") or "").strip() in allowed+ ]+ return {"items": items, "total": len(items)}async def outbound_get(self, agent_id: str) -> dict[str, Any]:return await self._require_outbound().get_agent(agent_id)async def outbound_set_user_enabled(- self, agent_id: str, *, enabled: bool+ self,+ agent_id: str,+ *,+ enabled: bool,+ source_resource_id: str | None = None,) -> dict[str, Any]:+ allowed = await self._resolve_authorized_a2a_agent_ids(source_resource_id)+ if allowed is not None and str(agent_id or "").strip() not in allowed:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)return await self._require_outbound().set_user_enabled(agent_id, enabled)async def outbound_edit(self, agent_id: str) -> dict[str, Any]:@@ -195,7 +215,21 @@ class A2AManager:async def outbound_delete(self, agent_id: str) -> dict[str, Any]:return await self._require_outbound().delete_agent(agent_id)- async def outbound_dispatch_get(self, dispatch_id: str) -> dict[str, Any]:+ async def outbound_dispatch_get(+ self,+ dispatch_id: str,+ *,+ source_session_id: str | None = None,+ source_resource_id: str | None = None,+ ) -> dict[str, Any]:+ if is_enterprise() and not str(source_resource_id or "").strip():+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)+ if source_resource_id is not None:+ return await self._require_outbound_dispatcher().query_dispatch(+ dispatch_id,+ source_session_id=str(source_session_id or ""),+ source_resource_id=source_resource_id,+ )return await self._require_outbound().get_dispatch(dispatch_id)async def outbound_dispatch_list(self, *, limit: int = 200) -> dict[str, Any]:@@ -207,11 +241,14 @@ class A2AManager:query: str = "",required_skills: list[str] | None = None,limit: int = 5,+ source_resource_id: str | None = None,) -> dict[str, Any]:+ allowed = await self._resolve_effective_a2a_agent_ids(source_resource_id)return await self._require_outbound_dispatcher().find_agents(query=query,required_skills=required_skills,limit=limit,+ allowed_agent_ids=allowed,)async def outbound_dispatch_task(@@ -221,24 +258,72 @@ class A2AManager:task: str,mode: str,source_session_id: str,+ source_resource_id: str | None = None,reason: str | None = None,) -> dict[str, Any]:+ await self._require_a2a_agent_authorized(source_resource_id, agent_id)return await self._require_outbound_dispatcher().dispatch(agent_id=agent_id,task=task,mode=mode,source_session_id=source_session_id,+ source_resource_id=source_resource_id,reason=reason,)async def outbound_get_dispatch(- self, *, dispatch_id: str, source_session_id: str+ self,+ *,+ dispatch_id: str,+ source_session_id: str,+ source_resource_id: str | None = None,) -> dict[str, Any]:+ if is_enterprise() and not str(source_resource_id or "").strip():+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)return await self._require_outbound_dispatcher().query_dispatch(dispatch_id,source_session_id=source_session_id,+ source_resource_id=source_resource_id,+ )++ async def _resolve_effective_a2a_agent_ids(+ self, resource_id: str | None+ ) -> frozenset[str] | None:+ outbound = self._outbound+ if outbound is None:+ return None+ return await outbound.resolve_effective_a2a_agent_ids(+ str(resource_id or "").strip())+ async def _resolve_authorized_a2a_agent_ids(+ self, resource_id: str | None+ ) -> frozenset[str] | None:+ outbound = self._outbound+ if outbound is None:+ return None+ resolver = getattr(outbound, "resolve_authorized_a2a_agent_ids", None)+ if not callable(resolver):+ return None+ return await resolver(str(resource_id or "").strip())++ async def _require_a2a_agent_authorized(+ self, resource_id: str | None, agent_id: str+ ) -> None:+ allowed = await self._resolve_effective_a2a_agent_ids(resource_id)+ normalized_agent_id = str(agent_id or "").strip()+ if allowed is None or normalized_agent_id in allowed:+ return+ authorized = await self._resolve_authorized_a2a_agent_ids(resource_id)+ if authorized is not None and normalized_agent_id not in authorized:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)+ projected = await self._require_outbound().get_agent(normalized_agent_id)+ if projected.get("manager_enabled") is False:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_MANAGER_DISABLED)+ if projected.get("user_enabled") is False:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_USER_DISABLED)+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)+def snapshot(self) -> A2AIngressSnapshot:config = self._configeffective = self._effective_config@@ -367,6 +452,7 @@ class A2AManager:async def start_from_config(self) -> A2AIngressSnapshot:"""Start during Gateway boot without delaying boot on A2A failures."""+ self._require_ingress_available()async with self._lock:if self._channel is not None:return self.snapshot()@@ -380,6 +466,7 @@ class A2AManager:async def update(self, patch: dict[str, Any], *, apply: bool = False) -> A2AIngressSnapshot:+ self._require_ingress_available()async with self._lock:next_config = self._config.with_patch(patch)self._persist_locked(next_config)@@ -391,6 +478,7 @@ class A2AManager:return self.snapshot()async def enable(self) -> A2AIngressSnapshot:+ self._require_ingress_available()async with self._lock:if not self._config.enabled:self._persist_locked(self._config.with_patch({"enabled": True}))@@ -410,6 +498,7 @@ class A2AManager:return self.snapshot()async def reload(self) -> A2AIngressSnapshot:+ self._require_ingress_available()async with self._lock:if not self._config.enabled:await self._disable_locked()@@ -433,6 +522,7 @@ class A2AManager:self._last_error = Noneasync def _create_and_start_locked(self, *, wait: bool) -> None:+ self._require_ingress_available()effective_config = self._configchannel = self._channel_factory(effective_config.to_channel_config(), self._router@@ -464,6 +554,14 @@ class A2AManager:if wait:await self._await_start_locked(task)+ @staticmethod+ def _require_ingress_available() -> None:+ if is_enterprise():+ raise A2AIngressError(+ "A2A_INGRESS_DISABLED",+ "A2A ingress is unavailable in enterprise edition",+ )+async def _await_start_locked(self, task: asyncio.Task[None]) -> None:try:await taskdiff --git a/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py b/jiuwenswarm/gateway/a2a_manager/outbound/discovery.pyindex 1b03b1c85b..adb10a2dff 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py@@ -363,7 +363,9 @@ class A2AOutboundDiscoveryService:)return source_url, normalized_path, card_url- async def _validate_network_target(self, url: str) -> _ValidatedTarget:+ async def _validate_network_target(+ self, url: str, *, network_policy: dict[str, bool] | None = None+ ) -> _ValidatedTarget:try:parts = urlsplit(url)scheme = parts.scheme.lower()@@ -382,10 +384,32 @@ class A2AOutboundDiscoveryService:loopback_only = all(ipaddress.ip_address(item).is_loopback for item in addresses)- if scheme == "http" and not (self._allow_loopback_http and loopback_only):- raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_BLOCKED)- if not all(_is_public_address(item) for item in addresses):- if not (self._allow_loopback_http and loopback_only):+ public_only = all(_is_public_address(item) for item in addresses)+ if network_policy is None:+ if scheme == "http" and not (self._allow_loopback_http and loopback_only):+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_BLOCKED)+ if not public_only and not (self._allow_loopback_http and loopback_only):+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_BLOCKED)+ else:+ private_networks = tuple(ipaddress.ip_network(cidr) for cidr in (+ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"+ ))+ # Match Manager's RFC1918-only policy; IPv6 ULA/mapped addresses+ # are not included in the private-network exception.+ private_only = all(+ address.version == 4+ and any(address in network for network in private_networks)+ for address in map(ipaddress.ip_address, addresses)+ )+ allowed_address = (+ public_only+ or (network_policy.get("allow_loopback") is True and loopback_only)+ or (network_policy.get("allow_private_network") is True and private_only)+ )+ if not allowed_address or (scheme == "http" and (+ network_policy.get("allow_http") is not True+ or (public_only and network_policy.get("allow_public_http") is not True)+ )):raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_BLOCKED)return _ValidatedTarget(host=parts.hostname.lower().rstrip("."),@@ -393,9 +417,11 @@ class A2AOutboundDiscoveryService:pinned_address=addresses[0],)- async def validate_network_target(self, url: str) -> _ValidatedTarget:+ async def validate_network_target(+ self, url: str, *, network_policy: dict[str, bool] | None = None+ ) -> _ValidatedTarget:"""Revalidate and resolve a target immediately before a connection."""- return await self._validate_network_target(url)+ return await self._validate_network_target(url, network_policy=network_policy)__all__ = [diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.pyindex 32dd505493..1492f783c1 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py@@ -188,6 +188,7 @@ class A2AOutboundDispatcher:query: str = "",required_skills: list[str] | tuple[str, ...] | None = None,limit: int = 5,+ allowed_agent_ids: frozenset[str] | None = None,) -> dict[str, Any]:normalized_query = str(query or "").strip().lower()query_terms = self._search_terms(normalized_query)@@ -199,6 +200,8 @@ class A2AOutboundDispatcher:normalized_limit = max(1, min(int(limit), 20))matches: list[tuple[int, dict[str, Any]]] = []for agent in await self._repository.list_agents():+ if allowed_agent_ids is not None and agent.agent_id not in allowed_agent_ids:+ continueif not self._callable(agent):continuecard = agent.agent_card@@ -272,6 +275,7 @@ class A2AOutboundDispatcher:task: str,mode: A2AOutboundDispatchMode | str,source_session_id: str,+ source_resource_id: str | None = None,reason: str | None = None,) -> dict[str, Any]:reason_present = bool(str(reason or "").strip())@@ -299,6 +303,7 @@ class A2AOutboundDispatcher:status=A2AOutboundDispatchStatus.CREATED,request_message_id=message_id,source_session_id=session_id,+ source_resource_id=str(source_resource_id or "").strip() or None,created_at=stamp,updated_at=stamp,agent_name=agent.display_name,@@ -356,12 +361,16 @@ class A2AOutboundDispatcher:return resultasync def query_dispatch(- self, dispatch_id: str, *, source_session_id: str+ self,+ dispatch_id: str,+ *,+ source_session_id: str,+ source_resource_id: str | None = None,) -> dict[str, Any]:normalized_id = str(dispatch_id or "").strip()async with self._query_locks.hold(normalized_id):current = await self._require_owned_dispatch(- normalized_id, source_session_id+ normalized_id, source_session_id, source_resource_id)if current.is_terminal or not current.remote_task_id:return self._public_dispatch(current)@@ -407,10 +416,16 @@ class A2AOutboundDispatcher:return self._public_dispatch(updated or current)async def cancel_dispatch(- self, dispatch_id: str, *, source_session_id: str+ self,+ dispatch_id: str,+ *,+ source_session_id: str,+ source_resource_id: str | None = None,) -> dict[str, Any]:async with self._query_locks.hold(str(dispatch_id)):- current = await self._require_owned_dispatch(dispatch_id, source_session_id)+ current = await self._require_owned_dispatch(+ dispatch_id, source_session_id, source_resource_id+ )if current.is_terminal or not current.remote_task_id:return self._public_dispatch(current)agent = await self._repository.get_agent(current.agent_id)@@ -648,7 +663,7 @@ class A2AOutboundDispatcher:if self._client_builder is not None:return await self._client_builder(agent, credential)target = await self._discovery.validate_network_target(- agent.selected_interface.url+ agent.selected_interface.url, network_policy=agent.network_policy)http_client = httpx.AsyncClient(transport=create_pinned_transport({target.host: target.pinned_address}),@@ -820,7 +835,10 @@ class A2AOutboundDispatcher:)async def _require_owned_dispatch(- self, dispatch_id: str, source_session_id: str+ self,+ dispatch_id: str,+ source_session_id: str,+ source_resource_id: str | None = None,) -> A2AOutboundDispatch:dispatch = await self._repository.get_dispatch(str(dispatch_id or "").strip())if dispatch is None:@@ -828,6 +846,11 @@ class A2AOutboundDispatcher:if dispatch.source_session_id != str(source_session_id or "").strip():# Deliberately indistinguishable from a missing ID.raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)+ expected_resource = str(source_resource_id or "").strip()+ if getattr(self._repository, "manager_owned", False) and not expected_resource:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)+ if expected_resource and dispatch.source_resource_id != expected_resource:+ raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)return dispatchasync def _apply_remote(diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py b/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.pyindex 6f832d875d..49475b0d9a 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import loggingfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import Any, Callable@@ -16,6 +17,8 @@ from .errors import A2AOutboundError, A2AOutboundErrorCode, safe_error_summaryfrom .models import A2AOutboundAgent, A2AOutboundAvailability, A2AOutboundDispatchfrom .repository import A2AOutboundRepository, JsonA2AOutboundRecordCodec+logger = logging.getLogger(__name__)+_DISPATCH_DATETIME_FIELDS = ("accepted_at","finished_at",@@ -104,11 +107,92 @@ class EnterpriseA2AProjection(A2AOutboundRepository):templates: EnterpriseRecordRepository,user_states: EnterpriseRecordRepository,runtime_states: EnterpriseRecordRepository,+ policies: EnterpriseRecordRepository | None = None,+ agent_templates: EnterpriseRecordRepository | None = None,+ instance_resources: EnterpriseRecordRepository | None = None,) -> None:super().__init__(store, _EnterpriseA2AOutboundRecordCodec())self._templates = templatesself._user_states = user_statesself._runtime_states = runtime_states+ self._policies = policies+ self._agent_templates = agent_templates+ self._instance_resources = instance_resources++ async def resolve_effective_a2a_agent_ids(+ self, resource_id: str+ ) -> frozenset[str]:+ """Resolve the current policy/manager/user intersection for one resource."""+ allowed, projected = await self._resolve_policy_scope(resource_id)+ return frozenset(+ item.agent.agent_id+ for item in projected+ if item.agent.agent_id in allowed+ and item.manager_enabled+ and item.user_enabled+ )++ async def resolve_authorized_a2a_agent_ids(+ self, resource_id: str+ ) -> frozenset[str]:+ """Resolve the policy-authorized catalog before local enablement state."""+ allowed, _ = await self._resolve_policy_scope(resource_id)+ return allowed++ async def _resolve_policy_scope(+ self, resource_id: str+ ) -> tuple[frozenset[str], list[EnterpriseA2AAgentView]]:+ if not all((self._policies, self._agent_templates, self._instance_resources)):+ return frozenset(), []+ resource = await self._instance_resources.get(+ resource_id=str(resource_id or "").strip()+ )+ if resource is None or not bool(resource.get("enabled")):+ return frozenset(), []+ expires_at = _to_datetime(resource.get("expires_at"))+ if expires_at is not None and expires_at <= _utc_now():+ return frozenset(), []++ template_id = str(resource.get("ref_template_id") or "").strip()+ agent_template = await self._agent_templates.get(template_id=template_id)+ if agent_template is None or not bool(agent_template.get("enabled")):+ return frozenset(), []+ template_ref = agent_template.get("template_ref")+ refs = (+ template_ref.get("a2a_access_policy")+ if isinstance(template_ref, dict)+ else None+ )+ if not isinstance(refs, list) or len(refs) != 1:+ return frozenset(), []+ policy_id = str(refs[0] or "").strip()+ if not policy_id or policy_id.startswith("${") or " or " in policy_id.lower():+ return frozenset(), []+ policy = await self._policies.get(policy_id=policy_id)+ if policy is None or not bool(policy.get("enabled")):+ return frozenset(), []++ members = {+ str(item).strip()+ for item in (policy.get("member_template_ids") or [])+ if str(item).strip()+ }+ projected = await self.list_projected_agents()+ mode = str(policy.get("mode") or "").strip().lower()+ if mode == "allowlist":+ policy_allowed = members+ elif mode == "denylist":+ policy_allowed = {item.agent.agent_id for item in projected} - members+ else:+ return frozenset(), projected+ return (+ frozenset(+ item.agent.agent_id+ for item in projected+ if item.agent.agent_id in policy_allowed+ ),+ projected,+ )@staticmethoddef _project(@@ -121,6 +205,17 @@ class EnterpriseA2AProjection(A2AOutboundRepository):True if user_state is None else bool(user_state.get("user_enabled")))runtime = runtime_state or {}+ network_policy = (template.get("data") or {}).get("network_policy")+ if network_policy is None:+ network_policy = {}+ elif not isinstance(network_policy, dict) or any(+ type(value) is not bool for value in network_policy.values()+ ):+ logger.warning(+ "Invalid A2A network_policy template_id=%s; using strict defaults",+ template.get("template_id"),+ )+ network_policy = {}availability = str(runtime.get("availability") or A2AOutboundAvailability.AVAILABLE.value)@@ -133,6 +228,7 @@ class EnterpriseA2AProjection(A2AOutboundRepository):"card_fingerprint": template.get("card_fingerprint"),"card_revision": template.get("card_revision"),"agent_card": template.get("agent_card"),+ "network_policy": network_policy,"selected_interface": template.get("selected_interface"),"enabled": manager_enabled and user_enabled,"availability": availability,diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py b/jiuwenswarm/gateway/a2a_manager/outbound/errors.pyindex 91e43fb3a4..9439851b9e 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/errors.py@@ -16,6 +16,9 @@ class A2AOutboundErrorCode(str, Enum):AGENT_NOT_REGISTERED = "A2A_AGENT_NOT_REGISTERED"AGENT_DISABLED = "A2A_AGENT_DISABLED"AGENT_UNAVAILABLE = "A2A_AGENT_UNAVAILABLE"+ AGENT_NOT_AUTHORIZED = "A2A_AGENT_NOT_AUTHORIZED"+ AGENT_USER_DISABLED = "A2A_AGENT_USER_DISABLED"+ AGENT_MANAGER_DISABLED = "A2A_AGENT_MANAGER_DISABLED"AGENT_REVIEW_REQUIRED = "A2A_AGENT_REVIEW_REQUIRED"AUTH_REQUIRED = "A2A_AUTH_REQUIRED"AUTH_SCHEME_MISSING = "A2A_AUTH_SCHEME_MISSING"@@ -42,6 +45,9 @@ _SAFE_SUMMARIES: dict[A2AOutboundErrorCode, str] = {A2AOutboundErrorCode.AGENT_NOT_REGISTERED: "指定的第三方 Agent 尚未注册。",A2AOutboundErrorCode.AGENT_DISABLED: "指定的第三方 Agent 已停用。",A2AOutboundErrorCode.AGENT_UNAVAILABLE: "指定的第三方 Agent 当前不可用。",+ A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED: "当前 Agent 无权调用该第三方 Agent。",+ A2AOutboundErrorCode.AGENT_USER_DISABLED: "该第三方 Agent 已被用户停用。",+ A2AOutboundErrorCode.AGENT_MANAGER_DISABLED: "该第三方 Agent 已被管理员停用。",A2AOutboundErrorCode.AGENT_REVIEW_REQUIRED: "第三方 Agent 配置变化需要确认。",A2AOutboundErrorCode.AUTH_REQUIRED: "第三方 Agent 需要有效凭据。",A2AOutboundErrorCode.AUTH_SCHEME_MISSING: "已配置凭据,但 Agent Card 未声明认证方式。请让对方补充认证声明后刷新 Card,或清除不需要的凭据。",diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/models.py b/jiuwenswarm/gateway/a2a_manager/outbound/models.pyindex e19d44c712..8d8819af6c 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/models.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/models.py@@ -212,8 +212,14 @@ class A2AOutboundAgent:pending_revision: dict[str, Any] | None = Nonecreated_at: str = ""updated_at: str = ""+ network_policy: dict[str, bool] | None = Nonedef validate(self) -> "A2AOutboundAgent":+ if self.network_policy is not None and (+ not isinstance(self.network_policy, dict)+ or any(type(value) is not bool for value in self.network_policy.values())+ ):+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)for name in ("agent_id","display_name",@@ -266,6 +272,7 @@ class A2AOutboundAgent:card_fingerprint=str(record.get("card_fingerprint") or "").strip(),card_revision=int(record.get("card_revision") or 0),agent_card=dict(record.get("agent_card") or {}),+ network_policy=record.get("network_policy"),selected_interface=A2ACompatibleInterface.from_dict(dict(record.get("selected_interface") or {})),diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py b/jiuwenswarm/gateway/a2a_manager/outbound/registry.pyindex ae19616a19..f957aa1480 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py@@ -231,6 +231,22 @@ class A2AOutboundRegistry:projected = await setter(agent_id, user_enabled)return projected.public_dict()+ async def resolve_effective_a2a_agent_ids(+ self, resource_id: str+ ) -> frozenset[str] | None:+ resolver = getattr(self._repository, "resolve_effective_a2a_agent_ids", None)+ if not callable(resolver):+ return None+ return await resolver(resource_id)++ async def resolve_authorized_a2a_agent_ids(+ self, resource_id: str+ ) -> frozenset[str] | None:+ resolver = getattr(self._repository, "resolve_authorized_a2a_agent_ids", None)+ if not callable(resolver):+ return None+ return await resolver(resource_id)+async def edit_agent(self, agent_id: str) -> dict[str, Any]:"""Read the credential only for an explicit management editing request."""self._require_mutable_catalog()diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex 9ee42a330b..3005ba32be 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -80,6 +80,22 @@ def _uses_external_agent_config() -> bool:return bool(os.getenv("GATEWAY_RUNTIME_MANAGER_URL", "").strip())+def _load_gateway_a2a_ingress_config():+ from jiuwenswarm.gateway.a2a_manager import (+ A2AIngressConfig,+ load_a2a_ingress_config_safely,+ )++ if is_enterprise():+ return A2AIngressConfig(), None+ return load_a2a_ingress_config_safely()+++async def _start_gateway_a2a_ingress(a2a_manager: Any) -> None:+ if not is_enterprise():+ await a2a_manager.start_from_config()++# Keep gateway idle-finalize fallback aligned with ACP channel default._PROMPT_IDLE_FINALIZE_SECONDS = 3.0_AGENT_PREWARM_EXCLUDED_CHANNELS = frozenset({"acp", "a2a"})@@ -1521,7 +1537,7 @@ async def _run_with_telemetry(web_path: str,telemetry_lifecycle,) -> bool:- from jiuwenswarm.gateway.a2a_manager import A2AManager, load_a2a_ingress_config_safely+ from jiuwenswarm.gateway.a2a_manager import A2AManagerfrom jiuwenswarm.gateway.channel_manager.im_platforms.dingtalk.dingtalk_connect import DingTalkChannel, \DingTalkConfigfrom jiuwenswarm.gateway.channel_manager.im_platforms.feishu.feishu_connect import FeishuChannel, FeishuConfig@@ -2032,7 +2048,7 @@ async def _run_with_telemetry(web_channel.git_watcher_registry = _git_watcher_registry_git_watcher_registry.set_channel(web_channel)- a2a_config, a2a_config_error = load_a2a_ingress_config_safely()+ a2a_config, a2a_config_error = _load_gateway_a2a_ingress_config()if a2a_config_error is not None:logger.error("a2a.ingress configuration is invalid; ingress remains disabled: %s", a2a_config_error)a2a_manager = A2AManager(@@ -2152,7 +2168,7 @@ async def _run_with_telemetry(binding.install(gateway_server)gateway_server.on_message(acp_inbound_server.handle_message)- await a2a_manager.start_from_config()+ await _start_gateway_a2a_ingress(a2a_manager)feishu_channel = Nonefeishu_task = Nonediff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex fcefc97148..132640c355 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1896,13 +1896,14 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:async def _a2a_ingress_reload(ws, req_id, params, session_id):await _send_a2a_snapshot(ws, req_id, lambda: a2a_manager.reload())- channel.register_method("a2a.ingress.get", _a2a_ingress_get)- channel.register_method("a2a.ingress.edit", _a2a_ingress_edit)- channel.register_method("a2a.ingress.history", _a2a_ingress_history)- channel.register_method("a2a.ingress.update", _a2a_ingress_update)- channel.register_method("a2a.ingress.enable", _a2a_ingress_enable)- channel.register_method("a2a.ingress.disable", _a2a_ingress_disable)- channel.register_method("a2a.ingress.reload", _a2a_ingress_reload)+ if not is_enterprise():+ channel.register_method("a2a.ingress.get", _a2a_ingress_get)+ channel.register_method("a2a.ingress.edit", _a2a_ingress_edit)+ channel.register_method("a2a.ingress.history", _a2a_ingress_history)+ channel.register_method("a2a.ingress.update", _a2a_ingress_update)+ channel.register_method("a2a.ingress.enable", _a2a_ingress_enable)+ channel.register_method("a2a.ingress.disable", _a2a_ingress_disable)+ channel.register_method("a2a.ingress.reload", _a2a_ingress_reload)async def _send_a2a_outbound(ws, req_id, operation) -> None:if a2a_manager is None or not a2a_manager.outbound_available:@@ -1973,7 +1974,15 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:)async def _a2a_outbound_list(ws, req_id, params, session_id):- await _send_a2a_outbound(ws, req_id, lambda: a2a_manager.outbound_list())+ await _send_a2a_outbound(+ ws,+ req_id,+ lambda: a2a_manager.outbound_list(+ source_resource_id=(+ str(params.get("bot_id") or "") if is_enterprise() else None+ )+ ),+ )async def _a2a_outbound_get(ws, req_id, params, session_id):await _send_a2a_outbound(@@ -2007,7 +2016,11 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:ws,req_id,lambda: a2a_manager.outbound_set_user_enabled(- str(params.get("agent_id") or ""), enabled=user_enabled+ str(params.get("agent_id") or ""),+ enabled=user_enabled,+ source_resource_id=(+ str(params.get("bot_id") or "") if is_enterprise() else None+ ),),)@@ -2051,7 +2064,13 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:await _send_a2a_outbound(ws,req_id,- lambda: a2a_manager.outbound_dispatch_get(str(params.get("dispatch_id") or "")),+ lambda: a2a_manager.outbound_dispatch_get(+ str(params.get("dispatch_id") or ""),+ source_session_id=(session_id if is_enterprise() else None),+ source_resource_id=(+ str(params.get("bot_id") or "") if is_enterprise() else None+ ),+ ),)async def _a2a_outbound_dispatch_list(ws, req_id, params, session_id):diff --git a/jiuwenswarm/gateway/channel_manager/web/invoke.py b/jiuwenswarm/gateway/channel_manager/web/invoke.pyindex 456e03ce4a..0fd01d4fc4 100644--- a/jiuwenswarm/gateway/channel_manager/web/invoke.py+++ b/jiuwenswarm/gateway/channel_manager/web/invoke.py@@ -21,7 +21,14 @@ logger = logging.getLogger(__name__)# AgentServer's E2A normalization. Local handlers only receive ``params``, so# merge ``metadata.routing`` into the handler params copy (not Message.params)._LOCAL_ROUTING_IDENTITY_PREFIXES = ("cron.", "skills.enterprise.")-_LOCAL_ROUTING_IDENTITY_METHODS = frozenset({"models.list", "project.get_sessions", "project.get_cron_sessions"})+_LOCAL_ROUTING_IDENTITY_METHODS = frozenset({+ "models.list",+ "project.get_sessions",+ "project.get_cron_sessions",+ "a2a.outbound.list",+ "a2a.outbound.enabled.update",+ "a2a.outbound.dispatch.get",+})_ENTERPRISE_BLOCKED_EXACT = frozenset({"config.set", "config.save_all", "models.replace_all", "models.save",diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py b/jiuwenswarm/gateway/channel_manager/web/web_http_app.pyindex 5ade09226b..6513f32c02 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py@@ -15,11 +15,12 @@ from fastapi import Body, FastAPI, File, Query, Request, Response, UploadFilefrom fastapi.responses import JSONResponse, RedirectResponse, StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field+from jiuwenswarm.edition import is_enterprisefrom jiuwenswarm.gateway.channel_manager.web.web_http_dispatch import dispatch_http_requestfrom jiuwenswarm.gateway.channel_manager.web.web_http_routes import (- MAPPED_ROUTES,WebHttpMappedRoute,catalog_entries,+ mapped_routes_for_edition,)from jiuwenswarm.gateway.channel_manager.web.web_http_file_compat import (catalog_file_compat_entries,@@ -381,6 +382,8 @@ def _schedule_abandoned_outbound_cleanup(def create_web_http_app(channel: Any) -> FastAPI:"""Build FastAPI app bound to an existing ``WebChannel`` instance."""+ enterprise_mode = is_enterprise()+ mapped_routes = mapped_routes_for_edition(enterprise=enterprise_mode)app = FastAPI(title="JiuwenSwarm Gateway Web HTTP",version="0.2.0",@@ -566,7 +569,7 @@ def create_web_http_app(channel: Any) -> FastAPI:"ok": True,"data": {"prefix": "/api/v1",- "routes": catalog_entries()+ "routes": catalog_entries(routes=mapped_routes)+ catalog_sessions_compat_entries()+ catalog_file_compat_entries(),},@@ -607,7 +610,7 @@ def create_web_http_app(channel: Any) -> FastAPI:request, channel, "harness.import", payload, bind_session_param=False,)- _register_mapped_routes(app, channel, MAPPED_ROUTES)+ _register_mapped_routes(app, channel, mapped_routes)register_sessions_compat_routes(app)register_file_compat_routes(app)return appdiff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.pyindex f5ea4414d1..a9c48b246b 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py@@ -797,6 +797,19 @@ MAPPED_ROUTES: tuple[WebHttpMappedRoute, ...] = (*WORKSPACE_ROUTES,)++def mapped_routes_for_edition(*, enterprise: bool) -> tuple[WebHttpMappedRoute, ...]:+ if not enterprise:+ return MAPPED_ROUTES+ ingress_route_keys = {+ (route.http_method, route.path) for route in _A2A_INGRESS_ROUTES+ }+ return tuple(+ route+ for route in MAPPED_ROUTES+ if (route.http_method, route.path) not in ingress_route_keys+ )+# Core routes implemented in web_http_app.py (hand-written because of SSE / history collect).CORE_ROUTE_CATALOG: tuple[tuple[str, str, str, str], ...] = (("GET", "/health", "", "探活(非 RPC method)"),@@ -851,8 +864,18 @@ def catalog_entries(include_core: bool = True,include_settings: bool = True,include_workspace: bool = True,+ routes: Sequence[WebHttpMappedRoute] | None = None,) -> list[dict[str, Any]]:"""Machine-readable map for GET /api/v1/catalog and docs generation."""+ route_keys = (+ None+ if routes is None+ else {(route.http_method, route.path) for route in routes}+ )++ def enabled(route: WebHttpMappedRoute) -> bool:+ return route_keys is None or (route.http_method, route.path) in route_keys+rows: list[dict[str, Any]] = []if include_core:for http_method, path, rpc_method, note in CORE_ROUTE_CATALOG:@@ -865,10 +888,12 @@ def catalog_entries(})if include_settings:for route in SETTINGS_ROUTES:- rows.append(_catalog_row_from_route(route, group="settings"))+ if enabled(route):+ rows.append(_catalog_row_from_route(route, group="settings"))if include_workspace:for route in WORKSPACE_ROUTES:- rows.append(_catalog_row_from_route(route, group="workspace"))+ if enabled(route):+ rows.append(_catalog_row_from_route(route, group="workspace"))rows.append({"http_method": "POST","path": "/api/v1/harness/packages/actions/import-file",diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex 48892e2dc1..556d3a5d8c 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -218,7 +218,7 @@ class MessageHandler(FileTransferMixin, ABC):self._running = Falseself._a2a_outbound_tool_manager: Any | None = Noneself._active_a2a_outbound_tool_tasks: dict[- str, tuple[asyncio.Task[Any], str]+ str, tuple[asyncio.Task[Any], str, str]] = {}self._forward_task: asyncio.Task | None = Noneself._stream_tasks: dict[str, asyncio.Task] = {} # request_id -> task@@ -2938,16 +2938,15 @@ class MessageHandler(FileTransferMixin, ABC):session_id: str | None = str(sid_raw)else:session_id = self._stream_sessions.get(rid)+ request_metadata = self._stream_metadata.get(rid)if await self._handle_a2a_outbound_tool_push(chunk=chunk,session_id=session_id,+ request_metadata=request_metadata,):return- # 获取原始请求的 metadata,用于合并- request_metadata = self._stream_metadata.get(rid)-# 获取 AgentServer 返回的 metadatawmd = wire.get("metadata")if isinstance(wmd, dict):@@ -3034,7 +3033,11 @@ class MessageHandler(FileTransferMixin, ABC):self._active_a2a_outbound_tool_tasks = {}async def _handle_a2a_outbound_tool_push(- self, *, chunk: Any, session_id: str | None+ self,+ *,+ chunk: Any,+ session_id: str | None,+ request_metadata: dict[str, Any] | None = None,) -> bool:from jiuwenswarm.common.e2a.adapters import build_acp_tool_response_messagefrom jiuwenswarm.gateway.a2a_manager.outbound import (@@ -3071,6 +3074,35 @@ class MessageHandler(FileTransferMixin, ABC):manager = self._a2a_outbound_tool_managercurrent_task = asyncio.current_task()trusted_session_id = str(session_id or "").strip()+ source_resource_id = ""+ resource_identity_invalid = False+ if is_enterprise():+ from jiuwenswarm.common.request_identity import web_routing_identity++ # Reverse RPC has its own request_id. Resolve identity from the+ # Gateway's active conversation, never from tool-supplied metadata.+ source_identity = web_routing_identity(request_metadata)+ if request_metadata is None and trusted_session_id:+ identities = [+ web_routing_identity(self._stream_metadata.get(active_rid))+ for active_rid, active_sid in getattr(self, "_stream_sessions", {}).items()+ if active_sid == trusted_session_id+ and self._stream_channels.get(active_rid) == chunk.channel_id+ ]+ if identities and all(item == identities[0] for item in identities):+ source_identity = identities[0]+ source_resource_id = str(source_identity.get("bot_id") or "").strip()+ requested_resource_id = str(params.get("resource_id") or "").strip()+ resource_identity_invalid = bool(+ not source_resource_id or requested_resource_id != source_resource_id+ )+ if resource_identity_invalid:+ logger.warning(+ "[A2A] reverse RPC identity missing or mismatched: method=%s session_id=%s "+ "channel_id=%s gateway_bot_id=%r tool_resource_id=%r",+ method, trusted_session_id, chunk.channel_id,+ source_resource_id, requested_resource_id,+ )active_calls = getattr(self, "_active_a2a_outbound_tool_tasks", None)if active_calls is None:active_calls = self._active_a2a_outbound_tool_tasks = {}@@ -3080,7 +3112,9 @@ class MessageHandler(FileTransferMixin, ABC):target = active[0] if active is not None else Nonecanceled = bool(active is not None+ and not resource_identity_invalidand active[1] == trusted_session_id+ and active[2] == source_resource_idand target is not current_task)if canceled:@@ -3099,8 +3133,14 @@ class MessageHandler(FileTransferMixin, ABC):await self.publish_user_messages(reply)return Trueif jsonrpc_id and current_task is not None:- active_calls[jsonrpc_id] = (current_task, trusted_session_id)+ active_calls[jsonrpc_id] = (+ current_task,+ trusted_session_id,+ source_resource_id,+ )try:+ if resource_identity_invalid:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)if manager is None:raise A2AOutboundError(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)source_session_id = trusted_session_id@@ -3110,24 +3150,33 @@ class MessageHandler(FileTransferMixin, ABC):required = params.get("required_skills")if required is not None and not isinstance(required, list):raise A2AOutboundError(A2AOutboundErrorCode.TASK_INVALID)- result = await manager.outbound_find_agents(- query=str(params.get("query") or ""),- required_skills=required,- limit=int(params.get("limit") or 5),- )+ call_params = {+ "query": str(params.get("query") or ""),+ "required_skills": required,+ "limit": int(params.get("limit") or 5),+ }+ if source_resource_id:+ call_params["source_resource_id"] = source_resource_id+ result = await manager.outbound_find_agents(**call_params)elif method == A2A_TOOL_DISPATCH_TASK:- result = await manager.outbound_dispatch_task(- agent_id=str(params.get("agent_id") or ""),- task=str(params.get("task") or ""),- mode=str(params.get("mode") or ""),- source_session_id=source_session_id,- reason=str(params.get("reason") or "") or None,- )+ call_params = {+ "agent_id": str(params.get("agent_id") or ""),+ "task": str(params.get("task") or ""),+ "mode": str(params.get("mode") or ""),+ "source_session_id": source_session_id,+ "reason": str(params.get("reason") or "") or None,+ }+ if source_resource_id:+ call_params["source_resource_id"] = source_resource_id+ result = await manager.outbound_dispatch_task(**call_params)elif method == A2A_TOOL_GET_DISPATCH:- result = await manager.outbound_get_dispatch(- dispatch_id=str(params.get("dispatch_id") or ""),- source_session_id=source_session_id,- )+ call_params = {+ "dispatch_id": str(params.get("dispatch_id") or ""),+ "source_session_id": source_session_id,+ }+ if source_resource_id:+ call_params["source_resource_id"] = source_resource_id+ result = await manager.outbound_get_dispatch(**call_params)response = {"jsonrpc": "2.0", "id": jsonrpc_id, "result": result}except A2AOutboundError as exc:response = {diff --git a/jiuwenswarm/gateway/routing/http_agent_client.py b/jiuwenswarm/gateway/routing/http_agent_client.pyindex 92f9089599..61a4cc0d59 100644--- a/jiuwenswarm/gateway/routing/http_agent_client.py+++ b/jiuwenswarm/gateway/routing/http_agent_client.py@@ -13,7 +13,10 @@ from urllib.parse import urlsplitimport httpx-from jiuwenswarm.common.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY+from jiuwenswarm.common.e2a.constants import (+ E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST,+ E2A_WIRE_SERVER_PUSH_KEY,+)from jiuwenswarm.common.e2a.models import E2AEnvelopefrom jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_chunkfrom jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk@@ -134,6 +137,8 @@ class HttpSseAgentServerClient(AgentServerClient):self._running = Falseself._on_server_push: Callable[[dict[str, Any]], Awaitable[None]] | None = Noneself._push_task: asyncio.Task[None] | None = None+ self._push_ready = asyncio.Event()+ self._push_handlers: set[asyncio.Task[None]] = set()self._stream_lock = asyncio.Lock()self._cancelled_request_ids: set[str] = set()self._inflight_stream_ids: set[str] = set()@@ -157,6 +162,20 @@ class HttpSseAgentServerClient(AgentServerClient):def server_ready(self) -> bool:return self._server_ready+ async def wait_push_ready(self) -> None:+ """Wait for server-side subscriber registration, not just HTTP headers."""+ await asyncio.wait_for(self._push_ready.wait(), timeout=_CONNECT_TIMEOUT_SECONDS)++ async def _handle_push(+ self,+ handler: Callable[[dict[str, Any]], Awaitable[None]],+ frame: dict[str, Any],+ ) -> None:+ try:+ await handler(frame)+ except Exception:+ logger.exception("[HttpSseAgentServerClient] server_push 处理失败")+def _ensure_http(self) -> httpx.AsyncClient:if self._http is None:self._http = httpx.AsyncClient(@@ -211,6 +230,7 @@ class HttpSseAgentServerClient(AgentServerClient):async def disconnect(self) -> None:self._running = Falseself._server_ready = False+ self._push_ready.clear()task = self._push_taskself._push_task = Noneif task is not None:@@ -219,6 +239,11 @@ class HttpSseAgentServerClient(AgentServerClient):await taskexcept (asyncio.CancelledError, Exception): # noqa: BLE001pass+ handlers = list(self._push_handlers)+ for handler_task in handlers:+ handler_task.cancel()+ await asyncio.gather(*handlers, return_exceptions=True)+ self._push_handlers.clear()if self._owns_http and self._http is not None:await self._http.aclose()self._http = None@@ -389,6 +414,9 @@ class HttpSseAgentServerClient(AgentServerClient):) as response:response.raise_for_status()async for frame in iter_sse_data_frames(response):+ if frame.get("event_type") == "gateway.push_ready":+ self._push_ready.set()+ continuemeta = frame.get("metadata")if not (isinstance(meta, dict) and meta.get(E2A_WIRE_SERVER_PUSH_KEY)):continue@@ -403,10 +431,13 @@ class HttpSseAgentServerClient(AgentServerClient):handler = self._on_server_pushif handler is None:continue- try:- await handler(frame)- except Exception:- logger.exception("[HttpSseAgentServerClient] server_push 处理失败")+ if frame.get("response_kind") != E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST:+ await self._handle_push(handler, frame)+ continue+ # Keep reading cancellation RPCs while a sync dispatch runs.+ task = asyncio.create_task(self._handle_push(handler, frame))+ self._push_handlers.add(task)+ task.add_done_callback(self._push_handlers.discard)except Exception as exc: # noqa: BLE001if not self._running:return@@ -422,6 +453,8 @@ class HttpSseAgentServerClient(AgentServerClient):"[HttpSseAgentServerClient] events/stream 结束,%.0fs 后重连",_PUSH_RETRY_SECONDS,)+ finally:+ self._push_ready.clear()await asyncio.sleep(_PUSH_RETRY_SECONDS)diff --git a/jiuwenswarm/gateway/storage_assembly/setup.py b/jiuwenswarm/gateway/storage_assembly/setup.pyindex de9d77a5b5..c9ad8075ae 100644--- a/jiuwenswarm/gateway/storage_assembly/setup.py+++ b/jiuwenswarm/gateway/storage_assembly/setup.py@@ -505,6 +505,15 @@ def create_a2a_outbound_repository(runtime_states=create_enterprise_record_repository(store, "a2a_outbound_runtime_state"),+ policies=create_enterprise_record_repository(+ store, "a2a_access_policy_template"+ ),+ agent_templates=create_enterprise_record_repository(+ store, "agent_template"+ ),+ instance_resources=create_enterprise_record_repository(+ store, "instance_agent_resource"+ ),)return A2AOutboundRepository(store, JsonA2AOutboundRecordCodec())diff --git a/jiuwenswarm/server/agent_http_routes.py b/jiuwenswarm/server/agent_http_routes.pyindex 3b4dde6ba6..7ed4a8924c 100644--- a/jiuwenswarm/server/agent_http_routes.py+++ b/jiuwenswarm/server/agent_http_routes.py@@ -676,6 +676,11 @@ def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:reverse_rpc_capable=reverse_rpc_capable,)try:+ if reverse_rpc_capable:+ yield {+ "event": "gateway.push_ready",+ "data": json.dumps({"event_type": "gateway.push_ready"}),+ }while True:item = await sink.queue.get()if item is STREAM_DONE:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 2f26981441..fe4c1fc64f 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -67,7 +67,6 @@ from jiuwenswarm.agents.harness.common.rails import (StructuredAskUserRail,)from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode, is_memory_enabled-from jiuwenswarm.edition import is_enterprisefrom jiuwenswarm.agents.harness.common.tools import (SkillToolkit,)@@ -683,7 +682,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):# already owns a Code session. Sub-mode is the reliable profile key:# normal/plan are single-Agent, while Team profiles are assembled by# the declarative swarm provider and must not register this rail twice.- if normalized_sub_mode in {"normal", "plan"} and not is_enterprise():+ if normalized_sub_mode in {"normal", "plan"}:# Append, don't insert at a fixed index, to avoid silent misplacement.rail_infos.append(_RailBuildInfo(diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 395610a920..730e96a286 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -618,6 +618,12 @@ _CRON_TOOL_BOUND: ContextVar[bool] = ContextVar("cron_tool_bound",default=False,)+_RUNTIME_TOOL_RESOURCE_ID: ContextVar[str] = ContextVar(+ "runtime_tool_resource_id", default=""+)+_RUNTIME_TOOL_A2A_POLICY_ID: ContextVar[str] = ContextVar(+ "runtime_tool_a2a_policy_id", default=""+)_LLM_TRACE_SESSION_ID: ContextVar[str] = ContextVar("llm_trace_session_id",@@ -671,6 +677,8 @@ class _RuntimeCronContextTokens:shell: Token[str | None] | Nonedeepresearch: _DeepResearchRouteContextToken | Nonesend_file: Token | None = None+ resource_id: Token[str] | None = None+ a2a_policy_id: Token[str] | None = Nonedef get_runtime_tool_session_id() -> str | None:@@ -687,6 +695,16 @@ def get_runtime_tool_metadata() -> dict[str, Any] | None:"""Request metadata bound for the current agent tool invocation (ContextVar)."""return _CRON_TOOL_METADATA.get()++def get_runtime_tool_resource_id() -> str:+ """Manager-owned resource id for the current tool invocation."""+ return _RUNTIME_TOOL_RESOURCE_ID.get()+++def get_runtime_tool_a2a_policy_id() -> str:+ """A2A policy selected by the current enterprise Agent template."""+ return _RUNTIME_TOOL_A2A_POLICY_ID.get()+logger = logging.getLogger(__name__)_PERSISTENT_CHECKPOINTER_LOCK: asyncio.Lock | None = None@@ -7690,9 +7708,23 @@ class JiuWenSwarmDeepAdapter:return Nonedef _build_a2a_outbound_toolkit_rail(self) -> A2AOutboundToolkitRail | None:- if is_enterprise():- return None- return A2AOutboundToolkitRail(runtime_route=self._get_a2a_outbound_tool_route)+ return A2AOutboundToolkitRail(+ runtime_route=self._get_a2a_outbound_tool_route,+ runtime_resource_id=self._get_a2a_outbound_tool_resource_id,+ )++ def _get_a2a_outbound_tool_resource_id(self) -> str:+ """Resolve resource identity from the same source as the A2A route."""+ if str(get_runtime_tool_session_id() or "").strip():+ return str(get_runtime_tool_resource_id() or "").strip()+ route = self._current_request_route+ if str(route.get("session_id") or "").strip():+ return str(route.get("resource_id") or "").strip()+ from jiuwenswarm.common.request_identity import web_routing_identity++ return str(+ web_routing_identity(self._runtime_cron_tool_context.metadata).get("bot_id") or ""+ ).strip()def _get_a2a_outbound_tool_route(self) -> tuple[str, str]:"""Return an adapter-owned route that survives DeepAgent task boundaries."""@@ -8025,13 +8057,14 @@ class JiuWenSwarmDeepAdapter:3 if self._filesystem_rail_enabled_for_profile() else 2,_RailBuildInfo("_skill_retrieval_prompt_rail", self._build_skill_retrieval_prompt_rail),)- rail_infos.insert(- 4 if self._filesystem_rail_enabled_for_profile() else 3,- _RailBuildInfo(- "_a2a_outbound_toolkit_rail",- self._build_a2a_outbound_toolkit_rail,- ),- )+ if mode not in {"team", "team.plan", "code.team"}:+ rail_infos.insert(+ 4 if self._filesystem_rail_enabled_for_profile() else 3,+ _RailBuildInfo(+ "_a2a_outbound_toolkit_rail",+ self._build_a2a_outbound_toolkit_rail,+ ),+ )rail_infos.insert(5 if self._filesystem_rail_enabled_for_profile() else 4,_RailBuildInfo(@@ -9605,6 +9638,21 @@ class JiuWenSwarmDeepAdapter:metadata_token = _CRON_TOOL_METADATA.set(normalized_metadata)mode_token = _CRON_TOOL_MODE.set(normalized_mode)bound_token = _CRON_TOOL_BOUND.set(True)+ resource_id = str(routing.get("bot_id") or "").strip()+ policy_id = ""+ enterprise_config = getattr(self, "_enterprise_config", None)+ if (+ enterprise_config is not None+ and str(getattr(enterprise_config, "resource_id", "") or "").strip()+ == resource_id+ ):+ policy_refs = getattr(enterprise_config, "template_ref", {}).get(+ "a2a_access_policy", []+ )+ if isinstance(policy_refs, list) and len(policy_refs) == 1:+ policy_id = str(policy_refs[0] or "").strip()+ resource_token = _RUNTIME_TOOL_RESOURCE_ID.set(resource_id)+ policy_token = _RUNTIME_TOOL_A2A_POLICY_ID.set(policy_id)shell_token = set_shell_session_id(session_id)# 绑定 send_file 专用路由 ContextVar(与 skill_turbo / test 仓对齐)。@@ -9655,6 +9703,8 @@ class JiuWenSwarmDeepAdapter:shell=shell_token,deepresearch=None,send_file=send_file_token,+ resource_id=resource_token,+ a2a_policy_id=policy_token,),suppress_errors=True,)@@ -9668,6 +9718,8 @@ class JiuWenSwarmDeepAdapter:shell=shell_token,deepresearch=_DeepResearchRouteContextToken(deepresearch_token),send_file=send_file_token,+ resource_id=resource_token,+ a2a_policy_id=policy_token,)@staticmethod@@ -9742,6 +9794,8 @@ class JiuWenSwarmDeepAdapter:_reset("send_file", reset_send_file_request_context)_reset("shell", reset_shell_session_id)_reset("bound", _CRON_TOOL_BOUND.reset)+ _reset("a2a_policy_id", _RUNTIME_TOOL_A2A_POLICY_ID.reset)+ _reset("resource_id", _RUNTIME_TOOL_RESOURCE_ID.reset)_reset("mode", _CRON_TOOL_MODE.reset)_reset("metadata", _CRON_TOOL_METADATA.reset)_reset("session", _CRON_TOOL_SESSION_ID.reset)@@ -16133,10 +16187,13 @@ class JiuWenSwarmDeepAdapter:getattr(self, "_model", None) and getattr(self._model, "model_config", None)and getattr(self._model.model_config, "model_name", "") or "")+ from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple+self._current_request_route = {"session_id": session_id,"request_id": request.request_id or "","channel_id": request.channel_id or "",+ "resource_id": extract_routing_triple(request.metadata, request.params)[1] or "","output_dir": self._deepresearch_artifact_output_dir(request.params.get("project_dir")if isinstance(request.params, dict)@@ -16829,10 +16886,13 @@ class JiuWenSwarmDeepAdapter:getattr(self, "_model", None) and getattr(self._model, "model_config", None)and getattr(self._model.model_config, "model_name", "") or "")+ from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple+self._current_request_route = {"session_id": session_id,"request_id": rid or "","channel_id": cid or "",+ "resource_id": extract_routing_triple(request.metadata, request.params)[1] or "","output_dir": self._deepresearch_artifact_output_dir(request.params.get("project_dir")if isinstance(request.params, dict)@@ -16844,6 +16904,19 @@ class JiuWenSwarmDeepAdapter:if mode in ("team", "team.plan", "code.team"):from jiuwenswarm.server.runtime.agent_adapter.team_helpers import process_team_message_stream+ team_context_tokens = self._bind_runtime_cron_context(+ channel_id=request.channel_id,+ session_id=request.session_id,+ metadata=request.metadata,+ request_id=request.request_id,+ mode=mode,+ project_dir=(+ request.params.get("project_dir")+ if isinstance(request.params, dict)+ else None+ ),+ params=request.params if isinstance(request.params, dict) else None,+ )set_perf_summary_context(getattr(self, "_request_summary_rail", None),channel_id=request.channel_id or "",@@ -16919,6 +16992,10 @@ class JiuWenSwarmDeepAdapter:session_id=session_id,request_id=request.request_id,)+ self._reset_runtime_cron_context(+ team_context_tokens,+ suppress_errors=True,+ )_LLM_TRACE_SESSION_ID.reset(token_trace_sid)_LLM_TRACE_REQUEST_ID.reset(token_trace_rid)_LLM_TRACE_ITERATION.reset(token_trace_iter)diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex a981083cad..0546fe8831 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -1776,6 +1776,15 @@ async def process_team_message_stream(try:request_metadata = dict(request.metadata or {})+ from jiuwenswarm.common.request_identity import apply_routing_metadata+ from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple++ group_id, bot_id, user_id = extract_routing_triple(request.metadata, getattr(request, "params", None))+ request_metadata = apply_routing_metadata(request_metadata, {+ key: value for key, value in (+ ("group_id", group_id), ("bot_id", bot_id), ("user_id", user_id)+ ) if value+ })# V2: 若请求携带 member_name(由 Gateway resolve_member_by_user 反查注入),# 在前拼接 $sender,让 OpenJiuwen 识别发言人身份。# 规则:diff --git a/jiuwenswarm/server/runtime/enterprise_config/db_queries.py b/jiuwenswarm/server/runtime/enterprise_config/db_queries.pyindex 3234ea8595..4af64f9724 100644--- a/jiuwenswarm/server/runtime/enterprise_config/db_queries.py+++ b/jiuwenswarm/server/runtime/enterprise_config/db_queries.py@@ -14,7 +14,7 @@ from jiuwenswarm.gateway.storage.backends.db import reader as _db_readerfrom .schemas import SLOT_ENTITY_TABLE, TemplateRefSlot-def _resolve_slot_table(slot: str) -> str:+def _resolve_slot_storage(slot: str) -> tuple[str, str]:try:slot_key = TemplateRefSlot(slot)except ValueError as exc:@@ -22,7 +22,12 @@ def _resolve_slot_table(slot: str) -> str:f"unknown template_ref slot {slot!r} "f"(known: {[s.value for s in TemplateRefSlot]})") from exc- return SLOT_ENTITY_TABLE[slot_key]+ id_field = (+ "policy_id"+ if slot_key is TemplateRefSlot.A2A_ACCESS_POLICY+ else "template_id"+ )+ return SLOT_ENTITY_TABLE[slot_key], id_fieldasync def fetch_templates_by_slot(@@ -34,7 +39,7 @@ async def fetch_templates_by_slot(``template_id`` 使用 foundation DB 的 ``IN`` 语义一次查出;返回顺序与入参``template_ids`` 一致(去重后)。未命中的 id 不出现在结果中。"""- table = _resolve_slot_table(slot)+ table, id_field = _resolve_slot_storage(slot)refs: list[str] = []seen: set[str] = set()for raw in template_ids:@@ -45,12 +50,12 @@ async def fetch_templates_by_slot(refs.append(ref)if not refs:return []- filters: dict[str, Any] = {"enabled": True, "template_id": refs}+ filters: dict[str, Any] = {"enabled": True, id_field: refs}rows = await list_records(table, filters=filters)by_id = {- str(row.get("template_id") or "").strip(): row+ str(row.get(id_field) or "").strip(): rowfor row in rows- if str(row.get("template_id") or "").strip()+ if str(row.get(id_field) or "").strip()}return [by_id[ref] for ref in refs if ref in by_id]diff --git a/jiuwenswarm/server/runtime/enterprise_config/loader.py b/jiuwenswarm/server/runtime/enterprise_config/loader.pyindex 8245711163..3235c82181 100644--- a/jiuwenswarm/server/runtime/enterprise_config/loader.py+++ b/jiuwenswarm/server/runtime/enterprise_config/loader.py@@ -50,6 +50,8 @@ def _apply_slot_entities(result.mcp = entitieselif slot == TemplateRefSlot.PERMISSIONS:result.permissions = entities+ elif slot == TemplateRefSlot.A2A_ACCESS_POLICY:+ result.a2a_access_policy = entitiesdef _any_requested_slot_loaded(@@ -69,6 +71,11 @@ def _any_requested_slot_loaded(return Trueif slot == TemplateRefSlot.PERMISSIONS and result.permissions:return True+ if (+ slot == TemplateRefSlot.A2A_ACCESS_POLICY+ and result.a2a_access_policy is not None+ ):+ return Truereturn False@@ -78,7 +85,12 @@ async def _fetch_slot_entities() -> list[dict[str, Any]]:entities = await db_queries.fetch_templates_by_slot(slot, template_ids)requested = {str(tid or "").strip() for tid in template_ids} - {""}- found = {str(row.get("template_id") or "").strip() for row in entities} - {""}+ id_field = (+ "policy_id"+ if slot == TemplateRefSlot.A2A_ACCESS_POLICY+ else "template_id"+ )+ found = {str(row.get(id_field) or "").strip() for row in entities} - {""}missing = requested - foundif missing:logger.warning(@@ -111,6 +123,23 @@ async def _fetch_agent_template_row(template_id: str) -> dict[str, Any] | None:return rows[0] if rows else None+def _literal_slot_template_id_map(+ refs: dict[str, list[str]],+) -> dict[str, list[str]]:+ """A2A 策略仅接受一个字面 policy_id,其余槽位保持原引用。"""+ slot_template_id_map = dict(refs)+ policy_refs = slot_template_id_map.get(TemplateRefSlot.A2A_ACCESS_POLICY)+ if policy_refs is None:+ return slot_template_id_map+ if (+ len(policy_refs) != 1+ or policy_refs[0].startswith("${")+ or " or " in policy_refs[0].lower()+ ):+ slot_template_id_map.pop(TemplateRefSlot.A2A_ACCESS_POLICY, None)+ return slot_template_id_map++async def load_effective_enterprise_config(request: AgentRequest | Any,slots: Collection[TemplateRefSlot],@@ -165,13 +194,13 @@ async def load_effective_enterprise_config(return Nonemerged_refs = normalize_template_ref(agent_template_row.get("template_ref"))- slot_template_id_map = {+ filtered_refs = {slot: refsfor slot, refs in merged_refs.items()if slot in load_slots}- if not slot_template_id_map:+ if not filtered_refs:logger.warning("[enterprise_config] agent_template has no template_ref for resource_id=%r slots=%s",rid,@@ -179,6 +208,16 @@ async def load_effective_enterprise_config()return None+ slot_template_id_map = _literal_slot_template_id_map(filtered_refs)+ if not slot_template_id_map:+ logger.warning(+ "[enterprise_config] agent template_ref has no valid references "+ "for resource_id=%r refs=%s",+ rid,+ filtered_refs,+ )+ return None+result = EffectiveEnterpriseConfig(routing=ctx,resource_id=rid,@@ -192,7 +231,19 @@ async def load_effective_enterprise_config()for slot, template_ids in slot_template_id_map.items():- entities = await _fetch_slot_entities(slot, template_ids)+ try:+ entities = await _fetch_slot_entities(slot, template_ids)+ except Exception as exc:+ if slot != TemplateRefSlot.A2A_ACCESS_POLICY:+ raise+ logger.warning(+ "[enterprise_config] A2A policy load failed: resource_id=%r "+ "template_ids=%s error_type=%s",+ rid,+ template_ids,+ type(exc).__name__,+ )+ continueif entities:_apply_slot_entities(result, slot, entities)@@ -208,10 +259,9 @@ async def load_effective_enterprise_config(return Nonelogger.info(- "[enterprise_config] loaded enterprise config by resource_id=%r slots=%s payload=%s",+ "[enterprise_config] loaded enterprise config by resource_id=%r slots=%s",rid,sorted(load_slots),- result.as_dict(),)return resultdiff --git a/jiuwenswarm/server/runtime/enterprise_config/schemas.py b/jiuwenswarm/server/runtime/enterprise_config/schemas.pyindex ed18039e01..23c5181427 100644--- a/jiuwenswarm/server/runtime/enterprise_config/schemas.py+++ b/jiuwenswarm/server/runtime/enterprise_config/schemas.py@@ -20,6 +20,7 @@ class TemplateRefSlot(StrEnum):EXTENSION_CONFIG = "extension_config"MCP = "mcp"PERMISSIONS = "permissions"+ A2A_ACCESS_POLICY = "a2a_access_policy"SLOT_ENTITY_TABLE: dict[TemplateRefSlot, str] = {@@ -33,6 +34,7 @@ SLOT_ENTITY_TABLE: dict[TemplateRefSlot, str] = {TemplateRefSlot.EXTENSION_CONFIG: "extension_config_template",TemplateRefSlot.MCP: "mcp_template",TemplateRefSlot.PERMISSIONS: "permissions_template",+ TemplateRefSlot.A2A_ACCESS_POLICY: "a2a_access_policy_template",}MODEL_SLOT_KEYS = frozenset({@@ -50,6 +52,7 @@ DEFAULT_AGENT_LOAD_SLOTS = frozenset({TemplateRefSlot.EXTENSION_CONFIG,TemplateRefSlot.MCP,TemplateRefSlot.PERMISSIONS,+ TemplateRefSlot.A2A_ACCESS_POLICY,})@@ -113,6 +116,7 @@ class EffectiveEnterpriseConfig:extension_config: list[dict[str, Any]] | None = Nonemcp: list[dict[str, Any]] | None = Nonepermissions: list[dict[str, Any]] | None = None+ a2a_access_policy: list[dict[str, Any]] | None = Noneservice_id: str | None = Nonesend_file_allowed: bool = Truedebug: dict[str, Any] = field(default_factory=dict)@@ -131,6 +135,7 @@ class EffectiveEnterpriseConfig:"extension_config": self.extension_config,"mcp": self.mcp,"permissions": self.permissions,+ "a2a_access_policy": self.a2a_access_policy,"service_id": self.service_id,"send_file_allowed": self.send_file_allowed,"debug": dict(self.debug),diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.pyindex 6a1368f7c6..887fa67554 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py@@ -184,13 +184,55 @@ class RuntimeRoutedAgentClient(AgentServerClient):self._touch_interval_seconds = max(0.0, float(touch_interval_seconds))self._route_attempts = max(1, int(route_attempts))self._connected = False- # 企业版 HTTP 半双工:响应走 POST+SSE,AgentServer→Gateway 的主动 push- # (cron.response / 文件下载 / evolution 等)必须额外订阅- # GET /api/v1/events/stream。此处按 Pod(base_url)懒建订阅,对齐个人版- # WebSocketAgentServerClient 天然具备的双向 push 能力。self._on_server_push: Callable[[dict[str, Any]], Awaitable[None]] | None = None- self._push_clients: dict[str, HttpSseAgentServerClient] = {}- self._push_lock = asyncio.Lock()+ self._pod_clients: dict[str, HttpSseAgentServerClient] = {}+ self._pod_connect_lock = asyncio.Lock()+ self._rpc_origins: dict[tuple[str, str], str] = {}++ def set_server_push_handler(+ self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None+ ) -> None:+ self._on_server_push = handler++ async def _handle_pod_push(self, base_url: str, wire: dict[str, Any]) -> None:+ from jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_chunk++ handler = self._on_server_push+ if handler is None:+ return+ chunk = parse_agent_server_wire_chunk(wire)+ payload = chunk.payload if isinstance(chunk.payload, dict) else {}+ rpc = payload.get("jsonrpc", payload)+ key = None+ if isinstance(rpc, dict) and rpc.get("id") is not None and rpc.get("method"):+ key = (str(wire.get("session_id") or ""), str(rpc["id"]))+ self._rpc_origins[key] = base_url+ try:+ await handler(wire)+ except BaseException:+ if key is not None:+ self._rpc_origins.pop(key, None)+ raise++ async def _ensure_pod_push(self, base_url: str) -> None:+ if self._on_server_push is None:+ return+ async with self._pod_connect_lock:+ self._ensure_connected()+ client = self._pod_clients.get(base_url)+ if client is None:+ client = HttpSseAgentServerClient()+ client.set_server_push_handler(+ lambda wire: self._handle_pod_push(base_url, wire)+ )+ try:+ await client.connect(base_url)+ await client.wait_push_ready()+ except BaseException:+ await client.disconnect()+ raise+ self._pod_clients[base_url] = client+ await client.wait_push_ready()async def connect(self, uri: str) -> None:_ = uri@@ -203,73 +245,27 @@ class RuntimeRoutedAgentClient(AgentServerClient):async def disconnect(self) -> None:self._connected = False+ async with self._pod_connect_lock:+ clients = list(self._pod_clients.values())+ self._pod_clients.clear()+ results = await asyncio.gather(+ *(client.disconnect() for client in clients),+ return_exceptions=True,+ )+ for result in results:+ if isinstance(result, Exception):+ logger.warning("Failed to disconnect routed push client: %s", result)+ self._rpc_origins.clear()if self._owns_http:try:await self._http.disconnect()- except Exception:- logger.exception("[RuntimeRouted] 断开 HTTP 连接失败")- push_clients = list(self._push_clients.values())- self._push_clients.clear()- for client in push_clients:- try:- await client.disconnect()- except Exception:- logger.exception("[RuntimeRouted] 断开 push 订阅失败")+ except Exception as exc:+ logger.warning("Failed to disconnect HTTP client: %s", exc)if self._owns_route:try:await self._route.aclose()- except Exception:- logger.exception("[RuntimeRouted] 关闭 route 失败")-- def set_server_push_handler(- self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None- ) -> None:- """注册 AgentServer 主动推送(server_push)回调。-- 与个人版 ``WebSocketAgentServerClient.set_server_push_handler`` 语义一致,- 供 ``MessageHandler`` 注入 ``_handle_agent_server_push``。企业版经 HTTP/SSE- 通信,push 由每个 Pod 的 ``HttpSseAgentServerClient`` 单独订阅,故此处把- 回调记录并同步到已建立的订阅客户端上。- """- self._on_server_push = handler- for client in self._push_clients.values():- client.set_server_push_handler(handler)-- async def _ensure_push_subscription(self, base_url: str) -> None:- """懒建立到指定 AgentServer Pod 的 push(``GET /api/v1/events/stream``)订阅。-- 个人版 WS 天然双向,push 走同一条连接;企业版 HTTP 半双工,响应走- POST+SSE,push 必须额外订阅。首次 route 到某 Pod 时为其建一个专用- ``HttpSseAgentServerClient`` 订阅并复用;未注册回调或 Pod 已订阅则跳过。- 订阅失败不阻断业务请求(route 已成功,下次请求会重试)。- """- if self._on_server_push is None:- return- base_url = (base_url or "").strip().rstrip("/")- if not base_url or base_url in self._push_clients:- return- async with self._push_lock:- if base_url in self._push_clients:- return- push_client = HttpSseAgentServerClient()- try:- await push_client.connect(base_url)- push_client.set_server_push_handler(self._on_server_push)- except Exception:- logger.exception(- "[RuntimeRouted] 建立 push 订阅失败,跳过: base_url=%s",- base_url,- )- try:- await push_client.disconnect()- except Exception:- logger.exception(- "[RuntimeRouted] 断开失败的 push 订阅时出错: base_url=%s",- base_url,- )- return- self._push_clients[base_url] = push_client- logger.info("[RuntimeRouted] 已建立 push 订阅: base_url=%s", base_url)+ except Exception as exc:+ logger.warning("Failed to close route client: %s", exc)def _ensure_connected(self) -> None:if not self._connected:@@ -285,6 +281,16 @@ class RuntimeRoutedAgentClient(AgentServerClient):async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:self._ensure_connected()+ if envelope.method == "acp.tool_response":+ params = envelope.params or {}+ key = (+ str(envelope.session_id or params.get("session_id") or ""),+ str(params.get("jsonrpc_id") or ""),+ )+ base_url = self._rpc_origins.pop(key, None)+ if base_url is None:+ raise RuntimeError("Reverse RPC origin Pod is unavailable")+ return await self._http.send_request(envelope, base_url=base_url)if _is_heartbeat_envelope(envelope):return self._heartbeat_response(envelope)# 对齐旧 RuntimeManagement:发 Agent 前补齐并 MD5 service/agent/workspace。@@ -300,8 +306,8 @@ class RuntimeRoutedAgentClient(AgentServerClient):request_id=request_id,user_id=user_id,)- await self._ensure_push_subscription(base_url)try:+ await self._ensure_pod_push(base_url)result = await self._http.send_request(envelope, base_url=base_url)except Exception as exc:if not _is_http_retryable(exc):@@ -318,7 +324,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):request_id=uuid.uuid4().hex,user_id=user_id,)- await self._ensure_push_subscription(base_url)+ await self._ensure_pod_push(base_url)result = await self._http.send_request(envelope, base_url=base_url)await self._touch_quiet(session_id, route_id)return result@@ -351,7 +357,6 @@ class RuntimeRoutedAgentClient(AgentServerClient):request_id=request_id,user_id=user_id,)- await self._ensure_push_subscription(base_url)yielded = 0try:async for chunk in self._stream_with_touch(@@ -374,7 +379,6 @@ class RuntimeRoutedAgentClient(AgentServerClient):request_id=uuid.uuid4().hex,user_id=user_id,)- await self._ensure_push_subscription(base_url)async for chunk in self._stream_with_touch(envelope, base_url=base_url, session_id=session_id, route_id=route_id):@@ -391,6 +395,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):route_id: str,) -> AsyncIterator[AgentResponseChunk]:last_touch = time.monotonic()+ await self._ensure_pod_push(base_url)async for chunk in self._http.send_request_stream(envelope, base_url=base_url):now = time.monotonic()if (diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pyindex 41e3a056c1..fe3989d160 100644--- a/tests/agents/swarm/test_swarm_assembly.py+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -19,6 +19,8 @@ touching a real LLM, the network, or a live ``DeepAgent``:from __future__ import annotationsimport inspect+import asyncio+import contextvarsimport jsonimport loggingimport types@@ -144,11 +146,46 @@ def test_team_a2a_outbound_rail_uses_live_route_when_context_session_is_empty(assert rail._runtime_route() == ("live-session", "live-channel")-def test_team_a2a_outbound_rail_is_excluded_from_enterprise_runtime(monkeypatch) -> None:+def test_team_a2a_outbound_rail_keeps_enterprise_resource(monkeypatch) -> None:monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")- context = SwarmBuildContext(session_id="session-a2a", channel="web")+ context = SwarmBuildContext(session_id="session-a2a", channel="web", request_metadata={"routing": {"bot_id": "resource-1"}})- assert member_rails._build_a2a_outbound_toolkit_rail({}, context) is None+ rail = member_rails._build_a2a_outbound_toolkit_rail({}, context)+ assert contextvars.Context().run(rail._runtime_resource_id) == "resource-1"++[email protected]("mode", ["team", "team.plan", "code.team"])+async def test_team_a2a_tools_keep_resource_in_empty_context(mode):+ context = SwarmBuildContext(session_id="session-a2a", channel="web", mode=mode,+ request_metadata={"routing": {"bot_id": "resource-1"}})+ rail = member_rails._build_a2a_outbound_toolkit_rail({}, context)+ tools = {}+ async def call(method, params, **route):+ return {"params": params, **route}+ rail._backend_provider = lambda: SimpleNamespace(ready=True, call=call)+ rail.init(SimpleNamespace(ability_manager=SimpleNamespace(+ add_ability=lambda card, tool: tools.update({card.name: tool})), system_prompt_builder=None))+ for name, params in (+ ("a2a_find_agents", {}),+ ("a2a_dispatch_task", {"agent_id": "weather", "task": "weather", "mode": "sync"}),+ ("a2a_get_dispatch", {"dispatch_id": "dispatch-1"}),+ ):+ result = await asyncio.create_task(tools[name].invoke(params), context=contextvars.Context())+ assert result["session_id"] == "session-a2a"+ assert result["params"]["resource_id"] == "resource-1"+++def test_team_a2a_live_session_does_not_borrow_build_identity():+ rail = member_rails._build_a2a_outbound_toolkit_rail({}, SwarmBuildContext(+ session_id="old", request_metadata={"routing": {"bot_id": "old-resource"}}))+ def check():+ interface_deep._CRON_TOOL_SESSION_ID.set("new")+ interface_deep._RUNTIME_TOOL_RESOURCE_ID.set("")+ assert rail._runtime_resource_id() == ""+ interface_deep._RUNTIME_TOOL_RESOURCE_ID.set("new-resource")+ assert rail._runtime_resource_id() == "new-resource"+ contextvars.Context().run(check)# Rail provider names shared by both roles (no role-specific evolution rails).# Harness todo planning is teammate-only; leaders use the team task board instead.diff --git a/tests/unit_tests/agentserver/test_code_adapter_a2a_outbound_rail.py b/tests/unit_tests/agentserver/test_code_adapter_a2a_outbound_rail.pyindex dae40c62e3..68f15516f4 100644--- a/tests/unit_tests/agentserver/test_code_adapter_a2a_outbound_rail.py+++ b/tests/unit_tests/agentserver/test_code_adapter_a2a_outbound_rail.py@@ -54,6 +54,6 @@ def test_code_team_modes_exclude_adapter_owned_a2a_outbound_rail(sub_mode):assert "_a2a_outbound_toolkit_rail" not in _rail_attr_names(sub_mode=sub_mode)-def test_enterprise_code_mode_excludes_a2a_outbound_rail(monkeypatch):+def test_enterprise_code_mode_includes_a2a_outbound_rail(monkeypatch):monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")- assert "_a2a_outbound_toolkit_rail" not in _rail_attr_names(sub_mode="normal")+ assert "_a2a_outbound_toolkit_rail" in _rail_attr_names(sub_mode="normal")diff --git a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.pyindex 545ef98798..86e30571a2 100644--- a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py+++ b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py@@ -95,6 +95,92 @@ def test_a2a_tool_route_survives_background_task_context(assert adapter._get_a2a_outbound_tool_route() == ("web-session", "web")[email protected]("tool_name, params", [+ ("a2a_find_agents", {"query": ""}),+ ("a2a_dispatch_task", {"agent_id": "weather", "task": "weather", "mode": "sync"}),+ ("a2a_get_dispatch", {"dispatch_id": "dispatch-1"}),+])+async def test_a2a_resource_survives_preexisting_runner_task(tool_name, params):+ """A runner created before request binding must use its adapter's identity."""+ ready = asyncio.Event()+ adapters = [_make_adapter(_current_request_route={}) for _ in range(2)]++ async def invoke(adapter):+ await ready.wait()+ tools = {}++ async def call(method, payload, **route):+ return {"params": payload, **route}++ rail = adapter._build_a2a_outbound_toolkit_rail()+ rail._backend_provider = lambda: SimpleNamespace(ready=True, call=call)+ rail.init(SimpleNamespace(+ ability_manager=SimpleNamespace(add_ability=lambda card, tool: tools.update({card.name: tool})),+ system_prompt_builder=None,+ ))+ return await tools[tool_name].invoke(params)++ runners = [+ asyncio.create_task(invoke(adapter), context=contextvars.Context())+ for adapter in adapters+ ]+ for index, adapter in enumerate(adapters):+ adapter._current_request_route = {+ "session_id": f"session-{index}", "channel_id": "web",+ "resource_id": f"bot-{index}",+ }+ ready.set()+ results = await asyncio.gather(*runners)+ for index, result in enumerate(results):+ assert result["session_id"] == f"session-{index}"+ assert result["params"]["resource_id"] == f"bot-{index}"+++def test_a2a_bound_identity_does_not_borrow_snapshot_resource():+ adapter = _make_adapter(_current_request_route={+ "session_id": "old-session", "resource_id": "old-bot",+ })++ def check():+ interface_deep._CRON_TOOL_SESSION_ID.set("new-session")+ interface_deep._RUNTIME_TOOL_RESOURCE_ID.set("")+ assert adapter._get_a2a_outbound_tool_resource_id() == ""+ interface_deep._RUNTIME_TOOL_RESOURCE_ID.set("new-bot")+ assert adapter._get_a2a_outbound_tool_resource_id() == "new-bot"++ contextvars.Context().run(check)+++def test_a2a_snapshot_missing_resource_does_not_borrow_cron_identity():+ adapter = _make_adapter(+ _current_request_route={"session_id": "new-session"},+ _runtime_cron_tool_context=SimpleNamespace(metadata={"routing": {"bot_id": "old-bot"}}),+ )+ assert contextvars.Context().run(adapter._get_a2a_outbound_tool_resource_id) == ""++[email protected]("mode", ["team", "team.plan", "code.team"])+def test_deep_team_modes_leave_a2a_rail_to_swarm_provider(mode: str) -> None:+ adapter = _make_adapter(+ _model=None,+ _config_cache={},+ _filesystem_rail=None,+ _skill_protocol_prompt_rail=None,+ _task_execution_rail=None,+ )+ adapter._filesystem_rail_enabled_for_profile = lambda: False+ adapter._skill_include_tools_for_profile = lambda: True+ adapter._task_execution_rail_enabled = lambda: False+ adapter._instantiate_rails = lambda rail_infos, _config: rail_infos++ rail_infos = adapter._build_agent_rails({}, {}, mode=mode)++ assert "_a2a_outbound_toolkit_rail" not in {+ info.attr_name for info in rail_infos+ }++def _make_message_adapter(monkeypatch: pytest.MonkeyPatch) -> JiuWenSwarmDeepAdapter:adapter = JiuWenSwarmDeepAdapter()adapter._instance = SimpleNamespace(get_context_usage=lambda **_kwargs: {})@@ -106,6 +192,89 @@ def _make_message_adapter(monkeypatch: pytest.MonkeyPatch) -> JiuWenSwarmDeepAdareturn adapter[email protected]("params_only", [False, True])+async def test_team_stream_binds_a2a_resource_context(+ monkeypatch: pytest.MonkeyPatch, params_only: bool,+) -> None:+ from jiuwenswarm.server.runtime.agent_adapter import team_helpers+ from jiuwenswarm.server.runtime import tenant_agent_pool++ adapter = _make_message_adapter(monkeypatch)+ adapter._deepresearch_rewrite_tx_uncertain = False+ adapter._config_cache = {}+ adapter._config_base_cache = {}+ adapter._runtime_prompt_rail = None+ adapter._project_dir = None+ adapter._workspace_dir = None+ monkeypatch.setattr(adapter, "_inject_extension_config_into_inputs", lambda _inputs: None)+ monkeypatch.setattr(adapter, "_try_skill_turbo_resume", AsyncMock(return_value=None))+ monkeypatch.setattr(adapter, "_arm_skill_turbo_interrupt_recovery_hint", AsyncMock())+ monkeypatch.setattr(adapter, "_deepresearch_artifact_output_dir", lambda _path: None)+ monkeypatch.setattr(+ adapter, "_prepare_multimodal_image_inputs", lambda _request, inputs: inputs+ )+ monkeypatch.setattr(adapter, "_native_image_input_enabled", lambda *_args: False)+ monkeypatch.setattr(+ adapter,+ "_prepare_react_image_tool_prompt",+ lambda _request, inputs, **_kwargs: inputs,+ )+ monkeypatch.setattr(adapter, "_resolve_runtime_language", lambda: "zh")+ monkeypatch.setattr(adapter, "_resolve_prompt_channel", lambda _session: "web")+ monkeypatch.setattr(adapter, "_write_runtime_state", lambda **_kwargs: None)+ monkeypatch.setattr(interface_deep, "set_perf_summary_context", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(interface_deep, "finalize_perf_summary_request", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(interface_deep, "clear_perf_summary_context", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(interface_deep, "resolve_tenant_sessions_dir", lambda _key: Path("."))+ monkeypatch.setattr(interface_deep, "evolution_slash_command_name", lambda _query: None)+ monkeypatch.setattr(+ tenant_agent_pool.TenantAgentPool,+ "extract_ids",+ staticmethod(lambda _request: ("agent", "service", "workspace")),+ )++ async def _team_stream(*_args, **_kwargs):+ assert interface_deep.get_runtime_tool_resource_id() == "resource-1"+ assert contextvars.Context().run(adapter._get_a2a_outbound_tool_resource_id) == "resource-1"+ yield SimpleNamespace(payload={"event_type": "chat.delta"})++ monkeypatch.setattr(team_helpers, "process_team_message_stream", _team_stream)+ request = AgentRequest(+ request_id="request-team",+ channel_id="web",+ session_id="session-team",+ is_stream=True,+ params={"query": "delegate", "mode": "team", "bot_id": "resource-1" if params_only else "untrusted"},+ metadata={} if params_only else {"routing": {"bot_id": "resource-1"}},+ )++ chunks = [+ chunk+ async for chunk in adapter.process_message_stream_impl(+ request, {"query": "delegate"}+ )+ ]++ assert len(chunks) == 1+ assert interface_deep.get_runtime_tool_resource_id() == ""++[email protected]("params_only", [False, True])+async def test_nonstream_entry_captures_a2a_resource_snapshot(monkeypatch, params_only):+ adapter = _make_message_adapter(monkeypatch)+ monkeypatch.setattr(adapter, "_deepresearch_artifact_output_dir", lambda _path: "")+ monkeypatch.setattr(adapter, "_handle_slash_command", AsyncMock(return_value={"result_type": "goal_control"}))+ request = AgentRequest(+ request_id="snapshot-request", channel_id="web", session_id="snapshot-session",+ params={"query": "test", "mode": "agent", "bot_id": "resource-1" if params_only else "untrusted"},+ metadata={} if params_only else {"routing": {"bot_id": "resource-1"}},+ )+ await adapter.process_message_impl(request, {"query": "test"})+ assert contextvars.Context().run(adapter._get_a2a_outbound_tool_resource_id) == "resource-1"++def _route_test_request(*, stream: bool = False) -> AgentRequest:return AgentRequest(request_id="req-pre-try",@@ -655,6 +824,33 @@ def test_runtime_route_binds_current_session_workspace(tmp_path: Path) -> None:adapter._reset_runtime_cron_context(tokens)+def test_runtime_route_binds_and_resets_enterprise_a2a_identity() -> None:+ enterprise = SimpleNamespace(+ resource_id="resource-1",+ template_ref={"a2a_access_policy": ["policy-1"]},+ )+ adapter = _make_adapter(+ _enterprise_config=enterprise,+ _env_service_id="service-1",+ _env_agent_id="agent-1",+ )+ tokens = adapter._bind_runtime_cron_context(+ channel_id="web",+ session_id="session-1",+ metadata={"routing": {"bot_id": "resource-1"}},+ request_id="request-1",+ mode="agent",+ )+ try:+ assert interface_deep.get_runtime_tool_resource_id() == "resource-1"+ assert interface_deep.get_runtime_tool_a2a_policy_id() == "policy-1"+ finally:+ adapter._reset_runtime_cron_context(tokens)++ assert interface_deep.get_runtime_tool_resource_id() == ""+ assert interface_deep.get_runtime_tool_a2a_policy_id() == ""++def test_deepresearch_tool_context_keeps_session_workspace_snapshot(tmp_path: Path,) -> None:diff --git a/tests/unit_tests/agentserver/test_enterprise_policy.py b/tests/unit_tests/agentserver/test_enterprise_policy.pyindex e9cdc95f7a..fab68610cd 100644--- a/tests/unit_tests/agentserver/test_enterprise_policy.py+++ b/tests/unit_tests/agentserver/test_enterprise_policy.py@@ -247,6 +247,102 @@ def test_embedding_slot_is_loaded_separately_from_model_slots() -> None:assert TemplateRefSlot.EMBEDDING_MODEL not in MODEL_SLOT_KEYS+async def test_a2a_policy_slot_loads_by_policy_id(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jiuwenswarm.server.runtime.enterprise_config import db_queries++ captured: dict[str, object] = {}++ async def _list_records(+ table: str,+ *,+ filters: dict | None = None,+ order_by: str = "",+ ) -> list[dict]:+ captured.update(table=table, filters=filters, order_by=order_by)+ return [{"policy_id": "policy-1", "enabled": True}]++ monkeypatch.setattr(db_queries, "list_records", _list_records)+ result = await db_queries.fetch_template_by_slot(+ "a2a_access_policy", "policy-1"+ )++ assert result == {"policy_id": "policy-1", "enabled": True}+ assert captured["table"] == "a2a_access_policy_template"+ assert captured["filters"] == {"enabled": True, "policy_id": ["policy-1"]}+++async def test_a2a_policy_load_failure_keeps_other_enterprise_slots(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jiuwenswarm.common.schema.agent import AgentRequest+ from jiuwenswarm.server.runtime.enterprise_config import db_queries+ from jiuwenswarm.server.runtime.enterprise_config.loader import (+ load_effective_enterprise_config,+ )+ from jiuwenswarm.server.runtime.enterprise_config.schemas import TemplateRefSlot++ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")++ async def _list_records(table, *, filters=None, order_by=""):+ del filters, order_by+ if table == "instance_agent_resource":+ return [{"resource_id": "resource-1", "ref_template_id": "agent-1"}]+ if table == "agent_template":+ return [+ {+ "template_id": "agent-1",+ "enabled": True,+ "template_ref": {+ "default_model": ["model-1"],+ "a2a_access_policy": ["policy-1"],+ },+ }+ ]+ return []++ async def _fetch_templates(slot, template_ids):+ if slot == TemplateRefSlot.A2A_ACCESS_POLICY:+ raise RuntimeError("policy table unavailable")+ return [{"template_id": template_ids[0], "model_id": template_ids[0]}]++ monkeypatch.setattr(db_queries, "list_records", _list_records)+ monkeypatch.setattr(db_queries, "fetch_templates_by_slot", _fetch_templates)+ request = AgentRequest(+ request_id="request-1",+ params={},+ metadata={"routing": {"bot_id": "resource-1"}},+ )++ loaded = await load_effective_enterprise_config(+ request,+ {TemplateRefSlot.DEFAULT_MODEL, TemplateRefSlot.A2A_ACCESS_POLICY},+ )++ assert loaded is not None+ assert loaded.models["default_model"][0]["model_id"] == "model-1"+ assert loaded.a2a_access_policy is None+++def test_a2a_policy_slot_requires_one_literal_reference() -> None:+ from jiuwenswarm.server.runtime.enterprise_config.loader import (+ _literal_slot_template_id_map,+ )++ assert _literal_slot_template_id_map(+ {"a2a_access_policy": ["policy-1"]}+ ) == {"a2a_access_policy": ["policy-1"]}+ assert _literal_slot_template_id_map(+ {"a2a_access_policy": ["policy-1", "policy-2"]}+ ) == {}+ assert _literal_slot_template_id_map(+ {"a2a_access_policy": ["${user::policy}"]}+ ) == {}++def test_image_gen_slot_is_registered_as_model_slot() -> None:from jiuwenswarm.server.runtime.enterprise_config.apply_models import (SLOT_TO_CONFIG_KEY,diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.pyindex 9a57642517..5c8e06b8e9 100644--- a/tests/unit_tests/agentserver/test_team_helpers.py+++ b/tests/unit_tests/agentserver/test_team_helpers.py@@ -1416,6 +1416,7 @@ async def test_process_team_message_stream_handles_team_evolve_list(monkeypatch,request_id="req-team-stream",channel_id="web",metadata=None,+ params={"bot_id": "cron-resource"},)inputs = {"query": "/evolve_list demo-skill"}@@ -1444,6 +1445,7 @@ async def test_process_team_message_stream_handles_team_evolve_list(monkeypatch,assert captured_specassert captured_context[0]["config_base"] == {"models": {"defaults": []}}assert captured_context[0]["sessions_root"] == tmp_path / "tenant-sessions"+ assert captured_context[0]["request_metadata"]["routing"]["bot_id"] == "cron-resource"@pytest.mark.anyiodiff --git a/tests/unit_tests/gateway/test_a2a_manager.py b/tests/unit_tests/gateway/test_a2a_manager.pyindex 73b5cb43a8..61c282135a 100644--- a/tests/unit_tests/gateway/test_a2a_manager.py+++ b/tests/unit_tests/gateway/test_a2a_manager.py@@ -18,6 +18,10 @@ from jiuwenswarm.gateway.a2a_manager import config as a2a_config_modulefrom jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import (A2ADependencyMissingError,)+from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2AOutboundError,+ A2AOutboundErrorCode,+)class _ChannelManagerProbe:@@ -910,3 +914,114 @@ async def test_failed_credential_persistence_keeps_saved_and_effective_values():await manager.update({"credential": "test-replacement-credential"}, apply=True)assert manager._config == originalassert manager.snapshot().config_revision == 0+++async def test_enterprise_outbound_tools_enforce_resource_policy(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")++ class _Registry:+ async def resolve_effective_a2a_agent_ids(self, resource_id):+ assert resource_id == "resource-1"+ return frozenset({"agent-1"})++ async def resolve_authorized_a2a_agent_ids(self, resource_id):+ assert resource_id == "resource-1"+ return frozenset({"agent-1", "agent-manager", "agent-user"})++ async def list_agents(self):+ return {+ "items": [{"agent_id": "agent-1"}, {"agent_id": "agent-2"}],+ "total": 2,+ }++ async def get_agent(self, agent_id):+ return {+ "agent_id": agent_id,+ "manager_enabled": agent_id != "agent-manager",+ "user_enabled": agent_id != "agent-user",+ }++ async def set_user_enabled(self, agent_id, enabled):+ return {"agent_id": agent_id, "user_enabled": enabled}++ class _Dispatcher:+ async def find_agents(self, **kwargs):+ return kwargs++ async def dispatch(self, **kwargs):+ return kwargs++ async def query_dispatch(self, dispatch_id, **kwargs):+ return {"dispatch_id": dispatch_id, **kwargs}++ manager = object.__new__(A2AManager)+ manager._outbound = _Registry()+ manager._outbound_dispatcher = _Dispatcher()++ found = await manager.outbound_find_agents(source_resource_id="resource-1")+ assert found["allowed_agent_ids"] == frozenset({"agent-1"})+ listed = await manager.outbound_list(source_resource_id="resource-1")+ assert listed == {"items": [{"agent_id": "agent-1"}], "total": 1}+ dispatched = await manager.outbound_dispatch_task(+ agent_id="agent-1",+ task="work",+ mode="sync",+ source_session_id="session-1",+ source_resource_id="resource-1",+ )+ assert dispatched["source_resource_id"] == "resource-1"+ queried = await manager.outbound_get_dispatch(+ dispatch_id="dispatch-1",+ source_session_id="session-1",+ source_resource_id="resource-1",+ )+ assert queried["source_resource_id"] == "resource-1"++ with pytest.raises(A2AOutboundError) as exc_info:+ await manager.outbound_get_dispatch(+ dispatch_id="dispatch-1",+ source_session_id="session-1",+ source_resource_id="",+ )+ assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED++ with pytest.raises(A2AOutboundError) as exc_info:+ await manager.outbound_dispatch_get(+ "dispatch-1",+ source_session_id="session-1",+ source_resource_id=None,+ )+ assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED++ with pytest.raises(A2AOutboundError) as exc_info:+ await manager.outbound_dispatch_task(+ agent_id="agent-2",+ task="work",+ mode="sync",+ source_session_id="session-1",+ source_resource_id="resource-1",+ )+ assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED++ for agent_id, expected_code in (+ ("agent-manager", A2AOutboundErrorCode.AGENT_MANAGER_DISABLED),+ ("agent-user", A2AOutboundErrorCode.AGENT_USER_DISABLED),+ ):+ with pytest.raises(A2AOutboundError) as exc_info:+ await manager.outbound_dispatch_task(+ agent_id=agent_id,+ task="work",+ mode="sync",+ source_session_id="session-1",+ source_resource_id="resource-1",+ )+ assert exc_info.value.code is expected_code++ with pytest.raises(A2AOutboundError) as exc_info:+ await manager.outbound_set_user_enabled(+ "agent-2", enabled=True, source_resource_id="resource-1"+ )+ assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZEDdiff --git a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.pyindex a15752da86..a832eb5a07 100644--- a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py+++ b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py@@ -404,6 +404,40 @@ async def test_a2a_outbound_user_enabled_requires_boolean():assert channel.responses[-1]["code"] == "A2A_OUTBOUND_STORE_INVALID"+async def test_enterprise_dispatch_get_passes_trusted_resource_scope(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ channel = _WebChannelProbe()+ calls = []++ class _Manager:+ outbound_available = True++ async def outbound_dispatch_get(self, dispatch_id, **kwargs):+ calls.append((dispatch_id, kwargs))+ return {"dispatch_id": dispatch_id}++ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=_Manager()))+ await channel.methods["a2a.outbound.dispatch.get"](+ object(),+ "dispatch-get",+ {"dispatch_id": "dispatch-1", "bot_id": "resource-1"},+ "session-1",+ )++ assert calls == [+ (+ "dispatch-1",+ {+ "source_session_id": "session-1",+ "source_resource_id": "resource-1",+ },+ )+ ]++@pytest.mark.asyncio@pytest.mark.parametrize("params", [{"agent_id": "agent-1"}, {"agent_id": "agent-1", "accept": "false"}]diff --git a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.pyindex e3eb7c6651..a41164b6e7 100644--- a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py+++ b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py@@ -233,6 +233,52 @@ async def _dispatcher(client: _FakeClient):)+async def test_dispatch_client_applies_template_network_policy(monkeypatch):+ import httpx+ from jiuwenswarm.gateway.a2a_manager.outbound import dispatcher as module++ async def resolver(host, port):+ return ["192.168.1.27"]++ pinned = []+ clients = []++ def transport(addresses):+ pinned.append(addresses)+ return httpx.MockTransport(lambda request: httpx.Response(200))++ class Factory:+ def __init__(self, config):+ clients.append(config.httpx_client)++ def create(self, card):+ return _FakeClient()++ monkeypatch.setattr(module, "create_pinned_transport", transport)+ monkeypatch.setattr(module, "ClientFactory", Factory)+ agent = _agent()+ interface = A2ACompatibleInterface("JSONRPC", "1.0.0", "http://weather.example.com/a2a")+ agent = replace(agent, selected_interface=interface, network_policy={+ "allow_http": True, "allow_private_network": True,+ }, agent_card={**agent.agent_card, "version": "1.0.0", "capabilities": {},+ "url": interface.url, "preferredTransport": "JSONRPC", "protocolVersion": "1.0.0"})+ dispatcher = A2AOutboundDispatcher(+ A2AOutboundRepository(InMemoryPersistentBackend()),+ discovery_service=A2AOutboundDiscoveryService(address_resolver=resolver),+ )+ try:+ await dispatcher._build_client(agent)+ assert pinned == [{"weather.example.com": "192.168.1.27"}]+ with pytest.raises(A2AOutboundError) as error:+ await dispatcher._build_client(replace(agent, network_policy={}))+ assert error.value.code is A2AOutboundErrorCode.DISCOVERY_BLOCKED+ assert len(pinned) == 1+ finally:+ for client in clients:+ await client.aclose()++@pytest.mark.asyncioasync def test_find_agents_returns_only_callable_minimal_catalog() -> None:client = _FakeClient()@@ -257,6 +303,17 @@ async def test_find_agents_returns_only_callable_minimal_catalog() -> None:] == []+async def test_find_agents_applies_enterprise_allowed_set_before_counting() -> None:+ dispatcher, _ = await _dispatcher(_FakeClient())++ result = await dispatcher.find_agents(allowed_agent_ids=frozenset())++ assert result["items"] == []+ assert result["total"] == 0+ assert result["total_matches"] == 0++@pytest.mark.asyncioasync def test_find_agents_natural_language_ranks_without_hiding_catalog() -> None:dispatcher, repository = await _dispatcher(_FakeClient())@@ -829,9 +886,13 @@ async def test_cancellation_uses_remote_cancel_result_when_available() -> None:@pytest.mark.asyncioasync def test_dispatch_query_is_scoped_to_originating_session() -> None:client = _FakeClient([_task_event(TaskState.TASK_STATE_SUBMITTED)])- dispatcher, _ = await _dispatcher(client)+ dispatcher, repository = await _dispatcher(client)accepted = await dispatcher.dispatch(- agent_id="agent-1", task="work", mode="async", source_session_id="s1"+ agent_id="agent-1",+ task="work",+ mode="async",+ source_session_id="s1",+ source_resource_id="resource-1",)with pytest.raises(A2AOutboundError) as error:@@ -840,12 +901,32 @@ async def test_dispatch_query_is_scoped_to_originating_session() -> None:)assert error.value.code is A2AOutboundErrorCode.DISPATCH_NOT_FOUND+ repository.manager_owned = True+ with pytest.raises(A2AOutboundError) as error:+ await dispatcher.query_dispatch(+ accepted["dispatch_id"], source_session_id="s1"+ )+ assert error.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED++ with pytest.raises(A2AOutboundError) as error:+ await dispatcher.query_dispatch(+ accepted["dispatch_id"],+ source_session_id="s1",+ source_resource_id="resource-2",+ )+ assert error.value.code is A2AOutboundErrorCode.DISPATCH_NOT_FOUND+class _Backend:ready = Trueasync def call(self, method, params, *, session_id, channel_id):- return {"method": method, "session_id": session_id, "channel_id": channel_id}+ return {+ "method": method,+ "params": params,+ "session_id": session_id,+ "channel_id": channel_id,+ }class _AbilityManager:@@ -992,18 +1073,24 @@ def test_real_agent_builders_expose_no_a2a_tools_without_gateway(monkeypatch, ki@pytest.mark.asyncioasync def test_toolkit_binds_session_and_exposes_no_url_or_credentials() -> None:- toolkit = A2AOutboundToolkit(_Backend(), runtime_route=lambda: ("session-1", "web"))+ toolkit = A2AOutboundToolkit(+ _Backend(),+ runtime_route=lambda: ("session-1", "web"),+ runtime_resource_id=lambda: "resource-1",+ )result = await toolkit.dispatch_task("agent-1", "task", "sync")tools = {tool.card.name: tool for tool in toolkit.get_tools()}find_tool = tools["a2a_find_agents"]dispatch_tool = tools["a2a_dispatch_task"]assert result["session_id"] == "session-1"+ assert result["params"]["resource_id"] == "resource-1"assert "query only ranks candidates" in find_tool.card.descriptionassert find_tool.card.input_params["properties"]["query"]["default"] == ""assert find_tool.card.input_params["properties"]["required_skills"]["default"] == []assert find_tool.card.input_params["additionalProperties"] is Falseproperties = dispatch_tool.card.input_params["properties"]+ assert "resource_id" not in propertiesassert not ({"url", "headers", "credential", "timeout"} & set(properties))@@ -1210,6 +1297,89 @@ async def test_gateway_bridge_handles_canonical_acp_output_request_wire() -> Nonassert replies[0].params["response"]["result"]["total"] == 1+async def test_enterprise_gateway_bridge_binds_trusted_resource_id(monkeypatch) -> None:+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ calls = []++ class _Manager:+ async def outbound_find_agents(self, **kwargs):+ calls.append(kwargs)+ return {"items": [], "total": 0}++ handler = object.__new__(MessageHandler)+ handler._a2a_outbound_tool_manager = _Manager()+ replies = []++ async def publish(message):+ replies.append(message)++ handler.publish_user_messages = publish+ chunk = SimpleNamespace(+ payload={+ "jsonrpc": "2.0",+ "id": "rpc-enterprise",+ "method": A2A_TOOL_FIND_AGENTS,+ "params": {"resource_id": "resource-1"},+ },+ channel_id="web",+ )++ await handler._handle_a2a_outbound_tool_push(+ chunk=chunk,+ session_id="session-1",+ request_metadata={"routing": {"bot_id": "resource-1"}},+ )++ assert calls[0]["source_resource_id"] == "resource-1"+ assert replies[0].params["response"]["result"]["total"] == 0+++async def test_enterprise_gateway_bridge_rejects_mismatched_resource_id(+ monkeypatch,+) -> None:+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ diagnostics = []+ monkeypatch.setattr(+ "jiuwenswarm.gateway.message_handler.message_handler.logger.warning",+ lambda message, *args: diagnostics.append(message % args),+ )++ class _Manager:+ async def outbound_find_agents(self, **kwargs):+ raise AssertionError(kwargs)++ handler = object.__new__(MessageHandler)+ handler._a2a_outbound_tool_manager = _Manager()+ replies = []++ async def publish(message):+ replies.append(message)++ handler.publish_user_messages = publish+ chunk = SimpleNamespace(+ payload={+ "jsonrpc": "2.0",+ "id": "rpc-enterprise",+ "method": A2A_TOOL_FIND_AGENTS,+ "params": {"resource_id": "resource-other"},+ },+ channel_id="web",+ )++ await handler._handle_a2a_outbound_tool_push(+ chunk=chunk,+ session_id="session-1",+ request_metadata={"routing": {"bot_id": "resource-1"}},+ )++ error = replies[0].params["response"]["error"]+ assert error["data"]["code"] == A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED.value+ assert "gateway_bot_id='resource-1'" in diagnostics[0]+ assert "tool_resource_id='resource-other'" in diagnostics[0]++@pytest.mark.asyncioasync def test_all_a2a_tools_reverse_rpc_round_trip_complete_original_futures(monkeypatch,diff --git a/tests/unit_tests/gateway/test_a2a_outbound_management.py b/tests/unit_tests/gateway/test_a2a_outbound_management.pyindex 6d4f46bdaa..73bacf7f29 100644--- a/tests/unit_tests/gateway/test_a2a_outbound_management.py+++ b/tests/unit_tests/gateway/test_a2a_outbound_management.py@@ -476,6 +476,48 @@ async def test_discovery_blocks_private_and_plain_http_targets() -> None:assert plain_error.value.code is A2AOutboundErrorCode.DISCOVERY_BLOCKED[email protected]("address,scheme,policy,allowed", [+ ("192.168.1.27", "http", {"allow_http": True, "allow_private_network": True}, True),+ ("192.168.1.27", "http", {"allow_private_network": True}, False),+ ("192.168.1.27", "http", {"allow_http": True}, False),+ ("10.0.0.8", "https", {"allow_private_network": True}, True),+ ("127.0.0.1", "http", {"allow_http": True, "allow_private_network": True}, False),+ ("127.0.0.1", "http", {"allow_http": True, "allow_loopback": True}, True),+ ("93.184.216.34", "https", {}, True),+ ("93.184.216.34", "http", {"allow_http": True}, False),+ ("93.184.216.34", "http", {"allow_http": True, "allow_public_http": True}, True),+ ("169.254.169.254", "http", {"allow_http": True, "allow_private_network": True}, False),+ ("0.0.0.0", "https", {"allow_private_network": True}, False),+ ("2001:4860:4860::8888", "https", {}, True),+ ("2001:4860:4860::8888", "http", {}, False),+ ("fc00::1", "https", {"allow_private_network": True}, False),+ ("::ffff:192.168.1.1", "https", {"allow_private_network": True}, False),+ ("::1", "http", {"allow_http": True, "allow_loopback": True}, True),+ (["2001:4860:4860::8888", "93.184.216.34"], "https", {}, True),+ (["93.184.216.34", "192.168.1.27"], "https", {"allow_private_network": True}, False),+ (["2001:4860:4860::8888", "192.168.1.27"], "https", {"allow_private_network": True}, False),+])+async def test_enterprise_network_policy(address, scheme, policy, allowed):+ addresses = address if isinstance(address, list) else [address]++ async def resolver(host, port):+ return addresses++ service = A2AOutboundDiscoveryService(address_resolver=resolver, allow_loopback_http=True)+ if allowed:+ target = await service.validate_network_target(+ f"{scheme}://weather.example.com/a2a", network_policy=policy+ )+ assert target.pinned_address == addresses[0]+ else:+ with pytest.raises(A2AOutboundError) as error:+ await service.validate_network_target(+ f"{scheme}://weather.example.com/a2a", network_policy=policy+ )+ assert error.value.code is A2AOutboundErrorCode.DISCOVERY_BLOCKED++@pytest.mark.asyncioasync def test_network_validation_accepts_case_insensitive_https_scheme() -> None:async def public_resolver(host: str, port: int) -> list[str]:diff --git a/tests/unit_tests/gateway/test_enterprise_a2a_web_gate.py b/tests/unit_tests/gateway/test_enterprise_a2a_web_gate.pyindex ee8deaf685..18e17ee487 100644--- a/tests/unit_tests/gateway/test_enterprise_a2a_web_gate.py+++ b/tests/unit_tests/gateway/test_enterprise_a2a_web_gate.py@@ -1,6 +1,57 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-from jiuwenswarm.gateway.channel_manager.web import invoke as web_invoke+import asyncio+import socket++import httpx+import pytest++from jiuwenswarm.gateway import app_gateway+from jiuwenswarm.gateway.a2a_manager import A2AIngressConfig, A2AIngressError, A2AManager+from jiuwenswarm.gateway.a2a_manager import manager as a2a_manager_module+from jiuwenswarm.gateway.channel_manager.web import (+ app_web_handlers,+ invoke as web_invoke,+ web_http_app,+)+++class _WebChannelProbe:+ def __init__(self) -> None:+ self.methods = {}++ def register_method(self, name, handler) -> None:+ self.methods[name] = handler++ def on_connect(self, handler) -> None:+ self.on_connect_handler = handler+++class _IngressManagerProbe:+ def __init__(self) -> None:+ self.started = False++ async def start_from_config(self) -> None:+ self.started = True+++class _ConfigRepositoryProbe:+ def __init__(self) -> None:+ self.saved = []++ def save(self, config) -> None:+ self.saved.append(config)+++class _OutboundSettingsRepositoryProbe:+ def load(self) -> dict[str, bool]:+ return {"allow_loopback_http": False}+++def _free_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])def test_enterprise_a2a_web_gate_only_allows_directory_toggle_and_history(@@ -34,6 +85,140 @@ def test_enterprise_a2a_web_gate_only_allows_directory_toggle_and_history(}assert all(not web_invoke.is_enterprise_write_forbidden(item) for item in allowed)+ assert {+ "a2a.outbound.list",+ "a2a.outbound.enabled.update",+ "a2a.outbound.dispatch.get",+ } <= web_invoke._LOCAL_ROUTING_IDENTITY_METHODSassert all(web_invoke.is_enterprise_write_forbidden(item) for item in blocked)monkeypatch.setattr(web_invoke, "is_enterprise", lambda: False)assert all(not web_invoke.is_enterprise_write_forbidden(item) for item in blocked)+++def test_enterprise_does_not_register_a2a_ingress_rpc_handlers(monkeypatch):+ monkeypatch.setattr(app_web_handlers, "is_enterprise", lambda: True)+ channel = _WebChannelProbe()++ app_web_handlers._register_web_handlers(+ app_web_handlers.WebHandlersBindParams(channel=channel)+ )++ assert not any(name.startswith("a2a.ingress.") for name in channel.methods)+ assert "a2a.outbound.list" in channel.methods+++async def test_enterprise_does_not_mount_or_advertise_a2a_ingress_http_routes(+ monkeypatch,+):+ monkeypatch.setattr(web_http_app, "is_enterprise", lambda: True)+ app = web_http_app.create_web_http_app(object())+ paths = {route.path for route in app.routes}++ assert not any(path.startswith("/api/v1/a2a/ingress") for path in paths)+ assert "/api/v1/a2a/outbound/agents" in paths++ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ response = await client.get("/api/v1/catalog")+ missing = [+ await client.get("/api/v1/a2a/ingress"),+ await client.get("/api/v1/a2a/ingress/history"),+ await client.get("/.well-known/agent-card.json"),+ await client.post("/a2a", json={}),+ ]++ assert response.status_code == 200+ assert all(item.status_code == 404 for item in missing)+ assert not any(+ str(row.get("rpc_method") or "").startswith("a2a.ingress.")+ for row in response.json()["data"]["routes"]+ )+++async def test_enterprise_ignores_ingress_environment_and_never_starts_listener(+ monkeypatch,+):+ monkeypatch.setattr(app_gateway, "is_enterprise", lambda: True)+ monkeypatch.setenv("A2A_SERVER_ENABLED", "true")++ config, error = app_gateway._load_gateway_a2a_ingress_config()+ manager = _IngressManagerProbe()+ await app_gateway._start_gateway_a2a_ingress(manager)++ assert config.enabled is False+ assert error is None+ assert manager.started is False+++async def test_personal_edition_keeps_a2a_ingress_startup(monkeypatch):+ monkeypatch.setattr(app_gateway, "is_enterprise", lambda: False)+ manager = _IngressManagerProbe()++ await app_gateway._start_gateway_a2a_ingress(manager)++ assert manager.started is True+++def test_personal_edition_keeps_a2a_ingress_rpc_and_http_routes(monkeypatch):+ monkeypatch.setattr(app_web_handlers, "is_enterprise", lambda: False)+ monkeypatch.setattr(web_http_app, "is_enterprise", lambda: False)+ channel = _WebChannelProbe()+ app_web_handlers._register_web_handlers(+ app_web_handlers.WebHandlersBindParams(channel=channel)+ )+ paths = {route.path for route in web_http_app.create_web_http_app(object()).routes}++ assert "a2a.ingress.get" in channel.methods+ assert "a2a.ingress.update" in channel.methods+ assert "/api/v1/a2a/ingress" in paths+ assert "/api/v1/a2a/ingress/history" in paths+++async def test_enterprise_manager_hard_gate_never_binds_ingress_port(monkeypatch):+ monkeypatch.setattr(a2a_manager_module, "is_enterprise", lambda: True)+ port = _free_port()+ manager = A2AManager(+ object(),+ object(),+ A2AIngressConfig(enabled=True, host="127.0.0.1", port=port),+ repository=_ConfigRepositoryProbe(),+ outbound_settings_repository=_OutboundSettingsRepositoryProbe(),+ )++ with pytest.raises(A2AIngressError) as exc_info:+ await manager.start_from_config()++ assert exc_info.value.code == "A2A_INGRESS_DISABLED"+ server = await asyncio.start_server(lambda reader, writer: None, "127.0.0.1", port)+ server.close()+ await server.wait_closed()++[email protected]("operation", ["enable", "update", "reload"])+async def test_enterprise_manager_rejects_all_ingress_start_operations(+ monkeypatch,+ operation,+):+ monkeypatch.setattr(a2a_manager_module, "is_enterprise", lambda: True)+ repository = _ConfigRepositoryProbe()+ manager = A2AManager(+ object(),+ object(),+ A2AIngressConfig(),+ repository=repository,+ outbound_settings_repository=_OutboundSettingsRepositoryProbe(),+ )++ with pytest.raises(A2AIngressError) as exc_info:+ if operation == "update":+ await manager.update({"enabled": True}, apply=True)+ else:+ await getattr(manager, operation)()++ assert exc_info.value.code == "A2A_INGRESS_DISABLED"+ assert repository.saved == []diff --git a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.pyindex d5e7d6f0b3..0de74cb7f5 100644--- a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py+++ b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py@@ -203,6 +203,36 @@ def a2a_receiver() -> Iterator[tuple[TestClient, dict[str, Any], _Secrets]]:clear_enterprise_record_repositories()[email protected]("invalid_policy", ["yes", {"allow_http": 1}, [], False])+async def test_invalid_network_policy_does_not_break_enterprise_directory(+ invalid_policy, caplog, monkeypatch+) -> None:+ from jiuwenswarm.gateway.a2a_manager.outbound.enterprise import logger++ monkeypatch.setattr(logger, "handlers", [*logger.handlers, caplog.handler])+ store = InMemoryPersistentBackend()+ repos = create_enterprise_record_repositories(store)+ valid = _projection_record()+ invalid = {+ **_projection_record(), "template_id": "invalid-policy-agent",+ "data": {"network_policy": invalid_policy},+ }+ await repos["a2a_outbound_template"].create(valid)+ await repos["a2a_outbound_template"].create(invalid)+ projection = EnterpriseA2AProjection(+ store, templates=repos["a2a_outbound_template"],+ user_states=repos["a2a_outbound_user_state"],+ runtime_states=repos["a2a_outbound_runtime_state"],+ )+ agents = {view.agent.agent_id: view.agent for view in await projection.list_projected_agents()}+ assert set(agents) == {"a2a-weather", "invalid-policy-agent"}+ assert agents["invalid-policy-agent"].network_policy == {}+ assert "Invalid A2A network_policy template_id=invalid-policy-agent" in caplog.text+ direct = await projection.get_projected_agent("invalid-policy-agent")+ assert direct.agent.network_policy == {}++def test_a2a_outbound_receiver_crud_and_secret_store(a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],) -> None:@@ -555,6 +585,18 @@ async def test_enterprise_projection_merges_manager_user_and_runtime_state() ->assert initial.user_enabled is Trueassert initial.effective_enabled is Trueassert initial.agent.enabled is True+ assert initial.agent.network_policy == {}+ network_policy = {"allow_http": True, "allow_private_network": True}+ await repos["a2a_outbound_template"].update(+ {"template_id": "a2a-weather"}, {"data": {"network_policy": network_policy}}+ )+ updated_policy = await projection.get_projected_agent("a2a-weather")+ assert updated_policy.agent.network_policy == network_policy+ await repos["a2a_outbound_template"].update(+ {"template_id": "a2a-weather"}, {"data": {"network_policy": {}}}+ )+ revoked_policy = await projection.get_projected_agent("a2a-weather")+ assert revoked_policy.agent.network_policy == {}disabled = await projection.set_user_enabled("a2a-weather", False)assert disabled.manager_enabled is True@@ -653,6 +695,18 @@ async def test_enterprise_projection_reuses_dispatch_repository() -> None:assert isinstance(dispatch_row["accepted_at"], datetime)assert isinstance(dispatch_row["finished_at"], datetime)+ await projection.set_user_enabled("a2a-weather", False)+ restarted = EnterpriseA2AProjection(+ store,+ templates=repos["a2a_outbound_template"],+ user_states=repos["a2a_outbound_user_state"],+ runtime_states=repos["a2a_outbound_runtime_state"],+ )+ restored_after_restart = await restarted.get_projected_agent("a2a-weather")+ assert restored_after_restart is not None+ assert restored_after_restart.user_enabled is False+ assert (await restarted.get_dispatch("dispatch-1")) is not None+@pytest.mark.asyncioasync def test_enterprise_dispatch_updates_shared_runtime_state() -> None:@@ -798,3 +852,139 @@ async def test_repository_factory_creates_enterprise_projection(assert isinstance(repository, EnterpriseA2AProjection)projected = await repository.get_agent("a2a-weather")assert projected is not None and projected.display_name == "Weather Agent"+++async def test_enterprise_projection_resolves_policy_manager_and_user_intersection() -> None:+ store = InMemoryPersistentBackend()+ repos = create_enterprise_record_repositories(store)+ weather = _projection_record()+ calendar = {**_projection_record(), "template_id": "a2a-calendar"}+ await repos["a2a_outbound_template"].create(weather)+ await repos["a2a_outbound_template"].create(calendar)+ await repos["a2a_access_policy_template"].create(+ {+ "policy_id": "policy-1",+ "policy_name": "Allowed",+ "mode": "allowlist",+ "member_template_ids": ["a2a-weather", "a2a-calendar"],+ "enabled": True,+ "revision": 1,+ "created_at": datetime.now(timezone.utc),+ "updated_at": datetime.now(timezone.utc),+ }+ )+ await repos["agent_template"].create(+ {+ "template_id": "agent-template-1",+ "template_name": "Agent",+ "template_ref": {"a2a_access_policy": ["policy-1"]},+ "enabled": True,+ "created_at": datetime.now(timezone.utc),+ "updated_at": datetime.now(timezone.utc),+ }+ )+ await repos["instance_agent_resource"].create(+ {+ "resource_id": "resource-1",+ "resource_name": "Agent",+ "ref_template_id": "agent-template-1",+ "enabled": True,+ "created_at": datetime.now(timezone.utc),+ "updated_at": datetime.now(timezone.utc),+ }+ )+ projection = EnterpriseA2AProjection(+ store,+ templates=repos["a2a_outbound_template"],+ user_states=repos["a2a_outbound_user_state"],+ runtime_states=repos["a2a_outbound_runtime_state"],+ policies=repos["a2a_access_policy_template"],+ agent_templates=repos["agent_template"],+ instance_resources=repos["instance_agent_resource"],+ )++ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == {+ "a2a-weather",+ "a2a-calendar",+ }+ await repos["a2a_access_policy_template"].update(+ {"policy_id": "policy-1"}, {"member_template_ids": []}+ )+ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ await repos["a2a_access_policy_template"].update(+ {"policy_id": "policy-1"}, {"mode": "denylist"}+ )+ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == {+ "a2a-weather",+ "a2a-calendar",+ }+ await repos["a2a_access_policy_template"].update(+ {"policy_id": "policy-1"},+ {+ "mode": "allowlist",+ "member_template_ids": ["a2a-weather", "a2a-calendar"],+ },+ )+ await repos["instance_agent_resource"].update(+ {"resource_id": "resource-1"}, {"enabled": False}+ )+ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ await repos["instance_agent_resource"].update(+ {"resource_id": "resource-1"},+ {"enabled": True, "expires_at": datetime(2020, 1, 1, tzinfo=timezone.utc)},+ )+ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ await repos["instance_agent_resource"].update(+ {"resource_id": "resource-1"}, {"expires_at": None}+ )+ await repos["a2a_access_policy_template"].update(+ {"policy_id": "policy-1"}, {"enabled": False}+ )+ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ await repos["a2a_access_policy_template"].update(+ {"policy_id": "policy-1"}, {"enabled": True}+ )+ await repos["a2a_access_policy_template"].update(+ {"policy_id": "policy-1"},+ {"mode": "denylist", "member_template_ids": ["a2a-weather"]},+ )+ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == {+ "a2a-calendar"+ }+ await repos["a2a_access_policy_template"].update(+ {"policy_id": "policy-1"},+ {+ "mode": "allowlist",+ "member_template_ids": ["a2a-weather", "a2a-calendar"],+ },+ )+ await projection.set_user_enabled("a2a-calendar", False)+ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == {+ "a2a-weather"+ }+ await repos["a2a_outbound_template"].update(+ {"template_id": "a2a-weather"}, {"enabled": False}+ )+ assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ assert await projection.resolve_authorized_a2a_agent_ids("resource-1") == {+ "a2a-weather",+ "a2a-calendar",+ }+++async def test_enterprise_projection_fails_closed_for_invalid_resource_or_policy() -> None:+ store = InMemoryPersistentBackend()+ repos = create_enterprise_record_repositories(store)+ projection = EnterpriseA2AProjection(+ store,+ templates=repos["a2a_outbound_template"],+ user_states=repos["a2a_outbound_user_state"],+ runtime_states=repos["a2a_outbound_runtime_state"],+ policies=repos["a2a_access_policy_template"],+ agent_templates=repos["agent_template"],+ instance_resources=repos["instance_agent_resource"],+ )++ assert await projection.resolve_effective_a2a_agent_ids("missing") == frozenset()diff --git a/tests/unit_tests/gateway/test_runtime_routed_client.py b/tests/unit_tests/gateway/test_runtime_routed_client.pyindex 0b7c298e76..01297c684b 100644--- a/tests/unit_tests/gateway/test_runtime_routed_client.py+++ b/tests/unit_tests/gateway/test_runtime_routed_client.py@@ -5,6 +5,9 @@from __future__ import annotationsimport importlib.util+import asyncio+import json+import socketimport sysimport typesfrom pathlib import Path@@ -75,6 +78,297 @@ def _chat_env():)[email protected]("stream", [False, True])+async def test_reverse_rpc_over_real_http_sse(monkeypatch, stream):+ """First chat waits for registration; tool result returns over HTTP to its Pod."""+ import uvicorn+ from jiuwenswarm.agents.harness.common.tools.a2a_outbound_tools import (+ GatewayA2AOutboundToolBackend,+ )+ from jiuwenswarm.agents.harness.common.tools.acp_output_tools import (+ get_acp_output_manager,+ )+ from jiuwenswarm.common.e2a.gateway_normalize import message_to_e2a+ from jiuwenswarm.gateway.a2a_manager.tool_rpc import A2A_TOOL_FIND_AGENTS+ from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler+ from jiuwenswarm.server.agent_http_routes import build_fastapi_app+ from jiuwenswarm.server.gateway_push.wire import build_server_push_wire+ from jiuwenswarm.server.transports import push_registry++ registry = push_registry.PushRegistry()+ monkeypatch.setattr(push_registry, "get_push_registry", lambda: registry)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.message_handler.message_handler.is_enterprise",+ lambda: stream,+ )+ output = get_acp_output_manager()+ output.reset_state()++ async def push(message):+ return await registry.push_reverse_rpc(build_server_push_wire(message))++ monkeypatch.setattr(output, "_send_push_callback", push)+ monkeypatch.setattr("jiuwenswarm.gateway.routing.http_agent_client._PUSH_RETRY_SECONDS", 0.01)+ received = []++ class Agent:+ async def iter_stream(self, method, params, **ctx):+ from jiuwenswarm.common.e2a.wire_codec import encode_agent_chunk_for_wire++ result, _ = await self.invoke_unary(method, params, **ctx)+ wire = encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id=ctx["request_id"],+ channel_id="web",+ payload=result["data"],+ is_complete=True,+ ),+ response_id="response",+ sequence=0,+ )+ yield {"data": json.dumps(wire)}++ async def invoke_unary(self, method, params, **ctx):+ if method == "acp.tool_response":+ received.append(params["jsonrpc_id"])+ assert output.complete_jsonrpc_response(params["jsonrpc_id"], params["response"])+ return {"ok": True, "data": {}}, 200+ assert registry.reverse_rpc_ready(), "chat must not race subscriber registration"+ result = await GatewayA2AOutboundToolBackend().call(+ A2A_TOOL_FIND_AGENTS,+ {"query": "weather", "resource_id": "bot-1"},+ session_id=ctx["session_id"],+ channel_id="web",+ )+ return {"ok": True, "data": result}, 200++ class Manager:+ async def outbound_find_agents(self, **kwargs):+ assert kwargs["query"] == "weather"+ if stream:+ assert kwargs["source_resource_id"] == "bot-1"+ return {"items": [{"agent_id": "weather"}], "total": 1}++ async def outbound_dispatch_task(self, **kwargs):+ dispatch_started.set()+ try:+ await asyncio.Event().wait()+ finally:+ dispatch_cancelled.set()++ dispatch_started = asyncio.Event()+ dispatch_cancelled = asyncio.Event()++ sock = socket.socket()+ sock.bind(("127.0.0.1", 0))+ base = f"http://127.0.0.1:{sock.getsockname()[1]}"+ server = uvicorn.Server(uvicorn.Config(build_fastapi_app(Agent()), log_level="error"))+ serving = asyncio.create_task(server.serve(sockets=[sock]))+ route = _FakeRoute()++ async def route_to_pod(**kwargs):+ route.routes.append(kwargs)+ return RouteResult(+ pod_sse_url=f"{base}/sse", pod_id="pod-1", request_id=kwargs["request_id"]+ )++ route.route = route_to_pod+ client = RuntimeRoutedAgentClient(route_client=route)+ handler = object.__new__(MessageHandler)+ handler._stream_sessions = {"req-1": "sess-1"}+ handler._stream_metadata = {"req-1": {"routing": {"bot_id": "bot-1"}}}+ handler._stream_channels = {"req-1": "web"}+ handler.set_a2a_outbound_tool_manager(Manager())++ async def publish(reply):+ assert (await client.send_request(message_to_e2a(reply))).ok++ handler.publish_user_messages = publish+ client.set_server_push_handler(handler._handle_agent_server_push)+ try:+ async with asyncio.timeout(5):+ while not server.started:+ await asyncio.sleep(0.01)+ await client.connect("unused")+ chat_number = 0++ async def chat():+ nonlocal chat_number+ chat_number += 1+ envelope = _chat_env()+ envelope.request_id = f"chat-{chat_number}"+ if stream:+ chunks = [chunk async for chunk in client.send_request_stream(envelope)]+ return chunks[-1]+ return await client.send_request(envelope)++ result = await asyncio.wait_for(chat(), 5)+ assert result.payload["total"] == 1+ assert received and len(route.routes) == 1, "reverse response must not re-route"+ assert not client._rpc_origins+ # Reusing a Pod does not add duplicate consumers.+ await chat()+ assert registry.subscriber_count() == 1+ # Force SSE EOF, then verify the next chat waits for re-registration.+ old_subscriber = next(iter(registry._subscribers))+ await registry._subscribers[old_subscriber].sink.finish()+ async with asyncio.timeout(5):+ while old_subscriber in registry._subscribers:+ await asyncio.sleep(0.01)+ assert (await asyncio.wait_for(chat(), 5)).payload["total"] == 1+ if not stream:+ from jiuwenswarm.gateway.a2a_manager.tool_rpc import A2A_TOOL_DISPATCH_TASK++ dispatch = asyncio.create_task(+ GatewayA2AOutboundToolBackend().call(+ A2A_TOOL_DISPATCH_TASK,+ {"agent_id": "weather", "task": "weather", "mode": "sync"},+ session_id="sess-1",+ channel_id="web",+ )+ )+ await asyncio.wait_for(dispatch_started.wait(), 5)+ dispatch.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(dispatch, 2)+ await asyncio.wait_for(dispatch_cancelled.wait(), 2)+ assert not client._rpc_origins+ finally:+ await client.disconnect()+ output.reset_state()+ server.should_exit = True+ await asyncio.wait_for(serving, 5)+ sock.close()+ assert registry.subscriber_count() == 0+++async def test_concurrent_pod_subscription_and_failed_registration_cleanup(monkeypatch):+ created = []++ class PodClient:+ def __init__(self):+ created.append(self)+ self.closed = False+ self.fail = False++ def set_server_push_handler(self, handler):+ self.handler = handler++ async def connect(self, uri):+ self.fail = "bad" in uri+ await asyncio.sleep(0)++ async def wait_push_ready(self):+ if self.fail:+ raise TimeoutError("no subscriber acknowledgement")++ async def disconnect(self):+ self.closed = True++ monkeypatch.setattr(_routed_mod, "HttpSseAgentServerClient", PodClient)+ client = RuntimeRoutedAgentClient(route_client=_FakeRoute(), http_client=_FakeHttp())+ client.set_server_push_handler(lambda wire: asyncio.sleep(0))+ await client.connect("unused")+ try:+ await asyncio.gather(*(client._ensure_pod_push("http://pod") for _ in range(3)))+ assert len(created) == 1+ with pytest.raises(TimeoutError):+ await client._ensure_pod_push("http://bad")+ assert created[-1].closed+ assert "http://bad" not in client._pod_clients+ finally:+ await client.disconnect()+ assert all(pod.closed for pod in created)+++async def test_reverse_rpc_reply_is_pinned_to_origin_pod():+ from jiuwenswarm.common.e2a.adapters import build_acp_tool_response_message+ from jiuwenswarm.common.e2a.gateway_normalize import message_to_e2a++ route, http = _FakeRoute(), _FakeHttp()+ client = RuntimeRoutedAgentClient(route_client=route, http_client=http)+ client.set_server_push_handler(lambda wire: asyncio.sleep(0))+ await client.connect("unused")+ try:+ for session, base in (("s1", "http://pod1:8080"), ("s2", "http://pod2:8080")):+ await client._handle_pod_push(+ base,+ {+ "protocol_version": "1.0",+ "response_id": "response",+ "request_id": "r",+ "session_id": session,+ "channel": "web",+ "response_kind": "acp.output_request",+ "body": {+ "jsonrpc": "2.0",+ "id": "same-id",+ "method": "a2a.outbound.tool.find_agents",+ },+ },+ )+ for session in ("s2", "s1"):+ reply = build_acp_tool_response_message("same-id", {"result": {}}, session, "web")+ await client.send_request(message_to_e2a(reply))+ assert [call[1] for call in http.calls] == [+ "http://pod2:8080",+ "http://pod1:8080",+ ]+ assert not route.routes+ with pytest.raises(RuntimeError, match="origin Pod"):+ await client.send_request(message_to_e2a(reply))+ finally:+ await client.disconnect()++[email protected]("mismatch", ["resource", "session", "channel", "ambiguous"])+async def test_reverse_rpc_identity_fallback_rejects_untrusted_scope(monkeypatch, mismatch):+ from types import SimpleNamespace+ from jiuwenswarm.gateway.a2a_manager.tool_rpc import A2A_TOOL_FIND_AGENTS+ from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler++ monkeypatch.setattr(+ "jiuwenswarm.gateway.message_handler.message_handler.is_enterprise", lambda: True+ )+ handler = object.__new__(MessageHandler)+ handler._stream_sessions = {"chat": "session"}+ handler._stream_channels = {"chat": "web"}+ handler._stream_metadata = {"chat": {"routing": {"bot_id": "allowed"}}}+ if mismatch == "ambiguous":+ handler._stream_sessions["other"] = "session"+ handler._stream_channels["other"] = "web"+ handler._stream_metadata["other"] = {"routing": {"bot_id": "other"}}+ calls = []++ async def find(**kwargs):+ calls.append(kwargs)+ return {"total": 0}++ replies = []++ async def publish(reply):+ replies.append(reply)++ handler.set_a2a_outbound_tool_manager(SimpleNamespace(outbound_find_agents=find))+ handler.publish_user_messages = publish+ await handler._handle_a2a_outbound_tool_push(+ chunk=SimpleNamespace(+ channel_id="other" if mismatch == "channel" else "web",+ payload={+ "jsonrpc": "2.0", "id": "rpc", "method": A2A_TOOL_FIND_AGENTS,+ "params": {"resource_id": "other" if mismatch == "resource" else "allowed"},+ },+ ),+ session_id="other" if mismatch == "session" else "session",+ )+ assert not calls+ assert replies[0].params["response"]["error"]["data"]["code"] == "A2A_AGENT_NOT_AUTHORIZED"++class _FakeRoute:def __init__(self) -> None:self.routes: list[dict] = []