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(cron): 企业版 HTTP 补 server_push 订阅,并对齐单次任务判定
caozhenhua00006b8aeb597252
diff --git a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.pyindex 70f155f261..ed1addc67e 100644--- a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport contextvarsimport logging+import uuidfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom pathlib import Path@@ -10,7 +11,7 @@ from typing import Anyfrom zoneinfo import ZoneInfofrom openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard-from jiuwenswarm.gateway.cron.cron_expr import normalize_cron_expr+from jiuwenswarm.gateway.cron.cron_expr import is_oneshot_cron_expr, normalize_cron_exprfrom jiuwenswarm.gateway.cron.store import CronJobStore, _PROACTIVE_TICK_MODEfrom jiuwenswarm.gateway.cron.scheduler import _cron_next_push_dt, CronSchedulerServicefrom jiuwenswarm.gateway.cron.models import (@@ -416,9 +417,17 @@ class CronTools:async def create_job(self, params: dict[str, Any]) -> Any:normalized = dict(params or {})+ # 幂等:id 在 AgentServer 侧生成一次,随 push 下发(企业版)或直接写入+ # 本地 store(个人版)。Gateway 收到同一 id 时靠 already-exists 检查去重,+ # 避免多副本扇出导致重复落库。与个人版"id 在 AgentServer 生成"保持一致。+ job_id = str(normalized.get("id") or "").strip() or uuid.uuid4().hexnormalized.pop("session_id", None)normalized["targets"] = self._normalize_targets_param(normalized.get("targets"))normalized["cron_expr"] = normalize_cron_expr(str(normalized.get("cron_expr") or "").strip())+ # 与手动创建规格对齐:LLM 工具 schema 无 delete_after_run 字段,未显式传入时+ # 按 cron_expr 推断「单次」任务(年份为固定值),保证对话创建与手动创建一致。+ if "delete_after_run" not in normalized:+ normalized["delete_after_run"] = is_oneshot_cron_expr(normalized["cron_expr"])targets_str = normalized["targets"]logger.info("[CronTools] create_job: route(channel=%s session=%s request=%s) input.targets=%s normalized.targets=%s",@@ -485,7 +494,7 @@ class CronTools:if self._enterprise_ready():push_payload = {**normalized,- "id": str(normalized.get("id") or "").strip() or None,+ "id": job_id,"project_id": resolved_project_id,"work_mode": work_mode,**session_kw,@@ -497,7 +506,7 @@ class CronTools:return push_payloadjob = await self._local_store.create_job(- job_id=str(normalized.get("id") or "").strip() or None,+ job_id=job_id,name=str(normalized.get("name") or "").strip(),cron_expr=str(normalized.get("cron_expr") or "").strip(),timezone=str(normalized.get("timezone") or "Asia/Shanghai").strip() or "Asia/Shanghai",diff --git a/jiuwenswarm/gateway/cron/cron_expr.py b/jiuwenswarm/gateway/cron/cron_expr.pyindex 4588157b1a..f1d2b6affe 100644--- a/jiuwenswarm/gateway/cron/cron_expr.py+++ b/jiuwenswarm/gateway/cron/cron_expr.py@@ -1,6 +1,7 @@from __future__ import annotationsimport math+import refrom datetime import datetimefrom typing import Any@@ -57,6 +58,39 @@ def normalize_cron_expr(raw: str) -> str:)+def is_oneshot_cron_expr(expr: str) -> bool:+ """判断 7 字段 Quartz 表达式是否为「单次」,与前端 ``cronExprToSchedule`` 的+ ``once`` 判定逐条对齐:++ - 秒/分/时/日/月 均为单个非负整数(前端 ``parseSingleInt`` 即 ``/^\\d+$/``);+ - 周字段为通配(``*`` 或 ``?``,前端 ``isWildcard``);+ - 年份为单个固定整数(非通配)。++ 仅用于在 AgentServer 侧创建任务时补全缺失的 ``delete_after_run``,+ 使对话创建与手动创建的规格对齐。+ """+ parts = str(expr or "").strip().split()+ if len(parts) != 7:+ return False+ second, minute, hour, day, month, week, year = parts++ def _wildcard(field: str) -> bool:+ return field in ("*", "?")++ def _single_int(field: str) -> bool:+ # 与前端 parseSingleInt(/^\d+$/) 等价:仅 [0-9]++ return re.fullmatch(r"[0-9]+", field) is not None++ if _wildcard(year):+ return False+ if not _wildcard(week):+ return False+ return all(+ _single_int(f)+ for f in (second, minute, hour, day, month, year)+ )++def iso_to_seven_field_cron(at_iso: str, *, timezone: str) -> str:"""Convert ISO8601 datetime into 7-field cron (Quartz format):second minute hour day month dow year.diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.pyindex c5ad3adcc6..6a1368f7c6 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py@@ -8,7 +8,7 @@ import asyncioimport loggingimport timeimport uuid-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Awaitable, Callablefrom typing import Anyfrom urllib.parse import urlsplit@@ -184,6 +184,13 @@ class RuntimeRoutedAgentClient(AgentServerClient):self._touch_interval_seconds = max(0.0, float(touch_interval_seconds))self._route_attempts = max(1, int(route_attempts))self._connected = False+ # 企业版 HTTP 半双工:响应走 POST+SSE,AgentServer→Gateway 的主动 push+ # (cron.response / 文件下载 / evolution 等)必须额外订阅+ # GET /api/v1/events/stream。此处按 Pod(base_url)懒建订阅,对齐个人版+ # WebSocketAgentServerClient 天然具备的双向 push 能力。+ self._on_server_push: Callable[[dict[str, Any]], Awaitable[None]] | None = None+ self._push_clients: dict[str, HttpSseAgentServerClient] = {}+ self._push_lock = asyncio.Lock()async def connect(self, uri: str) -> None:_ = uri@@ -197,9 +204,72 @@ class RuntimeRoutedAgentClient(AgentServerClient):async def disconnect(self) -> None:self._connected = Falseif self._owns_http:- await self._http.disconnect()+ try:+ await self._http.disconnect()+ except Exception:+ logger.exception("[RuntimeRouted] 断开 HTTP 连接失败")+ push_clients = list(self._push_clients.values())+ self._push_clients.clear()+ for client in push_clients:+ try:+ await client.disconnect()+ except Exception:+ logger.exception("[RuntimeRouted] 断开 push 订阅失败")if self._owns_route:- await self._route.aclose()+ try:+ await self._route.aclose()+ except Exception:+ logger.exception("[RuntimeRouted] 关闭 route 失败")++ def set_server_push_handler(+ self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None+ ) -> None:+ """注册 AgentServer 主动推送(server_push)回调。++ 与个人版 ``WebSocketAgentServerClient.set_server_push_handler`` 语义一致,+ 供 ``MessageHandler`` 注入 ``_handle_agent_server_push``。企业版经 HTTP/SSE+ 通信,push 由每个 Pod 的 ``HttpSseAgentServerClient`` 单独订阅,故此处把+ 回调记录并同步到已建立的订阅客户端上。+ """+ self._on_server_push = handler+ for client in self._push_clients.values():+ client.set_server_push_handler(handler)++ async def _ensure_push_subscription(self, base_url: str) -> None:+ """懒建立到指定 AgentServer Pod 的 push(``GET /api/v1/events/stream``)订阅。++ 个人版 WS 天然双向,push 走同一条连接;企业版 HTTP 半双工,响应走+ POST+SSE,push 必须额外订阅。首次 route 到某 Pod 时为其建一个专用+ ``HttpSseAgentServerClient`` 订阅并复用;未注册回调或 Pod 已订阅则跳过。+ 订阅失败不阻断业务请求(route 已成功,下次请求会重试)。+ """+ if self._on_server_push is None:+ return+ base_url = (base_url or "").strip().rstrip("/")+ if not base_url or base_url in self._push_clients:+ return+ async with self._push_lock:+ if base_url in self._push_clients:+ return+ push_client = HttpSseAgentServerClient()+ try:+ await push_client.connect(base_url)+ push_client.set_server_push_handler(self._on_server_push)+ except Exception:+ logger.exception(+ "[RuntimeRouted] 建立 push 订阅失败,跳过: base_url=%s",+ base_url,+ )+ try:+ await push_client.disconnect()+ except Exception:+ logger.exception(+ "[RuntimeRouted] 断开失败的 push 订阅时出错: base_url=%s",+ base_url,+ )+ return+ self._push_clients[base_url] = push_client+ logger.info("[RuntimeRouted] 已建立 push 订阅: base_url=%s", base_url)def _ensure_connected(self) -> None:if not self._connected:@@ -230,6 +300,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):request_id=request_id,user_id=user_id,)+ await self._ensure_push_subscription(base_url)try:result = await self._http.send_request(envelope, base_url=base_url)except Exception as exc:@@ -247,6 +318,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):request_id=uuid.uuid4().hex,user_id=user_id,)+ await self._ensure_push_subscription(base_url)result = await self._http.send_request(envelope, base_url=base_url)await self._touch_quiet(session_id, route_id)return result@@ -279,6 +351,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):request_id=request_id,user_id=user_id,)+ await self._ensure_push_subscription(base_url)yielded = 0try:async for chunk in self._stream_with_touch(@@ -301,6 +374,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):request_id=uuid.uuid4().hex,user_id=user_id,)+ await self._ensure_push_subscription(base_url)async for chunk in self._stream_with_touch(envelope, base_url=base_url, session_id=session_id, route_id=route_id):