lead.py 33.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
"""主 Agent:理解 → 快速通道 或(召回经验 → 分派子 Agent → 反思 → 行动建议)→ 作答。

    question
     → 本体链接(不调 LLM)
     → 快速通道(router,不调 LLM):问的是一个已定义指标 / 一个对象 / 一个定义时,直接组一次工具调用,
       拿到结果后作答一次就结束 —— 日常大多数提问走这条路,十来秒出结论
     → 走不了快速通道的:经验召回(相似案例、组织记忆)
     → 主 Agent 思考并分派:knowledge / data 并行;命中已验证的高相似案例时直接复用路径(快路径)
     → 子 Agent 各自「思考 → 调工具 → 观察 → 再思考」,工具一律经 MCP(审计 via=ask:<agent>)
     → 主 Agent 反思:有子 Agent 失败或没把握时,追加一轮分派
     → 行动 Agent:动作卡(预览 + 补参数)、流程卡
     → 作答(流式):结论 → 依据 → 数据与分析 → 建议下一步
     → 落库:轮次 + 完整推理轨迹;后台沉淀经验(案例、记忆、习惯)

同步生成器 yield 事件,由 deps.sse 桥接成 SSE。编排在后台线程里跑,
页面切走、断线只是不再有人听事件,编排在后台照常跑完并落库;回到对话就能看到结果。
只有用户明确点「停止」(stop_turn)才置取消标志,轮次记为 aborted。
"""
from __future__ import annotations

import contextvars
import json
import logging
import re
import threading
import time
from typing import Any, Iterator

from ..capability import defs
from ..core import llm
from ..governance import audit, llmlog
from ..kernel import linker, service as ksvc
from . import action as action_agent
from . import prompts, router, session
from .base import (AGENT_META, KNOWLEDGE, DATA, SUB_AGENTS, call_tool, run_parallel, result_text, think_json,
                   tools_text)
from .trace import Tracer

log = logging.getLogger(__name__)

_CHUNK_CITE = re.compile(r"\[\^([A-Za-z0-9_\-]+:[A-Za-z0-9_\-]+)\]")
_RUN_CITE = re.compile(r"\[\^run:(\d+)\]")
_ANY_CITE = re.compile(r"\[\^([^\]\s]{1,80})\]")


# ---------------------------------------------------------------- 给模型看的上下文
def ontology_text(limit: int = 40, links: dict | None = None) -> str:
    """已发布的函数与指标:按真实名称调用,而不是猜一个「补货规则」出来。
    给了 links 就只带「问句里提到的 + 少量其他」:函数一多,把四十个全塞进提示词既慢又分散注意力。"""
    out = []
    fns = ksvc.rt_by_kind("function")
    if links is not None:
        hit = {c["id"] for c in links.get("concepts") or []}
        fns = [c for c in fns if c["id"] in hit] + [c for c in fns if c["id"] not in hit][:12]
    for c in fns[:limit]:
        sp = c.get("spec") or {}
        cat = sp.get("category")
        if cat == "aggregate":
            sig = f"指标,单位 {sp.get('unit') or '-'},口径:{sp.get('formula_text') or ''}(取数用 data_ask 或 query_metric)"
        elif cat == "rule":
            sig = f"规则,vars {sp.get('params') or []}:{sp.get('expression') or sp.get('text') or ''}"
        elif cat == "decision":
            sig = f"决策表,inputs {[i.get('name') for i in sp.get('inputs') or []]}"
        else:
            sig = c.get("kind_label") or cat or ""
        out.append(f"- {c['name']}:{sig}")
    # 对象、属性(中文名)、关系:建模时花力气最多的部分,以前提问时从来不进提示词
    from ..kernel import grounding
    return ("\n".join(out) or "(无)") + "\n\n〔对象与关系〕\n" + grounding.digest()


def skills_text() -> str:
    return "\n".join(f"- {s['name']}:{s['description']} 输入 {[i['name'] for i in s['spec'].get('inputs') or []]}"
                     for s in defs.list_defs("skill", "published")) or "(无)"


