import secrets import logging import math from typing import Annotated from fastapi import APIRouter, Depends, Header, HTTPException, Response from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from fastapi.routing import APIRoute from pydantic import BaseModel, ConfigDict, Field from uuid import UUID from app.core.config import get_settings from app.modules.work_assistant.schemas import AnswerRequest, PlanRequest, ContinueRequest from app.modules.work_assistant.investigation import continue_investigation from app.modules.work_assistant.service import compose_answer, plan_question from app.modules.work_assistant.skills import SKILLS from app.modules.work_assistant.work_log_review import LogEntry, review_entry, review_progress from app.modules.work_assistant.decomposition import ReviewRequest, review_decomposition from app.modules.work_assistant.plan_review import PlanRequest as PlanReviewRequest, review_plan from app.modules.work_assistant.goal_review import GoalReviewRequest, review_goal from app.modules.work_assistant.task_review_contract import GOAL_RULE, DECOMPOSITION_RULE, SCHEMA_VERSION as TASK_REVIEW_SCHEMA from app.modules.work_assistant.meeting_review import MeetingItem, review_meeting from app.modules.work_assistant.model_gateway import ModelUnavailable, routing_revision from app.modules.work_assistant.project_document_review import ProjectDocument, review_project_document from app.modules.work_assistant.project_document_review import RULE_VERSION as DOCUMENT_RULE from app.modules.work_assistant.project_risk_review import ProjectRiskRequest, review_project_risk, validation_reason from app.modules.work_assistant.project_risk_review import RULE_VERSION as PROJECT_RISK_RULE from app.modules.work_assistant.review_jobs import JobDeferred, review_jobs from app.modules.work_assistant.model_dispatch import background_review, dispatch from app.modules.work_assistant.performance_review import PerformanceRequest, review_performance, validation_reason as performance_validation_reason, RULE_VERSION as PERFORMANCE_RULE from app.modules.work_assistant.personnel_profile import (ANNUAL_ASSESSMENT_VERSION, ProfileRequest, review_profile, verified_partial_profile, REVIEW_CACHE_RULE as PERSONNEL_RULE, REVIEW_POLICY as PERSONNEL_POLICY) from app.modules.work_assistant.sales_review import SalesRequest, review_sales, RULE_VERSION as SALES_RULE from app.modules.work_assistant.bid_writing import BidStep, bid_step, RULE_VERSION as BID_RULE from app.modules.work_assistant.bid_queue import bid_queue from app.modules.work_assistant.submission_advice import AdviceRequest, review_advice from app.modules.work_assistant.inspection_review import InspectionRequest, review_inspection def require_pms_bridge(x_work_assistant_key: Annotated[str | None, Header()] = None) -> None: expected = get_settings().work_assistant_shared_secret or "" if len(expected) < 32: raise HTTPException(503, "Work assistant bridge is not configured") if not x_work_assistant_key or not secrets.compare_digest(x_work_assistant_key.encode(), expected.encode()): raise HTTPException(401, "Invalid work assistant bridge credential") class BidValidationRoute(APIRoute): def get_route_handler(self): original = super().get_route_handler() async def handler(request): try: return await original(request) except RequestValidationError as exc: if not request.url.path.endswith('/bid-writing-step'): raise # Never include input values, validator context or upstream bodies. allowed = {'request_id', 'action', 'project', 'instructions', 'blocks', 'company', 'workbench', 'requirements', 'draft', 'extraction_context', 'body', 'text', 'location', 'id'} diagnostics = [] for error in exc.errors()[:8]: loc = [str(x) if isinstance(x, int) or x in allowed else 'field' for x in error['loc']] diagnostics.append({'field': '.'.join(loc), 'type': error['type']}) logger.warning('bid_request_validation fields=%s', diagnostics) first = diagnostics[0]['field'] if diagnostics else 'body' return JSONResponse(status_code=422, content={'detail': diagnostics}, headers={'X-Bid-Validation-Field': first}) return handler router = APIRouter(dependencies=[Depends(require_pms_bridge)], route_class=BidValidationRoute) logger = logging.getLogger(__name__) PERSONNEL_JOB_PROTOCOL = 1 @router.post('/submission-advice') def submission_advice(payload: AdviceRequest) -> dict: token = background_review.set(True) try: return review_advice(payload) except ModelUnavailable as exc: raise HTTPException(503, '业务提示暂未完成,仍可按原流程提交') from exc except (ValueError, TypeError) as exc: logger.warning('submission_advice_failed type=%s', type(exc).__name__) raise HTTPException(502, '提示依据尚未核对通过,仍可按原流程提交') from exc finally: background_review.reset(token) from app.modules.work_assistant.message_push import PushPreviewRequest, generate_preview from app.modules.work_assistant.message_push_feishu import dispatch_feishu from app.modules.work_assistant.message_push_email import dispatch_email @router.post('/message-push-email') def message_push_email(payload: dict) -> dict: return dispatch_email(payload) @router.post('/message-push-feishu') def message_push_feishu(payload: dict) -> dict: return dispatch_feishu(payload) @router.post('/message-push-preview') def message_push_preview(payload: PushPreviewRequest) -> dict: token = background_review.set(True) try: return generate_preview(payload) except ModelUnavailable as exc: raise HTTPException(503, '消息分析暂未完成,请稍后重试') from exc except (ValueError, TypeError) as exc: logger.warning('message_push_preview_failed type=%s', type(exc).__name__) raise HTTPException(502, '消息内容未通过依据校验') from exc finally: background_review.reset(token) @router.post("/personnel-profile-review") def personnel_profile_review(payload: ProfileRequest, response: Response = None) -> dict: token = background_review.set(True) from app.modules.work_assistant.personnel_workflow import MAX_UNCHANGED_SLICES, progress protocol_header = {"X-Personnel-Job-Protocol": str(PERSONNEL_JOB_PROTOCOL)} if response is not None: response.headers.update(protocol_header) latest={} def execute(checkpoint,save): if checkpoint:latest.update(checkpoint) def persist(value): latest.clear();latest.update(value);save(value) try: if payload.profile_kind in {'annual', 'history'}: from app.modules.work_assistant.personnel_talent import review_annual_talent from app.modules.work_assistant.personnel_history_cache import HistoryCache from app.modules.work_assistant.model_gateway import complete_json return review_annual_talent(payload,core_review=review_profile,invoke=complete_json, checkpoint=checkpoint,save_checkpoint=persist,staged=True, history_cache=HistoryCache(review_jobs.path.with_name('personnel-history.sqlite3'),routing_revision()) if payload.full_history else None) return review_profile(payload,checkpoint=checkpoint,save_checkpoint=persist,staged=True) except JobDeferred: previous = checkpoint or {} unchanged = progress(previous)['token'] == progress(latest)['token'] if unchanged: slices = previous.get('unchanged_slices', 0) + 1 if slices >= MAX_UNCHANGED_SLICES: if payload.profile_kind == 'history': raise ModelUnavailable('annual_panel_retry', retryable=True, retry_after=300) result = verified_partial_profile(payload, latest) logger.warning("personnel_profile_partial reason=unchanged_slices") return result persist({**latest, 'unchanged_slices': slices}) elif previous.get('unchanged_slices'): persist({**latest, 'unchanged_slices': 0}) raise except ValueError as exc: if payload.profile_kind in {'annual', 'history'} and latest.get('talent'): raise ModelUnavailable('annual_panel_retry', retryable=True, retry_after=300) from exc result = verified_partial_profile(payload, latest) logger.warning("personnel_profile_partial reason=validation") return result except ModelUnavailable as exc: if payload.profile_kind == 'history': # Keep the resumable portrait checkpoint. A context/output # failure must never become a cached legacy partial report. raise if exc.reason not in {'profile_context_limit', 'direct_output_truncated', 'gateway_output_truncated'} or exc.retryable: raise result = verified_partial_profile(payload, latest) logger.warning("personnel_profile_partial reason=%s", exc.reason) return result try: rule = PERSONNEL_RULE if payload.profile_kind in {'annual', 'history'}: from app.modules.work_assistant.personnel_talent import PANEL_REVISION rule += f':annual-{ANNUAL_ASSESSMENT_VERSION}:talent-{PANEL_REVISION}' from app.modules.work_assistant.personnel_talent import resume_cached_talent return review_jobs.run(payload.review_input(), rule + ':' + routing_revision(), execute, lease_seconds=180, rapid_recovery=True, progress_recovery=True, resume_context_failures=True, resume_ready=lambda result:resume_cached_talent(payload,result)) except ModelUnavailable as exc: # A saved time slice is waiting to continue, not a model outage. Keep # Java on its waiting path without consuming its service-failure budget. reason = exc.reason if reason not in {'review_continuation', 'review_suspended', 'review_in_progress', 'review_backoff', 'circuit_open', 'queue_full', 'queue_timeout', 'context_capacity', 'profile_context_limit'}: reason = ('model_timeout' if 'timeout' in reason else 'model_retrying') if exc.retryable else 'model_unavailable' delay = max(1, min(900, math.ceil(exc.retry_after or 15))) headers={**protocol_header, "X-Review-State": reason, "Retry-After": str(delay)} if latest: state=progress(latest) headers.update({'X-Review-Progress':state['token'],'X-Review-Phase':state['phase'], 'X-Review-Verified':str(state['verified']),'X-Review-Total':str(state['total']), 'X-Review-Read':str(state['read_records']),'X-Review-Source-Total':str(state['source_total'])}) raise HTTPException(503, "人员画像等待继续分析", headers=headers) from exc except (ValueError, TypeError, AttributeError) as exc: logger.warning("personnel_profile_failed type=%s", type(exc).__name__) raise HTTPException(502, "画像结论未通过依据校验,未发布结果", headers={**protocol_header, "X-Review-State": "validation"}) from exc finally: background_review.reset(token) class BidControl(BaseModel): model_config = ConfigDict(extra='forbid') task_id: UUID revision: int = Field(ge=1) paused: bool @router.post('/bid-writing-control') def bid_writing_control(payload: BidControl) -> dict: return bid_queue.control(str(payload.task_id), payload.revision, payload.paused) @router.post("/bid-writing-step") def bid_writing_step(payload: BidStep) -> dict: token = background_review.set(True) try: return bid_queue.submit(payload) except ModelUnavailable as exc: reason = exc.reason if exc.reason in {'review_suspended', 'review_in_progress', 'review_backoff', 'circuit_open', 'queue_full', 'queue_timeout'} else 'model_timeout' if 'timeout' in exc.reason else 'model_unavailable' delay = max(1, min(900, math.ceil(exc.retry_after or 60))) raise HTTPException(503, "标书任务等待自动继续", headers={"X-Review-State": reason, "Retry-After": str(delay)}) from exc except (ValueError, TypeError) as exc: logger.warning("bid_writing_failed action=%s type=%s", payload.action, type(exc).__name__) raise HTTPException(502, "标书结果未通过校验,将自动修订", headers={"X-Review-State": "validation", "Retry-After": "60"}) from exc finally: background_review.reset(token) @router.post("/sales-followup-review") def sales_followup_review(payload: SalesRequest) -> dict: token = background_review.set(True) try: return review_jobs.run(payload.model_dump(), SALES_RULE + ':' + routing_revision(), lambda checkpoint, save: review_sales(payload)) except ModelUnavailable as exc: reason = exc.reason if exc.reason in {'review_suspended', 'review_in_progress', 'review_backoff', 'circuit_open', 'queue_full', 'queue_timeout'} else 'model_timeout' if 'timeout' in exc.reason else 'model_unavailable' raise HTTPException(503, "销售跟进检查暂未完成,请稍后重试", headers={"X-Review-State": reason}) from exc except (ValueError, TypeError, AttributeError) as exc: logger.warning("sales_followup_failed reason=validation type=%s", type(exc).__name__) raise HTTPException(502, "销售跟进结论未通过依据校验,未发布结果", headers={"X-Review-State": "validation"}) from exc finally: background_review.reset(token) @router.post("/management-performance-review") def management_performance_review(payload: PerformanceRequest) -> dict: token = background_review.set(True) try: return review_jobs.run(payload.model_dump(), PERFORMANCE_RULE + ':' + routing_revision(), lambda checkpoint, save: review_performance(payload)) except ModelUnavailable as exc: reason = exc.reason if exc.reason in {'review_suspended', 'review_in_progress', 'review_backoff', 'circuit_open', 'queue_full', 'queue_timeout'} else 'model_timeout' if 'timeout' in exc.reason else 'model_unavailable' logger.warning("management_performance_failed reason=%s", reason) raise HTTPException(503, "绩效智能检查暂未完成,请稍后重试", headers={"X-Review-State": reason}) from exc except ValueError as exc: logger.warning("management_performance_failed reason=validation_%s type=%s", performance_validation_reason(exc), type(exc).__name__) raise HTTPException(502, "绩效分析结论未通过依据校验,未发布结果", headers={"X-Review-State": "validation"}) from exc finally: background_review.reset(token) @router.post("/project-risk-review") def project_risk_review(payload: ProjectRiskRequest) -> dict: token = background_review.set(True) try: return review_jobs.run(payload.model_dump(), PROJECT_RISK_RULE + ':dispatch-v1:' + routing_revision(), lambda checkpoint, save: review_project_risk(payload, checkpoint=checkpoint, save_checkpoint=save)) except ModelUnavailable as exc: logger.warning("project_risk_review_failed reason=%s", exc.reason) reason = exc.reason if exc.reason in {'review_suspended', 'review_in_progress', 'review_backoff', 'circuit_open', 'queue_full', 'queue_timeout'} else 'model_unavailable' raise HTTPException(503, "项目风险分析服务暂不可用", headers={"X-Review-State": reason}) from exc except ValueError as exc: # Log the failure category only; model output can contain business material. reason = validation_reason(exc) logger.warning("project_risk_review_failed reason=%s type=%s", reason, type(exc).__name__) raise HTTPException(502, "项目风险分析结果缺少有效依据", headers={"X-Project-Risk-Failure": reason.split(":", 1)[0]}) from exc finally: background_review.reset(token) @router.post("/project-document-review") def project_document_review(payload: ProjectDocument) -> dict: token = background_review.set(True) try: return review_jobs.run(payload.model_dump(), DOCUMENT_RULE + ':dispatch-v1:' + routing_revision(), lambda checkpoint, save: review_project_document(payload)) except ModelUnavailable as exc: reason = exc.reason if exc.reason in {'review_suspended', 'review_in_progress', 'review_backoff', 'circuit_open', 'queue_full', 'queue_timeout'} else 'model_unavailable' raise HTTPException(503, "文档预审模型暂不可用", headers={"X-Review-State": reason}) from exc except ValueError as exc: raise HTTPException(502, "文档预审结果缺少有效依据", headers={"X-Review-State": "review_suspended"}) from exc finally: background_review.reset(token) @router.get("/review-capabilities") def review_capabilities() -> dict: from app.modules.work_assistant.personnel_talent import PANEL_REVISION, QUALITY_REVISION return {"bid_writing_rule": BID_RULE, "project_risk_rule": PROJECT_RISK_RULE, "document_rule": DOCUMENT_RULE, "performance_rule": PERFORMANCE_RULE, "sales_rule": SALES_RULE, "dispatch_version": 1, "personnel_rule": PERSONNEL_POLICY, "personnel_job_protocol": PERSONNEL_JOB_PROTOCOL, "personnel_annual_assessment": ANNUAL_ASSESSMENT_VERSION, "personnel_talent_revision": PANEL_REVISION, "personnel_history_protocol": 2, "personnel_quality_revision": QUALITY_REVISION, "goal_review_rule": GOAL_RULE, "decomposition_rule": DECOMPOSITION_RULE, "task_review_schema": TASK_REVIEW_SCHEMA, "routing_revision": routing_revision(), "model_dispatch": dispatch.snapshot()} @router.post("/inspection-review") def inspection_review(payload: InspectionRequest) -> dict: token = background_review.set(True) try: return review_inspection(payload) except ModelUnavailable as error: raise HTTPException(503, "工作检查分析暂不可用") from error except ValueError as error: raise HTTPException(422, "工作检查依据核对未通过") from error finally: background_review.reset(token) @router.post("/meeting-work-review") def meeting_work_review(payload: MeetingItem) -> dict: try: return review_meeting(payload) except ValueError as exc: raise HTTPException(502, "会议分析依据不完整,请重试") from exc @router.post("/work-progress-review") def work_progress_review(payload: LogEntry) -> dict: try: return review_progress(payload) except ValueError as exc: raise HTTPException(502, "模型返回的进度分析格式无效,请重试") from exc @router.post("/work-log-review") def work_log_review(payload: LogEntry) -> dict: try: return review_entry(payload) except ValueError as exc: raise HTTPException(502, "模型返回的分析格式或附件引用无效,请重试") from exc @router.post("/plan-review") def plan_review(payload: PlanReviewRequest) -> dict: try: return review_plan(payload) except ValueError: raise HTTPException(422, "整组分析未通过任务或原文校验") @router.post("/goal-review") def goal_review(payload: GoalReviewRequest) -> dict: token = background_review.set(True) try: if not payload.children: return review_goal(payload) return review_jobs.run(payload.model_dump(mode="json", exclude={"as_of"}), GOAL_RULE + ':stages-v1:' + routing_revision(), lambda checkpoint, save: review_goal(payload, checkpoint=checkpoint, save_checkpoint=save), resume_incomplete=lambda result: not result["model_completed"] or any((result.get(key) or {}).get("status") == "incomplete" for key in ("requirements", "commentary"))) except ModelUnavailable: raise HTTPException(503, "目标分析正在等待可用的服务资源,已完成的核对会保留。") except ValueError: raise HTTPException(422, "目标检查的输入依据不完整或关联不一致") finally: background_review.reset(token) @router.post("/decomposition") def decomposition(payload: ReviewRequest) -> dict: token = background_review.set(True) try: return review_decomposition(payload) except ValueError: raise HTTPException(422, "分解检查的输入依据不完整或关联不一致") finally: background_review.reset(token) @router.get("/skills") def skills() -> list[dict]: return [{"id": s.id, "name": s.name, "description": s.description} for s in SKILLS.values()] @router.post("/plan") def plan(payload: PlanRequest) -> dict: result=plan_question(payload) if payload.protocol_version == 1: return result.model_dump(exclude={"question_spec":True,"planner_version":True, "resource_queries":{"__all__":{"query_id","purpose"}}}) return result.model_dump() @router.post("/answer") def answer(payload: AnswerRequest) -> dict: return compose_answer(payload) @router.post("/continue") def continue_query(payload: ContinueRequest) -> dict: result=continue_investigation(payload) if payload.protocol_version == 1: return result.model_dump(exclude={"evidence_gap":True, "resource_queries":{"__all__":{"query_id","purpose"}}}) return result.model_dump()