Skip to content

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

Python
24.9 KB
Raw Blame
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.

"""企业版 AgentServerClient:route → HTTP 发信封 → touch。"""

from __future__ import annotations

import asyncio
import logging
import time
import uuid
from collections.abc import AsyncIterator, Awaitable, Callable
from typing import Any
from urllib.parse import urlsplit

import httpx

from jiuwenswarm.common.e2a.models import E2AEnvelope
from jiuwenswarm.common.local_env_config import read_env
from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk
from jiuwenswarm.gateway.routing.agent_client import AgentServerClient
from jiuwenswarm.gateway.routing.http_agent_client import HttpSseAgentServerClient

from .agent_authorization import authorize_agent
from .invoke_ids import apply_invoke_ids_to_envelope
from .session_route_client import (
    FatalRouteError,
    RetryableRouteError,
    RuntimeSessionRouteClient,
)

logger = logging.getLogger(__name__)

_ROUTE_ATTEMPTS = 3
_TOUCH_INTERVAL_SECONDS = 20.0
_ROUTELESS_METHODS = frozenset(
    {
        "agent.reload_config",
        "agent.prewarm.sync",
        "agent.prewarm_sync",
        "browser.runtime_restart",
        "initialize",
    }
)


def http_base_from_pod_sse_url(pod_sse_url: str) -> str:
    """``http://ip:8080/sse`` → ``http://ip:8080``,交给协议层再拼 ``/api/v1``。"""
    parsed = urlsplit((pod_sse_url or "").strip())
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        raise FatalRouteError(
            f"invalid pod_sse_url: {pod_sse_url!r}",
            code="VALIDATION",
        )
    return f"{parsed.scheme}://{parsed.netloc}"


def _first_text(*values: Any) -> str:
    for value in values:
        if value is None:
            continue
        if isinstance(value, (list, tuple)):
            if not value:
                continue
            value = value[0]
        text = str(value).strip()
        if text:
            return text
    return ""


def _from_maps(key: str, *maps: Any) -> str:
    for mapping in maps:
        if not isinstance(mapping, dict):
            continue
        found = _first_text(mapping.get(key))
        if found:
            return found
        nested = mapping.get("query")
        if isinstance(nested, dict):
            found = _first_text(nested.get(key))
            if found:
                return found
        ext = mapping.get("ext")
        if isinstance(ext, dict):
            found = _first_text(ext.get(key))
            if found:
                return found
    return ""


def _is_heartbeat_envelope(envelope: E2AEnvelope) -> bool:
    if str(envelope.request_id or "").startswith("heartbeat-"):
        return True
    params = envelope.params if isinstance(envelope.params, dict) else {}
    run = params.get("run")
    if isinstance(run, dict) and str(run.get("kind") or "").strip().lower() == "heartbeat":
        return True
    return False


def _is_routeless_envelope(envelope: E2AEnvelope) -> bool:
    """无需 session route 的管理类请求(如启动期 reload_config)。"""
    if _is_heartbeat_envelope(envelope):
        return True
    method = str(envelope.method or "").strip().lower()
    return method in _ROUTELESS_METHODS


def _rebind_timeout() -> float:
    try:
        value = float(read_env("GATEWAY_RUNTIME_SESSION_REBIND_TIMEOUT", "2"))
    except (TypeError, ValueError):
        return 2.0
    return value if value > 0 else 2.0


def _default_http_base() -> str:
    """管理类请求(reload_config 等)的默认 Agent HTTP Base。

    须指向 Agent ``http_server``(默认 ``AGENT_HTTP_PORT=8766``),
    **不要**打 WS 口 ``AGENT_SERVER_PORT=18092``(对该口发 HTTP 会 426/400 且无 JSON)。
    """
    explicit = read_env("GATEWAY_RUNTIME_DEFAULT_HTTP_BASE", "").strip()
    if explicit:
        return explicit.rstrip("/")
    host = read_env("AGENT_SERVER_HOST", "127.0.0.1").strip() or "127.0.0.1"
    port = read_env("AGENT_HTTP_PORT", "8766").strip() or "8766"
    return f"http://{host}:{port}"


def identity_from_envelope(
    envelope: E2AEnvelope,
    *,
    authorized_identity: tuple[str, str, str] | None = None,
) -> tuple[str, str, str, str, str | None]:
    """返回 ``session_id, group_id, bot_id, request_id, user_id``。"""
    params = envelope.params if isinstance(envelope.params, dict) else {}
    ctx = envelope.channel_context if isinstance(envelope.channel_context, dict) else {}
    request_id = _first_text(envelope.request_id)
    user_id = _first_text(
        envelope.user_id,
        params.get("user_id"),
        _from_maps("user_id", params, ctx),
    ) or None
    group_id = _from_maps("group_id", params, ctx) or _first_text(envelope.chat_id)
    bot_id = _from_maps("bot_id", params, ctx)
    if not bot_id:
        bot_id = _from_maps("app_id", params, ctx)
    if not bot_id and isinstance(envelope.agent_ref, dict):
        bot_id = _first_text(
            envelope.agent_ref.get("bot_id"),
            envelope.agent_ref.get("agent_id"),
            envelope.agent_ref.get("id"),
        )
    if not bot_id:
        bot_id = _first_text(envelope.agent_id)
    # 如果 envelope 没带 group_id/bot_id/user_id,用默认值 route 到 wildcard scope
    if not user_id:
        user_id = "default"
    if not group_id:
        group_id = "default"
    if not bot_id:
        bot_id = "default"
    # 授权身份必须在合成 session key 前生效,不能仅覆盖最终路由参数。
    if authorized_identity is not None:
        group_id, bot_id, user_id = authorized_identity
    session_id = _first_text(envelope.session_id, params.get("session_id"))
    if not session_id and group_id and bot_id:
        session_id = f"{group_id}:{bot_id}:{user_id or '_'}"
    if not (session_id and group_id and bot_id and request_id):
        raise FatalRouteError(
            "route requires session_id/group_id/bot_id/request_id on envelope",
            code="VALIDATION",
        )
    return session_id, group_id, bot_id, request_id, user_id


def _is_http_retryable(exc: BaseException) -> bool:
    return isinstance(
        exc,
        (httpx.RequestError, httpx.HTTPStatusError, OSError, TimeoutError, asyncio.TimeoutError),
    )