def links_text(links: dict) -> str:
    lines = []
    for c in links.get("concepts") or []:
        full = ksvc.rt_get(c["id"]) or {}
        spec = full.get("spec") or {}
        extra = ""
        tk = c.get("type_key") or c.get("kind")
        if tk == "aggregate":
            b = ksvc.rt_binding(full, "metric_expr")
            dims = list((b or {}).get("ref", {}).get("dimensions") or {})
            extra = (f";可拆分维度:{'、'.join(dims) or '无'};单位:{spec.get('unit', '')}"
                     f";{'可按对象取值' if (b or {}).get('ref', {}).get('object_key_column') else ''}"
                     f"{';未绑定数据,不能取数' if not b else ''}")
        elif tk == "rule":
            extra = f";表达式:{spec.get('expression') or '(仅文字)'};参数:{spec.get('params')}"
        elif tk == "decision":
            extra = (f";决策表,输入:{'、'.join(i['name'] for i in spec.get('inputs') or [])}"
                     f";输出:{'、'.join(o['name'] for o in spec.get('outputs') or [])}")
        elif tk == "object_set":
            extra = f";一批「{spec.get('base') or ''}」:{spec.get('text') or ''}"
        label = full.get("kind_label") or tk
        lines.append(f"- {label}「{c['name']}」(问句中:{'、'.join(c.get('matched') or [])})"
                     f":{(full.get('description') or '')[:80]}{extra}")
    for i in links.get("instances") or []:
        lines.append(f"- 对象实例:{i['type_name']}「{i['label']}」主键={i['key']}")
    if links.get("time"):
        lines.append(f"- 时间:{links['time']}")
    return "\n".join(lines) or "(没有识别出本体概念)"


def history_text(hist: list[dict]) -> str:
    if not hist:
        return "(无)"
    out = []
    for h in hist:
        calls = ";".join(f"{s.get('call')}({json.dumps(s.get('args'), ensure_ascii=False)[:100]})"
                         for s in (h.get("plan") or {}).get("steps") or [])
        out.append(f"用户:{h['question']}\n做了:{calls or '无'}\n回答摘要:{h['answer'][:300]}")
    return "\n\n".join(out)


# ---------------------------------------------------------------- 分派
def _norm_delegations(raw: Any) -> list[dict]:
    """同一个子 Agent 的多个分派合并成一个(任务拼起来、首批调用合并)。"""
    merged: dict[str, dict] = {}
    for d in raw if isinstance(raw, list) else []:
        if not isinstance(d, dict):
            continue
        agent = str(d.get("agent") or "").strip().lower()
        if agent not in ("knowledge", "data", "action"):
            continue
        calls = [c for c in d.get("calls") or [] if isinstance(c, dict) and (c.get("tool") or c.get("call"))]
        cur = merged.setdefault(agent, {"agent": agent, "task": "", "calls": []})
        task = str(d.get("task") or "").strip()
        cur["task"] = f"{cur['task']};{task}".strip(";") if task else cur["task"]
        cur["calls"] = (cur["calls"] + calls)[:3]
    return list(merged.values())


def _from_case(case: dict, question: str) -> dict:
    """快路径:原样复用已验证案例的分派与首批调用。

    能走到这里,问题和案例高度相似、问的又是同一批对象(见 memory.recall),案例里当时写好的
    任务与取数问题比当前一句口语更精确,直接用。
    """
    p = case.get("plan") or {}
    return {"intent": p.get("intent") or "mixed", "rewrite": question,
            "delegations": _norm_delegations(p.get("delegations")),
            "follow_ups": p.get("follow_ups") or [], "clarify": "", "from_case": case["id"]}


