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(ask_user): 修复 StructuredAskUserRail 硬塞 [INVALID_ARGUMENT] 与 _is_auto_skip 空 answers 误判

d300296967e484aafdf00
diff --git a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
index 5df23ce221..eb8e592fa6 100644
--- a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
@@ -35,6 +35,7 @@ from openjiuwen.harness.rails.interrupt.interrupt_base import (
from jiuwenswarm.common.schema.ask_user import (
AskUserResponseError,
ask_user_response_schema,
+ decode_user_input,
parse_ask_user_response,
)
@@ -428,10 +429,23 @@ class StructuredAskUserRail(AskUserRail):
# Detect if this was a structured questions call by checking tool_args
is_structured = questions_data is not None and len(questions_data) > 0
+ # user_input is the USER's response, not the model's tool-call args.
+ # Any parse failure (non-dict, missing fields, illegal status, non-array
+ # answers, etc.) means "the user did not provide a usable structured
+ # answer" -> treat as skipped and let the model decide. Do NOT hardcode
+ # [INVALID_ARGUMENT] here: that code semantically signals "the MODEL's
+ # tool-call args were invalid" and misleads the LLM into thinking the
+ # tool is broken, triggering fallback cascades and deadlocks.
+ decoded = decode_user_input(user_input)
try:
- response = parse_ask_user_response(user_input)
+ response = parse_ask_user_response(decoded)
except AskUserResponseError as exc:
- return self.reject(tool_result=f"[INVALID_ARGUMENT] {exc}")
+ logger.info(
+ "[StructuredAskUserRail] user_input parse failed (%s), "
+ "treating as skipped",
+ exc,
+ )
+ return self.reject(tool_result=self._build_skipped_tool_result())
machine_payload = response.to_dict(include_original_request=False)
if is_structured and return_json:
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index fce2418f65..0283114b21 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -1481,9 +1481,14 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
) -> None:
"""Emit chat.ask_user_question for SkillTurbo nested ask_user HITL.
- Questions come from the inner ask_user tool_call; request_id is the
- outer skill_acceleration_exec tool_call.id so OfficeClaw resume keeps
- matching harness interrupt keys (e.g. call_c2967...).
+ request_id is the inner ask_user tool_call.id (unique per ask_user),
+ NOT the outer skill_acceleration_exec id. This ensures sequential
+ ask_user cards within the same skill_acceleration_exec have distinct
+ request_ids, so the frontend shows each as a separate card.
+
+ SkillTurbo resume (_resume_user_input_from_raw) extracts the user's
+ answer via ``next(iter(user_inputs.values()))`` — it ignores the key,
+ so using the inner ask_user id does not break resume.
"""
inner_tc = getattr(skill_turbo_tic, "tool_call", None)
payload = _ask_user_question_payload_from_interrupt(
@@ -1495,19 +1500,14 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
"[StreamEventRail] SkillTurbo HITL ask_user payload unavailable"
)
return
- # OfficeClaw resume matches harness interrupt keys on the outer
- # skill_acceleration_exec id. Emitting with the nested ask_user id is
- # worse than skipping: the UI would show a question that cannot resume.
- harness_id = str(getattr(outer_tool_call, "id", "") or "").strip()
- if not harness_id:
+ inner_request_id = str(payload.get("request_id") or "").strip()
+ if not inner_request_id:
logger.warning(
"[StreamEventRail] SkillTurbo HITL ask_user skipped: "
- "outer skill_acceleration_exec tool_call.id unavailable "
- "(would mismatch harness interrupt key); inner_request_id=%s",
- payload.get("request_id"),
+ "inner ask_user request_id unavailable; harness_id=%s",
+ getattr(outer_tool_call, "id", ""),
)
return
- payload["request_id"] = harness_id
try:
await session.write_stream(
OutputSchema(
@@ -1518,8 +1518,9 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
)
logger.info(
"[StreamEventRail] SkillTurbo HITL emitted chat.ask_user_question "
- "request_id=%s",
- payload.get("request_id"),
+ "request_id=%s harness_id=%s",
+ inner_request_id,
+ getattr(outer_tool_call, "id", ""),
)
except Exception:
logger.debug(
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
index 234c6b6b71..84884c77ff 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
@@ -18,6 +18,7 @@ from openjiuwen.core.foundation.tool import tool
from jiuwenswarm.common.schema.ask_user import (
AskUserResponse,
AskUserResponseError,
+ decode_user_input,
parse_ask_user_response,
)
@@ -244,23 +245,8 @@ def _append_timing_window(
return next_state
-def _decode_user_input(value: Any) -> Any:
- if isinstance(value, str):
- try:
- return json.loads(value)
- except (TypeError, ValueError):
- return value
- model_dump = getattr(value, "model_dump", None)
- if callable(model_dump):
- try:
- return model_dump(mode="json")
- except TypeError:
- return model_dump()
- return value
-
-
def _parse_response(value: Any) -> AskUserResponse:
- decoded = _decode_user_input(value)
+ decoded = decode_user_input(value)
if not isinstance(decoded, Mapping):
raise AskUserResponseError("AskUser response must be an object")
if decoded.get("status") in {"error", "cancelled"}:
@@ -269,7 +255,7 @@ def _parse_response(value: Any) -> AskUserResponse:
def _terminal_interaction_status(value: Any) -> str:
- decoded = _decode_user_input(value)
+ decoded = decode_user_input(value)
if not isinstance(decoded, Mapping):
return ""
status = str(decoded.get("status") or "").strip().lower()
@@ -543,7 +529,7 @@ def _marker_prompt(outcome: Mapping[str, Any]) -> str:
def _interaction_json(value: Any) -> str:
- decoded = _decode_user_input(value)
+ decoded = decode_user_input(value)
if isinstance(decoded, Mapping):
return json.dumps(dict(decoded), ensure_ascii=False, separators=(",", ":"))
return ""
diff --git a/jiuwenswarm/common/schema/ask_user.py b/jiuwenswarm/common/schema/ask_user.py
index 13e59aac9f..7f29acc184 100644
--- a/jiuwenswarm/common/schema/ask_user.py
+++ b/jiuwenswarm/common/schema/ask_user.py
@@ -4,6 +4,7 @@
from __future__ import annotations
+import json
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, Literal
@@ -206,3 +207,28 @@ def parse_ask_user_response(value: Any) -> AskUserResponse:
answers=value["answers"],
original_request=value.get("original_request"),
)
+
+
+def decode_user_input(value: Any) -> Any:
+ """Decode user_input into a canonical form before strict parsing.
+
+ Handles two accidental encodings that leak into resolve_interrupt:
+ 1. JSON string (double-encoded by transport layer) -> dict via json.loads.
+ 2. pydantic model with model_dump -> dict.
+
+ Anything else is returned as-is so callers (e.g. StructuredAskUserRail)
+ can treat non-Mapping values as "user did not provide a structured answer"
+ rather than raising INVALID_ARGUMENT on the model's behalf.
+ """
+ if isinstance(value, str):
+ try:
+ return json.loads(value)
+ except (TypeError, ValueError):
+ return value
+ model_dump = getattr(value, "model_dump", None)
+ if callable(model_dump):
+ try:
+ return model_dump(mode="json")
+ except TypeError:
+ return model_dump()
+ return value
diff --git a/jiuwenswarm/server/runtime/skill_turbo/rails/ask_user_rail.py b/jiuwenswarm/server/runtime/skill_turbo/rails/ask_user_rail.py
index 14923dca97..f55b0fdce8 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/rails/ask_user_rail.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/rails/ask_user_rail.py
@@ -25,6 +25,7 @@ from typing import Any, Optional
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from jiuwenswarm.agents.harness.common.rails.ask_user_rail import StructuredAskUserRail
+from jiuwenswarm.common.schema.ask_user import decode_user_input
logger = logging.getLogger(__name__)
@@ -59,7 +60,10 @@ class SkillTurboAskUserRail(StructuredAskUserRail):
)
return self.interrupt(self._build_ask_request(tool_call))
- answers = self._parse_user_answers(user_input)
+ # 与父类 resolve_interrupt 对齐:JSON 字符串(传输层双重编码)/ pydantic
+ # model 形态先归一为 dict/list,避免误判为不认识形态而 re-interrupt
+ # (重放时确定性 tool_call_id 相同,重问帧会被 sidecar dedup 吞掉)。
+ answers = self._parse_user_answers(decode_user_input(user_input))
if answers is None:
# 无法解析(不认识的 user_input 形态)→ 重新中断等待
logger.warning(
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/requirement_collect.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/requirement_collect.py
index f7dfd42137..20313541b6 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/requirement_collect.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/requirement_collect.py
@@ -804,9 +804,24 @@ def _answer_item_is_empty(item: Any) -> bool:
def _is_auto_skip(status: str, answers: list[Any]) -> bool:
- """Detect Relay-Claw 侧 120s 倒计时自动应答(answered + 全部空答案)。"""
- if status != "answered" or not answers:
+ """Detect when the user did not provide a usable answer.
+
+ Two shapes both count as "auto-skip" -> LLM fallback fills defaults:
+ 1. Relay-Claw 120s timeout auto-answer: ``status=="answered"`` with a
+ non-empty answers list whose items are all empty (blank
+ selected_options + no free text).
+ 2. Pure skip / empty answers: ``status=="answered"`` with an empty (or
+ None-coerced) answers list. The previous ``not answers`` short-circuit
+ wrongly classified this as a RequirementCollectError, which triggered
+ fallback subagent re-asks of ask_user in a loop (the LLM saw an empty
+ answers envelope and decided to ask again). Treating empty answers as
+ auto-skip lets the existing ``_llm_default_*`` fallback infer the field
+ from context, breaking the re-ask loop.
+ """
+ if status != "answered":
return False
+ if not answers:
+ return True
return all(_answer_item_is_empty(item) for item in answers)
diff --git a/tests/unit_tests/agentserver/test_ask_user_validation.py b/tests/unit_tests/agentserver/test_ask_user_validation.py
index 5ff5612080..926ba3e55b 100644
--- a/tests/unit_tests/agentserver/test_ask_user_validation.py
+++ b/tests/unit_tests/agentserver/test_ask_user_validation.py
@@ -311,7 +311,9 @@ async def test_non_exact_skipped_shapes_are_rejected(user_input):
decision = await rail.resolve_interrupt(MagicMock(), tc, user_input)
assert isinstance(decision, RejectResult)
- assert "INVALID_ARGUMENT" in decision.tool_result
+ # Non-exact / malformed shapes are treated as skipped (not [INVALID_ARGUMENT])
+ # so the LLM does not mistake the tool as broken and trigger fallback cascades.
+ assert "未提供回答" in decision.tool_result
@pytest.mark.asyncio
@@ -423,4 +425,6 @@ async def test_legacy_answer_representations_are_rejected(legacy_input):
decision = await rail.resolve_interrupt(MagicMock(), tc, legacy_input)
assert isinstance(decision, RejectResult)
- assert "INVALID_ARGUMENT" in decision.tool_result
+ # Legacy / unparseable representations are treated as skipped (not
+ # [INVALID_ARGUMENT]) to avoid misleading the LLM into fallback cascades.
+ assert "未提供回答" in decision.tool_result
diff --git a/tests/unit_tests/agentserver/test_stream_event_rail_todo.py b/tests/unit_tests/agentserver/test_stream_event_rail_todo.py
index a305f941e4..f673fa51b3 100644
--- a/tests/unit_tests/agentserver/test_stream_event_rail_todo.py
+++ b/tests/unit_tests/agentserver/test_stream_event_rail_todo.py
@@ -196,8 +196,10 @@ async def test_ask_user_interrupt_emits_question_event_from_tool_args():
@pytest.mark.asyncio
-async def test_skill_turbo_hitl_emits_ask_user_with_outer_request_id():
- """Nested ask_user questions, but resume key is outer skill_acceleration_exec id."""
+async def test_skill_turbo_hitl_emits_ask_user_with_inner_request_id():
+ """Nested ask_user questions use the inner ask_user tool_call.id as
+ request_id, so sequential ask_user cards are not conflated by the
+ frontend (which keys cards on requestId)."""
class ToolInterruptException(Exception):
def __init__(self):
super().__init__()
@@ -240,19 +242,19 @@ async def test_skill_turbo_hitl_emits_ask_user_with_outer_request_id():
assert len(session.outputs) == 1
output = session.outputs[0]
assert output.type == "chat.ask_user_question"
- assert output.payload["request_id"] == "call_c2967f3aec5c412583a203b9"
+ assert output.payload["request_id"] == "skill_turbo-tc-ask_user-54ee111d-0"
assert output.payload["source"] == "ask_user_interrupt"
assert output.payload["questions"][0]["question"] == "需要多少页?"
@pytest.mark.asyncio
-async def test_skill_turbo_hitl_skips_emit_when_outer_tool_call_missing(monkeypatch):
- """Without outer harness id, do not emit a nested ask_user request_id."""
+async def test_skill_turbo_hitl_skips_emit_when_inner_request_id_missing(monkeypatch):
+ """Without inner ask_user request_id, do not emit a question card."""
class ToolInterruptException(Exception):
def __init__(self):
super().__init__()
self.request = SimpleNamespace(
- tool_call_id="skill_turbo-tc-ask_user-54ee111d-0",
+ tool_call_id="",
tool_name="ask_user",
tool_args={
"questions": [
@@ -264,30 +266,9 @@ async def test_skill_turbo_hitl_skips_emit_when_outer_tool_call_missing(monkeypa
]
},
)
- self.tool_call = SimpleNamespace(
- id="skill_turbo-tc-ask_user-54ee111d-0",
- name="ask_user",
- arguments={
- "questions": [
- {
- "question": "需要多少页?",
- "header": "页数",
- "options": [{"label": "10页", "description": ""}],
- }
- ]
- },
- )
+ self.tool_call = None
session = _FakeSession()
- warnings: list[str] = []
-
- def _capture_warning(msg, *args, **kwargs):
- warnings.append(msg % args if args else str(msg))
-
- monkeypatch.setattr(
- "jiuwenswarm.agents.harness.common.rails.stream_event_rail.logger.warning",
- _capture_warning,
- )
await JiuSwarmStreamEventRail._emit_skill_turbo_ask_user_question(
session,
@@ -296,10 +277,6 @@ async def test_skill_turbo_hitl_skips_emit_when_outer_tool_call_missing(monkeypa
)
assert session.outputs == []
- assert any(
- "outer skill_acceleration_exec tool_call.id unavailable" in message
- for message in warnings
- )
@pytest.mark.asyncio