Spaces:
Sleeping
Sleeping
feat: add A2A gateway support (activated by A2A_PEERS env var)
Browse files- Add openclaw-a2a-gateway extension to Dockerfile
- Add a2a-proxy.cjs for port routing (7860 proxy β 7861 OpenClaw, 18800 A2A)
- Modify sync_hf.py: port 7861, A2A config only when A2A_PEERS is set
- No impact when A2A_PEERS is not set (proxy transparently forwards)
Files changed (4)
- Dockerfile+8
- scripts/a2a-proxy.cjsAdded+134
- scripts/entrypoint.sh+6
- scripts/sync_hf.py+42-5
51 unmodified lines52535455565751 unmodified lines&& echo "[build] version: $(cat /app/openclaw/.version)" \&& echo "[build][layer2] Total clone+install+build: $(($(date +%s) - START))s"# ββ Layer 3 (node): Scripts + Config ββββββββββββββββββββββββββββββββββββββββββCOPY --chown=node:node scripts /home/node/scriptsCOPY --chown=node:node openclaw.json /home/node/scripts/openclaw.json.default51 unmodified lines525354555657585960616263646551 unmodified lines&& echo "[build] version: $(cat /app/openclaw/.version)" \&& echo "[build][layer2] Total clone+install+build: $(($(date +%s) - START))s"# ββ Layer 2.5: A2A Gateway Extension (optional, activated by A2A_PEERS env) ββRUN echo "[build][layer2.5] Cloning A2A gateway extension..." && START=$(date +%s) \&& git clone --depth 1 https://github.com/win4r/openclaw-a2a-gateway.git /app/openclaw/extensions/a2a-gateway \&& cd /app/openclaw/extensions/a2a-gateway \&& npm install --production \&& echo "[build] A2A gateway installed: $(ls node_modules | wc -l) packages" \&& echo "[build][layer2.5] A2A gateway: $(($(date +%s) - START))s"# ββ Layer 3 (node): Scripts + Config ββββββββββββββββββββββββββββββββββββββββββCOPY --chown=node:node scripts /home/node/scriptsCOPY --chown=node:node openclaw.json /home/node/scripts/openclaw.json.default
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134/** * a2a-proxy.cjs β Reverse proxy on port 7860 * * Routes: * /.well-known/* β A2A gateway (port 18800) * /a2a/* β A2A gateway (port 18800) * /api/state β local state JSON (for Office frontend polling) * everything else β OpenClaw (port 7861) */'use strict';
const http = require('http');const url = require('url');
const LISTEN_PORT = 7860;const OPENCLAW_PORT = 7861;const A2A_PORT = 18800;const AGENT_NAME = process.env.AGENT_NAME || 'Agent';
let currentState = { state: 'syncing', detail: `${AGENT_NAME} is starting...`, progress: 0, updated_at: new Date().toISOString()};
// Poll OpenClaw health to track stateasync function pollOpenClawHealth() { try { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 5000); const resp = await fetch(`http://127.0.0.1:${OPENCLAW_PORT}/`, { signal: controller.signal }); clearTimeout(timeout); currentState = { state: resp.ok ? 'idle' : 'error', detail: resp.ok ? `${AGENT_NAME} is running` : `HTTP ${resp.status}`, progress: resp.ok ? 100 : 0, updated_at: new Date().toISOString() }; } catch (_) { currentState = { state: 'syncing', detail: `${AGENT_NAME} is starting...`, progress: 0, updated_at: new Date().toISOString() }; }}
setInterval(pollOpenClawHealth, 5000);pollOpenClawHealth();
function proxyRequest(req, res, targetPort) { const options = { hostname: '127.0.0.1', port: targetPort, path: req.url, method: req.method, headers: { ...req.headers, host: `127.0.0.1:${targetPort}` } };
const proxy = http.request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode, proxyRes.headers); proxyRes.pipe(res, { end: true }); });
proxy.on('error', (err) => { if (!res.headersSent) { res.writeHead(502, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Backend unavailable', target: targetPort })); } });
req.pipe(proxy, { end: true });}
const server = http.createServer((req, res) => { const pathname = url.parse(req.url).pathname;
// A2A routes β A2A gateway if (pathname.startsWith('/.well-known/') || pathname.startsWith('/a2a/')) { return proxyRequest(req, res, A2A_PORT); }
// State endpoint for Office frontend polling if (pathname === '/api/state' || pathname === '/status') { res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); return res.end(JSON.stringify(currentState)); }
// Everything else β OpenClaw proxyRequest(req, res, OPENCLAW_PORT);});
// Handle WebSocket upgradesserver.on('upgrade', (req, socket, head) => { const pathname = url.parse(req.url).pathname; const targetPort = (pathname.startsWith('/.well-known/') || pathname.startsWith('/a2a/')) ? A2A_PORT : OPENCLAW_PORT;
const options = { hostname: '127.0.0.1', port: targetPort, path: req.url, method: req.method, headers: { ...req.headers, host: `127.0.0.1:${targetPort}` } };
const proxy = http.request(options); proxy.on('upgrade', (proxyRes, proxySocket, proxyHead) => { socket.write( `HTTP/1.1 101 Switching Protocols\r\n` + Object.entries(proxyRes.headers).map(([k, v]) => `${k}: ${v}`).join('\r\n') + '\r\n\r\n' ); proxySocket.write(head); proxySocket.pipe(socket); socket.pipe(proxySocket); }); proxy.on('error', () => socket.end()); proxy.end();});
server.listen(LISTEN_PORT, '0.0.0.0', () => { console.log(`[a2a-proxy] Listening on port ${LISTEN_PORT}`); console.log(`[a2a-proxy] OpenClaw β :${OPENCLAW_PORT}, A2A β :${A2A_PORT}`); console.log(`[a2a-proxy] Agent: ${AGENT_NAME}`);});63 unmodified lines64656667686963 unmodified linesecho "[entrypoint] OpenClaw version: $OPENCLAW_VERSION"fi# ββ Start OpenClaw via sync_hf.py βββββββββββββββββββββββββββββββββββββββββecho "[entrypoint] Starting OpenClaw via sync_hf.py..."exec python3 -u /home/node/scripts/sync_hf.py63 unmodified lines64656667686970717273747563 unmodified linesecho "[entrypoint] OpenClaw version: $OPENCLAW_VERSION"fi# ββ Start A2A proxy on port 7860 (OpenClaw moves to 7861) βββββββββββββββββecho "[entrypoint] Starting A2A proxy on port 7860..."node /home/node/scripts/a2a-proxy.cjs &A2A_PROXY_PID=$!echo "[entrypoint] A2A proxy PID: $A2A_PROXY_PID"# ββ Start OpenClaw via sync_hf.py βββββββββββββββββββββββββββββββββββββββββecho "[entrypoint] Starting OpenClaw via sync_hf.py..."exec python3 -u /home/node/scripts/sync_hf.py
70 unmodified lines717273747576301 unmodified lines37837938038138238338451 unmodified lines4364374384394404414422 unmodified lines44544644744844945045138 unmodified lines49049149249349449549649749849950050150250370 unmodified lines# Gateway token (default: huggingclaw; override via GATEWAY_TOKEN env var)GATEWAY_TOKEN = os.environ.get("GATEWAY_TOKEN", "huggingclaw")# Default model for new conversations (infer from provider if not set)OPENCLAW_DEFAULT_MODEL = os.environ.get("OPENCLAW_DEFAULT_MODEL") or ("openai/gpt-5-nano" if OPENAI_API_KEY301 unmodified lineswith open(config_path, "w") as f:json.dump({"gateway": {"mode": "local", "bind": "lan", "port": 7860,"trustedProxies": ["0.0.0.0/0"],"controlUi": {"allowInsecureAuth": True,51 unmodified linesdata["gateway"] = {"mode": "local","bind": "lan","port": 7860,"auth": {"token": GATEWAY_TOKEN},"trustedProxies": ["0.0.0.0/0"],"controlUi": {2 unmodified lines"allowedOrigins": allowed_origins}}print(f"[SYNC] Set gateway config (auth=token, origins={len(allowed_origins)})")# Ensure agents defaultsdata.setdefault("agents", {}).setdefault("defaults", {}).setdefault("model", {})38 unmodified linesdata.setdefault("models", {})["providers"] = providersdata["agents"]["defaults"]["model"]["primary"] = OPENCLAW_DEFAULT_MODEL# Plugin whitelist (only load telegram + whatsapp to speed up startup)data.setdefault("plugins", {}).setdefault("entries", {})data["plugins"]["allow"] = ["telegram", "whatsapp"]if "telegram" not in data["plugins"]["entries"]:data["plugins"]["entries"]["telegram"] = {"enabled": True}elif isinstance(data["plugins"]["entries"]["telegram"], dict):data["plugins"]["entries"]["telegram"]["enabled"] = True# ββ Telegram channel defaults (open DM policy for HF Spaces) ββ# Personal bot on HF Spaces β no need for strict pairing.tg_ch = data.setdefault("channels", {}).setdefault("telegram", {})70 unmodified lines71727374757677787980301 unmodified lines38238338438538638738851 unmodified lines4404414424434444454462 unmodified lines44945045145245345445538 unmodified lines49449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954070 unmodified lines# Gateway token (default: huggingclaw; override via GATEWAY_TOKEN env var)GATEWAY_TOKEN = os.environ.get("GATEWAY_TOKEN", "huggingclaw")# A2A configuration (optional; only activated when A2A_PEERS is set)AGENT_NAME = os.environ.get("AGENT_NAME", "HuggingClaw")A2A_PEERS = os.environ.get("A2A_PEERS", "") # comma-separated peer URLs# Default model for new conversations (infer from provider if not set)OPENCLAW_DEFAULT_MODEL = os.environ.get("OPENCLAW_DEFAULT_MODEL") or ("openai/gpt-5-nano" if OPENAI_API_KEY301 unmodified lineswith open(config_path, "w") as f:json.dump({"gateway": {"mode": "local", "bind": "lan", "port": 7861,"trustedProxies": ["0.0.0.0/0"],"controlUi": {"allowInsecureAuth": True,51 unmodified linesdata["gateway"] = {"mode": "local","bind": "lan","port": 7861,"auth": {"token": GATEWAY_TOKEN},"trustedProxies": ["0.0.0.0/0"],"controlUi": {2 unmodified lines"allowedOrigins": allowed_origins}}print(f"[SYNC] Set gateway config (port=7861, auth=token, origins={len(allowed_origins)})")# Ensure agents defaultsdata.setdefault("agents", {}).setdefault("defaults", {}).setdefault("model", {})38 unmodified linesdata.setdefault("models", {})["providers"] = providersdata["agents"]["defaults"]["model"]["primary"] = OPENCLAW_DEFAULT_MODEL# Plugin whitelistdata.setdefault("plugins", {}).setdefault("entries", {})plugin_allow = ["telegram", "whatsapp"]if A2A_PEERS:plugin_allow.append("a2a-gateway")data["plugins"]["allow"] = plugin_allowif "telegram" not in data["plugins"]["entries"]:data["plugins"]["entries"]["telegram"] = {"enabled": True}elif isinstance(data["plugins"]["entries"]["telegram"], dict):data["plugins"]["entries"]["telegram"]["enabled"] = True# ββ A2A Gateway Plugin Configuration (only if A2A_PEERS is set) ββif A2A_PEERS:peers = []for peer_url in A2A_PEERS.split(","):peer_url = peer_url.strip()if not peer_url:continuename = peer_url.split("//")[-1].split(".")[0].split("-")[-1].capitalize()peers.append({"name": name,"agentCardUrl": f"{peer_url}/.well-known/agent-card.json"})print(f"[SYNC] A2A peer: {name} β {peer_url}")data["plugins"]["entries"]["a2a-gateway"] = {"enabled": True,"config": {"agentCard": {"name": AGENT_NAME,"description": f"{AGENT_NAME} - HuggingClaw A2A Agent","skills": [{"id": "chat", "name": "chat", "description": "Chat bridge"}]},"server": {"host": "0.0.0.0", "port": 18800},"security": {"inboundAuth": "none"},"routing": {"defaultAgentId": "main"},"peers": peers}}print(f"[SYNC] A2A gateway configured: name={AGENT_NAME}, port=18800, peers={len(peers)}")# ββ Telegram channel defaults (open DM policy for HF Spaces) ββ# Personal bot on HF Spaces β no need for strict pairing.tg_ch = data.setdefault("channels", {}).setdefault("telegram", {})
Dockerfile+8
scripts/a2a-proxy.cjsAdded+134
scripts/entrypoint.sh+6
scripts/sync_hf.py+42-5