From 24fdcbadfa94e595c1cf5a000329c3a69cf9e0d4 Mon Sep 17 00:00:00 2001
From: Chunyi Peng <86450844+hm1229@users.noreply.github.com>
Date: Mon, 13 Jul 2026 14:58:09 +0800
Subject: [PATCH 001/309] Update README.zh.md
---
README.zh.md | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/README.zh.md b/README.zh.md
index 1e6540162..c4837ef78 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -6,8 +6,7 @@
**把企业岗位转化为可配置、可执行、可观测数字员工的一体化平台。**
-[English](./README.md) | [简体中文](./README.zh.md)
-
+[English](./README.md) | 简体中文
@@ -325,4 +324,4 @@ npm run build
## 致谢
-URStaff 由 [OpenBMB](https://www.openbmb.cn/) 生态孵化。README 结构参考了 [PilotDeck](https://github.com/OpenBMB/PilotDeck) 简洁、Demo 优先的呈现方式。感谢 FastAPI、React、Vite、SQLModel、Pydantic 与 OpenAI 兼容 API 生态的开源贡献者。
+URStaff 由 [OpenBMB](https://www.openbmb.cn/) 生态孵化。
From 0767a0339fea0d1633692aa1657c51bb11e50a46 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Mon, 13 Jul 2026 20:38:40 +0800
Subject: [PATCH 002/309] feat: improve agent context and chat reliability
---
backend/app/core/agent_loop.py | 127 ++++++--
backend/app/core/context_projection.py | 180 ++++++-----
backend/app/core/conversation_context.py | 302 +++++++++++++-----
backend/app/core/reflection_agent.py | 21 +-
backend/app/core/response_generator.py | 40 ++-
backend/app/core/router.py | 49 +--
backend/app/core/step_agent.py | 29 +-
backend/app/db/database.py | 3 +
backend/app/db/models.py | 1 +
backend/app/general_skills/runner.py | 2 +-
backend/app/llm/client.py | 227 +++++++++++--
backend/app/llm/output_policy.py | 34 +-
backend/app/llm/prompts/reflection_prompt.md | 21 +-
.../llm/prompts/response_generator_prompt.md | 6 +-
backend/app/llm/prompts/router_prompt.md | 40 +--
backend/app/llm/prompts/step_agent_prompt.md | 30 +-
.../app/llm/prompts/unified_agent_prompt.md | 13 +
backend/app/llm/stage_protocol.py | 133 ++++++++
backend/app/skills/llm_limits.py | 2 +-
backend/app/skills/skill_distiller.py | 186 ++++++++++-
backend/tests/test_agent_loop_completion.py | 37 ++-
backend/tests/test_context_projection.py | 85 ++++-
backend/tests/test_conversation_context.py | 60 +++-
backend/tests/test_general_skills.py | 24 +-
backend/tests/test_llm_client.py | 147 +++++++--
backend/tests/test_response_generator.py | 4 +-
backend/tests/test_router.py | 17 +-
backend/tests/test_skill_distiller_generic.py | 46 +++
backend/tests/test_skill_editing_and_stats.py | 29 +-
backend/tests/test_step_agent_model_driven.py | 25 +-
backend/tests/test_unified_agent_prompt.py | 100 ++++++
.../src/pages/chat/chatHelpers.tsx | 38 ++-
.../src/pages/chat/chatPageStyles.ts | 12 +-
.../src/pages/chat/components/ChatDialogs.tsx | 2 +-
.../pages/chat/components/MessageBubble.tsx | 14 +-
.../src/pages/chat/components/MessageList.tsx | 6 +-
.../src/pages/chat/useChatSession.ts | 99 +++---
37 files changed, 1660 insertions(+), 531 deletions(-)
create mode 100644 backend/app/llm/prompts/unified_agent_prompt.md
create mode 100644 backend/app/llm/stage_protocol.py
create mode 100644 backend/tests/test_unified_agent_prompt.py
diff --git a/backend/app/core/agent_loop.py b/backend/app/core/agent_loop.py
index 76dad23ea..62dc636a7 100644
--- a/backend/app/core/agent_loop.py
+++ b/backend/app/core/agent_loop.py
@@ -59,7 +59,9 @@
knowledge_citations_from_results,
)
from app.knowledge.schema import KnowledgeSearchRequest, KnowledgeSearchResponse
-from app.llm import LLMError
+from app.llm import LLMClient, LLMError
+from app.llm.stage_protocol import stage_payload, unified_system_prompt
+from app.observability.spans import llm_operation
from app.memory.jobs import enqueue_memory_capture
from app.memory.service import MemoryService, memory_read
from app.observability import EventLog
@@ -85,7 +87,6 @@
DEFAULT_REFLECTION_MAX_ROUNDS = 1
REFLECTION_MAX_ROUNDS_LIMIT = 5
MAX_TOOL_ACTIONS_PER_TURN = 6
-ROUTER_CONTEXT_MESSAGES = 8
TOOL_CALL_HISTORY_SLOT = "_tool_call_history"
TOOL_RESULTS_SLOT = "_tool_results"
GRAPH_PENDING_STEPS_SLOT = "_graph_pending_steps"
@@ -1080,6 +1081,7 @@ def _stream_continue_pending_after_completion(
conversation_context,
reflection_stream_events,
completed_skill_ids_this_turn,
+ memory_context=memory_context,
)
for event_name, payload in reflection_stream_events:
yield self._stream_event(event_name, chat_session, payload)
@@ -1386,7 +1388,6 @@ def stream_failure_response(
chat_session,
{"newSessionId": chat_session.id, "sessionId": chat_session.id},
)
- yield self._stream_status(chat_session, "received", "已收到消息")
user_message = self._append_message(
request.tenant_id,
chat_session.id,
@@ -1424,6 +1425,12 @@ def stream_failure_response(
self.db.commit()
self.db.refresh(chat_session)
self.db.refresh(user_message)
+ yield self._stream_status(
+ chat_session,
+ "preparing",
+ "正在整理上下文",
+ user_message_id=user_message_id,
+ )
model_config = self._get_request_model(request, chat_session.agent_id)
if not model_config:
@@ -1546,16 +1553,18 @@ def stream_failure_response(
)
self.db.commit()
self.db.refresh(chat_session)
- conversation_context = self._conversation_context(chat_session)
- router_context = self._conversation_context(
- chat_session, max_messages=ROUTER_CONTEXT_MESSAGES
- )
+ conversation_context = self._conversation_context(chat_session, model_config=model_config)
yield self._stream_status(
chat_session, "routing", "正在判断用户意图", user_message_id=user_message_id
)
router_decision = self.router.decide(
- request.message, chat_session, skills, model_config, router_context, memory_context
+ request.message,
+ chat_session,
+ skills,
+ model_config,
+ conversation_context,
+ memory_context,
)
hydrated_slots = self._hydrate_router_decision_from_context(
chat_session, router_decision, skills, memory_context
@@ -1890,6 +1899,7 @@ def stream_failure_response(
reflection_max_rounds,
conversation_context,
reflection_stream_events,
+ memory_context=memory_context,
)
for event_name, payload in reflection_stream_events:
yield self._stream_event(
@@ -2219,14 +2229,16 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
)
self.db.commit()
self.db.refresh(chat_session)
- conversation_context = self._conversation_context(chat_session)
- router_context = self._conversation_context(
- chat_session, max_messages=ROUTER_CONTEXT_MESSAGES
- )
+ conversation_context = self._conversation_context(chat_session, model_config=model_config)
status("routing")
router_decision = self.router.decide(
- request.message, chat_session, skills, model_config, router_context, memory_context
+ request.message,
+ chat_session,
+ skills,
+ model_config,
+ conversation_context,
+ memory_context,
)
hydrated_slots = self._hydrate_router_decision_from_context(
chat_session, router_decision, skills, memory_context
@@ -2425,6 +2437,7 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
tool_result,
self._get_reflection_max_rounds(request.tenant_id),
conversation_context,
+ memory_context=memory_context,
)
(
active_skill,
@@ -2946,6 +2959,7 @@ def _try_continue_pending_after_completion(
self._get_reflection_max_rounds(request.tenant_id),
conversation_context,
completed_skill_ids_this_turn=completed_skill_ids_this_turn,
+ memory_context=memory_context,
)
(
active_skill,
@@ -3139,6 +3153,7 @@ def _run_reflection_rounds(
conversation_context: dict[str, object] | None = None,
stream_events: list[tuple[str, dict[str, object]]] | None = None,
completed_skill_ids_this_turn: set[str] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> tuple[Skill | None, RouterDecision, StepAgentResult, ToolResult | None]:
conversation_context = conversation_context or self._conversation_context(chat_session)
completed_skill_ids_this_turn = completed_skill_ids_this_turn or set()
@@ -3194,6 +3209,7 @@ def _run_reflection_rounds(
conversation_context,
stream_events,
completed_skill_ids_this_turn,
+ memory_context,
)
if not retried:
break
@@ -3334,6 +3350,7 @@ def _auto_progress_skill_graph(
conversation_context,
reflection_events,
completed_skill_ids_this_turn,
+ memory_context,
)
if reflection_events:
stream_events.extend(reflection_events)
@@ -3364,6 +3381,7 @@ def _reflect_and_retry(
conversation_context: dict[str, object] | None = None,
stream_events: list[tuple[str, dict[str, object]]] | None = None,
completed_skill_ids_this_turn: set[str] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> tuple[Skill | None, RouterDecision, StepAgentResult, ToolResult | None, bool]:
conversation_context = conversation_context or self._conversation_context(chat_session)
completed_skill_ids_this_turn = completed_skill_ids_this_turn or set()
@@ -3382,6 +3400,7 @@ def _reflect_and_retry(
tools,
model_config,
conversation_context,
+ memory_context,
)
except LLMError as exc:
self.events.record(
@@ -3653,6 +3672,7 @@ def _execute_tool_action_cycle(
status_callback: StatusCallback | None = None,
) -> tuple[StepAgentResult, ToolResult | None]:
tool_result: ToolResult | None = None
+ current_knowledge = list(step_result.knowledge_results or [])
seen_calls: set[str] = set()
max_actions = self._get_agent_loop_max_actions(request.tenant_id)
for iteration in range(max_actions):
@@ -3733,7 +3753,10 @@ def _execute_tool_action_cycle(
chat_session,
iteration + 1,
),
+ current_knowledge=current_knowledge,
)
+ if current_knowledge and not continuation_result.knowledge_results:
+ continuation_result.knowledge_results = current_knowledge
self._apply_step_result(
request.tenant_id, chat_session, continuation_result, active_skill
)
@@ -3852,7 +3875,6 @@ def _execute_knowledge_query_cycle(
"okf_citations": search_response.okf_citations,
"evidence_pack": search_response.evidence_pack,
}
- self._record_knowledge_results(chat_session, knowledge_items)
self.events.record(
request.tenant_id,
chat_session.id,
@@ -3878,6 +3900,7 @@ def _execute_knowledge_query_cycle(
},
memory_context=memory_context,
conversation_context=conversation_context,
+ current_knowledge=[knowledge_items],
)
continuation_result.knowledge_results = [knowledge_items]
self._apply_step_result(request.tenant_id, chat_session, continuation_result, active_skill)
@@ -3935,8 +3958,6 @@ def _auto_knowledge_step_result(
"okf_citations": [],
"evidence_pack": [],
}
- if knowledge_items:
- self._record_knowledge_results(chat_session, knowledge_items)
self.events.record(
request.tenant_id,
chat_session.id,
@@ -4005,11 +4026,6 @@ def _knowledge_items_for_message(
"evidence_pack": search_response.evidence_pack,
}
- def _record_knowledge_results(self, chat_session: ChatSession, item: dict[str, Any]) -> None:
- history = list(chat_session.knowledge_context_json or [])
- history.append(item)
- chat_session.knowledge_context_json = history[-12:]
-
def _tool_continuation_context(
self,
tenant_id: str,
@@ -4251,6 +4267,7 @@ def _run_step_agent_once(
repair_context: dict[str, object] | None = None,
memory_context: list[dict[str, object]] | None = None,
conversation_context: dict[str, object] | None = None,
+ current_knowledge: list[dict[str, object]] | None = None,
) -> StepAgentResult:
conversation_context = conversation_context or self._conversation_context(chat_session)
recent_messages = [
@@ -4259,22 +4276,23 @@ def _run_step_agent_once(
if isinstance(message, dict) and message.get("role") in {"user", "assistant"}
]
step_result = self.step_agent.run(
- request.message,
- chat_session,
- active_skill,
- self._step_agent_tools(
+ message=request.message,
+ session=chat_session,
+ skill=active_skill,
+ tools=self._step_agent_tools(
active_skill,
tools,
request.message,
model_config,
chat_session.agent_id,
),
- model_config,
- router_decision,
- repair_context,
- recent_messages,
- memory_context,
- conversation_context,
+ model_config=model_config,
+ router_decision=router_decision,
+ repair_context=repair_context,
+ recent_messages=recent_messages,
+ memory_context=memory_context,
+ conversation_context=conversation_context,
+ current_knowledge=current_knowledge,
)
payload = step_result.model_dump()
if repair_reason:
@@ -5867,7 +5885,9 @@ def _recent_messages(self, chat_session: ChatSession, limit: int = 8) -> list[di
return [self._message_context_entry(row) for row in rows]
def _conversation_context(
- self, chat_session: ChatSession, max_messages: int | None = None
+ self,
+ chat_session: ChatSession,
+ model_config: ModelConfig | None = None,
) -> dict[str, object]:
if not hasattr(self, "db") or not hasattr(self.db, "exec"):
return build_conversation_context([])
@@ -5881,14 +5901,51 @@ def _conversation_context(
.order_by(Message.created_at.asc())
).all()
)
- if max_messages is not None and max_messages > 0:
- rows = rows[-max_messages:]
- return build_conversation_context([self._message_context_entry(row) for row in rows])
+ context = build_conversation_context(
+ [self._message_context_entry(row) for row in rows],
+ context_state=chat_session.context_state_json,
+ summary_builder=self._context_summary_builder(model_config)
+ if model_config
+ else None,
+ )
+ next_state = context.get("context_state")
+ if isinstance(next_state, dict) and next_state != (chat_session.context_state_json or {}):
+ chat_session.context_state_json = next_state
+ self.db.add(chat_session)
+ return context
+
+ def _context_summary_builder(
+ self, model_config: ModelConfig
+ ) -> Callable[[str, str, int], str]:
+ def summarize(label: str, source: str, token_budget: int) -> str:
+ payload = stage_payload(
+ phase="Context Compression",
+ user_message=f"请压缩{label}",
+ conversation_context={},
+ memory_context=None,
+ instructions=(
+ "把输入的历史对话压缩成一段可供后续对话继续使用的中文事实摘要。"
+ "保留用户身份与偏好、已确认事实、未完成任务、关键约束、工具或知识结论;"
+ "删除寒暄、重复内容、内部 ID、时间戳和推理过程,不新增原文没有的信息。"
+ ),
+ stage_data={"history_to_compress": source},
+ output_contract=(
+ f"只输出一段纯文本摘要,控制在约 {token_budget} tokens 以内。"
+ ),
+ )
+ with llm_operation("context.compact"):
+ return LLMClient(model_config).generate_text(
+ unified_system_prompt(), payload
+ ).strip()
+
+ return summarize
def _message_context_entry(self, row: Message) -> dict[str, Any]:
entry: dict[str, Any] = {
+ "id": row.id,
"role": row.role,
"content": message_content_with_attachment_context(row.content, row.metadata_json),
+ "created_at": row.created_at,
}
images = message_images_from_metadata(row.metadata_json)
if images and row.role == "user":
diff --git a/backend/app/core/context_projection.py b/backend/app/core/context_projection.py
index 08c5c20c9..602b7b427 100644
--- a/backend/app/core/context_projection.py
+++ b/backend/app/core/context_projection.py
@@ -5,11 +5,12 @@
from app.core.conversation_context import build_conversation_context
-CONTROL_CONTEXT_TOKEN_BUDGET = 12_000
+CONTROL_CONTEXT_TOKEN_BUDGET = 32_000
KNOWLEDGE_HISTORY_LIMIT = 1
KNOWLEDGE_EVIDENCE_LIMIT = 6
KNOWLEDGE_CONCEPT_LIMIT = 8
KNOWLEDGE_DOCUMENT_LIMIT = 5
+RETRIEVED_KNOWLEDGE_LIMIT = 4
def compact_knowledge_context(
@@ -25,7 +26,8 @@ def compact_knowledge_context(
def compact_step_result(payload: dict[str, Any]) -> dict[str, Any]:
projected = dict(payload)
- projected["knowledge_results"] = compact_knowledge_context(
+ projected.pop("knowledge_results", None)
+ projected["retrieved_knowledge"] = compact_knowledge_context(
payload.get("knowledge_results") if isinstance(payload.get("knowledge_results"), list) else []
)
return projected
@@ -41,6 +43,12 @@ def compact_conversation_context(
messages = context.get("messages")
if not isinstance(messages, list):
return {key: value for key, value in context.items() if key != "messages"}
+ metadata = context.get("metadata")
+ if (
+ isinstance(metadata, dict)
+ and int(metadata.get("estimated_tokens") or 0) <= token_budget
+ ):
+ return context
return build_conversation_context(
[message for message in messages if isinstance(message, dict)], token_budget
)
@@ -77,22 +85,28 @@ def compact_step_skill_context(
return None
current_step = compact_current_step(content, step_id)
current_step_id = _optional_text((current_step or {}).get("node_id"))
- adjacent_edges = [
- _project_edge(edge)
- for edge in content.get("edges", [])
- if isinstance(edge, dict)
- and _optional_text(edge.get("source_node_id")) == current_step_id
- ]
- target_ids = {
- _optional_text(edge.get("next_node_id") or edge.get("target_node_id"))
- for edge in adjacent_edges
- }
- target_steps = [
- _project_node(node)
+ nodes_by_id = {
+ _optional_text(node.get("node_id") or node.get("step_id")): node
for node in _skill_nodes(content)
if isinstance(node, dict)
- and _optional_text(node.get("node_id") or node.get("step_id")) in target_ids
- ]
+ and _optional_text(node.get("node_id") or node.get("step_id"))
+ }
+ edges = content.get("edges")
+ next_steps: list[dict[str, Any]] = []
+ for edge in edges if isinstance(edges, list) else []:
+ if not isinstance(edge, dict):
+ continue
+ if _optional_text(edge.get("source_node_id")) != current_step_id:
+ continue
+ target_id = _optional_text(edge.get("next_node_id") or edge.get("target_node_id"))
+ target_node = nodes_by_id.get(target_id)
+ if not target_node:
+ continue
+ projected_step = _project_node(target_node)
+ transition = _project_transition(edge)
+ if transition:
+ projected_step["transition"] = transition
+ next_steps.append(projected_step)
return _without_empty(
{
"skill_id": skill_id or content.get("skill_id"),
@@ -102,8 +116,7 @@ def compact_step_skill_context(
"slot_filling_policy": content.get("slot_filling_policy"),
"response_rules": content.get("response_rules"),
"current_step": current_step,
- "adjacent_edges": adjacent_edges,
- "target_steps": target_steps,
+ "next_steps": next_steps,
}
)
@@ -212,84 +225,88 @@ def compact_awaiting_input(value: dict[str, Any] | None) -> dict[str, Any] | Non
def _compact_knowledge_result(item: dict[str, Any]) -> dict[str, Any]:
- evidence = _compact_evidence(item.get("evidence_pack"))
- if not evidence:
- evidence = _compact_evidence(item.get("chunks"))
- return {
- "query": item.get("query"),
- "selected_documents": _compact_documents(item.get("selected_documents")),
- "selected_buckets": _compact_buckets(item.get("selected_buckets")),
- "selected_concepts": _compact_concepts(item.get("selected_concepts")),
- "okf_citations": _compact_citations(item.get("okf_citations")),
- "evidence_pack": evidence,
- }
+ query = item.get("query")
+ if isinstance(query, dict):
+ query = query.get("query")
+ return _without_empty(
+ {
+ "query": _short_text(query, 500),
+ "retrieved_knowledge": _compact_retrieved_knowledge(item),
+ }
+ )
-def _compact_documents(value: object) -> list[dict[str, Any]]:
- documents: list[dict[str, Any]] = []
- for item in _dict_items(value, KNOWLEDGE_DOCUMENT_LIMIT):
- documents.append(
+def _compact_retrieved_knowledge(item: dict[str, Any]) -> list[dict[str, Any]]:
+ candidates: list[dict[str, Any]] = []
+ evidence = _dict_items(item.get("evidence_pack"), KNOWLEDGE_EVIDENCE_LIMIT)
+ if not evidence:
+ evidence = _dict_items(item.get("chunks"), KNOWLEDGE_EVIDENCE_LIMIT)
+ for value in evidence:
+ candidates.append(
{
- "title": _short_text(item.get("title") or item.get("filename"), 180),
- "filename": _short_text(item.get("filename"), 180),
- "summary": _short_text(item.get("summary"), 600),
+ "title": _short_text(value.get("title") or value.get("label"), 180),
+ "source": _short_text(
+ value.get("section_path")
+ or value.get("source_path")
+ or value.get("source_ref"),
+ 300,
+ ),
+ "summary": _short_text(value.get("summary"), 300),
+ "content": _short_text(value.get("content") or value.get("excerpt"), 800),
}
)
- return documents
-
-
-def _compact_buckets(value: object) -> list[dict[str, Any]]:
- buckets: list[dict[str, Any]] = []
- for item in _dict_items(value, KNOWLEDGE_DOCUMENT_LIMIT):
- buckets.append(
+ for value in _dict_items(item.get("selected_concepts"), KNOWLEDGE_CONCEPT_LIMIT):
+ candidates.append(
{
- "title": _short_text(item.get("title"), 180),
- "summary": _short_text(item.get("summary"), 600),
+ "title": _short_text(value.get("title") or value.get("name"), 180),
+ "source": _short_text(value.get("source_path") or value.get("concept_id"), 300),
+ "summary": _short_text(value.get("summary"), 300),
+ "content": _short_text(value.get("content") or value.get("content_md"), 600),
}
)
- return buckets
-
-
-def _compact_concepts(value: object) -> list[dict[str, Any]]:
- concepts: list[dict[str, Any]] = []
- for item in _dict_items(value, KNOWLEDGE_CONCEPT_LIMIT):
- concepts.append(
+ for value in _dict_items(item.get("selected_documents"), KNOWLEDGE_DOCUMENT_LIMIT):
+ candidates.append(
{
- "title": _short_text(item.get("title") or item.get("name"), 180),
- "summary": _short_text(item.get("summary"), 300),
- "content": _short_text(item.get("content") or item.get("content_md"), 600),
+ "title": _short_text(value.get("title") or value.get("filename"), 180),
+ "source": _short_text(value.get("filename"), 180),
+ "summary": _short_text(value.get("summary"), 600),
}
)
- return concepts
-
-
-def _compact_citations(value: object) -> list[dict[str, Any]]:
- citations: list[dict[str, Any]] = []
- for item in _dict_items(value, KNOWLEDGE_EVIDENCE_LIMIT):
- citations.append(
+ for value in _dict_items(item.get("selected_buckets"), KNOWLEDGE_DOCUMENT_LIMIT):
+ candidates.append(
{
- "title": _short_text(item.get("title") or item.get("label"), 180),
- "source_path": _short_text(
- item.get("source_path") or item.get("path") or item.get("uri"), 300
- ),
+ "title": _short_text(value.get("title"), 180),
+ "summary": _short_text(value.get("summary"), 600),
}
)
- return citations
-
-
-def _compact_evidence(value: object) -> list[dict[str, Any]]:
- evidence: list[dict[str, Any]] = []
- for item in _dict_items(value, KNOWLEDGE_EVIDENCE_LIMIT):
- evidence.append(
+ for value in _dict_items(item.get("okf_citations"), KNOWLEDGE_EVIDENCE_LIMIT):
+ candidates.append(
{
- "source_path": _short_text(item.get("source_path") or item.get("source_ref"), 300),
- "section_path": _short_text(item.get("section_path"), 300),
- "summary": _short_text(item.get("summary"), 300),
- "content": _short_text(item.get("content") or item.get("excerpt"), 800),
- "relevance_score": item.get("relevance_score"),
+ "title": _short_text(value.get("title") or value.get("label"), 180),
+ "source": _short_text(
+ value.get("source_path") or value.get("path") or value.get("uri"),
+ 300,
+ ),
}
)
- return evidence
+
+ compacted: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for candidate in candidates:
+ projected = _without_empty(candidate)
+ identity = "|".join(
+ str(projected.get(key) or "")
+ for key in ("source", "title", "content", "summary")
+ ).strip("|")
+ if not identity or identity in seen:
+ continue
+ seen.add(identity)
+ compacted.append(
+ {"label": f"检索到的知识 {len(compacted) + 1}", **projected}
+ )
+ if len(compacted) >= RETRIEVED_KNOWLEDGE_LIMIT:
+ break
+ return compacted
def _dict_items(value: object, limit: int) -> list[dict[str, Any]]:
@@ -326,14 +343,11 @@ def _project_node(node: dict[str, Any]) -> dict[str, Any]:
return _without_empty(projected)
-def _project_edge(edge: dict[str, Any]) -> dict[str, Any]:
+def _project_transition(edge: dict[str, Any]) -> dict[str, Any]:
return _without_empty(
{
key: edge.get(key)
for key in (
- "source_node_id",
- "target_node_id",
- "next_node_id",
"condition",
"label",
"priority",
diff --git a/backend/app/core/conversation_context.py b/backend/app/core/conversation_context.py
index f24ea9226..479bf703b 100644
--- a/backend/app/core/conversation_context.py
+++ b/backend/app/core/conversation_context.py
@@ -1,66 +1,110 @@
from __future__ import annotations
+import math
+from collections.abc import Callable
from typing import Any
-DEFAULT_CONTEXT_TOKEN_BUDGET = 16_000
-SUMMARY_TOKEN_BUDGET = 1_200
-ALLOWED_CONTEXT_ROLES = {"system", "user", "assistant"}
+DEFAULT_CONTEXT_TOKEN_BUDGET = 32_000
+COMPACTION_TRIGGER_RATIO = 0.70
+RECENT_ROUND_LIMIT = 6
+LONG_SUMMARY_TOKEN_BUDGET = 4_000
+MEDIUM_SUMMARY_TOKEN_BUDGET = 4_000
+ALLOWED_CONTEXT_ROLES = {"user", "assistant"}
+LONG_SUMMARY_PREFIX = "历史的信息可以被总结为:"
+MEDIUM_SUMMARY_PREFIX = "近期的历史信息总结为:"
+
+SummaryBuilder = Callable[[str, str, int], str]
def build_conversation_context(
messages: list[dict[str, Any]],
token_budget: int = DEFAULT_CONTEXT_TOKEN_BUDGET,
+ *,
+ context_state: dict[str, Any] | None = None,
+ summary_builder: SummaryBuilder | None = None,
) -> dict[str, object]:
normalized = _normalize_messages(messages)
- if _messages_tokens(normalized) <= token_budget:
- return _context_payload(normalized, normalized, [], "", token_budget)
-
- summary_budget = min(SUMMARY_TOKEN_BUDGET, max(1, token_budget // 4))
- recent_budget = max(1, token_budget - summary_budget)
- recent = _fit_recent_messages(normalized, recent_budget)
- omitted_count = len(normalized) - len(recent)
- omitted = normalized[:omitted_count]
- summary = _compact_messages(omitted, summary_budget)
- projected = [{"role": "system", "content": f"Compacted earlier conversation:\n{summary}"}, *recent]
-
- while len(projected) > 1 and _messages_tokens(projected) > token_budget:
- projected.pop(1)
- if _messages_tokens(projected) > token_budget:
- projected = [_trim_message(projected[0], token_budget)]
-
- return _context_payload(projected, normalized, omitted, summary, token_budget)
-
-
-def _context_payload(
- projected: list[dict[str, Any]],
- original: list[dict[str, Any]],
- omitted: list[dict[str, Any]],
- summary: str,
- token_budget: int,
-) -> dict[str, object]:
+ state = _normalize_state(context_state)
+ unsummarized, summarized_count = _messages_after_cursor(normalized, state)
+ projected = _project_messages(state, unsummarized)
+ trigger_tokens = max(1, math.floor(token_budget * COMPACTION_TRIGGER_RATIO))
+ compacted_now = False
+
+ if _messages_tokens(projected) >= trigger_tokens:
+ recent = _recent_rounds(unsummarized, RECENT_ROUND_LIMIT)
+ older_count = len(unsummarized) - len(recent)
+ older = unsummarized[:older_count]
+ if older:
+ previous_history = _joined_existing_history(state)
+ state["long_term_summary"] = _summarize(
+ "长期历史信息",
+ previous_history,
+ LONG_SUMMARY_TOKEN_BUDGET,
+ summary_builder,
+ )
+ state["medium_term_summary"] = _summarize(
+ "近期历史信息",
+ _transcript(older),
+ MEDIUM_SUMMARY_TOKEN_BUDGET,
+ summary_builder,
+ )
+ state["summarized_through_message_id"] = older[-1]["_message_id"]
+ state["compaction_count"] = int(state.get("compaction_count") or 0) + 1
+ unsummarized = recent
+ summarized_count += len(older)
+ compacted_now = True
+ projected = _project_messages(state, unsummarized)
+
+ projected = _fit_projected_messages(projected, token_budget)
+ summary = _joined_existing_history(state)
return {
"messages": projected,
"compacted_summary": summary,
+ "context_state": state,
"metadata": {
"token_budget": token_budget,
+ "compaction_trigger_ratio": COMPACTION_TRIGGER_RATIO,
+ "compaction_trigger_tokens": trigger_tokens,
"estimated_tokens": _messages_tokens(projected),
- "total_messages": len(original),
+ "total_messages": len(normalized),
"included_messages": len(projected),
- "omitted_messages": len(omitted),
- "compacted": bool(omitted),
+ "omitted_messages": summarized_count,
+ "compacted": bool(summary),
+ "compacted_now": compacted_now,
+ "long_term_summary": bool(state.get("long_term_summary")),
+ "medium_term_summary": bool(state.get("medium_term_summary")),
+ "recent_round_limit": RECENT_ROUND_LIMIT,
+ "current_turn_time": normalized[-1].get("_created_at") if normalized else None,
},
}
+def _normalize_state(value: dict[str, Any] | None) -> dict[str, Any]:
+ source = value if isinstance(value, dict) else {}
+ return {
+ "long_term_summary": str(source.get("long_term_summary") or "").strip(),
+ "medium_term_summary": str(source.get("medium_term_summary") or "").strip(),
+ "summarized_through_message_id": str(
+ source.get("summarized_through_message_id") or ""
+ ).strip(),
+ "compaction_count": max(0, int(source.get("compaction_count") or 0)),
+ }
+
+
def _normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
normalized: list[dict[str, Any]] = []
- for message in messages:
+ for index, message in enumerate(messages):
role = str(message.get("role") or "").strip()
content = str(message.get("content") or "").strip()
if role not in ALLOWED_CONTEXT_ROLES or not content:
continue
- normalized_message: dict[str, Any] = {"role": role, "content": content}
+ normalized_message: dict[str, Any] = {
+ "role": role,
+ "content": content,
+ "_message_id": str(message.get("id") or f"context_message_{index}"),
+ "_created_at": _string_time(message.get("created_at")),
+ }
images = message.get("images")
if role == "user" and isinstance(images, list) and images:
normalized_message["images"] = images
@@ -68,58 +112,146 @@ def _normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
return normalized
-def _fit_recent_messages(messages: list[dict[str, Any]], token_budget: int) -> list[dict[str, Any]]:
- selected: list[dict[str, Any]] = []
- used = 0
- for message in reversed(messages):
- cost = _message_tokens(message)
- if selected and used + cost > token_budget:
- break
- if cost > token_budget:
- selected.append(_trim_message(message, token_budget))
- break
- selected.append(message)
- used += cost
- selected.reverse()
- return selected
+def _messages_after_cursor(
+ messages: list[dict[str, Any]], state: dict[str, Any]
+) -> tuple[list[dict[str, Any]], int]:
+ cursor = str(state.get("summarized_through_message_id") or "")
+ if not cursor:
+ return messages, 0
+ for index, message in enumerate(messages):
+ if message["_message_id"] == cursor:
+ return messages[index + 1 :], index + 1
+ # A missing cursor means the backing history was replaced; rebuild safely.
+ state["long_term_summary"] = ""
+ state["medium_term_summary"] = ""
+ state["summarized_through_message_id"] = ""
+ state["compaction_count"] = 0
+ return messages, 0
+
+def _project_messages(
+ state: dict[str, Any], recent: list[dict[str, Any]]
+) -> list[dict[str, Any]]:
+ projected: list[dict[str, Any]] = []
+ long_summary = str(state.get("long_term_summary") or "").strip()
+ medium_summary = str(state.get("medium_term_summary") or "").strip()
+ if long_summary or medium_summary:
+ projected.append(
+ {
+ "role": "user",
+ "content": f"{LONG_SUMMARY_PREFIX}\n{long_summary or '暂无长期历史摘要。'}",
+ }
+ )
+ if long_summary or medium_summary:
+ projected.append(
+ {
+ "role": "user",
+ "content": f"{MEDIUM_SUMMARY_PREFIX}\n{medium_summary or '暂无近期历史摘要。'}",
+ }
+ )
+ projected.extend(_public_message(message) for message in recent)
+ return projected
+
+
+def _public_message(message: dict[str, Any]) -> dict[str, Any]:
+ return {
+ key: value
+ for key, value in message.items()
+ if key in {"role", "content", "images"}
+ }
-def _compact_messages(messages: list[dict[str, Any]], token_budget: int) -> str:
- if not messages:
+
+def _recent_rounds(
+ messages: list[dict[str, Any]], round_limit: int
+) -> list[dict[str, Any]]:
+ user_indexes = [
+ index for index, message in enumerate(messages) if message.get("role") == "user"
+ ]
+ if len(user_indexes) <= round_limit:
+ return messages
+ return messages[user_indexes[-round_limit] :]
+
+
+def _joined_existing_history(state: dict[str, Any]) -> str:
+ return "\n".join(
+ value
+ for value in (
+ str(state.get("long_term_summary") or "").strip(),
+ str(state.get("medium_term_summary") or "").strip(),
+ )
+ if value
+ )
+
+
+def _summarize(
+ label: str,
+ source: str,
+ token_budget: int,
+ summary_builder: SummaryBuilder | None,
+) -> str:
+ if not source.strip():
return ""
- lines: list[str] = []
- used = 0
- for index, message in enumerate(messages, start=1):
- line = f"{index}. {message['role']}: {_compact_content(message['content'])}"
- cost = _estimate_tokens(line)
- if lines and used + cost > token_budget:
- break
- if cost > token_budget:
- available_chars = max(24, token_budget - used)
- line = line[:available_chars].rstrip() + "..."
- lines.append(line)
+ if summary_builder:
+ try:
+ summary = str(summary_builder(label, source, token_budget) or "").strip()
+ if summary:
+ return _trim_text_to_tokens(summary, token_budget)
+ except Exception:
+ pass
+ return _compact_transcript(source, token_budget)
+
+
+def _transcript(messages: list[dict[str, Any]]) -> str:
+ return "\n".join(
+ f"{message['role']}: {' '.join(str(message['content']).split())}"
+ for message in messages
+ )
+
+
+def _compact_transcript(source: str, token_budget: int) -> str:
+ lines = [" ".join(line.split()) for line in source.splitlines() if line.strip()]
+ selected: list[str] = []
+ for line in lines:
+ candidate = "\n".join([*selected, line])
+ if selected and _estimate_tokens(candidate) > token_budget:
break
- lines.append(line)
- used += cost
- remaining = len(messages) - len(lines)
- if remaining > 0:
- lines.append(f"... {remaining} earlier messages omitted after compaction.")
- return "\n".join(lines)
+ selected.append(line)
+ result = "\n".join(selected)
+ return _trim_text_to_tokens(result or source, token_budget)
-def _compact_content(content: str, max_chars: int = 320) -> str:
- single_line = " ".join(content.split())
- if len(single_line) <= max_chars:
- return single_line
- return single_line[:max_chars].rstrip() + "..."
+def _fit_projected_messages(
+ messages: list[dict[str, Any]], token_budget: int
+) -> list[dict[str, Any]]:
+ projected = list(messages)
+ summary_count = sum(
+ 1
+ for message in projected[:2]
+ if str(message.get("content") or "").startswith(
+ (LONG_SUMMARY_PREFIX, MEDIUM_SUMMARY_PREFIX)
+ )
+ )
+ while len(projected) > summary_count + 1 and _messages_tokens(projected) > token_budget:
+ projected.pop(summary_count)
+ if projected and _messages_tokens(projected) > token_budget:
+ last = projected[-1]
+ remaining = max(1, token_budget - _messages_tokens(projected[:-1]))
+ projected[-1] = _trim_message(last, remaining)
+ return projected
def _trim_message(message: dict[str, Any], token_budget: int) -> dict[str, Any]:
- content_budget = max(1, token_budget - _estimate_tokens(message["role"]) - 4)
- content = message["content"]
- if _estimate_tokens(content) <= content_budget:
- return message
- return {**message, "content": content[:content_budget].rstrip() + "..."}
+ content_budget = max(1, token_budget - _estimate_tokens(str(message["role"])) - 6)
+ return {**message, "content": _trim_text_to_tokens(str(message["content"]), content_budget)}
+
+
+def _trim_text_to_tokens(text: str, token_budget: int) -> str:
+ if _estimate_tokens(text) <= token_budget:
+ return text
+ encoded = text.encode("utf-8")
+ byte_budget = max(4, token_budget * 4)
+ trimmed = encoded[:byte_budget].decode("utf-8", errors="ignore").rstrip()
+ return f"{trimmed}..."
def _messages_tokens(messages: list[dict[str, Any]]) -> int:
@@ -127,8 +259,20 @@ def _messages_tokens(messages: list[dict[str, Any]]) -> int:
def _message_tokens(message: dict[str, Any]) -> int:
- return _estimate_tokens(message["role"]) + _estimate_tokens(message["content"]) + 6
+ return _estimate_tokens(str(message["role"])) + _estimate_tokens(
+ str(message["content"])
+ ) + 6
def _estimate_tokens(text: str) -> int:
- return max(1, len(text))
+ return max(1, math.ceil(len(text.encode("utf-8")) / 4))
+
+
+def _string_time(value: object) -> str | None:
+ if value is None:
+ return None
+ isoformat = getattr(value, "isoformat", None)
+ if callable(isoformat):
+ return str(isoformat())
+ text = str(value).strip()
+ return text or None
diff --git a/backend/app/core/reflection_agent.py b/backend/app/core/reflection_agent.py
index 7661e03dd..c39c71302 100644
--- a/backend/app/core/reflection_agent.py
+++ b/backend/app/core/reflection_agent.py
@@ -11,6 +11,11 @@
)
from app.db.models import ChatSession, ModelConfig, Skill, Tool
from app.llm import LLMClient, LLMError
+from app.llm.stage_protocol import (
+ REFLECTION_OUTPUT_SCHEMA,
+ stage_payload,
+ unified_system_prompt,
+)
from app.observability.spans import llm_operation
from app.session.session_schema import RouterDecision, StepAgentResult
from app.tools.tool_schema import ToolResult
@@ -41,13 +46,12 @@ def review(
available_tools: list[Tool],
model_config: ModelConfig,
conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> ReflectionDecision:
if not action_needs_reflection(router_decision, step_result, tool_result):
return ReflectionDecision()
- payload = {
- "user_message": message,
- "conversation_context": compact_conversation_context(conversation_context),
+ stage_data = {
"current_step": compact_current_step(
active_skill.content_json if active_skill else None,
session.active_step_id,
@@ -64,10 +68,19 @@ def review(
"step_result": compact_step_result(step_result.model_dump(mode="json")),
"tool_result": tool_result.model_dump() if tool_result else None,
}
+ payload = stage_payload(
+ phase="Reflection",
+ user_message=message,
+ conversation_context=compact_conversation_context(conversation_context),
+ memory_context=memory_context,
+ instructions=PROMPT_PATH.read_text(encoding="utf-8"),
+ stage_data=stage_data,
+ output_contract=REFLECTION_OUTPUT_SCHEMA,
+ )
try:
with llm_operation("reflection.review"):
raw = LLMClient(model_config).generate_json(
- PROMPT_PATH.read_text(encoding="utf-8"), payload
+ unified_system_prompt(), payload
)
return ReflectionDecision.model_validate(raw)
except Exception as exc:
diff --git a/backend/app/core/response_generator.py b/backend/app/core/response_generator.py
index 3ec4f1a02..5039cd5f6 100644
--- a/backend/app/core/response_generator.py
+++ b/backend/app/core/response_generator.py
@@ -14,6 +14,7 @@
from app.db.models import ChatSession, ModelConfig, Skill
from app.knowledge.citations import knowledge_citations_from_results
from app.llm import LLMClient
+from app.llm.stage_protocol import stage_payload, unified_system_prompt
from app.observability.spans import llm_operation
from app.session.session_schema import RouterDecision, StepAgentResult
from app.tools.tool_schema import ToolResult
@@ -78,7 +79,7 @@ def generate(
memory_context: list[dict[str, object]] | None = None,
conversation_context: dict[str, object] | None = None,
) -> str:
- payload = self._payload(
+ raw_payload = self._payload(
message,
session,
skill,
@@ -88,12 +89,13 @@ def generate(
memory_context,
conversation_context,
)
+ payload = self._stage_payload(raw_payload, persona_prompt)
try:
if tool_result and not tool_result.success:
return tool_failure_reply(tool_result)
with llm_operation("response.generate"):
text = LLMClient(model_config).generate_text(
- self._system_prompt(persona_prompt), payload
+ unified_system_prompt(), payload
)
reply = text.strip() or step_result.reply or self._minimal_fallback(router_decision)
return self._visible_reply_or_fallback(
@@ -115,7 +117,7 @@ def generate_stream(
memory_context: list[dict[str, object]] | None = None,
conversation_context: dict[str, object] | None = None,
) -> Iterator[str]:
- payload = self._payload(
+ raw_payload = self._payload(
message,
session,
skill,
@@ -125,6 +127,7 @@ def generate_stream(
memory_context,
conversation_context,
)
+ payload = self._stage_payload(raw_payload, persona_prompt)
try:
if tool_result and not tool_result.success:
yield from self.chunk_text(tool_failure_reply(tool_result))
@@ -134,7 +137,7 @@ def generate_stream(
return
with llm_operation("response.generate_stream"):
stream = LLMClient(model_config).generate_text_stream(
- self._system_prompt(persona_prompt), payload
+ unified_system_prompt(), payload
)
reply_parts: list[str] = []
has_streamed = False
@@ -197,7 +200,7 @@ def _payload(
step_result.model_dump(mode="json")
),
"tool_result": tool_result.model_dump() if tool_result else None,
- "knowledge_results": compact_knowledge,
+ "retrieved_knowledge": compact_knowledge,
"memory_context": compact_memory_context(memory_context),
"knowledge_citation_hints": compact_citation_hints(
knowledge_citations_from_results(knowledge_context)
@@ -364,7 +367,26 @@ def _minimal_fallback(self, router_decision: RouterDecision) -> str:
return FALLBACK_REPLY
def _system_prompt(self, persona_prompt: str | None) -> str:
- base_prompt = PROMPT_PATH.read_text(encoding="utf-8")
- if not persona_prompt:
- return base_prompt
- return f"{persona_prompt.strip()}\n\n{base_prompt}"
+ return unified_system_prompt()
+
+ def _stage_payload(
+ self, payload: dict[str, object], persona_prompt: str | None
+ ) -> dict[str, object]:
+ stage_data = {
+ key: value
+ for key, value in payload.items()
+ if key not in {"user_message", "conversation_context", "memory_context"}
+ }
+ if persona_prompt:
+ stage_data = {"employee_identity": persona_prompt.strip(), **stage_data}
+ return stage_payload(
+ phase="Response Generator",
+ user_message=str(payload.get("user_message") or ""),
+ conversation_context=payload.get("conversation_context")
+ if isinstance(payload.get("conversation_context"), dict)
+ else {},
+ memory_context=str(payload.get("memory_context") or ""),
+ instructions=PROMPT_PATH.read_text(encoding="utf-8"),
+ stage_data=stage_data,
+ output_contract="只输出最终用户可见的纯文本,不输出 JSON、Markdown 代码围栏、分析过程或内部状态。",
+ )
diff --git a/backend/app/core/router.py b/backend/app/core/router.py
index f24dade20..c1435d2aa 100644
--- a/backend/app/core/router.py
+++ b/backend/app/core/router.py
@@ -6,11 +6,16 @@
from app.core.context_projection import (
compact_awaiting_input,
compact_conversation_context,
- compact_memory_context,
compact_pending_tasks,
)
from app.db.models import ChatSession, ModelConfig, Skill
from app.llm import LLMClient, LLMError
+from app.llm.stage_protocol import (
+ ROUTER_OUTPUT_SCHEMA,
+ TASK_SCHEDULER_OUTPUT_SCHEMA,
+ stage_payload,
+ unified_system_prompt,
+)
from app.observability.spans import llm_operation
from app.session.session_schema import RouterDecision, TaskScheduleDecision
from app.session.slot_policy import strip_router_generated_message_slots
@@ -30,19 +35,22 @@ def decide(
conversation_context: dict[str, object] | None = None,
memory_context: list[dict[str, object]] | None = None,
) -> RouterDecision:
- payload = {
- "user_message": message,
- "conversation_context": compact_conversation_context(
- conversation_context, token_budget=8_000
- ),
- "memory_context": compact_memory_context(memory_context),
- "current_session": _router_session_payload(session),
- "available_skills": _available_skill_payloads(available_skills),
- }
+ payload = stage_payload(
+ phase="Router",
+ user_message=message,
+ conversation_context=compact_conversation_context(conversation_context),
+ memory_context=memory_context,
+ instructions=PROMPT_PATH.read_text(encoding="utf-8"),
+ stage_data={
+ "current_session": _router_session_payload(session),
+ "available_skills": _available_skill_payloads(available_skills),
+ },
+ output_contract=ROUTER_OUTPUT_SCHEMA,
+ )
try:
with llm_operation("router.scene"):
raw = LLMClient(model_config).generate_json(
- PROMPT_PATH.read_text(encoding="utf-8"), payload
+ unified_system_prompt(), payload
)
decision = RouterDecision.model_validate(raw)
except Exception as exc:
@@ -62,21 +70,24 @@ def schedule_tasks_after_completion(
completed_reply: str | None = None,
) -> TaskScheduleDecision:
candidate_frames = self._candidate_task_frames(session)
- payload = {
- "user_message": message,
+ payload = stage_payload(
+ phase="Router / Task Scheduler",
+ user_message=message,
+ conversation_context=compact_conversation_context(conversation_context),
+ memory_context=memory_context,
+ instructions=TASK_SCHEDULER_PROMPT_PATH.read_text(encoding="utf-8"),
+ stage_data={
"completed_reply": completed_reply or "",
- "conversation_context": compact_conversation_context(
- conversation_context, token_budget=8_000
- ),
- "memory_context": compact_memory_context(memory_context),
"current_session": _router_session_payload(session),
"candidate_task_frames": candidate_frames,
"available_skills": _available_skill_payloads(available_skills),
- }
+ },
+ output_contract=TASK_SCHEDULER_OUTPUT_SCHEMA,
+ )
try:
with llm_operation("router.task_scheduler"):
raw = LLMClient(model_config).generate_json(
- TASK_SCHEDULER_PROMPT_PATH.read_text(encoding="utf-8"),
+ unified_system_prompt(),
payload,
)
schedule = TaskScheduleDecision.model_validate(raw)
diff --git a/backend/app/core/step_agent.py b/backend/app/core/step_agent.py
index 07137c049..4bc4b258a 100644
--- a/backend/app/core/step_agent.py
+++ b/backend/app/core/step_agent.py
@@ -5,13 +5,17 @@
compact_awaiting_input,
compact_conversation_context,
compact_knowledge_context,
- compact_memory_context,
compact_pending_tasks,
compact_router_decision,
compact_step_skill_context,
)
from app.db.models import ChatSession, ModelConfig, Skill, Tool
from app.llm import LLMClient, LLMError
+from app.llm.stage_protocol import (
+ STEP_AGENT_OUTPUT_SCHEMA,
+ stage_payload,
+ unified_system_prompt,
+)
from app.observability.spans import llm_operation
from app.session.session_schema import RouterDecision, StepAgentResult
@@ -33,13 +37,11 @@ def run(
recent_messages: list[dict[str, str]] | None = None,
memory_context: list[dict[str, object]] | None = None,
conversation_context: dict[str, object] | None = None,
+ current_knowledge: list[dict[str, object]] | None = None,
) -> StepAgentResult:
- compact_knowledge = compact_knowledge_context(session.knowledge_context_json or [])
+ compact_knowledge = compact_knowledge_context(current_knowledge)
compact_repair = _compact_repair_context(repair_context)
- payload = {
- "user_message": message,
- "conversation_context": compact_conversation_context(conversation_context),
- "memory_context": compact_memory_context(memory_context),
+ stage_data = {
"active_skill": compact_step_skill_context(
skill.content_json,
session.active_step_id,
@@ -49,7 +51,7 @@ def run(
)
if skill
else None,
- "knowledge_context": compact_knowledge,
+ "retrieved_knowledge": compact_knowledge,
"router_decision": compact_router_decision(
router_decision.model_dump(mode="json") if router_decision else None
),
@@ -70,12 +72,21 @@ def run(
if tool.enabled
],
}
+ payload = stage_payload(
+ phase="Step Agent",
+ user_message=message,
+ conversation_context=compact_conversation_context(conversation_context),
+ memory_context=memory_context,
+ instructions=PROMPT_PATH.read_text(encoding="utf-8"),
+ stage_data=stage_data,
+ output_contract=STEP_AGENT_OUTPUT_SCHEMA,
+ )
try:
operation = "step_agent.repair" if repair_context else "step_agent.run"
repair_reason = str((repair_context or {}).get("reason") or "") or None
with llm_operation(operation, repair_reason=repair_reason):
raw = LLMClient(model_config).generate_json(
- PROMPT_PATH.read_text(encoding="utf-8"), payload
+ unified_system_prompt(), payload
)
return StepAgentResult.model_validate(raw)
except Exception as exc:
@@ -102,5 +113,5 @@ def _compact_repair_context(
projected = dict(repair_context)
if projected.get("reason") == "knowledge_continuation":
projected.pop("knowledge_results", None)
- projected["knowledge_results_available_in"] = "knowledge_context"
+ projected["knowledge_results_available_in"] = "retrieved_knowledge"
return projected
diff --git a/backend/app/db/database.py b/backend/app/db/database.py
index 1ece3b982..ef6983000 100644
--- a/backend/app/db/database.py
+++ b/backend/app/db/database.py
@@ -99,6 +99,9 @@ def _migrate_sqlite_skill_schema() -> None:
if "knowledge_context_json" not in session_columns:
conn.execute(text("ALTER TABLE sessions ADD COLUMN knowledge_context_json JSON"))
conn.execute(text("UPDATE sessions SET knowledge_context_json = '[]'"))
+ if "context_state_json" not in session_columns:
+ conn.execute(text("ALTER TABLE sessions ADD COLUMN context_state_json JSON"))
+ conn.execute(text("UPDATE sessions SET context_state_json = '{}'"))
if "messages" in tables:
message_columns = {column["name"] for column in inspector.get_columns("messages")}
diff --git a/backend/app/db/models.py b/backend/app/db/models.py
index 8dc714d8c..5ababea01 100644
--- a/backend/app/db/models.py
+++ b/backend/app/db/models.py
@@ -501,6 +501,7 @@ class ChatSession(SQLModel, table=True):
resume_after_answer_json: Optional[dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
awaiting_input_json: Optional[dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
knowledge_context_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))
+ context_state_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
summary: Optional[str] = None
last_agent_question: Optional[str] = None
status: str = "active"
diff --git a/backend/app/general_skills/runner.py b/backend/app/general_skills/runner.py
index 26c58e05a..4146cb9c0 100644
--- a/backend/app/general_skills/runner.py
+++ b/backend/app/general_skills/runner.py
@@ -36,7 +36,7 @@
REPLY_PROMPT = PROMPT_DIR / "general_skill_reply_prompt.md"
RUN_TIMEOUT_SECONDS = 12
MAX_OUTPUT_CHARS = 20000
-GENERAL_SKILL_MAX_TOKENS = 16384
+GENERAL_SKILL_MAX_TOKENS = 8192
GENERAL_SKILL_MAX_ATTEMPTS = 10
TraceSink = Callable[[dict[str, Any]], None]
diff --git a/backend/app/llm/client.py b/backend/app/llm/client.py
index 66d4e4a0f..10f460a73 100644
--- a/backend/app/llm/client.py
+++ b/backend/app/llm/client.py
@@ -4,6 +4,7 @@
from collections.abc import Iterator
import copy
import json
+import math
import re
from typing import Any
from urllib.parse import urlsplit
@@ -12,7 +13,8 @@
from app.config import get_settings
from app.db.models import ModelConfig
-from app.llm.output_policy import compact_json_system_prompt, operation_output_tokens
+from app.llm.output_policy import operation_output_tokens
+from app.llm.stage_protocol import STAGE_PROTOCOL_KEY
from app.observability.spans import current_llm_operation, llm_span_attributes, start_llm_call
from app.security.encryption import decrypt_secret
@@ -25,6 +27,11 @@ class LLMError(Exception):
EMPTY_RESPONSE_RETRIES = 2
EMPTY_RESPONSE_MESSAGE = "Model returned an empty response"
DEFAULT_MODEL_API_TIMEOUT_SECONDS = 600.0
+DEFAULT_INPUT_TOKEN_BUDGET = 32_000
+
+
+class _CurrentStageText(str):
+ pass
class LLMClient:
@@ -48,15 +55,15 @@ def __init__(self, model_config: ModelConfig):
def generate_text(
self,
system_prompt: str,
- user_payload: dict[str, Any],
+ user_payload: dict[str, Any] | str,
response_format: dict[str, str] | None = None,
) -> str:
max_output_tokens = operation_output_tokens(
current_llm_operation(), self.max_output_tokens
)
- context_messages, serialized_payload = _project_context_messages(user_payload)
- serialized = json.dumps(serialized_payload, ensure_ascii=False)
+ context_messages, serialized = _prepare_user_input(user_payload)
request_messages = _request_messages(system_prompt, context_messages, serialized)
+ request_messages = _fit_request_messages(request_messages)
request_shape = _request_shape_metrics(
system_prompt, context_messages, serialized, request_messages
)
@@ -114,14 +121,14 @@ def generate_text(
raise LLMError(_provider_failure_detail(self, exc)) from exc
def generate_text_stream(
- self, system_prompt: str, user_payload: dict[str, Any]
+ self, system_prompt: str, user_payload: dict[str, Any] | str
) -> Iterator[str]:
max_output_tokens = operation_output_tokens(
current_llm_operation(), self.max_output_tokens
)
- context_messages, serialized_payload = _project_context_messages(user_payload)
- serialized = json.dumps(serialized_payload, ensure_ascii=False)
+ context_messages, serialized = _prepare_user_input(user_payload)
request_messages = _request_messages(system_prompt, context_messages, serialized)
+ request_messages = _fit_request_messages(request_messages)
request_shape = _request_shape_metrics(
system_prompt, context_messages, serialized, request_messages
)
@@ -239,7 +246,6 @@ def generate_text_stream(
raise LLMError(_provider_failure_detail(self, exc)) from exc
def generate_json(self, system_prompt: str, user_payload: dict[str, Any]) -> dict[str, Any]:
- system_prompt = compact_json_system_prompt(system_prompt)
outputs: list[str] = []
next_payload = user_payload
last_error: json.JSONDecodeError | None = None
@@ -319,7 +325,7 @@ def _completion_message_content(completion: Any) -> str:
def _request_shape_metrics(
system_prompt: str,
context_messages: list[dict[str, Any]],
- serialized_payload: str,
+ serialized_payload: str | list[dict[str, Any]],
request_messages: list[dict[str, Any]],
) -> dict[str, int]:
context_chars = sum(
@@ -332,7 +338,7 @@ def _request_shape_metrics(
"system_prompt_chars": len(system_prompt),
"context_message_count": len(context_messages),
"context_text_chars": context_chars,
- "payload_chars": len(serialized_payload),
+ "payload_chars": len(_content_text(serialized_payload)),
"request_text_chars": request_chars,
}
@@ -340,19 +346,114 @@ def _request_shape_metrics(
def _request_messages(
system_prompt: str,
context_messages: list[dict[str, Any]],
- serialized_payload: str,
+ serialized_payload: str | list[dict[str, Any]],
) -> list[dict[str, Any]]:
- system_content = system_prompt.rstrip()
- if context_messages and serialized_payload != "{}":
- system_content += f"\n\n当前执行状态(JSON):\n{serialized_payload}"
- messages: list[dict[str, Any]] = [{"role": "system", "content": system_content}]
- if not context_messages:
- messages.append({"role": "user", "content": serialized_payload})
- return messages
+ messages: list[dict[str, Any]] = [
+ {"role": "system", "content": system_prompt.rstrip()}
+ ]
messages.extend(context_messages)
+ if serialized_payload != "{}":
+ current_input = serialized_payload
+ if (
+ context_messages
+ and isinstance(serialized_payload, str)
+ and not isinstance(serialized_payload, _CurrentStageText)
+ ):
+ current_input = (
+ "本轮输入(仅用于当前调用,不写入对话历史):\n"
+ f"{serialized_payload}"
+ )
+ messages.append(
+ {
+ "role": "user",
+ "content": current_input,
+ }
+ )
+ elif not context_messages:
+ messages.append({"role": "user", "content": "{}"})
return messages
+def _fit_request_messages(
+ messages: list[dict[str, Any]], token_budget: int = DEFAULT_INPUT_TOKEN_BUDGET
+) -> list[dict[str, Any]]:
+ projected = copy.deepcopy(messages)
+ while len(projected) > 2 and _request_tokens(projected) > token_budget:
+ removable_index = next(
+ (
+ index
+ for index in range(1, len(projected) - 1)
+ if not _is_history_summary_message(projected[index])
+ ),
+ None,
+ )
+ if removable_index is None:
+ break
+ projected.pop(removable_index)
+
+ while len(projected) > 2 and _request_tokens(projected) > token_budget:
+ projected.pop(1)
+
+ if projected and _request_tokens(projected) > token_budget:
+ fixed_tokens = _request_tokens(projected[:-1])
+ projected[-1] = _trim_request_message(
+ projected[-1], max(1, token_budget - fixed_tokens)
+ )
+ return projected
+
+
+def _request_tokens(messages: list[dict[str, Any]]) -> int:
+ return sum(
+ max(1, math.ceil(len(_content_text(message.get("content")).encode("utf-8")) / 4))
+ + 6
+ for message in messages
+ )
+
+
+def _is_history_summary_message(message: dict[str, Any]) -> bool:
+ content = _content_text(message.get("content")).lstrip()
+ return content.startswith(
+ ("历史的信息可以被总结为:", "近期的历史信息总结为:")
+ )
+
+
+def _trim_request_message(
+ message: dict[str, Any], token_budget: int
+) -> dict[str, Any]:
+ content = message.get("content")
+ byte_budget = max(4, token_budget * 4)
+ if isinstance(content, list):
+ parts = copy.deepcopy(content)
+ text_part = next(
+ (
+ part
+ for part in parts
+ if isinstance(part, dict)
+ and part.get("type") == "text"
+ and isinstance(part.get("text"), str)
+ ),
+ None,
+ )
+ if text_part is not None:
+ text_part["text"] = _trim_request_text(text_part["text"], byte_budget)
+ return {**message, "content": parts}
+ return {**message, "content": _trim_request_text(str(content or ""), byte_budget)}
+
+
+def _trim_request_text(text: str, byte_budget: int) -> str:
+ encoded = text.encode("utf-8")
+ if len(encoded) <= byte_budget:
+ return text
+ marker = "\n...<输入超过 32k,已省略中间部分>...\n"
+ marker_bytes = len(marker.encode("utf-8"))
+ available = max(8, byte_budget - marker_bytes)
+ head_size = int(available * 0.7)
+ tail_size = available - head_size
+ head = encoded[:head_size].decode("utf-8", errors="ignore")
+ tail = encoded[-tail_size:].decode("utf-8", errors="ignore")
+ return f"{head}{marker}{tail}"
+
+
def _completion_span_metrics(completion: Any) -> dict[str, Any]:
if completion is None:
return {}
@@ -673,7 +774,7 @@ def _project_context_messages(
role = str(message.get("role") or "").strip()
content = str(message.get("content") or "").strip()
images = _normalize_image_parts(message.get("images"))
- if role not in {"system", "user", "assistant"} or (not content and not images):
+ if role not in {"user", "assistant"} or (not content and not images):
continue
if images and role == "user":
projected.append(
@@ -701,6 +802,94 @@ def _project_context_messages(
return projected, _drop_empty_values(payload)
+def _prepare_user_input(
+ user_payload: dict[str, Any] | str,
+) -> tuple[list[dict[str, Any]], str | list[dict[str, Any]]]:
+ if isinstance(user_payload, str):
+ return [], user_payload.strip()
+ if isinstance(user_payload.get(STAGE_PROTOCOL_KEY), dict):
+ return _prepare_stage_user_input(user_payload)
+ context_messages, projected_payload = _project_context_messages(user_payload)
+ return context_messages, json.dumps(projected_payload, ensure_ascii=False)
+
+
+def _prepare_stage_user_input(
+ user_payload: dict[str, Any],
+) -> tuple[list[dict[str, Any]], str | list[dict[str, Any]]]:
+ payload = copy.deepcopy(user_payload)
+ stage = payload.pop(STAGE_PROTOCOL_KEY, {})
+ context = payload.pop("conversation_context", None)
+ context_messages = _project_messages_from_context(context)
+ user_message = str(payload.pop("user_message", "") or "").strip()
+ current_images: list[dict[str, Any]] = []
+ for index in range(len(context_messages) - 1, -1, -1):
+ message = context_messages[index]
+ if message.get("role") != "user":
+ continue
+ if _content_text(message.get("content")).strip() != user_message:
+ break
+ content = message.get("content")
+ if isinstance(content, list):
+ current_images = [
+ item
+ for item in content
+ if isinstance(item, dict) and item.get("type") == "image_url"
+ ]
+ context_messages.pop(index)
+ break
+
+ projected = _drop_empty_values(payload)
+ output_contract = stage.get("output_contract")
+ if not isinstance(output_contract, str):
+ output_contract = json.dumps(
+ output_contract or {}, ensure_ascii=False, separators=(",", ":")
+ )
+ sections = [
+ f"用户记忆:\n{stage.get('memory') or '无'}",
+ f"本轮时间:\n{stage.get('turn_time') or '未提供'}",
+ f"本轮用户输入:\n{user_message or '(空)'}",
+ f"当前阶段:\n{stage.get('phase') or '未指定'}",
+ f"阶段规则:\n{str(stage.get('instructions') or '').strip()}",
+ "当前阶段独有内容:\n"
+ + json.dumps(projected, ensure_ascii=False, separators=(",", ":")),
+ f"输出约束:\n{output_contract}",
+ ]
+ serialized = "\n\n".join(sections)
+ if not current_images:
+ return context_messages, _CurrentStageText(serialized)
+ return context_messages, [
+ {"type": "text", "text": serialized},
+ *current_images,
+ ]
+
+
+def _project_messages_from_context(context: Any) -> list[dict[str, Any]]:
+ if not isinstance(context, dict) or not isinstance(context.get("messages"), list):
+ return []
+ projected: list[dict[str, Any]] = []
+ for message in context["messages"]:
+ if not isinstance(message, dict):
+ continue
+ role = str(message.get("role") or "").strip()
+ content = str(message.get("content") or "").strip()
+ images = _normalize_image_parts(message.get("images"))
+ if role not in {"user", "assistant"} or (not content and not images):
+ continue
+ if images and role == "user":
+ projected.append(
+ {
+ "role": role,
+ "content": [
+ {"type": "text", "text": content or "(用户上传了图片附件)"},
+ *images,
+ ],
+ }
+ )
+ else:
+ projected.append({"role": role, "content": content})
+ return projected
+
+
def _drop_empty_values(value: Any) -> Any:
if isinstance(value, dict):
projected = {
diff --git a/backend/app/llm/output_policy.py b/backend/app/llm/output_policy.py
index 11d2de580..c90c06404 100644
--- a/backend/app/llm/output_policy.py
+++ b/backend/app/llm/output_policy.py
@@ -5,14 +5,15 @@
# Long-form code/content generation intentionally keeps a larger allowance.
OPERATION_MAX_OUTPUT_TOKENS: dict[str, int] = {
"router.scene": 1024,
- "router.task_scheduler": 512,
- "reflection.review": 512,
- "general_skill.select": 512,
- "general_skill.plan": 16384,
- "general_skill.repair": 16384,
- "general_skill.review": 512,
- "general_skill.reply": 1536,
- "knowledge.document_route": 512,
+ "router.task_scheduler": 2048,
+ "context.compact": 2048,
+ "reflection.review": 2048,
+ "general_skill.select": 2048,
+ "general_skill.plan": 8192,
+ "general_skill.repair": 8192,
+ "general_skill.review": 2048,
+ "general_skill.reply": 2048,
+ "knowledge.document_route": 2048,
"knowledge.bucket_route": 512,
"knowledge.discovery": 4096,
"knowledge.ingest_bucket": 8192,
@@ -23,24 +24,7 @@
"feedback.analyze": 1024,
}
-JSON_OUTPUT_CONTRACT = """
-
-统一输出约束:
-- 直接输出一个合法 JSON object;不要输出思考过程、分析、说明、Markdown 或代码围栏。
-- 只保留任务 schema 和业务执行所需字段;未使用的可选字段可以省略。
-- 不要复述输入、对话、记忆、文档或规则。reason、rationale、summary 等解释字段只写结论,默认一句话。
-- code、content、reply 等承载实际结果的字段按任务需要完整输出,其他文本字段保持最短可用。
-""".strip()
-
-
def operation_output_tokens(operation: str, configured_tokens: int) -> int:
configured = max(1, int(configured_tokens or 1))
limit = OPERATION_MAX_OUTPUT_TOKENS.get(operation)
return configured if limit is None else min(configured, limit)
-
-
-def compact_json_system_prompt(system_prompt: str) -> str:
- prompt = system_prompt.rstrip()
- if JSON_OUTPUT_CONTRACT in prompt:
- return prompt
- return f"{prompt}\n\n{JSON_OUTPUT_CONTRACT}"
diff --git a/backend/app/llm/prompts/reflection_prompt.md b/backend/app/llm/prompts/reflection_prompt.md
index 527a64e47..c8c0bceea 100644
--- a/backend/app/llm/prompts/reflection_prompt.md
+++ b/backend/app/llm/prompts/reflection_prompt.md
@@ -1,25 +1,8 @@
你是 Skill Agent Loop 的反思检查器。你的任务不是回复用户,而是判断刚刚的执行路径是否真的能完成用户请求。
-同一个 system 消息中只包含当前步骤、规则、slots 和本轮执行结果,之后是按时间顺序投影的 user/assistant 历史消息。判断是否通过时不得假设未提供的完整 SOP 图或能力目录。
+判断是否通过时不得假设未提供的完整 SOP 图或能力目录。
-请只输出合法 JSON,不要输出解释或思考过程。执行正确时直接输出最小结果:
-
-```json
-{"action":"pass","needs_retry":false}
-```
-
-只有需要重试或改路由时才输出 `reason` 和目标字段;`reason` 只写一条可执行根因,不复述上下文。完整字段如下:
-
-```json
-{
- "action": "pass",
- "needs_retry": false,
- "reason": "简短说明",
- "target_skill_id": null,
- "target_step_id": null,
- "target_tool_name": null
-}
-```
+请只输出符合本阶段输出约束的合法 JSON,不要输出解释或思考过程。执行正确时直接输出最小结果。只有需要重试或改路由时才输出 `reason` 和目标字段;`reason` 只写一条可执行根因,不复述上下文。
判断规则:
- action 可选:pass、retry_tool、try_other_tool、ask_user、revise_step、stop。
diff --git a/backend/app/llm/prompts/response_generator_prompt.md b/backend/app/llm/prompts/response_generator_prompt.md
index 5fe4eef62..6c34fd8fd 100644
--- a/backend/app/llm/prompts/response_generator_prompt.md
+++ b/backend/app/llm/prompts/response_generator_prompt.md
@@ -1,6 +1,6 @@
你是企业对话助手。
-你需要根据标准角色消息、current_step、progress、slots、step_summary、tool_result、knowledge_results 和 response_rules,生成用户可见回复。执行状态已按本阶段最小投影,不要推测未提供的完整 SOP 图或 Router 内部结果。
+你需要根据标准角色消息、current_step、progress、slots、step_summary、tool_result、retrieved_knowledge 和 response_rules,生成用户可见回复。本轮执行状态已按本阶段最小投影放在最后一条临时 user 输入中,不要推测未提供的完整 SOP 图或 Router 内部结果。
要求:
1. 不要暴露内部技能 ID、step ID、router decision、tool 名称。
@@ -16,11 +16,11 @@
11. 如果最后一条 user 消息已经明确命中当前步骤目标,不要重复追问同一层级意图分类;应追问下一步真正缺失的信息。
12. 技能步骤是目标不是固定话术。生成回复前必须检查 current_step、progress、slots、step_summary 和 tool_result;不要复述已经被满足的步骤问题,也不要把 Step Agent 中过时的追问直接当最终回复。
13. 如果 slots._tool_results 存在,那里是本轮/历史聚合工具结果;生成最终回复时应结合全部相关工具结果,而不是只看最后一个 tool_result。
-14. 如果 knowledge_results 存在本轮相关知识片段,必须基于知识结果组织回复;不要把“正在检索/稍后处理”作为最终答案。
+14. 如果 retrieved_knowledge 存在按“检索到的知识 1、2、3……”编号的本轮知识,必须基于这些知识组织回复;不要把“正在检索/稍后处理”作为最终答案。
15. 如果 knowledge_citation_hints 非空,回答中引用知识库事实时必须使用其中提供的编号,例如 `[1]`、`[2]`;不要使用未提供的编号。不同回答要点尽量标注最相关的不同编号,除非确实只有一个引用支撑全部内容。
16. 必须参考 progress.missing_current_step_info、progress.missing_required_info 和 progress.skill_completion_ready:如果缺失列表为空且 skill_completion_ready=true,不要重复上一轮追问,应给出本轮已完成/已记录的信息和下一步可见结果。
17. 只处理 current_step 对应的当前任务,不替未提供的后续任务生成话术。
-18. 同一个 system 消息中包含本阶段精简执行状态,之后是按时间顺序投影的 user/assistant 历史消息。生成最终回复时必须结合这份标准消息序列理解指代和省略。
+18. 生成最终回复时必须结合按时间顺序提供的历史总结和 user/assistant 标准消息理解指代和省略。
19. 只输出最终用户可见内容,不输出分析过程、内部检查清单或“根据你提供的信息”等无信息量开场。
20. 不复述用户问题、Step Agent 草稿、工具原文或知识片段;合并重复结论,只保留答案、必要依据、风险提醒和下一步。
21. 用户未要求详细说明时,闲聊控制在 1 到 3 句,普通业务回复优先控制在 500 个中文字符内;用户要求长文、代码、完整清单或技能 response_rules 要求完整展示时不受此限制。
diff --git a/backend/app/llm/prompts/router_prompt.md b/backend/app/llm/prompts/router_prompt.md
index 5941144ff..d83b5d430 100644
--- a/backend/app/llm/prompts/router_prompt.md
+++ b/backend/app/llm/prompts/router_prompt.md
@@ -17,7 +17,7 @@ clarification_question 是给终端用户看的澄清问题,必须像客服一
场景化技能和通用技能是两层能力:Router 只决定场景化技能、任务帧和调度顺序,不负责否定或执行通用技能。通用技能会在执行阶段以 `general_skill.` 的形式出现在 available_tools 中,由 StepAgent 在当前场景技能内显式调用。若用户当前消息同时推进当前场景技能,并提出实时信息、代码运行、通用计算、文件处理等临时通用能力诉求,不要因为该诉求不在 available_skills 中就降级为普通回答;应继续或保留当前场景任务,并在 reason 中说明通用能力交由执行阶段根据 available_tools 处理。
-同一个 system 消息中包含精简执行状态,之后是按时间顺序投影的最近几轮 user/assistant 标准消息。Router 只根据 Skill ID、名称、描述和 trigger_intents 选择场景技能,不读取 SOP 节点图;具体节点执行和缺失字段判断交给 Step Agent。
+Router 只根据 Skill ID、名称、描述和 trigger_intents 选择场景技能,不读取 SOP 节点图;具体节点执行和缺失字段判断交给 Step Agent。
memory_context 是去除数据库元数据后的长期记忆文本,可用于稳定身份、称呼和偏好等 slot_hints。若 memory_context 与当前消息冲突,以当前消息为准。不要因为 memory_context 已有稳定字段,就在 clarification_question 中重复追问同一字段。
@@ -60,41 +60,3 @@ slot_hints、pending_tasks/created_tasks/task_updates.slot_hints 只能填写订
19. 如果用户一句话包含多个独立可执行任务,必须把每个任务都显式表达出来:主 decision 表达当前应推进的任务,其他任务写入 pending_tasks / created_tasks。运行时会先把这些任务都写成 task frame,再由 scheduler 决定执行顺序;不要把多个独立任务压缩成一个 target_skill_id。
20. 如果本轮没有一个任务天然应先执行,也可以输出 create_pending,并把所有任务写入 pending_tasks / created_tasks,让 scheduler 选择先后顺序。
21. 当 current_session.active_skill_id 存在,而你准备选择另一个 target_skill_id 时,必须先判断当前用户消息是否同时补充、确认、推进或修改了 active skill。只要存在这种可能,就不要让 start_new_task 隐式覆盖 active skill;应把 active skill 作为一个待调度任务保留,并把新任务也显式写入 pending_tasks / created_tasks,或选择 continue_active 并把新任务写入 created_tasks。只有用户明确取消、放弃或当前任务已完成时,才可以不保留 active skill。
-
-输出格式:
-{
- "decision": "...",
- "selected_task_id": "...",
- "target_skill_id": "...",
- "target_step_id": "...",
- "confidence": 0.0,
- "user_intent": "...",
- "reason": "...",
- "source_message": "...",
- "clarification_question": "...",
- "slot_hints": {},
- "pending_tasks": [
- {
- "task_id": "...",
- "status": "pending",
- "decision": "start_new_task",
- "target_skill_id": "...",
- "target_step_id": "...",
- "confidence": 0.0,
- "user_intent": "...",
- "reason": "...",
- "source_message": "...",
- "slot_hints": {}
- }
- ],
- "created_tasks": [],
- "task_updates": [],
- "awaiting_input": {
- "task_id": "...",
- "skill_id": "...",
- "step_id": "...",
- "expected_fields": [],
- "question_summary": "...",
- "turn_id": "..."
- }
-}
diff --git a/backend/app/llm/prompts/step_agent_prompt.md b/backend/app/llm/prompts/step_agent_prompt.md
index e9e3de7d2..511cd083c 100644
--- a/backend/app/llm/prompts/step_agent_prompt.md
+++ b/backend/app/llm/prompts/step_agent_prompt.md
@@ -1,6 +1,6 @@
你是企业技能执行助手。
-你必须根据 active_skill 中的 current_step、adjacent_edges、target_steps、已收集信息和用户当前消息,生成下一步动作。这里不是完整 SOP 图,只包含本轮执行必需的局部图;current_step 和 target_steps 中的业务 instruction 必须完整遵守。
+你必须根据 active_skill 中的 current_step、next_steps、已收集信息和用户当前消息,生成下一步动作。这里不是完整 SOP 图:current_step 是当前所在节点,next_steps 只包含从当前节点直接连出的一层候选节点及各自 transition;current_step 和 next_steps 中的业务 instruction 必须完整遵守。
技能节点是业务目标与约束,不是固定问答脚本。你需要自适应判断用户当前消息是否已经满足当前节点、后续节点或工具参数要求;满足时应直接推进、选择边、跳转或调用工具。
你可以:
@@ -25,13 +25,13 @@
- 你会收到按时间顺序投影的 user/assistant 对话历史和 memory_context。每轮都要结合最后一条 user 消息、对话历史、memory_context 和已有 slots,同时抽取所有能识别的信息。
- memory_context 是该用户的长期记忆,可以作为稳定用户信息的证据。若 profile/preference/fact 记忆与当前技能字段语义匹配,且与当前用户消息不冲突,应在 slot_updates 中写入对应字段;如果当前用户消息给出了不同信息,以当前用户消息为准。
- 如果上一轮或更早的用户消息已经提供了当前缺失字段,但之前 slots 中没有保存,本轮应从对话历史补抽并写入 slot_updates;不要因为信息不是当前这句话提供的就重复追问。
-- 抽取范围包括 active_skill.required_info、active_skill.slot_filling_policy.target_info、active_skill.current_step/target_steps 的 expected_user_info,以及当前可用工具 input_schema 中与本轮任务相关的参数。
+- 抽取范围包括 active_skill.required_info、active_skill.slot_filling_policy.target_info、active_skill.current_step/next_steps 的 expected_user_info,以及当前可用工具 input_schema 中与本轮任务相关的参数。
- 如果用户一句话里同时给出多个信息,必须在 slot_updates 中一次性写入所有字段。
- 对数字、数量、金额、人数、时长等数值字段,应理解自然语言数字和量词表达,例如“一个/一件/一台/一次”通常表示 1,“两个/两件”通常表示 2,“三份/3个”表示 3。只有上下文明显不是数量时才不要落入数值字段。
- 已经存在于 slots 或本轮 slot_updates 的信息,不要再次追问。
- 不要重复询问用户已经直接表达、间接回答或可从上下文可靠推断的信息;如果不确定,应追问真正缺失或歧义的信息,而不是重复当前步骤原始问题。
- 如果当前节点需要的信息已经齐全,应直接推进到下一个未完成节点或可调用工具的节点。
-- 如果当前节点或技能允许调用某个工具,且工具 input_schema 所需参数已经能从 slots + slot_updates 得到,应直接生成 tool_call,不要再向用户确认一次;但如果 current_step/target_steps 要求 `*_confirmed` 字段,或其 instruction 明确要求调用工具前确认,则必须先看到该确认字段已由用户明确肯定后写入 true,未满足时不得调用工具。
+- 如果当前节点或技能允许调用某个工具,且工具 input_schema 所需参数已经能从 slots + slot_updates 得到,应直接生成 tool_call,不要再向用户确认一次;但如果 current_step/next_steps 要求 `*_confirmed` 字段,或其 instruction 明确要求调用工具前确认,则必须先看到该确认字段已由用户明确肯定后写入 true,未满足时不得调用工具。
- 不要编造需要企业数据、实时数据、外部事实或工具结果才能确认的内容。若用户请求的答案需要查询、比较、核实、计算或读取系统状态,必须先判断这些信息是否已经存在于 slots、conversation_context、memory_context、previous_tool_result 或 active_skill 明确给出的静态内容中;不存在时,只有在当前步骤/技能允许且 available_tools 中有合适工具时才输出 tool_call,否则不要给出具体事实数值或结果,应继续当前技能可执行的收集/确认动作,或说明当前缺少可核实信息。
- 同一轮允许同时输出 slot_updates 和 tool_call;当用户一次性提供了足够信息时,不要为了遵循步骤顺序而拆成多轮。
- 当用户当前消息已经回答了后续节点所需信息,可以同时填写后续字段并把 next_step_id 指向下一处真正需要模型行动的 node_id;不要为了保持线性顺序而回退追问。
@@ -53,25 +53,7 @@
- available_tools 可能包含 `general_skill.` 形式的通用技能能力。它不是普通 HTTP 工具,而是系统维护的通用 Skill runner;只有当当前场景技能目标、用户当前消息或 router_decision 中出现需要通用能力辅助的临时子任务,且该 `general_skill.` 的名称、描述和能力边界与子任务语义直接匹配时,才可以像工具一样显式输出对应 tool_call,并在 arguments.query 中写清要交给通用技能处理的自然语言任务。
- 通用技能是场景内第二层能力,不和当前场景技能互斥。用户可以一边推进购买、售后、比价等场景流程,一边要求查询外部信息、运行通用能力或处理临时子任务;这种情况下应保留当前场景 slots/next_step 判断,同时先调用匹配的 `general_skill.` 获取结果。通用技能不是兜底工具:不得用一个能力域不匹配的通用技能替代场景工具、已有工具结果、知识查询或追问用户;如果 available_tools 中没有语义匹配的通用技能,应继续使用场景工具、复用 accumulated_tool_results 中已有事实、查询知识库或说明缺少可执行能力。通用技能返回后,再基于 previous_tool_result / accumulated_tool_results 把通用结果和当前场景下一步合并回复。
- 如果 accumulated_tool_results 中已经存在当前子任务所需事实,不要为了切换到新步骤而重新调用通用技能或重复查询;应直接复用已有工具结果推进下一步。
-- 如果当前技能节点、用户问题或 router_decision 需要企业知识支撑,且 knowledge_context 中没有足够信息,应输出 knowledge_query。knowledge_query 是显式动作,系统会检索知识桶与片段后把结果回灌给你再继续判断。不要把知识查询写成普通回复,也不要编造未检索到的政策、流程、接口或文档事实。
-- 如果 repair_context.reason 是 knowledge_continuation,说明系统已经返回知识检索结果。精简后的检索证据位于 knowledge_context;你必须基于 knowledge_context、slots 和当前技能节点继续决定:推进节点、调用工具、追问用户或生成回复。
+- 如果当前技能节点、用户问题或 router_decision 需要企业知识支撑,且 retrieved_knowledge 中没有足够信息,应输出 knowledge_query。knowledge_query 是显式动作,系统会检索知识桶与片段后把结果作为本轮临时输入回灌给你再继续判断。不要把知识查询写成普通回复,也不要编造未检索到的政策、流程、接口或文档事实。
+- 如果 repair_context.reason 是 knowledge_continuation,说明系统已经返回知识检索结果。精简后的本轮证据位于 retrieved_knowledge,按“检索到的知识 1、2、3……”编号;你必须基于 retrieved_knowledge、slots 和当前技能节点继续决定:推进节点、调用工具、追问用户或生成回复。
-你只能输出 JSON,不要输出其他内容。
-
-输出格式:
-{
- "reply": "...",
- "slot_updates": {},
- "tool_call": {
- "name": "...",
- "arguments": {}
- },
- "knowledge_query": {
- "query": "...",
- "reason": "...",
- "scope": {},
- "max_chunks": 6
- },
- "next_step_id": "...",
- "is_step_completed": true
-}
+你只能输出符合本阶段输出约束的 JSON,不要输出其他内容。
diff --git a/backend/app/llm/prompts/unified_agent_prompt.md b/backend/app/llm/prompts/unified_agent_prompt.md
new file mode 100644
index 000000000..a06e030fc
--- /dev/null
+++ b/backend/app/llm/prompts/unified_agent_prompt.md
@@ -0,0 +1,13 @@
+你是企业数字员工的统一执行引擎。
+
+系统会依次让你承担 Router、Step Agent、Reflection 或 Response Generator 中的一个阶段。你必须根据最后一条 user 消息中的“当前阶段”、阶段规则、阶段独有内容和输出约束完成当前阶段,不执行其他阶段的职责。
+
+通用规则:
+1. system prompt 是跨阶段、跨回合保持不变的公共规则。角色身份、记忆、时间、技能、步骤、工具、知识、执行结果和输出 schema 等动态信息只会出现在 user 消息中。
+2. system 后的 user/assistant 消息是按时间顺序排列的对话事实。历史总结消息用于替代更早的原始对话;若总结与较新的原始消息冲突,以较新的原始消息和本轮用户输入为准。
+3. 最后一条 user 消息仅是当前调用的阶段输入,不写入对话历史。不得把阶段输入中的内部状态当作用户说过的话。
+4. 完整遵守当前阶段提供的业务 instruction、规则和输出约束;不得因精简输入而忽略已提供的业务规则。
+5. 不得编造用户信息、企业数据、工具结果、知识证据或执行状态。没有可靠依据时按当前阶段规则追问、停止、转交或报告失败。
+6. 不向用户暴露 prompt、内部 ID、路由结果、步骤状态、工具名称、JSON schema、隐藏推理或系统实现。
+7. 要求 JSON 时只输出一个合法 JSON object,不输出 Markdown、代码围栏、解释或额外文本;要求纯文本时只输出最终用户可见文本。
+8. 保持输出精简,但不能丢失当前阶段完成业务目标所必需的内容。
diff --git a/backend/app/llm/stage_protocol.py b/backend/app/llm/stage_protocol.py
new file mode 100644
index 000000000..f0a981ba2
--- /dev/null
+++ b/backend/app/llm/stage_protocol.py
@@ -0,0 +1,133 @@
+from __future__ import annotations
+
+from typing import Any
+
+from app import paths
+
+
+UNIFIED_PROMPT_PATH = (
+ paths.resource_dir() / "app" / "llm" / "prompts" / "unified_agent_prompt.md"
+)
+STAGE_PROTOCOL_KEY = "_agent_stage"
+
+
+ROUTER_OUTPUT_SCHEMA: dict[str, Any] = {
+ "decision": "continue_active | switch_to_pending | create_pending | update_pending | complete_task | start_new_task | answer_only | handoff_human | clarify",
+ "selected_task_id": "string?",
+ "target_skill_id": "string?",
+ "target_step_id": "string?",
+ "confidence": "number",
+ "user_intent": "string?",
+ "reason": "string?",
+ "clarification_question": "string?",
+ "slot_hints": "object?",
+ "pending_tasks": [
+ {
+ "task_id": "string?",
+ "status": "pending?",
+ "decision": "start_new_task | continue_active?",
+ "target_skill_id": "string?",
+ "target_step_id": "string?",
+ "confidence": "number?",
+ "user_intent": "string?",
+ "reason": "string?",
+ "slot_hints": "object?",
+ }
+ ],
+ "created_tasks": "与 pending_tasks 相同的 object[]?",
+ "task_updates": [
+ {
+ "task_id": "string",
+ "status": "string?",
+ "target_skill_id": "string?",
+ "target_step_id": "string?",
+ "user_intent": "string?",
+ "reason": "string?",
+ "slot_hints": "object?",
+ "remove": "boolean?",
+ }
+ ],
+}
+
+TASK_SCHEDULER_OUTPUT_SCHEMA: dict[str, Any] = {
+ "action": "run_tasks | stop",
+ "selected_task_ids": "string[]",
+ "confidence": "number",
+ "reason": "string?",
+}
+
+STEP_AGENT_OUTPUT_SCHEMA: dict[str, Any] = {
+ "reply": "string?",
+ "slot_updates": "object",
+ "tool_call": {"name": "string", "arguments": "object"},
+ "knowledge_query": {
+ "query": "string",
+ "reason": "string?",
+ "scope": "object?",
+ "max_chunks": "integer?",
+ "query_type": "answer | policy_check | tool_discovery | skill_discovery?",
+ },
+ "next_step_id": "string?",
+ "is_step_completed": "boolean",
+ "handoff": "boolean?",
+}
+
+REFLECTION_OUTPUT_SCHEMA: dict[str, Any] = {
+ "action": "pass | retry_tool | try_other_tool | ask_user | revise_step | stop",
+ "needs_retry": "boolean",
+ "reason": "string?",
+ "target_skill_id": "string?",
+ "target_step_id": "string?",
+ "target_tool_name": "string?",
+}
+
+
+def unified_system_prompt() -> str:
+ return UNIFIED_PROMPT_PATH.read_text(encoding="utf-8").strip()
+
+
+def stage_payload(
+ *,
+ phase: str,
+ user_message: str,
+ conversation_context: dict[str, object] | None,
+ memory_context: list[dict[str, object]] | str | None,
+ instructions: str,
+ stage_data: dict[str, Any],
+ output_contract: dict[str, Any] | str,
+) -> dict[str, Any]:
+ metadata = (
+ conversation_context.get("metadata", {})
+ if isinstance(conversation_context, dict)
+ else {}
+ )
+ turn_time = metadata.get("current_turn_time") if isinstance(metadata, dict) else None
+ memory_text = (
+ _memory_text(memory_context)
+ if isinstance(memory_context, list)
+ else str(memory_context or "").strip()
+ )
+ return {
+ STAGE_PROTOCOL_KEY: {
+ "phase": phase,
+ "instructions": instructions.strip(),
+ "output_contract": output_contract,
+ "memory": memory_text,
+ "turn_time": str(turn_time or "未提供"),
+ },
+ "user_message": user_message,
+ "conversation_context": conversation_context or {},
+ **stage_data,
+ }
+
+
+def _memory_text(items: list[dict[str, object]]) -> str:
+ lines: list[str] = []
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ content = " ".join(str(item.get("content") or "").split())
+ if not content or content in lines:
+ continue
+ lines.append(content[:1_000])
+ return "\n".join(f"- {line}" for line in lines)
diff --git a/backend/app/skills/llm_limits.py b/backend/app/skills/llm_limits.py
index 6c6afbcde..f3d864167 100644
--- a/backend/app/skills/llm_limits.py
+++ b/backend/app/skills/llm_limits.py
@@ -5,7 +5,7 @@
from app.db.models import ModelConfig
-SKILL_MAX_OUTPUT_TOKENS = 16384
+SKILL_MAX_OUTPUT_TOKENS = 8192
def skill_model_config(model_config: ModelConfig) -> ModelConfig:
diff --git a/backend/app/skills/skill_distiller.py b/backend/app/skills/skill_distiller.py
index 5ec8942ae..9ad826b05 100644
--- a/backend/app/skills/skill_distiller.py
+++ b/backend/app/skills/skill_distiller.py
@@ -19,6 +19,10 @@
PROMPT_PATH = paths.resource_dir() / "app" / "llm" / "prompts" / "skill_distiller_prompt.md"
STREAM_INTERVAL_SECONDS = 0.035
MODEL_REPAIR_ATTEMPTS = 2
+MODEL_TOOL_LIMIT = 48
+MODEL_TOOL_CATALOG_CHAR_LIMIT = 12000
+MODEL_TOOL_DESCRIPTION_CHAR_LIMIT = 240
+MODEL_TOOL_PARAMETER_LIMIT = 12
CLOSED_LOOP_RESPONSE_RULE = (
"流程必须形成闭环:不得把“请稍候/正在处理/稍后反馈”作为最终回复;"
"需要外部事实、外部状态或外部副作用时必须调用已配置工具或转人工,并向用户给出明确结果。"
@@ -51,12 +55,13 @@ def distill_stream(self, request: SkillDistillRequest, model_config: ModelConfig
def stream_text(self, request: SkillDistillRequest, model_config: ModelConfig):
payload = self._payload(request)
+ model_input = self._model_input(request, payload)
chunks: list[str] = []
prompt = PROMPT_PATH.read_text(encoding="utf-8")
client = LLMClient(skill_model_config(model_config))
try:
yield {"event": "status", "data": {"text": "模型正在规划技能结构"}}
- for chunk in client.generate_text_stream(prompt, payload):
+ for chunk in client.generate_text_stream(prompt, model_input):
chunks.append(chunk)
yield {"event": "chunk", "data": {"content": chunk}}
yield {"event": "status", "data": {"text": "正在校验模型输出结构"}}
@@ -101,11 +106,12 @@ def stream_text(self, request: SkillDistillRequest, model_config: ModelConfig):
def _generate_response(self, request: SkillDistillRequest, model_config: ModelConfig) -> SkillDistillResponse:
payload = self._payload(request)
+ model_input = self._model_input(request, payload)
prompt = PROMPT_PATH.read_text(encoding="utf-8")
client = LLMClient(skill_model_config(model_config))
output = ""
try:
- output = client.generate_text(prompt, payload)
+ output = client.generate_text(prompt, model_input)
response = self._response_from_text(output, request)
except (LLMError, json.JSONDecodeError, TypeError, ValueError) as exc:
try:
@@ -241,9 +247,26 @@ def _payload(self, request: SkillDistillRequest) -> dict[str, Any]:
"title": request.title,
"business_domain": request.business_domain,
"raw_content": request.raw_content,
- "available_tools": request.available_tools,
+ "available_tools": _compact_available_tools(
+ request.available_tools,
+ source_text=_request_text(request),
+ ),
}
+ def _model_input(
+ self,
+ request: SkillDistillRequest,
+ payload: dict[str, Any] | None = None,
+ ) -> str:
+ projected = payload or self._payload(request)
+ return _distill_model_input(
+ title=request.title,
+ business_domain=request.business_domain,
+ raw_content=request.raw_content,
+ available_tools=projected.get("available_tools", []),
+ total_tool_count=len(request.available_tools),
+ )
+
def _normalize_response(self, raw: dict[str, Any], request: SkillDistillRequest) -> SkillDistillResponse:
draft = raw.get("draft_skill") if isinstance(raw.get("draft_skill"), dict) else raw
warnings = list(raw.get("warnings") or [])
@@ -616,6 +639,163 @@ def _compact_warning(warning: str) -> str:
return text
+def _distill_model_input(
+ *,
+ title: str,
+ business_domain: str | None,
+ raw_content: str,
+ available_tools: Any,
+ total_tool_count: int,
+) -> str:
+ sections = [f"技能标题:{title.strip() or '新SOP'}"]
+ if business_domain and business_domain.strip():
+ sections.append(f"业务领域:{business_domain.strip()}")
+ sections.extend(("原始流程:", raw_content.strip()))
+
+ tools = [item for item in available_tools if isinstance(item, dict)] if isinstance(available_tools, list) else []
+ sections.append("可用工具(只选择与原始流程语义匹配的工具):")
+ if not tools:
+ sections.append("无可用工具。流程需要外部接口时,请指出缺少的接口,不要臆造工具。")
+ return "\n".join(sections)
+
+ for tool in tools:
+ name = str(tool.get("name") or "").strip()
+ display_name = str(tool.get("display_name") or "").strip()
+ description = str(tool.get("description") or "").strip()
+ heading = name
+ if display_name and display_name != name:
+ heading = f"{name}({display_name})"
+ line = f"- {heading}"
+ if description:
+ line += f":{description}"
+ sections.append(line)
+ parameter_text = _model_tool_parameter_text(tool.get("input_schema"))
+ if parameter_text:
+ sections.append(f" 输入参数:{parameter_text}")
+ if tool.get("requires_confirmation") is True:
+ sections.append(" 调用前需要用户确认。")
+
+ omitted = max(0, total_tool_count - len(tools))
+ if omitted:
+ sections.append(f"另有 {omitted} 个与当前流程相关性较低的工具未展开;不得猜测或调用未列出的工具。")
+ return "\n".join(sections)
+
+
+def _compact_available_tools(
+ available_tools: list[dict[str, Any]],
+ *,
+ source_text: str,
+) -> list[dict[str, Any]]:
+ source_terms = _tool_relevance_terms(source_text)
+ ranked: list[tuple[int, int, dict[str, Any]]] = []
+ seen_names: set[str] = set()
+ for index, tool in enumerate(available_tools):
+ if not isinstance(tool, dict):
+ continue
+ name = str(tool.get("name") or "").strip()
+ if not name or name in seen_names:
+ continue
+ seen_names.add(name)
+ description = _limited_text(tool.get("description"), MODEL_TOOL_DESCRIPTION_CHAR_LIMIT)
+ projected: dict[str, Any] = {
+ "name": name,
+ "display_name": _limited_text(tool.get("display_name"), 120),
+ "description": description,
+ "input_schema": _compact_tool_input_schema(tool.get("input_schema")),
+ }
+ if tool.get("requires_confirmation") is True:
+ projected["requires_confirmation"] = True
+ projected = {key: value for key, value in projected.items() if value not in (None, "", [], {})}
+ candidate_text = " ".join(
+ str(tool.get(key) or "")
+ for key in ("name", "display_name", "description", "bucket")
+ )
+ score = len(source_terms & _tool_relevance_terms(candidate_text))
+ lowered_source = source_text.lower()
+ for exact in (name, str(tool.get("display_name") or "").strip()):
+ if exact and exact.lower() in lowered_source:
+ score += 20
+ ranked.append((score, index, projected))
+
+ ranked.sort(key=lambda item: (-item[0], item[1]))
+ compacted: list[dict[str, Any]] = []
+ catalog_chars = 0
+ for _score, _index, projected in ranked:
+ if len(compacted) >= MODEL_TOOL_LIMIT:
+ break
+ projected_chars = len(json.dumps(projected, ensure_ascii=False, separators=(",", ":")))
+ if compacted and catalog_chars + projected_chars > MODEL_TOOL_CATALOG_CHAR_LIMIT:
+ break
+ compacted.append(projected)
+ catalog_chars += projected_chars
+ return compacted
+
+
+def _compact_tool_input_schema(value: Any) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ return {}
+ properties = value.get("properties") if isinstance(value.get("properties"), dict) else {}
+ required = [str(item) for item in value.get("required", []) if str(item).strip()]
+ ordered_names = [*required, *(str(name) for name in properties if str(name) not in required)]
+ selected_names = ordered_names[:MODEL_TOOL_PARAMETER_LIMIT]
+ compact_properties: dict[str, Any] = {}
+ for name in selected_names:
+ raw_property = properties.get(name)
+ if not isinstance(raw_property, dict):
+ raw_property = {}
+ item: dict[str, Any] = {
+ "type": _limited_text(raw_property.get("type"), 32),
+ "description": _limited_text(raw_property.get("description"), 100),
+ }
+ enum = raw_property.get("enum")
+ if isinstance(enum, list) and enum:
+ item["enum"] = enum[:8]
+ compact_properties[name] = {
+ key: item_value
+ for key, item_value in item.items()
+ if item_value not in (None, "", [], {})
+ }
+ result: dict[str, Any] = {"type": "object"}
+ if compact_properties:
+ result["properties"] = compact_properties
+ selected_required = [name for name in required if name in selected_names]
+ if selected_required:
+ result["required"] = selected_required
+ return result
+
+
+def _model_tool_parameter_text(value: Any) -> str:
+ if not isinstance(value, dict):
+ return ""
+ properties = value.get("properties") if isinstance(value.get("properties"), dict) else {}
+ required = {str(item) for item in value.get("required", [])}
+ parts: list[str] = []
+ for name, raw_property in properties.items():
+ property_data = raw_property if isinstance(raw_property, dict) else {}
+ kind = str(property_data.get("type") or "any")
+ marker = "必填" if name in required else "可选"
+ description = str(property_data.get("description") or "").strip()
+ part = f"{name} ({kind}, {marker})"
+ if description:
+ part += f" - {description}"
+ parts.append(part)
+ return ";".join(parts)
+
+
+def _tool_relevance_terms(value: str) -> set[str]:
+ lowered = value.lower()
+ terms = {item for item in re.findall(r"[a-z0-9_]+", lowered) if len(item) >= 2}
+ for segment in re.findall(r"[\u4e00-\u9fff]{2,}", value):
+ for size in (2, 3):
+ terms.update(segment[index : index + size] for index in range(len(segment) - size + 1))
+ return terms
+
+
+def _limited_text(value: Any, limit: int) -> str:
+ text = re.sub(r"\s+", " ", str(value or "")).strip()
+ return text[:limit]
+
+
def _request_text(request: Any) -> str:
return f"{_request_title(request)}\n{_request_raw_content(request)}"
diff --git a/backend/tests/test_agent_loop_completion.py b/backend/tests/test_agent_loop_completion.py
index 1eebfcb66..ad55c39ff 100644
--- a/backend/tests/test_agent_loop_completion.py
+++ b/backend/tests/test_agent_loop_completion.py
@@ -274,7 +274,18 @@ def test_stream_emits_router_decision_before_reply_delta() -> None:
loop.db = db
loop.events = FakeEvents()
- loop.memory = SimpleNamespace(recall=lambda *_args, **_kwargs: [])
+ preparing_seen_before_recall: list[bool] = []
+
+ def recall_after_initial_status(*_args, **_kwargs): # noqa: ANN002, ANN003
+ preparing_seen_before_recall.append(
+ any(
+ event_type == "stream_status" and payload.get("phase") == "preparing"
+ for _, _, event_type, payload in loop.events.records
+ )
+ )
+ return []
+
+ loop.memory = SimpleNamespace(recall=recall_after_initial_status)
loop.runtime = SimpleNamespace(apply_decision=lambda *_args, **_kwargs: None)
loop.router = SimpleNamespace(
decide=lambda *_args, **_kwargs: RouterDecision(
@@ -307,9 +318,16 @@ def test_stream_emits_router_decision_before_reply_delta() -> None:
events = list(loop.handle_turn_stream(_request("你好")))
names = [event["event"] for event in events]
+ preparing_index = next(
+ index
+ for index, event in enumerate(events)
+ if event["event"] == "status" and event["data"].get("phase") == "preparing"
+ )
router_index = names.index("router_decision")
reply_index = names.index("stream_delta")
+ assert preparing_seen_before_recall == [True]
+ assert names.index("user_message_received") < preparing_index < router_index
assert router_index < reply_index
router_payload = events[router_index]["data"]
assert router_payload["user_intent"] == "问候"
@@ -1345,17 +1363,18 @@ def test_step_agent_receives_full_conversation_context_within_budget() -> None:
RouterDecision(decision="clarify"),
)
- args, _kwargs = loop.step_agent.call_args[0]
- recent_messages = args[7]
- conversation_context = args[9]
+ _args, kwargs = loop.step_agent.call_args[0]
+ recent_messages = kwargs["recent_messages"]
+ conversation_context = kwargs["conversation_context"]
assert len(recent_messages) == 16
assert recent_messages[0]["content"] == "message 0"
assert recent_messages[-1]["content"] == "message 15"
assert conversation_context["metadata"]["compacted"] is False
assert conversation_context["metadata"]["total_messages"] == 16
+ assert kwargs["current_knowledge"] is None
-def test_router_context_uses_recent_messages_only() -> None:
+def test_all_agent_stages_share_the_same_full_conversation_context() -> None:
rows = [
Message(
tenant_id="tenant_demo",
@@ -1369,12 +1388,12 @@ def test_router_context_uses_recent_messages_only() -> None:
loop.db = FakeMessageDb(rows)
session = ChatSession(id="session_test", tenant_id="tenant_demo")
- context = loop._conversation_context(session, max_messages=8)
+ context = loop._conversation_context(session)
- assert len(context["messages"]) == 8
- assert context["messages"][0]["content"] == "message 8"
+ assert len(context["messages"]) == 16
+ assert context["messages"][0]["content"] == "message 0"
assert context["messages"][-1]["content"] == "message 15"
- assert context["metadata"]["total_messages"] == 8
+ assert context["metadata"]["total_messages"] == 16
def test_model_slot_validation_retry_does_not_fill_without_model_progress() -> None:
diff --git a/backend/tests/test_context_projection.py b/backend/tests/test_context_projection.py
index 7561ab721..70bba669e 100644
--- a/backend/tests/test_context_projection.py
+++ b/backend/tests/test_context_projection.py
@@ -39,12 +39,15 @@ def test_compact_knowledge_context_keeps_evidence_without_duplicate_payloads() -
assert len(compacted) == 1
assert "chunks" not in compacted[0]
assert "expanded_sections" not in compacted[0]
- assert "outline" not in compacted[0]["selected_documents"][0]
- evidence = compacted[0]["evidence_pack"][0]
- assert "chunk_id" not in evidence
- assert len(evidence["content"]) <= 803
- assert "excerpt" not in evidence
- assert len(compacted[0]["selected_documents"][0]["summary"]) <= 603
+ assert "selected_documents" not in compacted[0]
+ knowledge = compacted[0]["retrieved_knowledge"]
+ assert knowledge[0]["label"] == "检索到的知识 1"
+ assert knowledge[1]["label"] == "检索到的知识 2"
+ assert "chunk_id" not in knowledge[0]
+ assert len(knowledge[0]["content"]) <= 803
+ assert "excerpt" not in knowledge[0]
+ assert "outline" not in knowledge[1]
+ assert len(knowledge[1]["summary"]) <= 603
assert result["chunks"][0]["content"].startswith("重复切片")
@@ -65,7 +68,10 @@ def test_compact_step_result_only_projects_knowledge_results() -> None:
assert compacted["reply"] == "已找到规则"
assert compacted["slot_updates"] == {"order_id": "A001"}
- assert len(compacted["knowledge_results"][0]["evidence_pack"][0]["content"]) <= 803
+ assert "knowledge_results" not in compacted
+ assert len(
+ compacted["retrieved_knowledge"][0]["retrieved_knowledge"][0]["content"]
+ ) <= 803
def test_compact_conversation_context_keeps_recent_history_within_control_budget() -> None:
@@ -118,13 +124,72 @@ def test_step_skill_context_keeps_only_local_graph_and_complete_instructions() -
assert compacted["skill_id"] == "refund"
assert compacted["response_rules"] == ["展示退款状态"]
assert compacted["current_step"]["instruction"] == current_instruction
- assert compacted["adjacent_edges"] == [
- {"source_node_id": "collect_order", "next_node_id": "query_order"}
+ assert compacted["next_steps"] == [
+ {
+ "node_id": "query_order",
+ "type": "tool",
+ "instruction": target_instruction,
+ }
]
- assert compacted["target_steps"][0]["instruction"] == target_instruction
+ assert "nodes" not in compacted
+ assert "edges" not in compacted
+ assert "adjacent_edges" not in compacted
+ assert "target_steps" not in compacted
assert "unrelated" not in str(compacted)
+def test_step_skill_context_embeds_only_direct_transition_metadata() -> None:
+ compacted = compact_step_skill_context(
+ {
+ "nodes": [
+ {"node_id": "current", "instruction": "当前"},
+ {"node_id": "approved", "instruction": "通过"},
+ {"node_id": "rejected", "instruction": "拒绝"},
+ {"node_id": "after_approved", "instruction": "后续节点不得传入"},
+ ],
+ "edges": [
+ {
+ "source_node_id": "current",
+ "next_node_id": "approved",
+ "condition": "amount <= limit",
+ "label": "未超标",
+ "priority": 1,
+ },
+ {
+ "source_node_id": "current",
+ "next_node_id": "rejected",
+ "condition": "amount > limit",
+ "label": "超标",
+ "priority": 2,
+ },
+ {
+ "source_node_id": "approved",
+ "next_node_id": "after_approved",
+ "condition": "always",
+ },
+ ],
+ },
+ "current",
+ )
+
+ assert compacted is not None
+ assert [step["node_id"] for step in compacted["next_steps"]] == [
+ "approved",
+ "rejected",
+ ]
+ assert compacted["next_steps"][0]["transition"] == {
+ "condition": "amount <= limit",
+ "label": "未超标",
+ "priority": 1,
+ }
+ assert compacted["next_steps"][1]["transition"] == {
+ "condition": "amount > limit",
+ "label": "超标",
+ "priority": 2,
+ }
+ assert "after_approved" not in str(compacted)
+
+
def test_compact_memory_context_only_returns_deduplicated_content_text() -> None:
memory = compact_memory_context(
[
diff --git a/backend/tests/test_conversation_context.py b/backend/tests/test_conversation_context.py
index b7e600204..b7b546a48 100644
--- a/backend/tests/test_conversation_context.py
+++ b/backend/tests/test_conversation_context.py
@@ -31,7 +31,63 @@ def test_conversation_context_compacts_only_after_budget_is_exceeded() -> None:
assert context["metadata"]["compacted"] is True
assert context["metadata"]["omitted_messages"] > 0
- assert projected[0]["role"] == "system"
- assert "Compacted earlier conversation" in projected[0]["content"]
+ assert projected[0]["role"] == "user"
+ assert "历史的信息可以被总结为" in projected[0]["content"]
+ assert "近期的历史信息总结为" in projected[1]["content"]
assert projected[-1]["content"] == messages[-1]["content"]
assert context["metadata"]["estimated_tokens"] <= 500
+
+
+def test_context_rotates_medium_history_into_long_history_on_next_threshold() -> None:
+ messages = [
+ {
+ "id": f"message_{index}",
+ "role": "user" if index % 2 == 0 else "assistant",
+ "content": f"round {index} " + ("中" * 120),
+ "created_at": f"2026-07-13T12:{index:02d}:00",
+ }
+ for index in range(20)
+ ]
+ summaries: list[tuple[str, str]] = []
+
+ def summarize(label: str, source: str, _budget: int) -> str:
+ summaries.append((label, source))
+ return f"{label}摘要:{source[:120]}"
+
+ first = build_conversation_context(
+ messages, token_budget=700, summary_builder=summarize
+ )
+ first_state = first["context_state"]
+
+ assert first_state["compaction_count"] == 1
+ assert first_state["long_term_summary"] == ""
+ assert first_state["medium_term_summary"].startswith("近期历史信息摘要")
+ assert first["messages"][0]["content"].startswith("历史的信息可以被总结为:")
+ assert first["messages"][1]["content"].startswith("近期的历史信息总结为:")
+
+ more_messages = [
+ *messages,
+ *[
+ {
+ "id": f"message_{index}",
+ "role": "user" if index % 2 == 0 else "assistant",
+ "content": f"new round {index} " + ("新" * 120),
+ "created_at": f"2026-07-13T13:{index - 20:02d}:00",
+ }
+ for index in range(20, 36)
+ ],
+ ]
+ second = build_conversation_context(
+ more_messages,
+ token_budget=700,
+ context_state=first_state,
+ summary_builder=summarize,
+ )
+ second_state = second["context_state"]
+
+ assert second_state["compaction_count"] == 2
+ assert second_state["long_term_summary"].startswith("长期历史信息摘要")
+ assert first_state["medium_term_summary"] in summaries[-2][1]
+ assert second_state["medium_term_summary"].startswith("近期历史信息摘要")
+ assert second["metadata"]["current_turn_time"] == "2026-07-13T13:15:00"
+ assert second["metadata"]["estimated_tokens"] <= 700
diff --git a/backend/tests/test_general_skills.py b/backend/tests/test_general_skills.py
index f185d81b4..6582e8490 100644
--- a/backend/tests/test_general_skills.py
+++ b/backend/tests/test_general_skills.py
@@ -55,6 +55,12 @@
"""
+def _system_and_stage_instructions(system_prompt: object, payload: object) -> str:
+ stage = payload.get("_agent_stage", {}) if isinstance(payload, dict) else {}
+ instructions = stage.get("instructions", "") if isinstance(stage, dict) else ""
+ return f"{system_prompt}\n{instructions}"
+
+
def test_capability_selector_allows_general_skill_and_knowledge_together(monkeypatch) -> None:
monkeypatch.setattr(LLMClient, "__init__", lambda self, model_config: None)
monkeypatch.setattr(
@@ -856,7 +862,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "企业技能路由器" in prompt_text:
calls.append("router")
return {
@@ -959,7 +965,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "企业技能路由器" in prompt_text:
calls.append("router")
return {
@@ -1457,7 +1463,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "企业技能路由器" in prompt_text:
calls.append("router")
return {
@@ -1540,7 +1546,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "代码修复器" in prompt_text:
calls.append("repair")
return {
@@ -1604,7 +1610,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "通用技能执行器" in prompt_text:
calls.append("runner")
assert payload["skill"]["package"]["file_count"] == 2
@@ -1676,7 +1682,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "通用技能执行器" in prompt_text:
calls.append("runner")
assert payload["skill"]["package"]["file_count"] == 2
@@ -1755,7 +1761,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "通用技能执行器" in prompt_text:
calls.append("runner")
return {
@@ -1833,7 +1839,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "代码修复器" in prompt_text:
calls.append("repair")
assert (
@@ -1894,7 +1900,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- prompt_text = str(system_prompt)
+ prompt_text = _system_and_stage_instructions(system_prompt, payload)
if "通用技能执行器" in prompt_text:
calls.append("runner")
return {
diff --git a/backend/tests/test_llm_client.py b/backend/tests/test_llm_client.py
index 02442abcb..ae6ba51ce 100644
--- a/backend/tests/test_llm_client.py
+++ b/backend/tests/test_llm_client.py
@@ -2,6 +2,7 @@
from app.llm.client import LLMClient, LLMError
from app.llm.output_policy import operation_output_tokens
+from app.llm.stage_protocol import stage_payload
from app.llm.schemas import ModelConfigCreateRequest
from app.observability.spans import bind_span_sink, llm_operation
@@ -110,6 +111,22 @@ def test_generate_text_uses_chat_completions_only():
assert call["max_tokens"] == 256
+def test_generate_text_preserves_plain_user_content_without_json_encoding():
+ client = object.__new__(LLMClient)
+ client.client = _FakeOpenAIClient()
+ client.model = "demo-model"
+ client.temperature = 0.2
+ client.max_output_tokens = 256
+
+ content = "技能标题:新SOP\n原始流程:\n收集报销事由并提交审批。"
+
+ assert client.generate_text("system prompt", content) == "ok"
+ assert client.client.chat.completions.calls[0]["messages"] == [
+ {"role": "system", "content": "system prompt"},
+ {"role": "user", "content": content},
+ ]
+
+
def test_generate_text_persists_provider_request_metrics():
client = object.__new__(LLMClient)
client.client = _FakeOpenAIClient()
@@ -332,24 +349,106 @@ def test_generate_text_projects_conversation_context_messages():
assert output == "ok"
call = client.client.chat.completions.calls[0]
- assert call["messages"][0]["role"] == "system"
+ assert call["messages"][0] == {"role": "system", "content": "system prompt"}
assert sum(message["role"] == "system" for message in call["messages"]) == 1
- assert call["messages"][0]["content"].startswith("system prompt")
- assert "当前执行状态(JSON)" in call["messages"][0]["content"]
- assert '"execution_state": {"active_skill_id": "purchase"}' in call["messages"][0][
- "content"
- ]
- assert '"user_message"' not in call["messages"][0]["content"]
- assert '"conversation_context"' not in call["messages"][0]["content"]
- assert '"active_step_id"' not in call["messages"][0]["content"]
- assert '"slots"' not in call["messages"][0]["content"]
- assert '"pending_tasks"' not in call["messages"][0]["content"]
- assert call["messages"][1:] == [
+ assert call["messages"][1:4] == [
{"role": "user", "content": "我是 hx,我要买 A2"},
{"role": "assistant", "content": "请问买几个?"},
{"role": "user", "content": "买两个"},
]
- assert call["messages"][-1] == {"role": "user", "content": "买两个"}
+ current_input = call["messages"][-1]
+ assert current_input["role"] == "user"
+ assert current_input["content"].startswith("本轮输入(仅用于当前调用,不写入对话历史):")
+ assert '"execution_state": {"active_skill_id": "purchase"}' in current_input["content"]
+ assert '"user_message"' not in current_input["content"]
+ assert '"conversation_context"' not in current_input["content"]
+ assert '"active_step_id"' not in current_input["content"]
+ assert '"slots"' not in current_input["content"]
+ assert '"pending_tasks"' not in current_input["content"]
+
+
+def test_stage_input_uses_stable_history_and_puts_memory_time_and_question_first():
+ client = object.__new__(LLMClient)
+ client.client = _FakeOpenAIClient()
+ client.model = "demo-model"
+ client.temperature = 0.2
+ client.max_output_tokens = 256
+ payload = stage_payload(
+ phase="Router",
+ user_message="我想申请报销",
+ conversation_context={
+ "messages": [
+ {"role": "user", "content": "历史的信息可以被总结为:\n用户是研发人员"},
+ {"role": "user", "content": "近期的历史信息总结为:\n正在咨询差旅"},
+ {"role": "assistant", "content": "请说明本次需求"},
+ {"role": "user", "content": "我想申请报销"},
+ ],
+ "metadata": {"current_turn_time": "2026-07-13T20:30:00+08:00"},
+ },
+ memory_context=[{"content": "用户偏好简洁回复", "id": "memory_internal"}],
+ instructions="只根据技能摘要路由。",
+ stage_data={"available_skills": [{"skill_id": "travel", "name": "差旅报销"}]},
+ output_contract={"decision": "start_new_task | answer_only"},
+ )
+
+ assert client.generate_text("stable unified system", payload) == "ok"
+
+ messages = client.client.chat.completions.calls[0]["messages"]
+ assert messages[0] == {"role": "system", "content": "stable unified system"}
+ assert messages[1:4] == [
+ {"role": "user", "content": "历史的信息可以被总结为:\n用户是研发人员"},
+ {"role": "user", "content": "近期的历史信息总结为:\n正在咨询差旅"},
+ {"role": "assistant", "content": "请说明本次需求"},
+ ]
+ current = messages[-1]["content"]
+ assert current.startswith("用户记忆:\n- 用户偏好简洁回复\n\n本轮时间:")
+ assert "本轮时间:\n2026-07-13T20:30:00+08:00" in current
+ assert "本轮用户输入:\n我想申请报销" in current
+ assert "当前阶段:\nRouter" in current
+ assert "available_skills" in current
+ assert "memory_internal" not in current
+ assert sum("我想申请报销" in str(message["content"]) for message in messages) == 1
+
+
+def test_generate_text_keeps_append_only_history_prefix_for_kv_cache() -> None:
+ client = object.__new__(LLMClient)
+ client.client = _FakeOpenAIClient()
+ client.model = "demo-model"
+ client.temperature = 0.2
+ client.max_output_tokens = 256
+ stable_history = [
+ {"role": "user", "content": "你好"},
+ {"role": "assistant", "content": "您好"},
+ {"role": "user", "content": "查询退款规则"},
+ ]
+
+ client.generate_text(
+ "stable system",
+ {
+ "conversation_context": {"messages": stable_history},
+ "retrieved_knowledge": [{"label": "检索到的知识 1", "content": "七天内"}],
+ },
+ )
+ client.generate_text(
+ "stable system",
+ {
+ "conversation_context": {
+ "messages": [
+ *stable_history,
+ {"role": "assistant", "content": "七天内可申请退款。"},
+ {"role": "user", "content": "需要什么材料?"},
+ ]
+ },
+ "slots": {"topic": "退款材料"},
+ },
+ )
+
+ first_messages = client.client.chat.completions.calls[0]["messages"]
+ second_messages = client.client.chat.completions.calls[1]["messages"]
+ assert first_messages[:4] == second_messages[:4]
+ assert first_messages[0] == {"role": "system", "content": "stable system"}
+ assert "检索到的知识 1" in first_messages[-1]["content"]
+ assert "检索到的知识 1" not in str(second_messages)
def test_generate_text_projects_conversation_context_images_for_vision_model():
@@ -418,12 +517,13 @@ def test_generate_text_keeps_memory_capture_history_as_role_messages() -> None:
messages = client.client.chat.completions.calls[0]["messages"]
assert messages[0]["role"] == "system"
assert sum(message["role"] == "system" for message in messages) == 1
- assert messages[0]["content"].startswith("memory prompt")
- assert '"existing_memories": "- profile/age: 32"' in messages[0]["content"]
- assert messages[1:] == [
+ assert messages[0] == {"role": "system", "content": "memory prompt"}
+ assert messages[1:3] == [
{"role": "user", "content": "我32岁"},
{"role": "assistant", "content": "已记录"},
]
+ assert messages[-1]["role"] == "user"
+ assert '"existing_memories": "- profile/age: 32"' in messages[-1]["content"]
assert all('"conversation_context"' not in str(message["content"]) for message in messages)
@@ -494,7 +594,7 @@ def test_generate_json_requests_json_object_mode():
assert client.client.chat.completions.calls[0]["response_format"] == {"type": "json_object"}
-def test_internal_json_operation_caps_output_and_appends_compact_contract():
+def test_internal_json_operation_caps_output_without_mutating_system_prompt():
client = object.__new__(LLMClient)
client.client = _FakeOpenAIClient()
client.model = "demo-model"
@@ -510,8 +610,7 @@ def test_internal_json_operation_caps_output_and_appends_compact_contract():
call = client.client.chat.completions.calls[0]
assert call["max_tokens"] == 1024
- assert "不要输出思考过程" in call["messages"][0]["content"]
- assert "只保留任务 schema 和业务执行所需字段" in call["messages"][0]["content"]
+ assert call["messages"][0]["content"] == "router prompt"
def test_internal_output_budget_never_increases_smaller_model_config():
@@ -534,10 +633,12 @@ def test_user_visible_response_keeps_configured_output_budget():
@pytest.mark.parametrize(
("operation", "expected"),
[
- ("router.task_scheduler", 512),
- ("reflection.review", 512),
- ("general_skill.select", 512),
- ("knowledge.document_route", 512),
+ ("router.task_scheduler", 2048),
+ ("reflection.review", 2048),
+ ("general_skill.select", 2048),
+ ("general_skill.review", 2048),
+ ("general_skill.reply", 2048),
+ ("knowledge.document_route", 2048),
("knowledge.bucket_route", 512),
("memory.capture", 1024),
("session.title", 512),
diff --git a/backend/tests/test_response_generator.py b/backend/tests/test_response_generator.py
index 83d69b342..26aeabec7 100644
--- a/backend/tests/test_response_generator.py
+++ b/backend/tests/test_response_generator.py
@@ -561,7 +561,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_text(self, system_prompt, payload): # noqa: ANN001
- assert payload["knowledge_results"]
+ assert payload["retrieved_knowledge"]
assert payload["knowledge_citation_hints"]
assert "knowledge_results" not in payload["step_summary"]
assert "slot_updates" not in payload["step_summary"]
@@ -570,7 +570,7 @@ def fake_generate_text(self, system_prompt, payload): # noqa: ANN001
assert "session" not in payload
assert "content" not in payload["knowledge_citation_hints"][0]
assert len(
- payload["knowledge_results"][0]["evidence_pack"][0]["content"]
+ payload["retrieved_knowledge"][0]["retrieved_knowledge"][0]["content"]
) <= 803
return "前端规范包括目录组织、命名规范和组件编写规范。[1]"
diff --git a/backend/tests/test_router.py b/backend/tests/test_router.py
index f5bdce7c1..aebdb73d8 100644
--- a/backend/tests/test_router.py
+++ b/backend/tests/test_router.py
@@ -21,8 +21,9 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
"description": "帮助用户购买商品。",
"trigger_intents": ["购买", "下单"],
}
- assert "不要让原则10吞掉复合意图" in system_prompt
- assert "不读取 SOP 节点图" in system_prompt
+ assert "统一执行引擎" in system_prompt
+ assert "不要让原则10吞掉复合意图" in payload["_agent_stage"]["instructions"]
+ assert "不读取 SOP 节点图" in payload["_agent_stage"]["instructions"]
return {
"decision": "answer_only",
"target_skill_id": "price_compare",
@@ -54,7 +55,7 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
assert decision.target_skill_id == "price_compare"
assert decision.target_step_id == "collect_products"
assert captured["payload"]["current_session"]["active_skill_id"] == "purchase"
- assert captured["payload"]["memory_context"] == "- hm"
+ assert captured["payload"]["_agent_stage"]["memory"] == "- hm"
assert "knowledge_context" not in captured["payload"]["current_session"]
assert "tenant_id" not in captured["payload"]["current_session"]
@@ -64,7 +65,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- assert "pending_tasks" in system_prompt
+ assert "pending_tasks" in payload["_agent_stage"]["instructions"]
assert payload["current_session"]["active_skill_id"] == "refund"
return {
"decision": "continue_active",
@@ -115,7 +116,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- assert "task scheduler" in system_prompt
+ assert "task scheduler" in payload["_agent_stage"]["instructions"]
assert payload["candidate_task_frames"][0]["task_id"] == "task_purchase_a3"
assert payload["candidate_task_frames"][1]["task_id"] == "task_purchase_a1"
return {
@@ -166,7 +167,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- assert "task scheduler" in system_prompt
+ assert "task scheduler" in payload["_agent_stage"]["instructions"]
assert payload["completed_reply"] == "购买流程已完成。"
assert len(payload["candidate_task_frames"]) == 1
candidate = payload["candidate_task_frames"][0]
@@ -276,7 +277,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- assert "不要编造 target_skill_id" in system_prompt
+ assert "不要编造 target_skill_id" in payload["_agent_stage"]["instructions"]
return {
"decision": "clarify",
"target_skill_id": "skill_weather_query",
@@ -306,7 +307,7 @@ def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- assert "禁止填写 `message_content`" in system_prompt
+ assert "禁止填写 `message_content`" in payload["_agent_stage"]["instructions"]
return {
"decision": "continue_active",
"target_skill_id": "purchase",
diff --git a/backend/tests/test_skill_distiller_generic.py b/backend/tests/test_skill_distiller_generic.py
index ccdbaf3b9..de00aaf6f 100644
--- a/backend/tests/test_skill_distiller_generic.py
+++ b/backend/tests/test_skill_distiller_generic.py
@@ -1,3 +1,5 @@
+import json
+
from app.skills.skill_distiller import SkillDistiller
from app.skills.skill_schema import SkillDistillRequest
@@ -69,6 +71,50 @@ def test_fallback_card_is_not_domain_hardcoded_for_commerce_text() -> None:
)
+def test_model_input_uses_plain_text_and_compacts_available_tools() -> None:
+ request = SkillDistillRequest(
+ tenant_id="tenant_demo",
+ title="新SOP",
+ raw_content="差旅报销申请,收集事由和金额后提交审批。",
+ available_tools=[
+ {
+ "id": "tool_internal_id",
+ "name": "expense.submit",
+ "display_name": "提交报销单",
+ "description": "提交差旅报销申请。",
+ "method": "POST",
+ "url": "http://localhost:5173/api/mock/expense/submit",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "reason": {"type": "string", "description": "报销事由"},
+ "amount": {"type": "number", "description": "报销金额"},
+ },
+ "required": ["reason", "amount"],
+ },
+ "output_schema": {
+ "type": "object",
+ "properties": {"request_id": {"type": "string"}},
+ },
+ }
+ ],
+ )
+ distiller = SkillDistiller()
+
+ payload = distiller._payload(request) # noqa: SLF001
+ model_input = distiller._model_input(request, payload) # noqa: SLF001
+
+ projected_tool = payload["available_tools"][0]
+ assert set(projected_tool) == {"name", "display_name", "description", "input_schema"}
+ assert "output_schema" not in json.dumps(payload, ensure_ascii=False)
+ assert "tool_internal_id" not in model_input
+ assert "localhost:5173" not in model_input
+ assert model_input.startswith("技能标题:新SOP\n原始流程:")
+ assert "expense.submit(提交报销单)" in model_input
+ assert "reason (string, 必填)" in model_input
+ assert not model_input.lstrip().startswith("{")
+
+
def test_slot_policy_targets_model_generated_fields() -> None:
request = SkillDistillRequest(
tenant_id="tenant_demo",
diff --git a/backend/tests/test_skill_editing_and_stats.py b/backend/tests/test_skill_editing_and_stats.py
index 2a124ee0a..e19cbf722 100644
--- a/backend/tests/test_skill_editing_and_stats.py
+++ b/backend/tests/test_skill_editing_and_stats.py
@@ -269,11 +269,11 @@ def test_skill_editor_applies_patch_response_without_full_draft() -> None:
def test_skill_editor_stream_repairs_invalid_json_once(monkeypatch) -> None:
def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
yield '{"assistant_message": "截断的输出", "patches": ['
def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
if payload.get("reflection_round"):
return _reflection_passes_json()
assert "previous_error" in payload
@@ -1015,8 +1015,11 @@ def test_skill_read_preserves_graph_node_ids() -> None:
def test_skill_distiller_stream_uses_generation_status(monkeypatch) -> None:
- def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ def fake_stream(self, _system_prompt: str, _payload: str): # noqa: ANN001
+ assert self.max_output_tokens == 8192
+ assert isinstance(_payload, str)
+ assert _payload.startswith("技能标题:商品比价\n原始流程:")
+ assert not _payload.lstrip().startswith("{")
yield """
{
"draft_skill": {
@@ -1060,7 +1063,7 @@ def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
"""
def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
assert payload.get("reflection_round") == 1
return _reflection_passes_json()
@@ -1089,7 +1092,7 @@ def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
def test_skill_distiller_stream_reflects_and_repairs_generated_skill(monkeypatch) -> None:
def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
yield json.dumps(
{
"draft_skill": {
@@ -1121,7 +1124,7 @@ def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
)
def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
if payload.get("reflection_round") == 1:
revised = dict(payload["candidate_skill"])
revised["nodes"] = [
@@ -1182,7 +1185,7 @@ def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
def test_skill_distiller_reflection_checks_tool_call_format_without_rule_fallback(monkeypatch) -> None:
def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
yield json.dumps(
{
"draft_skill": {
@@ -1222,7 +1225,7 @@ def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
)
def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
if payload.get("reflection_round") == 1:
rubric_names = {item["name"] for item in payload["rubrics"]}
assert "tool_call_format" in rubric_names
@@ -1293,11 +1296,11 @@ def test_skill_reflection_prompt_keeps_new_candidate_tool_actions() -> None:
def test_skill_distiller_stream_repairs_invalid_json_with_model(monkeypatch) -> None:
def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
yield '{"draft_skill": {"name": "截断"'
def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
if payload.get("reflection_round"):
return _reflection_passes_json()
assert payload["repair_attempt"] == 1
@@ -1367,11 +1370,11 @@ def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
def test_skill_distiller_stream_uses_staged_generation_after_repair_failure(monkeypatch) -> None:
def fake_stream(self, _system_prompt: str, _payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
yield '{"draft_skill": {"name": "截断"'
def fake_text(self, _system_prompt: str, payload: dict): # noqa: ANN001
- assert self.max_output_tokens == 16384
+ assert self.max_output_tokens == 8192
if payload.get("reflection_round"):
return _reflection_passes_json()
if "repair_instruction" in payload:
diff --git a/backend/tests/test_step_agent_model_driven.py b/backend/tests/test_step_agent_model_driven.py
index 2269ffc0d..53dd8cad9 100644
--- a/backend/tests/test_step_agent_model_driven.py
+++ b/backend/tests/test_step_agent_model_driven.py
@@ -67,20 +67,22 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
)
assert captured["payload"]["active_skill"]["skill_id"] == "repair_ticket"
- assert "技能节点是业务目标" in captured["system_prompt"]
+ assert "统一执行引擎" in captured["system_prompt"]
+ assert "技能节点是业务目标" in captured["payload"]["_agent_stage"]["instructions"]
assert captured["payload"]["active_skill"]["current_step"]["node_id"] == (
"collect_issue"
)
- assert captured["payload"]["active_skill"]["adjacent_edges"] == [
- {"source_node_id": "collect_issue", "next_node_id": "reply_ticket"}
- ]
assert [
- step["node_id"] for step in captured["payload"]["active_skill"]["target_steps"]
+ step["node_id"] for step in captured["payload"]["active_skill"]["next_steps"]
] == ["reply_ticket"]
+ assert "nodes" not in captured["payload"]["active_skill"]
+ assert "edges" not in captured["payload"]["active_skill"]
+ assert "adjacent_edges" not in captured["payload"]["active_skill"]
+ assert "target_steps" not in captured["payload"]["active_skill"]
assert "active_step" not in captured["payload"]
assert captured["payload"]["router_decision"]["user_intent"] == "设备报修"
assert "recent_messages" not in captured["payload"]
- assert captured["payload"]["memory_context"] == "- 张三"
+ assert captured["payload"]["_agent_stage"]["memory"] == "- 张三"
assert captured["payload"]["awaiting_input"]["question_summary"] == "请描述设备问题。"
assert "repair_context" in captured["payload"]
assert result.slot_updates["asset_id"] == "EQ-9"
@@ -119,7 +121,7 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
ChatSession(
id="session_test",
tenant_id="tenant_demo",
- knowledge_context_json=[knowledge_result],
+ knowledge_context_json=[{"evidence_pack": [{"content": "上一轮旧知识"}]}],
),
None,
[],
@@ -129,17 +131,20 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
"knowledge_results": knowledge_result,
},
recent_messages=[{"role": "user", "content": "设备无法启动"}],
+ current_knowledge=[knowledge_result],
)
assert "recent_messages" not in captured["payload"]
assert "knowledge_results" not in captured["payload"]["repair_context"]
assert captured["payload"]["repair_context"]["knowledge_results_available_in"] == (
- "knowledge_context"
+ "retrieved_knowledge"
)
- compacted = captured["payload"]["knowledge_context"][0]
+ compacted = captured["payload"]["retrieved_knowledge"][0]
assert "chunks" not in compacted
assert "expanded_sections" not in compacted
- assert len(compacted["evidence_pack"][0]["content"]) <= 803
+ assert "selected_documents" not in compacted
+ assert "上一轮旧知识" not in str(captured["payload"])
+ assert len(compacted["retrieved_knowledge"][0]["content"]) <= 803
def _repair_skill() -> Skill:
diff --git a/backend/tests/test_unified_agent_prompt.py b/backend/tests/test_unified_agent_prompt.py
new file mode 100644
index 000000000..2fcc2980b
--- /dev/null
+++ b/backend/tests/test_unified_agent_prompt.py
@@ -0,0 +1,100 @@
+from app.core.reflection_agent import ReflectionAgent
+from app.core.response_generator import ResponseGenerator
+from app.core.router import Router
+from app.core.step_agent import StepAgent
+from app.db.models import ChatSession
+from app.llm import LLMClient
+from app.session.session_schema import StepAgentResult
+from app.tools.tool_schema import ToolCall
+
+
+def test_four_agent_stages_use_identical_system_and_stage_local_user_content(
+ monkeypatch,
+) -> None:
+ systems: dict[str, str] = {}
+ payloads: dict[str, dict] = {}
+
+ def fake_init(self, model_config): # noqa: ANN001
+ return None
+
+ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
+ phase = payload["_agent_stage"]["phase"]
+ systems[phase] = system_prompt
+ payloads[phase] = payload
+ if phase == "Router":
+ return {"decision": "answer_only", "confidence": 0.9}
+ if phase == "Step Agent":
+ return {"reply": "正在处理", "is_step_completed": False}
+ if phase == "Reflection":
+ return {"action": "pass", "needs_retry": False}
+ raise AssertionError(f"unexpected phase: {phase}")
+
+ def fake_generate_text(self, system_prompt, payload): # noqa: ANN001
+ phase = payload["_agent_stage"]["phase"]
+ systems[phase] = system_prompt
+ payloads[phase] = payload
+ return "最终回复"
+
+ monkeypatch.setattr(LLMClient, "__init__", fake_init)
+ monkeypatch.setattr(LLMClient, "generate_json", fake_generate_json)
+ monkeypatch.setattr(LLMClient, "generate_text", fake_generate_text)
+
+ session = ChatSession(id="session_test", tenant_id="tenant_demo")
+ context = {
+ "messages": [{"role": "user", "content": "当前问题"}],
+ "metadata": {"current_turn_time": "2026-07-13T20:45:00+08:00"},
+ }
+ memory = [{"content": "用户偏好简洁回答", "id": "internal_memory_id"}]
+ router_decision = Router().decide(
+ "当前问题",
+ session,
+ [],
+ model_config=None, # type: ignore[arg-type]
+ conversation_context=context,
+ memory_context=memory,
+ )
+ step_result = StepAgent().run(
+ "当前问题",
+ session,
+ None,
+ [],
+ model_config=None, # type: ignore[arg-type]
+ router_decision=router_decision,
+ conversation_context=context,
+ memory_context=memory,
+ )
+ ReflectionAgent().review(
+ "当前问题",
+ session,
+ None,
+ router_decision,
+ StepAgentResult(tool_call=ToolCall(name="demo", arguments={})),
+ None,
+ [],
+ [],
+ model_config=None, # type: ignore[arg-type]
+ conversation_context=context,
+ memory_context=memory,
+ )
+ ResponseGenerator().generate(
+ "当前问题",
+ session,
+ None,
+ router_decision,
+ step_result,
+ None,
+ model_config=None, # type: ignore[arg-type]
+ memory_context=memory,
+ conversation_context=context,
+ )
+
+ assert set(systems) == {"Router", "Step Agent", "Reflection", "Response Generator"}
+ assert len(set(systems.values())) == 1
+ assert "统一执行引擎" in next(iter(systems.values()))
+ for phase, payload in payloads.items():
+ assert payload["_agent_stage"]["memory"] == "- 用户偏好简洁回答"
+ assert payload["_agent_stage"]["turn_time"] == "2026-07-13T20:45:00+08:00"
+ assert payload["user_message"] == "当前问题"
+ assert "internal_memory_id" not in str(payload)
+ assert payload["_agent_stage"]["instructions"]
+ assert payload["_agent_stage"]["output_contract"]
diff --git a/frontend-enterprise/src/pages/chat/chatHelpers.tsx b/frontend-enterprise/src/pages/chat/chatHelpers.tsx
index 48e86cf02..639fa6edb 100644
--- a/frontend-enterprise/src/pages/chat/chatHelpers.tsx
+++ b/frontend-enterprise/src/pages/chat/chatHelpers.tsx
@@ -177,11 +177,26 @@ export function renderInlineMarkdown(text: string, keyPrefix: string): ReactNode
return nodes;
}
-function renderInlineLines(lines: string[], keyPrefix: string): ReactNode[] {
+function softLineBreakSeparator(previousLine: string, currentLine: string): string {
+ const previous = previousLine.trimEnd();
+ const current = currentLine.trimStart();
+ if (!previous || !current) return '';
+
+ const previousCharacter = previous.charAt(previous.length - 1);
+ const currentCharacter = current.charAt(0);
+ const cjkCharacter = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
+ return cjkCharacter.test(previousCharacter) || cjkCharacter.test(currentCharacter) ? '' : ' ';
+}
+
+function renderInlineLines(lines: string[], keyPrefix: string, preserveLineBreaks: boolean): ReactNode[] {
return lines.flatMap((line, lineIndex) => {
- const nodes = renderInlineMarkdown(line, `${keyPrefix}-line-${lineIndex}`);
+ const renderedLine = preserveLineBreaks ? line : line.trim();
+ const nodes = renderInlineMarkdown(renderedLine, `${keyPrefix}-line-${lineIndex}`);
if (lineIndex === 0) return nodes;
- return [ , ...nodes];
+ const separator = preserveLineBreaks
+ ?
+ : softLineBreakSeparator(lines[lineIndex - 1], line);
+ return [separator, ...nodes];
});
}
@@ -299,7 +314,7 @@ function isBlockBoundary(line: string): boolean {
);
}
-export function renderMarkdownBlocks(content: string): ReactNode[] {
+export function renderMarkdownBlocks(content: string, preserveLineBreaks = true): ReactNode[] {
const lines = content.replace(/\r\n/g, '\n').split('\n');
const blocks: ReactNode[] = [];
let index = 0;
@@ -353,7 +368,7 @@ export function renderMarkdownBlocks(content: string): ReactNode[] {
quoteLines.push(lines[index].trim().replace(/^>\s?/, ''));
index += 1;
}
- blocks.push({renderMarkdownBlocks(quoteLines.join('\n'))} );
+ blocks.push({renderMarkdownBlocks(quoteLines.join('\n'), preserveLineBreaks)} );
blockIndex += 1;
continue;
}
@@ -410,15 +425,21 @@ export function renderMarkdownBlocks(content: string): ReactNode[] {
paragraphLines.push(lines[index]);
index += 1;
}
- blocks.push({renderInlineLines(paragraphLines, key)}
);
+ blocks.push({renderInlineLines(paragraphLines, key, preserveLineBreaks)}
);
blockIndex += 1;
}
return blocks;
}
-export function MarkdownMessage({ content }: { content: string }) {
- return {renderMarkdownBlocks(content)}
;
+export function MarkdownMessage({
+ content,
+ preserveLineBreaks = true,
+}: {
+ content: string;
+ preserveLineBreaks?: boolean;
+}) {
+ return {renderMarkdownBlocks(content, preserveLineBreaks)}
;
}
export function traceSummaryIconName(_summary: { state: TraceLine['state'] }): CotTraceIconName {
@@ -884,6 +905,7 @@ function publicStreamPhase(data: Record): string {
const phase = typeof data.phase === 'string' ? data.phase : '';
const text = typeof data.text === 'string' ? data.text : '';
if (phase === 'error') return text || '请求失败';
+ if (phase === 'preparing') return text || '正在整理上下文';
if (phase === 'scheduled_task_draft') return text || '生成定时任务草案';
if (isKnowledgeTracePhase(phase)) return text || knowledgeTraceText(data);
return '正在思考';
diff --git a/frontend-enterprise/src/pages/chat/chatPageStyles.ts b/frontend-enterprise/src/pages/chat/chatPageStyles.ts
index ed6e6277d..205797d67 100644
--- a/frontend-enterprise/src/pages/chat/chatPageStyles.ts
+++ b/frontend-enterprise/src/pages/chat/chatPageStyles.ts
@@ -46,9 +46,6 @@ export const CHAT_BUBBLE_ASSISTANT_CLASS =
export const CHAT_BUBBLE_USER_CLASS =
'rounded-[14px] bg-[#f6f6f6] px-[16px] py-[11px] text-[#18181a]';
export const CHAT_BUBBLE_ERROR_CLASS = 'border-[#f38989] bg-[#fce7e7] text-[#d20b0b]';
-export const CHAT_BUBBLE_STREAMING_PLACEHOLDER_CLASS =
- 'inline-grid h-[42px] w-[48px] max-w-[48px] place-items-center px-0 py-0';
-
export function chatRowClass(role: 'user' | 'assistant' | 'system' | 'tool'): string {
return cn(
CHAT_MESSAGE_ROW_BASE_CLASS,
@@ -71,9 +68,6 @@ export const CHAT_MESSAGE_MODE_CHIP_CLASS =
export const CHAT_QUEUED_STATUS_ROW_CLASS = 'mt-[5px] flex justify-end pr-[2px]';
export const CHAT_QUEUED_STATUS_CLASS =
'inline-flex items-center gap-[4px] text-[11px] font-medium leading-[1.4] text-[#858b9c]';
-export const CHAT_TYPING_CARET_CLASS =
- 'inline-block h-[15px] w-[2px] translate-y-[2px] animate-pulse bg-[#18181a]';
-
// ---------------------------------------------------------------------------
// Markdown answer (styled via child selectors, code delegates to CodeBlock)
// ---------------------------------------------------------------------------
@@ -264,15 +258,15 @@ export const CHAT_HANDOFF_BLOCK_CLASS =
export const CHAT_HANDOFF_ACTIONS_CLASS = 'flex justify-end gap-[8px]';
export const CHAT_HANDOFF_EMPTY_CLASS = 'py-[36px] text-center text-[13px] text-[#858b9c]';
-export const CHAT_CITATION_DETAIL_CLASS = 'grid gap-[14px]';
+export const CHAT_CITATION_DETAIL_CLASS = 'grid w-full min-w-0 gap-[14px]';
export const CHAT_CITATION_DETAIL_EYEBROW_CLASS = 'text-[12px] font-medium text-[#858b9c]';
export const CHAT_CITATION_DETAIL_TITLE_CLASS = 'text-[18px] font-semibold text-[#18181a]';
export const CHAT_CITATION_DETAIL_SECTION_CLASS =
- 'grid gap-[5px] [&>span]:text-[12px] [&>span]:font-medium [&>span]:text-[#757f9c] [&>p]:text-[13px] [&>p]:leading-[1.7] [&>p]:text-[#464c5e]';
+ 'grid w-full min-w-0 gap-[5px] [&>span]:text-[12px] [&>span]:font-medium [&>span]:text-[#757f9c] [&>p]:text-[13px] [&>p]:leading-[1.7] [&>p]:text-[#464c5e]';
export const CHAT_CITATION_DETAIL_QUOTE_CLASS =
'm-0 max-h-[min(52vh,520px)] overflow-y-auto overscroll-contain rounded-[10px] border-l-[3px] border-[#e3e7f1] bg-[#fafbfc] px-[12px] py-[8px] text-[13px] leading-[1.7] whitespace-pre-wrap wrap-anywhere text-[#464c5e]';
export const CHAT_CITATION_DETAIL_MARKDOWN_CLASS =
- 'max-h-[min(52vh,520px)] min-w-0 max-w-full overflow-y-auto overscroll-contain rounded-[10px] border-l-[3px] border-[#e3e7f1] bg-[#fafbfc] px-[12px] py-[8px] [&>div]:text-[13px] [&>div]:leading-[1.7] [&>div]:text-[#464c5e] [&_h1]:text-[16px] [&_h2]:text-[15px] [&_h3]:text-[14px] [&_h4]:text-[13px] [&_p]:wrap-anywhere [&_li]:wrap-anywhere [&_code]:wrap-anywhere [&_a]:wrap-anywhere';
+ 'max-h-[min(52vh,520px)] w-full min-w-0 max-w-full overflow-y-auto overscroll-contain rounded-[10px] border-l-[3px] border-[#e3e7f1] bg-[#fafbfc] px-[12px] py-[8px] [&>div]:w-full [&>div]:min-w-0 [&>div]:max-w-none [&>div]:text-[13px] [&>div]:leading-[1.7] [&>div]:text-[#464c5e] [&_h1]:text-[16px] [&_h2]:text-[15px] [&_h3]:text-[14px] [&_h4]:text-[13px] [&_p]:wrap-anywhere [&_li]:wrap-anywhere [&_code]:wrap-anywhere [&_a]:wrap-anywhere';
export const CHAT_CITATION_DETAIL_GRID_CLASS =
'grid grid-cols-2 gap-[12px] max-[520px]:grid-cols-1 [&>div]:grid [&>div]:gap-[3px] [&_span]:text-[11px] [&_span]:text-[#858b9c] [&_strong]:text-[13px] [&_strong]:font-medium [&_strong]:text-[#18181a]';
export const CHAT_CITATION_DETAIL_NOTE_CLASS = 'text-[12px] leading-[1.6] text-[#858b9c]';
diff --git a/frontend-enterprise/src/pages/chat/components/ChatDialogs.tsx b/frontend-enterprise/src/pages/chat/components/ChatDialogs.tsx
index 43ca4503d..a9c256162 100644
--- a/frontend-enterprise/src/pages/chat/components/ChatDialogs.tsx
+++ b/frontend-enterprise/src/pages/chat/components/ChatDialogs.tsx
@@ -240,7 +240,7 @@ export default function ChatDialogs({ chat }: { chat: UseChatSession }) {
function CitationMarkdown({ content }: { content: string }) {
return (
-
+
);
}
diff --git a/frontend-enterprise/src/pages/chat/components/MessageBubble.tsx b/frontend-enterprise/src/pages/chat/components/MessageBubble.tsx
index 1689657db..e398d117b 100644
--- a/frontend-enterprise/src/pages/chat/components/MessageBubble.tsx
+++ b/frontend-enterprise/src/pages/chat/components/MessageBubble.tsx
@@ -16,7 +16,6 @@ import {
CHAT_ATTACHMENT_LIST_CLASS,
CHAT_ATTACHMENT_META_CLASS,
CHAT_ATTACHMENT_NAME_CLASS,
- CHAT_BUBBLE_STREAMING_PLACEHOLDER_CLASS,
CHAT_CITATION_CHIP_CLASS,
CHAT_CITATION_HEADING_CLASS,
CHAT_CITATION_INDEX_CLASS,
@@ -32,7 +31,6 @@ import {
CHAT_PLAIN_ANSWER_CLASS,
CHAT_QUEUED_STATUS_CLASS,
CHAT_QUEUED_STATUS_ROW_CLASS,
- CHAT_TYPING_CARET_CLASS,
chatBubbleClass,
chatRowClass,
} from '../chatPageStyles';
@@ -60,7 +58,6 @@ export type MessageRender = {
scheduledTaskPrompt: boolean;
attachments: ChatAttachmentRead[];
statusOnly: boolean;
- showTypingCaret: boolean;
};
type MessageBubbleProps = {
@@ -84,21 +81,14 @@ export default function MessageBubble({ chat, item, render }: MessageBubbleProps
scheduledTaskPrompt,
attachments,
statusOnly,
- showTypingCaret,
} = render;
const queuedMessage = item.role === 'user' && item.metadata?.queued === true;
- const compactStreamingPlaceholder = Boolean(
- item.role === 'assistant' && showTypingCaret && !showInlineTrace && !visibleContent,
- );
return (
{statusOnly ? (
{visibleContent}
@@ -128,8 +118,6 @@ export default function MessageBubble({ chat, item, render }: MessageBubbleProps
{visibleContent}
)
- ) : showTypingCaret ? (
-
) : null}
{!statusOnly && attachments.length > 0 && (
diff --git a/frontend-enterprise/src/pages/chat/components/MessageList.tsx b/frontend-enterprise/src/pages/chat/components/MessageList.tsx
index d3846ca9d..4075721da 100644
--- a/frontend-enterprise/src/pages/chat/components/MessageList.tsx
+++ b/frontend-enterprise/src/pages/chat/components/MessageList.tsx
@@ -98,9 +98,10 @@ export default function MessageList({ chat }: { chat: UseChatSession }) {
expandedTraceIds.includes(traceTurnId)
|| (defaultExpanded && !collapsedTraceIds.includes(traceTurnId)),
);
- const visibleContent = staffdeckDisplayText(
+ const rawVisibleContent = staffdeckDisplayText(
item.role === 'assistant' ? stripTrailingCitationSummary(item.content) : item.content,
);
+ const visibleContent = normalizeMessageText(rawVisibleContent) ? rawVisibleContent : '';
const citations = item.role === 'assistant' ? knowledgeCitations(item, visibleContent) : [];
const scheduledTaskPrompt = isScheduledTaskPrompt(item);
const scheduledDraft = item.role === 'assistant' && !dismissedDraftMessageIds.includes(item.id)
@@ -126,7 +127,7 @@ export default function MessageList({ chat }: { chat: UseChatSession }) {
&& !scheduledDraft
&& !persistedCreatedTask
&& citations.length === 0
- && !item.isStreaming
+ && attachments.length === 0
) {
return null;
}
@@ -144,7 +145,6 @@ export default function MessageList({ chat }: { chat: UseChatSession }) {
scheduledTaskPrompt,
attachments,
statusOnly,
- showTypingCaret: !statusOnly && item.role === 'assistant' && Boolean(item.isStreaming) && !summary,
};
return
;
diff --git a/frontend-enterprise/src/pages/chat/useChatSession.ts b/frontend-enterprise/src/pages/chat/useChatSession.ts
index dcd473ffc..19a28f49a 100644
--- a/frontend-enterprise/src/pages/chat/useChatSession.ts
+++ b/frontend-enterprise/src/pages/chat/useChatSession.ts
@@ -1036,7 +1036,13 @@ export function useChatSession() {
stream.turnId = recoveredRunningTurnId;
stream.loading = true;
stream.phase = stream.phase || '正在思考';
- storeChanged = upsertStreamingTracePlaceholder(slot, id, recoveredRunningTurnId) || storeChanged;
+ const recoveredTrace = turnTraceRef.current.get(recoveredRunningTurnId);
+ const hasVisibleTrace = Boolean(recoveredTrace?.lines.some((line) => (
+ !line.provisional && !line.placeholder && Boolean(normalizeMessageText(line.text))
+ )));
+ if (hasVisibleTrace) {
+ storeChanged = upsertStreamingTracePlaceholder(slot, id, recoveredRunningTurnId) || storeChanged;
+ }
setExpandedTraceIds((expanded) => (expanded.includes(recoveredRunningTurnId) ? expanded : [...expanded, recoveredRunningTurnId]));
setCollapsedTraceIds((collapsed) => collapsed.filter((item) => item !== recoveredRunningTurnId));
} else if (stream.turnId && !stream.loading) {
@@ -1236,7 +1242,7 @@ export function useChatSession() {
notifyFeedback();
}, [getSlot, notifyFeedback]);
- const updateStreaming = useCallback((id: string, text: string, turnId?: string, allowEmpty = false) => {
+ const updateStreaming = useCallback((id: string, text: string, turnId?: string) => {
const slot = getSlot(id);
const stream = getStreamSlot(id);
const activeTurnId = turnId || stream.turnId || undefined;
@@ -1259,7 +1265,7 @@ export function useChatSession() {
&& canonicalMessageTurnId(item, aliasMap) === activeCanonicalTurnId
)
));
- if (!text && index < 0 && !allowEmpty) return;
+ if (!normalizeMessageText(text) && index < 0) return;
const previousMessage = index >= 0 ? slot.realtimeMessages[index] : undefined;
const previousCanonicalTurnId = previousMessage ? canonicalMessageTurnId(previousMessage, aliasMap) : undefined;
const previousCreatedAt = previousMessage && previousCanonicalTurnId === activeCanonicalTurnId
@@ -1302,8 +1308,19 @@ export function useChatSession() {
if (!turnId) return;
const stream = getStreamSlot(id);
if (!stream.loading) return;
- updateStreaming(id, stream.accumulated || '', turnId, true);
- }, [getStreamSlot, updateStreaming]);
+ const trace = turnTraceRef.current.get(turnId);
+ const hasVisibleTrace = Boolean(trace?.lines.some((line) => (
+ !line.provisional && !line.placeholder && Boolean(normalizeMessageText(line.text))
+ )));
+ if (normalizeMessageText(stream.accumulated)) {
+ updateStreaming(id, stream.accumulated, turnId);
+ return;
+ }
+ if (!hasVisibleTrace) return;
+ if (upsertStreamingTracePlaceholder(getSlot(id), id, turnId)) {
+ notifyStore();
+ }
+ }, [getSlot, getStreamSlot, notifyStore, updateStreaming]);
const flushStreaming = useCallback((id: string) => {
const stream = getStreamSlot(id);
@@ -1658,6 +1675,12 @@ export function useChatSession() {
const ownsStreamTurn = Boolean(eventStream.turnId)
&& (eventStream.turnId === traceTurnId || eventStream.turnId === turnId);
const shouldTouchStream = !options?.preserveExistingStreamTurn || ownsStreamTurn;
+ const upsertVisibleTraceLine = (line: TraceLine) => {
+ upsertTraceLine(traceTurnId, line);
+ if (shouldTouchStream && traceTurnId) {
+ ensureStreamingTraceMessage(eventSessionId, traceTurnId);
+ }
+ };
if (item.event === 'session_created') return;
if (item.event === 'heartbeat') return;
if (item.event === 'session_title_summarized') {
@@ -1673,10 +1696,7 @@ export function useChatSession() {
if (shouldTouchStream && eventStream.turnId !== traceTurnId) {
eventStream.turnId = traceTurnId;
}
- if (shouldTouchStream) {
- ensureStreamingTraceMessage(eventSessionId, traceTurnId);
- }
- scheduledTaskTraceLines(draft).forEach((line) => upsertTraceLine(traceTurnId, line));
+ scheduledTaskTraceLines(draft).forEach(upsertVisibleTraceLine);
finishTrace(traceTurnId);
notifyStream();
}
@@ -1686,16 +1706,13 @@ export function useChatSession() {
if (shouldTouchStream && eventStream.turnId !== traceTurnId) {
eventStream.turnId = traceTurnId;
}
- if (shouldTouchStream) {
- ensureStreamingTraceMessage(eventSessionId, traceTurnId);
- }
}
if (item.event === 'router_decision') {
- upsertTraceLine(traceTurnId, routerDecisionTraceLine(item.data));
+ upsertVisibleTraceLine(routerDecisionTraceLine(item.data));
return;
}
if (item.event === 'step_result') {
- upsertTraceLine(traceTurnId, stepResultTraceLine(item.data));
+ upsertVisibleTraceLine(stepResultTraceLine(item.data));
return;
}
if (item.event === 'skill_state') {
@@ -1705,7 +1722,7 @@ export function useChatSession() {
.filter((entry): entry is NonNullable
=> Boolean(entry))
.forEach((skill) => {
const label = streamSkillLabel(item.data, skill);
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: `skill_${skill.skillId}_${skill.state || 'active'}`,
kind: 'skill',
text: `${label} ${skill.name || skill.skillId}`,
@@ -1719,7 +1736,7 @@ export function useChatSession() {
if (item.event === 'general_skill_state') {
const skillName = typeof item.data.skillName === 'string' ? item.data.skillName : '';
const skillSlug = typeof item.data.skillSlug === 'string' ? item.data.skillSlug : '';
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: `general_skill_${skillSlug || skillName || 'selected'}`,
kind: 'skill',
text: `选择通用技能 ${skillName || skillSlug || ''}`.trim(),
@@ -1754,7 +1771,7 @@ export function useChatSession() {
const outputInfo = generalSkillTraceOutput(item.data, phase, detail);
const codePhases = new Set(['plan_created', 'plan_failed', 'attempt_started', 'running_code', 'stdout_chunk', 'stderr_chunk', 'code_finished', 'code_timeout']);
const runningPhases = new Set(['planning', 'repair_planning', 'attempt_started', 'running_code', 'reflection_reviewing', 'replying']);
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id,
kind: codePhases.has(phase) ? 'code' : 'decision',
text,
@@ -1775,7 +1792,7 @@ export function useChatSession() {
return;
}
if (item.event === 'knowledge_result') {
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: 'knowledge_lookup',
kind: 'knowledge',
text: '读取知识库',
@@ -1788,7 +1805,7 @@ export function useChatSession() {
if (item.event === 'tool_result') {
const tool = normalizeTraceTool(item.data);
if (tool) {
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: `tool_${tool.toolCallId || tool.rawToolName || tool.toolId}`,
kind: 'tool',
text: `${tool.isError ? '工具调用失败' : '调用工具'} ${tool.toolName}`,
@@ -1802,7 +1819,7 @@ export function useChatSession() {
if (item.event === 'agent_loop_continued' || item.event === 'agent_loop_completed') {
const iteration = typeof item.data.iteration === 'number' || typeof item.data.iteration === 'string' ? String(item.data.iteration) : '1';
const targetTool = typeof item.data.target_tool_name === 'string' ? item.data.target_tool_name : '';
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: `decision_stepping_tool_continuation_${iteration}`,
kind: 'decision',
text: '重新分析',
@@ -1817,7 +1834,7 @@ export function useChatSession() {
if (item.event === 'reflection_decision') {
const needsRetry = item.data.needs_retry === true;
const skipped = item.data.skipped === true;
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: 'reflection',
kind: 'decision',
text: skipped ? '反思已关闭' : needsRetry ? '反思后继续尝试' : '反思通过',
@@ -1841,17 +1858,17 @@ export function useChatSession() {
}
const scheduledTaskLine = scheduledTaskStatusTraceLine(phase, item.data);
if (scheduledTaskLine) {
- upsertTraceLine(traceTurnId, scheduledTaskLine);
+ upsertVisibleTraceLine(scheduledTaskLine);
} else if (phase === 'error') {
- upsertTraceLine(traceTurnId, streamErrorTraceLine(item.data, 'error_occurred'));
+ upsertVisibleTraceLine(streamErrorTraceLine(item.data, 'error_occurred'));
finishTrace(traceTurnId, true);
} else if (phase === 'tool' && typeof item.data.tool_name === 'string') {
const toolCallId = typeof item.data.tool_call_id === 'string' ? item.data.tool_call_id : item.data.tool_name;
- upsertTraceLine(traceTurnId, { id: `tool_${toolCallId}`, kind: 'tool', text: `正在调用 ${item.data.tool_name}`, state: 'running', icon: 'tool' });
+ upsertVisibleTraceLine({ id: `tool_${toolCallId}`, kind: 'tool', text: `正在调用 ${item.data.tool_name}`, state: 'running', icon: 'tool' });
} else if (phase === 'routing') {
- upsertTraceLine(traceTurnId, { id: 'decision_router', kind: 'decision', text: '判断意图', state: 'running', icon: 'judge', provisional: true });
+ upsertVisibleTraceLine({ id: 'decision_router', kind: 'decision', text: '判断意图', state: 'running', icon: 'judge' });
} else if (isKnowledgeTracePhase(phase)) {
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: 'knowledge_lookup',
kind: 'knowledge',
text: knowledgeTraceText(item.data),
@@ -1862,7 +1879,7 @@ export function useChatSession() {
} else if (phase === 'stepping') {
const repairReason = typeof item.data.repair_reason === 'string' ? item.data.repair_reason : 'main';
const iteration = typeof item.data.iteration === 'number' || typeof item.data.iteration === 'string' ? `_${item.data.iteration}` : '';
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: `decision_stepping_${repairReason}${iteration}`,
kind: 'decision',
text: repairReason === 'main' ? '决定下一步' : '重新分析',
@@ -1870,9 +1887,9 @@ export function useChatSession() {
icon: repairReason === 'main' ? 'advance' : 'loading',
});
} else if (phase === 'reflecting') {
- upsertTraceLine(traceTurnId, { id: 'reflection', kind: 'decision', text: '正在反思', state: 'running', icon: 'loading' });
+ upsertVisibleTraceLine({ id: 'reflection', kind: 'decision', text: '正在反思', state: 'running', icon: 'loading' });
} else if (phase !== 'received') {
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: `decision_status_${phase}`,
kind: 'decision',
text: shouldTouchStream ? eventStream.phase : publicStreamPhase(item.data),
@@ -1908,9 +1925,10 @@ export function useChatSession() {
}
}
if (next === previous) return;
- const wasEmpty = !previous;
+ const hadVisibleText = Boolean(normalizeMessageText(previous));
eventStream.accumulated = next;
- if (wasEmpty) {
+ if (!normalizeMessageText(next)) return;
+ if (!hadVisibleText) {
updateStreaming(eventSessionId, eventStream.accumulated, eventStream.turnId || traceTurnId);
notifyStream();
return;
@@ -1998,7 +2016,7 @@ export function useChatSession() {
clearStreamSlot(eventSessionId, true);
eventStream.relayRecoveryStartedAt = null;
eventStream.relayRecoveryTurnId = null;
- upsertTraceLine(traceTurnId, streamErrorTraceLine(item.data, item.event));
+ upsertVisibleTraceLine(streamErrorTraceLine(item.data, item.event));
window.setTimeout(() => {
loadMessages(eventSessionId);
loadTraces(eventSessionId);
@@ -2022,7 +2040,7 @@ export function useChatSession() {
const userIntent = typeof result.router_decision?.user_intent === 'string' ? result.router_decision.user_intent : '';
const decisionReason = typeof result.router_decision?.reason === 'string' ? result.router_decision.reason : '';
if (userIntent || decisionReason) {
- upsertTraceLine(traceTurnId, {
+ upsertVisibleTraceLine({
id: 'decision_router',
kind: 'decision',
text: userIntent ? `判断意图 ${userIntent}` : '完成SOP判断',
@@ -2191,8 +2209,8 @@ export function useChatSession() {
stream.accumulated = text;
stream.relayRecoveryStartedAt = stream.relayRecoveryStartedAt || Date.now();
stream.relayRecoveryTurnId = turnId;
- if (streamChanged) {
- updateStreaming(id, text, turnId, true);
+ if (streamChanged && normalizeMessageText(text)) {
+ updateStreaming(id, text, turnId);
}
setRunningTurn((current) => (
current?.sessionId === id && current.turnId === turnId
@@ -2260,7 +2278,7 @@ export function useChatSession() {
});
if (recoveredText && recoveredText !== stream.accumulated) {
stream.accumulated = recoveredText;
- updateStreaming(id, recoveredText, recoveringTurnId, true);
+ updateStreaming(id, recoveredText, recoveringTurnId);
notifyStream();
}
const hasTerminalRecoveryEvent = recoveryEvents.some((event) => isTerminalSessionEvent(event, isTerminalEvent));
@@ -2348,7 +2366,9 @@ export function useChatSession() {
}
stream.loading = true;
stream.phase = '执行中';
- updateStreaming(id, stream.accumulated || '', eventTurnId, true);
+ if (normalizeMessageText(stream.accumulated)) {
+ updateStreaming(id, stream.accumulated, eventTurnId);
+ }
notifyStream();
}
handleStreamEvent(streamEvent, id, eventTurnId, { preserveExistingStreamTurn: true });
@@ -2530,7 +2550,6 @@ export function useChatSession() {
setExpandedTraceIds((current) => (current.includes(turnId) ? current : [...current, turnId]));
stream.loading = true;
stream.phase = '正在思考';
- updateStreaming(currentConversationId, '', turnId, true);
setRunningTurn({ sessionId: currentConversationId, turnId });
notifyStream();
@@ -2691,7 +2710,9 @@ export function useChatSession() {
activeStream.turnId = activeTurnId;
activeStream.relayRecoveryStartedAt = activeStream.relayRecoveryStartedAt || Date.now();
activeStream.relayRecoveryTurnId = activeTurnId;
- updateStreaming(targetSessionId, activeStream.accumulated || '', activeTurnId, true);
+ if (normalizeMessageText(activeStream.accumulated)) {
+ updateStreaming(targetSessionId, activeStream.accumulated, activeTurnId);
+ }
setRunningTurn((current) => (
current?.sessionId === targetSessionId && current.turnId === activeTurnId
? current
From 5d0be6f4779baf43f009aed99303cc2adae80481 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Mon, 13 Jul 2026 22:45:26 +0800
Subject: [PATCH 003/309] refactor: streamline agent stages and thinking
feedback
---
backend/app/core/agent_loop.py | 688 ++++++++----------
backend/app/core/context_projection.py | 75 +-
backend/app/core/response_generator.py | 29 +-
backend/app/core/router.py | 90 +--
backend/app/core/step_agent.py | 187 ++++-
backend/app/general_skills/runner.py | 174 ++++-
backend/app/llm/client.py | 233 +++++-
backend/app/llm/output_policy.py | 2 -
.../app/llm/prompts/memory_reranker_prompt.md | 19 -
backend/app/llm/prompts/router_prompt.md | 8 +-
.../step_agent_awaiting_input_rules.md | 1 +
.../prompts/step_agent_general_skill_rules.md | 1 +
.../llm/prompts/step_agent_knowledge_rules.md | 1 +
backend/app/llm/prompts/step_agent_prompt.md | 72 +-
.../llm/prompts/step_agent_repair_rules.md | 1 +
.../step_agent_tool_continuation_rules.md | 1 +
.../app/llm/prompts/step_agent_tool_rules.md | 1 +
.../app/llm/prompts/task_scheduler_prompt.md | 39 -
.../app/llm/prompts/unified_agent_prompt.md | 2 +-
backend/app/llm/stage_protocol.py | 86 ++-
backend/app/memory/service.py | 131 +---
backend/app/session/session_schema.py | 18 +-
backend/tests/test_agent_loop_completion.py | 133 ++--
backend/tests/test_context_projection.py | 10 +-
backend/tests/test_general_skills.py | 87 ++-
backend/tests/test_llm_client.py | 130 +++-
backend/tests/test_memory_service.py | 32 +
backend/tests/test_reflection_agent_loop.py | 12 +-
backend/tests/test_response_generator.py | 39 +
backend/tests/test_router.py | 111 +--
backend/tests/test_step_agent_model_driven.py | 20 +-
backend/tests/test_unified_agent_prompt.py | 109 ++-
frontend-enterprise/src/styles.css | 10 +-
33 files changed, 1557 insertions(+), 995 deletions(-)
delete mode 100644 backend/app/llm/prompts/memory_reranker_prompt.md
create mode 100644 backend/app/llm/prompts/step_agent_awaiting_input_rules.md
create mode 100644 backend/app/llm/prompts/step_agent_general_skill_rules.md
create mode 100644 backend/app/llm/prompts/step_agent_knowledge_rules.md
create mode 100644 backend/app/llm/prompts/step_agent_repair_rules.md
create mode 100644 backend/app/llm/prompts/step_agent_tool_continuation_rules.md
create mode 100644 backend/app/llm/prompts/step_agent_tool_rules.md
delete mode 100644 backend/app/llm/prompts/task_scheduler_prompt.md
diff --git a/backend/app/core/agent_loop.py b/backend/app/core/agent_loop.py
index 62dc636a7..c6a2f2ef4 100644
--- a/backend/app/core/agent_loop.py
+++ b/backend/app/core/agent_loop.py
@@ -74,7 +74,6 @@
ChatTurnRequest,
ChatTurnResponse,
KnowledgeQuery,
- PendingTask,
RouterDecision,
StepAgentResult,
)
@@ -237,7 +236,7 @@ class PreparedTurn:
@dataclass
-class TaskScheduleContinuation:
+class QueuedTaskContinuation:
reply: str
active_skill: Skill | None
router_decision: RouterDecision
@@ -387,12 +386,41 @@ def handle_turn(self, request: ChatTurnRequest) -> ChatTurnResponse:
tool_result,
)
if finalize_state == "completed":
- self.events.record(
- request.tenant_id,
- chat_session.id,
- "pending_tasks_waiting",
- {"pending_tasks": chat_session.pending_tasks_json or []},
+ continuation = self._try_continue_pending_after_completion(
+ request,
+ chat_session,
+ prepared.model_config,
+ self._list_published_skills(request.tenant_id, chat_session.agent_id),
+ self._tools_with_general_skills(
+ request.tenant_id,
+ self._list_enabled_tools(
+ request.tenant_id, chat_session.agent_id
+ ),
+ chat_session.agent_id,
+ ),
+ self._get_persona_prompt(
+ request.tenant_id, chat_session.agent_id
+ ),
+ memory_context,
+ conversation_context,
+ reply,
)
+ if continuation:
+ reply = "\n\n".join(
+ part
+ for part in (reply.strip(), continuation.reply.strip())
+ if part
+ )
+ router_decision = continuation.router_decision
+ step_result = continuation.step_result
+ tool_result = continuation.tool_result
+ else:
+ self.events.record(
+ request.tenant_id,
+ chat_session.id,
+ "pending_tasks_waiting",
+ {"pending_tasks": chat_session.pending_tasks_json or []},
+ )
except AgentLoopPreconditionError as exc:
chat_session = chat_session or self._get_or_create_session(request)
@@ -466,7 +494,11 @@ def _try_handle_general_skill_after_scene_router(
if not self._scene_router_deferred_to_general(router_decision):
return None
capability = capability or self._select_general_capability(
- request.message, model_config, chat_session.agent_id
+ request.message,
+ model_config,
+ chat_session.agent_id,
+ conversation_context,
+ memory_context,
)
skill, selection = capability
if skill is None:
@@ -502,7 +534,12 @@ def _try_handle_general_skill_after_scene_router(
),
)
run_response = self.general_skill_runner.run(
- skill, request.message, model_config, request.user_id
+ skill,
+ request.message,
+ model_config,
+ request.user_id,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
self._record_general_skill_run_events(
request.tenant_id, chat_session, run_response, user_message_id
@@ -529,7 +566,11 @@ def _try_handle_general_skill_after_scene_router(
model_config,
self._get_persona_prompt(request.tenant_id, chat_session.agent_id),
memory_context or [],
- conversation_context or self._conversation_context(chat_session),
+ (
+ conversation_context
+ if conversation_context is not None
+ else self._conversation_context(chat_session)
+ ),
)
self._finalize_turn(
chat_session,
@@ -750,6 +791,8 @@ def general_skill_worker() -> None:
model_snapshot,
request.user_id,
event_sink=general_skill_sink,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
general_skill_events.put(("complete", response))
except Exception as exc: # pragma: no cover - defensive stream boundary
@@ -836,7 +879,11 @@ def general_skill_worker() -> None:
if persona_prompt is not None
else self._get_persona_prompt(request.tenant_id, chat_session.agent_id),
memory_context or [],
- conversation_context or self._conversation_context(chat_session),
+ (
+ conversation_context
+ if conversation_context is not None
+ else self._conversation_context(chat_session)
+ ),
):
reply += chunk
yield self._stream_event(
@@ -919,46 +966,33 @@ def _stream_continue_pending_after_completion(
step_result = StepAgentResult()
tool_result: ToolResult | None = None
- for schedule_round in range(max_actions):
+ for queue_round in range(max_actions):
if not chat_session.pending_tasks_json:
break
+ task_id = self._next_pending_task_id(chat_session)
+ if not task_id:
+ break
yield self._stream_status(
chat_session,
"routing",
- "正在规划后续任务",
- {"schedule_round": schedule_round + 1},
+ "正在继续后续任务",
+ {"queue_round": queue_round + 1},
user_message_id=user_message_id,
)
- schedule = self.router.schedule_tasks_after_completion(
- request.message,
- chat_session,
- skills,
- model_config,
- conversation_context,
- memory_context,
- completed_reply="\n\n".join([completed_reply, *replies]).strip(),
- )
self.events.record(
request.tenant_id,
chat_session.id,
- "task_scheduler_decision_created",
- {**schedule.model_dump(mode="json"), "round": schedule_round + 1},
+ "router_execution_order_advanced",
+ {"task_id": task_id, "queue_round": queue_round + 1},
)
- yield self._stream_event(
- "task_schedule",
- chat_session,
- {**schedule.model_dump(mode="json"), "round": schedule_round + 1},
- )
- if schedule.action != "run_tasks" or not schedule.selected_task_ids:
- break
- for task_id in schedule.selected_task_ids:
+ for task_id in [task_id]:
if executed_actions >= max_actions:
break
router_decision = self._router_decision_from_task_frame(
chat_session,
task_id,
- schedule.reason,
+ "按 Router 已确定的任务顺序继续执行。",
)
if not router_decision:
continue
@@ -1044,6 +1078,8 @@ def _stream_continue_pending_after_completion(
model_config,
step_result,
tool_stream_events,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
for event_name, payload in tool_stream_events:
yield self._stream_event(
@@ -1159,7 +1195,7 @@ def _stream_continue_pending_after_completion(
self._turn_payload({"content": chunk}, user_message_id),
)
self._pace_stream()
- replies, replaced_reply = self._merge_scheduled_reply_segment(replies, segment)
+ replies, replaced_reply = self._merge_queued_reply_segment(replies, segment)
if replaced_reply:
yield self._stream_event(
"stream_replace",
@@ -1180,21 +1216,21 @@ def _stream_continue_pending_after_completion(
if finalize_state == "completed" and active_skill:
completed_skill_ids_this_turn.add(active_skill.skill_id)
if finalize_state == "handoff":
- return self._scheduled_continuation(
+ return self._queued_continuation(
replies, active_skill, router_decision, step_result, tool_result
)
if finalize_state == "continued":
- if self._should_attempt_scheduled_task_followup(
+ if self._should_attempt_queued_task_followup(
request,
chat_session,
skills,
"\n\n".join([completed_reply, *replies]).strip(),
- schedule_round + 1,
+ queue_round + 1,
):
if active_skill:
completed_skill_ids_this_turn.add(active_skill.skill_id)
continue
- return self._scheduled_continuation(
+ return self._queued_continuation(
replies, active_skill, router_decision, step_result, tool_result
)
self.events.record(
@@ -1203,13 +1239,13 @@ def _stream_continue_pending_after_completion(
"pending_tasks_waiting",
{
"pending_tasks": chat_session.pending_tasks_json or [],
- "round": schedule_round + 1,
+ "round": queue_round + 1,
},
)
if executed_actions >= max_actions:
break
- return self._scheduled_continuation(
+ return self._queued_continuation(
replies, active_skill, router_decision, step_result, tool_result
)
@@ -1445,11 +1481,18 @@ def stream_failure_response(
persona_prompt = self._get_persona_prompt(request.tenant_id, chat_session.agent_id)
self._drop_unavailable_skill_state(request.tenant_id, chat_session, skills)
if not skills:
+ no_skill_context = self._conversation_context(
+ chat_session, model_config=model_config
+ )
yield self._stream_status(
chat_session, "routing", "正在判断用户意图", user_message_id=user_message_id
)
capability = self._select_general_capability(
- request.message, model_config, chat_session.agent_id
+ request.message,
+ model_config,
+ chat_session.agent_id,
+ no_skill_context,
+ [],
)
if capability[0] is not None:
yield from self._stream_general_skill_response(
@@ -1459,7 +1502,7 @@ def stream_failure_response(
(capability[0], capability[1]),
None,
[],
- self._conversation_context(chat_session),
+ no_skill_context,
persona_prompt,
user_message.id,
mark_current_turn_cancelled,
@@ -1501,7 +1544,7 @@ def stream_failure_response(
model_config,
persona_prompt,
[],
- self._conversation_context(chat_session),
+ no_skill_context,
):
reply += chunk
yield self._stream_event(
@@ -1536,11 +1579,9 @@ def stream_failure_response(
self._finish_stale_completed_skill(request.tenant_id, chat_session, skills)
memory_context = [
memory_read(row)
- for row in self.memory.recall(
+ for row in self.memory.context_memories(
request.tenant_id,
request.user_id,
- request.message,
- model_config=model_config,
agent_id=chat_session.agent_id,
)
]
@@ -1590,7 +1631,11 @@ def stream_failure_response(
capability_selection: GeneralSkillSelection | None = None
if self._scene_router_deferred_to_general(router_decision):
capability = self._select_general_capability(
- request.message, model_config, chat_session.agent_id
+ request.message,
+ model_config,
+ chat_session.agent_id,
+ conversation_context,
+ memory_context,
)
capability_selection = capability[1]
if capability[0] is not None:
@@ -1608,111 +1653,6 @@ def stream_failure_response(
)
return
- initial_schedule_decision = self._initial_scheduler_queue_decision(
- request,
- chat_session,
- router_decision,
- )
- if initial_schedule_decision:
- self.runtime.apply_decision(chat_session, initial_schedule_decision)
- self._release_active_task_to_scheduler(chat_session, initial_schedule_decision)
- self._drop_unavailable_skill_state(request.tenant_id, chat_session, skills)
- self.events.record(
- request.tenant_id,
- chat_session.id,
- "task_frames_seeded_for_scheduler",
- initial_schedule_decision.model_dump(mode="json"),
- )
- self.db.commit()
- self.db.refresh(chat_session)
- continuation = yield from self._stream_continue_pending_after_completion(
- request,
- chat_session,
- model_config,
- skills,
- tools,
- persona_prompt,
- memory_context,
- conversation_context,
- "",
- user_message_id=user_message_id,
- )
- if continuation:
- reply = continuation.reply
- active_skill = continuation.active_skill
- router_decision = continuation.router_decision
- step_result = continuation.step_result
- tool_result = continuation.tool_result
- else:
- router_decision = initial_schedule_decision
- yield self._stream_event(
- "router_decision",
- chat_session,
- self._turn_payload(
- router_decision.model_dump(mode="json"), user_message_id
- ),
- )
- yield self._stream_status(
- chat_session, "responding", "正在生成回复", user_message_id=user_message_id
- )
- chunks: list[str] = []
- for chunk in self._generate_reply_stream_segment(
- request.message,
- chat_session,
- None,
- router_decision,
- StepAgentResult(),
- None,
- model_config,
- persona_prompt,
- memory_context,
- conversation_context,
- ):
- chunks.append(chunk)
- yield self._stream_event(
- "stream_delta",
- chat_session,
- self._turn_payload({"content": chunk}, user_message_id),
- )
- self._pace_stream()
- reply = "".join(chunks).strip() or FALLBACK_REPLY
- if not chunks:
- for chunk in self.response_generator.chunk_text(reply):
- yield self._stream_event(
- "stream_delta",
- chat_session,
- self._turn_payload({"content": chunk}, user_message_id),
- )
- self._pace_stream()
- yield self._stream_event(
- "stream_end", chat_session, self._turn_payload({}, user_message_id)
- )
- finalize_turn_once(chat_session, reply, step_result, request.message)
- self.db.commit()
- self.db.refresh(chat_session)
- if memory_model_config:
- self._enqueue_memory_capture(
- request,
- chat_session,
- step_result,
- tool_result,
- memory_model_config,
- )
- result = ChatTurnResponse(
- reply=reply,
- session_id=chat_session.id,
- router_decision=router_decision,
- step_result=step_result,
- tool_result=tool_result,
- session_state=public_session(chat_session),
- )
- yield self._stream_event(
- "complete",
- chat_session,
- self._turn_payload(result.model_dump(mode="json"), user_message_id),
- )
- return
-
before_skill = chat_session.active_skill_id
before_step = chat_session.active_step_id
self.runtime.apply_decision(chat_session, router_decision)
@@ -1863,6 +1803,8 @@ def stream_failure_response(
model_config,
step_result,
tool_stream_events,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
for event_name, payload in tool_stream_events:
yield self._stream_event(
@@ -1973,12 +1915,43 @@ def stream_failure_response(
tool_result,
)
if finalize_state == "completed":
- self.events.record(
- request.tenant_id,
- chat_session.id,
- "pending_tasks_waiting",
- {"pending_tasks": chat_session.pending_tasks_json or []},
- )
+ continuation = None
+ if self._next_pending_task_id(chat_session):
+ separator = "\n\n"
+ yield self._stream_event(
+ "stream_delta",
+ chat_session,
+ self._turn_payload({"content": separator}, user_message_id),
+ )
+ continuation = yield from self._stream_continue_pending_after_completion(
+ request,
+ chat_session,
+ model_config,
+ skills,
+ tools,
+ persona_prompt,
+ memory_context,
+ conversation_context,
+ reply,
+ user_message_id=user_message_id,
+ )
+ if continuation:
+ reply = "\n\n".join(
+ part
+ for part in (reply.strip(), continuation.reply.strip())
+ if part
+ )
+ active_skill = continuation.active_skill
+ router_decision = continuation.router_decision
+ step_result = continuation.step_result
+ tool_result = continuation.tool_result
+ else:
+ self.events.record(
+ request.tenant_id,
+ chat_session.id,
+ "pending_tasks_waiting",
+ {"pending_tasks": chat_session.pending_tasks_json or []},
+ )
if mark_current_turn_cancelled():
return
yield self._stream_event(
@@ -2160,8 +2133,15 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
raise AgentLoopPreconditionError("missing_model_config", "没有默认模型配置。")
self._drop_unavailable_skill_state(request.tenant_id, chat_session, skills)
if not skills:
+ no_skill_context = self._conversation_context(
+ chat_session, model_config=model_config
+ )
capability = self._select_general_capability(
- request.message, model_config, chat_session.agent_id
+ request.message,
+ model_config,
+ chat_session.agent_id,
+ no_skill_context,
+ [],
)
router_decision = RouterDecision(
decision="answer_only",
@@ -2173,7 +2153,7 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
model_config,
router_decision,
[],
- self._conversation_context(chat_session),
+ no_skill_context,
user_message.id,
capability,
)
@@ -2186,7 +2166,7 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
step_result=StepAgentResult(),
tool_result=None,
memory_context=[],
- conversation_context=self._conversation_context(chat_session),
+ conversation_context=no_skill_context,
general_response=general_response,
user_message_id=user_message.id,
)
@@ -2206,17 +2186,15 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
step_result=step_result,
tool_result=None,
memory_context=[],
- conversation_context=self._conversation_context(chat_session),
+ conversation_context=no_skill_context,
user_message_id=user_message.id,
)
self._finish_stale_completed_skill(request.tenant_id, chat_session, skills)
memory_context = [
memory_read(row)
- for row in self.memory.recall(
+ for row in self.memory.context_memories(
request.tenant_id,
request.user_id,
- request.message,
- model_config=model_config,
agent_id=chat_session.agent_id,
)
]
@@ -2259,7 +2237,11 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
capability: tuple[GeneralSkill | None, GeneralSkillSelection] | None = None
if self._scene_router_deferred_to_general(router_decision):
capability = self._select_general_capability(
- request.message, model_config, chat_session.agent_id
+ request.message,
+ model_config,
+ chat_session.agent_id,
+ conversation_context,
+ memory_context,
)
general_response = self._try_handle_general_skill_after_scene_router(
request,
@@ -2285,59 +2267,6 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
user_message_id=user_message.id,
)
- initial_schedule_decision = self._initial_scheduler_queue_decision(
- request,
- chat_session,
- router_decision,
- )
- if initial_schedule_decision:
- self.runtime.apply_decision(chat_session, initial_schedule_decision)
- self._release_active_task_to_scheduler(chat_session, initial_schedule_decision)
- self._drop_unavailable_skill_state(request.tenant_id, chat_session, skills)
- self.events.record(
- request.tenant_id,
- chat_session.id,
- "task_frames_seeded_for_scheduler",
- initial_schedule_decision.model_dump(mode="json"),
- )
- self.db.commit()
- self.db.refresh(chat_session)
- continuation = self._try_continue_pending_after_completion(
- request,
- chat_session,
- model_config,
- skills,
- tools,
- self._get_persona_prompt(request.tenant_id, chat_session.agent_id),
- memory_context,
- conversation_context,
- "",
- )
- if continuation:
- return PreparedTurn(
- chat_session=chat_session,
- model_config=model_config,
- active_skill=continuation.active_skill,
- router_decision=continuation.router_decision,
- step_result=continuation.step_result,
- tool_result=continuation.tool_result,
- memory_context=memory_context,
- conversation_context=conversation_context,
- reply_override=continuation.reply,
- user_message_id=user_message.id,
- )
- return PreparedTurn(
- chat_session=chat_session,
- model_config=model_config,
- active_skill=None,
- router_decision=initial_schedule_decision,
- step_result=StepAgentResult(),
- tool_result=None,
- memory_context=memory_context,
- conversation_context=conversation_context,
- user_message_id=user_message.id,
- )
-
before_skill = chat_session.active_skill_id
before_step = chat_session.active_step_id
self.runtime.apply_decision(chat_session, router_decision)
@@ -2418,6 +2347,8 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
model_config,
step_result,
status_callback=status,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
(
@@ -2709,139 +2640,6 @@ def _generate_reply_stream_segment(
conversation_context,
)
- def _initial_scheduler_queue_decision(
- self,
- request: ChatTurnRequest,
- chat_session: ChatSession,
- router_decision: RouterDecision,
- ) -> RouterDecision | None:
- tasks: list[PendingTask] = [*router_decision.pending_tasks, *router_decision.created_tasks]
- existing_selected_count = 0
- if router_decision.decision == "switch_to_pending" and router_decision.selected_task_id:
- existing_selected_count = (
- 1 if self._find_task_frame(chat_session, router_decision.selected_task_id) else 0
- )
- primary_task = self._primary_task_from_router_decision(
- request, chat_session, router_decision
- )
- active_task = self._active_task_for_scheduler(
- request, chat_session, router_decision, primary_task
- )
- if active_task:
- tasks = [active_task, *tasks]
- if primary_task:
- tasks = [primary_task, *tasks]
- if len(tasks) + existing_selected_count < 2:
- return None
- return RouterDecision(
- decision="create_pending",
- confidence=router_decision.confidence,
- user_intent=router_decision.user_intent,
- reason=(
- "本轮包含多个由 Router 明确识别的任务,先写入 task frame,"
- "再交给 scheduler 决定执行顺序。"
- ),
- source_message=router_decision.source_message or request.message,
- pending_tasks=tasks,
- task_updates=router_decision.task_updates,
- )
-
- def _active_task_for_scheduler(
- self,
- request: ChatTurnRequest,
- chat_session: ChatSession,
- router_decision: RouterDecision,
- primary_task: PendingTask | None,
- ) -> PendingTask | None:
- if not chat_session.active_skill_id or not primary_task:
- return None
- if primary_task.target_skill_id == chat_session.active_skill_id:
- return None
- if router_decision.decision != "start_new_task":
- return None
- active_task_id = None
- if isinstance(chat_session.awaiting_input_json, dict):
- raw_task_id = chat_session.awaiting_input_json.get("task_id")
- active_task_id = str(raw_task_id) if raw_task_id else None
- if active_task_id:
- for update in router_decision.task_updates:
- if update.task_id == active_task_id and (
- update.remove or update.status in {"removed", "completed", "cancelled"}
- ):
- return None
- return PendingTask(
- task_id=active_task_id or new_id("task"),
- status="pending",
- decision="continue_active",
- target_skill_id=chat_session.active_skill_id,
- target_step_id=chat_session.active_step_id,
- confidence=router_decision.confidence,
- user_intent="继续当前未完成任务,并从本轮用户消息中提取与该任务相关的信息。",
- reason=(
- "Router 在已有 active task 时选择了另一个新任务;"
- "保留当前 active task 给 scheduler,由 scheduler 决定本轮是否以及何时继续。"
- ),
- source_message=request.message,
- slot_hints=dict(chat_session.slots_json or {}),
- )
-
- def _release_active_task_to_scheduler(
- self,
- chat_session: ChatSession,
- scheduler_queue_decision: RouterDecision,
- ) -> None:
- active_skill_id = chat_session.active_skill_id
- active_step_id = chat_session.active_step_id
- if not active_skill_id:
- return
- for task in scheduler_queue_decision.pending_tasks:
- if task.target_skill_id != active_skill_id:
- continue
- if task.target_step_id and active_step_id and task.target_step_id != active_step_id:
- continue
- chat_session.active_skill_id = None
- chat_session.active_step_id = None
- chat_session.slots_json = {}
- chat_session.awaiting_input_json = None
- return
-
- def _primary_task_from_router_decision(
- self,
- request: ChatTurnRequest,
- chat_session: ChatSession,
- router_decision: RouterDecision,
- ) -> PendingTask | None:
- if router_decision.decision in {
- "answer_only",
- "clarify",
- "create_pending",
- "update_pending",
- "complete_task",
- "handoff_human",
- "switch_to_pending",
- }:
- return None
- skill_id = router_decision.target_skill_id or chat_session.active_skill_id
- if not skill_id:
- return None
- step_id = router_decision.target_step_id or chat_session.active_step_id
- slots: dict[str, Any] = {}
- if skill_id == chat_session.active_skill_id and isinstance(chat_session.slots_json, dict):
- slots.update(chat_session.slots_json)
- slots.update(dict(router_decision.slot_hints or {}))
- return PendingTask(
- task_id=router_decision.selected_task_id or new_id("task"),
- status="pending",
- decision="start_new_task",
- target_skill_id=skill_id,
- target_step_id=step_id,
- confidence=router_decision.confidence,
- user_intent=router_decision.user_intent,
- reason=router_decision.reason,
- source_message=router_decision.source_message or request.message,
- slot_hints=slots,
- )
-
def _try_continue_pending_after_completion(
self,
request: ChatTurnRequest,
@@ -2854,7 +2652,7 @@ def _try_continue_pending_after_completion(
conversation_context: dict[str, object],
completed_reply: str,
completed_skill_ids_this_turn: set[str] | None = None,
- ) -> TaskScheduleContinuation | None:
+ ) -> QueuedTaskContinuation | None:
if not chat_session.pending_tasks_json:
return None
max_actions = max(1, self._get_agent_loop_max_actions(request.tenant_id))
@@ -2866,34 +2664,26 @@ def _try_continue_pending_after_completion(
step_result = StepAgentResult()
tool_result: ToolResult | None = None
- for schedule_round in range(max_actions):
+ for queue_round in range(max_actions):
if not chat_session.pending_tasks_json:
break
- schedule = self.router.schedule_tasks_after_completion(
- request.message,
- chat_session,
- skills,
- model_config,
- conversation_context,
- memory_context,
- completed_reply="\n\n".join([completed_reply, *replies]).strip(),
- )
+ task_id = self._next_pending_task_id(chat_session)
+ if not task_id:
+ break
self.events.record(
request.tenant_id,
chat_session.id,
- "task_scheduler_decision_created",
- {**schedule.model_dump(mode="json"), "round": schedule_round + 1},
+ "router_execution_order_advanced",
+ {"task_id": task_id, "queue_round": queue_round + 1},
)
- if schedule.action != "run_tasks" or not schedule.selected_task_ids:
- break
- for task_id in schedule.selected_task_ids:
+ for task_id in [task_id]:
if executed_actions >= max_actions:
break
router_decision = self._router_decision_from_task_frame(
chat_session,
task_id,
- schedule.reason,
+ "按 Router 已确定的任务顺序继续执行。",
)
if not router_decision:
continue
@@ -2939,6 +2729,8 @@ def _try_continue_pending_after_completion(
tools,
model_config,
step_result,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
(
@@ -2993,7 +2785,7 @@ def _try_continue_pending_after_completion(
conversation_context,
)
if segment:
- replies, _replaced_reply = self._merge_scheduled_reply_segment(replies, segment)
+ replies, _replaced_reply = self._merge_queued_reply_segment(replies, segment)
executed_actions += 1
finalize_state = self._finalize_execution_after_reply(
request.tenant_id,
@@ -3006,21 +2798,21 @@ def _try_continue_pending_after_completion(
if finalize_state == "completed" and active_skill:
completed_skill_ids_this_turn.add(active_skill.skill_id)
if finalize_state == "handoff":
- return self._scheduled_continuation(
+ return self._queued_continuation(
replies, active_skill, router_decision, step_result, tool_result
)
if finalize_state == "continued":
- if self._should_attempt_scheduled_task_followup(
+ if self._should_attempt_queued_task_followup(
request,
chat_session,
skills,
"\n\n".join([completed_reply, *replies]).strip(),
- schedule_round + 1,
+ queue_round + 1,
):
if active_skill:
completed_skill_ids_this_turn.add(active_skill.skill_id)
continue
- return self._scheduled_continuation(
+ return self._queued_continuation(
replies, active_skill, router_decision, step_result, tool_result
)
self.events.record(
@@ -3029,27 +2821,27 @@ def _try_continue_pending_after_completion(
"pending_tasks_waiting",
{
"pending_tasks": chat_session.pending_tasks_json or [],
- "round": schedule_round + 1,
+ "round": queue_round + 1,
},
)
if executed_actions >= max_actions:
break
- return self._scheduled_continuation(
+ return self._queued_continuation(
replies, active_skill, router_decision, step_result, tool_result
)
- def _scheduled_continuation(
+ def _queued_continuation(
self,
replies: list[str],
active_skill: Skill | None,
router_decision: RouterDecision,
step_result: StepAgentResult,
tool_result: ToolResult | None,
- ) -> TaskScheduleContinuation | None:
+ ) -> QueuedTaskContinuation | None:
if not replies:
return None
- return TaskScheduleContinuation(
+ return QueuedTaskContinuation(
reply="\n\n".join(replies).strip(),
active_skill=active_skill,
router_decision=router_decision,
@@ -3057,7 +2849,7 @@ def _scheduled_continuation(
tool_result=tool_result,
)
- def _should_attempt_scheduled_task_followup(
+ def _should_attempt_queued_task_followup(
self,
request: ChatTurnRequest,
chat_session: ChatSession,
@@ -3095,7 +2887,7 @@ def _should_attempt_scheduled_task_followup(
)
return True
- def _merge_scheduled_reply_segment(
+ def _merge_queued_reply_segment(
self, replies: list[str], segment: str
) -> tuple[list[str], bool]:
clean_segment = str(segment or "").strip()
@@ -3107,7 +2899,7 @@ def _router_decision_from_task_frame(
self,
chat_session: ChatSession,
task_id: str,
- scheduler_reason: str | None = None,
+ order_reason: str | None = None,
) -> RouterDecision | None:
frame = self._find_task_frame(chat_session, task_id)
if not frame:
@@ -3127,7 +2919,7 @@ def _router_decision_from_task_frame(
target_step_id=frame.get("step_id") or frame.get("target_step_id"),
confidence=float(frame.get("confidence") or 0.0),
user_intent=frame.get("intent_summary") or frame.get("user_intent"),
- reason=scheduler_reason or frame.get("reason"),
+ reason=order_reason or frame.get("reason"),
source_message=frame.get("source_message"),
slot_hints=slot_hints,
)
@@ -3138,6 +2930,19 @@ def _find_task_frame(self, chat_session: ChatSession, task_id: str) -> dict[str,
return frame
return None
+ def _next_pending_task_id(self, chat_session: ChatSession) -> str | None:
+ for frame in chat_session.pending_tasks_json or []:
+ if not isinstance(frame, dict):
+ continue
+ if str(frame.get("status") or "pending") != "pending":
+ continue
+ if not (frame.get("skill_id") or frame.get("target_skill_id")):
+ continue
+ task_id = str(frame.get("task_id") or "").strip()
+ if task_id:
+ return task_id
+ return None
+
def _run_reflection_rounds(
self,
request: ChatTurnRequest,
@@ -3155,7 +2960,8 @@ def _run_reflection_rounds(
completed_skill_ids_this_turn: set[str] | None = None,
memory_context: list[dict[str, object]] | None = None,
) -> tuple[Skill | None, RouterDecision, StepAgentResult, ToolResult | None]:
- conversation_context = conversation_context or self._conversation_context(chat_session)
+ if conversation_context is None:
+ conversation_context = self._conversation_context(chat_session)
completed_skill_ids_this_turn = completed_skill_ids_this_turn or set()
rounds = max(0, min(max_rounds, REFLECTION_MAX_ROUNDS_LIMIT))
if rounds <= 0:
@@ -3231,7 +3037,8 @@ def _auto_progress_skill_graph(
stream_events: list[tuple[str, dict[str, object]]] | None = None,
completed_skill_ids_this_turn: set[str] | None = None,
) -> tuple[Skill | None, RouterDecision, StepAgentResult, ToolResult | None]:
- conversation_context = conversation_context or self._conversation_context(chat_session)
+ if conversation_context is None:
+ conversation_context = self._conversation_context(chat_session)
completed_skill_ids_this_turn = completed_skill_ids_this_turn or set()
max_actions = max(1, self._get_agent_loop_max_actions(request.tenant_id))
for iteration in range(max_actions):
@@ -3327,6 +3134,8 @@ def _auto_progress_skill_graph(
model_config,
step_result,
tool_events,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
self.db.commit()
self.db.refresh(chat_session)
@@ -3383,7 +3192,8 @@ def _reflect_and_retry(
completed_skill_ids_this_turn: set[str] | None = None,
memory_context: list[dict[str, object]] | None = None,
) -> tuple[Skill | None, RouterDecision, StepAgentResult, ToolResult | None, bool]:
- conversation_context = conversation_context or self._conversation_context(chat_session)
+ if conversation_context is None:
+ conversation_context = self._conversation_context(chat_session)
completed_skill_ids_this_turn = completed_skill_ids_this_turn or set()
if not self._should_try_reflection(router_decision, step_result, tool_result):
return active_skill, router_decision, step_result, tool_result, False
@@ -3454,6 +3264,8 @@ def _reflect_and_retry(
stream_events,
tools,
model_config,
+ conversation_context,
+ memory_context,
)
return (*retry_result, True)
@@ -3474,6 +3286,7 @@ def _reflect_and_retry(
model_config,
conversation_context,
stream_events,
+ memory_context,
)
return (*retry_result, True)
@@ -3488,6 +3301,8 @@ def _reflect_and_retry(
stream_events,
tools,
model_config,
+ conversation_context,
+ memory_context,
)
return (*retry_result, True)
@@ -3514,6 +3329,8 @@ def _retry_with_reflection_tool_call(
stream_events: list[tuple[str, dict[str, object]]] | None = None,
tools: list[Tool] | None = None,
model_config: ModelConfig | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> tuple[Skill | None, RouterDecision, StepAgentResult, ToolResult | None]:
retry_step_result = StepAgentResult(
tool_call=retry_tool_call,
@@ -3538,6 +3355,8 @@ def _retry_with_reflection_tool_call(
model_config,
retry_step_result,
stream_events,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
return active_skill, router_decision, retry_step_result, retry_tool_result
@@ -3562,6 +3381,7 @@ def _retry_with_router_decision(
model_config: ModelConfig,
conversation_context: dict[str, object],
stream_events: list[tuple[str, dict[str, object]]] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> tuple[Skill | None, RouterDecision, StepAgentResult, ToolResult | None]:
self.events.record(
request.tenant_id,
@@ -3629,6 +3449,7 @@ def _retry_with_router_decision(
tools,
model_config,
router_decision,
+ memory_context=memory_context,
conversation_context=conversation_context,
stream_events=stream_events,
)
@@ -3645,6 +3466,8 @@ def _retry_with_router_decision(
model_config,
step_result,
stream_events,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
return active_skill, router_decision, step_result, tool_result
@@ -3670,6 +3493,8 @@ def _execute_tool_action_cycle(
step_result: StepAgentResult,
stream_events: list[tuple[str, dict[str, object]]] | None = None,
status_callback: StatusCallback | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> tuple[StepAgentResult, ToolResult | None]:
tool_result: ToolResult | None = None
current_knowledge = list(step_result.knowledge_results or [])
@@ -3710,6 +3535,8 @@ def _execute_tool_action_cycle(
tool_call,
tool_call_id,
stream_events=stream_events,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
self._record_tool_result_in_slots(chat_session, tool_call, tool_result)
if stream_events is not None:
@@ -3753,6 +3580,8 @@ def _execute_tool_action_cycle(
chat_session,
iteration + 1,
),
+ memory_context=memory_context,
+ conversation_context=conversation_context,
current_knowledge=current_knowledge,
)
if current_knowledge and not continuation_result.knowledge_results:
@@ -4110,7 +3939,8 @@ def _run_step_agent_with_context_repair(
conversation_context: dict[str, object] | None = None,
stream_events: list[tuple[str, dict[str, object]]] | None = None,
) -> StepAgentResult:
- conversation_context = conversation_context or self._conversation_context(chat_session)
+ if conversation_context is None:
+ conversation_context = self._conversation_context(chat_session)
step_result = self._run_step_agent_once(
request,
chat_session,
@@ -4269,7 +4099,8 @@ def _run_step_agent_once(
conversation_context: dict[str, object] | None = None,
current_knowledge: list[dict[str, object]] | None = None,
) -> StepAgentResult:
- conversation_context = conversation_context or self._conversation_context(chat_session)
+ if conversation_context is None:
+ conversation_context = self._conversation_context(chat_session)
recent_messages = [
message
for message in conversation_context.get("messages", [])
@@ -4285,6 +4116,10 @@ def _run_step_agent_once(
request.message,
model_config,
chat_session.agent_id,
+ conversation_context,
+ memory_context,
+ active_step_id=chat_session.active_step_id,
+ slots=chat_session.slots_json,
),
model_config=model_config,
router_decision=router_decision,
@@ -4312,9 +4147,30 @@ def _step_agent_tools(
user_message: str | None = None,
model_config: ModelConfig | None = None,
agent_id: str | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
+ *,
+ active_step_id: str | None = None,
+ slots: dict[str, object] | None = None,
) -> list[Tool]:
if active_skill is None:
return []
+ current_step = self._current_skill_step(active_skill, active_step_id)
+ if not current_step:
+ return []
+ actions = {
+ str(action).strip()
+ for action in current_step.get("allowed_actions") or []
+ if str(action).strip()
+ }
+ explicit_tool_names = {
+ action.split(":", 1)[1]
+ for action in actions
+ if action.startswith("call_tool:") and ":" in action
+ }
+ allow_any_tool = "call_tool" in actions
+ if not explicit_tool_names and not allow_any_tool:
+ return []
active_skill_id = active_skill.skill_id
scoped_tools: list[Tool] = []
general_skill_tools: list[Tool] = []
@@ -4322,6 +4178,8 @@ def _step_agent_tools(
if not getattr(tool, "enabled", False):
continue
tool_name = str(getattr(tool, "name", "") or "")
+ if not allow_any_tool and tool_name not in explicit_tool_names:
+ continue
if tool_name.startswith(GENERAL_SKILL_TOOL_PREFIX):
general_skill_tools.append(tool)
continue
@@ -4338,6 +4196,8 @@ def _step_agent_tools(
model_config,
agent_id,
general_skill_tools,
+ conversation_context,
+ memory_context,
)
if selected_general_tool:
scoped_tools.extend(
@@ -4353,6 +4213,8 @@ def _selected_general_skill_tool_name(
model_config: ModelConfig | None,
agent_id: str | None,
general_skill_tools: list[Tool],
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> str | None:
message = str(user_message or "").strip()
if not message or not model_config or not general_skill_tools:
@@ -4373,7 +4235,13 @@ def _selected_general_skill_tool_name(
if not candidates:
return None
try:
- selection = self.general_skill_selector.decide(message, candidates, model_config)
+ selection = self.general_skill_selector.decide(
+ message,
+ candidates,
+ model_config,
+ conversation_context,
+ memory_context,
+ )
except LLMError:
return None
if not selection.use_general_skill or not selection.selected_slug:
@@ -4798,6 +4666,8 @@ def _execute_tool_call(
tool_call: ToolCall,
tool_call_id: str | None = None,
stream_events: list[tuple[str, dict[str, object]]] | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> ToolResult:
if (
not tool_call.name.startswith(GENERAL_SKILL_TOOL_PREFIX)
@@ -4911,6 +4781,8 @@ def _execute_tool_call(
tool_call,
chat_session.agent_id,
stream_events=stream_events,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
else:
tool_result = self.tool_executor.execute(
@@ -4940,6 +4812,8 @@ def _execute_general_skill_tool_call(
tool_call: ToolCall,
agent_id: str | None,
stream_events: list[tuple[str, dict[str, object]]] | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> ToolResult:
slug = tool_call.name.removeprefix(GENERAL_SKILL_TOOL_PREFIX).strip()
if not slug:
@@ -4989,6 +4863,8 @@ def _execute_general_skill_tool_call(
query,
model_config,
agent_id,
+ conversation_context,
+ memory_context,
)
if guard_result is not None:
return guard_result
@@ -5018,6 +4894,8 @@ def trace_sink(trace_item: dict[str, Any]) -> None:
model_config,
request.user_id,
event_sink=trace_sink,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
)
except Exception as exc:
return ToolResult(
@@ -5077,6 +4955,8 @@ def _validate_general_skill_tool_match(
query: str,
model_config: ModelConfig,
agent_id: str | None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> ToolResult | None:
if not query:
return ToolResult(
@@ -5106,7 +4986,13 @@ def _validate_general_skill_tool_match(
),
)
try:
- selection = self.general_skill_selector.decide(query, candidates, model_config)
+ selection = self.general_skill_selector.decide(
+ query,
+ candidates,
+ model_config,
+ conversation_context,
+ memory_context,
+ )
except LLMError:
return None
selected_slug = selection.selected_slug if selection.use_general_skill else None
@@ -5701,8 +5587,16 @@ def _select_general_skill(
message: str,
model_config: ModelConfig,
agent_id: str | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> tuple[GeneralSkill, GeneralSkillSelection] | None:
- skill, selection = self._select_general_capability(message, model_config, agent_id)
+ skill, selection = self._select_general_capability(
+ message,
+ model_config,
+ agent_id,
+ conversation_context,
+ memory_context,
+ )
if skill is None:
return None
return skill, selection
@@ -5712,10 +5606,18 @@ def _select_general_capability(
message: str,
model_config: ModelConfig,
agent_id: str | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> tuple[GeneralSkill | None, GeneralSkillSelection]:
general_skills = self._list_published_general_skills(model_config.tenant_id, agent_id)
try:
- selection = self.general_skill_selector.decide(message, general_skills, model_config)
+ selection = self.general_skill_selector.decide(
+ message,
+ general_skills,
+ model_config,
+ conversation_context,
+ memory_context,
+ )
except LLMError as exc:
return None, GeneralSkillSelection(reason=f"Capability selection failed: {exc}")
if not selection.use_general_skill or not selection.selected_slug:
diff --git a/backend/app/core/context_projection.py b/backend/app/core/context_projection.py
index 602b7b427..20e003218 100644
--- a/backend/app/core/context_projection.py
+++ b/backend/app/core/context_projection.py
@@ -3,6 +3,7 @@
from typing import Any
from app.core.conversation_context import build_conversation_context
+from app.llm.stage_protocol import TURN_STAGE_MESSAGES_KEY
CONTROL_CONTEXT_TOKEN_BUDGET = 32_000
@@ -40,18 +41,22 @@ def compact_conversation_context(
) -> dict[str, object]:
if not isinstance(context, dict):
return build_conversation_context([], token_budget)
+ turn_messages = context.setdefault(TURN_STAGE_MESSAGES_KEY, [])
messages = context.get("messages")
if not isinstance(messages, list):
- return {key: value for key, value in context.items() if key != "messages"}
+ context["messages"] = []
+ return context
metadata = context.get("metadata")
if (
isinstance(metadata, dict)
and int(metadata.get("estimated_tokens") or 0) <= token_budget
):
return context
- return build_conversation_context(
+ compacted = build_conversation_context(
[message for message in messages if isinstance(message, dict)], token_budget
)
+ compacted[TURN_STAGE_MESSAGES_KEY] = turn_messages
+ return compacted
def compact_current_step(
@@ -102,20 +107,14 @@ def compact_step_skill_context(
target_node = nodes_by_id.get(target_id)
if not target_node:
continue
- projected_step = _project_node(target_node)
+ projected_step = _project_step_agent_node(target_node)
transition = _project_transition(edge)
if transition:
projected_step["transition"] = transition
next_steps.append(projected_step)
return _without_empty(
{
- "skill_id": skill_id or content.get("skill_id"),
- "name": name or content.get("name"),
- "description": description or content.get("description"),
- "required_info": content.get("required_info"),
- "slot_filling_policy": content.get("slot_filling_policy"),
- "response_rules": content.get("response_rules"),
- "current_step": current_step,
+ "current_step": _project_step_agent_node(current_step or {}),
"next_steps": next_steps,
}
)
@@ -143,6 +142,20 @@ def compact_router_decision(payload: dict[str, Any] | None) -> dict[str, Any] |
return projected or None
+def compact_step_router_decision(
+ payload: dict[str, Any] | None,
+) -> dict[str, Any] | None:
+ if not isinstance(payload, dict):
+ return None
+ projected = _without_empty(
+ {
+ "decision": payload.get("decision"),
+ "user_intent": _short_text(payload.get("user_intent"), 300),
+ }
+ )
+ return projected or None
+
+
def compact_response_step_result(payload: dict[str, Any]) -> dict[str, Any] | None:
projected = _without_empty(
{
@@ -210,6 +223,32 @@ def compact_pending_tasks(items: list[dict[str, Any]] | None) -> list[dict[str,
return tasks
+def compact_deferred_intents(
+ items: list[dict[str, Any]] | None,
+ *,
+ selected_task_id: str | None = None,
+) -> list[str]:
+ if not isinstance(items, list):
+ return []
+ intents: list[str] = []
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ if selected_task_id and str(item.get("task_id") or "") == selected_task_id:
+ continue
+ if str(item.get("status") or "pending") != "pending":
+ continue
+ intent = _short_text(
+ item.get("intent_summary")
+ or item.get("user_intent")
+ or item.get("source_message"),
+ 300,
+ )
+ if intent and intent not in intents:
+ intents.append(intent)
+ return intents
+
+
def compact_awaiting_input(value: dict[str, Any] | None) -> dict[str, Any] | None:
if not isinstance(value, dict):
return None
@@ -343,6 +382,21 @@ def _project_node(node: dict[str, Any]) -> dict[str, Any]:
return _without_empty(projected)
+def _project_step_agent_node(node: dict[str, Any]) -> dict[str, Any]:
+ if not isinstance(node, dict):
+ return {}
+ return _without_empty(
+ {
+ "node_id": node.get("node_id") or node.get("step_id"),
+ "type": node.get("type"),
+ "instruction": node.get("instruction"),
+ "expected_user_info": node.get("expected_user_info"),
+ "allowed_actions": node.get("allowed_actions"),
+ "knowledge_scope": node.get("knowledge_scope"),
+ }
+ )
+
+
def _project_transition(edge: dict[str, Any]) -> dict[str, Any]:
return _without_empty(
{
@@ -350,7 +404,6 @@ def _project_transition(edge: dict[str, Any]) -> dict[str, Any]:
for key in (
"condition",
"label",
- "priority",
)
}
)
diff --git a/backend/app/core/response_generator.py b/backend/app/core/response_generator.py
index 5039cd5f6..963eb066d 100644
--- a/backend/app/core/response_generator.py
+++ b/backend/app/core/response_generator.py
@@ -8,7 +8,6 @@
compact_citation_hints,
compact_current_step,
compact_knowledge_context,
- compact_memory_context,
compact_response_step_result,
)
from app.db.models import ChatSession, ModelConfig, Skill
@@ -79,6 +78,8 @@ def generate(
memory_context: list[dict[str, object]] | None = None,
conversation_context: dict[str, object] | None = None,
) -> str:
+ if self._can_use_step_reply_directly(step_result, tool_result):
+ return step_result.reply.strip()
raw_payload = self._payload(
message,
session,
@@ -117,6 +118,9 @@ def generate_stream(
memory_context: list[dict[str, object]] | None = None,
conversation_context: dict[str, object] | None = None,
) -> Iterator[str]:
+ if self._can_use_step_reply_directly(step_result, tool_result):
+ yield from self.chunk_text(step_result.reply or "")
+ return
raw_payload = self._payload(
message,
session,
@@ -175,6 +179,20 @@ def chunk_text(self, text: str, chunk_size: int = 8) -> Iterator[str]:
for index in range(0, len(stripped), chunk_size):
yield stripped[index : index + chunk_size]
+ def _can_use_step_reply_directly(
+ self,
+ step_result: StepAgentResult,
+ tool_result: ToolResult | None,
+ ) -> bool:
+ return bool(
+ str(step_result.reply or "").strip()
+ and step_result.action in {"ask_user", "clarify"}
+ and tool_result is None
+ and step_result.tool_call is None
+ and step_result.knowledge_query is None
+ and not step_result.knowledge_results
+ )
+
def _payload(
self,
message: str,
@@ -190,7 +208,9 @@ def _payload(
compact_knowledge = compact_knowledge_context(knowledge_context)
return {
"user_message": message,
- "conversation_context": conversation_context or {},
+ "conversation_context": (
+ conversation_context if isinstance(conversation_context, dict) else {}
+ ),
"current_step": compact_current_step(
skill.content_json if skill else None, session.active_step_id
),
@@ -201,7 +221,6 @@ def _payload(
),
"tool_result": tool_result.model_dump() if tool_result else None,
"retrieved_knowledge": compact_knowledge,
- "memory_context": compact_memory_context(memory_context),
"knowledge_citation_hints": compact_citation_hints(
knowledge_citations_from_results(knowledge_context)
),
@@ -375,7 +394,7 @@ def _stage_payload(
stage_data = {
key: value
for key, value in payload.items()
- if key not in {"user_message", "conversation_context", "memory_context"}
+ if key not in {"user_message", "conversation_context"}
}
if persona_prompt:
stage_data = {"employee_identity": persona_prompt.strip(), **stage_data}
@@ -385,7 +404,7 @@ def _stage_payload(
conversation_context=payload.get("conversation_context")
if isinstance(payload.get("conversation_context"), dict)
else {},
- memory_context=str(payload.get("memory_context") or ""),
+ memory_context=None,
instructions=PROMPT_PATH.read_text(encoding="utf-8"),
stage_data=stage_data,
output_contract="只输出最终用户可见的纯文本,不输出 JSON、Markdown 代码围栏、分析过程或内部状态。",
diff --git a/backend/app/core/router.py b/backend/app/core/router.py
index c1435d2aa..87d733d93 100644
--- a/backend/app/core/router.py
+++ b/backend/app/core/router.py
@@ -12,17 +12,15 @@
from app.llm import LLMClient, LLMError
from app.llm.stage_protocol import (
ROUTER_OUTPUT_SCHEMA,
- TASK_SCHEDULER_OUTPUT_SCHEMA,
stage_payload,
unified_system_prompt,
)
from app.observability.spans import llm_operation
-from app.session.session_schema import RouterDecision, TaskScheduleDecision
+from app.session.session_schema import RouterDecision
from app.session.slot_policy import strip_router_generated_message_slots
PROMPT_PATH = paths.resource_dir() / "app" / "llm" / "prompts" / "router_prompt.md"
-TASK_SCHEDULER_PROMPT_PATH = paths.resource_dir() / "app" / "llm" / "prompts" / "task_scheduler_prompt.md"
class Router:
@@ -59,44 +57,6 @@ def decide(
raise LLMError(f"Router returned invalid JSON schema: {exc}") from exc
return self._normalize_decision(decision, session, available_skills)
- def schedule_tasks_after_completion(
- self,
- message: str,
- session: ChatSession,
- available_skills: list[Skill],
- model_config: ModelConfig,
- conversation_context: dict[str, object] | None = None,
- memory_context: list[dict[str, object]] | None = None,
- completed_reply: str | None = None,
- ) -> TaskScheduleDecision:
- candidate_frames = self._candidate_task_frames(session)
- payload = stage_payload(
- phase="Router / Task Scheduler",
- user_message=message,
- conversation_context=compact_conversation_context(conversation_context),
- memory_context=memory_context,
- instructions=TASK_SCHEDULER_PROMPT_PATH.read_text(encoding="utf-8"),
- stage_data={
- "completed_reply": completed_reply or "",
- "current_session": _router_session_payload(session),
- "candidate_task_frames": candidate_frames,
- "available_skills": _available_skill_payloads(available_skills),
- },
- output_contract=TASK_SCHEDULER_OUTPUT_SCHEMA,
- )
- try:
- with llm_operation("router.task_scheduler"):
- raw = LLMClient(model_config).generate_json(
- unified_system_prompt(),
- payload,
- )
- schedule = TaskScheduleDecision.model_validate(raw)
- except Exception as exc:
- if isinstance(exc, LLMError):
- raise
- raise LLMError(f"Task scheduler returned invalid JSON schema: {exc}") from exc
- return self._normalize_schedule(schedule, candidate_frames)
-
def _normalize_decision(
self, decision: RouterDecision, session: ChatSession, available_skills: list[Skill]
) -> RouterDecision:
@@ -124,6 +84,28 @@ def _normalize_decision(
decision.decision = "clarify"
decision.clarification_question = "请问您想继续哪一项待处理任务?"
return decision
+ if decision.decision == "create_pending":
+ ordered_tasks = [*decision.pending_tasks, *decision.created_tasks]
+ if ordered_tasks:
+ primary = ordered_tasks[0]
+ decision.decision = "start_new_task"
+ decision.selected_task_id = primary.task_id
+ decision.target_skill_id = primary.target_skill_id
+ decision.target_step_id = primary.target_step_id
+ decision.user_intent = primary.user_intent or decision.user_intent
+ decision.slot_hints = {
+ **dict(primary.slot_hints or {}),
+ **dict(decision.slot_hints or {}),
+ }
+ decision.pending_tasks = ordered_tasks[1:]
+ decision.created_tasks = []
+ if not decision.target_skill_id or decision.target_skill_id not in skills:
+ decision.decision = "clarify"
+ decision.selected_task_id = None
+ decision.target_skill_id = None
+ decision.target_step_id = None
+ decision.clarification_question = "请问您想办理哪类业务?"
+ return decision
if not decision.target_skill_id and session.active_skill_id:
decision.target_skill_id = session.active_skill_id
if decision.target_skill_id and not decision.target_step_id:
@@ -154,32 +136,6 @@ def _normalize_tasks(self, tasks, skills: dict[str, Skill]):
normalized_tasks.append(task)
return normalized_tasks
- def _normalize_schedule(
- self, schedule: TaskScheduleDecision, candidate_frames: list[dict[str, Any]]
- ) -> TaskScheduleDecision:
- valid_ids = {
- str(frame.get("task_id"))
- for frame in candidate_frames
- if isinstance(frame, dict) and frame.get("task_id")
- }
- selected_ids: list[str] = []
- for task_id in schedule.selected_task_ids:
- if task_id in valid_ids and task_id not in selected_ids:
- selected_ids.append(task_id)
- schedule.selected_task_ids = selected_ids
- if not selected_ids:
- schedule.action = "stop"
- return schedule
-
- def _candidate_task_frames(self, session: ChatSession) -> list[dict[str, Any]]:
- frames = compact_pending_tasks(session.pending_tasks_json)
- for frame in frames:
- frame["source"] = "pending"
- frame["slots"] = strip_router_generated_message_slots(
- frame.get("slots") if isinstance(frame.get("slots"), dict) else {}
- )
- return [frame for frame in frames if frame.get("task_id")]
-
def _first_node_id(skill: Skill) -> str | None:
content = skill.content_json or {}
diff --git a/backend/app/core/step_agent.py b/backend/app/core/step_agent.py
index 4bc4b258a..4d5ebecac 100644
--- a/backend/app/core/step_agent.py
+++ b/backend/app/core/step_agent.py
@@ -4,9 +4,9 @@
from app.core.context_projection import (
compact_awaiting_input,
compact_conversation_context,
+ compact_deferred_intents,
compact_knowledge_context,
- compact_pending_tasks,
- compact_router_decision,
+ compact_step_router_decision,
compact_step_skill_context,
)
from app.db.models import ChatSession, ModelConfig, Skill, Tool
@@ -21,7 +21,32 @@
PROMPT_PATH = paths.resource_dir() / "app" / "llm" / "prompts" / "step_agent_prompt.md"
+RULE_PATHS = {
+ "repair": paths.resource_dir() / "app" / "llm" / "prompts" / "step_agent_repair_rules.md",
+ "tool_continuation": paths.resource_dir()
+ / "app"
+ / "llm"
+ / "prompts"
+ / "step_agent_tool_continuation_rules.md",
+ "knowledge": paths.resource_dir()
+ / "app"
+ / "llm"
+ / "prompts"
+ / "step_agent_knowledge_rules.md",
+ "awaiting_input": paths.resource_dir()
+ / "app"
+ / "llm"
+ / "prompts"
+ / "step_agent_awaiting_input_rules.md",
+ "general_skill": paths.resource_dir()
+ / "app"
+ / "llm"
+ / "prompts"
+ / "step_agent_general_skill_rules.md",
+ "tools": paths.resource_dir() / "app" / "llm" / "prompts" / "step_agent_tool_rules.md",
+}
INTERNAL_SCHEDULER_SLOT_KEYS = {"_graph_pending_steps"}
+GENERAL_SKILL_TOOL_PREFIX = "general_skill."
class StepAgent:
@@ -41,8 +66,8 @@ def run(
) -> StepAgentResult:
compact_knowledge = compact_knowledge_context(current_knowledge)
compact_repair = _compact_repair_context(repair_context)
- stage_data = {
- "active_skill": compact_step_skill_context(
+ active_skill = (
+ compact_step_skill_context(
skill.content_json,
session.active_step_id,
skill_id=skill.skill_id,
@@ -50,34 +75,40 @@ def run(
description=skill.description,
)
if skill
- else None,
+ else None
+ )
+ available_tools = _available_tools_for_step(
+ active_skill,
+ session.slots_json,
+ tools,
+ )
+ deferred_intents = compact_deferred_intents(
+ session.pending_tasks_json,
+ selected_task_id=router_decision.selected_task_id if router_decision else None,
+ )
+ stage_data = {
+ "active_skill": active_skill,
"retrieved_knowledge": compact_knowledge,
- "router_decision": compact_router_decision(
+ "router_decision": compact_step_router_decision(
router_decision.model_dump(mode="json") if router_decision else None
),
"slots": _step_agent_slots(session.slots_json),
"awaiting_input": compact_awaiting_input(session.awaiting_input_json),
- "pending_tasks": compact_pending_tasks(session.pending_tasks_json),
+ "deferred_intents": deferred_intents,
"repair_context": compact_repair,
- "available_tools": [
- {
- "name": tool.name,
- "display_name": tool.display_name,
- "description": tool.description,
- "bucket": getattr(tool, "bucket", None) or "未分桶",
- "input_schema": tool.input_schema,
- "allowed_skills": tool.allowed_skills_json,
- }
- for tool in tools
- if tool.enabled
- ],
+ "available_tools": available_tools,
}
payload = stage_payload(
phase="Step Agent",
user_message=message,
conversation_context=compact_conversation_context(conversation_context),
- memory_context=memory_context,
- instructions=PROMPT_PATH.read_text(encoding="utf-8"),
+ memory_context=None,
+ instructions=_step_instructions(
+ repair_context=compact_repair,
+ retrieved_knowledge=compact_knowledge,
+ awaiting_input=stage_data["awaiting_input"],
+ available_tools=available_tools,
+ ),
stage_data=stage_data,
output_contract=STEP_AGENT_OUTPUT_SCHEMA,
)
@@ -88,7 +119,10 @@ def run(
raw = LLMClient(model_config).generate_json(
unified_system_prompt(), payload
)
- return StepAgentResult.model_validate(raw)
+ result = StepAgentResult.model_validate(raw)
+ if not result.action:
+ result.action = _infer_action(result, router_decision)
+ return result
except Exception as exc:
if isinstance(exc, LLMError):
raise
@@ -115,3 +149,112 @@ def _compact_repair_context(
projected.pop("knowledge_results", None)
projected["knowledge_results_available_in"] = "retrieved_knowledge"
return projected
+
+
+def _step_instructions(
+ *,
+ repair_context: dict[str, object] | None,
+ retrieved_knowledge: list[dict[str, object]],
+ awaiting_input: dict[str, object] | None,
+ available_tools: list[dict[str, object]],
+) -> str:
+ sections = [PROMPT_PATH.read_text(encoding="utf-8").strip()]
+ repair_reason = str((repair_context or {}).get("reason") or "")
+ if repair_context and repair_reason not in {"tool_continuation", "knowledge_continuation"}:
+ sections.append(RULE_PATHS["repair"].read_text(encoding="utf-8").strip())
+ if repair_reason == "tool_continuation":
+ sections.append(
+ RULE_PATHS["tool_continuation"].read_text(encoding="utf-8").strip()
+ )
+ if retrieved_knowledge or repair_reason == "knowledge_continuation":
+ sections.append(RULE_PATHS["knowledge"].read_text(encoding="utf-8").strip())
+ if awaiting_input:
+ sections.append(RULE_PATHS["awaiting_input"].read_text(encoding="utf-8").strip())
+ if available_tools:
+ sections.append(RULE_PATHS["tools"].read_text(encoding="utf-8").strip())
+ if any(
+ str(tool.get("name") or "").startswith(GENERAL_SKILL_TOOL_PREFIX)
+ for tool in available_tools
+ ):
+ sections.append(RULE_PATHS["general_skill"].read_text(encoding="utf-8").strip())
+ return "\n\n".join(section for section in sections if section)
+
+
+def _available_tools_for_step(
+ active_skill: dict[str, object] | None,
+ slots: dict[str, object] | None,
+ tools: list[Tool],
+) -> list[dict[str, object]]:
+ if not isinstance(active_skill, dict):
+ return []
+ current_step = active_skill.get("current_step")
+ if not isinstance(current_step, dict):
+ return []
+ current_expected = [
+ str(field)
+ for field in current_step.get("expected_user_info") or []
+ if str(field).strip()
+ ]
+ slot_values = slots if isinstance(slots, dict) else {}
+ if any(not _slot_has_value(slot_values, field) for field in current_expected):
+ candidate_steps = [current_step]
+ else:
+ candidate_steps = [
+ current_step,
+ *[
+ step
+ for step in active_skill.get("next_steps") or []
+ if isinstance(step, dict)
+ ],
+ ]
+ actions = {
+ str(action).strip()
+ for step in candidate_steps
+ for action in step.get("allowed_actions") or []
+ if str(action).strip()
+ }
+ explicit_names = {
+ action.split(":", 1)[1]
+ for action in actions
+ if action.startswith("call_tool:") and ":" in action
+ }
+ allow_any = "call_tool" in actions
+ if not explicit_names and not allow_any:
+ return []
+ projected: list[dict[str, object]] = []
+ for tool in tools:
+ if not getattr(tool, "enabled", False):
+ continue
+ name = str(getattr(tool, "name", "") or "").strip()
+ if not name or (not allow_any and name not in explicit_names):
+ continue
+ projected.append(
+ {
+ "name": name,
+ "description": str(getattr(tool, "description", "") or "").strip(),
+ "input_schema": getattr(tool, "input_schema", None) or {},
+ }
+ )
+ return projected
+
+
+def _slot_has_value(slots: dict[str, object], field: str) -> bool:
+ value = slots.get(field)
+ return value is not None and value != "" and value != [] and value != {}
+
+
+def _infer_action(
+ result: StepAgentResult,
+ router_decision: RouterDecision | None,
+) -> str:
+ if result.tool_call:
+ return "call_tool"
+ if result.knowledge_query:
+ return "query_knowledge"
+ if result.handoff:
+ return "handoff"
+ if result.next_step_id or result.is_step_completed:
+ return "advance"
+ if result.reply:
+ return "clarify" if router_decision and router_decision.decision == "clarify" else "ask_user"
+ return "reply"
diff --git a/backend/app/general_skills/runner.py b/backend/app/general_skills/runner.py
index 4146cb9c0..f641bbc7b 100644
--- a/backend/app/general_skills/runner.py
+++ b/backend/app/general_skills/runner.py
@@ -25,6 +25,7 @@
)
from app.general_skills.runtime_env import GeneralSkillRuntimeError, ensure_runtime_python, runtime_environment
from app.llm import LLMClient, LLMError
+from app.llm.stage_protocol import stage_payload, unified_system_prompt
from app.observability.spans import llm_operation
@@ -39,6 +40,28 @@
GENERAL_SKILL_MAX_TOKENS = 8192
GENERAL_SKILL_MAX_ATTEMPTS = 10
TraceSink = Callable[[dict[str, Any]], None]
+GENERAL_SKILL_SELECTION_OUTPUT = {
+ "use_general_skill": "boolean",
+ "selected_slug": "string?",
+ "use_knowledge": "boolean",
+ "knowledge_query": "string?",
+ "confidence": "number",
+ "reason": "string?",
+}
+GENERAL_SKILL_PLAN_OUTPUT = {
+ "code": "string",
+ "runtime": "bash | python",
+ "rationale": "string?",
+ "expected_output": "string?",
+}
+GENERAL_SKILL_REVIEW_OUTPUT = {
+ "result_sufficient": "boolean",
+ "needs_retry": "boolean",
+ "terminal": "boolean",
+ "reason": "string",
+ "repair_hint": "string?",
+}
+GENERAL_SKILL_REPLY_OUTPUT = {"reply": "string"}
class GeneralSkillSelector:
@@ -47,24 +70,33 @@ def decide(
query: str,
general_skills: list[GeneralSkill],
model_config: ModelConfig,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> GeneralSkillSelection:
- payload = {
- "user_message": query,
- "general_skills": [
- {
- "slug": skill.slug,
- "name": skill.name,
- "description": skill.description,
- "homepage": skill.homepage,
- "status": skill.status,
- }
- for skill in general_skills
- if skill.status == "published"
- ],
- }
+ payload = stage_payload(
+ phase="Router / General Skill Selector",
+ user_message=query,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
+ instructions=SELECTOR_PROMPT.read_text(encoding="utf-8"),
+ stage_data={
+ "general_skills": [
+ {
+ "slug": skill.slug,
+ "name": skill.name,
+ "description": skill.description,
+ "homepage": skill.homepage,
+ "status": skill.status,
+ }
+ for skill in general_skills
+ if skill.status == "published"
+ ],
+ },
+ output_contract=GENERAL_SKILL_SELECTION_OUTPUT,
+ )
with llm_operation("general_skill.select"):
raw = LLMClient(model_config).generate_json(
- SELECTOR_PROMPT.read_text(encoding="utf-8"), payload
+ unified_system_prompt(), payload
)
decision = GeneralSkillSelection.model_validate(raw)
slugs = {skill.slug for skill in general_skills if skill.status == "published"}
@@ -82,6 +114,8 @@ def run(
user_id: str = "",
max_attempts: int = GENERAL_SKILL_MAX_ATTEMPTS,
event_sink: TraceSink | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> GeneralSkillRunResponse:
trace: list[dict[str, Any]] = []
max_attempts = max(1, min(max_attempts, GENERAL_SKILL_MAX_ATTEMPTS))
@@ -94,6 +128,8 @@ def run(
trace,
event_sink,
max_attempts,
+ conversation_context,
+ memory_context,
)
except LLMError as exc:
_emit(trace, {"phase": "plan_failed", "message": "模型生成 runner 失败", "error": str(exc)}, event_sink)
@@ -138,6 +174,8 @@ def run(
trace,
event_sink,
attempt,
+ conversation_context,
+ memory_context,
)
attempts.append(
{
@@ -195,7 +233,17 @@ def run(
event_sink,
)
try:
- plan = self._repair_plan(skill, query, model_config, trace, attempts, event_sink, attempt + 1)
+ plan = self._repair_plan(
+ skill,
+ query,
+ model_config,
+ trace,
+ attempts,
+ event_sink,
+ attempt + 1,
+ conversation_context,
+ memory_context,
+ )
except LLMError as exc:
_emit(
trace,
@@ -205,7 +253,18 @@ def run(
break
try:
- reply = self._generate_reply(skill, query, model_config, trace, stdout, stderr, structured_result, event_sink)
+ reply = self._generate_reply(
+ skill,
+ query,
+ model_config,
+ trace,
+ stdout,
+ stderr,
+ structured_result,
+ event_sink,
+ conversation_context,
+ memory_context,
+ )
except LLMError as exc:
_emit(trace, {"phase": "reply_failed", "message": "模型生成最终回复失败", "error": str(exc)}, event_sink)
reply = _fallback_reply(structured_result)
@@ -226,10 +285,11 @@ def _generate_plan(
model_config: ModelConfig,
trace: list[dict[str, Any]],
event_sink: TraceSink | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> GeneralSkillExecutionPlan:
_emit(trace, {"phase": "planning", "message": "正在根据 SKILL.md 生成 runner"}, event_sink)
- payload = {
- "query": query,
+ stage_data = {
"skill": {
"slug": skill.slug,
"name": skill.name,
@@ -250,9 +310,18 @@ def _generate_plan(
"timeout_seconds": RUN_TIMEOUT_SECONDS,
},
}
+ payload = stage_payload(
+ phase="Step Agent / General Skill Plan",
+ user_message=query,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
+ instructions=RUNNER_PROMPT.read_text(encoding="utf-8"),
+ stage_data=stage_data,
+ output_contract=GENERAL_SKILL_PLAN_OUTPUT,
+ )
with llm_operation("general_skill.plan"):
raw = LLMClient(_with_min_tokens(model_config, GENERAL_SKILL_MAX_TOKENS)).generate_json(
- RUNNER_PROMPT.read_text(encoding="utf-8"),
+ unified_system_prompt(),
payload,
)
plan = GeneralSkillExecutionPlan.model_validate(raw)
@@ -282,13 +351,26 @@ def _generate_plan_with_reflection(
trace: list[dict[str, Any]],
event_sink: TraceSink | None,
max_attempts: int,
+ conversation_context: dict[str, object] | None,
+ memory_context: list[dict[str, object]] | None,
) -> tuple[GeneralSkillExecutionPlan, list[dict[str, Any]]]:
planning_failures: list[dict[str, Any]] = []
last_error: LLMError | None = None
for plan_attempt in range(1, max_attempts + 1):
try:
if plan_attempt == 1:
- return self._generate_plan(skill, query, model_config, trace, event_sink), planning_failures
+ return (
+ self._generate_plan(
+ skill,
+ query,
+ model_config,
+ trace,
+ event_sink,
+ conversation_context,
+ memory_context,
+ ),
+ planning_failures,
+ )
return (
self._repair_plan(
skill,
@@ -298,6 +380,8 @@ def _generate_plan_with_reflection(
planning_failures,
event_sink,
plan_attempt,
+ conversation_context,
+ memory_context,
),
planning_failures,
)
@@ -357,14 +441,15 @@ def _repair_plan(
attempts: list[dict[str, Any]],
event_sink: TraceSink | None,
next_attempt: int,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> GeneralSkillExecutionPlan:
_emit(
trace,
{"phase": "repair_planning", "message": f"正在生成第 {next_attempt} 次运行代码", "attempt": next_attempt},
event_sink,
)
- payload = {
- "query": query,
+ stage_data = {
"skill": {
"slug": skill.slug,
"name": skill.name,
@@ -386,9 +471,18 @@ def _repair_plan(
},
"previous_attempts": attempts[-3:],
}
+ payload = stage_payload(
+ phase="Step Agent / General Skill Repair",
+ user_message=query,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
+ instructions=REPAIR_PROMPT.read_text(encoding="utf-8"),
+ stage_data=stage_data,
+ output_contract=GENERAL_SKILL_PLAN_OUTPUT,
+ )
with llm_operation("general_skill.repair", attempt=next_attempt):
raw = LLMClient(_with_min_tokens(model_config, GENERAL_SKILL_MAX_TOKENS)).generate_json(
- REPAIR_PROMPT.read_text(encoding="utf-8"),
+ unified_system_prompt(),
payload,
)
plan = GeneralSkillExecutionPlan.model_validate(raw)
@@ -564,10 +658,11 @@ def _generate_reply(
stderr: str,
structured_result: dict[str, Any],
event_sink: TraceSink | None = None,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> str:
_emit(trace, {"phase": "replying", "message": "正在根据运行结果生成回复"}, event_sink)
- payload = {
- "query": query,
+ stage_data = {
"skill": {
"slug": skill.slug,
"name": skill.name,
@@ -578,10 +673,19 @@ def _generate_reply(
"stderr": stderr,
"structured_result": structured_result,
}
+ payload = stage_payload(
+ phase="Response Generator / General Skill Reply",
+ user_message=query,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
+ instructions=REPLY_PROMPT.read_text(encoding="utf-8"),
+ stage_data=stage_data,
+ output_contract=GENERAL_SKILL_REPLY_OUTPUT,
+ )
try:
with llm_operation("general_skill.reply"):
raw = LLMClient(model_config).generate_json(
- REPLY_PROMPT.read_text(encoding="utf-8"), payload
+ unified_system_prompt(), payload
)
reply = GeneralSkillReply.model_validate(raw).reply.strip()
except LLMError:
@@ -605,6 +709,8 @@ def _review_execution_result(
trace: list[dict[str, Any]],
event_sink: TraceSink | None,
attempt: int,
+ conversation_context: dict[str, object] | None = None,
+ memory_context: list[dict[str, object]] | None = None,
) -> dict[str, Any]:
_emit(
trace,
@@ -615,8 +721,7 @@ def _review_execution_result(
},
event_sink,
)
- payload = {
- "query": query,
+ stage_data = {
"skill": {
"slug": skill.slug,
"name": skill.name,
@@ -635,10 +740,19 @@ def _review_execution_result(
"stderr": _truncate(stderr),
"structured_result": structured_result,
}
+ payload = stage_payload(
+ phase="Reflection / General Skill Review",
+ user_message=query,
+ conversation_context=conversation_context,
+ memory_context=memory_context,
+ instructions=REVIEW_PROMPT.read_text(encoding="utf-8"),
+ stage_data=stage_data,
+ output_contract=GENERAL_SKILL_REVIEW_OUTPUT,
+ )
try:
with llm_operation("general_skill.review", attempt=attempt):
raw = LLMClient(model_config).generate_json(
- REVIEW_PROMPT.read_text(encoding="utf-8"), payload
+ unified_system_prompt(), payload
)
review = GeneralSkillExecutionReview.model_validate(raw).model_dump(mode="json")
except Exception as exc:
diff --git a/backend/app/llm/client.py b/backend/app/llm/client.py
index 10f460a73..3ee29c07c 100644
--- a/backend/app/llm/client.py
+++ b/backend/app/llm/client.py
@@ -14,7 +14,11 @@
from app.config import get_settings
from app.db.models import ModelConfig
from app.llm.output_policy import operation_output_tokens
-from app.llm.stage_protocol import STAGE_PROTOCOL_KEY
+from app.llm.stage_protocol import (
+ STAGE_PROTOCOL_KEY,
+ TURN_STAGE_MESSAGES_KEY,
+ render_stage_user_message,
+)
from app.observability.spans import current_llm_operation, llm_span_attributes, start_llm_call
from app.security.encryption import decrypt_secret
@@ -28,6 +32,7 @@ class LLMError(Exception):
EMPTY_RESPONSE_MESSAGE = "Model returned an empty response"
DEFAULT_MODEL_API_TIMEOUT_SECONDS = 600.0
DEFAULT_INPUT_TOKEN_BUDGET = 32_000
+TURN_STAGE_MESSAGE_MARKER = "_agent_turn_message"
class _CurrentStageText(str):
@@ -64,6 +69,12 @@ def generate_text(
context_messages, serialized = _prepare_user_input(user_payload)
request_messages = _request_messages(system_prompt, context_messages, serialized)
request_messages = _fit_request_messages(request_messages)
+ if isinstance(user_payload, dict) and isinstance(
+ user_payload.get(STAGE_PROTOCOL_KEY), dict
+ ):
+ self._last_stage_request_user_content = copy.deepcopy(
+ request_messages[-1].get("content")
+ )
request_shape = _request_shape_metrics(
system_prompt, context_messages, serialized, request_messages
)
@@ -105,6 +116,14 @@ def generate_text(
status="success",
**metrics,
)
+ if not getattr(self, "_defer_stage_recording", False):
+ _record_stage_exchange(
+ user_payload,
+ content,
+ request_user_content=getattr(
+ self, "_last_stage_request_user_content", None
+ ),
+ )
return content
span.finish(
ttft_ms=span.elapsed_ms(),
@@ -129,6 +148,12 @@ def generate_text_stream(
context_messages, serialized = _prepare_user_input(user_payload)
request_messages = _request_messages(system_prompt, context_messages, serialized)
request_messages = _fit_request_messages(request_messages)
+ if isinstance(user_payload, dict) and isinstance(
+ user_payload.get(STAGE_PROTOCOL_KEY), dict
+ ):
+ self._last_stage_request_user_content = copy.deepcopy(
+ request_messages[-1].get("content")
+ )
request_shape = _request_shape_metrics(
system_prompt, context_messages, serialized, request_messages
)
@@ -147,6 +172,7 @@ def generate_text_stream(
**request_shape,
)
pending_parts: list[str] = []
+ recorded_parts: list[str] = []
emitted_text = False
chunk_count = 0
choice_chunk_count = 0
@@ -183,6 +209,7 @@ def generate_text_stream(
content = _content_text(getattr(delta, "content", None))
if not content:
continue
+ recorded_parts.append(content)
output_chars += len(content)
if first_content_ms is None:
first_content_ms = span.elapsed_ms()
@@ -217,6 +244,13 @@ def generate_text_stream(
finish_reasons=sorted(finish_reasons),
provider_response_ids=sorted(response_ids),
)
+ _record_stage_exchange(
+ user_payload,
+ "".join(recorded_parts),
+ request_user_content=getattr(
+ self, "_last_stage_request_user_content", None
+ ),
+ )
return
span.finish(
provider_setup_ms=provider_setup_ms,
@@ -257,18 +291,44 @@ def generate_json(self, system_prompt: str, user_payload: dict[str, Any]) -> dic
json_retry_count=attempt,
json_max_attempts=JSON_REPAIR_ATTEMPTS + 1,
):
- text = self._generate_json_candidate(system_prompt, next_payload, json_mode_supported)
- if json_mode_supported and _response_format_unsupported(text):
- json_mode_supported = False
- text = self.generate_text(system_prompt, next_payload)
+ previous_defer = getattr(self, "_defer_stage_recording", False)
+ self._defer_stage_recording = True
+ try:
+ text = self._generate_json_candidate(
+ system_prompt, next_payload, json_mode_supported
+ )
+ if json_mode_supported and _response_format_unsupported(text):
+ json_mode_supported = False
+ text = self.generate_text(system_prompt, next_payload)
+ finally:
+ self._defer_stage_recording = previous_defer
outputs.append(text)
try:
- return _loads_llm_json(text)
+ parsed = _loads_llm_json(text)
+ _record_stage_exchange(
+ next_payload,
+ text,
+ request_user_content=getattr(
+ self, "_last_stage_request_user_content", None
+ ),
+ )
+ return parsed
except json.JSONDecodeError as exc:
last_error = exc
+ _record_stage_exchange(
+ next_payload,
+ text,
+ request_user_content=getattr(
+ self, "_last_stage_request_user_content", None
+ ),
+ )
if attempt >= JSON_REPAIR_ATTEMPTS:
break
next_payload = copy.deepcopy(user_payload)
+ if isinstance(user_payload.get(STAGE_PROTOCOL_KEY), dict):
+ next_payload["conversation_context"] = user_payload.get(
+ "conversation_context"
+ )
next_payload["_json_repair"] = {
"attempt": attempt + 1,
"max_attempts": JSON_REPAIR_ATTEMPTS,
@@ -384,6 +444,7 @@ def _fit_request_messages(
index
for index in range(1, len(projected) - 1)
if not _is_history_summary_message(projected[index])
+ and not _is_turn_stage_message(projected[index])
),
None,
)
@@ -392,14 +453,30 @@ def _fit_request_messages(
projected.pop(removable_index)
while len(projected) > 2 and _request_tokens(projected) > token_budget:
- projected.pop(1)
+ removable_index = next(
+ (
+ index
+ for index in range(1, len(projected) - 1)
+ if not _is_turn_stage_message(projected[index])
+ ),
+ None,
+ )
+ if removable_index is None:
+ break
+ projected.pop(removable_index)
+
+ _trim_turn_stage_messages(projected, token_budget)
+ _drop_oldest_turn_stage_exchanges(projected, token_budget)
if projected and _request_tokens(projected) > token_budget:
fixed_tokens = _request_tokens(projected[:-1])
projected[-1] = _trim_request_message(
projected[-1], max(1, token_budget - fixed_tokens)
)
- return projected
+ return [
+ {key: value for key, value in message.items() if key != TURN_STAGE_MESSAGE_MARKER}
+ for message in projected
+ ]
def _request_tokens(messages: list[dict[str, Any]]) -> int:
@@ -417,6 +494,55 @@ def _is_history_summary_message(message: dict[str, Any]) -> bool:
)
+def _is_turn_stage_message(message: dict[str, Any]) -> bool:
+ return message.get(TURN_STAGE_MESSAGE_MARKER) is True
+
+
+def _trim_turn_stage_messages(
+ messages: list[dict[str, Any]], token_budget: int
+) -> None:
+ while _request_tokens(messages) > token_budget:
+ candidates = [
+ (len(_content_text(message.get("content"))), index)
+ for index, message in enumerate(messages[1:-1], start=1)
+ if _is_turn_stage_message(message)
+ and len(_content_text(message.get("content"))) > 512
+ ]
+ if not candidates:
+ break
+ current_length, index = max(candidates)
+ excess_tokens = _request_tokens(messages) - token_budget
+ target_tokens = max(128, math.ceil(current_length / 4) - excess_tokens)
+ trimmed = _trim_request_message(messages[index], target_tokens)
+ trimmed[TURN_STAGE_MESSAGE_MARKER] = True
+ if len(_content_text(trimmed.get("content"))) >= current_length:
+ break
+ messages[index] = trimmed
+
+
+def _drop_oldest_turn_stage_exchanges(
+ messages: list[dict[str, Any]], token_budget: int
+) -> None:
+ while _request_tokens(messages) > token_budget:
+ stage_indices = [
+ index
+ for index, message in enumerate(messages[1:-1], start=1)
+ if _is_turn_stage_message(message)
+ ]
+ if len(stage_indices) <= 2:
+ break
+ first_index = stage_indices[0]
+ remove_count = 1
+ if (
+ len(stage_indices) > 1
+ and stage_indices[1] == first_index + 1
+ and messages[first_index].get("role") == "user"
+ and messages[first_index + 1].get("role") == "assistant"
+ ):
+ remove_count = 2
+ del messages[first_index : first_index + remove_count]
+
+
def _trim_request_message(
message: dict[str, Any], token_budget: int
) -> dict[str, Any]:
@@ -816,9 +942,15 @@ def _prepare_user_input(
def _prepare_stage_user_input(
user_payload: dict[str, Any],
) -> tuple[list[dict[str, Any]], str | list[dict[str, Any]]]:
- payload = copy.deepcopy(user_payload)
- stage = payload.pop(STAGE_PROTOCOL_KEY, {})
- context = payload.pop("conversation_context", None)
+ context = user_payload.get("conversation_context")
+ payload = copy.deepcopy(
+ {
+ key: value
+ for key, value in user_payload.items()
+ if key != "conversation_context"
+ }
+ )
+ payload.pop(STAGE_PROTOCOL_KEY, None)
context_messages = _project_messages_from_context(context)
user_message = str(payload.pop("user_message", "") or "").strip()
current_images: list[dict[str, Any]] = []
@@ -838,23 +970,11 @@ def _prepare_stage_user_input(
context_messages.pop(index)
break
- projected = _drop_empty_values(payload)
- output_contract = stage.get("output_contract")
- if not isinstance(output_contract, str):
- output_contract = json.dumps(
- output_contract or {}, ensure_ascii=False, separators=(",", ":")
- )
- sections = [
- f"用户记忆:\n{stage.get('memory') or '无'}",
- f"本轮时间:\n{stage.get('turn_time') or '未提供'}",
- f"本轮用户输入:\n{user_message or '(空)'}",
- f"当前阶段:\n{stage.get('phase') or '未指定'}",
- f"阶段规则:\n{str(stage.get('instructions') or '').strip()}",
- "当前阶段独有内容:\n"
- + json.dumps(projected, ensure_ascii=False, separators=(",", ":")),
- f"输出约束:\n{output_contract}",
- ]
- serialized = "\n\n".join(sections)
+ turn_stage_messages = _project_turn_stage_messages(context)
+ context_messages.extend(turn_stage_messages)
+ serialized = render_stage_user_message(
+ user_payload, include_turn_header=not turn_stage_messages
+ )
if not current_images:
return context_messages, _CurrentStageText(serialized)
return context_messages, [
@@ -890,6 +1010,63 @@ def _project_messages_from_context(context: Any) -> list[dict[str, Any]]:
return projected
+def _project_turn_stage_messages(context: Any) -> list[dict[str, Any]]:
+ if not isinstance(context, dict):
+ return []
+ messages = context.get(TURN_STAGE_MESSAGES_KEY)
+ if not isinstance(messages, list):
+ return []
+ projected: list[dict[str, Any]] = []
+ for message in messages:
+ if not isinstance(message, dict):
+ continue
+ role = str(message.get("role") or "").strip()
+ content = message.get("content")
+ if role not in {"user", "assistant"} or not _content_text(content).strip():
+ continue
+ projected.append(
+ {
+ "role": role,
+ "content": content,
+ TURN_STAGE_MESSAGE_MARKER: True,
+ }
+ )
+ return projected
+
+
+def _record_stage_exchange(
+ context_payload: dict[str, Any] | str,
+ assistant_content: str,
+ *,
+ request_user_content: Any = None,
+) -> None:
+ if not isinstance(context_payload, dict):
+ return
+ if not isinstance(context_payload.get(STAGE_PROTOCOL_KEY), dict):
+ return
+ context = context_payload.get("conversation_context")
+ if not isinstance(context, dict):
+ return
+ turn_messages = context.setdefault(TURN_STAGE_MESSAGES_KEY, [])
+ if not isinstance(turn_messages, list):
+ return
+ content = str(assistant_content or "").strip()
+ if not content:
+ return
+ user_content = request_user_content
+ if not _content_text(user_content).strip():
+ user_content = render_stage_user_message(
+ context_payload,
+ include_turn_header=not _project_turn_stage_messages(context),
+ )
+ turn_messages.extend(
+ [
+ {"role": "user", "content": copy.deepcopy(user_content)},
+ {"role": "assistant", "content": content},
+ ]
+ )
+
+
def _drop_empty_values(value: Any) -> Any:
if isinstance(value, dict):
projected = {
diff --git a/backend/app/llm/output_policy.py b/backend/app/llm/output_policy.py
index c90c06404..7ec6365ab 100644
--- a/backend/app/llm/output_policy.py
+++ b/backend/app/llm/output_policy.py
@@ -5,7 +5,6 @@
# Long-form code/content generation intentionally keeps a larger allowance.
OPERATION_MAX_OUTPUT_TOKENS: dict[str, int] = {
"router.scene": 1024,
- "router.task_scheduler": 2048,
"context.compact": 2048,
"reflection.review": 2048,
"general_skill.select": 2048,
@@ -17,7 +16,6 @@
"knowledge.bucket_route": 512,
"knowledge.discovery": 4096,
"knowledge.ingest_bucket": 8192,
- "memory.rerank": 512,
"memory.capture": 1024,
"session.title": 512,
"scheduled_task.detect": 1024,
diff --git a/backend/app/llm/prompts/memory_reranker_prompt.md b/backend/app/llm/prompts/memory_reranker_prompt.md
deleted file mode 100644
index b68efc603..000000000
--- a/backend/app/llm/prompts/memory_reranker_prompt.md
+++ /dev/null
@@ -1,19 +0,0 @@
-你是用户长期记忆召回助手。
-
-目标:从候选长期记忆中选出当前用户消息最相关、最可能帮助本轮路由和执行的记忆。
-
-你会收到:
-- user_message:当前用户消息
-- candidate_memories:按 `m1: 记忆内容` 编号的纯文本候选
-- limit:最多返回数量
-
-要求:
-- profile 类记忆通常由系统固定注入;你主要选择 preference / fact。
-- 不要因为词面相同就选择一次性业务流水;只选择稳定偏好、长期事实、服务约束。
-- 如果没有相关记忆,返回空数组。
-- 只输出候选中的临时编号(如 m1、m2),不要输出理由、候选内容或其他字段。这不是数据库 ID。
-
-输出格式:
-{
- "memory_ids": ["..."]
-}
diff --git a/backend/app/llm/prompts/router_prompt.md b/backend/app/llm/prompts/router_prompt.md
index d83b5d430..b609d610f 100644
--- a/backend/app/llm/prompts/router_prompt.md
+++ b/backend/app/llm/prompts/router_prompt.md
@@ -15,7 +15,7 @@
clarification_question 是给终端用户看的澄清问题,必须像客服一样自然表达。
禁止在 clarification_question 中要求用户提供“当前用户消息、会话状态、技能进度、可用技能列表、路由信息、JSON、decision”等内部系统信息。
-场景化技能和通用技能是两层能力:Router 只决定场景化技能、任务帧和调度顺序,不负责否定或执行通用技能。通用技能会在执行阶段以 `general_skill.` 的形式出现在 available_tools 中,由 StepAgent 在当前场景技能内显式调用。若用户当前消息同时推进当前场景技能,并提出实时信息、代码运行、通用计算、文件处理等临时通用能力诉求,不要因为该诉求不在 available_skills 中就降级为普通回答;应继续或保留当前场景任务,并在 reason 中说明通用能力交由执行阶段根据 available_tools 处理。
+场景化技能和通用技能是两层能力:Router 只决定场景化技能和任务执行顺序,不负责否定或执行通用技能。通用技能会在执行阶段以 `general_skill.` 的形式出现。若用户当前消息同时推进当前场景技能,并提出实时信息、代码运行、通用计算、文件处理等临时通用能力诉求,不要因为该诉求不在 available_skills 中就降级为普通回答;应继续或保留当前场景任务。
Router 只根据 Skill ID、名称、描述和 trigger_intents 选择场景技能,不读取 SOP 节点图;具体节点执行和缺失字段判断交给 Step Agent。
@@ -57,6 +57,6 @@ slot_hints、pending_tasks/created_tasks/task_updates.slot_hints 只能填写订
16. 每轮都要先检查 current_session.pending_tasks。如果用户当前消息是在继续其中某个任务,选择 switch_to_pending,并填写 selected_task_id。不要只根据 target_skill_id 自动合并任务。
17. 如果 pending 为空,不能选择 switch_to_pending,但仍可继续 active 或启动新技能。
18. 如果用户重复表达已在 pending 中的同一任务,优先输出 task_updates 更新原 task,不要新增重复 pending。
-19. 如果用户一句话包含多个独立可执行任务,必须把每个任务都显式表达出来:主 decision 表达当前应推进的任务,其他任务写入 pending_tasks / created_tasks。运行时会先把这些任务都写成 task frame,再由 scheduler 决定执行顺序;不要把多个独立任务压缩成一个 target_skill_id。
-20. 如果本轮没有一个任务天然应先执行,也可以输出 create_pending,并把所有任务写入 pending_tasks / created_tasks,让 scheduler 选择先后顺序。
-21. 当 current_session.active_skill_id 存在,而你准备选择另一个 target_skill_id 时,必须先判断当前用户消息是否同时补充、确认、推进或修改了 active skill。只要存在这种可能,就不要让 start_new_task 隐式覆盖 active skill;应把 active skill 作为一个待调度任务保留,并把新任务也显式写入 pending_tasks / created_tasks,或选择 continue_active 并把新任务写入 created_tasks。只有用户明确取消、放弃或当前任务已完成时,才可以不保留 active skill。
+19. 如果用户一句话包含多个独立可执行任务,Router 必须直接决定执行顺序:主 decision 和 target_skill_id 表达第一个执行的任务,其余任务按执行先后写入 pending_tasks / created_tasks。运行时会严格按数组顺序继续执行,不会再调用独立 scheduler;不要把多个独立任务压缩成一个 target_skill_id。
+20. 不要把多个任务全部留给 create_pending。即使多个任务优先级接近,也必须选择一个作为本轮主任务,其余任务按顺序排队。
+21. 当 current_session.active_skill_id 存在,而你准备选择另一个 target_skill_id 时,必须先判断当前用户消息是否同时补充、确认、推进或修改了 active skill。只要存在这种可能,就不要让 start_new_task 隐式覆盖 active skill;应把 active skill 放在 pending_tasks / created_tasks 的正确顺序位置,或选择 continue_active 并把新任务排到后面。只有用户明确取消、放弃或当前任务已完成时,才可以不保留 active skill。
diff --git a/backend/app/llm/prompts/step_agent_awaiting_input_rules.md b/backend/app/llm/prompts/step_agent_awaiting_input_rules.md
new file mode 100644
index 000000000..b82453edf
--- /dev/null
+++ b/backend/app/llm/prompts/step_agent_awaiting_input_rules.md
@@ -0,0 +1 @@
+短回复映射规则:awaiting_input 表示上一轮正在等待的字段。用户当前回复较短时,先判断它是否在回答这些字段;是则写入 slot_updates,不是则不要强行映射。
diff --git a/backend/app/llm/prompts/step_agent_general_skill_rules.md b/backend/app/llm/prompts/step_agent_general_skill_rules.md
new file mode 100644
index 000000000..68059c0db
--- /dev/null
+++ b/backend/app/llm/prompts/step_agent_general_skill_rules.md
@@ -0,0 +1 @@
+通用技能规则:通用技能是场景内第二层能力,`general_skill.` 是当前场景允许调用的临时通用能力。只有用户当前子任务与其描述直接匹配时才能调用,并在 arguments.query 中写清任务;不得把它当作场景工具、知识检索或追问用户的兜底。
diff --git a/backend/app/llm/prompts/step_agent_knowledge_rules.md b/backend/app/llm/prompts/step_agent_knowledge_rules.md
new file mode 100644
index 000000000..ed1acf7ac
--- /dev/null
+++ b/backend/app/llm/prompts/step_agent_knowledge_rules.md
@@ -0,0 +1 @@
+知识续执行规则:retrieved_knowledge 是本轮检索到的临时证据。只基于这些证据和 slots 推进、追问、调用工具或回复;证据不足时不得编造政策、流程或文档事实。需要再次检索时输出 knowledge_query。
diff --git a/backend/app/llm/prompts/step_agent_prompt.md b/backend/app/llm/prompts/step_agent_prompt.md
index 511cd083c..0adab47c1 100644
--- a/backend/app/llm/prompts/step_agent_prompt.md
+++ b/backend/app/llm/prompts/step_agent_prompt.md
@@ -1,59 +1,19 @@
-你是企业技能执行助手。
+你是企业技能执行助手,只执行 active_skill 中当前节点及其直接相邻节点。
-你必须根据 active_skill 中的 current_step、next_steps、已收集信息和用户当前消息,生成下一步动作。这里不是完整 SOP 图:current_step 是当前所在节点,next_steps 只包含从当前节点直接连出的一层候选节点及各自 transition;current_step 和 next_steps 中的业务 instruction 必须完整遵守。
-技能节点是业务目标与约束,不是固定问答脚本。你需要自适应判断用户当前消息是否已经满足当前节点、后续节点或工具参数要求;满足时应直接推进、选择边、跳转或调用工具。
+active_skill 已经是当前 SOP 的最小投影:current_step 是当前节点,next_steps 是可直接到达的下一层节点。完整遵守其中的业务 instruction,但不要假设未提供的节点、规则或工具。
-你可以:
-1. 回复用户
-2. 抽取用户提供的信息
-3. 请求用户补充信息
-4. 调用可用工具
-5. 查询企业知识库
-6. 建议进入下一节点
-7. 建议转人工
+执行规则:
+1. 结合按时间顺序提供的 user/assistant 历史、当前用户输入和 slots,抽取当前节点及相邻节点明确需要的全部字段。
+2. 用户一次提供多个字段时,一次性写入 slot_updates;已有 slots 或本轮能可靠抽取的信息不要重复追问。
+3. 数字、金额、数量和时长要理解自然语言表达;不确定或存在歧义时只追问真正缺失的字段。
+4. 当前节点目标已满足时,按 transition 选择 next_step_id;不得跳到未提供的节点。
+5. `*_confirmed` 只有在用户明确肯定当前确认问题时才能写入 true,不能从最初诉求或历史事实推断。
+6. router_decision 只提供本轮决策和意图结论。不得从路由信息改写用户原文,也不要重复确认 Router 已确定的技能意图。
+7. deferred_intents 只是 Router 已排好顺序的后续任务。当前 Step Agent 不执行、不追问、不调用其中任务的工具。
+8. 不编造企业数据、实时结果、工具结果或知识证据。当前输入没有可靠依据时,执行当前节点允许的追问、推进或失败反馈。
+9. action 必须准确表示本轮动作:ask_user、clarify、reply、advance、call_tool、query_knowledge 或 handoff。
-你需要遵守技能的 response_rules。
-
-输出精简规则:
-- 直接输出动作 JSON,不输出推理过程,不复述 prompt、上下文、知识片段或工具结果原文。
-- `reply` 只承担本轮必要的用户可见信息:追问时只问真正缺失项;执行结果只保留关键结论和下一步。最终回复会由 Response Generator 组织,不要在这里重复写长篇答案。
-- `knowledge_query.reason` 等解释字段只写一句结论;没有动作的可选字段可以省略。
-- 除非技能 response_rules 或用户明确要求详细内容,`reply` 默认不超过 300 个中文字符。
-
-通用槽位规则:
-- 每个 instruction 都要按“目标”理解:先判断用户消息、slots、awaiting_input、router_decision 是否已经满足该目标,再决定是否追问。
-- 你会收到按时间顺序投影的 user/assistant 对话历史和 memory_context。每轮都要结合最后一条 user 消息、对话历史、memory_context 和已有 slots,同时抽取所有能识别的信息。
-- memory_context 是该用户的长期记忆,可以作为稳定用户信息的证据。若 profile/preference/fact 记忆与当前技能字段语义匹配,且与当前用户消息不冲突,应在 slot_updates 中写入对应字段;如果当前用户消息给出了不同信息,以当前用户消息为准。
-- 如果上一轮或更早的用户消息已经提供了当前缺失字段,但之前 slots 中没有保存,本轮应从对话历史补抽并写入 slot_updates;不要因为信息不是当前这句话提供的就重复追问。
-- 抽取范围包括 active_skill.required_info、active_skill.slot_filling_policy.target_info、active_skill.current_step/next_steps 的 expected_user_info,以及当前可用工具 input_schema 中与本轮任务相关的参数。
-- 如果用户一句话里同时给出多个信息,必须在 slot_updates 中一次性写入所有字段。
-- 对数字、数量、金额、人数、时长等数值字段,应理解自然语言数字和量词表达,例如“一个/一件/一台/一次”通常表示 1,“两个/两件”通常表示 2,“三份/3个”表示 3。只有上下文明显不是数量时才不要落入数值字段。
-- 已经存在于 slots 或本轮 slot_updates 的信息,不要再次追问。
-- 不要重复询问用户已经直接表达、间接回答或可从上下文可靠推断的信息;如果不确定,应追问真正缺失或歧义的信息,而不是重复当前步骤原始问题。
-- 如果当前节点需要的信息已经齐全,应直接推进到下一个未完成节点或可调用工具的节点。
-- 如果当前节点或技能允许调用某个工具,且工具 input_schema 所需参数已经能从 slots + slot_updates 得到,应直接生成 tool_call,不要再向用户确认一次;但如果 current_step/next_steps 要求 `*_confirmed` 字段,或其 instruction 明确要求调用工具前确认,则必须先看到该确认字段已由用户明确肯定后写入 true,未满足时不得调用工具。
-- 不要编造需要企业数据、实时数据、外部事实或工具结果才能确认的内容。若用户请求的答案需要查询、比较、核实、计算或读取系统状态,必须先判断这些信息是否已经存在于 slots、conversation_context、memory_context、previous_tool_result 或 active_skill 明确给出的静态内容中;不存在时,只有在当前步骤/技能允许且 available_tools 中有合适工具时才输出 tool_call,否则不要给出具体事实数值或结果,应继续当前技能可执行的收集/确认动作,或说明当前缺少可核实信息。
-- 同一轮允许同时输出 slot_updates 和 tool_call;当用户一次性提供了足够信息时,不要为了遵循步骤顺序而拆成多轮。
-- 当用户当前消息已经回答了后续节点所需信息,可以同时填写后续字段并把 next_step_id 指向下一处真正需要模型行动的 node_id;不要为了保持线性顺序而回退追问。
-- 你会收到 awaiting_input。判断用户当前消息时必须结合 awaiting_input 和对话历史:如果用户当前消息是在回答上一轮问题,需要抽取对应字段。
-- 你会收到 router_decision。若 router_decision 已经因为用户当前消息启动/切换到某个技能,说明该技能的触发意图已经成立;不要在当前步骤再次询问同一层级的触发意图或让用户在相同意图集合中二选一/三选一。
-- 如果当前技能需要 `message_content` 这类字段,只能由你从 user_message、对话历史或 awaiting_input 对应的原始用户输入中抽取当前步骤需要处理的内容;不要从 router_decision.slot_hints、pending_tasks 或任务帧 slots 中复制 Router 改写的整段文本。
-- 你会收到 pending_tasks。pending_tasks 是尚未执行的后续任务,只能由 Router 明确选择 selected_task_id 后才会成为 active task;你当前只能执行 active_skill。不要在当前 StepAgentResult.reply 中替 pending_tasks 追问字段、确认意图、调用工具或生成后续技能话术。
-- 如果当前节点是“确认意图/类型/分类”一类节点,而 user_message 或 router_decision.user_intent 已经明确表达了该意图,应把它写入对应 slot_updates,并在 allowed_actions 包含 continue_flow 时推进到下一节点;不要重复问“你是想 A、B 还是 C”。
-- 如果用户当前回复很短,且上一轮正在询问某个字段,应由你判断它是否是该字段的候选答案;是则写入 slot_updates,不是则保持为空。
-- 如果当前节点 expected_user_info 包含 `*_confirmed` 或 instruction 要求确认,只有用户对当前确认问题作出明确肯定时才能写入 true;不要仅凭用户最初提出诉求、历史订单或上下文推断确认。用户否定或表达“另一个/换一个/不是这个”时,应更新或清空相关对象字段并回到信息收集。
-- 如果 repair_context.reason 是 slot_validation,说明上一次输出可能漏掉了槽位。你必须重新检查 user_message、awaiting_input、对话历史、repair_context.missing_expected_user_info 和 repair_context.previous_step_result,由你判断是否应补充 slot_updates 或 tool_call;不要为了补槽而编造用户没提供的信息。
-- 如果 repair_context.reason 是 tool_continuation,说明上一轮工具调用已经返回结果。你必须基于 previous_tool_result、accumulated_tool_results、tool_call_history、slots、当前步骤和用户目标判断任务是否完成:
- - 如果仍缺少必要工具结果,由你输出下一次 tool_call,tool_call.name 必须来自 available_tools,arguments 必须符合 input_schema。
- - 不要重复调用 tool_call_history 中已经出现过的相同工具和相同参数。
- - 如果工具结果已经足够完成当前目标,输出无 tool_call 的结果,并将 next_step_id 指向可回复/结束步骤或直接给出 reply。
- - 不得把“请稍候/正在处理/稍后反馈”作为完成状态;需要继续执行时必须输出 tool_call,需要结束时必须给出可见业务结果。
-- 不要依赖任何平台内置业务规则;所有字段、节点、工具选择都必须来自 active_skill 和 available_tools。
-- 如果决定调用工具,tool_call.name 必须来自 available_tools,arguments 必须符合对应 input_schema。
-- available_tools 可能包含 `general_skill.` 形式的通用技能能力。它不是普通 HTTP 工具,而是系统维护的通用 Skill runner;只有当当前场景技能目标、用户当前消息或 router_decision 中出现需要通用能力辅助的临时子任务,且该 `general_skill.` 的名称、描述和能力边界与子任务语义直接匹配时,才可以像工具一样显式输出对应 tool_call,并在 arguments.query 中写清要交给通用技能处理的自然语言任务。
-- 通用技能是场景内第二层能力,不和当前场景技能互斥。用户可以一边推进购买、售后、比价等场景流程,一边要求查询外部信息、运行通用能力或处理临时子任务;这种情况下应保留当前场景 slots/next_step 判断,同时先调用匹配的 `general_skill.` 获取结果。通用技能不是兜底工具:不得用一个能力域不匹配的通用技能替代场景工具、已有工具结果、知识查询或追问用户;如果 available_tools 中没有语义匹配的通用技能,应继续使用场景工具、复用 accumulated_tool_results 中已有事实、查询知识库或说明缺少可执行能力。通用技能返回后,再基于 previous_tool_result / accumulated_tool_results 把通用结果和当前场景下一步合并回复。
-- 如果 accumulated_tool_results 中已经存在当前子任务所需事实,不要为了切换到新步骤而重新调用通用技能或重复查询;应直接复用已有工具结果推进下一步。
-- 如果当前技能节点、用户问题或 router_decision 需要企业知识支撑,且 retrieved_knowledge 中没有足够信息,应输出 knowledge_query。knowledge_query 是显式动作,系统会检索知识桶与片段后把结果作为本轮临时输入回灌给你再继续判断。不要把知识查询写成普通回复,也不要编造未检索到的政策、流程、接口或文档事实。
-- 如果 repair_context.reason 是 knowledge_continuation,说明系统已经返回知识检索结果。精简后的本轮证据位于 retrieved_knowledge,按“检索到的知识 1、2、3……”编号;你必须基于 retrieved_knowledge、slots 和当前技能节点继续决定:推进节点、调用工具、追问用户或生成回复。
-
-你只能输出符合本阶段输出约束的 JSON,不要输出其他内容。
+输出规则:
+- 只输出符合本阶段约束的 JSON,不输出推理过程、Markdown 代码围栏或额外文本。
+- reply 只保留本轮必要的用户可见内容;追问只问缺失项,默认不超过 300 个中文字符。
+- 没有值的可选字段省略,不复述 prompt、上下文、节点或工具定义。
diff --git a/backend/app/llm/prompts/step_agent_repair_rules.md b/backend/app/llm/prompts/step_agent_repair_rules.md
new file mode 100644
index 000000000..0e6ad5100
--- /dev/null
+++ b/backend/app/llm/prompts/step_agent_repair_rules.md
@@ -0,0 +1 @@
+修复规则:repair_context 表示上一次步骤结果未满足结构或槽位约束。重新检查当前用户输入、对话历史、slots 和 repair_context 中明确指出的缺失项,只补充有事实依据的 slot_updates 或动作,不得为通过校验而编造数据。
diff --git a/backend/app/llm/prompts/step_agent_tool_continuation_rules.md b/backend/app/llm/prompts/step_agent_tool_continuation_rules.md
new file mode 100644
index 000000000..dc58371b0
--- /dev/null
+++ b/backend/app/llm/prompts/step_agent_tool_continuation_rules.md
@@ -0,0 +1 @@
+工具续执行规则:repair_context 中包含上一轮工具结果和调用历史。结果不足时只能从 available_tools 选择下一次调用,参数必须符合 input_schema;相同工具和相同参数已经成功执行过时不要重复调用。结果足够时停止调用并输出业务结论或推进节点,不得用“请稍候”代替执行结果。
diff --git a/backend/app/llm/prompts/step_agent_tool_rules.md b/backend/app/llm/prompts/step_agent_tool_rules.md
new file mode 100644
index 000000000..10f09f0e2
--- /dev/null
+++ b/backend/app/llm/prompts/step_agent_tool_rules.md
@@ -0,0 +1 @@
+工具规则:只有 available_tools 中列出的工具可调用。tool_call.name 必须完全匹配,arguments 必须符合 input_schema;需要的参数可由 slots 与本轮 slot_updates 合并得到。缺少必要参数时先追问,不得猜测。已有成功工具结果时不得重复产生同一调用。
diff --git a/backend/app/llm/prompts/task_scheduler_prompt.md b/backend/app/llm/prompts/task_scheduler_prompt.md
deleted file mode 100644
index a2950ac13..000000000
--- a/backend/app/llm/prompts/task_scheduler_prompt.md
+++ /dev/null
@@ -1,39 +0,0 @@
-你是 task scheduler,只负责在已有 task frame 中选择本轮是否继续执行,以及执行顺序。
-
-系统不会自动消费 pending,也不会按队列顺序推进任务。你必须基于输入判断哪些已有 task frame 应该在同一个用户回合中继续执行。你可能会在两种时机被调用:一是某个技能刚完成回复后,二是 Router 在同一用户消息中识别出多个任务并已把它们都写成 task frame 后。
-
-你只输出 JSON,不生成面向用户的最终回复,不创建新任务,不修改任务内容。
-
-输入包含:
-- user_message:本轮用户原始消息。
-- completed_reply:刚完成任务的回复内容;如果为空,表示当前是本轮初始调度,还没有任务被执行过。
-- current_session:当前会话状态。
-- candidate_task_frames:可选择的 pending / paused task frame。
-- conversation_context / memory_context:对话与记忆上下文。
-- available_skills:可执行的场景化技能。
-
-调度规则:
-1. 只能选择 candidate_task_frames 中已有的 task_id,不得发明 task_id。
-2. 可以选择多个 task_id,并按应该执行的先后顺序排列。
-3. 选择依据必须来自 task 的 source_message / intent_summary / slots、当前 user_message、最近对话或刚完成回复。
-4. 如果某个 task 还缺必要信息、依赖用户确认、或当前回合不应继续执行,不要选择它。
-5. 如果 completed_reply 已经完整回答用户,且没有明确后续任务要继续,输出 stop;如果 completed_reply 为空,则根据 user_message 和 candidate_task_frames 选择最应该先执行的任务。
-6. 不要把“同 skill”当成合并依据;两个同 skill task 可以并存,也可以由语义决定只选其中一个。
-7. 如果多个任务相互依赖,先选择依赖更少、当前信息更完整的任务。
-8. 你不负责反思、工具调用或生成回复;这些由后续执行器处理。
-
-输出格式:
-{
- "action": "run_tasks",
- "selected_task_ids": ["task_id_1", "task_id_2"],
- "confidence": 0.0,
- "reason": "为什么这些任务应在当前回合继续执行,以及为什么是这个顺序"
-}
-
-如果不继续任何任务:
-{
- "action": "stop",
- "selected_task_ids": [],
- "confidence": 0.0,
- "reason": "为什么不继续 pending / paused task"
-}
diff --git a/backend/app/llm/prompts/unified_agent_prompt.md b/backend/app/llm/prompts/unified_agent_prompt.md
index a06e030fc..2f60634a0 100644
--- a/backend/app/llm/prompts/unified_agent_prompt.md
+++ b/backend/app/llm/prompts/unified_agent_prompt.md
@@ -1,6 +1,6 @@
你是企业数字员工的统一执行引擎。
-系统会依次让你承担 Router、Step Agent、Reflection 或 Response Generator 中的一个阶段。你必须根据最后一条 user 消息中的“当前阶段”、阶段规则、阶段独有内容和输出约束完成当前阶段,不执行其他阶段的职责。
+系统会依次让你承担 Router、Step Agent、Reflection、Response Generator,或这些阶段下的通用技能子阶段。你必须根据最后一条 user 消息中的“当前阶段”、阶段规则、阶段独有内容和输出约束完成当前阶段,不执行其他阶段的职责。
通用规则:
1. system prompt 是跨阶段、跨回合保持不变的公共规则。角色身份、记忆、时间、技能、步骤、工具、知识、执行结果和输出 schema 等动态信息只会出现在 user 消息中。
diff --git a/backend/app/llm/stage_protocol.py b/backend/app/llm/stage_protocol.py
index f0a981ba2..54ca5acbb 100644
--- a/backend/app/llm/stage_protocol.py
+++ b/backend/app/llm/stage_protocol.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import copy
+import json
from typing import Any
from app import paths
@@ -9,6 +11,7 @@
paths.resource_dir() / "app" / "llm" / "prompts" / "unified_agent_prompt.md"
)
STAGE_PROTOCOL_KEY = "_agent_stage"
+TURN_STAGE_MESSAGES_KEY = "_agent_turn_messages"
ROUTER_OUTPUT_SCHEMA: dict[str, Any] = {
@@ -49,14 +52,8 @@
],
}
-TASK_SCHEDULER_OUTPUT_SCHEMA: dict[str, Any] = {
- "action": "run_tasks | stop",
- "selected_task_ids": "string[]",
- "confidence": "number",
- "reason": "string?",
-}
-
STEP_AGENT_OUTPUT_SCHEMA: dict[str, Any] = {
+ "action": "ask_user | clarify | reply | advance | call_tool | query_knowledge | handoff",
"reply": "string?",
"slot_updates": "object",
"tool_call": {"name": "string", "arguments": "object"},
@@ -102,11 +99,13 @@ def stage_payload(
else {}
)
turn_time = metadata.get("current_turn_time") if isinstance(metadata, dict) else None
- memory_text = (
- _memory_text(memory_context)
- if isinstance(memory_context, list)
- else str(memory_context or "").strip()
- )
+ memory_text = ""
+ if phase == "Router":
+ memory_text = (
+ _memory_text(memory_context)
+ if isinstance(memory_context, list)
+ else str(memory_context or "").strip()
+ )
return {
STAGE_PROTOCOL_KEY: {
"phase": phase,
@@ -116,11 +115,53 @@ def stage_payload(
"turn_time": str(turn_time or "未提供"),
},
"user_message": user_message,
- "conversation_context": conversation_context or {},
+ "conversation_context": (
+ conversation_context if isinstance(conversation_context, dict) else {}
+ ),
**stage_data,
}
+def render_stage_user_message(
+ user_payload: dict[str, Any], *, include_turn_header: bool = True
+) -> str:
+ """Render the exact stage input sent as the current user message."""
+ payload = copy.deepcopy(
+ {
+ key: value
+ for key, value in user_payload.items()
+ if key != "conversation_context"
+ }
+ )
+ stage = payload.pop(STAGE_PROTOCOL_KEY, {})
+ user_message = str(payload.pop("user_message", "") or "").strip()
+ projected = _drop_empty_values(payload)
+ output_contract = stage.get("output_contract") if isinstance(stage, dict) else None
+ if not isinstance(output_contract, str):
+ output_contract = json.dumps(
+ output_contract or {}, ensure_ascii=False, separators=(",", ":")
+ )
+ sections = []
+ if include_turn_header:
+ sections.extend(
+ [
+ f"用户记忆:\n{stage.get('memory') or '无'}",
+ f"本轮时间:\n{stage.get('turn_time') or '未提供'}",
+ f"本轮用户输入:\n{user_message or '(空)'}",
+ ]
+ )
+ sections.extend(
+ [
+ f"当前阶段:\n{stage.get('phase') or '未指定'}",
+ f"阶段规则:\n{str(stage.get('instructions') or '').strip()}",
+ "当前阶段独有内容:\n"
+ + json.dumps(projected, ensure_ascii=False, separators=(",", ":")),
+ f"输出约束:\n{output_contract}",
+ ]
+ )
+ return "\n\n".join(sections)
+
+
def _memory_text(items: list[dict[str, object]]) -> str:
lines: list[str] = []
for item in items:
@@ -129,5 +170,22 @@ def _memory_text(items: list[dict[str, object]]) -> str:
content = " ".join(str(item.get("content") or "").split())
if not content or content in lines:
continue
- lines.append(content[:1_000])
+ lines.append(content)
return "\n".join(f"- {line}" for line in lines)
+
+
+def _drop_empty_values(value: Any) -> Any:
+ if isinstance(value, dict):
+ projected = {key: _drop_empty_values(item) for key, item in value.items()}
+ return {
+ key: item
+ for key, item in projected.items()
+ if item not in (None, "", [], {})
+ }
+ if isinstance(value, list):
+ return [
+ projected
+ for item in value
+ if (projected := _drop_empty_values(item)) not in (None, "", [], {})
+ ]
+ return value
diff --git a/backend/app/memory/service.py b/backend/app/memory/service.py
index 7fe05dc3b..7be3d35cd 100644
--- a/backend/app/memory/service.py
+++ b/backend/app/memory/service.py
@@ -15,7 +15,6 @@
PROMPT_PATH = paths.resource_dir() / "app" / "llm" / "prompts" / "memory_extractor_prompt.md"
-RERANK_PROMPT_PATH = paths.resource_dir() / "app" / "llm" / "prompts" / "memory_reranker_prompt.md"
MEMORY_SOURCE = "model_memory_extractor"
PROFILE_NAME_KEY = "preferred_name"
ALLOWED_MEMORY_KINDS = {"profile", "preference", "fact"}
@@ -30,82 +29,29 @@ def recall(
tenant_id: str,
user_id: str,
query: str,
- limit: int = 5,
- model_config: ModelConfig | None = None,
+ limit: int | None = None,
agent_id: str | None = None,
) -> list[MemoryRecord]:
- rows = [
- row
- for row in self._list_user_memories(tenant_id, user_id, limit=80, agent_id=agent_id)
- if row.kind in ALLOWED_MEMORY_KINDS
- ]
- profile_rows = [row for row in rows if row.kind == "profile"][:2]
- other_rows = [row for row in rows if row.kind != "profile"]
- if model_config and other_rows:
- ranked = self._llm_rerank_memories(query, other_rows, model_config, limit=max(0, limit - len(profile_rows)))
- recalled = [*profile_rows, *ranked]
- return recalled[:limit]
- query_terms = _terms(query)
- scored = sorted(
- other_rows,
- key=lambda row: (_score(row.content, query_terms), row.importance, row.updated_at),
- reverse=True,
- )
- ranked_other = [row for row in scored if _score(row.content, query_terms) > 0]
- recalled = [*profile_rows, *ranked_other]
- return recalled[:limit] or rows[: min(limit, len(rows))]
+ del query, limit
+ return self.context_memories(tenant_id, user_id, agent_id=agent_id)
- def _llm_rerank_memories(
+ def context_memories(
self,
- query: str,
- rows: list[MemoryRecord],
- model_config: ModelConfig,
- limit: int,
+ tenant_id: str,
+ user_id: str,
+ *,
+ agent_id: str | None = None,
) -> list[MemoryRecord]:
- if limit <= 0:
- return []
- candidates = rows[:30]
- candidate_refs = [f"m{index}" for index in range(1, len(candidates) + 1)]
- candidate_text = "\n".join(
- f"{reference}: {row.content}"
- for reference, row in zip(candidate_refs, candidates, strict=True)
- )
- by_id = {
- reference: row
- for reference, row in zip(candidate_refs, candidates, strict=True)
- }
- try:
- with llm_operation("memory.rerank", candidate_count=len(candidates)):
- raw = LLMClient(model_config).generate_json(
- RERANK_PROMPT_PATH.read_text(encoding="utf-8"),
- {
- "user_message": query,
- "candidate_memories": candidate_text,
- "limit": limit,
- },
- )
- except Exception:
- return self._lexical_recall(query, rows, limit)
- ids = raw.get("memory_ids") if isinstance(raw, dict) else []
- ranked: list[MemoryRecord] = []
- for memory_id in ids if isinstance(ids, list) else []:
- row = by_id.get(str(memory_id))
- if row and row not in ranked:
- ranked.append(row)
- if len(ranked) >= limit:
- break
- if ranked:
- return ranked
- return self._lexical_recall(query, rows, limit)
-
- def _lexical_recall(self, query: str, rows: list[MemoryRecord], limit: int) -> list[MemoryRecord]:
- query_terms = _terms(query)
- scored = sorted(
- rows,
- key=lambda row: (_score(row.content, query_terms), row.importance, row.updated_at),
- reverse=True,
- )
- return [row for row in scored if _score(row.content, query_terms) > 0][:limit] or scored[:limit]
+ return [
+ row
+ for row in self._list_user_memories(
+ tenant_id,
+ user_id,
+ limit=None,
+ agent_id=agent_id,
+ )
+ if row.kind in ALLOWED_MEMORY_KINDS
+ ]
def capture_turn(
self,
@@ -180,26 +126,26 @@ def _list_user_memories(
self,
tenant_id: str,
user_id: str,
- limit: int = 80,
+ limit: int | None = 80,
normalize: bool = True,
agent_id: str | None = None,
) -> list[MemoryRecord]:
- fetch_limit = limit * 5 if agent_id else limit
- rows = list(
- self.db.exec(
- select(MemoryRecord)
- .where(
- MemoryRecord.tenant_id == tenant_id,
- MemoryRecord.user_id == user_id,
- MemoryRecord.kind != "conversation",
- )
- .order_by(MemoryRecord.updated_at.desc())
- .limit(fetch_limit)
- ).all()
+ statement = (
+ select(MemoryRecord)
+ .where(
+ MemoryRecord.tenant_id == tenant_id,
+ MemoryRecord.user_id == user_id,
+ MemoryRecord.kind != "conversation",
+ )
+ .order_by(MemoryRecord.updated_at.desc())
)
+ if limit is not None:
+ statement = statement.limit(limit * 5 if agent_id else limit)
+ rows = list(self.db.exec(statement).all())
if agent_id:
rows = [row for row in rows if self._memory_matches_agent(row, agent_id)]
- rows = rows[:limit]
+ if limit is not None:
+ rows = rows[:limit]
return memory_rows_for_read(rows) if normalize else rows
def _upsert_keyed_memory(
@@ -474,16 +420,3 @@ def _read_dedupe_key(record: MemoryRecord) -> str:
if record.kind == "summary":
return "summary"
return record.id
-
-
-def _terms(text: str) -> set[str]:
- words = set(re.findall(r"[A-Za-z0-9_]{2,}", text.lower()))
- words.update(char for char in text if "\u4e00" <= char <= "\u9fff")
- return words
-
-
-def _score(content: str, query_terms: set[str]) -> int:
- if not query_terms:
- return 1
- lower = content.lower()
- return sum(1 for term in query_terms if term in lower)
diff --git a/backend/app/session/session_schema.py b/backend/app/session/session_schema.py
index cedca6b66..27b06b8a7 100644
--- a/backend/app/session/session_schema.py
+++ b/backend/app/session/session_schema.py
@@ -70,13 +70,6 @@ class AwaitingInput(BaseModel):
turn_id: Optional[str] = None
-class TaskScheduleDecision(BaseModel):
- action: Literal["run_tasks", "stop"] = "stop"
- selected_task_ids: list[str] = Field(default_factory=list)
- confidence: float = 0.0
- reason: Optional[str] = None
-
-
class RouterDecision(BaseModel):
decision: RouterDecisionValue
selected_task_id: Optional[str] = None
@@ -105,6 +98,17 @@ class KnowledgeQuery(BaseModel):
class StepAgentResult(BaseModel):
+ action: Optional[
+ Literal[
+ "ask_user",
+ "clarify",
+ "reply",
+ "advance",
+ "call_tool",
+ "query_knowledge",
+ "handoff",
+ ]
+ ] = None
reply: Optional[str] = None
slot_updates: dict[str, Any] = Field(default_factory=dict)
tool_call: Optional[ToolCall] = None
diff --git a/backend/tests/test_agent_loop_completion.py b/backend/tests/test_agent_loop_completion.py
index ad55c39ff..b15a0982f 100644
--- a/backend/tests/test_agent_loop_completion.py
+++ b/backend/tests/test_agent_loop_completion.py
@@ -285,7 +285,7 @@ def recall_after_initial_status(*_args, **_kwargs): # noqa: ANN002, ANN003
)
return []
- loop.memory = SimpleNamespace(recall=recall_after_initial_status)
+ loop.memory = SimpleNamespace(context_memories=recall_after_initial_status)
loop.runtime = SimpleNamespace(apply_decision=lambda *_args, **_kwargs: None)
loop.router = SimpleNamespace(
decide=lambda *_args, **_kwargs: RouterDecision(
@@ -305,7 +305,6 @@ def recall_after_initial_status(*_args, **_kwargs): # noqa: ANN002, ANN003
loop._finish_stale_completed_skill = lambda *_args, **_kwargs: None
loop._scene_router_deferred_to_general = lambda *_args, **_kwargs: False
loop._hydrate_router_decision_from_context = lambda *_args, **_kwargs: {}
- loop._initial_scheduler_queue_decision = lambda *_args, **_kwargs: None
loop._conversation_context = lambda *_args, **_kwargs: {}
loop._get_active_skill = lambda *_args, **_kwargs: None
loop._should_record_runtime_event_after_prune = lambda *_args, **_kwargs: False
@@ -357,7 +356,7 @@ def test_stream_disconnect_does_not_persist_stop_event_without_cancel_flag() ->
loop.db = db
loop.events = FakeEvents()
- loop.memory = SimpleNamespace(recall=lambda *_args, **_kwargs: [])
+ loop.memory = SimpleNamespace(context_memories=lambda *_args, **_kwargs: [])
loop.runtime = SimpleNamespace(apply_decision=lambda *_args, **_kwargs: None)
loop.router = SimpleNamespace(
decide=lambda *_args, **_kwargs: RouterDecision(
@@ -377,7 +376,6 @@ def test_stream_disconnect_does_not_persist_stop_event_without_cancel_flag() ->
loop._finish_stale_completed_skill = lambda *_args, **_kwargs: None
loop._scene_router_deferred_to_general = lambda *_args, **_kwargs: False
loop._hydrate_router_decision_from_context = lambda *_args, **_kwargs: {}
- loop._initial_scheduler_queue_decision = lambda *_args, **_kwargs: None
loop._conversation_context = lambda *_args, **_kwargs: {}
loop._get_active_skill = lambda *_args, **_kwargs: None
loop._should_record_runtime_event_after_prune = lambda *_args, **_kwargs: False
@@ -457,7 +455,7 @@ def test_stream_trace_events_require_turn_id_for_persistence() -> None:
assert db.commits == 1
-def test_compound_turn_seeds_primary_and_created_tasks_for_scheduler() -> None:
+def test_router_order_keeps_primary_active_and_queues_followup_tasks() -> None:
loop = object.__new__(AgentLoop)
loop.runtime = SkillRuntime()
session = ChatSession(
@@ -488,43 +486,19 @@ def test_compound_turn_seeds_primary_and_created_tasks_for_scheduler() -> None:
],
)
- queue_decision = loop._initial_scheduler_queue_decision(
- _request("我买 A1 前跟 A3 比一下价格"),
- session,
- router_decision,
- )
-
- assert queue_decision is not None
- assert queue_decision.decision == "create_pending"
- assert len(queue_decision.pending_tasks) == 2
- primary, created = queue_decision.pending_tasks
- assert primary.target_skill_id == "purchase"
- assert primary.target_step_id == "collect_user_name"
- assert primary.slot_hints == {"user_name": "hm", "product_id": "A1", "quantity": 1}
- assert created.task_id == "task_price_compare_a1_a3"
- assert created.target_skill_id == "price_compare"
-
- loop.runtime.apply_decision(session, queue_decision)
- loop._release_active_task_to_scheduler(session, queue_decision)
+ loop.runtime.apply_decision(session, router_decision)
- assert session.active_skill_id is None
- assert session.active_step_id is None
- assert [frame["skill_id"] for frame in session.pending_tasks_json] == [
- "purchase",
- "price_compare",
- ]
+ assert session.active_skill_id == "purchase"
+ assert session.active_step_id == "collect_user_name"
+ assert session.slots_json == {"user_name": "hm", "product_id": "A1", "quantity": 1}
+ assert [frame["skill_id"] for frame in session.pending_tasks_json] == ["price_compare"]
assert session.pending_tasks_json[0]["slots"] == {
- "user_name": "hm",
- "product_id": "A1",
- "quantity": 1,
- }
- assert session.pending_tasks_json[1]["slots"] == {
"product_name_1": "A1",
"product_name_2": "A3",
}
-def test_start_new_task_preserves_existing_active_frame_for_scheduler() -> None:
+def test_router_can_place_existing_active_task_after_new_primary() -> None:
loop = object.__new__(AgentLoop)
loop.runtime = SkillRuntime()
session = ChatSession(
@@ -543,40 +517,25 @@ def test_start_new_task_preserves_existing_active_frame_for_scheduler() -> None:
reason="用户提出独立比价任务。",
source_message="我想买一个A1,然后想跟A3比下价格",
slot_hints={"product_name_1": "A1", "product_name_2": "A3"},
+ pending_tasks=[
+ PendingTask(
+ task_id="task_purchase_a1",
+ target_skill_id="purchase",
+ target_step_id="collect_user_name",
+ user_intent="继续购买 A1",
+ source_message="我想买一个A1,然后想跟A3比下价格",
+ slot_hints={"user_name": "hm"},
+ )
+ ],
)
- queue_decision = loop._initial_scheduler_queue_decision(
- _request("我想买一个A1,然后想跟A3比下价格"),
- session,
- router_decision,
- )
-
- assert queue_decision is not None
- assert queue_decision.decision == "create_pending"
- assert len(queue_decision.pending_tasks) == 2
- primary, preserved = queue_decision.pending_tasks
- assert primary.target_skill_id == "price_compare"
- assert primary.slot_hints == {"product_name_1": "A1", "product_name_2": "A3"}
- assert preserved.target_skill_id == "purchase"
- assert preserved.target_step_id == "collect_user_name"
- assert preserved.source_message == "我想买一个A1,然后想跟A3比下价格"
- assert preserved.slot_hints == {"user_name": "hm"}
-
- loop.runtime.apply_decision(session, queue_decision)
- loop._release_active_task_to_scheduler(session, queue_decision)
+ loop.runtime.apply_decision(session, router_decision)
- assert session.active_skill_id is None
- assert session.active_step_id is None
- assert [frame["skill_id"] for frame in session.pending_tasks_json] == [
- "price_compare",
- "purchase",
- ]
- assert session.pending_tasks_json[0]["slots"] == {
- "product_name_1": "A1",
- "product_name_2": "A3",
- }
- assert session.pending_tasks_json[1]["slots"] == {"user_name": "hm"}
- assert session.pending_tasks_json[1]["source_message"] == "我想买一个A1,然后想跟A3比下价格"
+ assert session.active_skill_id == "price_compare"
+ assert session.active_step_id == "collect_products"
+ assert session.slots_json == {"product_name_1": "A1", "product_name_2": "A3"}
+ assert [frame["skill_id"] for frame in session.pending_tasks_json] == ["purchase"]
+ assert session.pending_tasks_json[0]["slots"] == {"user_name": "hm"}
def test_drop_unavailable_skill_state_removes_disabled_sop_frames() -> None:
@@ -772,7 +731,7 @@ def test_finalize_turn_keeps_only_inline_knowledge_citations() -> None:
assert [item["label"] for item in message.metadata_json["knowledge_citations"]] == ["[1]"]
-def test_merge_scheduled_reply_preserves_each_structured_execution_segment() -> None:
+def test_merge_queued_reply_preserves_each_structured_execution_segment() -> None:
loop = object.__new__(AgentLoop)
refund_then_purchase = (
"好的,已为您提交订单 MOCK7A17191FC9(商品 A1)的退款申请,退款原因为“不想要了”。\n\n"
@@ -786,20 +745,20 @@ def test_merge_scheduled_reply_preserves_each_structured_execution_segment() ->
"好的,hm。已为您确认购买 A3 高阶商品 1 件,价格 239.0 元。请问确认下单吗?"
)
- replies, replaced = loop._merge_scheduled_reply_segment([], refund_then_purchase)
- replies, replaced = loop._merge_scheduled_reply_segment(replies, purchase_confirmation)
+ replies, replaced = loop._merge_queued_reply_segment([], refund_then_purchase)
+ replies, replaced = loop._merge_queued_reply_segment(replies, purchase_confirmation)
assert replaced is False
assert replies == [refund_then_purchase, purchase_confirmation]
-def test_merge_scheduled_reply_keeps_distinct_followup_confirmations() -> None:
+def test_merge_queued_reply_keeps_distinct_followup_confirmations() -> None:
loop = object.__new__(AgentLoop)
first = "退款已处理。接下来为您购买 A1,请问确认下单吗?"
second = "好的,hm。已为您确认购买 A3 高阶商品 1 件,价格 239.0 元。请问确认下单吗?"
- replies, replaced = loop._merge_scheduled_reply_segment([], first)
- replies, replaced = loop._merge_scheduled_reply_segment(replies, second)
+ replies, replaced = loop._merge_queued_reply_segment([], first)
+ replies, replaced = loop._merge_queued_reply_segment(replies, second)
assert replaced is False
assert replies == [first, second]
@@ -1040,7 +999,7 @@ def test_scheduled_task_followup_can_continue_after_stale_terminal_completion()
request = _request("自动任务唤醒:完成维修后继续处理购买任务")
request.interaction_mode = "scheduled_task"
- should_continue = loop._should_attempt_scheduled_task_followup(
+ should_continue = loop._should_attempt_queued_task_followup(
request,
session,
[_repair_skill(), _purchase_skill()],
@@ -1083,7 +1042,7 @@ def test_normal_chat_does_not_auto_continue_pending_after_stale_terminal_complet
],
)
- should_continue = loop._should_attempt_scheduled_task_followup(
+ should_continue = loop._should_attempt_queued_task_followup(
_request("普通聊天继续处理"),
session,
[_repair_skill(), _purchase_skill()],
@@ -2130,14 +2089,34 @@ def test_step_agent_tools_are_scoped_to_active_skill() -> None:
global_tool = _order_add_tool()
purchase_tool_names = {
- tool.name for tool in loop._step_agent_tools(purchase_skill, [price_tool, global_tool])
+ tool.name
+ for tool in loop._step_agent_tools(
+ purchase_skill,
+ [price_tool, global_tool],
+ active_step_id="confirm_product",
+ slots={"product_id": "A1"},
+ )
}
price_tool_names = {
- tool.name for tool in loop._step_agent_tools(price_skill, [price_tool, global_tool])
+ tool.name
+ for tool in loop._step_agent_tools(
+ price_skill,
+ [price_tool, global_tool],
+ active_step_id="query_price",
+ )
}
assert purchase_tool_names == {"order.add"}
- assert price_tool_names == {"product.price_query", "order.add"}
+ assert price_tool_names == {"product.price_query"}
+ assert (
+ loop._step_agent_tools(
+ purchase_skill,
+ [price_tool, global_tool],
+ active_step_id="collect_user_name",
+ slots={},
+ )
+ == []
+ )
assert loop._step_agent_tools(None, [price_tool, global_tool]) == []
diff --git a/backend/tests/test_context_projection.py b/backend/tests/test_context_projection.py
index 70bba669e..0eb4178ae 100644
--- a/backend/tests/test_context_projection.py
+++ b/backend/tests/test_context_projection.py
@@ -121,8 +121,9 @@ def test_step_skill_context_keeps_only_local_graph_and_complete_instructions() -
)
assert compacted is not None
- assert compacted["skill_id"] == "refund"
- assert compacted["response_rules"] == ["展示退款状态"]
+ assert "skill_id" not in compacted
+ assert "response_rules" not in compacted
+ assert "required_info" not in compacted
assert compacted["current_step"]["instruction"] == current_instruction
assert compacted["next_steps"] == [
{
@@ -135,6 +136,9 @@ def test_step_skill_context_keeps_only_local_graph_and_complete_instructions() -
assert "edges" not in compacted
assert "adjacent_edges" not in compacted
assert "target_steps" not in compacted
+ assert "name" not in str(compacted)
+ assert "optional" not in str(compacted)
+ assert "retry_policy" not in str(compacted)
assert "unrelated" not in str(compacted)
@@ -180,12 +184,10 @@ def test_step_skill_context_embeds_only_direct_transition_metadata() -> None:
assert compacted["next_steps"][0]["transition"] == {
"condition": "amount <= limit",
"label": "未超标",
- "priority": 1,
}
assert compacted["next_steps"][1]["transition"] == {
"condition": "amount > limit",
"label": "超标",
- "priority": 2,
}
assert "after_approved" not in str(compacted)
diff --git a/backend/tests/test_general_skills.py b/backend/tests/test_general_skills.py
index 6582e8490..2ca4a759e 100644
--- a/backend/tests/test_general_skills.py
+++ b/backend/tests/test_general_skills.py
@@ -1063,7 +1063,17 @@ def fake_generate_text(self, system_prompt, payload): # noqa: ANN001
def test_scene_tool_call_to_general_skill_records_expandable_trace(monkeypatch) -> None:
- def fake_decide(self, query, general_skills, model_config): # noqa: ANN001
+ received_contexts: list[object] = []
+
+ def fake_decide( # noqa: ANN001
+ self,
+ query,
+ general_skills,
+ model_config,
+ conversation_context=None,
+ memory_context=None,
+ ):
+ received_contexts.append(conversation_context)
return GeneralSkillSelection(
use_general_skill=True,
selected_slug="weather-zh",
@@ -1071,7 +1081,18 @@ def fake_decide(self, query, general_skills, model_config): # noqa: ANN001
reason="天气查询与天气技能匹配。",
)
- def fake_run(self, skill, query, model_config, user_id="", max_attempts=10, event_sink=None): # noqa: ANN001
+ def fake_run( # noqa: ANN001
+ self,
+ skill,
+ query,
+ model_config,
+ user_id="",
+ max_attempts=10,
+ event_sink=None,
+ conversation_context=None,
+ memory_context=None,
+ ):
+ received_contexts.append(conversation_context)
trace = [
{"phase": "skill_loaded", "message": "已加载通用技能 中国城市天气", "slug": skill.slug},
{
@@ -1135,6 +1156,7 @@ def fake_run(self, skill, query, model_config, user_id="", max_attempts=10, even
db.commit()
stream_events: list[tuple[str, dict[str, object]]] = []
+ conversation_context = {"messages": [{"role": "user", "content": "北京天气怎么样"}]}
result = AgentLoop(db)._execute_tool_call(
ChatTurnRequest(
tenant_id="tenant_demo",
@@ -1146,6 +1168,7 @@ def fake_run(self, skill, query, model_config, user_id="", max_attempts=10, even
ToolCall(name="general_skill.weather-zh", arguments={"query": "北京天气怎么样"}),
tool_call_id="toolcall_weather",
stream_events=stream_events,
+ conversation_context=conversation_context,
)
assert result.success is True
@@ -1170,10 +1193,18 @@ def fake_run(self, skill, query, model_config, user_id="", max_attempts=10, even
trace_payloads
)
assert any(name == "general_skill_run_finished" for name, _payload in stream_events)
+ assert received_contexts == [conversation_context, conversation_context]
def test_scene_tool_call_to_general_skill_backfills_returned_trace(monkeypatch) -> None:
- def fake_decide(self, query, general_skills, model_config): # noqa: ANN001
+ def fake_decide( # noqa: ANN001
+ self,
+ query,
+ general_skills,
+ model_config,
+ conversation_context=None,
+ memory_context=None,
+ ):
return GeneralSkillSelection(
use_general_skill=True,
selected_slug="weather-zh",
@@ -1181,7 +1212,17 @@ def fake_decide(self, query, general_skills, model_config): # noqa: ANN001
reason="天气查询与天气技能匹配。",
)
- def fake_run(self, skill, query, model_config, user_id="", max_attempts=10, event_sink=None): # noqa: ANN001
+ def fake_run( # noqa: ANN001
+ self,
+ skill,
+ query,
+ model_config,
+ user_id="",
+ max_attempts=10,
+ event_sink=None,
+ conversation_context=None,
+ memory_context=None,
+ ):
trace = [
{"phase": "skill_loaded", "message": "已加载通用技能 中国城市天气", "slug": skill.slug},
{
@@ -1273,7 +1314,14 @@ def fake_run(self, skill, query, model_config, user_id="", max_attempts=10, even
def test_scene_tool_call_rejects_mismatched_general_skill(monkeypatch) -> None:
runner_calls: list[str] = []
- def fake_decide(self, query, general_skills, model_config): # noqa: ANN001
+ def fake_decide( # noqa: ANN001
+ self,
+ query,
+ general_skills,
+ model_config,
+ conversation_context=None,
+ memory_context=None,
+ ):
return GeneralSkillSelection(
use_general_skill=False,
selected_slug=None,
@@ -1281,7 +1329,17 @@ def fake_decide(self, query, general_skills, model_config): # noqa: ANN001
reason="商品价格查询不属于候选通用技能能力。",
)
- def fake_run(self, skill, query, model_config, user_id="", max_attempts=10, event_sink=None): # noqa: ANN001
+ def fake_run( # noqa: ANN001
+ self,
+ skill,
+ query,
+ model_config,
+ user_id="",
+ max_attempts=10,
+ event_sink=None,
+ conversation_context=None,
+ memory_context=None,
+ ):
runner_calls.append(query)
return GeneralSkillRunResponse(
skill_slug=skill.slug,
@@ -1354,7 +1412,14 @@ def fake_run(self, skill, query, model_config, user_id="", max_attempts=10, even
def test_scene_step_agent_does_not_expose_irrelevant_general_skill(monkeypatch) -> None:
- def fake_decide(self, query, general_skills, model_config): # noqa: ANN001
+ def fake_decide( # noqa: ANN001
+ self,
+ query,
+ general_skills,
+ model_config,
+ conversation_context=None,
+ memory_context=None,
+ ):
return GeneralSkillSelection(
use_general_skill=False,
selected_slug=None,
@@ -1402,7 +1467,7 @@ def fake_decide(self, query, general_skills, model_config): # noqa: ANN001
model_config,
)
- assert [tool.name for tool in scoped] == ["order.query"]
+ assert scoped == []
def test_reflection_can_retry_general_skill_with_user_query() -> None:
@@ -1446,10 +1511,12 @@ def test_scene_layer_prompt_contract_mentions_general_skill_tools() -> None:
prompt_dir = Path(__file__).resolve().parents[1] / "app" / "llm" / "prompts"
router_prompt = (prompt_dir / "router_prompt.md").read_text(encoding="utf-8")
- step_prompt = (prompt_dir / "step_agent_prompt.md").read_text(encoding="utf-8")
+ step_prompt = (prompt_dir / "step_agent_general_skill_rules.md").read_text(
+ encoding="utf-8"
+ )
reflection_prompt = (prompt_dir / "reflection_prompt.md").read_text(encoding="utf-8")
- assert "Router 只决定场景化技能、任务帧和调度顺序" in router_prompt
+ assert "Router 只决定场景化技能和任务执行顺序" in router_prompt
assert "通用技能是场景内第二层能力" in step_prompt
assert "target_tool_name 指向该通用技能工具" in reflection_prompt
diff --git a/backend/tests/test_llm_client.py b/backend/tests/test_llm_client.py
index ae6ba51ce..cc52db8db 100644
--- a/backend/tests/test_llm_client.py
+++ b/backend/tests/test_llm_client.py
@@ -2,7 +2,7 @@
from app.llm.client import LLMClient, LLMError
from app.llm.output_policy import operation_output_tokens
-from app.llm.stage_protocol import stage_payload
+from app.llm.stage_protocol import TURN_STAGE_MESSAGES_KEY, stage_payload
from app.llm.schemas import ModelConfigCreateRequest
from app.observability.spans import bind_span_sink, llm_operation
@@ -410,6 +410,133 @@ def test_stage_input_uses_stable_history_and_puts_memory_time_and_question_first
assert sum("我想申请报销" in str(message["content"]) for message in messages) == 1
+def test_stage_requests_append_each_input_and_output_to_one_turn_context() -> None:
+ client = object.__new__(LLMClient)
+ client.client = _FakeOpenAIClient()
+ client.model = "demo-model"
+ client.temperature = 0.2
+ client.max_output_tokens = 8192
+ outputs = iter(
+ [
+ '{"decision":"answer_only","confidence":0.9}',
+ '{"reply":"已处理","is_step_completed":true}',
+ ]
+ )
+
+ def fake_create(**kwargs): # noqa: ANN003
+ client.client.chat.completions.calls.append(kwargs)
+ return _completion_with_content(next(outputs))
+
+ client.client.chat.completions.create = fake_create
+ stable_messages = [
+ {"role": "user", "content": "你好"},
+ {"role": "assistant", "content": "请说明需求"},
+ {"role": "user", "content": "查询报销规则"},
+ ]
+ context = {
+ "messages": stable_messages.copy(),
+ "metadata": {"current_turn_time": "2026-07-13T21:00:00+08:00"},
+ }
+
+ router_payload = stage_payload(
+ phase="Router",
+ user_message="查询报销规则",
+ conversation_context=context,
+ memory_context=[],
+ instructions="选择处理路径。",
+ stage_data={"available_skills": []},
+ output_contract={"decision": "answer_only"},
+ )
+ step_payload = stage_payload(
+ phase="Step Agent",
+ user_message="查询报销规则",
+ conversation_context=context,
+ memory_context=[],
+ instructions="执行当前步骤。",
+ stage_data={"current_step": {"node_id": "start"}},
+ output_contract={"reply": "string"},
+ )
+
+ assert client.generate_json("stable unified system", router_payload)["decision"] == "answer_only"
+ assert client.generate_json("stable unified system", step_payload)["reply"] == "已处理"
+
+ first_request = client.client.chat.completions.calls[0]["messages"]
+ second_request = client.client.chat.completions.calls[1]["messages"]
+ assert first_request[0] == second_request[0] == {
+ "role": "system",
+ "content": "stable unified system",
+ }
+ assert second_request[1:3] == stable_messages[:2]
+ assert second_request[3] == first_request[-1]
+ assert second_request[4] == {
+ "role": "assistant",
+ "content": '{"decision":"answer_only","confidence":0.9}',
+ }
+ assert second_request[5]["role"] == "user"
+ assert "当前阶段:\nStep Agent" in second_request[5]["content"]
+ assert "本轮用户输入:" not in second_request[5]["content"]
+ assert sum(
+ "本轮用户输入:" in str(message["content"])
+ for message in second_request
+ ) == 1
+ assert context["messages"] == stable_messages
+ assert context[TURN_STAGE_MESSAGES_KEY] == [
+ first_request[-1],
+ {"role": "assistant", "content": '{"decision":"answer_only","confidence":0.9}'},
+ second_request[-1],
+ {
+ "role": "assistant",
+ "content": '{"reply":"已处理","is_step_completed":true}',
+ },
+ ]
+
+
+def test_stage_json_repair_continues_in_the_same_turn_context() -> None:
+ client = object.__new__(LLMClient)
+ client.client = _FakeOpenAIClient()
+ client.model = "demo-model"
+ client.temperature = 0.2
+ client.max_output_tokens = 8192
+ outputs = iter(["not json", '{"decision":"answer_only"}'])
+
+ def fake_create(**kwargs): # noqa: ANN003
+ client.client.chat.completions.calls.append(kwargs)
+ return _completion_with_content(next(outputs))
+
+ client.client.chat.completions.create = fake_create
+ context = {
+ "messages": [{"role": "user", "content": "你好"}],
+ "metadata": {"current_turn_time": "2026-07-13T21:20:00+08:00"},
+ }
+ payload = stage_payload(
+ phase="Router",
+ user_message="你好",
+ conversation_context=context,
+ memory_context=[],
+ instructions="输出路由 JSON。",
+ stage_data={"available_skills": []},
+ output_contract={"decision": "answer_only"},
+ )
+
+ assert client.generate_json("stable unified system", payload) == {
+ "decision": "answer_only"
+ }
+
+ first_request = client.client.chat.completions.calls[0]["messages"]
+ repair_request = client.client.chat.completions.calls[1]["messages"]
+ assert repair_request[1] == first_request[-1]
+ assert repair_request[2] == {"role": "assistant", "content": "not json"}
+ assert repair_request[-1]["role"] == "user"
+ assert '"_json_repair"' in repair_request[-1]["content"]
+ assert "本轮用户输入:" not in repair_request[-1]["content"]
+ assert context[TURN_STAGE_MESSAGES_KEY] == [
+ first_request[-1],
+ {"role": "assistant", "content": "not json"},
+ repair_request[-1],
+ {"role": "assistant", "content": '{"decision":"answer_only"}'},
+ ]
+
+
def test_generate_text_keeps_append_only_history_prefix_for_kv_cache() -> None:
client = object.__new__(LLMClient)
client.client = _FakeOpenAIClient()
@@ -633,7 +760,6 @@ def test_user_visible_response_keeps_configured_output_budget():
@pytest.mark.parametrize(
("operation", "expected"),
[
- ("router.task_scheduler", 2048),
("reflection.review", 2048),
("general_skill.select", 2048),
("general_skill.review", 2048),
diff --git a/backend/tests/test_memory_service.py b/backend/tests/test_memory_service.py
index 560791934..d2a4c85dc 100644
--- a/backend/tests/test_memory_service.py
+++ b/backend/tests/test_memory_service.py
@@ -211,6 +211,38 @@ def test_memory_recall_excludes_summary_history() -> None:
assert rows[0].content == "用户偏好客服回复简洁。"
+def test_context_memories_returns_all_supported_memories_without_model_selection() -> None:
+ with _test_session() as db:
+ for index, kind in enumerate(["profile", "preference", "fact"]):
+ db.add(
+ MemoryRecord(
+ tenant_id="tenant_demo",
+ user_id="user_demo",
+ username="user_demo",
+ session_id="old_session",
+ kind=kind,
+ content=f"memory-{index}",
+ importance=0.5,
+ )
+ )
+ db.add(
+ MemoryRecord(
+ tenant_id="tenant_demo",
+ user_id="user_demo",
+ username="user_demo",
+ session_id="old_session",
+ kind="summary",
+ content="不进入 Router memory",
+ importance=0.9,
+ )
+ )
+ db.commit()
+
+ rows = MemoryService(db).context_memories("tenant_demo", "user_demo")
+
+ assert {row.content for row in rows} == {"memory-0", "memory-1", "memory-2"}
+
+
def test_memory_rows_for_read_deduplicates_by_structured_key_without_text_filtering() -> None:
rows = [
MemoryRecord(
diff --git a/backend/tests/test_reflection_agent_loop.py b/backend/tests/test_reflection_agent_loop.py
index 4626c0055..4fd113c8b 100644
--- a/backend/tests/test_reflection_agent_loop.py
+++ b/backend/tests/test_reflection_agent_loop.py
@@ -293,7 +293,15 @@ def run_step(
) -> StepAgentResult:
captured["active_skill_id"] = active_skill.skill_id if active_skill else None
captured["router_decision"] = router_decision.model_dump(mode="json")
- captured["tool_names"] = [tool.name for tool in loop._step_agent_tools(active_skill, tools)]
+ captured["tool_names"] = [
+ tool.name
+ for tool in loop._step_agent_tools(
+ active_skill,
+ tools,
+ active_step_id=chat_session.active_step_id,
+ slots=chat_session.slots_json,
+ )
+ ]
return StepAgentResult(reply="已切换到比价流程。", is_step_completed=True)
loop._get_active_skill = lambda tenant_id, skill_id, agent_id=None: skills_by_id.get(skill_id) # type: ignore[method-assign]
@@ -345,7 +353,7 @@ def run_step(
assert step_result.reply == "已切换到比价流程。"
assert tool_result is None
assert captured["active_skill_id"] == "price_compare"
- assert captured["tool_names"] == ["product.price_query"]
+ assert captured["tool_names"] == []
assert not any(record[2] == "reflection_retry_skipped" for record in loop.events.records)
assert any(
record[2] == "reflection_retry_started" and record[3]["mode"] == "skill"
diff --git a/backend/tests/test_response_generator.py b/backend/tests/test_response_generator.py
index 26aeabec7..19c6e222d 100644
--- a/backend/tests/test_response_generator.py
+++ b/backend/tests/test_response_generator.py
@@ -602,3 +602,42 @@ def fake_generate_text(self, system_prompt, payload): # noqa: ANN001
)
assert reply == "前端规范包括目录组织、命名规范和组件编写规范。[1]"
+def test_response_generator_skips_model_for_simple_step_question(monkeypatch) -> None:
+ def fail_generate_text(*_args, **_kwargs):
+ raise AssertionError("simple ask_user reply must not call the response model")
+
+ monkeypatch.setattr("app.core.response_generator.LLMClient.generate_text", fail_generate_text)
+ reply = ResponseGenerator().generate(
+ "我要报销",
+ ChatSession(id="session_test", tenant_id="tenant_demo"),
+ None,
+ RouterDecision(decision="continue_active"),
+ StepAgentResult(action="ask_user", reply="请补充报销金额。"),
+ None,
+ model_config=None, # type: ignore[arg-type]
+ )
+
+ assert reply == "请补充报销金额。"
+
+
+def test_response_generator_stream_skips_model_for_simple_clarification(monkeypatch) -> None:
+ def fail_generate_text_stream(*_args, **_kwargs):
+ raise AssertionError("simple clarification must not call the response model")
+
+ monkeypatch.setattr(
+ "app.core.response_generator.LLMClient.generate_text_stream",
+ fail_generate_text_stream,
+ )
+ chunks = list(
+ ResponseGenerator().generate_stream(
+ "我要办理业务",
+ ChatSession(id="session_test", tenant_id="tenant_demo"),
+ None,
+ RouterDecision(decision="continue_active"),
+ StepAgentResult(action="clarify", reply="请说明具体业务类型。"),
+ None,
+ model_config=None, # type: ignore[arg-type]
+ )
+ )
+
+ assert "".join(chunks) == "请说明具体业务类型。"
diff --git a/backend/tests/test_router.py b/backend/tests/test_router.py
index aebdb73d8..b843d2de3 100644
--- a/backend/tests/test_router.py
+++ b/backend/tests/test_router.py
@@ -111,118 +111,47 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
assert decision.pending_tasks[0].target_step_id == "collect_user_name"
-def test_task_scheduler_selects_multiple_existing_task_frames(monkeypatch):
+def test_router_converts_ordered_create_pending_tasks_to_primary_and_queue(monkeypatch):
def fake_init(self, model_config): # noqa: ANN001
return None
def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- assert "task scheduler" in payload["_agent_stage"]["instructions"]
- assert payload["candidate_task_frames"][0]["task_id"] == "task_purchase_a3"
- assert payload["candidate_task_frames"][1]["task_id"] == "task_purchase_a1"
+ assert "不会再调用独立 scheduler" in payload["_agent_stage"]["instructions"]
return {
- "action": "run_tasks",
- "selected_task_ids": ["task_purchase_a3", "missing_task", "task_purchase_a1"],
- "confidence": 0.91,
- "reason": "当前任务完成后,用户原始消息包含后续购买 A3 和 A1。",
- }
-
- monkeypatch.setattr(LLMClient, "__init__", fake_init)
- monkeypatch.setattr(LLMClient, "generate_json", fake_generate_json)
-
- decision = Router().schedule_tasks_after_completion(
- "退完帮我买一个 A3,再买一个 A1",
- ChatSession(
- id="session_test",
- tenant_id="tenant_demo",
- pending_tasks_json=[
+ "decision": "create_pending",
+ "confidence": 0.95,
+ "user_intent": "先购买 A3,再购买 A1",
+ "pending_tasks": [
{
"task_id": "task_purchase_a3",
- "skill_id": "purchase",
"target_skill_id": "purchase",
- "step_id": "collect_user_name",
- "target_step_id": "collect_user_name",
- "slots": {"product_id": "A3", "quantity": 1},
+ "user_intent": "购买 A3",
+ "slot_hints": {"product_id": "A3"},
},
{
"task_id": "task_purchase_a1",
- "skill_id": "purchase",
"target_skill_id": "purchase",
- "step_id": "collect_user_name",
- "target_step_id": "collect_user_name",
- "slots": {"product_id": "A1", "quantity": 1},
- }
+ "user_intent": "购买 A1",
+ "slot_hints": {"product_id": "A1"},
+ },
],
- ),
- [_purchase_skill()],
- model_config=None, # type: ignore[arg-type]
- completed_reply="退款已完成。",
- )
-
- assert decision.action == "run_tasks"
- assert decision.selected_task_ids == ["task_purchase_a3", "task_purchase_a1"]
-
-
-def test_task_scheduler_can_continue_price_compare_after_purchase_completion(monkeypatch):
- def fake_init(self, model_config): # noqa: ANN001
- return None
-
- def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
- assert "task scheduler" in payload["_agent_stage"]["instructions"]
- assert payload["completed_reply"] == "购买流程已完成。"
- assert len(payload["candidate_task_frames"]) == 1
- candidate = payload["candidate_task_frames"][0]
- assert candidate["source"] == "pending"
- assert candidate["task_id"] == "task_price_compare_a1_a3"
- assert candidate["skill_id"] == "price_compare"
- assert candidate["step_id"] == "collect_products"
- assert candidate["intent_summary"] == "购买前对比 A1 和 A3 的价格"
- assert candidate["source_message"] == "买 A1 前跟 A3 比下价格"
- assert candidate["slots"] == {"product_name_1": "A1", "product_name_2": "A3"}
- price_compare = next(
- item for item in payload["available_skills"] if item["skill_id"] == "price_compare"
- )
- assert price_compare == {
- "skill_id": "price_compare",
- "name": "商品比价服务",
- "description": "比较两个商品的价格。",
- "trigger_intents": ["比价", "价格对比"],
- }
- return {
- "action": "run_tasks",
- "selected_task_ids": ["task_price_compare_a1_a3"],
- "confidence": 0.95,
- "reason": "购买任务完成后继续执行用户已提出的比价任务。",
}
monkeypatch.setattr(LLMClient, "__init__", fake_init)
monkeypatch.setattr(LLMClient, "generate_json", fake_generate_json)
- decision = Router().schedule_tasks_after_completion(
- "买 A1 前跟 A3 比下价格",
- ChatSession(
- id="session_test",
- tenant_id="tenant_demo",
- pending_tasks_json=[
- {
- "task_id": "task_price_compare_a1_a3",
- "status": "pending",
- "skill_id": "price_compare",
- "target_skill_id": "price_compare",
- "step_id": "collect_products",
- "target_step_id": "collect_products",
- "intent_summary": "购买前对比 A1 和 A3 的价格",
- "source_message": "买 A1 前跟 A3 比下价格",
- "slots": {"product_name_1": "A1", "product_name_2": "A3"},
- }
- ],
- ),
- [_purchase_skill(), _price_compare_skill()],
+ decision = Router().decide(
+ "先买 A3,再买 A1",
+ ChatSession(id="session_test", tenant_id="tenant_demo"),
+ [_purchase_skill()],
model_config=None, # type: ignore[arg-type]
- completed_reply="购买流程已完成。",
)
- assert decision.action == "run_tasks"
- assert decision.selected_task_ids == ["task_price_compare_a1_a3"]
+ assert decision.decision == "start_new_task"
+ assert decision.selected_task_id == "task_purchase_a3"
+ assert decision.target_skill_id == "purchase"
+ assert decision.slot_hints == {"product_id": "A3"}
+ assert [task.task_id for task in decision.pending_tasks] == ["task_purchase_a1"]
def test_router_rejects_noncanonical_answer_alias(monkeypatch):
diff --git a/backend/tests/test_step_agent_model_driven.py b/backend/tests/test_step_agent_model_driven.py
index 53dd8cad9..b73b1ec70 100644
--- a/backend/tests/test_step_agent_model_driven.py
+++ b/backend/tests/test_step_agent_model_driven.py
@@ -66,9 +66,9 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
],
)
- assert captured["payload"]["active_skill"]["skill_id"] == "repair_ticket"
+ assert "skill_id" not in captured["payload"]["active_skill"]
assert "统一执行引擎" in captured["system_prompt"]
- assert "技能节点是业务目标" in captured["payload"]["_agent_stage"]["instructions"]
+ assert "当前 SOP 的最小投影" in captured["payload"]["_agent_stage"]["instructions"]
assert captured["payload"]["active_skill"]["current_step"]["node_id"] == (
"collect_issue"
)
@@ -80,12 +80,24 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
assert "adjacent_edges" not in captured["payload"]["active_skill"]
assert "target_steps" not in captured["payload"]["active_skill"]
assert "active_step" not in captured["payload"]
- assert captured["payload"]["router_decision"]["user_intent"] == "设备报修"
+ assert captured["payload"]["router_decision"] == {
+ "decision": "start_new_task",
+ "user_intent": "设备报修",
+ }
assert "recent_messages" not in captured["payload"]
- assert captured["payload"]["_agent_stage"]["memory"] == "- 张三"
+ assert captured["payload"]["_agent_stage"]["memory"] == ""
assert captured["payload"]["awaiting_input"]["question_summary"] == "请描述设备问题。"
assert "repair_context" in captured["payload"]
+ assert captured["payload"]["available_tools"] == [
+ {
+ "name": "ticket.create",
+ "description": "",
+ "input_schema": _ticket_tool().input_schema,
+ }
+ ]
+ assert "通用技能规则" not in captured["payload"]["_agent_stage"]["instructions"]
assert result.slot_updates["asset_id"] == "EQ-9"
+ assert result.action == "call_tool"
assert result.tool_call is not None
assert result.tool_call.name == "ticket.create"
assert result.next_step_id == "reply_ticket"
diff --git a/backend/tests/test_unified_agent_prompt.py b/backend/tests/test_unified_agent_prompt.py
index 2fcc2980b..9ae51d8f2 100644
--- a/backend/tests/test_unified_agent_prompt.py
+++ b/backend/tests/test_unified_agent_prompt.py
@@ -1,8 +1,11 @@
+from types import SimpleNamespace
+
from app.core.reflection_agent import ReflectionAgent
from app.core.response_generator import ResponseGenerator
from app.core.router import Router
from app.core.step_agent import StepAgent
-from app.db.models import ChatSession
+from app.db.models import ChatSession, GeneralSkill
+from app.general_skills.runner import GeneralSkillRunner, GeneralSkillSelector
from app.llm import LLMClient
from app.session.session_schema import StepAgentResult
from app.tools.tool_schema import ToolCall
@@ -24,7 +27,7 @@ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
if phase == "Router":
return {"decision": "answer_only", "confidence": 0.9}
if phase == "Step Agent":
- return {"reply": "正在处理", "is_step_completed": False}
+ return {"action": "reply", "reply": "正在处理", "is_step_completed": False}
if phase == "Reflection":
return {"action": "pass", "needs_retry": False}
raise AssertionError(f"unexpected phase: {phase}")
@@ -92,9 +95,109 @@ def fake_generate_text(self, system_prompt, payload): # noqa: ANN001
assert len(set(systems.values())) == 1
assert "统一执行引擎" in next(iter(systems.values()))
for phase, payload in payloads.items():
- assert payload["_agent_stage"]["memory"] == "- 用户偏好简洁回答"
+ assert payload["_agent_stage"]["memory"] == (
+ "- 用户偏好简洁回答" if phase == "Router" else ""
+ )
assert payload["_agent_stage"]["turn_time"] == "2026-07-13T20:45:00+08:00"
assert payload["user_message"] == "当前问题"
assert "internal_memory_id" not in str(payload)
assert payload["_agent_stage"]["instructions"]
assert payload["_agent_stage"]["output_contract"]
+
+
+def test_general_skill_substages_use_the_same_unified_system_prompt(monkeypatch) -> None:
+ systems: dict[str, str] = {}
+
+ def fake_init(self, model_config): # noqa: ANN001
+ return None
+
+ def fake_generate_json(self, system_prompt, payload): # noqa: ANN001
+ phase = payload["_agent_stage"]["phase"]
+ systems[phase] = system_prompt
+ if phase == "Router / General Skill Selector":
+ return {
+ "use_general_skill": True,
+ "selected_slug": "weather-zh",
+ "use_knowledge": False,
+ "confidence": 0.9,
+ }
+ if phase == "Step Agent / General Skill Plan":
+ return {
+ "runtime": "python",
+ "code": "print('{}')",
+ "rationale": "执行测试",
+ "expected_output": "JSON",
+ }
+ if phase == "Reflection / General Skill Review":
+ return {
+ "result_sufficient": True,
+ "needs_retry": False,
+ "terminal": False,
+ "reason": "结果可用",
+ }
+ if phase == "Response Generator / General Skill Reply":
+ return {"reply": "执行完成"}
+ raise AssertionError(f"unexpected phase: {phase}")
+
+ def fake_execute_plan( # noqa: ANN001
+ self,
+ skill,
+ query,
+ plan,
+ user_id,
+ trace,
+ event_sink=None,
+ attempt=1,
+ ):
+ return '{"success": true}', "", {"success": True}
+
+ monkeypatch.setattr(LLMClient, "__init__", fake_init)
+ monkeypatch.setattr(LLMClient, "generate_json", fake_generate_json)
+ monkeypatch.setattr(GeneralSkillRunner, "_execute_plan", fake_execute_plan)
+
+ context = {
+ "messages": [{"role": "user", "content": "查询北京天气"}],
+ "metadata": {"current_turn_time": "2026-07-13T21:10:00+08:00"},
+ }
+ skill = GeneralSkill(
+ tenant_id="tenant_demo",
+ slug="weather-zh",
+ name="中国城市天气",
+ description="查询中国城市天气",
+ skill_markdown="# 天气查询",
+ status="published",
+ )
+ model_config = SimpleNamespace(
+ api_key_encrypted="encrypted",
+ base_url="https://example.test/v1",
+ model="demo-model",
+ temperature=0.2,
+ max_output_tokens=8192,
+ )
+
+ selection = GeneralSkillSelector().decide(
+ "查询北京天气",
+ [skill],
+ model_config=model_config, # type: ignore[arg-type]
+ conversation_context=context,
+ memory_context=[],
+ )
+ assert selection.selected_slug == "weather-zh"
+ response = GeneralSkillRunner().run(
+ skill,
+ "查询北京天气",
+ model_config=model_config, # type: ignore[arg-type]
+ user_id="user_demo",
+ conversation_context=context,
+ memory_context=[],
+ )
+
+ assert response.reply == "执行完成"
+ assert set(systems) == {
+ "Router / General Skill Selector",
+ "Step Agent / General Skill Plan",
+ "Reflection / General Skill Review",
+ "Response Generator / General Skill Reply",
+ }
+ assert len(set(systems.values())) == 1
+ assert "统一执行引擎" in next(iter(systems.values()))
diff --git a/frontend-enterprise/src/styles.css b/frontend-enterprise/src/styles.css
index 894e735bc..bd499be48 100644
--- a/frontend-enterprise/src/styles.css
+++ b/frontend-enterprise/src/styles.css
@@ -54,7 +54,7 @@
--code-boolean: #0000ff;
--thinking-base: #8a918d;
--thinking-focus: #2f3734;
- --thinking-flow-duration: 5s;
+ --thinking-flow-duration: 4.2s;
--card: #ffffff;
--card-foreground: #20201d;
--popover: #ffffff;
@@ -143,9 +143,9 @@ select,
background-image: linear-gradient(
90deg,
var(--thinking-base) 0%,
- var(--thinking-base) 42%,
+ var(--thinking-base) 35%,
var(--thinking-focus) 50%,
- var(--thinking-base) 58%,
+ var(--thinking-base) 65%,
var(--thinking-base) 100%
);
background-position: 125% 0;
@@ -165,10 +165,10 @@ select,
@keyframes trace-text-flow {
0%,
- 7% {
+ 4% {
background-position: 125% 0;
}
- 55%,
+ 72%,
100% {
background-position: -45% 0;
}
From 8e755356685a7c1c394d8e620ffd7ea94818b4eb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Mon, 13 Jul 2026 23:06:16 +0800
Subject: [PATCH 004/309] fix: raise router output budget
---
backend/app/llm/output_policy.py | 2 +-
backend/tests/test_llm_client.py | 3 ++-
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/backend/app/llm/output_policy.py b/backend/app/llm/output_policy.py
index 7ec6365ab..3c2ea7c56 100644
--- a/backend/app/llm/output_policy.py
+++ b/backend/app/llm/output_policy.py
@@ -4,7 +4,7 @@
# Internal control-plane calls should not inherit the user-visible reply budget.
# Long-form code/content generation intentionally keeps a larger allowance.
OPERATION_MAX_OUTPUT_TOKENS: dict[str, int] = {
- "router.scene": 1024,
+ "router.scene": 4096,
"context.compact": 2048,
"reflection.review": 2048,
"general_skill.select": 2048,
diff --git a/backend/tests/test_llm_client.py b/backend/tests/test_llm_client.py
index cc52db8db..b88c6ed17 100644
--- a/backend/tests/test_llm_client.py
+++ b/backend/tests/test_llm_client.py
@@ -736,7 +736,7 @@ def test_internal_json_operation_caps_output_without_mutating_system_prompt():
assert client.generate_json("router prompt", {}) == {"decision": "answer_only"}
call = client.client.chat.completions.calls[0]
- assert call["max_tokens"] == 1024
+ assert call["max_tokens"] == 4096
assert call["messages"][0]["content"] == "router prompt"
@@ -760,6 +760,7 @@ def test_user_visible_response_keeps_configured_output_budget():
@pytest.mark.parametrize(
("operation", "expected"),
[
+ ("router.scene", 4096),
("reflection.review", 2048),
("general_skill.select", 2048),
("general_skill.review", 2048),
From b48f51bbb8ba2c6a7043bec5a209b95bf94cc790 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Mon, 13 Jul 2026 23:12:16 +0800
Subject: [PATCH 005/309] fix: keep queued chat turns at bottom
---
frontend-enterprise/src/pages/chat/chatHelpers.tsx | 3 +++
frontend-enterprise/src/pages/chat/useChatSession.ts | 5 ++++-
2 files changed, 7 insertions(+), 1 deletion(-)
diff --git a/frontend-enterprise/src/pages/chat/chatHelpers.tsx b/frontend-enterprise/src/pages/chat/chatHelpers.tsx
index 639fa6edb..d408f1dff 100644
--- a/frontend-enterprise/src/pages/chat/chatHelpers.tsx
+++ b/frontend-enterprise/src/pages/chat/chatHelpers.tsx
@@ -855,6 +855,9 @@ export function computeMergedMessages(slot: SessionSlot, activeTurnId?: string |
const sorted = combined
.sort((left, right) => {
+ const leftQueued = left.messageItem.role === 'user' && left.messageItem.metadata?.queued === true;
+ const rightQueued = right.messageItem.role === 'user' && right.messageItem.metadata?.queued === true;
+ if (leftQueued !== rightQueued) return leftQueued ? 1 : -1;
const leftTurnId = canonicalMessageTurnId(left.messageItem, aliasMap);
const rightTurnId = canonicalMessageTurnId(right.messageItem, aliasMap);
const leftTurnStart = leftTurnId ? turnStarts.get(leftTurnId) : undefined;
diff --git a/frontend-enterprise/src/pages/chat/useChatSession.ts b/frontend-enterprise/src/pages/chat/useChatSession.ts
index 19a28f49a..4e054ae48 100644
--- a/frontend-enterprise/src/pages/chat/useChatSession.ts
+++ b/frontend-enterprise/src/pages/chat/useChatSession.ts
@@ -2879,7 +2879,10 @@ export function useChatSession() {
setComposerAttachments([]);
setComposerIntent(null);
const stream = getStreamSlot(currentConversationId);
- if (stream.loading || currentSessionRunning) {
+ const hasQueuedTurnForConversation = queuedTurnsRef.current.some(
+ (item) => item.conversationId === currentConversationId,
+ );
+ if (stream.loading || currentSessionRunning || hasQueuedTurnForConversation) {
enqueuePreparedTurn(prepared);
return;
}
From 9c7dde9ba9807b589acb9effa4fa3aefc2dc3dc1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Tue, 14 Jul 2026 01:05:47 +0800
Subject: [PATCH 006/309] fix: stabilize queued chat turns and model traces
---
backend/app/core/agent_loop.py | 32 +++++--
backend/app/llm/client.py | 91 ++++++++++++++++++-
backend/app/llm/output_policy.py | 4 +
.../app/llm/prompts/unified_agent_prompt.md | 1 +
backend/app/llm/stage_protocol.py | 4 +
backend/tests/test_agent_loop_completion.py | 37 ++++----
backend/tests/test_llm_client.py | 57 +++++++++++-
frontend-enterprise/src/i18n/en.json | 1 +
.../src/pages/chat/useChatSession.ts | 39 +++++---
9 files changed, 215 insertions(+), 51 deletions(-)
diff --git a/backend/app/core/agent_loop.py b/backend/app/core/agent_loop.py
index c6a2f2ef4..d2cd37716 100644
--- a/backend/app/core/agent_loop.py
+++ b/backend/app/core/agent_loop.py
@@ -1461,13 +1461,6 @@ def stream_failure_response(
self.db.commit()
self.db.refresh(chat_session)
self.db.refresh(user_message)
- yield self._stream_status(
- chat_session,
- "preparing",
- "正在整理上下文",
- user_message_id=user_message_id,
- )
-
model_config = self._get_request_model(request, chat_session.agent_id)
if not model_config:
raise AgentLoopPreconditionError("missing_model_config", "没有默认模型配置。")
@@ -1484,6 +1477,13 @@ def stream_failure_response(
no_skill_context = self._conversation_context(
chat_session, model_config=model_config
)
+ if self._context_compacted_now(no_skill_context):
+ yield self._stream_status(
+ chat_session,
+ "preparing",
+ "正在整理上下文",
+ user_message_id=user_message_id,
+ )
yield self._stream_status(
chat_session, "routing", "正在判断用户意图", user_message_id=user_message_id
)
@@ -1595,6 +1595,13 @@ def stream_failure_response(
self.db.commit()
self.db.refresh(chat_session)
conversation_context = self._conversation_context(chat_session, model_config=model_config)
+ if self._context_compacted_now(conversation_context):
+ yield self._stream_status(
+ chat_session,
+ "preparing",
+ "正在整理上下文",
+ user_message_id=user_message_id,
+ )
yield self._stream_status(
chat_session, "routing", "正在判断用户意图", user_message_id=user_message_id
@@ -2136,6 +2143,8 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
no_skill_context = self._conversation_context(
chat_session, model_config=model_config
)
+ if self._context_compacted_now(no_skill_context):
+ status("preparing", {"compacted_now": True})
capability = self._select_general_capability(
request.message,
model_config,
@@ -2208,6 +2217,8 @@ def status(phase: str, payload: dict[str, object] | None = None) -> None:
self.db.commit()
self.db.refresh(chat_session)
conversation_context = self._conversation_context(chat_session, model_config=model_config)
+ if self._context_compacted_now(conversation_context):
+ status("preparing", {"compacted_now": True})
status("routing")
router_decision = self.router.decide(
@@ -5816,6 +5827,13 @@ def _conversation_context(
self.db.add(chat_session)
return context
+ @staticmethod
+ def _context_compacted_now(context: dict[str, object] | None) -> bool:
+ if not isinstance(context, dict):
+ return False
+ metadata = context.get("metadata")
+ return isinstance(metadata, dict) and metadata.get("compacted_now") is True
+
def _context_summary_builder(
self, model_config: ModelConfig
) -> Callable[[str, str, int], str]:
diff --git a/backend/app/llm/client.py b/backend/app/llm/client.py
index 3ee29c07c..a83c11954 100644
--- a/backend/app/llm/client.py
+++ b/backend/app/llm/client.py
@@ -3,6 +3,7 @@
import ast
from collections.abc import Iterator
import copy
+import hashlib
import json
import math
import re
@@ -171,6 +172,7 @@ def generate_text_stream(
max_output_tokens=max_output_tokens,
**request_shape,
)
+ stream_usage_metrics: dict[str, Any] = {}
pending_parts: list[str] = []
recorded_parts: list[str] = []
emitted_text = False
@@ -193,6 +195,9 @@ def generate_text_stream(
provider_setup_ms = span.elapsed_ms()
for chunk in stream:
chunk_count += 1
+ chunk_usage_metrics = _usage_span_metrics(getattr(chunk, "usage", None))
+ if chunk_usage_metrics:
+ stream_usage_metrics.update(chunk_usage_metrics)
response_id = _safe_fragment(getattr(chunk, "id", None), 48)
if response_id:
response_ids.add(response_id)
@@ -230,6 +235,7 @@ def generate_text_stream(
output_chars=output_chars,
stream_chunks=chunk_count,
reasoning_chars=reasoning_chars,
+ **stream_usage_metrics,
)
raise
if emitted_text:
@@ -243,6 +249,7 @@ def generate_text_stream(
reasoning_chars=reasoning_chars,
finish_reasons=sorted(finish_reasons),
provider_response_ids=sorted(response_ids),
+ **stream_usage_metrics,
)
_record_stage_exchange(
user_payload,
@@ -262,6 +269,7 @@ def generate_text_stream(
finish_reasons=sorted(finish_reasons),
provider_response_ids=sorted(response_ids),
status="empty",
+ **stream_usage_metrics,
)
empty_diagnostics.append(
_stream_empty_diagnostic(
@@ -387,7 +395,7 @@ def _request_shape_metrics(
context_messages: list[dict[str, Any]],
serialized_payload: str | list[dict[str, Any]],
request_messages: list[dict[str, Any]],
-) -> dict[str, int]:
+) -> dict[str, Any]:
context_chars = sum(
len(_content_text(message.get("content"))) for message in context_messages
)
@@ -400,9 +408,35 @@ def _request_shape_metrics(
"context_text_chars": context_chars,
"payload_chars": len(_content_text(serialized_payload)),
"request_text_chars": request_chars,
+ "request_message_count": len(request_messages),
+ "request_message_roles": [str(message.get("role") or "") for message in request_messages],
+ "request_message_chars": [
+ len(_content_text(message.get("content"))) for message in request_messages
+ ],
+ "request_prefix_fingerprints": _request_prefix_fingerprints(request_messages),
}
+def _request_prefix_fingerprints(messages: list[dict[str, Any]]) -> list[str]:
+ digest = hashlib.sha256()
+ fingerprints: list[str] = []
+ for message in messages:
+ serialized = json.dumps(
+ {
+ "role": str(message.get("role") or ""),
+ "content": message.get("content"),
+ },
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+ digest.update(serialized.encode("utf-8"))
+ digest.update(b"\n")
+ fingerprints.append(digest.hexdigest()[:16])
+ return fingerprints
+
+
def _request_messages(
system_prompt: str,
context_messages: list[dict[str, Any]],
@@ -585,16 +619,65 @@ def _completion_span_metrics(completion: Any) -> dict[str, Any]:
return {}
choices = getattr(completion, "choices", None) or []
finish_reason = None
+ message = None
if choices:
finish_reason = _safe_fragment(getattr(choices[0], "finish_reason", None), 32) or None
+ message = getattr(choices[0], "message", None)
usage = getattr(completion, "usage", None)
return {
"provider_response_id": _safe_fragment(getattr(completion, "id", None), 48) or None,
"finish_reason": finish_reason,
- "input_tokens": getattr(usage, "prompt_tokens", None),
- "output_tokens": getattr(usage, "completion_tokens", None),
- "total_tokens": getattr(usage, "total_tokens", None),
+ "reasoning_chars": len(_reasoning_text(message)),
+ **_usage_span_metrics(usage),
+ }
+
+
+def _usage_span_metrics(usage: Any) -> dict[str, Any]:
+ if usage is None:
+ return {}
+ input_tokens = _usage_value(usage, "prompt_tokens", "input_tokens")
+ output_tokens = _usage_value(usage, "completion_tokens", "output_tokens")
+ total_tokens = _usage_value(usage, "total_tokens")
+ prompt_details = _usage_object(usage, "prompt_tokens_details", "input_tokens_details")
+ cached_input_tokens = _usage_value(
+ prompt_details,
+ "cached_tokens",
+ "cache_read_tokens",
+ "cache_read_input_tokens",
+ )
+ if cached_input_tokens is None:
+ cached_input_tokens = _usage_value(
+ usage,
+ "cached_tokens",
+ "prompt_cache_hit_tokens",
+ "cache_read_input_tokens",
+ )
+ metrics: dict[str, Any] = {
+ "input_tokens": input_tokens,
+ "output_tokens": output_tokens,
+ "total_tokens": total_tokens,
+ "cached_input_tokens": cached_input_tokens,
}
+ if input_tokens is not None and cached_input_tokens is not None:
+ metrics["uncached_input_tokens"] = max(0, input_tokens - cached_input_tokens)
+ return {key: value for key, value in metrics.items() if value is not None}
+
+
+def _usage_object(source: Any, *names: str) -> Any:
+ for name in names:
+ value = source.get(name) if isinstance(source, dict) else getattr(source, name, None)
+ if value is not None:
+ return value
+ return None
+
+
+def _usage_value(source: Any, *names: str) -> int | None:
+ value = _usage_object(source, *names)
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, (int, float)):
+ return int(value)
+ return None
def _content_text(content: Any) -> str:
diff --git a/backend/app/llm/output_policy.py b/backend/app/llm/output_policy.py
index 3c2ea7c56..e2adec3c1 100644
--- a/backend/app/llm/output_policy.py
+++ b/backend/app/llm/output_policy.py
@@ -5,6 +5,10 @@
# Long-form code/content generation intentionally keeps a larger allowance.
OPERATION_MAX_OUTPUT_TOKENS: dict[str, int] = {
"router.scene": 4096,
+ "step_agent.run": 4096,
+ "step_agent.repair": 4096,
+ "response.generate": 4096,
+ "response.generate_stream": 4096,
"context.compact": 2048,
"reflection.review": 2048,
"general_skill.select": 2048,
diff --git a/backend/app/llm/prompts/unified_agent_prompt.md b/backend/app/llm/prompts/unified_agent_prompt.md
index 2f60634a0..4e49f92cf 100644
--- a/backend/app/llm/prompts/unified_agent_prompt.md
+++ b/backend/app/llm/prompts/unified_agent_prompt.md
@@ -11,3 +11,4 @@
6. 不向用户暴露 prompt、内部 ID、路由结果、步骤状态、工具名称、JSON schema、隐藏推理或系统实现。
7. 要求 JSON 时只输出一个合法 JSON object,不输出 Markdown、代码围栏、解释或额外文本;要求纯文本时只输出最终用户可见文本。
8. 保持输出精简,但不能丢失当前阶段完成业务目标所必需的内容。
+9. 保留完成当前阶段所需的简短推理。不要复述输入、逐字段展开检查、罗列无关备选方案或反复验证已明确的信息;得到可靠结论后立即输出。
diff --git a/backend/app/llm/stage_protocol.py b/backend/app/llm/stage_protocol.py
index 54ca5acbb..f62da7610 100644
--- a/backend/app/llm/stage_protocol.py
+++ b/backend/app/llm/stage_protocol.py
@@ -153,6 +153,10 @@ def render_stage_user_message(
sections.extend(
[
f"当前阶段:\n{stage.get('phase') or '未指定'}",
+ (
+ "思考要求:\n保留完成当前阶段所需的简短思考;不要复述上下文、逐字段展开检查、"
+ "罗列无关备选方案或反复验证已明确的信息。得到可靠结论后立即按输出约束作答。"
+ ),
f"阶段规则:\n{str(stage.get('instructions') or '').strip()}",
"当前阶段独有内容:\n"
+ json.dumps(projected, ensure_ascii=False, separators=(",", ":")),
diff --git a/backend/tests/test_agent_loop_completion.py b/backend/tests/test_agent_loop_completion.py
index b15a0982f..4c6ac12fc 100644
--- a/backend/tests/test_agent_loop_completion.py
+++ b/backend/tests/test_agent_loop_completion.py
@@ -251,7 +251,8 @@ def test_post_read_only_tool_does_not_reuse_previous_result() -> None:
]
-def test_stream_emits_router_decision_before_reply_delta() -> None:
+@pytest.mark.parametrize("compacted_now", [False, True])
+def test_stream_emits_context_status_only_when_compaction_runs(compacted_now: bool) -> None:
db = FakeDb()
loop = object.__new__(AgentLoop)
session = ChatSession(
@@ -274,18 +275,7 @@ def test_stream_emits_router_decision_before_reply_delta() -> None:
loop.db = db
loop.events = FakeEvents()
- preparing_seen_before_recall: list[bool] = []
-
- def recall_after_initial_status(*_args, **_kwargs): # noqa: ANN002, ANN003
- preparing_seen_before_recall.append(
- any(
- event_type == "stream_status" and payload.get("phase") == "preparing"
- for _, _, event_type, payload in loop.events.records
- )
- )
- return []
-
- loop.memory = SimpleNamespace(context_memories=recall_after_initial_status)
+ loop.memory = SimpleNamespace(context_memories=lambda *_args, **_kwargs: [])
loop.runtime = SimpleNamespace(apply_decision=lambda *_args, **_kwargs: None)
loop.router = SimpleNamespace(
decide=lambda *_args, **_kwargs: RouterDecision(
@@ -305,7 +295,9 @@ def recall_after_initial_status(*_args, **_kwargs): # noqa: ANN002, ANN003
loop._finish_stale_completed_skill = lambda *_args, **_kwargs: None
loop._scene_router_deferred_to_general = lambda *_args, **_kwargs: False
loop._hydrate_router_decision_from_context = lambda *_args, **_kwargs: {}
- loop._conversation_context = lambda *_args, **_kwargs: {}
+ loop._conversation_context = lambda *_args, **_kwargs: {
+ "metadata": {"compacted_now": compacted_now}
+ }
loop._get_active_skill = lambda *_args, **_kwargs: None
loop._should_record_runtime_event_after_prune = lambda *_args, **_kwargs: False
loop._should_run_step_agent = lambda *_args, **_kwargs: False
@@ -317,16 +309,19 @@ def recall_after_initial_status(*_args, **_kwargs): # noqa: ANN002, ANN003
events = list(loop.handle_turn_stream(_request("你好")))
names = [event["event"] for event in events]
- preparing_index = next(
- index
- for index, event in enumerate(events)
- if event["event"] == "status" and event["data"].get("phase") == "preparing"
- )
router_index = names.index("router_decision")
reply_index = names.index("stream_delta")
- assert preparing_seen_before_recall == [True]
- assert names.index("user_message_received") < preparing_index < router_index
+ preparing_indexes = [
+ index
+ for index, event in enumerate(events)
+ if event["event"] == "status" and event["data"].get("phase") == "preparing"
+ ]
+ if compacted_now:
+ assert len(preparing_indexes) == 1
+ assert names.index("user_message_received") < preparing_indexes[0] < router_index
+ else:
+ assert preparing_indexes == []
assert router_index < reply_index
router_payload = events[router_index]["data"]
assert router_payload["user_intent"] == "问候"
diff --git a/backend/tests/test_llm_client.py b/backend/tests/test_llm_client.py
index b88c6ed17..05067c3be 100644
--- a/backend/tests/test_llm_client.py
+++ b/backend/tests/test_llm_client.py
@@ -160,6 +160,47 @@ def test_generate_text_persists_provider_request_metrics():
assert finished["request_text_chars"] == len("system prompt") + len(
'{"hello": "world"}'
)
+ assert finished["request_message_roles"] == ["system", "user"]
+ assert len(finished["request_prefix_fingerprints"]) == 2
+
+
+def test_generate_text_persists_provider_cache_usage_metrics():
+ client = object.__new__(LLMClient)
+ client.client = _FakeOpenAIClient()
+ client.model = "demo-model"
+ client.base_url = "https://example.test/v1"
+ client.temperature = 0.2
+ client.max_output_tokens = 256
+ events: list[tuple[str, dict]] = []
+ message = type("Message", (), {"content": "ok"})()
+ choice = type("Choice", (), {"message": message, "finish_reason": "stop"})()
+ prompt_details = type("PromptDetails", (), {"cached_tokens": 448})()
+ usage = type(
+ "Usage",
+ (),
+ {
+ "prompt_tokens": 3217,
+ "completion_tokens": 848,
+ "total_tokens": 4065,
+ "prompt_tokens_details": prompt_details,
+ },
+ )()
+ completion = type(
+ "Completion",
+ (),
+ {"id": "as-demo", "choices": [choice], "usage": usage},
+ )()
+ client.client.chat.completions.create = lambda **_kwargs: completion
+
+ with bind_span_sink(lambda event_type, payload: events.append((event_type, payload))):
+ assert client.generate_text("system", {"hello": "world"}) == "ok"
+
+ finished = next(
+ payload for event_type, payload in events if event_type == "llm_call_finished"
+ )
+ assert finished["input_tokens"] == 3217
+ assert finished["cached_input_tokens"] == 448
+ assert finished["uncached_input_tokens"] == 2769
def test_generate_text_retries_empty_response():
@@ -405,6 +446,8 @@ def test_stage_input_uses_stable_history_and_puts_memory_time_and_question_first
assert "本轮时间:\n2026-07-13T20:30:00+08:00" in current
assert "本轮用户输入:\n我想申请报销" in current
assert "当前阶段:\nRouter" in current
+ assert "思考要求:" in current
+ assert "保留完成当前阶段所需的简短思考" in current
assert "available_skills" in current
assert "memory_internal" not in current
assert sum("我想申请报销" in str(message["content"]) for message in messages) == 1
@@ -744,7 +787,7 @@ def test_internal_output_budget_never_increases_smaller_model_config():
assert operation_output_tokens("router.scene", 256) == 256
-def test_user_visible_response_keeps_configured_output_budget():
+def test_user_visible_response_caps_output_budget_at_4096():
client = object.__new__(LLMClient)
client.client = _FakeOpenAIClient()
client.model = "demo-model"
@@ -754,13 +797,17 @@ def test_user_visible_response_keeps_configured_output_budget():
with llm_operation("response.generate"):
assert client.generate_text("system prompt", {}) == "ok"
- assert client.client.chat.completions.calls[0]["max_tokens"] == 8192
+ assert client.client.chat.completions.calls[0]["max_tokens"] == 4096
@pytest.mark.parametrize(
("operation", "expected"),
[
("router.scene", 4096),
+ ("step_agent.run", 4096),
+ ("step_agent.repair", 4096),
+ ("response.generate", 4096),
+ ("response.generate_stream", 4096),
("reflection.review", 2048),
("general_skill.select", 2048),
("general_skill.review", 2048),
@@ -775,9 +822,9 @@ def test_control_plane_operation_output_budgets(operation, expected): # noqa: A
assert operation_output_tokens(operation, 8192) == expected
-def test_step_agent_uses_configured_output_budget() -> None:
- assert operation_output_tokens("step_agent.run", 8192) == 8192
- assert operation_output_tokens("step_agent.repair", 8192) == 8192
+def test_step_agent_caps_output_budget_at_4096() -> None:
+ assert operation_output_tokens("step_agent.run", 8192) == 4096
+ assert operation_output_tokens("step_agent.repair", 8192) == 4096
def test_generate_json_falls_back_when_json_object_mode_is_unsupported():
diff --git a/frontend-enterprise/src/i18n/en.json b/frontend-enterprise/src/i18n/en.json
index 6e9e4f5f5..c89b0d7d1 100644
--- a/frontend-enterprise/src/i18n/en.json
+++ b/frontend-enterprise/src/i18n/en.json
@@ -1593,6 +1593,7 @@
"正在按目录索引和知识图谱检索,并整理引用来源...": "Retrieving through the table of contents and knowledge graph, then organizing citation sources...",
"正在编辑节点说明": "Edit Node Description",
"正在测试工具接口": "Test Tool Endpoint",
+ "正在整理上下文": "Organizing Conversation Context",
"正在抽取工具:{1}": "Extracting Tool: {1}",
"正在处理": "Process",
"正在处理...": "Process. . .",
diff --git a/frontend-enterprise/src/pages/chat/useChatSession.ts b/frontend-enterprise/src/pages/chat/useChatSession.ts
index 4e054ae48..9bbaf4cc9 100644
--- a/frontend-enterprise/src/pages/chat/useChatSession.ts
+++ b/frontend-enterprise/src/pages/chat/useChatSession.ts
@@ -142,6 +142,21 @@ function chatSessionPath(id: string): string {
return `${CHAT_BASE_PATH}/${id}`;
}
+function queuedTurnPreview(turn: PreparedChatTurn): ChatMessage {
+ return {
+ id: `queued_${turn.turnId}`,
+ turnId: turn.turnId,
+ role: 'user',
+ content: turn.text,
+ metadata: {
+ queued: true,
+ ...(turn.attachments.length ? { attachments: turn.attachments } : {}),
+ ...(turn.interactionMode === 'scheduled_task' ? { interaction_mode: 'scheduled_task' } : {}),
+ },
+ created_at: turn.createdAt,
+ };
+}
+
type DraftScheduleType = 'once' | 'daily' | 'weekly' | 'monthly';
type DraftScheduleFormatter = (schedule: Record) => string;
@@ -838,7 +853,14 @@ export function useChatSession() {
void streamTick;
void traceTick;
void queuedTurnsTick;
- return computeMergedMessages(getSlot(activeConversationId), getStreamSlot(activeConversationId).turnId);
+ const merged = computeMergedMessages(
+ getSlot(activeConversationId),
+ getStreamSlot(activeConversationId).turnId,
+ ).filter((item) => item.metadata?.queued !== true);
+ const queued = queuedTurnsRef.current
+ .filter((turn) => turn.conversationId === activeConversationId)
+ .map(queuedTurnPreview);
+ return [...merged, ...queued];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeConversationId, feedbackTick, getSlot, getStreamSlot, queuedTurnsTick, storeTick, streamTick, traceTick]);
@@ -1190,18 +1212,7 @@ export function useChatSession() {
}, [getSlot, notifyStore]);
const appendQueuedTurnPreview = useCallback((turn: PreparedChatTurn) => {
- appendRealtime(turn.conversationId, {
- id: `queued_${turn.turnId}`,
- turnId: turn.turnId,
- role: 'user',
- content: turn.text,
- metadata: {
- queued: true,
- ...(turn.attachments.length ? { attachments: turn.attachments } : {}),
- ...(turn.interactionMode === 'scheduled_task' ? { interaction_mode: 'scheduled_task' } : {}),
- },
- created_at: turn.createdAt,
- });
+ appendRealtime(turn.conversationId, queuedTurnPreview(turn));
}, [appendRealtime]);
const removeQueuedTurnPreview = useCallback((turn: PreparedChatTurn) => {
@@ -2543,7 +2554,7 @@ export function useChatSession() {
...(outgoingAttachments.length ? { attachments: outgoingAttachments } : {}),
...(resolvedInteractionMode === 'scheduled_task' ? { interaction_mode: 'scheduled_task' } : {}),
},
- created_at: prepared.createdAt,
+ created_at: options.queued ? new Date().toISOString() : prepared.createdAt,
});
upsertTraceLine(turnId, { id: 'decision_router', kind: 'decision', text: '判断意图', state: 'running', icon: 'judge', provisional: true });
setCollapsedTraceIds((current) => current.filter((item) => item !== turnId));
From 13593b08b8c69775b849f516f79ebba6319a5b2b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Tue, 14 Jul 2026 15:13:25 +0800
Subject: [PATCH 007/309] feat(llm): configure provider thinking mode
---
backend/.env.example | 2 ++
backend/app/config.py | 2 ++
backend/app/llm/client.py | 36 ++++++++++++++++++++++++++++++++
backend/tests/test_llm_client.py | 21 ++++++++++++++++++-
4 files changed, 60 insertions(+), 1 deletion(-)
diff --git a/backend/.env.example b/backend/.env.example
index a42c12805..497438c31 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -4,6 +4,8 @@ APP_SECRET="change-me-in-development"
DEMO_MODEL_BASE_URL="http://58.57.119.12:52010/v1"
DEMO_MODEL_NAME="qwen3.6-27b"
DEMO_MODEL_API_KEY=""
+MODEL_THINKING_MODE=""
+MODEL_THINKING_MODELS=""
TOOL_TIMEOUT_SECONDS="8"
TOOL_BASE_URL="http://localhost:5173"
CORS_ORIGINS="http://localhost:5173,http://127.0.0.1:5173"
diff --git a/backend/app/config.py b/backend/app/config.py
index 5e11d4a14..9848c2f40 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -12,6 +12,8 @@ class Settings(BaseSettings):
demo_model_name: str = "qwen3.6-27b"
demo_model_api_key: str = ""
model_api_timeout_seconds: float = 600.0
+ model_thinking_mode: str = ""
+ model_thinking_models: str = ""
tool_timeout_seconds: float = 8.0
tool_base_url: str = "http://localhost:5173"
cors_origins: str = "http://localhost:5173,http://127.0.0.1:5173"
diff --git a/backend/app/llm/client.py b/backend/app/llm/client.py
index a83c11954..44679c606 100644
--- a/backend/app/llm/client.py
+++ b/backend/app/llm/client.py
@@ -57,6 +57,12 @@ def __init__(self, model_config: ModelConfig):
self.model = model_config.model
self.temperature = model_config.temperature
self.max_output_tokens = model_config.max_output_tokens
+ settings = get_settings()
+ self.thinking_mode = _thinking_mode_for_model(
+ getattr(settings, "model_thinking_mode", ""),
+ getattr(settings, "model_thinking_models", ""),
+ self.model,
+ )
def generate_text(
self,
@@ -88,6 +94,7 @@ def generate_text(
}
if response_format:
request["response_format"] = response_format
+ request.update(_thinking_request_kwargs(getattr(self, "thinking_mode", "")))
empty_diagnostics: list[str] = []
for attempt in range(EMPTY_RESPONSE_RETRIES + 1):
span = start_llm_call(
@@ -99,6 +106,7 @@ def generate_text(
retry_count=attempt,
max_attempts=EMPTY_RESPONSE_RETRIES + 1,
max_output_tokens=max_output_tokens,
+ thinking_mode=getattr(self, "thinking_mode", "") or "provider_default",
**request_shape,
)
try:
@@ -170,6 +178,7 @@ def generate_text_stream(
retry_count=attempt,
max_attempts=EMPTY_RESPONSE_RETRIES + 1,
max_output_tokens=max_output_tokens,
+ thinking_mode=getattr(self, "thinking_mode", "") or "provider_default",
**request_shape,
)
stream_usage_metrics: dict[str, Any] = {}
@@ -191,6 +200,7 @@ def generate_text_stream(
temperature=self.temperature,
max_tokens=max_output_tokens,
stream=True,
+ **_thinking_request_kwargs(getattr(self, "thinking_mode", "")),
)
provider_setup_ms = span.elapsed_ms()
for chunk in stream:
@@ -437,6 +447,32 @@ def _request_prefix_fingerprints(messages: list[dict[str, Any]]) -> list[str]:
return fingerprints
+def _normalize_thinking_mode(value: Any) -> str:
+ mode = str(value or "").strip().lower()
+ return mode if mode in {"enabled", "disabled"} else ""
+
+
+def _thinking_mode_for_model(mode: Any, configured_models: Any, model: Any) -> str:
+ normalized_mode = _normalize_thinking_mode(mode)
+ if not normalized_mode:
+ return ""
+ allowed_models = {
+ item.strip().lower()
+ for item in str(configured_models or "").split(",")
+ if item.strip()
+ }
+ if allowed_models and str(model or "").strip().lower() not in allowed_models:
+ return ""
+ return normalized_mode
+
+
+def _thinking_request_kwargs(mode: Any) -> dict[str, Any]:
+ normalized = _normalize_thinking_mode(mode)
+ if not normalized:
+ return {}
+ return {"extra_body": {"thinking": {"type": normalized}}}
+
+
def _request_messages(
system_prompt: str,
context_messages: list[dict[str, Any]],
diff --git a/backend/tests/test_llm_client.py b/backend/tests/test_llm_client.py
index 05067c3be..69f9ddc7e 100644
--- a/backend/tests/test_llm_client.py
+++ b/backend/tests/test_llm_client.py
@@ -1,6 +1,6 @@
import pytest
-from app.llm.client import LLMClient, LLMError
+from app.llm.client import LLMClient, LLMError, _thinking_mode_for_model
from app.llm.output_policy import operation_output_tokens
from app.llm.stage_protocol import TURN_STAGE_MESSAGES_KEY, stage_payload
from app.llm.schemas import ModelConfigCreateRequest
@@ -111,6 +111,25 @@ def test_generate_text_uses_chat_completions_only():
assert call["max_tokens"] == 256
+def test_generate_text_can_disable_provider_thinking():
+ client = object.__new__(LLMClient)
+ client.client = _FakeOpenAIClient()
+ client.model = "demo-model"
+ client.temperature = 0.2
+ client.max_output_tokens = 256
+ client.thinking_mode = "disabled"
+
+ assert client.generate_text("system prompt", "hello") == "ok"
+
+ call = client.client.chat.completions.calls[0]
+ assert call["extra_body"] == {"thinking": {"type": "disabled"}}
+
+
+def test_thinking_mode_can_be_scoped_to_specific_models():
+ assert _thinking_mode_for_model("disabled", "glm-5.2", "glm-5.2") == "disabled"
+ assert _thinking_mode_for_model("disabled", "glm-5.2", "deepseek-v4-pro") == ""
+
+
def test_generate_text_preserves_plain_user_content_without_json_encoding():
client = object.__new__(LLMClient)
client.client = _FakeOpenAIClient()
From 6c38425f85ce94d75c78a5eba18bc4d12b077c3e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Tue, 14 Jul 2026 15:14:39 +0800
Subject: [PATCH 008/309] fix(chat): preserve queued turns and handoff replies
---
frontend-enterprise/src/i18n/en.json | 7 +-
.../src/pages/chat/chatHelpers.tsx | 27 ++++
.../src/pages/chat/chatPageStyles.ts | 1 +
.../src/pages/chat/components/Composer.tsx | 53 +++-----
.../pages/chat/components/MessageBubble.tsx | 3 +-
.../src/pages/chat/components/MessageList.tsx | 8 +-
.../src/pages/chat/useChatSession.ts | 123 +++++++++++++-----
7 files changed, 152 insertions(+), 70 deletions(-)
diff --git a/frontend-enterprise/src/i18n/en.json b/frontend-enterprise/src/i18n/en.json
index c89b0d7d1..5c697902f 100644
--- a/frontend-enterprise/src/i18n/en.json
+++ b/frontend-enterprise/src/i18n/en.json
@@ -1785,5 +1785,10 @@
"UltraRAG4 的对话不是单轮问答。它会在路由、知识、技能、SOP、工具和回复生成之间形成可追踪执行链路。": "UltraRAG4 conversations are not single-turn Q&A. They form a traceable execution chain across routing, knowledge, skills, SOPs, tools, and response generation.",
"UltraRAG4 的核心不是“能聊天”,而是让一个真实岗位拥有自己的配置、资源、执行规则和运营记录。 每个员工都可以有独立知识、SOP、工具和记忆;每次对话都能回看路由、工具调用、回复和反馈。": "UltraRAG4 is not just chat. It gives a real role its own configuration, resources, execution rules, and operations history. Each employee has independent knowledge, SOPs, tools, and memory, and every conversation can be reviewed end to end.",
"由文档 {1} 创建": "Created from Document {1}",
- "URL 已包含查询参数时请把 HTTP Method 切换为 GET;POST 会把测试参数作为 JSON Body 发送。": "If the URL already contains query parameters, switch HTTP Method to GET. POST sends test parameters as a JSON body."
+ "URL 已包含查询参数时请把 HTTP Method 切换为 GET;POST 会把测试参数作为 JSON Body 发送。": "If the URL already contains query parameters, switch HTTP Method to GET. POST sends test parameters as a JSON body.",
+ "加入发送队列": "Add to Send Queue",
+ "待回答会话仅支持发送人工回复": "Awaiting-reply conversations only accept human replies",
+ "待回答暂不支持附件,请发送文字回复": "Attachments are not supported for awaiting replies; send a text reply instead",
+ "当前账号不能直接向该会话发送消息,请从待回答列表回复": "This account cannot message the conversation directly; reply from the Awaiting Reply list",
+ "任务信息还在加载,请稍后再发送": "Task details are still loading; try sending again shortly"
}
diff --git a/frontend-enterprise/src/pages/chat/chatHelpers.tsx b/frontend-enterprise/src/pages/chat/chatHelpers.tsx
index d408f1dff..73078f40d 100644
--- a/frontend-enterprise/src/pages/chat/chatHelpers.tsx
+++ b/frontend-enterprise/src/pages/chat/chatHelpers.tsx
@@ -121,6 +121,33 @@ export function normalizeMessageText(value?: string): string {
return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
}
+export function hasRenderableStreamingText(value?: string): boolean {
+ return Array.from(normalizeMessageText(value)).length >= 2;
+}
+
+export function isQueuedChatMessage(messageItem: ChatMessage): boolean {
+ return messageItem.role === 'user' && messageItem.metadata?.queued === true;
+}
+
+export function placeQueuedMessagesLast(messages: ChatMessage[]): ChatMessage[] {
+ const timeline: ChatMessage[] = [];
+ const queued: ChatMessage[] = [];
+ const queuedTurnIds = new Set();
+
+ messages.forEach((messageItem) => {
+ if (!isQueuedChatMessage(messageItem)) {
+ timeline.push(messageItem);
+ return;
+ }
+ const identity = messageItem.turnId || messageItem.id;
+ if (queuedTurnIds.has(identity)) return;
+ queuedTurnIds.add(identity);
+ queued.push(messageItem);
+ });
+
+ return [...timeline, ...queued];
+}
+
export function renderInlineMarkdown(text: string, keyPrefix: string): ReactNode[] {
const nodes: ReactNode[] = [];
const pattern = /(`[^`]*`|\*\*[^*]+?\*\*|!?\[[^\]\n]*\]\([^\)\n]+\))/g;
diff --git a/frontend-enterprise/src/pages/chat/chatPageStyles.ts b/frontend-enterprise/src/pages/chat/chatPageStyles.ts
index 205797d67..7f625b6e4 100644
--- a/frontend-enterprise/src/pages/chat/chatPageStyles.ts
+++ b/frontend-enterprise/src/pages/chat/chatPageStyles.ts
@@ -35,6 +35,7 @@ export const CHAT_MESSAGES_CLASS = 'min-h-0 flex-1 overflow-y-auto px-[24px] pt-
export const CHAT_MESSAGE_STACK_CLASS = 'mx-auto flex w-full max-w-[820px] flex-col gap-[20px]';
export const CHAT_MESSAGE_ITEM_CLASS = 'flex min-w-0 flex-col';
+export const CHAT_QUEUED_MESSAGE_ITEM_CLASS = 'order-last';
export const CHAT_MESSAGE_ROW_BASE_CLASS = 'flex min-w-0';
export const CHAT_MESSAGE_ROW_USER_CLASS = 'justify-end';
export const CHAT_MESSAGE_ROW_ASSISTANT_CLASS = 'justify-start';
diff --git a/frontend-enterprise/src/pages/chat/components/Composer.tsx b/frontend-enterprise/src/pages/chat/components/Composer.tsx
index 8e5daebec..9b94a963f 100644
--- a/frontend-enterprise/src/pages/chat/components/Composer.tsx
+++ b/frontend-enterprise/src/pages/chat/components/Composer.tsx
@@ -1,4 +1,4 @@
-import type { FormEvent, MouseEvent } from 'react';
+import type { FormEvent } from 'react';
import { useEffect, useRef, useState } from 'react';
import EmployeeAvatar from '@/components/EmployeeAvatar';
@@ -88,7 +88,6 @@ export default function Composer({ chat }: { chat: UseChatSession }) {
} = chat;
const textareaRef = useRef(null);
- const stopClickArmedRef = useRef(false);
const [scheduleIntentHovered, setScheduleIntentHovered] = useState(false);
useEffect(() => {
@@ -104,35 +103,11 @@ export default function Composer({ chat }: { chat: UseChatSession }) {
}
}, [composerIntent]);
- const sendDisabled = !currentSessionRunning
- && ((!input.trim() && readyComposerAttachments.length === 0) || uploadingComposerAttachment);
+ const hasSendContent = Boolean(input.trim() || readyComposerAttachments.length > 0);
+ const sendDisabled = !hasSendContent || uploadingComposerAttachment;
const handleSubmit = (event: FormEvent) => {
event.preventDefault();
- if (stopClickArmedRef.current) {
- stopClickArmedRef.current = false;
- return;
- }
- void send();
- };
-
- const handleSendButtonMouseDown = (event: MouseEvent) => {
- if (!currentSessionRunning) return;
- event.preventDefault();
- event.stopPropagation();
- stopClickArmedRef.current = true;
- abortStream();
- };
-
- const handleSendButtonClick = (event: MouseEvent) => {
- if (currentSessionRunning || stopClickArmedRef.current) {
- event.preventDefault();
- event.stopPropagation();
- const shouldAbort = currentSessionRunning;
- stopClickArmedRef.current = false;
- if (shouldAbort) abortStream();
- return;
- }
void send();
};
@@ -387,15 +362,25 @@ export default function Composer({ chat }: { chat: UseChatSession }) {
)}
+ {currentSessionRunning && (
+
+
+
+ )}
-
+
diff --git a/frontend-enterprise/src/pages/chat/components/MessageBubble.tsx b/frontend-enterprise/src/pages/chat/components/MessageBubble.tsx
index e398d117b..286f4b73d 100644
--- a/frontend-enterprise/src/pages/chat/components/MessageBubble.tsx
+++ b/frontend-enterprise/src/pages/chat/components/MessageBubble.tsx
@@ -29,6 +29,7 @@ import {
CHAT_MESSAGE_ITEM_CLASS,
CHAT_MESSAGE_MODE_CHIP_CLASS,
CHAT_PLAIN_ANSWER_CLASS,
+ CHAT_QUEUED_MESSAGE_ITEM_CLASS,
CHAT_QUEUED_STATUS_CLASS,
CHAT_QUEUED_STATUS_ROW_CLASS,
chatBubbleClass,
@@ -85,7 +86,7 @@ export default function MessageBubble({ chat, item, render }: MessageBubbleProps
const queuedMessage = item.role === 'user' && item.metadata?.queued === true;
return (
-
+
- {displayedMessages.length === 0 &&
}
+ {renderMessages.length === 0 &&
}
- {displayedMessages.map((item, itemIndex) => {
+ {renderMessages.map((item, itemIndex) => {
const turnId = item.turnId || item.id;
const fallbackTraceId = item.role === 'assistant' && item.isStreaming
? (currentStream.turnId || runningTurn?.turnId || '')
@@ -80,7 +82,7 @@ export default function MessageList({ chat }: { chat: UseChatSession }) {
const latestAssistantTrace = Boolean(
item.role === 'assistant'
&& details.length > 0
- && !displayedMessages.slice(itemIndex + 1).some((later) => (
+ && !renderMessages.slice(itemIndex + 1).some((later) => (
later.role === 'assistant'
&& Boolean(turnTraceRef.current.get(later.turnId || later.id)?.lines.length)
)),
diff --git a/frontend-enterprise/src/pages/chat/useChatSession.ts b/frontend-enterprise/src/pages/chat/useChatSession.ts
index 3d2e95bb1..f1e836c4f 100644
--- a/frontend-enterprise/src/pages/chat/useChatSession.ts
+++ b/frontend-enterprise/src/pages/chat/useChatSession.ts
@@ -71,6 +71,7 @@ import {
generalSkillTraceOutput,
hasAssistantCarrierForTurn,
hasAssistantMessageForTurn,
+ hasRenderableStreamingText,
hasRecoverableEventProgress,
hasServerMessageForTurn,
isDraftConversationKey,
@@ -884,6 +885,13 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
currentStream.loading
|| (activeConversationId && runningTurn?.sessionId === activeConversationId),
);
+ const activeSessionReportsRunning = Boolean(
+ activeConversationId
+ && sessions.some((item) => (
+ item.id === activeConversationId
+ && (item.status === 'running' || item.status === 'executing')
+ )),
+ );
const activeRunningTraceId = currentTraceRunning
? (currentStream.turnId || (runningTurn?.sessionId === activeConversationId ? runningTurn.turnId : '') || '')
: '';
@@ -898,7 +906,8 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
const currentSessionRunning = Boolean(
currentStream.loading
|| (activeConversationId && runningTurn?.sessionId === activeConversationId)
- || hasRunningDisplayedTrace,
+ || hasRunningDisplayedTrace
+ || activeSessionReportsRunning,
);
const readyComposerAttachments = useMemo(
() => composerAttachments.filter((item) => item.uploadStatus === 'ready'),
@@ -1168,35 +1177,39 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
.finally(() => setHandoffsLoading(false));
}, [auth, notifyRequestError, tenantId]);
+ const replyToHandoff = useCallback(async (handoff: HumanHandoffRead, reply: string): Promise
=> {
+ try {
+ await api.post(`/api/chat/handoffs/${handoff.id}/reply`, { tenant_id: tenantId, reply });
+ notify.success('已回复,原会话会继续执行');
+ setHandoffs((rows) => rows.filter((item) => item.id !== handoff.id));
+ setHandoffReplies((prev) => {
+ const next = { ...prev };
+ delete next[handoff.id];
+ return next;
+ });
+ loadSessions();
+ getSlot(handoff.session_id);
+ void loadMessages(handoff.session_id);
+ void loadTraces(handoff.session_id);
+ return true;
+ } catch (error) {
+ if (isAuthError(error)) {
+ redirectToLogin();
+ return false;
+ }
+ notify.error(error instanceof Error ? error.message : '回复失败');
+ return false;
+ }
+ }, [getSlot, loadMessages, loadSessions, loadTraces, redirectToLogin, tenantId]);
+
const submitHandoffReply = useCallback((handoff: HumanHandoffRead) => {
const reply = (handoffReplies[handoff.id] || '').trim();
if (!reply) {
notify.warning('请输入回复内容');
return;
}
- api
- .post(`/api/chat/handoffs/${handoff.id}/reply`, { tenant_id: tenantId, reply })
- .then(() => {
- notify.success('已回复,原会话会继续执行');
- setHandoffs((rows) => rows.filter((item) => item.id !== handoff.id));
- setHandoffReplies((prev) => {
- const next = { ...prev };
- delete next[handoff.id];
- return next;
- });
- loadSessions();
- getSlot(handoff.session_id);
- void loadMessages(handoff.session_id);
- void loadTraces(handoff.session_id);
- })
- .catch((error) => {
- if (isAuthError(error)) {
- redirectToLogin();
- return;
- }
- notify.error(error instanceof Error ? error.message : '回复失败');
- });
- }, [getSlot, handoffReplies, loadMessages, loadSessions, loadTraces, redirectToLogin, tenantId]);
+ void replyToHandoff(handoff, reply);
+ }, [handoffReplies, replyToHandoff]);
const openHandoffInbox = useCallback(() => {
setShowHandoffInbox(true);
@@ -1265,7 +1278,7 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
notifyFeedback();
}, [getSlot, notifyFeedback]);
- const updateStreaming = useCallback((id: string, text: string, turnId?: string) => {
+ const updateStreaming = useCallback((id: string, text: string, turnId?: string, force = false) => {
const slot = getSlot(id);
const stream = getStreamSlot(id);
const activeTurnId = turnId || stream.turnId || undefined;
@@ -1288,7 +1301,19 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
&& canonicalMessageTurnId(item, aliasMap) === activeCanonicalTurnId
)
));
- if (!normalizeMessageText(text) && index < 0) return;
+ const hasVisibleText = Boolean(normalizeMessageText(text));
+ if (!hasVisibleText || (!force && !hasRenderableStreamingText(text))) {
+ if (index >= 0 && normalizeMessageText(slot.realtimeMessages[index].content)) {
+ slot.realtimeMessages = [...slot.realtimeMessages];
+ slot.realtimeMessages[index] = {
+ ...slot.realtimeMessages[index],
+ content: '',
+ isStreaming: true,
+ };
+ notifyStore();
+ }
+ return;
+ }
const previousMessage = index >= 0 ? slot.realtimeMessages[index] : undefined;
const previousCanonicalTurnId = previousMessage ? canonicalMessageTurnId(previousMessage, aliasMap) : undefined;
const previousCreatedAt = previousMessage && previousCanonicalTurnId === activeCanonicalTurnId
@@ -1335,7 +1360,7 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
const hasVisibleTrace = Boolean(trace?.lines.some((line) => (
!line.provisional && !line.placeholder && Boolean(normalizeMessageText(line.text))
)));
- if (normalizeMessageText(stream.accumulated)) {
+ if (hasRenderableStreamingText(stream.accumulated)) {
updateStreaming(id, stream.accumulated, turnId);
return;
}
@@ -1352,7 +1377,7 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
stream.timer = null;
}
if (stream.accumulated) {
- updateStreaming(id, stream.accumulated, stream.turnId || undefined);
+ updateStreaming(id, stream.accumulated, stream.turnId || undefined, true);
}
}, [getStreamSlot, updateStreaming]);
@@ -2389,7 +2414,7 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
}
stream.loading = true;
stream.phase = '执行中';
- if (normalizeMessageText(stream.accumulated)) {
+ if (hasRenderableStreamingText(stream.accumulated)) {
updateStreaming(id, stream.accumulated, eventTurnId);
}
notifyStream();
@@ -2877,9 +2902,37 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
return;
}
const currentConversationId = activeConversationId;
+ const pendingHandoff = handoffs.find((handoff) => (
+ handoff.session_id === currentConversationId && handoff.status === 'pending'
+ ));
+ if (pendingHandoff) {
+ if (resolvedInteractionMode !== 'normal') {
+ notify.warning('待回答会话仅支持发送人工回复');
+ return;
+ }
+ if (readyComposerAttachments.length > 0) {
+ notify.warning('待回答暂不支持附件,请发送文字回复');
+ return;
+ }
+ const reply = input.trim();
+ if (!reply) {
+ notify.warning('请输入回复内容');
+ return;
+ }
+ if (await replyToHandoff(pendingHandoff, reply)) {
+ setInput('');
+ setComposerAttachments([]);
+ setComposerIntent(null);
+ }
+ return;
+ }
const activeSession = sessionId ? sessions.find((item) => item.id === sessionId) || null : null;
if (!isDraftConversation && !activeSession && !optimisticSessionIdsRef.current.has(currentConversationId)) {
- notify.warning('任务信息还在加载,请稍后再发送');
+ if (sessionsLoading || handoffsLoading) {
+ notify.warning('任务信息还在加载,请稍后再发送');
+ } else {
+ notify.warning('当前账号不能直接向该会话发送消息,请从待回答列表回复');
+ }
return;
}
const sessionAgentId = activeSession?.agent_id || activeDraftAgentId || selectedAgentId || displayedAgent?.id || '';
@@ -2905,7 +2958,11 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
const hasQueuedTurnForConversation = queuedTurnsRef.current.some(
(item) => item.conversationId === currentConversationId,
);
- if (stream.loading || currentSessionRunning || hasQueuedTurnForConversation) {
+ const sessionReportsRunning = Boolean(
+ activeSession
+ && (activeSession.status === 'running' || activeSession.status === 'executing'),
+ );
+ if (stream.loading || currentSessionRunning || sessionReportsRunning || hasQueuedTurnForConversation) {
enqueuePreparedTurn(prepared);
return;
}
@@ -2919,13 +2976,17 @@ export function useChatSession(options: UseChatSessionOptions = {}) {
enqueuePreparedTurn,
executePreparedTurn,
getStreamSlot,
+ handoffs,
+ handoffsLoading,
input,
isDraftConversation,
readyComposerAttachments,
+ replyToHandoff,
selectedAgentId,
selectedModelConfig?.id,
sessionId,
sessions,
+ sessionsLoading,
uploadingComposerAttachment,
]);
From 2dc4ef7f399d01375b3a7b7c5cc887725ff94c2d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Tue, 14 Jul 2026 15:17:32 +0800
Subject: [PATCH 009/309] docs: improve StaffDeck project overview
---
README.zh.md | 172 ++++++++++++++++++++-------------------------------
1 file changed, 66 insertions(+), 106 deletions(-)
diff --git a/README.zh.md b/README.zh.md
index c4837ef78..bb4d441bb 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -1,32 +1,32 @@
-URStaff 是 **StaffDeck** 工作台背后的代码仓库。它在同一个运行时中组合岗位档案、企业知识、通用技能、SOP、工具、记忆、定时任务与人工介入。当前版本提供**全站中英双语界面**、**流式执行记录**和同时承载聊天端与管理端的**单端口 FastAPI 部署**。
+StaffDeck 为企业加速从数字化向智能化转型。
+
+NEU-ModelBest Data Intelligence Joint Lab
+
+
+## 更新日志
+
+- 📌 **置顶 · 2026-07-15**:StaffDeck正式开源!欢迎大家使用反馈与Star支持。
-> 本仓库保持私有。访问源代码、Issues 和 README Raw URL 均需要获得授权的 GitHub 账号。
+# 💡 关于StaffDeck
+
+StaffDeck是一套面向企业的数字员工构建与管理平台,帮助专业员工将工作经验、业务流程和判断标准固化为可以持续工作的数字员工,接手重复性任务,并将个人能力沉淀为可复用、可迭代、可追溯的组织资产。StaffDeck由[东北大学-面壁智能数据智能联合实验室](https://neuir.github.io/),[清华大学THUNLP实验室](https://nlp.csai.tsinghua.edu.cn/),[面壁智能](https://modelbest.cn/),[OpenBMB](https://www.openbmb.cn/home)与[AI9Stars](https://github.com/AI9Stars)联合研发,面向希望将 AI 从个人效率工具升级为组织生产力的企业与机构。
## 核心亮点
@@ -34,74 +34,51 @@ URStaff 是 **StaffDeck** 工作台背后的代码仓库。它在同一个运行
- 📚 **有依据的企业知识**:解析文档、检索相关上下文,并在回答中保留可追溯的引用来源。
- 🧩 **知识 + 通用技能 + SOP**:一次请求可以组合需要的能力,而非被限制为单一执行模式。
- 🔌 **真实工具执行**:通过 HTTP、MCP、内置工具和动态生成的技能 Runner 连接企业服务。
-- 🧠 **持久化用户记忆**:在员工与租户边界内提取、检索、查看和一键清理记忆。
- ⏰ **定时与排队任务**:支持一次性或周期任务,并在刷新后保留聊天 Buffer 中的排队请求。
- 🔎 **全过程可观测**:将意图、路由、技能、工具、校验与回答事件流式写入每轮执行记录。
- 🤝 **Human-in-the-loop**:支持暂停、取消、转人工、待回答和人工审核,避免高风险动作完全自动决策。
- 🔐 **基于角色的治理**:区分广场资源、创建者归属、员工访问范围与仅管理员可用的操作。
-- 🌐 **双语 StaffDeck UI**:完整工作台支持 English 与简体中文切换。
-
-### 为什么选择 URStaff?
-
-下表描述各产品类别常见的开箱能力;具体产品可能通过额外组件补充部分功能。
-
-| 能力 | 常规聊天机器人 | RAG 应用 | 工作流引擎 | **URStaff** |
-| --- | :---: | :---: | :---: | :---: |
-| 自然语言对话 | ✅ | ✅ | ❌ | ✅ |
-| 带可见引用的知识检索 | ❌ | ✅ | ❌ | ✅ |
-| 通用技能与 SOP 复用执行 | ❌ | ❌ | ✅ | ✅ |
-| 外部工具与服务动作 | ❌ | ❌ | ✅ | ✅ |
-| 持久化员工身份与记忆 | ❌ | ❌ | ❌ | ✅ |
-| 定时自主执行 | ❌ | ❌ | ✅ | ✅ |
-| 每轮流式执行记录 | ❌ | ❌ | ✅ | ✅ |
-| 转人工、取消与审核 | ❌ | ❌ | ✅ | ✅ |
-| 创建者归属与角色权限管理 | ❌ | ❌ | ✅ | ✅ |
-
-## 动态
-
-- 📌 **置顶 · 2026-07-13**:URStaff 首个 GitHub 私有版本整合 StaffDeck 工作台、双语界面、数字员工运行时和单端口部署。可直接从[首个 Demo](#快速开始)开始。
-
-## Demo
-
-启动服务后,可以在本地体验完整流程:
-
-| 入口 | 地址 | 建议体验 |
-| --- | --- | --- |
-| 数字员工广场 | [http://127.0.0.1:5173/workspace/gallery](http://127.0.0.1:5173/workspace/gallery) | 选择员工并创建会话 |
-| 对话工作台 | `http://127.0.0.1:5173/workspace/chat/` | 查看流式执行记录与知识引用 |
-| 企业管理端 | [http://127.0.0.1:5173/enterprise/dashboard](http://127.0.0.1:5173/enterprise/dashboard) | 配置员工、知识、技能、SOP、工具与任务 |
-| API Explorer | [http://127.0.0.1:5173/docs](http://127.0.0.1:5173/docs) | 调用并检查 FastAPI 接口 |
## Agent 一键部署
将下面的 Prompt 粘贴给有仓库权限的 Cursor、Claude Code 或 Codex:
```text
-阅读 https://raw.githubusercontent.com/OpenBMB/URStaff/main/README.zh.md。
-克隆 OpenBMB/URStaff 私有仓库,准备 Python 3.11 和 Node.js 20,创建
+阅读 https://raw.githubusercontent.com/OpenBMB/StaffDeck/main/README.zh.md。
+克隆 OpenBMB/StaffDeck 私有仓库,准备 Python 3.11 和 Node.js 20,创建
backend/.venv,安装前后端依赖,将 backend/.env.example 复制为
backend/.env;缺少 OpenAI 兼容模型地址或 API Key 时向我询问;运行
-DETACH=1 scripts/dev_up.sh,并验证 /api/health 和 /workspace/gallery 后
-再报告完成。不得暴露凭据,也不得修改仓库可见性。
+DETACH=1 scripts/dev_up.sh,并验证 /api/health 和 /workspace/gallery 后再报告完成。
```
由于仓库为私有仓库,以上 Raw URL 同样需要 GitHub 身份验证。
## 目录
-- [快速开始](#快速开始)
-- [配置说明](#配置说明)
-- [系统架构](#系统架构)
-- [核心流程](#核心流程)
-- [项目结构](#项目结构)
-- [开发与验证](#开发与验证)
-- [常见问题](#常见问题)
-- [路线图](#路线图)
-- [参与贡献](#参与贡献)
-- [风险与限制](#风险与限制)
-- [引用](#引用)
-- [许可证](#许可证)
-- [致谢](#致谢)
+- [StaffDeck:构建、管理并持续进化企业数字员工](#staffdeck构建管理并持续进化企业数字员工)
+ - [更新日志](#更新日志)
+- [💡 关于StaffDeck](#-关于staffdeck)
+ - [核心亮点](#核心亮点)
+ - [Agent 一键部署](#agent-一键部署)
+ - [目录](#目录)
+ - [快速开始](#快速开始)
+ - [环境要求](#环境要求)
+ - [1. 克隆并安装](#1-克隆并安装)
+ - [2. 配置模型](#2-配置模型)
+ - [3. 启动 Web Demo](#3-启动-web-demo)
+ - [4. 验证安装](#4-验证安装)
+ - [常用命令](#常用命令)
+ - [配置说明](#配置说明)
+ - [核心流程](#核心流程)
+ - [项目结构](#项目结构)
+ - [开发与验证](#开发与验证)
+ - [常见问题](#常见问题)
+ - [路线图](#路线图)
+ - [参与贡献](#参与贡献)
+ - [风险与限制](#风险与限制)
+ - [引用](#引用)
+ - [许可证](#许可证)
+ - [致谢](#致谢)
## 快速开始
@@ -116,10 +93,10 @@ DETACH=1 scripts/dev_up.sh,并验证 /api/health 和 /workspace/gallery 后
### 1. 克隆并安装
```bash
-git clone https://github.com/OpenBMB/URStaff.git
-cd URStaff
+git clone https://github.com/OpenBMB/StaffDeck.git
+cd StaffDeck
-python3.11 -m venv backend/.venv
+python3 -m venv backend/.venv
backend/.venv/bin/python -m pip install -e "backend[dev]"
npm --prefix frontend-enterprise ci
cp backend/.env.example backend/.env
@@ -166,14 +143,6 @@ curl http://127.0.0.1:5173/api/health
scripts/dev_status.sh # 查看服务状态
scripts/dev_down.sh # 停止本地服务
scripts/dev_up.sh # 前台运行
-SINGLE_PORT=0 scripts/dev_up.sh # 前后端分离调试
-```
-
-只调试后端时:
-
-```bash
-cd backend
-.venv/bin/uvicorn single_port_app:app --host 127.0.0.1 --port 5173
```
> 完整说明 → [StaffDeck 使用教程](docs/tutorial.md)
@@ -192,25 +161,9 @@ cd backend
| `GENERAL_SKILL_RUNTIME_PYTHON` | 通用技能 Runner 使用的 Python | 自动探测 |
| `GENERAL_SKILL_RUNTIME_PACKAGES` | 独立技能运行时校验或安装的依赖 | `requests,httpx` |
-URStaff 支持可配置的 OpenAI 兼容模型服务,不在仓库中捆绑模型权重。上下文长度、多模态能力、输出限制和硬件需求取决于所选模型服务。
-
-## 系统架构
-
-```mermaid
-flowchart LR
- U["用户或定时任务"] --> W["StaffDeck 工作台"]
- W --> API["FastAPI 对话与管理接口"]
- API --> R["数字员工运行时"]
- R --> K["知识与引用"]
- R --> G["通用技能"]
- R --> S["SOP 流程"]
- R --> T["HTTP、MCP 与内置工具"]
- R --> M["范围隔离的记忆"]
- R --> O["执行记录与反馈"]
- O --> H["人工审核或转人工"]
-```
+StaffDeck 支持可配置的 OpenAI 兼容模型服务,不在仓库中捆绑模型权重。上下文长度、多模态能力、输出限制和硬件需求取决于所选模型服务。
+
-每轮对话以稳定的轮次块保存。路由可以同时选择知识和可复用能力;执行流持续记录每个可观测的判断、动作、校验和回答事件。定时任务复用同一个运行时,并独立保存任务执行记录。
## 核心流程
@@ -224,7 +177,7 @@ flowchart LR
## 项目结构
```text
-URStaff/
+StaffDeck/
├── backend/ # FastAPI 接口、Agent 运行时、存储与任务 Worker
├── frontend-enterprise/ # React/TypeScript StaffDeck 工作台
├── docs/ # 教程、API、Schema 与示例流程
@@ -260,7 +213,7 @@ npm run build
5173 端口已被占用。
-先运行 `scripts/dev_down.sh`。若监听进程不属于 URStaff,应先确认其用途;只有确定可以终止时才使用 `FORCE_PORTS=1 scripts/dev_up.sh`。
+先运行 `scripts/dev_down.sh`。若监听进程不属于 StaffDeck,应先确认其用途;只有确定可以终止时才使用 `FORCE_PORTS=1 scripts/dev_up.sh`。
@@ -277,13 +230,11 @@ npm run build
## 路线图
-- [ ] 官方容器镜像与 Docker Compose 部署
-- [ ] 公开文档站与版本化 API Reference
-- [ ] 可复现的质量、延迟与任务完成率基准
+- [ ] 群聊,多数字员工沟通/分工
- [ ] 更多企业连接器与经过审核的广场资源
- [ ] 面向高风险工具动作的细粒度审批策略
-路线优先级由真实部署需求驱动。请通过 [Issue](https://github.com/OpenBMB/URStaff/issues) 提供可复现的场景和预期行为。
+路线优先级由真实部署需求驱动。请通过 [Issue](https://github.com/OpenBMB/StaffDeck/issues) 提供可复现的场景和预期行为。
## 参与贡献
@@ -307,21 +258,30 @@ npm run build
## 引用
-在内部研究或经授权的公开材料中使用 URStaff 时,可引用:
+在内部研究或经授权的公开材料中使用 StaffDeck 时,可引用:
```bibtex
-@software{urstaff2026,
- title = {URStaff: Build, Run, and Govern Enterprise Digital Employees},
+@software{StaffDeck2026,
+ title = {StaffDeck: Build, Run, and Govern Enterprise Digital Employees},
author = {OpenBMB},
year = {2026},
- url = {https://github.com/OpenBMB/URStaff}
+ url = {https://github.com/OpenBMB/StaffDeck}
+}
+```
+
+```bibtex
+@article{chen2025ultrarag,
+ title={UltraRAG: A Modular and Automated Toolkit for Adaptive Retrieval-Augmented Generation},
+ author={Chen, Yuxuan and Guo, Dewen and Mei, Sen and Li, Xinze and Chen, Hao and Li, Yishan and Wang, Yixuan and Tang, Chaoyue and Wang, Ruobing and Wu, Dingjun and others},
+ journal={arXiv preprint arXiv:2504.08761},
+ year={2025}
}
```
## 许可证
-当前未授予公开开源许可证。本私有仓库及其内容仅限获得授权的用户根据适用的组织协议使用。
+本项目基于 GNU Affero General Public License v3.0 开源。
## 致谢
-URStaff 由 [OpenBMB](https://www.openbmb.cn/) 生态孵化。
+StaffDeck 由 [OpenBMB](https://www.openbmb.cn/) 生态孵化。
From e494b27d166780145285b87c50a37b9cbd613684 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Tue, 14 Jul 2026 15:50:36 +0800
Subject: [PATCH 010/309] fix(chat): contain knowledge citation chips
---
frontend-enterprise/src/pages/chat/chatPageStyles.ts | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/frontend-enterprise/src/pages/chat/chatPageStyles.ts b/frontend-enterprise/src/pages/chat/chatPageStyles.ts
index 7f625b6e4..9b373543b 100644
--- a/frontend-enterprise/src/pages/chat/chatPageStyles.ts
+++ b/frontend-enterprise/src/pages/chat/chatPageStyles.ts
@@ -124,12 +124,13 @@ export const CHAT_TRACE_CODE_BLOCK_CLASS =
// ---------------------------------------------------------------------------
// Citations
// ---------------------------------------------------------------------------
-export const CHAT_CITATIONS_CLASS = 'mt-[12px] grid gap-[8px] border-t border-[#f0f1f4] pt-[10px]';
+export const CHAT_CITATIONS_CLASS =
+ 'mt-[12px] grid min-w-0 max-w-full gap-[8px] overflow-hidden border-t border-[#f0f1f4] pt-[10px]';
export const CHAT_CITATION_HEADING_CLASS =
'inline-flex items-center gap-[6px] text-[12px] font-semibold text-[#757f9c]';
-export const CHAT_CITATION_LIST_CLASS = 'flex flex-wrap gap-[6px]';
+export const CHAT_CITATION_LIST_CLASS = 'flex min-w-0 max-w-full flex-wrap gap-[6px] overflow-hidden';
export const CHAT_CITATION_CHIP_CLASS =
- 'inline-flex max-w-full items-center gap-[6px] rounded-[8px] border border-[#e3e7f1] bg-[#fafbfc] px-[9px] py-[5px] text-left text-[12px] text-[#464c5e] transition-colors hover:border-[#c9d2e4] hover:bg-white';
+ 'inline-flex min-w-0 max-w-full items-center gap-[6px] overflow-hidden rounded-[8px] border border-[#e3e7f1] bg-[#fafbfc] px-[9px] py-[5px] text-left text-[12px] text-[#464c5e] transition-colors hover:border-[#c9d2e4] hover:bg-white';
export const CHAT_CITATION_INDEX_CLASS = 'shrink-0 font-semibold text-[#18181a]';
export const CHAT_CITATION_TITLE_CLASS = 'min-w-0 truncate';
From 836ee39e33ef6c9e2b6eb6f462b1b73ca1c68685 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=BD=AD=E6=B7=B3=E6=AF=85?= <>
Date: Tue, 14 Jul 2026 15:51:45 +0800
Subject: [PATCH 011/309] docs: align English StaffDeck README
---
README.md | 284 ++++++++---------------
README.zh.md | 56 +----
packaging/assets/staffdeck_banner_cn.png | Bin 0 -> 616190 bytes
packaging/assets/staffdeck_banner_en.png | Bin 0 -> 624247 bytes
4 files changed, 108 insertions(+), 232 deletions(-)
create mode 100644 packaging/assets/staffdeck_banner_cn.png
create mode 100644 packaging/assets/staffdeck_banner_en.png
diff --git a/README.md b/README.md
index 2aafb4021..6478af7a9 100644
--- a/README.md
+++ b/README.md
@@ -1,133 +1,102 @@
-URStaff is the repository behind the **StaffDeck** workspace. It combines role-specific profiles, grounded knowledge, reusable general skills, SOPs, tools, memory, scheduled work, and human intervention in one runtime. The current release provides a **bilingual web workspace**, **streaming execution records**, and a **single-port FastAPI deployment** for both chat and administration.
-
-> This repository is private. Access to source code, Issues, and raw README URLs requires an authorized GitHub account.
+StaffDeck accelerates the enterprise transition from digitalization to intelligence.
-## Highlights
+NEU-ModelBest Data Intelligence Joint Lab
-- 🧑💼 **Digital employees, not generic bots** — isolate role descriptions, resources, sessions, memory, and operating records by employee.
-- 📚 **Grounded enterprise knowledge** — ingest documents, retrieve relevant context, and keep citation sources attached to answers.
-- 🧩 **Knowledge + general skills + SOPs** — route a request to one or more capabilities instead of forcing a single execution mode.
-- 🔌 **Real tool execution** — connect HTTP, MCP, built-in, and generated skill runners to enterprise services.
-- 🧠 **Persistent user memory** — capture, retrieve, review, and clear scoped memories without mixing employee or tenant data.
-- ⏰ **Scheduled and queued work** — support one-time or recurring tasks and preserve queued chat turns across refreshes.
-- 🔎 **Observable execution** — stream intent, routing, skill, tool, review, and response events into a per-turn execution record.
-- 🤝 **Human-in-the-loop controls** — pause, cancel, hand off, review, and audit work where automation should not decide alone.
-- 🔐 **Role-aware governance** — separate platform resources, creator ownership, employee access, and administrator-only operations.
-- 🌐 **Bilingual StaffDeck UI** — switch the complete workspace between English and Simplified Chinese.
-
-### Why URStaff?
-
-The matrix describes typical out-of-the-box behavior for each product category; individual products may add some of these capabilities separately.
-
-| Capability | Typical chatbot | RAG application | Workflow engine | **URStaff** |
-| --- | :---: | :---: | :---: | :---: |
-| Natural-language conversation | ✅ | ✅ | ❌ | ✅ |
-| Knowledge retrieval with visible citations | ❌ | ✅ | ❌ | ✅ |
-| Reusable general skills and SOP execution | ❌ | ❌ | ✅ | ✅ |
-| External tools and service actions | ❌ | ❌ | ✅ | ✅ |
-| Persistent employee identity and memory | ❌ | ❌ | ❌ | ✅ |
-| Scheduled autonomous work | ❌ | ❌ | ✅ | ✅ |
-| Streaming per-turn execution record | ❌ | ❌ | ✅ | ✅ |
-| Human handoff, cancellation, and review | ❌ | ❌ | ✅ | ✅ |
-| Creator ownership and role-aware management | ❌ | ❌ | ✅ | ✅ |
## News
-- 📌 **Pinned · 2026-07-13** — The first private GitHub release of URStaff packages the StaffDeck workspace, bilingual UI, digital employee runtime, and one-port deployment. Start with the [first demo](#quick-start).
+- 📌 **Pinned · 2026-07-15**: StaffDeck is now open source! We welcome your feedback and support with a Star.
-## Demo
+# 💡 About StaffDeck
-After starting the service, the complete experience is available locally:
+StaffDeck is an enterprise platform for building and managing digital employees. It helps professionals turn their work experience, business processes, and decision criteria into digital employees that can operate continuously, take over repetitive tasks, and preserve individual expertise as reusable, evolvable, and traceable organizational assets. StaffDeck is jointly developed by the [NEU-ModelBest Data Intelligence Joint Lab](https://neuir.github.io/), [ModelBest](https://modelbest.cn/), [OpenBMB](https://www.openbmb.cn/home), and [AI9Stars](https://github.com/AI9Stars) for enterprises and institutions seeking to advance AI from a personal productivity tool to an organizational capability.
-| Entry | URL | What to try |
-| --- | --- | --- |
-| Digital Employee Marketplace | [http://127.0.0.1:5173/workspace/gallery](http://127.0.0.1:5173/workspace/gallery) | Select an employee and start a session |
-| Chat Workspace | `http://127.0.0.1:5173/workspace/chat/` | Inspect streaming execution records and citations |
-| Enterprise Console | [http://127.0.0.1:5173/enterprise/dashboard](http://127.0.0.1:5173/enterprise/dashboard) | Configure employees, knowledge, skills, SOPs, tools, and tasks |
-| API Explorer | [http://127.0.0.1:5173/docs](http://127.0.0.1:5173/docs) | Call and inspect the FastAPI endpoints |
+## Highlights
+
+- 🧑💼 **Build and manage digital employees**: Turn professional experience, processes, and decision criteria into digital employees with positions, employee IDs, capability profiles, and work records. Support capability growth, permission isolation, publishing, and reuse.
+- 🧩 **State-machine-driven procedural skills**: Generate structured SOPs from natural language and use state machines to execute complex processes accurately. Support real-time switching across multiple flows, context preservation, visual editing, version management, and branch evolution.
+- 📚 **Document-structure-aware knowledge retrieval**: Build navigable indexes across documents, chapters, pages, summaries, and other levels, allowing digital employees to first estimate where information may reside and then locate the original text step by step. Support knowledge buckets, targeted retrieval, source citations, and retrieval debugging.
+- 🔌 **Autonomous execution and continuous improvement**: Perform real business operations through HTTP APIs, MCP, and scheduled tasks, then close the improvement loop with long-term memory, complete traces, human takeover, user feedback, and feedback analysis.
## Agent-Friendly Quick Deploy
-Paste the prompt below into an authenticated coding agent such as Cursor, Claude Code, or Codex:
+Paste the prompt below into Cursor, Claude Code, or Codex:
```text
-Read https://raw.githubusercontent.com/OpenBMB/URStaff/main/README.md.
-Clone the private OpenBMB/URStaff repository, prepare Python 3.11 and Node.js 20,
+Read https://raw.githubusercontent.com/OpenBMB/StaffDeck/main/README.md.
+Clone the OpenBMB/StaffDeck repository, prepare Python 3.11 and Node.js 20,
create backend/.venv, install the backend and frontend dependencies, copy
backend/.env.example to backend/.env, ask me for the OpenAI-compatible model
endpoint and API key if they are missing, run DETACH=1 scripts/dev_up.sh, and
verify /api/health plus /workspace/gallery before reporting success.
-Do not expose credentials or change the repository visibility.
```
-The raw URL requires GitHub authentication because this repository is private.
## Table of Contents
-- [Quick Start](#quick-start)
-- [Configuration](#configuration)
-- [Architecture](#architecture)
-- [Core Workflows](#core-workflows)
-- [Project Structure](#project-structure)
-- [Development and Validation](#development-and-validation)
-- [FAQ](#faq)
-- [Roadmap](#roadmap)
-- [Contributing](#contributing)
-- [Risks and Limitations](#risks-and-limitations)
-- [Citation](#citation)
-- [License](#license)
-- [Acknowledgments](#acknowledgments)
+- [StaffDeck: Build, Manage, and Continuously Evolve Enterprise Digital Employees](#staffdeck-build-manage-and-continuously-evolve-enterprise-digital-employees)
+ - [News](#news)
+- [💡 About StaffDeck](#-about-staffdeck)
+ - [Highlights](#highlights)
+ - [Agent-Friendly Quick Deploy](#agent-friendly-quick-deploy)
+ - [Table of Contents](#table-of-contents)
+ - [Quick Start](#quick-start)
+ - [Requirements](#requirements)
+ - [1. Clone and Install](#1-clone-and-install)
+ - [2. Configure a Model](#2-configure-a-model)
+ - [3. Launch the Web Demo](#3-launch-the-web-demo)
+ - [4. Verify the Installation](#4-verify-the-installation)
+ - [Useful Commands](#useful-commands)
+ - [Core Workflows](#core-workflows)
+ - [Project Structure](#project-structure)
+ - [FAQ](#faq)
+ - [Roadmap](#roadmap)
+ - [Contributing](#contributing)
+ - [Risks and Limitations](#risks-and-limitations)
+ - [Citation](#citation)
+ - [License](#license)
+ - [Acknowledgments](#acknowledgments)
## Quick Start
### Requirements
-- macOS, Linux, or WSL for the development scripts
+- macOS, Linux, or WSL when using the development scripts
- Python **3.11+**
- Node.js **20+** and npm
- An OpenAI-compatible Chat Completions endpoint and API key
-- No CUDA requirement for the application itself; model hardware is managed by your chosen model provider
+- No CUDA requirement for the application itself; hardware requirements depend on the selected model service
-### 1. Clone and install
+### 1. Clone and Install
```bash
-git clone https://github.com/OpenBMB/URStaff.git
-cd URStaff
+git clone https://github.com/OpenBMB/StaffDeck.git
+cd StaffDeck
-python3.11 -m venv backend/.venv
+python3 -m venv backend/.venv
backend/.venv/bin/python -m pip install -e "backend[dev]"
npm --prefix frontend-enterprise ci
cp backend/.env.example backend/.env
```
-### 2. Configure a model
+### 2. Configure a Model
Edit `backend/.env` before the first startup:
@@ -138,9 +107,9 @@ DEMO_MODEL_NAME="your-model-name"
DEMO_MODEL_API_KEY="your-api-key"
```
-The API key is used to seed the initial model configuration and is encrypted before database storage. Keep `backend/.env` out of version control. You can also configure providers later from **Admin → Model Configuration**.
+The API key is used to create the initial model configuration and is encrypted before being stored in the database. Do not commit `backend/.env`. After startup, model services can also be managed from **Admin → Model Configuration**.
-### 3. Launch the Web demo
+### 3. Launch the Web Demo
```bash
DETACH=1 scripts/dev_up.sh
@@ -148,7 +117,7 @@ DETACH=1 scripts/dev_up.sh
The script builds the StaffDeck frontend and serves the UI, API, and Swagger documentation from one FastAPI process on port `5173`.
-### 4. Verify the installation
+### 4. Verify the Installation
```bash
curl http://127.0.0.1:5173/api/health
@@ -160,169 +129,118 @@ Expected output:
{"status":"ok"}
```
-Open [http://127.0.0.1:5173/workspace/gallery](http://127.0.0.1:5173/workspace/gallery), select a digital employee, and send the first message. The assistant answer and its execution record should stream into the same turn.
+Open [http://127.0.0.1:5173/workspace/gallery](http://127.0.0.1:5173/workspace/gallery), select a digital employee, and send the first message. The answer and its execution record should stream into the same conversation turn.
-### Useful commands
+### Useful Commands
```bash
-scripts/dev_status.sh # inspect running services
-scripts/dev_down.sh # stop the local stack
+scripts/dev_status.sh # inspect service status
+scripts/dev_down.sh # stop the local service
scripts/dev_up.sh # run in the foreground
-SINGLE_PORT=0 scripts/dev_up.sh # split frontend/backend mode for UI debugging
```
-For focused backend debugging:
+> Full guide → [StaffDeck Tutorial](docs/tutorial.md)
-```bash
-cd backend
-.venv/bin/uvicorn single_port_app:app --host 127.0.0.1 --port 5173
-```
-> Full walkthrough → [StaffDeck tutorial](docs/tutorial.md)
-
-## Configuration
-
-Important environment variables are documented in [`backend/.env.example`](backend/.env.example).
-
-| Variable | Purpose | Default |
-| --- | --- | --- |
-| `APP_SECRET` | Encrypts stored provider credentials; replace it outside local development | `change-me-in-development` |
-| `DEMO_MODEL_BASE_URL` | OpenAI-compatible API base URL used for initial model seeding | Demo endpoint |
-| `DEMO_MODEL_NAME` | Initial model identifier | `qwen3.6-27b` |
-| `DEMO_MODEL_API_KEY` | Optional key for initial model seeding | Empty |
-| `TOOL_TIMEOUT_SECONDS` | HTTP tool timeout | `8` |
-| `GENERAL_SKILL_RUNTIME_PYTHON` | Prepared Python used by generated general-skill runners | Auto-detected |
-| `GENERAL_SKILL_RUNTIME_PACKAGES` | Packages verified or installed in the isolated skill runtime | `requests,httpx` |
-
-URStaff supports configurable OpenAI-compatible providers rather than bundling model weights. Provider limits, context windows, multimodal support, and hardware requirements therefore depend on the selected model service.
-
-## Architecture
-
-```mermaid
-flowchart LR
- U["User or Scheduled Task"] --> W["StaffDeck Workspace"]
- W --> API["FastAPI Chat and Admin APIs"]
- API --> R["Digital Employee Runtime"]
- R --> K["Knowledge and Citations"]
- R --> G["General Skills"]
- R --> S["SOP Flows"]
- R --> T["HTTP, MCP, and Built-in Tools"]
- R --> M["Scoped Memory"]
- R --> O["Execution Record and Feedback"]
- O --> H["Human Review or Handoff"]
-```
-A chat turn is stored as a stable turn block. Routing may select knowledge and reusable capabilities together, while the execution stream records each observable decision, action, review, and response event. Scheduled tasks reuse the same runtime and persist their own run records.
## Core Workflows
-1. **Create a digital employee** — define the position, role boundary, service style, creator, and access scope.
-2. **Attach capabilities** — copy or create knowledge bases, general skills, SOPs, and tools without modifying marketplace originals.
-3. **Start a session** — use the marketplace or employee roster; the session becomes persistent after the first message.
-4. **Run and observe** — follow streaming intent, retrieval, skill, tool, review, and response events in the execution record.
-5. **Intervene when needed** — queue another request, cancel a run, hand it to a person, or review a pending answer.
-6. **Operate continuously** — use memory, feedback, conversation logs, and scheduled tasks to improve the employee over time.
+1. **Create a digital employee**: Define the position, role boundaries, service style, creator, and access scope.
+2. **Configure employee capabilities**: Copy from the marketplace or create knowledge bases, general skills, SOPs, and tools without modifying marketplace originals.
+3. **Start a session**: Enter from the digital employee marketplace or employee list; the formal session is persisted after the first message is sent.
+4. **Execute and observe**: Inspect streaming intent, retrieval, skill, tool, review, and response events in the execution record.
+5. **Intervene when necessary**: Continue with queued requests, cancel a run, hand work to a person, or process pending answers.
+6. **Operate continuously**: Improve employee capabilities over time through memory, feedback, conversation logs, and scheduled tasks.
## Project Structure
```text
-URStaff/
-├── backend/ # FastAPI APIs, agent runtime, persistence, workers
+StaffDeck/
+├── backend/ # FastAPI APIs, agent runtime, storage, and task workers
├── frontend-enterprise/ # React/TypeScript StaffDeck workspace
-├── docs/ # Tutorial, API, schemas, and example flows
-├── scripts/ # Single-port lifecycle and validation scripts
+├── docs/ # Tutorials, APIs, schemas, and example flows
+├── scripts/ # Single-port service lifecycle and validation scripts
├── packaging/ # macOS, Linux, and Windows packaging assets
-└── README.md # English project guide
+├── README.md # English
+└── README.zh.md # Simplified Chinese
```
-## Development and Validation
-
-```bash
-# Backend tests
-cd backend
-.venv/bin/python -m pytest tests
-
-# Frontend i18n and production build
-cd ../frontend-enterprise
-npm run i18n:check
-npm run build
-```
-
-For UI changes, validate the real mounted routes under `/workspace/*` and `/enterprise/*`; do not test components only in isolation.
## FAQ
-The UI opens, but the employee does not answer.
+The page opens, but the digital employee does not answer.
-Verify the selected model configuration, API key, provider network access, and model name. Then inspect the execution record and backend log under `.dev/logs/app.log` for the exact provider error.
+Check the selected model configuration, API key, model name, and model service network. Then inspect the execution record and `.dev/logs/app.log` to identify the exact error returned by the model service.
-Port 5173 is already in use.
+Can StaffDeck run without a local GPU?
-Run `scripts/dev_down.sh`. If the listener is not managed by URStaff, inspect it first, then run `FORCE_PORTS=1 scripts/dev_up.sh` only when it is safe to stop.
+Yes. The application calls an OpenAI-compatible model endpoint, so GPU requirements depend on the model service you deploy or use.
-Can URStaff run without a local GPU?
+Why can regular users use marketplace resources but not edit them?
-Yes. The application calls an OpenAI-compatible model endpoint. GPU requirements belong to the model service you choose to host or consume.
-
-
-
-Why can a user use a marketplace resource but not edit it?
-
-Marketplace resources are reusable templates. Non-administrators can copy or attach authorized resources to their employees, while the original resource remains protected by creator and administrator permissions.
+Marketplace resources are reusable templates. Regular users can copy or bind authorized resources to their own employees, while the original resources remain protected by creator and administrator permissions.
## Roadmap
-- [ ] Official container image and Docker Compose deployment
-- [ ] Public documentation site and versioned API reference
-- [ ] Reproducible quality, latency, and task-completion benchmarks
+- [ ] Group chat, multi-digital-employee communication, and task division
- [ ] More enterprise connectors and reviewed marketplace resources
-- [ ] Expanded approval policies for high-risk tool actions
+- [ ] Fine-grained approval policies for high-risk tool actions
-Priorities are driven by real deployments. Open an [Issue](https://github.com/OpenBMB/URStaff/issues) with a reproducible scenario and expected behavior.
+Roadmap priorities are driven by real deployment needs. Please open an [Issue](https://github.com/OpenBMB/StaffDeck/issues) with a reproducible scenario and expected behavior.
## Contributing
-Contributions from authorized collaborators are welcome:
+Contributions from collaborators with repository access are welcome:
-- Report reproducible bugs and permission issues
-- Propose employee, knowledge, skill, SOP, or tool workflows
+- Submit reproducible bugs and permission issues
+- Propose digital employee, knowledge, skill, SOP, or tool workflows
- Submit focused pull requests with tests and browser validation
- Improve documentation and Chinese/English translations
-Keep unrelated worktree changes intact, add tests proportional to the affected behavior, and include the routes and user roles used for UI verification.
+Keep unrelated worktree changes intact, add tests proportional to the affected behavior, and state the routes and user roles used for UI verification in each pull request.
## Risks and Limitations
-- Model outputs can be incorrect, incomplete, or inconsistent; execution records improve auditability but do not guarantee correctness.
-- Retrieved knowledge is limited by document quality, parsing, indexing, permissions, and the selected model.
-- External tools and generated runners can have real side effects. Use least-privilege credentials and require human approval for high-risk actions.
-- Scheduled tasks depend on a continuously running worker and correctly configured user time zones.
-- This project is not a substitute for legal, medical, financial, security, or other regulated professional review.
-- Do not use the platform to process data or automate decisions without appropriate authorization, privacy controls, and human oversight.
+- Model responses can be incorrect, incomplete, or inconsistent. Execution records improve auditability but do not guarantee correctness.
+- Knowledge retrieval quality depends on source-document quality, parsing, indexing, permissions, and model capabilities.
+- External tools and generated runners can have real side effects. Use least-privilege credentials and configure human approval for high-risk actions.
+- Scheduled tasks depend on a continuously running worker and correct user time-zone settings.
+- This project is not a substitute for professional review in legal, medical, financial, security, or other regulated fields.
+- Do not use this platform to process data or automate important decisions without appropriate authorization, privacy protection, and human oversight.
## Citation
-If you use URStaff in internal research or an authorized publication, cite the software as:
+When using StaffDeck in internal research or authorized public materials, cite:
```bibtex
-@software{urstaff2026,
- title = {URStaff: Build, Run, and Govern Enterprise Digital Employees},
+@software{StaffDeck2026,
+ title = {StaffDeck: Build, Run, and Govern Enterprise Digital Employees},
author = {OpenBMB},
year = {2026},
- url = {https://github.com/OpenBMB/URStaff}
+ url = {https://github.com/OpenBMB/StaffDeck}
+}
+```
+
+```bibtex
+@article{chen2025ultrarag,
+ title={UltraRAG: A Modular and Automated Toolkit for Adaptive Retrieval-Augmented Generation},
+ author={Chen, Yuxuan and Guo, Dewen and Mei, Sen and Li, Xinze and Chen, Hao and Li, Yishan and Wang, Yixuan and Tang, Chaoyue and Wang, Ruobing and Wu, Dingjun and others},
+ journal={arXiv preprint arXiv:2504.08761},
+ year={2025}
}
```
## License
-No public open-source license is currently granted. This private repository and its contents may only be used by authorized users under the applicable organizational agreement.
+This project is open source under the GNU Affero General Public License v3.0.
## Acknowledgments
-URStaff is developed within the [OpenBMB](https://www.openbmb.cn/) ecosystem. Its README structure follows the concise, demo-first presentation used by [PilotDeck](https://github.com/OpenBMB/PilotDeck). Thanks to the open-source communities behind FastAPI, React, Vite, SQLModel, Pydantic, and the OpenAI-compatible API ecosystem.
+StaffDeck is incubated by the [OpenBMB](https://www.openbmb.cn/) ecosystem.
diff --git a/README.zh.md b/README.zh.md
index bb4d441bb..6c601bbd1 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -1,6 +1,6 @@
-
+
# StaffDeck:构建、管理并持续进化企业数字员工
@@ -26,22 +26,18 @@ NEU-ModelBest Data Intelligence Joint Lab
# 💡 关于StaffDeck
-StaffDeck是一套面向企业的数字员工构建与管理平台,帮助专业员工将工作经验、业务流程和判断标准固化为可以持续工作的数字员工,接手重复性任务,并将个人能力沉淀为可复用、可迭代、可追溯的组织资产。StaffDeck由[东北大学-面壁智能数据智能联合实验室](https://neuir.github.io/),[清华大学THUNLP实验室](https://nlp.csai.tsinghua.edu.cn/),[面壁智能](https://modelbest.cn/),[OpenBMB](https://www.openbmb.cn/home)与[AI9Stars](https://github.com/AI9Stars)联合研发,面向希望将 AI 从个人效率工具升级为组织生产力的企业与机构。
+StaffDeck是一套面向企业的数字员工构建与管理平台,帮助专业员工将工作经验、业务流程和判断标准固化为可以持续工作的数字员工,接手重复性任务,并将个人能力沉淀为可复用、可迭代、可追溯的组织资产。StaffDeck由[面壁智能](https://modelbest.cn/),[东北大学-面壁智能数据智能联合实验室](https://neuir.github.io/),[清华大学THUNLP实验室](https://nlp.csai.tsinghua.edu.cn/),[OpenBMB](https://www.openbmb.cn/home)与[AI9Stars](https://github.com/AI9Stars)联合研发,面向希望将 AI 从个人效率工具升级为组织生产力的企业与机构。
## 核心亮点
-- 🧑💼 **数字员工,而非通用机器人**:按员工隔离岗位描述、能力资源、会话、记忆与运营记录。
-- 📚 **有依据的企业知识**:解析文档、检索相关上下文,并在回答中保留可追溯的引用来源。
-- 🧩 **知识 + 通用技能 + SOP**:一次请求可以组合需要的能力,而非被限制为单一执行模式。
-- 🔌 **真实工具执行**:通过 HTTP、MCP、内置工具和动态生成的技能 Runner 连接企业服务。
-- ⏰ **定时与排队任务**:支持一次性或周期任务,并在刷新后保留聊天 Buffer 中的排队请求。
-- 🔎 **全过程可观测**:将意图、路由、技能、工具、校验与回答事件流式写入每轮执行记录。
-- 🤝 **Human-in-the-loop**:支持暂停、取消、转人工、待回答和人工审核,避免高风险动作完全自动决策。
-- 🔐 **基于角色的治理**:区分广场资源、创建者归属、员工访问范围与仅管理员可用的操作。
+- 🧑💼 **数字员工构建与管理**:将专业员工的经验、流程和判断标准固化为拥有岗位、工号、能力档案和工作记录的数字员工;支持能力成长、权限隔离及发布复用。
+- 🧩 **状态机驱动的流程型技能**:通过自然语言生成结构化 SOP,以状态机保证复杂流程准确执行;支持多个流程实时切换、上下文保留、可视化编辑、版本管理和分支演化。
+- 📚 **文档结构感知的知识检索**:基于文档、章节、页面和摘要等层级构建可导航索引,让数字员工先判断信息可能位于哪里,再逐层定位原文;支持知识分桶、定向检索、来源引用和检索调试。
+- 🔌 **自主执行与持续迭代**:通过 HTTP API、MCP 和定时任务执行真实业务操作,并结合长期记忆、完整 Trace、真人接管、用户反馈和反馈分析形成持续迭代闭环。
## Agent 一键部署
-将下面的 Prompt 粘贴给有仓库权限的 Cursor、Claude Code 或 Codex:
+将下面的 Prompt 粘贴给 Cursor、Claude Code 或 Codex:
```text
阅读 https://raw.githubusercontent.com/OpenBMB/StaffDeck/main/README.zh.md。
@@ -51,7 +47,6 @@ backend/.env;缺少 OpenAI 兼容模型地址或 API Key 时向我询问;运
DETACH=1 scripts/dev_up.sh,并验证 /api/health 和 /workspace/gallery 后再报告完成。
```
-由于仓库为私有仓库,以上 Raw URL 同样需要 GitHub 身份验证。
## 目录
@@ -68,10 +63,8 @@ DETACH=1 scripts/dev_up.sh,并验证 /api/health 和 /workspace/gallery 后再
- [3. 启动 Web Demo](#3-启动-web-demo)
- [4. 验证安装](#4-验证安装)
- [常用命令](#常用命令)
- - [配置说明](#配置说明)
- [核心流程](#核心流程)
- [项目结构](#项目结构)
- - [开发与验证](#开发与验证)
- [常见问题](#常见问题)
- [路线图](#路线图)
- [参与贡献](#参与贡献)
@@ -147,21 +140,6 @@ scripts/dev_up.sh # 前台运行
> 完整说明 → [StaffDeck 使用教程](docs/tutorial.md)
-## 配置说明
-
-主要环境变量见 [`backend/.env.example`](backend/.env.example)。
-
-| 变量 | 作用 | 默认值 |
-| --- | --- | --- |
-| `APP_SECRET` | 加密模型凭据,非本地环境必须替换 | `change-me-in-development` |
-| `DEMO_MODEL_BASE_URL` | 首次启动时创建模型配置所用的 OpenAI 兼容接口 | Demo 地址 |
-| `DEMO_MODEL_NAME` | 初始模型标识 | `qwen3.6-27b` |
-| `DEMO_MODEL_API_KEY` | 可选的初始模型 API Key | 空 |
-| `TOOL_TIMEOUT_SECONDS` | HTTP 工具超时 | `8` |
-| `GENERAL_SKILL_RUNTIME_PYTHON` | 通用技能 Runner 使用的 Python | 自动探测 |
-| `GENERAL_SKILL_RUNTIME_PACKAGES` | 独立技能运行时校验或安装的依赖 | `requests,httpx` |
-
-StaffDeck 支持可配置的 OpenAI 兼容模型服务,不在仓库中捆绑模型权重。上下文长度、多模态能力、输出限制和硬件需求取决于所选模型服务。
@@ -187,20 +165,6 @@ StaffDeck/
└── README.zh.md # 简体中文
```
-## 开发与验证
-
-```bash
-# 后端测试
-cd backend
-.venv/bin/python -m pytest tests
-
-# 前端 i18n 检查与生产构建
-cd ../frontend-enterprise
-npm run i18n:check
-npm run build
-```
-
-修改 UI 后必须验证 `/workspace/*` 与 `/enterprise/*` 下的真实挂载路由,不能只测试孤立组件。
## 常见问题
@@ -210,12 +174,6 @@ npm run build
检查所选模型配置、API Key、模型名和模型服务网络。随后查看执行记录与 `.dev/logs/app.log`,定位模型服务返回的具体错误。
-
-5173 端口已被占用。
-
-先运行 `scripts/dev_down.sh`。若监听进程不属于 StaffDeck,应先确认其用途;只有确定可以终止时才使用 `FORCE_PORTS=1 scripts/dev_up.sh`。
-
-
没有本地 GPU 可以运行吗?
diff --git a/packaging/assets/staffdeck_banner_cn.png b/packaging/assets/staffdeck_banner_cn.png
new file mode 100644
index 0000000000000000000000000000000000000000..e3d940c1071cdc547b56265514849af6cb95a989
GIT binary patch
literal 616190
zcmeEt`#;lt_`i;%9J(cP?5rqLku#NBXNS@#$B>*2bKWUA>@J}@Ne(kQ5W~n}P8(Uc
zBc{YKnT@1`p^53|=^+yuUP>4I2Ux60Jo
z!&dL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