defs.py 29.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
"""动作 / AI 函数的校验,以及「外部端点」的存储。

四元组化之后,动作(kind=action)和 AI 分析函数(kind=function, category=ai)都是本体里的元素,
跟对象、关系一起草稿、发布、回滚;这里只保留:
- 它们的 spec 校验(schema.normalize_spec 调过来);
- 按旧接口读取它们的门面(find / list_defs),运行时代码(动作生命周期、SOP、编排)不用关心存在哪;
- 外部端点(URL + 加密密钥)仍存在 otlg_capability 表里 —— 它属于「数据集成 → 外部系统连接」。

动作 spec:
{
  "target_type": "对象类型名或 id(可选;可以是接口)",
  "transition": {"property": "状态属性", "from": ["从哪些状态"], "to": "到哪个状态"}(可选:这个动作完成的状态流转),
  "params": [{"name","label","type":"string|number|boolean|object|text|enum","required","enum"}],
  "criteria": [{"expression": "规则表达式,变量为参数与 obj", "message": "不满足时的提示"}],
  "effects":  [{"tool": "object.write", "args": {"object_type": "...", "key": "$obj_key", ...}}],
  "approval": {"mode": "manual|auto|conditional", "approver_roles": ["角色名"],
               "decision": {"function": "审批决策表", "inputs": {...}},
               "auto_when": "条件自动时的条件表达式,如 priority == 'P3' and eff.amount < 5000"},
  "reversible": true
}
参数引用写法:`$参数名`、`$obj.属性`;字符串里也可以内嵌("跟进 $obj.name")。
"""
from __future__ import annotations

import re
from typing import Any

from fastapi import HTTPException
from sqlalchemy import or_, select

from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, session
from ..governance import audit
from ..kernel import rules
from . import registry
from .models import CapabilityDef

KINDS = {"skill": "AI 分析函数", "action": "动作", "endpoint": "外部端点"}
# 审批策略:manual 一律人工审批;auto 提议即执行(仍留审计、可撤销);
# conditional 满足条件(auto_when 为真,或审批决策表输出 auto=是)自动执行,否则走人工审批。
APPROVAL_MODES = {"manual": "人工审批", "auto": "自动执行", "conditional": "条件自动"}
PARAM_TYPES = ("string", "text", "number", "integer", "boolean", "enum", "object", "date", "list")
COLUMN_TYPES = ("string", "number", "integer", "boolean", "date", "object")
_NAME = re.compile(r"^[\w一-鿿.\-]{2,64}$")
_SECRET_KEY = "__secret__"


def _dict(c: CapabilityDef) -> dict:
    spec = jload(c.spec_json, {})
    spec.pop(_SECRET_KEY, None)
    return {"id": c.id, "kind": c.kind, "kind_label": KINDS.get(c.kind, c.kind), "name": c.name,
            "display_name": c.display_name or "", "description": c.description or "",
            "spec": spec, "status": c.status, "version": c.version, "risk_level": c.risk_level,
            "created_by": c.created_by, "created_at": iso(c.created_at),
            "updated_at": iso(c.updated_at)}


def _ws() -> str:
    return identity.current().workspace


# ---------------- 校验 ----------------
def _exprs(v) -> list[str]:
    """效果参数里以 = 开头的表达式。"""
    if isinstance(v, str):
        return [v[1:]] if v.startswith("=") else []
    if isinstance(v, dict):
        return [x for item in v.values() for x in _exprs(item)]
    if isinstance(v, list):
        return [x for item in v for x in _exprs(item)]
    return []


