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
Merge remote-tracking branch 'upstream/dev-stable' into dev-stable
jdfff5a7d09fef220
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.pyindex 6128962747..234c6b6b71 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py@@ -23,6 +23,7 @@ from jiuwenswarm.common.schema.ask_user import (from .stream_router import _format_outline_card_markdownfrom .tools import _call_deepresearch_stream_impl+from .usage import normalize_workflow_llm_token_usagelogger = logging.getLogger(__name__)@@ -637,7 +638,9 @@ def _outline_sections(outline_text: str) -> list[str]:]-def _completion_content(state: Mapping[str, Any], report_chars: Any) -> str:+def _completion_content(+ state: Mapping[str, Any], report_chars: Any, html_style_status: Any = None+) -> str:file_name = str(state.get("file_name") or "研究报告").strip()title = re.sub(r"\.(?:md|markdown)$", "", file_name, flags=re.IGNORECASE)lines = [@@ -663,6 +666,14 @@ def _completion_content(state: Mapping[str, Any], report_chars: Any) -> str:f" {index}. {section}"for index, section in enumerate(normalized_sections, start=1))+ if html_style_status == "fallback":+ lines.extend(+ [+ "",+ "⚠️ HTML 已交付内置基础视觉模板,但 AI 生成的增强样式未应用;"+ "Markdown 报告内容不受影响。",+ ]+ )lines.extend(["",@@ -822,9 +833,38 @@ async def _handle_outcome()if status == "completed" and outcome.get("report_delivered") is True:report_chars = outcome.get("report_chars")- content = _completion_content(state, report_chars)- state = _persist(context, state, "completed", conversation_id=conversation_id)- return _result("completed", state, content=content)+ html_style_status = outcome.get("html_style_status")+ if html_style_status not in {"applied", "fallback"}:+ html_style_status = None+ html_style_phase = outcome.get("html_style_phase")+ html_style_reason_code = outcome.get("html_style_reason_code")+ if (+ html_style_status != "fallback"+ or not isinstance(html_style_phase, str)+ or not isinstance(html_style_reason_code, str)+ ):+ html_style_phase = None+ html_style_reason_code = None+ content = _completion_content(state, report_chars, html_style_status)+ completed_updates: dict[str, Any] = {"conversation_id": conversation_id}+ if html_style_status is not None:+ completed_updates["html_style_status"] = html_style_status+ if html_style_phase is not None:+ completed_updates["html_style_phase"] = html_style_phase+ completed_updates["html_style_reason_code"] = html_style_reason_code+ state = _persist(context, state, "completed", **completed_updates)+ result_fields: dict[str, Any] = {"content": content}+ if html_style_status is not None:+ result_fields["html_style_status"] = html_style_status+ if html_style_phase is not None:+ result_fields["html_style_phase"] = html_style_phase+ result_fields["html_style_reason_code"] = html_style_reason_code+ workflow_usage = normalize_workflow_llm_token_usage(+ outcome.get("workflow_llm_token_usage")+ )+ if workflow_usage is not None:+ result_fields["workflow_llm_token_usage"] = workflow_usage+ return _result("completed", state, **result_fields)if status == "cancelled":state = _persist(context, state, "cancelled", conversation_id=conversation_id)return _result("cancelled", state, content="DeepResearch 任务已取消。")diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/rewrite_tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/rewrite_tools.pyindex 6e2fcb6298..3a38b8a8d4 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/rewrite_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/rewrite_tools.py@@ -398,6 +398,9 @@ async def _deliver_report(async def _deliver_html(html_path: Path,route: dict[str, object],+ html_style_status: str | None = None,+ html_style_phase: str | None = None,+ html_style_reason_code: str | None = None,) -> bool:if not route.get("session_id") or not route.get("channel_id"):return False@@ -406,14 +409,29 @@ async def _deliver_html()transport = WebSocketGatewayPushTransport()+ payload: dict[str, object] = {+ "event_type": "chat.file",+ "files": [{"path": str(html_path), "name": html_path.name}],+ }+ metadata: dict[str, object] = {}+ if html_style_status in {"applied", "fallback"}:+ metadata["htmlStyleStatus"] = html_style_status+ if (+ html_style_status == "fallback"+ and isinstance(html_style_phase, str)+ and isinstance(html_style_reason_code, str)+ ):+ metadata.update({+ "htmlStylePhase": html_style_phase,+ "htmlStyleReasonCode": html_style_reason_code,+ })+ if metadata:+ payload["metadata"] = metadataawait transport.send_push({"request_id": route.get("request_id", ""),"channel_id": route["channel_id"],"session_id": route["session_id"],- "payload": {- "event_type": "chat.file",- "files": [{"path": str(html_path), "name": html_path.name}],- },+ "payload": payload,"is_complete": False,})return True@@ -548,7 +566,7 @@ async def deepresearch_generate_rewrite_html(})try:- html_path = await _generate_report_html(+ generated_html = await _generate_report_html(export["final_result"],Path(export["report_path"]),export["final_result"]["response_content"],@@ -558,7 +576,22 @@ async def deepresearch_generate_rewrite_html("deepresearch rewrite HTML generation failed: type=%s",type(exc).__name__,)- html_path = None+ generated_html = None+ html_style_status = None+ html_style_phase = None+ html_style_reason_code = None+ if isinstance(generated_html, tuple) and len(generated_html) == 4:+ (+ html_path,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ ) = generated_html+ elif isinstance(generated_html, tuple):+ html_path, html_style_status = generated_html+ else:+ # Preserve compatibility with older private callers and test doubles.+ html_path = generated_htmlif html_path is None:return json.dumps({"status": "error",@@ -569,7 +602,13 @@ async def deepresearch_generate_rewrite_html(})try:- delivered = await _deliver_html(html_path, route)+ delivered = await _deliver_html(+ html_path,+ route,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ )except Exception as exc: # pylint: disable=broad-exception-caughtlogger.error("deepresearch rewrite HTML delivery failed: type=%s",@@ -583,11 +622,21 @@ async def deepresearch_generate_rewrite_html("error": "HTML delivery failed; the Markdown rewrite remains available",})- return json.dumps({+ result = {"status": "completed","html_delivered": True,"delivery_status": "delivered",- })+ }+ if html_style_status in {"applied", "fallback"}:+ result["html_style_status"] = html_style_status+ if (+ html_style_status == "fallback"+ and isinstance(html_style_phase, str)+ and isinstance(html_style_reason_code, str)+ ):+ result["html_style_phase"] = html_style_phase+ result["html_style_reason_code"] = html_style_reason_code+ return json.dumps(result)__all__ = [diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.pyindex 380d22f820..fed422414c 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py@@ -45,6 +45,25 @@ _BRIDGE_ZIP_MEMBER_MAX_BYTES = 64 * 1024 * 1024_BRIDGE_JSON_MAX_DEPTH = 64_BRIDGE_JSON_MAX_NODES = 100_000_BRIDGE_JSON_MAX_CONTAINER = 20_000+_BRIDGE_REQUEST_SCHEMA_VERSION = 2+_STYLE_PHASES = frozenset({+ "build_style_context",+ "apply_prompt",+ "invoke_llm",+ "extract_css_response",+ "normalize_css_output",+ "append_cover_title_contrast_safeguard",+ "inject_css",+})+_STYLE_REASON_CODES = frozenset({+ "style_context_failed",+ "style_prompt_failed",+ "llm_call_failed",+ "css_response_invalid",+ "css_response_empty",+ "css_safeguard_failed",+ "css_injection_failed",+})class DeepResearchRuntimeError(RuntimeError):@@ -59,6 +78,17 @@ class _BridgeArtifact:descriptor: int+@dataclass(frozen=True, slots=True)+class StyledReportArchiveResult:+ """Validated report archive plus the SDK's styling outcome."""++ path: Path+ style_applied: bool+ style_status: str+ style_phase: str | None = None+ style_reason_code: str | None = None++def _virtualenv_root(executable: Path) -> Path | None:root = executable.parent.parentreturn root if (root / "pyvenv.cfg").is_file() else None@@ -194,12 +224,15 @@ def _remove_bridge_artifact(artifact: _BridgeArtifact) -> None:def _encode_bridge_request(final_result: dict[str, Any],llm_config: dict[str, Any],+ llm_auth: dict[str, str],tls: dict[str, bool],) -> bytes:+ _validate_bridge_llm_auth(llm_auth)request = {- "schema_version": 1,+ "schema_version": _BRIDGE_REQUEST_SCHEMA_VERSION,"final_result": final_result,"llm_config": llm_config,+ "llm_auth": llm_auth,"tls": tls,}_validate_json_tree(request)@@ -217,6 +250,34 @@ def _encode_bridge_request(return payload+def _validate_bridge_llm_auth(llm_auth: object) -> None:+ if not isinstance(llm_auth, dict):+ raise DeepResearchRuntimeError("sdk_bridge_request_invalid")+ if not llm_auth:+ return+ if set(llm_auth) != {"default_headers"}:+ raise DeepResearchRuntimeError("sdk_bridge_request_invalid")+ raw_headers = llm_auth.get("default_headers")+ if not isinstance(raw_headers, str) or not raw_headers.strip():+ raise DeepResearchRuntimeError("sdk_bridge_request_invalid")+ try:+ headers = json.loads(raw_headers)+ except (TypeError, ValueError) as exc:+ raise DeepResearchRuntimeError("sdk_bridge_request_invalid") from exc+ if not isinstance(headers, dict):+ raise DeepResearchRuntimeError("sdk_bridge_request_invalid")+ authorization = [+ value+ for key, value in headers.items()+ if isinstance(key, str) and key.lower() == "authorization"+ ]+ if len(headers) != 1 or len(authorization) != 1:+ raise DeepResearchRuntimeError("sdk_bridge_request_invalid")+ authorization_value = authorization[0]+ if not isinstance(authorization_value, str) or not authorization_value.strip():+ raise DeepResearchRuntimeError("sdk_bridge_request_invalid")++def _validate_json_tree(value: object) -> None:stack: list[tuple[object, int]] = [(value, 0)]visited: set[int] = set()@@ -347,14 +408,15 @@ async def stylize_report_archive(*,final_result: dict[str, Any],llm_config: dict[str, Any],+ llm_auth: dict[str, str],tls: dict[str, bool],manager: Any,session_id: str,-) -> AsyncIterator[Path]:+) -> AsyncIterator[StyledReportArchiveResult]:"""Yield one validated private SDK ZIP and clean it after installation."""executable = resolve_python_executable()script = _bridge_script()- payload = _encode_bridge_request(final_result, llm_config, tls)+ payload = _encode_bridge_request(final_result, llm_config, llm_auth, tls)artifact = _create_bridge_artifact()process = Nonetracked = False@@ -397,17 +459,24 @@ async def stylize_report_archive(result = json.loads(decoded)except ValueError as exc:raise DeepResearchRuntimeError("sdk_bridge_protocol_invalid") from exc- expected = {+ required = {"schema_version","status","output_path","style_applied","style_status",}+ optional = {"style_phase", "style_reason_code"}+ result_keys = set(result) if isinstance(result, dict) else set()+ style_phase = result.get("style_phase") if isinstance(result, dict) else None+ style_reason_code = (+ result.get("style_reason_code") if isinstance(result, dict) else None+ )invalid_result = (returncode != 0or not isinstance(result, dict)- or set(result) != expected+ or not required.issubset(result_keys)+ or not result_keys.issubset(required | optional)or not isinstance(result.get("schema_version"), int)or isinstance(result.get("schema_version"), bool)or result.get("schema_version").__class__ is not int@@ -416,11 +485,36 @@ async def stylize_report_archive(or result.get("output_path") != str(artifact.path)or not isinstance(result.get("style_applied"), bool)or result.get("style_status") not in {"applied", "fallback"}+ or (style_phase is None) != (style_reason_code is None)+ or (+ style_phase is not None+ and (+ not isinstance(style_phase, str)+ or style_phase not in _STYLE_PHASES+ )+ )+ or (+ style_reason_code is not None+ and (+ not isinstance(style_reason_code, str)+ or style_reason_code not in _STYLE_REASON_CODES+ )+ )+ or (+ result.get("style_status") != "fallback"+ and style_phase is not None+ ))if invalid_result:raise DeepResearchRuntimeError("sdk_bridge_failed")_validate_bridge_output(artifact)- yield artifact.path+ yield StyledReportArchiveResult(+ path=artifact.path,+ style_applied=result["style_applied"],+ style_status=result["style_status"],+ style_phase=style_phase,+ style_reason_code=style_reason_code,+ )except asyncio.CancelledError:if process is not None:cleanup = asyncio.create_task(_stop_bridge_process(process))@@ -441,6 +535,7 @@ async def stylize_report_archive(__all__ = ["DeepResearchRuntimeError",+ "StyledReportArchiveResult","build_child_env","resolve_python_executable","stylize_report_archive",diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.pyindex a7a4b5c11c..fabfd3d8bc 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/sdk_bridge.py@@ -28,7 +28,26 @@ BRIDGE_JSON_MAX_CONTAINER = 20_000BRIDGE_ZIP_MAX_MEMBERS = 1024BRIDGE_ZIP_MEMBER_MAX_BYTES = 64 * 1024 * 1024BRIDGE_ZIP_TOTAL_MAX_BYTES = 128 * 1024 * 1024+BRIDGE_REQUEST_SCHEMA_VERSION = 2_TLS_KEYS = frozenset({"LLM_SSL_VERIFY", "TOOL_SSL_VERIFY"})+_STYLE_PHASES = frozenset({+ "build_style_context",+ "apply_prompt",+ "invoke_llm",+ "extract_css_response",+ "normalize_css_output",+ "append_cover_title_contrast_safeguard",+ "inject_css",+})+_STYLE_REASON_CODES = frozenset({+ "style_context_failed",+ "style_prompt_failed",+ "llm_call_failed",+ "css_response_invalid",+ "css_response_empty",+ "css_safeguard_failed",+ "css_injection_failed",+})class BridgeError(RuntimeError):@@ -90,6 +109,7 @@ def read_request(stream: BinaryIO) -> dict[str, object]:"schema_version","final_result","llm_config",+ "llm_auth","tls",}:raise BridgeError("bridge_request_invalid")@@ -99,10 +119,14 @@ def read_request(stream: BinaryIO) -> dict[str, object]:and not isinstance(schema_version, bool)and schema_version.__class__ is int)- if not is_exact_schema_version_type or schema_version != 1:+ if (+ not is_exact_schema_version_type+ or schema_version != BRIDGE_REQUEST_SCHEMA_VERSION+ ):raise BridgeError("bridge_request_invalid")if not isinstance(request["final_result"], dict) or not isinstance(request["llm_config"], dict):raise BridgeError("bridge_request_invalid")+ _validate_llm_auth(request["llm_auth"])tls = request["tls"]invalid_tls = (not isinstance(tls, dict)@@ -114,6 +138,34 @@ def read_request(stream: BinaryIO) -> dict[str, object]:return request+def _validate_llm_auth(llm_auth: object) -> None:+ if not isinstance(llm_auth, dict):+ raise BridgeError("bridge_request_invalid")+ if not llm_auth:+ return+ if set(llm_auth) != {"default_headers"}:+ raise BridgeError("bridge_request_invalid")+ raw_headers = llm_auth.get("default_headers")+ if not isinstance(raw_headers, str) or not raw_headers.strip():+ raise BridgeError("bridge_request_invalid")+ try:+ headers = json.loads(raw_headers)+ except (TypeError, ValueError) as exc:+ raise BridgeError("bridge_request_invalid") from exc+ if not isinstance(headers, dict):+ raise BridgeError("bridge_request_invalid")+ authorization = [+ value+ for key, value in headers.items()+ if isinstance(key, str) and key.lower() == "authorization"+ ]+ if len(headers) != 1 or len(authorization) != 1:+ raise BridgeError("bridge_request_invalid")+ authorization_value = authorization[0]+ if not isinstance(authorization_value, str) or not authorization_value.strip():+ raise BridgeError("bridge_request_invalid")++def _decode_archive(convert_content: object) -> bytes:if not isinstance(convert_content, str):raise BridgeError("bridge_archive_invalid")@@ -238,19 +290,50 @@ async def stylize_request(request: dict[str, object], output: str | Path) -> dicfor key in _TLS_KEYS:os.environ[key] = "true" if tls[key] else "false"with redirect_stdout(sys.stderr):- from openjiuwen_deepsearch.algorithm.report_style.service import stylize_report- from openjiuwen_deepsearch.framework.openjiuwen.llm.report_style_runtime import report_style_llm_context+ from jiuwenswarm.common.local_env_config import (+ bind_task_env_overlay,+ reset_task_env_overlay,+ )+ from jiuwenswarm.llm_sse_patch import apply_openai_auth_header_patch++ llm_auth = request["llm_auth"]+ if __debug__ and not isinstance(llm_auth, dict):+ raise AssertionError()+ auth_token = bind_task_env_overlay(llm_auth)+ try:+ apply_openai_auth_header_patch()+ from openjiuwen_deepsearch.algorithm.report_style.service import stylize_report+ from openjiuwen_deepsearch.framework.openjiuwen.llm.report_style_runtime import report_style_llm_context- llm_config = _sdk_llm_config(request["llm_config"])- async with report_style_llm_context(llm_config) as llm:- result = await stylize_report(request["final_result"], llm)+ llm_config = _sdk_llm_config(request["llm_config"])+ async with report_style_llm_context(llm_config) as llm:+ result = await stylize_report(request["final_result"], llm)+ finally:+ reset_task_env_overlay(auth_token)write_convert_content(output, getattr(result, "convert_content", None))+ style_status = str(getattr(result, "style_status", "fallback"))+ style_phase = getattr(result, "style_phase", None)+ style_reason_code = getattr(result, "style_reason_code", None)+ valid_style_fallback = style_status == "fallback"+ if valid_style_fallback:+ valid_style_fallback = isinstance(style_phase, str)+ if valid_style_fallback:+ valid_style_fallback = style_phase in _STYLE_PHASES+ if valid_style_fallback:+ valid_style_fallback = isinstance(style_reason_code, str)+ if valid_style_fallback:+ valid_style_fallback = style_reason_code in _STYLE_REASON_CODES+ if not valid_style_fallback:+ style_phase = None+ style_reason_code = Nonereturn {"schema_version": 1,"status": "completed","output_path": str(Path(output)),"style_applied": bool(getattr(result, "style_applied", False)),- "style_status": str(getattr(result, "style_status", "fallback")),+ "style_status": style_status,+ "style_phase": style_phase,+ "style_reason_code": style_reason_code,}except BridgeError:raisediff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.pyindex 16c777ed74..a1498fd758 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py@@ -431,11 +431,20 @@ def _stage_snapshot_frames(state: RouterState, *, complete: bool = False) -> lis}return [task_update,- {"event_type": "chat.reasoning", **message},{"event_type": "chat.delta", **message},]+def _stage_completion_frame(stage: int) -> dict:+ title = DEEPRESEARCH_STAGES[stage - 1]+ return {+ "event_type": "chat.delta",+ "task_id": f"deepresearch_stage_{stage}",+ "task_content": title,+ "content": f"[DeepResearch 阶段完成] Stage {stage}:{title}\n",+ }++def advance_stage(state: RouterState, stage: int, *, complete: bool = False) -> list[dict]:"""Advance monotonically and emit every missing Stage-facing snapshot."""if complete:@@ -452,6 +461,8 @@ def advance_stage(state: RouterState, stage: int, *, complete: bool = False) ->frames: list[dict] = []for next_stage in range(state.current_stage + 1, stage + 1):+ if state.current_stage > 0:+ frames.append(_stage_completion_frame(state.current_stage))state.current_stage = next_stageframes.extend(_stage_snapshot_frames(state))return framesdiff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.pyindex 4a49a49559..de61ab7a9c 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py@@ -19,6 +19,7 @@ import timeimport unicodedataimport uuidimport zipfile+from collections.abc import AsyncIterator, Awaitable, Callable, Mappingfrom contextlib import contextmanager, suppressfrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -58,6 +59,9 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch.todo_progress import (deepresearch_todo_path,persist_deepresearch_task_update,)+from jiuwenswarm.agents.harness.common.tools.deepresearch.usage import (+ normalize_workflow_llm_token_usage,+)from jiuwenswarm.agents.harness.common.tools.deepresearch_task_manager import (extract_deepresearch_section_titles,get_deepresearch_manager,@@ -67,6 +71,7 @@ from jiuwenswarm.common.config import get_configfrom jiuwenswarm.common.local_env_config import (build_effective_env_overlay,get_task_env_overlay,+ parse_default_headers,)from jiuwenswarm.common.utils import (JIUWENSWARM_SHARED_SKILLS_DIRS_ENV,@@ -84,9 +89,11 @@ DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES = 16 * 1024 * 1024DEEPRESEARCH_STDERR_TAIL_MAX_BYTES = 20_000DEEPRESEARCH_ERROR_TEXT_MAX_CHARS = 2048DEEPRESEARCH_STDERR_OUTCOME_MAX_CHARS = 2048+_HUAWEI_MAAS_PLACEHOLDER_API_KEY = "huawei-maas-session"DEEPRESEARCH_STREAM_JSON_MAX_DEPTH = 64DEEPRESEARCH_STREAM_JSON_MAX_NODES = 100_000DEEPRESEARCH_STREAM_JSON_MAX_TEXT_CHARS = 16 * 1024 * 1024+DEEPRESEARCH_FINAL_REPORT_PROGRESS_INTERVAL_SECONDS = 60.0DEEPRESEARCH_OUTLINE_CACHE_TENANTS = 256DEEPRESEARCH_OUTLINE_CACHE_CONVERSATIONS = 128DEEPRESEARCH_OUTLINE_CACHE_TITLES = 128@@ -265,6 +272,11 @@ _TIMED_SDK_NODES = frozenset({"brief_mermaid_generator","brief_source_tracer",})+_RESUME_NODE_CURRENT_STAGE = {+ "feedback_handler": 1,+ "outline_interaction": 2,+ "user_feedback_processor": 3,+}def push_deepresearch_route(@@ -523,9 +535,11 @@ def _build_deepresearch_request_config(return config-def _build_styled_export_llm_config() -> dict[str, dict[str, object]]:+def _build_styled_export_llm_config(+ runtime_config: Mapping[str, str] | None = None,+) -> dict[str, dict[str, object]]:"""Build the exact JSON-safe LLM config consumed by the isolated SDK."""- resolved = load_deepresearch_config()+ resolved = load_deepresearch_config(runtime_config)api_key = str(resolved.get("LLM_API_KEY", "")).strip()model_name = str(resolved.get("LLM_MODEL_NAME", "")).strip()base_url = str(resolved.get("LLM_BASE_URL", "")).strip()@@ -555,6 +569,41 @@ def _build_styled_export_llm_config() -> dict[str, dict[str, object]]:}+def _build_styled_export_llm_auth(+ runtime_config: Mapping[str, str],+ llm_config: Mapping[str, object],+) -> dict[str, str]:+ """Carry only request-scoped MaaS Authorization into the style child."""+ general = llm_config.get("general")+ api_key = (+ str(general.get("api_key", "") or "").strip()+ if isinstance(general, Mapping)+ else ""+ )+ if api_key != _HUAWEI_MAAS_PLACEHOLDER_API_KEY:+ return {}++ headers = parse_default_headers(+ str(runtime_config.get("default_headers", "") or "")+ )+ authorization = [+ value+ for key, value in (headers or {}).items()+ if key.lower() == "authorization" and value.strip()+ ]+ if len(authorization) != 1:+ raise ValueError(+ "styled HTML Huawei MaaS Authorization is unavailable"+ )+ return {+ "default_headers": json.dumps(+ {"Authorization": authorization[0]},+ ensure_ascii=False,+ separators=(",", ":"),+ )+ }++def _build_deepresearch_child_env(*,interactive_ask: bool,@@ -898,6 +947,41 @@ async def _iter_ndjson_lines(yield bytes(pending)+async def _await_with_periodic_progress(+ awaitable: Awaitable[Any],+ progress: Callable[[], Awaitable[None]],+) -> Any:+ """Wait without cancelling the underlying operation on each progress tick."""+ pending = asyncio.ensure_future(awaitable)+ try:+ while True:+ done, _ = await asyncio.wait(+ {pending},+ timeout=DEEPRESEARCH_FINAL_REPORT_PROGRESS_INTERVAL_SECONDS,+ )+ if done:+ return pending.result()+ await progress()+ finally:+ if not pending.done():+ pending.cancel()+ with suppress(BaseException):+ await pending+++async def _iter_with_periodic_progress(+ lines: AsyncIterator[bytes],+ progress: Callable[[], Awaitable[None]],+) -> AsyncIterator[bytes]:+ iterator = lines.__aiter__()+ while True:+ try:+ line = await _await_with_periodic_progress(anext(iterator), progress)+ except StopAsyncIteration:+ return+ yield line++def _interaction_answer_has_user_input(item: Any) -> bool:if not isinstance(item, dict):return True@@ -2025,7 +2109,11 @@ async def _consume_stream(if isinstance(existing_state, RouterState)else RouterState(section_titles=dict(cached_titles),- current_stage=(1 if action == "resume" and node == "feedback_handler" else 0),+ current_stage=(+ _RESUME_NODE_CURRENT_STAGE.get(node, 0)+ if action == "resume"+ else 0+ ),final_report_started=(action == "resume" and node == "user_feedback_processor"),@@ -2086,6 +2174,18 @@ async def _consume_stream("error": "no terminal marker",}first_sdk_node_ns: int | None = None+ report_delivery_settled = False++ async def send_final_report_progress() -> None:+ if not state.final_report_started or report_delivery_settled:+ return+ await send(+ {+ "event_type": "chat.processing_status",+ "is_processing": True,+ "current_task": "in_progress",+ }+ )def terminal_timing(chunk: dict[str, Any]) -> dict[str, Any] | None:timing = chunk.get("timing")@@ -2107,11 +2207,14 @@ async def _consume_stream(result["timing"] = timingreturn result- async for raw in _iter_ndjson_lines(- proc.stdout,- request_id=str(route.get("request_id") or ""),- session_id=str(route.get("session_id") or ""),- conversation_id=conversation_id,+ async for raw in _iter_with_periodic_progress(+ _iter_ndjson_lines(+ proc.stdout,+ request_id=str(route.get("request_id") or ""),+ session_id=str(route.get("session_id") or ""),+ conversation_id=conversation_id,+ ),+ send_final_report_progress,):try:line = raw.decode("utf-8").strip()@@ -2270,11 +2373,14 @@ async def _consume_stream("error": "Markdown report file route is unavailable",}, chunk)try:- artifacts = await _write_report_artifacts_stream(- final_result,- file_name,- str(chunk.get("conversation_id") or outcome_cid),- _normalize_citation_artifacts(chunk),+ artifact_result = await _await_with_periodic_progress(+ _write_report_artifacts_stream(+ final_result,+ file_name,+ str(chunk.get("conversation_id") or outcome_cid),+ _normalize_citation_artifacts(chunk),+ ),+ send_final_report_progress,)except Exception as exc: # pylint: disable=broad-exception-caughtreturn attach_terminal_timing({@@ -2283,6 +2389,21 @@ async def _consume_stream("error_code": "report_file_write_failed","error": type(exc).__name__,}, chunk)+ html_style_phase = None+ html_style_reason_code = None+ if isinstance(artifact_result, tuple) and len(artifact_result) == 4:+ (+ artifacts,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ ) = artifact_result+ elif isinstance(artifact_result, tuple):+ artifacts, html_style_status = artifact_result+ else:+ # Preserve compatibility with private test doubles and older callers.+ artifacts = artifact_result+ html_style_status = Nonefiles = [{"path": value, "name": Path(value).name}for value in artifacts.values()@@ -2293,8 +2414,20 @@ async def _consume_stream(}markdown_index = list(artifacts).index("md")bundle = _build_related_artifact_bundle(chunk, markdown_index)+ file_metadata: dict[str, Any] = {}if bundle:- file_payload["metadata"] = {"artifactBundle": bundle}+ file_metadata["artifactBundle"] = bundle+ if html_style_status in {"applied", "fallback"}:+ file_metadata["htmlStyleStatus"] = html_style_status+ if (+ html_style_status == "fallback"+ and isinstance(html_style_phase, str)+ and isinstance(html_style_reason_code, str)+ ):+ file_metadata["htmlStylePhase"] = html_style_phase+ file_metadata["htmlStyleReasonCode"] = html_style_reason_code+ if file_metadata:+ file_payload["metadata"] = file_metadataif not await send(file_payload):return attach_terminal_timing({"status": "error",@@ -2303,14 +2436,44 @@ async def _consume_stream("error": "Report files could not be delivered","report_path": artifacts.get("md", ""),}, chunk)+ report_delivery_settled = Truefor payload in advance_stage(state, 4, complete=True):await send(payload)- return attach_terminal_timing({+ completed_outcome: dict[str, Any] = {"status": "completed","conversation_id": chunk.get("conversation_id", outcome_cid),"report_delivered": True,"report_chars": len(response_content),- }, chunk)+ }+ if html_style_status in {"applied", "fallback"}:+ completed_outcome["html_style_status"] = html_style_status+ if html_style_status == "fallback":+ if (+ isinstance(html_style_phase, str)+ and isinstance(html_style_reason_code, str)+ ):+ completed_outcome["html_style_phase"] = html_style_phase+ completed_outcome["html_style_reason_code"] = (+ html_style_reason_code+ )+ logger.warning(+ "[deepresearch_stream] HTML style fallback "+ "request_id=%s session_id=%s conversation_id=%s "+ "style_phase=%s style_reason_code=%s",+ _safe_log_correlation_id(route.get("request_id")),+ _safe_log_correlation_id(route.get("session_id")),+ _safe_log_correlation_id(+ chunk.get("conversation_id") or outcome_cid+ ),+ html_style_phase,+ html_style_reason_code,+ )+ workflow_usage = normalize_workflow_llm_token_usage(+ final_result.get("workflow_llm_token_usage")+ )+ if workflow_usage is not None:+ completed_outcome["workflow_llm_token_usage"] = workflow_usage+ return attach_terminal_timing(completed_outcome, chunk)if status_value == "error":return attach_terminal_timing({"status": "error",@@ -2932,7 +3095,7 @@ async def _generate_report_html(final_result: dict[str, Any],report_path_md: Path,fallback_markdown: str | None,-) -> Path | None:+) -> tuple[Path, str, str | None, str | None] | None:"""Prefer isolated SDK styling, then fall back to safe offline HTML."""report_path_html = report_path_md.with_suffix(".html")try:@@ -2947,20 +3110,28 @@ async def _generate_report_html("TOOL_SSL_VERIFY": runtime_config.get("TOOL_SSL_VERIFY", "false"),})manager = get_deepresearch_manager(_route_scope())+ llm_config = _build_styled_export_llm_config(runtime_config)+ llm_auth = _build_styled_export_llm_auth(runtime_config, llm_config)async with stylize_report_archive(final_result=final_result,- llm_config=_build_styled_export_llm_config(),+ llm_config=llm_config,+ llm_auth=llm_auth,tls=tls,manager=manager,session_id=str(route.get("session_id") or ""),- ) as archive_path:+ ) as styled_archive:with tempfile.TemporaryDirectory(prefix="deepresearch-report-styled-") as temporary_dir:destination = Path(temporary_dir) / "extracted"- bundle_root = _extract_styled_archive(archive_path, destination)+ bundle_root = _extract_styled_archive(styled_archive.path, destination)_install_styled_bundle(bundle_root, report_path_html)- return report_path_html+ return (+ report_path_html,+ styled_archive.style_status,+ getattr(styled_archive, "style_phase", None),+ getattr(styled_archive, "style_reason_code", None),+ )except Exception as exc: # pylint: disable=broad-exception-caughtlogger.warning("SDK styled HTML export failed; using offline conversion. type=%s",@@ -2984,7 +3155,7 @@ async def _generate_report_html(convert_md_to_html(source, target)html_bytes = target.read_bytes()_exclusive_write(report_path_html, html_bytes)- return report_path_html+ return report_path_html, "fallback", None, Noneexcept Exception as exc: # pylint: disable=broad-exception-caughtlogger.warning("Offline HTML conversion failed type=%s", type(exc).__name__@@ -2997,7 +3168,7 @@ async def _write_report_artifacts_stream(file_name: str,conversation_id: str,citation_artifacts: object = None,-) -> dict[str, str]:+) -> tuple[dict[str, str], str | None, str | None, str | None]:report_path_md = Path(await asyncio.to_thread(_write_report_markdown,@@ -3012,12 +3183,26 @@ async def _write_report_artifacts_stream(fallback_markdown = report_path_md.read_text(encoding="utf-8")except (OSError, UnicodeError):fallback_markdown = None- report_path_html = await _generate_report_html(+ generated_html = await _generate_report_html(final_result, report_path_md, fallback_markdown)- if report_path_html is not None:+ html_style_status = None+ html_style_phase = None+ html_style_reason_code = None+ if generated_html is not None:+ (+ report_path_html,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ ) = generated_htmlartifacts["html"] = str(report_path_html)- return artifacts+ return (+ artifacts,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ )def enable_deepresearch() -> bool:diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/usage.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/usage.pynew file mode 100644index 0000000000..14aab9057a--- /dev/null+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/usage.py@@ -0,0 +1,52 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Validation helpers for DeepResearch SDK workflow token usage."""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any+++_TOKEN_FIELDS = ("input_tokens", "output_tokens", "total_tokens", "llm_call_count")+++def _nonnegative_int(value: Any) -> int | None:+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ return None+ return value+++def normalize_workflow_llm_token_usage(value: Any) -> dict[str, Any] | None:+ """Return a bounded SDK usage mapping, or ``None`` for an invalid payload."""+ if not isinstance(value, Mapping):+ return None+ normalized: dict[str, Any] = {}+ for field in _TOKEN_FIELDS:+ token_value = _nonnegative_int(value.get(field))+ if token_value is None:+ return None+ normalized[field] = token_value++ agent_usage: list[dict[str, Any]] = []+ raw_agent_usage = value.get("agent_name_token_usage", [])+ if not isinstance(raw_agent_usage, list):+ return None+ for item in raw_agent_usage:+ if not isinstance(item, Mapping):+ return None+ agent_name = item.get("agent_name")+ if not isinstance(agent_name, str) or not agent_name.strip():+ return None+ normalized_item: dict[str, Any] = {"agent_name": agent_name.strip()}+ for field in _TOKEN_FIELDS:+ token_value = _nonnegative_int(item.get(field))+ if token_value is None:+ return None+ normalized_item[field] = token_value+ agent_usage.append(normalized_item)+ normalized["agent_name_token_usage"] = agent_usage+ return normalized+++__all__ = ["normalize_workflow_llm_token_usage"]diff --git a/jiuwenswarm/perf/accumulator.py b/jiuwenswarm/perf/accumulator.pyindex ced21a636d..25326c5d3d 100644--- a/jiuwenswarm/perf/accumulator.py+++ b/jiuwenswarm/perf/accumulator.py@@ -56,6 +56,7 @@ class RequestSummaryAccumulator:unattributed_ms: float = 0.0input_tokens: int = 0output_tokens: int = 0+ total_tokens: int = 0cache_read_tokens: int = 0tasks: list[dict[str, Any]] = field(default_factory=list)bottleneck_llm: list[dict[str, Any]] = field(default_factory=list)@@ -73,6 +74,7 @@ class RequestSummaryAccumulator:_agent_llm: dict[str, LlmStatsAccumulator] = field(default_factory=dict)_agent_tool: dict[str, ToolStatsAccumulator] = field(default_factory=dict)_agent_tokens: dict[str, dict[str, int]] = field(default_factory=dict)+ _recorded_external_usage_ids: set[tuple[str, str]] = field(default_factory=set)def _task_stat_pair(self, task_id: str) -> tuple[LlmStatsAccumulator, ToolStatsAccumulator]:pair = self._task_stats.get(task_id)@@ -115,6 +117,7 @@ class RequestSummaryAccumulator:)self.input_tokens += max(0, event.input_tokens)self.output_tokens += max(0, event.output_tokens)+ self.total_tokens += max(0, event.input_tokens) + max(0, event.output_tokens)if self._include_by_agent:agent_key = self._agent_key(event.agent_id)self._agent_llm.setdefault(agent_key, LlmStatsAccumulator()).record(@@ -162,6 +165,25 @@ class RequestSummaryAccumulator:top_n=self._bottleneck_top_n,)+ def record_external_token_usage(+ self,+ *,+ source: str,+ usage_id: str,+ input_tokens: int,+ output_tokens: int,+ total_tokens: int,+ ) -> bool:+ """Add one external aggregate without fabricating an LLM timing event."""+ key = (source.strip(), usage_id.strip())+ if not all(key) or key in self._recorded_external_usage_ids:+ return False+ self._recorded_external_usage_ids.add(key)+ self.input_tokens += max(0, input_tokens)+ self.output_tokens += max(0, output_tokens)+ self.total_tokens += max(0, total_tokens)+ return True+def record_tool(self, event: ToolPerfEvent) -> None:self.tool_stats.record(duration_ms=event.duration_ms,@@ -322,6 +344,7 @@ class RequestSummaryAccumulator:"tokens": {"input": self.input_tokens,"output": self.output_tokens,+ "total": self.total_tokens,"cache_read": self.cache_read_tokens,},},diff --git a/jiuwenswarm/perf/collector.py b/jiuwenswarm/perf/collector.pyindex c9d0857707..e6014cb4ab 100644--- a/jiuwenswarm/perf/collector.py+++ b/jiuwenswarm/perf/collector.py@@ -98,6 +98,27 @@ class PerfCollector:returnacc.record_llm(event)+ def record_external_token_usage(+ self,+ request_id: str,+ *,+ source: str,+ usage_id: str,+ input_tokens: int,+ output_tokens: int,+ total_tokens: int,+ ) -> bool:+ acc = self.get_accumulator(request_id)+ if acc is None:+ return False+ return acc.record_external_token_usage(+ source=source,+ usage_id=usage_id,+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ total_tokens=total_tokens,+ )+def record_tool(self, request_id: str, event: ToolPerfEvent) -> None:acc = self.get_accumulator(request_id)if acc is None:diff --git a/jiuwenswarm/perf/interface_hooks.py b/jiuwenswarm/perf/interface_hooks.pyindex 0876aab9f0..3dbaf894ee 100644--- a/jiuwenswarm/perf/interface_hooks.py+++ b/jiuwenswarm/perf/interface_hooks.py@@ -38,14 +38,42 @@ def snapshot_perf_summary_usage(request_id: str | None) -> dict[str, int] | Noneoutput_tokens = max(0, int(getattr(acc, "output_tokens", 0) or 0))if input_tokens <= 0 and output_tokens <= 0:return None+ total_tokens = max(0, int(getattr(acc, "total_tokens", 0) or 0))return {"input_tokens": input_tokens,"output_tokens": output_tokens,- "total_tokens": input_tokens + output_tokens,+ "total_tokens": total_tokens or input_tokens + output_tokens,"cache_tokens": max(0, int(getattr(acc, "cache_read_tokens", 0) or 0)),}+def record_deepresearch_sdk_token_usage(+ request_id: str | None,+ usage_id: str,+ usage: dict[str, Any],+) -> None:+ """Best-effort accounting for one terminal DeepResearch SDK usage snapshot."""+ rid = (request_id or "").strip()+ if not rid:+ return++ def _record() -> None:+ get_perf_collector().record_external_token_usage(+ rid,+ source="deepresearch_sdk",+ usage_id=usage_id,+ input_tokens=int(usage["input_tokens"]),+ output_tokens=int(usage["output_tokens"]),+ total_tokens=int(usage["total_tokens"]),+ )++ run_perf_safe(+ _COMPONENT,+ f"external token usage request_id={rid} source=deepresearch_sdk",+ _record,+ )++def merge_perf_summary_usage_fallback(stream_usage: dict[str, Any],perf_usage: dict[str, int] | None,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 79850aa4c0..c448fb67bc 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -432,9 +432,13 @@ from jiuwenswarm.perf.interface_hooks import (mark_request_first_byte,merge_perf_summary_usage_fallback,maybe_mark_answer_first_byte,+ record_deepresearch_sdk_token_usage,set_perf_summary_context,snapshot_perf_summary_usage,)+from jiuwenswarm.agents.harness.common.tools.deepresearch.usage import (+ normalize_workflow_llm_token_usage,+)from jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargsfrom jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (build_filesystem_policy,@@ -9988,6 +9992,70 @@ class JiuWenSwarmDeepAdapter:for cost in ("input_cost", "output_cost", "total_cost"):acc[cost] += usage_meta.get(cost, 0.0) or 0.0+ @staticmethod+ def _extract_deepresearch_sdk_usage(+ payload: Any,+ ) -> tuple[str, dict[str, Any]] | None:+ if not isinstance(payload, dict):+ return None+ result_info = payload.get("tool_result", payload)+ if not isinstance(result_info, dict):+ return None+ tool_name = result_info.get("tool_name") or result_info.get("name")+ if tool_name != "deepresearch_execute":+ return None+ raw_output = result_info.get("raw_output")+ if raw_output is None:+ raw_output = result_info.get("rawOutput")+ if raw_output is None:+ raw_output = result_info.get("result")+ if isinstance(raw_output, str):+ try:+ raw_output = json.loads(raw_output)+ except (TypeError, ValueError):+ return None+ if not isinstance(raw_output, dict) or raw_output.get("kind") != "completed":+ return None+ usage = normalize_workflow_llm_token_usage(+ raw_output.get("workflow_llm_token_usage")+ )+ if usage is None or max(+ usage["total_tokens"],+ usage["input_tokens"] + usage["output_tokens"],+ ) <= 0:+ return None+ state = raw_output.get("state")+ conversation_id = (+ raw_output.get("conversation_id")+ or (state.get("conversation_id") if isinstance(state, dict) else None)+ or result_info.get("tool_call_id")+ or result_info.get("toolCallId")+ )+ usage_id = str(conversation_id or "").strip()+ if not usage_id:+ return None+ return usage_id, usage++ @classmethod+ def _account_deepresearch_sdk_usage(+ cls,+ payload: Any,+ *,+ request_id: str,+ usage_accumulator: dict[str, Any],+ accounted_usage_ids: set[str],+ ) -> bool:+ extracted = cls._extract_deepresearch_sdk_usage(payload)+ if extracted is None:+ return False+ usage_id, usage = extracted+ if usage_id in accounted_usage_ids:+ return False+ accounted_usage_ids.add(usage_id)+ cls._accumulate_usage(usage_accumulator, usage)+ record_deepresearch_sdk_token_usage(request_id, usage_id, usage)+ return True+@staticmethoddef _rewrite_skill_turbo_usage_chunk(chunk: AgentResponseChunk,@@ -14853,6 +14921,7 @@ class JiuWenSwarmDeepAdapter:"total_cost": 0.0,}emitted_ask_user_request_ids: set[str] = set()+ accounted_deepresearch_usage_ids: set[str] = set()approved_plan_exit_tool_call_id = self._approved_plan_exit_resume_tool_call_id(request.params)@@ -15666,6 +15735,13 @@ class JiuWenSwarmDeepAdapter:is_complete=False,)accumulated_reasoning = ""+ if chunk_type == "tool_result":+ self._account_deepresearch_sdk_usage(+ chunk.payload,+ request_id=rid,+ usage_accumulator=usage_accumulator,+ accounted_usage_ids=accounted_deepresearch_usage_ids,+ )parsed = self._parse_stream_chunk(chunk)parsed = self._adapt_goal_intermediate_final(parsed)if parsed is not None:diff --git a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.pyindex 9dc18a1677..b1ec15dff9 100644--- a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py+++ b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py@@ -118,11 +118,19 @@ async def test_runner_error_preserves_bounded_subprocess_diagnostics():@pytest.mark.asyncioasync def test_new_query_starts_sdk_directly():+ sdk_usage = {+ "input_tokens": 120,+ "output_tokens": 30,+ "total_tokens": 150,+ "llm_call_count": 2,+ "agent_name_token_usage": [],+ }completed = {"status": "completed","conversation_id": "conversation-1","report_delivered": True,"report_chars": 42,+ "workflow_llm_token_usage": sdk_usage,}with patch.object(de,@@ -132,6 +140,7 @@ async def test_new_query_starts_sdk_directly():result, saved = await _invoke(query="研究智能家电竞争格局")assert result["kind"] == "completed"+ assert result["workflow_llm_token_usage"] == sdk_usageassert saved[0]["phase"] == "starting"stream.assert_awaited_once()@@ -411,6 +420,37 @@ async def test_feedback_answer_resumes_once_and_returns_direct_completion():assert "空调与冰箱" in stream.await_args.kwargs["feedback"]+async def test_completion_warns_when_html_style_falls_back():+ completed = {+ "status": "completed",+ "conversation_id": "conversation-1",+ "report_delivered": True,+ "report_chars": 42,+ "html_style_status": "fallback",+ "html_style_phase": "invoke_llm",+ "html_style_reason_code": "llm_call_failed",+ }+ with patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),+ ):+ result, saved = await _invoke(query="研究智能家电竞争格局")++ assert result["kind"] == "completed"+ assert result["html_style_status"] == "fallback"+ assert result["html_style_phase"] == "invoke_llm"+ assert result["html_style_reason_code"] == "llm_call_failed"+ assert (+ "HTML 已交付内置基础视觉模板,但 AI 生成的增强样式未应用"+ in result["content"]+ )+ assert saved[-1]["html_style_status"] == "fallback"+ assert saved[-1]["html_style_phase"] == "invoke_llm"+ assert saved[-1]["html_style_reason_code"] == "llm_call_failed"++@pytest.mark.asyncioasync def test_terminal_result_preserves_all_sdk_timing_windows():previous_window = {diff --git a/tests/unit_tests/agentserver/test_deepresearch_rewrite_tools.py b/tests/unit_tests/agentserver/test_deepresearch_rewrite_tools.pyindex 44df45f5a1..f5132fe0f5 100644--- a/tests/unit_tests/agentserver/test_deepresearch_rewrite_tools.py+++ b/tests/unit_tests/agentserver/test_deepresearch_rewrite_tools.py@@ -832,7 +832,14 @@ async def test_generate_rewrite_html_passes_inputs_generates_once_and_delivers_o"final_result": final_result,}html_path = Path("/workspace/child.html")- generator = AsyncMock(return_value=html_path)+ generator = AsyncMock(+ return_value=(+ html_path,+ "fallback",+ "invoke_llm",+ "llm_call_failed",+ )+ )delivery = AsyncMock(return_value=True)with patch.object(rt, "_get_route", return_value=route), patch.object(rt, "_get_effective_request_output_dir", return_value="/workspace"@@ -852,6 +859,9 @@ async def test_generate_rewrite_html_passes_inputs_generates_once_and_delivers_o"status": "completed","html_delivered": True,"delivery_status": "delivered",+ "html_style_status": "fallback",+ "html_style_phase": "invoke_llm",+ "html_style_reason_code": "llm_call_failed",}prepare.assert_called_once_with(workspace_root="/workspace",@@ -863,7 +873,13 @@ async def test_generate_rewrite_html_passes_inputs_generates_once_and_delivers_oPath("/workspace/child.md"),"rewritten",)- delivery.assert_awaited_once_with(html_path, route)+ delivery.assert_awaited_once_with(+ html_path,+ route,+ "fallback",+ "invoke_llm",+ "llm_call_failed",+ )assert "/workspace" not in raw@@ -1050,14 +1066,20 @@ async def test_generate_rewrite_html_unexpected_preparation_failure_is_safe(capl@pytest.mark.asyncio-async def test_deliver_html_sends_exactly_one_html_file_without_metadata():+async def test_deliver_html_sends_style_status_metadata():push = AsyncMock()route = {"request_id": "R1", "channel_id": "CH1", "session_id": "S1"}with patch("jiuwenswarm.server.gateway_push.transport.WebSocketGatewayPushTransport",return_value=push,):- delivered = await rt._deliver_html(Path("/workspace/child.html"), route)+ delivered = await rt._deliver_html(+ Path("/workspace/child.html"),+ route,+ "fallback",+ "invoke_llm",+ "llm_call_failed",+ )assert delivered is Truepush.send_push.assert_awaited_once_with({@@ -1067,6 +1089,11 @@ async def test_deliver_html_sends_exactly_one_html_file_without_metadata():"payload": {"event_type": "chat.file","files": [{"path": "/workspace/child.html", "name": "child.html"}],+ "metadata": {+ "htmlStyleStatus": "fallback",+ "htmlStylePhase": "invoke_llm",+ "htmlStyleReasonCode": "llm_call_failed",+ },},"is_complete": False,})diff --git a/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py b/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.pyindex 63c7e00603..a51b66c90d 100644--- a/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py+++ b/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py@@ -18,6 +18,7 @@ import pytestfrom jiuwenswarm.agents.harness.common.tools.deepresearch import sdk_bridge as bridgefrom jiuwenswarm.agents.harness.common.tools.deepresearch import runtime+from jiuwenswarm.common.local_env_config import get_task_env_overlaydef _zip_bytes() -> bytes:@@ -34,9 +35,10 @@ def _private_file(path: Path) -> None:def _request() -> dict:return {- "schema_version": 1,+ "schema_version": 2,"final_result": {"response_content": "report"},"llm_config": {"general": {"api_key": "secret", "model_name": "m"}},+ "llm_auth": {},"tls": {"LLM_SSL_VERIFY": False, "TOOL_SSL_VERIFY": True},}@@ -77,7 +79,7 @@ def test_bridge_streaming_reader_handles_short_reads():"mutation",[lambda request: request.update(extra=True),- lambda request: request.update(schema_version=2),+ lambda request: request.update(schema_version=1),lambda request: request.update(tls={"LLM_SSL_VERIFY": False}),lambda request: request.update(tls={"LLM_SSL_VERIFY": "false", "TOOL_SSL_VERIFY": True}),],@@ -89,7 +91,28 @@ def test_request_schema_is_strict(mutation):bridge.read_request(io.BytesIO(json.dumps(request).encode()))[email protected]("schema_version", [True, 1.0, "1", -1])+ "llm_auth",+ [+ None,+ {"default_headers": ""},+ {"default_headers": "not-json"},+ {"default_headers": "{}"},+ {"default_headers": '{"X-Extra":"1"}'},+ {+ "default_headers": '{"Authorization":"Basic abc","X-Extra":"1"}'+ },+ {"default_headers": '{"Authorization":"Basic abc"}', "extra": "x"},+ ],+)+def test_request_schema_rejects_nonminimal_llm_auth(llm_auth):+ request = _request()+ request["llm_auth"] = llm_auth+ with pytest.raises(bridge.BridgeError, match="bridge_request_invalid"):+ bridge.read_request(io.BytesIO(json.dumps(request).encode()))++[email protected]("schema_version", [True, 2.0, "2", -1])def test_request_schema_version_requires_exact_integer(schema_version):request = _request()request["schema_version"] = schema_version@@ -325,8 +348,10 @@ async def test_sdk_is_lazy_logs_only_to_stderr_and_restores_tls(tmp_path: Path,print("sdk-style-log")return types.SimpleNamespace(convert_content=base64.b64encode(_zip_bytes()).decode(),- style_applied=True,- style_status="applied",+ style_applied=False,+ style_status="fallback",+ style_phase="invoke_llm",+ style_reason_code="llm_call_failed",)modules = {@@ -349,6 +374,8 @@ async def test_sdk_is_lazy_logs_only_to_stderr_and_restores_tls(tmp_path: Path,result = await bridge.stylize_request(_request(), output)captured = capsys.readouterr()assert result["status"] == "completed"+ assert result["style_phase"] == "invoke_llm"+ assert result["style_reason_code"] == "llm_call_failed"assert captured.out == ""assert "sdk-context-log" in captured.err and "sdk-style-log" in captured.errassert observed["tls"] == ("false", "true")@@ -357,6 +384,68 @@ async def test_sdk_is_lazy_logs_only_to_stderr_and_restores_tls(tmp_path: Path,assert "TOOL_SSL_VERIFY" not in os.environ+async def test_sdk_binds_request_scoped_auth_overlay_and_restores_it(+ tmp_path: Path, monkeypatch+):+ output = tmp_path / "styled.zip"+ _private_file(output)+ authorization = "Basic c3R5bGUtY2hpbGQ="+ observed = {}++ @asynccontextmanager+ async def context(_config):+ observed["overlay"] = get_task_env_overlay()+ from openjiuwen.core.foundation.llm.model_clients.openai_model_client import (+ OpenAIModelClient,+ )+ from openjiuwen.core.foundation.llm.schema.config import (+ ModelClientConfig,+ ModelRequestConfig,+ )++ model_client = OpenAIModelClient(+ ModelRequestConfig(),+ ModelClientConfig(+ api_key="huawei-maas-session",+ api_base="https://example.invalid/v1",+ client_provider="OpenAI",+ use_shared_llm_http_client=False,+ ),+ )+ client = model_client._create_async_openai_client()+ observed["authorization"] = client._custom_headers.get("Authorization")+ await client.close()+ yield {"llm": True}++ async def stylize(_final_result, _llm):+ return types.SimpleNamespace(+ convert_content=base64.b64encode(_zip_bytes()).decode(),+ style_applied=True,+ style_status="applied",+ )++ service = types.ModuleType("openjiuwen_deepsearch.algorithm.report_style.service")+ style_runtime = types.ModuleType(+ "openjiuwen_deepsearch.framework.openjiuwen.llm.report_style_runtime"+ )+ service.stylize_report = stylize+ style_runtime.report_style_llm_context = context+ monkeypatch.setitem(sys.modules, service.__name__, service)+ monkeypatch.setitem(sys.modules, style_runtime.__name__, style_runtime)+ request = _request()+ request["llm_auth"] = {+ "default_headers": json.dumps({"Authorization": authorization})+ }++ result = await bridge.stylize_request(request, output)++ assert result["status"] == "completed"+ assert observed["overlay"] == request["llm_auth"]+ assert observed["authorization"] == authorization+ assert get_task_env_overlay() is None++@pytest.mark.asyncioasync def test_sdk_exception_is_safe_and_restores_tls(tmp_path: Path, monkeypatch):output = tmp_path / "styled.zip"@@ -376,6 +465,46 @@ async def test_sdk_exception_is_safe_and_restores_tls(tmp_path: Path, monkeypatcwith pytest.raises(bridge.BridgeError, match="SDK report styling failed") as caught:await bridge.stylize_request(_request(), output)assert "secret" not in str(caught.value)+ assert get_task_env_overlay() is None+++async def test_sdk_cancellation_restores_auth_overlay(tmp_path: Path, monkeypatch):+ output = tmp_path / "styled.zip"+ _private_file(output)+ started = asyncio.Event()+ observed = {}++ @asynccontextmanager+ async def context(_config):+ observed["overlay"] = get_task_env_overlay()+ yield {"llm": True}++ async def stylize(_final_result, _llm):+ started.set()+ await asyncio.Event().wait()++ service = types.ModuleType("openjiuwen_deepsearch.algorithm.report_style.service")+ style_runtime = types.ModuleType(+ "openjiuwen_deepsearch.framework.openjiuwen.llm.report_style_runtime"+ )+ service.stylize_report = stylize+ style_runtime.report_style_llm_context = context+ monkeypatch.setitem(sys.modules, service.__name__, service)+ monkeypatch.setitem(sys.modules, style_runtime.__name__, style_runtime)+ request = _request()+ request["llm_auth"] = {+ "default_headers": '{"Authorization":"Basic Y2FuY2Vs"}'+ }++ task = asyncio.create_task(bridge.stylize_request(request, output))+ await started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert observed["overlay"] == request["llm_auth"]+ assert get_task_env_overlay() is Nonedef test_cli_stdout_is_exactly_one_versioned_result_line(tmp_path: Path, monkeypatch, capsys):@@ -390,6 +519,8 @@ def test_cli_stdout_is_exactly_one_versioned_result_line(tmp_path: Path, monkeyp"output_path": str(output),"style_applied": True,"style_status": "applied",+ "style_phase": None,+ "style_reason_code": None,}async def stylize(_request_value, _output_value):@@ -488,6 +619,7 @@ async def test_parent_client_tracks_validates_and_cleans_owned_archive(tmp_path:executable.parent.mkdir(parents=True)executable.write_text("python")output_holder = {}+ authorization = "Basic cGFyZW50LXRvLWNoaWxk"manager = types.SimpleNamespace(track_process=lambda *_: None, untrack_process=lambda *_: None)async def spawn(*args, **kwargs):@@ -498,11 +630,16 @@ async def test_parent_client_tracks_validates_and_cleans_owned_archive(tmp_path:"schema_version": 1,"status": "completed","output_path": str(output),- "style_applied": True,- "style_status": "applied",+ "style_applied": False,+ "style_status": "fallback",+ "style_phase": "invoke_llm",+ "style_reason_code": "llm_call_failed",}output_holder["env"] = kwargs["env"]- return _Process((json.dumps(frame) + "\n").encode(), b"sdk logs")+ output_holder["args"] = args+ process = _Process((json.dumps(frame) + "\n").encode(), b"sdk logs")+ output_holder["process"] = process+ return processmonkeypatch.setattr(runtime, "resolve_python_executable", lambda: executable)monkeypatch.setattr(runtime, "build_child_env", lambda _: {@@ -514,16 +651,50 @@ async def test_parent_client_tracks_validates_and_cleans_owned_archive(tmp_path:async with runtime.stylize_report_archive(final_result={"response_content": "r"},llm_config={"general": {"api_key": "secret"}},+ llm_auth={+ "default_headers": json.dumps({"Authorization": authorization})+ },tls={"LLM_SSL_VERIFY": False, "TOOL_SSL_VERIFY": False},manager=manager,session_id="S1",) as archive:- assert archive == output_holder["path"]- assert archive.exists()+ assert archive.path == output_holder["path"]+ assert archive.path.exists()+ assert archive.style_applied is False+ assert archive.style_status == "fallback"+ assert archive.style_phase == "invoke_llm"+ assert archive.style_reason_code == "llm_call_failed"assert not output_holder["path"].exists()assert not output_holder["path"].parent.exists()assert "LLM_SSL_VERIFY" not in output_holder["env"]assert "TOOL_SSL_VERIFY" not in output_holder["env"]+ request = json.loads(bytes(output_holder["process"].stdin.data))+ assert request["schema_version"] == 2+ assert request["llm_auth"] == {+ "default_headers": json.dumps({"Authorization": authorization})+ }+ assert authorization not in " ".join(map(str, output_holder["args"]))+ assert authorization not in json.dumps(output_holder["env"])+++ "llm_auth",+ [+ {"default_headers": "{}"},+ {"default_headers": '{"Authorization":"Basic abc","X-Extra":"1"}'},+ {"unexpected": "value"},+ ],+)+def test_parent_rejects_nonminimal_llm_auth_before_spawn(llm_auth):+ with pytest.raises(+ runtime.DeepResearchRuntimeError, match="sdk_bridge_request_invalid"+ ):+ runtime._encode_bridge_request(+ final_result={},+ llm_config={},+ llm_auth=llm_auth,+ tls={"LLM_SSL_VERIFY": False, "TOOL_SSL_VERIFY": False},+ )@pytest.mark.asyncio@@ -545,7 +716,7 @@ async def test_parent_client_rejects_stdout_injection_and_cleans(tmp_path: Path,monkeypatch.setattr("asyncio.create_subprocess_exec", spawn)with pytest.raises(runtime.DeepResearchRuntimeError, match="sdk_bridge_protocol_invalid"):async with runtime.stylize_report_archive(- final_result={}, llm_config={},+ final_result={}, llm_config={}, llm_auth={},tls={"LLM_SSL_VERIFY": False, "TOOL_SSL_VERIFY": False},manager=manager, session_id="S1",):@@ -586,6 +757,7 @@ async def test_parent_client_requires_exact_integer_schema_version(async with runtime.stylize_report_archive(final_result={},llm_config={},+ llm_auth={},tls={"LLM_SSL_VERIFY": False, "TOOL_SSL_VERIFY": False},manager=manager,session_id="S1",@@ -612,7 +784,7 @@ async def test_parent_client_track_failure_reaps_and_does_not_untrack(tmp_path:monkeypatch.setattr("asyncio.create_subprocess_exec", spawn)with pytest.raises(RuntimeError, match="closed"):async with runtime.stylize_report_archive(- final_result={}, llm_config={},+ final_result={}, llm_config={}, llm_auth={},tls={"LLM_SSL_VERIFY": False, "TOOL_SSL_VERIFY": False},manager=manager, session_id="S1",):@@ -643,7 +815,7 @@ async def test_parent_client_repeated_cancel_reaps_untracks_and_cleans(tmp_path:async def invoke():async with runtime.stylize_report_archive(- final_result={}, llm_config={},+ final_result={}, llm_config={}, llm_auth={},tls={"LLM_SSL_VERIFY": False, "TOOL_SSL_VERIFY": False},manager=manager, session_id="S1",):diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py b/tests/unit_tests/agentserver/test_deepresearch_stream_router.pyindex 6d27952a11..1b35120b3e 100644--- a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py@@ -85,21 +85,14 @@ class _CountingList(list):self.items_visited = 0-def test_advance_stage_emits_ordered_task_reasoning_and_foreground_events():+def test_advance_stage_emits_status_only_to_task_list_and_foreground():frames = advance_stage(RouterState(), 1)assert [frame["event_type"] for frame in frames] == ["task.update",- "chat.reasoning","chat.delta",]assert frames[1] == {- "event_type": "chat.reasoning",- "task_id": "deepresearch_stage_1",- "task_content": "研究主题澄清",- "content": "[DeepResearch 阶段切换] 开始 Stage 1:研究主题澄清\n",- }- assert frames[2] == {"event_type": "chat.delta","task_id": "deepresearch_stage_1","task_content": "研究主题澄清",@@ -113,11 +106,11 @@ def test_advance_stage_backfills_every_missing_stage_in_event_order():frames = advance_stage(state, 4)assert [frame["event_type"] for frame in frames] == [+ "chat.delta","task.update",- "chat.reasoning",+ "chat.delta","chat.delta","task.update",- "chat.reasoning","chat.delta",]updates = [@@ -136,20 +129,37 @@ def test_advance_stage_backfills_every_missing_stage_in_event_order():for frame in framesif frame["event_type"] == "chat.delta"] == [+ "[DeepResearch 阶段完成] Stage 2:大纲生成\n","[DeepResearch 阶段切换] 开始 Stage 3:并行调研与章节撰写\n",+ "[DeepResearch 阶段完成] Stage 3:并行调研与章节撰写\n","[DeepResearch 阶段切换] 开始 Stage 4:报告交付\n",]assert state.current_stage == 4+def test_advance_stage_marks_previous_stage_complete_before_next_stage_starts():+ state = RouterState(current_stage=1)++ frames = advance_stage(state, 2)++ visible_stage_events = [+ frame["content"]+ for frame in frames+ if frame["event_type"] == "chat.delta"+ ]+ assert visible_stage_events == [+ "[DeepResearch 阶段完成] Stage 1:研究主题澄清\n",+ "[DeepResearch 阶段切换] 开始 Stage 2:大纲生成\n",+ ]+ _assert_stage(_stage_update(frames), 2)++def test_stage_2_uses_outline_generation_title_on_all_surfaces():- frames = advance_stage(RouterState(), 2)[-3:]+ frames = advance_stage(RouterState(), 2)[-2:]assert frames[0]["tasks"][1]["task_content"] == "大纲生成"assert frames[1]["task_content"] == "大纲生成"assert frames[1]["content"] == "[DeepResearch 阶段切换] 开始 Stage 2:大纲生成\n"- assert frames[2]["task_content"] == "大纲生成"- assert frames[2]["content"] == "[DeepResearch 阶段切换] 开始 Stage 2:大纲生成\n"def test_advance_stage_completion_keeps_all_four_completed_tasks_visible():@@ -160,7 +170,6 @@ def test_advance_stage_completion_keeps_all_four_completed_tasks_visible():assert [frame["event_type"] for frame in frames] == ["task.update",- "chat.reasoning","chat.delta",]update = frames[0]@@ -170,7 +179,6 @@ def test_advance_stage_completion_keeps_all_four_completed_tasks_visible():]assert all(task["status"] == "completed" for task in update["tasks"])assert frames[1]["content"] == "[DeepResearch 阶段完成] Stage 4:报告交付\n"- assert frames[2]["content"] == "[DeepResearch 阶段完成] Stage 4:报告交付\n"def test_advance_stage_does_not_repeat_or_regress_transition_messages():@@ -1171,10 +1179,9 @@ def test_interrupt_chunk_not_forwarded():_assert_stage(_stage_update(frames), 2)assert [frame["event_type"] for frame in frames] == ["task.update",- "chat.reasoning",+ "chat.delta","chat.delta","task.update",- "chat.reasoning","chat.delta",]@@ -1767,14 +1774,19 @@ def test_brief_outline_uses_stage_two_and_outline_preview_contract():"brief_source_tracer",],)-def test_brief_research_nodes_are_visible_in_stage_three(agent):+def test_brief_research_nodes_advance_stage_three_in_foreground(agent):frames = route_chunk({"agent": agent, "event": "start", "content": "处理中"},RouterState(current_stage=2),)_assert_stage(_stage_update(frames), 3)- assert any(frame["event_type"] == "chat.reasoning" for frame in frames)+ assert any(+ frame["event_type"] == "chat.delta"+ and frame["content"]+ == "[DeepResearch 阶段切换] 开始 Stage 3:并行调研与章节撰写\n"+ for frame in frames+ )@pytest.mark.parametrize(diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.pyindex 4af42b3e4b..12dc78808f 100644--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py@@ -66,6 +66,42 @@ class _Reader:return self.payload+class _DelayedFinalReportReader:+ def __init__(+ self,+ initial: bytes,+ terminal: bytes,+ delay: float,+ *,+ initial_delay: float = 0.0,+ ):+ self.initial = initial+ self.terminal = terminal+ self.delay = delay+ self.initial_delay = initial_delay+ self.reads = 0+ self.cancelled = False++ async def read(self, _size: int = -1) -> bytes:+ self.reads += 1+ if self.reads == 1:+ if self.initial_delay:+ try:+ await asyncio.sleep(self.initial_delay)+ except asyncio.CancelledError:+ self.cancelled = True+ raise+ return self.initial+ if self.reads == 2:+ try:+ await asyncio.sleep(self.delay)+ except asyncio.CancelledError:+ self.cancelled = True+ raise+ return self.terminal+ return b""++class _Proc:"""Small asyncio subprocess double with observable lifecycle."""@@ -1118,6 +1154,13 @@ async def test_completed_marker_requires_all_section_progress():async def test_completed_marker_accepts_p_numbered_sections_beneath_wrapper_heading(tmp_path: Path,):+ sdk_usage = {+ "input_tokens": 120,+ "output_tokens": 30,+ "total_tokens": 150,+ "llm_call_count": 2,+ "agent_name_token_usage": [],+ }outline = ("# 大纲:用户需求洞察报告\n""## 页面规划\n"@@ -1145,7 +1188,10 @@ async def test_completed_marker_accepts_p_numbered_sections_beneath_wrapper_head{"__deepsearch_status__": "completed","conversation_id": "C1",- "final_result": {"response_content": "# Final"},+ "final_result": {+ "response_content": "# Final",+ "workflow_llm_token_usage": sdk_usage,+ },}),]@@ -1180,6 +1226,7 @@ async def test_completed_marker_accepts_p_numbered_sections_beneath_wrapper_head"conversation_id": "C1","report_delivered": True,"report_chars": len("# Final"),+ "workflow_llm_token_usage": sdk_usage,}@@ -1511,7 +1558,12 @@ async def test_completed_report_delivers_markdown_html_and_hidden_bundle(tmp_pat}push = AsyncMock()write_report = AsyncMock(- return_value={"md": str(tmp_path / "r.md"), "html": str(tmp_path / "r.html")}+ return_value=(+ {"md": str(tmp_path / "r.md"), "html": str(tmp_path / "r.html")},+ "fallback",+ "invoke_llm",+ "llm_call_failed",+ ))patches = _stream_patches(proc, route=route)with ExitStack() as stack:@@ -1530,6 +1582,9 @@ async def test_completed_report_delivers_markdown_html_and_hidden_bundle(tmp_pat"conversation_id": "C1","report_delivered": True,"report_chars": len("# Final"),+ "html_style_status": "fallback",+ "html_style_phase": "invoke_llm",+ "html_style_reason_code": "llm_call_failed",}file_payload = next(call.args[0]["payload"]@@ -1537,12 +1592,127 @@ async def test_completed_report_delivers_markdown_html_and_hidden_bundle(tmp_patif call.args[0]["payload"].get("event_type") == "chat.file")assert [item["name"] for item in file_payload["files"]] == ["r.md", "r.html"]+ assert file_payload["metadata"]["htmlStyleStatus"] == "fallback"+ assert file_payload["metadata"]["htmlStylePhase"] == "invoke_llm"+ assert file_payload["metadata"]["htmlStyleReasonCode"] == "llm_call_failed"serialized = json.dumps(file_payload)assert "/hidden/raw.md" in serializedassert "/hidden/citations.preview.json" in serializedassert "/must/not/expose.json" not in serialized+async def test_final_report_idle_stream_emits_processing_heartbeat_without_cancelling_reader(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ initial = b"".join(+ (+ json.dumps(+ {"__deepsearch_status__": "started", "conversation_id": "C1"}+ ).encode("utf-8")+ + b"\n",+ json.dumps(+ {+ "agent": "sub_reporter",+ "section_idx": "1",+ "section_total": 1,+ "event": "done",+ }+ ).encode("utf-8")+ + b"\n",+ )+ )+ terminal = (+ json.dumps(+ {+ "__deepsearch_status__": "completed",+ "conversation_id": "C1",+ "final_result": {"response_content": "# Final"},+ }+ ).encode("utf-8")+ + b"\n"+ )+ reader = _DelayedFinalReportReader(+ initial,+ terminal,+ delay=0.08,+ initial_delay=0.06,+ )+ proc = _Proc()+ proc.stdout = reader+ route = {+ "request_id": "R1",+ "channel_id": "CH1",+ "session_id": "S1",+ "service_id": "default",+ "agent_id": "default",+ }+ push = AsyncMock()+ heartbeat_observations: list[tuple[str, int]] = []+ phase = "stream"++ async def record_push(envelope: dict[str, Any]) -> None:+ payload = envelope["payload"]+ if (+ payload.get("event_type") == "chat.processing_status"+ and payload.get("current_task") == "in_progress"+ ):+ heartbeat_observations.append((phase, reader.reads))++ push.send_push.side_effect = record_push++ async def delayed_write(*_args: Any, **_kwargs: Any) -> dict[str, str]:+ nonlocal phase+ phase = "artifact"+ await asyncio.sleep(0.08)+ return {"md": str(tmp_path / "r.md")}++ monkeypatch.setattr(+ dt,+ "DEEPRESEARCH_FINAL_REPORT_PROGRESS_INTERVAL_SECONDS",+ 0.02,+ raising=False,+ )+ patches = _stream_patches(proc, route=route)+ with ExitStack() as stack:+ for item in patches:+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ stack.enter_context(+ patch.object(+ dt,+ "_write_report_artifacts_stream",+ new=delayed_write,+ )+ )+ outcome = json.loads(+ await dt.deepresearch_stream._func(action="start", query="q")+ )++ heartbeats = [+ call.args[0]["payload"]+ for call in push.send_push.await_args_list+ if call.args[0]["payload"].get("event_type") == "chat.processing_status"+ and call.args[0]["payload"].get("current_task") == "in_progress"+ ]+ assert len(heartbeats) >= 4+ stream_heartbeat_reads = {+ read_number+ for observed_phase, read_number in heartbeat_observations+ if observed_phase == "stream"+ }+ assert stream_heartbeat_reads == {2}+ assert any(+ observed_phase == "artifact"+ for observed_phase, _read_number in heartbeat_observations+ )+ assert reader.cancelled is False+ assert outcome["status"] == "completed"+ assert outcome["report_delivered"] is True++def test_offline_html_converter_sanitizes_active_content(tmp_path: Path):from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.convert_html_offline import (convert_md_to_html,@@ -1701,11 +1871,19 @@ async def test_report_publication_writes_markdown_html_snapshot_and_provenance("citations_preview_path": "/hidden/citations.preview.json",}with patch.object(dt, "get_cwd", return_value=str(tmp_path)):- artifacts = await dt._write_report_artifacts_stream(+ (+ artifacts,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ ) = await dt._write_report_artifacts_stream(final_result, "Research", "C1", citation_artifacts)assert set(artifacts) == {"md", "html"}+ assert html_style_status == "fallback"+ assert html_style_phase is None+ assert html_style_reason_code is Nonemarkdown = Path(artifacts["md"])assert markdown.read_text(encoding="utf-8").startswith("# Report")assert Path(artifacts["html"]).read_text(encoding="utf-8").startswith("<!DOCTYPE html>")@@ -1727,11 +1905,19 @@ async def test_html_failure_keeps_published_markdown(tmp_path: Path):with patch.object(dt, "get_cwd", return_value=str(tmp_path)), patch.object(dt, "_generate_report_html", new=AsyncMock(return_value=None)):- artifacts = await dt._write_report_artifacts_stream(+ (+ artifacts,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ ) = await dt._write_report_artifacts_stream(final_result, "Research", "C1")assert set(artifacts) == {"md"}+ assert html_style_status is None+ assert html_style_phase is None+ assert html_style_reason_code is Noneassert Path(artifacts["md"]).is_file()@@ -1775,11 +1961,13 @@ async def test_concurrent_same_title_report_publication_allocates_distinct_outpu"chart_messages": [],}with patch.object(dt, "get_cwd", return_value=str(tmp_path)):- first, second = await asyncio.gather(+ first_result, second_result = await asyncio.gather(dt._write_report_artifacts_stream(final_result, "Same", "C1"),dt._write_report_artifacts_stream(final_result, "Same", "C2"),)+ first, _, _, _ = first_result+ second, _, _, _ = second_resultassert first["md"] != second["md"]assert Path(first["md"]).is_file()assert Path(second["md"]).is_file()@@ -1940,6 +2128,49 @@ def test_build_deepresearch_config_empty_values_are_not_forwarded():assert all(value != "" for value in config.values())+def test_styled_export_auth_carries_only_maas_authorization():+ authorization = "Basic c3R5bGUtcmVxdWVzdA=="+ auth = dt._build_styled_export_llm_auth(+ {+ "default_headers": json.dumps(+ {"authorization": authorization, "X-Unrelated": "must-not-cross"}+ )+ },+ {"general": {"api_key": "huawei-maas-session"}},+ )++ assert json.loads(auth["default_headers"]) == {+ "Authorization": authorization+ }+ assert "X-Unrelated" not in auth["default_headers"]+++def test_styled_export_auth_does_not_apply_to_ordinary_api_keys():+ assert dt._build_styled_export_llm_auth(+ {"default_headers": "not-json"},+ {"general": {"api_key": "ordinary-api-key"}},+ ) == {}+++ "raw_headers",+ [+ "",+ "{}",+ '{"X-Other":"1"}',+ '{"Authorization":"Basic one","authorization":"Basic two"}',+ ],+)+def test_styled_export_auth_fails_closed_without_one_maas_authorization(+ raw_headers: str,+):+ with pytest.raises(ValueError, match="MaaS Authorization is unavailable"):+ dt._build_styled_export_llm_auth(+ {"default_headers": raw_headers},+ {"general": {"api_key": "huawei-maas-session"}},+ )++def test_resolve_runner_rejects_symlink_and_hardlink(tmp_path: Path):shared = tmp_path / "shared"scripts = shared / "deepresearch" / "scripts"@@ -2436,6 +2667,59 @@ async def test_feedback_resume_does_not_repeat_stage_one_transition():assert stage_one_updates == []+async def test_outline_resume_starts_from_stage_three_without_replaying_prior_stages():+ proc = _Proc(+ [+ json.dumps({"__deepsearch_status__": "resuming", "conversation_id": "C1"}),+ json.dumps(+ {+ "agent": "collector_info_retrieval",+ "section_idx": "1",+ "section_total": 1,+ "event": "start",+ "content": "searching",+ }+ ),+ json.dumps({"__deepsearch_status__": "error", "error": "stop"}),+ ]+ )+ route = {+ "request_id": "R",+ "channel_id": "CH",+ "session_id": "S",+ "service_id": "default",+ "agent_id": "default",+ }+ push = AsyncMock()+ patches = _stream_patches(proc, route=route)+ with ExitStack() as stack:+ for item in patches:+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ await dt.deepresearch_stream._func(+ action="resume",+ conversation_id="C1",+ node="outline_interaction",+ interaction_result=(+ '{"status":"answered","answers":[{"question":"q",'+ '"selected_options":["outline_confirm"],"custom_input":null}]}'+ ),+ )++ transition_payloads = [+ call.args[0]["payload"]+ for call in push.send_push.await_args_list+ if call.args[0]["payload"].get("event_type") == "chat.delta"+ and "[DeepResearch 阶段切换]" in call.args[0]["payload"].get("content", "")+ ]+ assert [payload["task_id"] for payload in transition_payloads] == [+ "deepresearch_stage_3"+ ]++@pytest.mark.asyncioasync def test_user_feedback_resume_can_complete_final_report_without_section_replay(tmp_path: Path,@@ -2459,12 +2743,13 @@ async def test_user_feedback_resume_can_complete_final_report_without_section_re"service_id": "default","agent_id": "default",}+ push = AsyncMock()patches = _stream_patches(proc, route=route)with ExitStack() as stack:for item in patches:stack.enter_context(item)stack.enter_context(- patch.object(dt, "WebSocketGatewayPushTransport", return_value=AsyncMock())+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push))stack.enter_context(patch.object(@@ -2481,6 +2766,14 @@ async def test_user_feedback_resume_can_complete_final_report_without_section_re))assert outcome["status"] == "completed"+ transition_task_ids = [+ call.args[0]["payload"]["task_id"]+ for call in push.send_push.await_args_list+ if call.args[0]["payload"].get("event_type") == "chat.delta"+ and "[DeepResearch 阶段切换]"+ in call.args[0]["payload"].get("content", "")+ ]+ assert transition_task_ids == ["deepresearch_stage_4"]def test_artifact_bundle_ignores_blank_and_unapproved_companions():@@ -2512,8 +2805,12 @@ async def test_offline_html_uses_verified_snapshot_and_preserves_occupied_output):markdown = tmp_path / "report.md"markdown.write_text("mutated source", encoding="utf-8")- result = await dt._generate_report_html({}, markdown, "verified snapshot")- assert result is not None+ generated = await dt._generate_report_html({}, markdown, "verified snapshot")+ assert generated is not None+ result, html_style_status, html_style_phase, html_style_reason_code = generated+ assert html_style_status == "fallback"+ assert html_style_phase is None+ assert html_style_reason_code is Nonerendered = result.read_text(encoding="utf-8")assert "verified snapshot" in renderedassert "mutated source" not in rendered@@ -2541,33 +2838,61 @@ async def test_styled_html_uses_isolated_bridge_as_primary(tmp_path: Path):@asynccontextmanagerasync def bridge(**kwargs):observed.update(kwargs)- yield archive+ yield SimpleNamespace(+ path=archive,+ style_status="fallback",+ style_phase="invoke_llm",+ style_reason_code="llm_call_failed",+ )route = {"session_id": "S1","service_id": "svc","agent_id": "agent",}+ authorization = "Basic c3R5bGUtY2hpbGQ="+ runtime_config = {+ "LLM_SSL_VERIFY": "false",+ "TOOL_SSL_VERIFY": "true",+ "default_headers": json.dumps(+ {"Authorization": authorization, "X-Unrelated": "do-not-forward"}+ ),+ }with patch.object(dt, "_get_route", return_value=route), patch.object(dt, "_build_deepresearch_request_config",- return_value={"LLM_SSL_VERIFY": "false", "TOOL_SSL_VERIFY": "true"},+ return_value=runtime_config,), patch.object(dt, "_build_styled_export_llm_config",- return_value={"general": {"api_key": "secret"}},- ), patch.object(dt, "get_deepresearch_manager", return_value=Mock()), patch.object(+ return_value={"general": {"api_key": "huawei-maas-session"}},+ ) as build_llm, patch.object(+ dt, "get_deepresearch_manager", return_value=Mock()+ ), patch.object(dt, "stylize_report_archive", bridge):result = await dt._generate_report_html({"response_content": "report"}, markdown, "offline")- assert result == markdown.with_suffix(".html")- assert result.read_text(encoding="utf-8") == "<h1>styled</h1>"+ assert result == (+ markdown.with_suffix(".html"),+ "fallback",+ "invoke_llm",+ "llm_call_failed",+ )+ assert result[0].read_text(encoding="utf-8") == "<h1>styled</h1>"assert observed["tls"] == {"LLM_SSL_VERIFY": False,"TOOL_SSL_VERIFY": True,}assert observed["session_id"] == "S1"+ assert observed["llm_auth"] == {+ "default_headers": json.dumps(+ {"Authorization": authorization},+ ensure_ascii=False,+ separators=(",", ":"),+ )+ }+ build_llm.assert_called_once_with(runtime_config)@pytest.mark.asyncio@@ -2588,7 +2913,7 @@ async def test_styled_html_primary_does_not_require_offline_markdown(tmp_path: Pasync def bridge(**_kwargs):nonlocal bridge_callsbridge_calls += 1- yield archive+ yield SimpleNamespace(path=archive, style_status="applied")route = {"session_id": "S1", "service_id": "svc", "agent_id": "agent"}with patch.object(dt, "_get_route", return_value=route), patch.object(@@ -2603,8 +2928,34 @@ async def test_styled_html_primary_does_not_require_offline_markdown(tmp_path: P)assert bridge_calls == 1- assert result == markdown.with_suffix(".html")- assert result.read_text(encoding="utf-8") == "<h1>styled</h1>"+ assert result == (markdown.with_suffix(".html"), "applied", None, None)+ assert result[0].read_text(encoding="utf-8") == "<h1>styled</h1>"+++async def test_styled_html_missing_maas_auth_falls_back_without_starting_bridge(+ tmp_path: Path,+):+ markdown = tmp_path / "report.md"+ bridge = Mock()+ with patch.object(+ dt,+ "_build_deepresearch_request_config",+ return_value={"LLM_SSL_VERIFY": "false", "TOOL_SSL_VERIFY": "false"},+ ), patch.object(+ dt,+ "_build_styled_export_llm_config",+ return_value={"general": {"api_key": "huawei-maas-session"}},+ ), patch.object(+ dt, "get_deepresearch_manager", return_value=Mock()+ ), patch.object(+ dt, "stylize_report_archive", bridge+ ):+ result = await dt._generate_report_html({}, markdown, "offline report")++ assert result == (markdown.with_suffix(".html"), "fallback", None, None)+ assert "offline report" in result[0].read_text(encoding="utf-8")+ bridge.assert_not_called()@pytest.mark.asynciodiff --git a/tests/unit_tests/agentserver/test_skill_turbo_resume_usage.py b/tests/unit_tests/agentserver/test_skill_turbo_resume_usage.pyindex e3ea489621..4135067c05 100644--- a/tests/unit_tests/agentserver/test_skill_turbo_resume_usage.py+++ b/tests/unit_tests/agentserver/test_skill_turbo_resume_usage.py@@ -137,3 +137,96 @@ def test_resume_usage_loop_accumulates_and_keeps_other_events() -> None:None,]assert out[-1].is_complete is True+++def test_deepresearch_sdk_usage_is_accounted_once_from_terminal_tool_result(+ monkeypatch,+) -> None:+ usage = {+ "input_tokens": 500,+ "output_tokens": 80,+ "total_tokens": 580,+ "llm_call_count": 4,+ "agent_name_token_usage": [+ {+ "agent_name": "reporter",+ "input_tokens": 500,+ "output_tokens": 80,+ "total_tokens": 580,+ "llm_call_count": 4,+ }+ ],+ }+ payload = {+ "tool_result": {+ "tool_name": "deepresearch_execute",+ "tool_call_id": "call-1",+ "raw_output": {+ "schema_version": "openjiuwen.deepresearch.execute.v1",+ "kind": "completed",+ "state": {"conversation_id": "conversation-1"},+ "workflow_llm_token_usage": usage,+ },+ }+ }+ recorded: list[tuple[str, str, dict]] = []+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep."+ "record_deepresearch_sdk_token_usage",+ lambda request_id, usage_id, value: recorded.append(+ (request_id, usage_id, value)+ ),+ )+ accumulator = JiuWenSwarmDeepAdapter._new_usage_accumulator()+ accounted: set[str] = set()++ first = JiuWenSwarmDeepAdapter._account_deepresearch_sdk_usage(+ payload,+ request_id="request-1",+ usage_accumulator=accumulator,+ accounted_usage_ids=accounted,+ )+ second = JiuWenSwarmDeepAdapter._account_deepresearch_sdk_usage(+ payload,+ request_id="request-1",+ usage_accumulator=accumulator,+ accounted_usage_ids=accounted,+ )++ assert first is True+ assert second is False+ assert accumulator["input_tokens"] == 500+ assert accumulator["output_tokens"] == 80+ assert accumulator["total_tokens"] == 580+ assert recorded == [("request-1", "conversation-1", usage)]+++def test_deepresearch_sdk_usage_rejects_invalid_or_nonterminal_payloads() -> None:+ invalid_usage = {+ "input_tokens": -1,+ "output_tokens": 2,+ "total_tokens": 1,+ "llm_call_count": 1,+ "agent_name_token_usage": [],+ }++ for kind, tool_name in (+ ("completed", "other_tool"),+ ("interaction", "deepresearch_execute"),+ ("completed", "deepresearch_execute"),+ ):+ usage = invalid_usage if tool_name == "deepresearch_execute" else {+ **invalid_usage,+ "input_tokens": 1,+ }+ payload = {+ "tool_result": {+ "tool_name": tool_name,+ "tool_call_id": "call-1",+ "raw_output": {+ "kind": kind,+ "workflow_llm_token_usage": usage,+ },+ }+ }+ assert JiuWenSwarmDeepAdapter._extract_deepresearch_sdk_usage(payload) is Nonediff --git a/tests/unit_tests/perf/test_interface_deep_perf_wiring.py b/tests/unit_tests/perf/test_interface_deep_perf_wiring.pyindex 5af7a4436c..8cbfd490a7 100644--- a/tests/unit_tests/perf/test_interface_deep_perf_wiring.py+++ b/tests/unit_tests/perf/test_interface_deep_perf_wiring.py@@ -26,6 +26,8 @@ def test_interface_deep_wires_request_summary_rail() -> None:"maybe_mark_answer_first_byte","snapshot_perf_summary_usage","merge_perf_summary_usage_fallback",+ "record_deepresearch_sdk_token_usage",+ "_account_deepresearch_sdk_usage","def _build_request_summary_rail",'RequestSummaryRail(record_only=True)','_RailBuildInfo("_request_summary_rail"',diff --git a/tests/unit_tests/perf/test_request_summary.py b/tests/unit_tests/perf/test_request_summary.pyindex 373d42d6d2..f9706c9bd5 100644--- a/tests/unit_tests/perf/test_request_summary.py+++ b/tests/unit_tests/perf/test_request_summary.py@@ -77,6 +77,37 @@ def test_perf_usage_fallback_does_not_duplicate_complete_stream_usage() -> None:assert stream_usage["total_tokens"] == 1_100+def test_external_token_usage_hook_routes_sdk_snapshot_to_collector(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jiuwenswarm.perf import interface_hooks++ calls: list[tuple[tuple, dict]] = []+ collector = SimpleNamespace(+ record_external_token_usage=lambda *args, **kwargs: calls.append((args, kwargs))+ )+ monkeypatch.setattr(interface_hooks, "get_perf_collector", lambda: collector)++ interface_hooks.record_deepresearch_sdk_token_usage(+ "request-1",+ "conversation-1",+ {"input_tokens": 500, "output_tokens": 80, "total_tokens": 580},+ )++ assert calls == [+ (+ ("request-1",),+ {+ "source": "deepresearch_sdk",+ "usage_id": "conversation-1",+ "input_tokens": 500,+ "output_tokens": 80,+ "total_tokens": 580,+ },+ )+ ]++def test_request_summary_rail_imports_required_symbols() -> None:"""Regression: ensure request_summary_rail imports all runtime dependencies."""import ast@@ -176,6 +207,54 @@ def test_accumulator_finalize_schema() -> None:assert "errors" not in summary+def test_accumulator_adds_external_token_usage_once_without_fake_llm_call() -> None:+ acc = RequestSummaryAccumulator(+ meta=RequestMeta(+ session_id="sess-1",+ request_id="req-1",+ channel_id="web",+ mode="plan",+ trace_id=None,+ started_at=1000.0,+ )+ )+ acc.record_llm(+ LlmPerfEvent(+ llm_call_id="llm-1",+ duration_ms=1000.0,+ model="deepseek-chat",+ iteration=1,+ input_tokens=100,+ output_tokens=50,+ status="ok",+ )+ )++ assert acc.record_external_token_usage(+ source="deepresearch_sdk",+ usage_id="conversation-1",+ input_tokens=500,+ output_tokens=80,+ total_tokens=580,+ ) is True+ assert acc.record_external_token_usage(+ source="deepresearch_sdk",+ usage_id="conversation-1",+ input_tokens=500,+ output_tokens=80,+ total_tokens=580,+ ) is False++ summary = acc.finalize(status="ok", ended_at=1002.0)+ assert summary["summary"]["tokens"] == {+ "input": 600,+ "output": 130,+ "total": 730,+ "cache_read": 0,+ }+ assert summary["summary"]["stats"]["llm"]["count"] == 1++def test_accumulator_include_by_agent_when_enabled() -> None:acc = RequestSummaryAccumulator(meta=RequestMeta(