普通用户建应用集成收尾:

- 问数据和个人应用的图放行绑定只读查询等合规工具的调用工具节点,只读和遮罩在这条路径上生效;被治理成写入的工具在只读运行里直接拒;知识库范围在工具层固定(图级默认值、参数名纠错、Agent 都改不了)
- 个人应用的刷新和个人蓝图的试运行只有拥有者能读:运行、事件、证据、工件、文件、运行与审批列表、对比、可验证报告、质询、假设分析、提取工作流一并收紧;个人蓝图的试运行不论谁发起都按个人应用约束
- 共享蓝图只给拥有者、对应应用的管理者、管理员,看不到的一律 404;审核副本归审核人;管理员看别人的个人应用只有元数据、可以归档
- 记录表跨版本汇总(只读挂载旧版本、按当前列 UNION ALL、各版本各自固定高水位,缺的版本照实写进印章);停用前发起的运行可以继续写旧版本;更正沿用原提交人、更正人记审计
- 约定收口:待办种类 review、事件 file.extracted、表单错误 file、模板定义带示例与预置;前端类型一次补齐、去掉临时的局部类型;审核待办卡不再给打不开的链接;读附件事件有中文说法;检查脚本补断言
This commit is contained in:
ThearchyHelios
2026-10-15 13:55:19 +08:00
parent a702a5c14b
commit 7739340607
95 changed files with 3107 additions and 611 deletions
+52 -6
View File
@@ -133,19 +133,29 @@ async def _summary(session: AsyncSession, app: App, principal: Principal, role:
"published_version": app.published_version, "level": version.level if version else None,
"needs_upgrade": await _needs_upgrade(session, version),
"pending_tasks": await _pending(session, app.id, principal), "my_role": role,
"created_at": app.created_at.isoformat() if app.created_at else None,
"updated_at": app.updated_at.isoformat() if app.updated_at else None,
# 个人应用(N7):scope=personal、拥有者;出自哪个蓝图(共享应用经发布单生成的也有)
"scope": app.scope or "shared", "owner": app.owner, "blueprint_id": app.blueprint_id}
def _personal_stub(app: App) -> dict[str, Any]:
"""管理员在应用列表里看到的别人的个人应用:在不在、谁的、叫什么、状态,能归档;说明、页面、数一概不给(P4)。"""
"""管理员看到的别人的个人应用(列表、详情、归档的回包同一份):名称、拥有者、状态、创建和更新时间,能归档;说明、
页面、数、运行、蓝图一概不给(P4,N7「管理员看得到谁有几个个人应用,可以归档,但不看内容」)。"""
return {"id": app.id, "name": app.name, "description": "", "icon": "app", "status": app.status,
"published_version": None, "level": None, "needs_upgrade": False, "pending_tasks": 0, "my_role": None,
"created_at": app.created_at.isoformat() if app.created_at else None,
"updated_at": app.updated_at.isoformat() if app.updated_at else None,
"scope": "personal", "owner": app.owner, "blueprint_id": None}
def _sees_stub(principal: Principal, app: App) -> bool:
"""这个人对这个应用只看得到元数据(_personal_stub):开了登录的管理员看别人的个人应用。"""
from app.apps.access import is_personal
return is_personal(app) and principal.mode != "off" and principal.role == "admin"
def _published_outline(version: AppVersion | None) -> dict[str, Any] | None:
"""当前发布版里使用面要的那一点:有哪些页面、哪些入口(名字和标题)。页面内容走页面解析,表单走页面的 forms。"""
if version is None:
@@ -158,6 +168,36 @@ def _published_outline(version: AppVersion | None) -> dict[str, Any] | None:
if isinstance(e, dict) and e.get("id")]}
def _draft_changed(app: App, previous: AppVersion | None) -> bool | None:
"""草稿和当前发布版是否一致(N6,页面上直接改时说「有未发布的改动」还是「和发布版相同」)。按发布时的规整方式比
(publish_draft:parse_spec 规整成同一个形状),两边都过一遍,老版本发布时还没有的字段按缺省补齐、不算改动;钉住项的
级别发布时按库里的那一版补、不出自草稿,不比。岗位绑定一并比。没发布过、发布版规整不了的为 None(不知道,界面不猜);
草稿规整不了的算改过(发布前得先改好)。"""
from pydantic import ValidationError
from app.apps.lint import pins_with_state
from app.apps.spec import parse_spec
from app.core.artifact_store import canonical_json
def normal(spec: Any) -> str:
out = parse_spec(spec or {}).model_dump(mode="json", by_alias=True)
out["pins"] = pins_with_state(out, {})
return canonical_json(out)
if previous is None:
return None
try:
published = normal(previous.spec)
except ValidationError:
return None
try:
draft = normal(app.draft)
except ValidationError:
return True
bindings = {"slots": {}, **(app.draft_bindings or {})}
return draft != published or canonical_json(bindings) != canonical_json(previous.bindings or {"slots": {}})
async def _detail(session: AsyncSession, app: App, principal: Principal, role: str | None, *,
with_backfill: bool = False) -> dict[str, Any]:
"""应用详情。草稿和草稿里的岗位绑定只给 manage(D-m):草稿是还没发布、没过检查的东西,岗位绑定是这个部署里具体
@@ -167,8 +207,8 @@ async def _detail(session: AsyncSession, app: App, principal: Principal, role: s
归档这些改动的回包里不算(编辑器存一次草稿就算一遍太浪费,补算只看发布版,草稿改了也不变)。"""
from app.apps.spec import empty_spec
out = {**await _summary(session, app, principal, role),
"published": _published_outline(await _previous(session, app))}
previous = await _previous(session, app)
out = {**await _summary(session, app, principal, role), "published": _published_outline(previous)}
if not at_least(role, "manage"):
return out
out.update(draft=app.draft or empty_spec(app.name), draft_bindings={"slots": {}, **(app.draft_bindings or {})},
@@ -179,6 +219,8 @@ async def _detail(session: AsyncSession, app: App, principal: Principal, role: s
out["personal"] = await personal_state(session, app, principal)
return out
if (changed := _draft_changed(app, previous)) is not None:
out["draft_changed"] = changed
if with_backfill:
from app.apps.backfill import backfillable
@@ -200,7 +242,6 @@ async def list_apps(include_archived: bool = False, scope: str | None = None,
个人看管理员的开关,blueprints/personal.allowed)。"""
from sqlalchemy import or_
from app.apps.access import is_personal
from app.blueprints.personal import allowed
principal = _principal(x_actor)
@@ -215,7 +256,7 @@ async def list_apps(include_archived: bool = False, scope: str | None = None,
for app in (await session.execute(query)).scalars():
role = await app_role(session, principal, app)
if role is None:
if is_personal(app) and principal.mode != "off" and principal.role == "admin":
if _sees_stub(principal, app):
items.append(_personal_stub(app))
continue
items.append(await _summary(session, app, principal, role))
@@ -279,7 +320,12 @@ async def derive(payload: DeriveIn, session: AsyncSession = Depends(get_session)
@router.get("/{app_id}")
async def get_app(app_id: str, session: AsyncSession = Depends(get_session),
x_actor: str | None = Header(default=None)) -> dict[str, Any]:
"""应用详情(_detail)。管理员打开别人的个人应用只拿到元数据(_personal_stub,同列表里那一条),页面、草稿、刷新、
蓝图的接口照旧当它不存在。"""
principal = _principal(x_actor)
stub = await session.get(App, app_id)
if stub is not None and _sees_stub(principal, stub) and await app_role(session, principal, stub) is None:
return {**_personal_stub(stub), "published": None}
app, role = await _app(session, app_id, principal, "use")
return await _detail(session, app, principal, role, with_backfill=True)
@@ -354,7 +400,7 @@ async def archive_app(app_id: str, session: AsyncSession = Depends(get_session),
await session.commit()
await session.refresh(app)
if role is None:
return _personal_stub(app)
return {**_personal_stub(app), "published": None}
return await _detail(session, app, principal, role)
+3 -2
View File
@@ -17,11 +17,12 @@ _MAX_INLINE = 2 * 1024 * 1024
async def get_artifact(artifact_id: str) -> dict[str, Any]:
"""按内容哈希取回一个工件。取回时会复验哈希——内容不可变是这层的全部承诺。
开了登录:builder 及以上照旧拿原文。user 角色只能取它能读的运行引用的工件(can_read_artifact),而且对它来说遮罩
开了登录:builder 及以上照旧拿原文,只被别人的个人应用刷新、个人蓝图试运行引用的除外(只给拥有者,管理员也一样,
auth/access.artifact_readable)。user 角色只能取它能读的运行引用的工件(can_read_artifact),而且对它来说遮罩
就是边界:只给白名单里的几种,按派生遮罩处理后再给(_masked_for_user),别的种类一律不给。"""
principal = current_principal()
restricted = principal.mode != "off" and not principal.at_least("builder")
if restricted and not await can_read_artifact(principal, artifact_id):
if principal.mode != "off" and not await can_read_artifact(principal, artifact_id):
raise HTTPException(403, "没有权限查看这件工件")
try:
content = artifact_store.load(artifact_id)
+26 -15
View File
@@ -1,7 +1,9 @@
"""蓝图、试运行、发布单的接口(docs/design/normal-user-apps.md §3.5、§3.6、§3.10)。
权限在接口里判:共享蓝图要 builder(受管级发布单再要 admin),个人蓝图要拥有者且能用个人应用(blueprints/personal.allowed:
开了登录的搭建者及以上随时能,使用者和关登录时看管理员开没开 apps.user_personal_apps)。别人的个人蓝图一律当不存在(404)。
权限在接口里判:共享蓝图要 builder(受管级发布单再要 admin),而且只给拥有者、它发布出来的应用的管理者和管理员
(blueprints/store.can_access),别的搭建者列表里看不到、直接访问 404;个人蓝图要拥有者且能用个人应用
(blueprints/personal.allowed:开了登录的搭建者及以上随时能,使用者和关登录时看管理员开没开 apps.user_personal_apps)。
看不到的蓝图一律当不存在(404)。
- 起点四个,都落到同一个蓝图(N1):conversation(空蓝图,另建一段蓝图对话)、template(按模板预置卡片)、run(问数据
的一轮回答:按 /copilot/from-run 同一个提取规则取出执行路径,模板记「自由形」)、workflow_version(已发布的版本:
@@ -36,6 +38,8 @@ FREEFORM = "freeform"
#: 蓝图对话(Conversation.kind)
CONVERSATION_KIND = "blueprint"
DEFAULT_NAME = "新应用"
#: 蓝图列表最多列几张
_LIST_MAX = 200
# --------------------------------------------------------------------------
@@ -66,8 +70,8 @@ async def _personal_allowed(session: AsyncSession, principal: Principal) -> None
async def _blueprint(session: AsyncSession, blueprint_id: str) -> Blueprint:
"""取蓝图并判权限(blueprints/store.load,蓝图接口和蓝图助手同一条规则):共享的要搭建者;个人的要拥有者(别人的
个人蓝图当不存在)且能用个人应用。"""
"""取蓝图并判权限(blueprints/store.load,蓝图接口和蓝图助手同一条规则):共享的要搭建者,且是拥有者、它发布出来的
应用的管理者或管理员;个人的要拥有者且能用个人应用。看不到的当不存在(404)。"""
from app.blueprints.store import load
return await load(session, blueprint_id)
@@ -247,23 +251,29 @@ async def _from_version(session: AsyncSession, spec: dict[str, Any], workflow_id
async def list_blueprints(scope: Literal["shared", "personal"] | None = None,
session: AsyncSession = Depends(get_session),
x_actor: str | None = Header(default=None)) -> dict[str, Any]:
"""共享蓝图(搭建者看得到)和我的个人蓝图(能用个人应用时),按最近改动排。"""
"""我能读写的共享蓝图(搭建者及以上:自己的、自己管理的应用出自的;管理员全部,blueprints/store.can_access)和我的
个人蓝图(能用个人应用时),按最近改动排。别的搭建者的共享蓝图不列。"""
from app.blueprints.personal import allowed
from app.blueprints.store import shared_listed
principal = _principal(x_actor)
wanted = []
rows: list[Blueprint] = []
if scope in (None, "shared") and principal.at_least("builder"):
wanted.append(Blueprint.scope == "shared")
query = select(Blueprint).where(Blueprint.scope == "shared")
if principal.mode != "off" and principal.role != "admin":
# 候选只有自己的、发布成了应用的(要不要列看应用的管理权,shared_listed 逐个应用核对)
query = query.where(or_(Blueprint.owner == (principal.username or ""), Blueprint.app_id.is_not(None)))
else:
query = query.order_by(Blueprint.updated_at.desc()).limit(_LIST_MAX)
rows += await shared_listed(session, principal, list((await session.execute(query)).scalars()))
if scope in (None, "personal") and await allowed(session, principal):
mine = Blueprint.scope == "personal"
if principal.mode != "off":
mine = mine & (Blueprint.owner == (principal.username or ""))
wanted.append(mine)
if not wanted:
return {"items": []}
rows = (await session.execute(select(Blueprint).where(or_(*wanted)).order_by(Blueprint.updated_at.desc())
.limit(200))).scalars()
return {"items": [blueprint_out(bp) for bp in rows]}
rows += list((await session.execute(select(Blueprint).where(mine).order_by(Blueprint.updated_at.desc())
.limit(_LIST_MAX))).scalars())
rows.sort(key=lambda bp: bp.updated_at or bp.created_at, reverse=True)
return {"items": [blueprint_out(bp) for bp in rows[:_LIST_MAX]]}
@router.get("/blueprints/{blueprint_id}")
@@ -351,7 +361,8 @@ class TrialIn(BaseModel):
@router.post("/blueprints/{blueprint_id}/trial")
async def trial(blueprint_id: str, payload: TrialIn, session: AsyncSession = Depends(get_session),
x_actor: str | None = Header(default=None)) -> Any:
"""用真数试运行:实例化 → 保存图 → 发起探索运行,交回 {run_id, blueprint}。缺项、待填的关节挡住时回 409 和问题。"""
"""用真数试运行:实例化 → 保存图 → 发起探索运行,交回 {run_id, blueprint, inputs}(inputs 是这次实际用的输入:
看板类补齐了统计期,流程类是示例表单按入口映射换成的图输入)。缺项、待填的关节挡住时回 409 和问题。"""
from app.blueprints.trial import TrialRefused, start_trial
from app.engine.launch import LaunchRefused
@@ -365,7 +376,7 @@ async def trial(blueprint_id: str, payload: TrialIn, session: AsyncSession = Dep
raise _refused(e) from e
except LaunchRefused as e:
raise _refused(e) from e
return {"run_id": run.id, "blueprint": blueprint_out(bp)}
return {"run_id": run.id, "blueprint": blueprint_out(bp), "inputs": dict(run.input or {})}
@router.get("/blueprints/{blueprint_id}/preview")
+17 -12
View File
@@ -821,23 +821,22 @@ def _graph_system(sources: list[Any], scope: set[str] | None, datasources: str,
def _chat_user_kinds() -> str:
from app.auth.chat_policy import CHAT_NODE_TYPES
return "、".join(sorted(CHAT_NODE_TYPES - {"merge"}))
return "、".join(sorted(CHAT_NODE_TYPES))
#: 开登录后 user 角色在问数据里生成的图(D-c)要守的约束,接在结构要求后面(_graph_system 的 chat_user)。发起时按
#: app/auth/chat_policy.py 收窄,节点手册里取数的标准写法(tool 节点查库、merge 按键合并)搭出来的图发起时一律被拒,所以先
#: 说给模型听。规则本身只在 chat_policy 一处:节点类型从那里取,自查也按它判(_chat_user_issues),这里只是把它讲成模型
#: 照着搭得出来的写法
#: app/auth/chat_policy.py 收窄:节点只许读数据、整理、撰写这一类,tool 节点和 agent 只能用数据源查询和只读的内置工具,
#: 所以先说给模型听。规则本身只在 chat_policy 一处:节点类型从那里取,自查也按它判(_chat_user_issues),这里只是把它讲成
#: 模型照着搭得出来的写法
_CHAT_USER_PROMPT = (
"\n\n这位用户是「使用者」:这张图以他的身份运行,只能读数据、整理、撰写。下面几条优先于上面节点手册和搭图规则里的"
"写法:\n"
f"1. 节点只用 {_chat_user_kinds()}。不要用 tool、code、merge、supervisor、subgraph、loop、human、memory、validate 等"
"其他节点(merge 的输入只能是 tool 节点,所以同样用不了)\n"
"2. 取数只用 agent:tools 里绑定 db_query__<数据源> 和 db_schema__<数据源>。数字要进口径卡、报告时,给这个 agent 配 "
"output_schema 和 cite_fields: true,口径卡取 vars.<agent 的 assign_to>.字段。数据在两个库时,让一个 agent 绑两个库的"
"查询工具,各自聚合后在 output_schema 里一起交回\n"
f"1. 节点只用 {_chat_user_kinds()}。不要用 code、supervisor、subgraph、loop、human、memory、validate 等其他节点\n"
"2. tool 节点和 agent 都只能用 db_query__<数据源>、db_schema__<数据源> 和上面列出的内置工具:取数用 tool 节点"
"(tool 写 db_query__<数据源>,args.sql 写好 SQL)或 agent(tools 里绑定这两种数据源工具)。不要用 http_request、"
"records_append 这类写入或连外部的工具,工具名不要用 {{ }} 拼\n"
"3. 查询一律只读,不要写改数据的 SQL\n"
"4. 任何节点、图级 defaults 里都不要写 memory_scope、collection:记忆范围和知识库由平台定"
"4. 任何节点、图级 defaults、tool 节点的 args 里都不要写 memory_scope、collection:记忆范围和知识库由平台定"
)
@@ -851,7 +850,7 @@ def _chat_user_issues(nodes: dict[str, dict[str, Any]], edges: list[dict[str, An
return []
return [{"level": "error", "node_id": None, "edge_id": None, "field": None, "code": "chat.not_allowed",
"message": problem,
"for_model": f"{problem}。按 system 里「使用者」那一段的约束改:取数改成 agent 绑定数据源查询工具,"
"for_model": f"{problem}。按 system 里「使用者」那一段的约束改:取数用 tool 节点或 agent 调数据源查询工具,"
"去掉不允许的节点、工具和记忆范围 / 知识库配置"}]
@@ -2593,10 +2592,13 @@ async def extract_run_path(session: AsyncSession, run_id: str) -> RunPath:
参数化成入口字段的默认值。不落库。「提取成工作流」(/from-run)和蓝图的「从问数据的回答开始」共用。"""
from sqlalchemy import select as _sel
from app.api.deps import can_read_run, current_principal
from app.db.models import Run, RunEvent
run = await session.get(Run, run_id)
if not run:
# 读不到的运行当它不存在:别人的个人应用刷新、个人蓝图试运行只给拥有者(auth/access.private_owner),提取出的图就是
# 那张蓝图的内容,管理员、搭建者也不给
if not run or not await can_read_run(current_principal(), run):
raise PathRefused(404, "运行记录不存在,可能已被删除")
# 没跑通的路径提出来是半截骨架:失败节点之后的步骤一步都不在里面,
# 人拿去审改时却看不出它缺了什么
@@ -2752,12 +2754,15 @@ async def review_run(
规则层先扫一遍(engine/review.py:scan),没扫出东西就到此为止、直接返回,
不花一次模型调用;扫出来了才叫模型重组答案并把异常说破。
"""
from app.api.deps import PRIVATE_RUN, can_read_run, current_principal
from app.db.models import Run, RunEvent
from app.engine import review as rv
run = await session.get(Run, payload.run_id)
if not run:
raise HTTPException(404, "运行记录不存在,可能已被删除")
if not await can_read_run(current_principal(), run):
raise HTTPException(403, PRIVATE_RUN)
rows = list((await session.execute(
select(RunEvent).where(RunEvent.run_id == payload.run_id).order_by(RunEvent.seq)
+2 -2
View File
@@ -4,8 +4,8 @@
- POST /api/copilot/fill-joints-stream:按模板填生成关节(sql、metric_expr)。TemplateApplier 只收 fill_joint、只收模板声明过的
关节;不同 group 的关节并行填。
都复用 api/copilot_gen.Generation。权限按蓝图判(blueprints/store.ensure_access):共享蓝图要搭建者;个人蓝图只给拥有者,且
管理员开了个人应用。
都复用 api/copilot_gen.Generation。权限按蓝图判(blueprints/store.ensure_access):共享蓝图要搭建者,且是拥有者、它发布出来
的应用的管理者或管理员;个人蓝图只给拥有者,且管理员开了个人应用。
**调用次数的预算**(N11):起草蓝图 1 次主调用加最多 2 次查看;填关节每组 1 次调用、各自最多 1 次查看(系统先代为查看
这一组要用的表,不占次数),不同的组并行。并行调用出错(多半是模型服务限流)的组,等别的组做完再按顺序试一次。
+51 -10
View File
@@ -11,7 +11,9 @@
- run_events_readable(principal, run):运行的原始记录、事件、实时流能不能读(user 只读查询结果在工具边界遮过的);
- ensure_conversation_access(session, conversation_id):接受 conversation_id 的接口核对对话归属(对话按人隔离);
- run_scope / evidence_scope / chat_scope:main.py 挂在运行、证据、问数据几组路由上的依赖,按 run_id 判断能不能读。
run_scope 同样管运行的 WebSocket,握手时按运行判。
run_scope 同样管运行的 WebSocket,握手时按运行判;
- private_run_scope:挂在只给搭建者的运行子路由(对比、可验证报告、质询、假设分析)上,别人的个人应用刷新、个人蓝图
试运行只有拥有者能碰(auth/access.py 的 private_owner),管理员、搭建者也不例外。
关登录时:所有人等同 admin、全部放行,行为和加这一层之前一模一样(界面上挂横幅说明)。
@@ -189,12 +191,15 @@ def masked_at_boundary(run: Any) -> bool:
async def run_events_readable(principal: Principal, run: Any) -> bool:
"""能不能读这次运行的原始记录、事件和实时流(GET /api/runs/{id}、/events、/graph,WebSocket /stream)。
关登录、builder 及以上:能。user:这次运行它能读(can_read_run),而且查询结果在工具边界就遮过(masked_at_boundary)。
两个条件缺一不可:没在边界遮过的运行,事件里 tool.end 的预览、运行状态里是查询结果的原文,遮罩管不到——自己发起的
应用实例、有授权的应用视图运行经应用页和证据接口读(那两处按派生遮罩给)。实际上满足两条的就是它自己开登录后发起的
关登录:能。builder 及以上:这次运行它能读就能(can_read_run:别人的个人应用刷新、个人蓝图试运行读不了)。
user:这次运行它能读(can_read_run),而且查询结果在工具边界就遮过(masked_at_boundary)。两个条件缺一不可:
没在边界遮过的运行,事件里 tool.end 的预览、运行状态里是查询结果的原文,遮罩管不到——自己发起的应用实例、
有授权的应用视图运行经应用页和证据接口读(那两处按派生遮罩给)。实际上满足两条的就是它自己开登录后发起的
问数据运行;关登录时自报同名留下的老运行没在边界遮过,开了登录也读不到。"""
if principal.mode == "off" or principal.at_least("builder"):
if principal.mode == "off":
return True
if principal.at_least("builder"):
return await can_read_run(principal, run)
if run is None or not principal.username or not masked_at_boundary(run):
return False
return await can_read_run(principal, run)
@@ -206,7 +211,8 @@ def _own_chat_run(principal: Principal, run: Any) -> bool:
async def _run_scope(conn: HTTPConnection) -> None:
"""/api/runs 下的接口和运行的实时流。builder 及以上全部放行;user 角色只在管理员开了问数据(Q2)时能碰这组接口:
"""/api/runs 下的接口和运行的实时流。builder 及以上放行,只有别人的个人应用刷新、个人蓝图试运行例外(只给拥有者,
_refuse_private);user 角色只在管理员开了问数据(Q2)时能碰这组接口:
- 列表、别人的运行一律不给(记录页是给搭建者看的);
- 能发起(只能是问数据的探索运行,start_run 里按请求体再查);能停止自己的问数据运行;
- 能读运行记录、事件、运行时的图,能连 WebSocket:按运行判(run_events_readable),握手时就判,不再一刀切只给
@@ -214,7 +220,10 @@ async def _run_scope(conn: HTTPConnection) -> None:
- 自己发起的应用实例、有授权的应用视图运行、参与的实例,经应用页(/api/apps/{id}/instances)和证据接口
(evidence_scope)读,这里不给原始事件和状态:tool.end 的预览、运行状态里是查询结果的原文,遮罩管不到。"""
principal = current_principal()
if principal.mode == "off" or principal.at_least("builder"):
if principal.mode == "off":
return
if principal.at_least("builder"):
await _refuse_private(conn, principal)
return
if conn.scope["type"] == "websocket":
# 握手前拒:服务端回 1008,不建立连接。没登录的中间件已经挡掉了,这里只剩按运行判
@@ -256,6 +265,34 @@ async def _load_run(run_id: str | None) -> Any:
return await session.get(Run, run_id)
#: 搭建者、管理员碰别人的个人应用刷新、个人蓝图试运行时的说法
PRIVATE_RUN = "没有权限查看这次运行:个人应用的刷新和个人蓝图的试运行只有拥有者能看"
#: 运行子路由里另带的运行 id(对比的基准 ?base=)
_RUN_QUERY_KEYS = ("base",)
async def _refuse_private(conn: HTTPConnection, principal: Principal) -> None:
"""builder 及以上:路径里的运行(和对比的基准)是别人的个人应用刷新、个人蓝图试运行时拒(403,WebSocket 握手前
1008)。不存在的运行放过去,由接口照旧回 404。"""
ids = [conn.path_params.get("run_id"), *(conn.query_params.get(k) for k in _RUN_QUERY_KEYS)]
for run_id in (i for i in ids if i):
if await can_read_run(principal, run_id):
continue
if conn.scope["type"] == "websocket":
from fastapi import WebSocketException, status
raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
raise HTTPException(403, PRIVATE_RUN)
async def _private_run_scope(conn: HTTPConnection) -> None:
"""只给搭建者的运行子路由(main.py 里对比、可验证报告、质询、假设分析):角色由 require_role 判,这里只管别人的
个人应用刷新、个人蓝图试运行。"""
principal = current_principal()
if principal.mode != "off":
await _refuse_private(conn, principal)
def restricted() -> bool:
"""这次请求的人是不是开登录后的 user 角色:对它来说遮罩就是边界,只能做问数据、用应用这几件事。"""
principal = current_principal()
@@ -263,10 +300,13 @@ def restricted() -> bool:
async def _evidence_scope(conn: HTTPConnection) -> None:
"""/api/runs/{run_id}/evidence… 这组证据接口:builder 及以上全部放行;user 角色只读(GET),而且这次运行要能读
(can_read_run)。证据接口交出的查询行本身按派生遮罩处理过。"""
"""/api/runs/{run_id}/evidence… 这组证据接口:builder 及以上放行,别人的个人应用刷新、个人蓝图试运行除外(只给
拥有者);user 角色只读(GET),而且这次运行要能读(can_read_run)。证据接口交出的查询行本身按派生遮罩处理过。"""
principal = current_principal()
if principal.mode == "off" or principal.at_least("builder") or conn.scope["type"] != "http":
if principal.mode == "off" or conn.scope["type"] != "http":
return
if principal.at_least("builder"):
await _refuse_private(conn, principal)
return
ensure_role("user")
if conn.scope.get("method", "GET") != "GET":
@@ -298,6 +338,7 @@ _CHAT_ROUTES = frozenset({("POST", "/api/copilot/generate-stream"), ("GET", "/ap
run_scope = Depends(_run_scope)
evidence_scope = Depends(_evidence_scope)
chat_scope = Depends(_chat_scope)
private_run_scope = Depends(_private_run_scope)
def role_by_method(*, read: str, write: str) -> Any:
+6 -1
View File
@@ -98,12 +98,17 @@ async def exploratory_clusters(
这就是模板生长的触发器。用本地 embedding 做贪心聚类,
出现 ≥3 次的簇标记为晋升候选。
"""
from sqlalchemy import not_
from app.api.deps import current_principal
from app.auth.access import hidden_runs
from app.memory.embeddings import cosine, embed_texts
rows = list(
await session.execute(
select(Run.id, Run.input, Run.workflow_name, Run.created_at)
.where(Run.run_class != "formal")
# 别人的个人应用刷新、个人蓝图试运行只给拥有者(同运行列表),不进聚类
.where(Run.run_class != "formal", not_(hidden_runs(current_principal())))
.order_by(Run.created_at.desc())
.limit(limit)
)
+17 -1
View File
@@ -170,8 +170,14 @@ async def list_runs(
以前只有 limit:待审批的运行排在第 145 位,列表只取 100 条,点了徽标也找不到它。
筛选都走服务端,翻页用 created_at 做游标(before 传上一页最后一条的 created_at)。
别人的个人应用刷新、个人蓝图试运行不列(只给拥有者,auth/access.hidden_runs),管理员也一样。
"""
stmt = select(Run).order_by(Run.created_at.desc()).limit(limit)
from sqlalchemy import not_
from app.api.deps import current_principal
from app.auth.access import hidden_runs
stmt = select(Run).where(not_(hidden_runs(current_principal()))).order_by(Run.created_at.desc()).limit(limit)
if workflow_id == UNSAVED:
stmt = stmt.where(Run.workflow_id.is_(None))
elif workflow_id:
@@ -649,12 +655,18 @@ async def list_approvals(
limit: int = Query(default=100, ge=1, le=500),
session: AsyncSession = Depends(get_session),
) -> list[ApprovalOut]:
from sqlalchemy import not_
from app.api.deps import current_principal
from app.auth.access import hidden_runs
from app.db.models import Task
stmt = (
select(Approval, Run, Task.id)
.join(Run, Run.id == Approval.run_id, isouter=True)
.join(Task, Task.approval_id == Approval.id, isouter=True)
# 别人的个人应用刷新、个人蓝图试运行上的审批不列(只给拥有者,同运行列表)
.where(or_(Run.id.is_(None), not_(hidden_runs(current_principal()))))
.order_by(Approval.created_at.desc())
.limit(limit)
)
@@ -698,9 +710,13 @@ async def decide(
x_actor: str | None = Header(default=None),
) -> Any:
"""兼容垫片:改走待办服务(app/process/tasks.py 的 respond)。请求体照旧,只当一票、原样交给节点。"""
from app.api.deps import PRIVATE_RUN, can_read_run, current_principal
approval = await session.get(Approval, approval_id)
if not approval:
raise HTTPException(404, "审批记录不存在,所属的运行可能已被删除")
if not await can_read_run(current_principal(), approval.run_id):
raise HTTPException(403, PRIVATE_RUN)
if approval.status != "pending":
raise HTTPException(409, "这条审批已处理过,请刷新页面查看最新状态")
# 在落签批人之前拦:拒掉的批准不该留下「谁试图批的」
+5 -5
View File
@@ -1,7 +1,8 @@
"""场景模板列表(docs/design/normal-user-apps.md §3.3):GET /api/templates。登录即可看(新建应用的「从场景模板开始」)。
模板登记在导入这个模块时核对一遍(blueprints/instantiate.registry_problems):首批都登记了、关节类型认得、每个模板的
示例蓝图实例化出来过得了画布校验、骨架比对没有差异。缺一样启动即报错(N3:模板定义、实例化、测试三样都要给)。
模板登记在导入这个模块时核对一遍(blueprints/templates.check_registry → instantiate.registry_problems):首批都登记了、
关节类型认得、每个模板的示例蓝图实例化出来过得了画布校验、骨架比对没有差异。缺一样启动即报错(N3:模板定义、实例化、
测试三样都要给)。
"""
from __future__ import annotations
@@ -9,12 +10,11 @@ from typing import Any
from fastapi import APIRouter
from app.blueprints.instantiate import registry_problems
from app.blueprints.templates import list_templates
from app.blueprints.templates import check_registry, list_templates
router = APIRouter(prefix="/api/templates", tags=["templates"])
_PROBLEMS = registry_problems()
_PROBLEMS = check_registry()
if _PROBLEMS:
raise RuntimeError("场景模板登记不完整:" + ";".join(_PROBLEMS))