def _dispatch(tracer: Tracer, question: str, links: dict, hist: list[dict], mem: dict) -> dict:
    from ..memory import service as memory
    fast = mem.get("fast")
    if fast:
        tracer.thought("lead", f"这个问题和已验证的案例「{fast['question'][:40]}」高度相似"
                               f"({fast['score']:.0%}),直接复用当时的分析路径,省去一轮规划。", "lead")
        return _from_case(fast, question)
    sub_tools = list(dict.fromkeys(KNOWLEDGE.tools + DATA.tools))
    # 流程卡与动作的目录只在「用户是在让系统做事」时才给全:纯查询用不上,白占一大段提示词
    operate = router.is_operation(question)
    msgs = [{"role": "system", "content": prompts.LEAD_SYSTEM.format(
                tools=tools_text(sub_tools), ontology=ontology_text(links=links), skills=skills_text(),
                sops=action_agent.sops_catalog() if operate else action_agent.sops_brief(),
                actions=action_agent.actions_catalog() if operate else "(用户没有要求做事,这一轮不需要)",
                facts=memory.facts_text(mem), cases=memory.cases_text(mem))},
            {"role": "user", "content": prompts.LEAD_USER.format(
                history=history_text(hist), links=links_text(links), question=question)}]
    try:
        p = think_json(tracer, "lead", "lead", msgs)
    except Exception as e:  # noqa: BLE001
        log.warning("主 Agent 分派失败,退回知识检索 + 问数:%s", str(e)[:200])
        p = {}
    if not p.get("delegations") and not p.get("clarify") and p.get("intent") != "chitchat":
        p = {**p, "intent": p.get("intent") or "mixed", "delegations": [
            {"agent": "knowledge", "task": question, "calls": [
                {"tool": "search_knowledge", "args": {"query": question}, "why": "先找文档依据"}]}]}
    p["delegations"] = _norm_delegations(p.get("delegations"))
    p["follow_ups"] = [str(x) for x in p.get("follow_ups") or [] if x][:3]
    return p


def _wants_action(p: dict, question: str) -> bool:
    """这一轮要不要出动作 / 流程的卡片:只在用户明确让系统做事时才出。
    以前只要问句里带「补货」「流程卡」「标记」这些词就触发,问一句「补货流程是什么」也会跑出一张卡。"""
    if router.is_operation(question):
        return True
    return p.get("intent") == "action" and any(d["agent"] == "action" for d in p["delegations"])


def _action_task(p: dict) -> str:
    return next((d["task"] for d in p["delegations"] if d["agent"] == "action" and d.get("task")), "")


def _reflect(tracer: Tracer, question: str, reports: list[dict]) -> dict:
    text = "\n\n".join(_report_text(r) for r in reports)
    msgs = [{"role": "system", "content": prompts.REFLECT_SYSTEM.format(
                tools=tools_text(list(dict.fromkeys(KNOWLEDGE.tools + DATA.tools))))},
            {"role": "user", "content": prompts.REFLECT_USER.format(question=question, reports=text)}]
    try:
        r = think_json(tracer, "lead", "lead", msgs)
    except Exception:  # noqa: BLE001
        return {"sufficient": True}
    r["delegations"] = [d for d in _norm_delegations(r.get("delegations")) if d["agent"] != "action"][:2]
    return r


def _report_text(r: dict) -> str:
    lines = [f"【{r['label']}】任务:{r['task']}", f"结论:{r['summary']}(把握 {r['confidence']:.0%})"]
    if r.get("findings"):
        lines.append("发现:" + ";".join(r["findings"]))
    if r.get("insights"):
        lines.append("解读:" + ";".join(r["insights"]))
    return "\n".join(lines)


def _run_agents(tracer: Tracer, delegs: list[dict], question: str, ltext: str, onto: str) -> list[dict]:
    todo = [d for d in delegs if d["agent"] in SUB_AGENTS]
    return run_parallel([
        (lambda d=d: SUB_AGENTS[d["agent"]].run(tracer, d["task"] or question, question=question,
                                                links_text=ltext, ontology=onto, first_calls=d["calls"]))
        for d in todo])


# ---------------------------------------------------------------- 主流程
_tracers: dict[str, Tracer] = {}                   # 轮次 → 追踪器(「停止」按它置取消标志)
_workers: dict[str, threading.Thread] = {}       # 轮次 → 工作线程(收尾时自己摘掉;测试里用来等它结束)


def wait_worker(turn_id: str, timeout: float = 10.0) -> bool:
    """等某一轮的工作线程结束。返回它是否已经结束。"""
    t = _workers.get(turn_id)
    if t is not None:
        t.join(timeout)
    return t is None or not t.is_alive()


def run(question: str, conversation_id: str = "", overrides: dict | None = None) -> Iterator[dict]:
    question = (question or "").strip()
    tracer = Tracer()
    conv_id = session.ensure_conversation(conversation_id, question)
    turn_id = session.new_turn(conv_id, question)
    tracer.emit({"type": "start", "conversation_id": conv_id, "turn_id": turn_id,
                 "agents": AGENT_META})
    ctx = contextvars.copy_context()
    worker = threading.Thread(target=lambda: ctx.run(_work, tracer, question, conv_id, turn_id), daemon=True)
    _workers[turn_id] = worker
    _tracers[turn_id] = tracer
    worker.start()
    # 听事件的一端断开(切走页面、网络断了)不影响编排:工作线程自己跑完、自己落库
    yield from tracer.drain()


