代码提交

This commit is contained in:
董宏凯 committed 2026-07-15 16:13:03 +08:00
1 parent 27e6b0b23e
commit d7ad0624b7
36 files changed
+2194 -287

No files matched your search

@@ -78,6 +78,8 @@ from app.gateway.routers import (
system_settings,
tags,
task_buttons,
taskcop_tasks,
task_reports,
thread_runs,
tool_metrics,
thread_shares,
@@ -85,6 +87,7 @@ from app.gateway.routers import (
uploads,
user_preferences,
user_prompts,
weknora_sources,
writing,
)
from deerflow.config import app_config as deerflow_app_config
@@ -1329,6 +1332,12 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
cors_origins_env = os.environ.get("GATEWAY_CORS_ORIGINS", "").strip()
cors_origins: list[str] = [o.strip() for o in cors_origins_env.split(",") if o.strip()] if cors_origins_env else []
# The standalone TaskCOP Vue UI is served on a separate Vite dev server and
# calls the Gateway directly via b1ConsumerUrl. Keep these local origins in
# the Gateway policy even when another frontend has set CORS origins.
taskcop_vite_origins = ["http://localhost:8080", "http://127.0.0.1:8080"]
if cors_origins:
cors_origins = list(dict.fromkeys([*cors_origins, *taskcop_vite_origins]))
# Headers the LangGraph SDK / browser clients need to read from cross-origin
# responses. Without exposing them, the SDK's `response.headers.get(...)` returns
@@ -1341,6 +1350,18 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
"X-Thread-Id",
]
# Public pages (e.g. http://47.x.x.x:7010) calling this Gateway on localhost
# trigger Chrome/Edge Private Network Access preflights. Without
# allow_private_network=True the browser reports a generic CORS failure even
# when Access-Control-Allow-Origin is correct.
cors_kwargs = {
"allow_credentials": True,
"allow_methods": ["*"],
"allow_headers": ["*"],
"expose_headers": cors_expose_headers,
"allow_private_network": True,
}
if _cors_allow_any_origin():
logger.warning(
"Permissive CORS enabled ? any Origin is echoed back (GATEWAY_CORS_ALLOW_ALL or "
@@ -1351,10 +1372,7 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
allow_origins=[],
# fullmatch() on the Origin header; browsers send scheme://host[:port]
allow_origin_regex=r".+",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=cors_expose_headers,
**cors_kwargs,
)
elif cors_origins:
if "*" in cors_origins:
@@ -1367,10 +1385,7 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
app.add_middleware(
CORSMiddleware,
allow_origins=cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=cors_expose_headers,
**cors_kwargs,
)
else:
# Safe-by-default fallback for local frontend development. Without any CORS
@@ -1381,6 +1396,7 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
"http://127.0.0.1:5173",
"http://localhost:5174",
"http://127.0.0.1:5174",
*taskcop_vite_origins,
"http://localhost:3000",
"http://127.0.0.1:3000",
]
@@ -1392,10 +1408,7 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
app.add_middleware(
CORSMiddleware,
allow_origins=dev_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=cors_expose_headers,
**cors_kwargs,
)
# Include routers
@@ -1405,6 +1418,9 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
# MCP API is mounted at /api/mcp
app.include_router(mcp.router)
# Authenticated source-context proxy for the WeKnora retrieval skill.
app.include_router(weknora_sources.router)
# Memory API is mounted at /api/memory
app.include_router(memory.router)
@@ -1467,6 +1483,12 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
# Task-workspace configurable jump buttons (按钮管理) at /api/task-buttons
app.include_router(task_buttons.router)
# Temporary compatibility bridge for the TaskCOP situation-overview frontend.
app.include_router(taskcop_tasks.router)
# Task-scoped situation-report details used by dashboard drawing / task gates.
app.include_router(task_reports.router)
# Standalone parallel multi-agent panel: fan-out streaming + saved tasks
app.include_router(parallel_agents.router)
app.include_router(parallel_agent_tasks.router)
@@ -53,7 +53,7 @@ _PUBLIC_EXACT_PATHS: frozenset[str] = frozenset(
"/api/v1/auth/setup-status",
"/api/v1/auth/initialize",
# 并行多智能体面板专用的「绕过常规登录」取 token 端点(内网部署限制了标准登录时用)。
"/api/parallel-agents/auth/token",
"/api/parallel-agents/auth/token",
}
)
@@ -71,7 +71,7 @@ _AUTH_EXEMPT_PATHS: frozenset[str] = frozenset(
"/api/v1/auth/register",
"/api/v1/auth/initialize",
# 并行多智能体面板专用取 token 端点(公共 + CSRF 豁免)。
"/api/parallel-agents/auth/token",
"/api/parallel-agents/auth/token",
}
)
@@ -281,9 +281,17 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
from deerflow.persistence.task_buttons import make_task_button_store
app.state.task_button_store = make_task_button_store(sf)
from deerflow.persistence.parallel_agent_tasks import make_parallel_agent_task_store
app.state.task_button_store = make_task_button_store(sf)
from deerflow.persistence.taskcop_tasks import make_taskcop_task_store
app.state.taskcop_task_store = make_taskcop_task_store(sf)
from deerflow.persistence.task_reports import make_task_report_store
app.state.task_report_store = make_task_report_store(sf)
from deerflow.persistence.parallel_agent_tasks import make_parallel_agent_task_store
app.state.parallel_agent_task_store = make_parallel_agent_task_store(sf)
@@ -0,0 +1,266 @@
"""Task-scoped situation-report detail API.
The report payload intentionally mirrors the existing ``selectSqReport``
Consumer contract:
``{state, msg, data: [{id, taskId, createTime, updateTime, sessionId,
contentJson, categoryType}]}``. ``contentJson`` stays a JSON string so the
dashboard parser can continue to deserialize it category by category.
Routes (all authenticated by the Gateway middleware):
GET /api/task-reports/by-task/{task_id}
POST /api/task-reports/by-task/{task_id}
PUT /api/task-reports/by-task/{task_id}
"""
from __future__ import annotations
import json
from datetime import UTC, datetime
from typing import Any
from uuid import uuid4
from fastapi import APIRouter, Body, HTTPException, Request
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictStr
from app.gateway.deps import get_current_user
from deerflow.persistence.task_reports import TaskReportStore
router = APIRouter(prefix="/api/task-reports", tags=["task-reports"])
class TaskReportRecordInput(BaseModel):
"""One ``data`` entry in the legacy-compatible report envelope."""
model_config = ConfigDict(populate_by_name=True)
id: StrictStr | None = Field(default=None, max_length=128)
task_id: str | int | None = Field(
default=None,
validation_alias=AliasChoices("taskId", "task_id"),
)
create_time: StrictStr | None = Field(
default=None,
validation_alias=AliasChoices("createTime", "create_time"),
)
update_time: StrictStr | None = Field(
default=None,
validation_alias=AliasChoices("updateTime", "update_time"),
)
session_id: StrictStr = Field(
default="",
max_length=255,
validation_alias=AliasChoices("sessionId", "session_id"),
)
content_json: StrictStr = Field(
...,
validation_alias=AliasChoices("contentJson", "content_json"),
)
category_type: StrictStr = Field(
...,
max_length=255,
validation_alias=AliasChoices("categoryType", "category_type"),
)
class TaskReportWriteRequest(BaseModel):
data: list[TaskReportRecordInput] = Field(min_length=1)
class TaskReportRecordResponse(BaseModel):
model_config = ConfigDict(populate_by_name=True)
id: str
task_id: int | str = Field(serialization_alias="taskId")
create_time: str = Field(serialization_alias="createTime")
update_time: str = Field(serialization_alias="updateTime")
session_id: str = Field(serialization_alias="sessionId")
content_json: str = Field(serialization_alias="contentJson")
category_type: str = Field(serialization_alias="categoryType")
class TaskReportResponse(BaseModel):
state: str = "200"
msg: str = "操作成功!"
data: list[TaskReportRecordResponse]
def _get_store(request: Request) -> TaskReportStore:
store = getattr(request.app.state, "task_report_store", None)
if store is None:
raise HTTPException(status_code=503, detail="Task report store not available")
return store
async def _mark_task_analysis_completed(request: Request, task_id: str) -> None:
"""Reflect a non-empty saved report in the TaskCOP task-list status."""
task_store = getattr(request.app.state, "taskcop_task_store", None)
if task_store is not None:
await task_store.mark_analysis_completed(task_id)
def _public_task_id(task_id: str) -> int | str:
"""Keep numeric task ids numeric, matching the supplied mock payload."""
return int(task_id) if task_id.isdecimal() and task_id == str(int(task_id)) else task_id
def _to_response(records: list[dict[str, Any]]) -> TaskReportResponse:
return TaskReportResponse(
data=[
TaskReportRecordResponse(
id=str(record["id"]),
task_id=record["taskId"],
create_time=str(record["createTime"]),
update_time=str(record["updateTime"]),
session_id=str(record["sessionId"]),
content_json=str(record["contentJson"]),
category_type=str(record["categoryType"]),
)
for record in records
]
)
def _normalize_records(
task_id: str,
data: list[TaskReportRecordInput],
previous: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
"""Return the exact public record shape and preserve original create times."""
existing_by_id = {str(item.get("id")): item for item in previous or [] if item.get("id")}
now = datetime.now(UTC).isoformat()
normalized: list[dict[str, Any]] = []
seen_ids: set[str] = set()
for item in data:
if item.task_id is not None and str(item.task_id) != task_id:
raise HTTPException(status_code=422, detail="data.taskId must match the path task id")
record_id = item.id or uuid4().hex
if record_id in seen_ids:
raise HTTPException(status_code=422, detail="data contains duplicate id values")
seen_ids.add(record_id)
before = existing_by_id.get(record_id, {})
normalized.append(
{
"id": record_id,
"taskId": _public_task_id(task_id),
# Importing the supplied mock retains its createTime. On later
# edits, matching ids retain their original createTime.
"createTime": before.get("createTime") or item.create_time or now,
"updateTime": now,
"sessionId": item.session_id,
"contentJson": item.content_json,
"categoryType": item.category_type,
}
)
return normalized
def _import_records(payload: Any, task_id: str) -> list[TaskReportRecordInput]:
"""Read the supplied mock envelope and bind every record to ``task_id``.
Detail files are frequently exported from another task. The import page
deliberately makes the selected task authoritative, so stale taskId values
inside the file cannot write or reject the intended target.
"""
if isinstance(payload, list):
raw_records = payload
elif isinstance(payload, dict):
raw_records = payload.get("data", payload.get("records"))
else:
raw_records = None
if not isinstance(raw_records, list) or not raw_records:
raise HTTPException(status_code=422, detail="详情导入文件必须包含非空的 data 或 records 数组")
records: list[TaskReportRecordInput] = []
for index, raw in enumerate(raw_records, start=1):
if not isinstance(raw, dict):
raise HTTPException(status_code=422, detail=f"第 {index} 条详情数据不是对象")
value = dict(raw)
content_key = "contentJson" if "contentJson" in value else "content_json"
if content_key in value and not isinstance(value[content_key], str):
value[content_key] = json.dumps(value[content_key], ensure_ascii=False, separators=(",", ":"))
# Prefer the public key so AliasChoices resolves this value consistently.
value.pop("task_id", None)
value["taskId"] = task_id
try:
records.append(TaskReportRecordInput.model_validate(value))
except Exception as error:
raise HTTPException(status_code=422, detail=f"第 {index} 条详情数据格式不正确:{error}") from error
return records
@router.get("/by-task/{task_id}", response_model=TaskReportResponse)
async def get_task_report(request: Request, task_id: str) -> TaskReportResponse:
"""Read a task report. Missing reports use the same envelope with ``data: []``."""
row = await _get_store(request).get_by_task(task_id)
return _to_response(row.get("records", []) if row is not None else [])
@router.post("/by-task/{task_id}", response_model=TaskReportResponse)
async def create_task_report(
request: Request,
task_id: str,
body: TaskReportWriteRequest,
) -> TaskReportResponse:
"""Save a task's first report document; reject duplicate initial saves."""
records = _normalize_records(task_id, body.data)
row = await _get_store(request).create_by_task(
task_id,
records,
updated_by=await get_current_user(request),
)
if row is None:
raise HTTPException(status_code=409, detail="Task report already exists; use PUT to modify it")
await _mark_task_analysis_completed(request, task_id)
return _to_response(row["records"])
@router.put("/by-task/{task_id}", response_model=TaskReportResponse)
async def update_task_report(
request: Request,
task_id: str,
body: TaskReportWriteRequest,
) -> TaskReportResponse:
"""Modify a report by atomically replacing its complete ``data`` array."""
store = _get_store(request)
current = await store.get_by_task(task_id)
if current is None:
raise HTTPException(status_code=404, detail="Task report not found; use POST to save it first")
records = _normalize_records(task_id, body.data, current.get("records", []))
row = await store.update_by_task(
task_id,
records,
updated_by=await get_current_user(request),
)
if row is None: # defensive: another process could remove it between read and write
raise HTTPException(status_code=404, detail="Task report not found")
await _mark_task_analysis_completed(request, task_id)
return _to_response(row["records"])
@router.post("/import/by-task/{task_id}", response_model=TaskReportResponse)
async def import_task_report(
request: Request, task_id: str, payload: Any = Body(...)
) -> TaskReportResponse:
"""Import and replace a selected task's complete report document."""
task_id = task_id.strip()
if not task_id:
raise HTTPException(status_code=422, detail="task id is required")
task_store = getattr(request.app.state, "taskcop_task_store", None)
if task_store is not None and await task_store.get_task(task_id) is None:
raise HTTPException(status_code=404, detail="任务不存在,请先导入或创建任务")
store = _get_store(request)
current = await store.get_by_task(task_id)
records = _normalize_records(task_id, _import_records(payload, task_id), current.get("records", []) if current else None)
if current is None:
row = await store.create_by_task(task_id, records, updated_by=await get_current_user(request))
else:
row = await store.update_by_task(task_id, records, updated_by=await get_current_user(request))
if row is None: # defensive: a concurrent delete/import may have won the race
raise HTTPException(status_code=409, detail="详情导入时发生并发冲突,请重试")
await _mark_task_analysis_completed(request, task_id)
return _to_response(row["records"])
@@ -0,0 +1,336 @@
"""Temporary compatibility API for the TaskCOP situation-overview frontend.
The Vue page at ``/situation-overview/action/sentiment`` currently talks to a
legacy Consumer service. These routes retain that service's paths and response
envelopes while persisting data in DeerFlow's own database:
* ``POST /cop/saveSuperiorTask``
* ``GET /taskAnalyseSearch/cop-task-three-list``
* ``GET /taskAnalyseSearch/cop-my-tasks``
* ``GET /taskAnalyseSearch/cop-task-detail``
The separately deployed legacy UI signs in through DeerFlow before calling
these routes. The Gateway authentication middleware therefore supplies the
creator identity, which keeps the "my tasks" endpoint correctly scoped.
"""
from __future__ import annotations
from datetime import datetime
from typing import Annotated, Any
from fastapi import APIRouter, Body, HTTPException, Query, Request
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, ValidationError, field_validator
from deerflow.runtime.user_context import DEFAULT_USER_ID, get_effective_user_id
router = APIRouter(tags=["taskcop-compat"])
class SaveSuperiorTaskRequest(BaseModel):
"""Payload posted by the legacy ``AddTaskDialog`` component."""
model_config = ConfigDict(populate_by_name=True)
issuing_dept: str = Field(default="", validation_alias=AliasChoices("issuingDept", "issuing_dept"))
overview: str = Field(min_length=1, max_length=50_000)
task_direction: str = Field(
default="W方向", validation_alias=AliasChoices("taskDirection", "task_direction"), max_length=64
)
task_end_date: datetime | None = Field(
default=None, validation_alias=AliasChoices("taskEndDate", "task_end_date")
)
task_level: str = Field(
default="1", validation_alias=AliasChoices("taskLevel", "task_level"), max_length=32
)
task_name: str = Field(
min_length=1, max_length=512, validation_alias=AliasChoices("taskName", "task_name")
)
task_no: str = Field(default="", validation_alias=AliasChoices("taskNo", "task_no"), max_length=255)
task_start_date: datetime | None = Field(
default=None, validation_alias=AliasChoices("taskStartDate", "task_start_date")
)
task_status: int = Field(default=0, validation_alias=AliasChoices("taskStatus", "task_status"))
task_superior_flag: int = Field(
default=0, validation_alias=AliasChoices("taskSuperiorFlag", "task_superior_flag")
)
task_type: int = Field(default=1, validation_alias=AliasChoices("taskType", "task_type"))
parent_task_id: str | None = Field(
default=None, validation_alias=AliasChoices("pTaskId", "parent_task_id"), max_length=64
)
class TaskImportRecord(BaseModel):
"""One task accepted by the JSON import page.
Both the legacy ``taskName/taskContent`` keys and the internal snake_case
keys are accepted, so exported task-list files can be uploaded unchanged.
"""
model_config = ConfigDict(populate_by_name=True)
id: str = Field(..., validation_alias=AliasChoices("id", "taskId"), max_length=64)
task_name: str = Field(
..., validation_alias=AliasChoices("taskName", "task_name"), min_length=1, max_length=512
)
overview: str = Field(
default="", validation_alias=AliasChoices("taskContent", "overview"), max_length=50_000
)
issuing_dept: str = Field(default="", validation_alias=AliasChoices("issuingDept", "issuing_dept"))
task_direction: str = Field(
default="W方向", validation_alias=AliasChoices("taskDirection", "task_direction"), max_length=64
)
task_end_date: datetime | None = Field(
default=None, validation_alias=AliasChoices("taskEndDate", "task_end_date")
)
task_level: str = Field(
default="1", validation_alias=AliasChoices("taskLevel", "task_level"), max_length=32
)
task_no: str = Field(default="", validation_alias=AliasChoices("taskNo", "task_no"), max_length=255)
task_start_date: datetime | None = Field(
default=None, validation_alias=AliasChoices("taskStartDate", "task_start_date")
)
task_status: int = Field(default=0, validation_alias=AliasChoices("taskStatus", "task_status"))
task_superior_flag: int = Field(
default=0, validation_alias=AliasChoices("taskSuperiorFlag", "task_superior_flag")
)
task_type: int = Field(default=1, validation_alias=AliasChoices("taskType", "task_type"))
parent_task_id: str | None = Field(
default=None, validation_alias=AliasChoices("pTaskId", "parent_task_id"), max_length=64
)
@field_validator("id", "task_name")
@classmethod
def strip_required_text(cls, value: str) -> str:
value = value.strip()
if not value:
raise ValueError("must not be blank")
return value
def _store(request: Request):
store = getattr(request.app.state, "taskcop_task_store", None)
if store is None:
raise HTTPException(status_code=503, detail="TaskCOP task store not available")
return store
def _request_user_id(request: Request) -> str:
user = getattr(request.state, "user", None)
if user is not None:
return str(user.id)
try:
return get_effective_user_id()
except RuntimeError:
return DEFAULT_USER_ID
def _parse_statuses(task_status: str | None) -> set[int] | None:
if not task_status or not task_status.strip():
return None
try:
return {int(value.strip()) for value in task_status.split(",") if value.strip()}
except ValueError:
# The legacy service treats malformed filters as no filter.
return None
def _bounded_page(page_num: int, page_size: int) -> tuple[int, int]:
return max(page_num, 1), min(max(page_size, 1), 100)
async def _list_tasks(
request: Request,
*,
mine: bool,
content: str,
page_num: int,
page_size: int,
task_status: str | None,
task_direction: str | None,
start_time: datetime | None,
end_time: datetime | None,
) -> dict:
page_num, page_size = _bounded_page(page_num, page_size)
total, records = await _store(request).list_tasks(
created_by=_request_user_id(request) if mine else None,
keyword=content,
task_direction=task_direction,
task_statuses=_parse_statuses(task_status),
start_time=start_time,
end_time=end_time,
page_num=page_num,
page_size=page_size,
)
return {"state": 200, "msg": "查询成功", "data": {"total": total, "records": records}}
TaskListQuery = Annotated[str, Query(max_length=512)]
@router.post("/cop/saveSuperiorTask", status_code=201)
async def save_superior_task(request: Request, body: SaveSuperiorTaskRequest) -> dict:
"""Create a task using the legacy ``{state, msg, data}`` response shape."""
row = await _store(request).create_task(
{
**body.model_dump(),
"task_name": body.task_name.strip(),
"overview": body.overview.strip(),
"created_by": _request_user_id(request),
}
)
return {"state": 201, "msg": "创建任务成功", "data": row}
def _import_task_rows(payload: Any) -> list[Any]:
"""Accept array, ``{tasks: [...]}``, or legacy list-response envelopes."""
if isinstance(payload, list):
rows = payload
elif isinstance(payload, dict):
data = payload.get("tasks", payload.get("records", payload.get("data", payload)))
if isinstance(data, dict):
data = data.get("records", data.get("tasks", data))
rows = data if isinstance(data, list) else [data]
else:
raise HTTPException(status_code=422, detail="任务导入文件必须是 JSON 数组或包含 tasks/records 的对象")
if not rows or not all(isinstance(row, dict) for row in rows):
raise HTTPException(status_code=422, detail="任务导入文件中至少需要一条任务对象")
return rows
@router.post("/api/taskcop/import/tasks")
async def import_tasks(request: Request, payload: Any = Body(...)) -> dict:
"""Import tasks by id; a duplicate id atomically replaces that task."""
rows = _import_task_rows(payload)
created = 0
updated = 0
records: list[dict[str, Any]] = []
for index, raw in enumerate(rows, start=1):
try:
item = TaskImportRecord.model_validate(raw)
except ValidationError as error:
raise HTTPException(
status_code=422,
detail={"message": f"第 {index} 条任务数据格式不正确", "errors": error.errors()},
) from error
record, inserted = await _store(request).upsert_task(
{
**item.model_dump(),
"task_name": item.task_name,
"overview": item.overview,
"created_by": _request_user_id(request),
}
)
records.append(record)
created += int(inserted)
updated += int(not inserted)
return {
"state": 200,
"msg": "任务导入成功",
"data": {"created": created, "updated": updated, "records": records},
}
@router.delete("/cop/tasks/{task_id}")
async def delete_task(request: Request, task_id: str) -> dict:
"""Delete a TaskCOP task and its shared report document."""
task_id = task_id.strip()
if not task_id:
raise HTTPException(status_code=422, detail="task id is required")
task_store = _store(request)
if await task_store.get_task(task_id) is None:
raise HTTPException(status_code=404, detail="task not found")
if not await task_store.delete_task(task_id):
raise HTTPException(status_code=404, detail="task not found")
report_store = getattr(request.app.state, "task_report_store", None)
if report_store is not None:
await report_store.delete_by_task(task_id)
return {"state": 200, "msg": "task deleted", "data": {"id": task_id}}
@router.get("/taskAnalyseSearch/cop-task-three-list")
async def list_task_three(
request: Request,
content: TaskListQuery = "",
pageNum: int = Query(default=1),
pageSize: int = Query(default=10),
taskStatus: str | None = Query(default=None),
taskDirection: str | None = Query(default=None),
startTime: datetime | None = Query(default=None),
endTime: datetime | None = Query(default=None),
) -> dict:
"""List all tasks for the sentiment screen's default "全部" tab."""
return await _list_tasks(
request,
mine=False,
content=content,
page_num=pageNum,
page_size=pageSize,
task_status=taskStatus,
task_direction=taskDirection,
start_time=startTime,
end_time=endTime,
)
@router.get("/taskAnalyseSearch/cop-my-tasks")
async def list_my_tasks(
request: Request,
content: TaskListQuery = "",
pageNum: int = Query(default=1),
pageSize: int = Query(default=10),
taskStatus: str | None = Query(default=None),
taskDirection: str | None = Query(default=None),
startTime: datetime | None = Query(default=None),
endTime: datetime | None = Query(default=None),
) -> dict:
"""List the caller's tasks for the sentiment screen's "我的" tab."""
return await _list_tasks(
request,
mine=True,
content=content,
page_num=pageNum,
page_size=pageSize,
task_status=taskStatus,
task_direction=taskDirection,
start_time=startTime,
end_time=endTime,
)
@router.get("/taskAnalyseSearch/cop-task-list")
async def list_task_analysis(
request: Request,
content: TaskListQuery = "",
pageNum: int = Query(default=1),
pageSize: int = Query(default=10),
taskStatus: str | None = Query(default=None),
taskDirection: str | None = Query(default=None),
startTime: datetime | None = Query(default=None),
endTime: datetime | None = Query(default=None),
) -> dict:
"""Compatibility alias used by the neighbouring task-analysis screen."""
return await _list_tasks(
request,
mine=False,
content=content,
page_num=pageNum,
page_size=pageSize,
task_status=taskStatus,
task_direction=taskDirection,
start_time=startTime,
end_time=endTime,
)
@router.get("/taskAnalyseSearch/cop-task-detail")
async def get_task_detail(request: Request, taskId: str = Query(min_length=1, max_length=64)) -> dict:
"""Return a task selected in the list or opened via a task link."""
row = await _store(request).get_task(taskId)
if row is None:
raise HTTPException(status_code=404, detail="任务不存在")
return {"state": 200, "msg": "查询成功", "data": row}
@@ -0,0 +1,147 @@
"""Authenticated proxy for WeKnora source-context previews.
The browser may ask for the source behind a DeerFlow skill citation, but it
must never receive the narrow WeKnora publication token. This router reads
the same server-side MCP configuration as the retrieval skill and forwards
only an authenticated, read-only context request.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import quote
import httpx
from fastapi import APIRouter, HTTPException, Query
from deerflow.config.extensions_config import get_extensions_config
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/weknora", tags=["weknora"])
_MCP_SERVER_NAME = "weknora-retrieval"
_DEFAULT_TIMEOUT_SECONDS = 15.0
@dataclass(frozen=True)
class WeKnoraConnection:
base_url: str
share_token: str
timeout_seconds: float
def _read_secret_file(path_value: str) -> str:
try:
value = Path(path_value).read_text(encoding="utf-8").strip()
except OSError as exc:
raise RuntimeError("cannot read the WeKnora share-token file") from exc
if not value:
raise RuntimeError("the WeKnora share-token file is empty")
return value
def _connection_from_env(env: dict[str, str]) -> WeKnoraConnection:
base_url = env.get("WEKNORA_BASE_URL", "").strip().rstrip("/")
token_file = env.get("WEKNORA_DEERFLOW_SHARE_TOKEN_FILE", "").strip()
if not base_url:
raise RuntimeError("WEKNORA_BASE_URL is not configured")
if not token_file:
raise RuntimeError("WEKNORA_DEERFLOW_SHARE_TOKEN_FILE is not configured")
try:
timeout_seconds = float(
env.get("WEKNORA_REQUEST_TIMEOUT_SECONDS", _DEFAULT_TIMEOUT_SECONDS),
)
except (TypeError, ValueError) as exc:
raise RuntimeError("invalid WeKnora request timeout") from exc
if not 0 < timeout_seconds <= 60:
raise RuntimeError("invalid WeKnora request timeout")
return WeKnoraConnection(
base_url=base_url,
share_token=_read_secret_file(token_file),
timeout_seconds=timeout_seconds,
)
def load_weknora_connection() -> WeKnoraConnection:
config = get_extensions_config()
server = config.mcp_servers.get(_MCP_SERVER_NAME)
if server is None or not server.enabled:
raise RuntimeError("the WeKnora retrieval integration is not enabled")
return _connection_from_env(server.env)
async def fetch_source_context(
client: httpx.AsyncClient,
connection: WeKnoraConnection,
knowledge_base_id: str,
chunk_id: str,
) -> dict:
"""Fetch one context window and return only the WeKnora response data."""
path = (
"/api/v1/deerflow/knowledge-bases/"
f"{quote(knowledge_base_id, safe='')}/chunks/"
f"{quote(chunk_id, safe='')}/context"
)
response = await client.get(
f"{connection.base_url}{path}",
headers={"X-DeerFlow-Share-Token": connection.share_token},
)
if response.status_code == 404:
raise HTTPException(status_code=404, detail="The original source is no longer available")
if response.status_code >= 400:
raise RuntimeError(f"WeKnora source context returned HTTP {response.status_code}")
try:
payload = response.json()
except ValueError as exc:
raise RuntimeError("WeKnora source context returned invalid JSON") from exc
if not isinstance(payload, dict) or payload.get("success") is not True:
raise RuntimeError("WeKnora source context was rejected")
data = payload.get("data")
if not isinstance(data, dict) or not isinstance(data.get("chunks"), list):
raise RuntimeError("WeKnora source context returned an invalid payload")
return data
@router.get("/source-context", summary="Preview the original context of a WeKnora retrieval hit")
async def get_source_context(
knowledge_base_id: str = Query(..., min_length=1, max_length=128),
chunk_id: str = Query(..., min_length=1, max_length=128),
) -> dict:
"""Return nearby original chunks for a result cited by the WeKnora skill."""
try:
connection = load_weknora_connection()
except RuntimeError:
logger.exception("WeKnora source-context proxy is not configured")
raise HTTPException(
status_code=503,
detail="Original source preview is temporarily unavailable",
) from None
try:
timeout = httpx.Timeout(connection.timeout_seconds)
async with httpx.AsyncClient(timeout=timeout) as client:
data = await fetch_source_context(
client,
connection,
knowledge_base_id,
chunk_id,
)
except HTTPException:
raise
except httpx.HTTPError:
logger.warning("WeKnora source-context request failed", exc_info=True)
raise HTTPException(
status_code=502,
detail="Original source preview is temporarily unavailable",
) from None
except RuntimeError:
logger.warning("WeKnora source-context response was invalid", exc_info=True)
raise HTTPException(
status_code=502,
detail="Original source preview is temporarily unavailable",
) from None
return {"success": True, "data": data}