def _check_ops(ops: list, what: str) -> None:
    from ..kernel.objects import WRITE_OPS
    if not isinstance(ops, list) or not ops:
        raise HTTPException(422, f"「{what}」还没有要写入的内容")
    names = set()
    for i, op in enumerate(ops, 1):
        if not isinstance(op, dict) or op.get("op") not in WRITE_OPS:
            raise HTTPException(422, f"「{what}」第 {i} 条写入的类型不对,只能是 {'/'.join(WRITE_OPS.values())}")
        kind = op["op"]
        if kind in ("link", "unlink"):
            if not str(op.get("link") or "").strip():
                raise HTTPException(422, f"「{what}」第 {i} 条是{WRITE_OPS[kind]},要选是哪条关系")
            if op.get("from_key") in (None, "") or op.get("to_key") in (None, ""):
                raise HTTPException(422, f"「{what}」第 {i} 条是{WRITE_OPS[kind]},两头的对象都要指定")
            continue
        if not str(op.get("object_type") or "").strip():
            raise HTTPException(422, f"「{what}」第 {i} 条写入还没选写哪类对象")
        if kind in ("update", "delete", "transition") and op.get("key") in (None, ""):
            raise HTTPException(422, f"「{what}」第 {i} 条是{WRITE_OPS[kind]},要指定是哪一个(主键)")
        if kind == "transition" and (not str(op.get("property") or "").strip() or op.get("to") in (None, "")):
            raise HTTPException(422, f"「{what}」第 {i} 条是状态流转,要写哪个状态属性、流转到哪个状态")
        if kind == "create_rows" and not op.get("rows"):
            raise HTTPException(422, f"「{what}」第 {i} 条是按行新建,要选按哪份多行数据")
        if kind in ("update", "create_rows") and not op.get("values"):
            raise HTTPException(422, f"「{what}」第 {i} 条写入还没填字段")
        n = str(op.get("as") or "").strip()
        if n:
            if n in names:
                raise HTTPException(422, f"「{what}」里写入的名字「{n}」重复了")
            names.add(n)


