Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(a2a): resolve codecheck G.TYP.08, G.CTL.03, and G.EXP.04

NickFuryXXXecb6a2acfbf5
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py b/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py
index adb10a2dff..338cca1ef9 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py
@@ -177,6 +177,40 @@ def _is_public_address(address: str) -> bool:
)
+_RFC1918_NETWORKS = (
+ ipaddress.ip_network("10.0.0.0/8"),
+ ipaddress.ip_network("172.16.0.0/12"),
+ ipaddress.ip_network("192.168.0.0/16"),
+)
+
+
+def _is_rfc1918_ipv4_only(addresses: list[str]) -> bool:
+ # Match Manager's RFC1918-only policy; IPv6 ULA/mapped addresses
+ # are not included in the private-network exception.
+ for item in addresses:
+ address = ipaddress.ip_address(item)
+ if address.version != 4:
+ return False
+ in_private = False
+ for network in _RFC1918_NETWORKS:
+ if address in network:
+ in_private = True
+ break
+ if not in_private:
+ return False
+ return True
+
+
+def _http_blocked_by_policy(
+ network_policy: dict[str, bool], *, public_only: bool
+) -> bool:
+ if network_policy.get("allow_http") is not True:
+ return True
+ if public_only and network_policy.get("allow_public_http") is not True:
+ return True
+ return False
+
+
class A2AOutboundDiscoveryService:
"""Resolve a caller-supplied Card URL without granting invocation rights."""
@@ -391,25 +425,17 @@ class A2AOutboundDiscoveryService:
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)
- )):
+ private_only = _is_rfc1918_ipv4_only(addresses)
+ allowed_address = public_only
+ if network_policy.get("allow_loopback") is True and loopback_only:
+ allowed_address = True
+ if network_policy.get("allow_private_network") is True and private_only:
+ allowed_address = True
+ if not allowed_address:
+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_BLOCKED)
+ if scheme == "http" and _http_blocked_by_policy(
+ network_policy, public_only=public_only
+ ):
raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_BLOCKED)
return _ValidatedTarget(
host=parts.hostname.lower().rstrip("."),
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py b/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py
index 49475b0d9a..aed1237fc0 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py
@@ -124,13 +124,16 @@ class EnterpriseA2AProjection(A2AOutboundRepository):
) -> 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
- )
+ effective_ids = []
+ for item in projected:
+ if item.agent.agent_id not in allowed:
+ continue
+ if not item.manager_enabled:
+ continue
+ if not item.user_enabled:
+ continue
+ effective_ids.append(item.agent.agent_id)
+ return frozenset(effective_ids)
async def resolve_authorized_a2a_agent_ids(
self, resource_id: str
@@ -206,11 +209,17 @@ class EnterpriseA2AProjection(A2AOutboundRepository):
)
runtime = runtime_state or {}
network_policy = (template.get("data") or {}).get("network_policy")
+ invalid_policy = False
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()
- ):
+ elif not isinstance(network_policy, dict):
+ invalid_policy = True
+ else:
+ for value in network_policy.values():
+ if not isinstance(value, bool):
+ invalid_policy = True
+ break
+ if invalid_policy:
logger.warning(
"Invalid A2A network_policy template_id=%s; using strict defaults",
template.get("template_id"),
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/models.py b/jiuwenswarm/gateway/a2a_manager/outbound/models.py
index 8d8819af6c..d042db09c2 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/models.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/models.py
@@ -109,6 +109,17 @@ def _required(value: Any, field_name: str) -> str:
return text
+def _is_bool_network_policy(policy: Any) -> bool:
+ if policy is None:
+ return True
+ if not isinstance(policy, dict):
+ return False
+ for value in policy.values():
+ if not isinstance(value, bool):
+ return False
+ return True
+
+
def _positive_seconds(value: Any) -> float:
try:
parsed = float(value)
@@ -215,10 +226,7 @@ class A2AOutboundAgent:
network_policy: dict[str, bool] | None = None
def 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())
- ):
+ if not _is_bool_network_policy(self.network_policy):
raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)
for name in (
"agent_id",
diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.py
index 556d3a5d8c..9eea226bab 100644
--- a/jiuwenswarm/gateway/message_handler/message_handler.py
+++ b/jiuwenswarm/gateway/message_handler/message_handler.py
@@ -3083,12 +3083,15 @@ class MessageHandler(FileTransferMixin, ABC):
# 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
- ]
+ identities = []
+ for active_rid, active_sid in getattr(self, "_stream_sessions", {}).items():
+ if active_sid != trusted_session_id:
+ continue
+ if self._stream_channels.get(active_rid) != chunk.channel_id:
+ continue
+ identities.append(
+ web_routing_identity(self._stream_metadata.get(active_rid))
+ )
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()
diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
index 0546fe8831..bfc666adfd 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
@@ -1780,11 +1780,14 @@ async def process_team_message_stream(
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
- })
+ routing = {}
+ if group_id:
+ routing["group_id"] = group_id
+ if bot_id:
+ routing["bot_id"] = bot_id
+ if user_id:
+ routing["user_id"] = user_id
+ request_metadata = apply_routing_metadata(request_metadata, routing)
# V2: 若请求携带 member_name(由 Gateway resolve_member_by_user 反查注入),
# 在前拼接 $sender,让 OpenJiuwen 识别发言人身份。
# 规则: