mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-23 02:32:00 +00:00
端到端验收修复与指标出具:
- 身份与工具:登录页建第一个管理员(认人接口的 401 说明能不能建);搭建者有只读的人和组名录,选人给候选并核对名字;授权三行带标题;端点请求头名校验(空名、非法名存不进、发不出时说清原因);写入能力在工具页试运行一律演练、不发送,HTTP 状态照实说成败;写记忆不算只读、查询能力只能选同一端点上的只读能力;审批与遮罩的说法和实际规则一致;开登录时不要署名、导入和发布记登录的人;使用者不显示推演等只给搭建者的操作,403 按是否开登录说话;登录页只认一次人 - 流程与实例:图里用到的岗位(派给谁、超时升级给谁、发送确认派给谁)全部派生、没绑人的发布时报错;写外部系统的参数按能力声明的类型收拢后再算哈希和发送,收不成就不发;发起人的实例页只看这一步的状态,处理人才给待办卡;会签进度带登录核实和时间,升级后照实写规则;实例状态写流程的结论(已退回、未确认、等待核实写入结果),核实生效后不再挂失败原因;流程应用首页不派生最近封存运行的结果块,看板没数据时是安静的空态;样例⑩的金额带类型和下限、待办标题带金额,表单上下限前后端一起生效 - 看板与证据:定时任务模板加 ISO 周、上一 ISO 周、本月、上月;出处链穿过原样解析查询结果的整形节点,追不到原始数据的照实说停在哪里,样例⑨改用 cell();应用首页和版本历史都能做成应用;指标块单位不重复;版本列表带退役说明;定时任务页头跟着刷新;删视图要确认、新视图能起名;编辑器属性用中文名、术语带解释 - 指标出具(用户 2026-10-15 拍板):契约只写「指标来自」、上游没有报告撰写节点、成果里没有模型写的话时按指标出具——必需指标齐、指标输入追到原始数据、成果字段里的数回指得上才完整出具;受管级要求每个指标静态地追到原始数据(governed.metric_untraced);出具横幅和应用印章写明按指标 - 受管工作流降为已发布只给管理员(Q8 顺延,服务端同样拦);工作流接口带当前发布版的级别,画布上改过之后也认得出受管工作流
This commit is contained in:
@@ -691,7 +691,7 @@ async def list_instances(app_id: str, who: str = "mine", entry: str | None = Non
|
||||
async def get_instance(app_id: str, run_id: str, session: AsyncSession = Depends(get_session),
|
||||
x_actor: str | None = Header(default=None)) -> dict[str, Any]:
|
||||
"""一个实例:列表里的那一行,加上实例页的视图模型(应用里叫 instance 的页;没有就给一页默认的)。"""
|
||||
from app.apps.resolve import ViewRefused, instance_page, instance_row, pending_counts, resolve_page
|
||||
from app.apps.resolve import ViewRefused, instance_page, instance_rows, resolve_page
|
||||
|
||||
principal = _principal(x_actor)
|
||||
app, role = await _app(session, app_id, principal, "use")
|
||||
@@ -715,8 +715,7 @@ async def get_instance(app_id: str, run_id: str, session: AsyncSession = Depends
|
||||
version=version, actor=actor_of(x_actor))
|
||||
except ViewRefused as e:
|
||||
raise _view_refused(e) from e
|
||||
counts = await pending_counts(session, [run.id])
|
||||
return {**instance_row(run, counts.get(run.id, 0)), "view": view}
|
||||
return {**(await instance_rows(session, [run]))[0], "view": view}
|
||||
|
||||
|
||||
class RefreshIn(BaseModel):
|
||||
|
||||
@@ -42,16 +42,18 @@ def principal_out(p: Principal) -> dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me(x_actor: str | None = Header(default=None)) -> Any:
|
||||
async def me(x_actor: str | None = Header(default=None), session: AsyncSession = Depends(get_session)) -> Any:
|
||||
"""当前是谁。关登录:mode=off、role=admin、username 是自报的署名。开登录没登录:401,带 mode(登录页据此显示
|
||||
账号密码还是单点登录)。"""
|
||||
账号密码还是单点登录)和 can_bootstrap:账号密码登录、库里还没有能登录的管理员时为真(环境变量直接指定了 local
|
||||
的新部署),登录页据此给「建第一个管理员」——条件和 POST /bootstrap 同一个,不多说别的。"""
|
||||
principal = current_principal()
|
||||
if principal.mode == "off":
|
||||
actor = decode_actor(x_actor)
|
||||
return principal_out(Principal(username=actor, display_name=actor, role="admin", mode="off"))
|
||||
if not principal.username:
|
||||
can_bootstrap = principal.mode == "local" and not await _local_admin_exists(session)
|
||||
return JSONResponse(status_code=401, content={"detail": "请先登录", "code": "auth_required",
|
||||
"mode": principal.mode})
|
||||
"mode": principal.mode, "can_bootstrap": can_bootstrap})
|
||||
return principal_out(principal)
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,8 @@ require_role("builder"),写接口在里面再要 admin。
|
||||
- 治理带 version 乐观锁:读到的是 v3、提交时已经是 v4 的回 409,界面重新读一遍再改;
|
||||
- 字段语义沿用数据目录「项」的状态和审阅(data/capability_review.py):GET /capabilities/review-queue 列推断的项,
|
||||
POST /capabilities/review/batch 批量确认、驳回、撤销审阅(逐个能力按 version 乐观锁,写审计);
|
||||
- 端点的认证头只回掩码,提交掩码值表示保持原值;allow_intranet 只有管理员能开(写接口本身只给管理员)。
|
||||
- 端点的认证头只回掩码,提交掩码值表示保持原值;头的名字和值不合法(空名字、带空格、换行、中文)的 422 说清是哪一项;
|
||||
allow_intranet 只有管理员能开(写接口本身只给管理员)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -175,6 +176,8 @@ async def create_endpoint(payload: EndpointIn, session: AsyncSession = Depends(g
|
||||
ensure_role("admin")
|
||||
if (await session.execute(select(Endpoint.id).where(Endpoint.name == payload.name))).first():
|
||||
raise HTTPException(409, f"已存在名为「{payload.name}」的端点,请换一个名称")
|
||||
if problem := ep.idempotency_header_problem(payload.idempotency_header):
|
||||
raise HTTPException(422, problem)
|
||||
try:
|
||||
envs = ep.seal_environments(payload.environments, None)
|
||||
except ep.EndpointError as e:
|
||||
@@ -202,6 +205,8 @@ async def update_endpoint(endpoint_id: str, payload: EndpointPatch, session: Asy
|
||||
if (await session.execute(select(Endpoint.id).where(Endpoint.name == payload.name))).first():
|
||||
raise HTTPException(409, f"已存在名为「{payload.name}」的端点,请换一个名称")
|
||||
values["name"] = payload.name
|
||||
if payload.idempotency_header is not None and (problem := ep.idempotency_header_problem(payload.idempotency_header)):
|
||||
raise HTTPException(422, problem)
|
||||
if payload.environments is not None:
|
||||
try:
|
||||
values["environments"] = ep.seal_environments(payload.environments, row.environments)
|
||||
|
||||
@@ -18,7 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api import health
|
||||
from app.api.coded import PROFILE_SETTINGS_INVALID, CodedHTTPException
|
||||
from app.api.runs import actor_of
|
||||
from app.api.deps import signer_of
|
||||
from app.core.errors import AUTH, NETWORK, TIMEOUT, classify, explain, raw
|
||||
from app.core.config import settings
|
||||
from app.core.crypto import encrypt, mask
|
||||
@@ -1065,8 +1065,8 @@ async def purge_raw(
|
||||
raise CodedHTTPException(422, "请填写清除原件的理由", "reason_required")
|
||||
if len(reason) > _PURGE_REASON_MAX:
|
||||
raise CodedHTTPException(422, f"理由不能超过 {_PURGE_REASON_MAX} 字", "reason_required")
|
||||
signed = body.get("signed_by")
|
||||
signed_by = signed.strip()[:_SIGNED_MAX] if isinstance(signed, str) and signed.strip() else actor_of(x_actor)
|
||||
# 开了登录是登录的人;关登录时请求体的 signed_by 优先,其次 X-Actor(signer_of)
|
||||
signed_by = signer_of(body.get("signed_by"), x_actor, _SIGNED_MAX)
|
||||
if imp.raw_state == "absent":
|
||||
raise CodedHTTPException(409, "这次导入没有保存原件", "raw_absent")
|
||||
if imp.raw_state == "purged":
|
||||
|
||||
@@ -92,6 +92,17 @@ def actor_of(header: str | None) -> str | None:
|
||||
return decode_actor(header)
|
||||
|
||||
|
||||
def signer_of(given: Any, header: str | None, limit: int = 100) -> str | None:
|
||||
"""请求体里自带署名(signed_by)的留痕记谁:开了登录一律是认证过的用户名,请求体里填的不看——不然随手填一个名字就
|
||||
盖掉了登录的人;关登录时请求体里填的优先(截到 limit 个字),其次 X-Actor,都只原样记下(未认证)。"""
|
||||
principal = _principal.get()
|
||||
if principal is not None and principal.mode != "off":
|
||||
return principal.username
|
||||
if isinstance(given, str) and given.strip():
|
||||
return given.strip()[:limit]
|
||||
return decode_actor(header)
|
||||
|
||||
|
||||
def current_principal() -> Principal:
|
||||
"""这次请求的完整身份。关登录时:等同 admin、未认证,username 是中间件按 X-Actor 解出的自报署名;中间件没写
|
||||
(不在请求里,比如测试直接调函数、启动时的整理、调度循环)时同样等同 admin、未认证,username 为空。"""
|
||||
|
||||
@@ -128,6 +128,7 @@ from app.engine.evidence import (
|
||||
withhold_metrics,
|
||||
)
|
||||
from app.engine.judge import FIELDS_MAX, SETTLED, UNSUPPORTED, VERDICTS, candidates, outdated
|
||||
from app.engine.lineage import untraced
|
||||
from app.engine.merge_query import MERGE_SOURCE, trace_cell
|
||||
from app.engine.schema import CLAIMS_JUDGE, GraphSpec, challenge_report, dual_check_card
|
||||
from app.engine.toolcalls import QUERY_PREFIX
|
||||
@@ -962,6 +963,10 @@ async def _metric_chain(seg: dict[str, Any], cite: dict[str, Any], entry: dict[s
|
||||
# 期 4:这个指标做没做过双盲复算、结果如何。没有双盲复算复核过这份指标集时没有这个键,老运行一字不差
|
||||
if checked := _dual_check_of(sealed, str(entry.get("node_id") or ""), artifact, metric_id, metric):
|
||||
step["dual_check"] = checked
|
||||
if metric is not None and metric.get("inputs"):
|
||||
# 输入追没追到原始数据(engine/lineage.py):和「有出处」(确定性复算一致)是两件事,面板分开说。追不到的照实说
|
||||
# 出处追到哪个节点为止;卡上没有输入(常量)的没有可追的,不给这个键
|
||||
step["untraced"] = _untraced_steps(metric, sealed)
|
||||
catalog = doc.get("catalog") or {}
|
||||
inputs: list[dict[str, Any]] = []
|
||||
#: 输入指到的查询快照 → 被引用的格;同一份快照只给一个查询步骤,格合在一起高亮
|
||||
@@ -969,6 +974,9 @@ async def _metric_chain(seg: dict[str, Any], cite: dict[str, Any], entry: dict[s
|
||||
held, word = await _metric_masks(metric or {}, str(entry.get("node_id") or ""), artifact, sealed, masks, card=card)
|
||||
for item in (metric or {}).get("inputs") or []:
|
||||
one = {"step": "input", **item}
|
||||
if item.get("through"):
|
||||
# 穿过原样解析查询结果的整形节点按位置取的格:面板写明经过的是哪个节点(图里的名字)
|
||||
one["through_label"] = _node_label(sealed, item["through"])
|
||||
artifact_of = item.get("artifact")
|
||||
if artifact_of and item.get("via") in ("tool_cell", "agent_field"):
|
||||
one["query"] = _query_alias(catalog, artifact_of)
|
||||
@@ -991,6 +999,26 @@ async def _metric_chain(seg: dict[str, Any], cite: dict[str, Any], entry: dict[s
|
||||
return [step, *inputs, *queries]
|
||||
|
||||
|
||||
def _node_label(sealed: _Sealed, node_id: Any) -> str:
|
||||
"""封存的图里这个节点的名字,没有名字的写 id。"""
|
||||
node = next((n for n in (sealed.graph or {}).get("nodes") or [] if isinstance(n, dict) and n.get("id") == node_id), {})
|
||||
return str((node.get("data") or {}).get("label") or node_id or "")
|
||||
|
||||
|
||||
def _untraced_steps(metric: dict[str, Any], sealed: _Sealed) -> list[dict[str, Any]]:
|
||||
"""指标的输入里追不到原始数据的:[{path, node_id, label, type}],label 是封存的图里那个节点的名字、type 是节点类型
|
||||
(面板按它写「数据整形」「沙箱代码」)。认不出是哪个节点的,node_id、label 为 None。"""
|
||||
nodes = {n.get("id"): n for n in (sealed.graph or {}).get("nodes") or [] if isinstance(n, dict)}
|
||||
out = []
|
||||
for item in untraced(metric.get("inputs") or []):
|
||||
node_id = item.get("node_id")
|
||||
node = nodes.get(node_id) or {}
|
||||
out.append({"path": item.get("path"), "node_id": node_id,
|
||||
"label": _node_label(sealed, node_id) if node_id else None,
|
||||
"type": node.get("type") or None})
|
||||
return out
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Held:
|
||||
"""一个输入不给值的原因(_InputMasks.check、_metric_masks)。kind:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""用户、组、审计(BE-1,只给管理员:main.py 挂 require_role("admin"))。设计文档 §2.7、§3.10。
|
||||
"""用户、组、审计(BE-1,只给管理员:main.py 挂 require_role("admin"));人和组的名录(只读,给搭建者及以上)。
|
||||
设计文档 §2.7、§3.10。
|
||||
|
||||
- 用户名一经建立就不改(各「人」列开了登录就写它);改叫法改显示名。单点登录来的用户角色每次登录按映射重算,这里改了
|
||||
下次登录会被映射盖掉;
|
||||
@@ -23,6 +24,9 @@ from app.db.models import AuditEvent, Group, GroupMember, User
|
||||
from app.db.models_identity import ROLES
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["identity"])
|
||||
#: 人和组的名录(GET /api/directory):只读、给搭建者及以上(main.py 挂 require_role("builder")),岗位绑定、应用授权的
|
||||
#: 选人控件据此给候选、核对填的名字在不在。只有用户名、显示名、是否停用和组名,不含邮箱、角色、登录时间
|
||||
directory_router = APIRouter(prefix="/api", tags=["identity"])
|
||||
|
||||
|
||||
def _iso(value: Any) -> str | None:
|
||||
@@ -205,6 +209,19 @@ async def delete_group(group_id: str, session: AsyncSession = Depends(get_sessio
|
||||
await session.commit()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 名录
|
||||
|
||||
|
||||
@directory_router.get("/directory")
|
||||
async def directory(session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""选人用的名录。停用的人也列出来(标 disabled):已经绑着他的岗位、授权要能认出「这个人停用了」,不是「没有这个人」。"""
|
||||
users = (await session.execute(select(User).order_by(User.username))).scalars()
|
||||
groups = (await session.execute(select(Group).order_by(Group.name))).scalars()
|
||||
return {"users": [{"username": u.username, "display_name": u.display_name or u.username, "disabled": u.disabled}
|
||||
for u in users],
|
||||
"groups": [{"name": g.name, "label": g.label or g.name} for g in groups]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 审计
|
||||
|
||||
|
||||
|
||||
@@ -410,7 +410,8 @@ async def _get(session: AsyncSession, schedule_id: str) -> Schedule:
|
||||
|
||||
@router.get("/variables")
|
||||
async def list_variables(tz: str | None = Query(default=None, alias="timezone")) -> list[dict[str, str]]:
|
||||
"""输入模板能用的变量:[{name, label, example}]。示例按现在这一刻、timezone(默认 Asia/Shanghai)触发算。"""
|
||||
"""输入模板能用的变量:[{name, label, example, note}]。示例按现在这一刻、timezone(默认 Asia/Shanghai)触发算;
|
||||
note 是补充说明(ISO 周的跨年规则),没有的是空串。"""
|
||||
zone = _timezone(tz) if tz is not None else service.DEFAULT_TIMEZONE
|
||||
return service.variables(tz=zone)
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
**写操作一律要 confirm: true 和界面看到的当前版本(expected_current_snapshot_id)**(7.7):确认框是按那个版本
|
||||
写的后果,别人在这期间提交、启用过,锁内比对不上就 409 base_changed,不能照旧切过去。移除、作废还要写理由。
|
||||
署名取请求体的 signed_by,其次请求头 X-Actor,只原样记下(未认证)。
|
||||
署名:开了登录是登录的人;关登录时取请求体的 signed_by,其次请求头 X-Actor,只原样记下(未认证)。
|
||||
|
||||
路径都是 /{source_id}/snapshots… 和 /{source_id}/imports/{import_id}/(manifest|remove|revoke-acceptance),与
|
||||
datasources.py 的 /{source_id}/imports(GET)、/{source_id}/imports/{import_id}/purge-raw 不重叠;在 main.py 里
|
||||
@@ -21,7 +21,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.coded import CodedHTTPException
|
||||
from app.api.datasources import _out
|
||||
from app.api.runs import actor_of
|
||||
from app.api.deps import signer_of
|
||||
from app.data import source_versions, table_versions
|
||||
from app.data.recipe_imports import ImportRefused
|
||||
from app.db.base import get_session
|
||||
@@ -55,10 +55,8 @@ async def _body(request: Request) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _signed(body: dict[str, Any], header: str | None) -> str | None:
|
||||
raw = body.get("signed_by")
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
return raw.strip()[:_SIGNED_MAX]
|
||||
return actor_of(header)
|
||||
"""开了登录是登录的人;关登录时请求体的 signed_by 优先,其次 X-Actor(api/deps.signer_of)。"""
|
||||
return signer_of(body.get("signed_by"), header, _SIGNED_MAX)
|
||||
|
||||
|
||||
async def _source(session: AsyncSession, source_id: str) -> DataSource:
|
||||
|
||||
@@ -28,7 +28,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.coded import CodedHTTPException
|
||||
from app.api.datasources import _NAME_PATTERN, _out, read_upload
|
||||
from app.api.runs import actor_of
|
||||
from app.api.deps import current_principal, signer_of
|
||||
from app.data import recipe_imports, table_versions
|
||||
from app.data.recipe_imports import EditRequest, ImportRefused
|
||||
from app.data.recipe_types import Acceptance, AiAvailability, PeriodInput, Recipe, Selection
|
||||
@@ -53,11 +53,13 @@ def _refused(e: Exception) -> CodedHTTPException:
|
||||
|
||||
|
||||
def _signed(body: dict[str, Any] | None, header: str | None) -> str | None:
|
||||
"""署名:请求体的 signed_by 优先,其次请求头 X-Actor。只原样记下(未认证)。"""
|
||||
"""署名:开了登录是登录的人;关登录时请求体的 signed_by 优先,其次请求头 X-Actor,只原样记下(未认证)。"""
|
||||
raw = (body or {}).get("signed_by") if isinstance(body, dict) else None
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
return raw.strip()[:_SIGNED_MAX]
|
||||
return actor_of(header)
|
||||
return signer_of(raw, header, _SIGNED_MAX)
|
||||
|
||||
|
||||
def _login_on() -> bool:
|
||||
return current_principal().mode != "off"
|
||||
|
||||
|
||||
#: JSON 请求体的字节上限和嵌套层数上限(SE-5)。最大的合法配方(200 个标签、几十个分段)也只有一两百 KB、
|
||||
@@ -371,9 +373,10 @@ def _context_inputs(raw: Any, signed_by: str | None) -> dict[str, PeriodInput] |
|
||||
if start > end:
|
||||
raise bad
|
||||
who = value.get("signed_by")
|
||||
# 开了登录时 signed_by 已经是登录的人,这里填的不看(signer_of 同一条)
|
||||
out[key] = PeriodInput(start=start, end=end,
|
||||
signed_by=(str(who).strip()[:_SIGNED_MAX] if isinstance(who, str) and who.strip()
|
||||
else signed_by))
|
||||
signed_by=(str(who).strip()[:_SIGNED_MAX]
|
||||
if isinstance(who, str) and who.strip() and not _login_on() else signed_by))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
+62
-18
@@ -15,7 +15,7 @@ from app.capabilities.endpoints import bound_endpoint_ref, find_endpoint
|
||||
from app.core.errors import explain, raw
|
||||
from app.db.base import get_session
|
||||
from app.db.models import CustomTool, Endpoint, McpServer
|
||||
from app.tools.custom import ToolFailure, schema_problem, trial
|
||||
from app.tools.custom import ToolFailure, held_write, http_failure, schema_problem, trial
|
||||
from app.tools.mcp_manager import mcp_manager
|
||||
from app.tools.registry import (
|
||||
ToolArgsError, ToolBuildError, ToolContext, Versions, all_specs, build_tools, call_is_dangerous,
|
||||
@@ -138,7 +138,7 @@ async def _side_effect(name: str, args: dict[str, Any], session: AsyncSession) -
|
||||
if ref := bound_endpoint_ref(row):
|
||||
endpoint = await find_endpoint(session, ref)
|
||||
return (f"将经登记的端点「{endpoint.name if endpoint else ref}」发送 {cfg.get('method') or 'GET'} 请求"
|
||||
"(试用按探索运行处理:有测试环境时发往测试环境,写入在没有测试环境时只演练、不发送)")
|
||||
"(试用按探索运行处理:有测试环境时发往测试环境,没有时发往生产环境)")
|
||||
if row.kind == "http":
|
||||
return (f"将调用自定义接口「{name}」"
|
||||
f"({cfg.get('method') or 'GET'} {cfg.get('url') or '(未填写地址)'})")
|
||||
@@ -152,6 +152,16 @@ async def _side_effect(name: str, args: dict[str, Any], session: AsyncSession) -
|
||||
return None
|
||||
|
||||
|
||||
async def _held(name: str, custom: CustomTool | None, session: AsyncSession) -> bool:
|
||||
"""在工具库里执行它是不是只演练:写外部系统的能力。自定义工具按它绑定的端点认(tools/custom.held_write),别的按
|
||||
能力登记的治理认。"""
|
||||
if custom is not None:
|
||||
return await held_write(session, custom)
|
||||
cap = await capability_registry.get_capability(session, name)
|
||||
return cap is not None and capability_registry.writes_externally(
|
||||
name, capability_registry.effective_effect(cap), cap.endpoint_id)
|
||||
|
||||
|
||||
@router.post("/{tool_name:path}/run")
|
||||
async def run_tool(
|
||||
tool_name: str,
|
||||
@@ -164,8 +174,20 @@ async def run_tool(
|
||||
有副作用的工具先 409 说清它会做什么,带上 confirm 再来一次才执行。工作流里
|
||||
同一个「需确认」意味着要人工审批,在这里却点一下就真跑了——同一个标签两种
|
||||
含义,工具库里试 file_write、shell_exec 的人会以为还有一道关。
|
||||
|
||||
写入外部系统的能力(capabilities.registry.writes_externally,和运行时同一个判断)在这里一律演练、不发送,结果标
|
||||
rehearsal:对外写入只经调用工具节点(要确认、带幂等键、留生效记录,A5)。没有副作用,也就不先 409。
|
||||
"""
|
||||
if not (confirm or payload.confirm):
|
||||
import json
|
||||
import time
|
||||
|
||||
custom = (await session.execute(select(CustomTool).where(CustomTool.name == tool_name))).scalar_one_or_none()
|
||||
rehearsal = await _held(tool_name, custom, session)
|
||||
if rehearsal and custom is None:
|
||||
# 被治理为写入的 MCP、数据源、内置工具:拼不出将要发送的请求,不执行,交回这次的参数
|
||||
return {"ok": True, "rehearsal": True, "duration_ms": 0,
|
||||
"result": {"rehearsal": True, "message": "演练:写入能力不在这里真的执行", "args": payload.args}}
|
||||
if not (rehearsal or confirm or payload.confirm):
|
||||
effect = await _side_effect(tool_name, payload.args, session)
|
||||
if effect:
|
||||
# 只说后果,不说怎么确认:弹窗还是再点一次是界面的事,写死在这里
|
||||
@@ -175,8 +197,6 @@ async def run_tool(
|
||||
# 不在运行里:上传表格查当前版本(运行里查的是发起时固定的那一版)
|
||||
ctx = ToolContext(run_id="playground", node_id="playground",
|
||||
sandbox_session=payload.sandbox_session, data_versions=Versions.CURRENT)
|
||||
import time
|
||||
|
||||
started = time.perf_counter()
|
||||
notes: list[str] = []
|
||||
try:
|
||||
@@ -196,13 +216,23 @@ async def run_tool(
|
||||
"detail": raw(e),
|
||||
"duration_ms": int((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
return {
|
||||
"ok": True,
|
||||
"result": result,
|
||||
"duration_ms": int((time.perf_counter() - started) * 1000),
|
||||
# 参数名写错、被替换成唯一候选跑通了:运行时会报出来,这里也得说
|
||||
**({"note": notes[0]} if notes else {}),
|
||||
}
|
||||
took = int((time.perf_counter() - started) * 1000)
|
||||
# 参数名写错、被替换成唯一候选跑通了:运行时会报出来,这里也得说
|
||||
extra = {"note": notes[0]} if notes else {}
|
||||
if rehearsal:
|
||||
# 演练回执是平台拼的 JSON:按对象交回,界面逐项画(方法、地址、请求头、请求体)。拼不出请求(路径参数不合法)的
|
||||
# 交回的是 {error}:照实说失败
|
||||
try:
|
||||
value = json.loads(result) if isinstance(result, str) else result
|
||||
except ValueError:
|
||||
value = None
|
||||
if not (isinstance(value, dict) and value.get("rehearsal")):
|
||||
error = value.get("error") if isinstance(value, dict) else None
|
||||
return {"ok": False, "error": str(error or result), "hint": "", "detail": "", "duration_ms": took, **extra}
|
||||
return {"ok": True, "rehearsal": True, "result": value, "duration_ms": took, **extra}
|
||||
if custom is not None and (failed := http_failure(custom, result)):
|
||||
return {"ok": False, **failed, "duration_ms": took, **extra}
|
||||
return {"ok": True, "result": result, "duration_ms": took, **extra}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -249,10 +279,16 @@ def _refuse_bad_schema(parameters: Any) -> None:
|
||||
|
||||
|
||||
def _seal_config(config: dict[str, Any], previous: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""请求头的值加密;提交的是原值的掩码时保持原值。"""
|
||||
"""请求头的值加密;提交的是原值的掩码时保持原值。名字不合法(空的、带空格、冒号、中文)的不让存:存进去之后每次
|
||||
调用都在发出之前失败。值里可以写 {{ 参数 }} 模板,不查。"""
|
||||
if "headers" not in config:
|
||||
return config
|
||||
return {**config, "headers": vault.seal(config.get("headers"), (previous or {}).get("headers"))}
|
||||
headers = config.get("headers")
|
||||
if headers is not None and not isinstance(headers, dict):
|
||||
raise HTTPException(422, "请求头需要写成 JSON 对象,每个请求头名称对应一个值")
|
||||
if problem := vault.header_problem(headers, check_values=False):
|
||||
raise HTTPException(422, problem)
|
||||
return {**config, "headers": vault.seal(headers, (previous or {}).get("headers"))}
|
||||
|
||||
|
||||
async def _refuse_bad_binding(session: AsyncSession, kind: str, config: dict[str, Any]) -> None:
|
||||
@@ -322,8 +358,9 @@ async def delete_custom(tool_id: str, session: AsyncSession = Depends(get_sessio
|
||||
await capability_registry.sync_all(session)
|
||||
|
||||
|
||||
async def _trial(row: CustomTool, args: dict[str, Any]) -> dict[str, Any]:
|
||||
"""试跑一次,返回和工具库「执行」同一种形状:{ok, result | error/hint/detail, duration_ms, note?}。"""
|
||||
async def _trial(row: CustomTool, args: dict[str, Any], session: AsyncSession) -> dict[str, Any]:
|
||||
"""试跑一次,返回和工具库「执行」同一种形状:{ok, result | error/hint/detail, duration_ms, note?, rehearsal?}。
|
||||
写入能力只演练(rehearsal: true,结果是将要发送的请求);HTTP 工具的结果按状态码说成败,非 2xx 是失败。"""
|
||||
import json
|
||||
import time
|
||||
|
||||
@@ -341,6 +378,7 @@ async def _trial(row: CustomTool, args: dict[str, Any]) -> dict[str, Any]:
|
||||
"hint": '参数定义是 JSON Schema,格式如 {"type": "object", "properties": '
|
||||
'{"n": {"type": "integer", "description": "…"}}, "required": ["n"]}',
|
||||
"detail": "", "duration_ms": 0}
|
||||
rehearsal = await held_write(session, row)
|
||||
try:
|
||||
result, note = await trial(row, args, ctx)
|
||||
except ToolArgsError as e:
|
||||
@@ -363,6 +401,10 @@ async def _trial(row: CustomTool, args: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"ok": False, "error": error, "hint": hint,
|
||||
"detail": json.dumps(dict(result), ensure_ascii=False), "duration_ms": took(),
|
||||
**extra}
|
||||
if rehearsal:
|
||||
return {"ok": True, "rehearsal": True, "result": result, "duration_ms": took(), **extra}
|
||||
if failed := http_failure(row, result):
|
||||
return {"ok": False, **failed, "duration_ms": took(), **extra}
|
||||
return {"ok": True, "result": result, "duration_ms": took(), **extra}
|
||||
|
||||
|
||||
@@ -395,6 +437,8 @@ async def test_custom_draft(payload: CustomToolDraftIn, session: AsyncSession =
|
||||
立刻用上一个还没试过的版本。
|
||||
|
||||
编辑已保存的工具时,界面上的请求头是掩码:按同名工具存着的值认回来,不然试跑带着掩码去请求。
|
||||
绑定端点的草稿按草稿的方法、路径、请求体拼请求(不是同名的已保存那一版);读写按已保存的治理和草稿的方法里更严的
|
||||
一个认(tools/custom._effect_of):把只读的改成 POST 去试,只演练、不发送。
|
||||
"""
|
||||
problem = _draft_problem(payload.kind, payload.config)
|
||||
if problem:
|
||||
@@ -402,7 +446,7 @@ async def test_custom_draft(payload: CustomToolDraftIn, session: AsyncSession =
|
||||
saved = (await session.execute(select(CustomTool).where(CustomTool.name == payload.name))).scalar_one_or_none()
|
||||
draft = CustomTool(name=payload.name or "draft_tool", kind=payload.kind, parameters=payload.parameters,
|
||||
config=_seal_config(payload.config, saved.config if saved else None))
|
||||
return await _trial(draft, payload.args)
|
||||
return await _trial(draft, payload.args, session)
|
||||
|
||||
|
||||
@custom_router.post("/{tool_id}/test")
|
||||
@@ -412,7 +456,7 @@ async def test_custom(
|
||||
row = await session.get(CustomTool, tool_id)
|
||||
if not row:
|
||||
raise HTTPException(404, "工具不存在,可能已被删除")
|
||||
return await _trial(row, payload.args)
|
||||
return await _trial(row, payload.args, session)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
@@ -64,6 +64,8 @@ class WorkflowOut(BaseModel):
|
||||
status: str = "draft"
|
||||
published_version: int | None = None
|
||||
published_by: str | None = None
|
||||
#: 当前发布版本的级别(published / governed)。status 在画布上改过之后会回到 draft,「这是不是受管工作流」看这一项
|
||||
published_level: str | None = None
|
||||
created_at: Any = None
|
||||
updated_at: Any = None
|
||||
run_count: int = 0
|
||||
@@ -71,6 +73,15 @@ class WorkflowOut(BaseModel):
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
async def _published_levels(session: AsyncSession, ids: list[str] | None = None) -> dict[str, str]:
|
||||
"""各工作流当前发布版本的级别 {工作流 id: level}。没发布过、或老数据没记级别的不在里面。"""
|
||||
stmt = select(WorkflowVersion.workflow_id, WorkflowVersion.level).join(
|
||||
Workflow, (Workflow.id == WorkflowVersion.workflow_id) & (Workflow.published_version == WorkflowVersion.version))
|
||||
if ids is not None:
|
||||
stmt = stmt.where(WorkflowVersion.workflow_id.in_(ids))
|
||||
return {wid: level for wid, level in (await session.execute(stmt)).all() if level}
|
||||
|
||||
|
||||
async def _run_counts(session: AsyncSession, ids: list[str] | None = None) -> dict[str, int]:
|
||||
"""各工作流的运行次数 {工作流 id: 次数},ids 为 None 时算全部。列表和单个工作流的接口都按它算:以前只有列表
|
||||
计数,详情、保存、恢复的返回落在 WorkflowOut 的默认值 0 上,同一个工作流两处说的次数不一样。"""
|
||||
@@ -84,6 +95,7 @@ async def _workflow_out(session: AsyncSession, workflow: Workflow) -> WorkflowOu
|
||||
"""返回单个工作流的接口都走这里,run_count 和列表一致。"""
|
||||
item = WorkflowOut.model_validate(workflow)
|
||||
item.run_count = (await _run_counts(session, [workflow.id])).get(workflow.id, 0)
|
||||
item.published_level = (await _published_levels(session, [workflow.id])).get(workflow.id)
|
||||
return item
|
||||
|
||||
|
||||
@@ -93,10 +105,12 @@ async def list_workflows(session: AsyncSession = Depends(get_session)) -> list[W
|
||||
(await session.execute(select(Workflow).order_by(Workflow.updated_at.desc()))).scalars()
|
||||
)
|
||||
counts = await _run_counts(session)
|
||||
levels = await _published_levels(session)
|
||||
out: list[WorkflowOut] = []
|
||||
for row in rows:
|
||||
item = WorkflowOut.model_validate(row)
|
||||
item.run_count = counts.get(row.id, 0)
|
||||
item.published_level = levels.get(row.id)
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
@@ -240,11 +254,12 @@ class VersionOut(BaseModel):
|
||||
created_at: Any = None
|
||||
#: 这一版按哪一档发布的(published / governed)。没发布过、或者是记级别之前发布的为 null
|
||||
level: str | None = None
|
||||
#: 这一版是谁、什么时候发布的;退役了的是什么时候、谁退的。存量为 null
|
||||
#: 这一版是谁、什么时候发布的;退役了的是什么时候、谁退的、退役时写的说明(没写为 null)。存量为 null
|
||||
published_at: Any = None
|
||||
published_by: str | None = None
|
||||
retired_at: Any = None
|
||||
retired_by: str | None = None
|
||||
retire_note: str | None = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -277,7 +292,6 @@ class VersionDetailOut(VersionOut):
|
||||
catalog_changes: list[dict[str, Any]] = Field(default_factory=list)
|
||||
#: 入口字段换成表单(agentlab.form/1):发起表单、应用入口用同一个渲染器(X2)
|
||||
input_schema: dict[str, Any] = Field(default_factory=dict)
|
||||
retire_note: str | None = None
|
||||
#: 账本(L4):固定这一版的应用、生效记录数、正式运行数
|
||||
usage: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
@@ -417,6 +431,10 @@ async def publish_workflow(
|
||||
workflow = await session.get(Workflow, workflow_id)
|
||||
if not workflow:
|
||||
raise HTTPException(404, _GONE)
|
||||
if payload.level != "governed" and workflow.published_version and \
|
||||
(await _published_levels(session, [workflow_id])).get(workflow_id) == "governed":
|
||||
# 把受管工作流降成已发布,之后的正式运行就不再过治理门禁:和以受管级别发布是同一级的决定(Q8)
|
||||
_require_admin("把受管工作流降为已发布")
|
||||
|
||||
version = payload.version or workflow.version
|
||||
snapshot = (
|
||||
|
||||
Reference in New Issue
Block a user