class RuntimeRoutedAgentClient(AgentServerClient):
    """查 Runtime Manager 路由,再用 HTTP 客户端把信封发到对应 Pod。"""

    def __init__(
        self,
        *,
        route_client: RuntimeSessionRouteClient | None = None,
        http_client: HttpSseAgentServerClient | None = None,
        touch_interval_seconds: float = _TOUCH_INTERVAL_SECONDS,
        route_attempts: int = _ROUTE_ATTEMPTS,
    ) -> None:
        self._route = route_client or RuntimeSessionRouteClient()
        self._owns_route = route_client is None
        self._http = http_client or HttpSseAgentServerClient()
        self._owns_http = http_client is None
        self._touch_interval_seconds = max(0.0, float(touch_interval_seconds))
        self._route_attempts = max(1, int(route_attempts))
        self._connected = False
        self._on_server_push: Callable[[dict[str, Any]], Awaitable[None]] | None = None
        self._pod_clients: dict[str, HttpSseAgentServerClient] = {}
        # [PERF] 全局连接锁改 per-pod:10 个冷 Pod 首波建连由串行 ~0.3s×N 变并行 ~0.3s
        self._pod_connect_locks: dict[str, asyncio.Lock] = {}
        self._pod_locks_guard = asyncio.Lock()
        self._rpc_origins: dict[tuple[str, str], str] = {}
        self._drop_tasks: set[asyncio.Task[None]] = set()
        self._last_rebind_warn = 0.0   # rebind 降级告警节流(滚动期旧 runtime 404 防刷屏)

    def set_server_push_handler(
        self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None
    ) -> None:
        self._on_server_push = handler

    async def _handle_pod_push(self, base_url: str, wire: dict[str, Any]) -> None:
        from jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_chunk

        handler = self._on_server_push
        if handler is None:
            return
        chunk = parse_agent_server_wire_chunk(wire)
        payload = chunk.payload if isinstance(chunk.payload, dict) else {}
        rpc = payload.get("jsonrpc", payload)
        key = None
        if isinstance(rpc, dict) and rpc.get("id") is not None and rpc.get("method"):
            key = (str(wire.get("session_id") or ""), str(rpc["id"]))
            self._rpc_origins[key] = base_url
        try:
            await handler(wire)
        except BaseException:
            if key is not None:
                self._rpc_origins.pop(key, None)
            raise

    async def _pod_lock_for(self, base_url: str) -> asyncio.Lock:
        """[PERF] 按 Pod 取连接锁:不同 Pod 的建连互不阻塞。"""
        async with self._pod_locks_guard:
            lock = self._pod_connect_locks.get(base_url)
            if lock is None:
                lock = self._pod_connect_locks[base_url] = asyncio.Lock()
            return lock

    async def _ensure_pod_push(self, base_url: str) -> None:
        if self._on_server_push is None:
            return
        stale: HttpSseAgentServerClient | None = None
        async with await self._pod_lock_for(base_url):
            self._ensure_connected()
            client = self._pod_clients.get(base_url)
            # Fallback if push-done drop hasn't run yet (same IP reused).
            if client is not None and not getattr(client, "_running", True):
                stale = self._pod_clients.pop(base_url)
                client = None
            if client is None:
                client = HttpSseAgentServerClient(retry_push_connect=False)
                client.set_server_push_handler(
                    lambda wire: self._handle_pod_push(base_url, wire)
                )
                try:
                    await client.connect(base_url)
                    await client.wait_push_ready()
                except BaseException:
                    await client.disconnect()
                    raise
                self._pod_clients[base_url] = client
                client.add_push_done_callback(
                    lambda _task, url=base_url, bound=client: self._schedule_drop_pod_client(
                        url, bound
                    )
                )
        if stale is not None:
            try:
                await stale.disconnect()
            except Exception as exc:  # noqa: BLE001
                logger.warning(
                    "[RuntimeRouted] 断开旧 Pod 推送客户端失败: %s (%s)",
                    base_url,
                    exc,
                )
        await client.wait_push_ready()

    def _schedule_drop_pod_client(
        self, base_url: str, client: HttpSseAgentServerClient
    ) -> None:
        if not self._connected:
            return
        try:
            task = asyncio.get_running_loop().create_task(
                self._drop_pod_client(base_url, client),
                name="runtime-drop-pod-push",
            )
        except RuntimeError:
            return
        self._drop_tasks.add(task)
        task.add_done_callback(self._drop_tasks.discard)

    async def _drop_pod_client(
        self, base_url: str, client: HttpSseAgentServerClient
    ) -> None:
        async with await self._pod_lock_for(base_url):
            if self._pod_clients.get(base_url) is not client:
                return
            self._pod_clients.pop(base_url, None)
        logger.warning(
            "[RuntimeRouted] 推送循环已结束,丢弃客户端: %s",
            base_url,
        )
        try:
            await client.disconnect()
        except Exception as exc:  # noqa: BLE001
            logger.warning(
                "[RuntimeRouted] 断开旧 Pod 推送客户端失败: %s (%s)",
                base_url,
                exc,
            )


    async def connect(self, uri: str) -> None:
        _ = uri
        self._connected = True

    @property
    def server_ready(self) -> bool:
        """WebChannel on_connect 依赖此标志发送 connection.ack。"""
        return self._connected

    async def disconnect(self) -> None:
        self._connected = False
        async with self._pod_locks_guard:
            clients = list(self._pod_clients.values())
            self._pod_clients.clear()
            self._pod_connect_locks.clear()
        drop_tasks = list(self._drop_tasks)
        self._drop_tasks.clear()
        if drop_tasks:
            await asyncio.gather(*drop_tasks, return_exceptions=True)
        results = await asyncio.gather(
            *(client.disconnect() for client in clients),
            return_exceptions=True,
        )
        for result in results:
            if isinstance(result, Exception):
                logger.warning("Failed to disconnect routed push client: %s", result)
        self._rpc_origins.clear()
        if self._owns_http:
            try:
                await self._http.disconnect()
            except Exception as exc:
                logger.warning("Failed to disconnect HTTP client: %s", exc)
        if self._owns_route:
            try:
                await self._route.aclose()
            except Exception as exc:
                logger.warning("Failed to close route client: %s", exc)

    def _ensure_connected(self) -> None:
        if not self._connected:
            raise RuntimeError("client not connected")

    def _heartbeat_response(self, envelope: E2AEnvelope) -> AgentResponse:
        return AgentResponse(
            request_id=str(envelope.request_id or ""),
            channel_id=str(envelope.channel or "web"),
            ok=True,
            payload={},
        )

    async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:
        self._ensure_connected()
        authorized_identity = await authorize_agent(envelope)
        if envelope.method == "acp.tool_response":
            params = envelope.params or {}
            key = (
                str(envelope.session_id or params.get("session_id") or ""),
                str(params.get("jsonrpc_id") or ""),
            )
            base_url = self._rpc_origins.pop(key, None)
            if base_url is None:
                raise RuntimeError("Reverse RPC origin Pod is unavailable")
            return await self._http.send_request(envelope, base_url=base_url)
        if _is_heartbeat_envelope(envelope):
            return self._heartbeat_response(envelope)
        # 对齐旧 RuntimeManagement:发 Agent 前补齐并 MD5 service/agent/workspace。
        apply_invoke_ids_to_envelope(envelope)
        if _is_routeless_envelope(envelope):
            result = await self._http.send_request(envelope, base_url=_default_http_base())
            return result
        session_id, group_id, bot_id, request_id, user_id = identity_from_envelope(
            envelope, authorized_identity=authorized_identity,
        )
        base_url, route_id = await self._route_with_retry(
            session_id=session_id,
            group_id=group_id,
            bot_id=bot_id,
            request_id=request_id,
            user_id=user_id,
        )
        try:
            await self._ensure_pod_push(base_url)
            result = await self._http.send_request(envelope, base_url=base_url)
        except Exception as exc:
            if not _is_http_retryable(exc):
                raise
            logger.warning(
                "[RuntimeRouted] unary http failed, re-route: session=%s err=%s",
                session_id,
                exc,
            )
            base_url, route_id = await self._route_with_retry(
                session_id=session_id,
                group_id=group_id,
                bot_id=bot_id,
                request_id=uuid.uuid4().hex,
                user_id=user_id,
            )
            await self._ensure_pod_push(base_url)
            result = await self._http.send_request(envelope, base_url=base_url)
        await self._touch_quiet(session_id, route_id)
        await self._rebind_after_create(envelope, result, session_id)
        return result

    async def _rebind_after_create(
        self, envelope: E2AEnvelope, result: AgentResponse, session_id: str,
    ) -> None:
        """session.create 响应返回上层之前,把临时路由 key 原子改绑为真实 id。

        修复(runtime 侧 2026-09-session-create-rebind):create 以临时 key
        (sess_*/webhttp_*/身份组合串)route 占槽,真实 id 首条 chat.send 会二次
        占槽(双计数)且可能落别的 Pod(亲和断裂)。本方法在 ``send_request``
        返回前 await——**时序保证**:客户端拿到真实 id 时改绑已完成,chat.send
        不可能抢先。

        - 响应 ok:rebind(临时 key → 真实 id),亲和钉在 create 实际服务的 Pod;
        - 响应失败:rebind(临时 key → 空) 驱逐,立即释放槽位(不等 session_ttl);
        - 失败/超时一律降级(warning 节流 + 照常返回响应)=旧行为;旧 runtime
          (无 /api/session/rebind 端点)同走降级,滚动期不阻塞 create。
        """
        if str(envelope.method or "") != "session.create":
            return
        payload = result.payload if isinstance(result.payload, dict) else {}
        if result.ok:
            real = str(payload.get("session_id") or payload.get("sessionId") or "").strip()
        else:
            real = ""
        if real and real == session_id:
            return
        try:
            action = await asyncio.wait_for(
                self._route.rebind(
                    from_session_id=session_id,
                    to_session_id=real or None,
                    request_id=uuid.uuid4().hex,
                ),
                timeout=_rebind_timeout(),
            )
            logger.info(
                "[RuntimeRouted] session.create rebind: from=%s to=%s action=%s",
                session_id,
                real or "(evict)",
                action,
            )
        except Exception as exc:  # noqa: BLE001 - 降级=现状(临时 key 等 TTL 过期)
            now = time.monotonic()
            if now - self._last_rebind_warn >= 60.0:
                self._last_rebind_warn = now
                logger.warning(
                    "[RuntimeRouted] session.create rebind failed (degraded, "
                    "temp key expires via session_ttl): %s",
                    exc,
                )
            else:
                logger.debug(
                    "[RuntimeRouted] session.create rebind failed: %s", exc,
                )

    async def release_session(self, session_id: str) -> str | None:
        """立刻释放一条已结束的 Runtime 路由槽位(``rebind`` 的 ``to`` 为空)。

        定时任务跑完或审批续跑真正结束后调用。失败、超时、旧 Runtime 没有
        rebind 端点时只打日志并返回 ``None``,槽位退回按 ``session_ttl`` 过期,
        不把这次任务标成失败。会话已不在时 Runtime 返回 ``noop``。
        """
        sid = str(session_id or "").strip()
        if not sid:
            return None
        try:
            action = await asyncio.wait_for(
                self._route.rebind(
                    from_session_id=sid,
                    to_session_id=None,
                    request_id=uuid.uuid4().hex,
                ),
                timeout=_rebind_timeout(),
            )
            logger.info(
                "[RuntimeRouted] release session: session=%s action=%s",
                sid,
                action,
            )
            return action
        except Exception as exc:  # noqa: BLE001 - 降级=按 session_ttl 自然过期
            now = time.monotonic()
            if now - self._last_rebind_warn >= 60.0:
                self._last_rebind_warn = now
                logger.warning(
                    "[RuntimeRouted] release session failed (degraded, "
                    "slot expires via session_ttl): session=%s err=%s",
                    sid,
                    exc,
                )
            else:
                logger.debug(
                    "[RuntimeRouted] release session failed: session=%s err=%s",
                    sid,
                    exc,
                )
            return None

    async def send_request_stream(
        self, envelope: E2AEnvelope
    ) -> AsyncIterator[AgentResponseChunk]:
        self._ensure_connected()
        authorized_identity = await authorize_agent(envelope)
        if _is_heartbeat_envelope(envelope):
            yield AgentResponseChunk(
                request_id=str(envelope.request_id or ""),
                channel_id=str(envelope.channel or "web"),
                payload={},
                is_complete=True,
            )
            return
        # 对齐旧 RuntimeManagement:发 Agent 前补齐并 MD5 service/agent/workspace。
        apply_invoke_ids_to_envelope(envelope)
        if _is_routeless_envelope(envelope):
            async for chunk in self._http.send_request_stream(
                envelope, base_url=_default_http_base()
            ):
                yield chunk
            return
        session_id, group_id, bot_id, request_id, user_id = identity_from_envelope(
            envelope, authorized_identity=authorized_identity,
        )
        base_url, route_id = await self._route_with_retry(
            session_id=session_id,
            group_id=group_id,
            bot_id=bot_id,
            request_id=request_id,
            user_id=user_id,
        )
        yielded = 0
        try:
            async for chunk in self._stream_with_touch(
                envelope, base_url=base_url, session_id=session_id, route_id=route_id
            ):
                yielded += 1
                yield chunk
        except Exception as exc:
            if yielded or not _is_http_retryable(exc):
                raise
            logger.warning(
                "[RuntimeRouted] stream http failed before first chunk, re-route: session=%s err=%s",
                session_id,
                exc,
            )
            base_url, route_id = await self._route_with_retry(
                session_id=session_id,
                group_id=group_id,
                bot_id=bot_id,
                request_id=uuid.uuid4().hex,
                user_id=user_id,
            )
            async for chunk in self._stream_with_touch(
                envelope, base_url=base_url, session_id=session_id, route_id=route_id
            ):
                yield chunk
        finally:
            await self._touch_quiet(session_id, route_id)

    async def _stream_with_touch(
        self,
        envelope: E2AEnvelope,
        *,
        base_url: str,
        session_id: str,
        route_id: str,
    ) -> AsyncIterator[AgentResponseChunk]:
        last_touch = time.monotonic()
        await self._ensure_pod_push(base_url)
        async for chunk in self._http.send_request_stream(envelope, base_url=base_url):
            now = time.monotonic()
            if (
                self._touch_interval_seconds > 0
                and now - last_touch >= self._touch_interval_seconds
            ):
                touched = await self._touch_quiet(session_id, route_id)
                last_touch = now
                if touched is False:
                    logger.warning(
                        "[RuntimeRouted] touch expired mid-stream: session=%s",
                        session_id,
                    )
            yield chunk

    async def _route_with_retry(
        self,
        *,
        session_id: str,
        group_id: str,
        bot_id: str,
        request_id: str,
        user_id: str | None,
    ) -> tuple[str, str]:
        last_error: RetryableRouteError | None = None
        route_id = request_id
        for attempt in range(1, self._route_attempts + 1):
            try:
                result = await self._route.route(
                    session_id=session_id,
                    group_id=group_id,
                    bot_id=bot_id,
                    request_id=route_id,
                    user_id=user_id,
                )
                return http_base_from_pod_sse_url(result.pod_sse_url), result.request_id
            except RetryableRouteError as exc:
                last_error = exc
                delay = float(exc.retry_after) if exc.retry_after is not None else 1.0
                logger.warning(
                    "[RuntimeRouted] route retryable: code=%s attempt=%s/%s sleep=%.1fs",
                    exc.code,
                    attempt,
                    self._route_attempts,
                    delay,
                )
                if attempt >= self._route_attempts:
                    break
                await asyncio.sleep(delay)
        if last_error is None:
            raise RetryableRouteError("route failed", code="TRANSPORT")
        raise last_error

    async def _touch_quiet(self, session_id: str, request_id: str) -> bool | None:
        try:
            return await self._route.touch(session_id=session_id, request_id=request_id)
        except Exception:
            logger.warning(
                "[RuntimeRouted] touch failed: session=%s request_id=%s",
                session_id,
                request_id,
                exc_info=True,
            )
            return None