mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-22 23:11:59 +00:00
合入 W1-b 已知遗留:人工驳回记成已取消 + end_reason=rejected(不重试、不被出错时继续吞掉),各处照实写「被驳回」;个人渠道「我发起的实例完成 / 失败」生效;导入清单如实记「是否认证」;使用者选人按候选池、开登录时服务端核对;自由形蓝图按导入的图列「谁来做」;tick 按 id 断言
This commit is contained in:
@@ -53,7 +53,8 @@ async def export_bundle(run_id: str) -> Response:
|
||||
raise CodedHTTPException(404, "运行记录不存在", RUN_NOT_FOUND)
|
||||
info = {"id": run.id, "workflow_id": run.workflow_id, "workflow_name": run.workflow_name,
|
||||
"version": run.version, "version_hash": run.version_hash, "run_class": run.run_class,
|
||||
"status": run.status, "started_at": run.started_at, "finished_at": run.finished_at}
|
||||
"status": run.status, "end_reason": run.end_reason, "started_at": run.started_at,
|
||||
"finished_at": run.finished_at}
|
||||
# 封存之后追加的事件(按需裁判、审批质询):_sealed 只留了封存范围内的,这几条另取,单列在页面上
|
||||
later = [tuple(r) for r in await session.execute(
|
||||
select(RunEvent.seq, RunEvent.type, RunEvent.node_id, RunEvent.data)
|
||||
|
||||
@@ -118,7 +118,7 @@ class ConversationOut(BaseModel):
|
||||
turn_count: int = 0
|
||||
#: 列表里给个副标题,让人一眼认出是哪次聊天
|
||||
last_question: str = ""
|
||||
#: 最后一轮停在哪:running | waiting | error | cancelled | suspended | done,
|
||||
#: 最后一轮停在哪:running | waiting | error | cancelled | rejected | suspended | done,
|
||||
#: 没有轮次时为 None。见 last_status()
|
||||
last_status: str | None = None
|
||||
#: 最后一轮的运行。建图阶段就断了的没有
|
||||
@@ -173,18 +173,24 @@ BUILD_STALE = timedelta(minutes=15)
|
||||
|
||||
|
||||
def last_status(
|
||||
turn: Any, run_status: str | None, pending: bool, now: datetime | None = None,
|
||||
turn: Any, run_status: str | None, pending: bool, now: datetime | None = None, end_reason: str | None = None,
|
||||
) -> str:
|
||||
"""一轮停在哪。轮次状态只有 running / done / error 三种,细分要看运行和元数据。
|
||||
|
||||
轮次状态是前端写的:页面关掉、服务重启时它停在 running,这时要以运行的状态为准;
|
||||
运行也没有的,是断在了建图阶段。已经收尾的轮次以轮次自己为准——它写下的就是
|
||||
用户看到的结局(取消、服务重启挂起在 error 里分开记)。
|
||||
|
||||
被审批人驳回结束的(运行 cancelled + end_reason=rejected,05-已知遗留 (a))单独记 rejected,不和手动停止混成
|
||||
cancelled:前端落库时 meta 里记着 rejected(outcome 照旧是 cancelled),页面关掉没落库的看运行的 end_reason。
|
||||
"""
|
||||
outcome = (turn_meta(turn) or {}).get("outcome")
|
||||
meta = turn_meta(turn) or {}
|
||||
outcome = meta.get("outcome")
|
||||
if turn.status == "done":
|
||||
return "done"
|
||||
if turn.status == "error":
|
||||
if outcome == "cancelled" and meta.get("rejected"):
|
||||
return "rejected"
|
||||
if outcome == "cancelled" or (turn.error or "").strip() == "已取消":
|
||||
return "cancelled"
|
||||
if outcome == "suspended":
|
||||
@@ -192,7 +198,7 @@ def last_status(
|
||||
live = _from_run(run_status, pending)
|
||||
return live if live in ("running", "waiting") else "suspended"
|
||||
return "error"
|
||||
live = _from_run(run_status, pending)
|
||||
live = _from_run(run_status, pending, end_reason)
|
||||
if live:
|
||||
return live
|
||||
updated = turn.updated_at
|
||||
@@ -202,7 +208,9 @@ def last_status(
|
||||
return "error" if stale else "running"
|
||||
|
||||
|
||||
def _from_run(run_status: str | None, pending: bool) -> str | None:
|
||||
def _from_run(run_status: str | None, pending: bool, end_reason: str | None = None) -> str | None:
|
||||
if run_status == "cancelled" and end_reason == "rejected":
|
||||
return "rejected"
|
||||
return {
|
||||
"queued": "running", "running": "running",
|
||||
"interrupted": "waiting" if pending else "suspended",
|
||||
@@ -236,11 +244,14 @@ async def _statuses(
|
||||
run_of = {cid: turn_run_id(t) for cid, t in turns.items()}
|
||||
run_ids = {r for r in run_of.values() if r}
|
||||
runs: dict[str, str] = {}
|
||||
ended: dict[str, str | None] = {}
|
||||
waiting: set[str] = set()
|
||||
if run_ids:
|
||||
runs = dict((await session.execute(
|
||||
select(Run.id, Run.status).where(Run.id.in_(run_ids))
|
||||
)).all())
|
||||
rows = (await session.execute(
|
||||
select(Run.id, Run.status, Run.end_reason).where(Run.id.in_(run_ids))
|
||||
)).all()
|
||||
runs = {r: st for r, st, _ in rows}
|
||||
ended = {r: reason for r, _, reason in rows}
|
||||
stopped = [r for r, st in runs.items() if st == "interrupted"]
|
||||
if stopped:
|
||||
waiting = set((await session.execute(
|
||||
@@ -251,7 +262,8 @@ async def _statuses(
|
||||
out: dict[str, tuple[str, str | None]] = {}
|
||||
for cid, turn in turns.items():
|
||||
run_id = run_of[cid] if run_of[cid] in runs else None
|
||||
out[cid] = (last_status(turn, runs.get(run_id or ""), run_id in waiting, now),
|
||||
out[cid] = (last_status(turn, runs.get(run_id or ""), run_id in waiting, now,
|
||||
end_reason=ended.get(run_id or "")),
|
||||
run_id)
|
||||
return out
|
||||
|
||||
|
||||
@@ -293,7 +293,7 @@ async def blueprint_stream(payload: BlueprintStreamIn, session: AsyncSession = D
|
||||
system = "\n\n".join(part for part in (
|
||||
BLUEPRINT_SYSTEM_PROMPT, _templates_text(personal=personal), await looks.overview(), BLUEPRINT_PROTOCOL_PROMPT,
|
||||
looks.guide(), BLUEPRINT_LOOK_WHEN_PROMPT) if part)
|
||||
missing = [i for i in blueprint_issues(spec, for_="trial") if i["level"] == "error"]
|
||||
missing = [i for i in blueprint_issues(spec, for_="trial", graph=row.graph) if i["level"] == "error"]
|
||||
human = copilot._with_history(BLUEPRINT_REQUEST_PROMPT.format(
|
||||
spec=json.dumps(spec, ensure_ascii=False), instruction=instruction,
|
||||
issues=BLUEPRINT_ISSUES_PROMPT.format(lines="\n".join(f"- {i['path']} {i['message']}" for i in missing))
|
||||
|
||||
@@ -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.deps import signer_of
|
||||
from app.api.deps import signer_of, signer_verified
|
||||
from app.core.errors import AUTH, NETWORK, TIMEOUT, classify, explain, raw
|
||||
from app.core.config import settings
|
||||
from app.core.crypto import encrypt, mask
|
||||
@@ -1104,7 +1104,8 @@ async def purge_raw(
|
||||
if imp.raw_state == "purged":
|
||||
raise CodedHTTPException(409, "这次导入的原件已经清除", "raw_already_purged")
|
||||
try:
|
||||
purged = await table_versions.purge_import_raw(session, imp, reason=reason, signed_by=signed_by)
|
||||
purged = await table_versions.purge_import_raw(session, imp, reason=reason, signed_by=signed_by,
|
||||
signer_verified=signer_verified())
|
||||
except table_versions.StoreUnavailable as e:
|
||||
raise CodedHTTPException(503, str(e), "store_unavailable") from e
|
||||
deleted, others = purged.deleted, purged.others
|
||||
|
||||
@@ -105,6 +105,15 @@ def signer_of(given: Any, header: str | None, limit: int = 100) -> str | None:
|
||||
return decode_actor(header)
|
||||
|
||||
|
||||
def signer_verified() -> bool:
|
||||
"""signer_of 记下的署名是不是认证过的身份:开了登录、这次请求的身份认证过时为真;关登录时署名是自报的,为假。
|
||||
|
||||
导入清单、累积快照清单、作废记录、清除原件记录的「是否认证」记这个(docs/design/next-round/05-已知遗留.md (c)),
|
||||
和审计表、待办派单、run.origin 的 verified 同一个口径。证据要在生成那一刻定下:调用方和 signed_by 一起往下传。"""
|
||||
principal = _principal.get()
|
||||
return principal is not None and principal.mode != "off" and bool(principal.verified)
|
||||
|
||||
|
||||
def current_principal() -> Principal:
|
||||
"""这次请求的完整身份。关登录时:等同 admin、未认证,username 是中间件按 X-Actor 解出的自报署名;中间件没写
|
||||
(不在请求里,比如测试直接调函数、启动时的整理、调度循环)时同样等同 admin、未认证,username 为空。"""
|
||||
|
||||
@@ -2851,7 +2851,7 @@ async def export_report_html(run_id: str, report: str | None = None) -> Response
|
||||
if run is None: # 两次读之间被删掉了
|
||||
raise CodedHTTPException(404, "运行记录不存在", RUN_NOT_FOUND)
|
||||
info = {"id": run.id, "workflow_id": run.workflow_id, "workflow_name": run.workflow_name,
|
||||
"run_class": run.run_class, "status": run.status,
|
||||
"run_class": run.run_class, "status": run.status, "end_reason": run.end_reason,
|
||||
"started_at": run.started_at, "finished_at": run.finished_at}
|
||||
data = build_report(info, report_node=chosen.node_id, doc_artifact=chosen.doc_artifact,
|
||||
doc_hash_ok=chosen.hash_ok, doc=doc, seal=sealed.seal, chains=chains, refs=refs,
|
||||
|
||||
@@ -27,6 +27,9 @@ router = APIRouter(prefix="/api", tags=["identity"])
|
||||
#: 人和组的名录(GET /api/directory):只读、给搭建者及以上(main.py 挂 require_role("builder")),岗位绑定、应用授权的
|
||||
#: 选人控件据此给候选、核对填的名字在不在。只有用户名、显示名、是否停用和组名,不含邮箱、角色、登录时间
|
||||
directory_router = APIRouter(prefix="/api", tags=["identity"])
|
||||
#: 使用者选人的候选(GET /api/directory/candidates,05-已知遗留 (b)):任何登录的人都能调(main.py 挂 require_role("user")),
|
||||
#: 按用途给候选池,只有用户名和显示名
|
||||
candidates_router = APIRouter(prefix="/api", tags=["identity"])
|
||||
|
||||
|
||||
def _iso(value: Any) -> str | None:
|
||||
@@ -224,6 +227,56 @@ async def directory(session: AsyncSession = Depends(get_session)) -> dict[str, A
|
||||
"groups": [{"name": g.name, "label": g.label} for g in known.groups.values()]}
|
||||
|
||||
|
||||
@candidates_router.get("/directory/candidates")
|
||||
async def candidates(purpose: str, app_id: str | None = None, entry: str | None = None, task_id: str | None = None,
|
||||
field: str | None = None, q: str | None = None, limit: int = 20,
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""使用者选人时的候选:{users: [{username, display_name}], groups: [{name, label}], truncated, needs_query?}。
|
||||
|
||||
不给是否停用(停用的直接不列)、角色、邮箱、组成员。purpose=form:表单里的选人控件,带 app_id 和 entry(入口表单)
|
||||
或 task_id(待办表单)、field(哪个控件),池按字段的 x-principal 算、缺省是能用这个应用的人,要求调用的人能用这个
|
||||
应用(否则 403);应用授权给了所有人时不带前缀 q 不列(needs_query)。purpose=review:个人应用提交审核,启用的搭建者
|
||||
和管理员。q 按用户名或显示名的开头筛,limit 最多 50。开了登录时提交的值按同一个池核对(auth/directory.principal_errors)。"""
|
||||
from app.api.coded import CodedHTTPException
|
||||
from app.api.deps import current_principal
|
||||
from app.apps.access import app_role, at_least
|
||||
from app.apps.tree import entry_of, resolve_form
|
||||
from app.auth.directory import PURPOSES, field_pool, principal_fields, review_pool
|
||||
from app.db.models_apps import App, AppVersion
|
||||
from app.db.models_process import Task
|
||||
|
||||
if purpose not in PURPOSES:
|
||||
raise CodedHTTPException(422, f"候选的用途只能是 {' / '.join(PURPOSES)}", "candidates_purpose")
|
||||
if purpose == "review":
|
||||
return (await review_pool(session)).pick(q, limit) | {"groups": []}
|
||||
principal = current_principal()
|
||||
bindings: dict[str, Any] | None = None
|
||||
form: Any = None
|
||||
task = await session.get(Task, task_id) if task_id else None
|
||||
app = await session.get(App, task.app_id if task is not None else app_id) if (task or app_id) else None
|
||||
if app is None or (task_id and task is None):
|
||||
raise CodedHTTPException(404, "应用或待办不存在", "candidates_not_found")
|
||||
if not at_least(await app_role(session, principal, app), "use"):
|
||||
raise CodedHTTPException(403, "你没有这个应用的使用权限,看不到它的候选人", "candidates_forbidden")
|
||||
if task is not None:
|
||||
form = task.form
|
||||
if task.app_version is not None:
|
||||
bindings = await session.scalar(select(AppVersion.bindings).where(
|
||||
AppVersion.app_id == app.id, AppVersion.version == task.app_version))
|
||||
else:
|
||||
version = (await session.execute(select(AppVersion).where(
|
||||
AppVersion.app_id == app.id, AppVersion.version == app.published_version))).scalar_one_or_none() \
|
||||
if app.published_version else None
|
||||
spec = version.spec if version is not None else {}
|
||||
found = entry_of(spec or {}, entry or "") if entry else None
|
||||
form = resolve_form(spec or {}, found.get("form")) if found else None
|
||||
bindings = version.bindings if version is not None else None
|
||||
target = principal_fields(form).get(field or "")
|
||||
if target is None:
|
||||
raise CodedHTTPException(404, "表单里没有这个选人控件", "candidates_not_found")
|
||||
return (await field_pool(session, app, bindings, target)).pick(q, limit)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 审计
|
||||
|
||||
|
||||
|
||||
@@ -56,6 +56,9 @@ class RunOut(BaseModel):
|
||||
input: dict[str, Any]
|
||||
output: dict[str, Any]
|
||||
error: str | None
|
||||
#: 结束在 cancelled 的原因(docs/design/next-round/00-总方案.md X9):rejected 人工驳回、stopped 手动停止。
|
||||
#: 其余终态、加这一列之前的运行为空。界面、通知、定时推送都读这一个字段,不再解析报错原文
|
||||
end_reason: str | None = None
|
||||
usage: dict[str, Any]
|
||||
run_class: str | None = "exploratory"
|
||||
version: int | None = None
|
||||
@@ -331,11 +334,13 @@ async def cancel_run(run_id: str, x_actor: str | None = Header(default=None)) ->
|
||||
run = await session.get(Run, run_id)
|
||||
if run is None:
|
||||
raise HTTPException(404, "运行记录不存在")
|
||||
raise HTTPException(409, _cannot_cancel(run.status))
|
||||
raise HTTPException(409, _cannot_cancel(run.status, run.end_reason))
|
||||
return {"ok": True, "status": outcome}
|
||||
|
||||
|
||||
def _cannot_cancel(status: str) -> str:
|
||||
def _cannot_cancel(status: str, end_reason: str | None = None) -> str:
|
||||
if status == "cancelled" and end_reason == "rejected":
|
||||
return "这次运行已被驳回结束,没有要停止的。"
|
||||
return {
|
||||
"succeeded": "这次运行已完成,没有要停止的。",
|
||||
"failed": "这次运行已失败结束,没有要停止的;如需继续,请点「继续运行」。",
|
||||
@@ -438,7 +443,7 @@ async def continue_run(
|
||||
except KeyError as e:
|
||||
raise _missing(e) from e
|
||||
except ContinueRefused as e:
|
||||
# 正式运行带图(formal_graph_locked)、写入结果未知还没核实(action_unresolved):带机器码
|
||||
# 正式运行带图(formal_graph_locked)、写入结果未知还没核实(action_unresolved)、被驳回了的(run_rejected):带机器码
|
||||
raise CodedHTTPException(409, str(e), e.code) from e
|
||||
except ValueError as e:
|
||||
raise HTTPException(409, str(e)) from e
|
||||
|
||||
@@ -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.deps import signer_of
|
||||
from app.api.deps import signer_of, signer_verified
|
||||
from app.data import source_versions, table_versions
|
||||
from app.data.recipe_imports import ImportRefused
|
||||
from app.db.base import get_session
|
||||
@@ -170,7 +170,8 @@ async def remove_period(source_id: str, import_id: str, request: Request, x_acto
|
||||
source = await _source(session, source_id)
|
||||
try:
|
||||
out = await source_versions.remove_period(session, source, import_id, expected_current=expected,
|
||||
reason=reason or "", signed_by=_signed(body, x_actor))
|
||||
reason=reason or "", signed_by=_signed(body, x_actor),
|
||||
signer_verified=signer_verified())
|
||||
except _REFUSALS as e:
|
||||
raise _refused(e) from e
|
||||
return {"source": await _source_out(session, source_id), **out}
|
||||
@@ -193,7 +194,7 @@ async def revoke_acceptance(source_id: str, import_id: str, request: Request,
|
||||
try:
|
||||
out = await source_versions.revoke_acceptance(
|
||||
session, source, import_id, expected_current=expected, expected_target=target, ack_mask_lost=ack,
|
||||
reason=reason or "", signed_by=_signed(body, x_actor))
|
||||
reason=reason or "", signed_by=_signed(body, x_actor), signer_verified=signer_verified())
|
||||
except _REFUSALS as e:
|
||||
raise _refused(e) from e
|
||||
return {"source": await _source_out(session, source_id), **out}
|
||||
|
||||
@@ -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.deps import current_principal, signer_of
|
||||
from app.api.deps import current_principal, signer_of, signer_verified
|
||||
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
|
||||
@@ -422,7 +422,8 @@ async def commit(staging_id: str, request: Request, x_actor: str | None = Header
|
||||
try:
|
||||
result = await recipe_imports.commit_staging(
|
||||
session, staging, trial_id=trial_id if isinstance(trial_id, str) else "",
|
||||
confirmations=confirmations, acceptances=_acceptances(body.get("acceptances"), who), signed_by=who)
|
||||
confirmations=confirmations, acceptances=_acceptances(body.get("acceptances"), who), signed_by=who,
|
||||
signer_verified=signer_verified())
|
||||
except _REFUSALS as e:
|
||||
raise _refused(e) from e
|
||||
source = await session.get(DataSource, result.source_id, populate_existing=True)
|
||||
|
||||
Reference in New Issue
Block a user