def validate_action(spec: dict, extra_names: set[str] | frozenset = frozenset()) -> tuple[dict, str]:
    """extra_names:发起方额外带进来的变量(流程卡里内联的写数据步骤:前面各步的结果)。"""
    params = []
    names = set()
    for p in spec.get("params") or []:
        n = str(p.get("name") or "").strip()
        if not n or not re.match(r"^[A-Za-z_]\w*$", n):
            raise HTTPException(422, f"动作参数名只能用字母数字下划线:{n!r}")
        if n in names:
            raise HTTPException(422, f"动作参数重名:{n}")
        names.add(n)
        t = p.get("type") or "string"
        item = {"name": n, "label": p.get("label") or n,
                "type": t if t in PARAM_TYPES else "string",
                "required": bool(p.get("required")),
                "enum": [str(x) for x in p.get("enum") or []],
                "description": str(p.get("description") or "").strip(),
                "unit": str(p.get("unit") or "").strip()[:16],
                "object_type": str(p.get("object_type") or "").strip() if t == "object" else ""}
        if t == "list":
            # 明细行:每一行有哪些列(如 配件、数量、单价),新建主单 + 明细时按行写入
            cols = []
            for c in p.get("columns") or []:
                cn = str(c.get("name") or "").strip()
                if not cn:
                    continue
                if not re.match(r"^[A-Za-z_\w]\w*$", cn):
                    raise HTTPException(422, f"明细列名不合法:{cn!r}")
                ct = str(c.get("type") or "string")
                cols.append({"name": cn, "label": str(c.get("label") or cn), "type": ct if ct in COLUMN_TYPES else "string",
                             "required": bool(c.get("required")),
                             "object_type": str(c.get("object_type") or "") if ct == "object" else ""})
            if not cols:
                raise HTTPException(422, f"明细参数「{item['label']}」至少要有一列")
            item["columns"] = cols
        if p.get("default") not in (None, ""):
            item["default"] = p["default"]
        params.append(item)
    target = str(spec.get("target_type") or "")
    # 参数是对象时,可以用「参数名_obj.属性」取到那个对象的属性
    obj_params = {f"{p['name']}_obj" for p in params if p["type"] == "object" and p["object_type"]}
    # 还要用到的其他对象:按条件查出来一个,给校验和执行内容用(如「这个客户本月的额度」)
    lookups = []
    for lk in spec.get("lookups") or []:
        n = str(lk.get("name") or "").strip()
        if not n and not lk.get("object_type"):
            continue
        if not re.match(r"^[A-Za-z_]\w*$", n):
            raise HTTPException(422, f"相关对象的标识只能用字母数字下划线:{n!r}")
        if n in names or n in obj_params or n in ("obj", "rel", "eff", "today", "now_id", "priority"):
            raise HTTPException(422, f"相关对象的标识和别的变量重名:{n}")
        if not str(lk.get("object_type") or "").strip():
            raise HTTPException(422, f"相关对象「{lk.get('label') or n}」要选是哪类对象")
        where = [{"property": str(w.get("property") or ""), "op": str(w.get("op") or "eq"), "value": w.get("value")}
                 for w in lk.get("where") or [] if w.get("property")]
        if not where:
            raise HTTPException(422, f"相关对象「{lk.get('label') or n}」要写怎么找到它(至少一个条件)")
        item = {"name": n, "label": str(lk.get("label") or n), "object_type": str(lk["object_type"]).strip(),
                "where": where}
        if lk.get("mode") == "list":              # 取多个(如 这张单的全部明细行),校验里可以用 count / sum_by
            item.update(mode="list", limit=max(1, min(int(lk.get("limit") or 50), 500)))
        lookups.append(item)
    lookup_names = {lk["name"] for lk in lookups}
    env_names = (names | obj_params | lookup_names | {"today", "now_id", "this_month"} | set(extra_names)
                 | ({"obj", "obj_key", "rel"} if target else set()))
    criteria = []
    for c in spec.get("criteria") or []:
        expr = str(c.get("expression") or "").strip()
        if not expr:
            continue
        try:
            free = rules.free_names(expr)
        except rules.RuleError as e:
            raise HTTPException(422, f"前置条件表达式错误:{e}") from e
        unknown = [x for x in free if x not in env_names]
        if unknown:
            raise HTTPException(422, f"前置条件引用了未定义的变量:{'、'.join(unknown)}")
        criteria.append({"expression": expr, "message": c.get("message") or f"不满足:{expr}",
                         "label": str(c.get("label") or "").strip()})
    effects = []
    risk = "low"
    order = {"low": 0, "medium": 1, "high": 2}
    def one_effect(e: dict, extra: frozenset = frozenset()) -> dict:
        nonlocal risk
        tool = registry.TOOLS.get(e.get("tool") or "")
        if tool is None:
            raise HTTPException(422, f"没有「{e.get('tool')}」这种执行内容。"
                                     f"可用:{'、'.join(t.title for t in registry.TOOLS.values())}")
        what = e.get("label") or tool.title
        args = e.get("args") or {}
        # ops:同一事务里前面写入新建出来的;row:按行新建时的「这一行」
        known = env_names | extra | {"ops", "row"}
        if tool.name == "object.batch":
            _check_ops(args.get("ops") or [], what)
        for ref in _refs(args):
            head = re.split(r"[.\[]", ref)[0]
            if head not in known:
                raise HTTPException(422, f"「{what}」引用了没有定义的变量 ${ref}")
        for expr in _exprs(args):
            try:
                unknown = [x for x in rules.free_names(expr) if x not in known]
            except rules.RuleError as ex:
                raise HTTPException(422, f"「{what}」的公式「={expr}」有误:{ex}") from ex
            if unknown:
                # 常见写法错误:文字前缀没加引号(=PO$now_id),说清楚该怎么写,AI 照着改一次就对
                glued = [(x, k) for x in unknown for k in known if k and x != k and x.endswith(k) and len(x) > len(k)]
                hint = ";".join(f"「{x}」像是文字「{x[:-len(k)]}」接上变量 {k},公式里要写成 '{x[:-len(k)]}' + {k}"
                                for x, k in glued[:2])
                raise HTTPException(422, f"「{what}」的公式引用了没有定义的变量:{'、'.join(unknown)}" + (f"({hint})" if hint else ""))
        if order[tool.risk_level] > order[risk]:
            risk = tool.risk_level
        out = {"tool": tool.name, "args": args, "label": what}
        if str(e.get("as") or "").strip():
            out["as"] = str(e["as"]).strip()
        when = str(e.get("when") or "").strip()
        if when:                                   # 只在满足条件时才做这一项
            try:
                unknown = [x for x in rules.free_names(when) if x not in known]
            except rules.RuleError as ex:
                raise HTTPException(422, f"「{what}」的执行条件有误:{ex}") from ex
            if unknown:
                raise HTTPException(422, f"「{what}」的执行条件引用了没有定义的变量:{'、'.join(unknown)}")
            out["when"] = when
        return out

    for e in spec.get("effects") or []:
        effects.append(one_effect(e))
    # 状态流转:这个动作把目标对象的状态从 from 变成 to(执行时系统自动写,提交时核对当前状态)
    transition = None
    tr = spec.get("transition") or {}
    if isinstance(tr, dict) and str(tr.get("property") or "").strip():
        if not target:
            raise HTTPException(422, "状态流转要作用在一个对象上:先选这个动作作用的对象")
        to = str(tr.get("to") or "").strip()
        if not to:
            raise HTTPException(422, "状态流转要写流转到哪个状态")
        frm = tr.get("from") or []
        frm = [x.strip() for x in (re.split(r"[,,、]", frm) if isinstance(frm, str) else frm) if str(x).strip()]
        transition = {"property": str(tr["property"]).strip(), "from": [str(x) for x in frm], "to": to}
    if not effects and not transition:
        raise HTTPException(422, "动作至少要有一项执行内容(或一个状态流转)")
    # 被驳回时要做的事(如把驳回原因写回单据)。可以用 $reject_reason
    on_reject = [one_effect(e, frozenset({"reject_reason"})) for e in spec.get("on_reject") or []]
    appr = spec.get("approval") or {}
    mode = str(appr.get("mode") or "manual")
    approval = {"mode": mode if mode in APPROVAL_MODES else "manual",
                "approver_roles": [str(x) for x in appr.get("approver_roles") or [] if x]}
    # 审批决策函数:用本体里的决策表按「这一单的实际情况」算优先级和审批人。
    # 没有它的话优先级只能取动作的静态 risk_level —— 手册里「金额≥5万归采购经理、
    # 涉及延期供应商 P0」这类规则就永远落不了地。
    dec = appr.get("decision") or {}
    if isinstance(dec, dict) and str(dec.get("function") or "").strip():
        inputs = {}
        for k, v in (dec.get("inputs") or {}).items():
            k = str(k).strip()
            if not k:
                continue
            inputs[k] = v
            if isinstance(v, str) and v.startswith("="):
                try:
                    unknown = [x for x in rules.free_names(v[1:]) if x not in env_names | {"eff", "rel"}]
                except rules.RuleError as ex:
                    raise HTTPException(422, f"审批决策输入「{k}」的表达式有误:{ex}") from ex
                if unknown:
                    raise HTTPException(422, f"审批决策输入「{k}」引用了未定义的变量:{'、'.join(unknown)}")
        approval["decision"] = {"function": str(dec["function"]).strip(), "inputs": inputs}
    auto_when = str(appr.get("auto_when") or "").strip()
    if auto_when:
        try:
            unknown = [x for x in rules.free_names(auto_when)
                       if x not in env_names | {"eff", "rel", "priority"}]
        except rules.RuleError as ex:
            raise HTTPException(422, f"自动执行条件有误:{ex}") from ex
        if unknown:
            raise HTTPException(422, f"自动执行条件引用了未定义的变量:{'、'.join(unknown)}"
                                     f"(可用:参数、obj、eff(效果里算出的值)、rel(关联对象)、priority)")
        approval["auto_when"] = auto_when
    if approval["mode"] == "conditional" and not auto_when and "decision" not in approval:
        raise HTTPException(422, "「条件自动」要写自动执行条件,或配一张输出 auto 列的审批决策表")
    # 分段审批:一段批完才轮到下一段(如 部门内 → 总部)。每一段可以写「什么情况下这一段不用批」
    stages = []
    for st in appr.get("stages") or []:
        name = str(st.get("name") or "").strip()
        roles = [str(x) for x in st.get("approver_roles") or [] if x]
        if not name and not roles:
            continue
        skip = str(st.get("skip_when") or "").strip()
        if skip:
            try:
                unknown = [x for x in rules.free_names(skip) if x not in env_names | {"eff", "priority"}]
            except rules.RuleError as ex:
                raise HTTPException(422, f"审批环节「{name}」的免批条件有误:{ex}") from ex
            if unknown:
                raise HTTPException(422, f"审批环节「{name}」的免批条件引用了没有定义的变量:{'、'.join(unknown)}")
        stages.append({"name": name or f"第 {len(stages) + 1} 段", "approver_roles": roles, "skip_when": skip})
    if stages:
        approval["stages"] = stages
        approval["approver_roles"] = stages[0]["approver_roles"]
    reversible = bool(spec.get("reversible", True)) and all(
        registry.TOOLS[e["tool"]].revert is not None for e in effects)
    out = {"target_type": target, "params": params, "criteria": criteria, "effects": effects,
           "approval": approval, "reversible": reversible}
    if transition:
        out["transition"] = transition
    if lookups:
        out["lookups"] = lookups
    if on_reject:
        out["on_reject"] = on_reject
    return out, risk


