Skip to content

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

Python

feat(a2a): enhance A2A outbound management with enterprise support

NickFuryXXX19fa897311fd
diff --git a/jiuwenswarm/gateway/a2a_manager/manager.py b/jiuwenswarm/gateway/a2a_manager/manager.py
index 34a159832f..cd6d16f94f 100644
--- a/jiuwenswarm/gateway/a2a_manager/manager.py
+++ b/jiuwenswarm/gateway/a2a_manager/manager.py
@@ -167,6 +167,11 @@ class A2AManager:
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
+ ) -> dict[str, Any]:
+ return await self._require_outbound().set_user_enabled(agent_id, enabled)
+
async def outbound_edit(self, agent_id: str) -> dict[str, Any]:
return await self._require_outbound().edit_agent(agent_id)
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py b/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py
index 03883b2976..fd91e02d8a 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py
@@ -3,6 +3,7 @@
from .credentials import A2AOutboundCredentialStore
from .discovery import A2AOutboundDiscoveryService, DiscoveredCard
from .dispatcher import A2AOutboundDispatcher
+from .enterprise import EnterpriseA2AAgentView, EnterpriseA2AProjection
from .errors import A2AOutboundError, A2AOutboundErrorCode, safe_error_summary
from .models import (
A2ACompatibleInterface,
@@ -31,6 +32,8 @@ __all__ = [
"A2AOutboundCredentialStore",
"A2AOutboundDiscoveryService",
"A2AOutboundDispatcher",
+ "EnterpriseA2AAgentView",
+ "EnterpriseA2AProjection",
"A2AOutboundRegistry",
"A2AOutboundDiscovery",
"A2AOutboundDispatch",
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
index 0511971c30..32dd505493 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
@@ -164,6 +164,25 @@ class A2AOutboundDispatcher:
def set_allow_loopback_http(self, enabled: bool) -> None:
self._discovery.set_allow_loopback_http(enabled)
+ async def _update_runtime_state(
+ self,
+ agent_id: str,
+ availability: A2AOutboundAvailability,
+ *,
+ error_code: A2AOutboundErrorCode | None = None,
+ ) -> None:
+ try:
+ await self._repository.update_runtime_state(
+ agent_id,
+ availability,
+ error_code=error_code.value if error_code is not None else None,
+ )
+ except Exception:
+ logger.exception(
+ "a2a.outbound runtime state update failed agent_id=%s",
+ agent_id,
+ )
+
async def find_agents(
self,
query: str = "",
@@ -282,6 +301,7 @@ class A2AOutboundDispatcher:
source_session_id=session_id,
created_at=stamp,
updated_at=stamp,
+ agent_name=agent.display_name,
input_length=len(task_text),
input_content_type="text/plain",
input_digest=f"sha256:{hashlib.sha256(task_text.encode()).hexdigest()}",
@@ -434,6 +454,7 @@ class A2AOutboundDispatcher:
)
client: _ClientLike | None = None
last_remote = _NormalizedRemote(A2AOutboundDispatchStatus.SUBMITTING)
+ observed_response = False
try:
client = await self._build_client(agent)
request = SendMessageRequest(
@@ -451,7 +472,7 @@ class A2AOutboundDispatcher:
)
async def consume() -> _NormalizedRemote:
- nonlocal last_remote
+ nonlocal last_remote, observed_response
# The outer sync_wait timeout owns the total synchronous task budget.
# Keeping the SDK call context unset prevents it from replacing the
# client's granular connect/write/pool limits with a short read limit.
@@ -465,6 +486,12 @@ class A2AOutboundDispatcher:
context=call_context,
):
last_remote = self._normalize_stream_event(event, last_remote)
+ if not observed_response:
+ observed_response = True
+ await self._update_runtime_state(
+ agent.agent_id,
+ A2AOutboundAvailability.AVAILABLE,
+ )
applied = await self._apply_remote(
dispatch.dispatch_id, last_remote
)
@@ -515,6 +542,12 @@ class A2AOutboundDispatcher:
dispatch.dispatch_id, last_remote, polled=True
)
except TimeoutError:
+ if not observed_response:
+ await self._update_runtime_state(
+ agent.agent_id,
+ A2AOutboundAvailability.UNREACHABLE,
+ error_code=A2AOutboundErrorCode.DISPATCH_TIMEOUT,
+ )
updated = await self._repository.transition_dispatch(
dispatch.dispatch_id,
A2AOutboundDispatchStatus.TIMED_OUT,
@@ -554,6 +587,12 @@ class A2AOutboundDispatcher:
)
raise
except A2AOutboundError as exc:
+ if exc.code is A2AOutboundErrorCode.AGENT_UNAVAILABLE:
+ await self._update_runtime_state(
+ agent.agent_id,
+ A2AOutboundAvailability.INCOMPATIBLE,
+ error_code=exc.code,
+ )
status = (
A2AOutboundDispatchStatus.AUTH_REQUIRED
if exc.code is A2AOutboundErrorCode.AUTH_REQUIRED
@@ -568,6 +607,12 @@ class A2AOutboundDispatcher:
)
return self._public_dispatch(updated or current)
except Exception:
+ if not observed_response:
+ await self._update_runtime_state(
+ agent.agent_id,
+ A2AOutboundAvailability.UNREACHABLE,
+ error_code=A2AOutboundErrorCode.AGENT_UNAVAILABLE,
+ )
target = (
A2AOutboundDispatchStatus.UNKNOWN
if last_remote.remote_task_id
@@ -996,6 +1041,7 @@ class A2AOutboundDispatcher:
"ok": ok,
"dispatch_id": dispatch.dispatch_id,
"agent_id": dispatch.agent_id,
+ "agent_name": dispatch.agent_name,
"mode": dispatch.mode.value,
"status": dispatch.status.value,
"created_at": dispatch.created_at,
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py b/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py
new file mode 100644
index 0000000000..6f832d875d
--- /dev/null
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py
@@ -0,0 +1,270 @@
+"""Enterprise projection over Manager-owned A2A templates and local state."""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Callable
+
+from jiuwenswarm.gateway.config.enterprise.repository import (
+ EnterpriseRecordRepository,
+)
+from jiuwenswarm.gateway.storage.protocols.persistent import PersistentStore
+
+from .errors import A2AOutboundError, A2AOutboundErrorCode, safe_error_summary
+from .models import A2AOutboundAgent, A2AOutboundAvailability, A2AOutboundDispatch
+from .repository import A2AOutboundRepository, JsonA2AOutboundRecordCodec
+
+_DISPATCH_DATETIME_FIELDS = (
+ "accepted_at",
+ "finished_at",
+ "last_polled_at",
+ "created_at",
+ "updated_at",
+)
+
+
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _to_datetime(value: Any) -> datetime | None:
+ if value is None or isinstance(value, datetime):
+ return value
+ text = str(value).strip()
+ if not text:
+ return None
+ if text.endswith("Z"):
+ text = f"{text[:-1]}+00:00"
+ try:
+ parsed = datetime.fromisoformat(text)
+ except ValueError as exc:
+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID) from exc
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)
+
+
+def _to_timestamp_text(value: Any) -> Any:
+ if not isinstance(value, datetime):
+ return value
+ normalized = (
+ value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
+ )
+ return normalized.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+class _EnterpriseA2AOutboundRecordCodec(JsonA2AOutboundRecordCodec):
+ """Adapt the shared dispatch domain record to enterprise datetime columns."""
+
+ @staticmethod
+ def dispatch_to_record(dispatch: A2AOutboundDispatch) -> dict[str, Any]:
+ record = dispatch.to_record()
+ for field in _DISPATCH_DATETIME_FIELDS:
+ if field in record:
+ record[field] = _to_datetime(record[field])
+ return record
+
+ @staticmethod
+ def dispatch_from_record(record: Any) -> A2AOutboundDispatch:
+ values = dict(record)
+ for field in _DISPATCH_DATETIME_FIELDS:
+ if field in values:
+ values[field] = _to_timestamp_text(values[field])
+ return A2AOutboundDispatch.from_record(values)
+
+
+@dataclass(frozen=True)
+class EnterpriseA2AAgentView:
+ agent: A2AOutboundAgent
+ manager_enabled: bool
+ user_enabled: bool
+
+ @property
+ def effective_enabled(self) -> bool:
+ return self.manager_enabled and self.user_enabled
+
+ def public_dict(self) -> dict[str, Any]:
+ return {
+ **self.agent.public_dict(),
+ "manager_enabled": self.manager_enabled,
+ "user_enabled": self.user_enabled,
+ "effective_enabled": self.effective_enabled,
+ }
+
+
+class EnterpriseA2AProjection(A2AOutboundRepository):
+ """Project enterprise rows into the existing outbound domain model."""
+
+ manager_owned = True
+
+ def __init__(
+ self,
+ store: PersistentStore,
+ *,
+ templates: EnterpriseRecordRepository,
+ user_states: EnterpriseRecordRepository,
+ runtime_states: EnterpriseRecordRepository,
+ ) -> None:
+ super().__init__(store, _EnterpriseA2AOutboundRecordCodec())
+ self._templates = templates
+ self._user_states = user_states
+ self._runtime_states = runtime_states
+
+ @staticmethod
+ def _project(
+ template: dict[str, Any],
+ user_state: dict[str, Any] | None,
+ runtime_state: dict[str, Any] | None,
+ ) -> EnterpriseA2AAgentView:
+ manager_enabled = bool(template.get("enabled"))
+ user_enabled = (
+ True if user_state is None else bool(user_state.get("user_enabled"))
+ )
+ runtime = runtime_state or {}
+ availability = str(
+ runtime.get("availability") or A2AOutboundAvailability.AVAILABLE.value
+ )
+ agent = A2AOutboundAgent.from_record(
+ {
+ "agent_id": template.get("template_id"),
+ "display_name": template.get("template_name"),
+ "source_url": template.get("source_url"),
+ "card_path": template.get("card_path"),
+ "card_fingerprint": template.get("card_fingerprint"),
+ "card_revision": template.get("card_revision"),
+ "agent_card": template.get("agent_card"),
+ "selected_interface": template.get("selected_interface"),
+ "enabled": manager_enabled and user_enabled,
+ "availability": availability,
+ "credential_ref": template.get("credential_ref"),
+ "connect_timeout_seconds": template.get("connect_timeout_seconds"),
+ "sync_wait_seconds": template.get("sync_wait_seconds"),
+ "last_checked_at": _to_timestamp_text(runtime.get("last_checked_at")),
+ "last_success_at": _to_timestamp_text(runtime.get("last_success_at")),
+ "last_error_code": runtime.get("last_error_code"),
+ "last_error_summary": runtime.get("last_error_summary"),
+ "created_at": _to_timestamp_text(template.get("created_at")),
+ "updated_at": _to_timestamp_text(template.get("updated_at")),
+ }
+ )
+ return EnterpriseA2AAgentView(
+ agent=agent,
+ manager_enabled=manager_enabled,
+ user_enabled=user_enabled,
+ )
+
+ async def get_projected_agent(
+ self, template_id: str
+ ) -> EnterpriseA2AAgentView | None:
+ normalized = str(template_id or "").strip()
+ template = await self._templates.get(template_id=normalized)
+ if template is None:
+ return None
+ user_state, runtime_state = await asyncio.gather(
+ self._user_states.get(template_id=normalized),
+ self._runtime_states.get(template_id=normalized),
+ )
+ return self._project(template, user_state, runtime_state)
+
+ async def list_projected_agents(self) -> list[EnterpriseA2AAgentView]:
+ templates, user_rows, runtime_rows = await asyncio.gather(
+ self._templates.list(order_by="updated_at DESC"),
+ self._user_states.list(),
+ self._runtime_states.list(),
+ )
+ user_states = {row["template_id"]: row for row in user_rows}
+ runtime_states = {row["template_id"]: row for row in runtime_rows}
+ return [
+ self._project(
+ template,
+ user_states.get(template.get("template_id")),
+ runtime_states.get(template.get("template_id")),
+ )
+ for template in templates
+ ]
+
+ async def get_agent(self, agent_id: str) -> A2AOutboundAgent | None:
+ projected = await self.get_projected_agent(agent_id)
+ return None if projected is None else projected.agent
+
+ async def list_agents(self) -> list[A2AOutboundAgent]:
+ return [item.agent for item in await self.list_projected_agents()]
+
+ async def set_user_enabled(
+ self, template_id: str, user_enabled: bool
+ ) -> EnterpriseA2AAgentView:
+ if not isinstance(user_enabled, bool):
+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)
+ normalized = str(template_id or "").strip()
+ if await self._templates.get(template_id=normalized) is None:
+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)
+ await self._user_states.upsert(
+ {
+ "template_id": normalized,
+ "user_enabled": user_enabled,
+ "updated_at": _utc_now(),
+ }
+ )
+ projected = await self.get_projected_agent(normalized)
+ if projected is None:
+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)
+ return projected
+
+ async def update_runtime_state(
+ self,
+ template_id: str,
+ availability: A2AOutboundAvailability | str,
+ *,
+ error_code: str | None = None,
+ ) -> None:
+ normalized = str(template_id or "").strip()
+ if await self._templates.get(template_id=normalized) is None:
+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)
+ try:
+ state = A2AOutboundAvailability(availability)
+ except ValueError as exc:
+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID) from exc
+ now = _utc_now()
+ existing = await self._runtime_states.get(template_id=normalized)
+ values = {
+ "template_id": normalized,
+ "availability": state.value,
+ "last_checked_at": now,
+ "last_success_at": (
+ now
+ if state is A2AOutboundAvailability.AVAILABLE
+ else _to_datetime((existing or {}).get("last_success_at"))
+ ),
+ "last_error_code": error_code,
+ "last_error_summary": (
+ safe_error_summary(error_code) if error_code else None
+ ),
+ "updated_at": now,
+ }
+ await self._runtime_states.upsert(values)
+
+ async def clear_agent_state(self, template_id: str) -> None:
+ key = {"template_id": str(template_id or "").strip()}
+ await asyncio.gather(
+ self._user_states.delete(key),
+ self._runtime_states.delete(key),
+ )
+
+ async def create_agent(self, agent: A2AOutboundAgent) -> A2AOutboundAgent:
+ del agent
+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)
+
+ async def update_agent(
+ self,
+ agent_id: str,
+ updater: Callable[[A2AOutboundAgent], A2AOutboundAgent],
+ ) -> A2AOutboundAgent | None:
+ del agent_id, updater
+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)
+
+ async def delete_agent(self, agent_id: str) -> bool:
+ del agent_id
+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)
+
+
+__all__ = ["EnterpriseA2AAgentView", "EnterpriseA2AProjection"]
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/models.py b/jiuwenswarm/gateway/a2a_manager/outbound/models.py
index 97a95355e0..e19d44c712 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/models.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/models.py
@@ -310,6 +310,8 @@ class A2AOutboundDispatch:
source_session_id: str
created_at: str
updated_at: str
+ agent_name: str | None = None
+ source_resource_id: str | None = None
remote_task_id: str | None = None
remote_context_id: str | None = None
accepted_at: str | None = None
@@ -367,6 +369,8 @@ class A2AOutboundDispatch:
source_session_id=str(record.get("source_session_id") or "").strip(),
created_at=str(record.get("created_at") or ""),
updated_at=str(record.get("updated_at") or ""),
+ agent_name=record.get("agent_name"),
+ source_resource_id=record.get("source_resource_id"),
remote_task_id=record.get("remote_task_id"),
remote_context_id=record.get("remote_context_id"),
accepted_at=record.get("accepted_at"),
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py
index dd32cc2664..ae19616a19 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py
@@ -102,10 +102,15 @@ class A2AOutboundRegistry:
self._registration_lock = asyncio.Lock()
self._agent_operation_locks = KeyedLockPool()
+ def _require_mutable_catalog(self) -> None:
+ if getattr(self._repository, "manager_owned", False):
+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)
+
def set_allow_loopback_http(self, enabled: bool) -> None:
self._discovery.set_allow_loopback_http(enabled)
async def discover(self, url: str, card_path: str | None = None) -> dict[str, Any]:
+ self._require_mutable_catalog()
card = await self._discovery.discover(url, card_path)
now = self._now()
item = A2AOutboundDiscovery(
@@ -127,6 +132,7 @@ class A2AOutboundRegistry:
return item.to_dict()
async def register(self, params: Mapping[str, Any]) -> dict[str, Any]:
+ self._require_mutable_catalog()
discovery_id = str(params.get("discovery_id") or "").strip()
if not discovery_id:
raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_NOT_FOUND)
@@ -199,14 +205,35 @@ class A2AOutboundRegistry:
return created.public_dict()
async def list_agents(self) -> dict[str, Any]:
+ list_projected = getattr(self._repository, "list_projected_agents", None)
+ if callable(list_projected):
+ projected = await list_projected()
+ items = [item.public_dict() for item in projected]
+ return {"items": items, "total": len(items)}
items = [item.public_dict() for item in await self._repository.list_agents()]
return {"items": items, "total": len(items)}
async def get_agent(self, agent_id: str) -> dict[str, Any]:
+ get_projected = getattr(self._repository, "get_projected_agent", None)
+ if callable(get_projected):
+ projected = await get_projected(agent_id)
+ if projected is None:
+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)
+ return projected.public_dict()
return (await self._require_agent(agent_id)).public_dict()
+ async def set_user_enabled(
+ self, agent_id: str, user_enabled: bool
+ ) -> dict[str, Any]:
+ setter = getattr(self._repository, "set_user_enabled", None)
+ if not callable(setter):
+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)
+ projected = await setter(agent_id, user_enabled)
+ return projected.public_dict()
+
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()
async with self._agent_operation_locks.hold(agent_id):
agent = await self._require_agent(agent_id)
result = agent.public_dict()
@@ -216,6 +243,7 @@ class A2AOutboundRegistry:
async def update_agent(
self, agent_id: str, params: Mapping[str, Any]
) -> dict[str, Any]:
+ self._require_mutable_catalog()
allowed = {
"display_name",
"enabled",
@@ -284,6 +312,7 @@ class A2AOutboundRegistry:
return updated.public_dict()
async def refresh_agent(self, agent_id: str) -> dict[str, Any]:
+ self._require_mutable_catalog()
async with self._agent_operation_locks.hold(agent_id):
current = await self._require_agent(agent_id)
try:
@@ -370,6 +399,7 @@ class A2AOutboundRegistry:
return updated.public_dict()
async def confirm_revision(self, agent_id: str, *, accept: bool) -> dict[str, Any]:
+ self._require_mutable_catalog()
if not isinstance(accept, bool):
raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)
@@ -416,6 +446,7 @@ class A2AOutboundRegistry:
return updated.public_dict()
async def delete_agent(self, agent_id: str) -> dict[str, Any]:
+ self._require_mutable_catalog()
async with self._agent_operation_locks.hold(agent_id):
if not await self._repository.delete_agent(agent_id):
raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)
@@ -438,6 +469,7 @@ class A2AOutboundRegistry:
{
"dispatch_id": item.dispatch_id,
"agent_id": item.agent_id,
+ "agent_name": item.agent_name,
"mode": item.mode.value,
"status": item.status.value,
"remote_task_id": item.remote_task_id,
@@ -447,6 +479,7 @@ class A2AOutboundRegistry:
"finished_at": item.finished_at,
"error_code": item.error_code,
"error_summary": item.error_summary,
+ "source_resource_id": item.source_resource_id,
}
)
return {"items": items, "total": total}
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py b/jiuwenswarm/gateway/a2a_manager/outbound/repository.py
index a92f0432de..a843d48800 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/repository.py
@@ -15,6 +15,7 @@ from .errors import safe_error_summary
from .locks import KeyedLockPool
from .models import (
A2AOutboundAgent,
+ A2AOutboundAvailability,
A2AOutboundDispatch,
A2AOutboundDispatchStatus,
TERMINAL_DISPATCH_STATUSES,
@@ -194,6 +195,16 @@ class A2AOutboundRepository:
key,
)
+ async def update_runtime_state(
+ self,
+ agent_id: str,
+ availability: A2AOutboundAvailability | str,
+ *,
+ error_code: str | None = None,
+ ) -> None:
+ """Persist runtime health when the repository provides a separate store."""
+ del agent_id, availability, error_code
+
async def get_dispatch(self, dispatch_id: str) -> A2AOutboundDispatch | None:
row = await self._store.get(
A2A_OUTBOUND_DISPATCH_STORE_NAME,
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index 42d70cd6b5..9e66842e49 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -1647,14 +1647,13 @@ async def _run_with_telemetry(
):
gateway_storage_ctx = await setup_gateway_storage_repositories(full_cfg)
if gateway_storage_ctx is not None:
- if not is_enterprise():
- from jiuwenswarm.gateway.storage_assembly import (
- create_a2a_outbound_repository,
- )
+ from jiuwenswarm.gateway.storage_assembly import (
+ create_a2a_outbound_repository,
+ )
- a2a_outbound_repository = create_a2a_outbound_repository(
- await gateway_storage_ctx.persistent()
- )
+ a2a_outbound_repository = create_a2a_outbound_repository(
+ await gateway_storage_ctx.persistent()
+ )
wired: list[str] = []
if is_session_map_repository_enabled(full_cfg):
wired.append("session_map")
diff --git a/jiuwenswarm/gateway/config/enterprise/catalog.py b/jiuwenswarm/gateway/config/enterprise/catalog.py
index ba118daa4c..a71776b7fa 100644
--- a/jiuwenswarm/gateway/config/enterprise/catalog.py
+++ b/jiuwenswarm/gateway/config/enterprise/catalog.py
@@ -34,6 +34,9 @@ ENTERPRISE_RECORD_SPECS: dict[str, EnterpriseRecordSpec] = {
"agent_template": EnterpriseRecordSpec(key_fields=("template_id",)),
"a2a_outbound_template": EnterpriseRecordSpec(key_fields=("template_id",)),
"a2a_access_policy_template": EnterpriseRecordSpec(key_fields=("policy_id",)),
+ "a2a_outbound_user_state": EnterpriseRecordSpec(key_fields=("template_id",)),
+ "a2a_outbound_runtime_state": EnterpriseRecordSpec(key_fields=("template_id",)),
+ "a2a_outbound_dispatch": EnterpriseRecordSpec(key_fields=("dispatch_id",)),
"instance_agent_resource": EnterpriseRecordSpec(key_fields=("resource_id",)),
"log_masking_rule": EnterpriseRecordSpec(key_fields=("rule_id",)),
"cron_job": EnterpriseRecordSpec(key_fields=("job_id",)),
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py b/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py
new file mode 100644
index 0000000000..f361c1be73
--- /dev/null
+++ b/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py
@@ -0,0 +1,85 @@
+# coding: utf-8
+# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
+
+"""Enterprise A2A local state and dispatch history tables."""
+
+from __future__ import annotations
+
+from openjiuwen_runtime.foundation.db.table_def import (
+ ColumnDefinition,
+ IndexDefinition,
+ TableDefinition,
+)
+
+A2A_OUTBOUND_USER_STATE_TABLE_DEF = TableDefinition(
+ table_name="a2a_outbound_user_state",
+ columns=[
+ ColumnDefinition(
+ "id", "integer", primary_key=True, autoincrement=True, nullable=False
+ ),
+ ColumnDefinition("template_id", "string", length=100, nullable=False),
+ ColumnDefinition("user_enabled", "boolean", nullable=False, default=True),
+ ColumnDefinition("updated_at", "datetime", nullable=False),
+ ],
+ indexes=[IndexDefinition(["template_id"], unique=True)],
+)
+
+A2A_OUTBOUND_RUNTIME_STATE_TABLE_DEF = TableDefinition(
+ table_name="a2a_outbound_runtime_state",
+ columns=[
+ ColumnDefinition(
+ "id", "integer", primary_key=True, autoincrement=True, nullable=False
+ ),
+ ColumnDefinition("template_id", "string", length=100, nullable=False),
+ ColumnDefinition("availability", "string", length=32, nullable=False),
+ ColumnDefinition("last_checked_at", "datetime", nullable=True),
+ ColumnDefinition("last_success_at", "datetime", nullable=True),
+ ColumnDefinition("last_error_code", "string", length=64, nullable=True),
+ ColumnDefinition("last_error_summary", "string", length=512, nullable=True),
+ ColumnDefinition("updated_at", "datetime", nullable=False),
+ ],
+ indexes=[IndexDefinition(["template_id"], unique=True)],
+)
+
+A2A_OUTBOUND_DISPATCH_TABLE_DEF = TableDefinition(
+ table_name="a2a_outbound_dispatch",
+ columns=[
+ ColumnDefinition(
+ "id", "integer", primary_key=True, autoincrement=True, nullable=False
+ ),
+ ColumnDefinition("dispatch_id", "string", length=100, nullable=False),
+ ColumnDefinition("agent_id", "string", length=100, nullable=False),
+ ColumnDefinition("agent_name", "string", length=128, nullable=True),
+ ColumnDefinition("agent_revision", "integer", nullable=False),
+ ColumnDefinition("mode", "string", length=16, nullable=False),
+ ColumnDefinition("status", "string", length=32, nullable=False),
+ ColumnDefinition("request_message_id", "string", length=100, nullable=False),
+ ColumnDefinition("source_session_id", "string", length=512, nullable=False),
+ ColumnDefinition("source_resource_id", "string", length=100, nullable=True),
+ ColumnDefinition("remote_task_id", "string", length=256, nullable=True),
+ ColumnDefinition("remote_context_id", "string", length=256, nullable=True),
+ ColumnDefinition("accepted_at", "datetime", nullable=True),
+ ColumnDefinition("finished_at", "datetime", nullable=True),
+ ColumnDefinition("result", "json", nullable=True),
+ ColumnDefinition("error_code", "string", length=64, nullable=True),
+ ColumnDefinition("error_summary", "string", length=512, nullable=True),
+ ColumnDefinition("last_polled_at", "datetime", nullable=True),
+ ColumnDefinition("input_length", "integer", nullable=True),
+ ColumnDefinition("input_content_type", "string", length=128, nullable=True),
+ ColumnDefinition("input_digest", "string", length=128, nullable=True),
+ ColumnDefinition("created_at", "datetime", nullable=False),
+ ColumnDefinition("updated_at", "datetime", nullable=False),
+ ],
+ indexes=[
+ IndexDefinition(["dispatch_id"], unique=True),
+ IndexDefinition(["source_session_id"]),
+ IndexDefinition(["source_resource_id"]),
+ IndexDefinition(["created_at"]),
+ ],
+)
+
+__all__ = (
+ "A2A_OUTBOUND_DISPATCH_TABLE_DEF",
+ "A2A_OUTBOUND_RUNTIME_STATE_TABLE_DEF",
+ "A2A_OUTBOUND_USER_STATE_TABLE_DEF",
+)
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py b/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
index 96b6bc66d7..9ffc12b2d9 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/table_init.py
@@ -8,6 +8,11 @@ from __future__ import annotations
from openjiuwen_runtime.foundation.db.handler import DBHandler
from openjiuwen_runtime.foundation.db.table_def import TableDefinition
+from .a2a_models import (
+ A2A_OUTBOUND_DISPATCH_TABLE_DEF,
+ A2A_OUTBOUND_RUNTIME_STATE_TABLE_DEF,
+ A2A_OUTBOUND_USER_STATE_TABLE_DEF,
+)
from .application_config_models import (
LOG_MASKING_RULE_TABLE_DEF,
LOGGING_CONFIG_TABLE_DEF,
@@ -47,6 +52,9 @@ ALL_TABLE_DEFINITIONS: tuple[TableDefinition, ...] = (
AGENT_TEMPLATE_TABLE_DEF,
A2A_OUTBOUND_TEMPLATE_TABLE_DEF,
A2A_ACCESS_POLICY_TEMPLATE_TABLE_DEF,
+ A2A_OUTBOUND_USER_STATE_TABLE_DEF,
+ A2A_OUTBOUND_RUNTIME_STATE_TABLE_DEF,
+ A2A_OUTBOUND_DISPATCH_TABLE_DEF,
INSTANCE_AGENT_RESOURCE_TABLE_DEF,
LOG_MASKING_RULE_TABLE_DEF,
LOGGING_CONFIG_TABLE_DEF,
diff --git a/jiuwenswarm/gateway/storage_assembly/layouts.py b/jiuwenswarm/gateway/storage_assembly/layouts.py
index 5756f6453f..e40a6e5d58 100644
--- a/jiuwenswarm/gateway/storage_assembly/layouts.py
+++ b/jiuwenswarm/gateway/storage_assembly/layouts.py
@@ -264,6 +264,8 @@ def _build_layouts(
for table in ENTERPRISE_RECORD_STORE_NAMES:
if table == "cron_job":
continue
+ if persistent_root is not None and table in _JSON_ONLY_STORES:
+ continue
layouts[table] = _db_table(table)
return layouts
diff --git a/jiuwenswarm/gateway/storage_assembly/setup.py b/jiuwenswarm/gateway/storage_assembly/setup.py
index 7fe0116f67..de9d77a5b5 100644
--- a/jiuwenswarm/gateway/storage_assembly/setup.py
+++ b/jiuwenswarm/gateway/storage_assembly/setup.py
@@ -486,12 +486,26 @@ def create_session_map_repository(store: PersistentStore):
def create_a2a_outbound_repository(
store: PersistentStore,
):
- """Create the personal-edition JSON-backed outbound Repository."""
+ """Create the edition-specific outbound Repository."""
from jiuwenswarm.gateway.a2a_manager.outbound import (
A2AOutboundRepository,
+ EnterpriseA2AProjection,
JsonA2AOutboundRecordCodec,
)
+ if is_enterprise():
+ return EnterpriseA2AProjection(
+ store,
+ templates=create_enterprise_record_repository(
+ store, "a2a_outbound_template"
+ ),
+ user_states=create_enterprise_record_repository(
+ store, "a2a_outbound_user_state"
+ ),
+ runtime_states=create_enterprise_record_repository(
+ store, "a2a_outbound_runtime_state"
+ ),
+ )
return A2AOutboundRepository(store, JsonA2AOutboundRecordCodec())
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
index d9dbca1f40..6255d5af12 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py
@@ -30,6 +30,9 @@ INSTANCE_PURGE_TABLES: tuple[str, ...] = (
"permissions_template",
"a2a_outbound_template",
"a2a_access_policy_template",
+ "a2a_outbound_user_state",
+ "a2a_outbound_runtime_state",
+ "a2a_outbound_dispatch",
"agent_template",
"instance_agent_resource",
"log_masking_rule",
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py
index 9a261f5f19..86656986b6 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py
@@ -21,9 +21,23 @@ from ...schemas.template_schemas import (
)
_TABLE = A2A_OUTBOUND_TEMPLATE_TABLE_DEF.table_name
+_USER_STATE_TABLE = "a2a_outbound_user_state"
+_RUNTIME_STATE_TABLE = "a2a_outbound_runtime_state"
logger = logging.getLogger(__name__)
+def _row_for_restore(
+ row: dict[str, Any] | None, *datetime_fields: str
+) -> dict[str, Any] | None:
+ if row is None:
+ return None
+ values = {key: value for key, value in row.items() if key != "id"}
+ for field in datetime_fields:
+ if field in values:
+ values[field] = parse_iso_datetime(values[field])
+ return values
+
+
def _template_id(value: Any) -> str:
template_id = str(value or "").strip()
if not template_id:
@@ -133,20 +147,47 @@ class A2AOutboundTemplateService:
async def delete(self, template_id: str) -> None:
tid = _template_id(template_id)
repo = require_enterprise_repository(_TABLE)
+ user_states = require_enterprise_repository(_USER_STATE_TABLE)
+ runtime_states = require_enterprise_repository(_RUNTIME_STATE_TABLE)
existing = await repo.get(template_id=tid)
+ old_user_state = await user_states.get(template_id=tid)
+ old_runtime_state = await runtime_states.get(template_id=tid)
credential_ref = (
str(existing.get("credential_ref") or "")
if existing
else self._credentials.reference_for(tid)
)
old_secret = self._credentials.get(credential_ref)
- self._credentials.delete(credential_ref)
try:
+ self._credentials.delete(credential_ref)
if existing is not None:
await repo.delete(template_id=tid)
+ await user_states.delete(template_id=tid)
+ await runtime_states.delete(template_id=tid)
except Exception:
- if old_secret:
- self._credentials.set_for_agent(tid, old_secret)
+ try:
+ projection = _row_for_restore(existing, "created_at", "updated_at")
+ if projection is not None:
+ await repo.upsert(projection)
+ user_state = _row_for_restore(old_user_state, "updated_at")
+ if user_state is not None:
+ await user_states.upsert(user_state)
+ runtime_state = _row_for_restore(
+ old_runtime_state,
+ "last_checked_at",
+ "last_success_at",
+ "updated_at",
+ )
+ if runtime_state is not None:
+ await runtime_states.upsert(runtime_state)
+ if old_secret:
+ self._credentials.set_for_agent(tid, old_secret)
+ except Exception:
+ logger.exception(
+ "[ManagerConfigReceiver] a2a outbound delete rollback failed "
+ "template_id=%s",
+ tid,
+ )
raise
logger.info(
"[ManagerConfigReceiver] a2a_outbound_templates delete template_id=%s",
diff --git a/tests/unit_tests/gateway/test_a2a_outbound_repository.py b/tests/unit_tests/gateway/test_a2a_outbound_repository.py
index f08e59e671..a79b828ea0 100644
--- a/tests/unit_tests/gateway/test_a2a_outbound_repository.py
+++ b/tests/unit_tests/gateway/test_a2a_outbound_repository.py
@@ -464,7 +464,9 @@ async def test_file_backend_cas_preserves_first_terminal_winner(tmp_path) -> Non
}
-def test_storage_registry_exposes_only_personal_a2a_layouts(tmp_path) -> None:
+def test_storage_registry_uses_file_dispatch_for_personal_and_db_for_enterprise(
+ tmp_path,
+) -> None:
personal = build_gateway_store_registry(persistent_root=tmp_path)
enterprise = build_gateway_store_registry()
@@ -477,7 +479,12 @@ def test_storage_registry_exposes_only_personal_a2a_layouts(tmp_path) -> None:
assert personal_layout.file.path == str(tmp_path / filename)
assert personal_layout.file.key_fields == (key,)
assert personal_layout.db is None
- assert enterprise.get(name) is None
+ assert enterprise.get("a2a_outbound_agent") is None
+ enterprise_dispatch = enterprise.get("a2a_outbound_dispatch")
+ assert enterprise_dispatch is not None
+ assert enterprise_dispatch.file is None
+ assert enterprise_dispatch.db is not None
+ assert enterprise_dispatch.db.table == "a2a_outbound_dispatch"
def test_repository_factory_creates_personal_json_repository() -> None:
diff --git a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py
index 53ff94ec77..8b3f6bc3c1 100644
--- a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py
+++ b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py
@@ -7,10 +7,12 @@ from __future__ import annotations
import logging
import sys
from collections.abc import Iterator
+from datetime import datetime, timezone
from types import ModuleType
from typing import Any
import pytest
+from a2a.types import Message, Part, Role, StreamResponse
from fastapi.testclient import TestClient
@@ -54,6 +56,17 @@ def _install_runtime_db_stubs() -> None:
_install_runtime_db_stubs()
from jiuwenswarm.common.secrets import SecretStore
+from jiuwenswarm.gateway.a2a_manager.outbound import (
+ A2AOutboundAvailability,
+ A2AOutboundDispatch,
+ A2AOutboundDispatcher,
+ A2AOutboundDispatchMode,
+ A2AOutboundDispatchStatus,
+ A2AOutboundError,
+ A2AOutboundErrorCode,
+ A2AOutboundRegistry,
+ EnterpriseA2AProjection,
+)
from jiuwenswarm.gateway.config.enterprise import (
clear_enterprise_record_repositories,
set_enterprise_record_repositories,
@@ -65,6 +78,7 @@ from jiuwenswarm.gateway.storage.backends.memory_persistent import (
InMemoryPersistentBackend,
)
from jiuwenswarm.gateway.storage_assembly.setup import (
+ create_a2a_outbound_repository,
create_enterprise_record_repositories,
)
from jiuwenswarm.infrastructure.module_importer import (
@@ -87,6 +101,29 @@ class _Secrets:
self.values.pop(key, None)
+class _CompletedClient:
+ async def send_message(self, request: Any, *, context: Any = None):
+ del request, context
+ yield StreamResponse(
+ message=Message(
+ message_id="remote-message",
+ role=Role.ROLE_AGENT,
+ parts=[Part(text="done")],
+ )
+ )
+
+ async def close(self) -> None:
+ return None
+
+
+class _UnreachableClient(_CompletedClient):
+ async def send_message(self, request: Any, *, context: Any = None):
+ del request, context
+ if False:
+ yield None
+ raise OSError("connection refused")
+
+
def _outbound_payload(
*, operation: str = "replace", value: str | None = "secret"
) -> dict[str, Any]:
@@ -117,6 +154,14 @@ def _outbound_payload(
}
+def _projection_record() -> dict[str, Any]:
+ payload = _outbound_payload(operation="clear", value=None)
+ payload.pop("credential")
+ payload["credential_ref"] = None
+ payload["created_at"] = "2026-09-05T00:00:00Z"
+ return payload
+
+
@pytest.fixture
def a2a_receiver() -> Iterator[tuple[TestClient, dict[str, Any], _Secrets]]:
store = InMemoryPersistentBackend()
@@ -189,7 +234,43 @@ def test_a2a_outbound_receiver_crud_and_secret_store(
assert projection["credential_ref"] is None
assert credential_ref not in secrets.values
+ user_states = repos["a2a_outbound_user_state"]
+ runtime_states = repos["a2a_outbound_runtime_state"]
+ dispatches = repos["a2a_outbound_dispatch"]
+ client.portal.call(
+ lambda: user_states.create(
+ {
+ "template_id": "a2a-weather",
+ "user_enabled": False,
+ "updated_at": "2026-09-05T00:00:00Z",
+ }
+ )
+ )
+ client.portal.call(
+ lambda: runtime_states.create(
+ {
+ "template_id": "a2a-weather",
+ "availability": "available",
+ "updated_at": "2026-09-05T00:00:00Z",
+ }
+ )
+ )
+ client.portal.call(
+ lambda: dispatches.create(
+ {"dispatch_id": "dispatch-history", "agent_id": "a2a-weather"}
+ )
+ )
+
assert client.request("DELETE", f"{path}/a2a-weather", json={}).status_code == 200
+ assert client.portal.call(
+ lambda: user_states.get(template_id="a2a-weather")
+ ) is None
+ assert client.portal.call(
+ lambda: runtime_states.get(template_id="a2a-weather")
+ ) is None
+ assert client.portal.call(
+ lambda: dispatches.get(dispatch_id="dispatch-history")
+ ) is not None
assert client.request("DELETE", f"{path}/a2a-weather", json={}).status_code == 200
@@ -356,16 +437,25 @@ def test_a2a_outbound_purge_removes_projection_and_secret(
assert secrets.values == {}
assert "a2a_outbound_template" in lifecycle.INSTANCE_PURGE_TABLES
assert "a2a_access_policy_template" in lifecycle.INSTANCE_PURGE_TABLES
+ assert "a2a_outbound_user_state" in lifecycle.INSTANCE_PURGE_TABLES
+ assert "a2a_outbound_runtime_state" in lifecycle.INSTANCE_PURGE_TABLES
+ assert "a2a_outbound_dispatch" in lifecycle.INSTANCE_PURGE_TABLES
def test_a2a_tables_are_in_enterprise_init_and_catalog() -> None:
table_names = {definition.table_name for definition in ALL_TABLE_DEFINITIONS}
assert "a2a_outbound_template" in table_names
assert "a2a_access_policy_template" in table_names
+ assert "a2a_outbound_user_state" in table_names
+ assert "a2a_outbound_runtime_state" in table_names
+ assert "a2a_outbound_dispatch" in table_names
repos = create_enterprise_record_repositories(InMemoryPersistentBackend())
assert "a2a_outbound_template" in repos
assert "a2a_access_policy_template" in repos
+ assert "a2a_outbound_user_state" in repos
+ assert "a2a_outbound_runtime_state" in repos
+ assert "a2a_outbound_dispatch" in repos
def test_manager_config_public_endpoint_can_advertise_https() -> None:
@@ -381,3 +471,267 @@ def test_manager_config_public_endpoint_can_advertise_https() -> None:
assert public_endpoint.resolve_public_endpoint(settings) == (
"https://gateway.test:443"
)
+
+
+async def test_enterprise_projection_merges_manager_user_and_runtime_state() -> None:
+ store = InMemoryPersistentBackend()
+ repos = create_enterprise_record_repositories(store)
+ await repos["a2a_outbound_template"].create(_projection_record())
+ projection = EnterpriseA2AProjection(
+ store,
+ templates=repos["a2a_outbound_template"],
+ user_states=repos["a2a_outbound_user_state"],
+ runtime_states=repos["a2a_outbound_runtime_state"],
+ )
+ registry = A2AOutboundRegistry(projection)
+
+ initial = await projection.get_projected_agent("a2a-weather")
+ assert initial is not None
+ assert initial.manager_enabled is True
+ assert initial.user_enabled is True
+ assert initial.effective_enabled is True
+ assert initial.agent.enabled is True
+
+ disabled = await projection.set_user_enabled("a2a-weather", False)
+ assert disabled.manager_enabled is True
+ assert disabled.user_enabled is False
+ assert disabled.effective_enabled is False
+ user_row = await store.get(
+ "a2a_outbound_user_state", {"template_id": "a2a-weather"}
+ )
+ assert isinstance(user_row["updated_at"], datetime)
+ with pytest.raises(A2AOutboundError) as exc_info:
+ await projection.set_user_enabled("missing-agent", True)
+ assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_REGISTERED
+ await repos["a2a_outbound_template"].update(
+ {"template_id": "a2a-weather"},
+ {"template_name": "Weather Agent v2", "card_revision": 2},
+ )
+ persisted = await projection.get_projected_agent("a2a-weather")
+ assert persisted is not None and persisted.user_enabled is False
+
+ await projection.set_user_enabled("a2a-weather", True)
+ await repos["a2a_outbound_template"].update(
+ {"template_id": "a2a-weather"}, {"enabled": False}
+ )
+ manager_disabled = await projection.get_projected_agent("a2a-weather")
+ assert manager_disabled is not None
+ assert manager_disabled.manager_enabled is False
+ assert manager_disabled.user_enabled is True
+ assert manager_disabled.effective_enabled is False
+ assert manager_disabled.agent.enabled is False
+
+ await projection.update_runtime_state(
+ "a2a-weather",
+ A2AOutboundAvailability.UNREACHABLE,
+ error_code=A2AOutboundErrorCode.CARD_FETCH_FAILED.value,
+ )
+ runtime_failed = await projection.get_projected_agent("a2a-weather")
+ assert runtime_failed is not None
+ assert runtime_failed.agent.availability is A2AOutboundAvailability.UNREACHABLE
+ assert runtime_failed.agent.last_error_summary == "无法获取第三方 Agent Card。"
+ runtime_row = await store.get(
+ "a2a_outbound_runtime_state", {"template_id": "a2a-weather"}
+ )
+ assert isinstance(runtime_row["updated_at"], datetime)
+ assert isinstance(runtime_row["last_checked_at"], datetime)
+
+ listed = await registry.list_agents()
+ assert listed["items"][0]["manager_enabled"] is False
+ assert listed["items"][0]["user_enabled"] is True
+ assert listed["items"][0]["effective_enabled"] is False
+ with pytest.raises(A2AOutboundError) as exc_info:
+ await registry.edit_agent("a2a-weather")
+ assert exc_info.value.code is A2AOutboundErrorCode.STORE_INVALID
+
+
+async def test_enterprise_projection_reuses_dispatch_repository() -> None:
+ store = InMemoryPersistentBackend()
+ repos = create_enterprise_record_repositories(store)
+ await repos["a2a_outbound_template"].create(_projection_record())
+ projection = EnterpriseA2AProjection(
+ store,
+ templates=repos["a2a_outbound_template"],
+ user_states=repos["a2a_outbound_user_state"],
+ runtime_states=repos["a2a_outbound_runtime_state"],
+ )
+ dispatch = A2AOutboundDispatch(
+ dispatch_id="dispatch-1",
+ agent_id="a2a-weather",
+ agent_name="Weather Agent",
+ agent_revision=1,
+ mode=A2AOutboundDispatchMode.ASYNC,
+ status=A2AOutboundDispatchStatus.CREATED,
+ request_message_id="message-1",
+ source_session_id="session-1",
+ source_resource_id="resource-1",
+ created_at="2026-09-05T00:00:00Z",
+ updated_at="2026-09-05T00:00:00Z",
+ )
+
+ await projection.create_dispatch(dispatch)
+ await projection.transition_dispatch(
+ "dispatch-1",
+ A2AOutboundDispatchStatus.COMPLETED,
+ accepted_at="2026-09-05T00:00:01Z",
+ )
+ restored = await projection.get_dispatch("dispatch-1")
+ assert restored is not None
+ assert restored.status is A2AOutboundDispatchStatus.COMPLETED
+ assert restored.agent_name == "Weather Agent"
+ assert restored.source_resource_id == "resource-1"
+ dispatch_row = await store.get(
+ "a2a_outbound_dispatch", {"dispatch_id": "dispatch-1"}
+ )
+ assert isinstance(dispatch_row["created_at"], datetime)
+ assert isinstance(dispatch_row["updated_at"], datetime)
+ assert isinstance(dispatch_row["accepted_at"], datetime)
+ assert isinstance(dispatch_row["finished_at"], datetime)
+
+
+async def test_enterprise_dispatch_updates_shared_runtime_state() -> None:
+ store = InMemoryPersistentBackend()
+ repos = create_enterprise_record_repositories(store)
+ await repos["a2a_outbound_template"].create(_projection_record())
+ projection = EnterpriseA2AProjection(
+ store,
+ templates=repos["a2a_outbound_template"],
+ user_states=repos["a2a_outbound_user_state"],
+ runtime_states=repos["a2a_outbound_runtime_state"],
+ )
+
+ async def build_client(agent: Any, credential: str) -> _CompletedClient:
+ del agent, credential
+ return _CompletedClient()
+
+ dispatcher = A2AOutboundDispatcher(projection, client_builder=build_client)
+ result = await dispatcher.dispatch(
+ agent_id="a2a-weather",
+ task="weather",
+ mode="sync",
+ source_session_id="session-1",
+ )
+
+ assert result["status"] == A2AOutboundDispatchStatus.COMPLETED.value
+ runtime_row = await store.get(
+ "a2a_outbound_runtime_state", {"template_id": "a2a-weather"}
+ )
+ assert runtime_row["availability"] == A2AOutboundAvailability.AVAILABLE.value
+ assert isinstance(runtime_row["last_success_at"], datetime)
+
+
+async def test_enterprise_dispatch_records_unreachable_runtime_state() -> None:
+ store = InMemoryPersistentBackend()
+ repos = create_enterprise_record_repositories(store)
+ await repos["a2a_outbound_template"].create(_projection_record())
+ projection = EnterpriseA2AProjection(
+ store,
+ templates=repos["a2a_outbound_template"],
+ user_states=repos["a2a_outbound_user_state"],
+ runtime_states=repos["a2a_outbound_runtime_state"],
+ )
+
+ async def build_client(agent: Any, credential: str) -> _UnreachableClient:
+ del agent, credential
+ return _UnreachableClient()
+
+ dispatcher = A2AOutboundDispatcher(projection, client_builder=build_client)
+ result = await dispatcher.dispatch(
+ agent_id="a2a-weather",
+ task="weather",
+ mode="sync",
+ source_session_id="session-1",
+ )
+
+ assert result["status"] == A2AOutboundDispatchStatus.DISPATCH_FAILED.value
+ runtime_row = await store.get(
+ "a2a_outbound_runtime_state", {"template_id": "a2a-weather"}
+ )
+ assert runtime_row["availability"] == A2AOutboundAvailability.UNREACHABLE.value
+ assert (
+ runtime_row["last_error_code"] == A2AOutboundErrorCode.AGENT_UNAVAILABLE.value
+ )
+
+
+def test_a2a_delete_restores_projection_and_local_state_on_cleanup_failure(
+ a2a_receiver: tuple[TestClient, dict[str, Any], _Secrets],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client, repos, secrets = a2a_receiver
+ path = "/api/v1/a2a-outbound-templates"
+ credential_ref = "a2a/outbound/a2a-weather.api_key"
+ assert client.post(path, json=_outbound_payload()).status_code == 200
+ user_states = repos["a2a_outbound_user_state"]
+ runtime_states = repos["a2a_outbound_runtime_state"]
+ client.portal.call(
+ lambda: user_states.create(
+ {
+ "template_id": "a2a-weather",
+ "user_enabled": False,
+ "updated_at": datetime.now(timezone.utc),
+ }
+ )
+ )
+ client.portal.call(
+ lambda: runtime_states.create(
+ {
+ "template_id": "a2a-weather",
+ "availability": A2AOutboundAvailability.UNREACHABLE.value,
+ "updated_at": datetime.now(timezone.utc),
+ }
+ )
+ )
+ original_delete = runtime_states.delete
+
+ async def fail_delete(*args: Any, **kwargs: Any) -> bool:
+ del args, kwargs
+ raise RuntimeError("runtime state delete failed")
+
+ monkeypatch.setattr(runtime_states, "delete", fail_delete)
+ template_module = import_manager_config_receiver_module(
+ "core.template.a2a_outbound_template"
+ )
+ service = template_module.A2AOutboundTemplateService()
+ with pytest.raises(RuntimeError, match="runtime state delete failed"):
+ client.portal.call(lambda: service.delete("a2a-weather"))
+
+ assert (
+ client.portal.call(
+ lambda: repos["a2a_outbound_template"].get(template_id="a2a-weather")
+ )
+ is not None
+ )
+ assert (
+ client.portal.call(lambda: user_states.get(template_id="a2a-weather"))[
+ "user_enabled"
+ ]
+ is False
+ )
+ assert client.portal.call(
+ lambda: runtime_states.get(template_id="a2a-weather")
+ )["availability"] == A2AOutboundAvailability.UNREACHABLE.value
+ assert secrets.values[credential_ref] == "secret"
+
+ monkeypatch.setattr(runtime_states, "delete", original_delete)
+ client.portal.call(lambda: service.delete("a2a-weather"))
+ assert (
+ client.portal.call(lambda: user_states.get(template_id="a2a-weather")) is None
+ )
+
+
+async def test_repository_factory_creates_enterprise_projection(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
+ store = InMemoryPersistentBackend()
+ repos = create_enterprise_record_repositories(store)
+ await repos["a2a_outbound_template"].create(_projection_record())
+ repository = create_a2a_outbound_repository(store)
+ assert isinstance(repository, EnterpriseA2AProjection)
+ projected = await repository.get_agent("a2a-weather")
+ assert projected is not None and projected.display_name == "Weather Agent"