JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(server): instrument the chat message pipeline
alan_cheng13a9550d48f2
diff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.pyindex 9bbc958b33..e0279e710e 100644--- a/jiuwenswarm/agents/harness/team/team_manager.py+++ b/jiuwenswarm/agents/harness/team/team_manager.py@@ -20,6 +20,7 @@ from openjiuwen.agent_teams.runtime.pool import RuntimeStatefrom openjiuwen.agent_teams.schema.blueprint import TeamAgentSpecfrom openjiuwen.agent_teams.context import reset_session_id, set_session_idfrom openjiuwen.core.runner import Runner+from openjiuwen.core.common.logging import server_loggerfrom openjiuwen.harness import DeepAgentfrom openjiuwen.harness.rails import (SkillEvolutionRail,@@ -27,6 +28,7 @@ from openjiuwen.harness.rails import (TeamSkillEvolutionRail,)from jiuwenswarm.agents.harness.team.bootstrap import configure_agent_teams_home+from jiuwenswarm.common.log_preview import preview_textfrom jiuwenswarm.common.utils import get_user_workspace_dirconfigure_agent_teams_home()@@ -83,6 +85,24 @@ _PG_POST_START_READY_BACKOFF = 1.45_PG_POST_START_LOG_EVERY_SEC = 5.0_TEAM_STREAM_EXIT_GRACE_TIMEOUT_SEC = 1.5++def _safe_payload_preview(payload: Any) -> str:+ """Render an interact payload as a bounded single-line log fragment.++ Args:+ payload: Raw interact payload, either plain text or a team message+ object (``GodViewMessage`` / ``HumanAgentMessage`` / ...).++ Returns:+ Clipped text of the payload body, prefixed with the payload type when+ it is not a plain string.+ """+ if isinstance(payload, str):+ return preview_text(payload)+ body = getattr(payload, "body", None)+ text = body if isinstance(body, str) else str(payload)+ return f"<{type(payload).__name__}>{preview_text(text)}"+# ── Team Observability ──────────────────────────────────────# Tracks whether observability is currently active so we can# detect config toggles (enabled → disabled or vice-versa)@@ -1229,6 +1249,13 @@ class TeamManager:)return False, "not_active"+ # Last stop before the message enters the team runner interact path.+ server_logger.info(+ "[AgentServer] team message entering runner interact: session_id=%s team=%s payload=%s",+ session_id,+ team_name,+ _safe_payload_preview(user_input),+ )result = await Runner.interact_agent_team(user_input,team_name=team_name,diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 27561aa75d..d5600ab773 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -1,4 +1,4 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved."""AgentWebSocketServer - Gateway 与 AgentServer 之间的 WebSocket 服务端."""@@ -112,6 +112,8 @@ from jiuwenswarm.agents.harness.code.prompt.plan_approval import (PLAN_MODE_EXITED_EVENT_TYPE,)from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.common.log_preview import preview_text+from openjiuwen.core.common.logging import server_loggerlogger = logging.getLogger(__name__)@@ -1364,6 +1366,17 @@ class AgentWebSocketServer:request.is_stream,)+ # First touch point of frontend chat input inside AgentServer: record it through the+ # agent-core logging system so it lands in the unified agent log stream.+ if request.req_method == ReqMethod.CHAT_SEND:+ server_logger.info(+ "[AgentServer] chat input received: request_id=%s session_id=%s channel_id=%s query=%s",+ request.request_id,+ request.session_id,+ request.channel_id,+ preview_text(_request_query_text(request)),+ )+try:if request.channel_id == "acp" and request.req_method != ReqMethod.INITIALIZE:metadata = dict(request.metadata or {})diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 8d06275392..08a942674f 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -1,4 +1,4 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved."""JiuWenSwarm Deep Adapter - 基于 openjiuwen DeepAgent 的适配器实现.@@ -37,6 +37,7 @@ from openjiuwen.core.foundation.llm import ModelRequestConfig, ModelClientConfigfrom openjiuwen.core.foundation.llm.utils.provider_utils import is_openai_account_providerfrom openjiuwen.core.foundation.store.base_embedding import EmbeddingConfigfrom openjiuwen.core.foundation.tool import ToolCard, McpServerConfig+from openjiuwen.core.common.logging import server_loggerfrom openjiuwen.core.runner import Runnerfrom openjiuwen.core.session.checkpointer import CheckpointerFactoryfrom openjiuwen.core.session.checkpointer.checkpointer import CheckpointerConfig@@ -151,6 +152,7 @@ from jiuwenswarm.agents.harness.common.rails.execution_guard import ()from jiuwenswarm.common.config import get_model_namesfrom jiuwenswarm.common.hooks_config import load_hooks_config+from jiuwenswarm.common.log_preview import preview_textfrom jiuwenswarm.server.hooks.user_hook_rail import UserHookRailfrom jiuwenswarm.agents.harness.common.rails.permissions.owner_scopes import (TOOL_PERMISSION_CONTEXT,@@ -1187,13 +1189,16 @@ class JiuWenSwarmDeepAdapter:if isinstance(self._session_instance_config, dict)else None)+ create_started_at = time.monotonic()await adapter.create_instance(config,mode=self._session_instance_mode,sub_mode=self._session_instance_sub_mode,)+ instance_ready_at = time.monotonic()await adapter.start_interaction(session_id=sid)+ interaction_ready_at = time.monotonic()self._session_adapters[sid] = adapter# A brand-new session adapter is created from ``_session_instance_config``@@ -1204,7 +1209,16 @@ class JiuWenSwarmDeepAdapter:# (including the no-pending case, where it silently catches up).await self._reload_session_adapter_if_stale(sid, adapter)self._touch_session_adapter(sid)- logger.info("[JiuWenSwarmDeepAdapter] session scoped DeepAgent created: session_id=%s", sid)+ # Cold-start cost of a session's first turn, split so a slow one can+ # be attributed to agent assembly vs. interaction startup.+ server_logger.info(+ "[AgentServer] session adapter created: session_id=%s create_instance_ms=%.1f"+ " start_interaction_ms=%.1f total_ms=%.1f",+ sid,+ (instance_ready_at - create_started_at) * 1000,+ (interaction_ready_at - instance_ready_at) * 1000,+ (time.monotonic() - create_started_at) * 1000,+ )return adapter@staticmethod@@ -7926,6 +7940,9 @@ class JiuWenSwarmDeepAdapter:Yields:AgentResponseChunk 流式响应块"""+ # Start of this adapter's own share of the turn; reported on the+ # "entering runner streaming" line so the pre-dispatch work is visible.+ stream_impl_started_at = time.monotonic()if not self._is_session_scoped_adapter:session_adapter = await self._get_or_create_session_adapter(request.session_id)try:@@ -8467,6 +8484,17 @@ class JiuWenSwarmDeepAdapter:# Interrupt resumes (permission/confirm/ask-user) must send_input# even when Goal already holds the output lease.interaction_stream = await self._instance.attach_output()+ # Last stop before the message is injected into the running+ # single-agent interaction (interrupt / HITL resume).+ server_logger.info(+ "[AgentServer] message entering runner interaction inject: session_id=%s"+ " request_id=%s channel_id=%s mode=%s query=%s",+ session_id,+ rid,+ cid,+ mode,+ preview_text(inputs.get("query", "")),+ )await self._instance.send_input(SendInputRequest(request_id=rid,@@ -8486,6 +8514,19 @@ class JiuWenSwarmDeepAdapter:yield chunkinteraction_stream_abort = Falsereturn+ # Last stop before the message enters the single-agent runner+ # streaming path. ``prepare_ms`` covers everything this adapter+ # did with the turn before handing it over.+ server_logger.info(+ "[AgentServer] message entering runner streaming: session_id=%s request_id=%s"+ " channel_id=%s mode=%s prepare_ms=%.1f query=%s",+ session_id,+ rid,+ cid,+ mode,+ (time.monotonic() - stream_impl_started_at) * 1000,+ preview_text(inputs.get("query", "")),+ )await self._instance.send_input(SendInputRequest(request_id=rid,@@ -8494,6 +8535,10 @@ class JiuWenSwarmDeepAdapter:))run_failure: tuple[str, str] | None = None+ # Start of the wait for the runner's first chunk; every branch above+ # has either handed the message over or attached to a running round.+ runner_stream_started_at = time.monotonic()+ first_chunk_seen = False# A plain user-chat consumer stream (not a command.goal / attach-goal# stream). Only these may be hijacked by a goal round before the user# round produces its first visible token; used to allow a bubble@@ -8505,6 +8550,20 @@ class JiuWenSwarmDeepAdapter:and not goal_stream_request)async for chunk in interaction_stream:+ # First chunk handed back by the runner: records the time to+ # first token for this round.+ if not first_chunk_seen:+ first_chunk_seen = True+ server_logger.info(+ "[AgentServer] runner streaming first chunk: session_id=%s request_id=%s"+ " channel_id=%s mode=%s elapsed_ms=%.1f chunk_type=%s",+ session_id,+ rid,+ cid,+ mode,+ (time.monotonic() - runner_stream_started_at) * 1000,+ getattr(chunk, "type", None) or type(chunk).__name__,+ )if _debug_logger is not None:_debug_logger.feed(chunk)# Surface run-level terminal failures (model/task_failed,diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex c76ec6fccb..e684d5c4d3 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -23,9 +23,11 @@ from openjiuwen.agent_teams.runtime import RunActionKindfrom openjiuwen.agent_teams.schema.team import TeamRolefrom openjiuwen.agent_teams.monitor import TeamStreamLoggerfrom openjiuwen.core.runner import Runner+from openjiuwen.core.common.logging import server_loggerfrom openjiuwen.harness import DeepAgentfrom jiuwenswarm.agents.harness.team import TeamManager, get_team_manager+from jiuwenswarm.common.log_preview import DEFAULT_PREVIEW_MAX_CHARS, preview_textfrom jiuwenswarm.common.cron_team_completion import (_cron_solo_harness_end_pending,_drain_cron_delegation_grace_events,@@ -517,10 +519,14 @@ def _resolve_request_language(request: Any) -> str:return "zh"-def _safe_query_preview(query: Any, limit: int = 200) -> str:- if isinstance(query, str):- return query[:limit]- return str(query)[:limit]+def _safe_query_preview(query: Any, limit: int = DEFAULT_PREVIEW_MAX_CHARS) -> str:+ return preview_text(query, limit)+++# Parsed event types that carry text produced by a model, as opposed to the+# framework control events (team.runtime_ready, tool.use, ...) that also travel+# on the same stream.+_MODEL_OUTPUT_EVENT_TYPES = frozenset({"chat.delta", "chat.final", "chat.reasoning"})def _normalize_team_query(query: Any, *, channel_id: str | None, language: str) -> Any:@@ -1924,6 +1930,7 @@ async def _consume_stream_with_query(_envs = envs or {}hide_dm: bool = bool(_envs.get("hide_dm", False))received_chunks = 0+ first_model_output_at: float | None = Noneemitted_ask_user_request_ids: set[str] = set()# Reset the team-events flag at the start of a new round so chat.final# can correctly determine whether the team is active.@@ -1959,6 +1966,16 @@ async def _consume_stream_with_query(traces_dir = get_agent_teams_home() / "traces"traces_dir.mkdir(parents=True, exist_ok=True)lg = TeamStreamLogger(file_path=str(traces_dir / f"dump-team-{session_id}.txt"))+ # Last stop before the message enters the team runner streaming path.+ server_logger.info(+ "[AgentServer] team message entering runner streaming: channel_id=%s session_id=%s"+ " round_id=%s query=%s",+ _resolve_channel_id(channel_id),+ session_id,+ round_id,+ _safe_query_preview(initial_query),+ )+ runner_entered_at = time.monotonic()async for chunk in Runner.run_agent_team_streaming(agent_team=team_spec,inputs={"query": initial_query},@@ -1967,6 +1984,20 @@ async def _consume_stream_with_query(stream_logger=lg,):received_chunks += 1+ # First event of any kind from the runner — usually a framework+ # control event (team.runtime_ready and friends), not model output.+ # It marks how long team startup took before the stream came alive.+ if received_chunks == 1:+ server_logger.info(+ "[AgentServer] team runner streaming first event: channel_id=%s session_id=%s"+ " round_id=%s elapsed_ms=%.1f role=%s type=%s",+ _resolve_channel_id(channel_id),+ session_id,+ round_id,+ (time.monotonic() - runner_entered_at) * 1000,+ getattr(chunk, "role", None),+ getattr(chunk, "type", None),+ )# 诊断:每 30 个 chunk 或首个 chunk 时打印进度if received_chunks == 1 or received_chunks % 30 == 0:_role = getattr(chunk, "role", None)@@ -1994,6 +2025,21 @@ async def _consume_stream_with_query(continueparsed = parse_stream_chunk(chunk)if parsed is not None:+ # Time to first token: the first frame actually produced by a+ # model (reasoning counts — on a thinking model it comes first).+ if first_model_output_at is None and parsed.get("event_type") in _MODEL_OUTPUT_EVENT_TYPES:+ first_model_output_at = time.monotonic()+ server_logger.info(+ "[AgentServer] team runner first model output: channel_id=%s session_id=%s"+ " round_id=%s elapsed_ms=%.1f received=%s event_type=%s role=%s",+ _resolve_channel_id(channel_id),+ session_id,+ round_id,+ (first_model_output_at - runner_entered_at) * 1000,+ received_chunks,+ parsed.get("event_type"),+ parsed.get("role") or getattr(chunk, "role", None),+ )if not is_leader and parsed.get("event_type") == "chat.reasoning":continueif _is_duplicate_ask_user_question(parsed, emitted_ask_user_request_ids):