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
a2a: 出站注册与持久化(第二批)
NickFuryXXX2563f2bc0dad
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 17efcb62bb..2327dd1b05 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -551,7 +551,7 @@},"a2aIngress": {"title": "A2A Control Center",- "subtitle": "Manage the A2A ingress service exposed by JiuwenSwarm.",+ "subtitle": "Manage the A2A service exposed by JiuwenSwarm.","tabs": { "ariaLabel": "A2A Control Center pages", "config": "Ingress Configuration", "history": "Processing History" },"enable": "Enable service", "enabling": "Enabling...", "disable": "Disable service", "disabling": "Disabling...", "reload": "Reload", "reloading": "Reloading...","save": "Save configuration", "saveAndApply": "Save and apply", "applying": "Applying...", "saved": "Configuration saved; it has not been applied to the running service.", "savedAndApplied": "Configuration saved and applied.",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex c40287d280..4527c799da 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -552,8 +552,8 @@},"a2aIngress": {"title": "A2A 调度中心",- "subtitle": "管理 JiuwenSwarm 对外提供的 A2A 入站服务。",- "tabs": { "ariaLabel": "A2A 调度中心页面", "config": "入向配置", "history": "处理历史" },+ "subtitle": "管理 JiuwenSwarm 对外提供的 A2A 服务。",+ "tabs": { "ariaLabel": "A2A 调度中心页面", "config": "入站配置", "history": "处理历史" },"enable": "启用服务", "enabling": "启用中...", "disable": "停用服务", "disabling": "停用中...", "reload": "重新加载", "reloading": "重载中...","save": "保存配置", "saveAndApply": "保存并应用", "applying": "应用中...", "saved": "配置已保存,尚未应用到正在运行的服务。", "savedAndApplied": "配置已保存并应用。","disconnected": "当前未连接到 Gateway,无法读取或修改 A2A 服务。",diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py b/jiuwenswarm/gateway/a2a_manager/outbound/__init__.pynew file mode 100644index 0000000000..f0f315713f--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py@@ -0,0 +1,41 @@+"""A2A outbound domain models and persistence contracts."""++from .credentials import A2AOutboundCredentialStore+from .errors import A2AOutboundError, A2AOutboundErrorCode, safe_error_summary+from .models import (+ A2ACompatibleInterface,+ A2ADiscoveredAgent,+ A2AOutboundAgent,+ A2AOutboundAvailability,+ A2AOutboundDiscovery,+ A2AOutboundDispatch,+ A2AOutboundDispatchMode,+ A2AOutboundDispatchStatus,+ TERMINAL_DISPATCH_STATUSES,+)+from .repository import (+ A2A_OUTBOUND_AGENT_STORE_NAME,+ A2A_OUTBOUND_DISPATCH_STORE_NAME,+ A2AOutboundRepository,+ JsonA2AOutboundRecordCodec,+)++__all__ = [+ "A2ACompatibleInterface",+ "A2ADiscoveredAgent",+ "A2AOutboundAgent",+ "A2AOutboundAvailability",+ "A2AOutboundCredentialStore",+ "A2AOutboundDiscovery",+ "A2AOutboundDispatch",+ "A2AOutboundDispatchMode",+ "A2AOutboundDispatchStatus",+ "A2AOutboundError",+ "A2AOutboundErrorCode",+ "A2AOutboundRepository",+ "A2A_OUTBOUND_AGENT_STORE_NAME",+ "A2A_OUTBOUND_DISPATCH_STORE_NAME",+ "JsonA2AOutboundRecordCodec",+ "TERMINAL_DISPATCH_STATUSES",+ "safe_error_summary",+]diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/credentials.py b/jiuwenswarm/gateway/a2a_manager/outbound/credentials.pynew file mode 100644index 0000000000..191d83f4a7--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/credentials.py@@ -0,0 +1,76 @@+"""SecretStore-backed credential references for registered outbound agents."""++from __future__ import annotations++import re+from typing import Protocol++from jiuwenswarm.common.secrets import SecretStore+++_CREDENTIAL_PREFIX = "a2a/outbound/"+_CREDENTIAL_REF_RE = re.compile(r"^a2a/outbound/([^/\\\r\n]+)\.api_key$")+++class SecretStoreLike(Protocol):+ def get(self, key: str) -> str:+ raise NotImplementedError++ def set(+ self, key: str, value: str, *, algorithm: str | None = None+ ) -> None:+ raise NotImplementedError++ def delete(self, key: str) -> None:+ raise NotImplementedError+++class A2AOutboundCredentialStore:+ """Own credential values while domain records retain only ``credential_ref``."""++ def __init__(self, secret_store: SecretStoreLike | None = None) -> None:+ self._store = secret_store or SecretStore.get_instance()++ @staticmethod+ def reference_for(agent_id: str) -> str:+ normalized = str(agent_id or "").strip()+ if not normalized or any(char in normalized for char in "\\/\r\n"):+ raise ValueError("invalid A2A outbound agent_id")+ return f"{_CREDENTIAL_PREFIX}{normalized}.api_key"++ @staticmethod+ def validate_reference(credential_ref: str) -> str:+ normalized = str(credential_ref or "").strip()+ if _CREDENTIAL_REF_RE.fullmatch(normalized) is None:+ raise ValueError("invalid A2A outbound credential_ref")+ return normalized++ @classmethod+ def validate_for_agent(cls, agent_id: str, credential_ref: str) -> str:+ normalized = cls.validate_reference(credential_ref)+ if normalized != cls.reference_for(agent_id):+ raise ValueError("credential_ref does not belong to A2A outbound agent")+ return normalized++ def set_for_agent(+ self,+ agent_id: str,+ secret: str,+ *,+ algorithm: str | None = None,+ ) -> str:+ credential_ref = self.reference_for(agent_id)+ self._store.set(credential_ref, str(secret), algorithm=algorithm)+ return credential_ref++ def get(self, credential_ref: str | None) -> str:+ if not credential_ref:+ return ""+ return self._store.get(self.validate_reference(credential_ref))++ def delete(self, credential_ref: str | None) -> None:+ if credential_ref:+ self._store.delete(self.validate_reference(credential_ref))+++__all__ = ["A2AOutboundCredentialStore", "SecretStoreLike"]diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py b/jiuwenswarm/gateway/a2a_manager/outbound/errors.pynew file mode 100644index 0000000000..059e740d1d--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/errors.py@@ -0,0 +1,83 @@+"""Stable errors exposed by the A2A outbound domain."""++from __future__ import annotations++from enum import Enum+++class A2AOutboundErrorCode(str, Enum):+ DISCOVERY_URL_INVALID = "A2A_DISCOVERY_URL_INVALID"+ DISCOVERY_BLOCKED = "A2A_DISCOVERY_BLOCKED"+ CARD_FETCH_FAILED = "A2A_CARD_FETCH_FAILED"+ CARD_INVALID = "A2A_CARD_INVALID"+ AGENT_NOT_REGISTERED = "A2A_AGENT_NOT_REGISTERED"+ AGENT_DISABLED = "A2A_AGENT_DISABLED"+ AGENT_UNAVAILABLE = "A2A_AGENT_UNAVAILABLE"+ AGENT_REVIEW_REQUIRED = "A2A_AGENT_REVIEW_REQUIRED"+ AUTH_REQUIRED = "A2A_AUTH_REQUIRED"+ DISPATCH_NOT_FOUND = "A2A_DISPATCH_NOT_FOUND"+ DISPATCH_REJECTED = "A2A_DISPATCH_REJECTED"+ DISPATCH_TIMEOUT = "A2A_DISPATCH_TIMEOUT"+ DISPATCH_CONFLICT = "A2A_DISPATCH_CONFLICT"+ REMOTE_STATUS_UNKNOWN = "A2A_REMOTE_STATUS_UNKNOWN"+ OUTBOUND_BUSY = "A2A_OUTBOUND_BUSY"+ STORE_INVALID = "A2A_OUTBOUND_STORE_INVALID"+++_SAFE_SUMMARIES: dict[A2AOutboundErrorCode, str] = {+ A2AOutboundErrorCode.DISCOVERY_URL_INVALID: "发现地址无效。",+ A2AOutboundErrorCode.DISCOVERY_BLOCKED: "发现地址被安全策略拦截。",+ A2AOutboundErrorCode.CARD_FETCH_FAILED: "无法获取第三方 Agent Card。",+ A2AOutboundErrorCode.CARD_INVALID: "第三方 Agent Card 无效或不兼容。",+ A2AOutboundErrorCode.AGENT_NOT_REGISTERED: "指定的第三方 Agent 尚未注册。",+ A2AOutboundErrorCode.AGENT_DISABLED: "指定的第三方 Agent 已停用。",+ A2AOutboundErrorCode.AGENT_UNAVAILABLE: "指定的第三方 Agent 当前不可用。",+ A2AOutboundErrorCode.AGENT_REVIEW_REQUIRED: "第三方 Agent 配置变化需要确认。",+ A2AOutboundErrorCode.AUTH_REQUIRED: "第三方 Agent 需要有效凭据。",+ A2AOutboundErrorCode.DISPATCH_NOT_FOUND: "未找到指定的出站请求。",+ A2AOutboundErrorCode.DISPATCH_REJECTED: "第三方 Agent 拒绝了本次请求。",+ A2AOutboundErrorCode.DISPATCH_TIMEOUT: "等待第三方 Agent 回复超时。",+ A2AOutboundErrorCode.DISPATCH_CONFLICT: "出站请求状态已发生变化。",+ A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN: "暂时无法确认第三方请求状态。",+ A2AOutboundErrorCode.OUTBOUND_BUSY: "A2A 出站服务当前繁忙。",+ A2AOutboundErrorCode.STORE_INVALID: "A2A 出站数据无效。",+}+++def safe_error_summary(code: A2AOutboundErrorCode | str) -> str:+ """Return a fixed displayable summary without exposing exception details."""+ try:+ normalized = (+ code+ if isinstance(code, A2AOutboundErrorCode)+ else A2AOutboundErrorCode(str(code))+ )+ except ValueError:+ return "A2A 出站请求处理失败。"+ return _SAFE_SUMMARIES[normalized]+++class A2AOutboundError(RuntimeError):+ """Domain error whose public text is selected from a stable code."""++ def __init__(self, code: A2AOutboundErrorCode | str) -> None:+ try:+ self.code = (+ code+ if isinstance(code, A2AOutboundErrorCode)+ else A2AOutboundErrorCode(str(code))+ )+ except ValueError:+ self.code = A2AOutboundErrorCode.STORE_INVALID+ super().__init__(safe_error_summary(self.code))++ @property+ def summary(self) -> str:+ return safe_error_summary(self.code)+++__all__ = [+ "A2AOutboundError",+ "A2AOutboundErrorCode",+ "safe_error_summary",+]diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/locks.py b/jiuwenswarm/gateway/a2a_manager/outbound/locks.pynew file mode 100644index 0000000000..4c64d02f8b--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/locks.py@@ -0,0 +1,53 @@+"""Per-entity asyncio locks used by the A2A outbound repositories."""++from __future__ import annotations++import asyncio+from contextlib import asynccontextmanager+from dataclasses import dataclass+from typing import AsyncIterator+++@dataclass+class _LockEntry:+ lock: asyncio.Lock+ users: int = 0+++class KeyedLockPool:+ """Create one lock per active key and evict it after the last user exits."""++ def __init__(self) -> None:+ self._guard = asyncio.Lock()+ self._entries: dict[str, _LockEntry] = {}++ @property+ def size(self) -> int:+ return len(self._entries)++ async def _acquire_entry(self, key: str) -> tuple[str, _LockEntry]:+ normalized = str(key or "").strip()+ if not normalized:+ raise ValueError("lock key cannot be empty")+ async with self._guard:+ entry = self._entries.get(normalized)+ if entry is None:+ entry = _LockEntry(lock=asyncio.Lock())+ self._entries[normalized] = entry+ entry.users += 1+ return normalized, entry++ @asynccontextmanager+ async def hold(self, key: str) -> AsyncIterator[None]:+ normalized, entry = await self._acquire_entry(key)+ try:+ async with entry.lock:+ yield+ finally:+ async with self._guard:+ entry.users -= 1+ if entry.users == 0 and not entry.lock.locked():+ self._entries.pop(normalized, None)+++__all__ = ["KeyedLockPool"]diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/models.py b/jiuwenswarm/gateway/a2a_manager/outbound/models.pynew file mode 100644index 0000000000..d6dfe36831--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/models.py@@ -0,0 +1,398 @@+"""Domain models for A2A outbound discovery, registration, and dispatch."""++from __future__ import annotations++from dataclasses import asdict, dataclass, field, replace+from enum import Enum+from typing import Any, Mapping++from .credentials import A2AOutboundCredentialStore+from .errors import A2AOutboundError, A2AOutboundErrorCode+++class A2AOutboundAvailability(str, Enum):+ AVAILABLE = "available"+ UNREACHABLE = "unreachable"+ INCOMPATIBLE = "incompatible"+ REVIEW_REQUIRED = "review_required"+++class A2AOutboundDispatchMode(str, Enum):+ SYNC = "sync"+ ASYNC = "async"+++class A2AOutboundDispatchStatus(str, Enum):+ CREATED = "created"+ SUBMITTING = "submitting"+ ACCEPTED = "accepted"+ WORKING = "working"+ COMPLETED = "completed"+ FAILED = "failed"+ CANCELED = "canceled"+ REJECTED = "rejected"+ INPUT_REQUIRED = "input_required"+ AUTH_REQUIRED = "auth_required"+ UNKNOWN = "unknown"+ TIMED_OUT = "timed_out"+ DISPATCH_FAILED = "dispatch_failed"+++TERMINAL_DISPATCH_STATUSES: frozenset[A2AOutboundDispatchStatus] = frozenset(+ {+ A2AOutboundDispatchStatus.COMPLETED,+ A2AOutboundDispatchStatus.FAILED,+ A2AOutboundDispatchStatus.CANCELED,+ A2AOutboundDispatchStatus.REJECTED,+ A2AOutboundDispatchStatus.DISPATCH_FAILED,+ }+)++_SENSITIVE_KEYS = frozenset(+ {+ "authorization",+ "cookie",+ "password",+ "secret",+ "token",+ "access_token",+ "refresh_token",+ "api_key",+ "apikey",+ "credential",+ "credentials",+ }+)+_REDACTED = "******"+_SENSITIVE_KEY_COMPACTS = (+ "authorization",+ "cookie",+ "password",+ "secret",+ "token",+ "apikey",+ "credential",+)+++def _is_sensitive_key(key: str) -> bool:+ normalized = key.strip().lower().replace("-", "_")+ compact = normalized.replace("_", "")+ return (+ normalized in _SENSITIVE_KEYS+ or compact.startswith(_SENSITIVE_KEY_COMPACTS)+ or compact.endswith(_SENSITIVE_KEY_COMPACTS)+ )+++def sanitize_persisted_value(value: Any) -> Any:+ """Recursively redact credential-like values before repository persistence."""+ if isinstance(value, Mapping):+ result: dict[str, Any] = {}+ for raw_key, item in value.items():+ key = str(raw_key)+ result[key] = (+ _REDACTED if _is_sensitive_key(key) else sanitize_persisted_value(item)+ )+ return result+ if isinstance(value, (list, tuple)):+ return [sanitize_persisted_value(item) for item in value]+ if value is None or isinstance(value, (str, int, float, bool)):+ return value+ return str(value)+++def _required(value: Any, field_name: str) -> str:+ text = str(value or "").strip()+ if not text:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)+ return text+++def _positive_seconds(value: Any) -> float:+ try:+ parsed = float(value)+ except (TypeError, ValueError) as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID) from exc+ if parsed <= 0:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)+ return parsed+++@dataclass(frozen=True)+class A2ACompatibleInterface:+ protocol_binding: str+ protocol_version: str+ url: str++ def validate(self) -> "A2ACompatibleInterface":+ _required(self.protocol_binding, "protocol_binding")+ _required(self.protocol_version, "protocol_version")+ _required(self.url, "url")+ return self++ @classmethod+ def from_dict(cls, data: Mapping[str, Any]) -> "A2ACompatibleInterface":+ return cls(+ protocol_binding=str(data.get("protocol_binding") or "").strip(),+ protocol_version=str(data.get("protocol_version") or "").strip(),+ url=str(data.get("url") or "").strip(),+ ).validate()+++@dataclass(frozen=True)+class A2ADiscoveredAgent:+ name: str+ description: str = ""+ version: str = ""+ skills: tuple[dict[str, Any], ...] = ()+ compatible_interfaces: tuple[A2ACompatibleInterface, ...] = ()++ def to_dict(self) -> dict[str, Any]:+ return {+ "name": self.name,+ "description": self.description,+ "version": self.version,+ "skills": sanitize_persisted_value(list(self.skills)),+ "compatible_interfaces": [+ asdict(item) for item in self.compatible_interfaces+ ],+ }+++@dataclass(frozen=True)+class A2AOutboundDiscovery:+ """Short-lived discovery preview. It is deliberately not a callable registration."""++ discovery_id: str+ expires_at: str+ source_url: str+ card_path: str+ card_fingerprint: str+ agent: A2ADiscoveredAgent+ agent_card: dict[str, Any] = field(default_factory=dict)+ security_requirements: tuple[dict[str, Any], ...] = ()+ warnings: tuple[str, ...] = ()++ def to_dict(self) -> dict[str, Any]:+ return {+ "discovery_id": self.discovery_id,+ "expires_at": self.expires_at,+ "source_url": self.source_url,+ "card_path": self.card_path,+ "card_fingerprint": self.card_fingerprint,+ "agent": self.agent.to_dict(),+ "agent_card": sanitize_persisted_value(self.agent_card),+ "security_requirements": sanitize_persisted_value(+ list(self.security_requirements)+ ),+ "warnings": list(self.warnings),+ }+++@dataclass(frozen=True)+class A2AOutboundAgent:+ agent_id: str+ display_name: str+ source_url: str+ card_path: str+ card_fingerprint: str+ card_revision: int+ agent_card: dict[str, Any]+ selected_interface: A2ACompatibleInterface+ enabled: bool+ availability: A2AOutboundAvailability+ credential_ref: str | None+ connect_timeout_seconds: float+ sync_wait_seconds: float+ last_checked_at: str | None = None+ last_success_at: str | None = None+ last_error_code: str | None = None+ last_error_summary: str | None = None+ created_at: str = ""+ updated_at: str = ""++ def validate(self) -> "A2AOutboundAgent":+ for name in (+ "agent_id",+ "display_name",+ "source_url",+ "card_path",+ "card_fingerprint",+ "created_at",+ "updated_at",+ ):+ _required(getattr(self, name), name)+ if int(self.card_revision) < 1:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)+ _positive_seconds(self.connect_timeout_seconds)+ _positive_seconds(self.sync_wait_seconds)+ self.selected_interface.validate()+ if self.credential_ref is not None:+ try:+ A2AOutboundCredentialStore.validate_for_agent(+ self.agent_id,+ _required(self.credential_ref, "credential_ref"),+ )+ except ValueError as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID) from exc+ return self++ def to_record(self) -> dict[str, Any]:+ self.validate()+ record = asdict(self)+ record["availability"] = self.availability.value+ record["agent_card"] = sanitize_persisted_value(self.agent_card)+ record["selected_interface"] = asdict(self.selected_interface)+ return record++ def public_dict(self) -> dict[str, Any]:+ record = self.to_record()+ record["has_credential"] = bool(self.credential_ref)+ record.pop("credential_ref", None)+ return record++ @classmethod+ def from_record(cls, record: Mapping[str, Any]) -> "A2AOutboundAgent":+ try:+ item = cls(+ agent_id=str(record.get("agent_id") or "").strip(),+ display_name=str(record.get("display_name") or "").strip(),+ source_url=str(record.get("source_url") or "").strip(),+ card_path=str(record.get("card_path") or "").strip(),+ 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 {}),+ selected_interface=A2ACompatibleInterface.from_dict(+ dict(record.get("selected_interface") or {})+ ),+ enabled=bool(record.get("enabled")),+ availability=A2AOutboundAvailability(+ str(record.get("availability") or "")+ ),+ credential_ref=(+ str(record.get("credential_ref")).strip()+ if record.get("credential_ref") is not None+ else None+ ),+ connect_timeout_seconds=float(+ record.get("connect_timeout_seconds") or 0+ ),+ sync_wait_seconds=float(record.get("sync_wait_seconds") or 0),+ last_checked_at=record.get("last_checked_at"),+ last_success_at=record.get("last_success_at"),+ last_error_code=record.get("last_error_code"),+ last_error_summary=record.get("last_error_summary"),+ created_at=str(record.get("created_at") or ""),+ updated_at=str(record.get("updated_at") or ""),+ )+ except (TypeError, ValueError) as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID) from exc+ return item.validate()+++@dataclass(frozen=True)+class A2AOutboundDispatch:+ dispatch_id: str+ agent_id: str+ agent_revision: int+ mode: A2AOutboundDispatchMode+ status: A2AOutboundDispatchStatus+ request_message_id: str+ source_session_id: str+ created_at: str+ updated_at: str+ remote_task_id: str | None = None+ remote_context_id: str | None = None+ accepted_at: str | None = None+ finished_at: str | None = None+ result: dict[str, Any] | None = None+ error_code: str | None = None+ error_summary: str | None = None+ last_polled_at: str | None = None+ input_length: int | None = None+ input_content_type: str | None = None+ input_digest: str | None = None++ @property+ def is_terminal(self) -> bool:+ return self.status in TERMINAL_DISPATCH_STATUSES++ def validate(self) -> "A2AOutboundDispatch":+ for name in (+ "dispatch_id",+ "agent_id",+ "request_message_id",+ "source_session_id",+ "created_at",+ "updated_at",+ ):+ _required(getattr(self, name), name)+ if int(self.agent_revision) < 1:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)+ if self.input_length is not None and int(self.input_length) < 0:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)+ return self++ def to_record(self) -> dict[str, Any]:+ self.validate()+ record = asdict(self)+ record["mode"] = self.mode.value+ record["status"] = self.status.value+ if self.result is not None:+ record["result"] = sanitize_persisted_value(self.result)+ return record++ def with_changes(self, **changes: Any) -> "A2AOutboundDispatch":+ return replace(self, **changes).validate()++ @classmethod+ def from_record(cls, record: Mapping[str, Any]) -> "A2AOutboundDispatch":+ try:+ item = cls(+ dispatch_id=str(record.get("dispatch_id") or "").strip(),+ agent_id=str(record.get("agent_id") or "").strip(),+ agent_revision=int(record.get("agent_revision") or 0),+ mode=A2AOutboundDispatchMode(str(record.get("mode") or "")),+ status=A2AOutboundDispatchStatus(str(record.get("status") or "")),+ request_message_id=str(record.get("request_message_id") or "").strip(),+ 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 ""),+ remote_task_id=record.get("remote_task_id"),+ remote_context_id=record.get("remote_context_id"),+ accepted_at=record.get("accepted_at"),+ finished_at=record.get("finished_at"),+ result=(+ dict(record.get("result") or {})+ if record.get("result") is not None+ else None+ ),+ error_code=record.get("error_code"),+ error_summary=record.get("error_summary"),+ last_polled_at=record.get("last_polled_at"),+ input_length=(+ int(record.get("input_length"))+ if record.get("input_length") is not None+ else None+ ),+ input_content_type=record.get("input_content_type"),+ input_digest=record.get("input_digest"),+ )+ except (TypeError, ValueError) as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID) from exc+ return item.validate()+++__all__ = [+ "A2ACompatibleInterface",+ "A2ADiscoveredAgent",+ "A2AOutboundAgent",+ "A2AOutboundAvailability",+ "A2AOutboundDiscovery",+ "A2AOutboundDispatch",+ "A2AOutboundDispatchMode",+ "A2AOutboundDispatchStatus",+ "TERMINAL_DISPATCH_STATUSES",+ "sanitize_persisted_value",+]diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py b/jiuwenswarm/gateway/a2a_manager/outbound/repository.pynew file mode 100644index 0000000000..20db5a1fbe--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/repository.py@@ -0,0 +1,360 @@+"""PersistentStore repositories for A2A outbound agents and dispatches."""++from __future__ import annotations++import asyncio+from contextlib import asynccontextmanager+from dataclasses import replace+from datetime import datetime, timedelta, timezone+from typing import Any, AsyncIterator, Callable, Mapping, Protocol++from jiuwenswarm.gateway.storage.protocols.persistent import PersistentStore++from .credentials import A2AOutboundCredentialStore+from .errors import safe_error_summary+from .locks import KeyedLockPool+from .models import (+ A2AOutboundAgent,+ A2AOutboundDispatch,+ A2AOutboundDispatchStatus,+ TERMINAL_DISPATCH_STATUSES,+)++A2A_OUTBOUND_AGENT_STORE_NAME = "a2a_outbound_agent"+A2A_OUTBOUND_DISPATCH_STORE_NAME = "a2a_outbound_dispatch"+DEFAULT_DISPATCH_RETENTION_MAX_RECORDS = 1_000+DEFAULT_DISPATCH_RETENTION_DAYS = 30+++def utc_now_text() -> str:+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+++def _parse_timestamp(value: str | None) -> datetime | None:+ text = str(value or "").strip()+ if not text:+ return None+ if text.endswith("Z"):+ text = f"{text[:-1]}+00:00"+ try:+ parsed = datetime.fromisoformat(text)+ except ValueError:+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed.astimezone(timezone.utc)+++class A2AOutboundRecordCodec(Protocol):+ def agent_identity(self, agent_id: str) -> dict[str, Any]:+ raise NotImplementedError++ def dispatch_identity(self, dispatch_id: str) -> dict[str, Any]:+ raise NotImplementedError++ def list_filters(self) -> dict[str, Any] | None:+ raise NotImplementedError++ def agent_to_record(self, agent: A2AOutboundAgent) -> dict[str, Any]:+ raise NotImplementedError++ def agent_from_record(self, record: Mapping[str, Any]) -> A2AOutboundAgent:+ raise NotImplementedError++ def dispatch_to_record(self, dispatch: A2AOutboundDispatch) -> dict[str, Any]:+ raise NotImplementedError++ def dispatch_from_record(+ self, record: Mapping[str, Any]+ ) -> A2AOutboundDispatch:+ raise NotImplementedError+++class JsonA2AOutboundRecordCodec:+ """Personal-edition JSON shape containing the complete domain record."""++ @staticmethod+ def agent_identity(agent_id: str) -> dict[str, Any]:+ return {"agent_id": str(agent_id)}++ @staticmethod+ def dispatch_identity(dispatch_id: str) -> dict[str, Any]:+ return {"dispatch_id": str(dispatch_id)}++ @staticmethod+ def list_filters() -> dict[str, Any] | None:+ return None++ @staticmethod+ def agent_to_record(agent: A2AOutboundAgent) -> dict[str, Any]:+ return agent.to_record()++ @staticmethod+ def agent_from_record(record: Mapping[str, Any]) -> A2AOutboundAgent:+ return A2AOutboundAgent.from_record(record)++ @staticmethod+ def dispatch_to_record(dispatch: A2AOutboundDispatch) -> dict[str, Any]:+ return dispatch.to_record()++ @staticmethod+ def dispatch_from_record(record: Mapping[str, Any]) -> A2AOutboundDispatch:+ return A2AOutboundDispatch.from_record(record)+++class A2AOutboundRepository:+ """Personal-edition domain repository with per-entity transition locks."""++ def __init__(+ self,+ store: PersistentStore,+ codec: A2AOutboundRecordCodec | None = None,+ credential_store: A2AOutboundCredentialStore | None = None,+ ) -> None:+ self._store = store+ self._codec = codec or JsonA2AOutboundRecordCodec()+ self._credential_store = credential_store or A2AOutboundCredentialStore()+ self._agent_locks = KeyedLockPool()+ self._dispatch_locks = KeyedLockPool()+ self._discovery_locks = KeyedLockPool()+ self._retention_lock = asyncio.Lock()++ @asynccontextmanager+ async def hold_discovery(self, discovery_id: str) -> AsyncIterator[None]:+ """Serialize registration attempts that consume the same discovery result."""+ async with self._discovery_locks.hold(discovery_id):+ yield++ async def get_agent(self, agent_id: str) -> A2AOutboundAgent | None:+ row = await self._store.get(+ A2A_OUTBOUND_AGENT_STORE_NAME,+ self._codec.agent_identity(agent_id),+ )+ return None if row is None else self._codec.agent_from_record(row)++ async def list_agents(self) -> list[A2AOutboundAgent]:+ rows = await self._store.list(+ A2A_OUTBOUND_AGENT_STORE_NAME,+ filters=self._codec.list_filters(),+ order_by="updated_at DESC",+ limit=None,+ )+ return [self._codec.agent_from_record(row) for row in rows]++ async def create_agent(self, agent: A2AOutboundAgent) -> A2AOutboundAgent:+ agent.validate()+ async with self._agent_locks.hold(agent.agent_id):+ created = await self._store.create(+ A2A_OUTBOUND_AGENT_STORE_NAME,+ self._codec.agent_to_record(agent),+ )+ return self._codec.agent_from_record(created)++ async def update_agent(+ self,+ agent_id: str,+ updater: Callable[[A2AOutboundAgent], A2AOutboundAgent],+ ) -> A2AOutboundAgent | None:+ """Read, mutate, and persist an Agent while holding its per-Agent lock."""+ async with self._agent_locks.hold(agent_id):+ key = self._codec.agent_identity(agent_id)+ row = await self._store.get(A2A_OUTBOUND_AGENT_STORE_NAME, key)+ if row is None:+ return None+ current = self._codec.agent_from_record(row)+ updated_agent = updater(current).validate()+ if updated_agent.agent_id != current.agent_id:+ raise ValueError("agent updater cannot change agent_id")+ record = self._codec.agent_to_record(updated_agent)+ updates = {name: value for name, value in record.items() if name not in key}+ updated = await self._store.update(+ A2A_OUTBOUND_AGENT_STORE_NAME,+ key,+ updates,+ )+ return None if updated is None else self._codec.agent_from_record(updated)++ async def delete_agent(self, agent_id: str) -> bool:+ async with self._agent_locks.hold(agent_id):+ key = self._codec.agent_identity(agent_id)+ row = await self._store.get(A2A_OUTBOUND_AGENT_STORE_NAME, key)+ if row is None:+ return False+ agent = self._codec.agent_from_record(row)+ if agent.credential_ref:+ credential_ref = self._credential_store.validate_for_agent(+ agent.agent_id,+ agent.credential_ref,+ )+ # Delete the secret first. If record deletion then fails, a retry is+ # safe and the remaining registration cannot authenticate remotely.+ self._credential_store.delete(credential_ref)+ return await self._store.delete(+ A2A_OUTBOUND_AGENT_STORE_NAME,+ key,+ )++ async def get_dispatch(self, dispatch_id: str) -> A2AOutboundDispatch | None:+ row = await self._store.get(+ A2A_OUTBOUND_DISPATCH_STORE_NAME,+ self._codec.dispatch_identity(dispatch_id),+ )+ return None if row is None else self._codec.dispatch_from_record(row)++ async def list_dispatches(+ self,+ *,+ limit: int | None = None,+ offset: int = 0,+ ) -> list[A2AOutboundDispatch]:+ rows = await self._store.list(+ A2A_OUTBOUND_DISPATCH_STORE_NAME,+ filters=self._codec.list_filters(),+ order_by="created_at DESC",+ limit=None if limit is None else max(0, int(limit)),+ offset=max(0, int(offset)),+ )+ return [self._codec.dispatch_from_record(row) for row in rows]++ async def create_dispatch(+ self,+ dispatch: A2AOutboundDispatch,+ ) -> A2AOutboundDispatch:+ dispatch.validate()+ async with self._dispatch_locks.hold(dispatch.dispatch_id):+ created = await self._store.create(+ A2A_OUTBOUND_DISPATCH_STORE_NAME,+ self._codec.dispatch_to_record(dispatch),+ )+ return self._codec.dispatch_from_record(created)++ async def transition_dispatch(+ self,+ dispatch_id: str,+ status: A2AOutboundDispatchStatus | str,+ *,+ updated_at: str | None = None,+ **changes: Any,+ ) -> A2AOutboundDispatch | None:+ """Apply a locked state transition; an existing terminal state is immutable."""+ normalized_status = A2AOutboundDispatchStatus(status)+ allowed_changes = {+ "remote_task_id",+ "remote_context_id",+ "accepted_at",+ "finished_at",+ "result",+ "error_code",+ "error_summary",+ "last_polled_at",+ }+ unknown = set(changes) - allowed_changes+ if unknown:+ raise ValueError(+ f"unsupported dispatch fields: {', '.join(sorted(unknown))}"+ )++ async with self._dispatch_locks.hold(dispatch_id):+ row = await self._store.get(+ A2A_OUTBOUND_DISPATCH_STORE_NAME,+ self._codec.dispatch_identity(dispatch_id),+ )+ if row is None:+ return None+ current = self._codec.dispatch_from_record(row)+ if current.status in TERMINAL_DISPATCH_STATUSES:+ return current++ stamp = updated_at or utc_now_text()+ if normalized_status in TERMINAL_DISPATCH_STATUSES:+ changes.setdefault("finished_at", stamp)+ error_code = changes.get("error_code")+ if error_code:+ changes["error_summary"] = safe_error_summary(error_code)+ next_value = replace(+ current,+ status=normalized_status,+ updated_at=stamp,+ **changes,+ ).validate()+ record = self._codec.dispatch_to_record(next_value)+ key = self._codec.dispatch_identity(dispatch_id)+ updates = {name: value for name, value in record.items() if name not in key}+ # Include the observed state in the update predicate so the personal+ # file backend cannot overwrite a terminal state with a late event.+ compare_key = {**key, "status": current.status.value}+ updated = await self._store.update(+ A2A_OUTBOUND_DISPATCH_STORE_NAME,+ compare_key,+ updates,+ )+ if updated is not None:+ return self._codec.dispatch_from_record(updated)+ # Another writer may have won the comparison. Return the persisted+ # winner, never the uncommitted candidate.+ latest = await self._store.get(A2A_OUTBOUND_DISPATCH_STORE_NAME, key)+ return None if latest is None else self._codec.dispatch_from_record(latest)++ async def cleanup_dispatches(+ self,+ *,+ now: datetime | None = None,+ max_records: int = DEFAULT_DISPATCH_RETENTION_MAX_RECORDS,+ max_age_days: int = DEFAULT_DISPATCH_RETENTION_DAYS,+ ) -> int:+ """Delete terminal records older than either enabled retention boundary."""+ max_records = max(0, int(max_records))+ max_age_days = max(0, int(max_age_days))+ current_time = now or datetime.now(timezone.utc)+ if current_time.tzinfo is None:+ current_time = current_time.replace(tzinfo=timezone.utc)+ cutoff = (+ current_time.astimezone(timezone.utc) - timedelta(days=max_age_days)+ if max_age_days > 0+ else None+ )++ async with self._retention_lock:+ records = await self.list_dispatches()+ ordered = sorted(+ (item for item in records if item.is_terminal),+ key=lambda item: (+ _parse_timestamp(item.created_at)+ or datetime.min.replace(tzinfo=timezone.utc)+ ),+ )+ expired_ids: set[str] = set()+ if cutoff is not None:+ for item in ordered:+ created_at = _parse_timestamp(item.created_at)+ if (+ created_at or datetime.min.replace(tzinfo=timezone.utc)+ ) < cutoff:+ expired_ids.add(item.dispatch_id)+ survivors = [+ item for item in ordered if item.dispatch_id not in expired_ids+ ]+ overflow = max(0, len(survivors) - max_records) if max_records > 0 else 0+ expired_ids.update(item.dispatch_id for item in survivors[:overflow])++ deleted = 0+ for dispatch_id in expired_ids:+ async with self._dispatch_locks.hold(dispatch_id):+ if await self._store.delete(+ A2A_OUTBOUND_DISPATCH_STORE_NAME,+ self._codec.dispatch_identity(dispatch_id),+ ):+ deleted += 1+ return deleted+++__all__ = [+ "A2A_OUTBOUND_AGENT_STORE_NAME",+ "A2A_OUTBOUND_DISPATCH_STORE_NAME",+ "A2AOutboundRecordCodec",+ "A2AOutboundRepository",+ "DEFAULT_DISPATCH_RETENTION_DAYS",+ "DEFAULT_DISPATCH_RETENTION_MAX_RECORDS",+ "JsonA2AOutboundRecordCodec",+ "utc_now_text",+]diff --git a/jiuwenswarm/gateway/storage_assembly/__init__.py b/jiuwenswarm/gateway/storage_assembly/__init__.pyindex 5ca4a9a580..316deaf25d 100644--- a/jiuwenswarm/gateway/storage_assembly/__init__.py+++ b/jiuwenswarm/gateway/storage_assembly/__init__.py@@ -11,6 +11,7 @@ from jiuwenswarm.gateway.storage_assembly.manager_ws_bridge import (wire_manager_ws_table_store,)from jiuwenswarm.gateway.storage_assembly.setup import (+ create_a2a_outbound_repository,create_a2ui_config_repository,create_browser_config_repository,create_channel_config_repository,@@ -43,6 +44,7 @@ __all__ = ["GatewayDbConnection","assert_replicas_db_compat","build_gateway_store_registry",+ "create_a2a_outbound_repository","clear_manager_ws_table_store","create_a2ui_config_repository","create_browser_config_repository",diff --git a/jiuwenswarm/gateway/storage_assembly/layouts.py b/jiuwenswarm/gateway/storage_assembly/layouts.pyindex 5d55917191..56f75dacdd 100644--- a/jiuwenswarm/gateway/storage_assembly/layouts.py+++ b/jiuwenswarm/gateway/storage_assembly/layouts.py@@ -93,6 +93,27 @@ def _json_and_db(return StoreLayout(file=file, db=DbLayout(table=table))+def _json_only(+ rel: str,+ *,+ persistent_root: Path | None,+ shape: Literal["map", "list"] = "map",+ key_fields: tuple[str, ...] = (),+) -> StoreLayout | None:+ """形态:仅个人版独立 JSON;企业装配时不注册。"""+ if persistent_root is None:+ return None+ return StoreLayout(+ file=FileLayout(+ path=str(persistent_root / rel),+ format="json",+ shape=shape,+ key_fields=key_fields,+ ),+ db=None,+ )++def _json_and_db_at_path(table: str,path: Path,@@ -135,6 +156,19 @@ _YAML_ONLY_SECTIONS: dict[str, _YamlSectionSpec] = {"a2ui_config": ("/a2ui", (), ""),}+_JSON_ONLY_STORES: dict[str, _JsonAndDbSpec] = {+ "a2a_outbound_agent": (+ "a2a_outbound_agents.json",+ "map",+ ("agent_id",),+ ),+ "a2a_outbound_dispatch": (+ "a2a_outbound_dispatches.json",+ "map",+ ("dispatch_id",),+ ),+}+_JSON_AND_DB_STORES: dict[str, _JsonAndDbSpec] = {"session_map": ("session_map.json", "map", ("identity_key",)),}@@ -170,6 +204,16 @@ def _build_layouts(layouts["cron_job"] = _legacy_gateway_cron_job_layout(cron_jobs_path_template)+ for name, (rel, shape, key_fields) in _JSON_ONLY_STORES.items():+ layout = _json_only(+ rel,+ persistent_root=persistent_root,+ shape=shape,+ key_fields=key_fields,+ )+ if layout is not None:+ layouts[name] = layout+for name, (rel, shape, key_fields) in _JSON_AND_DB_STORES.items():if name == "session_map":continuediff --git a/jiuwenswarm/gateway/storage_assembly/setup.py b/jiuwenswarm/gateway/storage_assembly/setup.pyindex eaba90906d..eaf880a192 100644--- a/jiuwenswarm/gateway/storage_assembly/setup.py+++ b/jiuwenswarm/gateway/storage_assembly/setup.py@@ -504,6 +504,18 @@ def create_session_map_repository(store: PersistentStore):return SessionMapRepository(store)+def create_a2a_outbound_repository(+ store: PersistentStore,+):+ """Create the personal-edition JSON-backed outbound Repository."""+ from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2AOutboundRepository,+ JsonA2AOutboundRecordCodec,+ )++ return A2AOutboundRepository(store, JsonA2AOutboundRecordCodec())++def create_permissions_config_repository(store: PersistentStore,*,@@ -675,6 +687,7 @@ def create_enterprise_record_repositories(__all__ = [+ "create_a2a_outbound_repository","create_a2ui_config_repository","create_browser_config_repository","create_channel_config_repository",diff --git a/tests/unit_tests/gateway/test_a2a_outbound_repository.py b/tests/unit_tests/gateway/test_a2a_outbound_repository.pynew file mode 100644index 0000000000..f08e59e671--- /dev/null+++ b/tests/unit_tests/gateway/test_a2a_outbound_repository.py@@ -0,0 +1,547 @@+"""Stage-1 coverage for the A2A outbound domain and persistence contract."""++from __future__ import annotations++import asyncio+import json+from dataclasses import replace+from datetime import datetime, timedelta, timezone++import pytest++from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2ACompatibleInterface,+ A2ADiscoveredAgent,+ A2AOutboundAgent,+ A2AOutboundAvailability,+ A2AOutboundCredentialStore,+ A2AOutboundDiscovery,+ A2AOutboundDispatch,+ A2AOutboundDispatchMode,+ A2AOutboundDispatchStatus,+ A2AOutboundError,+ A2AOutboundErrorCode,+ A2AOutboundRepository,+)+from jiuwenswarm.gateway.storage.backends.file_persistent import FilePersistentBackend+from jiuwenswarm.gateway.storage.backends.memory_persistent import (+ InMemoryPersistentBackend,+)+from jiuwenswarm.gateway.storage_assembly import (+ build_gateway_store_registry,+ create_a2a_outbound_repository,+)+from jiuwenswarm.gateway.a2a_manager.outbound.locks import KeyedLockPool+++def _stamp(offset_days: int = 0) -> str:+ value = datetime(2026, 8, 26, tzinfo=timezone.utc) + timedelta(days=offset_days)+ return value.isoformat().replace("+00:00", "Z")+++def _agent(agent_id: str = "agent-1") -> A2AOutboundAgent:+ return A2AOutboundAgent(+ agent_id=agent_id,+ display_name="Research Agent",+ source_url="https://agent.example.com",+ card_path="/.well-known/agent-card.json",+ card_fingerprint="sha256:card",+ card_revision=1,+ agent_card={+ "name": "Research Agent",+ "authorization": "Bearer must-not-persist",+ "nested": {+ "apiKey": "also-secret",+ "clientSecret": "client-secret",+ "secret_key": "secret-key",+ "passwordField": "password",+ "tokenValue": "token",+ "credential_data": "credential",+ "description": "safe",+ },+ },+ selected_interface=A2ACompatibleInterface(+ protocol_binding="JSONRPC",+ protocol_version="1.0",+ url="https://agent.example.com/a2a",+ ),+ enabled=True,+ availability=A2AOutboundAvailability.AVAILABLE,+ credential_ref=f"a2a/outbound/{agent_id}.api_key",+ connect_timeout_seconds=10,+ sync_wait_seconds=300,+ created_at=_stamp(),+ updated_at=_stamp(),+ )+++def _dispatch(+ dispatch_id: str = "dispatch-1",+ *,+ status: A2AOutboundDispatchStatus = A2AOutboundDispatchStatus.CREATED,+ created_at: str | None = None,+) -> A2AOutboundDispatch:+ return A2AOutboundDispatch(+ dispatch_id=dispatch_id,+ agent_id="agent-1",+ agent_revision=1,+ mode=A2AOutboundDispatchMode.ASYNC,+ status=status,+ request_message_id=f"message-{dispatch_id}",+ source_session_id="session-1",+ created_at=created_at or _stamp(),+ updated_at=created_at or _stamp(),+ input_length=12,+ input_content_type="text/plain",+ input_digest="sha256:input",+ )+++class _SecretProbe:+ def __init__(self) -> None:+ self.values: dict[str, str] = {}++ def get(self, key: str) -> str:+ return self.values.get(key, "")++ def set(self, key: str, value: str, *, algorithm: str | None = None) -> None:+ assert algorithm is None+ self.values[key] = value++ def delete(self, key: str) -> None:+ self.values.pop(key, None)+++async def test_agent_roundtrip_redacts_card_secrets_and_hides_credential_ref() -> None:+ store = InMemoryPersistentBackend()+ repository = A2AOutboundRepository(store)++ created = await repository.create_agent(_agent())+ row = await store.get("a2a_outbound_agent", {"agent_id": "agent-1"})++ assert row is not None+ assert row["credential_ref"] == "a2a/outbound/agent-1.api_key"+ assert row["agent_card"]["authorization"] == "******"+ assert row["agent_card"]["nested"] == {+ "apiKey": "******",+ "clientSecret": "******",+ "secret_key": "******",+ "passwordField": "******",+ "tokenValue": "******",+ "credential_data": "******",+ "description": "safe",+ }+ assert created.public_dict()["has_credential"] is True+ assert "credential_ref" not in created.public_dict()+++async def test_agent_crud_uses_repository_contract() -> None:+ secret_probe = _SecretProbe()+ credentials = A2AOutboundCredentialStore(secret_probe)+ credentials.set_for_agent("agent-1", "secret-value")+ repository = A2AOutboundRepository(+ InMemoryPersistentBackend(), credential_store=credentials+ )+ await repository.create_agent(_agent())++ updated = await repository.update_agent(+ "agent-1",+ lambda current: replace(current, enabled=False, updated_at=_stamp(1)),+ )++ assert updated is not None+ assert updated.enabled is False+ assert [item.agent_id for item in await repository.list_agents()] == ["agent-1"]+ assert await repository.delete_agent("agent-1") is True+ assert await repository.get_agent("agent-1") is None+ assert secret_probe.values == {}+++async def test_agent_updates_are_atomic_under_per_agent_lock() -> None:+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ await repository.create_agent(_agent())++ first, second = await asyncio.gather(+ repository.update_agent(+ "agent-1",+ lambda current: replace(current, enabled=False),+ ),+ repository.update_agent(+ "agent-1",+ lambda current: replace(current, display_name="Updated Agent"),+ ),+ )++ persisted = await repository.get_agent("agent-1")+ assert first is not None and second is not None and persisted is not None+ assert persisted.enabled is False+ assert persisted.display_name == "Updated Agent"+++async def test_terminal_dispatch_cannot_be_overwritten_by_late_event() -> None:+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ await repository.create_dispatch(_dispatch())+ completed = await repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.COMPLETED,+ result={"text": "done"},+ updated_at=_stamp(1),+ )+ late = await repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.CANCELED,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ updated_at=_stamp(2),+ )++ assert completed is not None and late is not None+ assert late.status is A2AOutboundDispatchStatus.COMPLETED+ assert late.result == {"text": "done"}+ assert late.finished_at == _stamp(1)+++async def test_timed_out_dispatch_can_later_converge_to_remote_terminal_state() -> None:+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ await repository.create_dispatch(_dispatch())+ timed_out = await repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.TIMED_OUT,+ remote_task_id="remote-1",+ error_code=A2AOutboundErrorCode.DISPATCH_TIMEOUT.value,+ )+ completed = await repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.COMPLETED,+ result={"text": "eventual result"},+ )++ assert timed_out is not None+ assert timed_out.error_summary == "等待第三方 Agent 回复超时。"+ assert completed is not None+ assert completed.status is A2AOutboundDispatchStatus.COMPLETED+ assert completed.remote_task_id == "remote-1"+++async def test_concurrent_terminal_updates_share_per_dispatch_lock() -> None:+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ await repository.create_dispatch(_dispatch())++ first, second = await asyncio.gather(+ repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.COMPLETED,+ result={"text": "done"},+ ),+ repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.FAILED,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ ),+ )++ assert first is not None and second is not None+ assert first.status == second.status+ assert first.status in {+ A2AOutboundDispatchStatus.COMPLETED,+ A2AOutboundDispatchStatus.FAILED,+ }+++class _RacingStore(InMemoryPersistentBackend):+ def __init__(self) -> None:+ super().__init__()+ self.readers = 0+ self.ready = asyncio.Event()++ async def get(self, name, key):+ if name == "a2a_outbound_dispatch" and self.readers < 2:+ self.readers += 1+ if self.readers == 2:+ self.ready.set()+ await self.ready.wait()+ return await super().get(name, key)+++async def test_compare_and_set_protects_terminal_state_across_repositories() -> None:+ store = _RacingStore()+ first_repository = A2AOutboundRepository(store)+ second_repository = A2AOutboundRepository(store)+ await first_repository.create_dispatch(_dispatch())++ first, second = await asyncio.gather(+ first_repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.COMPLETED,+ result={"text": "done"},+ ),+ second_repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.FAILED,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ ),+ )++ persisted = await first_repository.get_dispatch("dispatch-1")+ assert first is not None and second is not None and persisted is not None+ assert first.status == second.status == persisted.status+ assert persisted.status in {+ A2AOutboundDispatchStatus.COMPLETED,+ A2AOutboundDispatchStatus.FAILED,+ }+++async def test_retention_uses_age_then_record_limit() -> None:+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ for index, day in enumerate((-40, -3, -2, -1)):+ await repository.create_dispatch(+ _dispatch(+ f"dispatch-{index}",+ status=A2AOutboundDispatchStatus.COMPLETED,+ created_at=_stamp(day),+ )+ )++ deleted = await repository.cleanup_dispatches(+ now=datetime(2026, 8, 26, tzinfo=timezone.utc),+ max_age_days=30,+ max_records=2,+ )++ assert deleted == 2+ assert [item.dispatch_id for item in await repository.list_dispatches()] == [+ "dispatch-3",+ "dispatch-2",+ ]+++async def test_retention_never_deletes_non_terminal_dispatches() -> None:+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ for dispatch in (+ _dispatch(+ "working-old",+ status=A2AOutboundDispatchStatus.WORKING,+ created_at=_stamp(-40),+ ),+ replace(+ _dispatch(+ "timed-out-old",+ status=A2AOutboundDispatchStatus.TIMED_OUT,+ created_at=_stamp(-40),+ ),+ remote_task_id="remote-1",+ ),+ _dispatch(+ "unknown-old",+ status=A2AOutboundDispatchStatus.UNKNOWN,+ created_at=_stamp(-40),+ ),+ _dispatch(+ "completed-old",+ status=A2AOutboundDispatchStatus.COMPLETED,+ created_at=_stamp(-40),+ ),+ ):+ await repository.create_dispatch(dispatch)++ deleted = await repository.cleanup_dispatches(+ now=datetime(2026, 8, 26, tzinfo=timezone.utc),+ max_age_days=30,+ max_records=1,+ )++ assert deleted == 1+ assert {item.dispatch_id for item in await repository.list_dispatches()} == {+ "working-old",+ "timed-out-old",+ "unknown-old",+ }+++async def test_zero_retention_limits_disable_both_cleanup_dimensions() -> None:+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ await repository.create_dispatch(+ _dispatch(+ "completed-old",+ status=A2AOutboundDispatchStatus.COMPLETED,+ created_at=_stamp(-100),+ )+ )++ deleted = await repository.cleanup_dispatches(+ now=datetime(2026, 8, 26, tzinfo=timezone.utc),+ max_age_days=0,+ max_records=0,+ )++ assert deleted == 0+ assert await repository.get_dispatch("completed-old") is not None+++async def test_personal_json_layout_survives_backend_recreation(tmp_path) -> None:+ registry = build_gateway_store_registry(persistent_root=tmp_path)+ first = FilePersistentBackend(registry=registry)+ await A2AOutboundRepository(first).create_agent(_agent())++ second = FilePersistentBackend(registry=registry)+ restored = await A2AOutboundRepository(second).get_agent("agent-1")++ assert restored is not None+ assert restored.display_name == "Research Agent"+ payload = json.loads((tmp_path / "a2a_outbound_agents.json").read_text("utf-8"))+ assert "must-not-persist" not in json.dumps(payload)+++class _BarrierFileStore:+ def __init__(self, backend: FilePersistentBackend, barrier: asyncio.Event) -> None:+ self._backend = backend+ self._barrier = barrier+ self._counter: list[int] | None = None++ def bind_counter(self, counter: list[int]) -> None:+ self._counter = counter++ async def get(self, name, key):+ row = await self._backend.get(name, key)+ if name == "a2a_outbound_dispatch" and self._counter is not None:+ self._counter[0] += 1+ if self._counter[0] == 2:+ self._barrier.set()+ if self._counter[0] <= 2:+ await self._barrier.wait()+ return row++ def __getattr__(self, name):+ return getattr(self._backend, name)+++async def test_file_backend_cas_preserves_first_terminal_winner(tmp_path) -> None:+ registry = build_gateway_store_registry(persistent_root=tmp_path)+ seed_backend = FilePersistentBackend(registry=registry)+ await A2AOutboundRepository(seed_backend).create_dispatch(_dispatch())++ barrier = asyncio.Event()+ counter = [0]+ first_store = _BarrierFileStore(FilePersistentBackend(registry=registry), barrier)+ second_store = _BarrierFileStore(FilePersistentBackend(registry=registry), barrier)+ first_store.bind_counter(counter)+ second_store.bind_counter(counter)+ first_repository = A2AOutboundRepository(first_store)+ second_repository = A2AOutboundRepository(second_store)++ first, second = await asyncio.gather(+ first_repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.COMPLETED,+ result={"text": "done"},+ ),+ second_repository.transition_dispatch(+ "dispatch-1",+ A2AOutboundDispatchStatus.FAILED,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ ),+ )++ restored = await A2AOutboundRepository(+ FilePersistentBackend(registry=registry)+ ).get_dispatch("dispatch-1")+ assert first is not None and second is not None and restored is not None+ assert first.status == second.status == restored.status+ assert restored.status in {+ A2AOutboundDispatchStatus.COMPLETED,+ A2AOutboundDispatchStatus.FAILED,+ }+++def test_storage_registry_exposes_only_personal_a2a_layouts(tmp_path) -> None:+ personal = build_gateway_store_registry(persistent_root=tmp_path)+ enterprise = build_gateway_store_registry()++ for name, filename, key in (+ ("a2a_outbound_agent", "a2a_outbound_agents.json", "agent_id"),+ ("a2a_outbound_dispatch", "a2a_outbound_dispatches.json", "dispatch_id"),+ ):+ personal_layout = personal.get(name)+ assert personal_layout is not None and personal_layout.file is not 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+++def test_repository_factory_creates_personal_json_repository() -> None:+ store = InMemoryPersistentBackend()+ personal = create_a2a_outbound_repository(store)++ assert isinstance(personal, A2AOutboundRepository)+++def test_credentials_live_in_secret_store_behind_reference() -> None:+ probe = _SecretProbe()+ credentials = A2AOutboundCredentialStore(probe)++ credential_ref = credentials.set_for_agent("agent-1", "secret-value")++ assert credential_ref == "a2a/outbound/agent-1.api_key"+ assert credentials.get(credential_ref) == "secret-value"+ assert "secret-value" not in _agent().to_record().values()+ credentials.delete(credential_ref)+ assert credentials.get(credential_ref) == ""+++def test_discovery_dto_is_preview_only_and_redacts_credentials() -> None:+ preview = A2AOutboundDiscovery(+ discovery_id="disc-1",+ expires_at=_stamp(1),+ source_url="https://agent.example.com",+ card_path="/.well-known/agent-card.json",+ card_fingerprint="sha256:card",+ agent=A2ADiscoveredAgent(+ name="Research Agent",+ compatible_interfaces=(+ A2ACompatibleInterface(+ "JSONRPC", "1.0", "https://agent.example.com/a2a"+ ),+ ),+ ),+ agent_card={"clientSecret": "must-not-leak"},+ ).to_dict()++ assert preview["discovery_id"] == "disc-1"+ assert "agent_id" not in preview+ assert "enabled" not in preview+ assert preview["agent_card"]["clientSecret"] == "******"+++def test_invalid_external_credential_reference_is_rejected() -> None:+ credentials = A2AOutboundCredentialStore(_SecretProbe())+ with pytest.raises(ValueError, match="invalid"):+ credentials.get("llm.api_key")+++def test_credential_reference_must_belong_to_agent() -> None:+ with pytest.raises(A2AOutboundError, match="A2A 出站数据无效"):+ replace(+ _agent("agent-1"),+ credential_ref=A2AOutboundCredentialStore.reference_for("agent-2"),+ ).validate()+++async def test_keyed_lock_pool_evicts_inactive_keys() -> None:+ pool = KeyedLockPool()+ for index in range(100):+ async with pool.hold(f"key-{index}"):+ assert pool.size == 1+ assert pool.size == 0