def validate_skill(spec: dict) -> dict:
    funcs = [str(f) for f in spec.get("functions") or []]
    bad = [f for f in funcs if f not in registry.FUNCTIONS]
    if bad:
        raise HTTPException(422, f"技能只能使用只读函数,以下不存在或不是函数:{'、'.join(bad)}")
    if not str(spec.get("instructions") or "").strip():
        raise HTTPException(422, "技能需要写明指令(instructions)")
    from ..kernel import signature
    fields = []
    for f in spec.get("output_fields") or []:
        n = str((f or {}).get("name") or "").strip()
        if not n:
            continue
        if not re.match(r"^[A-Za-z_\w]\w*$", n):
            raise HTTPException(422, f"输出字段名不合法:{n!r}")
        t = str(f.get("type") or "string")
        item = {"name": n, "label": str(f.get("label") or n),
                "type": t if t in ("string", "number", "boolean", "date", "list") else "string"}
        if f.get("options"):
            item["options"] = [str(x) for x in f["options"] if str(x).strip()]
        fields.append(item)
    return {"instructions": str(spec["instructions"]), "functions": funcs,
            "inputs": signature.norm_inputs(spec.get("inputs"), "string"),
            "output_fields": fields,
            "output_schema": spec.get("output_schema") or {"conclusion": "结论", "details": []},
            "examples": spec.get("examples") or [],
            "max_steps": max(1, min(int(spec.get("max_steps") or 4), 8))}


