初始化
This commit is contained in:
1 parent
34474bd5fc
commit
b638b541d0
3008 files changed
+837699
No files matched your search
@@ -0,0 +1,11 @@
|
||||
"""Runtime user-intervention pipeline for report collaboration."""
|
||||
|
||||
from app.report_collaboration.interventions.impact_analyzer import CommandImpact, ImpactAnalyzer
|
||||
from app.report_collaboration.interventions.intent_router import RuntimeIntentContext, RuntimeIntentRouterAgent
|
||||
|
||||
__all__ = [
|
||||
"CommandImpact",
|
||||
"ImpactAnalyzer",
|
||||
"RuntimeIntentContext",
|
||||
"RuntimeIntentRouterAgent",
|
||||
]
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
"""Deterministic blast-radius calculation for runtime user commands."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.report_collaboration.contracts.commands import IntentDecision
|
||||
|
||||
|
||||
class CommandImpact(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True)
|
||||
|
||||
target_type: str | None = None
|
||||
target_node_ids: list[str] = Field(default_factory=list)
|
||||
impact_nodes: list[str] = Field(default_factory=list)
|
||||
waiting_boundary_nodes: list[str] = Field(default_factory=list)
|
||||
requires_confirmation: bool = False
|
||||
cost_level: str = "low"
|
||||
reason: str
|
||||
|
||||
|
||||
class ImpactAnalyzer:
|
||||
"""Resolve exact nodes from plan topology; never asks an LLM to mutate a DAG."""
|
||||
|
||||
def __init__(self, *, confirmation_threshold: float = 0.8) -> None:
|
||||
self._confirmation_threshold = max(0.0, min(1.0, confirmation_threshold))
|
||||
|
||||
def analyze(
|
||||
self,
|
||||
decision: IntentDecision,
|
||||
*,
|
||||
plan: dict,
|
||||
node_runs: list[dict],
|
||||
agent_runs: list[dict],
|
||||
explicit_target_node_ids: list[str],
|
||||
) -> CommandImpact:
|
||||
nodes = {str(item["id"]): item for item in plan.get("nodes") or [] if item.get("id")}
|
||||
order = [str(item["id"]) for item in plan.get("nodes") or [] if item.get("id")]
|
||||
deps = _dependency_map(plan, nodes)
|
||||
selected = [node_id for node_id in explicit_target_node_ids if node_id in nodes]
|
||||
intent = decision.intent
|
||||
|
||||
if intent in {"ask_report", "cancel"}:
|
||||
impacted: set[str] = set()
|
||||
roots: set[str] = set()
|
||||
elif intent == "answer_question":
|
||||
awaiting = _latest_with_status(node_runs, "awaiting_input")
|
||||
roots = set(selected or awaiting)
|
||||
impacted = set(roots)
|
||||
elif intent in {"update_requirements", "replan"}:
|
||||
roots = set(order)
|
||||
impacted = set(order)
|
||||
elif intent == "research_again":
|
||||
roots = _role_targets("researcher", selected, nodes, deps)
|
||||
impacted = _downstream_closure(roots, deps)
|
||||
elif intent == "add_angle":
|
||||
candidates = _role_targets("researcher", selected, nodes, deps)
|
||||
# A new angle is assigned to one deterministic research branch.
|
||||
# This keeps unrelated parallel evidence live and avoids mutating
|
||||
# the frozen canvas graph behind the user's selected proposal.
|
||||
chosen = next((node_id for node_id in order if node_id in candidates), None)
|
||||
roots = {chosen} if chosen else set()
|
||||
impacted = _downstream_closure(roots, deps)
|
||||
elif intent == "reanalyze":
|
||||
roots = _role_targets("analyst", selected, nodes, deps)
|
||||
impacted = _downstream_closure(roots, deps)
|
||||
elif intent in {"rewrite_section", "polish_report"}:
|
||||
roots = _role_targets(("writer", "reviser"), selected, nodes, deps)
|
||||
impacted = _downstream_closure(roots, deps)
|
||||
else:
|
||||
roots = set(selected)
|
||||
impacted = _downstream_closure(roots, deps)
|
||||
|
||||
if not roots and intent not in {"ask_report", "cancel"}:
|
||||
# replan / update_requirements are whole-graph by design and already
|
||||
# confirmation-gated. rerun_node must not silently expand.
|
||||
roots = set(order) if intent in {"replan", "update_requirements"} else set()
|
||||
impacted = _downstream_closure(roots, deps)
|
||||
|
||||
impact_order = [node_id for node_id in order if node_id in impacted]
|
||||
running_node_run_ids = {
|
||||
str(item.get("node_run_id"))
|
||||
for item in agent_runs
|
||||
if item.get("status") == "running" and item.get("node_run_id")
|
||||
}
|
||||
latest = _latest_nodes(node_runs)
|
||||
waiting = [
|
||||
node_id
|
||||
for node_id in impact_order
|
||||
if latest.get(node_id, {}).get("status") in {"running", "validating"}
|
||||
or latest.get(node_id, {}).get("node_run_id") in running_node_run_ids
|
||||
]
|
||||
root_branches = _independent_roots(roots, deps)
|
||||
ambiguous = bool(intent not in {"ask_report", "cancel"} and not roots)
|
||||
broad_parallel = len(root_branches) > 1 and intent not in {"update_requirements", "replan"}
|
||||
requires_confirmation = bool(
|
||||
decision.requires_confirmation
|
||||
or decision.confidence < self._confirmation_threshold
|
||||
or decision.cost_level == "high"
|
||||
or ambiguous
|
||||
or broad_parallel
|
||||
)
|
||||
reason = decision.reason
|
||||
if ambiguous:
|
||||
reason += ";没有找到可安全执行的目标节点"
|
||||
elif broad_parallel:
|
||||
reason += ";将同时影响多个独立分支"
|
||||
return CommandImpact(
|
||||
target_type=decision.scope if impact_order else None,
|
||||
target_node_ids=[node_id for node_id in order if node_id in roots],
|
||||
impact_nodes=impact_order,
|
||||
waiting_boundary_nodes=waiting,
|
||||
requires_confirmation=requires_confirmation,
|
||||
cost_level=decision.cost_level,
|
||||
reason=reason,
|
||||
)
|
||||
|
||||
|
||||
def _dependency_map(plan: dict, nodes: dict[str, dict]) -> dict[str, set[str]]:
|
||||
deps = {node_id: {str(item) for item in spec.get("depends_on") or [] if str(item) in nodes} for node_id, spec in nodes.items()}
|
||||
for edge in plan.get("edges") or []:
|
||||
source, target = str(edge.get("source") or ""), str(edge.get("target") or "")
|
||||
if source in nodes and target in nodes:
|
||||
deps.setdefault(target, set()).add(source)
|
||||
return deps
|
||||
|
||||
|
||||
def _latest_nodes(rows: list[dict]) -> dict[str, dict]:
|
||||
latest: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
node_id = str(row.get("node_id") or "")
|
||||
if node_id and (node_id not in latest or int(row.get("attempt") or 0) >= int(latest[node_id].get("attempt") or 0)):
|
||||
latest[node_id] = row
|
||||
return latest
|
||||
|
||||
|
||||
def _latest_with_status(rows: list[dict], status: str) -> list[str]:
|
||||
return [node_id for node_id, row in _latest_nodes(rows).items() if row.get("status") == status]
|
||||
|
||||
|
||||
def _role_targets(
|
||||
roles: str | tuple[str, ...],
|
||||
selected: list[str],
|
||||
nodes: dict[str, dict],
|
||||
deps: dict[str, set[str]],
|
||||
) -> set[str]:
|
||||
accepted = {roles} if isinstance(roles, str) else set(roles)
|
||||
candidates = {node_id for node_id, spec in nodes.items() if str(spec.get("role_key") or "") in accepted}
|
||||
if not selected:
|
||||
return candidates
|
||||
direct = set(selected) & candidates
|
||||
if direct:
|
||||
return direct
|
||||
related: set[str] = set()
|
||||
for target in selected:
|
||||
ancestors = _ancestors(target, deps)
|
||||
descendants = _downstream_closure({target}, deps)
|
||||
related.update(candidates & (ancestors | descendants))
|
||||
return related or candidates
|
||||
|
||||
|
||||
def _ancestors(node_id: str, deps: dict[str, set[str]]) -> set[str]:
|
||||
found: set[str] = set()
|
||||
stack = list(deps.get(node_id) or set())
|
||||
while stack:
|
||||
item = stack.pop()
|
||||
if item in found:
|
||||
continue
|
||||
found.add(item)
|
||||
stack.extend(deps.get(item) or set())
|
||||
return found
|
||||
|
||||
|
||||
def _downstream_closure(roots: set[str], deps: dict[str, set[str]]) -> set[str]:
|
||||
found = set(roots)
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for node_id, parents in deps.items():
|
||||
if node_id not in found and parents & found:
|
||||
found.add(node_id)
|
||||
changed = True
|
||||
return found
|
||||
|
||||
|
||||
def _independent_roots(roots: set[str], deps: dict[str, set[str]]) -> set[str]:
|
||||
return {node_id for node_id in roots if not (_ancestors(node_id, deps) & roots)}
|
||||
|
||||
|
||||
__all__ = ["CommandImpact", "ImpactAnalyzer"]
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
"""Constrained runtime IntentRouterAgent.
|
||||
|
||||
The agent is deliberately not a scheduler: it can only return an
|
||||
``IntentDecision``. Target validation, impact calculation and every state
|
||||
mutation stay in deterministic application code.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Protocol
|
||||
|
||||
from app.report_collaboration.agentscope_runtime.model_adapter import DeerFlowChatModelAdapter
|
||||
from app.report_collaboration.agentscope_runtime.model_resolver import resolve_role_model
|
||||
from app.report_collaboration.contracts.commands import IntentDecision
|
||||
from app.report_collaboration.requirement.extractor import (
|
||||
extract_angles,
|
||||
extract_audience,
|
||||
extract_language,
|
||||
extract_source_constraints,
|
||||
extract_time_range,
|
||||
)
|
||||
from deerflow.config.app_config import AppConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuntimeIntentContext:
|
||||
text: str
|
||||
requirement: dict[str, Any]
|
||||
plan_nodes: list[dict[str, Any]]
|
||||
target_node_ids: list[str] = field(default_factory=list)
|
||||
target_agent_run_id: str | None = None
|
||||
awaiting_node_ids: list[str] = field(default_factory=list)
|
||||
report_summary: str | None = None
|
||||
|
||||
|
||||
class IntentModel(Protocol):
|
||||
async def classify(self, context: RuntimeIntentContext) -> IntentDecision:
|
||||
...
|
||||
|
||||
|
||||
_EXPLICIT_RULES: tuple[tuple[str, re.Pattern[str]], ...] = (
|
||||
("cancel", re.compile(r"(?:^|[,。;\s])(取消|停止|终止)(?:本次|当前|这次|报告|任务|执行)?")),
|
||||
("research_again", re.compile(r"重新(?:检索|搜索|搜集|收集)|再(?:检索|搜索|搜集)|资料.{0,8}(?:不行|过时|太旧|不准确)|补充(?:资料|证据|来源)")),
|
||||
("reanalyze", re.compile(r"重新分析|再分析|分析.{0,10}(?:不到位|不对|有问题|不充分)")),
|
||||
("rewrite_section", re.compile(r"(?:重写|改写|重做).{0,12}(?:段|章节|部分|正文|结论|摘要)|(?:这段|本段|这一节).{0,8}(?:重写|改写)")),
|
||||
("polish_report", re.compile(r"润色|调整(?:语气|措辞|文风|表达)|优化(?:表达|行文|文风)")),
|
||||
("add_angle", re.compile(r"(?:增加|新增|补充|加入|添加).{0,16}(?:角度|维度|分析|视角)")),
|
||||
("rerun_node", re.compile(r"重跑|重新执行|再执行|重新做这个节点")),
|
||||
("replan", re.compile(r"重新规划|重做流程|换(?:一个|套)?方案|重新编排")),
|
||||
("update_requirements", re.compile(r"(?:修改|调整|改成|换成).{0,16}(?:主题|受众|范围|模板|时间|语言|篇幅|口吻|要求)")),
|
||||
("ask_report", re.compile(r"(?:报告|结论|正文|内容).{0,10}(?:是什么|为什么|怎么样|有哪些|总结|解释)|(?:总结|解释).{0,8}(?:报告|结论)")),
|
||||
)
|
||||
|
||||
_INTENT_META: dict[str, tuple[str, str, bool]] = {
|
||||
"answer_question": ("node", "low", False),
|
||||
"update_requirements": ("plan", "high", True),
|
||||
"add_angle": ("artifact_lineage", "medium", False),
|
||||
"research_again": ("artifact_lineage", "medium", False),
|
||||
"reanalyze": ("artifact_lineage", "medium", False),
|
||||
"rerun_node": ("node", "medium", False),
|
||||
"rewrite_section": ("section", "medium", False),
|
||||
"polish_report": ("section", "low", False),
|
||||
"ask_report": ("conversation", "low", False),
|
||||
"replan": ("plan", "high", True),
|
||||
"cancel": ("conversation", "high", True),
|
||||
}
|
||||
|
||||
|
||||
class RuntimeIntentRouterAgent:
|
||||
"""Understand a user turn and return a typed decision; never mutate state."""
|
||||
|
||||
def __init__(self, model: IntentModel | None = None) -> None:
|
||||
self._model = model
|
||||
|
||||
async def route(self, context: RuntimeIntentContext) -> IntentDecision:
|
||||
text = _clean(context.text)
|
||||
if context.awaiting_node_ids and not _matches_explicit_mutation(text):
|
||||
return self._decision("answer_question", context, confidence=0.99, reason="当前节点正在等待用户回答")
|
||||
for intent, pattern in _EXPLICIT_RULES:
|
||||
if intent == "cancel" and re.search(r"(?:不要|不用|别)取消", text):
|
||||
continue
|
||||
if intent == "research_again" and _negated_research(text):
|
||||
continue
|
||||
if pattern.search(text):
|
||||
return self._decision(intent, context, confidence=0.94, reason=f"命中明确的{intent}表达")
|
||||
if context.target_node_ids and re.search(r"不对|不行|有问题|改一下|调整一下|重新来", text):
|
||||
return self._decision(
|
||||
"rerun_node",
|
||||
context,
|
||||
confidence=0.66,
|
||||
reason="用户指向了节点但修改类型不够明确",
|
||||
requires_confirmation=True,
|
||||
)
|
||||
if self._model is not None:
|
||||
try:
|
||||
decision = await self._model.classify(context)
|
||||
return self._normalize_model_decision(decision, context)
|
||||
except Exception as exc: # Model failure must degrade to confirmation, never mutate broadly.
|
||||
logger.warning("runtime intent model failed; falling back to confirmation (%s)", exc.__class__.__name__)
|
||||
return self._decision(
|
||||
"rerun_node" if context.target_node_ids else "replan",
|
||||
context,
|
||||
confidence=0.35,
|
||||
reason="无法可靠判断用户希望修改的范围",
|
||||
requires_confirmation=True,
|
||||
)
|
||||
|
||||
def _decision(
|
||||
self,
|
||||
intent: str,
|
||||
context: RuntimeIntentContext,
|
||||
*,
|
||||
confidence: float,
|
||||
reason: str,
|
||||
requires_confirmation: bool | None = None,
|
||||
) -> IntentDecision:
|
||||
scope, cost, default_confirm = _INTENT_META[intent]
|
||||
patch = _requirement_patch(intent, context)
|
||||
requested = list(context.target_node_ids) or _infer_targets(intent, context)
|
||||
return IntentDecision.model_validate(
|
||||
{
|
||||
"intent": intent,
|
||||
"confidence": confidence,
|
||||
"normalized_instruction": _clean(context.text)[:4000],
|
||||
"scope": scope,
|
||||
"requested_target_ids": requested,
|
||||
"requirement_patch": patch,
|
||||
"requires_confirmation": default_confirm if requires_confirmation is None else requires_confirmation,
|
||||
"cost_level": cost,
|
||||
"reason": reason,
|
||||
}
|
||||
)
|
||||
|
||||
def _normalize_model_decision(self, decision: IntentDecision, context: RuntimeIntentContext) -> IntentDecision:
|
||||
payload = decision.model_dump(mode="json")
|
||||
valid_ids = {str(item.get("id")) for item in context.plan_nodes if item.get("id")}
|
||||
model_targets = [node_id for node_id in decision.requested_target_ids if node_id in valid_ids]
|
||||
payload["requested_target_ids"] = list(context.target_node_ids) or model_targets
|
||||
payload["normalized_instruction"] = _clean(payload.get("normalized_instruction") or context.text)[:4000]
|
||||
scope, cost, default_confirm = _INTENT_META[decision.intent]
|
||||
payload["scope"] = scope
|
||||
payload["cost_level"] = cost
|
||||
payload["requires_confirmation"] = bool(payload.get("requires_confirmation") or default_confirm)
|
||||
payload["requirement_patch"] = _requirement_patch(decision.intent, context)
|
||||
return IntentDecision.model_validate(payload)
|
||||
|
||||
|
||||
class DeerFlowIntentModel:
|
||||
"""LLM fallback for ambiguous language; output is strict JSON and tool-free."""
|
||||
|
||||
def __init__(self, app_config: AppConfig) -> None:
|
||||
snapshot = resolve_role_model("coordinator", app_config=app_config)
|
||||
self._adapter = DeerFlowChatModelAdapter(snapshot, app_config=app_config, thinking_enabled=False)
|
||||
|
||||
async def classify(self, context: RuntimeIntentContext) -> IntentDecision:
|
||||
node_view = [
|
||||
{
|
||||
"id": item.get("id"),
|
||||
"label": item.get("label"),
|
||||
"role_key": item.get("role_key"),
|
||||
"angle": item.get("angle"),
|
||||
}
|
||||
for item in context.plan_nodes
|
||||
]
|
||||
prompt = {
|
||||
"user_text": context.text,
|
||||
"selected_node_ids": context.target_node_ids,
|
||||
"awaiting_node_ids": context.awaiting_node_ids,
|
||||
"requirement": context.requirement,
|
||||
"nodes": node_view,
|
||||
"report_summary": context.report_summary,
|
||||
}
|
||||
system = (
|
||||
"你是报告协作运行期的意图识别智能体。你只能分类,不能安排任务、调用工具或修改状态。"
|
||||
"intent 必须是 answer_question/update_requirements/add_angle/research_again/reanalyze/"
|
||||
"rerun_node/rewrite_section/polish_report/ask_report/replan/cancel 之一。"
|
||||
"仅输出一个 JSON 对象,字段为 intent,confidence,normalized_instruction,scope,"
|
||||
"requested_target_ids,requirement_patch,requires_confirmation,cost_level,reason。"
|
||||
"requirement_patch 一律输出 null,目标一律沿用输入的 selected_node_ids。语义含糊时置信度低于0.8并要求确认。"
|
||||
)
|
||||
final = ""
|
||||
async for response in self._adapter.astream_chat(
|
||||
[{"role": "system", "content": system}, {"role": "user", "content": json.dumps(prompt, ensure_ascii=False)}]
|
||||
):
|
||||
if response.is_last:
|
||||
final = "".join(str(block.get("text") or "") for block in response.content if block.get("type") == "text")
|
||||
return IntentDecision.model_validate(json.loads(_json_object(final)))
|
||||
|
||||
|
||||
def build_runtime_intent_router(app_config: AppConfig) -> RuntimeIntentRouterAgent:
|
||||
try:
|
||||
return RuntimeIntentRouterAgent(DeerFlowIntentModel(app_config))
|
||||
except Exception:
|
||||
return RuntimeIntentRouterAgent()
|
||||
|
||||
|
||||
def _requirement_patch(intent: str, context: RuntimeIntentContext) -> dict[str, Any] | None:
|
||||
if intent not in {"add_angle", "update_requirements"}:
|
||||
return None
|
||||
current = dict(context.requirement or {})
|
||||
if not current.get("topic"):
|
||||
return None
|
||||
changed = False
|
||||
if intent == "add_angle":
|
||||
angles = list(current.get("required_angles") or [])
|
||||
discovered = extract_angles(context.text) or _custom_angles(context.text)
|
||||
for angle in discovered:
|
||||
if angle not in angles:
|
||||
angles.append(angle)
|
||||
changed = True
|
||||
current["required_angles"] = angles
|
||||
else:
|
||||
audience = extract_audience(context.text)
|
||||
language = extract_language(context.text)
|
||||
time_range = extract_time_range(context.text)
|
||||
source_constraints = extract_source_constraints(context.text)
|
||||
for key, value in {
|
||||
"audience": audience,
|
||||
"language": language,
|
||||
"time_range": time_range,
|
||||
"source_constraints": source_constraints,
|
||||
"topic": _explicit_value(context.text, "主题"),
|
||||
"geography": _explicit_value(context.text, "范围|地域|地区"),
|
||||
"report_structure_id": _explicit_value(context.text, "模板|报告结构"),
|
||||
"length_target": _explicit_value(context.text, "篇幅|字数"),
|
||||
"tone": _explicit_value(context.text, "口吻|语气|文风"),
|
||||
}.items():
|
||||
if value is not None and current.get(key) != value:
|
||||
current[key] = value
|
||||
changed = True
|
||||
angles = extract_angles(context.text)
|
||||
if angles:
|
||||
current["required_angles"] = angles
|
||||
changed = True
|
||||
if not changed:
|
||||
return None
|
||||
current["revision"] = int(current.get("revision") or 0) + 1
|
||||
return current
|
||||
|
||||
|
||||
def _negated_research(text: str) -> bool:
|
||||
"""POC-4 rewrite commands say「不要重新检索」; that must not win over rewrite_section."""
|
||||
|
||||
return bool(re.search(r"(?:不要|不用|别).{0,8}(?:重新)?(?:检索|搜索|搜集|收集)", text or ""))
|
||||
|
||||
|
||||
def _matches_explicit_mutation(text: str) -> bool:
|
||||
return any(
|
||||
intent != "ask_report" and not (intent == "research_again" and _negated_research(text)) and pattern.search(text)
|
||||
for intent, pattern in _EXPLICIT_RULES
|
||||
)
|
||||
|
||||
|
||||
def _custom_angles(text: str) -> list[str]:
|
||||
match = re.search(r"(?:增加|新增|补充|加入|添加)(?:一个|新的|从)?\s*([^,。;]{2,24}?)(?:角度|维度|视角)(?:分析)?", text or "")
|
||||
if not match:
|
||||
return []
|
||||
value = match.group(1).strip(" ::,,")
|
||||
return [value] if value else []
|
||||
|
||||
|
||||
def _infer_targets(intent: str, context: RuntimeIntentContext) -> list[str]:
|
||||
roles: dict[str, set[str]] = {
|
||||
"research_again": {"researcher"},
|
||||
"reanalyze": {"analyst"},
|
||||
"rewrite_section": {"writer", "reviser"},
|
||||
"polish_report": {"writer", "reviser"},
|
||||
}
|
||||
accepted = roles.get(intent)
|
||||
if not accepted:
|
||||
return []
|
||||
text = context.text
|
||||
normalized_angles = set(extract_angles(text))
|
||||
aliases = {
|
||||
"市场份额": ("市场", "份额"),
|
||||
"价格策略": ("价格", "定价"),
|
||||
"技术路线": ("技术", "电池", "智驾"),
|
||||
"海外进展": ("海外", "出口", "出海"),
|
||||
"政策环境": ("政策", "监管", "补贴"),
|
||||
"风险与机会": ("风险", "机会", "展望"),
|
||||
"竞争格局": ("竞争", "对手"),
|
||||
"供应链与原材料": ("供应链", "原材料"),
|
||||
}
|
||||
scored: list[tuple[int, str]] = []
|
||||
for node in context.plan_nodes:
|
||||
if str(node.get("role_key") or "") not in accepted or not node.get("id"):
|
||||
continue
|
||||
angle = str(node.get("angle") or "")
|
||||
label = str(node.get("label") or "")
|
||||
tokens = [angle, label]
|
||||
tokens.extend(alias for key, values in aliases.items() if key == angle for alias in values)
|
||||
hits = {token for token in tokens if token and token in text}
|
||||
if hits:
|
||||
# Prefer the most specific semantic match. “海外市场” should pick
|
||||
# the overseas branch rather than both overseas and generic market.
|
||||
score = (
|
||||
sum(len(token) for token in hits)
|
||||
+ (30 if angle in normalized_angles else 0)
|
||||
+ (20 if angle and angle in text else 0)
|
||||
+ (10 if label and label in text else 0)
|
||||
)
|
||||
scored.append((score, str(node["id"])))
|
||||
if not scored:
|
||||
return []
|
||||
best = max(score for score, _node_id in scored)
|
||||
return [node_id for score, node_id in scored if score == best]
|
||||
|
||||
|
||||
def _explicit_value(text: str, field_pattern: str) -> str | None:
|
||||
match = re.search(rf"(?:{field_pattern})(?:修改|调整)?(?:为|成|:|:)\s*([^,。;]{{2,100}})", text or "")
|
||||
return match.group(1).strip() if match else None
|
||||
|
||||
|
||||
def _clean(value: Any) -> str:
|
||||
return re.sub(r"\s+", " ", str(value or "")).strip()
|
||||
|
||||
|
||||
def _json_object(text: str) -> str:
|
||||
raw = (text or "").strip()
|
||||
if raw.startswith("```"):
|
||||
raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw, flags=re.I)
|
||||
start, end = raw.find("{"), raw.rfind("}")
|
||||
if start < 0 or end < start:
|
||||
raise ValueError("intent model did not return a JSON object")
|
||||
return raw[start : end + 1]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DeerFlowIntentModel",
|
||||
"IntentModel",
|
||||
"RuntimeIntentContext",
|
||||
"RuntimeIntentRouterAgent",
|
||||
"build_runtime_intent_router",
|
||||
]
|
||||
@@ -0,0 +1,629 @@
|
||||
"""Runtime command orchestration with safe-point application."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.report_collaboration.contracts.commands import CollaborationCommand, IntentDecision
|
||||
from app.report_collaboration.execution.ledger import TaskLedger
|
||||
from app.report_collaboration.execution.quality_gate import requirement_from_session_record
|
||||
from app.report_collaboration.interventions.impact_analyzer import CommandImpact, ImpactAnalyzer
|
||||
from app.report_collaboration.interventions.intent_router import RuntimeIntentContext, RuntimeIntentRouterAgent
|
||||
from deerflow.config.report_collaboration_config import ReportCollaborationConfig
|
||||
from deerflow.persistence.report_collaboration.base import (
|
||||
ReportCollaborationConflictError,
|
||||
ReportCollaborationNotFoundError,
|
||||
ReportCollaborationStore,
|
||||
ReportCollaborationValidationError,
|
||||
)
|
||||
from deerflow.persistence.report_collaboration.codec import parse_lease_until
|
||||
|
||||
_PROCESSABLE = {"accepted", "accepted_waiting_boundary"}
|
||||
_CANCELLABLE = {"pending", "classified", "confirmation_required", "accepted", "accepted_waiting_boundary"}
|
||||
|
||||
|
||||
class RuntimeCommandService:
|
||||
"""Classify, confirm and apply user commands without delegating scheduling."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: ReportCollaborationStore,
|
||||
*,
|
||||
router: RuntimeIntentRouterAgent | None = None,
|
||||
analyzer: ImpactAnalyzer | None = None,
|
||||
config: ReportCollaborationConfig | None = None,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._router = router or RuntimeIntentRouterAgent()
|
||||
self._analyzer = analyzer or ImpactAnalyzer(
|
||||
confirmation_threshold=(config or ReportCollaborationConfig()).intent_confirmation_threshold
|
||||
)
|
||||
self._config = config or ReportCollaborationConfig()
|
||||
self._ledger = TaskLedger(store)
|
||||
|
||||
async def submit(
|
||||
self,
|
||||
run_id: str,
|
||||
*,
|
||||
text: str,
|
||||
idempotency_key: str,
|
||||
target_node_id: str | None = None,
|
||||
agent_run_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
run, session, plan, node_runs, agent_runs = await self._context(run_id)
|
||||
existing = next(
|
||||
(item for item in await self._store.list_commands(run["session_id"], run_id=run_id) if item["idempotency_key"] == idempotency_key),
|
||||
None,
|
||||
)
|
||||
if existing is not None:
|
||||
if existing.get("status") != "pending":
|
||||
return existing
|
||||
# Resume an interrupted classification from the durable command,
|
||||
# never from a retry request carrying a different payload.
|
||||
text = str(existing.get("text") or text)
|
||||
stored_targets = list(existing.get("target_ids") or [])
|
||||
target_node_id = stored_targets[0] if stored_targets else None
|
||||
agent_run_id = None
|
||||
target_nodes, target_node_run_id = self._resolve_targets(
|
||||
plan=plan,
|
||||
node_runs=node_runs,
|
||||
agent_runs=agent_runs,
|
||||
target_node_id=target_node_id,
|
||||
agent_run_id=agent_run_id,
|
||||
)
|
||||
command = existing or await self._store.create_command(
|
||||
run["session_id"],
|
||||
idempotency_key=idempotency_key,
|
||||
text=text,
|
||||
run_id=run_id,
|
||||
operation="command",
|
||||
target_type="node" if target_nodes else None,
|
||||
target_ids=target_nodes,
|
||||
expected_revision=int(session.get("requirement_revision") or 0),
|
||||
status="pending",
|
||||
)
|
||||
# A concurrent duplicate may have won the unique idempotency key.
|
||||
if command.get("status") != "pending":
|
||||
return command
|
||||
message = await self._store.create_message(
|
||||
run["session_id"],
|
||||
role="human",
|
||||
content=text,
|
||||
# Command and message use separate uniqueness domains. Reusing the
|
||||
# client key lets the frontend replace its optimistic bubble.
|
||||
idempotency_key=idempotency_key,
|
||||
metadata={
|
||||
"idempotency_key": idempotency_key,
|
||||
"target_node_id": target_node_id,
|
||||
"agent_run_id": agent_run_id,
|
||||
"runtime_command": True,
|
||||
},
|
||||
command_id=command["command_id"],
|
||||
agent_run_id=agent_run_id,
|
||||
node_run_id=target_node_run_id,
|
||||
completed=True,
|
||||
)
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run_id,
|
||||
event_type="message.created",
|
||||
data={"message": message},
|
||||
)
|
||||
requirement = requirement_from_session_record(session)
|
||||
latest = _latest_nodes(node_runs)
|
||||
report_versions = await self._store.list_report_versions(run["session_id"])
|
||||
report_summary = None
|
||||
if report_versions:
|
||||
report_summary = str(report_versions[-1].get("markdown") or "")[:1200]
|
||||
decision = await self._router.route(
|
||||
RuntimeIntentContext(
|
||||
text=text,
|
||||
requirement=requirement.model_dump(mode="json") if requirement else {},
|
||||
plan_nodes=list(plan.get("nodes") or []),
|
||||
target_node_ids=target_nodes,
|
||||
target_agent_run_id=agent_run_id,
|
||||
awaiting_node_ids=[node_id for node_id, row in latest.items() if row.get("status") == "awaiting_input"],
|
||||
report_summary=report_summary,
|
||||
)
|
||||
)
|
||||
valid_node_ids = {str(item.get("id")) for item in plan.get("nodes") or [] if item.get("id")}
|
||||
decision_targets = [node_id for node_id in decision.requested_target_ids if node_id in valid_node_ids]
|
||||
impact = self._analyzer.analyze(
|
||||
decision,
|
||||
plan=plan,
|
||||
node_runs=node_runs,
|
||||
agent_runs=agent_runs,
|
||||
explicit_target_node_ids=target_nodes or decision_targets,
|
||||
)
|
||||
if decision.intent == "add_angle" and not impact.target_node_ids:
|
||||
rejected = await self._reject_classified(
|
||||
run,
|
||||
command,
|
||||
decision,
|
||||
impact,
|
||||
error="没有可用的研究支路承接新角度",
|
||||
)
|
||||
return rejected
|
||||
final_status = "confirmation_required" if impact.requires_confirmation else (
|
||||
"accepted_waiting_boundary" if impact.waiting_boundary_nodes else "accepted"
|
||||
)
|
||||
patch = _classification_patch(decision, impact, status=final_status)
|
||||
classified = {**command, **patch, "status": "classified"}
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run_id,
|
||||
event_type="command.classified",
|
||||
data={"command": CollaborationCommand.model_validate(classified).model_dump(mode="json")},
|
||||
)
|
||||
try:
|
||||
command = await self._store.patch_command(
|
||||
command["command_id"],
|
||||
patch=patch,
|
||||
expected_statuses={"pending"},
|
||||
)
|
||||
except ReportCollaborationConflictError:
|
||||
# Another request carrying the same key classified it first. The
|
||||
# unique command remains the only source of effects.
|
||||
return await self._store.get_command(command["command_id"]) or command
|
||||
if final_status == "confirmation_required":
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run_id,
|
||||
event_type="command.confirmation.required",
|
||||
data={"command": command},
|
||||
)
|
||||
return command
|
||||
await self._emit_accepted(run, command, bool(impact.waiting_boundary_nodes))
|
||||
if not impact.waiting_boundary_nodes:
|
||||
await self.process_safe_point(run_id)
|
||||
command = await self._store.get_command(command["command_id"]) or command
|
||||
return command
|
||||
|
||||
async def confirm(self, run_id: str, command_id: str, *, idempotency_key: str) -> dict[str, Any]:
|
||||
run, _session, plan, node_runs, agent_runs = await self._context(run_id)
|
||||
existing_audit = next(
|
||||
(item for item in await self._store.list_commands(run["session_id"], run_id=run_id) if item["idempotency_key"] == idempotency_key),
|
||||
None,
|
||||
)
|
||||
command = await self._command_for_run(run, command_id)
|
||||
if existing_audit is not None:
|
||||
return command
|
||||
if command.get("status") in {"accepted", "accepted_waiting_boundary", "executing", "completed"}:
|
||||
return command
|
||||
if command.get("status") != "confirmation_required":
|
||||
raise ReportCollaborationConflictError("COMMAND_STATE_CONFLICT", f"命令当前状态为 {command.get('status')},不能确认")
|
||||
await self._store.create_command(
|
||||
run["session_id"],
|
||||
idempotency_key=idempotency_key,
|
||||
text="",
|
||||
run_id=run_id,
|
||||
operation="confirm_command",
|
||||
target_type="command",
|
||||
target_ids=[command_id],
|
||||
status="completed",
|
||||
)
|
||||
decision = _decision_from_command(command)
|
||||
impact = self._analyzer.analyze(
|
||||
decision,
|
||||
plan=plan,
|
||||
node_runs=node_runs,
|
||||
agent_runs=agent_runs,
|
||||
explicit_target_node_ids=list(command.get("target_ids") or []),
|
||||
)
|
||||
status = "accepted_waiting_boundary" if impact.waiting_boundary_nodes else "accepted"
|
||||
try:
|
||||
command = await self._store.patch_command(
|
||||
command_id,
|
||||
patch={"status": status, "impact_nodes": impact.impact_nodes, "error": None},
|
||||
expected_statuses={"confirmation_required"},
|
||||
)
|
||||
except ReportCollaborationConflictError:
|
||||
current = await self._command_for_run(run, command_id)
|
||||
if current.get("status") in {"accepted", "accepted_waiting_boundary", "executing", "completed"}:
|
||||
return current
|
||||
raise
|
||||
await self._emit_accepted(run, command, bool(impact.waiting_boundary_nodes))
|
||||
if not impact.waiting_boundary_nodes:
|
||||
await self.process_safe_point(run_id)
|
||||
command = await self._store.get_command(command_id) or command
|
||||
return command
|
||||
|
||||
async def cancel(self, run_id: str, command_id: str, *, idempotency_key: str) -> dict[str, Any]:
|
||||
run, _session, _plan, _nodes, _agents = await self._context(run_id)
|
||||
command = await self._command_for_run(run, command_id)
|
||||
audits = await self._store.list_commands(run["session_id"], run_id=run_id)
|
||||
if any(item["idempotency_key"] == idempotency_key for item in audits):
|
||||
return command
|
||||
await self._store.create_command(
|
||||
run["session_id"],
|
||||
idempotency_key=idempotency_key,
|
||||
text="",
|
||||
run_id=run_id,
|
||||
operation="cancel_command",
|
||||
target_type="command",
|
||||
target_ids=[command_id],
|
||||
status="completed",
|
||||
)
|
||||
if command.get("status") == "cancelled":
|
||||
return command
|
||||
try:
|
||||
cancelled = await self._store.patch_command(
|
||||
command_id,
|
||||
patch={"status": "cancelled"},
|
||||
expected_statuses=_CANCELLABLE,
|
||||
)
|
||||
except ReportCollaborationConflictError:
|
||||
current = await self._command_for_run(run, command_id)
|
||||
if current.get("status") == "cancelled":
|
||||
return current
|
||||
raise
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run["id"],
|
||||
event_type="command.cancelled",
|
||||
data={"command_id": command_id, "command": cancelled},
|
||||
)
|
||||
return cancelled
|
||||
|
||||
async def process_safe_point(self, run_id: str, *, completed_node_id: str | None = None) -> list[str]:
|
||||
"""Apply accepted commands in creation order at a model/tool/commit boundary."""
|
||||
|
||||
run, _session, _plan, node_runs, agent_runs = await self._context(run_id)
|
||||
applied: list[str] = []
|
||||
await self.reclaim_executing(run_id, force=False)
|
||||
commands = await self._store.list_commands(run["session_id"], run_id=run_id)
|
||||
# One command may mutate several attempts and artifacts. Never overlap
|
||||
# two such mutations for the same run, even across Gateway/worker
|
||||
# processes. CAS on the oldest command elects the processor.
|
||||
if any(item.get("status") == "executing" for item in commands):
|
||||
return applied
|
||||
for command in commands:
|
||||
if command.get("operation", "command") != "command" and not command.get("intent"):
|
||||
continue
|
||||
if command.get("status") not in _PROCESSABLE:
|
||||
continue
|
||||
running = _running_impacted_nodes(node_runs, agent_runs, list(command.get("impact_nodes") or []))
|
||||
if completed_node_id:
|
||||
running.discard(completed_node_id)
|
||||
if running:
|
||||
if command.get("status") == "accepted":
|
||||
await self._store.patch_command(
|
||||
command["command_id"],
|
||||
patch={"status": "accepted_waiting_boundary"},
|
||||
expected_statuses={"accepted"},
|
||||
)
|
||||
continue
|
||||
try:
|
||||
claimed = await self._store.patch_command(
|
||||
command["command_id"],
|
||||
patch={"status": "executing", "error": None},
|
||||
expected_statuses=_PROCESSABLE,
|
||||
)
|
||||
except ReportCollaborationConflictError:
|
||||
return applied
|
||||
try:
|
||||
result = await self._apply(run, claimed)
|
||||
await self._store.patch_command(
|
||||
command["command_id"],
|
||||
patch={"status": "completed", "reason": result},
|
||||
expected_statuses={"executing"},
|
||||
)
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run_id,
|
||||
event_type="command.completed",
|
||||
data={"command_id": command["command_id"], "result_summary": result},
|
||||
)
|
||||
applied.append(command["command_id"])
|
||||
except Exception as exc:
|
||||
message = str(exc)[:500]
|
||||
await self._store.patch_command(
|
||||
command["command_id"],
|
||||
patch={"status": "failed", "error": message},
|
||||
expected_statuses={"executing"},
|
||||
)
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run_id,
|
||||
event_type="command.failed",
|
||||
data={"command_id": command["command_id"], "error": message},
|
||||
)
|
||||
return applied
|
||||
|
||||
async def _apply(self, run: dict[str, Any], command: dict[str, Any]) -> str:
|
||||
intent = str(command.get("intent") or "")
|
||||
instruction = str(command.get("normalized_instruction") or command.get("text") or "")
|
||||
current_run = await self._store.get_run(run["id"])
|
||||
if (
|
||||
current_run
|
||||
and (current_run.get("cancel_requested") or current_run.get("status") == "cancelled")
|
||||
and intent not in {"cancel", "ask_report"}
|
||||
):
|
||||
raise ReportCollaborationConflictError("RUN_CANCELLED", "运行已取消,不能再应用修改")
|
||||
if intent == "cancel":
|
||||
await self._store.request_cancel_run(run["id"], idempotency_key=f"{command['idempotency_key']}:natural-cancel")
|
||||
return "已提交取消执行请求"
|
||||
if intent == "ask_report":
|
||||
versions = await self._store.list_report_versions(run["session_id"])
|
||||
artifacts = await self._store.list_artifacts(run["id"])
|
||||
if versions:
|
||||
answer = f"当前报告为 v{versions[-1]['version']},正文已生成;已有 {len(artifacts)} 项协作成果。"
|
||||
else:
|
||||
answer = f"报告仍在生成中,目前已有 {len(artifacts)} 项协作成果。"
|
||||
message = await self._store.create_message(
|
||||
run["session_id"],
|
||||
role="ai",
|
||||
content=answer,
|
||||
idempotency_key=f"{command['idempotency_key']}:answer",
|
||||
name="协作协调者",
|
||||
command_id=command["command_id"],
|
||||
completed=True,
|
||||
)
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run["id"],
|
||||
event_type="message.created",
|
||||
data={"message": message},
|
||||
)
|
||||
return "已回答当前报告状态"
|
||||
if intent == "answer_question":
|
||||
resumed = await self._ledger.apply_user_answer(
|
||||
run["id"],
|
||||
command_id=command["command_id"],
|
||||
instruction=instruction,
|
||||
node_ids=list(command.get("impact_nodes") or command.get("target_ids") or []),
|
||||
)
|
||||
if not resumed:
|
||||
raise ReportCollaborationValidationError("NO_AWAITING_NODE", "当前没有可由该回答恢复的等待节点")
|
||||
return f"已将回答交给 {len(resumed)} 个等待节点"
|
||||
|
||||
impact_nodes = list(command.get("impact_nodes") or [])
|
||||
if not impact_nodes:
|
||||
raise ReportCollaborationValidationError("NO_IMPACT_NODE", "没有找到可安全返工的节点")
|
||||
changed = await self._ledger.apply_command_rework(
|
||||
run["id"],
|
||||
command_id=command["command_id"],
|
||||
instruction=instruction,
|
||||
node_ids=impact_nodes,
|
||||
)
|
||||
if not changed:
|
||||
raise ReportCollaborationValidationError("COMMAND_NO_EFFECT", "目标节点已过期或命令已经应用")
|
||||
await self._apply_requirement_patch(run, command)
|
||||
return f"已在安全边界应用修改,重新排队 {len(changed)} 个节点"
|
||||
|
||||
async def reclaim_executing(self, run_id: str, *, force: bool = True) -> list[str]:
|
||||
"""Return stuck ``executing`` commands to ``accepted`` so a takeover can finish them.
|
||||
|
||||
``force=True`` is for lease reclaim: the previous worker is gone.
|
||||
``force=False`` only releases commands whose ``updated_at`` exceeded the lease TTL.
|
||||
"""
|
||||
|
||||
run = await self._store.get_run(run_id)
|
||||
if run is None:
|
||||
return []
|
||||
ttl = max(30, int(self._config.lease_seconds))
|
||||
now = datetime.now(UTC)
|
||||
reclaimed: list[str] = []
|
||||
for command in await self._store.list_commands(run["session_id"], run_id=run_id):
|
||||
if command.get("status") != "executing":
|
||||
continue
|
||||
if not force:
|
||||
updated = parse_lease_until(command.get("updated_at"))
|
||||
if updated is not None and now - updated < timedelta(seconds=ttl):
|
||||
continue
|
||||
try:
|
||||
await self._store.patch_command(
|
||||
command["command_id"],
|
||||
patch={"status": "accepted", "error": None},
|
||||
expected_statuses={"executing"},
|
||||
)
|
||||
except ReportCollaborationConflictError:
|
||||
continue
|
||||
reclaimed.append(command["command_id"])
|
||||
return reclaimed
|
||||
|
||||
async def _reject_classified(
|
||||
self,
|
||||
run: dict[str, Any],
|
||||
command: dict[str, Any],
|
||||
decision: IntentDecision,
|
||||
impact: CommandImpact,
|
||||
*,
|
||||
error: str,
|
||||
) -> dict[str, Any]:
|
||||
patch = _classification_patch(decision, impact, status="rejected")
|
||||
patch["error"] = error
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run["id"],
|
||||
event_type="command.classified",
|
||||
data={"command": {**command, **patch}},
|
||||
)
|
||||
try:
|
||||
rejected = await self._store.patch_command(
|
||||
command["command_id"],
|
||||
patch=patch,
|
||||
expected_statuses={"pending"},
|
||||
)
|
||||
except ReportCollaborationConflictError:
|
||||
return await self._store.get_command(command["command_id"]) or command
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run["id"],
|
||||
event_type="command.failed",
|
||||
data={"command_id": rejected["command_id"], "error": error},
|
||||
)
|
||||
return rejected
|
||||
|
||||
async def _apply_requirement_patch(self, run: dict[str, Any], command: dict[str, Any]) -> None:
|
||||
intent = str(command.get("intent") or "")
|
||||
if intent not in {"add_angle", "update_requirements"}:
|
||||
return
|
||||
session = await self._store.get_session_record(run["session_id"])
|
||||
if not session:
|
||||
raise ReportCollaborationNotFoundError("session", run["session_id"])
|
||||
current = requirement_from_session_record(session)
|
||||
if current is None:
|
||||
return
|
||||
# Recreate the same deterministic patch used by the router. It is not
|
||||
# persisted on the command row, so confirmed commands cannot trust an
|
||||
# arbitrary client payload.
|
||||
context = RuntimeIntentContext(
|
||||
text=str(command.get("text") or ""),
|
||||
requirement=current.model_dump(mode="json"),
|
||||
plan_nodes=[],
|
||||
)
|
||||
decision = await RuntimeIntentRouterAgent().route(context)
|
||||
if decision.requirement_patch is None:
|
||||
return
|
||||
state = dict(session.get("requirement_json") or {})
|
||||
snapshot = decision.requirement_patch.model_dump(mode="json")
|
||||
if isinstance(state.get("snapshot"), dict):
|
||||
state["snapshot"] = snapshot
|
||||
else:
|
||||
state = snapshot
|
||||
await self._store.save_requirement_state(
|
||||
run["session_id"],
|
||||
requirement_json=state,
|
||||
requirement_revision=int(snapshot["revision"]),
|
||||
status="running",
|
||||
)
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run["id"],
|
||||
event_type="requirement.updated",
|
||||
data={"requirement": snapshot, "revision": snapshot["revision"], "command_id": command["command_id"]},
|
||||
)
|
||||
|
||||
async def _emit_accepted(self, run: dict[str, Any], command: dict[str, Any], waiting: bool) -> None:
|
||||
await self._store.append_event(
|
||||
session_id=run["session_id"],
|
||||
run_id=run["id"],
|
||||
event_type="command.accepted",
|
||||
data={
|
||||
"command_id": command["command_id"],
|
||||
"waiting_boundary": waiting,
|
||||
"impact_nodes": list(command.get("impact_nodes") or []),
|
||||
},
|
||||
)
|
||||
|
||||
async def _command_for_run(self, run: dict[str, Any], command_id: str) -> dict[str, Any]:
|
||||
command = await self._store.get_command(command_id)
|
||||
if command is None:
|
||||
raise ReportCollaborationNotFoundError("command", command_id)
|
||||
commands = await self._store.list_commands(run["session_id"], run_id=run["id"])
|
||||
if not any(item["command_id"] == command_id for item in commands):
|
||||
raise ReportCollaborationNotFoundError("command", command_id)
|
||||
return command
|
||||
|
||||
async def _context(self, run_id: str) -> tuple[dict, dict, dict, list[dict], list[dict]]:
|
||||
run = await self._store.get_run(run_id)
|
||||
if run is None:
|
||||
raise ReportCollaborationNotFoundError("run", run_id)
|
||||
session = await self._store.get_session_record(run["session_id"])
|
||||
if session is None:
|
||||
raise ReportCollaborationNotFoundError("session", run["session_id"])
|
||||
plan = await self._store.get_plan(run["plan_id"])
|
||||
if plan is None:
|
||||
raise ReportCollaborationNotFoundError("plan", run["plan_id"])
|
||||
return run, session, plan, await self._store.list_node_runs(run_id), await self._store.list_agent_runs(run_id)
|
||||
|
||||
@staticmethod
|
||||
def _resolve_targets(
|
||||
*,
|
||||
plan: dict,
|
||||
node_runs: list[dict],
|
||||
agent_runs: list[dict],
|
||||
target_node_id: str | None,
|
||||
agent_run_id: str | None,
|
||||
) -> tuple[list[str], str | None]:
|
||||
valid_nodes = {str(item.get("id")) for item in plan.get("nodes") or [] if item.get("id")}
|
||||
node_by_run = {str(item.get("node_run_id")): str(item.get("node_id")) for item in node_runs if item.get("node_run_id")}
|
||||
resolved: list[str] = []
|
||||
node_run_id: str | None = None
|
||||
if target_node_id:
|
||||
if target_node_id not in valid_nodes:
|
||||
raise ReportCollaborationValidationError("TARGET_NOT_FOUND", f"目标节点不存在:{target_node_id}")
|
||||
resolved.append(target_node_id)
|
||||
latest = [item for item in node_runs if item.get("node_id") == target_node_id]
|
||||
if latest:
|
||||
node_run_id = max(latest, key=lambda item: int(item.get("attempt") or 0)).get("node_run_id")
|
||||
if agent_run_id:
|
||||
agent = next((item for item in agent_runs if item.get("agent_run_id") == agent_run_id), None)
|
||||
if agent is None:
|
||||
raise ReportCollaborationValidationError("TARGET_NOT_FOUND", f"智能体运行不存在:{agent_run_id}")
|
||||
agent_node_run = str(agent.get("node_run_id") or "")
|
||||
agent_node = node_by_run.get(agent_node_run)
|
||||
if not agent_node:
|
||||
raise ReportCollaborationValidationError("TARGET_NOT_FOUND", f"智能体运行没有对应节点:{agent_run_id}")
|
||||
if resolved and resolved[0] != agent_node:
|
||||
raise ReportCollaborationValidationError("TARGET_MISMATCH", "目标节点与智能体运行不属于同一节点")
|
||||
if agent_node not in resolved:
|
||||
resolved.append(agent_node)
|
||||
node_run_id = agent_node_run
|
||||
return resolved, node_run_id
|
||||
|
||||
|
||||
def _classification_patch(decision: IntentDecision, impact: CommandImpact, *, status: str) -> dict[str, Any]:
|
||||
return {
|
||||
"intent": decision.intent,
|
||||
"confidence": decision.confidence,
|
||||
"target_type": impact.target_type,
|
||||
"target_ids": impact.target_node_ids,
|
||||
"normalized_instruction": decision.normalized_instruction,
|
||||
"requires_confirmation": impact.requires_confirmation,
|
||||
"cost_level": impact.cost_level,
|
||||
"reason": impact.reason,
|
||||
"impact_nodes": impact.impact_nodes,
|
||||
"status": status,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
|
||||
def _decision_from_command(command: dict[str, Any]) -> IntentDecision:
|
||||
intent = command.get("intent")
|
||||
if not intent:
|
||||
raise ReportCollaborationValidationError("COMMAND_NOT_CLASSIFIED", "命令尚未完成意图识别")
|
||||
return IntentDecision.model_validate(
|
||||
{
|
||||
"intent": intent,
|
||||
"confidence": command.get("confidence") or 0,
|
||||
"normalized_instruction": command.get("normalized_instruction") or command.get("text") or "",
|
||||
"scope": command.get("target_type") or "conversation",
|
||||
"requested_target_ids": command.get("target_ids") or [],
|
||||
"requirement_patch": None,
|
||||
"requires_confirmation": False,
|
||||
"cost_level": command.get("cost_level") or "low",
|
||||
"reason": command.get("reason") or "用户已确认",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _latest_nodes(rows: list[dict]) -> dict[str, dict]:
|
||||
latest: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
node_id = str(row.get("node_id") or "")
|
||||
if node_id and (node_id not in latest or int(row.get("attempt") or 0) >= int(latest[node_id].get("attempt") or 0)):
|
||||
latest[node_id] = row
|
||||
return latest
|
||||
|
||||
|
||||
def _running_impacted_nodes(node_runs: list[dict], agent_runs: list[dict], impact_nodes: list[str]) -> set[str]:
|
||||
wanted = set(impact_nodes)
|
||||
latest = _latest_nodes(node_runs)
|
||||
node_by_run = {str(row.get("node_run_id")): node_id for node_id, row in latest.items()}
|
||||
running = {
|
||||
node_id
|
||||
for node_id, row in latest.items()
|
||||
if node_id in wanted and row.get("status") in {"running", "validating"}
|
||||
}
|
||||
for agent in agent_runs:
|
||||
if agent.get("status") == "running":
|
||||
node_id = node_by_run.get(str(agent.get("node_run_id") or ""))
|
||||
if node_id in wanted:
|
||||
running.add(node_id)
|
||||
return running
|
||||
|
||||
|
||||
__all__ = ["RuntimeCommandService"]
|
||||
Reference in new issue
Block a user