def stop_turn(turn_id: str) -> bool:
    """用户点「停止」:置取消标志,轮次立刻记为中断。返回是否真有一轮在跑。"""
    tracer = _tracers.get(turn_id)
    if tracer is None:
        return False
    tracer.cancel.set()
    try:
        session.save_turn(turn_id, "aborted")
        session.save_trace(turn_id, tracer.snapshot(), tracer.summary())
    except Exception:  # noqa: BLE001
        log.exception("记录中断的提问失败 %s", turn_id)
    return True


def _work(tracer: Tracer, question: str, conv_id: str, turn_id: str) -> None:
    started = tracer.started
    state: dict[str, Any] = {"links": None, "plan": None, "steps": None, "memory": {}}
    try:
        with llmlog.feature("ask"):
            _orchestrate(tracer, question, conv_id, turn_id, state)
    except Exception as e:  # noqa: BLE001
        log.exception("提问失败 %s", turn_id)
        tracer.emit({"type": "error", "stage": "ask", "error": str(e)[:500]})
        session.save_turn(turn_id, "error", links=state["links"], plan=state["plan"],
                          steps=state["steps"], started=started)
        session.save_trace(turn_id, tracer.snapshot(), tracer.summary(), state["memory"])
    finally:
        tracer.close()
        _workers.pop(turn_id, None)
        _tracers.pop(turn_id, None)


