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

fix(skill_turbo): HITL 暂停信号改随工具返回值传递,修复 ask_user 中断加速通道

d3002969613d1eae76ad0
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index ae53cde98a..0fd2413077 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -652,15 +652,24 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
content: str,
tool_name: str,
) -> bool:
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ _SKILL_TURBO_HITL_PLACEHOLDER,
+ )
+
legacy_templates = [
f"[Tool execution interrupted] Tool {tool_name} was interrupted by user during execution, "
f"no result available.",
f"[Tool interrupted] Tool {tool_name} was interrupted by the user and has no result.",
f"[工具执行被中断] 工具 {tool_name} 执行过程中被用户打断,没有执行结果。",
+ # HITL 暂停 tool_msg(skill_acceleration_exec 专用文案)
+ _SKILL_TURBO_HITL_PLACEHOLDER
+ if tool_name == "skill_acceleration_exec"
+ else "",
]
normalized_content = self._normalize_tool_interrupt_text(content)
return any(
- normalized_content == self._normalize_tool_interrupt_text(template)
+ template
+ and normalized_content == self._normalize_tool_interrupt_text(template)
for template in legacy_templates
)
@@ -1203,47 +1212,79 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
if tc_id:
self._inflight_tool_calls.pop(tc_id, None)
- # SkillTurbo HITL: skill_turbo_tools 在 ContextVar 存了 ToolInterruptException,
- # 此处改写 ctx.inputs.tool_result 为 TIE,使 harness 原生 HITL 机制检测并暂停。
- if self._skill_turbo_adapter is not None:
- try:
- from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
- get_skill_turbo_hitl_tic,
- set_skill_turbo_hitl_tic,
- )
- _skill_turbo_tic = get_skill_turbo_hitl_tic()
- if _skill_turbo_tic is not None:
- set_skill_turbo_hitl_tic(None)
- if isinstance(ctx.inputs, ToolCallInputs):
- from openjiuwen.core.single_agent.interrupt.exception import (
- ToolInterruptException,
- )
- new_tic = ToolInterruptException(
- request=_skill_turbo_tic.request,
- tool_call=ctx.inputs.tool_call,
+ # SkillTurbo HITL:主信号是工具返回值里的 __skill_turbo_hitl__ 标记
+ # (deepcopy 安全、随返回值穿越任何执行上下文),ContextVar 中的
+ # ToolInterruptException 作为旧路径兜底。此处把 ctx.inputs.tool_result
+ # 改写为 TIE,使 harness 原生 HITL 机制(build_interrupt_state)检测并暂停。
+ # 暂停处理不依赖 _skill_turbo_adapter 绑定:适配器缺失时同样必须暂停,
+ # 否则外层模型会把暂停占位当失败而放弃加速通道。
+ # (token 复位已在函数入口 reset_skill_turbo_context 统一完成。)
+ try:
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ _SKILL_TURBO_HITL_PLACEHOLDER,
+ _SKILL_TURBO_HITL_RESULT_KEY,
+ get_skill_turbo_hitl_tic,
+ set_skill_turbo_hitl_tic,
+ )
+ _hitl_request_dump: dict[str, Any] | None = None
+ _raw_tool_result = ctx.inputs.tool_result
+ if (
+ isinstance(_raw_tool_result, dict)
+ and _raw_tool_result.get(_SKILL_TURBO_HITL_RESULT_KEY)
+ and isinstance(_raw_tool_result.get("request"), dict)
+ ):
+ _hitl_request_dump = _raw_tool_result["request"]
+ _skill_turbo_tic = (
+ get_skill_turbo_hitl_tic() if _hitl_request_dump is None else None
+ )
+ if _hitl_request_dump is not None or _skill_turbo_tic is not None:
+ set_skill_turbo_hitl_tic(None)
+ if isinstance(ctx.inputs, ToolCallInputs):
+ from openjiuwen.core.single_agent.interrupt.exception import (
+ ToolInterruptException,
+ )
+ from openjiuwen.core.single_agent.interrupt.response import (
+ ToolCallInterruptRequest,
+ )
+ if _hitl_request_dump is not None:
+ _hitl_request: Any = ToolCallInterruptRequest.model_validate(
+ _hitl_request_dump
)
- ctx.inputs.tool_result = new_tic
- ctx.inputs.tool_msg = ToolMessage(
- content=self._tool_interrupted_message(
- ctx.inputs.tool_name or "skill_acceleration_exec"
- ),
- tool_call_id=ctx.inputs.tool_call.id,
+ _original_tcid = str(_hitl_request.tool_call_id or "?")
+ else:
+ _hitl_request = _skill_turbo_tic.request
+ _original_tcid = (
+ _skill_turbo_tic.tool_call.id
+ if _skill_turbo_tic.tool_call
+ else "?"
)
+ new_tic = ToolInterruptException(
+ request=_hitl_request,
+ tool_call=ctx.inputs.tool_call,
+ )
+ ctx.inputs.tool_result = new_tic
+ ctx.inputs.tool_msg = ToolMessage(
+ content=_SKILL_TURBO_HITL_PLACEHOLDER,
+ tool_call_id=ctx.inputs.tool_call.id,
+ )
logger.info(
"[StreamEventRail] SkillTurbo HITL: rewrote tool_result to TIE. "
- "original_tcid=%s harness_tcid=%s",
- _skill_turbo_tic.tool_call.id if _skill_turbo_tic.tool_call else "?",
- ctx.inputs.tool_call.id if isinstance(ctx.inputs, ToolCallInputs) else "?",
+ "source=%s original_tcid=%s harness_tcid=%s",
+ "result_marker" if _hitl_request_dump is not None else "contextvar",
+ _original_tcid,
+ ctx.inputs.tool_call.id
+ if isinstance(ctx.inputs, ToolCallInputs)
+ else "?",
)
# 卡片由 harness __interaction__ 转换统一发出(外层
# tool_call_id,harness 恢复按同一 id 对齐);此处不再主动
# emit,避免同一次中断发出两张 ask_user 卡片。
return # 跳过 _emit_tool_result:中断态无结果可发
- except Exception:
- logger.debug(
- "[StreamEventRail] skill_turbo HITL rewrite failed",
- exc_info=True,
- )
+ except Exception:
+ logger.warning(
+ "[StreamEventRail] skill_turbo HITL rewrite failed",
+ exc_info=True,
+ )
if (
str(getattr(tc, "name", "") or "").strip() == "deepresearch_execute"
diff --git a/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py b/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py
index b0e3da0dff..feb3b6efe7 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py
@@ -55,6 +55,8 @@ def _build_skill_turbo_guide_text(language: str, skill_names: list[str]) -> str:
若 `skill_acceleration_exec` 返回成功(产物已生成),**禁止**再用 `skill_tool` 重复同一任务——直接向用户总结结果即可。若 `skill_acceleration_exec` 返回失败或未处理,**必须**继续用 `skill_tool` 加载对应技能走标准流程完成用户任务。
+⏸️ **暂停不是失败**:当 `skill_acceleration_exec` 暂停等待用户回答(返回"技能加速已暂停"类信息,或向用户弹出补充问题卡片)时,这是任务流的正常提问环节。**必须停止后续工具调用,等待用户回答**;用户回答后加速通道会自动从断点继续。**禁止**把暂停当成失败而改走 `skill_tool` 标准流程,那会丢弃已完成的阶段并从头重跑。
+
🚫 **选区/编辑已有 PPT 排除(重要例外,仅适用于 PPT 类任务)**:当用户消息出现"{keywords}"等选区字段,或意图是**编辑、修改已有 PPT 文件的局部内容**(如改字体颜色、改某段文案、调某页样式、替换某区域)而非从零生成整套演示文稿时,**禁止调用 `skill_acceleration_exec`**——它只会从流水线 Stage 1 重新生成全新 PPT,无法复用已有文件做局部修改。此类请求请改用 `skill_tool` 加载 pptx-craft 标准流程(支持编辑已有 PPT),或直接用 `edit_file`/读写 pptx 的普通工具完成局部修改。本条仅约束 PPT 局部编辑类请求,不适用于从零生成新产物的任务。
"""
names = ", ".join(skill_names)
@@ -66,6 +68,8 @@ If you have already mistakenly called `skill_tool` to load the corresponding ski
If `skill_acceleration_exec` returns success (the artifact is already generated), you are **forbidden** from calling `skill_tool` again for the same task — just summarize the result to the user. If `skill_acceleration_exec` returns failure or is not handled, you **MUST** fall back to `skill_tool` to load the corresponding skill and complete the user's task via the standard flow.
+⏸️ **Pause is NOT failure**: When `skill_acceleration_exec` pauses to wait for the user's answer (returning a "skill acceleration paused" style message, or showing a follow-up question card to the user), that is a normal clarification step of the pipeline. You **MUST stop making further tool calls and wait for the user's answer**; the acceleration channel will automatically resume from the breakpoint once answered. **DO NOT** treat the pause as a failure and switch to the `skill_tool` standard flow — that would discard completed stages and rerun from scratch.
+
🚫 **PPT region/edit-existing exclusion (critical exception, PPT tasks only)**: When the user message contains selection fields such as "{keywords}", or the intent is to **edit or modify a local part of an existing PPT file** (e.g. change font color, rewrite a paragraph, restyle a slide, replace a region) rather than generating a full deck from scratch, you are **FORBIDDEN from calling `skill_acceleration_exec`** — it only regenerates a brand-new PPT from pipeline Stage 1 and cannot reuse an existing file for local edits. For such requests, use `skill_tool` to load the pptx-craft standard flow (which supports editing existing PPTs), or directly use `edit_file` / pptx read-write tools to make the local change. This clause applies ONLY to local edits of existing PPTs, not to creating new artifacts from scratch.
"""
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
index b69d51d90a..2061913e47 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
@@ -289,13 +289,14 @@ PPT_TURBO_UNCONFIRMED_FINISH_TEXT = (
)
_SKILL_TURBO_ARTIFACT_SUMMARY_MARKER = "[SkillAccelerationExec 产物摘要]"
-# 工具返回值会先被 AbilityManager 收成 ToolMessage。after_tool_call 再用
-# StreamEventRail._tool_interrupted_message(随 prompt 语言中/英)覆写 tool_msg。
-# _fix_incomplete_tool_context 认 rail 文案 + 中英文 legacy 模板,故本常量取中文
-# 默认句即可。禁止返回 {'success': False, 'error': '任务已暂停等待审批'}:
-# str(dict) 进 ToolMessage 后模型会当成加速失败并回退 skill_tool。
+# HITL 暂停时工具不再返回本占位文案(改返回 _SKILL_TURBO_HITL_RESULT_KEY 标记
+# dict,见 build_skill_turbo_hitl_result)。本常量保留两个用途:
+# 1) after_tool_call 改写后的 tool_msg 文案基准("已暂停等待回答",非"被用户打断",
+# 防止外层模型把暂停误读为失败而放弃加速通道);
+# 2) _fix_incomplete_tool_context 的中断占位识别模板。
_SKILL_TURBO_HITL_PLACEHOLDER = (
- "[工具执行被中断] 工具 skill_acceleration_exec 执行过程中被用户打断,没有执行结果。"
+ "[技能加速已暂停] 工具 skill_acceleration_exec 正在等待用户回答,"
+ "回答后将自动继续执行,没有失败。"
)
# ── 待在外层 tool_result 之后发出的 PPT 交付总结 ──
@@ -467,8 +468,15 @@ def reset_skill_turbo_outer_todo_active(token: Token) -> None:
# skill_turbo_tools catch AbortError 后提取 ToolInterruptException 存入此 ContextVar,
# StreamEventRail.after_tool_call 读取后改写 ctx.inputs.tool_result 为 TIE,
# 使 harness 原生 HITL 机制(build_interrupt_state)检测并触发暂停。
+# ContextVar 依赖工具体与 after_tool_call 同执行上下文,跨上下文时不可见,
+# 仅作为旧路径兜底;主信号走工具返回值中的 _SKILL_TURBO_HITL_RESULT_KEY 标记。
_skill_turbo_hitl_tic: ContextVar[Any] = ContextVar("skill_turbo_hitl_tic", default=None)
+# HITL 暂停信号随工具返回值传递:SDK tracer 在工具结束时会对含返回值的
+# span 执行 copy.deepcopy,故标记值必须是可深拷贝的纯数据(dict/JSON),
+# 禁止直接返回 ToolInterruptException 等异常对象(无法按 SDK 方式重建)。
+_SKILL_TURBO_HITL_RESULT_KEY = "__skill_turbo_hitl__"
+
def set_skill_turbo_hitl_tic(tic: Any) -> Token:
return _skill_turbo_hitl_tic.set(tic)
@@ -478,6 +486,13 @@ def get_skill_turbo_hitl_tic() -> Any:
return _skill_turbo_hitl_tic.get()
+def build_skill_turbo_hitl_result(tic: Any) -> dict[str, Any]:
+ """构造随工具返回值传递的 HITL 暂停标记(deepcopy 安全的纯数据)。"""
+ request = getattr(tic, "request", None)
+ dump = request.model_dump(mode="json") if request is not None else {}
+ return {_SKILL_TURBO_HITL_RESULT_KEY: True, "request": dump}
+
+
def set_pending_ppt_delivery_summary(summary: str) -> None:
text = str(summary or "").strip()
_pending_ppt_delivery_summary.set(text or None)
@@ -1165,7 +1180,7 @@ async def skill_turbo(query: str) -> dict[str, Any] | str:
)
set_skill_turbo_hitl_tic(tic)
hitl_interrupt = True
- return _SKILL_TURBO_HITL_PLACEHOLDER
+ return build_skill_turbo_hitl_result(tic)
# Fallback: AbortError 无 ToolInterruptException cause,返回错误
logger.warning("[SkillTurboTool] AbortError without ToolInterruptException cause")
return _wrap_skill_turbo_result(
diff --git a/tests/unit_tests/agentserver/test_skill_turbo_hitl_resume_react.py b/tests/unit_tests/agentserver/test_skill_turbo_hitl_resume_react.py
index eeaaccc7a8..695d9ee655 100644
--- a/tests/unit_tests/agentserver/test_skill_turbo_hitl_resume_react.py
+++ b/tests/unit_tests/agentserver/test_skill_turbo_hitl_resume_react.py
@@ -11,6 +11,8 @@ import pytest
from openjiuwen.core.foundation.llm import AssistantMessage, ToolMessage, UserMessage
from openjiuwen.core.session.interaction.interactive_input import InteractiveInput
+from openjiuwen.core.single_agent.interrupt.exception import ToolInterruptException
+from openjiuwen.core.single_agent.interrupt.response import ToolCallInterruptRequest
from openjiuwen.core.single_agent.interrupt.state import RESUME_USER_INPUT_KEY
from openjiuwen.core.single_agent.rail.base import ToolCallInputs
from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
@@ -883,14 +885,65 @@ async def test_skill_turbo_hitl_after_tool_call_writes_placeholder_tool_msg():
finally:
set_skill_turbo_hitl_tic(None)
+ assert isinstance(ctx.inputs.tool_result, ToolInterruptException)
assert isinstance(ctx.inputs.tool_msg, ToolMessage)
- assert ctx.inputs.tool_msg.content == rail._tool_interrupted_message(
- "skill_acceleration_exec"
- )
+ assert ctx.inputs.tool_msg.content == _SKILL_TURBO_HITL_PLACEHOLDER
assert ctx.inputs.tool_msg.tool_call_id == "call_982c"
assert ctx.inputs.tool_msg is not leaked
+async def test_skill_turbo_hitl_after_tool_call_rewrites_from_result_marker():
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ build_skill_turbo_hitl_result,
+ )
+
+ rail = JiuSwarmStreamEventRail()
+ rail.set_skill_turbo_adapter(object())
+ session = _StreamSession()
+ tool_call = SimpleNamespace(
+ id="call_982d",
+ name="skill_acceleration_exec",
+ arguments={"query": "生成PPT"},
+ )
+ ctx = SimpleNamespace(
+ session=session,
+ inputs=ToolCallInputs(
+ tool_call=tool_call,
+ tool_name="skill_acceleration_exec",
+ tool_args={"query": "生成PPT"},
+ tool_result=build_skill_turbo_hitl_result(
+ ToolInterruptException(
+ request=ToolCallInterruptRequest(
+ message="风格",
+ auto_confirm_key="ask_user:style",
+ ),
+ tool_call=SimpleNamespace(
+ id="skill_turbo-tc-ask_user-2",
+ name="ask_user",
+ arguments={},
+ ),
+ )
+ ),
+ tool_msg=None,
+ ),
+ extra={},
+ exception=None,
+ request_force_finish=lambda *_args, **_kwargs: None,
+ )
+ set_skill_turbo_hitl_tic(None)
+ await rail.after_tool_call(ctx)
+
+ assert isinstance(ctx.inputs.tool_result, ToolInterruptException)
+ rebuilt_request = ctx.inputs.tool_result.request
+ assert getattr(rebuilt_request, "message", "") == "风格"
+ assert getattr(rebuilt_request, "auto_confirm_key", "") == "ask_user:style"
+ assert ctx.inputs.tool_result.tool_call is tool_call
+ assert isinstance(ctx.inputs.tool_msg, ToolMessage)
+ assert ctx.inputs.tool_msg.content == _SKILL_TURBO_HITL_PLACEHOLDER
+ assert ctx.inputs.tool_msg.tool_call_id == "call_982d"
+
+
class _ModelContext:
def __init__(self, messages):
self.messages = list(messages)
diff --git a/tests/unit_tests/agentserver/test_skill_turbo_hitl_tie_rewrite_repro.py b/tests/unit_tests/agentserver/test_skill_turbo_hitl_tie_rewrite_repro.py
new file mode 100644
index 0000000000..9b403d917f
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_skill_turbo_hitl_tie_rewrite_repro.py
@@ -0,0 +1,236 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""验证 skill_turbo HITL TIC 经工具链后仍被 after_tool_call TIE 改写消费。"""
+
+from __future__ import annotations
+
+import uuid
+from types import SimpleNamespace
+
+import pytest
+from openjiuwen.core.foundation.llm import (
+ ModelClientConfig,
+ ModelRequestConfig,
+ ToolCall,
+)
+from openjiuwen.core.foundation.llm.schema.message_chunk import AssistantMessageChunk
+from openjiuwen.core.foundation.tool import Tool, ToolCard
+from openjiuwen.core.runner import Runner
+from openjiuwen.core.session.agent import Session
+from openjiuwen.core.single_agent.ability_manager import AbilityManager
+from openjiuwen.core.single_agent.agent_callback_manager import AgentCallbackManager
+from openjiuwen.core.single_agent.interrupt.exception import ToolInterruptException
+from openjiuwen.core.single_agent.interrupt.response import InterruptRequest
+from openjiuwen.core.single_agent.rail.base import (
+ AgentCallbackContext,
+ ToolCallInputs,
+)
+from openjiuwen.harness import create_deep_agent
+
+from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
+ JiuSwarmStreamEventRail,
+)
+from jiuwenswarm.server.runtime.skill_turbo import skill_turbo_tools
+from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ build_skill_turbo_hitl_result,
+ set_skill_turbo_hitl_tic,
+)
+
+TOOL_NAME = "skill_turbo_hitl_repro_tool"
+
+
+class _StreamSession:
+ def __init__(self):
+ self.chunks = []
+
+ async def write_stream(self, chunk):
+ self.chunks.append(chunk)
+
+
+def _make_tic() -> ToolInterruptException:
+ inner_tc = SimpleNamespace(
+ id="skill_turbo-tc-ask_user-stub-0",
+ name="ask_user",
+ arguments={"questions": [{"question": "页数"}]},
+ )
+ return ToolInterruptException(
+ request=InterruptRequest(message="页数"),
+ tool_call=inner_tc,
+ )
+
+
+def _hitl_result_marker() -> dict:
+ return build_skill_turbo_hitl_result(_make_tic())
+
+
+async def _hitl_stub(query: str = "") -> dict:
+ set_skill_turbo_hitl_tic(_make_tic())
+ return _hitl_result_marker()
+
+
+class _HitlTool(Tool):
+ def __init__(self, name: str):
+ super().__init__(ToolCard(name=name, description="hitl repro"))
+ self.calls = 0
+
+ async def invoke(self, inputs, **kwargs):
+ self.calls += 1
+ set_skill_turbo_hitl_tic(_make_tic())
+ return _hitl_result_marker()
+
+ async def stream(self, inputs, **kwargs):
+ yield await self.invoke(inputs, **kwargs)
+
+
+class _HitlModel:
+ def __init__(self):
+ self.model_client_config = ModelClientConfig(
+ client_provider="OpenAI", api_key="fake", api_base="https://fake.invalid"
+ )
+ self.model_config = ModelRequestConfig(model_name="fake")
+ self.calls = []
+
+ def _respond(self):
+ from openjiuwen.core.foundation.llm import AssistantMessage
+
+ if len(self.calls) == 1:
+ return AssistantMessage(
+ content="",
+ tool_calls=[
+ ToolCall(
+ id="call-hitl-1",
+ type="function",
+ name=TOOL_NAME,
+ arguments="{}",
+ )
+ ],
+ )
+ return AssistantMessage(content="fallback to standard flow")
+
+ async def invoke(self, messages, **kwargs):
+ self.calls.append(list(messages))
+ return self._respond()
+
+ async def stream(self, messages, **kwargs):
+ msg = await self.invoke(messages, **kwargs)
+ if msg.tool_calls:
+ yield AssistantMessageChunk(content="", tool_calls=msg.tool_calls)
+ else:
+ yield AssistantMessageChunk(content=msg.content)
+
+
+async def test_skill_turbo_hitl_tie_rewrite_survives_ability_manager_chain():
+ tool_name = f"skill_turbo_hitl_repro_{uuid.uuid4().hex[:8]}"
+ from openjiuwen.core.foundation.tool import LocalFunction
+
+ tool = LocalFunction(
+ ToolCard(id=tool_name, name=tool_name, description="repro", stateless=True),
+ _hitl_stub,
+ )
+ Runner.resource_mgr.add_tool(tool)
+ ability_manager = AbilityManager()
+ ability_manager.add(tool.card)
+
+ rail = JiuSwarmStreamEventRail()
+ rail.set_skill_turbo_adapter(SimpleNamespace(_instance=None))
+ ns = f"repro_{uuid.uuid4().hex[:8]}"
+ agent = SimpleNamespace(agent_callback_manager=AgentCallbackManager(ns))
+ await agent.agent_callback_manager.register_rail(rail, agent)
+
+ session = _StreamSession()
+ tool_call = ToolCall(
+ id=f"call_{uuid.uuid4().hex[:24]}",
+ type="function",
+ name=tool_name,
+ arguments="{}",
+ )
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=ToolCallInputs(
+ tool_call=tool_call,
+ tool_name=tool_name,
+ tool_args={},
+ ),
+ config=None,
+ session=session,
+ context=None,
+ extra={},
+ )
+ try:
+ results = await ability_manager.execute(ctx, tool_call, session)
+ result = results[0][0]
+ assert isinstance(result, ToolInterruptException), (
+ f"TIE rewrite ineffective: outer agent got {result!r} "
+ "and will treat it as user-interrupted then abandon the turbo channel"
+ )
+ finally:
+ Runner.resource_mgr.remove_tool(tool.card.id)
+ await agent.agent_callback_manager.unregister_rail(rail, agent)
+
+
+async def test_skill_turbo_hitl_tie_rewrite_pauses_deep_agent_react_loop():
+ await Runner.start()
+ tool = _HitlTool(TOOL_NAME)
+ model = _HitlModel()
+ rail = JiuSwarmStreamEventRail()
+ rail.set_skill_turbo_adapter(SimpleNamespace(_instance=None))
+ core = create_deep_agent(
+ model=model,
+ tools=[tool],
+ rails=[rail],
+ system_prompt="Test",
+ enable_task_loop=False,
+ max_iterations=6,
+ )
+ sid = "hitl-tie-repro-" + uuid.uuid4().hex
+ session = Session(session_id=sid)
+ try:
+ await core.start(session=session)
+ result = await core.invoke({"query": "make a ppt"}, session=session)
+ assert result.get("result_type") == "interrupt", (
+ "outer ReAct loop consumed the HITL placeholder as a normal "
+ f"tool_result and continued: got {result!r}"
+ )
+ finally:
+ await core.stop()
+
+
+async def test_skill_turbo_hitl_tie_rewrite_survives_context_isolation(monkeypatch):
+ """验证 ContextVar 跨上下文不可见时,返回值标记仍能完成 TIE 改写并暂停。"""
+ monkeypatch.setattr(skill_turbo_tools, "get_skill_turbo_hitl_tic", lambda: None)
+ await Runner.start()
+ tool = _HitlTool(TOOL_NAME)
+ model = _HitlModel()
+ rail = JiuSwarmStreamEventRail()
+ rail.set_skill_turbo_adapter(SimpleNamespace(_instance=None))
+ core = create_deep_agent(
+ model=model,
+ tools=[tool],
+ rails=[rail],
+ system_prompt="Test",
+ enable_task_loop=False,
+ max_iterations=6,
+ )
+ sid = "hitl-tie-ctx-" + uuid.uuid4().hex
+ session = Session(session_id=sid)
+ try:
+ await core.start(session=session)
+ result = await core.invoke({"query": "make a ppt"}, session=session)
+ assert result.get("result_type") == "interrupt", (
+ "TIC invisible across contexts and result-marker rewrite "
+ f"ineffective: outer agent got {result!r}"
+ )
+ finally:
+ await core.stop()
+
+
+def test_skill_turbo_hitl_result_marker_is_deepcopy_safe():
+ """验证 HITL 标记可被 SDK tracer 对含工具返回值的 span 做 deepcopy。"""
+ import copy
+
+ marker = _hitl_result_marker()
+ cloned = copy.deepcopy(marker)
+ assert cloned == marker
+ assert cloned["request"]["message"] == "页数"
diff --git a/tests/unit_tests/agentserver/test_skill_turbo_tools.py b/tests/unit_tests/agentserver/test_skill_turbo_tools.py
index be22a67e8b..3349a56f32 100644
--- a/tests/unit_tests/agentserver/test_skill_turbo_tools.py
+++ b/tests/unit_tests/agentserver/test_skill_turbo_tools.py
@@ -279,7 +279,7 @@ async def test_hitl_abort_does_not_clear_or_post_run_turbo_session(
),
):
from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
- _SKILL_TURBO_HITL_PLACEHOLDER,
+ _SKILL_TURBO_HITL_RESULT_KEY,
set_skill_turbo_hitl_tic,
)
@@ -289,7 +289,9 @@ async def test_hitl_abort_does_not_clear_or_post_run_turbo_session(
finally:
set_skill_turbo_hitl_tic(None)
- assert result == _SKILL_TURBO_HITL_PLACEHOLDER
+ assert isinstance(result, dict)
+ assert result.get(_SKILL_TURBO_HITL_RESULT_KEY) is True
+ assert isinstance(result.get("request"), dict)
clear_ctx.assert_not_awaited()
turbo_session.post_run.assert_not_awaited()
turbo_session.close_stream.assert_not_awaited()