defs.py 11.9 KB
"""用户可配置的能力:技能(skill)、动作(action)、外部端点(endpoint)。

动作 spec:
{
  "target_type": "对象类型名或 id(可选)",
  "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", "approver_roles": ["角色名"]},
  "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": "技能", "action": "动作", "endpoint": "外部端点"}
PARAM_TYPES = ("string", "text", "number", "integer", "boolean", "enum", "object", "date")
_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 _validate_action(spec: dict) -> tuple[dict, str]:
    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"
        params.append({"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": p.get("description") or ""})
    target = str(spec.get("target_type") or "")
    env_names = names | ({"obj", "obj_key"} 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}"})
    effects = []
    risk = "low"
    order = {"low": 0, "medium": 1, "high": 2}
    for e in spec.get("effects") or []:
        tool = registry.TOOLS.get(e.get("tool") or "")
        if tool is None:
            raise HTTPException(422, f"动作只能调用已注册的工具,没有「{e.get('tool')}」。"
                                     f"可用:{'、'.join(registry.TOOLS)}")
        args = e.get("args") or {}
        for ref in _refs(args):
            head = ref.split(".")[0]
            if head not in env_names:
                raise HTTPException(422, f"工具 {tool.name} 的参数引用了未定义的变量 ${ref}")
        effects.append({"tool": tool.name, "args": args, "label": e.get("label") or tool.title})
        if order[tool.risk_level] > order[risk]:
            risk = tool.risk_level
    if not effects:
        raise HTTPException(422, "动作至少要有一个效果(调用一个工具)")
    appr = spec.get("approval") or {}
    approval = {"mode": "manual",       # 当前阶段:所有动作一律人工审批
                "approver_roles": [str(x) for x in appr.get("approver_roles") or [] if x]}
    reversible = bool(spec.get("reversible", True)) and all(
        registry.TOOLS[e["tool"]].revert is not None for e in effects)
    return ({"target_type": target, "params": params, "criteria": criteria, "effects": effects,
             "approval": approval, "reversible": reversible}, 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)")
    return {"instructions": str(spec["instructions"]), "functions": funcs,
            "inputs": [{"name": str(i.get("name")), "description": str(i.get("description") or "")}
                       for i in spec.get("inputs") or [] if i.get("name")],
            "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.]*)")


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}")


# ---------------- CRUD ----------------
def list_defs(kind: str = "", status: str = "") -> list[dict]:
    with session() as s:
        stmt = select(CapabilityDef).where(CapabilityDef.workspace == _ws())
        if kind:
            stmt = stmt.where(CapabilityDef.kind == kind)
        if status:
            stmt = stmt.where(CapabilityDef.status == status)
        return [_dict(c) for c in s.scalars(stmt.order_by(CapabilityDef.kind,
                                                           CapabilityDef.name)).all()]


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:
    with session() as s:
        stmt = select(CapabilityDef).where(CapabilityDef.workspace == _ws(),
                                           or_(CapabilityDef.id == ref, CapabilityDef.name == ref,
                                               CapabilityDef.display_name == ref))
        if kind:
            stmt = stmt.where(CapabilityDef.kind == kind)
        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 not in KINDS:
        raise HTTPException(422, f"未知的能力类别:{kind}")
    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]:
    out = []
    with session() as s:
        for c in s.scalars(select(CapabilityDef).where(CapabilityDef.workspace == _ws())).all():
            text = c.spec_json or ""
            if concept_id in text or any(f'"{n}"' in text or f"@{n}" in text for n in names if n):
                out.append({"type": "capability", "id": c.id, "name": c.display_name or c.name,
                            "kind": c.kind})
    return out