def _orchestrate(tracer: Tracer, question: str, conv_id: str, turn_id: str, state: dict) -> None:
    from ..memory import service as memory
    started = tracer.started
    hist = session.history(conv_id)

    # 1) 链接
    links = linker.link(question)
    state["links"] = links
    tracer.emit({"type": "link", "span": "lead", "concepts": links["concepts"],
                 "instances": links["instances"], "time": links["time"]})
    tracer.emit({"type": "agent_start", "span": "lead", "parent": "", "agent": "lead",
                 "label": AGENT_META["lead"]["label"], "task": question})

    # 2) 快速通道:一次工具调用能答的问题不走多智能体
    last = next(((h.get("plan") or {}).get("fast") for h in reversed(hist) if (h.get("plan") or {}).get("fast")), None)
    try:
        fast = router.route(question, links, last)
    except Exception:  # noqa: BLE001  路由只是捷径,出错就照常走多智能体
        log.exception("快速通道选路失败")
        fast = None
    if fast and _fast_lane(tracer, question, links, fast, conv_id, turn_id, state):
        return

    # 3) 经验召回
    mem = memory.recall(question, links, follow_up=bool(hist))
    state["memory"] = memory.brief(mem)
    if mem.get("cases") or mem.get("facts"):
        tracer.stats["memory"] = len(mem.get("cases") or []) + len(mem.get("facts") or [])
        tracer.emit({"type": "memory", "span": "lead", **state["memory"]})

    # 4) 理解与分派
    p = _dispatch(tracer, question, links, hist, mem)
    state["plan"] = p
    tracer.emit({"type": "plan", "span": "lead", "intent": p.get("intent", ""), "rewrite": p.get("rewrite", ""),
                 "delegations": p["delegations"], "follow_ups": p.get("follow_ups") or [],
                 "clarify": p.get("clarify", ""), "from_case": p.get("from_case", "")})
    q2 = p.get("rewrite") or question

    if p.get("clarify") and not p["delegations"]:
        answer = str(p["clarify"])
        tracer.emit({"type": "answer_start"})
        tracer.emit({"type": "answer_delta", "text": answer})
        _finish(tracer, turn_id, conv_id, question, links, p, [], answer, {}, {}, [], [], started, clarify=True)
        return

    # 5) 子 Agent 并行
    onto = ontology_text(links=links)
    ltext = links_text(links)
    reports = _run_agents(tracer, p["delegations"], q2, ltext, onto) if not tracer.cancel.is_set() else []

    # 6) 反思:有子 Agent 没拿到结果才追加一轮(「把握不大」不算 —— 多想一轮要再等二三十秒,往往换不来更好的答案);
    #    时间预算用完了也不再追加
    if reports and not tracer.cancel.is_set() and not tracer.over_budget() and any(not r["ok"] for r in reports):
        rf = _reflect(tracer, q2, reports)
        tracer.emit({"type": "reflect", "span": "lead", "sufficient": bool(rf.get("sufficient", True)),
                     "missing": str(rf.get("missing") or ""), "delegations": rf.get("delegations") or []})
        if not rf.get("sufficient", True) and rf.get("delegations") and not tracer.cancel.is_set():
            reports += _run_agents(tracer, rf["delegations"], q2, ltext, onto)

    records = [rec for r in reports for rec in r["records"]]
    results = {rec["id"]: rec["_result"] for rec in records}
    # 「本次用到的本体」:实际执行过的指标 / 规则 / 决策表 / 概念,而不只是问句里匹配到的
    from ..kernel import grounding
    used = grounding.used_concepts(list(results.values()))
    if used:
        tracer.emit({"type": "onto_used", "span": "lead", "items": used})
    steps = [{k: v for k, v in rec.items() if k != "_result"} for rec in records]
    state["steps"] = steps
    p["steps"] = [{"id": s["id"], "call": s["call"], "args": s["args"], "why": s.get("why", ""),
                   "agent": s.get("agent", "")} for s in steps]
    chunk_pool, data_pool = _pools(records)
    results_text = "\n\n".join(result_text(rec, rec["_result"]) for rec in records) or "(没有执行任何调用)"

    # 7) 行动建议:只在用户明确让系统做事时
    cards: list[dict] = []
    sops: list[dict] = []
    if _wants_action(p, question) and not tracer.cancel.is_set():
        act = action_agent.run(tracer, q2, links, ltext, results, results_text, task=_action_task(p))
        cards, sops = act["cards"], act["sops"]
        if cards:
            tracer.emit({"type": "actions", "items": cards})
        if sops:
            tracer.emit({"type": "sops", "items": sops})

    if tracer.cancel.is_set():
        return

    # 8) 作答。只把**真的生成了**的卡片告诉作答模型:预览失败、找不到流程卡的那些不算,
    #    否则它会照着提示词说「已为您生成审批卡」,而页面上什么都没有
    ok_cards = [c for c in cards if not c.get("error")]
    ok_sops = [c for c in sops if not c.get("error")]
    cards_text = "\n".join(
        [f"- 动作卡「{c['display_name']}」:{(c.get('preview') or {}).get('summary') or ''}(理由:{c['reason']})"
         for c in ok_cards]
        + [f"- 流程卡「{c.get('sop')}」:等用户确认后发起(理由:{c.get('reason', '')})" for c in ok_sops]) or "无"
    msgs = [{"role": "system", "content": prompts.ANSWER_SYSTEM},
            {"role": "user", "content": prompts.ANSWER_USER.format(
                question=q2, links=ltext, facts=memory.facts_text(mem),
                reports="\n\n".join(_report_text(r) for r in reports) or "(没有分派子 Agent)",
                results=_fit(results_text, records, 14000), cards=cards_text)}]
    tracer.emit({"type": "answer_start"})
    buf: list[str] = []
    try:
        for piece in llm.chat_stream(msgs, temperature=0.2):
            if tracer.cancel.is_set():
                break
            buf.append(piece)
            tracer.emit({"type": "answer_delta", "text": piece})
    except Exception as e:  # noqa: BLE001
        msg = f"(作答失败:{str(e)[:200]})"
        buf.append(msg)
        tracer.emit({"type": "answer_delta", "text": msg})
    tracer.stats["llm"] += 1
    answer = normalize_cites("".join(buf), steps, results, chunk_pool, data_pool)
    answer = defabricate(answer, bool(ok_cards or ok_sops))
    _finish(tracer, turn_id, conv_id, question, links, p, steps, answer, chunk_pool, data_pool, cards, sops,
            started, reports=reports, memory_brief=state["memory"])


def _fit(results_text: str, records: list[dict], budget: int) -> str:
    """放不下时「数据优先」:先保留取数结果,再放文档原文,而不是从头截断(那样排在后面的数据会被整段丢掉)。"""
    if llm.count_tokens(results_text) <= budget:
        return results_text
    data = [r for r in records if isinstance(r["_result"], dict) and r["_result"].get("columns") is not None]
    rest = [r for r in records if r not in data]
    text = "\n\n".join(result_text(r, r["_result"]) for r in data + rest)
    return llm.truncate_to_tokens(text, budget)


