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

feat:enterprise分支代码回合dev-stable分支

liubuyu14b31153bc189
diff --git a/jiuwenswarm/agents/harness/common/rails/__init__.py b/jiuwenswarm/agents/harness/common/rails/__init__.py
index 01742685b2..fab6070a3a 100644
--- a/jiuwenswarm/agents/harness/common/rails/__init__.py
+++ b/jiuwenswarm/agents/harness/common/rails/__init__.py
@@ -20,6 +20,7 @@ from jiuwenswarm.agents.harness.common.rails.ask_user_rail import StructuredAskU
from jiuwenswarm.agents.harness.common.rails.multimodal_image_rail import MultimodalImageRail
from jiuwenswarm.agents.harness.common.rails.stream_event_rail import JiuSwarmStreamEventRail
from jiuwenswarm.agents.harness.common.rails.task_execution_rail import TaskExecutionRail
+from jiuwenswarm.agents.harness.common.rails.context_overflow_recovery_rail import ContextOverflowRecoveryRail
__all__ = [
"JiuSwarmStreamEventRail",
@@ -33,4 +34,5 @@ __all__ = [
"SymphonyOrchestrationRail",
"MemberSkillToolkitRail",
"StructuredAskUserRail",
+ "ContextOverflowRecoveryRail"
]
diff --git a/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py b/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py
new file mode 100644
index 0000000000..7bd1f71e63
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py
@@ -0,0 +1,273 @@
+# coding: utf-8
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import re
+from typing import Any, Optional
+
+from openjiuwen.core.context_engine.processor.compressor.full_compact_processor import (
+ FullCompactProcessor,
+)
+from openjiuwen.harness.rails.base import DeepAgentRail
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.core.common.logging import logger
+
+# 413 恢复时 threshold_override 占模型窗口的比例
+# 0.85 表示压缩后上下文最多占模型窗口的 85%,预留 15% 给 LLM 输出
+RECOVERY_THRESHOLD_RATIO = 0.85
+
+
+def _parse_token_limits(exc: Exception) -> tuple[int | None, int | None]:
+ """从 413 错误解析 limit_tokens 和 actual_tokens。
+
+ Returns: (actual_tokens, limit_tokens)
+ """
+ msg = str(exc)
+
+ # Anthropic: "prompt is too long: N tokens > M maximum"
+ m = re.search(r'(\d+)\s*tokens?\s*>\s*(\d+)', msg, re.IGNORECASE)
+ if m:
+ return int(m.group(1)), int(m.group(2))
+
+ # 华为: "prompt length N must less than maximum input length M"
+ m = re.search(r'prompt length\s+(\d+).*?maximum input length\s+(\d+)', msg, re.IGNORECASE)
+ if m:
+ return int(m.group(1)), int(m.group(2))
+
+ # OpenAI: "maximum context length is N"
+ m = re.search(r'maximum context length is\s+(\d+)', msg, re.IGNORECASE)
+ if m:
+ return None, int(m.group(1))
+
+ return None, None
+
+
+def _get_config_context_limit(ctx: AgentCallbackContext) -> int:
+ """从 config 读 context_window_limit_tokens 作为 fallback。
+
+ Returns 0 if not found (triggers circuit_break_with_model_hint).
+ """
+ agent = getattr(ctx, "agent", None)
+ if agent is None:
+ return 0
+ deep_config = getattr(agent, "deep_config", None)
+ if deep_config is None:
+ return 0
+ # context_window_limit_tokens 在 deep_config 或 yaml 中
+ limit = getattr(deep_config, "context_window_limit_tokens", None)
+ if isinstance(limit, int) and limit > 0:
+ return limit
+ return 0
+
+
+class ContextOverflowRecoveryRail(DeepAgentRail):
+ """Context overflow recovery chain (reactive + proactive bridge).
+
+ **Reactive** — when an LLM call fails with a context-overflow error (413, 400 with
+ "context_length_exceeded", etc.):
+ 1. **Detect** — keyword matching on the exception message.
+ 2. **SessionMemory** — force an incremental notes update (bypass trigger_tokens).
+ 3. **FullCompact** — set ``force_compact`` flag so the next ``get_context_window``
+ unconditionally triggers FullCompact (bypass ``trigger_total_tokens``).
+ 4. **Retry** — call ``ctx.request_retry()`` to re-enter the LLM call.
+ 5. **Circuit-break** — after ``max_recovery_attempts`` consecutive failures,
+ stop retrying and let the exception propagate with a clear user-facing message.
+ Priority: 100 (higher value = runs first; higher than StreamEventRail's 80
+ and ContextEngineeringRail's 85), so ``on_model_exception`` fires **before**
+ those rails.
+ """
+
+ priority = 100
+
+ def __init__(self, max_recovery_attempts: int = 2) -> None:
+ super().__init__()
+ self._max_recovery_attempts = max_recovery_attempts
+ self._consecutive_overflow_count: int = 0
+ self._context_engineering_rail: Optional[Any] = None
+ self._logged_missing_full_compact_bridge_api = False
+
+ # ------------------------------------------------------------------
+ # on_model_exception: core recovery logic
+ # ------------------------------------------------------------------
+
+ async def on_model_exception(self, ctx: AgentCallbackContext) -> None:
+ exc = ctx.exception
+ if exc is None or not self._is_context_overflow_error(exc):
+ return
+
+ self._consecutive_overflow_count += 1
+ actual_tokens, limit_tokens = _parse_token_limits(exc)
+ logger.warning(f"[ContextOverflowRecovery] Context overflow detected "
+ f"(attempt {self._consecutive_overflow_count}/{self._max_recovery_attempts}) "
+ f"actual_tokens={actual_tokens} limit_tokens={limit_tokens}")
+
+ if self._consecutive_overflow_count > self._max_recovery_attempts:
+ await self._circuit_break(ctx)
+ return
+
+ threshold_override = self._resolve_threshold_override(ctx, limit_tokens)
+ logger.warning(f"[ContextOverflowRecovery] Calculate threshold_override = {threshold_override}")
+ compact_success = self._set_force_compact_flag(ctx, threshold_override=threshold_override)
+
+ if compact_success:
+ ctx.request_retry(delay_seconds=0)
+ logger.info("[ContextOverflowRecovery] Recovery actions taken, requesting retry")
+ else:
+ logger.warning(f"[ContextOverflowRecovery] Could not set force_compact flag or compact context failed; "
+ f"retrying anyway (attempt {self._consecutive_overflow_count}/{self._max_recovery_attempts}"
+ f"threshold_override={threshold_override})")
+ ctx.request_retry(delay_seconds=0)
+
+ # ------------------------------------------------------------------
+ # after_model_call: reset counter on success
+ # ------------------------------------------------------------------
+
+ async def after_model_call(self, ctx: AgentCallbackContext) -> None:
+ if ctx.exception is None:
+ if self._consecutive_overflow_count > 0:
+ logger.info(
+ "[ContextOverflowRecovery] LLM call succeeded after %d overflow recovery attempt(s)",
+ self._consecutive_overflow_count,
+ )
+ self._consecutive_overflow_count = 0
+
+ # ------------------------------------------------------------------
+ # Detection: structured → status code → keyword fallback
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _is_context_overflow_error(exc: Exception) -> bool:
+ """判断异常是否为上下文溢出错误。
+ 1. status_code=413 — 明确的溢出语义,直接判定
+ 2. status_code=400 + 溢出关键词 — 400 状态码 对应多种错误类型(参数错误、权限错误等),必须结合关键词,
+ 才能区分出上下文溢出,避免误判
+ 3. 无 status_code + 溢出关键词兜底 — 非 SDK 标准异常的纯文本匹配
+ """
+ status_code = getattr(exc, "status_code", None)
+ exc_str = str(exc)
+ error_message_lower = exc_str.lower()
+
+ overflow_keys = (
+ "prompt is too long", # Anthropic 精确前缀
+ "input too long", # Anthropic 新格式
+ "context_length_exceeded", # OpenAI 标准 error code
+ "maximum context length", # OpenAI: "maximum context length is N"
+ "maximum input length", # 华为: "maximum input length M"
+ "must less than the maximum input",
+ "context length exceeded"
+ )
+ error_key = "Error code: 400"
+ error_code = "ModelArts.81001"
+ has_overflow_keyword = any(keyword in error_message_lower for keyword in overflow_keys)
+
+ if status_code == 413 or (status_code == 400 and has_overflow_keyword):
+ return True
+
+ # 无 status_code 但有溢出关键词
+ if status_code is None and has_overflow_keyword:
+ return True
+
+ if (error_key in error_message_lower) and (error_code in error_message_lower) and has_overflow_keyword:
+ return True
+
+ return False
+
+ @staticmethod
+ def _find_full_compact_processor(context: Any) -> Any | None:
+ if context is None:
+ logger.warning("[ContextOverflowRecovery] No context available when finding FullCompactProcessor")
+ return None
+
+ processors = getattr(context, "_processors", None)
+ if not processors:
+ logger.warning("[ContextOverflowRecovery] Context has no _processors when finding FullCompactProcessor")
+ return None
+ for processor in processors:
+ if isinstance(processor, FullCompactProcessor):
+ return processor
+ logger.warning(
+ "[ContextOverflowRecovery] No FullCompactProcessor found in context processors: %s",
+ [type(processor).__name__ for processor in processors],
+ )
+ return None
+
+ # ------------------------------------------------------------------
+ # threshold_override resolution
+ # ------------------------------------------------------------------
+
+ @classmethod
+ def _resolve_threshold_override(cls, ctx: AgentCallbackContext, parsed_limit: int | None) -> int | None:
+ """Compute threshold_override for FullCompact adaptive chain.
+
+ threshold_override = model_limit * RECOVERY_THRESHOLD_RATIO
+ 自适应模型窗口大小,按照比例设置压缩阈值。
+ """
+ if parsed_limit is not None:
+ return int(parsed_limit * RECOVERY_THRESHOLD_RATIO)
+
+ config_limit = _get_config_context_limit(ctx)
+ if config_limit > 0:
+ return int(config_limit * RECOVERY_THRESHOLD_RATIO)
+
+ # No parsed limit, no config — FullCompactProcessor will use default trigger_total_tokens
+ logger.info("[ContextOverflowRecovery] No limit parsed, no config limit; "
+ "FullCompactProcessor will use default trigger_total_tokens")
+ return None
+
+ # ------------------------------------------------------------------
+ # Set force_compact flag on FullCompactProcessor
+ # ------------------------------------------------------------------
+
+ def _set_force_compact_flag(self, ctx: AgentCallbackContext, *, threshold_override: int | None = None) -> bool:
+ """Set force_compact flag on the FullCompactProcessor attached to context."""
+ processor = self._find_full_compact_processor(ctx.context)
+ if processor is None:
+ return False
+
+ set_force_compact = getattr(processor, "set_force_compact", None)
+ if not callable(set_force_compact):
+ logger.warning(
+ "[ContextOverflowRecovery] FullCompactProcessor has no set_force_compact method"
+ )
+ return False
+
+ set_force_compact(True)
+ logger.info(
+ "[ContextOverflowRecovery] Set force_compact=True on %s",
+ type(processor).__name__,
+ )
+ if threshold_override is not None and hasattr(processor, "set_overflow_threshold_override"):
+ processor.set_overflow_threshold_override(threshold_override)
+ logger.info(f"[ContextOverflowRecovery] Set force_compact=True and "
+ f"threshold_override={threshold_override} on {type(processor).__name__}")
+ return True
+
+ # ------------------------------------------------------------------
+ # Circuit breaker: overflow recovery exhausted
+ # ------------------------------------------------------------------
+
+ async def _circuit_break(self, ctx: AgentCallbackContext) -> None:
+ logger.error(f"[ContextOverflowRecovery] Circuit breaker triggered after {self._consecutive_overflow_count} "
+ f"consecutive context overflow errors. Will not retry.")
+
+ session = ctx.session
+ if session is not None and hasattr(session, "write_stream"):
+ try:
+ from openjiuwen.core.session.stream import OutputSchema
+ await session.write_stream(
+ OutputSchema(
+ type="error",
+ payload={
+ "error_type": "context_overflow_circuit_break",
+ "message": (
+ f"上下文持续溢出(连续 {self._consecutive_overflow_count} 次),"
+ "自动压缩恢复失败。建议:/compact 手动压缩上下文,或开始新会话。"
+ ),
+ "consecutive_errors": self._consecutive_overflow_count,
+ },
+ )
+ )
+ self._consecutive_overflow_count = 0
+ except Exception as e:
+ logger.warning("[ContextOverflowRecovery] Failed to send circuit-break event: %s", e)
diff --git a/jiuwenswarm/extensions/extension_config_sync.py b/jiuwenswarm/extensions/extension_config_sync.py
new file mode 100644
index 0000000000..71764cd17f
--- /dev/null
+++ b/jiuwenswarm/extensions/extension_config_sync.py
@@ -0,0 +1,77 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""扩展配置加解密与持久化。"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+def extension_registry_crypto():
+ """从 ExtensionRegistry 取 CryptoProvider;未初始化或无扩展时返回 None。"""
+ from jiuwenswarm.extensions.registry import ExtensionRegistry
+
+ try:
+ return ExtensionRegistry.get_instance().get_crypto_provider()
+ except Exception:
+ return None
+
+
+def decrypt_extensions_sensitive_inplace(config_base: dict[str, Any]) -> None:
+ """就地解密 ``extensions.extension_security_configs``(磁盘上为密文)。"""
+ exts = config_base.get("extensions")
+ if not isinstance(exts, dict):
+ return
+ raw = exts.get("extension_security_configs")
+ if not isinstance(raw, str) or not raw.strip():
+ return
+ crypto = extension_registry_crypto()
+ if crypto is None:
+ return
+ try:
+ exts["extension_security_configs"] = crypto.decrypt(raw)
+ except Exception as exc:
+ logger.warning("[extension_config_sync] extension_security_configs 解密失败,保留密文: %s", exc)
+
+
+def decrypt_extensions_sensitive_for_agent(config_base: dict[str, Any]) -> dict[str, Any]:
+ """为发送给 AgentServer 解密敏感配置(返回副本,不修改原对象)。
+
+ 在 Gateway 端调用,解密 extension_security_configs 后发送给 AgentServer。
+ AgentServer 本身不能进行加解密操作,需要接收明文配置。
+ """
+ import copy
+ result = copy.deepcopy(config_base)
+ decrypt_extensions_sensitive_inplace(result)
+ return result
+
+
+def update_extensions_in_config(
+ extension_configs: str | None = None,
+ extension_security_configs: str | None = None,
+) -> None:
+ """更新扩展配置并写回 config.yaml。
+
+ Args:
+ extension_configs: 扩展配置字符串。
+ extension_security_configs: 敏感配置明文,落盘前会加密。
+ """
+ from jiuwenswarm.common.config import _CONFIG_YAML_PATH, _dump_yaml_round_trip, _load_yaml_round_trip
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
+ if "extensions" not in data or not isinstance(data["extensions"], dict):
+ data["extensions"] = {}
+ ext = data["extensions"]
+
+ if extension_configs is not None:
+ ext["extension_configs"] = extension_configs
+
+ if extension_security_configs is not None:
+ crypto = extension_registry_crypto()
+ if crypto is None:
+ raise RuntimeError("没有找到加解密算法,无法加密敏感配置")
+ ext["extension_security_configs"] = crypto.encrypt(extension_security_configs)
+
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
diff --git a/jiuwenswarm/extensions/registry.py b/jiuwenswarm/extensions/registry.py
index 3ab3498623..986aa79077 100644
--- a/jiuwenswarm/extensions/registry.py
+++ b/jiuwenswarm/extensions/registry.py
@@ -36,6 +36,9 @@ class ExtensionRegistry:
raise RuntimeError("ExtensionRegistry 尚未初始化,请先调用 create_instance()")
return cls._instance
+ def update_config(self, full_config) -> None:
+ self._config.config = full_config
+
@classmethod
def create_instance(
cls,
@@ -44,7 +47,8 @@ class ExtensionRegistry:
logger: Any,
) -> "ExtensionRegistry":
if cls._instance is not None:
- raise RuntimeError("ExtensionRegistry 已初始化,请勿重复调用 create_instance()")
+ logger.warning("ExtensionRegistry 已初始化,将返回已存在实例")
+ return cls._instance
cls._instance = cls(
callback_framework=callback_framework,
config=config,
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index 0dfa333704..fabe58178f 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -41,6 +41,7 @@ from jiuwenswarm.common.utils import (
prepare_workspace,
reset_free_search_runtime_flags,
)
+from jiuwenswarm.extensions.extension_config_sync import decrypt_extensions_sensitive_for_agent
# Ensure workspace initialized
_workspace_dir = get_user_workspace_dir()
@@ -1675,8 +1676,10 @@ async def _run(
"VISION_API_KEY",
}
try:
+ # 发送给 AgentServer 前解密扩展敏感配置
+ decrypted_config = decrypt_extensions_sensitive_for_agent(config_payload or {})
client.set_or_update_server_config(
- config=dict(config_payload or {}),
+ config=dict(decrypted_config),
env=dict(env_updates or {}),
)
@@ -1686,7 +1689,7 @@ async def _run(
req_method=ReqMethod.AGENT_RELOAD_CONFIG,
params={
# config: full config snapshot after save; Agent should prefer this over local yaml.
- "config": dict(config_payload or {}),
+ "config": dict(decrypted_config),
# env: incremental environment updates; missing keys mean unchanged.
"env": dict(env_updates or {}),
**dict(reload_options or {}),
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 7947edb4a8..064be737e3 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -103,6 +103,7 @@ from jiuwenswarm.agents.harness.common.auto_harness import AutoHarnessService
from jiuwenswarm.agents.harness.common.tools.web_file_download import build_file_download_info
from jiuwenswarm.common.version import __version__
from jiuwenswarm.common.local_env_config import decrypt, encrypt
+from jiuwenswarm.extensions.extension_config_sync import update_extensions_in_config
from jiuwenswarm.gateway.media_attachments import normalize_chat_media_attachments
from jiuwenswarm.gateway.document_attachments import (
coerce_document_parse_flag,
@@ -1950,6 +1951,22 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
except Exception as e:
logger.warning("[config.set] 写回 skill_retrieval 失败: %s", e)
+ ext_configs = params.get("extension_configs", None)
+ ext_security = params.get("extension_security_configs", None)
+ if not isinstance(ext_configs, str) and ext_configs is not None:
+ raise _ConfigBadRequest("extension_configs must be string")
+ if not isinstance(ext_security, str) and ext_security is not None:
+ raise _ConfigBadRequest("extension_security_configs must be string")
+ if ext_configs is not None or ext_security is not None:
+ try:
+ update_extensions_in_config(ext_configs, ext_security)
+ if ext_configs is not None:
+ yaml_updated.append("extension_configs")
+ if ext_security is not None:
+ yaml_updated.append("extension_security_configs")
+ except RuntimeError as e:
+ raise _ConfigInternalError(str(e)) from e
+
for env_key, value in env_updates.items():
os.environ[env_key] = value
if env_updates:
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 7ba8f8a024..62f7f1663c 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -7997,6 +7997,16 @@ class AgentWebSocketServer:
"""Public test helper that delegates to ACP tool-response handling."""
await self._handle_acp_tool_response(ws, request, send_lock)
+ def is_working(self) -> bool:
+ """返回 Agent 是否正在工作.
+
+ 用于沙箱保活校验。
+
+ Returns:
+ bool: 是否正在工作
+ """
+ return self._agent_manager.is_working()
+
async def _handle_harness_packages_get(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
) -> None:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/agent_adapters.py b/jiuwenswarm/server/runtime/agent_adapter/agent_adapters.py
index 6ad59610ea..aff89e013f 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/agent_adapters.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/agent_adapters.py
@@ -96,6 +96,18 @@ class AgentAdapter(Protocol):
async def handle_heartbeat(self, request: AgentRequest) -> AgentResponse:
"""Handle heartbeat requests."""
+ def is_working(self, session_tasks: dict, session_queues: dict) -> bool:
+ """Return whether the agent is currently working.
+
+ Args:
+ session_tasks: Dict of session_id -> asyncio.Task
+ session_queues: Dict of session_id -> asyncio.PriorityQueue
+
+ Returns:
+ bool: True if agent is working, False otherwise.
+ """
+ ...
+
def resolve_sdk_choice() -> str:
"""Resolve SDK choice from environment variable.
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 70e42af429..0556ced1e4 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -155,6 +155,7 @@ from jiuwenswarm.agents.harness.common.rails import (
StructuredAskUserRail,
SymphonyOrchestrationRail,
TaskExecutionRail,
+ ContextOverflowRecoveryRail,
)
from jiuwenswarm.agents.harness.common.rails.execution_guard import (
CircuitBreakerRail,
@@ -1507,6 +1508,7 @@ class JiuWenSwarmDeepAdapter:
self._skill_retrieval_tools_registered: bool = False
self._skill_retrieval_tools: list[Any] = []
self._skill_retrieval_prompt_rail: SkillRetrievalPromptRail | None = None
+ self._context_overflow_recovery_rail: ContextOverflowRecoveryRail | None = None
self._skill_manager: SkillManager | None = None
self._a2x_client: Any | None = None
self._a2x_config: dict[str, Any] = {}
@@ -4763,6 +4765,17 @@ class JiuWenSwarmDeepAdapter:
stream_event_rail = None
return stream_event_rail
+ @staticmethod
+ def _build_context_overflow_recovery_rail() -> ContextOverflowRecoveryRail | None:
+ """Build ContextOverflowRecoveryRail."""
+ try:
+ recovery_rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ logger.info("[JiuWenClawDeepAdapter] ContextOverflowRecoveryRail create success")
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] ContextOverflowRecoveryRail create failed: %s", exc)
+ recovery_rail = None
+ return recovery_rail
+
@staticmethod
def _build_task_execution_rail() -> TaskExecutionRail | None:
"""Build TaskExecutionRail for task.start/complete/update lifecycle events."""
@@ -5230,6 +5243,7 @@ class JiuWenSwarmDeepAdapter:
_RailBuildInfo("_task_planning_rail", self._build_task_planning_rail),
_RailBuildInfo("_security_rail", self._build_security_rail),
_RailBuildInfo("_heartbeat_rail", self._build_heartbeat_rail),
+ _RailBuildInfo("_context_overflow_recovery_rail", self._build_context_overflow_recovery_rail),
_RailBuildInfo(
"_llm_retry_rail",
self._build_llm_retry_rail,
@@ -6153,6 +6167,16 @@ class JiuWenSwarmDeepAdapter:
else:
config_base = resolve_env_vars(config_base)
+ # 同步扩展配置到 ExtensionRegistry
+ # Gateway 已解密 extension_security_configs,AgentServer 直接使用明文
+ try:
+ from jiuwenswarm.extensions.registry import ExtensionRegistry
+ registry = ExtensionRegistry.get_instance()
+ registry.update_config(config_base)
+ logger.info("[JiuWenSwarm] Extension config synced to Registry")
+ except Exception as exc:
+ logger.warning("[JiuWenSwarm] ExtensionRegistry update failed: %s", exc)
+
self._config_base_cache = config_base.copy()
self._refresh_multimodal_configs(config_base)
self._config_cache = config_base.get("react", {}).copy()
@@ -8099,6 +8123,56 @@ class JiuWenSwarmDeepAdapter:
self._resolve_model_by_name(requested_model_name)
)
+ @classmethod
+ def is_working(cls, session_tasks: dict[str, asyncio.Task],
+ session_queues: dict[str, asyncio.PriorityQueue]) -> bool:
+ """返回 Agent 是否正在工作.
+
+ 用于沙箱保活校验,一旦发现任何活跃状态立即返回 True.
+
+ 判断维度:
+ 1. 非流式任务:_session_tasks 中正在执行的 Task
+ 2. 待处理消息:_session_queues 中队列的消息数
+ 3. Team 流式任务:TeamManager._stream_tasks 中正在执行的 Team 模式流式任务
+ 4. Team monitors:TeamManager._team_monitors 中正在运行的监控处理器
+ 5. ACP 待响应请求:AcpOutputManager._pending 中等待用户响应的 ACP 工具请求
+
+ Returns:
+ bool: 是否正在工作
+ """
+ # 检查正在执行的非流式任务
+ for task in session_tasks.values():
+ if task is not None and not task.done():
+ return True
+
+ # 检查队列中待处理的消息
+ for queue in session_queues.values():
+ if queue.qsize() > 0:
+ return True
+
+ # 检查 Team 模式下的流式任务和 monitors
+ try:
+ from jiuwenswarm.agents.harness.team import get_team_manager
+ team_manager = get_team_manager()
+ for task in team_manager._stream_tasks.values(): # pylint: disable=protected-access
+ if task is not None and not task.done():
+ return True
+ for monitor in team_manager._team_monitors.values(): # pylint: disable=protected-access
+ if monitor is not None and monitor.is_running:
+ return True
+ except Exception:
+ pass
+
+ # 检查 ACP 待响应请求
+ try:
+ from jiuwenswarm.agents.harness.common.tools.acp_output_tools import get_acp_output_manager
+ if len(get_acp_output_manager()._pending) > 0: # pylint: disable=protected-access
+ return True
+ except Exception:
+ pass
+
+ return False
+
async def handle_user_answer(self, request: AgentRequest) -> AgentResponse:
"""Handle chat.user_answer request."""
if not self._is_session_scoped_adapter:
diff --git a/jiuwenswarm/server/runtime/session/session_manager.py b/jiuwenswarm/server/runtime/session/session_manager.py
index e836d47dee..7a6e1a216b 100644
--- a/jiuwenswarm/server/runtime/session/session_manager.py
+++ b/jiuwenswarm/server/runtime/session/session_manager.py
@@ -37,6 +37,14 @@ class SessionManager:
"""获取 session_id,默认为 'default'."""
return session_id or "default"
+ def get_session_tasks(self) -> dict[str, asyncio.Task]:
+ """返回 session_id -> asyncio.Task 映射(用于工作状态判定)."""
+ return self._session_tasks
+
+ def get_session_queues(self) -> dict[str, asyncio.PriorityQueue]:
+ """返回 session_id -> asyncio.PriorityQueue 映射(用于工作状态判定)."""
+ return self._session_queues
+
@staticmethod
def _is_oneshot_session(session_id: str) -> bool:
"""判断是否为一次性 session(心跳/定时任务),其 session_id 永不复用.
diff --git a/jiuwenswarm/server/runtime/tenant_agent_pool.py b/jiuwenswarm/server/runtime/tenant_agent_pool.py
index 4836991d1f..3415591f58 100644
--- a/jiuwenswarm/server/runtime/tenant_agent_pool.py
+++ b/jiuwenswarm/server/runtime/tenant_agent_pool.py
@@ -154,3 +154,7 @@ class TenantAgentPool:
logger.info("[TenantAgentPool] Cleaning up...")
await self._agent_manager.cleanup()
logger.info("[TenantAgentPool] Cleanup complete")
+
+ def is_working(self) -> bool:
+ """返回是否有任何租户 Agent 正在工作."""
+ return self._agent_manager.is_working()