sync update from LAN repo (source dhk-1 @ 3e87be55)
This commit is contained in:
1 parent
ab6068a7c1
commit
42f2a26fa8
1482 files changed
+227759
-9584
No files matched your search
@@ -0,0 +1,173 @@
|
||||
"""Task-detail API for externally initiated single-agent deep links.
|
||||
|
||||
The detail snapshot is deliberately owned by DeerFlow. The embedding system
|
||||
writes it once, then the browser only reads it after login; no frontend call is
|
||||
made back to the embedding system for task content.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Path, Request
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from app.gateway.deps import get_task_deeplink_detail_store
|
||||
|
||||
router = APIRouter(prefix="/api/task-deeplink-details", tags=["task-deeplink-details"])
|
||||
|
||||
_B5_DETAIL_TYPE = "b5-1"
|
||||
_MAX_EXTRA_BYTES = 64 * 1024
|
||||
|
||||
|
||||
class TaskDeeplinkDetailUpsertRequest(BaseModel):
|
||||
"""Complete task snapshot supplied by the embedding system.
|
||||
|
||||
``extra`` is intentionally an object, not a bag of top-level fields, so
|
||||
the stable contract stays small while integrators can attach their own
|
||||
structured fields.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
task_name: str = Field(
|
||||
min_length=1,
|
||||
max_length=512,
|
||||
validation_alias=AliasChoices("taskName", "task_name"),
|
||||
)
|
||||
task_content: str = Field(
|
||||
min_length=1,
|
||||
max_length=20_000,
|
||||
validation_alias=AliasChoices("taskContent", "task_content"),
|
||||
)
|
||||
overview: str = Field(default="", max_length=4_000)
|
||||
extra: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
@field_validator("task_name", "task_content", "overview")
|
||||
@classmethod
|
||||
def strip_text(cls, value: str) -> str:
|
||||
return value.strip()
|
||||
|
||||
@field_validator("task_name", "task_content")
|
||||
@classmethod
|
||||
def require_nonblank_text(cls, value: str) -> str:
|
||||
if not value:
|
||||
raise ValueError("text must not be blank")
|
||||
return value
|
||||
|
||||
@field_validator("extra")
|
||||
@classmethod
|
||||
def require_bounded_json_object(cls, value: dict[str, Any]) -> dict[str, Any]:
|
||||
try:
|
||||
encoded = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("extra must be JSON serializable") from exc
|
||||
if len(encoded.encode("utf-8")) > _MAX_EXTRA_BYTES:
|
||||
raise ValueError(f"extra must not exceed {_MAX_EXTRA_BYTES} bytes")
|
||||
return value
|
||||
|
||||
|
||||
class TaskDeeplinkDetailResponse(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
detail_type: Literal["b5-1"] = Field(serialization_alias="type")
|
||||
detail_id: str = Field(serialization_alias="id")
|
||||
task_name: str = Field(serialization_alias="taskName")
|
||||
task_content: str = Field(serialization_alias="taskContent")
|
||||
overview: str = ""
|
||||
extra: dict[str, Any] = Field(default_factory=dict)
|
||||
version: int
|
||||
updated_at: str | None = Field(default=None, serialization_alias="updatedAt")
|
||||
|
||||
|
||||
class TaskDeeplinkDetailEnvelope(BaseModel):
|
||||
data: TaskDeeplinkDetailResponse
|
||||
|
||||
|
||||
class TaskDeeplinkDetailUpsertEnvelope(TaskDeeplinkDetailEnvelope):
|
||||
created: bool
|
||||
changed: bool
|
||||
|
||||
|
||||
def _detail_response(row: dict[str, Any]) -> TaskDeeplinkDetailResponse:
|
||||
return TaskDeeplinkDetailResponse(
|
||||
detail_type=row["detail_type"],
|
||||
detail_id=row["detail_id"],
|
||||
task_name=row["task_name"],
|
||||
task_content=row["task_content"],
|
||||
overview=row.get("overview") or "",
|
||||
extra=row.get("extra") or {},
|
||||
version=int(row.get("version") or 1),
|
||||
updated_at=str(row["updated_at"]) if row.get("updated_at") else None,
|
||||
)
|
||||
|
||||
|
||||
def _normalized_detail_id(detail_id: str) -> str:
|
||||
normalized = detail_id.strip()
|
||||
if not normalized:
|
||||
raise HTTPException(status_code=422, detail="detail id must not be blank")
|
||||
return normalized
|
||||
|
||||
|
||||
def _is_administrator(request: Request) -> bool:
|
||||
"""The external integration key is checked by AuthMiddleware.
|
||||
|
||||
Browser-authenticated writes stay available to administrators for support
|
||||
and testing, but ordinary users can only read the detail after login.
|
||||
"""
|
||||
|
||||
if getattr(request.state, "task_deeplink_external_writer", False):
|
||||
return True
|
||||
user = getattr(request.state, "user", None)
|
||||
return user is None or getattr(user, "system_role", None) == "admin"
|
||||
|
||||
|
||||
def _writer_id(request: Request) -> str:
|
||||
if getattr(request.state, "task_deeplink_external_writer", False):
|
||||
return "external:task-deeplink"
|
||||
user = getattr(request.state, "user", None)
|
||||
return str(getattr(user, "id", "system"))
|
||||
|
||||
|
||||
@router.get("/{detail_type}/{detail_id}", response_model=TaskDeeplinkDetailEnvelope)
|
||||
async def get_task_deeplink_detail(
|
||||
request: Request,
|
||||
detail_type: Literal["b5-1"],
|
||||
detail_id: str = Path(min_length=1, max_length=128),
|
||||
) -> TaskDeeplinkDetailEnvelope:
|
||||
"""Read one persisted snapshot for a post-login deep-link workspace."""
|
||||
|
||||
store = get_task_deeplink_detail_store(request)
|
||||
row = await store.get_detail(detail_type, _normalized_detail_id(detail_id))
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Task deep-link detail not found")
|
||||
return TaskDeeplinkDetailEnvelope(data=_detail_response(row))
|
||||
|
||||
|
||||
@router.put("/{detail_type}/{detail_id}", response_model=TaskDeeplinkDetailUpsertEnvelope)
|
||||
async def upsert_task_deeplink_detail(
|
||||
request: Request,
|
||||
body: TaskDeeplinkDetailUpsertRequest,
|
||||
detail_type: Literal["b5-1"],
|
||||
detail_id: str = Path(min_length=1, max_length=128),
|
||||
) -> TaskDeeplinkDetailUpsertEnvelope:
|
||||
"""Idempotently create or update a snapshot before ``goPath=b5-1``."""
|
||||
|
||||
if not _is_administrator(request):
|
||||
raise HTTPException(status_code=403, detail="Only administrators may write task deep-link details")
|
||||
store = get_task_deeplink_detail_store(request)
|
||||
row, created, changed = await store.upsert_detail(
|
||||
detail_type,
|
||||
_normalized_detail_id(detail_id),
|
||||
task_name=body.task_name,
|
||||
task_content=body.task_content,
|
||||
overview=body.overview,
|
||||
extra=body.extra,
|
||||
updated_by=_writer_id(request),
|
||||
)
|
||||
return TaskDeeplinkDetailUpsertEnvelope(
|
||||
data=_detail_response(row),
|
||||
created=created,
|
||||
changed=changed,
|
||||
)
|
||||
Reference in new issue
Block a user