_CLAIM = re.compile(r"已(?:经)?(?:为您|为你|帮您|帮你|替您|替你)?(?:成功)?(?:生成|提交|发起|创建|启动|下达|派发)了?")


def defabricate(answer: str, has_cards: bool) -> str:
    """这一轮没有生成任何卡片,答案里却说「已为您生成 / 已提交 / 已发起……」:改成建议的口吻。
    模型偶尔会这样说,而用户会当真 —— 以为单子已经提了。"""
    if has_cards or not _CLAIM.search(answer):
        return answer
    return _CLAIM.sub("建议", answer)


def _fast_lane(tracer: Tracer, question: str, links: dict, fast: dict, conv_id: str, turn_id: str,
               state: dict) -> bool:
    """走快速通道。返回 False 表示没走通(工具调用失败 / 什么都没查到),调用方改走多智能体。"""
    from ..memory import service as memory
    lane = fast["lane"]
    p: dict[str, Any] = {"intent": "knowledge" if lane == "knowledge" else "data", "rewrite": question,
                         "delegations": [], "follow_ups": [], "clarify": "", "lane": lane,
                         "lane_label": router.LANE_LABEL[lane], "why": fast["why"]}
    tracer.emit({"type": "plan", "span": "lead", "intent": p["intent"], "rewrite": question, "delegations": [],
                 "follow_ups": [], "clarify": "", "from_case": "", "lane": lane,
                 "lane_label": p["lane_label"], "why": fast["why"]})
    tracer.thought("lead", f"{fast['why']},走{p['lane_label']},不用再层层分派。", "lead")
    records = run_parallel([lambda c=c: call_tool(tracer, "lead", "lead", "f", c) for c in fast["calls"]])
    ok = [r for r in records if not r.get("error")]
    useful = [r for r in ok if _has_content(r["_result"])]
    if not useful:
        why = ";".join(str(r.get("error") or "没有查到内容") for r in records)[:200]
        tracer.thought("lead", f"\n快速通道没走通({why}),改用多智能体仔细查。", "lead")
        return False
    notes = list(fast.get("notes") or [])
    for r in ok:
        res = r["_result"]
        if fast.get("where") and isinstance(res.get("rows"), list) and "value" in (res.get("columns") or []):
            i = res["columns"].index("value")
            res["rows"] = [row for row in res["rows"] if isinstance(row[i], (int, float)) and row[i] > 0]
        notes += [str(n) for n in res.get("notes") or []]
        if res.get("truncated"):
            notes.append("结果行数超过上限,只取了前面一部分")
        if isinstance(res.get("rows"), list) and not res["rows"] and res.get("columns"):
            notes.append("查询成功但没有符合条件的数据")
    results = {r["id"]: r["_result"] for r in records}
    steps = [{k: v for k, v in r.items() if k != "_result"} for r in records]
    state["steps"] = steps
    p["steps"] = [{"id": s["id"], "call": s["call"], "args": s["args"], "why": s.get("why", ""), "agent": "lead"}
                  for s in steps]
    p["fast"] = fast.get("memo") or {"lane": lane}
    p["follow_ups"] = _fast_follow_ups(fast, links)
    state["plan"] = p
    from ..kernel import grounding
    used = grounding.used_concepts(list(results.values()))
    if used:
        tracer.emit({"type": "onto_used", "span": "lead", "items": used})
    chunk_pool, data_pool = _pools(records)
    results_text = "\n\n".join(result_text(r, r["_result"]) for r in records)
    prefs = memory.preferences_text()
    msgs = [{"role": "system", "content": prompts.FAST_ANSWER_SYSTEM},
            {"role": "user", "content": prompts.FAST_ANSWER_USER.format(
                question=question, why=fast["why"], results=_fit(results_text, records, 8000),
                notes="\n".join(f"- {n}" for n in dict.fromkeys(notes)) or "(无)", facts=prefs)}]
    tracer.emit({"type": "answer_start"})
    buf: list[str] = []
    try:
        for piece in llm.chat_stream(msgs, temperature=0.2):
            if tracer.cancel.is_set():
                break
            buf.append(piece)
            tracer.emit({"type": "answer_delta", "text": piece})
    except Exception as e:  # noqa: BLE001
        msg = f"(作答失败:{str(e)[:200]})"
        buf.append(msg)
        tracer.emit({"type": "answer_delta", "text": msg})
    tracer.stats["llm"] += 1
    answer = defabricate(normalize_cites("".join(buf), steps, results, chunk_pool, data_pool), False)
    _finish(tracer, turn_id, conv_id, question, links, p, steps, answer, chunk_pool, data_pool, [], [],
            tracer.started, memory_brief={})
    return True