def _validate_endpoint(spec: dict) -> dict:
    url = str(spec.get("url") or "")
    if not re.match(r"^https?://", url):
        raise HTTPException(422, "端点地址必须是 http(s) URL")
    method = str(spec.get("method") or "POST").upper()
    if method not in ("POST", "PUT", "PATCH"):
        raise HTTPException(422, "端点方法只能是 POST/PUT/PATCH")
    return {"url": url, "method": method, "timeout": min(float(spec.get("timeout") or 15), 60)}


_REF = re.compile(r"\$([A-Za-z_一-鿿][\w一-鿿]*(?:\[\d+\]|\.[\w一-鿿]+)*)")


def _refs(v: Any) -> list[str]:
    if isinstance(v, str):
        return _REF.findall(v)
    if isinstance(v, dict):
        return [r for x in v.values() for r in _refs(x)]
    if isinstance(v, list):
        return [r for x in v for r in _refs(x)]
    return []


def normalize(kind: str, spec: dict) -> tuple[dict, str]:
    if kind == "action":
        return validate_action(spec)
    if kind == "skill":
        return validate_skill(spec), "low"
    if kind == "endpoint":
        return _validate_endpoint(spec), "high"
    raise HTTPException(422, f"未知的能力类别:{kind}")


# ---------------- 读取(动作 / AI 函数来自本体,端点来自本表) ----------------
def _from_concept(c: dict, published: bool) -> dict:
    kind = "action" if c["kind"] == "action" else "skill"
    spec = dict(c.get("spec") or {})
    spec.pop("ui", None)
    return {"id": c["id"], "kind": kind, "kind_label": KINDS[kind], "name": c["name"],
            "display_name": c.get("display_name") or "", "description": c.get("description") or "",
            "spec": spec, "status": "published" if published else "draft",
            "version": c.get("version") or 1,
            "risk_level": spec.get("risk_level") or ("low" if kind == "skill" else "medium"),
            "object_type": spec.get("object_type") or spec.get("target_type") or "",
            "created_by": c.get("created_by") or "", "created_at": c.get("created_at") or "",
            "updated_at": c.get("updated_at") or ""}


