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 panel and management RPC (batch 3/7)
NickFuryXXXaf0e8b9fc01e
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex f171b6dafa..edc636a3aa 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -26,6 +26,7 @@"test:user-web-entry": "esbuild src/EnterpriseEntry.tsx --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/user-web-entry/EnterpriseEntry.mjs --alias:virtual:login-auth-simulate-provider=./src/auth/simulate/available.ts --define:import.meta.env.VITE_USER_WEB_MODE='\"personal\"' --define:import.meta.env.VITE_ENABLE_USER_WEB_EMBEDDING='\"false\"' --define:import.meta.env.VITE_LOGIN_AUTH_SIMULATE='\"false\"' && esbuild src/auth/config.ts src/auth/simulate/SimulatedAuthProvider.ts --bundle --packages=external --platform=node --format=esm --outdir=node_modules/.cache/user-web-entry/auth && node --test tests/userWebEntry.test.mjs","test:editable-combobox": "tsc src/components/SessionSidebar/editableComboboxModel.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/editable-combobox --skipLibCheck --noEmitOnError && node --test tests/editableCombobox.test.mjs","test:a2a-ingress-panel": "tsc src/components/A2AIngressPanel/a2aIngressPanelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/a2a-ingress-panel-state --skipLibCheck --noEmitOnError && node --test tests/a2aIngressPanelState.test.mjs",+ "test:a2a-outbound-panel": "tsc src/components/A2AIngressPanel/a2aOutboundPanelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/a2a-outbound-panel-state --skipLibCheck --noEmitOnError && node --test tests/a2aOutboundPanelState.test.mjs","test:chat-store-streaming": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/chatStoreStreaming.test.mjs","test:settle-historical-tool-executions": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/settleHistoricalToolExecutions.test.mjs","test:history-pagination": "tsc src/features/historyPagination.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/history-pagination --skipLibCheck --noEmitOnError && node --test tests/historyPagination.test.mjs",diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsxnew file mode 100644index 0000000000..ff31f83b91--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx@@ -0,0 +1,162 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import type { WebError } from '../../types/websocket';+import {+ normalizeA2AOutboundAgent,+ normalizeA2AOutboundDiscovery,+ normalizeA2AOutboundList,+ shouldAcceptA2AOutboundResponse,+ type A2AOutboundAgent,+ type A2AOutboundAvailability,+ type A2AOutboundDiscovery,+} from './a2aOutboundPanelState';++interface Props {+ isConnected: boolean;+ request: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>;+}++const BADGE: Record<A2AOutboundAvailability, string> = {+ available: 'bg-ok/15 text-ok', unreachable: 'bg-danger/15 text-danger',+ incompatible: 'bg-danger/15 text-danger', review_required: 'bg-warn/15 text-warn',+};++const errorMessage = (error: unknown): string => (error as WebError)?.message || String(error);++export function A2AOutboundPanel({ isConnected, request }: Props) {+ const { t, i18n } = useTranslation();+ const [url, setUrl] = useState('');+ const [discovery, setDiscovery] = useState<A2AOutboundDiscovery | null>(null);+ const [agents, setAgents] = useState<A2AOutboundAgent[]>([]);+ const [displayName, setDisplayName] = useState('');+ const [credential, setCredential] = useState('');+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);+ const [editing, setEditing] = useState<{ agentId: string; displayName: string; connectTimeout: string; syncWait: string; credential: string; clearCredential: boolean } | null>(null);+ const generationRef = useRef(0);++ const refresh = useCallback(async () => {+ if (!isConnected) return;+ const generation = ++generationRef.current;+ try {+ const payload = await request('a2a.outbound.list');+ if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;+ const next = normalizeA2AOutboundList(payload);+ if (!next) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));+ setAgents(next);+ setError(null);+ } catch (nextError) {+ if (shouldAcceptA2AOutboundResponse(generation, generationRef.current)) setError(errorMessage(nextError));+ }+ }, [isConnected, request, t]);++ useEffect(() => { void refresh(); }, [refresh]);++ const discover = async () => {+ if (!url.trim() || busy || !isConnected) return;+ setBusy('discover'); setError(null); setNotice(null); setDiscovery(null);+ try {+ const next = normalizeA2AOutboundDiscovery(await request('a2a.outbound.discover', { url: url.trim() }));+ if (!next) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));+ setDiscovery(next); setDisplayName(next.agent.name); setCredential('');+ setNotice(t('a2aIngress.outbound.discovery.previewReady'));+ } catch (nextError) { setError(errorMessage(nextError)); }+ finally { setBusy(null); }+ };++ const register = async () => {+ if (!discovery || busy || !isConnected) return;+ setBusy('register'); setError(null);+ try {+ const payload = await request('a2a.outbound.register', {+ discovery_id: discovery.discovery_id, display_name: displayName.trim() || discovery.agent.name,+ enabled: true, ...(credential ? { credential } : {}),+ });+ const created = normalizeA2AOutboundAgent(payload);+ if (!created) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));+ generationRef.current += 1; setAgents(current => [created, ...current]); setDiscovery(null); setCredential('');+ setNotice(t('a2aIngress.outbound.registered'));+ } catch (nextError) { setError(errorMessage(nextError)); }+ finally { setBusy(null); }+ };++ const operate = async (agent: A2AOutboundAgent, operation: 'toggle' | 'refresh' | 'confirm' | 'reject' | 'delete') => {+ if (busy || !isConnected) return;+ if (operation === 'delete' && !window.confirm(t('a2aIngress.outbound.deleteConfirm'))) return;+ setBusy(`${operation}:${agent.agent_id}`); setError(null); setNotice(null); generationRef.current += 1;+ try {+ let payload: unknown;+ if (operation === 'toggle') payload = await request('a2a.outbound.update', { agent_id: agent.agent_id, enabled: !agent.enabled });+ else if (operation === 'refresh') payload = await request('a2a.outbound.refresh', { agent_id: agent.agent_id });+ else if (operation === 'confirm' || operation === 'reject') payload = await request('a2a.outbound.confirm_revision', { agent_id: agent.agent_id, accept: operation === 'confirm' });+ else payload = await request('a2a.outbound.delete', { agent_id: agent.agent_id });+ if (operation === 'delete') setAgents(current => current.filter(item => item.agent_id !== agent.agent_id));+ else {+ const updated = normalizeA2AOutboundAgent(payload);+ if (!updated) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));+ setAgents(current => current.map(item => item.agent_id === updated.agent_id ? updated : item));+ }+ } catch (nextError) { setError(errorMessage(nextError)); void refresh(); }+ finally { setBusy(null); }+ };++ const saveSettings = async (agent: A2AOutboundAgent) => {+ if (!editing || editing.agentId !== agent.agent_id || busy || !isConnected) return;+ const connectTimeout = Number(editing.connectTimeout);+ const syncWait = Number(editing.syncWait);+ if (!editing.displayName.trim() || !Number.isFinite(connectTimeout) || connectTimeout <= 0 || !Number.isFinite(syncWait) || syncWait <= 0) {+ setError(t('a2aIngress.outbound.errors.invalidSettings')); return;+ }+ setBusy(`save:${agent.agent_id}`); setError(null); generationRef.current += 1;+ try {+ const payload = await request('a2a.outbound.update', {+ agent_id: agent.agent_id, display_name: editing.displayName.trim(),+ connect_timeout_seconds: connectTimeout, sync_wait_seconds: syncWait,+ ...(editing.credential ? { credential: editing.credential } : {}),+ ...(editing.clearCredential ? { clear_credential: true } : {}),+ });+ const updated = normalizeA2AOutboundAgent(payload);+ if (!updated) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));+ setAgents(current => current.map(item => item.agent_id === updated.agent_id ? updated : item));+ setEditing(null); setNotice(t('a2aIngress.outbound.saved'));+ } catch (nextError) { setError(errorMessage(nextError)); void refresh(); }+ finally { setBusy(null); }+ };++ return <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-auto pr-1 pt-1">+ {!isConnected && <Notice tone="warn">{t('a2aIngress.disconnected')}</Notice>}+ {error && <Notice tone="danger">{error}</Notice>}+ {notice && <Notice tone="ok">{notice}</Notice>}+ <section className="rounded-xl border border-border bg-panel-strong/60 p-4">+ <h3 className="text-sm font-semibold text-text">{t('a2aIngress.outbound.discovery.title')}</h3>+ <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.discovery.description')}</p>+ <div className="mt-4 flex gap-2">+ <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>+ </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>+ <div className="mt-4 grid gap-3 text-xs md:grid-cols-2"><Value label={t('a2aIngress.outbound.fields.version')} value={discovery.agent.version || '-'} /><Value label={t('a2aIngress.outbound.fields.endpoint')} value={discovery.agent.compatible_interfaces[0].url} /><Value label={t('a2aIngress.outbound.fields.protocol')} value={`${discovery.agent.compatible_interfaces[0].protocol_binding} ${discovery.agent.compatible_interfaces[0].protocol_version}`} /><Value label={t('a2aIngress.outbound.fields.expiresAt')} value={formatTime(discovery.expires_at, i18n.language)} /></div>+ <div className="mt-4 grid gap-3 md:grid-cols-2"><Input label={t('a2aIngress.outbound.fields.displayName')} value={displayName} onChange={setDisplayName} /><Input label={t('a2aIngress.outbound.fields.credential')} value={credential} onChange={setCredential} type="password" /></div>+ <div className="mt-4 flex justify-end gap-2"><button type="button" className="btn secondary" onClick={() => setDiscovery(null)} disabled={!!busy}>{t('common.cancel')}</button><button type="button" className="btn primary" onClick={() => void register()} disabled={!!busy}>{busy === 'register' ? t('a2aIngress.outbound.registering') : t('a2aIngress.outbound.register')}</button></div>+ </section>}+ <section className="rounded-xl border border-border bg-panel-strong/60">+ <div className="flex items-center justify-between border-b border-border px-4 py-3"><div><h3 className="text-sm font-semibold text-text">{t('a2aIngress.outbound.list.title')}</h3><p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.list.total', { count: agents.length })}</p></div><button type="button" className="btn secondary" onClick={() => void refresh()} disabled={!isConnected || !!busy}>{t('common.refresh')}</button></div>+ {agents.length === 0 ? <div className="px-4 py-12 text-center text-sm text-text-muted">{t('a2aIngress.outbound.list.empty')}</div> : <div className="divide-y divide-border">{agents.map(agent => <div key={agent.agent_id} className="p-4">+ <div className="flex flex-wrap items-start justify-between gap-3"><div><div className="flex items-center gap-2"><span className="font-medium text-text">{agent.display_name}</span><span className={`rounded-full px-2 py-0.5 text-xs ${BADGE[agent.availability]}`}>{t(`a2aIngress.outbound.availability.${agent.availability}`)}</span><span className="rounded-full bg-secondary px-2 py-0.5 text-xs text-text-muted">{agent.enabled ? t('a2aIngress.outbound.enabled') : t('a2aIngress.outbound.disabled')}</span></div><div className="mt-2 break-all font-mono text-xs text-text-muted">{agent.selected_interface.url}</div></div><div className="flex flex-wrap gap-2"><button type="button" className="btn secondary" onClick={() => setEditing({ agentId: agent.agent_id, displayName: agent.display_name, connectTimeout: String(agent.connect_timeout_seconds), syncWait: String(agent.sync_wait_seconds), credential: '', clearCredential: false })} disabled={!!busy}>{t('a2aIngress.outbound.settings')}</button><button type="button" className="btn secondary" onClick={() => void operate(agent, 'toggle')} disabled={!!busy || agent.availability === 'review_required'}>{agent.enabled ? t('a2aIngress.outbound.disable') : t('a2aIngress.outbound.enable')}</button><button type="button" className="btn secondary" onClick={() => void operate(agent, 'refresh')} disabled={!!busy}>{t('a2aIngress.outbound.refresh')}</button><button type="button" className="btn secondary text-danger" onClick={() => void operate(agent, 'delete')} disabled={!!busy}>{t('common.delete')}</button></div></div>+ <div className="mt-3 flex flex-wrap gap-x-5 gap-y-1 text-xs text-text-muted"><span>{t('a2aIngress.outbound.fields.revision')}: {agent.card_revision}</span><span>{t('a2aIngress.outbound.fields.credentialState')}: {agent.has_credential ? t('a2aIngress.outbound.configured') : t('a2aIngress.outbound.notConfigured')}</span><span>{t('a2aIngress.outbound.fields.lastChecked')}: {agent.last_checked_at ? formatTime(agent.last_checked_at, i18n.language) : '-'}</span></div>+ {agent.last_error_summary && <p className="mt-2 text-xs text-danger">{agent.last_error_summary}</p>}+ {editing?.agentId === agent.agent_id && <div className="mt-3 rounded-lg border border-border bg-bg p-3"><div className="grid gap-3 md:grid-cols-2"><Input label={t('a2aIngress.outbound.fields.displayName')} value={editing.displayName} onChange={value => setEditing(current => current ? { ...current, displayName: value } : current)} /><Input label={t('a2aIngress.outbound.fields.connectTimeout')} value={editing.connectTimeout} onChange={value => setEditing(current => current ? { ...current, connectTimeout: value } : current)} /><Input label={t('a2aIngress.outbound.fields.syncWait')} value={editing.syncWait} onChange={value => setEditing(current => current ? { ...current, syncWait: value } : current)} /><Input label={t('a2aIngress.outbound.fields.replaceCredential')} value={editing.credential} onChange={value => setEditing(current => current ? { ...current, credential: value, clearCredential: false } : current)} type="password" /></div><label className="mt-3 flex items-center gap-2 text-sm text-text"><input type="checkbox" checked={editing.clearCredential} onChange={event => setEditing(current => current ? { ...current, clearCredential: event.target.checked, credential: event.target.checked ? '' : current.credential } : current)} />{t('a2aIngress.outbound.clearCredential')}</label><div className="mt-3 flex justify-end gap-2"><button type="button" className="btn secondary" onClick={() => setEditing(null)}>{t('common.cancel')}</button><button type="button" className="btn primary" onClick={() => void saveSettings(agent)} disabled={!!busy}>{t('common.save')}</button></div></div>}+ {agent.availability === 'review_required' && <div className="mt-3 rounded-lg border border-warn/30 bg-warn/10 p-3 text-sm"><p>{t('a2aIngress.outbound.reviewRequired')}</p><PendingDiff agent={agent} label={t('a2aIngress.outbound.endpointChange')} /><div className="mt-3 flex gap-2"><button type="button" className="btn primary" onClick={() => void operate(agent, 'confirm')} disabled={!!busy}>{t('a2aIngress.outbound.confirm')}</button><button type="button" className="btn secondary" onClick={() => void operate(agent, 'reject')} disabled={!!busy}>{t('a2aIngress.outbound.reject')}</button></div></div>}+ </div>)}</div>}+ </section>+ </div>;+}++function formatTime(value: string, language: string): string { return new Date(value).toLocaleString(language.startsWith('zh') ? 'zh-CN' : 'en-US', { hour12: false }); }+function Notice({ tone, children }: { tone: 'warn' | 'danger' | 'ok'; children: React.ReactNode }) { const style = tone === 'danger' ? 'border-danger/30 bg-danger/10' : tone === 'warn' ? 'border-warn/30 bg-warn/10' : 'border-ok/30 bg-ok/10'; return <div className={`rounded-xl border px-4 py-3 text-sm text-text ${style}`}>{children}</div>; }+function Value({ label, value }: { label: string; value: string }) { return <div><div className="text-text-muted">{label}</div><div className="mt-1 break-all text-text">{value}</div></div>; }+function Input({ label, value, onChange, type = 'text' }: { label: string; value: string; onChange: (value: string) => void; type?: 'text' | 'password' }) { return <label><span className="text-xs font-medium text-text-muted">{label}</span><input type={type} className="mt-2 w-full rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent" value={value} onChange={event => onChange(event.target.value)} /></label>; }+function PendingDiff({ agent, label }: { agent: A2AOutboundAgent; label: string }) { const pending = agent.pending_revision?.selected_interface as Record<string, unknown> | undefined; const nextUrl = typeof pending?.url === 'string' ? pending.url : ''; if (!nextUrl || nextUrl === agent.selected_interface.url) return null; return <div className="mt-2 grid gap-1 rounded-md bg-bg/70 p-2 text-xs"><span className="font-medium text-text">{label}</span><span className="break-all text-text-muted">{agent.selected_interface.url}</span><span className="break-all text-warn">→ {nextUrl}</span></div>; }diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.ts b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.tsnew file mode 100644index 0000000000..ee98712874--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aOutboundPanelState.ts@@ -0,0 +1,109 @@+export type A2AOutboundAvailability = 'available' | 'unreachable' | 'incompatible' | 'review_required';++export interface A2AOutboundInterface {+ protocol_binding: string;+ protocol_version: string;+ url: string;+}++export interface A2AOutboundDiscovery {+ discovery_id: string;+ expires_at: string;+ source_url: string;+ card_path: string;+ card_fingerprint: string;+ agent: {+ name: string;+ description: string;+ version: string;+ skills: Array<Record<string, unknown>>;+ compatible_interfaces: A2AOutboundInterface[];+ };+ security_requirements: Array<Record<string, unknown>>;+ warnings: string[];+}++export interface A2AOutboundAgent {+ agent_id: string;+ display_name: string;+ card_revision: number;+ agent_card: Record<string, unknown>;+ selected_interface: A2AOutboundInterface;+ enabled: boolean;+ availability: A2AOutboundAvailability;+ has_credential: boolean;+ connect_timeout_seconds: number;+ sync_wait_seconds: number;+ last_checked_at: string | null;+ last_error_summary: string | null;+ pending_revision: Record<string, unknown> | null;+}++const asString = (value: unknown): string => typeof value === 'string' ? value : '';+const asNumber = (value: unknown): number => typeof value === 'number' && Number.isFinite(value) ? value : 0;++function normalizeInterface(value: unknown): A2AOutboundInterface | null {+ if (!value || typeof value !== 'object') return null;+ const item = value as Record<string, unknown>;+ const url = asString(item.url);+ const protocolBinding = asString(item.protocol_binding);+ if (!url || !protocolBinding) return null;+ return { url, protocol_binding: protocolBinding, protocol_version: asString(item.protocol_version) };+}++export function normalizeA2AOutboundDiscovery(value: unknown): A2AOutboundDiscovery | null {+ if (!value || typeof value !== 'object') return null;+ const payload = value as Record<string, unknown>;+ const rawAgent = payload.agent;+ if (!rawAgent || typeof rawAgent !== 'object') return null;+ const agent = rawAgent as Record<string, unknown>;+ const interfaces = Array.isArray(agent.compatible_interfaces)+ ? agent.compatible_interfaces.map(normalizeInterface).filter((item): item is A2AOutboundInterface => item !== null)+ : [];+ const discoveryId = asString(payload.discovery_id);+ if (!discoveryId || !asString(agent.name) || interfaces.length === 0) return null;+ return {+ discovery_id: discoveryId,+ expires_at: asString(payload.expires_at),+ source_url: asString(payload.source_url),+ card_path: asString(payload.card_path),+ card_fingerprint: asString(payload.card_fingerprint),+ agent: {+ name: asString(agent.name), description: asString(agent.description), version: asString(agent.version),+ skills: Array.isArray(agent.skills) ? agent.skills.filter(item => !!item && typeof item === 'object') as Array<Record<string, unknown>> : [],+ compatible_interfaces: interfaces,+ },+ security_requirements: Array.isArray(payload.security_requirements) ? payload.security_requirements as Array<Record<string, unknown>> : [],+ warnings: Array.isArray(payload.warnings) ? payload.warnings.map(asString).filter(Boolean) : [],+ };+}++export function normalizeA2AOutboundAgent(value: unknown): A2AOutboundAgent | null {+ if (!value || typeof value !== 'object') return null;+ const item = value as Record<string, unknown>;+ const availability = asString(item.availability) as A2AOutboundAvailability;+ const selectedInterface = normalizeInterface(item.selected_interface);+ if (!asString(item.agent_id) || !selectedInterface || !['available', 'unreachable', 'incompatible', 'review_required'].includes(availability)) return null;+ return {+ agent_id: asString(item.agent_id), display_name: asString(item.display_name), card_revision: asNumber(item.card_revision),+ agent_card: item.agent_card && typeof item.agent_card === 'object' ? item.agent_card as Record<string, unknown> : {},+ selected_interface: selectedInterface, enabled: item.enabled === true, availability,+ has_credential: item.has_credential === true, connect_timeout_seconds: asNumber(item.connect_timeout_seconds),+ sync_wait_seconds: asNumber(item.sync_wait_seconds), last_checked_at: typeof item.last_checked_at === 'string' ? item.last_checked_at : null,+ last_error_summary: typeof item.last_error_summary === 'string' ? item.last_error_summary : null,+ pending_revision: item.pending_revision && typeof item.pending_revision === 'object' ? item.pending_revision as Record<string, unknown> : null,+ };+}++export function normalizeA2AOutboundList(value: unknown): A2AOutboundAgent[] | null {+ if (!value || typeof value !== 'object' || !Array.isArray((value as Record<string, unknown>).items)) return null;+ const result: A2AOutboundAgent[] = [];+ for (const raw of (value as { items: unknown[] }).items) {+ const item = normalizeA2AOutboundAgent(raw);+ if (!item) return null;+ result.push(item);+ }+ return result;+}++export const shouldAcceptA2AOutboundResponse = (generation: number, current: number): boolean => generation === current;diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsxindex 0a18417d6c..1e033635c9 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import type { WebError } from '../../types/websocket';+import { A2AOutboundPanel } from './A2AOutboundPanel';import {canOperateA2AIngress,draftFromA2AIngressSnapshot,@@ -41,7 +42,7 @@ function errorMessage(error: unknown): string {export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps) {const { t, i18n } = useTranslation();- const [activeTab, setActiveTab] = useState<'config' | 'history'>('config');+ const [activeTab, setActiveTab] = useState<'config' | 'outbound' | 'history'>('config');const [snapshot, setSnapshot] = useState<A2AIngressSnapshot | null>(null);const [draft, setDraft] = useState<A2AIngressDraft | null>(null);const [loading, setLoading] = useState(false);@@ -196,12 +197,12 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)<button type="button" className="btn secondary" onClick={() => void runOperation('reload')} disabled={!canReload}>{operation === 'reload' ? t('a2aIngress.reloading') : t('a2aIngress.reload')}</button>- </div> : <button type="button" className="btn secondary" onClick={() => void refreshHistory()} disabled={!isConnected || historyLoading}>+ </div> : activeTab === 'history' ? <button type="button" className="btn secondary" onClick={() => void refreshHistory()} disabled={!isConnected || historyLoading}>{historyLoading ? t('common.refreshing') : t('common.refresh')}- </button>}+ </button> : null}</div><div className="app-subtabs shrink-0" role="tablist" aria-label={t('a2aIngress.tabs.ariaLabel')}>- {(['config', 'history'] as const).map(tab => (+ {(['config', 'outbound', 'history'] as const).map(tab => (<buttonkey={tab}type="button"@@ -319,7 +320,7 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)</div></section>)}- </div> : <div id="a2a-ingress-panel-history" role="tabpanel" aria-labelledby="a2a-ingress-tab-history" className="flex min-h-0 flex-1 flex-col gap-3 pt-1">+ </div> : activeTab === 'outbound' ? <div id="a2a-ingress-panel-outbound" role="tabpanel" aria-labelledby="a2a-ingress-tab-outbound" className="flex min-h-0 flex-1 flex-col pt-1"><A2AOutboundPanel isConnected={isConnected} request={request} /></div> : <div id="a2a-ingress-panel-history" role="tabpanel" aria-labelledby="a2a-ingress-tab-history" className="flex min-h-0 flex-1 flex-col gap-3 pt-1">{!isConnected && <Alert tone="warn">{t('a2aIngress.disconnected')}</Alert>}{historyError && <Alert tone="danger">{historyError}</Alert>}<section className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-panel-strong/60">diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 7a999a006a..c1a358a84d 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -539,7 +539,7 @@"a2aIngress": {"title": "A2A Control Center","subtitle": "Manage the A2A service exposed by JiuwenSwarm.",- "tabs": { "ariaLabel": "A2A Control Center pages", "config": "Ingress Configuration", "history": "Processing History" },+ "tabs": { "ariaLabel": "A2A Control Center pages", "config": "Ingress Configuration", "outbound": "Outbound Configuration", "history": "Processing History" },"enable": "Enable service", "enabling": "Enabling...", "disable": "Disable service", "disabling": "Disabling...", "reload": "Reload", "reloading": "Reloading...","save": "Save configuration", "saveAndApply": "Save and apply", "applying": "Applying...", "saved": "Configuration saved; it has not been applied to the running service.", "savedAndApplied": "Configuration saved and applied.","disconnected": "Gateway is disconnected, so the A2A service cannot be read or changed.",@@ -547,6 +547,17 @@"states": { "disabled": "Disabled", "starting": "Starting", "running": "Running", "stopping": "Stopping", "error": "Error" },"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." },+ "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" },+ "register": "Register", "registering": "Registering...", "registered": "The third-party Agent is registered and can now participate in outbound calls when enabled and available.",+ "enabled": "Enabled", "disabled": "Disabled", "enable": "Enable", "disable": "Disable", "refresh": "Refresh Card",+ "configured": "Configured", "notConfigured": "Not configured", "settings": "Settings", "saved": "Registration settings saved.", "clearCredential": "Clear saved credential", "reviewRequired": "A critical endpoint, protocol, security, or identity change was detected. New calls are paused until confirmation.", "endpointChange": "Endpoint change",+ "confirm": "Confirm and apply", "reject": "Reject change", "deleteConfirm": "Delete this registration? Existing dispatch history is retained, but new calls will be rejected immediately.",+ "errors": { "invalidResponse": "The A2A outbound manager returned invalid data.", "invalidSettings": "Enter a valid display name and timeout values greater than zero." }+ },"history": {"title": "Ingress request history", "description": "Shows the latest 200 A2A ingress requests in this Gateway process without retaining request bodies.", "total": "{{count}} total", "empty": "No processing history", "emptyDescription": "Incoming A2A request statuses will appear here.", "processing": "Processing","statuses": { "processing": "Processing", "completed": "Completed", "failed": "Failed", "canceled": "Canceled" },diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 290965bdc5..2e8fbfcb89 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -540,7 +540,7 @@"a2aIngress": {"title": "A2A 调度中心","subtitle": "管理 JiuwenSwarm 对外提供的 A2A 服务。",- "tabs": { "ariaLabel": "A2A 调度中心页面", "config": "入站配置", "history": "处理历史" },+ "tabs": { "ariaLabel": "A2A 调度中心页面", "config": "入站配置", "outbound": "出站配置", "history": "处理历史" },"enable": "启用服务", "enabling": "启用中...", "disable": "停用服务", "disabling": "停用中...", "reload": "重新加载", "reloading": "重载中...","save": "保存配置", "saveAndApply": "保存并应用", "applying": "应用中...", "saved": "配置已保存,尚未应用到正在运行的服务。", "savedAndApplied": "配置已保存并应用。","disconnected": "当前未连接到 Gateway,无法读取或修改 A2A 服务。",@@ -548,6 +548,17 @@"states": { "disabled": "已关闭", "starting": "启动中", "running": "运行中", "stopping": "停止中", "error": "异常" },"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": "发现成功。请核对信息并显式注册,当前候选尚不可调用。" },+ "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": "待确认" },+ "register": "注册", "registering": "注册中...", "registered": "第三方 Agent 已注册,现在可按启用和可用状态参与出站调用。",+ "enabled": "已启用", "disabled": "已停用", "enable": "启用", "disable": "停用", "refresh": "刷新 Card",+ "configured": "已配置", "notConfigured": "未配置", "settings": "配置", "saved": "注册项配置已保存。", "clearCredential": "清除已保存凭据", "reviewRequired": "检测到 Endpoint、协议、安全要求或身份信息的关键变化。确认前已暂停新调用。", "endpointChange": "Endpoint 变化",+ "confirm": "确认并应用", "reject": "拒绝变化", "deleteConfirm": "确定删除该注册项吗?已有派发历史会保留,但新调用将立即被拒绝。",+ "errors": { "invalidResponse": "A2A 出站管理服务返回了无效数据。", "invalidSettings": "请填写有效的显示名称和大于 0 的超时时间。" }+ },"history": {"title": "入向请求处理历史", "description": "显示当前 Gateway 进程内最近 200 条 A2A 入向请求,不记录请求正文。", "total": "共 {{count}} 条", "empty": "暂无处理记录", "emptyDescription": "收到 A2A 入向请求后,处理状态会显示在这里。", "processing": "处理中","statuses": { "processing": "处理中", "completed": "已完成", "failed": "失败", "canceled": "已取消" },diff --git a/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjs b/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjsnew file mode 100644index 0000000000..b9a9d8467a--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/a2aOutboundPanelState.test.mjs@@ -0,0 +1,70 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import {+ normalizeA2AOutboundAgent,+ normalizeA2AOutboundDiscovery,+ normalizeA2AOutboundList,+ shouldAcceptA2AOutboundResponse,+} from '../node_modules/.cache/a2a-outbound-panel-state/components/A2AIngressPanel/a2aOutboundPanelState.js';++const selectedInterface = {+ protocol_binding: 'JSONRPC',+ protocol_version: '1.0.0',+ url: 'https://agent.example.com/a2a',+};++const agent = {+ agent_id: 'agent-1',+ display_name: 'Research Agent',+ card_revision: 1,+ agent_card: { name: 'Research Agent' },+ selected_interface: selectedInterface,+ enabled: true,+ availability: 'available',+ has_credential: false,+ connect_timeout_seconds: 10,+ sync_wait_seconds: 300,+ last_checked_at: null,+ last_error_summary: null,+ pending_revision: null,+};++test('A2A outbound discovery requires an id, name, and compatible interface', () => {+ const discovery = normalizeA2AOutboundDiscovery({+ discovery_id: 'disc-1',+ expires_at: '2026-08-26T12:00:00Z',+ source_url: 'https://agent.example.com',+ card_path: '/.well-known/agent-card.json',+ card_fingerprint: 'sha256:card',+ agent: {+ name: 'Research Agent',+ description: 'Researches',+ version: '1.0.0',+ skills: [],+ compatible_interfaces: [selectedInterface],+ },+ security_requirements: [],+ warnings: [],+ });++ assert.ok(discovery);+ assert.equal(discovery.agent.compatible_interfaces[0].url, selectedInterface.url);+ assert.equal(normalizeA2AOutboundDiscovery({ discovery_id: 'disc-1', agent: { name: 'Agent' } }), null);+});++test('A2A outbound agent rejects unknown availability and malformed interfaces', () => {+ assert.ok(normalizeA2AOutboundAgent(agent));+ assert.equal(normalizeA2AOutboundAgent({ ...agent, availability: 'working' }), null);+ assert.equal(normalizeA2AOutboundAgent({ ...agent, selected_interface: { url: selectedInterface.url } }), null);+});++test('A2A outbound list rejects any malformed item', () => {+ assert.deepEqual(normalizeA2AOutboundList({ items: [agent] }), [agent]);+ assert.equal(normalizeA2AOutboundList({ items: [agent, { agent_id: '' }] }), null);+ assert.equal(normalizeA2AOutboundList({ items: 'invalid' }), 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/manager.py b/jiuwenswarm/gateway/a2a_manager/manager.pyindex a6231794e2..06524b1d4d 100644--- a/jiuwenswarm/gateway/a2a_manager/manager.py+++ b/jiuwenswarm/gateway/a2a_manager/manager.py@@ -1,9 +1,10 @@-"""Lifecycle and management operations for the Gateway's inbound A2A adapter."""+"""Lifecycle and management operations for Gateway A2A services."""from __future__ import annotationsimport asyncioimport logging+import osimport timefrom collections import dequefrom collections.abc import Callable@@ -13,6 +14,13 @@ from jiuwenswarm.gateway.channel_manager.protocol.a2a.a2a_connect import A2AChanfrom .config import A2AIngressConfigRepositoryfrom .models import A2AIngressConfig, A2AIngressError, A2AIngressSnapshot, A2AIngressState+from .outbound import (+ A2AOutboundDiscoveryService,+ A2AOutboundError,+ A2AOutboundErrorCode,+ A2AOutboundRegistry,+ A2AOutboundRepository,+)logger = logging.getLogger(__name__)@@ -44,6 +52,8 @@ class A2AManager:repository: A2AIngressConfigRepository | Any | None = None,channel_factory: ChannelFactory = A2AChannel,initial_error: A2AIngressError | None = None,+ outbound_repository: A2AOutboundRepository | None = None,+ outbound_registry: A2AOutboundRegistry | None = None,) -> None:self._channel_manager = channel_managerself._router = router@@ -61,11 +71,64 @@ class A2AManager:self._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 = outbound_registry+ if self._outbound is None and outbound_repository is not None:+ self._outbound = A2AOutboundRegistry(+ outbound_repository,+ discovery_service=A2AOutboundDiscoveryService(+ allow_loopback_http=allow_loopback_http+ ),+ )@propertydef channel(self) -> _ManagedA2AChannel | None:return self._channel+ @property+ def outbound_available(self) -> bool:+ return self._outbound is not None++ def _require_outbound(self) -> A2AOutboundRegistry:+ if self._outbound is None:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)+ return self._outbound++ 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_register(self, params: dict[str, Any]) -> dict[str, Any]:+ return await self._require_outbound().register(params)++ async def outbound_list(self) -> dict[str, Any]:+ return await self._require_outbound().list_agents()++ async def outbound_get(self, agent_id: str) -> dict[str, Any]:+ return await self._require_outbound().get_agent(agent_id)++ async def outbound_update(+ self, agent_id: str, params: dict[str, Any]+ ) -> dict[str, Any]:+ return await self._require_outbound().update_agent(agent_id, params)++ async def outbound_refresh(self, agent_id: str) -> dict[str, Any]:+ return await self._require_outbound().refresh_agent(agent_id)++ async def outbound_confirm_revision(+ self, agent_id: str, *, accept: bool+ ) -> dict[str, Any]:+ return await self._require_outbound().confirm_revision(agent_id, accept=accept)++ async def outbound_delete(self, agent_id: str) -> dict[str, Any]:+ return await self._require_outbound().delete_agent(agent_id)++ async def outbound_dispatch_get(self, dispatch_id: str) -> dict[str, Any]:+ return await self._require_outbound().get_dispatch(dispatch_id)+def snapshot(self) -> A2AIngressSnapshot:config = self._configeffective = self._effective_configdiff --git a/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py b/jiuwenswarm/gateway/a2a_manager/outbound/__init__.pyindex f0f315713f..aa72ef5a49 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/__init__.py@@ -1,6 +1,7 @@"""A2A outbound domain models and persistence contracts."""from .credentials import A2AOutboundCredentialStore+from .discovery import A2AOutboundDiscoveryService, DiscoveredCardfrom .errors import A2AOutboundError, A2AOutboundErrorCode, safe_error_summaryfrom .models import (A2ACompatibleInterface,@@ -19,6 +20,7 @@ from .repository import (A2AOutboundRepository,JsonA2AOutboundRecordCodec,)+from .registry import A2AOutboundRegistry__all__ = ["A2ACompatibleInterface",@@ -26,12 +28,15 @@ __all__ = ["A2AOutboundAgent","A2AOutboundAvailability","A2AOutboundCredentialStore",+ "A2AOutboundDiscoveryService",+ "A2AOutboundRegistry","A2AOutboundDiscovery","A2AOutboundDispatch","A2AOutboundDispatchMode","A2AOutboundDispatchStatus","A2AOutboundError","A2AOutboundErrorCode",+ "DiscoveredCard","A2AOutboundRepository","A2A_OUTBOUND_AGENT_STORE_NAME","A2A_OUTBOUND_DISPATCH_STORE_NAME",diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py b/jiuwenswarm/gateway/a2a_manager/outbound/discovery.pynew file mode 100644index 0000000000..4880d1dbcf--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/discovery.py@@ -0,0 +1,383 @@+"""Secure Agent Card discovery for the personal-edition outbound manager."""++from __future__ import annotations++import asyncio+import copy+import hashlib+import ipaddress+import json+import socket+from dataclasses import dataclass+from typing import Any, AsyncIterator, Awaitable, Callable, Mapping+from urllib.parse import urljoin, urlsplit, urlunsplit++import httpcore+import httpx+from a2a.client import ClientConfig+from a2a.client.card_resolver import parse_agent_card+from a2a.client.client_factory import ClientFactory+from google.protobuf.json_format import MessageToDict+from httpcore._backends.auto import AutoBackend++from .errors import A2AOutboundError, A2AOutboundErrorCode+from .models import A2ACompatibleInterface, A2ADiscoveredAgent++DEFAULT_CARD_PATH = "/.well-known/agent-card.json"+MAX_DISCOVERY_URL_LENGTH = 2048+MAX_REDIRECTS = 3+MAX_CARD_BYTES = 1_048_576++AddressResolver = Callable[[str, int], Awaitable[list[str]]]+TransportFactory = Callable[[Mapping[str, str]], httpx.AsyncBaseTransport]+++@dataclass(frozen=True)+class DiscoveredCard:+ source_url: str+ card_path: str+ card_url: str+ card_fingerprint: str+ agent: A2ADiscoveredAgent+ agent_card: dict[str, Any]+ security_requirements: tuple[dict[str, Any], ...]+ warnings: tuple[str, ...]+++@dataclass(frozen=True)+class _ValidatedTarget:+ host: str+ port: int+ pinned_address: str+++class _PinnedNetworkBackend(httpcore.AsyncNetworkBackend):+ """Connect hostnames to addresses selected by the SSRF validator.++ httpcore still receives the original URL host, so TLS uses the original+ hostname for SNI and certificate verification. Only the TCP destination is+ replaced, closing the validate-then-resolve DNS rebinding window.+ """++ def __init__(+ self,+ pinned_addresses: Mapping[str, str],+ *,+ backend: httpcore.AsyncNetworkBackend | None = None,+ ) -> None:+ self._pinned_addresses = {+ str(host).lower().rstrip("."): str(address)+ for host, address in pinned_addresses.items()+ }+ self._backend = backend or AutoBackend()++ async def connect_tcp(+ self,+ host: str,+ port: int,+ timeout: float | None = None,+ local_address: str | None = None,+ socket_options=None,+ ):+ normalized_host = str(host).lower().rstrip(".")+ pinned = self._pinned_addresses.get(normalized_host)+ if pinned is None:+ raise httpcore.ConnectError("connection target was not validated")+ return await self._backend.connect_tcp(+ pinned,+ port,+ timeout=timeout,+ local_address=local_address,+ socket_options=socket_options,+ )++ async def connect_unix_socket(self, path, timeout=None, socket_options=None):+ raise httpcore.ConnectError("unix sockets are not allowed")++ async def sleep(self, seconds: float) -> None:+ await self._backend.sleep(seconds)+++class _HttpcoreResponseStream(httpx.AsyncByteStream):+ def __init__(self, stream: AsyncIterator[bytes]) -> None:+ self._stream = stream++ async def __aiter__(self):+ async for chunk in self._stream:+ yield chunk++ async def aclose(self) -> None:+ await self._stream.aclose()+++class _PinnedAsyncHTTPTransport(httpx.AsyncBaseTransport):+ def __init__(self, pinned_addresses: Mapping[str, str]) -> None:+ self._pool = httpcore.AsyncConnectionPool(+ ssl_context=httpx.create_ssl_context(trust_env=False),+ max_connections=4,+ max_keepalive_connections=0,+ network_backend=_PinnedNetworkBackend(pinned_addresses),+ )++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ response = await self._pool.handle_async_request(+ httpcore.Request(+ method=request.method,+ url=httpcore.URL(+ scheme=request.url.raw_scheme,+ host=request.url.raw_host,+ port=request.url.port,+ target=request.url.raw_path,+ ),+ headers=request.headers.raw,+ content=request.stream,+ extensions=request.extensions,+ )+ )+ return httpx.Response(+ status_code=response.status,+ headers=response.headers,+ stream=_HttpcoreResponseStream(response.stream),+ extensions=response.extensions,+ )++ async def aclose(self) -> None:+ await self._pool.aclose()+++def _pinned_transport_factory(+ pinned_addresses: Mapping[str, str],+) -> httpx.AsyncBaseTransport:+ return _PinnedAsyncHTTPTransport(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)+ return sorted({str(row[4][0]).split("%", 1)[0] for row in rows})+++def _is_public_address(address: str) -> bool:+ ip = ipaddress.ip_address(address)+ return bool(ip.is_global) and not any(+ (+ ip.is_loopback,+ ip.is_link_local,+ ip.is_multicast,+ ip.is_reserved,+ ip.is_unspecified,+ )+ )+++class A2AOutboundDiscoveryService:+ """Resolve a caller-supplied Card URL without granting invocation rights."""++ def __init__(+ self,+ *,+ allow_loopback_http: bool = False,+ address_resolver: AddressResolver = _resolve_addresses,+ transport_factory: TransportFactory = _pinned_transport_factory,+ ) -> None:+ self._allow_loopback_http = allow_loopback_http+ self._address_resolver = address_resolver+ self._transport_factory = transport_factory++ 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+ parsed = None+ canonical: dict[str, Any] | None = None+ for redirect_count in range(MAX_REDIRECTS + 1):+ target = await self._validate_network_target(current)+ transport = self._transport_factory({target.host: target.pinned_address})+ try:+ async with httpx.AsyncClient(+ transport=transport,+ follow_redirects=False,+ timeout=httpx.Timeout(10.0),+ trust_env=False,+ ) as client:+ async with client.stream(+ "GET", current, headers={"Accept": "application/json"}+ ) as response:+ if response.is_redirect:+ if redirect_count >= MAX_REDIRECTS:+ raise A2AOutboundError(+ A2AOutboundErrorCode.CARD_FETCH_FAILED+ )+ location = response.headers.get("location", "")+ next_url = urljoin(current, location)+ next_host = (urlsplit(next_url).hostname or "").lower()+ current_host = (urlsplit(current).hostname or "").lower()+ if next_host != current_host:+ raise A2AOutboundError(+ A2AOutboundErrorCode.DISCOVERY_BLOCKED+ )+ current = next_url+ continue+ response.raise_for_status()+ body = bytearray()+ async for chunk in response.aiter_bytes():+ body.extend(chunk)+ if len(body) > MAX_CARD_BYTES:+ raise A2AOutboundError(+ A2AOutboundErrorCode.CARD_INVALID+ )+ try:+ raw_card = json.loads(body)+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:+ raise A2AOutboundError(+ A2AOutboundErrorCode.CARD_INVALID+ ) from exc+ if not isinstance(raw_card, dict):+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_INVALID)+ parsed = parse_agent_card(copy.deepcopy(raw_card))+ canonical = MessageToDict(+ parsed, preserving_proto_field_name=False+ )+ # ClientFactory is the SDK source of truth for transport+ # compatibility. The client remains open for this check.+ factory = ClientFactory(ClientConfig(httpx_client=client))+ factory.create(parsed)+ break+ except A2AOutboundError:+ raise+ except httpx.HTTPStatusError as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_FETCH_FAILED) from exc+ except (httpx.RequestError, httpcore.NetworkError, OSError) as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_FETCH_FAILED) from exc+ except Exception as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_INVALID) from exc+ else: # pragma: no cover - loop always exits or raises+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_FETCH_FAILED)++ if parsed is None or canonical is None:+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_INVALID)++ interfaces = tuple(+ A2ACompatibleInterface(+ protocol_binding=item.protocol_binding,+ protocol_version=item.protocol_version,+ url=item.url,+ ).validate()+ for item in parsed.supported_interfaces+ if item.protocol_binding.upper() == "JSONRPC"+ )+ if not interfaces:+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_INVALID)+ for interface in interfaces:+ await self._validate_network_target(interface.url)++ skills = tuple(+ {+ "id": item.id,+ "name": item.name,+ "description": item.description,+ "tags": list(item.tags),+ }+ for item in parsed.skills+ )+ security = tuple(canonical.get("securityRequirements") or [])+ fingerprint_source = json.dumps(+ canonical, sort_keys=True, separators=(",", ":")+ )+ fingerprint = (+ f"sha256:{hashlib.sha256(fingerprint_source.encode()).hexdigest()}"+ )+ final_parts = urlsplit(current)+ return DiscoveredCard(+ source_url=source_url,+ card_path=normalized_path,+ card_url=urlunsplit(+ (final_parts.scheme, final_parts.netloc, final_parts.path, "", "")+ ),+ card_fingerprint=fingerprint,+ agent=A2ADiscoveredAgent(+ name=parsed.name,+ description=parsed.description,+ version=parsed.version,+ skills=skills,+ compatible_interfaces=interfaces,+ ),+ agent_card=canonical,+ security_requirements=security,+ warnings=(),+ )++ @staticmethod+ def _normalize(url: str, card_path: str | None) -> tuple[str, str, str]:+ text = str(url or "").strip()+ if not text or len(text) > MAX_DISCOVERY_URL_LENGTH:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_URL_INVALID)+ try:+ parts = urlsplit(text)+ _ = parts.port+ except ValueError as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_URL_INVALID) from exc+ if parts.scheme.lower() not in {"https", "http"} or not parts.hostname:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_URL_INVALID)+ if parts.username or parts.password or parts.fragment:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_URL_INVALID)+ if parts.query:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_URL_INVALID)+ scheme = parts.scheme.lower()+ host = parts.hostname.lower().rstrip(".")+ port = parts.port+ default_port = 443 if scheme == "https" else 80+ netloc = f"[{host}]" if ":" in host else host+ if port and port != default_port:+ netloc = f"{netloc}:{port}"+ path = parts.path or "/"+ direct_card = card_path is None and path != "/"+ normalized_path = (+ path if direct_card else str(card_path or DEFAULT_CARD_PATH).strip()+ )+ if (+ not normalized_path.startswith("/")+ or "?" in normalized_path+ or "#" in normalized_path+ ):+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_URL_INVALID)+ source_path = "/" if direct_card else path.rstrip("/") or "/"+ source_url = urlunsplit((scheme, netloc, source_path, "", ""))+ card_url = (+ urlunsplit((scheme, netloc, normalized_path, "", ""))+ if direct_card+ else urljoin(f"{source_url.rstrip('/')}/", normalized_path.lstrip("/"))+ )+ return source_url, normalized_path, card_url++ async def _validate_network_target(self, url: str) -> _ValidatedTarget:+ try:+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ port = parts.port or (443 if scheme == "https" else 80)+ except ValueError as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_URL_INVALID) from exc+ has_credentials = bool(parts.username or parts.password)+ if scheme not in {"https", "http"} or not parts.hostname or has_credentials:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_URL_INVALID)+ try:+ addresses = await self._address_resolver(parts.hostname, port)+ except OSError as exc:+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_FETCH_FAILED) from exc+ if not addresses:+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_FETCH_FAILED)+ loopback_only = all(+ ipaddress.ip_address(item).is_loopback for item in addresses+ )+ if scheme == "http" and not (self._allow_loopback_http and loopback_only):+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_BLOCKED)+ if not all(_is_public_address(item) for item in addresses):+ if not (self._allow_loopback_http and loopback_only):+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_BLOCKED)+ return _ValidatedTarget(+ host=parts.hostname.lower().rstrip("."),+ port=port,+ pinned_address=addresses[0],+ )+++__all__ = ["A2AOutboundDiscoveryService", "DiscoveredCard", "DEFAULT_CARD_PATH"]diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py b/jiuwenswarm/gateway/a2a_manager/outbound/errors.pyindex 059e740d1d..6367ec675d 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/errors.py@@ -10,6 +10,9 @@ class A2AOutboundErrorCode(str, Enum):DISCOVERY_BLOCKED = "A2A_DISCOVERY_BLOCKED"CARD_FETCH_FAILED = "A2A_CARD_FETCH_FAILED"CARD_INVALID = "A2A_CARD_INVALID"+ DISCOVERY_NOT_FOUND = "A2A_DISCOVERY_NOT_FOUND"+ DISCOVERY_EXPIRED = "A2A_DISCOVERY_EXPIRED"+ AGENT_ALREADY_REGISTERED = "A2A_AGENT_ALREADY_REGISTERED"AGENT_NOT_REGISTERED = "A2A_AGENT_NOT_REGISTERED"AGENT_DISABLED = "A2A_AGENT_DISABLED"AGENT_UNAVAILABLE = "A2A_AGENT_UNAVAILABLE"@@ -29,6 +32,9 @@ _SAFE_SUMMARIES: dict[A2AOutboundErrorCode, str] = {A2AOutboundErrorCode.DISCOVERY_BLOCKED: "发现地址被安全策略拦截。",A2AOutboundErrorCode.CARD_FETCH_FAILED: "无法获取第三方 Agent Card。",A2AOutboundErrorCode.CARD_INVALID: "第三方 Agent Card 无效或不兼容。",+ A2AOutboundErrorCode.DISCOVERY_NOT_FOUND: "未找到指定的发现候选。",+ A2AOutboundErrorCode.DISCOVERY_EXPIRED: "发现候选已过期,请重新发现。",+ A2AOutboundErrorCode.AGENT_ALREADY_REGISTERED: "该第三方 Agent 已注册。",A2AOutboundErrorCode.AGENT_NOT_REGISTERED: "指定的第三方 Agent 尚未注册。",A2AOutboundErrorCode.AGENT_DISABLED: "指定的第三方 Agent 已停用。",A2AOutboundErrorCode.AGENT_UNAVAILABLE: "指定的第三方 Agent 当前不可用。",diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/models.py b/jiuwenswarm/gateway/a2a_manager/outbound/models.pyindex d6dfe36831..97a95355e0 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/models.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/models.py@@ -209,6 +209,7 @@ class A2AOutboundAgent:last_success_at: str | None = Nonelast_error_code: str | None = Nonelast_error_summary: str | None = None+ pending_revision: dict[str, Any] | None = Nonecreated_at: str = ""updated_at: str = ""@@ -244,6 +245,8 @@ class A2AOutboundAgent:record["availability"] = self.availability.valuerecord["agent_card"] = sanitize_persisted_value(self.agent_card)record["selected_interface"] = asdict(self.selected_interface)+ if self.pending_revision is not None:+ record["pending_revision"] = sanitize_persisted_value(self.pending_revision)return recorddef public_dict(self) -> dict[str, Any]:@@ -283,6 +286,11 @@ class A2AOutboundAgent:last_success_at=record.get("last_success_at"),last_error_code=record.get("last_error_code"),last_error_summary=record.get("last_error_summary"),+ pending_revision=(+ dict(record.get("pending_revision") or {})+ if record.get("pending_revision") is not None+ else None+ ),created_at=str(record.get("created_at") or ""),updated_at=str(record.get("updated_at") or ""),)diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py b/jiuwenswarm/gateway/a2a_manager/outbound/registry.pynew file mode 100644index 0000000000..c0c2545768--- /dev/null+++ b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py@@ -0,0 +1,442 @@+"""Discovery cache and registered-Agent management for A2A outbound."""++from __future__ import annotations++import asyncio+import logging+from dataclasses import dataclass, replace+from datetime import datetime, timedelta, timezone+from typing import Any, Callable, Mapping+from uuid import uuid4++from .credentials import A2AOutboundCredentialStore+from .discovery import A2AOutboundDiscoveryService, DiscoveredCard+from .errors import A2AOutboundError, A2AOutboundErrorCode+from .locks import KeyedLockPool+from .models import A2AOutboundAgent, A2AOutboundAvailability, A2AOutboundDiscovery+from .repository import A2AOutboundRepository, utc_now_text++DISCOVERY_TTL_SECONDS = 600+DEFAULT_CONNECT_TIMEOUT_SECONDS = 10.0+DEFAULT_SYNC_WAIT_SECONDS = 300.0++logger = logging.getLogger(__name__)+++def _parse_time(value: str) -> datetime:+ text = value[:-1] + "+00:00" if value.endswith("Z") else value+ return datetime.fromisoformat(text).astimezone(timezone.utc)+++def _pending_payload(card: DiscoveredCard) -> dict[str, Any]:+ return {+ "source_url": card.source_url,+ "card_path": card.card_path,+ "card_fingerprint": card.card_fingerprint,+ "agent_card": card.agent_card,+ "selected_interface": card.agent.compatible_interfaces[0].__dict__,+ "security_requirements": list(card.security_requirements),+ }+++@dataclass(frozen=True)+class _CriticalIdentity:+ """The subset of an Agent Card that must not silently change underfoot."""++ url: str+ protocol_binding: str+ security_requirements: tuple[Any, ...]+ security_schemes: tuple[str, ...]+ provider_url: str+ signature_protected: tuple[str, ...]+++def _critical_identity(agent: A2AOutboundAgent) -> _CriticalIdentity:+ card = agent.agent_card+ return _CriticalIdentity(+ url=agent.selected_interface.url,+ protocol_binding=agent.selected_interface.protocol_binding,+ security_requirements=tuple(card.get("securityRequirements") or ()),+ security_schemes=tuple(sorted((card.get("securitySchemes") or {}).keys())),+ provider_url=str((card.get("provider") or {}).get("url") or ""),+ signature_protected=tuple(+ str((signature or {}).get("protected") or "")+ for signature in card.get("signatures") or ()+ ),+ )+++def _critical_discovered_identity(card: DiscoveredCard) -> _CriticalIdentity:+ selected = card.agent.compatible_interfaces[0]+ payload = card.agent_card+ return _CriticalIdentity(+ url=selected.url,+ protocol_binding=selected.protocol_binding,+ security_requirements=tuple(payload.get("securityRequirements") or ()),+ security_schemes=tuple(sorted((payload.get("securitySchemes") or {}).keys())),+ provider_url=str((payload.get("provider") or {}).get("url") or ""),+ signature_protected=tuple(+ str((signature or {}).get("protected") or "")+ for signature in payload.get("signatures") or ()+ ),+ )+++class A2AOutboundRegistry:+ def __init__(+ self,+ repository: A2AOutboundRepository,+ *,+ discovery_service: A2AOutboundDiscoveryService | None = None,+ credential_store: A2AOutboundCredentialStore | None = None,+ discovery_ttl_seconds: int = DISCOVERY_TTL_SECONDS,+ now_factory: Callable[[], datetime] | None = None,+ ) -> None:+ self._repository = repository+ self._discovery = discovery_service or A2AOutboundDiscoveryService()+ self._credentials = credential_store or A2AOutboundCredentialStore()+ self._ttl = max(1, int(discovery_ttl_seconds))+ self._now = now_factory or (lambda: datetime.now(timezone.utc))+ self._discoveries: dict[str, A2AOutboundDiscovery] = {}+ self._cache_lock = asyncio.Lock()+ self._registration_lock = asyncio.Lock()+ self._agent_operation_locks = KeyedLockPool()++ 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()+ item = A2AOutboundDiscovery(+ discovery_id=f"disc_{uuid4().hex}",+ expires_at=(now + timedelta(seconds=self._ttl))+ .isoformat()+ .replace("+00:00", "Z"),+ source_url=card.source_url,+ card_path=card.card_path,+ card_fingerprint=card.card_fingerprint,+ agent=card.agent,+ agent_card=card.agent_card,+ security_requirements=card.security_requirements,+ warnings=card.warnings,+ )+ async with self._cache_lock:+ self._purge_expired_locked(now)+ self._discoveries[item.discovery_id] = item+ return item.to_dict()++ async def register(self, params: Mapping[str, Any]) -> dict[str, Any]:+ discovery_id = str(params.get("discovery_id") or "").strip()+ if not discovery_id:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_NOT_FOUND)+ async with self._repository.hold_discovery(discovery_id):+ discovery = await self._get_discovery(discovery_id)+ async with self._registration_lock:+ for existing in await self._repository.list_agents():+ if (+ existing.source_url == discovery.source_url+ and existing.card_path == discovery.card_path+ ) or existing.selected_interface.url in {+ item.url for item in discovery.agent.compatible_interfaces+ }:+ raise A2AOutboundError(+ A2AOutboundErrorCode.AGENT_ALREADY_REGISTERED+ )+ if not discovery.agent.compatible_interfaces:+ raise A2AOutboundError(A2AOutboundErrorCode.CARD_INVALID)+ agent_id = f"agent_{uuid4().hex}"+ timeouts = (+ params.get("timeouts")+ if isinstance(params.get("timeouts"), Mapping)+ else {}+ )+ credential = str(params.get("credential") or "")+ credential_ref = (+ self._credentials.reference_for(agent_id) if credential else None+ )+ stamp = utc_now_text()+ agent = A2AOutboundAgent(+ agent_id=agent_id,+ display_name=str(+ params.get("display_name") or discovery.agent.name+ ).strip(),+ source_url=discovery.source_url,+ card_path=discovery.card_path,+ card_fingerprint=discovery.card_fingerprint,+ card_revision=1,+ agent_card=discovery.agent_card,+ selected_interface=discovery.agent.compatible_interfaces[0],+ enabled=params.get("enabled") is not False,+ availability=A2AOutboundAvailability.AVAILABLE,+ credential_ref=credential_ref,+ connect_timeout_seconds=float(+ timeouts.get("connect_seconds", DEFAULT_CONNECT_TIMEOUT_SECONDS)+ ),+ sync_wait_seconds=float(+ timeouts.get("sync_wait_seconds", DEFAULT_SYNC_WAIT_SECONDS)+ ),+ last_checked_at=stamp,+ last_success_at=stamp,+ created_at=stamp,+ updated_at=stamp,+ ).validate()+ try:+ if credential:+ self._credentials.set_for_agent(agent_id, credential)+ created = await self._repository.create_agent(agent)+ except Exception:+ if credential_ref:+ self._credentials.delete(credential_ref)+ raise+ async with self._cache_lock:+ self._discoveries.pop(discovery_id, None)+ logger.info(+ "a2a.outbound audit action=register agent_id=%s enabled=%s",+ created.agent_id,+ created.enabled,+ )+ return created.public_dict()++ async def list_agents(self) -> dict[str, Any]:+ items = [item.public_dict() for item in await self._repository.list_agents()]+ return {"items": items, "total": len(items)}++ async def get_agent(self, agent_id: str) -> dict[str, Any]:+ return (await self._require_agent(agent_id)).public_dict()++ async def update_agent(+ self, agent_id: str, params: Mapping[str, Any]+ ) -> dict[str, Any]:+ allowed = {+ "display_name",+ "enabled",+ "connect_timeout_seconds",+ "sync_wait_seconds",+ "credential",+ "clear_credential",+ }+ if set(params) - allowed:+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)+ async with self._agent_operation_locks.hold(agent_id):+ current = await self._require_agent(agent_id)+ credential_present = "credential" in params+ credential = str(params.get("credential") or "")+ clear_credential = params.get("clear_credential") is True+ credential_ref = self._credentials.reference_for(agent_id)+ secret_changed = (+ credential_present and bool(credential)+ ) or clear_credential+ old_secret = (+ self._credentials.get(current.credential_ref) if secret_changed else ""+ )++ if credential_present and credential:+ self._credentials.set_for_agent(agent_id, credential)+ elif clear_credential:+ self._credentials.delete(credential_ref)++ def updater(item: A2AOutboundAgent) -> A2AOutboundAgent:+ changes: dict[str, Any] = {"updated_at": utc_now_text()}+ if "display_name" in params:+ changes["display_name"] = str(params["display_name"] or "").strip()+ if "enabled" in params:+ changes["enabled"] = params["enabled"] is True+ for field in ("connect_timeout_seconds", "sync_wait_seconds"):+ if field in params:+ changes[field] = float(params[field])+ if credential_present and credential:+ changes["credential_ref"] = credential_ref+ elif clear_credential:+ changes["credential_ref"] = None+ return replace(item, **changes)++ try:+ updated = await self._repository.update_agent(agent_id, updater)+ if updated is None:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)+ except Exception:+ if secret_changed:+ try:+ if current.credential_ref and old_secret:+ self._credentials.set_for_agent(agent_id, old_secret)+ else:+ self._credentials.delete(credential_ref)+ except Exception:+ logger.exception(+ "a2a.outbound credential rollback failed agent_id=%s",+ agent_id,+ )+ raise+ logger.info(+ "a2a.outbound audit action=update agent_id=%s fields=%s",+ agent_id,+ ",".join(sorted(set(params) - {"credential"})),+ )+ return updated.public_dict()++ async def refresh_agent(self, agent_id: str) -> dict[str, Any]:+ async with self._agent_operation_locks.hold(agent_id):+ current = await self._require_agent(agent_id)+ try:+ card = await self._discovery.discover(+ current.source_url, current.card_path+ )+ except A2AOutboundError as exc:+ error_code = exc.code.value+ error_summary = exc.summary+ updated = await self._repository.update_agent(+ agent_id,+ lambda item: replace(+ item,+ availability=(+ A2AOutboundAvailability.REVIEW_REQUIRED+ if item.pending_revision+ else A2AOutboundAvailability.UNREACHABLE+ ),+ last_checked_at=utc_now_text(),+ last_error_code=error_code,+ last_error_summary=error_summary,+ updated_at=utc_now_text(),+ ),+ )+ if updated is None:+ raise A2AOutboundError(+ A2AOutboundErrorCode.AGENT_NOT_REGISTERED+ ) from exc+ return updated.public_dict()++ def updater(item: A2AOutboundAgent) -> A2AOutboundAgent:+ stamp = utc_now_text()+ common = {+ "last_checked_at": stamp,+ "last_success_at": stamp,+ "last_error_code": None,+ "last_error_summary": None,+ "updated_at": stamp,+ }+ if (+ item.availability is A2AOutboundAvailability.REVIEW_REQUIRED+ and item.pending_revision+ ):+ return replace(+ item,+ pending_revision=_pending_payload(card),+ **common,+ )+ critical = _critical_identity(item) != _critical_discovered_identity(+ card+ )+ if critical:+ return replace(+ item,+ availability=A2AOutboundAvailability.REVIEW_REQUIRED,+ pending_revision=_pending_payload(card),+ **common,+ )+ return replace(+ item,+ card_fingerprint=card.card_fingerprint,+ card_revision=item.card_revision+ + (card.card_fingerprint != item.card_fingerprint),+ agent_card=card.agent_card,+ selected_interface=card.agent.compatible_interfaces[0],+ availability=A2AOutboundAvailability.AVAILABLE,+ pending_revision=None,+ **common,+ )++ updated = await self._repository.update_agent(agent_id, updater)+ if updated is None:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)+ logger.info(+ "a2a.outbound audit action=refresh agent_id=%s review_required=%s",+ agent_id,+ updated.availability is A2AOutboundAvailability.REVIEW_REQUIRED,+ )+ return updated.public_dict()++ async def confirm_revision(self, agent_id: str, *, accept: bool) -> dict[str, Any]:+ if not isinstance(accept, bool):+ raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)++ def updater(item: A2AOutboundAgent) -> A2AOutboundAgent:+ pending = item.pending_revision+ if (+ item.availability is not A2AOutboundAvailability.REVIEW_REQUIRED+ or not pending+ ):+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_REVIEW_REQUIRED)+ stamp = utc_now_text()+ if not accept:+ return replace(+ item,+ availability=A2AOutboundAvailability.AVAILABLE,+ pending_revision=None,+ updated_at=stamp,+ )+ return replace(+ item,+ source_url=str(pending["source_url"]),+ card_path=str(pending["card_path"]),+ card_fingerprint=str(pending["card_fingerprint"]),+ card_revision=item.card_revision + 1,+ agent_card=dict(pending["agent_card"]),+ selected_interface=item.selected_interface.from_dict(+ pending["selected_interface"]+ ),+ availability=A2AOutboundAvailability.AVAILABLE,+ pending_revision=None,+ last_success_at=stamp,+ updated_at=stamp,+ )++ async with self._agent_operation_locks.hold(agent_id):+ updated = await self._repository.update_agent(agent_id, updater)+ if updated is None:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)+ logger.info(+ "a2a.outbound audit action=confirm_revision agent_id=%s accepted=%s",+ agent_id,+ accept,+ )+ return updated.public_dict()++ async def delete_agent(self, agent_id: str) -> dict[str, Any]:+ async with self._agent_operation_locks.hold(agent_id):+ if not await self._repository.delete_agent(agent_id):+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)+ logger.info("a2a.outbound audit action=delete agent_id=%s", agent_id)+ return {"agent_id": agent_id, "deleted": True}++ async def get_dispatch(self, dispatch_id: str) -> dict[str, Any]:+ item = await self._repository.get_dispatch(str(dispatch_id or "").strip())+ if item is None:+ raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)+ return item.to_record()++ async def _require_agent(self, agent_id: str) -> A2AOutboundAgent:+ item = await self._repository.get_agent(str(agent_id or "").strip())+ if item is None:+ raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)+ return item++ async def _get_discovery(self, discovery_id: str) -> A2AOutboundDiscovery:+ now = self._now()+ async with self._cache_lock:+ item = self._discoveries.get(discovery_id)+ if item is None:+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_NOT_FOUND)+ if _parse_time(item.expires_at) <= now:+ self._discoveries.pop(discovery_id, None)+ raise A2AOutboundError(A2AOutboundErrorCode.DISCOVERY_EXPIRED)+ return item++ def _purge_expired_locked(self, now: datetime) -> None:+ expired = [+ key+ for key, item in self._discoveries.items()+ if _parse_time(item.expires_at) <= now+ ]+ for key in expired:+ self._discoveries.pop(key, None)+++__all__ = ["A2AOutboundRegistry", "DISCOVERY_TTL_SECONDS"]diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex 5d436e8e47..36a2337eb0 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -1633,6 +1633,7 @@ async def _run_with_telemetry(await init_gateway_redis_from_config(dict(full_cfg or {}))gateway_storage_ctx = None+ a2a_outbound_repository = Nonetry:from jiuwenswarm.gateway.storage_assembly.setup import (is_session_map_repository_enabled,@@ -1645,6 +1646,14 @@ async def _run_with_telemetry():gateway_storage_ctx = await setup_gateway_storage_repositories(full_cfg)if gateway_storage_ctx is not None:+ if not is_enterprise():+ from jiuwenswarm.gateway.storage_assembly import (+ create_a2a_outbound_repository,+ )++ a2a_outbound_repository = create_a2a_outbound_repository(+ await gateway_storage_ctx.persistent()+ )wired: list[str] = []if is_session_map_repository_enabled(full_cfg):wired.append("session_map")@@ -2008,6 +2017,7 @@ async def _run_with_telemetry(_DummyBus(),a2a_config,initial_error=a2a_config_error,+ outbound_repository=a2a_outbound_repository,)_register_web_handlers(diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 7f356131a4..edfdec86bc 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1666,6 +1666,122 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:channel.register_method("a2a.ingress.disable", _a2a_ingress_disable)channel.register_method("a2a.ingress.reload", _a2a_ingress_reload)+ async def _send_a2a_outbound(ws, req_id, operation) -> None:+ if a2a_manager is None or not a2a_manager.outbound_available:+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error="A2A 出站管理服务当前不可用。",+ code="A2A_OUTBOUND_STORE_INVALID",+ )+ return+ try:+ payload = await operation()+ except Exception as exc: # noqa: BLE001+ from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2AOutboundError,+ A2AOutboundErrorCode,+ safe_error_summary,+ )++ if isinstance(exc, A2AOutboundError):+ code = exc.code.value+ error = exc.summary+ else:+ code = A2AOutboundErrorCode.STORE_INVALID.value+ error = safe_error_summary(A2AOutboundErrorCode.STORE_INVALID)+ await channel.send_response(+ ws, req_id, ok=False, error=error, code=code+ )+ return+ await channel.send_response(ws, req_id, ok=True, payload=payload)++ async def _a2a_outbound_discover(ws, req_id, params, session_id):+ await _send_a2a_outbound(+ ws,+ req_id,+ lambda: a2a_manager.outbound_discover(+ str(params.get("url") or ""),+ str(params["card_path"]) if params.get("card_path") is not None else None,+ ),+ )++ 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))+ )++ async def _a2a_outbound_list(ws, req_id, params, session_id):+ await _send_a2a_outbound(ws, req_id, lambda: a2a_manager.outbound_list())++ async def _a2a_outbound_get(ws, req_id, params, session_id):+ await _send_a2a_outbound(+ ws, req_id, lambda: a2a_manager.outbound_get(str(params.get("agent_id") or ""))+ )++ async def _a2a_outbound_update(ws, req_id, params, session_id):+ payload = dict(params)+ agent_id = str(payload.pop("agent_id", ""))+ await _send_a2a_outbound(+ ws, req_id, lambda: a2a_manager.outbound_update(agent_id, payload)+ )++ async def _a2a_outbound_refresh(ws, req_id, params, session_id):+ await _send_a2a_outbound(+ ws, req_id, lambda: a2a_manager.outbound_refresh(str(params.get("agent_id") or ""))+ )++ async def _a2a_outbound_confirm_revision(ws, req_id, params, session_id):+ accept = params.get("accept")+ if not isinstance(accept, bool):+ from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2AOutboundErrorCode,+ safe_error_summary,+ )++ code = A2AOutboundErrorCode.STORE_INVALID+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error=safe_error_summary(code),+ code=code.value,+ )+ return+ await _send_a2a_outbound(+ ws,+ req_id,+ lambda: a2a_manager.outbound_confirm_revision(+ str(params.get("agent_id") or ""),+ accept=accept,+ ),+ )++ async def _a2a_outbound_delete(ws, req_id, params, session_id):+ await _send_a2a_outbound(+ ws, req_id, lambda: a2a_manager.outbound_delete(str(params.get("agent_id") or ""))+ )++ async def _a2a_outbound_dispatch_get(ws, req_id, params, session_id):+ await _send_a2a_outbound(+ ws,+ req_id,+ lambda: a2a_manager.outbound_dispatch_get(str(params.get("dispatch_id") or "")),+ )++ 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)+ channel.register_method("a2a.outbound.get", _a2a_outbound_get)+ channel.register_method("a2a.outbound.update", _a2a_outbound_update)+ channel.register_method("a2a.outbound.refresh", _a2a_outbound_refresh)+ channel.register_method(+ "a2a.outbound.confirm_revision", _a2a_outbound_confirm_revision+ )+ channel.register_method("a2a.outbound.delete", _a2a_outbound_delete)+ channel.register_method("a2a.outbound.dispatch.get", _a2a_outbound_dispatch_get)+from jiuwenswarm.common.schema.message import Message, EventTypedef _resolve(ref, key="value"):diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.pyindex 959467170f..a38e09bd14 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py@@ -83,6 +83,84 @@ _A2A_INGRESS_ROUTES: tuple[WebHttpMappedRoute, ...] = (),)+_A2A_OUTBOUND_ROUTES: tuple[WebHttpMappedRoute, ...] = (+ WebHttpMappedRoute(+ "POST",+ "/a2a/outbound/discover",+ "a2a.outbound.discover",+ "a2a",+ "发现并预览第三方 A2A Agent",+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "POST",+ "/a2a/outbound/agents",+ "a2a.outbound.register",+ "a2a",+ "显式注册第三方 A2A Agent",+ accept_body=True,+ created=True,+ ),+ WebHttpMappedRoute(+ "GET",+ "/a2a/outbound/agents",+ "a2a.outbound.list",+ "a2a",+ "列出已注册第三方 A2A Agent",+ ),+ WebHttpMappedRoute(+ "GET",+ "/a2a/outbound/agents/{agent_id}",+ "a2a.outbound.get",+ "a2a",+ "读取第三方 A2A Agent 注册项",+ path_to_param={"agent_id": "agent_id"},+ ),+ WebHttpMappedRoute(+ "PATCH",+ "/a2a/outbound/agents/{agent_id}",+ "a2a.outbound.update",+ "a2a",+ "更新第三方 A2A Agent 注册项",+ path_to_param={"agent_id": "agent_id"},+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "POST",+ "/a2a/outbound/agents/{agent_id}:refresh",+ "a2a.outbound.refresh",+ "a2a",+ "刷新第三方 A2A Agent Card",+ path_to_param={"agent_id": "agent_id"},+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "POST",+ "/a2a/outbound/agents/{agent_id}:confirm-revision",+ "a2a.outbound.confirm_revision",+ "a2a",+ "确认第三方 Agent Card 关键变化",+ path_to_param={"agent_id": "agent_id"},+ accept_body=True,+ ),+ WebHttpMappedRoute(+ "DELETE",+ "/a2a/outbound/agents/{agent_id}",+ "a2a.outbound.delete",+ "a2a",+ "删除第三方 A2A Agent 注册项",+ path_to_param={"agent_id": "agent_id"},+ ),+ WebHttpMappedRoute(+ "GET",+ "/a2a/outbound/dispatches/{dispatch_id}",+ "a2a.outbound.dispatch.get",+ "a2a",+ "读取 A2A 出站派发状态",+ path_to_param={"dispatch_id": "dispatch_id"},+ ),+)+_MODELS_ROUTES: tuple[WebHttpMappedRoute, ...] = (WebHttpMappedRoute("GET", "/models", "models.list",@@ -153,6 +231,7 @@ _CRON_ROUTES: tuple[WebHttpMappedRoute, ...] = (SETTINGS_ROUTES: tuple[WebHttpMappedRoute, ...] = (*_CONFIG_ROUTES,*_A2A_INGRESS_ROUTES,+ *_A2A_OUTBOUND_ROUTES,*_MODELS_ROUTES,*_LOCALE_ROUTES,*_CRON_ROUTES,diff --git a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.pyindex 2de53ca593..460b7cad14 100644--- a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py+++ b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py@@ -19,8 +19,12 @@ class _WebChannelProbe:def on_connect(self, handler) -> None:self.on_connect_handler = handler- async def send_response(self, ws, req_id, *, ok, payload=None, error=None, code=None) -> None:- self.responses.append({"id": req_id, "ok": ok, "payload": payload, "error": error, "code": code})+ async def send_response(+ self, ws, req_id, *, ok, payload=None, error=None, code=None+ ) -> None:+ self.responses.append(+ {"id": req_id, "ok": ok, "payload": payload, "error": error, "code": code}+ )class _ChannelManagerProbe:@@ -46,17 +50,51 @@ class _ChannelProbe:return None+class _OutboundRegistryProbe:+ async def discover(self, url, card_path=None):+ return {"discovery_id": "disc-1", "url": url, "card_path": card_path}++ async def register(self, params):+ return {"agent_id": "agent-1", "display_name": params.get("display_name")}++ async def list_agents(self):+ return {"items": [], "total": 0}++ async def get_agent(self, agent_id):+ return {"agent_id": agent_id}++ async def update_agent(self, agent_id, params):+ return {"agent_id": agent_id, **params}++ async def refresh_agent(self, agent_id):+ return {"agent_id": agent_id, "refreshed": True}++ async def confirm_revision(self, agent_id, *, accept=True):+ return {"agent_id": agent_id, "accepted": accept}++ async def delete_agent(self, agent_id):+ return {"agent_id": agent_id, "deleted": True}++ async def get_dispatch(self, dispatch_id):+ return {"dispatch_id": dispatch_id}++@pytest.mark.asyncioasync def test_a2a_ingress_web_handlers_return_snapshots():channel = _WebChannelProbe()manager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=_RepositoryProbe(),+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_RepositoryProbe(),channel_factory=lambda config, router: _ChannelProbe(),)_register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))await channel.methods["a2a.ingress.get"](object(), "get", {}, "session")- await channel.methods["a2a.ingress.history"](object(), "history", {"limit": 20}, "session")+ await channel.methods["a2a.ingress.history"](+ object(), "history", {"limit": 20}, "session"+ )await channel.methods["a2a.ingress.update"](object(), "update", {"port": 19123}, "session")@@ -72,7 +110,10 @@ async def test_a2a_ingress_web_handlers_return_snapshots():async def test_a2a_ingress_update_apply_disables_the_running_service():channel = _WebChannelProbe()manager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=_RepositoryProbe(),+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_RepositoryProbe(),channel_factory=lambda config, router: _ChannelProbe(),)_register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))@@ -91,13 +132,19 @@ async def test_a2a_ingress_update_apply_disables_the_running_service():async def test_a2a_ingress_handler_returns_operation_error_snapshot():channel = _WebChannelProbe()manager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=_RepositoryProbe(),+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_RepositoryProbe(),channel_factory=lambda config, router: _ChannelProbe(),)_register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))await channel.methods["a2a.ingress.update"](- object(), "update", {"config": {"rpc_path": "not-absolute"}, "apply": True}, "session"+ object(),+ "update",+ {"config": {"rpc_path": "not-absolute"}, "apply": True},+ "session",)assert channel.responses[-1]["ok"] is False@@ -109,7 +156,10 @@ async def test_a2a_ingress_handler_returns_operation_error_snapshot():async def test_a2a_ingress_history_rejects_non_integer_limit():channel = _WebChannelProbe()manager = A2AManager(- _ChannelManagerProbe(), object(), A2AIngressConfig(), repository=_RepositoryProbe(),+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_RepositoryProbe(),channel_factory=lambda config, router: _ChannelProbe(),)_register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))@@ -137,7 +187,9 @@ async def test_a2a_ingress_lifecycle_handlers_tolerate_missing_manager():def test_a2a_ingress_http_routes_map_to_rpc_methods():- routes = {(route.http_method, route.path): route.rpc_method for route in MAPPED_ROUTES}+ routes = {+ (route.http_method, route.path): route.rpc_method for route in MAPPED_ROUTES+ }assert routes[("GET", "/a2a/ingress")] == "a2a.ingress.get"assert routes[("GET", "/a2a/ingress/history")] == "a2a.ingress.history"@@ -145,3 +197,133 @@ def test_a2a_ingress_http_routes_map_to_rpc_methods():assert routes[("POST", "/a2a/ingress:enable")] == "a2a.ingress.enable"assert routes[("POST", "/a2a/ingress:disable")] == "a2a.ingress.disable"assert routes[("POST", "/a2a/ingress:reload")] == "a2a.ingress.reload"+++async def test_a2a_outbound_web_handlers_expose_management_facade():+ channel = _WebChannelProbe()+ manager = A2AManager(+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_RepositoryProbe(),+ channel_factory=lambda config, router: _ChannelProbe(),+ outbound_registry=_OutboundRegistryProbe(),+ )+ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))++ await channel.methods["a2a.outbound.discover"](+ object(), "discover", {"url": "https://agent.example.com"}, "session"+ )+ await channel.methods["a2a.outbound.register"](+ object(),+ "register",+ {"discovery_id": "disc-1", "display_name": "Agent"},+ "session",+ )+ await channel.methods["a2a.outbound.list"](object(), "list", {}, "session")+ await channel.methods["a2a.outbound.get"](+ object(), "get", {"agent_id": "agent-1"}, "session"+ )+ await channel.methods["a2a.outbound.update"](+ object(), "update", {"agent_id": "agent-1", "enabled": False}, "session"+ )+ await channel.methods["a2a.outbound.refresh"](+ object(), "refresh", {"agent_id": "agent-1"}, "session"+ )+ await channel.methods["a2a.outbound.confirm_revision"](+ object(), "confirm", {"agent_id": "agent-1", "accept": False}, "session"+ )+ await channel.methods["a2a.outbound.delete"](+ object(), "delete", {"agent_id": "agent-1"}, "session"+ )+ await channel.methods["a2a.outbound.dispatch.get"](+ object(), "dispatch_get", {"dispatch_id": "dispatch-1"}, "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+ assert channel.responses[3]["payload"]["agent_id"] == "agent-1"+ assert channel.responses[4]["payload"]["enabled"] is False+ assert channel.responses[5]["payload"]["refreshed"] is True+ assert channel.responses[6]["payload"]["accepted"] is False+ assert channel.responses[7]["payload"]["deleted"] is True+ assert channel.responses[8]["payload"]["dispatch_id"] == "dispatch-1"+ assert all(item["ok"] for item in channel.responses)++[email protected]("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(+ _ChannelManagerProbe(),+ object(),+ A2AIngressConfig(),+ repository=_RepositoryProbe(),+ channel_factory=lambda config, router: _ChannelProbe(),+ outbound_registry=_OutboundRegistryProbe(),+ )+ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))++ await channel.methods["a2a.outbound.confirm_revision"](+ object(), "confirm", params, "session"+ )++ assert channel.responses[-1]["ok"] is False+ assert channel.responses[-1]["code"] == "A2A_OUTBOUND_STORE_INVALID"+++async def test_a2a_outbound_handlers_tolerate_missing_manager():+ channel = _WebChannelProbe()+ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=None))++ await channel.methods["a2a.outbound.discover"](+ object(), "discover", {"url": "https://agent.example.com"}, "session"+ )+ await channel.methods["a2a.outbound.list"](object(), "list", {}, "session")+ await channel.methods["a2a.outbound.get"](+ object(), "get", {"agent_id": "agent-1"}, "session"+ )+ await channel.methods["a2a.outbound.update"](+ object(), "update", {"agent_id": "agent-1"}, "session"+ )+ await channel.methods["a2a.outbound.refresh"](+ object(), "refresh", {"agent_id": "agent-1"}, "session"+ )+ await channel.methods["a2a.outbound.confirm_revision"](+ object(), "confirm", {"agent_id": "agent-1", "accept": True}, "session"+ )+ await channel.methods["a2a.outbound.delete"](+ object(), "delete", {"agent_id": "agent-1"}, "session"+ )+ await channel.methods["a2a.outbound.dispatch.get"](+ object(), "dispatch_get", {"dispatch_id": "dispatch-1"}, "session"+ )++ assert [item["ok"] for item in channel.responses] == [False] * 8+ assert {item["code"] for item in channel.responses} == {"A2A_OUTBOUND_STORE_INVALID"}+++def test_a2a_outbound_http_routes_map_to_rpc_methods():+ routes = {+ (route.http_method, route.path): route.rpc_method for route in MAPPED_ROUTES+ }++ 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"+ assert routes[("PATCH", "/a2a/outbound/agents/{agent_id}")] == "a2a.outbound.update"+ assert (+ routes[("POST", "/a2a/outbound/agents/{agent_id}:refresh")]+ == "a2a.outbound.refresh"+ )+ assert (+ routes[("POST", "/a2a/outbound/agents/{agent_id}:confirm-revision")]+ == "a2a.outbound.confirm_revision"+ )+ assert (+ routes[("DELETE", "/a2a/outbound/agents/{agent_id}")] == "a2a.outbound.delete"+ )diff --git a/tests/unit_tests/gateway/test_a2a_outbound_management.py b/tests/unit_tests/gateway/test_a2a_outbound_management.pynew file mode 100644index 0000000000..3f4fb02d97--- /dev/null+++ b/tests/unit_tests/gateway/test_a2a_outbound_management.py@@ -0,0 +1,545 @@+"""Stage-2 coverage for A2A outbound discovery and registration management."""++from __future__ import annotations++import asyncio+from datetime import datetime, timedelta, timezone++import httpcore+import httpx+import pytest++from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2ACompatibleInterface,+ A2ADiscoveredAgent,+ A2AOutboundCredentialStore,+ A2AOutboundDiscoveryService,+ A2AOutboundError,+ A2AOutboundErrorCode,+ A2AOutboundRegistry,+ A2AOutboundRepository,+ DiscoveredCard,+)+from jiuwenswarm.gateway.storage.backends.memory_persistent import (+ InMemoryPersistentBackend,+)+from jiuwenswarm.gateway.a2a_manager.outbound import discovery as discovery_module+++class _SecretProbe:+ def __init__(self) -> None:+ self.values: dict[str, str] = {}++ def get(self, key: str) -> str:+ return self.values.get(key, "")++ def set(self, key: str, value: str, *, algorithm=None) -> None:+ self.values[key] = value++ def delete(self, key: str) -> None:+ self.values.pop(key, None)+++class _FailingUpdateRepository(A2AOutboundRepository):+ fail_next_update = False++ async def update_agent(self, agent_id, updater):+ if self.fail_next_update:+ self.fail_next_update = False+ raise RuntimeError("persistence unavailable")+ return await super().update_agent(agent_id, updater)+++def _card(+ endpoint: str = "https://agent.example.com/a2a", *, name: str = "Research Agent"+) -> DiscoveredCard:+ payload = {+ "name": name,+ "description": "Researches a topic",+ "version": "1.0.0",+ "supportedInterfaces": [+ {+ "url": endpoint,+ "protocolBinding": "JSONRPC",+ "protocolVersion": "1.0.0",+ }+ ],+ "skills": [+ {"id": "research", "name": "Research", "description": "", "tags": []}+ ],+ }+ return DiscoveredCard(+ source_url="https://agent.example.com",+ card_path="/.well-known/agent-card.json",+ card_url="https://agent.example.com/.well-known/agent-card.json",+ card_fingerprint=f"sha256:{name}:{endpoint}",+ agent=A2ADiscoveredAgent(+ name=name,+ description="Researches a topic",+ version="1.0.0",+ skills=(+ {"id": "research", "name": "Research", "description": "", "tags": []},+ ),+ compatible_interfaces=(+ A2ACompatibleInterface("JSONRPC", "1.0.0", endpoint),+ ),+ ),+ agent_card=payload,+ security_requirements=(),+ warnings=(),+ )+++class _DiscoverySequence:+ def __init__(self, *cards: DiscoveredCard) -> None:+ self.cards = list(cards)++ async def discover(self, url: str, card_path: str | None = None) -> DiscoveredCard:+ return self.cards.pop(0)+++def _registry(*cards: DiscoveredCard, now_factory=None):+ secret_probe = _SecretProbe()+ credentials = A2AOutboundCredentialStore(secret_probe)+ repository = A2AOutboundRepository(+ InMemoryPersistentBackend(), credential_store=credentials+ )+ return (+ A2AOutboundRegistry(+ repository,+ discovery_service=_DiscoverySequence(*cards),+ credential_store=credentials,+ now_factory=now_factory,+ ),+ repository,+ secret_probe,+ )+++async def test_discovery_preview_does_not_register_agent() -> None:+ registry, repository, _ = _registry(_card())++ preview = await registry.discover("https://agent.example.com")++ assert preview["discovery_id"].startswith("disc_")+ assert await repository.list_agents() == []+++async def test_registration_is_explicit_single_use_and_secret_is_not_returned() -> None:+ registry, repository, secrets = _registry(_card())+ preview = await registry.discover("https://agent.example.com")++ created = await registry.register(+ {+ "discovery_id": preview["discovery_id"],+ "display_name": "External Research",+ "credential": "must-not-return",+ }+ )++ assert created["display_name"] == "External Research"+ assert created["has_credential"] is True+ assert "credential" not in created and "credential_ref" not in created+ persisted = await repository.get_agent(created["agent_id"])+ assert persisted is not None+ assert secrets.values[persisted.credential_ref] == "must-not-return"+ with pytest.raises(A2AOutboundError) as error:+ await registry.register({"discovery_id": preview["discovery_id"]})+ assert error.value.code is A2AOutboundErrorCode.DISCOVERY_NOT_FOUND+++async def test_duplicate_source_cannot_be_registered_twice() -> None:+ registry, _, _ = _registry(_card(), _card())+ first = await registry.discover("https://agent.example.com")+ await registry.register({"discovery_id": first["discovery_id"]})+ second = await registry.discover("https://agent.example.com")++ with pytest.raises(A2AOutboundError) as error:+ await registry.register({"discovery_id": second["discovery_id"]})+ assert error.value.code is A2AOutboundErrorCode.AGENT_ALREADY_REGISTERED+++async def test_concurrent_discoveries_cannot_register_duplicate_agent() -> None:+ registry, repository, _ = _registry(_card(), _card())+ first, second = await asyncio.gather(+ registry.discover("https://agent.example.com"),+ registry.discover("https://agent.example.com"),+ )++ results = await asyncio.gather(+ registry.register({"discovery_id": first["discovery_id"]}),+ registry.register({"discovery_id": second["discovery_id"]}),+ return_exceptions=True,+ )++ assert len(await repository.list_agents()) == 1+ errors = [item for item in results if isinstance(item, A2AOutboundError)]+ assert len(errors) == 1+ assert errors[0].code is A2AOutboundErrorCode.AGENT_ALREADY_REGISTERED+++async def test_critical_refresh_requires_confirmation_before_switching_endpoint() -> (+ None+):+ registry, repository, _ = _registry(_card(), _card("https://new.example.com/a2a"))+ preview = await registry.discover("https://agent.example.com")+ created = await registry.register({"discovery_id": preview["discovery_id"]})++ refreshed = await registry.refresh_agent(created["agent_id"])+ assert refreshed["availability"] == "review_required"+ assert refreshed["selected_interface"]["url"] == "https://agent.example.com/a2a"+ assert (+ refreshed["pending_revision"]["selected_interface"]["url"]+ == "https://new.example.com/a2a"+ )++ confirmed = await registry.confirm_revision(created["agent_id"], accept=True)+ assert confirmed["availability"] == "available"+ assert confirmed["card_revision"] == 2+ assert confirmed["selected_interface"]["url"] == "https://new.example.com/a2a"+ assert (await repository.get_agent(created["agent_id"])).pending_revision is None+++async def test_refresh_does_not_clear_an_unconfirmed_pending_revision() -> None:+ registry, _, _ = _registry(+ _card(),+ _card("https://new.example.com/a2a"),+ _card(name="Research Agent v2"),+ )+ preview = await registry.discover("https://agent.example.com")+ created = await registry.register({"discovery_id": preview["discovery_id"]})+ await registry.refresh_agent(created["agent_id"])++ refreshed_again = await registry.refresh_agent(created["agent_id"])++ assert refreshed_again["availability"] == "review_required"+ assert refreshed_again["selected_interface"]["url"] == (+ "https://agent.example.com/a2a"+ )+ assert refreshed_again["pending_revision"] is not None+ assert refreshed_again["pending_revision"]["agent_card"]["name"] == (+ "Research Agent v2"+ )+++async def test_reject_revision_keeps_effective_card_and_clears_pending() -> None:+ registry, _, _ = _registry(_card(), _card("https://new.example.com/a2a"))+ preview = await registry.discover("https://agent.example.com")+ created = await registry.register({"discovery_id": preview["discovery_id"]})+ await registry.refresh_agent(created["agent_id"])++ rejected = await registry.confirm_revision(created["agent_id"], accept=False)++ assert rejected["availability"] == "available"+ assert rejected["card_revision"] == 1+ assert rejected["selected_interface"]["url"] == "https://agent.example.com/a2a"+ assert rejected["pending_revision"] is None+++async def test_noncritical_refresh_applies_new_card_revision_immediately() -> None:+ registry, _, _ = _registry(_card(), _card(name="Research Agent v2"))+ preview = await registry.discover("https://agent.example.com")+ created = await registry.register({"discovery_id": preview["discovery_id"]})++ refreshed = await registry.refresh_agent(created["agent_id"])++ assert refreshed["availability"] == "available"+ assert refreshed["card_revision"] == 2+ assert refreshed["agent_card"]["name"] == "Research Agent v2"+++async def test_discovery_expiry_uses_injected_clock() -> None:+ now = [datetime(2026, 8, 26, tzinfo=timezone.utc)]+ registry, _, _ = _registry(_card(), now_factory=lambda: now[0])+ preview = await registry.discover("https://agent.example.com")+ now[0] += timedelta(minutes=11)++ with pytest.raises(A2AOutboundError) as error:+ await registry.register({"discovery_id": preview["discovery_id"]})++ assert error.value.code is A2AOutboundErrorCode.DISCOVERY_EXPIRED+++async def test_credential_update_and_clear_are_persisted_together() -> None:+ registry, repository, secrets = _registry(_card())+ preview = await registry.discover("https://agent.example.com")+ created = await registry.register({"discovery_id": preview["discovery_id"]})++ updated = await registry.update_agent(+ created["agent_id"], {"credential": "new-secret"}+ )+ persisted = await repository.get_agent(created["agent_id"])+ assert persisted is not None+ assert updated["has_credential"] is True+ assert secrets.values[persisted.credential_ref] == "new-secret"++ cleared = await registry.update_agent(+ created["agent_id"], {"clear_credential": True}+ )+ assert cleared["has_credential"] is False+ assert secrets.values == {}+++async def test_credential_change_rolls_back_when_agent_update_fails() -> None:+ secrets = _SecretProbe()+ credentials = A2AOutboundCredentialStore(secrets)+ repository = _FailingUpdateRepository(+ InMemoryPersistentBackend(), credential_store=credentials+ )+ registry = A2AOutboundRegistry(+ repository,+ discovery_service=_DiscoverySequence(_card()),+ credential_store=credentials,+ )+ preview = await registry.discover("https://agent.example.com")+ created = await registry.register(+ {"discovery_id": preview["discovery_id"], "credential": "old-secret"}+ )+ repository.fail_next_update = True++ with pytest.raises(RuntimeError, match="persistence unavailable"):+ await registry.update_agent(+ created["agent_id"], {"credential": "replacement-secret"}+ )++ persisted = await repository.get_agent(created["agent_id"])+ assert persisted is not None+ assert secrets.values[persisted.credential_ref] == "old-secret"+++async def test_discovery_blocks_private_and_plain_http_targets() -> None:+ async def private_resolver(host: str, port: int) -> list[str]:+ return ["10.0.0.8"]++ service = A2AOutboundDiscoveryService(address_resolver=private_resolver)+ with pytest.raises(A2AOutboundError) as private_error:+ await service.discover("https://private.example.com")+ assert private_error.value.code is A2AOutboundErrorCode.DISCOVERY_BLOCKED++ async def public_resolver(host: str, port: int) -> list[str]:+ return ["93.184.216.34"]++ plain_service = A2AOutboundDiscoveryService(address_resolver=public_resolver)+ with pytest.raises(A2AOutboundError) as plain_error:+ await plain_service.discover("http://example.com")+ assert plain_error.value.code is A2AOutboundErrorCode.DISCOVERY_BLOCKED+++async def test_network_validation_accepts_case_insensitive_https_scheme() -> None:+ async def public_resolver(host: str, port: int) -> list[str]:+ return ["93.184.216.34"]++ service = A2AOutboundDiscoveryService(address_resolver=public_resolver)++ target = await service._validate_network_target("HTTPS://agent.example.com/a2a")++ assert target.host == "agent.example.com"+ assert target.port == 443+++async def test_discovery_revalidates_and_rejects_cross_host_redirect() -> None:+ async def public_resolver(host: str, port: int) -> list[str]:+ return ["93.184.216.34"]++ async def redirect(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 302, headers={"location": "https://other.example/card.json"}+ )++ service = A2AOutboundDiscoveryService(+ address_resolver=public_resolver,+ transport_factory=lambda _: httpx.MockTransport(redirect),+ )+ with pytest.raises(A2AOutboundError) as error:+ await service.discover("https://agent.example.com")+ assert error.value.code is A2AOutboundErrorCode.DISCOVERY_BLOCKED+++async def test_discovery_follows_case_insensitive_same_host_redirect() -> None:+ async def public_resolver(host: str, port: int) -> list[str]:+ return ["93.184.216.34"]++ card = {+ "name": "Research Agent",+ "description": "Researches",+ "version": "1.0.0",+ "protocolVersion": "1.0.0",+ "url": "https://agent.example.com/a2a",+ "preferredTransport": "JSONRPC",+ "skills": [],+ "capabilities": {},+ "defaultInputModes": ["text/plain"],+ "defaultOutputModes": ["text/plain"],+ }++ calls: list[httpx.URL] = []++ async def redirect_then_respond(request: httpx.Request) -> httpx.Response:+ calls.append(request.url)+ if len(calls) == 1:+ return httpx.Response(+ 302, headers={"location": "https://Agent.Example.com/a2a"}+ )+ return httpx.Response(200, json=card)++ service = A2AOutboundDiscoveryService(+ address_resolver=public_resolver,+ transport_factory=lambda _: httpx.MockTransport(redirect_then_respond),+ )++ result = await service.discover("https://agent.example.com")++ assert len(calls) == 2+ assert result.agent.name == "Research Agent"+++async def test_validated_ip_is_pinned_for_tcp_connection() -> None:+ calls = []+ sentinel = object()++ class _NetworkProbe:+ async def connect_tcp(self, host, port, **kwargs):+ calls.append((host, port))+ return sentinel++ async def sleep(self, seconds):+ return None++ backend = discovery_module._PinnedNetworkBackend(+ {"agent.example.com": "93.184.216.34"}, backend=_NetworkProbe()+ )++ result = await backend.connect_tcp("agent.example.com", 443)++ assert result is sentinel+ assert calls == [("93.184.216.34", 443)]+ with pytest.raises(httpcore.ConnectError):+ await backend.connect_tcp("unvalidated.example.com", 443)+++class _ChunkStream(httpx.AsyncByteStream):+ def __init__(self, chunks: list[bytes]) -> None:+ self.chunks = chunks+ self.consumed = 0++ async def __aiter__(self):+ for chunk in self.chunks:+ self.consumed += 1+ yield chunk+++async def test_card_size_limit_stops_streaming_before_full_response() -> None:+ async def public_resolver(host: str, port: int) -> list[str]:+ return ["93.184.216.34"]++ stream = _ChunkStream([b"x" * 600_000, b"y" * 600_000, b"z" * 600_000])++ async def respond(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, stream=stream)++ service = A2AOutboundDiscoveryService(+ address_resolver=public_resolver,+ transport_factory=lambda _: httpx.MockTransport(respond),+ )+ with pytest.raises(A2AOutboundError) as error:+ await service.discover("https://agent.example.com")++ assert error.value.code is A2AOutboundErrorCode.CARD_INVALID+ assert stream.consumed == 2+++async def test_valid_sdk_card_is_normalized_and_compatible(monkeypatch) -> None:+ async def public_resolver(host: str, port: int) -> list[str]:+ return ["93.184.216.34"]++ card = {+ "name": "Research Agent",+ "description": "Researches",+ "version": "1.0.0",+ "protocolVersion": "1.0.0",+ "url": "https://agent.example.com/a2a",+ "preferredTransport": "JSONRPC",+ "skills": [],+ "capabilities": {},+ "defaultInputModes": ["text/plain"],+ "defaultOutputModes": ["text/plain"],+ }++ async def respond(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=card)++ pinned = []+ client_closed_states = []+ real_factory = discovery_module.ClientFactory++ class _ClientFactoryProbe:+ def __init__(self, config):+ client_closed_states.append(config.httpx_client.is_closed)+ self._delegate = real_factory(config)++ def create(self, parsed):+ return self._delegate.create(parsed)++ monkeypatch.setattr(discovery_module, "ClientFactory", _ClientFactoryProbe)++ def transport_factory(addresses):+ pinned.append(dict(addresses))+ return httpx.MockTransport(respond)++ service = A2AOutboundDiscoveryService(+ address_resolver=public_resolver,+ transport_factory=transport_factory,+ )+ result = await service.discover("https://agent.example.com")++ assert result.agent.name == "Research Agent"+ assert result.agent.compatible_interfaces[0].protocol_binding == "JSONRPC"+ assert result.card_fingerprint.startswith("sha256:")+ assert pinned == [{"agent.example.com": "93.184.216.34"}]+ assert client_closed_states == [False]+++def test_app_gateway_wires_outbound_repository_without_removed_edition_module():+ """`jiuwenswarm.gateway.edition` was removed from the mainline; the a2a+ outbound repository wiring in app_gateway.py must resolve personal vs.+ enterprise edition via `is_enterprise()` instead, or every Gateway boot+ silently swallows the ImportError and leaves the outbound panel showing+ "A2A 出站管理服务当前不可用" regardless of configuration.+ """+ import ast+ import importlib.util+ from pathlib import Path++ spec = importlib.util.find_spec("jiuwenswarm.gateway.app_gateway")+ assert spec is not None and spec.origin+ source = Path(spec.origin).read_text(encoding="utf-8")+ tree = ast.parse(source)++ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom) and node.module:+ assert not node.module.startswith("jiuwenswarm.gateway.edition"), (+ "app_gateway.py must not import from the removed "+ "jiuwenswarm.gateway.edition module"+ )++ from jiuwenswarm.gateway.storage_assembly import create_a2a_outbound_repository++ assert callable(create_a2a_outbound_repository)