def _has_content(res: Any) -> bool:
    if not isinstance(res, dict):
        return bool(res)
    if res.get("columns") is not None:
        return True                           # 取数成功(哪怕 0 行,也是一个明确的答案)
    return any(res.get(k) for k in ("chunks", "concept", "items", "groups", "properties", "key"))


def _fast_follow_ups(fast: dict, links: dict) -> list[str]:
    """快速通道不让模型想追问,按查的内容给几个顺手的下一句。"""
    memo = fast.get("memo") or {}
    if memo.get("lane") != "metric":
        return []
    m = ksvc.rt_get(memo.get("metric") or "") or {}
    ref = (ksvc.rt_binding(m, "metric_expr") or {}).get("ref") or {}
    args = memo.get("args") or {}
    out = []
    unused = [d for d in ref.get("dimensions") or {} if d not in (args.get("dimensions") or [])]
    if unused:
        out.append(f"按{unused[0]}拆开看呢")
    if ref.get("time_column") and not links.get("time"):
        out.append("那上个月呢")
    out.append(f"{m.get('name') or '这个数'}为什么是这样?有什么建议")
    return out[:3]


def _pools(records: list[dict]) -> tuple[dict, dict]:
    chunk_pool: dict[str, dict] = {}
    data_pool: dict[int, dict] = {}
    for rec in records:
        res = rec["_result"]
        if not isinstance(res, dict) or rec.get("error"):
            continue
        for c in res.get("chunks") or []:
            if isinstance(c, dict) and c.get("id"):
                chunk_pool[c["id"]] = c
        for e in res.get("evidence") or []:
            if isinstance(e, dict) and e.get("chunk_id"):
                chunk_pool.setdefault(e["chunk_id"], {"id": e["chunk_id"], "heading": e.get("heading", ""),
                                                      "doc_id": e.get("doc_id"), "text": e.get("snippet", "")})
        # 取数记录编号是整数。别的工具也叫 run_id(流程卡运行 sr_xxx、审批单 ar_xxx),
        # 以前一律 int() 转,一碰上就整轮报错,答案都没了。
        rid = res.get("run_id")
        if isinstance(rid, bool) or not (isinstance(rid, int) or (isinstance(rid, str) and rid.isdigit())):
            continue
        if res.get("columns") is not None:
            data_pool[int(rid)] = {
                "run_id": int(rid), "sql": res.get("sql", ""), "columns": res.get("columns") or [],
                "rows": (res.get("rows") or [])[:50], "metric": res.get("metric"), "period": res.get("period"),
                "calibre": res.get("calibre"), "step_id": rec["id"], "route": res.get("route", ""),
                "notes": res.get("notes") or []}
    return chunk_pool, data_pool


