"""项目主页的 LLM 调度对话接口。""" from __future__ import annotations from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy import func, select from sqlalchemy.orm import Session from app import schemas from app.api import deps from app.db import get_db from app.models import AgentRun from app.services import agent router = APIRouter(tags=["agent"]) def _http_error(exc: Exception) -> HTTPException: if isinstance(exc, agent.AgentConfigurationError): return HTTPException(409, str(exc)) if isinstance(exc, agent.AgentStateError): return HTTPException(409, str(exc)) if isinstance(exc, agent.AgentPlanError): return HTTPException(502, str(exc)) return HTTPException(500, f"智能调度失败:{exc}") def _run_for_project(db: Session, project_id: int, run_id: int) -> AgentRun: deps.get_project(db, project_id) run = db.get(AgentRun, run_id) if run is None or run.project_id != project_id: raise HTTPException(404, "智能调度记录不存在") return run @router.get("/api/projects/{project_id}/agent/runs") def list_agent_runs(project_id: int, limit: int = Query(20, ge=1, le=100), db: Session = Depends(get_db)): deps.get_project(db, project_id) rows = agent.list_runs(db, project_id, limit=limit) # total = 该项目的全部指令条数(本页只带回最近 limit 条), # 概览页的「指令历史」要靠它判断是否还有更早的记录没显示。 total = db.scalar(select(func.count(AgentRun.id)).where(AgentRun.project_id == project_id)) return {"runs": [agent.run_dict(row) for row in rows], "count": len(rows), "total": int(total or 0), "limit": len(rows)} @router.get("/api/projects/{project_id}/agent/runs/{run_id}") def get_agent_run(project_id: int, run_id: int, db: Session = Depends(get_db)): return {"run": agent.run_dict(_run_for_project(db, project_id, run_id))} @router.post("/api/projects/{project_id}/agent/plan") def plan_project(project_id: int, data: schemas.AgentPlanRequest, db: Session = Depends(get_db)): """下达一句指令。 页面走 wait=false:立刻落一条 planning 记录并返回,模型规划(几十秒到 110s+)与之后的整条执行链都在服务端线程里推进,前端只需轮询 run。 以前规划完全挂在这次 HTTP 请求上:刷新页面、代理断线或用户以为卡死而 关掉标签,计划就没了,项目也就「毫无推进」。 """ project = deps.get_project(db, project_id) message = data.message.strip() if data.wait: try: run = agent.create_plan( db, project, message=message, auto_approve=data.auto_approve, thinking=data.thinking, ) except Exception as exc: db.rollback() raise _http_error(exc) from exc if data.auto_execute: agent.auto_execute_plan(db, run, timeout_seconds=data.timeout_seconds) db.expire_all() run = db.get(AgentRun, run.id) return {"run": agent.run_dict(run), "async": False} try: run = agent.create_planning_run( db, project, message=message, auto_approve=data.auto_approve, thinking=data.thinking, ) except Exception as exc: db.rollback() raise _http_error(exc) from exc snapshot = agent.run_dict(run) agent.plan_in_background(run.id, auto_execute=data.auto_execute, timeout_seconds=data.timeout_seconds) return {"run": snapshot, "async": True} @router.post("/api/projects/{project_id}/agent/runs/{run_id}/execute") def execute_agent_run(project_id: int, run_id: int, data: schemas.AgentExecuteRequest, db: Session = Depends(get_db)): run = _run_for_project(db, project_id, run_id) if run.status == "planning": raise HTTPException(409, "LLM 还在盘点项目并生成计划,稍候几秒再执行") if run.status not in ("planned", "failed", "waiting_review"): raise HTTPException(409, f"当前计划状态为 {run.status},不能执行;如需继续请重新下达指令") if not run.steps_json: raise HTTPException(409, "该计划没有可执行步骤") if data.wait: agent.execute_run(run.id, timeout_seconds=data.timeout_seconds) db.expire_all() return {"run": agent.run_dict(db.get(AgentRun, run.id)), "async": False} # 先同步把状态翻到 running,再交给后台线程: # 否则校验失败只发生在线程里,前端拿到 planned + 「已启动」提示,项目却毫无推进。 try: agent.start_run(db, run, timeout_seconds=data.timeout_seconds) except Exception as exc: db.rollback() raise _http_error(exc) from exc snapshot = agent.run_dict(run) agent.execute_in_background(run.id, timeout_seconds=data.timeout_seconds, prestarted=True) return {"run": snapshot, "async": True} @router.post("/api/projects/{project_id}/agent/runs/{run_id}/cancel") def cancel_agent_run(project_id: int, run_id: int, data: schemas.AgentCancelRequest, db: Session = Depends(get_db)): run = _run_for_project(db, project_id, run_id) try: fresh = agent.cancel_run(db, run, reason=data.reason) except Exception as exc: raise _http_error(exc) from exc return {"run": agent.run_dict(fresh)}