Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: support debug and trace

huanggawaa83f4361e1ce
diff --git a/deploy/observability/upload_traces_to_langfuse.py b/deploy/observability/upload_traces_to_langfuse.py
index 6bfff61ab2..6edd4b18f1 100644
--- a/deploy/observability/upload_traces_to_langfuse.py
+++ b/deploy/observability/upload_traces_to_langfuse.py
@@ -49,7 +49,14 @@ from pathlib import Path
_logger = logging.getLogger(__name__)
-_COLLECTOR = "http://localhost:4318/v1/traces"
+# NOTE: use 127.0.0.1, not "localhost". On macOS, getaddrinfo("localhost")
+# returns IPv6 ::1 first and Python's socket.create_connection stops at the
+# first address whose TCP handshake completes. Docker Desktop's IPv6 loopback
+# port-forward accepts the connection but cannot relay it to the container,
+# answering 502 Bad Gateway with an empty body — so every POST fails. The
+# IPv4 path (127.0.0.1) works. curl avoids this via Happy Eyeballs; Python does
+# not fall back once ::1 connects. See deploy/observability/README.md.
+_COLLECTOR = "http://127.0.0.1:4318/v1/traces"
def _default_traces_dir() -> str:
diff --git a/jiuwenswarm/agents/harness/agent_observability.py b/jiuwenswarm/agents/harness/agent_observability.py
new file mode 100644
index 0000000000..78397aa502
--- /dev/null
+++ b/jiuwenswarm/agents/harness/agent_observability.py
@@ -0,0 +1,278 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Single-agent / coding-agent observability lifecycle.
+
+This is the non-team counterpart of the team observability adapter in
+``jiuwenswarm.agents.harness.team.team_manager`` (``sync_team_observability``
+/ ``shutdown_team_observability``). It is kept in a **separate file with its
+own state and config section** on purpose, so the existing team scenario is
+not affected.
+
+Once ``openjiuwen.agent_teams.observability.init_observability`` has run, the
+generic ``OtelCallbackHandler`` is registered against the **global**
+``Runner.callback_framework``. LLM and tool events are emitted from the shared
+foundation layer (``core/foundation/llm/model.py`` /
+``core/foundation/tool/base.py``) for *every* agent, team or not — so simply
+ensuring the provider is initialized before ``Runner.run_agent_streaming`` /
+``Runner.run_agent`` gives single-agent and coding-agent runs automatic
+LLM/tool span tracing. The team-only ``OtelTeamMonitorHandler`` (team/member/
+task/message spans) is intentionally never attached here.
+
+Shared-provider caveat (important):
+ OpenTelemetry allows exactly ONE global ``TracerProvider`` per process,
+ and ``init_observability`` is a no-op if already initialized. In a process
+ where BOTH team and agent observability are enabled, whichever runs first
+ wins; the other silently reuses it (its exporter/endpoint/service_name are
+ ignored). To stay safe in that case we track ``_agent_owns_provider``:
+ agent shutdown only tears down the provider when the agent actually
+ created it, and never tears down a provider the team subsystem depends on.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from jiuwenswarm.common.config import get_config
+from jiuwenswarm.common.utils import get_user_workspace_dir
+
+logger = logging.getLogger(__name__)
+
+# ── Single-Agent Observability ─────────────────────────────────
+# Tracks whether observability is currently active so we can detect config
+# toggles (enabled -> disabled or vice-versa) and init / shutdown accordingly
+# on each single-agent request.
+_agent_observability_active: bool = False
+# True only when THIS module called ``init_observability()`` and therefore owns
+# the shared global TracerProvider. When the team subsystem (or a prior run)
+# already initialized it, this is False and shutdown must leave it intact.
+_agent_owns_provider: bool = False
+# Sticky flag: once any single-agent request has force-enabled observability
+# (e.g. a ``/debug`` run with ``debug_trace.<mode>.otel_enabled``), we never
+# auto-teardown the provider for the rest of the process. OTel allows only one
+# global TracerProvider and re-init after shutdown is fragile, so a /debug
+# toggle must not churn init/shutdown across alternating requests. The normal
+# config-gated path (agent_observability.enabled hot-reload) is unaffected
+# unless force was ever used.
+_force_ever_enabled: bool = False
+
+
+def sync_agent_observability(*, force: bool = False) -> None:
+ """Synchronize single-agent observability state with current config.
+
+ Called before each ``Runner.run_agent_streaming`` / ``Runner.run_agent`` so
+ that hot-reloading the ``agent_observability.enabled`` flag takes effect
+ immediately:
+
+ * disabled -> enabled : ``init_observability()`` (or reuse if already up)
+ * enabled -> disabled : ``shutdown_agent_observability()``
+ * unchanged : no-op
+
+ ``force=True`` (set by a ``/debug`` run when ``debug_trace.<mode>.otel_enabled``
+ is true) treats ``want_enabled`` as true regardless of config, so a debug
+ request can pull up OTel even when ``agent_observability.enabled`` is false.
+ Once force is ever used, the provider stays up for the process (sticky — see
+ ``_force_ever_enabled``) to avoid init/shutdown churn across alternating
+ requests; the normal config hot-reload teardown is unchanged otherwise.
+ """
+ global _agent_observability_active, _agent_owns_provider, _force_ever_enabled
+
+ cfg = get_config().get("agent_observability", {}) or {}
+ want_enabled = bool(cfg.get("enabled", False)) or force
+ if force:
+ _force_ever_enabled = True
+
+ if want_enabled and not _agent_observability_active:
+ try:
+ from openjiuwen.agent_teams.observability import (
+ ObservabilityConfig,
+ init_observability,
+ is_initialized,
+ )
+
+ if is_initialized():
+ # Another subsystem (e.g. team) already owns the provider.
+ # Reuse it so the global OtelCallbackHandler keeps emitting
+ # LLM/tool spans for this single agent too — do NOT re-init.
+ _agent_observability_active = True
+ _agent_owns_provider = False
+ logger.info(
+ "[AgentObservability] reusing existing observability provider "
+ "(owned by another subsystem)"
+ )
+ return
+
+ obs_cfg = ObservabilityConfig(
+ enabled=True,
+ service_name=cfg.get("service_name", "jiuwenswarm-agent"),
+ exporter=cfg.get("exporter", "otlp_grpc"),
+ endpoint=cfg.get("endpoint", "http://localhost:4317"),
+ sample_rate=cfg.get("sample_rate", 1.0),
+ attribute_value_max_length=cfg.get("attribute_value_max_length", 10240),
+ redact_prompts=cfg.get("redact_prompts", False),
+ redact_completions=cfg.get("redact_completions", False),
+ langfuse_public_key=cfg.get("langfuse_public_key", ""),
+ langfuse_secret_key=cfg.get("langfuse_secret_key", ""),
+ traces_dir=cfg.get("traces_dir") or str(get_user_workspace_dir() / ".trace"),
+ file_retention_days=cfg.get("file_retention_days", 7),
+ )
+ init_observability(obs_cfg)
+ _agent_observability_active = True
+ _agent_owns_provider = True
+ if obs_cfg.exporter == "file":
+ logger.info(
+ "[AgentObservability] enabled: exporter=%s traces_dir=%s",
+ obs_cfg.exporter, obs_cfg.traces_dir,
+ )
+ else:
+ logger.info(
+ "[AgentObservability] enabled: exporter=%s endpoint=%s",
+ obs_cfg.exporter, obs_cfg.endpoint,
+ )
+ except Exception as exc:
+ logger.warning("[AgentObservability] init failed: %s", exc)
+
+ elif not want_enabled and _agent_observability_active and not _force_ever_enabled:
+ shutdown_agent_observability()
+
+
+def shutdown_agent_observability() -> None:
+ """Shutdown single-agent observability (on disable or process exit)."""
+ global _agent_observability_active, _agent_owns_provider
+ if not _agent_observability_active:
+ return
+
+ if not _agent_owns_provider:
+ # Provider is owned by the team subsystem (or another run); tearing it
+ # down here would break team tracing. Just drop our activation flag.
+ _agent_observability_active = False
+ logger.info(
+ "[AgentObservability] disabled (provider owned elsewhere, left intact)"
+ )
+ return
+
+ try:
+ from openjiuwen.agent_teams.observability import shutdown_observability
+
+ shutdown_observability()
+ _agent_observability_active = False
+ _agent_owns_provider = False
+ logger.info("[AgentObservability] disabled")
+ except Exception as exc:
+ logger.warning("[AgentObservability] shutdown failed: %s", exc)
+
+
+# ── Per-run root span ───────────────────────────────────────────
+# openjiuwen's OtelCallbackHandler skips LLM/tool span creation when no parent
+# span exists (``get_team_span`` / ``get_current_agent_span`` both None — see
+# callback_handler._get_parent_context_for_llm_tool). Single-agent runs set
+# neither, so without a root span zero spans are produced even after a clean
+# ``init_observability``. These helpers open a root span and register it via
+# ``set_team_span`` — the exact mechanism team mode uses internally
+# (team_runner._maybe_attach_observability → get_or_create_team_span). LLM/tool
+# spans then nest under it and are exported.
+#
+# Usage (must be paired, in the same coroutine so the ContextVar propagates
+# into the runner's LLM calls):
+# handle = open_agent_run_span(session_id=sid)
+# try:
+# ... Runner.run_agent_streaming / Runner.run_agent ...
+# finally:
+# close_agent_run_span(handle)
+def _build_run_span_name(*, mode: str, session_id: str) -> str:
+ """Build a hierarchical OTel span name: ``agent.<mode>.<session_id>``.
+
+ ``mode`` is the JiuwenSwarm request mode, shaped ``<category>.<submode>``
+ (e.g. ``agent.plan`` / ``agent.fast`` / ``code.normal`` / ``code.plan``),
+ so it yields the hierarchy directly:
+
+ agent.plan -> agent.agent.plan.<session_id>
+ code.normal -> agent.code.normal.<session_id>
+
+ Falls back gracefully when either component is empty.
+ """
+ m = (mode or "").strip()
+ sid = (session_id or "").strip()
+ if not m:
+ return f"agent.run.{sid}" if sid else "agent.run"
+ if not sid:
+ return f"agent.{m}.run"
+ return f"agent.{m}.{sid}"
+
+
+def open_agent_run_span(*, session_id: str = "", mode: str = "") -> Any:
+ """Open a root team span around a single-agent run.
+
+ Returns an opaque handle to pass to :func:`close_agent_run_span`, or
+ ``None`` when observability is not initialized (in which case closing is
+ a no-op).
+ """
+ try:
+ from opentelemetry.trace import SpanKind
+
+ from openjiuwen.agent_teams.observability import (
+ get_tracer,
+ is_initialized,
+ )
+ from openjiuwen.agent_teams.observability.semconv import LANGFUSE_SESSION_ID
+ from openjiuwen.agent_teams.observability.span_context import set_team_span
+
+ if not is_initialized():
+ return None
+
+ tracer = get_tracer("jiuwenswarm.agent")
+ name = _build_run_span_name(mode=mode, session_id=session_id)
+ span = tracer.start_span(name=name, kind=SpanKind.SERVER)
+ span.set_attribute(LANGFUSE_SESSION_ID, session_id or "")
+ # Tag the mode so traces can be filtered in Langfuse without parsing
+ # the span name.
+ span.set_attribute("jiuwenswarm.mode", mode or "")
+ # Register as the team span so OtelCallbackHandler's parent lookup
+ # (get_team_span fallback) finds it for LLM/tool span creation.
+ set_team_span(span, team_name="single-agent")
+ logger.info("[AgentObservability] root span opened: name=%s", name)
+ return span
+ except Exception as exc:
+ logger.warning("[AgentObservability] open root span failed: %s", exc)
+ return None
+
+
+def close_agent_run_span(handle: Any) -> None:
+ """End the root span opened by :func:`open_agent_run_span` and clear it."""
+ if handle is None:
+ return
+ try:
+ from openjiuwen.agent_teams.observability.span_context import (
+ cascade_close_children,
+ clear_team_span,
+ flush_child_spans,
+ )
+
+ # End any still-open child LLM/tool spans (e.g. run aborted mid-call).
+ # Two nets are needed for the single-agent path:
+ # 1. cascade_close_children — closes spans whose state was pushed on
+ # the _llm_span_stack / _tool_span_map ContextVars in THIS context.
+ # 2. flush_child_spans — the SpanProcessor-backed safety net Team mode
+ # relies on (finalize_trace -> flush_child_spans via
+ # ActiveSpanTracker). The single-agent runner opens LLM spans inside
+ # its own child context, so their ContextVar state is not visible
+ # here; the tracker closes them by trace_id regardless of context.
+ # Must run BEFORE handle.end()/clear_team_span(): flush_child_spans reads
+ # the team span ContextVar to resolve this trace's id, and scopes the
+ # close to our trace only (flush_spans_for_trace), so concurrent runs are
+ # not affected.
+ try:
+ cascade_close_children()
+ except Exception as exc:
+ logger.debug("[AgentObservability] cascade_close_children failed: %s", exc)
+ try:
+ flush_child_spans()
+ except Exception as exc:
+ logger.debug("[AgentObservability] flush_child_spans failed: %s", exc)
+ try:
+ handle.end()
+ except Exception as exc:
+ logger.debug("[AgentObservability] end root span failed: %s", exc)
+ clear_team_span()
+ except Exception as exc:
+ logger.warning("[AgentObservability] close root span failed: %s", exc)
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/debug.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/debug.ts
new file mode 100644
index 0000000000..66a2f71571
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/debug.ts
@@ -0,0 +1,31 @@
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+/**
+ * /debug - 为本轮请求开启调试 dump(透传到服务端解析)。
+ * Usage: /debug <prompt>
+ *
+ * 将原始 `/debug <prompt>` 字符串原样发往后端。后端 adapter 剥离前缀、
+ * 挂载 DebugTraceLogger,把模型输出与工具调用写入
+ * `~/.jiuwenswarm/.agent/traces/` 或 `.code/traces/` 下的 dump 文件。
+ * 解析逻辑集中在服务端,TUI 只做透传,与 Team 模式行为一致。
+ */
+export function createDebugCommand(): SlashCommand {
+ return {
+ name: "debug",
+ description: "为本轮请求开启调试 dump(透传到服务端解析)",
+ usage: "/debug <prompt>",
+ example: "/debug 你好",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: (ctx, args) => {
+ const command = args.trim() ? `/debug ${args.trim()}` : "/debug";
+ const requestId = ctx.sendMessage(command);
+ if (!requestId) {
+ ctx.addItem(
+ makeItem(ctx.sessionId, "error", "offline: 等待重连后再发送 /debug 请求"),
+ );
+ }
+ },
+ };
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
index fe834ac0f0..3c463c4baf 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
@@ -109,13 +109,18 @@ export function createModeCommand(): SlashCommand {
ctx.sendEventOnly("chat.interrupt", { intent: "cancel", mode: currentMode });
}
+ // Optimistically update this.mode BEFORE the async mode.set round-trip.
+ // Otherwise a message sent immediately after /mode (e.g. /debug) reads
+ // the stale mode in sendMessage and is dispatched with the old mode.
+ // mode.set is best-effort: many backends carry the mode per chat.send, so
+ // a failed mode.set is ignored (matching prior behavior — no rollback).
+ ctx.setMode(nextMode);
+ ctx.addItem(makeItem(ctx.sessionId, "info", `Mode set to ${nextMode}`, "m"));
try {
await ctx.request("mode.set", { mode: nextMode });
} catch {
// Some backends still accept mode only on chat.send.
}
- ctx.setMode(nextMode);
- ctx.addItem(makeItem(ctx.sessionId, "info", `Mode set to ${nextMode}`, "m"));
},
};
}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
index 39e27c26b2..24ed982c93 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
@@ -48,6 +48,7 @@ import { createThemeCommand } from "./builtins/theme.js";
import { createWorkspaceCommand } from "./builtins/workspace-dir.js";
import { createUsageCommand } from "./builtins/usage.js";
import { createReviewCommand } from "./builtins/review.js";
+import { createDebugCommand } from "./builtins/debug.js";
import { createSecurityReviewCommand } from "./builtins/security-review.js";
export function createBuiltinCommands(): SlashCommand[] {
@@ -95,6 +96,7 @@ export function createBuiltinCommands(): SlashCommand[] {
createWorkspaceCommand(),
createUsageCommand(),
createReviewCommand(),
+ createDebugCommand(),
createSecurityReviewCommand(),
createMemoryCommand(),
createPluginCommand(),
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index f0131ecbab..ee764cb00a 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -352,6 +352,74 @@ team_observability:
traces_dir: "" # file exporter 输出目录,默认 ~/.jiuwenswarm/.trace
file_retention_days: 7 # file exporter 文件保留天数
+# ============================================================
+# 单 Agent / Coding Agent 可观测性配置
+# ============================================================
+# 与 team_observability 对应,但作用于非 team 的运行路径
+#(Runner.run_agent / Runner.run_agent_streaming,即 agent.* 与 code.* 模式)。
+# 启用后会调用 init_observability() 注册全局 OtelCallbackHandler,
+# 自动为 LLM 调用与工具调用生成 span(不含 team/member/task 级 span,
+# 那是 team 模式专属)。
+#
+# 注意:OTel 一个进程只允许一个全局 TracerProvider。若本进程内 team 与
+# agent 可观测性同时开启,先初始化的一方生效,另一方复用同一个 provider
+#(其 exporter/endpoint 会被忽略)。代码层面用 ownership 标记保证
+# 关闭时不会误拆对方依赖的 provider。
+#
+# 前置条件(otlp 模式):启动 OTel Collector + Langfuse。
+# ============================================================
+agent_observability:
+ enabled: false # 单 agent 可观测性总开关
+ exporter: file # otlp_grpc / otlp_http / file
+ endpoint: http://localhost:4317 # OTLP gRPC endpoint(file 模式不需要)
+ service_name: jiuwenswarm-agent # 服务名称(OTel resource service.name)
+ sample_rate: 1.0 # 采样率 (0.0-1.0)
+ redact_prompts: false # 是否脱敏 prompt 内容
+ redact_completions: false # 是否脱敏 completion 内容
+ attribute_value_max_length: 10240 # OTel attribute value 最大长度
+ langfuse_public_key: "" # Langfuse OTLP 认证 public key(可选)
+ langfuse_secret_key: "" # Langfuse OTLP 认证 secret key(可选)
+ traces_dir: "" # file exporter 输出目录,默认 ~/.jiuwenswarm/.trace
+ file_retention_days: 7 # file exporter 文件保留天数
+
+# ============================================================
+# Agent / Code 调试链路追踪(Debug Trace)配置
+# ============================================================
+# 控制非 team 模式(agent.* / code.*)的人类可读本地 dump。
+# 生效逻辑(resolve_debug_trace_settings):
+# debug_enabled = 请求带 /debug OR debug_trace.enabled OR debug_trace.<mode>.enabled
+# dump_enabled = debug_enabled AND debug_trace.<mode>.dump_enabled != false
+# dump 写入 ~/.jiuwenswarm/.agent/traces/ 或 .code/traces/(按模式)。
+# 与 agent_observability(OTel span)相互独立:本块只管本地文本 dump,
+# OTel 接入在后续阶段。
+# ============================================================
+debug_trace:
+ enabled: false # 全局开关(true=所有模式常开 dump)
+ agent: # agent 模式(agent.plan / agent.fast …)
+ enabled: false # 仅 agent 模式开关
+ dump_enabled: true # debug 开启时是否写本地 dump
+ otel_enabled: false # debug 时是否顺带 force-enable agent_observability(产 OTel span)
+ include_model_output: true # 记录模型文本输出
+ include_reasoning: true # 记录推理片段
+ include_tool_args: true # 记录工具参数
+ include_tool_result: true # 记录工具结果
+ code: # code 模式(code.normal / code.plan …)
+ enabled: false
+ dump_enabled: true
+ otel_enabled: false # debug 时是否顺带 force-enable agent_observability(产 OTel span)
+ include_model_output: true
+ include_reasoning: true
+ include_tool_args: true
+ include_tool_result: true
+ limits:
+ tool_args_max_chars: 2000 # 工具参数截断阈值
+ tool_result_max_chars: 8000 # 工具结果截断阈值
+ generic_payload_max_chars: 4000 # 通用载荷/run input 截断阈值
+ max_model_output_chars: # 空=不截模型输出;填数字则截断
+ redaction:
+ redact_prompts: false # 脱敏 prompt/completion(密钥字段始终打码)
+ redact_completions: false
+
react:
agent_name: main_agent
enable_task_loop: false
diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.py
index 1d3abbe3ba..266dc97353 100644
--- a/jiuwenswarm/server/app_agentserver.py
+++ b/jiuwenswarm/server/app_agentserver.py
@@ -225,6 +225,16 @@ async def _run(host: str, port: int) -> None:
shutdown_team_observability()
except Exception as exc:
logger.warning("[AgentServer] team observability shutdown failed: %s", exc)
+ # Shutdown single-agent / coding-agent observability. Independently
+ # tracked from team observability; no-op unless an agent run owned the
+ # provider (it will not tear down a provider the team still owns).
+ try:
+ from jiuwenswarm.agents.harness.agent_observability import (
+ shutdown_agent_observability,
+ )
+ shutdown_agent_observability()
+ except Exception as exc:
+ logger.warning("[AgentServer] agent observability shutdown failed: %s", exc)
logger.info("[AgentServer] stopped")
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index dacc67606f..d93c5f81a2 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -914,6 +914,16 @@ class JiuWenSwarm:
query = params.get("query")
if query is None or query == "":
query = params.get("content", "")
+ # /debug 请求级指令:仅 agent/code 在此剥离前缀;team 自行从原始
+ # query 解析 /debug(process_message_stream 用 raw_query 覆写
+ # inputs["query"]),故此处对 team 不剥离。
+ _request_debug = False
+ _dbg_mode = params.get("mode")
+ _dbg_mode_s = _dbg_mode.strip().lower() if isinstance(_dbg_mode, str) else ""
+ if not (params.get("team") or _dbg_mode_s in {"team", "team.plan", "code.team"}):
+ if isinstance(query, str):
+ from jiuwenswarm.server.runtime.debug_trace.directives import strip_debug_directive
+ query, _request_debug = strip_debug_directive(query)
if self._is_malformed_team_plan_approval_payload(params):
raise _TeamPlanApprovalPayloadError(self._team_plan_approval_payload_error_message())
channel = request.channel_id or (request.session_id.split('_')[0] if request.session_id else "web")
@@ -1010,6 +1020,8 @@ class JiuWenSwarm:
"channel": channel,
"language": language,
}
+ if _request_debug:
+ inputs["_request_debug"] = True
if request.metadata and request.metadata.get("skip_a2ui") is True:
inputs["skip_a2ui"] = True
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index a9dbe985e7..05ba87fcd3 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -667,6 +667,19 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
)
except Exception as e:
logger.warning("[JiuwenSwarmCodeAdapter] Failed to load UserHookRail: %s", e)
+ # Observability rail: opens an agent-layer span (agent.<name>.task_iteration.<n>
+ # for task-loop runs, or agent.<name>.invoke for single-round) under the root
+ # run span per iteration/round. It is the only thing that creates the
+ # task_iteration / invoke spans that llm.call + tool.* nest under. It
+ # self-disables (before_* returns early when get_team_span() is None), so
+ # attaching it unconditionally is safe and also adapts to runtime
+ # enable/disable of agent_observability without rebuilding the agent.
+ try:
+ from openjiuwen.agent_teams.observability.rail import ObservabilityRail
+ rails_list.append(ObservabilityRail())
+ logger.info("[JiuwenSwarmCodeAdapter] ObservabilityRail attached")
+ except Exception as e:
+ logger.warning("[JiuwenSwarmCodeAdapter] Failed to attach ObservabilityRail: %s", e)
return rails_list
# ─── Code 专属 Rail 构建 ────────────────
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 112208ab1a..597f5b82ad 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -3871,6 +3871,19 @@ class JiuWenSwarmDeepAdapter:
)
except Exception as e:
logger.warning("[JiuWenSwarmDeepAdapter] Failed to load UserHookRail: %s", e)
+ # Observability rail: opens an agent-layer span (agent.<name>.task_iteration.<n>
+ # for task-loop runs, or agent.<name>.invoke for single-round) under the root
+ # run span per iteration/round. It is the only thing that creates the
+ # task_iteration / invoke spans that llm.call + tool.* nest under. It
+ # self-disables (before_* returns early when get_team_span() is None), so
+ # attaching it unconditionally is safe and also adapts to runtime
+ # enable/disable of agent_observability without rebuilding the agent.
+ try:
+ from openjiuwen.agent_teams.observability.rail import ObservabilityRail
+ rails_list.append(ObservabilityRail())
+ logger.info("[JiuWenSwarmDeepAdapter] ObservabilityRail attached")
+ except Exception as e:
+ logger.warning("[JiuWenSwarmDeepAdapter] Failed to attach ObservabilityRail: %s", e)
return rails_list
@staticmethod
@@ -6215,6 +6228,7 @@ class JiuWenSwarmDeepAdapter:
if self._stream_event_rail is not None:
self._stream_event_rail.reset_abort(session_id)
image_files_token = None
+ _run_span: Any = None
try:
await self._update_runtime_config(
self._RuntimeConfig(
@@ -6251,6 +6265,16 @@ class JiuWenSwarmDeepAdapter:
image_files_token = set_current_multimodal_image_files(
inputs.pop("_multimodal_image_files", []) or []
)
+ # Sync single-agent / coding-agent observability with current
+ # config before running, and open a root span so OtelCallbackHandler
+ # has a parent for LLM/tool spans (see streaming path for details).
+ from jiuwenswarm.agents.harness.agent_observability import (
+ close_agent_run_span,
+ open_agent_run_span,
+ sync_agent_observability,
+ )
+ sync_agent_observability()
+ _run_span = open_agent_run_span(session_id=session_id, mode=mode)
result = await Runner.run_agent(agent=self._instance, inputs=inputs)
except asyncio.CancelledError:
logger.info(
@@ -6263,6 +6287,7 @@ class JiuWenSwarmDeepAdapter:
logger.error("[JiuWenSwarmDeepAdapter] Agent 任务执行异常: %s", e)
raise
finally:
+ close_agent_run_span(_run_span)
if image_files_token is not None:
from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
reset_current_multimodal_image_files,
@@ -6484,6 +6509,8 @@ class JiuWenSwarmDeepAdapter:
self._register_session_agent_task(session_id)
stream_consumer_cancelled = False
image_files_token = None
+ _run_span: Any = None
+ _debug_logger = None
try:
await self._update_runtime_config(
self._RuntimeConfig(
@@ -6534,7 +6561,64 @@ class JiuWenSwarmDeepAdapter:
image_files_token = set_current_multimodal_image_files(
inputs.pop("_multimodal_image_files", []) or []
)
+ # Resolve debug-trace settings early: its otel_enabled drives the
+ # OTel force-enable below. Best-effort (config read never raises).
+ from jiuwenswarm.server.runtime.debug_trace.config import (
+ resolve_debug_trace_settings,
+ )
+ _dbg_settings = resolve_debug_trace_settings(
+ mode=mode, request_debug=bool(inputs.get("_request_debug"))
+ )
+ # Sync single-agent / coding-agent observability with current config
+ # before running. init_observability() wires the global
+ # OtelCallbackHandler so LLM/tool spans are emitted automatically.
+ # force=True (a /debug run with debug_trace.<mode>.otel_enabled) pulls
+ # up OTel even when agent_observability.enabled is false.
+ from jiuwenswarm.agents.harness.agent_observability import (
+ close_agent_run_span,
+ open_agent_run_span,
+ sync_agent_observability,
+ )
+ sync_agent_observability(force=_dbg_settings.otel_enabled)
+ # Open a root span so OtelCallbackHandler has a parent for LLM/tool
+ # spans. Closed in the finally below.
+ _run_span = open_agent_run_span(session_id=session_id, mode=mode)
+ # Capture OTel trace/span ids (empty when no span was opened, e.g.
+ # OTel not enabled) so the dump can be cross-referenced with a trace.
+ _otel_trace_id = ""
+ _otel_span_id = ""
+ if _run_span is not None:
+ try:
+ _span_ctx = _run_span.get_span_context()
+ _otel_trace_id = format(_span_ctx.trace_id, "032x")
+ _otel_span_id = format(_span_ctx.span_id, "016x")
+ except Exception:
+ pass
+ # --- debug trace dump (request-level /debug OR config-level, best-effort) ---
+ try:
+ from jiuwenswarm.server.runtime.debug_trace.paths import debug_trace_file
+ from jiuwenswarm.server.runtime.debug_trace.stream_logger import (
+ DebugTraceLogger,
+ )
+ if _dbg_settings.enabled and _dbg_settings.dump_enabled:
+ _debug_logger = DebugTraceLogger(
+ file_path=debug_trace_file(mode, session_id),
+ mode=mode,
+ session_id=session_id,
+ request_id=rid,
+ settings=_dbg_settings,
+ )
+ _debug_logger.start_run(
+ input_text=inputs.get("query"),
+ otel_trace_id=_otel_trace_id,
+ otel_span_id=_otel_span_id,
+ )
+ except Exception as _dbg_exc:
+ logger.warning("[JiuWenSwarmDeepAdapter] debug trace init failed: %s", _dbg_exc)
+ _debug_logger = None
async for chunk in Runner.run_agent_streaming(self._instance, inputs):
+ if _debug_logger is not None:
+ _debug_logger.feed(chunk)
if not (hasattr(chunk, "type") and hasattr(chunk, "payload")):
parsed = self._parse_stream_chunk(chunk)
if parsed is not None:
@@ -6729,6 +6813,8 @@ class JiuWenSwarmDeepAdapter:
)
task.add_done_callback(self._on_evolution_watcher_done)
self._evolution_watcher_tasks.add(task)
+ if _debug_logger is not None:
+ _debug_logger.end_run(status="ok")
except asyncio.CancelledError:
stream_consumer_cancelled = True
logger.info(
@@ -6743,9 +6829,13 @@ class JiuWenSwarmDeepAdapter:
self._resolve_interrupt_session_id(session_id),
"stream_cancel",
)
+ if _debug_logger is not None:
+ _debug_logger.end_run(status="cancelled")
raise
except Exception as exc:
logger.exception("[JiuWenSwarmDeepAdapter] 流式任务异常: %s", exc)
+ if _debug_logger is not None:
+ _debug_logger.end_run(status="error", error=exc)
yield AgentResponseChunk(
request_id=rid,
channel_id=cid,
@@ -6757,6 +6847,9 @@ class JiuWenSwarmDeepAdapter:
is_complete=False,
)
finally:
+ close_agent_run_span(_run_span)
+ if _debug_logger is not None:
+ _debug_logger.flush()
if image_files_token is not None:
from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
reset_current_multimodal_image_files,
diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
index 8f9268f381..a92673ae1e 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
@@ -95,7 +95,12 @@ _STREAM_TRACE_ENV_KEY = "JIUWENSWARM_TEAM_STREAM_TRACE"
# When set to "true", non-leader teammate frames are filtered out in team
# streaming so the frontend only receives leader output.
_HIDE_TEAMMATE_ENV_KEY = "JIUWENSWARM_TEAM_HIDE_TEAMMATE"
-_DEBUG_PREFIX = "/debug"
+# /debug 剥离原语与 Agent/Code 共享(debug_trace.directives),消除两份实现。
+# 别名保持 _DEBUG_PREFIX / _strip_directive 不变,_extract_query_directives 零改动。
+from jiuwenswarm.server.runtime.debug_trace.directives import (
+ DEBUG_PREFIX as _DEBUG_PREFIX,
+ strip_slash_directive as _strip_directive,
+)
_FOLLOWUP_INTERACT_RETRY_TIMEOUT_SEC = 1.0
_FOLLOWUP_INTERACT_RACE_WAIT_TIMEOUT_SEC = 3.0
_FOLLOWUP_INTERACT_POLL_INTERVAL_SEC = 0.05
@@ -313,20 +318,6 @@ def _build_team_event_chunk_meta(event: Any) -> tuple[dict | None, dict]:
return agent_ref, metadata
-def _strip_directive(query: str, prefix: str) -> tuple[str, bool]:
- """Strip a leading slash directive from a query string.
-
- Returns the cleaned query and whether the directive was present.
- """
- stripped = query.lstrip()
- if not stripped.startswith(prefix):
- return query, False
- remainder = stripped[len(prefix):]
- if remainder and not remainder[0].isspace():
- return query, False
- return remainder.lstrip(), True
-
-
def _extract_query_directives(query: str) -> tuple[str, bool, bool]:
"""Strip all leading slash directives from the first team query.
diff --git a/jiuwenswarm/server/runtime/debug_trace/__init__.py b/jiuwenswarm/server/runtime/debug_trace/__init__.py
new file mode 100644
index 0000000000..d83bea074c
--- /dev/null
+++ b/jiuwenswarm/server/runtime/debug_trace/__init__.py
@@ -0,0 +1,30 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Agent/Code debug trace — request-level human-readable dump.
+
+Phase 1: request-level ``/debug`` directive only. Mirrors the Team mode
+``TeamStreamLogger`` concept (see ``openjiuwen.agent_teams.monitor``) but
+with mode/source fields instead of team member/role, plus explicit run
+boundaries. OTel and the ``debug_trace`` config block are deferred to
+later phases.
+"""
+
+from jiuwenswarm.server.runtime.debug_trace.config import (
+ DebugTraceSettings,
+ resolve_debug_trace_settings,
+)
+from jiuwenswarm.server.runtime.debug_trace.directives import strip_debug_directive
+from jiuwenswarm.server.runtime.debug_trace.paths import (
+ debug_trace_dir,
+ debug_trace_file,
+)
+from jiuwenswarm.server.runtime.debug_trace.stream_logger import DebugTraceLogger
+
+__all__ = [
+ "DebugTraceLogger",
+ "DebugTraceSettings",
+ "debug_trace_dir",
+ "debug_trace_file",
+ "resolve_debug_trace_settings",
+ "strip_debug_directive",
+]
diff --git a/jiuwenswarm/server/runtime/debug_trace/config.py b/jiuwenswarm/server/runtime/debug_trace/config.py
new file mode 100644
index 0000000000..a8b7ea6028
--- /dev/null
+++ b/jiuwenswarm/server/runtime/debug_trace/config.py
@@ -0,0 +1,122 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Effective debug-trace settings resolution.
+
+Merges the request-level ``/debug`` flag with the ``debug_trace`` config block:
+
+ debug_enabled = request_debug OR debug_trace.enabled OR debug_trace.<mode>.enabled
+ dump_enabled = debug_enabled AND debug_trace.<mode>.dump_enabled != false
+
+Per-mode ``include_*`` toggles, ``limits`` and ``redaction`` are read with
+sensible defaults. OTel is still off (third phase). Config reading is
+best-effort: any failure falls back to request-level-only behaviour.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+
+@dataclass(frozen=True)
+class DebugTraceSettings:
+ """Resolved debug-trace behaviour for one run."""
+
+ mode: str
+ enabled: bool
+ dump_enabled: bool
+ otel_enabled: bool
+ # Include toggles.
+ include_model_output: bool = True
+ include_reasoning: bool = True
+ include_tool_args: bool = True
+ include_tool_result: bool = True
+ # Payload caps (chars).
+ tool_args_max_chars: int = 2000
+ tool_result_max_chars: int = 8000
+ generic_payload_max_chars: int = 4000
+ max_model_output_chars: int | None = None # None = never cap model text
+ # Redaction (secret-key masking is always on regardless).
+ redact_prompts: bool = False
+ redact_completions: bool = False
+
+
+def _load_debug_trace_config() -> dict[str, Any]:
+ """Best-effort read of the ``debug_trace`` config block."""
+ try:
+ from jiuwenswarm.common.config import get_config
+
+ cfg = get_config().get("debug_trace", {})
+ return cfg if isinstance(cfg, dict) else {}
+ except Exception:
+ return {}
+
+
+def _mode_key(mode: str) -> str:
+ return "code" if (mode or "").startswith("code") else "agent"
+
+
+def _as_int(value: Any, default: int) -> int:
+ try:
+ if value is None or value == "":
+ return default
+ return int(value)
+ except (TypeError, ValueError):
+ return default
+
+
+def resolve_debug_trace_settings(*, mode: str, request_debug: bool) -> DebugTraceSettings:
+ """Resolve effective settings for *mode* given the request-level flag.
+
+ Merges request-level ``/debug`` with the ``debug_trace`` config block.
+ """
+ cfg = _load_debug_trace_config()
+ mode_cfg = cfg.get(_mode_key(mode), {})
+ if not isinstance(mode_cfg, dict):
+ mode_cfg = {}
+ limits = cfg.get("limits", {})
+ if not isinstance(limits, dict):
+ limits = {}
+ redaction = cfg.get("redaction", {})
+ if not isinstance(redaction, dict):
+ redaction = {}
+
+ debug_enabled = bool(
+ request_debug
+ or cfg.get("enabled")
+ or mode_cfg.get("enabled")
+ )
+ dump_enabled = debug_enabled and (mode_cfg.get("dump_enabled", True) is not False)
+ # /debug-driven OTel: only force-enable agent_observability when this run is
+ # debugged AND the mode opted into OTel. (When agent_observability.enabled is
+ # already true, OTel runs regardless — handled by sync_agent_observability.)
+ otel_enabled = debug_enabled and bool(mode_cfg.get("otel_enabled", False))
+
+ # max_model_output_chars: empty/None -> no cap.
+ mmo_raw = limits.get("max_model_output_chars")
+ max_model_output_chars: int | None = None
+ if mmo_raw not in (None, ""):
+ try:
+ max_model_output_chars = int(mmo_raw)
+ except (TypeError, ValueError):
+ max_model_output_chars = None
+
+ return DebugTraceSettings(
+ mode=mode,
+ enabled=debug_enabled,
+ dump_enabled=dump_enabled,
+ otel_enabled=otel_enabled,
+ include_model_output=bool(mode_cfg.get("include_model_output", True)),
+ include_reasoning=bool(mode_cfg.get("include_reasoning", True)),
+ include_tool_args=bool(mode_cfg.get("include_tool_args", True)),
+ include_tool_result=bool(mode_cfg.get("include_tool_result", True)),
+ tool_args_max_chars=_as_int(limits.get("tool_args_max_chars"), 2000),
+ tool_result_max_chars=_as_int(limits.get("tool_result_max_chars"), 8000),
+ generic_payload_max_chars=_as_int(limits.get("generic_payload_max_chars"), 4000),
+ max_model_output_chars=max_model_output_chars,
+ redact_prompts=bool(redaction.get("redact_prompts", False)),
+ redact_completions=bool(redaction.get("redact_completions", False)),
+ )
+
+
+__all__ = ["DebugTraceSettings", "resolve_debug_trace_settings"]
diff --git a/jiuwenswarm/server/runtime/debug_trace/directives.py b/jiuwenswarm/server/runtime/debug_trace/directives.py
new file mode 100644
index 0000000000..94138703cc
--- /dev/null
+++ b/jiuwenswarm/server/runtime/debug_trace/directives.py
@@ -0,0 +1,88 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Slash directive parsing — shared between Agent/Code and Team modes.
+
+``strip_slash_directive`` is the generic primitive (strip a leading
+``/<prefix> `` directive, requiring whitespace after the prefix). Team mode
+reuses it for ``/debug`` and ``/hide_dm``; Agent/Code use the
+``strip_debug_directive`` wrapper, which additionally tolerates a leading
+``<system-reminder>`` block (Plan mode) and rejects a bare ``/debug`` so an
+empty query never reaches the model.
+"""
+
+from __future__ import annotations
+
+import re
+
+DEBUG_PREFIX = "/debug"
+
+# A leading <system-reminder>...</system-reminder> block may be prepended to
+# the user query before it reaches the adapter — notably by Plan mode
+# (``agent_ws_server._inject_plan_mode_activation_reminder`` prepends it to
+# ``request.params["query"]`` for code.plan). The real user input follows it,
+# so /debug is no longer at offset 0. Match (non-greedy, DOTALL) and skip it.
+_LEADING_SYSTEM_REMINDER_RE = re.compile(
+ r"^(\s*<system-reminder>.*?</system-reminder>)(.*)", re.DOTALL
+)
+
+
+def strip_slash_directive(query: str, prefix: str) -> tuple[str, bool]:
+ """Strip a leading ``<prefix> `` directive from *query*.
+
+ Returns ``(cleaned_query, was_present)``. Requires whitespace after the
+ prefix (``/debugfoo x`` is NOT recognised for prefix ``/debug``). A bare
+ prefix with no following text IS recognised and yields ``("", True)`` —
+ callers that must reject a bare directive (e.g. Agent/Code ``/debug``)
+ do so themselves.
+
+ Non-str inputs are returned unchanged with ``was_present=False``.
+ """
+ if not isinstance(query, str):
+ return query, False
+ stripped = query.lstrip()
+ if not stripped.startswith(prefix):
+ return query, False
+ remainder = stripped[len(prefix):]
+ if remainder and not remainder[0].isspace():
+ return query, False
+ return remainder.lstrip(), True
+
+
+def _split_leading_system_reminder(query: str) -> tuple[str, str]:
+ """Split a leading ``<system-reminder>...</system-reminder>`` block off.
+
+ Returns ``(prefix, body)`` where *prefix* includes the reminder (kept
+ verbatim so Plan-mode guidance still reaches the model) and *body* is the
+ remaining user text. If there is no leading reminder, returns ``("", query)``.
+ """
+ m = _LEADING_SYSTEM_REMINDER_RE.match(query)
+ if m:
+ return m.group(1), m.group(2)
+ return "", query
+
+
+def strip_debug_directive(query: str) -> tuple[str, bool]:
+ """Strip a leading ``/debug `` directive from *query* (Agent/Code path).
+
+ Unlike the bare :func:`strip_slash_directive`, this:
+
+ * tolerates a leading ``<system-reminder>...</system-reminder>`` block
+ (injected by Plan mode before the adapter sees the query) — the reminder
+ is preserved and ``/debug`` is looked for in the user text after it;
+ * rejects a bare ``/debug`` with no prompt, so an empty query is never sent
+ to the model.
+
+ Returns ``(cleaned_query, was_present)``.
+ """
+ if not isinstance(query, str):
+ return query, False
+ prefix, body = _split_leading_system_reminder(query)
+ cleaned, present = strip_slash_directive(body, DEBUG_PREFIX)
+ if not present:
+ return query, False
+ if not cleaned.strip(): # bare /debug — reject (Agent/Code semantics)
+ return query, False
+ return prefix + cleaned, True
+
+
+__all__ = ["DEBUG_PREFIX", "strip_debug_directive", "strip_slash_directive"]
diff --git a/jiuwenswarm/server/runtime/debug_trace/paths.py b/jiuwenswarm/server/runtime/debug_trace/paths.py
new file mode 100644
index 0000000000..329811bf8c
--- /dev/null
+++ b/jiuwenswarm/server/runtime/debug_trace/paths.py
@@ -0,0 +1,46 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Debug trace directory / file resolution.
+
+All paths derive from ``jiuwenswarm.common.utils.get_user_workspace_dir``
+(respects ``JIUWENSWARM_DATA_DIR``, falls back to ``~/.jiuwenswarm``).
+Mode-prefixed dirs keep Agent and Code dumps separate:
+
+ ~/.jiuwenswarm/.agent/traces/dump-agent-<session_id>.txt
+ ~/.jiuwenswarm/.code/traces/dump-code-<session_id>.txt
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from jiuwenswarm.common.utils import get_user_workspace_dir
+
+
+def _safe_segment(value: str, fallback: str = "_") -> str:
+ """Sanitize an untrusted string into a single safe path segment.
+
+ Mirrors ``openjiuwen.agent_teams.paths._safe_segment``: replaces every
+ character outside ``[A-Za-z0-9_.-]`` with ``_`` and strips leading/
+ trailing separators so the result can never escape its parent dir.
+ """
+ normalized = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "").strip())
+ normalized = normalized.strip("._-")
+ return normalized[:96] or fallback
+
+
+def debug_trace_dir(mode: str) -> Path:
+ """Return the trace directory for *mode* (``.agent`` or ``.code``)."""
+ root = get_user_workspace_dir()
+ kind = ".code" if (mode or "").startswith("code") else ".agent"
+ return root / kind / "traces"
+
+
+def debug_trace_file(mode: str, session_id: str) -> Path:
+ """Return the per-session dump file path for *mode*."""
+ kind = "code" if (mode or "").startswith("code") else "agent"
+ return debug_trace_dir(mode) / f"dump-{kind}-{_safe_segment(session_id)}.txt"
+
+
+__all__ = ["debug_trace_dir", "debug_trace_file"]
diff --git a/jiuwenswarm/server/runtime/debug_trace/stream_logger.py b/jiuwenswarm/server/runtime/debug_trace/stream_logger.py
new file mode 100644
index 0000000000..14f4b860ff
--- /dev/null
+++ b/jiuwenswarm/server/runtime/debug_trace/stream_logger.py
@@ -0,0 +1,486 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Generic Agent/Code debug trace logger.
+
+Mirrors ``openjiuwen.agent_teams.monitor.TeamStreamLogger`` in spirit —
+aggregate token-streamed model output, categorise tool calls/results, write
+human-readable timestamped text records, and never let logging break the
+run — but adapted for single-agent / coding-agent streams:
+
+* record header uses ``mode=`` / ``source=`` (not team ``member=``/``role=``);
+* explicit ``run start`` / ``run end`` boundaries bracket each request;
+* chunk payloads follow the Agent/Code shapes (``payload["tool_call"]``,
+ ``payload["tool_result"]``, ``payload["usage_metadata"]`` …) seen in
+ ``interface_deep._parse_stream_chunk``;
+* payload truncation and secret-key masking are always on.
+
+The logger is best-effort throughout: any failure (dir creation, file open,
+per-chunk formatting) is swallowed so it can never affect the model run.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, TextIO
+
+from jiuwenswarm.server.runtime.debug_trace.config import DebugTraceSettings
+
+_logger = logging.getLogger(__name__)
+
+# ── chunk type vocabulary (mirrors interface_deep in-loop switch) ──────────
+_CHUNK_LLM_OUTPUT = "llm_output"
+_CHUNK_LLM_REASONING = "llm_reasoning"
+_CHUNK_LLM_USAGE = "llm_usage"
+_CHUNK_ANSWER = "answer"
+_CHUNK_TOOL_CALL = "tool_call"
+_CHUNK_TOOL_UPDATE = "tool_update"
+_CHUNK_TOOL_RESULT = "tool_result"
+
+_ACCUMULATING_TYPES = frozenset({_CHUNK_LLM_OUTPUT, _CHUNK_LLM_REASONING})
+
+# category -> level
+_CATEGORY_LEVEL = {
+ "text": "INFO",
+ "reasoning": "DEBUG",
+ "tool_call": "DEBUG",
+ "tool_result": "DEBUG",
+ "tool_update": "DEBUG",
+ "context_usage": "DEBUG",
+ "interaction": "WARN",
+ "controller_output": "WARN",
+ "message": "INFO",
+ "todo": "INFO",
+ "other": "INFO",
+}
+
+# secret-like dict keys whose values are masked even without full redaction.
+# Matched by tokenising the key on non-alphanumerics so that token COUNTS
+# (tokens_used, total_tokens, input_tokens …) are NOT mistaken for secrets,
+# while genuine secret names (access_token, api_key, password …) still match.
+_SECRET_TOKENS = frozenset(
+ {"token", "password", "passwd", "pwd", "secret", "apikey", "authorization",
+ "authorisation", "cookie"}
+)
+
+
+def _looks_secret(key: str) -> bool:
+ """True if *key* names a secret-like field whose value should be masked.
+
+ Tokenises the key on non-alphanumeric separators (``_ - . /`` …) so
+ ``tokens_used`` → {"tokens","used"} is NOT a secret (plural = a count),
+ but ``access_token`` → {"access","token"} and ``api_key`` → {"api","key"} are.
+ """
+ if not isinstance(key, str):
+ return False
+ tokens = {t for t in re.split(r"[^a-z0-9]+", key.lower()) if t}
+ if not tokens:
+ return False
+ if "tokens" in tokens: # plural = token counts (tokens_used, total_tokens)
+ return False
+ if tokens & _SECRET_TOKENS:
+ return True
+ if {"api", "key"} <= tokens: # api_key / api-key
+ return True
+ return False
+
+
+_UNKNOWN = "<unknown>"
+
+
+def _now_ts() -> str:
+ return datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
+
+
+def _truncate(text: str, limit: int | None) -> str:
+ """Truncate *text* to *limit* chars with a visible original-length marker.
+
+ ``None`` limit (or non-positive) means never truncate.
+ """
+ if not limit or limit <= 0:
+ return text
+ if len(text) <= limit:
+ return text
+ return text[:limit] + f"... (truncated, original_chars={len(text)})"
+
+
+def _mask_secrets(value: Any) -> Any:
+ """Recursively mask values whose dict key looks secret-like.
+
+ Returns a shallow-ish copy for dicts/lists so the caller's payload is
+ untouched. Non-container values pass through unchanged.
+ """
+ if isinstance(value, dict):
+ out: dict[str, Any] = {}
+ for k, v in value.items():
+ if isinstance(k, str) and _looks_secret(k):
+ out[k] = "***"
+ else:
+ out[k] = _mask_secrets(v)
+ return out
+ if isinstance(value, list):
+ return [_mask_secrets(v) for v in value]
+ return value
+
+
+def _extract_content(payload: Any) -> str:
+ if isinstance(payload, dict):
+ return payload.get("content", "") or payload.get("output", "") or ""
+ if isinstance(payload, str):
+ return payload
+ return str(payload) if payload is not None else ""
+
+
+def _classify(ctype: str, payload: Any) -> str:
+ if ctype in (_CHUNK_LLM_OUTPUT, _CHUNK_ANSWER):
+ return "text"
+ if ctype == _CHUNK_LLM_REASONING:
+ return "reasoning"
+ if ctype == _CHUNK_LLM_USAGE:
+ return "context_usage"
+ if ctype == _CHUNK_TOOL_CALL:
+ return "tool_call"
+ if ctype == _CHUNK_TOOL_RESULT:
+ return "tool_result"
+ if ctype == _CHUNK_TOOL_UPDATE:
+ return "tool_update"
+ if ctype == "controller_output":
+ return "controller_output"
+ if ctype == "message":
+ return "message"
+ if ctype == "todo.updated":
+ return "todo"
+ return "other"
+
+
+class _Run:
+ """A pending accumulation of token-streamed chunks (single source)."""
+
+ __slots__ = ("category", "buf")
+
+ def __init__(self, category: str) -> None:
+ self.category = category
+ self.buf: list[str] = []
+
+
+class DebugTraceLogger:
+ """Best-effort human-readable dump writer for one Agent/Code run.
+
+ Construct per request (when ``/debug`` is active), call ``start_run``
+ once, ``feed`` every stream chunk, then ``end_run`` + ``flush``. All
+ public methods are no-ops after a construction failure (``_disabled``).
+ """
+
+ def __init__(
+ self,
+ *,
+ file_path: Path | str,
+ mode: str,
+ session_id: str,
+ request_id: str | None,
+ round_id: int | None = None,
+ settings: DebugTraceSettings,
+ ) -> None:
+ self._mode = mode or ""
+ self._session_id = session_id or ""
+ self._request_id = request_id
+ self._round_id = round_id
+ self._settings = settings
+
+ self._path = Path(file_path)
+ self._file: TextIO | None = None
+ self._disabled = False
+ self._started = False
+ self._ended = False
+ self._start_monotonic: float | None = None
+ self._chunk_count = 0
+
+ # Single-source accumulation (Phase 1: no subagent source metadata).
+ self._run: _Run | None = None
+ self._llm_output_seen = False
+
+ try:
+ self._path.parent.mkdir(parents=True, exist_ok=True)
+ self._file = open(self._path, "a", encoding="utf-8")
+ except Exception as exc:
+ _logger.warning(
+ "[DebugTrace] disabled for session=%s mode=%s: open failed: %s",
+ self._session_id, self._mode, exc,
+ )
+ self._disabled = True
+
+ # ── public API ───────────────────────────────────────────────────────
+ def start_run(
+ self,
+ *,
+ input_text: str | None = None,
+ otel_trace_id: str = "",
+ otel_span_id: str = "",
+ ) -> None:
+ if self._disabled or self._started:
+ return
+ self._started = True
+ self._start_monotonic = time.monotonic()
+ try:
+ lines = [
+ "========== run start ==========",
+ f"timestamp={_now_ts()}",
+ f"mode={self._mode or _UNKNOWN}",
+ f"session_id={self._session_id or _UNKNOWN}",
+ f"request_id={self._request_id or _UNKNOWN}",
+ ]
+ if self._round_id is not None:
+ lines.append(f"round_id={self._round_id}")
+ # OTel ids when a run span was opened (empty when OTel not enabled).
+ # Lets the dump be cross-referenced with a Langfuse/collector trace.
+ lines.append(f"otel_trace_id={otel_trace_id or ''}")
+ lines.append(f"otel_span_id={otel_span_id or ''}")
+ preview = _truncate(
+ input_text or "",
+ self._settings.generic_payload_max_chars,
+ )
+ lines.append(f"input={preview}")
+ self._write_raw("\n".join(lines))
+ except Exception as exc:
+ self._safe_warn(f"start_run error: {exc!r}")
+
+ def feed(self, chunk: Any) -> None:
+ if self._disabled:
+ return
+ try:
+ self._feed(chunk)
+ except Exception as exc: # never break the stream
+ self._safe_warn(f"feed error: {exc!r}")
+
+ def end_run(self, *, status: str, error: BaseException | None = None) -> None:
+ if self._disabled or self._ended:
+ return
+ self._ended = True
+ try:
+ self._flush_run()
+ elapsed = (
+ int((time.monotonic() - self._start_monotonic) * 1000)
+ if self._start_monotonic is not None
+ else 0
+ )
+ lines = [
+ "========== run end ==========",
+ f"timestamp={_now_ts()}",
+ f"status={status}",
+ f"elapsed_ms={elapsed}",
+ f"chunks={self._chunk_count}",
+ ]
+ if error is not None:
+ lines.append(f"error_type={type(error).__name__}")
+ lines.append(f"error={error}")
+ self._write_raw("\n".join(lines))
+ except Exception as exc:
+ self._safe_warn(f"end_run error: {exc!r}")
+
+ def flush(self) -> None:
+ if self._disabled:
+ return
+ try:
+ self._flush_run()
+ if self._file is not None:
+ self._file.flush()
+ except Exception as exc:
+ _logger.debug("[DebugTrace] flush error: %s", exc)
+ finally:
+ if self._file is not None:
+ try:
+ self._file.close()
+ except Exception as exc:
+ _logger.debug("[DebugTrace] close error: %s", exc)
+ self._file = None
+
+ # ── internals ────────────────────────────────────────────────────────
+ def _feed(self, chunk: Any) -> None:
+ self._chunk_count += 1
+
+ ctype, payload = self._unpack(chunk)
+ if ctype is None:
+ # Dict / untyped chunk: record as 'other' for visibility.
+ self._flush_run()
+ self._emit("other", "main", _truncate(_safe_str(chunk), self._settings.generic_payload_max_chars))
+ return
+
+ category = _classify(ctype, payload)
+
+ # `answer` duplicates already-streamed llm_output — drop if seen.
+ if ctype == _CHUNK_ANSWER and self._llm_output_seen:
+ return
+
+ if ctype in _ACCUMULATING_TYPES:
+ if ctype == _CHUNK_LLM_OUTPUT and not self._settings.include_model_output:
+ return
+ if ctype == _CHUNK_LLM_REASONING and not self._settings.include_reasoning:
+ return
+ content = _extract_content(payload)
+ if not content:
+ return
+ if self._run is not None and self._run.category != category:
+ self._flush_run()
+ if self._run is None:
+ self._run = _Run(category)
+ self._run.buf.append(content)
+ if ctype == _CHUNK_LLM_OUTPUT:
+ self._llm_output_seen = True
+ return
+
+ # Discrete chunk: flush pending text, then emit a summary now.
+ self._flush_run()
+ summary = self._discrete_summary(ctype, category, payload)
+ if summary:
+ self._emit(category, "main", summary)
+
+ @staticmethod
+ def _unpack(chunk: Any) -> tuple[str | None, Any]:
+ """Extract (type, payload) from a chunk, tolerating shapes."""
+ ctype = getattr(chunk, "type", None)
+ payload = getattr(chunk, "payload", None)
+ if ctype is None and isinstance(chunk, dict):
+ ctype = chunk.get("type") or chunk.get("event_type")
+ payload = chunk.get("payload") or chunk.get("data") or chunk
+ return (str(ctype) if ctype is not None else None), payload
+
+ def _discrete_summary(self, ctype: str, category: str, payload: Any) -> str:
+ s = self._settings
+ if category == "tool_call":
+ return self._tool_call_summary(payload, s.tool_args_max_chars)
+ if category == "tool_result":
+ return self._tool_result_summary(payload, s.tool_result_max_chars)
+ if category == "tool_update":
+ return self._tool_update_summary(payload, s.tool_args_max_chars)
+ if category == "context_usage":
+ return self._usage_summary(payload)
+ if ctype in ("controller_output", "message", "todo.updated"):
+ content = _extract_content(payload)
+ if content:
+ return _truncate(content, s.generic_payload_max_chars)
+ return _truncate(_safe_str(_mask_secrets(_as_dict(payload))), s.generic_payload_max_chars)
+ # other
+ return _truncate(_safe_str(_mask_secrets(_as_dict(payload))), s.generic_payload_max_chars)
+
+ def _tool_call_summary(self, payload: Any, args_limit: int) -> str:
+ info = payload.get("tool_call", payload) if isinstance(payload, dict) else payload
+ info = _mask_secrets(_as_dict(info)) if isinstance(info, dict) else info
+ if not isinstance(info, dict):
+ return _truncate(_safe_str(info), self._settings.generic_payload_max_chars)
+ name = info.get("name") or info.get("tool_name") or ""
+ call_id = info.get("id") or info.get("tool_call_id") or ""
+ args_raw = info.get("arguments") or info.get("args") or info.get("tool_args") or ""
+ if not self._settings.include_tool_args:
+ args_raw = "<redacted>"
+ args = _truncate(_stringify(args_raw), args_limit)
+ return f"tool_name={name} tool_call_id={call_id}\narguments={args}"
+
+ def _tool_result_summary(self, payload: Any, result_limit: int) -> str:
+ info = payload.get("tool_result", payload) if isinstance(payload, dict) else payload
+ info = _mask_secrets(_as_dict(info)) if isinstance(info, dict) else info
+ if not isinstance(info, dict):
+ return _truncate(_safe_str(info), self._settings.generic_payload_max_chars)
+ name = info.get("tool_name") or info.get("name") or ""
+ call_id = info.get("tool_call_id") or info.get("id") or ""
+ lines = [f"tool_name={name} tool_call_id={call_id}"]
+ if info.get("is_error") or info.get("error"):
+ err = info.get("error", "")
+ lines.append(f"is_error=True error={_truncate(_stringify(err), result_limit)}")
+ status = info.get("status")
+ if status:
+ lines.append(f"status={status}")
+ if self._settings.include_tool_result:
+ result_raw = info.get("result")
+ if result_raw is None:
+ result_raw = info.get("raw_output", "")
+ lines.append(f"result: {_truncate(_stringify(result_raw), result_limit)}")
+ return "\n".join(lines)
+
+ def _tool_update_summary(self, payload: Any, args_limit: int) -> str:
+ update = payload.get("tool_update", payload) if isinstance(payload, dict) else payload
+ update = _mask_secrets(_as_dict(update)) if isinstance(update, dict) else update
+ if not isinstance(update, dict):
+ return _truncate(_safe_str(update), self._settings.generic_payload_max_chars)
+ name = update.get("tool_name") or update.get("name") or ""
+ status = update.get("status", "")
+ call_id = update.get("tool_call_id") or update.get("id") or ""
+ args = _truncate(_stringify(update.get("arguments", "")), args_limit)
+ return f"tool_name={name} status={status} tool_call_id={call_id}\narguments={args}"
+
+ def _usage_summary(self, payload: Any) -> str:
+ meta = payload.get("usage_metadata", payload) if isinstance(payload, dict) else {}
+ if not isinstance(meta, dict):
+ return _truncate(_safe_str(payload), self._settings.generic_payload_max_chars)
+ parts = []
+ for key in ("input_tokens", "output_tokens", "total_tokens"):
+ if key in meta:
+ parts.append(f"{key}={meta[key]}")
+ for key in ("model_name",):
+ if key in meta and meta[key]:
+ parts.append(f"{key}={meta[key]}")
+ if not parts:
+ return _truncate(_safe_str(payload), self._settings.generic_payload_max_chars)
+ return " ".join(parts)
+
+ def _flush_run(self) -> None:
+ run = self._run
+ self._run = None
+ if run is None or not run.buf:
+ return
+ text = "".join(run.buf)
+ limit = self._settings.max_model_output_chars if run.category == "text" else None
+ self._emit(run.category, "main", _truncate(text, limit))
+
+ def _emit(self, category: str, source: str, content: str) -> None:
+ if not content:
+ return
+ level = _CATEGORY_LEVEL.get(category, "INFO")
+ header = f"[{level}] mode={self._mode or _UNKNOWN} source={source} category={category}"
+ prefixed = "\n".join(f" | {line}" for line in content.split("\n"))
+ self._write_raw(f"{header}\n{prefixed}")
+
+ def _write_raw(self, body: str) -> None:
+ if self._file is None:
+ return
+ try:
+ self._file.write(f"{body}\n")
+ self._file.flush()
+ except Exception as exc:
+ _logger.debug("[DebugTrace] write failed: %s", exc)
+
+ def _safe_warn(self, msg: str) -> None:
+ _logger.warning("[DebugTrace] %s (session=%s)", msg, self._session_id)
+ if self._file is not None:
+ try:
+ self._file.write(f"{_now_ts()} [WARN] {msg}\n")
+ self._file.flush()
+ except Exception as exc:
+ _logger.debug("[DebugTrace] failed to write warning to dump file: %s", exc)
+
+
+def _as_dict(value: Any) -> Any:
+ """Coerce a payload into a dict for masking when it's dict-like."""
+ return value if isinstance(value, dict) else value
+
+
+def _stringify(value: Any) -> str:
+ if isinstance(value, str):
+ return value
+ try:
+ return json.dumps(value, ensure_ascii=False, default=str)
+ except Exception:
+ return str(value)
+
+
+def _safe_str(value: Any) -> str:
+ try:
+ return _stringify(value)
+ except Exception:
+ return repr(value)
+
+
+__all__ = ["DebugTraceLogger"]
diff --git a/tests/unit_tests/agentserver/test_debug_trace.py b/tests/unit_tests/agentserver/test_debug_trace.py
new file mode 100644
index 0000000000..ffc7f67fa6
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_debug_trace.py
@@ -0,0 +1,444 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for the Agent/Code debug_trace package (Phase 1: request-level /debug)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jiuwenswarm.server.runtime.debug_trace import (
+ DebugTraceLogger,
+ resolve_debug_trace_settings,
+)
+from jiuwenswarm.server.runtime.debug_trace import config as debug_config
+from jiuwenswarm.server.runtime.debug_trace import directives as directives_mod
+from jiuwenswarm.server.runtime.debug_trace import paths as paths_mod
+from jiuwenswarm.server.runtime.debug_trace.directives import (
+ DEBUG_PREFIX,
+ strip_debug_directive,
+ strip_slash_directive,
+)
+
+
+# ── helpers ────────────────────────────────────────────────────────────────
+def _chunk(ctype: str, payload: Any) -> SimpleNamespace:
+ return SimpleNamespace(type=ctype, payload=payload)
+
+
+def _logger(tmp_path: Path, *, mode: str = "code.normal", session_id: str = "sess") -> DebugTraceLogger:
+ s = resolve_debug_trace_settings(mode=mode, request_debug=True)
+ return DebugTraceLogger(
+ file_path=tmp_path / f"dump-{mode.split('.')[0]}-{session_id}.txt",
+ mode=mode,
+ session_id=session_id,
+ request_id="req-1",
+ settings=s,
+ )
+
+
+def _read(log: DebugTraceLogger) -> str:
+ log.flush()
+ # _file is closed by flush; read directly from the path.
+ return Path(log._path).read_text(encoding="utf-8")
+
+
+# ── directives ─────────────────────────────────────────────────────────────
+class TestStripDebugDirective:
+ def test_strips_prefix_and_prompt(self):
+ assert strip_debug_directive("/debug 你好") == ("你好", True)
+
+ def test_requires_whitespace_after_prefix(self):
+ # /debugfoo is NOT the directive (no whitespace after /debug).
+ assert strip_debug_directive("/debugfoo x") == ("/debugfoo x", False)
+
+ def test_bare_debug_not_recognised(self):
+ # No prompt -> not recognised, so an empty query is never sent to the model.
+ assert strip_debug_directive("/debug") == ("/debug", False)
+
+ def test_leading_whitespace_and_multiple_words(self):
+ assert strip_debug_directive(" /debug hello world") == ("hello world", True)
+
+ def test_no_prefix_unchanged(self):
+ assert strip_debug_directive("hello") == ("hello", False)
+
+ def test_non_str_unchanged(self):
+ assert strip_debug_directive(None) == (None, False)
+
+ def test_plan_mode_system_reminder_prefix(self):
+ # code.plan / Plan mode prepends a <system-reminder>...</system-reminder>
+ # block to the query BEFORE the adapter sees it. /debug lives in the user
+ # text after the reminder; the reminder must be preserved for the model.
+ reminder = (
+ "\n\n<system-reminder>\nPlan mode is active. You must only plan.\n"
+ "</system-reminder>"
+ )
+ cleaned, present = strip_debug_directive(reminder + "/debug 你好")
+ assert present is True
+ assert cleaned == reminder + "你好"
+ assert "/debug" not in cleaned
+
+ def test_system_reminder_without_debug_unchanged(self):
+ reminder = "\n\n<system-reminder>\nPlan mode is active.\n</system-reminder>"
+ cleaned, present = strip_debug_directive(reminder + "just planning")
+ assert present is False
+ assert cleaned == reminder + "just planning"
+
+
+# ── paths ──────────────────────────────────────────────────────────────────
+class TestPaths:
+ def test_agent_modes_use_agent_dir(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(paths_mod, "get_user_workspace_dir", lambda: tmp_path)
+ assert paths_mod.debug_trace_dir("agent.plan") == tmp_path / ".agent" / "traces"
+ assert paths_mod.debug_trace_dir("agent.fast") == tmp_path / ".agent" / "traces"
+
+ def test_code_mode_uses_code_dir(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(paths_mod, "get_user_workspace_dir", lambda: tmp_path)
+ assert paths_mod.debug_trace_dir("code.normal") == tmp_path / ".code" / "traces"
+
+ def test_file_names(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(paths_mod, "get_user_workspace_dir", lambda: tmp_path)
+ assert paths_mod.debug_trace_file("agent.plan", "sess").name == "dump-agent-sess.txt"
+ assert paths_mod.debug_trace_file("code.normal", "sess").name == "dump-code-sess.txt"
+
+ def test_session_id_sanitised(self, monkeypatch, tmp_path):
+ monkeypatch.setattr(paths_mod, "get_user_workspace_dir", lambda: tmp_path)
+ # Slashes / dots stripped so the segment can't escape the traces dir.
+ f = paths_mod.debug_trace_file("agent.plan", "../evil")
+ assert f.parent == tmp_path / ".agent" / "traces"
+ assert ".." not in f.name
+ assert "/" not in f.name
+
+
+# ── config ─────────────────────────────────────────────────────────────────
+class TestSettings:
+ def _cfg(self, monkeypatch, cfg):
+ monkeypatch.setattr(debug_config, "_load_debug_trace_config", lambda: cfg)
+
+ def test_request_debug_enables(self, monkeypatch):
+ self._cfg(monkeypatch, {})
+ s = resolve_debug_trace_settings(mode="code.normal", request_debug=True)
+ assert s.enabled and s.dump_enabled
+ assert not s.otel_enabled # default: otel off unless debug_trace.<mode>.otel_enabled
+
+ def test_no_request_debug_disables(self, monkeypatch):
+ self._cfg(monkeypatch, {})
+ s = resolve_debug_trace_settings(mode="agent.plan", request_debug=False)
+ assert not s.enabled and not s.dump_enabled
+
+ def test_otel_enabled_requires_debug_and_flag(self, monkeypatch):
+ # debug + otel_enabled -> on
+ self._cfg(monkeypatch, {"code": {"otel_enabled": True}})
+ assert resolve_debug_trace_settings(mode="code.normal", request_debug=True).otel_enabled
+ # otel_enabled but no debug -> off (debug_enabled gate)
+ assert not resolve_debug_trace_settings(mode="code.normal", request_debug=False).otel_enabled
+ # debug but otel_enabled false -> off (default)
+ self._cfg(monkeypatch, {"code": {"otel_enabled": False}})
+ assert not resolve_debug_trace_settings(mode="code.normal", request_debug=True).otel_enabled
+
+ def test_config_global_enabled(self, monkeypatch):
+ self._cfg(monkeypatch, {"enabled": True})
+ s = resolve_debug_trace_settings(mode="agent.plan", request_debug=False)
+ assert s.enabled and s.dump_enabled
+
+ def test_config_mode_enabled(self, monkeypatch):
+ # only agent mode enabled -> code disabled
+ self._cfg(monkeypatch, {"agent": {"enabled": True}})
+ assert resolve_debug_trace_settings(mode="agent.plan", request_debug=False).enabled
+ assert not resolve_debug_trace_settings(mode="code.normal", request_debug=False).enabled
+
+ def test_config_dump_disabled_escape_hatch(self, monkeypatch):
+ self._cfg(monkeypatch, {"enabled": True, "code": {"dump_enabled": False}})
+ s = resolve_debug_trace_settings(mode="code.normal", request_debug=False)
+ assert s.enabled and not s.dump_enabled
+
+ def test_config_include_toggles(self, monkeypatch):
+ self._cfg(monkeypatch, {"enabled": True, "code": {"include_reasoning": False}})
+ s = resolve_debug_trace_settings(mode="code.normal", request_debug=False)
+ assert s.include_reasoning is False
+ assert s.include_model_output is True # untouched default
+
+ def test_config_limits_override(self, monkeypatch):
+ self._cfg(monkeypatch, {"enabled": True, "limits": {"tool_args_max_chars": 100}})
+ s = resolve_debug_trace_settings(mode="agent.plan", request_debug=False)
+ assert s.tool_args_max_chars == 100
+ assert s.tool_result_max_chars == 8000 # untouched default
+
+ def test_config_max_model_output_chars(self, monkeypatch):
+ self._cfg(monkeypatch, {"enabled": True, "limits": {"max_model_output_chars": 500}})
+ s = resolve_debug_trace_settings(mode="agent.plan", request_debug=False)
+ assert s.max_model_output_chars == 500
+ # empty/null -> no cap
+ self._cfg(monkeypatch, {"enabled": True, "limits": {"max_model_output_chars": ""}})
+ assert resolve_debug_trace_settings(mode="agent.plan", request_debug=False).max_model_output_chars is None
+
+ def test_config_redaction(self, monkeypatch):
+ self._cfg(monkeypatch, {"enabled": True, "redaction": {"redact_completions": True}})
+ s = resolve_debug_trace_settings(mode="agent.plan", request_debug=False)
+ assert s.redact_completions is True
+ assert s.redact_prompts is False
+
+ def test_request_debug_wins_over_config_off(self, monkeypatch):
+ self._cfg(monkeypatch, {}) # nothing in config
+ s = resolve_debug_trace_settings(mode="code.normal", request_debug=True)
+ assert s.enabled # request-level still works (regression)
+
+
+# ── logger feed / format ───────────────────────────────────────────────────
+class TestDebugTraceLoggerFeed:
+ def test_records_model_text(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run(input_text="hi")
+ lg.feed(_chunk("llm_output", {"content": "hello world"}))
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "run start" in out and "run end" in out and "status=ok" in out
+ assert "category=text" in out and "hello world" in out
+
+ def test_run_start_writes_otel_ids(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run(input_text="hi", otel_trace_id="abc123", otel_span_id="def456")
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "otel_trace_id=abc123" in out
+ assert "otel_span_id=def456" in out
+
+ def test_run_start_otel_ids_empty_by_default(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run(input_text="hi") # no otel ids (OTel not enabled)
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "otel_trace_id=" in out # key present, value empty
+ assert "otel_span_id=" in out
+
+ def test_records_reasoning(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.feed(_chunk("llm_reasoning", {"content": "thinking..."}))
+ lg.end_run(status="ok")
+ assert "category=reasoning" in _read(lg)
+
+ def test_records_tool_call(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.feed(_chunk("tool_call", {"tool_call": {
+ "name": "shell_command", "arguments": {"command": "pytest -q"}, "id": "call_1",
+ }}))
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "category=tool_call" in out
+ assert "tool_name=shell_command" in out and "tool_call_id=call_1" in out
+ assert "pytest -q" in out
+
+ def test_records_tool_result(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.feed(_chunk("tool_result", {"tool_result": {
+ "tool_name": "shell_command", "tool_call_id": "call_1",
+ "result": "10 passed", "is_error": False,
+ }}))
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "category=tool_result" in out and "10 passed" in out
+
+ def test_records_usage(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.feed(_chunk("llm_usage", {"usage_metadata": {
+ "input_tokens": 100, "output_tokens": 20, "total_tokens": 120, "model_name": "GLM-5.2",
+ }}))
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "category=context_usage" in out
+ assert "input_tokens=100" in out and "model_name=GLM-5.2" in out
+
+
+# ── truncation / redaction ─────────────────────────────────────────────────
+class TestTruncationAndRedaction:
+ def test_tool_args_truncated(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ big = "x" * 5000
+ lg.feed(_chunk("tool_call", {"tool_call": {"name": "t", "arguments": {"cmd": big}, "id": "c"}}))
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "truncated, original_chars=" in out
+ # full payload not present
+ assert big not in out
+
+ def test_tool_result_truncated(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ big = "y" * 20000
+ lg.feed(_chunk("tool_result", {"tool_result": {
+ "tool_name": "t", "tool_call_id": "c", "result": big,
+ }}))
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "truncated, original_chars=" in out
+ assert big not in out
+
+ def test_secret_keys_masked(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.feed(_chunk("tool_result", {"tool_result": {
+ "tool_name": "t", "tool_call_id": "c",
+ "result": {"api_key": "sk-super-secret", "password": "hunter2", "ok": "visible"},
+ }}))
+ lg.end_run(status="ok")
+ out = _read(lg)
+ assert "sk-super-secret" not in out
+ assert "hunter2" not in out
+ assert "***" in out
+ assert "visible" in out
+
+ def test_token_counts_not_masked(self, tmp_path):
+ # "tokens_used" / "total_tokens" are token COUNTS, not secrets — the
+ # 'token' substring must not trigger masking.
+ from jiuwenswarm.server.runtime.debug_trace.stream_logger import _looks_secret
+ assert not _looks_secret("tokens_used")
+ assert not _looks_secret("total_tokens")
+ assert not _looks_secret("input_tokens")
+ assert not _looks_secret("output_tokens")
+ # genuine secret names still match
+ assert _looks_secret("access_token")
+ assert _looks_secret("api_key")
+ assert _looks_secret("api-key")
+ assert _looks_secret("password")
+ assert _looks_secret("set-cookie")
+
+
+# ── error handling / best-effort ───────────────────────────────────────────
+class TestBestEffort:
+ def test_write_failure_does_not_raise(self, tmp_path):
+ # parent is a regular file -> mkdir fails -> logger disables itself.
+ blocker = tmp_path / "blocker"
+ blocker.write_text("x")
+ s = resolve_debug_trace_settings(mode="agent.plan", request_debug=True)
+ lg = DebugTraceLogger(
+ file_path=blocker / "dump.txt",
+ mode="agent.plan", session_id="s", request_id="r", settings=s,
+ )
+ assert lg._disabled is True
+ # all public methods are no-ops and never raise
+ lg.start_run(input_text="hi")
+ lg.feed(_chunk("llm_output", {"content": "x"}))
+ lg.end_run(status="ok")
+ lg.flush()
+
+ def test_end_run_error_records_metadata(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ exc = RuntimeError("boom")
+ lg.end_run(status="error", error=exc)
+ out = _read(lg)
+ assert "status=error" in out
+ assert "error_type=RuntimeError" in out
+ assert "error=boom" in out
+
+ def test_end_run_idempotent(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.end_run(status="ok")
+ lg.end_run(status="error", error=RuntimeError("x")) # second call: no-op
+ out = _read(lg)
+ assert out.count("run end") == 1
+ assert "status=ok" in out
+ assert "status=error" not in out
+
+ def test_cancelled_status(self, tmp_path):
+ lg = _logger(tmp_path)
+ lg.start_run()
+ lg.end_run(status="cancelled")
+ assert "status=cancelled" in _read(lg)
+
+
+# ── generic slash-directive primitive (shared with team_helpers) ───────────
+class TestStripSlashDirective:
+ def test_basic(self):
+ assert strip_slash_directive("/debug 你好", "/debug") == ("你好", True)
+
+ def test_requires_whitespace(self):
+ assert strip_slash_directive("/debugfoo x", "/debug") == ("/debugfoo x", False)
+
+ def test_bare_prefix_recognised(self):
+ # generic primitive DOES recognise a bare prefix (team semantics);
+ # agent/code reject it at the strip_debug_directive wrapper layer.
+ assert strip_slash_directive("/debug", "/debug") == ("", True)
+
+ def test_unknown_prefix(self):
+ assert strip_slash_directive("hello", "/debug") == ("hello", False)
+
+ def test_works_for_hide_dm(self):
+ # team uses it for /hide_dm too
+ assert strip_slash_directive("/hide_dm hello", "/hide_dm") == ("hello", True)
+
+
+# ── directive parity with team_helpers (single source of truth) ────────────
+class TestTeamParity:
+ def test_team_reuses_shared_primitive(self):
+ from jiuwenswarm.server.runtime.agent_adapter import team_helpers
+ # team's aliases ARE the shared objects (no duplicate implementation)
+ assert team_helpers._DEBUG_PREFIX is DEBUG_PREFIX
+ assert team_helpers._strip_directive is strip_slash_directive
+
+
+# ── agent_observability force-enable + sticky teardown ─────────────────────
+class TestAgentObservabilityForce:
+ """sync_agent_observability(force=) pulls up OTel when config is off, and
+ once force is used the provider stays up (sticky) to avoid init/shutdown
+ churn. The normal config-gated teardown still works when force was never used."""
+
+ def _reset(self):
+ import jiuwenswarm.agents.harness.agent_observability as ao
+ ao._agent_observability_active = False
+ ao._agent_owns_provider = False
+ ao._force_ever_enabled = False
+
+ def test_force_inits_and_sticky_blocks_teardown(self, monkeypatch):
+ import jiuwenswarm.agents.harness.agent_observability as ao
+ import openjiuwen.agent_teams.observability as obs
+ self._reset()
+ calls = {"init": 0, "shutdown": 0}
+ monkeypatch.setattr(ao, "get_config", lambda: {"agent_observability": {"enabled": False}})
+ monkeypatch.setattr(obs, "is_initialized", lambda: False)
+ monkeypatch.setattr(obs, "ObservabilityConfig", lambda **kw: kw)
+
+ def fake_init(_cfg):
+ calls["init"] += 1
+
+ monkeypatch.setattr(obs, "init_observability", fake_init)
+ monkeypatch.setattr(
+ ao, "shutdown_agent_observability",
+ lambda: calls.__setitem__("shutdown", calls["shutdown"] + 1),
+ )
+ # force=True with config off -> init + sticky flag set + active
+ ao.sync_agent_observability(force=True)
+ assert calls["init"] == 1
+ assert ao._force_ever_enabled is True
+ assert ao._agent_observability_active is True
+ # next request: force=False, config off, active -> sticky blocks teardown
+ ao.sync_agent_observability()
+ assert calls["shutdown"] == 0
+ assert ao._agent_observability_active is True
+
+ def test_normal_path_still_tears_down_without_force(self, monkeypatch):
+ import jiuwenswarm.agents.harness.agent_observability as ao
+ self._reset()
+ calls = {"shutdown": 0}
+ # simulate a config-gated active provider (force never used)
+ ao._agent_observability_active = True
+ ao._agent_owns_provider = True
+ ao._force_ever_enabled = False
+ monkeypatch.setattr(ao, "get_config", lambda: {"agent_observability": {"enabled": False}})
+ monkeypatch.setattr(
+ ao, "shutdown_agent_observability",
+ lambda: calls.__setitem__("shutdown", calls["shutdown"] + 1),
+ )
+ ao.sync_agent_observability() # enabled off + active + never forced -> teardown
+ assert calls["shutdown"] == 1
+ assert ao._force_ever_enabled is False
+