def _finish(tracer: Tracer, turn_id: str, conv_id: str, question: str, links: dict, p: dict, steps: list,
            answer: str, chunk_pool: dict, data_pool: dict, cards: list, sops: list, started: float,
            clarify: bool = False, reports: list[dict] | None = None, memory_brief: dict | None = None) -> None:
    from ..memory import service as memory
    cited_chunks = []
    for cid in dict.fromkeys(_CHUNK_CITE.findall(answer)):
        if cid.startswith("run:"):
            continue
        c = chunk_pool.get(cid)
        if c:
            cited_chunks.append({"chunk_id": cid, "heading": c.get("heading", ""),
                                 "doc_id": c.get("doc_id"), "text": (c.get("text") or "")[:800]})
    data_refs = []
    cited_runs = [int(x) for x in dict.fromkeys(_RUN_CITE.findall(answer))]
    for rid in cited_runs + [r for r in data_pool if r not in cited_runs]:
        if rid in data_pool:
            data_refs.append({**data_pool[rid], "cited": rid in cited_runs})
    agents = [{"agent": r["agent"], "label": r["label"], "summary": r["summary"], "ok": r["ok"],
               "confidence": r["confidence"], "ms": r["ms"], "tools": [x["call"] for x in r["records"]]}
              for r in reports or []]
    p = {**p, "agents": agents}
    status = "aborted" if tracer.cancel.is_set() else "done"
    session.save_turn(turn_id, status, links=links, plan=p, steps=steps, answer=answer, citations=cited_chunks,
                      data_refs=data_refs, cards=cards, sops=sops, started=started)
    tracer.emit({"type": "agent_done", "span": "lead", "parent": "", "agent": "lead",
                 "label": AGENT_META["lead"]["label"], "summary": "已作答", "ok": True,
                 "ms": tracer.elapsed_ms()})
    stats = tracer.summary()
    tracer.emit({"type": "answer", "answer": answer, "citations": cited_chunks, "data_refs": data_refs,
                 "actions": cards, "sops": sops, "follow_ups": p.get("follow_ups") or [], "clarify": clarify,
                 "plan": p, "stats": stats, "turn_id": turn_id, "conversation_id": conv_id,
                 "duration_ms": stats["duration_ms"]})
    session.save_trace(turn_id, tracer.snapshot(), stats, memory_brief)
    audit.record("ask", "turn", turn_id, f"提问:{question[:200]}",
                 after={"intent": p.get("intent"), "agents": [a["agent"] for a in agents],
                        "steps": [s["call"] for s in steps], "suggested_actions": [c["action"] for c in cards],
                        "suggested_sops": [s.get("sop") for s in sops],
                        "from_case": p.get("from_case", "")})
    if status == "done" and not clarify:
        memory.learn_async(turn_id)
    tracer.emit({"type": "done", "turn_id": turn_id})


def normalize_cites(answer: str, steps: list[dict], results: dict, chunks: dict, data: dict) -> str:
    """把模型写歪的角标纠正过来,纠正不了的删掉 —— 界面上绝不能出现点不开的引用。

    常见写法:[^run:d2](拿调用编号当数据编号)、[^run:d7:c6](给原文加了 run 前缀)、[^k1]。
    """
    def step_ref(sid: str) -> str:
        res = results.get(sid)
        if isinstance(res, dict):
            if res.get("run_id") and int(res["run_id"]) in data:
                return f"[^run:{int(res['run_id'])}]"
            for c in (res.get("chunks") or []) + (res.get("evidence") or []):
                cid = c.get("id") or c.get("chunk_id")
                if cid in chunks:
                    return f"[^{cid}]"
        return ""

    step_ids = {s["id"] for s in steps}

    def fix(m: re.Match) -> str:
        ref = m.group(1)
        body = ref[4:] if ref.startswith("run:") else ref
        if ref.startswith("run:") and body.isdigit():
            return m.group(0) if int(body) in data else ""
        if body in chunks:
            return f"[^{body}]"
        if body in step_ids:
            return step_ref(body)
        return ""
    return _ANY_CITE.sub(fix, answer)


def run_collect(question: str, conversation_id: str = "") -> dict:
    """非流式运行,评测与 MCP 用。"""
    out: dict[str, Any] = {"steps": []}
    for ev in run(question, conversation_id):
        t = ev["type"]
        if t == "link":
            out["links"] = ev
        elif t == "plan":
            out.setdefault("plan", ev)
        elif t == "tool_done":
            out["steps"].append(ev)
        elif t == "answer":
            out.update(ev)
        elif t == "error":
            out["error"] = ev.get("error")
    return out


def run_agent(agent: str, task: str) -> dict:
    """A2A:外部 Agent 直接把任务交给某个子 Agent(经 MCP 工具 ask_knowledge_agent / ask_data_agent)。"""
    tracer = Tracer()
    links = linker.link(task)
    r = SUB_AGENTS[agent].run(tracer, task, question=task, links_text=links_text(links),
                              ontology=ontology_text())
    tracer.close()
    return {"agent": agent, "summary": r["summary"], "findings": r["findings"], "insights": r["insights"],
            "confidence": r["confidence"],
            "evidence": [{"tool": rec["call"], "summary": rec.get("summary") or rec.get("error")}
                         for rec in r["records"]],
            "data": [{"run_id": rec["_result"]["run_id"], "sql": rec["_result"].get("sql"),
                      "columns": rec["_result"].get("columns"), "rows": (rec["_result"].get("rows") or [])[:100]}
                     for rec in r["records"] if isinstance(rec["_result"], dict) and rec["_result"].get("run_id")]}