def _concept_matches(c: dict, kind: str) -> bool:
    if kind == "action":
        return c["kind"] == "action"
    if kind == "skill":
        return c["kind"] == "function" and (c.get("spec") or {}).get("category") == "ai"
    return False


def list_defs(kind: str = "", status: str = "", working: bool = False) -> list[dict]:
    """working=True 给配置界面用:发布过但又改了的动作 / AI 函数,返回正在编辑的工作副本
    (带 pending_changes 标记),而不是线上那一版 —— 刚给动作加了参数,流程卡里马上就要能填。"""
    from ..kernel import service as ksvc
    out: list[dict] = []
    if kind in ("", "action", "skill"):
        rt = ksvc.runtime()
        kinds = [kind] if kind else ["skill", "action"]
        seen = set()
        dirty = {b["id"] for b in ksvc.list_concepts(status="dirty")} if working else set()
        for c in rt.values():
            for k in kinds:
                if _concept_matches(c, k):
                    if c["id"] in dirty:
                        out.append({**_from_concept(ksvc.get_concept(c["id"]), True), "pending_changes": True})
                    else:
                        out.append(_from_concept(c, True))
                    seen.add(c["id"])
        if status != "published":
            for brief in ksvc.list_concepts(kind="action" if kind == "action" else
                                            "function" if kind == "skill" else ""):
                if brief["id"] in seen or brief["kind"] not in ("action", "function"):
                    continue
                c = ksvc.get_concept(brief["id"])
                for k in kinds:
                    if _concept_matches(c, k):
                        out.append(_from_concept(c, False))
        if status == "draft":
            out = [d for d in out if d["status"] == "draft"]
    if kind in ("", "endpoint"):
        with session() as s:
            stmt = select(CapabilityDef).where(CapabilityDef.workspace == _ws(),
                                               CapabilityDef.kind == "endpoint")
            if status:
                stmt = stmt.where(CapabilityDef.status == status)
            out += [_dict(c) for c in s.scalars(stmt.order_by(CapabilityDef.name)).all()]
    return sorted(out, key=lambda d: (d["kind"], d["name"]))


def get(cap_id: str) -> dict:
    with session() as s:
        c = s.get(CapabilityDef, cap_id)
        if c is None or c.workspace != _ws():
            raise HTTPException(404, "外部端点不存在")
        return _dict(c)


def find(ref: str, kind: str | None = None) -> dict | None:
    """按 id / 名称 / 显示名找。动作与 AI 函数优先取已发布版本,没发布的以 status=draft 返回(试运行可用)。"""
    from ..kernel import service as ksvc
    if not ref:
        return None
    if kind in (None, "action", "skill"):
        for k in ([kind] if kind else ["action", "skill"]):
            ck = "action" if k == "action" else "function"
            c = ksvc.rt_find(ref, ck)
            if c and _concept_matches(c, k):
                return _from_concept(c, True)
            w = ksvc.find(ref, ck)
            if w and _concept_matches(w, k) and w["status"] != "deprecated":
                return _from_concept(w, False)
        if kind:
            return None
    with session() as s:
        stmt = select(CapabilityDef).where(CapabilityDef.workspace == _ws(),
                                           CapabilityDef.kind == "endpoint",
                                           or_(CapabilityDef.id == ref, CapabilityDef.name == ref,
                                               CapabilityDef.display_name == ref))
        c = s.scalars(stmt).first()
        return _dict(c) if c else None


