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: adapt subagent thinking control for task_tool on dev-stable

xiaowenzihwl3409c5bf0226
diff --git a/jiuwenswarm/common/thinking/__init__.py b/jiuwenswarm/common/thinking/__init__.py
new file mode 100644
index 0000000000..bca88f0e24
--- /dev/null
+++ b/jiuwenswarm/common/thinking/__init__.py
@@ -0,0 +1,21 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Subagent thinking control: semantic thinking → vendor kwargs."""
+
+from __future__ import annotations
+
+from jiuwenswarm.common.thinking.adapter import adapt_thinking
+from jiuwenswarm.common.thinking.rail import ThinkingInjectRail
+from jiuwenswarm.common.thinking.types import (
+ THINKING_VALUES,
+ ThinkingProfile,
+ normalize_thinking,
+)
+
+__all__ = [
+ "THINKING_VALUES",
+ "ThinkingInjectRail",
+ "ThinkingProfile",
+ "adapt_thinking",
+ "normalize_thinking",
+]
diff --git a/jiuwenswarm/common/thinking/adapter.py b/jiuwenswarm/common/thinking/adapter.py
new file mode 100644
index 0000000000..09a2359ea4
--- /dev/null
+++ b/jiuwenswarm/common/thinking/adapter.py
@@ -0,0 +1,89 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Adapt semantic thinking (default|off|on) to frozen vendor kwargs."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from jiuwenswarm.common.thinking.types import (
+ ThinkingProfile,
+ freeze_llm_call_kwargs,
+ normalize_thinking,
+)
+from jiuwenswarm.common.thinking.vendor_map import match_vendor_style, style_to_kwargs
+from jiuwenswarm.common.utils import logger
+
+
+def _resolve_model_name(model: Any) -> str:
+ """Best-effort model name from openjiuwen Model / config objects."""
+ if model is None:
+ return ""
+ if isinstance(model, str):
+ return model.strip()
+ cfg = getattr(model, "model_config", None)
+ if cfg is not None:
+ for attr in ("model_name", "model"):
+ val = getattr(cfg, attr, None)
+ if isinstance(val, str) and val.strip():
+ return val.strip()
+ client_cfg = getattr(model, "model_client_config", None)
+ if client_cfg is not None:
+ val = getattr(client_cfg, "model_name", None)
+ if isinstance(val, str) and val.strip():
+ return val.strip()
+ return ""
+
+
+def adapt_thinking(thinking: str | None, model: Any = None, *, model_name: str = "") -> ThinkingProfile:
+ """Build a frozen ThinkingProfile for one subagent lifetime.
+
+ Never raises: unsupported / invalid → empty kwargs + degraded flag.
+ Nested kwargs are deep-copied before freeze so later inject mutations
+ cannot write through into the profile.
+ """
+ name = (model_name or "").strip() or _resolve_model_name(model)
+ try:
+ level, invalid = normalize_thinking(thinking)
+ if invalid:
+ return ThinkingProfile.empty(
+ thinking="default",
+ degraded=True,
+ reason="invalid_value",
+ model_name=name,
+ )
+ if level == "default":
+ return ThinkingProfile.empty(thinking="default", model_name=name)
+
+ style = match_vendor_style(name)
+ if style is None:
+ logger.info(
+ "[Thinking] unsupported model for thinking toggle model=%r thinking=%s",
+ name,
+ level,
+ )
+ return ThinkingProfile.empty(
+ thinking=level,
+ degraded=True,
+ reason="unsupported_model",
+ model_name=name,
+ )
+
+ kwargs = style_to_kwargs(style, enabled=(level == "on"))
+ return ThinkingProfile(
+ thinking=level,
+ llm_call_kwargs=freeze_llm_call_kwargs(kwargs),
+ injected=True,
+ degraded=False,
+ reason=None,
+ vendor_style=style,
+ model_name=name,
+ )
+ except Exception as exc:
+ logger.warning("[Thinking] adapt failed: %s", exc)
+ return ThinkingProfile.empty(
+ thinking="default",
+ degraded=True,
+ reason="adapter_error",
+ model_name=name,
+ )
diff --git a/jiuwenswarm/common/thinking/rail.py b/jiuwenswarm/common/thinking/rail.py
new file mode 100644
index 0000000000..ea3f974921
--- /dev/null
+++ b/jiuwenswarm/common/thinking/rail.py
@@ -0,0 +1,75 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Rail that injects frozen thinking kwargs into each model call."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+from jiuwenswarm.common.thinking.types import (
+ ThinkingProfile,
+ kwargs_digest,
+ thaw_llm_call_kwargs,
+)
+from jiuwenswarm.common.utils import logger
+
+
+class ThinkingInjectRail(DeepAgentRail):
+ """Replay frozen thinking llm_call_kwargs before each model call.
+
+ Profile is resolved once at spawn/fork; this rail only injects a deep copy
+ of the same kwargs every iteration (KV-cache friendly). Compatible with
+ older cores that ignore ``llm_call_kwargs`` (injection is a no-op until
+ core is upgraded).
+ """
+
+ priority = 15 # early, before most model-call rails
+
+ def __init__(
+ self,
+ profile: ThinkingProfile | None,
+ *,
+ role_id: str = "",
+ agent_id: str = "",
+ ) -> None:
+ super().__init__()
+ self._profile = profile
+ self._role_id = role_id or ""
+ self._agent_id = agent_id or ""
+ self._inject_logged = False
+
+ async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ profile = self._profile
+ if profile is None:
+ return
+ kwargs = getattr(profile, "llm_call_kwargs", None)
+ if not kwargs:
+ return
+ try:
+ extra = getattr(ctx, "extra", None)
+ if not isinstance(extra, dict):
+ return
+ # Thaw to a deep mutable copy so inject mutations cannot affect profile.
+ injected: dict[str, Any] = thaw_llm_call_kwargs(kwargs)
+ extra["llm_call_kwargs"] = injected
+ if not self._inject_logged:
+ self._inject_logged = True
+ logger.info(
+ "[Thinking] inject_once role_id=%s agent_id=%s model=%r "
+ "thinking=%s digest=%s",
+ self._role_id,
+ self._agent_id,
+ getattr(profile, "model_name", "") or "",
+ getattr(profile, "thinking", ""),
+ kwargs_digest(injected),
+ )
+ except Exception as exc:
+ logger.warning(
+ "[ThinkingInjectRail] inject skipped role_id=%s agent_id=%s: %s",
+ self._role_id,
+ self._agent_id,
+ exc,
+ )
diff --git a/jiuwenswarm/common/thinking/register_hook.py b/jiuwenswarm/common/thinking/register_hook.py
new file mode 100644
index 0000000000..f14dab2edd
--- /dev/null
+++ b/jiuwenswarm/common/thinking/register_hook.py
@@ -0,0 +1,78 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Register TaskTool subagent thinking hook with openjiuwen core.
+
+Core TaskTool calls ``apply_subagent_thinking`` after ``create_subagent``.
+When this host hook is registered, semantic ``thinking`` (default|off|on) is
+adapted to vendor kwargs and attached via :class:`ThinkingInjectRail`.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from jiuwenswarm.common.thinking.adapter import adapt_thinking
+from jiuwenswarm.common.thinking.rail import ThinkingInjectRail
+from jiuwenswarm.common.utils import logger
+
+_REGISTERED = False
+
+
+def _on_subagent_thinking(subagent: Any, *, thinking: str, model: Any = None) -> None:
+ """Attach ThinkingInjectRail when thinking is explicitly off/on."""
+ profile = adapt_thinking(thinking, model=model)
+ if not getattr(profile, "injected", False):
+ # default / unsupported / invalid → leave subagent model config as-is
+ if getattr(profile, "degraded", False):
+ logger.info(
+ "[Thinking] skip inject degraded reason=%s thinking=%r model=%r",
+ getattr(profile, "reason", ""),
+ getattr(profile, "thinking", ""),
+ getattr(profile, "model_name", ""),
+ )
+ return
+
+ role_id = ""
+ agent_id = ""
+ card = getattr(subagent, "card", None)
+ if card is not None:
+ agent_id = str(getattr(card, "id", "") or "")
+ role_id = str(getattr(card, "name", "") or agent_id)
+
+ rail = ThinkingInjectRail(profile, role_id=role_id, agent_id=agent_id)
+ add_rail = getattr(subagent, "add_rail", None)
+ if not callable(add_rail):
+ logger.warning("[Thinking] subagent has no add_rail; skip inject")
+ return
+ add_rail(rail)
+ logger.info(
+ "[Thinking] rail attached role_id=%s agent_id=%s thinking=%s model=%r",
+ role_id,
+ agent_id,
+ profile.thinking,
+ profile.model_name,
+ )
+
+
+def register_thinking_hook() -> None:
+ """Idempotent registration of the core TaskTool thinking hook."""
+ global _REGISTERED
+ if _REGISTERED:
+ return
+ try:
+ from openjiuwen.harness.tools.subagent.thinking_hook import (
+ register_subagent_thinking_hook,
+ )
+ except ImportError as exc:
+ logger.warning(
+ "[Thinking] core thinking_hook unavailable (upgrade openjiuwen): %s",
+ exc,
+ )
+ return
+
+ register_subagent_thinking_hook(_on_subagent_thinking)
+ _REGISTERED = True
+ logger.info("[Thinking] TaskTool thinking hook registered")
+
+
+__all__ = ["register_thinking_hook"]
diff --git a/jiuwenswarm/common/thinking/types.py b/jiuwenswarm/common/thinking/types.py
new file mode 100644
index 0000000000..af0f16509c
--- /dev/null
+++ b/jiuwenswarm/common/thinking/types.py
@@ -0,0 +1,124 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Types for subagent thinking control (semantic tiers)."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from dataclasses import dataclass
+from types import MappingProxyType
+from typing import Any, Mapping
+
+from jiuwenswarm.common.utils import logger
+
+# Public contract for spawn/fork tool parameter ``thinking``.
+THINKING_VALUES = frozenset({"", "default", "off", "on"})
+
+
+def _deep_freeze(obj: Any) -> Any:
+ """Recursively freeze mappings/lists so nested values are immutable."""
+ if isinstance(obj, Mapping):
+ return MappingProxyType({k: _deep_freeze(v) for k, v in obj.items()})
+ if isinstance(obj, list):
+ return tuple(_deep_freeze(v) for v in obj)
+ if isinstance(obj, tuple):
+ return tuple(_deep_freeze(v) for v in obj)
+ return obj
+
+
+def freeze_llm_call_kwargs(kwargs: Mapping[str, Any] | None) -> Mapping[str, Any]:
+ """Deep-copy then recursively freeze so nested dicts cannot be mutated."""
+ return _deep_freeze(deepcopy(dict(kwargs or {})))
+
+
+def thaw_llm_call_kwargs(kwargs: Mapping[str, Any] | None) -> dict[str, Any]:
+ """Return a deep mutable copy of frozen kwargs (safe for per-call inject)."""
+
+ def _thaw(obj: Any) -> Any:
+ if isinstance(obj, Mapping):
+ return {k: _thaw(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_thaw(v) for v in obj]
+ return obj
+
+ return _thaw(kwargs or {})
+
+
+@dataclass(frozen=True)
+class ThinkingProfile:
+ """Frozen per-subagent thinking injection profile."""
+
+ thinking: str
+ llm_call_kwargs: Mapping[str, Any]
+ injected: bool
+ degraded: bool
+ reason: str | None = None
+ vendor_style: str | None = None
+ model_name: str = ""
+
+ @staticmethod
+ def empty(
+ *,
+ thinking: str = "default",
+ degraded: bool = False,
+ reason: str | None = None,
+ vendor_style: str | None = None,
+ model_name: str = "",
+ ) -> ThinkingProfile:
+ return ThinkingProfile(
+ thinking=thinking,
+ llm_call_kwargs=freeze_llm_call_kwargs({}),
+ injected=False,
+ degraded=degraded,
+ reason=reason,
+ vendor_style=vendor_style,
+ model_name=model_name,
+ )
+
+
+def normalize_thinking(raw: Any) -> tuple[str, bool]:
+ """Normalize tool input to default|off|on.
+
+ Returns:
+ (normalized_value, was_invalid)
+ Invalid / unknown values become ``default`` with was_invalid=True.
+ """
+ if raw is None:
+ return "default", False
+ if not isinstance(raw, str):
+ logger.warning(
+ "[Thinking] invalid thinking type=%s; treat as default",
+ type(raw).__name__,
+ )
+ return "default", True
+ value = raw.strip().lower()
+ if value in ("", "default"):
+ return "default", False
+ if value in ("off", "on"):
+ return value, False
+ logger.warning(
+ "[Thinking] invalid thinking=%r; treat as default",
+ raw,
+ )
+ return "default", True
+
+
+def kwargs_digest(kwargs: Mapping[str, Any] | None) -> str:
+ """Compact, log-safe summary of injected kwargs (no secrets expected)."""
+ if not kwargs:
+ return "{}"
+ try:
+ extra_body = kwargs.get("extra_body") if hasattr(kwargs, "get") else None
+ if isinstance(extra_body, dict):
+ thinking = extra_body.get("thinking")
+ if isinstance(thinking, dict) and "type" in thinking:
+ return f"extra_body.thinking.type={thinking.get('type')!r}"
+ if "enable_thinking" in extra_body:
+ return f"extra_body.enable_thinking={extra_body.get('enable_thinking')!r}"
+ if "reasoning_effort" in extra_body:
+ return f"extra_body.reasoning_effort={extra_body.get('reasoning_effort')!r}"
+ if "reasoning_effort" in kwargs:
+ return f"reasoning_effort={kwargs.get('reasoning_effort')!r}"
+ return f"keys={sorted(kwargs.keys())}"
+ except Exception:
+ return "<unrepr>"
diff --git a/jiuwenswarm/common/thinking/vendor_map.py b/jiuwenswarm/common/thinking/vendor_map.py
new file mode 100644
index 0000000000..b0fc9dfa29
--- /dev/null
+++ b/jiuwenswarm/common/thinking/vendor_map.py
@@ -0,0 +1,49 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Vendor match table for thinking control (no skill/role knowledge).
+
+Only explicitly allowlisted model families participate in thinking toggle.
+Currently: GLM-5 / GLM-5.1 / GLM-5.2 / DeepSeek-V3.2.
+"""
+
+from __future__ import annotations
+
+import re
+
+# Ordered: first match wins. Patterns are intentionally narrow to avoid
+# false positives (e.g. glm-4, glm-50, deepseek-chat, deepseek-v3.1).
+_VENDOR_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
+ (
+ re.compile(r"(?:^|[^a-z0-9])glm[-_]?5(?:\.(?:1|2))?(?:$|[^0-9.])", re.IGNORECASE),
+ "extra_body_thinking_type",
+ ),
+ (
+ re.compile(r"(?:^|[^a-z0-9])deepseek[-_]?v?3\.2(?:$|[^0-9])", re.IGNORECASE),
+ "extra_body_thinking_type",
+ ),
+)
+
+
+def match_vendor_style(model_name: str) -> str | None:
+ """Return vendor style id for model_name, or None if unsupported."""
+ name = (model_name or "").strip()
+ if not name:
+ return None
+ for pattern, style in _VENDOR_PATTERNS:
+ if pattern.search(name):
+ return style
+ return None
+
+
+def style_to_kwargs(style: str, *, enabled: bool) -> dict:
+ """Map vendor style + on/off to physical llm_call_kwargs."""
+ if style == "extra_body_thinking_type":
+ return {
+ "extra_body": {
+ "thinking": {"type": "enabled" if enabled else "disabled"},
+ }
+ }
+ if style == "extra_body_enable_thinking":
+ # Kept for forward-compat / tests; not matched by current allowlist.
+ return {"extra_body": {"enable_thinking": bool(enabled)}}
+ raise ValueError(f"unknown thinking vendor style: {style}")
diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.py
index b2afb0a99a..4f84fd917b 100644
--- a/jiuwenswarm/server/app_agentserver.py
+++ b/jiuwenswarm/server/app_agentserver.py
@@ -136,6 +136,11 @@ from jiuwenswarm.server.runtime.debug_trace.task_tool_patch import (
apply_task_tool_debug_patch()
+# Subagent thinking control (task_tool optional ``thinking`` param).
+# Requires openjiuwen core with llm_call_kwargs + thinking_hook; otherwise no-op.
+from jiuwenswarm.common.thinking.register_hook import register_thinking_hook
+
+register_thinking_hook()
async def _run(host: str, port: int) -> None:
diff --git a/tests/unit_tests/common/test_thinking_adapter.py b/tests/unit_tests/common/test_thinking_adapter.py
new file mode 100644
index 0000000000..33e5e45453
--- /dev/null
+++ b/tests/unit_tests/common/test_thinking_adapter.py
@@ -0,0 +1,95 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Unit tests for subagent thinking adapter."""
+
+from __future__ import annotations
+
+import pytest
+
+from jiuwenswarm.common.thinking.adapter import adapt_thinking
+from jiuwenswarm.common.thinking.types import normalize_thinking
+from jiuwenswarm.common.thinking.vendor_map import match_vendor_style, style_to_kwargs
+
+
+class TestNormalizeThinking:
+ def test_empty_and_default(self):
+ assert normalize_thinking("") == ("default", False)
+ assert normalize_thinking("default") == ("default", False)
+ assert normalize_thinking(None) == ("default", False)
+
+ def test_off_on_case_insensitive(self):
+ assert normalize_thinking("OFF") == ("off", False)
+ assert normalize_thinking(" On ") == ("on", False)
+
+ def test_invalid(self):
+ value, invalid = normalize_thinking("low")
+ assert value == "default"
+ assert invalid is True
+
+
+class TestVendorMap:
+ def test_match_glm_allowlist(self):
+ assert match_vendor_style("glm-5") == "extra_body_thinking_type"
+ assert match_vendor_style("GLM-5.1") == "extra_body_thinking_type"
+ assert match_vendor_style("glm-5.2") == "extra_body_thinking_type"
+ assert match_vendor_style("provider/glm_5.1") == "extra_body_thinking_type"
+
+ def test_match_deepseek_v32(self):
+ assert match_vendor_style("DeepSeek-V3.2") == "extra_body_thinking_type"
+ assert match_vendor_style("deepseek-v3.2") == "extra_body_thinking_type"
+ assert match_vendor_style("deepseek_v3.2") == "extra_body_thinking_type"
+
+ def test_unsupported(self):
+ assert match_vendor_style("doubao-pro") is None
+ assert match_vendor_style("qwen3-max") is None
+ assert match_vendor_style("deepseek-chat") is None
+ assert match_vendor_style("deepseek-v3.1") is None
+ assert match_vendor_style("glm-4") is None
+ assert match_vendor_style("glm-50") is None
+ assert match_vendor_style("glm-5.3") is None
+ assert match_vendor_style("") is None
+
+ def test_style_kwargs(self):
+ off = style_to_kwargs("extra_body_thinking_type", enabled=False)
+ assert off["extra_body"]["thinking"]["type"] == "disabled"
+ on = style_to_kwargs("extra_body_enable_thinking", enabled=True)
+ assert on["extra_body"]["enable_thinking"] is True
+
+
+class TestAdaptThinking:
+ def test_default_no_inject(self):
+ profile = adapt_thinking("", model_name="glm-5")
+ assert profile.thinking == "default"
+ assert profile.injected is False
+ assert dict(profile.llm_call_kwargs) == {}
+ assert profile.model_name == "glm-5"
+
+ def test_off_glm(self):
+ profile = adapt_thinking("off", model_name="glm-5.1")
+ assert profile.injected is True
+ assert profile.degraded is False
+ assert profile.llm_call_kwargs["extra_body"]["thinking"]["type"] == "disabled"
+
+ def test_on_deepseek_v32(self):
+ profile = adapt_thinking("on", model_name="DeepSeek-V3.2")
+ assert profile.injected is True
+ assert profile.llm_call_kwargs["extra_body"]["thinking"]["type"] == "enabled"
+
+ def test_unsupported_degraded(self):
+ profile = adapt_thinking("off", model_name="qwen3-plus")
+ assert profile.injected is False
+ assert profile.degraded is True
+ assert profile.reason == "unsupported_model"
+
+ def test_invalid_degraded(self):
+ profile = adapt_thinking("high", model_name="glm-5")
+ assert profile.thinking == "default"
+ assert profile.degraded is True
+ assert profile.reason == "invalid_value"
+
+ def test_profile_nested_freeze(self):
+ profile = adapt_thinking("off", model_name="glm-5")
+ # Nested mappings are frozen; assignment must raise.
+ with pytest.raises(TypeError):
+ profile.llm_call_kwargs["extra_body"]["thinking"]["type"] = "enabled"
+ assert profile.llm_call_kwargs["extra_body"]["thinking"]["type"] == "disabled"
diff --git a/tests/unit_tests/common/test_thinking_inject_rail.py b/tests/unit_tests/common/test_thinking_inject_rail.py
new file mode 100644
index 0000000000..c7145615ac
--- /dev/null
+++ b/tests/unit_tests/common/test_thinking_inject_rail.py
@@ -0,0 +1,40 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Unit tests for ThinkingInjectRail."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jiuwenswarm.common.thinking.types import ThinkingProfile, freeze_llm_call_kwargs
+from jiuwenswarm.common.thinking.rail import ThinkingInjectRail
+
+
+async def test_thinking_inject_rail_writes_kwargs():
+ profile = ThinkingProfile(
+ thinking="off",
+ llm_call_kwargs=freeze_llm_call_kwargs(
+ {"extra_body": {"thinking": {"type": "disabled"}}}
+ ),
+ injected=True,
+ degraded=False,
+ model_name="glm-5.1",
+ )
+ rail = ThinkingInjectRail(profile, role_id="Charlie", agent_id="subagent_abc")
+ ctx = SimpleNamespace(extra={})
+ await rail.before_model_call(ctx)
+ assert ctx.extra["llm_call_kwargs"]["extra_body"]["thinking"]["type"] == "disabled"
+ # Nested mutation of injected dict must not mutate frozen profile
+ ctx.extra["llm_call_kwargs"]["extra_body"]["thinking"]["type"] = "enabled"
+ assert profile.llm_call_kwargs["extra_body"]["thinking"]["type"] == "disabled"
+
+
+async def test_thinking_inject_rail_noop_when_empty():
+ rail = ThinkingInjectRail(ThinkingProfile.empty())
+ ctx = SimpleNamespace(extra={})
+ await rail.before_model_call(ctx)
+ assert "llm_call_kwargs" not in ctx.extra
diff --git a/tests/unit_tests/common/test_thinking_register_hook.py b/tests/unit_tests/common/test_thinking_register_hook.py
new file mode 100644
index 0000000000..506685ea14
--- /dev/null
+++ b/tests/unit_tests/common/test_thinking_register_hook.py
@@ -0,0 +1,57 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Unit tests for thinking hook registration."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jiuwenswarm.common.thinking import register_hook as rh
+from jiuwenswarm.common.thinking.adapter import adapt_thinking
+
+
+def test_on_subagent_thinking_default_skips_rail(monkeypatch):
+ added: list = []
+
+ class FakeSub:
+ card = SimpleNamespace(id="a1", name="explore_agent")
+
+ def add_rail(self, rail):
+ added.append(rail)
+
+ rh._on_subagent_thinking(FakeSub(), thinking="default", model="glm-5")
+ assert added == []
+
+
+def test_on_subagent_thinking_off_attaches_rail(monkeypatch):
+ added: list = []
+
+ class FakeSub:
+ card = SimpleNamespace(id="a1", name="explore_agent")
+
+ def add_rail(self, rail):
+ added.append(rail)
+
+ # Force a vendor that supports thinking toggle
+ profile = adapt_thinking("off", model_name="glm-5")
+ if not profile.injected:
+ # vendor map may not match glm-5 in this env; stub adapter
+ from jiuwenswarm.common.thinking.types import ThinkingProfile, freeze_llm_call_kwargs
+
+ monkeypatch.setattr(
+ rh,
+ "adapt_thinking",
+ lambda thinking, model=None, model_name="": ThinkingProfile(
+ thinking="off",
+ llm_call_kwargs=freeze_llm_call_kwargs(
+ {"extra_body": {"thinking": {"type": "disabled"}}}
+ ),
+ injected=True,
+ degraded=False,
+ model_name="glm-5",
+ ),
+ )
+
+ rh._on_subagent_thinking(FakeSub(), thinking="off", model="glm-5")
+ assert len(added) == 1
+ assert added[0].__class__.__name__ == "ThinkingInjectRail"