api.py
11.6 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
"""能力层接口 /api/cap:能力目录、技能/动作/端点定义、动作审批、人工任务、收件箱汇总。"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from ..core import identity
from ..core.identity import require
from ..governance import notify, review
from . import actions, defs, registry, skills, tasks
router = APIRouter(prefix="/api/cap", tags=["capability"])
class DefIn(BaseModel):
kind: str
name: str
display_name: str = ""
description: str = ""
spec: dict = Field(default_factory=dict)
secret: dict | None = None # 仅外部端点:请求头里的凭据,加密存储、永不回显
class StatusIn(BaseModel):
status: str
class CallIn(BaseModel):
args: dict = Field(default_factory=dict)
class ProposeIn(BaseModel):
params: dict = Field(default_factory=dict)
object_key: str = ""
reason: str = ""
initiator_kind: str = "user" # user / ai(用户提交 AI 建议的动作卡时)
source_ref: str = ""
priority: str = "" # P0~P3,不填按动作风险定
evidence: list = Field(default_factory=list)
now_id: str = "" # 预览时生成的编号:带回来,提交后的单号就和预览看到的一样
class DecideIn(BaseModel):
approve: bool
comment: str = ""
class CompleteIn(BaseModel):
result: dict = Field(default_factory=dict)
comment: str = ""
# ---------- 目录 ----------
@router.get("/catalog")
async def catalog(_: identity.Actor = Depends(require("view"))):
return {"functions": [f.brief() for f in registry.FUNCTIONS.values()],
"tools": [t.brief() for t in registry.TOOLS.values()],
"defs": defs.list_defs(working=True)}
@router.get("/ref-options")
async def ref_options(ref: str, of: str = "", _: identity.Actor = Depends(require("view"))):
"""参数下拉的选项(含草稿,带 status)。ref 见 refs 模块说明,of 为依赖参数当前的值。"""
from . import refs
return refs.options(ref, of)
@router.post("/ref-scan")
async def ref_scan(body: dict, _: identity.Actor = Depends(require("view"))):
"""一组参数引用了哪些还没发布 / 不存在的元素:{function|tool: 名, args}。"""
from . import refs
name = str(body.get("function") or body.get("tool") or "")
d = registry.FUNCTIONS.get(name) or registry.TOOLS.get(name)
if d is None:
raise HTTPException(404, f"没有名为「{name}」的函数或效果")
return refs.scan_refs(d.input_schema, body.get("args") or {})
@router.post("/functions/{name}/call")
async def call_function(name: str, body: CallIn, _: identity.Actor = Depends(require("ask"))):
return registry.call_function(name, body.args)
# ---------- 定义 ----------
@router.get("/defs")
async def list_defs(kind: str = "", status: str = "", working: bool = False,
_: identity.Actor = Depends(require("view"))):
return defs.list_defs(kind, status, working)
@router.post("/defs")
async def create_def(body: DefIn, _: identity.Actor = Depends(require("build"))):
return defs.upsert(body.kind, body.name, display_name=body.display_name,
description=body.description, spec=body.spec, secret=body.secret)
@router.get("/defs/{cap_id}")
async def get_def(cap_id: str, _: identity.Actor = Depends(require("view"))):
return defs.get(cap_id)
@router.put("/defs/{cap_id}")
async def update_def(cap_id: str, body: DefIn, _: identity.Actor = Depends(require("build"))):
cur = defs.get(cap_id)
return defs.upsert(cur["kind"], body.name, display_name=body.display_name,
description=body.description, spec=body.spec, cap_id=cap_id,
secret=body.secret)
@router.post("/defs/{cap_id}/status")
async def set_status(cap_id: str, body: StatusIn, _: identity.Actor = Depends(require("build"))):
return defs.set_status(cap_id, body.status)
@router.delete("/defs/{cap_id}")
async def delete_def(cap_id: str, _: identity.Actor = Depends(require("build"))):
defs.delete(cap_id)
return {"ok": True}
# ---------- MCP 服务(工具目录 / 在线调用 / 调用日志) ----------
@router.get("/mcp/tools")
async def mcp_tools(_: identity.Actor = Depends(require("view"))):
from ..core import db as core_db
from . import mcp
return {"enabled": bool(core_db.get_config("MCP_TOKEN", "")), "endpoint": "/mcp",
"protocol": mcp.PROTOCOL, "tools": mcp.tools()}
@router.post("/mcp/call/{name}")
async def mcp_call(name: str, body: CallIn, actor: identity.Actor = Depends(require("ask"))):
import asyncio
from . import mcp
ok, out = await asyncio.to_thread(mcp.call_logged, actor, name, body.args, "console")
return {"ok": ok, "result": out if ok else None, "error": None if ok else out}
@router.get("/mcp/logs")
async def mcp_logs(limit: int = 50, actor: identity.Actor = Depends(require("view"))):
from ..governance import audit
return audit.query(workspace=actor.workspace, event="mcp.call", limit=limit)["items"]
# ---------- AI 分析函数 ----------
@router.post("/skills/{ref}/run")
async def run_skill(ref: str, body: CallIn, actor: identity.Actor = Depends(require("ask"))):
# 建设者可以试跑草稿技能
return skills.run(ref, body.args, require_published=not actor.can("build"))
# ---------- 动作 ----------
@router.post("/actions/{ref}/prepare")
async def prepare_action(ref: str, body: ProposeIn, _: identity.Actor = Depends(require("ask"))):
# 预览可以引用草稿(动作本身、它用到的决策表),正式提议仍只认已发布的
from ..kernel import service as ksvc
with ksvc.draft_runtime():
return actions.prepare(ref, body.params, body.object_key, strict=False)
@router.post("/actions/{ref}/propose")
async def propose_action(ref: str, body: ProposeIn,
actor: identity.Actor = Depends(require("operate"))):
if body.initiator_kind not in ("user", "ai"):
raise HTTPException(422, "initiator_kind 只能是 user 或 ai")
if body.initiator_kind == "ai":
tok = identity.set_current(identity.as_ai(actor))
try:
return actions.propose(ref, body.params, object_key=body.object_key,
reason=body.reason, initiator_kind="ai",
source_ref=body.source_ref, priority=body.priority,
evidence=body.evidence, now_id=body.now_id)
finally:
identity.reset(tok)
return actions.propose(ref, body.params, object_key=body.object_key, reason=body.reason,
source_ref=body.source_ref, priority=body.priority, evidence=body.evidence,
now_id=body.now_id)
@router.get("/runs")
async def list_runs(status: str = "", action_id: str = "", target_ref: str = "",
source_ref: str = "", limit: int = 100,
_: identity.Actor = Depends(require("view"))):
return actions.list_runs(status=status, action_id=action_id, target_ref=target_ref,
source_ref=source_ref, limit=limit)
@router.get("/runs/{run_id}")
async def get_run(run_id: str, _: identity.Actor = Depends(require("view"))):
return actions.get(run_id)
@router.post("/runs/{run_id}/decide")
async def decide(run_id: str, body: DecideIn, _: identity.Actor = Depends(require("view"))):
# 权限在 actions.decide 里按「审批角色 + 四眼原则」细判
return actions.decide(run_id, body.approve, body.comment)
@router.post("/runs/{run_id}/retry")
async def retry(run_id: str, _: identity.Actor = Depends(require("operate"))):
return actions.retry(run_id)
@router.post("/runs/{run_id}/cancel")
async def cancel(run_id: str, body: dict | None = None,
_: identity.Actor = Depends(require("operate"))):
return actions.cancel(run_id, (body or {}).get("reason", ""))
@router.post("/runs/{run_id}/revert")
async def revert(run_id: str, body: dict | None = None,
_: identity.Actor = Depends(require("operate"))):
return actions.propose_revert(run_id, (body or {}).get("reason", ""))
@router.get("/approvals")
async def approvals(actor: identity.Actor = Depends(require("view"))):
return actions.pending_for(actor)
# ---------- 任务 ----------
@router.get("/tasks")
async def list_tasks(scope: str = "mine", status: str = "open", object_ref: str = "",
_: identity.Actor = Depends(require("view"))):
return tasks.list_tasks(scope=scope, status=status, object_ref=object_ref)
@router.get("/tasks/{task_id}")
async def get_task(task_id: str, _: identity.Actor = Depends(require("view"))):
return tasks.get(task_id)
@router.post("/tasks/{task_id}/complete")
async def complete_task(task_id: str, body: CompleteIn,
_: identity.Actor = Depends(require("operate"))):
return tasks.complete(task_id, body.result, body.comment)
@router.post("/tasks/{task_id}/claim")
async def claim_task(task_id: str, _: identity.Actor = Depends(require("operate"))):
return tasks.claim(task_id)
# ---------- 运行时总览 ----------
@router.get("/runtime/overview")
async def runtime_overview(actor: identity.Actor = Depends(require("view"))):
import datetime as dt
from ..governance import audit
from ..kernel import pipeline
from ..sop import engine as sop_engine
since = (dt.datetime.now() - dt.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
calls = audit.query(workspace=actor.workspace, event="mcp.call", since=since, limit=2000,
full=True)["items"]
by_tool: dict[str, dict] = {}
by_via: dict[str, int] = {}
ok = 0
for c in calls:
a = c.get("after") or {}
t = by_tool.setdefault(c["target_id"], {"tool": c["target_id"], "calls": 0, "failed": 0,
"total_ms": 0})
t["calls"] += 1
t["total_ms"] += int(a.get("duration_ms") or 0)
if a.get("ok"):
ok += 1
else:
t["failed"] += 1
via = a.get("via") or "agent"
by_via[via] = by_via.get(via, 0) + 1
tools = sorted(by_tool.values(), key=lambda x: -x["calls"])
for t in tools:
t["avg_ms"] = int(t["total_ms"] / t["calls"]) if t["calls"] else 0
pending = actions.pending_for(actor)
by_prio: dict[str, int] = {}
for r in pending:
by_prio[r["priority"]] = by_prio.get(r["priority"], 0) + 1
return {"mcp": {"calls_24h": len(calls), "success_rate": round(ok / len(calls), 3) if calls else None,
"by_via": by_via, "top_tools": tools[:10]},
"approvals": {"pending": len(pending), "by_priority": by_prio,
"top": [{k: r[k] for k in ("id", "action_name", "priority", "reason", "created_at")}
for r in pending[:5]]},
"actions": actions.stats(actor), "runcards": sop_engine.stats(),
"pipelines": {**pipeline.status(), "items": pipeline.list_pipelines()}}
# ---------- 收件箱汇总 ----------
@router.get("/inbox")
async def inbox(actor: identity.Actor = Depends(require("view"))):
from ..kernel import service as ksvc
counts = review.counts() if actor.can("review") else {}
counts.pop("release", None)
releases = sum(1 for r in ksvc.list_releases("pending") if r["can_decide"]) if actor.can("review") or actor.can("approve") else 0
return {"approvals": actions.count_pending(actor), "tasks": tasks.count_open(actor),
"reviews": sum(counts.values()), "review_counts": counts, "releases": releases,
"notifications": notify.unread_count(actor)}