def upsert(kind: str, name: str, *, display_name: str = "", description: str = "",
           spec: dict | None = None, cap_id: str = "", secret: dict | None = None) -> dict:
    if kind != "endpoint":
        raise HTTPException(422, "动作与 AI 函数在本体里编辑(/api/kernel/concepts),这里只管理外部端点")
    name = (name or "").strip()
    if not _NAME.match(name):
        raise HTTPException(422, "能力名称需 2~64 个字符(字母、数字、中文、点、横线、下划线)")
    norm, risk = normalize(kind, spec or {})
    actor = identity.current()
    with session() as s:
        dup = s.scalars(select(CapabilityDef).where(
            CapabilityDef.workspace == actor.workspace, CapabilityDef.kind == kind,
            CapabilityDef.name == name)).first()
        c = s.get(CapabilityDef, cap_id) if cap_id else None
        if dup and (c is None or dup.id != c.id):
            raise HTTPException(409, f"已存在同名{KINDS[kind]}「{name}」")
        before = _dict(c) if c else None
        if c is None:
            c = CapabilityDef(id=new_id(kind[:3]), workspace=actor.workspace, kind=kind,
                              created_by=actor.id, status="draft")
            s.add(c)
        else:
            c.version += 1
            if c.status == "published":
                c.status = "draft"      # 改过就要重新发布,运行时才会用新定义
        old_secret = jload(c.spec_json, {}).get(_SECRET_KEY) if c.spec_json else None
        if kind == "endpoint":
            if secret is not None:
                from ..text2sql import crypto
                norm[_SECRET_KEY] = crypto.encrypt(jdump(secret)) if secret else ""
            elif old_secret:
                norm[_SECRET_KEY] = old_secret
        c.name, c.display_name, c.description = name, display_name or "", description or ""
        c.spec_json = jdump(norm)
        c.risk_level = risk
        s.commit()
        out = _dict(c)
    audit.record(f"capability.{'update' if before else 'create'}", "capability", out["id"],
                 f"{'修改' if before else '新建'}{KINDS[kind]}「{name}」", before=before, after=out)
    return out


def set_status(cap_id: str, status: str) -> dict:
    if status not in ("draft", "published", "disabled"):
        raise HTTPException(422, "状态只能是 draft/published/disabled")
    before = get(cap_id)
    if status == "published":
        normalize(before["kind"], before["spec"])        # 发布前再校验一次(引用的工具/函数可能已变)
    with session() as s:
        c = s.get(CapabilityDef, cap_id)
        c.status = status
        s.commit()
        out = _dict(c)
    audit.record(f"capability.{status}", "capability", cap_id,
                 f"{KINDS[out['kind']]}「{out['name']}」→ {status}", before=before, after=out)
    return out


def delete(cap_id: str) -> None:
    before = get(cap_id)
    from .models import ActionRun
    with session() as s:
        used = s.scalars(select(ActionRun.id).where(ActionRun.action_id == cap_id)).first()
        if used:
            raise HTTPException(409, "该动作已有运行记录,不能删除,只能停用(保证审计可追溯)")
        s.delete(s.get(CapabilityDef, cap_id))
        s.commit()
    audit.record("capability.delete", "capability", cap_id, f"删除「{before['name']}」",
                 before=before)


def endpoint_secret(cap_id: str) -> str:
    from ..text2sql import crypto
    with session() as s:
        c = s.get(CapabilityDef, cap_id)
        token = jload(c.spec_json, {}).get(_SECRET_KEY) if c else ""
    return crypto.decrypt(token) if token else ""


def usage_provider(concept_id: str, names: list[str]) -> list[dict]:
    """动作、AI 函数引用本体概念时按名称写在 spec 里(如 object.write 的 object_type),这里补上名称引用。"""
    from ..kernel import service as ksvc
    out = []
    for brief in ksvc.list_concepts():
        if brief["id"] == concept_id or brief["kind"] not in ("action", "function"):
            continue
        c = ksvc.get_concept(brief["id"])
        text = jdump(c.get("spec") or {})
        if concept_id in text:
            continue                    # 按 id 引用的由内核自己的引用分析覆盖
        if any(f'"{n}"' in text or f"@{n}" in text for n in names if n):
            out.append({"type": "concept", "id": c["id"], "name": c["display_name"] or c["name"],
                        "kind": c["kind"]})
    return out