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): outbound loopback HTTP debugging support (batch 4/7)
NickFuryXXXc1266ffe4eba
diff --git a/.env.example b/.env.exampleindex 08c83620cf..ffa546845b 100644--- a/.env.example+++ b/.env.example@@ -84,7 +84,6 @@ LOG_MASK_ENABLED=true# Instance id used for enterprise config isolation (set by Manager WS register.ack)# JIUWENCLAW_ID=-# ====================== 统一工具开关(黑名单)======================# 禁用的工具列表(逗号或分号分隔),config.yaml 中通过 disabled_tools: ${DISABLED_TOOLS-...} 引用# 列出的工具名将在 agent init 后从注册表注销,模型不可见;未列出者默认注册。@@ -93,3 +92,7 @@ LOG_MASK_ENABLED=true# 那条链路走 SkillManager.handle_skills_install,不经模型工具)。# 留空 = 全部启用;覆盖默认三工具可填:DISABLED_TOOLS=DISABLED_TOOLS=search_skill,install_skill,uninstall_skill++# Allow plaintext A2A Agents on 127.0.0.1 / ::1 for local E2E only.+# Prefer changing this from A2A 调度中心 -> 出站配置; keep false in production.+A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP=falsediff --git a/jiuwenswarm/agents/harness/common/rails/a2a_outbound_toolkit_rail.py b/jiuwenswarm/agents/harness/common/rails/a2a_outbound_toolkit_rail.pynew file mode 100644index 0000000000..ace8ff8d35--- /dev/null+++ b/jiuwenswarm/agents/harness/common/rails/a2a_outbound_toolkit_rail.py@@ -0,0 +1,118 @@+"""Lifecycle rail for the three built-in A2A outbound Agent tools."""++from __future__ import annotations++from typing import Any, Callable++from openjiuwen.harness.prompts import PromptSection+from openjiuwen.harness.rails.base import DeepAgentRail++from jiuwenswarm.agents.harness.common.tools.a2a_outbound_tools import (+ A2AOutboundToolBackend,+ A2AOutboundToolkit,+ GatewayA2AOutboundToolBackend,+)++_SECTION_NAME = "a2a_outbound_usage"+_TOOL_NAMES = ("a2a_find_agents", "a2a_dispatch_task", "a2a_get_dispatch")+++class A2AOutboundToolkitRail(DeepAgentRail):+ """Keep the three narrow tools visible across Gateway connection timing."""++ priority = 45++ def __init__(+ self,+ *,+ backend_provider: Callable[[], A2AOutboundToolBackend | None] | None = None,+ runtime_route: Callable[[], tuple[str, str]] | None = None,+ ) -> None:+ super().__init__()+ self._backend_provider = backend_provider or GatewayA2AOutboundToolBackend+ self._runtime_route = runtime_route+ self._registered: list[str] = []+ self._prompt_builder: Any = None+ self._agent: Any = None++ def init(self, agent: Any) -> None:+ self._agent = agent+ self._prompt_builder = getattr(agent, "system_prompt_builder", None)+ self._try_register(agent)++ def _try_register(self, agent: Any) -> None:+ if self._registered:+ return+ backend = self._backend_provider()+ if backend is None:+ return+ ability_manager = getattr(agent, "ability_manager", None)+ if ability_manager is None:+ return+ toolkit = (+ A2AOutboundToolkit(backend, runtime_route=self._runtime_route)+ if self._runtime_route is not None+ else A2AOutboundToolkit(backend)+ )+ tools = toolkit.get_tools()+ for tool in tools:+ ability_manager.add_ability(tool.card, tool)+ self._registered.append(tool.card.name)+ self._sync_prompt()++ def uninit(self, agent: Any) -> None:+ ability_manager = getattr(agent, "ability_manager", None)+ if ability_manager is not None:+ for name in reversed(self._registered):+ ability_manager.remove_ability(name)+ self._registered.clear()+ builder = getattr(agent, "system_prompt_builder", None) or self._prompt_builder+ if builder is not None:+ builder.remove_section(_SECTION_NAME)+ self._prompt_builder = None+ self._agent = None++ async def before_model_call(self, ctx: Any) -> None:+ live_agent = getattr(ctx, "agent", None) or self._agent+ if not self._registered and live_agent is not None:+ self._try_register(live_agent)+ if not self._registered:+ return+ live_builder = getattr(+ getattr(ctx, "agent", None), "system_prompt_builder", None+ )+ if live_builder is not None:+ self._prompt_builder = live_builder+ self._sync_prompt()++ def _sync_prompt(self) -> None:+ if self._prompt_builder is None or not self._registered:+ return+ language = getattr(self._prompt_builder, "language", "cn") or "cn"+ content = (+ """## A2A 出站工具++需要调用外部 A2A Agent 时:+1. 先用 a2a_find_agents 查询已注册且可用的候选;+2. 选择与任务技能匹配的 agent_id;+3. 需要立即取得答案时用 sync,长任务或不阻塞当前轮次时用 async;+4. async 返回后仅用 a2a_get_dispatch(dispatch_id) 查询,不自行构造远端请求。"""+ if language == "cn"+ else """## A2A outbound tools++When calling an external A2A Agent:+1. First use a2a_find_agents to list registered, callable candidates.+2. Select a skill-matching agent_id.+3. Use sync for an immediate answer and async for long-running work.+4. After async dispatch, query only with a2a_get_dispatch(dispatch_id); never construct a remote request."""+ )+ self._prompt_builder.add_section(+ PromptSection(+ name=_SECTION_NAME,+ content={language: content},+ priority=self.priority,+ )+ )+++__all__ = ["A2AOutboundToolkitRail"]diff --git a/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py b/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.pynew file mode 100644index 0000000000..162593a15d--- /dev/null+++ b/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py@@ -0,0 +1,241 @@+"""Narrow Agent tools that proxy A2A outbound work to the Gateway manager."""++from __future__ import annotations++import asyncio+from typing import Any, Callable, Protocol++from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard++from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2AOutboundErrorCode,+ safe_error_summary,+)+from jiuwenswarm.gateway.a2a_manager.tool_rpc import (+ A2A_TOOL_CANCEL_CALL as _RPC_CANCEL,+ A2A_TOOL_DISPATCH_TASK as _RPC_DISPATCH,+ A2A_TOOL_FIND_AGENTS as _RPC_FIND,+ A2A_TOOL_GET_DISPATCH as _RPC_GET,+)++from .acp_output_tools import get_acp_output_manager++_RPC_DISPATCH_TIMEOUT_SECONDS = 360.0+_RPC_QUERY_TIMEOUT_SECONDS = 15.0+++class A2AOutboundToolBackend(Protocol):+ @property+ def ready(self) -> bool:+ raise NotImplementedError++ async def call(+ self,+ method: str,+ params: dict[str, Any],+ *,+ session_id: str,+ channel_id: str,+ ) -> dict[str, Any]:+ raise NotImplementedError+++class GatewayA2AOutboundToolBackend:+ """Use the established AgentServer-to-Gateway reverse RPC connection."""++ @property+ def ready(self) -> bool:+ from jiuwenswarm.server.transports.push_registry import get_push_registry++ return bool(+ callable(getattr(get_acp_output_manager(), "_send_push_callback", None))+ and get_push_registry().subscriber_count() > 0+ )++ async def call(+ self,+ method: str,+ params: dict[str, Any],+ *,+ session_id: str,+ channel_id: str,+ ) -> dict[str, Any]:+ if not self.ready:+ return _error(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)+ try:+ response = await get_acp_output_manager().send_jsonrpc_request(+ method,+ params,+ session_id=session_id,+ channel_id=channel_id,+ timeout=(+ _RPC_DISPATCH_TIMEOUT_SECONDS+ if method == _RPC_DISPATCH+ else _RPC_QUERY_TIMEOUT_SECONDS+ ),+ log_params=False,+ cancel_method=(_RPC_CANCEL if method == _RPC_DISPATCH else None),+ )+ except (asyncio.TimeoutError, RuntimeError):+ return _error(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)+ result = response.get("result")+ if isinstance(result, dict):+ return result+ error = response.get("error")+ if isinstance(error, dict):+ code = str(error.get("data", {}).get("code") or "")+ return _error(code or A2AOutboundErrorCode.MANAGER_UNAVAILABLE)+ return _error(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)+++def _error(code: A2AOutboundErrorCode | str) -> dict[str, Any]:+ value = code.value if isinstance(code, A2AOutboundErrorCode) else str(code)+ return {+ "ok": False,+ "error_code": value,+ "error_summary": safe_error_summary(value),+ }+++def _runtime_route() -> tuple[str, str]:+ # Lazy import avoids coupling this reusable toolkit module to adapter startup.+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ get_runtime_tool_channel_id,+ get_runtime_tool_session_id,+ )++ return (+ str(get_runtime_tool_session_id() or "").strip(),+ str(get_runtime_tool_channel_id() or "default").strip() or "default",+ )+++class A2AOutboundToolkit:+ def __init__(+ self,+ backend: A2AOutboundToolBackend,+ *,+ runtime_route: Callable[[], tuple[str, str]] = _runtime_route,+ ) -> None:+ self._backend = backend+ self._runtime_route = runtime_route++ async def find_agents(+ self,+ query: str = "",+ required_skills: list[str] | None = None,+ limit: int = 5,+ ) -> dict[str, Any]:+ return await self._call(+ _RPC_FIND,+ {"query": query, "required_skills": required_skills or [], "limit": limit},+ )++ async def dispatch_task(+ self,+ agent_id: str,+ task: str,+ mode: str = "sync",+ context: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ reason = ""+ if isinstance(context, dict):+ reason = str(context.get("reason") or "")[:1000]+ return await self._call(+ _RPC_DISPATCH,+ {"agent_id": agent_id, "task": task, "mode": mode, "reason": reason},+ )++ async def get_dispatch(self, dispatch_id: str) -> dict[str, Any]:+ return await self._call(_RPC_GET, {"dispatch_id": dispatch_id})++ async def _call(self, method: str, params: dict[str, Any]) -> dict[str, Any]:+ session_id, channel_id = self._runtime_route()+ if not session_id:+ # No remote Agent has been contacted at this point. Report the+ # local routing failure instead of mislabeling it as a rejection.+ return _error(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)+ return await self._backend.call(+ method,+ params,+ session_id=session_id,+ channel_id=channel_id,+ )++ def get_tools(self) -> list[Tool]:+ def make_tool(+ name: str, description: str, input_params: dict[str, Any], func+ ) -> Tool:+ return LocalFunction(+ card=ToolCard(+ id=name,+ name=name,+ description=description,+ input_params=input_params,+ ),+ func=func,+ )++ return [+ make_tool(+ "a2a_find_agents",+ "Search only registered and currently callable external A2A Agents. "+ "Call this before dispatching; never invent an agent_id or remote URL.",+ {+ "type": "object",+ "properties": {+ "query": {"type": "string"},+ "required_skills": {+ "type": "array",+ "items": {"type": "string"},+ },+ "limit": {"type": "integer", "minimum": 1, "maximum": 20},+ },+ },+ self.find_agents,+ ),+ make_tool(+ "a2a_dispatch_task",+ "Dispatch a text task to a registered agent_id. sync waits for a final "+ "reply; async returns only after the remote Agent provides a queryable task ID. "+ "URLs, headers, credentials, and custom timeouts are intentionally unsupported.",+ {+ "type": "object",+ "properties": {+ "agent_id": {"type": "string"},+ "task": {"type": "string"},+ "mode": {"type": "string", "enum": ["sync", "async"]},+ "context": {+ "type": "object",+ "properties": {"reason": {"type": "string"}},+ "additionalProperties": False,+ },+ },+ "required": ["agent_id", "task", "mode"],+ "additionalProperties": False,+ },+ self.dispatch_task,+ ),+ make_tool(+ "a2a_get_dispatch",+ "Query a prior outbound request by its local dispatch_id. Do not pass a "+ "remote task ID or endpoint.",+ {+ "type": "object",+ "properties": {"dispatch_id": {"type": "string"}},+ "required": ["dispatch_id"],+ "additionalProperties": False,+ },+ self.get_dispatch,+ ),+ ]+++__all__ = [+ "A2AOutboundToolBackend",+ "A2AOutboundToolkit",+ "GatewayA2AOutboundToolBackend",+ "_RPC_DISPATCH",+ "_RPC_FIND",+ "_RPC_GET",+]diff --git a/jiuwenswarm/agents/harness/common/tools/acp_output_tools.py b/jiuwenswarm/agents/harness/common/tools/acp_output_tools.pyindex f97ddfa4ac..4d2c2855ac 100644--- a/jiuwenswarm/agents/harness/common/tools/acp_output_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/acp_output_tools.py@@ -54,14 +54,12 @@ class AcpOutputRequest:class AcpOutputManager:_instance: AcpOutputManager | None = None_pending: dict[str, AcpOutputRequest]- _jsonrpc_counter: int_send_push_callback: Anydef __new__(cls) -> AcpOutputManager:if cls._instance is None:cls._instance = super().__new__(cls)cls._instance._pending = {}- cls._instance._jsonrpc_counter = 0cls._instance._send_push_callback = Nonereturn cls._instance@@ -71,13 +69,16 @@ class AcpOutputManager:def set_send_push_callback(self, callback: Any) -> None:self._send_push_callback = callback+ @property+ def pending_count(self) -> int:+ return len(self._pending)+def reset_state(self) -> None:"""Reset runtime state.Intended for unit tests and controlled lifecycle cleanup."""self._pending.clear()- self._jsonrpc_counter = 0def add_pending_request(self, request: AcpOutputRequest) -> None:"""Register a pending request explicitly.@@ -141,23 +142,26 @@ class AcpOutputManager:channel_id: str = "acp",session_id: str | None = None,timeout: float = _ACP_REQUEST_TIMEOUT_SECONDS,+ log_params: bool = True,+ cancel_method: str | None = None,) -> dict[str, Any]:+ loop = asyncio.get_running_loop()+ deadline = loop.time() + timeoutlogger.info("[AcpOutput] send_jsonrpc_request called: method=%s params=%s",method,- params,+ params if log_params else "<redacted>",)if self._send_push_callback is None:logger.error("[AcpOutput] send_push callback is None!")raise RuntimeError("ACP output send_push callback not set")- self._jsonrpc_counter += 1- jsonrpc_id = str(self._jsonrpc_counter)+ # IDs cross the AgentServer -> Gateway boundary and must remain unique+ # across process restarts and multiple AgentServer instances.+ jsonrpc_id = f"acp-{uuid.uuid4().hex}"request_id = f"acp_out_{uuid.uuid4().hex[:12]}"- future: asyncio.Future[dict[str, Any]] = (- asyncio.get_event_loop().create_future()- )+ future: asyncio.Future[dict[str, Any]] = loop.create_future()acp_req = AcpOutputRequest(jsonrpc_id=jsonrpc_id,method=method,@@ -212,11 +216,40 @@ class AcpOutputManager:try:callback_result = self._send_push_callback(push_msg)if inspect.isawaitable(callback_result):- await callback_result+ callback_result = await asyncio.wait_for(+ callback_result,+ timeout=max(0.0, deadline - loop.time()),+ )+ if callback_result is False or (+ isinstance(callback_result, int) and callback_result <= 0+ ):+ raise RuntimeError("ACP output request was not delivered")+ except asyncio.CancelledError:+ await self._handle_cancellation(+ cancel_method=cancel_method,+ jsonrpc_id=jsonrpc_id,+ channel_id=channel_id,+ session_id=session_id,+ method=method,+ )+ raiseexcept Exception as exc:self._pending.pop(jsonrpc_id, None)raise RuntimeError(f"Failed to send ACP output request: {exc}") from exc+ # wait_for() on Python 3.11 can swallow a cancellation that races+ # with the callback's completion; detect it explicitly.+ current_task = asyncio.current_task()+ if current_task is not None and current_task.cancelling():+ await self._handle_cancellation(+ cancel_method=cancel_method,+ jsonrpc_id=jsonrpc_id,+ channel_id=channel_id,+ session_id=session_id,+ method=method,+ )+ raise asyncio.CancelledError()+logger.info("[AcpOutput] sent E2A request: jsonrpc_id=%s method=%s request_id=%s",jsonrpc_id,@@ -225,7 +258,22 @@ class AcpOutputManager:)try:- return await asyncio.wait_for(future, timeout=timeout)+ if future.done():+ result = future.result()+ else:+ result = await asyncio.wait_for(+ future,+ timeout=max(0.0, deadline - loop.time()),+ )+ except asyncio.CancelledError:+ await self._handle_cancellation(+ cancel_method=cancel_method,+ jsonrpc_id=jsonrpc_id,+ channel_id=channel_id,+ session_id=session_id,+ method=method,+ )+ raiseexcept asyncio.TimeoutError:self._pending.pop(jsonrpc_id, None)logger.warning(@@ -236,6 +284,68 @@ class AcpOutputManager:)raise+ if current_task is not None and current_task.cancelling():+ await self._handle_cancellation(+ cancel_method=cancel_method,+ jsonrpc_id=jsonrpc_id,+ channel_id=channel_id,+ session_id=session_id,+ method=method,+ )+ raise asyncio.CancelledError()++ return result++ async def _handle_cancellation(+ self,+ *,+ cancel_method: str | None,+ jsonrpc_id: str,+ channel_id: str,+ session_id: str | None,+ method: str,+ ) -> None:+ self._pending.pop(jsonrpc_id, None)+ await self._notify_cancellation(+ cancel_method=cancel_method,+ jsonrpc_id=jsonrpc_id,+ channel_id=channel_id,+ session_id=session_id,+ method=method,+ )++ async def _notify_cancellation(+ self,+ *,+ cancel_method: str | None,+ jsonrpc_id: str,+ channel_id: str,+ session_id: str | None,+ method: str,+ ) -> None:+ if not cancel_method:+ return+ cancel_task = asyncio.create_task(+ self.send_jsonrpc_request(+ cancel_method,+ {"jsonrpc_id": jsonrpc_id},+ channel_id=channel_id,+ session_id=session_id,+ timeout=5.0,+ log_params=False,+ ),+ name=f"acp-cancel-{jsonrpc_id}",+ )+ try:+ await asyncio.shield(cancel_task)+ except Exception:+ logger.warning(+ "[AcpOutput] cancellation notification failed: "+ "jsonrpc_id=%s method=%s",+ jsonrpc_id,+ method,+ )+def get_acp_output_manager() -> AcpOutputManager:return AcpOutputManager()diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsxindex ff31f83b91..6e6f44dab0 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx@@ -1,10 +1,13 @@import { useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { ChevronDown } from 'lucide-react';import type { WebError } from '../../types/websocket';+import { Switch } from '../Switch';import {normalizeA2AOutboundAgent,normalizeA2AOutboundDiscovery,normalizeA2AOutboundList,+ normalizeA2AOutboundSettings,shouldAcceptA2AOutboundResponse,type A2AOutboundAgent,type A2AOutboundAvailability,@@ -28,6 +31,9 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {const [url, setUrl] = useState('');const [discovery, setDiscovery] = useState<A2AOutboundDiscovery | null>(null);const [agents, setAgents] = useState<A2AOutboundAgent[]>([]);+ const [allowLoopbackHttp, setAllowLoopbackHttp] = useState(false);+ const [savedAllowLoopbackHttp, setSavedAllowLoopbackHttp] = useState(false);+ const [advancedOpen, setAdvancedOpen] = useState(false);const [displayName, setDisplayName] = useState('');const [credential, setCredential] = useState('');const [busy, setBusy] = useState<string | null>(null);@@ -40,11 +46,17 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {if (!isConnected) return;const generation = ++generationRef.current;try {- const payload = await request('a2a.outbound.list');+ const [payload, rawSettings] = await Promise.all([+ request('a2a.outbound.list'),+ request('a2a.outbound.settings.get'),+ ]);if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;const next = normalizeA2AOutboundList(payload);- if (!next) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));+ const settings = normalizeA2AOutboundSettings(rawSettings);+ if (!next || !settings) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));setAgents(next);+ setAllowLoopbackHttp(settings.allow_loopback_http);+ setSavedAllowLoopbackHttp(settings.allow_loopback_http);setError(null);} catch (nextError) {if (shouldAcceptA2AOutboundResponse(generation, generationRef.current)) setError(errorMessage(nextError));@@ -65,6 +77,29 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {finally { setBusy(null); }};+ const updateAllowLoopbackHttp = async (nextEnabled: boolean) => {+ if (busy || !isConnected) return;+ const generation = ++generationRef.current;+ const previous = savedAllowLoopbackHttp;+ setAllowLoopbackHttp(nextEnabled);+ setBusy('settings'); setError(null); setNotice(null);+ try {+ const settings = normalizeA2AOutboundSettings(await request('a2a.outbound.settings.update', {+ allow_loopback_http: nextEnabled,+ }));+ if (!settings) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));+ if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;+ setAllowLoopbackHttp(settings.allow_loopback_http);+ setSavedAllowLoopbackHttp(settings.allow_loopback_http);+ setNotice(t('a2aIngress.outbound.localDebug.saved'));+ } catch (nextError) {+ if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;+ setAllowLoopbackHttp(previous);+ setError(errorMessage(nextError));+ }+ finally { setBusy(null); }+ };+const register = async () => {if (!discovery || busy || !isConnected) return;setBusy('register'); setError(null);@@ -135,6 +170,32 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {<input className="min-w-0 flex-1 rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent" value={url} onChange={event => setUrl(event.target.value)} placeholder="https://agent.example.com" disabled={!!busy} /><button type="button" className="btn primary" onClick={() => void discover()} disabled={!isConnected || !!busy || !url.trim()}>{busy === 'discover' ? t('a2aIngress.outbound.discovery.discovering') : t('a2aIngress.outbound.discovery.action')}</button></div>+ <div className="mt-4 border-t border-border pt-3">+ <button+ type="button"+ className="flex w-full items-center justify-between gap-3 text-left text-sm font-medium text-text-muted hover:text-text"+ aria-expanded={advancedOpen}+ onClick={() => setAdvancedOpen(open => !open)}+ >+ <span>{t('a2aIngress.outbound.discovery.advanced')}</span>+ <ChevronDown size={16} className={`shrink-0 transition-transform ${advancedOpen ? 'rotate-180' : ''}`} />+ </button>+ {advancedOpen && <div className="mt-3 rounded-lg border border-border bg-bg/60 p-3">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium text-text">{t('a2aIngress.outbound.localDebug.allow')}</div>+ <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.localDebug.description')}</p>+ </div>+ <Switch+ checked={allowLoopbackHttp}+ onChange={nextEnabled => void updateAllowLoopbackHttp(nextEnabled)}+ disabled={!isConnected || !!busy}+ title={t('a2aIngress.outbound.localDebug.allow')}+ />+ </div>+ {allowLoopbackHttp && <p className="mt-3 border-t border-warn/20 pt-3 text-xs text-warn">{t('a2aIngress.outbound.localDebug.warning')}</p>}+ </div>}+ </div></section>{discovery && <section className="rounded-xl border border-accent/30 bg-accent/5 p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h3 className="font-semibold text-text">{discovery.agent.name}</h3><p className="mt-1 text-sm text-text-muted">{discovery.agent.description || '-'}</p></div><span className="rounded-full bg-secondary px-2.5 py-1 text-xs text-text-muted">{t('a2aIngress.outbound.discovery.previewOnly')}</span></div>diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.ts b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.tsindex ee98712874..c549441ce8 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.ts+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.ts@@ -39,6 +39,10 @@ export interface A2AOutboundAgent {pending_revision: Record<string, unknown> | null;}+export interface A2AOutboundSettings {+ allow_loopback_http: boolean;+}+const asString = (value: unknown): string => typeof value === 'string' ? value : '';const asNumber = (value: unknown): number => typeof value === 'number' && Number.isFinite(value) ? value : 0;@@ -106,4 +110,10 @@ export function normalizeA2AOutboundList(value: unknown): A2AOutboundAgent[] | nreturn result;}+export function normalizeA2AOutboundSettings(value: unknown): A2AOutboundSettings | null {+ if (!value || typeof value !== 'object') return null;+ const enabled = (value as Record<string, unknown>).allow_loopback_http;+ return typeof enabled === 'boolean' ? { allow_loopback_http: enabled } : null;+}+export const shouldAcceptA2AOutboundResponse = (generation: number, current: number): boolean => generation === current;diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 712423829a..6023c10023 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -567,7 +567,8 @@"status": { "title": "Service status", "configRevision": "Configuration revision: {{revision}}", "effectiveRpcUrl": "Effective JSON-RPC URL", "effectiveCardUrl": "Effective Agent Card URL", "notListening": "Not listening" },"config": { "title": "Ingress configuration", "description": "Save updates the desired configuration only; Save and apply reloads the running service." },"outbound": {- "discovery": { "title": "Discover a third-party Agent", "description": "Discovery only fetches and previews the Agent Card. JiuwenSwarm can call the Agent only after explicit registration.", "action": "Discover Agent", "discovering": "Discovering...", "previewOnly": "Preview only, not registered", "previewReady": "Discovery succeeded. Review and explicitly register this candidate before it can be called." },+ "localDebug": { "title": "Local Agent debugging", "description": "Controls whether plaintext HTTP Agents on loopback addresses may be discovered and called. Changes apply immediately after saving.", "allow": "Allow local HTTP Agents", "warning": "For local E2E debugging only. This relaxes SSRF protection for 127.0.0.1 / ::1 and must remain disabled in production.", "saving": "Saving...", "saved": "Outbound local debugging settings were saved and applied immediately." },+ "discovery": { "title": "Discover a third-party Agent", "description": "Discovery only fetches and previews the Agent Card. JiuwenSwarm can call the Agent only after explicit registration.", "action": "Discover Agent", "discovering": "Discovering...", "previewOnly": "Preview only, not registered", "previewReady": "Discovery succeeded. Review and explicitly register this candidate before it can be called.", "advanced": "Advanced settings" },"list": { "title": "Registered Agents", "total": "{{count}} total", "empty": "No third-party Agents are registered" },"fields": { "version": "Version", "endpoint": "Effective endpoint", "protocol": "Protocol", "expiresAt": "Candidate expires", "displayName": "Display name", "credential": "API Key / Bearer (optional, never displayed)", "revision": "Card revision", "credentialState": "Credential", "lastChecked": "Last checked", "connectTimeout": "Connect timeout (seconds)", "syncWait": "Sync wait timeout (seconds)", "replaceCredential": "Replace credential (leave blank to keep)" },"availability": { "available": "Available", "unreachable": "Unreachable", "incompatible": "Incompatible", "review_required": "Review required" },diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 8ac60e44ec..6a8389498d 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -568,7 +568,8 @@"status": { "title": "服务状态", "configRevision": "配置版本:{{revision}}", "effectiveRpcUrl": "实际 JSON-RPC 地址", "effectiveCardUrl": "实际 Agent Card 地址", "notListening": "当前未监听" },"config": { "title": "入站服务配置", "description": "保存只更新目标配置;“保存并应用”会重载正在运行的服务。" },"outbound": {- "discovery": { "title": "发现第三方 Agent", "description": "发现仅获取并预览 Agent Card;完成手动注册后,JiuwenSwarm 才能调用该 Agent。", "action": "发现 Agent", "discovering": "发现中...", "previewOnly": "仅预览,尚未注册", "previewReady": "发现成功。请核对信息并显式注册,当前候选尚不可调用。" },+ "localDebug": { "title": "本地 Agent 调试", "description": "控制是否允许发现和调用本机 loopback 地址上的明文 HTTP Agent。设置保存后立即生效。", "allow": "允许本机 HTTP Agent", "warning": "仅用于本机 E2E 调试。启用后会放宽针对 127.0.0.1 / ::1 的 SSRF 防护,请勿在生产环境开启。", "saving": "保存中...", "saved": "出站本地调试设置已保存并立即生效。" },+ "discovery": { "title": "发现第三方 Agent", "description": "发现仅获取并预览 Agent Card;完成手动注册后,JiuwenSwarm 才能调用该 Agent。", "action": "发现 Agent", "discovering": "发现中...", "previewOnly": "仅预览,尚未注册", "previewReady": "发现成功。请核对信息并显式注册,当前候选尚不可调用。", "advanced": "高级配置" },"list": { "title": "已注册 Agent", "total": "共 {{count}} 个", "empty": "暂无已注册的第三方 Agent" },"fields": { "version": "版本", "endpoint": "实际 Endpoint", "protocol": "协议", "expiresAt": "候选过期时间", "displayName": "显示名称", "credential": "API Key / Bearer(可选,不会回显)", "revision": "Card 版本", "credentialState": "凭据", "lastChecked": "最近检查", "connectTimeout": "连接超时(秒)", "syncWait": "同步等待超时(秒)", "replaceCredential": "替换凭据(留空则不修改)" },"availability": { "available": "可用", "unreachable": "不可达", "incompatible": "不兼容", "review_required": "待确认" },diff --git a/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjs b/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjsindex b9a9d8467a..cff5c8da0b 100644--- a/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjs@@ -4,6 +4,7 @@ import {normalizeA2AOutboundAgent,normalizeA2AOutboundDiscovery,normalizeA2AOutboundList,+ normalizeA2AOutboundSettings,shouldAcceptA2AOutboundResponse,} from '../node_modules/.cache/a2a-outbound-panel-state/components/A2AIngressPanel/a2aOutboundPanelState.js';@@ -64,6 +65,12 @@ test('A2A outbound list rejects any malformed item', () => {assert.equal(normalizeA2AOutboundList({ items: 'invalid' }), null);});+test('A2A outbound settings require an explicit loopback boolean', () => {+ assert.deepEqual(normalizeA2AOutboundSettings({ allow_loopback_http: true }), { allow_loopback_http: true });+ assert.equal(normalizeA2AOutboundSettings({ allow_loopback_http: 'true' }), null);+ assert.equal(normalizeA2AOutboundSettings({}), null);+});+test('A2A outbound ignores obsolete responses', () => {assert.equal(shouldAcceptA2AOutboundResponse(7, 7), true);assert.equal(shouldAcceptA2AOutboundResponse(6, 7), false);diff --git a/jiuwenswarm/gateway/a2a_manager/__init__.py b/jiuwenswarm/gateway/a2a_manager/__init__.pyindex bdb8ad464a..3c1ad2c03d 100644--- a/jiuwenswarm/gateway/a2a_manager/__init__.py+++ b/jiuwenswarm/gateway/a2a_manager/__init__.py@@ -1,10 +1,16 @@"""A2A ingress lifecycle, configuration persistence, and management API types."""-from .config import A2AIngressConfigRepository, load_a2a_ingress_config, load_a2a_ingress_config_safely+from .config import (+ A2AIngressConfigRepository,+ A2AOutboundSettingsRepository,+ load_a2a_ingress_config,+ load_a2a_ingress_config_safely,+)from .manager import A2AManagerfrom .models import A2AIngressConfig, A2AIngressError, A2AIngressSnapshot, A2AIngressState__all__ = ["A2AIngressConfig", "A2AIngressConfigRepository", "A2AIngressError", "A2AIngressSnapshot",- "A2AIngressState", "A2AManager", "load_a2a_ingress_config", "load_a2a_ingress_config_safely",+ "A2AIngressState", "A2AManager", "A2AOutboundSettingsRepository",+ "load_a2a_ingress_config", "load_a2a_ingress_config_safely",]diff --git a/jiuwenswarm/gateway/a2a_manager/config.py b/jiuwenswarm/gateway/a2a_manager/config.pyindex c1be90b8dd..1cf4ecf4b4 100644--- a/jiuwenswarm/gateway/a2a_manager/config.py+++ b/jiuwenswarm/gateway/a2a_manager/config.py@@ -5,22 +5,93 @@ from __future__ import annotationsimport osimport reimport tempfile+import threadingfrom collections.abc import Mappingfrom pathlib import Path+import portalocker+from .models import A2AIngressConfig, A2AIngressError_TRUE_VALUES = {"1", "true", "yes", "on"}_FALSE_VALUES = {"0", "false", "no", "off"}A2A_INGRESS_ENV_MAP = {- "enabled": "A2A_SERVER_ENABLED", "host": "A2A_SERVER_HOST", "port": "A2A_SERVER_PORT",- "rpc_path": "A2A_SERVER_PATH", "protocol_version": "A2A_SERVER_PROTOCOL_VERSION",- "card_path": "A2A_SERVER_CARD_PATH", "extended_card_path": "A2A_SERVER_EXTENDED_CARD_PATH",- "app_name": "A2A_SERVER_APP_NAME", "app_description": "A2A_SERVER_APP_DESCRIPTION",- "app_version": "A2A_SERVER_APP_VERSION", "expose_reasoning": "A2A_SERVER_EXPOSE_REASONING",+ "enabled": "A2A_SERVER_ENABLED",+ "host": "A2A_SERVER_HOST",+ "port": "A2A_SERVER_PORT",+ "rpc_path": "A2A_SERVER_PATH",+ "protocol_version": "A2A_SERVER_PROTOCOL_VERSION",+ "card_path": "A2A_SERVER_CARD_PATH",+ "extended_card_path": "A2A_SERVER_EXTENDED_CARD_PATH",+ "app_name": "A2A_SERVER_APP_NAME",+ "app_description": "A2A_SERVER_APP_DESCRIPTION",+ "app_version": "A2A_SERVER_APP_VERSION",+ "expose_reasoning": "A2A_SERVER_EXPOSE_REASONING",}-_ENV_ASSIGNMENT_RE = re.compile(r"^(?P<indent>\s*)(?P<export>export\s+)?(?P<key>[A-Za-z_][A-Za-z0-9_]*)\s*=")+A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP_ENV = "A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP"+_ENV_ASSIGNMENT_RE = re.compile(+ r"^(?P<indent>\s*)(?P<export>export\s+)?(?P<key>[A-Za-z_][A-Za-z0-9_]*)\s*="+)+_DOTENV_WRITE_LOCK = threading.Lock()+_DOTENV_LOCK_TIMEOUT_SECONDS = 10.0+++def _quote_dotenv_value(value: str) -> str:+ return (+ value.replace("\\", "\\\\")+ .replace('"', '\\"')+ .replace("\r", "\\r")+ .replace("\n", "\\n")+ )+++def _persist_dotenv_updates(env_path: Path, updates: Mapping[str, str]) -> None:+ """Atomically merge allow-listed values under one shared .env writer lock."""+ temp_path: Path | None = None+ env_path.parent.mkdir(parents=True, exist_ok=True)+ lock_path = env_path.with_name(f"{env_path.name}.lock")+ try:+ with _DOTENV_WRITE_LOCK:+ with portalocker.Lock(+ str(lock_path), timeout=_DOTENV_LOCK_TIMEOUT_SECONDS+ ):+ lines = (+ env_path.read_text(encoding="utf-8").splitlines(keepends=True)+ if env_path.is_file()+ else []+ )+ pending = dict(updates)+ output: list[str] = []+ for line in lines:+ match = _ENV_ASSIGNMENT_RE.match(line)+ key = match.group("key") if match else ""+ if key not in pending:+ output.append(line)+ continue+ output.append(+ f"{match.group('indent')}{match.group('export') or ''}{key}="+ f'"{_quote_dotenv_value(pending.pop(key))}"\n'+ )+ output.extend(+ f'{key}="{_quote_dotenv_value(value)}"\n'+ for key, value in pending.items()+ )+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ dir=env_path.parent,+ prefix=f".{env_path.name}.",+ suffix=".tmp",+ delete=False,+ ) as temp_file:+ temp_file.write("".join(output))+ temp_path = Path(temp_file.name)+ os.replace(temp_path, env_path)+ temp_path = None+ finally:+ if temp_path is not None and temp_path.exists():+ temp_path.unlink(missing_ok=True)def _value(env: Mapping[str, str], name: str, default: str) -> str:@@ -43,9 +114,13 @@ def load_a2a_ingress_config(env: Mapping[str, str] | None = None) -> A2AIngressCtry:port = int(port_text)except ValueError as exc:- raise A2AIngressError("A2A_CONFIG_INVALID", "A2A_SERVER_PORT must be an integer") from exc+ raise A2AIngressError(+ "A2A_CONFIG_INVALID", "A2A_SERVER_PORT must be an integer"+ ) from excif not 1 <= port <= 65535:- raise A2AIngressError("A2A_CONFIG_INVALID", "A2A_SERVER_PORT must be between 1 and 65535")+ raise A2AIngressError(+ "A2A_CONFIG_INVALID", "A2A_SERVER_PORT must be between 1 and 65535"+ )return A2AIngressConfig(enabled=_bool(source, "A2A_SERVER_ENABLED", False),@@ -53,12 +128,18 @@ def load_a2a_ingress_config(env: Mapping[str, str] | None = None) -> A2AIngressCport=port,rpc_path=_value(source, "A2A_SERVER_PATH", "/a2a"),protocol_version=_value(source, "A2A_SERVER_PROTOCOL_VERSION", "1.0.0"),- card_path=_value(source, "A2A_SERVER_CARD_PATH", "/.well-known/agent-card.json"),+ card_path=_value(+ source, "A2A_SERVER_CARD_PATH", "/.well-known/agent-card.json"+ ),extended_card_path=_value(source, "A2A_SERVER_EXTENDED_CARD_PATH", "/agent/authenticatedExtendedCard"),- app_name=_value(source, "A2A_SERVER_APP_NAME", "JiuwenSwarm Gateway A2A Server"),- app_description=_value(source, "A2A_SERVER_APP_DESCRIPTION", "A2A ingress for JiuwenSwarm Gateway"),+ app_name=_value(+ source, "A2A_SERVER_APP_NAME", "JiuwenSwarm Gateway A2A Server"+ ),+ app_description=_value(+ source, "A2A_SERVER_APP_DESCRIPTION", "A2A ingress for JiuwenSwarm Gateway"+ ),app_version=_value(source, "A2A_SERVER_APP_VERSION", "0.1.0"),expose_reasoning=_bool(source, "A2A_SERVER_EXPOSE_REASONING", True),).validate()@@ -86,55 +167,69 @@ class A2AIngressConfigRepository:def save(self, config: A2AIngressConfig) -> None:updates = self._to_env_updates(config.validate())- temp_path: Path | None = Nonetry:- lines = (- self._env_path.read_text(encoding="utf-8").splitlines(keepends=True)- if self._env_path.is_file()- else []- )- pending = dict(updates)- output: list[str] = []- for line in lines:- match = _ENV_ASSIGNMENT_RE.match(line)- key = match.group("key") if match else ""- if key not in pending:- output.append(line)- continue- output.append(- f'{match.group("indent")}{match.group("export") or ""}{key}='- f'"{self._quote_dotenv_value(pending.pop(key))}"\n'- )- output.extend(- f'{key}="{self._quote_dotenv_value(value)}"\n' for key, value in pending.items()- )- self._env_path.parent.mkdir(parents=True, exist_ok=True)- with tempfile.NamedTemporaryFile(- mode="w", encoding="utf-8", dir=self._env_path.parent,- prefix=f".{self._env_path.name}.", suffix=".tmp", delete=False,- ) as temp_file:- temp_file.write("".join(output))- temp_path = Path(temp_file.name)- os.replace(temp_path, self._env_path)- except OSError as exc:- raise A2AIngressError("A2A_CONFIG_INVALID", f"Failed to persist A2A ingress config: {exc}") from exc- finally:- if temp_path is not None and temp_path.exists():- temp_path.unlink(missing_ok=True)+ _persist_dotenv_updates(self._env_path, updates)+ except (OSError, portalocker.exceptions.LockException) as exc:+ raise A2AIngressError(+ "A2A_CONFIG_INVALID", f"Failed to persist A2A ingress config: {exc}"+ ) from excos.environ.update(updates)@staticmethoddef _quote_dotenv_value(value: str) -> str:- return value.replace("\\", "\\\\").replace('"', '\\"').replace("\r", "\\r").replace("\n", "\\n")+ return _quote_dotenv_value(value)@staticmethoddef _to_env_updates(config: A2AIngressConfig) -> dict[str, str]:values = {- "enabled": "true" if config.enabled else "false", "host": config.host,- "port": str(config.port), "rpc_path": config.rpc_path,- "protocol_version": config.protocol_version, "card_path": config.card_path,- "extended_card_path": config.extended_card_path, "app_name": config.app_name,- "app_description": config.app_description, "app_version": config.app_version,+ "enabled": "true" if config.enabled else "false",+ "host": config.host,+ "port": str(config.port),+ "rpc_path": config.rpc_path,+ "protocol_version": config.protocol_version,+ "card_path": config.card_path,+ "extended_card_path": config.extended_card_path,+ "app_name": config.app_name,+ "app_description": config.app_description,+ "app_version": config.app_version,"expose_reasoning": "true" if config.expose_reasoning else "false",}return {A2A_INGRESS_ENV_MAP[name]: value for name, value in values.items()}+++class A2AOutboundSettingsRepository:+ """Persist the small personal-edition outbound settings surface in ``.env``."""++ def __init__(self, env_path: Path | None = None) -> None:+ if env_path is None:+ from jiuwenswarm.common.utils import get_env_file++ env_path = get_env_file()+ self._env_path = Path(env_path)++ @staticmethod+ def load(env: Mapping[str, str] | None = None) -> dict[str, bool]:+ source = os.environ if env is None else env+ return {+ "allow_loopback_http": _bool(+ source, A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP_ENV, False+ )+ }++ def save(self, *, allow_loopback_http: bool) -> None:+ if not isinstance(allow_loopback_http, bool):+ raise A2AIngressError(+ "A2A_CONFIG_INVALID", "allow_loopback_http must be a boolean"+ )+ update = "true" if allow_loopback_http else "false"+ try:+ _persist_dotenv_updates(+ self._env_path,+ {A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP_ENV: update},+ )+ except (OSError, portalocker.exceptions.LockException) as exc:+ raise A2AIngressError(+ "A2A_CONFIG_INVALID",+ f"Failed to persist A2A outbound settings: {exc}",+ ) from exc+ os.environ[A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP_ENV] = updatediff --git a/jiuwenswarm/gateway/a2a_manager/manager.py b/jiuwenswarm/gateway/a2a_manager/manager.pyindex 06524b1d4d..fbd5a732ee 100644--- a/jiuwenswarm/gateway/a2a_manager/manager.py+++ b/jiuwenswarm/gateway/a2a_manager/manager.py@@ -4,18 +4,26 @@ from __future__ import annotationsimport asyncioimport logging-import osimport timefrom collections import dequefrom collections.abc import Callablefrom typing import Any, Protocol-from jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import A2AChannel, A2ADependencyMissingError+from jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import (+ A2AChannel,+ A2ADependencyMissingError,+)-from .config import A2AIngressConfigRepository-from .models import A2AIngressConfig, A2AIngressError, A2AIngressSnapshot, A2AIngressState+from .config import A2AIngressConfigRepository, A2AOutboundSettingsRepository+from .models import (+ A2AIngressConfig,+ A2AIngressError,+ A2AIngressSnapshot,+ A2AIngressState,+)from .outbound import (A2AOutboundDiscoveryService,+ A2AOutboundDispatcher,A2AOutboundError,A2AOutboundErrorCode,A2AOutboundRegistry,@@ -54,6 +62,8 @@ class A2AManager:initial_error: A2AIngressError | None = None,outbound_repository: A2AOutboundRepository | None = None,outbound_registry: A2AOutboundRegistry | None = None,+ outbound_dispatcher: A2AOutboundDispatcher | None = None,+ outbound_settings_repository: A2AOutboundSettingsRepository | Any | None = None,) -> None:self._channel_manager = channel_managerself._router = router@@ -64,16 +74,20 @@ class A2AManager:self._effective_config: A2AIngressConfig | None = Noneself._starting_config: A2AIngressConfig | None = Noneself._start_task: asyncio.Task[None] | None = None- self._state = A2AIngressState.ERROR if initial_error else A2AIngressState.DISABLED+ self._state = (+ A2AIngressState.ERROR if initial_error else A2AIngressState.DISABLED+ )self._started_at: float | None = Noneself._last_error: str | None = str(initial_error) if initial_error else Noneself._config_revision = 0self._request_history: deque[dict[str, Any]] = deque(maxlen=200)self._lock = asyncio.Lock()self._pending_callbacks: set[asyncio.Task[None]] = set()- allow_loopback_http = os.getenv(- "A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP", ""- ).strip().lower() in {"1", "true", "yes", "on"}+ self._outbound_settings_repository = (+ outbound_settings_repository or A2AOutboundSettingsRepository()+ )+ outbound_settings = self._outbound_settings_repository.load()+ allow_loopback_http = bool(outbound_settings.get("allow_loopback_http", False))self._outbound = outbound_registryif self._outbound is None and outbound_repository is not None:self._outbound = A2AOutboundRegistry(@@ -82,6 +96,15 @@ class A2AManager:allow_loopback_http=allow_loopback_http),)+ self._outbound_dispatcher = outbound_dispatcher+ if self._outbound_dispatcher is None and outbound_repository is not None:+ self._outbound_dispatcher = A2AOutboundDispatcher(+ outbound_repository,+ discovery_service=A2AOutboundDiscoveryService(+ allow_loopback_http=allow_loopback_http+ ),+ )+ self._apply_outbound_settings(allow_loopback_http)@propertydef channel(self) -> _ManagedA2AChannel | None:@@ -96,11 +119,34 @@ class A2AManager:raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)return self._outbound+ def _require_outbound_dispatcher(self) -> A2AOutboundDispatcher:+ if self._outbound_dispatcher is None:+ raise A2AOutboundError(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)+ return self._outbound_dispatcher+async def outbound_discover(self, url: str, card_path: str | None = None) -> dict[str, Any]:return await self._require_outbound().discover(url, card_path)+ async def outbound_get_settings(self) -> dict[str, bool]:+ return dict(self._outbound_settings_repository.load())++ async def outbound_update_settings(+ self, *, allow_loopback_http: bool+ ) -> dict[str, bool]:+ if not isinstance(allow_loopback_http, bool):+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)+ self._outbound_settings_repository.save(allow_loopback_http=allow_loopback_http)+ self._apply_outbound_settings(allow_loopback_http)+ return {"allow_loopback_http": allow_loopback_http}++ def _apply_outbound_settings(self, allow_loopback_http: bool) -> None:+ for target in (self._outbound, self._outbound_dispatcher):+ setter = getattr(target, "set_allow_loopback_http", None)+ if callable(setter):+ setter(allow_loopback_http)+async def outbound_register(self, params: dict[str, Any]) -> dict[str, Any]:return await self._require_outbound().register(params)@@ -129,11 +175,51 @@ class A2AManager:async def outbound_dispatch_get(self, dispatch_id: str) -> dict[str, Any]:return await self._require_outbound().get_dispatch(dispatch_id)+ async def outbound_find_agents(+ self,+ *,+ query: str = "",+ required_skills: list[str] | None = None,+ limit: int = 5,+ ) -> dict[str, Any]:+ return await self._require_outbound_dispatcher().find_agents(+ query=query,+ required_skills=required_skills,+ limit=limit,+ )++ async def outbound_dispatch_task(+ self,+ *,+ agent_id: str,+ task: str,+ mode: str,+ source_session_id: str,+ reason: str | None = None,+ ) -> dict[str, Any]:+ return await self._require_outbound_dispatcher().dispatch(+ agent_id=agent_id,+ task=task,+ mode=mode,+ source_session_id=source_session_id,+ reason=reason,+ )++ async def outbound_get_dispatch(+ self, *, dispatch_id: str, source_session_id: str+ ) -> dict[str, Any]:+ return await self._require_outbound_dispatcher().query_dispatch(+ dispatch_id,+ source_session_id=source_session_id,+ )+def snapshot(self) -> A2AIngressSnapshot:config = self._configeffective = self._effective_configdesired_base_url = f"http://{config.host}:{config.port}"- effective_base_url = f"http://{effective.host}:{effective.port}" if effective else None+ effective_base_url = (+ f"http://{effective.host}:{effective.port}" if effective else None+ )return A2AIngressSnapshot(enabled=config.enabled,state=self._state,@@ -153,11 +239,16 @@ class A2AManager:effective_port=effective.port if effective else None,effective_rpc_path=effective.rpc_path if effective else None,effective_card_path=effective.card_path if effective else None,- effective_rpc_url=(f"{effective_base_url}{effective.rpc_path}" if effective else None),- effective_card_url=(f"{effective_base_url}{effective.card_path}" if effective else None),+ effective_rpc_url=(+ f"{effective_base_url}{effective.rpc_path}" if effective else None+ ),+ effective_card_url=(+ f"{effective_base_url}{effective.card_path}" if effective else None+ ),exposure_warning=("A2A ingress is bound to all network interfaces; configure network access controls."- if config.host == "0.0.0.0" else None+ if config.host == "0.0.0.0"+ else None),started_at=self._started_at,last_error=self._last_error,@@ -168,14 +259,27 @@ class A2AManager:"""Return newest-first request lifecycle metadata for this Gateway process."""normalized_limit = max(1, min(int(limit), 200))items = list(reversed(self._request_history))[:normalized_limit]- return {"items": [dict(item) for item in items], "total": len(self._request_history)}+ return {+ "items": [dict(item) for item in items],+ "total": len(self._request_history),+ }def _record_request_event(self, event: dict[str, Any]) -> None:request_id = str(event.get("request_id") or "").strip()if not request_id:return- existing = next((item for item in self._request_history if item["request_id"] == request_id), None)- if existing is not None and existing.get("status") in _TERMINAL_REQUEST_STATUSES:+ existing = next(+ (+ item+ for item in self._request_history+ if item["request_id"] == request_id+ ),+ None,+ )+ if (+ existing is not None+ and existing.get("status") in _TERMINAL_REQUEST_STATUSES+ ):returnif existing is None:started_at = float(event.get("started_at") or time.time())@@ -197,7 +301,10 @@ class A2AManager:if existing.get("finished_at") is not None:existing["duration_ms"] = max(0,- round((float(existing["finished_at"]) - float(existing["started_at"])) * 1000),+ round(+ (float(existing["finished_at"]) - float(existing["started_at"]))+ * 1000+ ),)async def start_from_config(self) -> A2AIngressSnapshot:@@ -212,7 +319,9 @@ class A2AManager:await self._create_and_start_locked(wait=False)return self.snapshot()- async def update(self, patch: dict[str, Any], *, apply: bool = False) -> A2AIngressSnapshot:+ async def update(+ self, patch: dict[str, Any], *, apply: bool = False+ ) -> A2AIngressSnapshot:async with self._lock:next_config = self._config.with_patch(patch)self._persist_locked(next_config)@@ -267,7 +376,9 @@ class A2AManager:async def _create_and_start_locked(self, *, wait: bool) -> None:effective_config = self._config- channel = self._channel_factory(effective_config.to_channel_config(), self._router)+ channel = self._channel_factory(+ effective_config.to_channel_config(), self._router+ )set_request_observer = getattr(channel, "set_request_observer", None)if callable(set_request_observer):set_request_observer(self._record_request_event)@@ -315,7 +426,10 @@ class A2AManager:try:await taskexcept asyncio.CancelledError:- if asyncio.current_task() is not None and asyncio.current_task().cancelling():+ if (+ asyncio.current_task() is not None+ and asyncio.current_task().cancelling()+ ):propagate_cancellation = Trueexcept Exception: # noqa: BLE001pass@@ -353,7 +467,9 @@ class A2AManager:self._effective_config = self._starting_configlogger.info("a2a.ingress running")- async def _record_background_error(self, task: asyncio.Task[None], exc: Exception) -> None:+ async def _record_background_error(+ self, task: asyncio.Task[None], exc: Exception+ ) -> None:async with self._lock:if self._start_task is task:self._record_start_error(exc)@@ -382,4 +498,8 @@ class A2AManager:"""Gateway shutdown; does not persist a configuration change."""async with self._lock:await self._dispose_channel_locked()- self._state = A2AIngressState.DISABLED if not self._config.enabled else A2AIngressState.ERROR+ self._state = (+ A2AIngressState.DISABLED+ if not self._config.enabled+ else A2AIngressState.ERROR+ )diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py b/jiuwenswarm/gateway/a2a_manager/outbound/__init__.pyindex aa72ef5a49..03883b2976 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py@@ -2,6 +2,7 @@from .credentials import A2AOutboundCredentialStorefrom .discovery import A2AOutboundDiscoveryService, DiscoveredCard+from .dispatcher import A2AOutboundDispatcherfrom .errors import A2AOutboundError, A2AOutboundErrorCode, safe_error_summaryfrom .models import (A2ACompatibleInterface,@@ -29,6 +30,7 @@ __all__ = ["A2AOutboundAvailability","A2AOutboundCredentialStore","A2AOutboundDiscoveryService",+ "A2AOutboundDispatcher","A2AOutboundRegistry","A2AOutboundDiscovery","A2AOutboundDispatch",diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py b/jiuwenswarm/gateway/a2a_manager/outbound/discovery.pyindex 4880d1dbcf..1b03b1c85b 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py@@ -151,6 +151,13 @@ def _pinned_transport_factory(return _PinnedAsyncHTTPTransport(pinned_addresses)+def create_pinned_transport(+ pinned_addresses: Mapping[str, str],+) -> httpx.AsyncBaseTransport:+ """Build the shared DNS-pinned transport used by discovery and dispatch."""+ return _pinned_transport_factory(pinned_addresses)++async def _resolve_addresses(host: str, port: int) -> list[str]:loop = asyncio.get_running_loop()rows = await loop.getaddrinfo(host, port, type=socket.SOCK_STREAM)@@ -184,6 +191,13 @@ class A2AOutboundDiscoveryService:self._address_resolver = address_resolverself._transport_factory = transport_factory+ @property+ def allow_loopback_http(self) -> bool:+ return self._allow_loopback_http++ def set_allow_loopback_http(self, enabled: bool) -> None:+ self._allow_loopback_http = bool(enabled)+async def discover(self, url: str, card_path: str | None = None) -> DiscoveredCard:source_url, normalized_path, card_url = self._normalize(url, card_path)current = card_url@@ -379,5 +393,14 @@ class A2AOutboundDiscoveryService:pinned_address=addresses[0],)+ async def validate_network_target(self, url: str) -> _ValidatedTarget:+ """Revalidate and resolve a target immediately before a connection."""+ return await self._validate_network_target(url)+-__all__ = ["A2AOutboundDiscoveryService", "DiscoveredCard", "DEFAULT_CARD_PATH"]+__all__ = [+ "A2AOutboundDiscoveryService",+ "DiscoveredCard",+ "DEFAULT_CARD_PATH",+ "create_pinned_transport",+]diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.pynew file mode 100644index 0000000000..b0f7b24bb7--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py@@ -0,0 +1,870 @@+"""Registered-Agent-only A2A outbound dispatching for the personal edition."""++from __future__ import annotations++import asyncio+import copy+import hashlib+import logging+import time+import uuid+from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from typing import Any, Protocol++import httpx+from a2a.client import ClientCallContext, ClientConfig+from a2a.client.card_resolver import parse_agent_card+from a2a.client.client_factory import ClientFactory+from a2a.types import (+ CancelTaskRequest,+ GetTaskRequest,+ Message,+ Part,+ Role,+ SendMessageConfiguration,+ SendMessageRequest,+ Task,+ TaskState,+)++from .credentials import A2AOutboundCredentialStore+from .discovery import A2AOutboundDiscoveryService, create_pinned_transport+from .errors import A2AOutboundError, A2AOutboundErrorCode, safe_error_summary+from .locks import KeyedLockPool+from .models import (+ A2AOutboundAgent,+ A2AOutboundAvailability,+ A2AOutboundDispatch,+ A2AOutboundDispatchMode,+ A2AOutboundDispatchStatus,+)+from .repository import A2AOutboundRepository, utc_now_text++logger = logging.getLogger(__name__)++MAX_TASK_TEXT_LENGTH = 64 * 1024+MAX_RESULT_TEXT_LENGTH = 64 * 1024+MAX_RESULT_ARTIFACTS = 32+DEFAULT_GLOBAL_CONCURRENCY = 16+DEFAULT_AGENT_CONCURRENCY = 4+DEFAULT_QUERY_INTERVAL_SECONDS = 1.0+++class _ClientLike(Protocol):+ async def send_message(self, request, *, context=None):+ raise NotImplementedError++ async def get_task(self, request, *, context=None):+ raise NotImplementedError++ async def cancel_task(self, request, *, context=None):+ raise NotImplementedError++ async def close(self) -> None:+ raise NotImplementedError+++def _is_selected_interface(item: Any, selected: Any) -> bool:+ """Match a parsed Agent Card interface against the agent's pinned selection."""+ same_url = item.url == selected.url+ same_binding = item.protocol_binding.upper() == selected.protocol_binding.upper()+ return same_url and same_binding+++def _skill_search_tokens(skills: Any) -> set[str]:+ """Collect lowercase id/name/tag tokens for one agent's public skills."""+ tokens: set[str] = set()+ for skill in skills:+ tokens.add(str(skill.get("id") or "").lower())+ tokens.add(str(skill.get("name") or "").lower())+ for tag in skill.get("tags") or ():+ tokens.add(str(tag).lower())+ tokens.discard("")+ return tokens+++ClientBuilder = Callable[[A2AOutboundAgent, str], Awaitable[_ClientLike]]+++@dataclass(frozen=True)+class _NormalizedRemote:+ status: A2AOutboundDispatchStatus+ remote_task_id: str | None = None+ remote_context_id: str | None = None+ result: dict[str, Any] | None = None+++class _CapacityLease:+ def __init__(self, dispatcher: "A2AOutboundDispatcher", agent_id: str) -> None:+ self._dispatcher = dispatcher+ self._agent_id = agent_id++ async def __aenter__(self) -> None:+ async with self._dispatcher._capacity_lock:+ agent_active = self._dispatcher._agent_active.get(self._agent_id, 0)+ if (+ self._dispatcher._global_active >= self._dispatcher._global_limit+ or agent_active >= self._dispatcher._agent_limit+ ):+ raise A2AOutboundError(A2AOutboundErrorCode.OUTBOUND_BUSY)+ self._dispatcher._global_active += 1+ self._dispatcher._agent_active[self._agent_id] = agent_active + 1++ async def __aexit__(self, *_args: object) -> None:+ async with self._dispatcher._capacity_lock:+ self._dispatcher._global_active = max(+ 0, self._dispatcher._global_active - 1+ )+ remaining = self._dispatcher._agent_active.get(self._agent_id, 1) - 1+ if remaining > 0:+ self._dispatcher._agent_active[self._agent_id] = remaining+ else:+ self._dispatcher._agent_active.pop(self._agent_id, None)+++class A2AOutboundDispatcher:+ """Dispatch through persisted registrations and normalize remote A2A state."""++ def __init__(+ self,+ repository: A2AOutboundRepository,+ *,+ credential_store: A2AOutboundCredentialStore | None = None,+ discovery_service: A2AOutboundDiscoveryService | None = None,+ client_builder: ClientBuilder | None = None,+ global_concurrency: int = DEFAULT_GLOBAL_CONCURRENCY,+ agent_concurrency: int = DEFAULT_AGENT_CONCURRENCY,+ query_interval_seconds: float = DEFAULT_QUERY_INTERVAL_SECONDS,+ monotonic: Callable[[], float] = time.monotonic,+ ) -> None:+ self._repository = repository+ self._credentials = credential_store or A2AOutboundCredentialStore()+ self._discovery = discovery_service or A2AOutboundDiscoveryService()+ self._client_builder = client_builder+ self._global_limit = max(1, int(global_concurrency))+ self._agent_limit = max(1, int(agent_concurrency))+ self._query_interval = max(0.0, float(query_interval_seconds))+ self._monotonic = monotonic+ self._capacity_lock = asyncio.Lock()+ self._global_active = 0+ self._agent_active: dict[str, int] = {}+ self._query_locks = KeyedLockPool()+ self._last_query_monotonic: dict[str, float] = {}++ def set_allow_loopback_http(self, enabled: bool) -> None:+ self._discovery.set_allow_loopback_http(enabled)++ async def find_agents(+ self,+ query: str = "",+ required_skills: list[str] | tuple[str, ...] | None = None,+ limit: int = 5,+ ) -> dict[str, Any]:+ normalized_query = str(query or "").strip().lower()+ required = {+ str(value).strip().lower()+ for value in (required_skills or ())+ if str(value).strip()+ }+ normalized_limit = max(1, min(int(limit), 20))+ matches: list[tuple[int, dict[str, Any]]] = []+ for agent in await self._repository.list_agents():+ if not self._callable(agent):+ continue+ card = agent.agent_card+ skills = self._public_skills(card)+ skill_tokens = _skill_search_tokens(skills)+ if required and not required.issubset(skill_tokens):+ continue+ searchable = " ".join(+ [agent.display_name, str(card.get("description") or "")]+ + [+ " ".join(+ str(skill.get(key) or "")+ for key in ("id", "name", "description")+ )+ for skill in skills+ ]+ ).lower()+ score = sum(1 for token in normalized_query.split() if token in searchable)+ if normalized_query and score == 0:+ continue+ matches.append(+ (+ score,+ {+ "agent_id": agent.agent_id,+ "name": agent.display_name,+ "description": str(card.get("description") or ""),+ "skills": skills,+ "input_modes": list(card.get("defaultInputModes") or []),+ "output_modes": list(card.get("defaultOutputModes") or []),+ "availability": agent.availability.value,+ },+ )+ )+ matches.sort(key=lambda item: (-item[0], item[1]["name"].lower()))+ items = [item for _, item in matches[:normalized_limit]]+ return {"items": items, "total": len(items)}++ async def dispatch(+ self,+ *,+ agent_id: str,+ task: str,+ mode: A2AOutboundDispatchMode | str,+ source_session_id: str,+ reason: str | None = None,+ ) -> dict[str, Any]:+ reason_present = bool(str(reason or "").strip())+ task_text = str(task or "")+ if not task_text.strip() or len(task_text) > MAX_TASK_TEXT_LENGTH:+ raise A2AOutboundError(A2AOutboundErrorCode.TASK_INVALID)+ try:+ normalized_mode = A2AOutboundDispatchMode(str(mode))+ except ValueError as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.MODE_INVALID) from exc+ session_id = str(source_session_id or "").strip()+ if not session_id:+ raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_REJECTED)+ agent = await self._require_callable_agent(agent_id)++ dispatch_id = f"disp_{uuid.uuid4().hex}"+ message_id = f"msg_{uuid.uuid4().hex}"+ stamp = utc_now_text()+ dispatch = A2AOutboundDispatch(+ dispatch_id=dispatch_id,+ agent_id=agent.agent_id,+ agent_revision=agent.card_revision,+ mode=normalized_mode,+ status=A2AOutboundDispatchStatus.CREATED,+ request_message_id=message_id,+ source_session_id=session_id,+ created_at=stamp,+ updated_at=stamp,+ input_length=len(task_text),+ input_content_type="text/plain",+ input_digest=f"sha256:{hashlib.sha256(task_text.encode()).hexdigest()}",+ )+ create_task: asyncio.Task[A2AOutboundDispatch] | None = None+ try:+ create_task = asyncio.create_task(+ self._repository.create_dispatch(dispatch),+ name=f"a2a-outbound-create-{dispatch.dispatch_id}",+ )+ await asyncio.shield(create_task)+ try:+ async with _CapacityLease(self, agent.agent_id):+ result = await self._submit(agent, dispatch, task_text)+ except A2AOutboundError as exc:+ if exc.code is not A2AOutboundErrorCode.OUTBOUND_BUSY:+ raise+ updated = await self._repository.transition_dispatch(+ dispatch.dispatch_id,+ A2AOutboundDispatchStatus.DISPATCH_FAILED,+ error_code=exc.code.value,+ )+ result = self._public_dispatch(updated or dispatch)+ except asyncio.CancelledError:+ if create_task is not None:+ try:+ await asyncio.shield(create_task)+ except Exception:+ logger.debug(+ "a2a.outbound create_dispatch failed during cancellation",+ exc_info=True,+ )+ await asyncio.shield(+ self._repository.transition_dispatch(+ dispatch.dispatch_id,+ A2AOutboundDispatchStatus.UNKNOWN,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ )+ )+ raise+ logger.info(+ "a2a.outbound audit action=dispatch dispatch_id=%s agent_id=%s "+ "agent_revision=%s mode=%s status=%s source_session_id=%s reason_present=%s",+ dispatch.dispatch_id,+ dispatch.agent_id,+ dispatch.agent_revision,+ dispatch.mode.value,+ result.get("status"),+ dispatch.source_session_id,+ reason_present,+ )+ return result++ async def query_dispatch(+ self, dispatch_id: str, *, source_session_id: str+ ) -> dict[str, Any]:+ normalized_id = str(dispatch_id or "").strip()+ async with self._query_locks.hold(normalized_id):+ current = await self._require_owned_dispatch(+ normalized_id, source_session_id+ )+ if current.is_terminal or not current.remote_task_id:+ return self._public_dispatch(current)+ now = self._monotonic()+ last = self._last_query_monotonic.get(normalized_id)+ if last is not None and now - last < self._query_interval:+ return self._public_dispatch(+ current,+ retry_after_seconds=round(self._query_interval - (now - last), 3),+ )+ self._last_query_monotonic[normalized_id] = now+ agent = await self._repository.get_agent(current.agent_id)+ if agent is None:+ return self._public_dispatch(current)+ try:+ client = await self._build_client(agent)+ try:+ task = await client.get_task(+ GetTaskRequest(id=current.remote_task_id, history_length=1),+ context=ClientCallContext(+ timeout=agent.connect_timeout_seconds+ ),+ )+ finally:+ await client.close()+ normalized = self._normalize_task(task)+ updated = await self._apply_remote(+ current.dispatch_id, normalized, polled=True+ )+ return self._public_dispatch(updated or current)+ except Exception:+ logger.debug(+ "a2a.outbound query_dispatch failed: dispatch_id=%s",+ normalized_id,+ exc_info=True,+ )+ updated = await self._repository.transition_dispatch(+ current.dispatch_id,+ A2AOutboundDispatchStatus.UNKNOWN,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ last_polled_at=utc_now_text(),+ )+ return self._public_dispatch(updated or current)++ async def cancel_dispatch(+ self, dispatch_id: str, *, source_session_id: str+ ) -> dict[str, Any]:+ async with self._query_locks.hold(str(dispatch_id)):+ current = await self._require_owned_dispatch(dispatch_id, source_session_id)+ if current.is_terminal or not current.remote_task_id:+ return self._public_dispatch(current)+ agent = await self._repository.get_agent(current.agent_id)+ if agent is None:+ return self._public_dispatch(current)+ try:+ client = await self._build_client(agent)+ try:+ task = await client.cancel_task(+ CancelTaskRequest(id=current.remote_task_id),+ context=ClientCallContext(+ timeout=agent.connect_timeout_seconds+ ),+ )+ finally:+ await client.close()+ normalized = self._normalize_task(task)+ updated = await self._apply_remote(current.dispatch_id, normalized)+ return self._public_dispatch(updated or current)+ except Exception:+ logger.debug(+ "a2a.outbound cancel_dispatch failed: dispatch_id=%s",+ dispatch_id,+ exc_info=True,+ )+ updated = await self._repository.transition_dispatch(+ current.dispatch_id,+ A2AOutboundDispatchStatus.UNKNOWN,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ )+ return self._public_dispatch(updated or current)++ async def _submit(+ self,+ agent: A2AOutboundAgent,+ dispatch: A2AOutboundDispatch,+ task_text: str,+ ) -> dict[str, Any]:+ current = await self._repository.transition_dispatch(+ dispatch.dispatch_id, A2AOutboundDispatchStatus.SUBMITTING+ )+ client: _ClientLike | None = None+ last_remote = _NormalizedRemote(A2AOutboundDispatchStatus.SUBMITTING)+ try:+ client = await self._build_client(agent)+ request = SendMessageRequest(+ message=Message(+ message_id=dispatch.request_message_id,+ role=Role.ROLE_USER,+ parts=[Part(text=task_text)],+ ),+ configuration=SendMessageConfiguration(+ return_immediately=dispatch.mode is A2AOutboundDispatchMode.ASYNC+ ),+ )++ async def consume() -> _NormalizedRemote:+ nonlocal last_remote+ # 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.+ call_context = (+ None+ if dispatch.mode is A2AOutboundDispatchMode.SYNC+ else ClientCallContext(timeout=agent.connect_timeout_seconds)+ )+ async for event in client.send_message(+ request,+ context=call_context,+ ):+ last_remote = self._normalize_stream_event(event, last_remote)+ applied = await self._apply_remote(+ dispatch.dispatch_id, last_remote+ )+ if applied is not None:+ current_status = applied.status+ if applied.is_terminal or current_status in {+ A2AOutboundDispatchStatus.INPUT_REQUIRED,+ A2AOutboundDispatchStatus.AUTH_REQUIRED,+ }:+ break+ if (+ dispatch.mode is A2AOutboundDispatchMode.ASYNC+ and last_remote.remote_task_id+ ):+ break+ return last_remote++ if dispatch.mode is A2AOutboundDispatchMode.SYNC:+ try:+ async with asyncio.timeout(agent.sync_wait_seconds):+ await consume()+ while True:+ latest = await self._repository.get_dispatch(+ dispatch.dispatch_id+ )+ if latest is None:+ raise A2AOutboundError(+ A2AOutboundErrorCode.DISPATCH_NOT_FOUND+ )+ if latest.is_terminal or latest.status in {+ A2AOutboundDispatchStatus.INPUT_REQUIRED,+ A2AOutboundDispatchStatus.AUTH_REQUIRED,+ }:+ break+ if not latest.remote_task_id:+ break+ await asyncio.sleep(min(self._query_interval, 1.0))+ remote_task = await client.get_task(+ GetTaskRequest(+ id=latest.remote_task_id, history_length=1+ ),+ context=ClientCallContext(+ timeout=agent.connect_timeout_seconds+ ),+ )+ last_remote = self._normalize_task(remote_task)+ await self._apply_remote(+ dispatch.dispatch_id, last_remote, polled=True+ )+ except TimeoutError:+ updated = await self._repository.transition_dispatch(+ dispatch.dispatch_id,+ A2AOutboundDispatchStatus.TIMED_OUT,+ remote_task_id=last_remote.remote_task_id,+ remote_context_id=last_remote.remote_context_id,+ error_code=A2AOutboundErrorCode.DISPATCH_TIMEOUT.value,+ )+ return self._public_dispatch(updated or current)+ else:+ await consume()++ updated = await self._repository.get_dispatch(dispatch.dispatch_id)+ if updated is None:+ raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)+ if (+ dispatch.mode is A2AOutboundDispatchMode.ASYNC+ and not updated.is_terminal+ and not updated.remote_task_id+ ):+ updated = (+ await self._repository.transition_dispatch(+ dispatch.dispatch_id,+ A2AOutboundDispatchStatus.DISPATCH_FAILED,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ )+ or updated+ )+ return self._public_dispatch(updated)+ except asyncio.CancelledError:+ await asyncio.shield(+ self._settle_cancelled(+ client,+ agent,+ dispatch.dispatch_id,+ last_remote,+ )+ )+ raise+ except A2AOutboundError as exc:+ status = (+ A2AOutboundDispatchStatus.AUTH_REQUIRED+ if exc.code is A2AOutboundErrorCode.AUTH_REQUIRED+ else A2AOutboundDispatchStatus.DISPATCH_FAILED+ )+ updated = await self._repository.transition_dispatch(+ dispatch.dispatch_id,+ status,+ remote_task_id=last_remote.remote_task_id,+ remote_context_id=last_remote.remote_context_id,+ error_code=exc.code.value,+ )+ return self._public_dispatch(updated or current)+ except Exception:+ target = (+ A2AOutboundDispatchStatus.UNKNOWN+ if last_remote.remote_task_id+ else A2AOutboundDispatchStatus.DISPATCH_FAILED+ )+ code = (+ A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN+ if last_remote.remote_task_id+ else A2AOutboundErrorCode.DISPATCH_REJECTED+ )+ updated = await self._repository.transition_dispatch(+ dispatch.dispatch_id,+ target,+ remote_task_id=last_remote.remote_task_id,+ remote_context_id=last_remote.remote_context_id,+ error_code=code.value,+ )+ return self._public_dispatch(updated or current)+ finally:+ if client is not None:+ try:+ await client.close()+ except Exception:+ logger.debug("a2a.outbound client close failed", exc_info=True)++ async def _build_client(self, agent: A2AOutboundAgent) -> _ClientLike:+ credential = self._credentials.get(agent.credential_ref)+ if agent.agent_card.get("securityRequirements") and not credential:+ raise A2AOutboundError(A2AOutboundErrorCode.AUTH_REQUIRED)+ if self._client_builder is not None:+ return await self._client_builder(agent, credential)+ target = await self._discovery.validate_network_target(+ agent.selected_interface.url+ )+ headers: dict[str, str] = {}+ if credential:+ headers["Authorization"] = (+ credential+ if credential.lower().startswith("bearer ")+ else f"Bearer {credential}"+ )+ http_client = httpx.AsyncClient(+ transport=create_pinned_transport({target.host: target.pinned_address}),+ headers=headers,+ follow_redirects=False,+ trust_env=False,+ timeout=httpx.Timeout(+ connect=agent.connect_timeout_seconds,+ write=agent.connect_timeout_seconds,+ pool=agent.connect_timeout_seconds,+ read=None,+ ),+ )+ try:+ parsed = parse_agent_card(copy.deepcopy(agent.agent_card))+ selected = agent.selected_interface+ matching = [+ item+ for item in parsed.supported_interfaces+ if _is_selected_interface(item, selected)+ ]+ if not matching:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_UNAVAILABLE)+ del parsed.supported_interfaces[:]+ parsed.supported_interfaces.extend(matching)+ return ClientFactory(+ ClientConfig(+ streaming=True,+ polling=False,+ httpx_client=http_client,+ supported_protocol_bindings=[selected.protocol_binding],+ )+ ).create(parsed)+ except Exception:+ await http_client.aclose()+ raise++ async def _require_callable_agent(self, agent_id: str) -> A2AOutboundAgent:+ agent = await self._repository.get_agent(str(agent_id or "").strip())+ if agent is None:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)+ if not agent.enabled:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_DISABLED)+ if agent.availability is A2AOutboundAvailability.REVIEW_REQUIRED:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_REVIEW_REQUIRED)+ if agent.availability is not A2AOutboundAvailability.AVAILABLE:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_UNAVAILABLE)+ return agent++ @staticmethod+ def _callable(agent: A2AOutboundAgent) -> bool:+ return bool(+ agent.enabled and agent.availability is A2AOutboundAvailability.AVAILABLE+ )++ async def _require_owned_dispatch(+ self, dispatch_id: str, source_session_id: str+ ) -> A2AOutboundDispatch:+ dispatch = await self._repository.get_dispatch(str(dispatch_id or "").strip())+ if dispatch is None:+ raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)+ if dispatch.source_session_id != str(source_session_id or "").strip():+ # Deliberately indistinguishable from a missing ID.+ raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)+ return dispatch++ async def _apply_remote(+ self, dispatch_id: str, remote: _NormalizedRemote, *, polled: bool = False+ ) -> A2AOutboundDispatch | None:+ stamp = utc_now_text()+ changes: dict[str, Any] = {+ "remote_task_id": remote.remote_task_id,+ "remote_context_id": remote.remote_context_id,+ "result": remote.result,+ "error_code": None,+ "error_summary": None,+ }+ if remote.remote_task_id:+ changes["accepted_at"] = stamp+ if polled:+ changes["last_polled_at"] = stamp+ if remote.status is A2AOutboundDispatchStatus.AUTH_REQUIRED:+ changes["error_code"] = A2AOutboundErrorCode.AUTH_REQUIRED.value+ elif remote.status is A2AOutboundDispatchStatus.REJECTED:+ changes["error_code"] = A2AOutboundErrorCode.DISPATCH_REJECTED.value+ elif remote.status is A2AOutboundDispatchStatus.UNKNOWN:+ changes["error_code"] = A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value+ return await self._repository.transition_dispatch(+ dispatch_id, remote.status, **changes+ )++ async def _settle_cancelled(+ self,+ client: _ClientLike | None,+ agent: A2AOutboundAgent,+ dispatch_id: str,+ remote: _NormalizedRemote,+ ) -> None:+ if client is not None and remote.remote_task_id:+ try:+ task = await client.cancel_task(+ CancelTaskRequest(id=remote.remote_task_id),+ context=ClientCallContext(timeout=agent.connect_timeout_seconds),+ )+ await self._apply_remote(dispatch_id, self._normalize_task(task))+ return+ except Exception:+ logger.debug(+ "a2a.outbound remote cancel_task failed dispatch_id=%s",+ dispatch_id,+ exc_info=True,+ )+ await self._repository.transition_dispatch(+ dispatch_id,+ A2AOutboundDispatchStatus.UNKNOWN,+ remote_task_id=remote.remote_task_id,+ remote_context_id=remote.remote_context_id,+ error_code=A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN.value,+ )++ def _normalize_stream_event(+ self, event: Any, previous: _NormalizedRemote+ ) -> _NormalizedRemote:+ if event.HasField("message"):+ message = event.message+ return _NormalizedRemote(+ A2AOutboundDispatchStatus.COMPLETED,+ remote_task_id=message.task_id or previous.remote_task_id,+ remote_context_id=message.context_id or previous.remote_context_id,+ result=self._result_from_message(message),+ )+ if event.HasField("task"):+ return self._normalize_task(event.task)+ if event.HasField("status_update"):+ update = event.status_update+ status = self._map_task_state(update.status.state)+ result = (+ self._result_from_message(update.status.message)+ if update.status.HasField("message")+ else previous.result+ )+ if status is A2AOutboundDispatchStatus.COMPLETED:+ result = self._promote_artifact_text(result)+ return _NormalizedRemote(+ status,+ remote_task_id=update.task_id or previous.remote_task_id,+ remote_context_id=update.context_id or previous.remote_context_id,+ result=result,+ )+ if event.HasField("artifact_update"):+ update = event.artifact_update+ result = dict(previous.result or {"text": "", "artifacts": []})+ artifacts = list(result.get("artifacts") or [])+ if len(artifacts) < MAX_RESULT_ARTIFACTS:+ artifacts.append(self._artifact_summary(update.artifact))+ result["artifacts"] = artifacts+ return _NormalizedRemote(+ previous.status,+ remote_task_id=update.task_id or previous.remote_task_id,+ remote_context_id=update.context_id or previous.remote_context_id,+ result=result,+ )+ return previous++ def _normalize_task(self, task: Task) -> _NormalizedRemote:+ result = None+ if task.status.HasField("message") or task.artifacts:+ result = (+ self._result_from_message(task.status.message)+ if task.status.HasField("message")+ else {"text": "", "artifacts": []}+ )+ result["artifacts"] = [+ self._artifact_summary(item)+ for item in list(task.artifacts)[:MAX_RESULT_ARTIFACTS]+ ]+ if self._map_task_state(task.status.state) is A2AOutboundDispatchStatus.COMPLETED:+ result = self._promote_artifact_text(result)+ return _NormalizedRemote(+ self._map_task_state(task.status.state),+ remote_task_id=task.id or None,+ remote_context_id=task.context_id or None,+ result=result,+ )++ @staticmethod+ def _map_task_state(state: int) -> A2AOutboundDispatchStatus:+ return {+ TaskState.TASK_STATE_SUBMITTED: A2AOutboundDispatchStatus.ACCEPTED,+ TaskState.TASK_STATE_WORKING: A2AOutboundDispatchStatus.WORKING,+ TaskState.TASK_STATE_COMPLETED: A2AOutboundDispatchStatus.COMPLETED,+ TaskState.TASK_STATE_FAILED: A2AOutboundDispatchStatus.FAILED,+ TaskState.TASK_STATE_CANCELED: A2AOutboundDispatchStatus.CANCELED,+ TaskState.TASK_STATE_INPUT_REQUIRED: A2AOutboundDispatchStatus.INPUT_REQUIRED,+ TaskState.TASK_STATE_REJECTED: A2AOutboundDispatchStatus.REJECTED,+ TaskState.TASK_STATE_AUTH_REQUIRED: A2AOutboundDispatchStatus.AUTH_REQUIRED,+ }.get(state, A2AOutboundDispatchStatus.UNKNOWN)++ @staticmethod+ def _result_from_message(message: Message) -> dict[str, Any]:+ text = "\n".join(part.text for part in message.parts if part.HasField("text"))+ truncated = len(text) > MAX_RESULT_TEXT_LENGTH+ return {+ "text": text[:MAX_RESULT_TEXT_LENGTH],+ "artifacts": [],+ **({"truncated": True} if truncated else {}),+ }++ @staticmethod+ def _artifact_summary(artifact: Any) -> dict[str, Any]:+ text = "\n".join(part.text for part in artifact.parts if part.HasField("text"))+ truncated = len(text) > MAX_RESULT_TEXT_LENGTH+ return {+ "artifact_id": artifact.artifact_id or None,+ "name": artifact.name or None,+ "description": artifact.description or None,+ "text": text[:MAX_RESULT_TEXT_LENGTH],+ **({"truncated": True} if truncated else {}),+ }++ @staticmethod+ def _promote_artifact_text(+ result: dict[str, Any] | None,+ ) -> dict[str, Any] | None:+ """Use completed artifact content as the primary tool result text."""+ if not result:+ return result+ artifact_texts = [+ str(item.get("text") or "").strip()+ for item in result.get("artifacts") or []+ if isinstance(item, dict) and str(item.get("text") or "").strip()+ ]+ if not artifact_texts:+ return result+ promoted = dict(result)+ text = "\n".join(artifact_texts)+ promoted["text"] = text[:MAX_RESULT_TEXT_LENGTH]+ if len(text) > MAX_RESULT_TEXT_LENGTH:+ promoted["truncated"] = True+ return promoted++ @staticmethod+ def _public_skills(card: dict[str, Any]) -> list[dict[str, Any]]:+ return [+ {+ "id": str(item.get("id") or ""),+ "name": str(item.get("name") or ""),+ "description": str(item.get("description") or ""),+ "tags": [str(tag) for tag in item.get("tags") or []],+ }+ for item in card.get("skills") or []+ if isinstance(item, dict)+ ]++ @staticmethod+ def _public_dispatch(+ dispatch: A2AOutboundDispatch,+ *,+ retry_after_seconds: float | None = None,+ ) -> dict[str, Any]:+ ok = dispatch.status in {+ A2AOutboundDispatchStatus.ACCEPTED,+ A2AOutboundDispatchStatus.WORKING,+ A2AOutboundDispatchStatus.COMPLETED,+ }+ payload: dict[str, Any] = {+ "ok": ok,+ "dispatch_id": dispatch.dispatch_id,+ "agent_id": dispatch.agent_id,+ "mode": dispatch.mode.value,+ "status": dispatch.status.value,+ "remote_task_id": dispatch.remote_task_id,+ "remote_context_id": dispatch.remote_context_id,+ "created_at": dispatch.created_at,+ "accepted_at": dispatch.accepted_at,+ "finished_at": dispatch.finished_at,+ "result": dispatch.result,+ "error_code": dispatch.error_code,+ "error_summary": (+ safe_error_summary(dispatch.error_code) if dispatch.error_code else None+ ),+ }+ if dispatch.remote_task_id and dispatch.status in {+ A2AOutboundDispatchStatus.ACCEPTED,+ A2AOutboundDispatchStatus.WORKING,+ A2AOutboundDispatchStatus.TIMED_OUT,+ A2AOutboundDispatchStatus.UNKNOWN,+ }:+ payload["next_action"] = (+ "Call a2a_get_dispatch with dispatch_id to retrieve status and result."+ )+ if retry_after_seconds is not None:+ payload["retry_after_seconds"] = retry_after_seconds+ return payload+++__all__ = [+ "A2AOutboundDispatcher",+ "DEFAULT_AGENT_CONCURRENCY",+ "DEFAULT_GLOBAL_CONCURRENCY",+ "MAX_TASK_TEXT_LENGTH",+]diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py b/jiuwenswarm/gateway/a2a_manager/outbound/errors.pyindex 6367ec675d..da6851f15e 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/errors.py@@ -24,6 +24,9 @@ class A2AOutboundErrorCode(str, Enum):DISPATCH_CONFLICT = "A2A_DISPATCH_CONFLICT"REMOTE_STATUS_UNKNOWN = "A2A_REMOTE_STATUS_UNKNOWN"OUTBOUND_BUSY = "A2A_OUTBOUND_BUSY"+ TASK_INVALID = "A2A_OUTBOUND_TASK_INVALID"+ MODE_INVALID = "A2A_OUTBOUND_MODE_INVALID"+ MANAGER_UNAVAILABLE = "A2A_OUTBOUND_MANAGER_UNAVAILABLE"STORE_INVALID = "A2A_OUTBOUND_STORE_INVALID"@@ -46,6 +49,9 @@ _SAFE_SUMMARIES: dict[A2AOutboundErrorCode, str] = {A2AOutboundErrorCode.DISPATCH_CONFLICT: "出站请求状态已发生变化。",A2AOutboundErrorCode.REMOTE_STATUS_UNKNOWN: "暂时无法确认第三方请求状态。",A2AOutboundErrorCode.OUTBOUND_BUSY: "A2A 出站服务当前繁忙。",+ A2AOutboundErrorCode.TASK_INVALID: "A2A 出站任务文本无效。",+ A2AOutboundErrorCode.MODE_INVALID: "A2A 出站派发模式无效。",+ A2AOutboundErrorCode.MANAGER_UNAVAILABLE: "A2A 出站管理服务当前不可用。",A2AOutboundErrorCode.STORE_INVALID: "A2A 出站数据无效。",}diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py b/jiuwenswarm/gateway/a2a_manager/outbound/registry.pyindex c0c2545768..a4de234e87 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py@@ -102,6 +102,9 @@ class A2AOutboundRegistry:self._registration_lock = asyncio.Lock()self._agent_operation_locks = KeyedLockPool()+ 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]:card = await self._discovery.discover(url, card_path)now = self._now()diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py b/jiuwenswarm/gateway/a2a_manager/outbound/repository.pyindex 20db5a1fbe..01413108cc 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/repository.py@@ -265,6 +265,11 @@ class A2AOutboundRepository:if current.status in TERMINAL_DISPATCH_STATUSES:return current+ # Lifecycle timestamps record the first observation and must not+ # drift on later working/poll events.+ if current.accepted_at is not None:+ changes["accepted_at"] = current.accepted_at+stamp = updated_at or utc_now_text()if normalized_status in TERMINAL_DISPATCH_STATUSES:changes.setdefault("finished_at", stamp)diff --git a/jiuwenswarm/gateway/a2a_manager/tool_rpc.py b/jiuwenswarm/gateway/a2a_manager/tool_rpc.pynew file mode 100644index 0000000000..4cdf8413a1--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/tool_rpc.py@@ -0,0 +1,22 @@+"""Private AgentServer-to-Gateway method names for A2A outbound tools."""++A2A_TOOL_FIND_AGENTS = "a2a.outbound.tool.find_agents"+A2A_TOOL_DISPATCH_TASK = "a2a.outbound.tool.dispatch_task"+A2A_TOOL_GET_DISPATCH = "a2a.outbound.tool.get_dispatch"+A2A_TOOL_CANCEL_CALL = "a2a.outbound.tool.cancel_call"+A2A_TOOL_METHODS = frozenset(+ {+ A2A_TOOL_FIND_AGENTS,+ A2A_TOOL_DISPATCH_TASK,+ A2A_TOOL_GET_DISPATCH,+ A2A_TOOL_CANCEL_CALL,+ }+)++__all__ = [+ "A2A_TOOL_DISPATCH_TASK",+ "A2A_TOOL_CANCEL_CALL",+ "A2A_TOOL_FIND_AGENTS",+ "A2A_TOOL_GET_DISPATCH",+ "A2A_TOOL_METHODS",+]diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex d6858c81b8..8fd51feb6f 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -2031,6 +2031,7 @@ async def _run_with_telemetry(initial_error=a2a_config_error,outbound_repository=a2a_outbound_repository,)+ message_handler.set_a2a_outbound_tool_manager(a2a_manager)_register_web_handlers(WebHandlersBindParams(diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex a14fdbbb3b..8925eaac61 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1778,6 +1778,28 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:),)+ async def _a2a_outbound_settings_get(ws, req_id, params, session_id):+ await _send_a2a_outbound(ws, req_id, a2a_manager.outbound_get_settings)++ async def _a2a_outbound_settings_update(ws, req_id, params, session_id):+ enabled = params.get("allow_loopback_http")+ if not isinstance(enabled, bool):+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error="allow_loopback_http must be a boolean",+ code="A2A_CONFIG_INVALID",+ )+ return+ await _send_a2a_outbound(+ ws,+ req_id,+ lambda: a2a_manager.outbound_update_settings(+ allow_loopback_http=enabled+ ),+ )+async def _a2a_outbound_register(ws, req_id, params, session_id):await _send_a2a_outbound(ws, req_id, lambda: a2a_manager.outbound_register(dict(params))@@ -1841,6 +1863,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:lambda: a2a_manager.outbound_dispatch_get(str(params.get("dispatch_id") or "")),)+ channel.register_method("a2a.outbound.settings.get", _a2a_outbound_settings_get)+ channel.register_method("a2a.outbound.settings.update", _a2a_outbound_settings_update)channel.register_method("a2a.outbound.discover", _a2a_outbound_discover)channel.register_method("a2a.outbound.register", _a2a_outbound_register)channel.register_method("a2a.outbound.list", _a2a_outbound_list)diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.pyindex 3bf0882d0a..8de00b8619 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py@@ -84,6 +84,21 @@ _A2A_INGRESS_ROUTES: tuple[WebHttpMappedRoute, ...] = ()_A2A_OUTBOUND_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "GET",+ "/a2a/outbound/settings",+ "a2a.outbound.settings.get",+ "a2a",+ "读取 A2A 出站设置",+ ),+ WebHttpMappedRoute(+ "PATCH",+ "/a2a/outbound/settings",+ "a2a.outbound.settings.update",+ "a2a",+ "更新 A2A 出站设置",+ accept_body=True,+ ),WebHttpMappedRoute("POST","/a2a/outbound/discover",diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex 513d040dde..00a0093db2 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -214,6 +214,10 @@ class MessageHandler(ABC):self._user_messages: asyncio.Queue["Message"] = asyncio.Queue()self._robot_messages: asyncio.Queue["Message"] = asyncio.Queue()self._running = False+ self._a2a_outbound_tool_manager: Any | None = None+ self._active_a2a_outbound_tool_tasks: dict[+ str, tuple[asyncio.Task[Any], str]+ ] = {}self._forward_task: asyncio.Task | None = Noneself._stream_tasks: dict[str, asyncio.Task] = {} # request_id -> taskself._stream_channels: dict[str, str] = {} # request_id -> channel_id@@ -2846,6 +2850,12 @@ class MessageHandler(ABC):session_id: str | None = str(sid_raw)else:session_id = self._stream_sessions.get(rid)++ if await self._handle_a2a_outbound_tool_push(+ chunk=chunk,+ session_id=session_id,+ ):+ return# 获取原始请求的 metadata,用于合并request_metadata = self._stream_metadata.get(rid)@@ -2910,6 +2920,160 @@ class MessageHandler(ABC):_push_app_id,)+ def set_a2a_outbound_tool_manager(self, manager: Any | None) -> None:+ """Bind the Gateway-owned Manager used by private Agent tool RPC."""+ self._a2a_outbound_tool_manager = manager+ if not hasattr(self, "_active_a2a_outbound_tool_tasks"):+ self._active_a2a_outbound_tool_tasks = {}++ async def _handle_a2a_outbound_tool_push(+ self, *, chunk: Any, session_id: str | None+ ) -> bool:+ from jiuwenswarm.common.e2a.adapters import build_acp_tool_response_message+ from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2AOutboundError,+ A2AOutboundErrorCode,+ safe_error_summary,+ )+ from jiuwenswarm.gateway.a2a_manager.tool_rpc import (+ A2A_TOOL_CANCEL_CALL,+ A2A_TOOL_DISPATCH_TASK,+ A2A_TOOL_FIND_AGENTS,+ A2A_TOOL_GET_DISPATCH,+ A2A_TOOL_METHODS,+ )++ payload = chunk.payload if isinstance(chunk.payload, dict) else {}+ # ``acp.output_request`` is normalized from E2A as+ # {"event_type": "acp.output_request", "jsonrpc": {...}}. Keep+ # accepting the legacy flat shape, but route the canonical wire shape+ # through its nested JSON-RPC envelope.+ nested_jsonrpc = payload.get("jsonrpc")+ rpc_payload = (+ dict(nested_jsonrpc)+ if payload.get("event_type") == "acp.output_request"+ and isinstance(nested_jsonrpc, dict)+ else payload+ )+ method = str(rpc_payload.get("method") or "").strip()+ if method not in A2A_TOOL_METHODS:+ return False+ jsonrpc_id = str(rpc_payload.get("id") or "").strip()+ params = rpc_payload.get("params")+ params = dict(params) if isinstance(params, dict) else {}+ manager = self._a2a_outbound_tool_manager+ current_task = asyncio.current_task()+ trusted_session_id = str(session_id or "").strip()+ active_calls = getattr(self, "_active_a2a_outbound_tool_tasks", None)+ if active_calls is None:+ active_calls = self._active_a2a_outbound_tool_tasks = {}+ if method == A2A_TOOL_CANCEL_CALL:+ target_id = str(params.get("jsonrpc_id") or "").strip()+ active = active_calls.get(target_id)+ target = active[0] if active is not None else None+ canceled = bool(+ active is not None+ and active[1] == trusted_session_id+ and target is not current_task+ )+ if canceled:+ target.cancel()+ response = {+ "jsonrpc": "2.0",+ "id": jsonrpc_id,+ "result": {"canceled": canceled},+ }+ reply = build_acp_tool_response_message(+ jsonrpc_id,+ response,+ str(session_id or "") or None,+ channel_id=str(chunk.channel_id or "default"),+ )+ await self.publish_user_messages(reply)+ return True+ if jsonrpc_id and current_task is not None:+ active_calls[jsonrpc_id] = (current_task, trusted_session_id)+ try:+ if manager is None:+ raise A2AOutboundError(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)+ source_session_id = trusted_session_id+ if not source_session_id:+ raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_REJECTED)+ if method == A2A_TOOL_FIND_AGENTS:+ required = params.get("required_skills")+ if required is not None and not isinstance(required, list):+ raise A2AOutboundError(A2AOutboundErrorCode.TASK_INVALID)+ result = await manager.outbound_find_agents(+ query=str(params.get("query") or ""),+ required_skills=required,+ limit=int(params.get("limit") or 5),+ )+ elif method == A2A_TOOL_DISPATCH_TASK:+ result = await manager.outbound_dispatch_task(+ agent_id=str(params.get("agent_id") or ""),+ task=str(params.get("task") or ""),+ mode=str(params.get("mode") or ""),+ source_session_id=source_session_id,+ reason=str(params.get("reason") or "") or None,+ )+ elif method == A2A_TOOL_GET_DISPATCH:+ result = await manager.outbound_get_dispatch(+ dispatch_id=str(params.get("dispatch_id") or ""),+ source_session_id=source_session_id,+ )+ response = {"jsonrpc": "2.0", "id": jsonrpc_id, "result": result}+ except A2AOutboundError as exc:+ response = {+ "jsonrpc": "2.0",+ "id": jsonrpc_id,+ "error": {+ "code": -32060,+ "message": exc.summary,+ "data": {"code": exc.code.value},+ },+ }+ except (TypeError, ValueError):+ code = A2AOutboundErrorCode.TASK_INVALID+ response = {+ "jsonrpc": "2.0",+ "id": jsonrpc_id,+ "error": {+ "code": -32602,+ "message": safe_error_summary(code),+ "data": {"code": code.value},+ },+ }+ except Exception:+ logger.exception(+ "[MessageHandler] A2A outbound tool RPC failed: method=%s session_id=%s",+ method,+ session_id,+ )+ code = A2AOutboundErrorCode.MANAGER_UNAVAILABLE+ response = {+ "jsonrpc": "2.0",+ "id": jsonrpc_id,+ "error": {+ "code": -32061,+ "message": safe_error_summary(code),+ "data": {"code": code.value},+ },+ }+ finally:+ if (+ jsonrpc_id+ and active_calls.get(jsonrpc_id, (None, ""))[0] is current_task+ ):+ active_calls.pop(jsonrpc_id, None)+ reply = build_acp_tool_response_message(+ jsonrpc_id,+ response,+ str(session_id or "") or None,+ channel_id=str(chunk.channel_id or "default"),+ )+ await self.publish_user_messages(reply)+ return True+async def _push_file_to_web_and_get_token(self,file_path: str,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex d71d1d34d0..481aafaa77 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -398,6 +398,9 @@ from jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail importfrom jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (ProgressiveToolRail,)+from jiuwenswarm.agents.harness.common.rails.a2a_outbound_toolkit_rail import (+ A2AOutboundToolkitRail,+)from jiuwenswarm.symphony.config import load_symphony_configfrom jiuwenswarm.agents.harness.common.tools.wiki_tools import wiki_ingest, wiki_query, wiki_lintfrom jiuwenswarm.agents.harness.common.tools.harness_named_web_tools import (@@ -7076,6 +7079,29 @@ class JiuWenSwarmDeepAdapter:logger.warning("[JiuWenSwarmDeepAdapter] SkillRetrievalPromptRail create failed: %s", exc)return None+ def _build_a2a_outbound_toolkit_rail(self) -> A2AOutboundToolkitRail | None:+ if is_enterprise():+ return None+ return A2AOutboundToolkitRail(runtime_route=self._get_a2a_outbound_tool_route)++ def _get_a2a_outbound_tool_route(self) -> tuple[str, str]:+ """Return an adapter-owned route that survives DeepAgent task boundaries."""+ context_session = str(get_runtime_tool_session_id() or "").strip()+ if context_session:+ context_channel = str(get_runtime_tool_channel_id() or "").strip()+ return context_session, context_channel or "default"++ route = self._current_request_route+ session_id = str(route.get("session_id") or "").strip()+ channel_id = str(route.get("channel_id") or "").strip()+ if session_id:+ return session_id, channel_id or "default"++ runtime_context = self._runtime_cron_tool_context+ session_id = str(runtime_context.session_id or "").strip()+ channel_id = str(runtime_context.channel_id or "").strip()+ return session_id, channel_id or "default"+def _build_progressive_tool_rail(self, config: dict[str, Any]) -> ProgressiveToolRail | None:@@ -7370,6 +7396,13 @@ class JiuWenSwarmDeepAdapter:)rail_infos.insert(4 if self._filesystem_rail_enabled_for_profile() else 3,+ _RailBuildInfo(+ "_a2a_outbound_toolkit_rail",+ self._build_a2a_outbound_toolkit_rail,+ ),+ )+ rail_infos.insert(+ 5 if self._filesystem_rail_enabled_for_profile() else 4,_RailBuildInfo("_symphony_orchestration_rail",self._build_symphony_orchestration_rail,diff --git a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.pyindex 094df88119..6281792488 100644--- a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py+++ b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py@@ -15,6 +15,7 @@ import pytestfrom openjiuwen.core.single_agent.interrupt.state import INTERRUPTION_KEYfrom jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.server.runtime.agent_adapter import interface_deepfrom jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapterfrom jiuwenswarm.server.runtime.skill_turbo.permission_bridge import (SKILL_TURBO_RESUME_CTX_KEY,@@ -71,6 +72,26 @@ def _make_adapter(**state: object) -> JiuWenSwarmDeepAdapter:return adapter+def test_a2a_tool_route_survives_background_task_context(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(interface_deep, "get_runtime_tool_session_id", lambda: None)+ monkeypatch.setattr(interface_deep, "get_runtime_tool_channel_id", lambda: "default")+ adapter = _make_adapter(+ _current_request_route={+ "session_id": "web-session",+ "request_id": "request-1",+ "channel_id": "web",+ },+ _runtime_cron_tool_context=SimpleNamespace(+ session_id=None,+ channel_id="default",+ ),+ )++ assert adapter._get_a2a_outbound_tool_route() == ("web-session", "web")++def _make_message_adapter(monkeypatch: pytest.MonkeyPatch) -> JiuWenSwarmDeepAdapter:adapter = JiuWenSwarmDeepAdapter()adapter._instance = SimpleNamespace(get_context_usage=lambda **_kwargs: {})diff --git a/tests/unit_tests/gateway/test_a2a_manager.py b/tests/unit_tests/gateway/test_a2a_manager.pyindex 4135d8c460..bbae624d50 100644--- a/tests/unit_tests/gateway/test_a2a_manager.py+++ b/tests/unit_tests/gateway/test_a2a_manager.py@@ -1,4 +1,6 @@import asyncio+import time+from concurrent.futures import ThreadPoolExecutorimport pytest@@ -7,11 +9,15 @@ from jiuwenswarm.gateway.a2a_manager import (A2AIngressConfigRepository,A2AIngressError,A2AIngressState,+ A2AOutboundSettingsRepository,A2AManager,load_a2a_ingress_config,load_a2a_ingress_config_safely,)-from jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import A2ADependencyMissingError+from jiuwenswarm.gateway.a2a_manager import config as a2a_config_module+from jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import (+ A2ADependencyMissingError,+)class _ChannelManagerProbe:@@ -106,6 +112,60 @@ def test_invalid_a2a_config_has_a_disabled_boot_fallback():assert error.code == "A2A_CONFIG_INVALID"+def test_outbound_loopback_setting_round_trips_through_dotenv(tmp_path, monkeypatch):+ env_path = tmp_path / ".env"+ env_path.write_text(+ 'KEEP_ME="yes"\nA2A_OUTBOUND_ALLOW_LOOPBACK_HTTP="false"\n', "utf-8"+ )+ monkeypatch.delenv("A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP", raising=False)+ repository = A2AOutboundSettingsRepository(env_path)++ assert repository.load({}) == {"allow_loopback_http": False}+ repository.save(allow_loopback_http=True)++ assert repository.load() == {"allow_loopback_http": True}+ content = env_path.read_text("utf-8")+ assert 'KEEP_ME="yes"' in content+ assert content.count("A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP") == 1+ assert 'A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP="true"' in content+++def test_ingress_and_outbound_repositories_share_one_dotenv_writer(tmp_path):+ env_path = tmp_path / ".env"+ env_path.write_text('KEEP_ME="yes"\n', "utf-8")+ ingress = A2AIngressConfigRepository(env_path)+ outbound = A2AOutboundSettingsRepository(env_path)++ # Holding the shared lock proves both public repositories enter the same+ # read-modify-write critical section instead of racing independent writers.+ executor = ThreadPoolExecutor(max_workers=2)+ a2a_config_module._DOTENV_WRITE_LOCK.acquire()+ try:+ ingress_future = executor.submit(+ ingress.save,+ A2AIngressConfig(port=19234, app_name="Concurrent ingress"),+ )+ outbound_future = executor.submit(+ outbound.save,+ allow_loopback_http=True,+ )+ time.sleep(0.05)+ assert ingress_future.done() is False+ assert outbound_future.done() is False+ finally:+ a2a_config_module._DOTENV_WRITE_LOCK.release()+ try:+ ingress_future.result(timeout=2)+ outbound_future.result(timeout=2)+ finally:+ executor.shutdown(wait=True)++ content = env_path.read_text("utf-8")+ assert 'KEEP_ME="yes"' in content+ assert 'A2A_SERVER_PORT="19234"' in content+ assert 'A2A_OUTBOUND_ALLOW_LOOPBACK_HTTP="true"' in content++@pytest.mark.asyncioasync def test_manager_exposes_boot_config_error_without_starting_a_channel():config, error = load_a2a_ingress_config_safely({"A2A_SERVER_PATH": "missing-slash"})@@ -129,7 +189,12 @@ async def test_manager_registers_starts_and_stops_channel_once():channels.append(channel)return channel- manager = A2AManager(channel_manager, object(), A2AIngressConfig(enabled=True), channel_factory=factory)+ manager = A2AManager(+ channel_manager,+ object(),+ A2AIngressConfig(enabled=True),+ channel_factory=factory,+ )await manager.start_from_config()await manager.start_from_config()await asyncio.sleep(0)@@ -155,7 +220,9 @@ async def test_manager_retains_disabled_config_for_the_protocol_adapter():channels.append(channel)return channel- manager = A2AManager(channel_manager, object(), A2AIngressConfig(), channel_factory=factory)+ manager = A2AManager(+ channel_manager, object(), A2AIngressConfig(), channel_factory=factory+ )await manager.start_from_config()await asyncio.sleep(0)await manager.stop()@@ -170,9 +237,16 @@ async def test_manager_handles_start_failure_and_still_stops():channel_manager = _ChannelManagerProbe()def factory(config, router):- return _ChannelProbe(config, router, start_error=RuntimeError("a2a sdk missing"))+ return _ChannelProbe(+ config, router, start_error=RuntimeError("a2a sdk missing")+ )- manager = A2AManager(channel_manager, object(), A2AIngressConfig(enabled=True), channel_factory=factory)+ manager = A2AManager(+ channel_manager,+ object(),+ A2AIngressConfig(enabled=True),+ channel_factory=factory,+ )await manager.start_from_config()await asyncio.sleep(0)await manager.stop()@@ -192,17 +266,32 @@ async def test_manager_retains_bounded_request_history_across_channel_reload():return channelmanager = A2AManager(- channel_manager, object(), A2AIngressConfig(enabled=True), channel_factory=factory,+ channel_manager,+ object(),+ A2AIngressConfig(enabled=True),+ channel_factory=factory,)await manager.enable()- channels[0].request_observer({- "request_id": "req-1", "context_id": "ctx-1", "message_id": "msg-1",- "status": "processing", "started_at": 10.0,- })- channels[0].request_observer({- "request_id": "req-1", "context_id": "ctx-1", "message_id": "msg-1",- "status": "completed", "started_at": 10.0, "finished_at": 10.125, "error": None,- })+ channels[0].request_observer(+ {+ "request_id": "req-1",+ "context_id": "ctx-1",+ "message_id": "msg-1",+ "status": "processing",+ "started_at": 10.0,+ }+ )+ channels[0].request_observer(+ {+ "request_id": "req-1",+ "context_id": "ctx-1",+ "message_id": "msg-1",+ "status": "completed",+ "started_at": 10.0,+ "finished_at": 10.125,+ "error": None,+ }+ )await manager.reload()history = manager.history()@@ -223,21 +312,40 @@ async def test_manager_retains_bounded_request_history_across_channel_reload():def test_manager_request_history_terminal_status_cannot_be_overwritten():manager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=_ConfigRepositoryProbe(),+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_ConfigRepositoryProbe(),+ )+ manager._record_request_event(+ {+ "request_id": "req-completed",+ "status": "processing",+ "started_at": 10.0,+ }+ )+ manager._record_request_event(+ {+ "request_id": "req-completed",+ "status": "completed",+ "finished_at": 10.1,+ }+ )+ manager._record_request_event(+ {+ "request_id": "req-completed",+ "status": "canceled",+ "finished_at": 10.2,+ }+ )+ manager._record_request_event(+ {+ "request_id": "req-completed",+ "status": "failed",+ "finished_at": 10.3,+ "error": "late failure",+ })- manager._record_request_event({- "request_id": "req-completed", "status": "processing", "started_at": 10.0,- })- manager._record_request_event({- "request_id": "req-completed", "status": "completed", "finished_at": 10.1,- })- manager._record_request_event({- "request_id": "req-completed", "status": "canceled", "finished_at": 10.2,- })- manager._record_request_event({- "request_id": "req-completed", "status": "failed", "finished_at": 10.3,- "error": "late failure",- })item = manager.history()["items"][0]assert item["status"] == "completed"@@ -248,17 +356,32 @@ def test_manager_request_history_terminal_status_cannot_be_overwritten():def test_manager_request_history_keeps_cancellation_terminal():manager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=_ConfigRepositoryProbe(),+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_ConfigRepositoryProbe(),+ )+ manager._record_request_event(+ {+ "request_id": "req-canceled",+ "status": "processing",+ "started_at": 20.0,+ }+ )+ manager._record_request_event(+ {+ "request_id": "req-canceled",+ "status": "canceled",+ "finished_at": 20.2,+ }+ )+ manager._record_request_event(+ {+ "request_id": "req-canceled",+ "status": "completed",+ "finished_at": 20.3,+ })- manager._record_request_event({- "request_id": "req-canceled", "status": "processing", "started_at": 20.0,- })- manager._record_request_event({- "request_id": "req-canceled", "status": "canceled", "finished_at": 20.2,- })- manager._record_request_event({- "request_id": "req-canceled", "status": "completed", "finished_at": 20.3,- })item = manager.history()["items"][0]assert item["status"] == "canceled"@@ -269,9 +392,13 @@ def test_manager_request_history_keeps_cancellation_terminal():@pytest.mark.asyncioasync def test_stop_propagates_its_own_cancellation_after_channel_cleanup():channel_manager = _ChannelManagerProbe()- channel = _CancellationProbe(A2AIngressConfig(enabled=True).to_channel_config(), object())+ channel = _CancellationProbe(+ A2AIngressConfig(enabled=True).to_channel_config(), object()+ )manager = A2AManager(- channel_manager, object(), A2AIngressConfig(enabled=True),+ channel_manager,+ object(),+ A2AIngressConfig(enabled=True),channel_factory=lambda config, router: channel,)await manager.start_from_config()@@ -328,7 +455,9 @@ def test_repository_persists_only_a2a_environment_fields(tmp_path, monkeypatch):environ = {}monkeypatch.setattr(a2a_config.os, "environ", environ)- A2AIngressConfigRepository(env_path).save(A2AIngressConfig(enabled=True, port=19123))+ A2AIngressConfigRepository(env_path).save(+ A2AIngressConfig(enabled=True, port=19123)+ )text = env_path.read_text(encoding="utf-8")assert "MODEL_NAME=kept" in text@@ -336,7 +465,9 @@ def test_repository_persists_only_a2a_environment_fields(tmp_path, monkeypatch):assert environ["A2A_SERVER_ENABLED"] == "true"-def test_repository_escapes_values_and_preserves_comments_and_export_lines(tmp_path, monkeypatch):+def test_repository_escapes_values_and_preserves_comments_and_export_lines(+ tmp_path, monkeypatch+):from jiuwenswarm.gateway.a2a_manager import config as a2a_configenv_path = tmp_path / ".env"@@ -362,7 +493,10 @@ def test_repository_escapes_values_and_preserves_comments_and_export_lines(tmp_pasync def test_invalid_patch_does_not_persist_or_change_running_config():repository = _ConfigRepositoryProbe()manager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=repository,+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=repository,channel_factory=lambda config, router: _ChannelProbe(config, router),)@@ -378,7 +512,10 @@ async def test_invalid_patch_does_not_persist_or_change_running_config():async def test_update_apply_false_separates_desired_and_effective_addresses():channel_manager = _ChannelManagerProbe()manager = A2AManager(- channel_manager, object(), A2AIngressConfig(), repository=_ConfigRepositoryProbe(),+ channel_manager,+ object(),+ A2AIngressConfig(),+ repository=_ConfigRepositoryProbe(),channel_factory=lambda config, router: _ChannelProbe(config, router),)@@ -404,7 +541,11 @@ async def test_enable_applies_a_saved_but_unapplied_running_config():return channelmanager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=_ConfigRepositoryProbe(), channel_factory=factory,+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_ConfigRepositoryProbe(),+ channel_factory=factory,)await manager.enable()await manager.update({"port": 19123}, apply=False)@@ -418,7 +559,10 @@ async def test_enable_applies_a_saved_but_unapplied_running_config():@pytest.mark.asyncioasync def test_update_apply_false_warns_when_desired_bind_is_public():manager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=_ConfigRepositoryProbe(),+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_ConfigRepositoryProbe(),channel_factory=lambda config, router: _ChannelProbe(config, router),)@@ -438,7 +582,11 @@ async def test_update_apply_true_with_disabled_config_stops_running_service():return channelmanager = A2AManager(- channel_manager, object(), A2AIngressConfig(), repository=_ConfigRepositoryProbe(), channel_factory=factory,+ channel_manager,+ object(),+ A2AIngressConfig(),+ repository=_ConfigRepositoryProbe(),+ channel_factory=factory,)await manager.enable()snapshot = await manager.update({"enabled": False}, apply=True)@@ -507,7 +655,10 @@ async def test_on_start_done_keeps_callback_task_referenced():@pytest.mark.parametrize(("start_error", "code"),[- (A2ADependencyMissingError("optional dependency a2a-sdk is missing"), "A2A_DEPENDENCY_MISSING"),+ (+ A2ADependencyMissingError("optional dependency a2a-sdk is missing"),+ "A2A_DEPENDENCY_MISSING",+ ),(OSError("address already in use"), "A2A_BIND_FAILED"),(ValueError("bad channel config"), "A2A_CONFIG_INVALID"),(RuntimeError("unexpected startup failure"), "A2A_START_FAILED"),@@ -519,7 +670,9 @@ async def test_enable_surfaces_stable_startup_error_codes(start_error, code):object(),A2AIngressConfig(),repository=_ConfigRepositoryProbe(),- channel_factory=lambda config, router: _ChannelProbe(config, router, start_error=start_error),+ channel_factory=lambda config, router: _ChannelProbe(+ config, router, start_error=start_error+ ),)with pytest.raises(A2AIngressError) as exc_info:diff --git a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.pyindex 460b7cad14..2a762b983b 100644--- a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py+++ b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py@@ -79,6 +79,17 @@ class _OutboundRegistryProbe:return {"dispatch_id": dispatch_id}+class _OutboundSettingsProbe:+ def __init__(self) -> None:+ self.enabled = False++ def load(self):+ return {"allow_loopback_http": self.enabled}++ def save(self, *, allow_loopback_http):+ self.enabled = allow_loopback_http++@pytest.mark.asyncioasync def test_a2a_ingress_web_handlers_return_snapshots():channel = _WebChannelProbe()@@ -202,6 +213,7 @@ def test_a2a_ingress_http_routes_map_to_rpc_methods():@pytest.mark.asyncioasync def test_a2a_outbound_web_handlers_expose_management_facade():channel = _WebChannelProbe()+ settings = _OutboundSettingsProbe()manager = A2AManager(_ChannelManagerProbe(),object(),@@ -209,6 +221,7 @@ async def test_a2a_outbound_web_handlers_expose_management_facade():repository=_RepositoryProbe(),channel_factory=lambda config, router: _ChannelProbe(),outbound_registry=_OutboundRegistryProbe(),+ outbound_settings_repository=settings,)_register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))@@ -241,6 +254,13 @@ async def test_a2a_outbound_web_handlers_expose_management_facade():object(), "dispatch_get", {"dispatch_id": "dispatch-1"}, "session")+ await channel.methods["a2a.outbound.settings.get"](+ object(), "settings-get", {}, "session"+ )+ await channel.methods["a2a.outbound.settings.update"](+ object(), "settings-update", {"allow_loopback_http": True}, "session"+ )+assert channel.responses[0]["payload"]["discovery_id"] == "disc-1"assert channel.responses[1]["payload"]["agent_id"] == "agent-1"assert channel.responses[2]["payload"]["total"] == 0@@ -250,11 +270,16 @@ async def test_a2a_outbound_web_handlers_expose_management_facade():assert channel.responses[6]["payload"]["accepted"] is Falseassert channel.responses[7]["payload"]["deleted"] is Trueassert channel.responses[8]["payload"]["dispatch_id"] == "dispatch-1"+ assert channel.responses[9]["payload"] == {"allow_loopback_http": False}+ assert channel.responses[10]["payload"] == {"allow_loopback_http": True}+ assert settings.enabled is Trueassert all(item["ok"] for item in channel.responses)@pytest.mark.asyncio[email protected]("params", [{"agent_id": "agent-1"}, {"agent_id": "agent-1", "accept": "false"}])+ "params", [{"agent_id": "agent-1"}, {"agent_id": "agent-1", "accept": "false"}]+)async def test_a2a_outbound_confirm_revision_requires_explicit_boolean(params):channel = _WebChannelProbe()manager = A2AManager(@@ -312,6 +337,8 @@ def test_a2a_outbound_http_routes_map_to_rpc_methods():(route.http_method, route.path): route.rpc_method for route in MAPPED_ROUTES}+ assert routes[("GET", "/a2a/outbound/settings")] == "a2a.outbound.settings.get"+ assert routes[("PATCH", "/a2a/outbound/settings")] == "a2a.outbound.settings.update"assert routes[("POST", "/a2a/outbound/discover")] == "a2a.outbound.discover"assert routes[("POST", "/a2a/outbound/agents")] == "a2a.outbound.register"assert routes[("GET", "/a2a/outbound/agents")] == "a2a.outbound.list"diff --git a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.pynew file mode 100644index 0000000000..e6438de788--- /dev/null+++ b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py@@ -0,0 +1,1269 @@+"""Stage-3 coverage for the outbound Dispatcher and Agent toolkit Rail."""++from __future__ import annotations++import asyncio+import json+from dataclasses import dataclass, replace+from types import SimpleNamespace++import pytest+from a2a.types import (+ Artifact,+ Message,+ Part,+ Role,+ StreamResponse,+ Task,+ TaskArtifactUpdateEvent,+ TaskState,+ TaskStatus,+ TaskStatusUpdateEvent,+)++from jiuwenswarm.agents.harness.common.rails.a2a_outbound_toolkit_rail import (+ A2AOutboundToolkitRail,+)+from jiuwenswarm.agents.harness.common.tools.a2a_outbound_tools import (+ A2AOutboundToolkit,+)+from jiuwenswarm.agents.harness.common.tools.acp_output_tools import (+ get_acp_output_manager,+)+from jiuwenswarm.common.e2a.constants import (+ E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST,+ E2A_RESPONSE_STATUS_IN_PROGRESS,+)+from jiuwenswarm.common.e2a.gateway_normalize import message_to_e2a+from jiuwenswarm.common.e2a.models import E2AResponse+from jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_chunk+from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2ACompatibleInterface,+ A2AOutboundAgent,+ A2AOutboundAvailability,+ A2AOutboundDiscoveryService,+ A2AOutboundDispatchStatus,+ A2AOutboundDispatcher,+ A2AOutboundError,+ A2AOutboundErrorCode,+ A2AOutboundRepository,+)+from jiuwenswarm.gateway.a2a_manager.tool_rpc import (+ A2A_TOOL_CANCEL_CALL,+ A2A_TOOL_DISPATCH_TASK,+ A2A_TOOL_FIND_AGENTS,+ A2A_TOOL_GET_DISPATCH,+)+from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler+from jiuwenswarm.gateway.storage.backends.memory_persistent import (+ InMemoryPersistentBackend,+)+from jiuwenswarm.server.gateway_push.wire import build_server_push_wire+from jiuwenswarm.server.wire_parse import parse_inbound+++def _agent(agent_id: str = "agent-1") -> A2AOutboundAgent:+ stamp = "2026-08-26T00:00:00Z"+ 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",+ "description": "Researches and summarizes",+ "skills": [+ {+ "id": "research",+ "name": "Research",+ "description": "Find evidence",+ "tags": ["summarization"],+ }+ ],+ "defaultInputModes": ["text/plain"],+ "defaultOutputModes": ["text/plain"],+ },+ selected_interface=A2ACompatibleInterface(+ "JSONRPC", "1.0.0", "https://agent.example.com/a2a"+ ),+ enabled=True,+ availability=A2AOutboundAvailability.AVAILABLE,+ credential_ref=None,+ connect_timeout_seconds=1,+ sync_wait_seconds=0.05,+ created_at=stamp,+ updated_at=stamp,+ )+++class _FakeClient:+ def __init__(self, events=(), *, tasks=(), block_after_events: bool = False):+ self.events = list(events)+ self.tasks = list(tasks)+ self.block_after_events = block_after_events+ self.closed = 0+ self.sent_requests = []+ self.get_requests = []++ async def send_message(self, request, *, context=None):+ self.sent_requests.append((request, context))+ for event in self.events:+ yield event+ if self.block_after_events:+ await asyncio.Event().wait()++ async def get_task(self, request, *, context=None):+ self.get_requests.append((request, context))+ return self.tasks.pop(0)++ async def cancel_task(self, request, *, context=None):+ return self.tasks.pop(0)++ async def close(self) -> None:+ self.closed += 1+++def _message_event(text: str = "done") -> StreamResponse:+ return StreamResponse(+ message=Message(+ message_id="remote-message",+ context_id="ctx-1",+ role=Role.ROLE_AGENT,+ parts=[Part(text=text)],+ )+ )+++def _task(+ state: int,+ *,+ task_id: str = "remote-task",+ text: str | None = None,+) -> Task:+ status = TaskStatus(state=state)+ if text is not None:+ status.message.CopyFrom(+ Message(+ message_id="remote-message",+ role=Role.ROLE_AGENT,+ parts=[Part(text=text)],+ )+ )+ return Task(id=task_id, context_id="ctx-1", status=status)+++def _task_event(state: int) -> StreamResponse:+ return StreamResponse(task=_task(state))+++def _artifact_event(text: str) -> StreamResponse:+ return StreamResponse(+ artifact_update=TaskArtifactUpdateEvent(+ task_id="remote-task",+ context_id="ctx-1",+ artifact=Artifact(+ artifact_id="answer",+ name="response",+ parts=[Part(text=text)],+ ),+ last_chunk=True,+ )+ )+++def _status_event(state: int, *, text: str | None = None) -> StreamResponse:+ status = TaskStatus(state=state)+ if text is not None:+ status.message.CopyFrom(+ Message(+ message_id="status-message",+ role=Role.ROLE_AGENT,+ parts=[Part(text=text)],+ )+ )+ return StreamResponse(+ status_update=TaskStatusUpdateEvent(+ task_id="remote-task",+ context_id="ctx-1",+ status=status,+ )+ )+++async def _dispatcher(client: _FakeClient):+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ await repository.create_agent(_agent())++ async def builder(_agent, _credential):+ return client++ return (+ A2AOutboundDispatcher(+ repository,+ client_builder=builder,+ query_interval_seconds=0,+ ),+ repository,+ )+++async def test_find_agents_returns_only_callable_minimal_catalog() -> None:+ client = _FakeClient()+ dispatcher, repository = await _dispatcher(client)+ await repository.create_agent(replace(_agent("disabled"), enabled=False))++ result = await dispatcher.find_agents(+ query="research summary", required_skills=["research"], limit=5+ )++ assert [item["agent_id"] for item in result["items"]] == ["agent-1"]+ assert "url" not in result["items"][0]+ assert "credential_ref" not in result["items"][0]+++async def test_find_agents_required_skill_match_is_exact_not_substring() -> None:+ """Regression test: 'ai' must not match a skill named 'brain' via substring."""+ client = _FakeClient()+ dispatcher, repository = await _dispatcher(client)+ await repository.create_agent(+ replace(+ _agent("agent-ai"),+ agent_card={+ "name": "AI Agent",+ "description": "Does AI things",+ "skills": [{"id": "ai", "name": "AI", "tags": []}],+ "defaultInputModes": ["text/plain"],+ "defaultOutputModes": ["text/plain"],+ },+ )+ )+ await repository.create_agent(+ replace(+ _agent("agent-brain"),+ agent_card={+ "name": "Brainy Agent",+ "description": "Not an AI agent",+ "skills": [{"id": "brain", "name": "Brain", "tags": []}],+ "defaultInputModes": ["text/plain"],+ "defaultOutputModes": ["text/plain"],+ },+ )+ )++ result = await dispatcher.find_agents(required_skills=["ai"], limit=5)++ assert [item["agent_id"] for item in result["items"]] == ["agent-ai"]+++async def test_sync_dispatch_returns_normalized_final_message() -> None:+ client = _FakeClient([_message_event("final answer")])+ dispatcher, repository = await _dispatcher(client)++ result = await dispatcher.dispatch(+ agent_id="agent-1", task="do research", mode="sync", source_session_id="s1"+ )++ assert result["ok"] is True+ assert result["status"] == "completed"+ assert result["result"]["text"] == "final answer"+ persisted = await repository.get_dispatch(result["dispatch_id"])+ assert (+ persisted is not None+ and persisted.status is A2AOutboundDispatchStatus.COMPLETED+ )+ assert persisted.input_digest.startswith("sha256:")+ assert client.sent_requests[0][0].message.parts[0].text == "do research"+ assert client.sent_requests[0][1] is None+ assert client.closed == 1+++async def test_real_http_stream_can_outlive_connect_timeout_within_sync_budget() -> None:+ served = asyncio.Event()++ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ try:+ header_bytes = await reader.readuntil(b"\r\n\r\n")+ header_text = header_bytes.decode("iso-8859-1")+ content_length = 0+ for line in header_text.split("\r\n"):+ if line.lower().startswith("content-length:"):+ content_length = int(line.split(":", 1)[1].strip())+ break+ request = json.loads((await reader.readexactly(content_length)).decode())+ response = {+ "jsonrpc": "2.0",+ "id": request["id"],+ "result": {+ "message": {+ "messageId": "remote-message",+ "role": "ROLE_AGENT",+ "parts": [{"text": "slow final"}],+ }+ },+ }+ body = f"data: {json.dumps(response)}\n\n".encode()+ writer.write(+ b"HTTP/1.1 200 OK\r\n"+ b"Content-Type: text/event-stream\r\n"+ + f"Content-Length: {len(body)}\r\n".encode()+ + b"Connection: close\r\n\r\n"+ )+ await writer.drain()+ await asyncio.sleep(0.12)+ writer.write(body)+ await writer.drain()+ finally:+ writer.close()+ await writer.wait_closed()+ served.set()++ server = await asyncio.start_server(handle, "127.0.0.1", 0)+ port = server.sockets[0].getsockname()[1]+ endpoint = f"http://127.0.0.1:{port}/a2a"+ agent = replace(+ _agent(),+ source_url=f"http://127.0.0.1:{port}",+ selected_interface=A2ACompatibleInterface("JSONRPC", "1.0.0", endpoint),+ connect_timeout_seconds=0.05,+ sync_wait_seconds=0.4,+ agent_card={+ "name": "Slow Agent",+ "description": "Responds after the connect timeout",+ "version": "1.0.0",+ "supportedInterfaces": [+ {+ "url": endpoint,+ "protocolBinding": "JSONRPC",+ "protocolVersion": "1.0.0",+ }+ ],+ "capabilities": {"streaming": True},+ "defaultInputModes": ["text/plain"],+ "defaultOutputModes": ["text/plain"],+ "skills": [],+ },+ )+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ await repository.create_agent(agent)+ dispatcher = A2AOutboundDispatcher(+ repository,+ discovery_service=A2AOutboundDiscoveryService(allow_loopback_http=True),+ )+ try:+ result = await dispatcher.dispatch(+ agent_id=agent.agent_id,+ task="slow request",+ mode="sync",+ source_session_id="s1",+ )+ await asyncio.wait_for(served.wait(), timeout=1)+ finally:+ server.close()+ await server.wait_closed()++ assert result["status"] == "completed"+ assert result["result"]["text"] == "slow final"+++async def test_completed_stream_promotes_final_artifact_over_progress_text() -> None:+ client = _FakeClient(+ [+ _status_event(TaskState.TASK_STATE_WORKING, text="正在查询天气演示数据……"),+ _artifact_event("北京当前晴,25°C。"),+ _status_event(TaskState.TASK_STATE_COMPLETED),+ ]+ )+ dispatcher, _ = await _dispatcher(client)++ result = await dispatcher.dispatch(+ agent_id="agent-1", task="查询北京天气", mode="sync", source_session_id="s1"+ )++ assert result["status"] == "completed"+ assert result["result"]["text"] == "北京当前晴,25°C。"+ assert result["result"]["artifacts"][0]["text"] == "北京当前晴,25°C。"+++async def test_sync_dispatch_polls_an_accepted_task_to_terminal() -> None:+ client = _FakeClient(+ [_task_event(TaskState.TASK_STATE_SUBMITTED)],+ tasks=[_task(TaskState.TASK_STATE_COMPLETED, text="polled answer")],+ )+ dispatcher, _ = await _dispatcher(client)++ result = await dispatcher.dispatch(+ agent_id="agent-1", task="do research", mode="sync", source_session_id="s1"+ )++ assert result["status"] == "completed"+ assert result["result"]["text"] == "polled answer"+ assert len(client.get_requests) == 1+++async def test_async_dispatch_requires_remote_task_id_then_query_converges() -> None:+ client = _FakeClient(+ [_task_event(TaskState.TASK_STATE_SUBMITTED)],+ tasks=[_task(TaskState.TASK_STATE_COMPLETED, text="async answer")],+ )+ dispatcher, _ = await _dispatcher(client)++ accepted = await dispatcher.dispatch(+ agent_id="agent-1", task="long work", mode="async", source_session_id="s1"+ )+ completed = await dispatcher.query_dispatch(+ accepted["dispatch_id"], source_session_id="s1"+ )++ assert accepted["status"] == "accepted"+ assert accepted["remote_task_id"] == "remote-task"+ assert "a2a_get_dispatch" in accepted["next_action"]+ assert completed["status"] == "completed"+ assert completed["result"]["text"] == "async answer"+++async def test_async_without_remote_id_is_dispatch_failed() -> None:+ client = _FakeClient([])+ dispatcher, _ = await _dispatcher(client)++ result = await dispatcher.dispatch(+ agent_id="agent-1", task="long work", mode="async", source_session_id="s1"+ )++ assert result["ok"] is False+ assert result["status"] == "dispatch_failed"+++async def test_sync_timeout_keeps_known_ids_queryable() -> None:+ client = _FakeClient(+ [_task_event(TaskState.TASK_STATE_SUBMITTED)], block_after_events=True+ )+ dispatcher, repository = await _dispatcher(client)++ result = await dispatcher.dispatch(+ agent_id="agent-1", task="slow", mode="sync", source_session_id="s1"+ )++ assert result["status"] == "timed_out"+ assert result["remote_task_id"] == "remote-task"+ assert "a2a_get_dispatch" in result["next_action"]+ persisted = await repository.get_dispatch(result["dispatch_id"])+ assert persisted is not None and not persisted.is_terminal+++async def test_query_completion_clears_prior_timeout_error() -> None:+ client = _FakeClient(+ [_task_event(TaskState.TASK_STATE_SUBMITTED)], block_after_events=True+ )+ dispatcher, _ = await _dispatcher(client)+ timed_out = await dispatcher.dispatch(+ agent_id="agent-1", task="slow", mode="sync", source_session_id="s1"+ )+ client.block_after_events = False+ client.tasks.append(_task(TaskState.TASK_STATE_COMPLETED, text="late answer"))++ completed = await dispatcher.query_dispatch(+ timed_out["dispatch_id"], source_session_id="s1"+ )++ assert completed["status"] == "completed"+ assert completed["error_code"] is None+ assert completed["error_summary"] is None+++async def test_required_remote_auth_without_credential_is_not_left_submitting() -> None:+ client = _FakeClient()+ dispatcher, repository = await _dispatcher(client)+ await repository.update_agent(+ "agent-1",+ lambda current: replace(+ current,+ agent_card={**current.agent_card, "securityRequirements": [{"bearer": []}]},+ ),+ )++ result = await dispatcher.dispatch(+ agent_id="agent-1", task="work", mode="sync", source_session_id="s1"+ )++ assert result["status"] == "auth_required"+ assert result["error_code"] == A2AOutboundErrorCode.AUTH_REQUIRED.value+ assert client.sent_requests == []+++async def test_cancellation_moves_record_out_of_processing_and_reraises() -> None:+ client = _FakeClient(+ [_task_event(TaskState.TASK_STATE_SUBMITTED)], block_after_events=True+ )+ dispatcher, repository = await _dispatcher(client)+ started = asyncio.create_task(+ dispatcher.dispatch(+ agent_id="agent-1", task="slow", mode="sync", source_session_id="s1"+ )+ )+ while not client.sent_requests:+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ started.cancel()++ with pytest.raises(asyncio.CancelledError):+ await started+ records = await repository.list_dispatches()+ assert records[0].status is A2AOutboundDispatchStatus.UNKNOWN+ assert records[0].remote_task_id == "remote-task"+++async def test_cancellation_uses_remote_cancel_result_when_available() -> None:+ client = _FakeClient(+ [_task_event(TaskState.TASK_STATE_SUBMITTED)],+ tasks=[_task(TaskState.TASK_STATE_CANCELED)],+ block_after_events=True,+ )+ dispatcher, repository = await _dispatcher(client)+ started = asyncio.create_task(+ dispatcher.dispatch(+ agent_id="agent-1", task="slow", mode="sync", source_session_id="s1"+ )+ )+ while not client.sent_requests:+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ started.cancel()++ with pytest.raises(asyncio.CancelledError):+ await started+ records = await repository.list_dispatches()+ assert records[0].status is A2AOutboundDispatchStatus.CANCELED+++async def test_dispatch_query_is_scoped_to_originating_session() -> None:+ client = _FakeClient([_task_event(TaskState.TASK_STATE_SUBMITTED)])+ dispatcher, _ = await _dispatcher(client)+ accepted = await dispatcher.dispatch(+ agent_id="agent-1", task="work", mode="async", source_session_id="s1"+ )++ with pytest.raises(A2AOutboundError) as error:+ await dispatcher.query_dispatch(+ accepted["dispatch_id"], source_session_id="other"+ )+ assert error.value.code is A2AOutboundErrorCode.DISPATCH_NOT_FOUND+++class _Backend:+ ready = True++ async def call(self, method, params, *, session_id, channel_id):+ return {"method": method, "session_id": session_id, "channel_id": channel_id}+++class _AbilityManager:+ def __init__(self):+ self.tools = {}++ def add_ability(self, card, tool):+ self.tools[card.name] = tool++ def remove_ability(self, name):+ self.tools.pop(name, None)+++class _PromptBuilder:+ language = "cn"++ def __init__(self):+ self.sections = {}++ def add_section(self, section):+ self.sections[section.name] = section++ def remove_section(self, name):+ self.sections.pop(name, None)+++@dataclass+class _Agent:+ ability_manager: _AbilityManager+ system_prompt_builder: _PromptBuilder+++def test_rail_registers_three_tools_and_cleans_up() -> None:+ agent = _Agent(_AbilityManager(), _PromptBuilder())+ rail = A2AOutboundToolkitRail(backend_provider=lambda: _Backend())++ rail.init(agent)+ assert set(agent.ability_manager.tools) == {+ "a2a_find_agents",+ "a2a_dispatch_task",+ "a2a_get_dispatch",+ }+ assert "a2a_outbound_usage" in agent.system_prompt_builder.sections++ rail.uninit(agent)+ assert agent.ability_manager.tools == {}+ assert agent.system_prompt_builder.sections == {}+++def test_rail_keeps_tools_visible_when_gateway_proxy_is_not_ready() -> None:+ backend = _Backend()+ backend.ready = False+ agent = _Agent(_AbilityManager(), _PromptBuilder())+ rail = A2AOutboundToolkitRail(backend_provider=lambda: backend)++ rail.init(agent)++ assert set(agent.ability_manager.tools) == {+ "a2a_find_agents",+ "a2a_dispatch_task",+ "a2a_get_dispatch",+ }+++async def test_rail_registers_on_first_model_call_after_gateway_becomes_ready() -> None:+ backend = _Backend()+ current_backend = None+ agent = _Agent(_AbilityManager(), _PromptBuilder())+ rail = A2AOutboundToolkitRail(backend_provider=lambda: current_backend)++ rail.init(agent)+ current_backend = backend+ await rail.before_model_call(SimpleNamespace(agent=agent))++ assert set(agent.ability_manager.tools) == {+ "a2a_find_agents",+ "a2a_dispatch_task",+ "a2a_get_dispatch",+ }+ prompt = agent.system_prompt_builder.sections["a2a_outbound_usage"].content["cn"]+ assert '"\n' not in prompt+ assert "a2a_find_agents" in prompt+++async def test_toolkit_binds_session_and_exposes_no_url_or_credentials() -> None:+ toolkit = A2AOutboundToolkit(_Backend(), runtime_route=lambda: ("session-1", "web"))+ result = await toolkit.dispatch_task("agent-1", "task", "sync")+ dispatch_tool = {tool.card.name: tool for tool in toolkit.get_tools()}[+ "a2a_dispatch_task"+ ]++ assert result["session_id"] == "session-1"+ properties = dispatch_tool.card.input_params["properties"]+ assert not ({"url", "headers", "credential", "timeout"} & set(properties))+++async def test_rail_uses_adapter_owned_route_provider() -> None:+ backend = _Backend()+ agent = _Agent(_AbilityManager(), _PromptBuilder())+ rail = A2AOutboundToolkitRail(+ backend_provider=lambda: backend,+ runtime_route=lambda: ("persistent-session", "web"),+ )+ rail.init(agent)++ result = await agent.ability_manager.tools["a2a_find_agents"].invoke(+ {"query": "weather"}+ )++ assert result["session_id"] == "persistent-session"+ assert result["channel_id"] == "web"+++async def test_toolkit_missing_route_is_not_reported_as_remote_rejection() -> None:+ toolkit = A2AOutboundToolkit(_Backend(), runtime_route=lambda: ("", "web"))++ result = await toolkit.find_agents(query="weather")++ assert result["ok"] is False+ assert result["error_code"] == A2AOutboundErrorCode.MANAGER_UNAVAILABLE.value+++async def test_gateway_bridge_binds_wire_session_instead_of_caller_params() -> None:+ calls = []++ class _Manager:+ async def outbound_dispatch_task(self, **kwargs):+ calls.append(kwargs)+ return {"ok": True, "dispatch_id": "disp-1"}++ handler = object.__new__(MessageHandler)+ handler._a2a_outbound_tool_manager = _Manager()+ replies = []++ async def publish(message):+ replies.append(message)++ handler.publish_user_messages = publish+ chunk = SimpleNamespace(+ payload={+ "id": "rpc-1",+ "method": A2A_TOOL_DISPATCH_TASK,+ "params": {+ "agent_id": "agent-1",+ "task": "secret task body",+ "mode": "sync",+ "sessionId": "spoofed",+ },+ },+ channel_id="web",+ )++ handled = await handler._handle_a2a_outbound_tool_push(+ chunk=chunk, session_id="trusted-session"+ )++ assert handled is True+ assert calls[0]["source_session_id"] == "trusted-session"+ assert replies[0].params["response"]["result"]["dispatch_id"] == "disp-1"+++async def test_gateway_bridge_handles_canonical_acp_output_request_wire() -> None:+ calls = []++ class _Manager:+ async def outbound_find_agents(self, **kwargs):+ calls.append(kwargs)+ return {"items": [{"agent_id": "agent-1"}], "total": 1}++ handler = object.__new__(MessageHandler)+ handler._a2a_outbound_tool_manager = _Manager()+ replies = []++ async def publish(message):+ replies.append(message)++ handler.publish_user_messages = publish+ response = E2AResponse(+ request_id="acp-out-1",+ response_id="acp-response-1",+ response_kind=E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST,+ status=E2A_RESPONSE_STATUS_IN_PROGRESS,+ is_final=False,+ session_id="trusted-session",+ channel="web",+ body={+ "jsonrpc": "2.0",+ "id": "rpc-1",+ "method": "a2a.outbound.tool.find_agents",+ "params": {"query": "weather", "limit": 5},+ },+ )+ push = response.to_dict()+ push["channel_id"] = "web"+ push["payload"] = dict(response.body)+ wire = build_server_push_wire(push)+ chunk = parse_agent_server_wire_chunk(wire)++ handled = await handler._handle_a2a_outbound_tool_push(+ chunk=chunk,+ session_id=wire["session_id"],+ )++ assert handled is True+ assert calls == [{"query": "weather", "required_skills": None, "limit": 5}]+ assert replies[0].params["response"]["result"]["total"] == 1+++async def test_all_a2a_tools_reverse_rpc_round_trip_complete_original_futures(+ monkeypatch,+) -> None:+ output_manager = get_acp_output_manager()+ output_manager.reset_state()++ class _Manager:+ dispatch_modes = []++ async def outbound_find_agents(self, **kwargs):+ assert kwargs == {+ "query": "weather",+ "required_skills": ["weather"],+ "limit": 3,+ }+ return {"items": [{"agent_id": "agent-1"}], "total": 1}++ async def outbound_dispatch_task(self, **kwargs):+ assert kwargs["agent_id"] == "agent-1"+ assert kwargs["source_session_id"] == "trusted-session"+ self.dispatch_modes.append(kwargs["mode"])+ if kwargs["mode"] == "async":+ return {"ok": True, "dispatch_id": "disp-2", "status": "accepted"}+ assert kwargs["task"] == "query weather"+ assert kwargs["reason"] == "diagnostic"+ return {"ok": True, "dispatch_id": "disp-1", "status": "completed"}++ async def outbound_get_dispatch(self, **kwargs):+ assert kwargs == {+ "dispatch_id": "disp-1",+ "source_session_id": "trusted-session",+ }+ return {"ok": True, "dispatch_id": "disp-1", "status": "completed"}++ handler = object.__new__(MessageHandler)+ handler._a2a_outbound_tool_manager = _Manager()++ async def publish(reply):+ envelope = message_to_e2a(reply)+ parsed = parse_inbound(json.dumps(envelope.to_dict(), ensure_ascii=False))+ assert parsed.ok is True+ request = parsed.request+ assert request is not None+ assert request.req_method.value == "acp.tool_response"+ assert output_manager.complete_jsonrpc_response(+ request.params["jsonrpc_id"], request.params["response"]+ )++ handler.publish_user_messages = publish++ async def send_push(push):+ wire = build_server_push_wire(push)+ chunk = parse_agent_server_wire_chunk(wire)+ handled = await handler._handle_a2a_outbound_tool_push(+ chunk=chunk,+ session_id=wire.get("session_id"),+ )+ assert handled is True+ return True++ monkeypatch.setattr(output_manager, "_send_push_callback", send_push)+ try:+ found = await output_manager.send_jsonrpc_request(+ A2A_TOOL_FIND_AGENTS,+ {"query": "weather", "required_skills": ["weather"], "limit": 3},+ session_id="trusted-session",+ channel_id="web",+ timeout=0.5,+ log_params=False,+ )+ dispatched = await output_manager.send_jsonrpc_request(+ A2A_TOOL_DISPATCH_TASK,+ {+ "agent_id": "agent-1",+ "task": "query weather",+ "mode": "sync",+ "reason": "diagnostic",+ },+ session_id="trusted-session",+ channel_id="web",+ timeout=0.5,+ log_params=False,+ )+ dispatched_async = await output_manager.send_jsonrpc_request(+ A2A_TOOL_DISPATCH_TASK,+ {+ "agent_id": "agent-1",+ "task": "query weather later",+ "mode": "async",+ },+ session_id="trusted-session",+ channel_id="web",+ timeout=0.5,+ log_params=False,+ )+ queried = await output_manager.send_jsonrpc_request(+ A2A_TOOL_GET_DISPATCH,+ {"dispatch_id": "disp-1"},+ session_id="trusted-session",+ channel_id="web",+ timeout=0.5,+ log_params=False,+ )+ finally:+ output_manager.reset_state()++ assert found["result"]["total"] == 1+ assert dispatched["result"]["dispatch_id"] == "disp-1"+ assert dispatched_async["result"]["status"] == "accepted"+ assert handler._a2a_outbound_tool_manager.dispatch_modes == ["sync", "async"]+ assert queried["result"]["status"] == "completed"+++async def test_canonical_reverse_rpc_cancel_reaches_and_stops_gateway_call(+ monkeypatch,+) -> None:+ output_manager = get_acp_output_manager()+ output_manager.reset_state()+ started = asyncio.Event()+ stopped = asyncio.Event()++ class _Manager:+ async def outbound_dispatch_task(self, **_kwargs):+ started.set()+ try:+ await asyncio.Event().wait()+ finally:+ stopped.set()++ handler = object.__new__(MessageHandler)+ handler._a2a_outbound_tool_manager = _Manager()+ handler._active_a2a_outbound_tool_tasks = {}+ gateway_tasks: list[asyncio.Task] = []+ responses = []++ async def publish(reply):+ responses.append(reply.params["response"])+ envelope = message_to_e2a(reply)+ parsed = parse_inbound(json.dumps(envelope.to_dict(), ensure_ascii=False))+ assert parsed.ok is True and parsed.request is not None+ assert output_manager.complete_jsonrpc_response(+ parsed.request.params["jsonrpc_id"],+ parsed.request.params["response"],+ )++ handler.publish_user_messages = publish++ async def send_push(push):+ wire = build_server_push_wire(push)+ chunk = parse_agent_server_wire_chunk(wire)+ task = asyncio.create_task(+ handler._handle_a2a_outbound_tool_push(+ chunk=chunk,+ session_id=wire.get("session_id"),+ )+ )+ gateway_tasks.append(task)+ return True++ monkeypatch.setattr(output_manager, "_send_push_callback", send_push)+ request = asyncio.create_task(+ output_manager.send_jsonrpc_request(+ A2A_TOOL_DISPATCH_TASK,+ {+ "agent_id": "agent-1",+ "task": "slow task",+ "mode": "sync",+ },+ session_id="trusted-session",+ channel_id="web",+ timeout=30,+ log_params=False,+ cancel_method=A2A_TOOL_CANCEL_CALL,+ )+ )+ try:+ await asyncio.wait_for(started.wait(), timeout=0.5)+ request.cancel()+ with pytest.raises(asyncio.CancelledError):+ await request+ await asyncio.wait_for(stopped.wait(), timeout=0.5)+ await asyncio.gather(*gateway_tasks, return_exceptions=True)+ finally:+ output_manager.reset_state()++ assert any(item.get("result") == {"canceled": True} for item in responses)+ assert handler._active_a2a_outbound_tool_tasks == {}+++async def test_reverse_rpc_emits_cancel_notification_when_tool_is_canceled(+ monkeypatch,+) -> None:+ manager = get_acp_output_manager()+ manager.reset_state()+ pushes = []++ async def send_push(wire):+ pushes.append(wire)+ if wire["body"]["method"] == A2A_TOOL_CANCEL_CALL:+ rpc_id = wire["body"]["id"]+ manager.complete_jsonrpc_response(+ rpc_id, {"jsonrpc": "2.0", "id": rpc_id, "result": {"canceled": True}}+ )++ monkeypatch.setattr(manager, "_send_push_callback", send_push)+ pending = asyncio.create_task(+ manager.send_jsonrpc_request(+ A2A_TOOL_DISPATCH_TASK,+ {"task": "secret"},+ session_id="s1",+ log_params=False,+ cancel_method=A2A_TOOL_CANCEL_CALL,+ )+ )+ while not pushes:+ await asyncio.sleep(0)+ pending.cancel()++ with pytest.raises(asyncio.CancelledError):+ await pending+ assert [item["body"]["method"] for item in pushes] == [+ A2A_TOOL_DISPATCH_TASK,+ A2A_TOOL_CANCEL_CALL,+ ]+ assert pushes[1]["body"]["params"]["jsonrpc_id"] == pushes[0]["body"]["id"]+ manager.reset_state()+++async def test_reverse_rpc_cancel_racing_callback_completion_still_cancels(+ monkeypatch,+) -> None:+ """Regression test: cancellation must not be swallowed by wait_for's+ Python 3.11 race with the push callback's completion. Cancel is called+ from inside the mocked callback to make the race deterministic.+ """+ manager = get_acp_output_manager()+ manager.reset_state()+ pushes = []+ holder: dict[str, asyncio.Task] = {}++ async def send_push(wire):+ pushes.append(wire)+ if wire["body"]["method"] == A2A_TOOL_DISPATCH_TASK:+ holder["task"].cancel()+ elif wire["body"]["method"] == A2A_TOOL_CANCEL_CALL:+ rpc_id = wire["body"]["id"]+ manager.complete_jsonrpc_response(+ rpc_id, {"jsonrpc": "2.0", "id": rpc_id, "result": {"canceled": True}}+ )++ monkeypatch.setattr(manager, "_send_push_callback", send_push)+ try:+ pending = asyncio.create_task(+ manager.send_jsonrpc_request(+ A2A_TOOL_DISPATCH_TASK,+ {"task": "secret"},+ session_id="s1",+ log_params=False,+ cancel_method=A2A_TOOL_CANCEL_CALL,+ )+ )+ holder["task"] = pending++ with pytest.raises(asyncio.CancelledError):+ await pending+ assert [item["body"]["method"] for item in pushes] == [+ A2A_TOOL_DISPATCH_TASK,+ A2A_TOOL_CANCEL_CALL,+ ]+ finally:+ manager.reset_state()+++async def test_reverse_rpc_delivery_failure_fails_immediately(monkeypatch) -> None:+ manager = get_acp_output_manager()+ manager.reset_state()++ async def reject_delivery(_wire):+ return False++ monkeypatch.setattr(manager, "_send_push_callback", reject_delivery)+ try:+ with pytest.raises(RuntimeError, match="not delivered"):+ await manager.send_jsonrpc_request(+ A2A_TOOL_FIND_AGENTS,+ {"query": "weather"},+ session_id="s1",+ timeout=30,+ log_params=False,+ )+ finally:+ manager.reset_state()+++async def test_reverse_rpc_zero_delivered_subscribers_fails_immediately(+ monkeypatch,+) -> None:+ """Regression test: send_push() returning int 0 must fail fast too,+ not just ``False``."""+ manager = get_acp_output_manager()+ manager.reset_state()++ async def deliver_to_zero_subscribers(_wire):+ return 0++ monkeypatch.setattr(manager, "_send_push_callback", deliver_to_zero_subscribers)+ try:+ with pytest.raises(RuntimeError, match="not delivered"):+ await manager.send_jsonrpc_request(+ A2A_TOOL_FIND_AGENTS,+ {"query": "weather"},+ session_id="s1",+ timeout=30,+ log_params=False,+ )+ finally:+ manager.reset_state()+++async def test_reverse_rpc_ids_remain_unique_across_manager_state_reset(+ monkeypatch,+) -> None:+ manager = get_acp_output_manager()+ manager.reset_state()+ ids = []++ async def complete_delivery(wire):+ rpc_id = wire["body"]["id"]+ ids.append(rpc_id)+ manager.complete_jsonrpc_response(+ rpc_id,+ {"jsonrpc": "2.0", "id": rpc_id, "result": {"items": []}},+ )+ return True++ monkeypatch.setattr(manager, "_send_push_callback", complete_delivery)+ try:+ await manager.send_jsonrpc_request(+ A2A_TOOL_FIND_AGENTS, {}, session_id="s1", timeout=0.5+ )+ manager.reset_state()+ await manager.send_jsonrpc_request(+ A2A_TOOL_FIND_AGENTS, {}, session_id="s1", timeout=0.5+ )+ finally:+ manager.reset_state()++ assert len(set(ids)) == 2+ assert all(rpc_id.startswith("acp-") for rpc_id in ids)+++async def test_reverse_rpc_cancel_during_delivery_clears_pending_and_notifies(+ monkeypatch,+) -> None:+ manager = get_acp_output_manager()+ manager.reset_state()+ delivery_started = asyncio.Event()+ methods = []++ async def send_push(wire):+ method = wire["body"]["method"]+ methods.append(method)+ if method == A2A_TOOL_DISPATCH_TASK:+ delivery_started.set()+ await asyncio.Event().wait()+ else:+ rpc_id = wire["body"]["id"]+ manager.complete_jsonrpc_response(+ rpc_id,+ {"jsonrpc": "2.0", "id": rpc_id, "result": {"canceled": True}},+ )+ return True++ monkeypatch.setattr(manager, "_send_push_callback", send_push)+ request = asyncio.create_task(+ manager.send_jsonrpc_request(+ A2A_TOOL_DISPATCH_TASK,+ {"agent_id": "agent-1", "task": "slow", "mode": "sync"},+ session_id="s1",+ timeout=30,+ log_params=False,+ cancel_method=A2A_TOOL_CANCEL_CALL,+ )+ )+ try:+ await asyncio.wait_for(delivery_started.wait(), timeout=0.5)+ request.cancel()+ with pytest.raises(asyncio.CancelledError):+ await request+ assert manager.pending_count == 0+ finally:+ manager.reset_state()++ assert methods == [A2A_TOOL_DISPATCH_TASK, A2A_TOOL_CANCEL_CALL]+++async def test_reverse_rpc_timeout_covers_delivery_stage(monkeypatch) -> None:+ manager = get_acp_output_manager()+ manager.reset_state()++ async def blocked_delivery(_wire):+ await asyncio.Event().wait()++ monkeypatch.setattr(manager, "_send_push_callback", blocked_delivery)+ try:+ with pytest.raises(RuntimeError, match="Failed to send ACP output request"):+ await manager.send_jsonrpc_request(+ A2A_TOOL_FIND_AGENTS,+ {"query": "weather"},+ session_id="s1",+ timeout=0.01,+ log_params=False,+ )+ assert manager.pending_count == 0+ finally:+ manager.reset_state()+++async def test_gateway_cancel_call_cancels_only_same_session_active_rpc() -> None:+ started = asyncio.Event()++ class _Manager:+ async def outbound_dispatch_task(self, **kwargs):+ started.set()+ await asyncio.Event().wait()++ handler = object.__new__(MessageHandler)+ handler._a2a_outbound_tool_manager = _Manager()+ handler._active_a2a_outbound_tool_tasks = {}+ replies = []++ async def publish(message):+ replies.append(message)++ handler.publish_user_messages = publish+ dispatch_chunk = SimpleNamespace(+ payload={+ "id": "rpc-dispatch",+ "method": A2A_TOOL_DISPATCH_TASK,+ "params": {"agent_id": "agent-1", "task": "work", "mode": "sync"},+ },+ channel_id="web",+ )+ dispatch_call = asyncio.create_task(+ handler._handle_a2a_outbound_tool_push(chunk=dispatch_chunk, session_id="s1")+ )+ await started.wait()++ wrong_session = SimpleNamespace(+ payload={+ "id": "rpc-cancel-other",+ "method": A2A_TOOL_CANCEL_CALL,+ "params": {"jsonrpc_id": "rpc-dispatch"},+ },+ channel_id="web",+ )+ await handler._handle_a2a_outbound_tool_push(+ chunk=wrong_session, session_id="other"+ )+ assert dispatch_call.done() is False++ same_session = SimpleNamespace(+ payload={+ "id": "rpc-cancel-own",+ "method": A2A_TOOL_CANCEL_CALL,+ "params": {"jsonrpc_id": "rpc-dispatch"},+ },+ channel_id="web",+ )+ await handler._handle_a2a_outbound_tool_push(chunk=same_session, session_id="s1")+ with pytest.raises(asyncio.CancelledError):+ await dispatch_call+ assert replies[-1].params["response"]["result"]["canceled"] is True