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
fix: 大文件拆分,将完全不属于这个类的内容拆出
hewenlif204458ee169
diff --git a/jiuwenswarm/server/runtime/agent_adapter/deep/model_factory.py b/jiuwenswarm/server/runtime/agent_adapter/deep/model_factory.pyindex 1a7d9fe3b9..a65dcb3966 100644--- a/jiuwenswarm/server/runtime/agent_adapter/deep/model_factory.py+++ b/jiuwenswarm/server/runtime/agent_adapter/deep/model_factory.py@@ -3,6 +3,7 @@from __future__ import annotationsimport hashlibimport json+import loggingimport refrom pathlib import Pathfrom typing import Any@@ -30,11 +31,11 @@ from jiuwenswarm.agents.harness.common.tools.multimodal_config import (from jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargsfrom jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.utils import DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL-import loggingfrom jiuwenswarm.server.runtime.agent_adapter.deep.pure_helpers import _normalize_reload_valuelogger = logging.getLogger(__name__)+def _mcc_looks_usable(mcc: dict) -> bool:"""检查 model_client_config 是否包含有效的 API 凭据。"""api_base = str(mcc.get("api_base", "") or "").strip()@@ -49,6 +50,7 @@ def _mcc_looks_usable(mcc: dict) -> bool:api_key = str(mcc.get("api_key", "") or "").strip()return bool(api_key)+def parse_int(value: Any, default: int) -> int:"""Parse integer-like values safely."""try:@@ -58,6 +60,7 @@ def parse_int(value: Any, default: int) -> int:except (TypeError, ValueError):return default+def _build_vision_model_config(config_base: dict[str, Any],) -> VisionModelConfig | None:@@ -122,6 +125,7 @@ def _build_vision_model_config(max_retries=parse_int(read_env("VISION_MAX_RETRIES"), 3),)+def _build_audio_model_config(config_base: dict[str, Any],) -> AudioModelConfig | None:@@ -169,6 +173,7 @@ def _build_audio_model_config(config_kwargs["question_answering_model"] = question_answering_modelreturn AudioModelConfig(**config_kwargs)+def _build_video_model_config(config_base: dict[str, Any],) -> bool:@@ -188,6 +193,7 @@ def _build_video_model_config(return Falsereturn True+def _build_image_gen_model_config(config_base: dict[str, Any],) -> bool:@@ -198,6 +204,7 @@ def _build_image_gen_model_config(return Falsereturn True+def _mask_model_secret(value: Any) -> str:text = str(value or "").strip()if not text:@@ -206,6 +213,7 @@ def _mask_model_secret(value: Any) -> str:return "***"return f"{text[:4]}***{text[-2:]}"+def _inject_model_selection_into_inputs(request: AgentRequest, inputs: dict[str, Any]) -> None:@@ -233,6 +241,7 @@ def _inject_model_selection_into_inputs("[JiuWenSwarmDeepAdapter] model_selection injected: value=%s", raw)+def _inject_model_routing_into_inputs(request: AgentRequest, inputs: dict[str, Any]) -> None:@@ -260,11 +269,13 @@ def _inject_model_routing_into_inputs("[JiuWenSwarmDeepAdapter] enable_routing injected: value=True")+def _stable_reload_fingerprint(value: Any) -> str:normalized = _normalize_reload_value(value)payload = json.dumps(normalized, sort_keys=True, ensure_ascii=False, default=str)return hashlib.sha256(payload.encode("utf-8")).hexdigest()+def _model_reload_fingerprint(deep_cfg: Any | None) -> str | None:if deep_cfg is None:return None@@ -283,6 +294,7 @@ def _model_reload_fingerprint(deep_cfg: Any | None) -> str | None:})+def _system_prompt_reload_fingerprint(deep_cfg: Any | None) -> str | None:if deep_cfg is None:return None@@ -297,6 +309,7 @@ def _system_prompt_reload_fingerprint(deep_cfg: Any | None) -> str | None:})+def _build_model_from_entry(mcc: dict, mco: dict) -> Model:"""根据单个模型条目的 model_client_config / model_config_obj 构建 Model 实例。"""name = mcc.get("model_name", "")@@ -392,6 +405,7 @@ def _build_model_from_entry(mcc: dict, mco: dict) -> Model:)return Model(model_client_config=ModelClientConfig(**mcc_fields), model_config=m_config)+def _models_config_fingerprint(config: dict) -> str:"""计算模型配置段的指纹,用于判断是否需要重建模型缓存。"""models = config.get("models", {})@@ -436,6 +450,7 @@ def _models_config_fingerprint(config: dict) -> str:)return hashlib.sha256(payload.encode("utf-8")).hexdigest()+def _prepare_multimodal_image_inputs(request: AgentRequest,inputs: dict[str, Any],@@ -457,6 +472,7 @@ def _prepare_multimodal_image_inputs()return updated+def _prepare_react_image_tool_prompt(request: AgentRequest,inputs: dict[str, Any],@@ -527,6 +543,7 @@ def _prepare_react_image_tool_prompt()return updated+def _build_image_tool_fallback_notice(request: AgentRequest,*,@@ -561,12 +578,14 @@ def _build_image_tool_fallback_notice(notice["model_name"] = model_namereturn notice+def _resolve_enable_read_image_multimodal(config: dict[str, Any]) -> bool:configured = config.get("enable_read_image_multimodal")if isinstance(configured, bool):return configuredreturn DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL+def _build_multimodal_image_rail(enable_image_multimodal: bool | None = None,) -> MultimodalImageRail | None:@@ -581,6 +600,7 @@ def _build_multimodal_image_rail(multimodal_image_rail = Nonereturn multimodal_image_rail+def _embedding_config_fingerprint(config: dict | None) -> str:"""计算 config.yaml embed 段的配置指纹,用于检测是否变化。@@ -602,6 +622,7 @@ def _embedding_config_fingerprint(config: dict | None) -> str:api_key_hash = hashlib.sha256(api_key.encode()).hexdigest()[:16]return f"{model}:{base_url}:{api_key_hash}"+def _model_looks_usable(model: Model | None) -> bool:if model is None:return False@@ -614,6 +635,7 @@ def _model_looks_usable(model: Model | None) -> bool:"client_provider": getattr(mcc_obj, "client_provider", None),})+def _build_messages_for_model(records: list[dict[str, Any]]) -> list[Any]:from openjiuwen.core.foundation.llm.schema.message import UserMessage, AssistantMessagediff --git a/jiuwenswarm/server/runtime/agent_adapter/deep/pure_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/deep/pure_helpers.pyindex 7c55d08954..4151f715e0 100644--- a/jiuwenswarm/server/runtime/agent_adapter/deep/pure_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/deep/pure_helpers.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncioimport json+import loggingimport operatorimport timefrom pathlib import Path@@ -56,17 +57,18 @@ from jiuwenswarm.agents.harness.common.auto_harness.service import _HARNESS_PACKfrom jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethodfrom jiuwenswarm.common.utils import get_user_workspace_dir-import logginglogger = logging.getLogger(__name__)# 进程内已完成卡一次性守卫:同 (session, goal) 只落盘一次;跨进程重复由磁盘检查兜底_GOAL_COMPLETED_PERSISTED: ClassVar[set[tuple[str, str]]] = set()+def _session_adapter_key(session_id: str | None) -> str:sid = str(session_id or "").strip()return sid or "default"+def _enterprise_resource_id_from_request(request: AgentRequest | None) -> str:"""Return the authenticated Agent resource id carried by a request."""if request is None:@@ -77,6 +79,7 @@ def _enterprise_resource_id_from_request(request: AgentRequest | None) -> str:identity = web_routing_identity(metadata)return str(identity.get("bot_id") or "").strip()+def _session_has_live_subagent_runtime(adapter: "JiuWenSwarmDeepAdapter",session_id: str,@@ -108,15 +111,18 @@ def _session_has_live_subagent_runtime()return True+def _session_adapter_lock_has_waiters(lock: asyncio.Lock) -> bool:# asyncio.Lock has no public waiter inspection; keep the lock if a reconnect is queued on it.waiters = getattr(lock, "_waiters", None)return any(not waiter.cancelled() for waiter in list(waiters or ()))+def _get_a2x_config(config_base: dict[str, Any]) -> dict[str, Any]:"""Resolve A2X config from ``react.a2x_registry`` with safe defaults."""return resolve_a2x_config(config_base)+def _is_related_session(target_sid: str, other_sid: str) -> bool:"""Return True when *other_sid* belongs to the same session tree as *target_sid*.@@ -132,6 +138,7 @@ def _is_related_session(target_sid: str, other_sid: str) -> bool:return Truereturn other_sid.startswith(f"{target_sid}_") or target_sid.startswith(f"{other_sid}_")+def _resolve_managed_browser_binary_from_config(config_base: dict[str, Any] | None = None,) -> str:@@ -142,6 +149,7 @@ def _resolve_managed_browser_binary_from_config(return resolve_managed_browser_binary(config_base)+def _resolve_headless_from_config(config_base: dict[str, Any] | None = None,) -> bool:@@ -150,6 +158,7 @@ def _resolve_headless_from_config(return resolve_headless(config_base)+def _leftover_request_mcp_servers(request_mcp_servers: dict[str, dict[str, Any]] | None,covered_names: list[str],@@ -164,6 +173,7 @@ def _leftover_request_mcp_servers(}return (leftover or None), dropped+def _inject_request_id_into_inputs(request: AgentRequest, inputs: dict[str, Any]) -> None:@@ -186,6 +196,7 @@ def _inject_request_id_into_inputs(if isinstance(run_extra, dict):run_extra["request_id"] = rid+def _normalize_reload_value(value: Any) -> Any:"""Normalize config-like values for stable hot-reload comparisons."""if value is None or isinstance(value, (str, int, float, bool)):@@ -217,6 +228,7 @@ def _normalize_reload_value(value: Any) -> Any:return _normalize_reload_value(vars(value))return repr(value)+def _restore_omitted_reload_fields(deep_cfg: DeepAgentConfig,omitted_fields: dict[str, Any],@@ -224,11 +236,13 @@ def _restore_omitted_reload_fields(for field_name, field_value in omitted_fields.items():setattr(deep_cfg, field_name, field_value)+def _inject_attribution_to_config(config: dict) -> None:"""Inject OpenRouter attribution headers into all model_client_config entries in-place."""from jiuwenswarm.common.openrouter_attribution import inject_attribution_to_configinject_attribution_to_config(config)+def _sys_operation_isolation_key(sysop_card: SysOperationCard) -> str | None:try:sys_operation = SysOperation(sysop_card)@@ -240,6 +254,7 @@ def _sys_operation_isolation_key(sysop_card: SysOperationCard) -> str | None:)return None+def _get_registered_sys_operation_by_isolation_key(isolation_key_template: str | None,) -> SysOperation | None:@@ -263,6 +278,7 @@ def _get_registered_sys_operation_by_isolation_key()return None+def _get_active_package_config_paths() -> list[str]:"""Read harness-packages.json to get config_path from active packages.@@ -304,6 +320,7 @@ def _get_active_package_config_paths() -> list[str]:return config_paths+def _resolve_skill_sleep_traces_dir() -> Path:"""Resolve OTel file-exporter traces dir for skill sleep harvest."""try:@@ -320,6 +337,7 @@ def _resolve_skill_sleep_traces_dir() -> Path:return Path(raw).expanduser()return get_user_workspace_dir() / ".trace"+async def _push_skill_sleep_published(*,skill_name: str,@@ -352,6 +370,7 @@ async def _push_skill_sleep_published(request_id,)+async def _push_skill_sleep_suggest(*,skill_name: str,@@ -384,6 +403,7 @@ async def _push_skill_sleep_suggest(request_id,)+def _ttse_consult_knobs(ttse_cfg: dict[str, Any]) -> tuple[int, str]:"""Parse live ``consult_top_k`` / ``consult_retrieve_mode`` from yaml."""try:@@ -405,6 +425,7 @@ def _ttse_consult_knobs(ttse_cfg: dict[str, Any]) -> tuple[int, str]:ttse_cfg.get("consult_retrieve_mode"))+def _coerce_circuit_breaker_threshold(value: object, default: int) -> int:try:parsed = int(value) # type: ignore[arg-type]@@ -414,6 +435,7 @@ def _coerce_circuit_breaker_threshold(value: object, default: int) -> int:return defaultreturn parsed+def _circuit_breaker_config_from_mapping(cb_cfg: dict,defaults: CircuitBreakerConfig,@@ -450,6 +472,7 @@ def _circuit_breaker_config_from_mapping(non_retryable_threshold=non_retryable,)+def _resolve_enable_task_loop(config: dict[str, Any], config_base: dict[str, Any] | None) -> bool:@@ -491,6 +514,7 @@ def _resolve_enable_task_loop(return Truereturn configured_value+def _reset_deepresearch_route_context(tokens: _RuntimeCronContextTokens) -> None:"""Reset one DeepResearch route token at most once."""route_token = tokens.deepresearch@@ -500,6 +524,7 @@ def _reset_deepresearch_route_context(tokens: _RuntimeCronContextTokens) -> Nonereset_deepresearch_route(token)route_token.token = None+def _run_cleanup_steps(steps: list[tuple[str, Callable[[], None]]],) -> BaseException | None:@@ -518,6 +543,7 @@ def _run_cleanup_steps()return first_error+def _reset_runtime_cron_context(tokens: _RuntimeCronContextTokens,*,@@ -577,6 +603,7 @@ def _reset_runtime_cron_context(if first_error is not None and not suppress_errors:raise first_error+def _acp_runtime_tools_enabled(request_metadata: dict[str, Any] | None,) -> tuple[bool, bool]:@@ -614,6 +641,7 @@ def _acp_runtime_tools_enabled(return fs_enabled, terminal_enabled+def _extract_request_system_prompt(request: AgentRequest | None) -> str | None:"""Read non-empty request.params.system_prompt."""if request is None or not isinstance(request.params, dict):@@ -625,6 +653,7 @@ def _extract_request_system_prompt(request: AgentRequest | None) -> str | None:return valuereturn None+def _extract_request_interactive_ask(request: AgentRequest | None) -> bool:"""Guided mode is params.interactive_ask opt-in; never infer from HITL capability."""from jiuwenswarm.server.runtime.skill_turbo.interactive_ask import (@@ -637,6 +666,7 @@ def _extract_request_interactive_ask(request: AgentRequest | None) -> bool:metadata = request.metadata if isinstance(getattr(request, "metadata", None), dict) else Nonereturn extract_interactive_ask(params, metadata)+def _resolve_eternal_conversation_enabled(params: Any) -> bool:"""Resolve the V1 frontend runtime flag; absent remains disabled."""if not isinstance(params, dict):@@ -648,6 +678,7 @@ def _resolve_eternal_conversation_enabled(params: Any) -> bool:return value.strip().casefold() in {"1", "true", "yes", "on", "enabled"}return bool(value)+def _is_eternal_interaction_resume(params: Any) -> bool:if not isinstance(params, dict):return False@@ -658,6 +689,7 @@ def _is_eternal_interaction_resume(params: Any) -> bool:# the eternal-conversation evidence chain.return str(params.get("source") or "").strip() in INTERRUPT_RESUME_SOURCES+def _cron_session_has_context(inner_session: Any) -> bool:"""检测 AgentSession 的 global_state['context'] 是否已带 messages。@@ -679,6 +711,7 @@ def _cron_session_has_context(inner_session: Any) -> bool:passreturn False+def _cron_execution_checkpointer(inner_session: Any) -> Any:"""cron 落盘用的是 session 自己的 checkpointer,恢复必须读同一份。"""getter = getattr(inner_session, "checkpointer", None)@@ -688,6 +721,7 @@ def _cron_execution_checkpointer(inner_session: Any) -> Any:return checkpointerreturn CheckpointerFactory.get_checkpointer()+def _has_uploaded_file(params: dict) -> bool:"""Whether the request params carry a user-uploaded file (new content)."""try:@@ -701,10 +735,14 @@ def _has_uploaded_file(params: dict) -> bool:return len(files) > 0if isinstance(files, dict):return bool(files.get("files"))- except Exception:- pass+ except Exception as exc:+ logger.debug(+ "[JiuWenSwarmDeepAdapter] uploaded file params are not parseable: %s",+ exc,+ )return False+def _new_usage_accumulator() -> dict[str, Any]:return {"input_tokens": 0,@@ -716,6 +754,7 @@ def _new_usage_accumulator() -> dict[str, Any]:"total_cost": 0.0,}+def _extract_usage_metadata(payload: Any) -> dict[str, Any] | None:"""Pull GLM/OpenAI usage numbers out of a SkillTurbo or adapter payload."""if not isinstance(payload, dict):@@ -732,12 +771,14 @@ def _extract_usage_metadata(payload: Any) -> dict[str, Any] | None:return inner if isinstance(inner, dict) else Nonereturn None+def _accumulate_usage(acc: dict[str, Any], usage_meta: dict[str, Any]) -> None:for token in ("input_tokens", "output_tokens", "total_tokens", "cache_tokens"):acc[token] += usage_meta.get(token, 0) or 0for cost in ("input_cost", "output_cost", "total_cost"):acc[cost] += usage_meta.get(cost, 0.0) or 0.0+def _extract_deepresearch_sdk_usage(payload: Any,) -> tuple[str, dict[str, Any]] | None:@@ -781,6 +822,7 @@ def _extract_deepresearch_sdk_usage(return Nonereturn usage_id, usage+def _account_deepresearch_sdk_usage(payload: Any,*,@@ -799,6 +841,7 @@ def _account_deepresearch_sdk_usage(record_deepresearch_sdk_token_usage(request_id, usage_id, usage)return True+def _format_llm_usage_summary(usage_accumulator: dict[str, Any]) -> dict[str, Any]:summary = {"input_tokens": usage_accumulator["input_tokens"],@@ -818,6 +861,7 @@ def _format_llm_usage_summary(usage_accumulator: dict[str, Any]) -> dict[str, Ansummary["total_cost"] = round(usage_accumulator["total_cost"], 6)return summary+def _skill_turbo_answers_to_confirm_payload(answers: list,resume_ctx: dict[str, Any],@@ -852,6 +896,7 @@ def _skill_turbo_answers_to_confirm_payload()return _SkillTurboConfirmPayload(approved=True)+def _select_registered_runtime_tool_names(runtime_tool_candidates: tuple[str, ...],ability_names: set[str],@@ -862,9 +907,11 @@ def _select_registered_runtime_tool_names(selected_names.append(name)return selected_names+def _resolve_interrupt_session_id(session_id: str | None) -> str:return (session_id or "default").strip() or "default"+def _append_cancelled_tools_to_history(request: AgentRequest,cancelled_tool_results: list[dict[str, Any]],@@ -897,6 +944,7 @@ def _append_cancelled_tools_to_history(mode=mode,)+def _approved_plan_exit_resume_tool_call_id(params: Any) -> str:"""返回已批准 plan-exit resume 对应的工具调用 ID。@@ -922,6 +970,7 @@ def _approved_plan_exit_resume_tool_call_id(params: Any) -> str:selected = str(options[0] or "").strip().lower()return tool_call_id if selected in approved_values else ""+def _should_fill_reasoning_only_empty_final(parsed: dict[str, Any] | None,*,@@ -939,6 +988,7 @@ def _should_fill_reasoning_only_empty_final(return Falsereturn not visible_text_since_last_final+def _apply_reasoning_only_empty_reply_fallback(*,has_streamed_content: bool,@@ -960,6 +1010,7 @@ def _apply_reasoning_only_empty_reply_fallback(return fallback_contentreturn reasoning_only_fallback+def _resolve_input_dispatch_mode(params: Any) -> InputDispatchMode | None:"""Map host ``input_mode`` / ``runtime_mode`` onto OpenJiuwen dispatch mode.@@ -977,9 +1028,11 @@ def _resolve_input_dispatch_mode(params: Any) -> InputDispatchMode | None:return InputDispatchMode.STEERreturn None+def _wants_attach_goal(params: Any) -> bool:return isinstance(params, dict) and params.get("attach_goal") is True+def _should_parse_tui_goal_slash(*,pending_goal_op: dict[str, Any] | None,@@ -994,6 +1047,7 @@ def _should_parse_tui_goal_slash(return Falsereturn isinstance(query, str)+def _parse_goal_slash_intent(query: str) -> dict[str, Any] | None:"""Parse ``/goal ...`` into an action dict without touching GoalManager."""text = query.strip()@@ -1011,6 +1065,7 @@ def _parse_goal_slash_intent(query: str) -> dict[str, Any] | None:return {"action": "set", "objective": ""}return {"action": "set", "objective": args}+def _is_subagent_approval_answer(request_id: str, params: Any) -> bool:"""子代理委托审批应答:显式 source 或 request_id 前缀(兼容旧通道)。"""source = str(params.get("source") or "").strip() if isinstance(params, dict) else ""@@ -1020,6 +1075,7 @@ def _is_subagent_approval_answer(request_id: str, params: Any) -> bool:("subagent_skill_load_", "subagent_tool_permission_"))+def _resolve_subagent_approval_answer(request: AgentRequest,request_id: str,@@ -1047,6 +1103,7 @@ def _resolve_subagent_approval_answer()return False+def _is_interrupt_resume_dispatch(params: Any) -> bool:"""HITL answers must inject into the existing interaction when possible.@@ -1078,6 +1135,7 @@ def _is_interrupt_resume_dispatch(params: Any) -> bool:return is_interrupt_evolution_approval_answer_payload(params)+def _structured_goal_op_from_request(request: AgentRequest,) -> dict[str, Any] | None:@@ -1107,6 +1165,7 @@ def _structured_goal_op_from_request(op[key] = int(value.strip())return op+def _is_interrupt_skill_evolution_approval_params(request_id: str, params: Any) -> bool:if not isinstance(params, dict):return False@@ -1118,6 +1177,7 @@ def _is_interrupt_skill_evolution_approval_params(request_id: str, params: Any)and _is_regular_skill_evolution_approval_params(params))+def _is_regular_skill_evolution_approval_params(params: Any) -> bool:if not isinstance(params, dict):return False@@ -1138,6 +1198,7 @@ def _is_regular_skill_evolution_approval_params(params: Any) -> bool:rail_kind = evolution_meta.get("rail_kind")return approval_kind in (None, "", "evolve") and rail_kind in (None, "", "regular")+async def _push_team_skill_evolve_resolution_status(request_id: str,*,@@ -1178,6 +1239,7 @@ async def _push_team_skill_evolve_resolution_status(exc,)+def _format_approval_summary(*,skill_name: str,@@ -1189,9 +1251,11 @@ def _format_approval_summary()return f"已为 Skill '{skill_name}' {action_label} {len(questions)} 条待审批内容:\n{summaries}"+def _generated_metric_id_key(skill_name: str, entry_id: str) -> str:return f"{skill_name}\0{entry_id}"+def _strip_skill_md_fence(text: str) -> str:"""Remove optional markdown code fences around a SKILL.md body."""content = str(text or "").strip()@@ -1204,6 +1268,7 @@ def _strip_skill_md_fence(text: str) -> str:lines = lines[:-1]return "\n".join(lines).strip()+async def _push_auto_rebuild_published_metric(job: AutoRebuildJob,*,@@ -1260,6 +1325,7 @@ async def _push_auto_rebuild_published_metric(exc,)+def _followup_response(action: str, followup_prompt: str, skill_name: str) -> dict[str, Any]:return {"action": action,@@ -1268,6 +1334,7 @@ def _followup_response(action: str, followup_prompt: str, skill_name: str) -> di"result_type": "followup",}+def _extract_followup_prompt(slash_result: dict[str, Any] | None) -> str | None:"""Return follow-up prompt when a slash command should continue as an agent turn."""if not isinstance(slash_result, dict):@@ -1280,12 +1347,14 @@ def _extract_followup_prompt(slash_result: dict[str, Any] | None) -> str | None:prompt = prompt.strip()return prompt or None+def _goal_record_payload(record: Any | None) -> dict[str, Any] | None:if record is None:return Noneto_dict = getattr(record, "to_dict", None)return to_dict() if callable(to_dict) else None+def _format_goal_control_message(action: str, goal: dict[str, Any] | None) -> str:if action == "get":return "No goal in this session." if goal is None else f"Goal: {goal.get('objective', '')}"@@ -1297,6 +1366,7 @@ def _format_goal_control_message(action: str, goal: dict[str, Any] | None) -> streturn "Goal resumed." if goal is not None else "No goal in this session."return "Goal set." if goal is not None else "Goal was not set."+def _record_goal_set_history_if_needed(request: AgentRequest,*,@@ -1331,6 +1401,7 @@ def _record_goal_set_history_if_needed(},)+def _goal_completed_history_exists(session_id: str, goal_id: str) -> bool:"""Return True when this session already persisted a completion card for goal_id."""message_id = f"goal-completed-{goal_id}"@@ -1351,6 +1422,7 @@ def _goal_completed_history_exists(session_id: str, goal_id: str) -> bool:)return False+def _record_goal_completed_history_if_needed(*,session_id: str,@@ -1401,6 +1473,7 @@ def _record_goal_completed_history_if_needed()_GOAL_COMPLETED_PERSISTED.add((sid, goal_id))+def _interaction_goal_updated_payload(payload: Any) -> dict[str, Any]:"""Normalize goal updates to the public Web/TUI payload shape."""from jiuwenswarm.server.runtime.agent_adapter.interface_deep import GOAL_UPDATED_EVENT_TYPE@@ -1416,6 +1489,7 @@ def _interaction_goal_updated_payload(payload: Any) -> dict[str, Any]:"goal": payload or None,}+def _valid_deepresearch_rewrite_request_id(request_id: object) -> bool:from jiuwenswarm.server.runtime.agent_adapter.interface_deep import _DEEPRESEARCH_REWRITE_REQUEST_ID_MAX_LENGTHreturn (@@ -1423,6 +1497,7 @@ def _valid_deepresearch_rewrite_request_id(request_id: object) -> bool:and 0 < len(request_id) <= _DEEPRESEARCH_REWRITE_REQUEST_ID_MAX_LENGTH)+def _deepresearch_rewrite_replay_conflict() -> RewriteFastPathResult:return RewriteFastPathResult(recognized=True,@@ -1439,6 +1514,7 @@ def _deepresearch_rewrite_replay_conflict() -> RewriteFastPathResult:commit_result=None,)+def _deepresearch_rewrite_publish_uncertain(target: RewriteHtmlTarget | None = None,) -> RewriteFastPathResult:@@ -1467,6 +1543,7 @@ def _deepresearch_rewrite_publish_uncertain(),)+def _deepresearch_rewrite_terminal_kind(result: RewriteFastPathResult,) -> str | None:@@ -1504,6 +1581,7 @@ def _deepresearch_rewrite_terminal_kind(return "success"return None+def _normalize_deepresearch_usage(value: object) -> dict[str, float] | None:keys = ("input_tokens",@@ -1534,6 +1612,7 @@ def _normalize_deepresearch_usage(value: object) -> dict[str, float] | None:normalized[key] = operator.getitem(raw, key)return normalized or None+def _deepresearch_usage_summary(usage: dict[str, float],) -> dict[str, float | str]:@@ -1552,6 +1631,7 @@ def _deepresearch_usage_summary(summary[cost] = round(usage[cost], 6)return summary+def _is_approval_event(evt) -> bool:"""Check whether an OutputSchema event is an approval request."""evt_type = getattr(evt, "type", "")diff --git a/jiuwenswarm/server/runtime/agent_adapter/deep/rail_factory.py b/jiuwenswarm/server/runtime/agent_adapter/deep/rail_factory.pyindex a7cdfd952d..437cc295d0 100644--- a/jiuwenswarm/server/runtime/agent_adapter/deep/rail_factory.py+++ b/jiuwenswarm/server/runtime/agent_adapter/deep/rail_factory.py@@ -3,6 +3,7 @@from __future__ import annotationsimport hashlibimport importlib+import loggingimport osimport threadingfrom typing import (@@ -27,7 +28,6 @@ from jiuwenswarm.common.mcp_config import (_positive_timeout_s,)from jiuwenswarm.common.schema.agent import AgentRequest-import logginglogger = logging.getLogger(__name__)@@ -39,6 +39,7 @@ _EXTRA_TOOLS_CACHE: dict[str, list[Any]] = {}_EXTRA_TOOLS_CACHE_LOCK = threading.Lock()+def _stage_request_mcp_tools(request: AgentRequest,server_name: str,@@ -81,6 +82,7 @@ def _stage_request_mcp_tools()buffers.pending_tools.append((tool, strict))+def _office_claw_thread_id_from_tools(tools: list[RequestScopedOfficeClawMcpTool],) -> str:@@ -96,6 +98,7 @@ def _office_claw_thread_id_from_tools(return thread_idreturn ""+def _is_sandbox_bound_rail(rail: Any) -> bool:"""动手类 rail:必须跟 deep_config / 沙箱 sysop,不能强制本地。"""if isinstance(rail, (SysOperationRail, SkillUseRail)):@@ -103,8 +106,11 @@ def _is_sandbox_bound_rail(rail: Any) -> bool:try:if isinstance(rail, ConcurrentSafeSysOperationRail):return True- except Exception:- pass+ except Exception as exc:+ logger.debug(+ "[JiuWenSwarmDeepAdapter] sandbox rail type check failed: %s",+ exc,+ )return type(rail).__name__ in {"SysOperationRail","FileSystemRail",@@ -113,6 +119,7 @@ def _is_sandbox_bound_rail(rail: Any) -> bool:"SkillUseRail",}+def _set_rail_sys_operation(rail: Any, sysop: SysOperation) -> bool:"""给单个 rail 写入 sys_operation;成功返回 True。"""setter = getattr(rail, "set_sys_operation", None)@@ -124,6 +131,7 @@ def _set_rail_sys_operation(rail: Any, sysop: SysOperation) -> bool:return Truereturn False+def _build_task_execution_rail() -> TaskExecutionRail | None:"""Build TaskExecutionRail for task.start/complete/update lifecycle events."""try:@@ -134,6 +142,7 @@ def _build_task_execution_rail() -> TaskExecutionRail | None:task_rail = Nonereturn task_rail+def _build_extension_config_debug_rail() -> Any | None:"""Build ExtensionConfigDebugRail when explicitly enabled.@@ -161,6 +170,7 @@ def _build_extension_config_debug_rail() -> Any | None:rail = Nonereturn rail+def _load_extra_rails_from_env() -> list[Any]:"""Load extra DeepAgentRails from AGENT_EXTRA_RAILS env var.@@ -205,6 +215,7 @@ def _load_extra_rails_from_env() -> list[Any]:)return extra_rails+def _load_extra_tools_from_env() -> list[Any]:"""Load extra tools from AGENT_EXTRA_TOOLS env var.@@ -264,6 +275,7 @@ def _load_extra_tools_from_env() -> list[Any]:)return extra_tools+def _build_heartbeat_rail() -> HeartbeatRail | None:"""Build HeartbeatRail."""try:@@ -274,6 +286,7 @@ def _build_heartbeat_rail() -> HeartbeatRail | None:heartbeat_rail = Nonereturn heartbeat_rail+def _build_avatar_rail() -> Any | None:"""Build AvatarPromptRail for digital avatar mode."""try:@@ -286,6 +299,7 @@ def _build_avatar_rail() -> Any | None:logger.warning("[JiuWenSwarmDeepAdapter] AvatarPromptRail create failed: %s", exc)return None+def _build_llm_retry_rail(config_base: dict[str, Any] | None = None) -> NotifyingLLMRetryRail | None:try:config_base = config_base or get_config()@@ -312,6 +326,7 @@ def _build_llm_retry_rail(config_base: dict[str, Any] | None = None) -> Notifyinlogger.warning("[JiuWenSwarmDeepAdapter] LLMRetryRail create failed: %s", exc)return None+def _build_work_plan_approval_rail() -> Any | None:"""构建 work plan 的审批 rail(``exit_plan_mode`` 即时弹窗)。"""try:@@ -326,6 +341,7 @@ def _build_work_plan_approval_rail() -> Any | None:)return None+def _should_register_acp_runtime_tools(channel_id: str | None,request_id: str | None,@@ -338,6 +354,7 @@ def _should_register_acp_runtime_tools(return Falsereturn has_runtime_capability+def _build_skill_protocol_prompt_rail() -> Any | None:"""构建 SkillProtocolPromptRail: 注入技能执行规范提示词。"""try:@@ -351,6 +368,7 @@ def _build_skill_protocol_prompt_rail() -> Any | None:logger.warning("[JiuWenSwarmDeepAdapter] SkillProtocolPromptRail create failed: %s", exc)return None+def _suspend_subagent_permission_rails(subagent: Any) -> Callable[[], None]:"""临时禁用 fallback 子代理继承的权限审批 rail,返回恢复函数。@@ -441,6 +459,7 @@ def _suspend_subagent_permission_rails(subagent: Any) -> Callable[[], None]:return restore+def find_team_skill_rail(request_id: str, channel_id: str | None = None):"""Find TeamSkillEvolutionRail that owns the given pending request_id."""try:diff --git a/jiuwenswarm/server/runtime/agent_adapter/deep/stream_parse.py b/jiuwenswarm/server/runtime/agent_adapter/deep/stream_parse.pyindex 7a88a983f1..e84bc15c17 100644--- a/jiuwenswarm/server/runtime/agent_adapter/deep/stream_parse.py+++ b/jiuwenswarm/server/runtime/agent_adapter/deep/stream_parse.py@@ -1,12 +1,19 @@"""解析 SDK / runner 的流式 chunk,生成对外事件、文本载荷和 HITL 相关判断。"""from __future__ import annotations+import loggingfrom typing import Anyfrom jiuwenswarm.server.runtime.agent_adapter.refusal_text_scrub import is_refusal_scrub_controlfrom jiuwenswarm.server.runtime.agent_adapter.todo_close_text_hold import is_todo_close_control-from jiuwenswarm.agents.harness.common.tools.deepresearch.deepresearch_rewrite_fast_path import RewriteFastPathResult-from jiuwenswarm.agents.harness.common.tools.deepresearch.deepresearch_rewrite_html_followup import RewriteHtmlFollowupResult-from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import convert_interactions_to_ask_user_question+from jiuwenswarm.agents.harness.common.tools.deepresearch.deepresearch_rewrite_fast_path import (+ RewriteFastPathResult,+)+from jiuwenswarm.agents.harness.common.tools.deepresearch.deepresearch_rewrite_html_followup import (+ RewriteHtmlFollowupResult,+)+from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (+ convert_interactions_to_ask_user_question,+)from jiuwenswarm.server.runtime.agent_adapter.subagent_stream import try_handle_subagent_chunkfrom jiuwenswarm.server.utils.stream_utils import (build_tool_result_payload,@@ -14,7 +21,6 @@ from jiuwenswarm.server.utils.stream_utils import (parse_ask_user_question_payload,)from jiuwenswarm.common.schema.agent import AgentResponseChunk-import loggingfrom jiuwenswarm.server.runtime.agent_adapter.deep.pure_helpers import (_extract_usage_metadata,_interaction_goal_updated_payload,@@ -22,6 +28,7 @@ from jiuwenswarm.server.runtime.agent_adapter.deep.pure_helpers import (logger = logging.getLogger(__name__)+def _propagate_stream_source_id(src_payload: Any, result: dict[str, Any] | None) -> dict[str, Any] | None:@@ -42,6 +49,7 @@ def _propagate_stream_source_id(result["task_id"] = task_id.strip()return result+def _rewrite_skill_turbo_usage_chunk(chunk: AgentResponseChunk,*,@@ -78,6 +86,7 @@ def _rewrite_skill_turbo_usage_chunk(usage_meta,)+def _iter_delta_for_unstreamed_final(*, content: str, chunk_payload: Any) -> list[dict[str, Any]]:@@ -100,6 +109,7 @@ def _iter_delta_for_unstreamed_final()return [payload]+def _drain_final_content_to_deltas(parsed: dict[str, Any],*,@@ -148,6 +158,7 @@ def _drain_final_content_to_deltas(parsed["content"] = ""return deltas+def _approval_chunk_from_event(event: Any) -> dict[str, Any] | None:parsed = _parse_stream_chunk(event)if not isinstance(parsed, dict) or parsed.get("event_type") != "chat.ask_user_question":@@ -160,6 +171,7 @@ def _approval_chunk_from_event(event: Any) -> dict[str, Any] | None:return Nonereturn parsed+def _fast_path_chunks(result: RewriteFastPathResult,*,@@ -191,6 +203,7 @@ def _fast_path_chunks(),)+def _rewrite_html_followup_chunks(result: RewriteHtmlFollowupResult,*,@@ -209,6 +222,7 @@ def _rewrite_html_followup_chunks(),)+def _stream_text_payload(event_type: str,content: Any,@@ -218,6 +232,7 @@ def _stream_text_payload(return Nonereturn {"event_type": event_type, "content": content}+def _is_ask_user_payload(payload: Any) -> bool:"""HITL 暂停判定:是否为会打断外层流的 checkpoint ask_user 卡片。@@ -233,6 +248,7 @@ def _is_ask_user_payload(payload: Any) -> bool:source = str(payload.get("source") or "").strip()return source not in {"subagent_skill_load", "subagent_tool_permission"}+def _is_hitl_suppress_noise_chunk(chunk: Any) -> bool:"""Metadata that may follow ask_user before the stream truly pauses.@@ -255,6 +271,7 @@ def _is_hitl_suppress_noise_chunk(chunk: Any) -> bool:return _run_failure(chunk) is Nonereturn False+def _apply_hitl_suppress_clear(chunk: Any,*,@@ -290,6 +307,7 @@ def _apply_hitl_suppress_clear()return False, False+def _run_failure(chunk) -> tuple[str, str] | None:"""Return ``(error_type, message)`` if *chunk* is a run-level terminal failure.@@ -352,6 +370,7 @@ def _run_failure(chunk) -> tuple[str, str] | None:return None+def _parse_stream_chunk(chunk,*,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 7471414d44..92e564ee35 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -3510,7 +3510,7 @@ class JiuWenSwarmDeepAdapter:session_id = str(getattr(request, "session_id", None) or "").strip()if not session_id:return- sid = self._session_adapter_key(session_id)+ sid = _session_adapter_key(session_id)if sid not in self._session_adapters:# Synthetic facade sessions (bff-*) never create a session adapter# on this root; keep the lazy next-turn behavior for them.