feat: 深度研究支持独立新报告与原文改写,并完善沙箱、模型管理与全文改写
新报告不再覆盖当前文件卡片,写入时打开沙箱;步骤条仅在改写原文时位于卡片上方。同时补齐改写本地回退、模型管理与会商第三步相关改动。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
11f928bc95
commit
a5a9c952e8
63 files changed
+4113
-929
No files matched your search
@@ -144,6 +144,7 @@ class DocumentRewriteRequest(BaseModel):
|
||||
instruction: str = Field(..., min_length=1, max_length=4_000)
|
||||
style: str | None = Field(default=None)
|
||||
model_name: str | None = Field(default=None, alias="modelName")
|
||||
report_outline: str | None = Field(default=None, alias="reportOutline", max_length=20_000)
|
||||
generate_images: bool = Field(default=False, alias="generateImages")
|
||||
max_generated_images: int = Field(default=2, alias="maxGeneratedImages", ge=1, le=4)
|
||||
expected_hash: str | None = Field(default=None, alias="expectedHash")
|
||||
@@ -172,6 +173,22 @@ def _document_rewrite_key(path: Path) -> str:
|
||||
return os.path.normcase(str(path.resolve()))
|
||||
|
||||
|
||||
def _instruction_with_report_outline(instruction: str, report_outline: str | None) -> str:
|
||||
"""Make an optional report template an explicit constraint for the rewrite model."""
|
||||
normalized_instruction = instruction.strip()
|
||||
normalized_outline = (report_outline or "").strip()
|
||||
if not normalized_outline:
|
||||
return normalized_instruction
|
||||
return "\n\n".join(
|
||||
(
|
||||
normalized_instruction,
|
||||
"【报告结构要求】",
|
||||
"请按以下 Markdown 章节结构重组全文;不适用的章节可以合并或省略,且不得为套用结构编造事实。",
|
||||
normalized_outline,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _reserve_document_rewrite(path: Path) -> bool:
|
||||
"""Reserve a physical document until its SSE generator reaches a terminal state."""
|
||||
key = _document_rewrite_key(path)
|
||||
@@ -213,6 +230,7 @@ def _artifact_job_response(job: dict) -> dict:
|
||||
"instruction": str(snapshot.get("instruction") or ""),
|
||||
"style": str(snapshot.get("style") or "professional"),
|
||||
"modelName": snapshot.get("model_name"),
|
||||
"reportOutline": str(snapshot.get("report_outline") or ""),
|
||||
"generateImages": bool(snapshot.get("generate_images")),
|
||||
"maxGeneratedImages": int(snapshot.get("max_generated_images") or 2),
|
||||
"originalContent": snapshot.get("original_content") or "",
|
||||
@@ -383,6 +401,8 @@ async def start_durable_document_rewrite_job(
|
||||
if job_store is None or dispatcher is None:
|
||||
raise HTTPException(status_code=503, detail="改写任务服务暂不可用。")
|
||||
scope = _artifact_rewrite_scope(body.thread_id, requested_path)
|
||||
report_outline = body.report_outline.strip() if body.report_outline else ""
|
||||
instruction = _instruction_with_report_outline(body.instruction, report_outline)
|
||||
snapshot = {
|
||||
"kind": "artifact_document_rewrite",
|
||||
"session_id": scope,
|
||||
@@ -391,7 +411,8 @@ async def start_durable_document_rewrite_job(
|
||||
"path": requested_path,
|
||||
"original_content": original,
|
||||
"base_hash": base_hash,
|
||||
"instruction": body.instruction.strip(),
|
||||
"instruction": instruction,
|
||||
"report_outline": report_outline,
|
||||
"style": body.style or "professional",
|
||||
"model_name": body.model_name,
|
||||
"generate_images": body.generate_images,
|
||||
@@ -401,7 +422,8 @@ async def start_durable_document_rewrite_job(
|
||||
json.dumps(
|
||||
{
|
||||
"base_hash": base_hash,
|
||||
"instruction": body.instruction.strip(),
|
||||
"instruction": instruction,
|
||||
"report_outline": report_outline,
|
||||
"style": body.style or "professional",
|
||||
"model_name": body.model_name,
|
||||
"generate_images": body.generate_images,
|
||||
@@ -433,13 +455,20 @@ async def start_durable_document_rewrite_job(
|
||||
|
||||
|
||||
@router.get("/document-rewrite/jobs/latest")
|
||||
@require_permission("threads", "read", owner_check=True)
|
||||
@require_permission("threads", "read")
|
||||
async def get_latest_durable_document_rewrite_job(
|
||||
request: Request,
|
||||
thread_id: str = Query(..., min_length=1),
|
||||
path: str = Query(..., min_length=1),
|
||||
) -> dict:
|
||||
"""Hydrate the latest artifact rewrite after a page refresh."""
|
||||
"""Hydrate the current user's latest artifact rewrite after a page refresh.
|
||||
|
||||
The durable-job store is already filtered by ``user_id`` below. Do not
|
||||
additionally perform a thread-owner lookup here: a historical thread can
|
||||
be displayed under a guest/SSO alias even though the current user has no
|
||||
matching ``threads_meta`` owner row, and the redundant check would turn an
|
||||
otherwise safe empty history into a 404.
|
||||
"""
|
||||
user_id = await get_current_user(request)
|
||||
job_store = getattr(request.app.state, "deep_research_job_store", None)
|
||||
if job_store is None:
|
||||
@@ -454,14 +483,20 @@ async def get_latest_durable_document_rewrite_job(
|
||||
|
||||
|
||||
@router.get("/document-rewrite/jobs")
|
||||
@require_permission("threads", "read", owner_check=True)
|
||||
@require_permission("threads", "read")
|
||||
async def list_durable_document_rewrite_jobs(
|
||||
request: Request,
|
||||
thread_id: str = Query(..., min_length=1),
|
||||
path: str = Query(..., min_length=1),
|
||||
limit: int = Query(default=20, ge=1, le=20),
|
||||
) -> dict:
|
||||
"""Return recent persisted rewrite jobs for a single sandbox Markdown file."""
|
||||
"""Return the current user's persisted rewrite jobs for one Markdown file.
|
||||
|
||||
``list_by_session(..., user_id=user_id)`` below is the access boundary for
|
||||
this metadata-only recovery endpoint. It must return an empty list rather
|
||||
than a thread-ownership 404 when a legacy thread's display login differs
|
||||
from its persisted creator identity.
|
||||
"""
|
||||
user_id = await get_current_user(request)
|
||||
job_store = getattr(request.app.state, "deep_research_job_store", None)
|
||||
if job_store is None:
|
||||
@@ -539,6 +574,8 @@ async def rewrite_document(
|
||||
requested_path = body.path.strip()
|
||||
user_id = await get_current_user(request)
|
||||
version_store = getattr(request.app.state, "document_rewrite_version_store", None)
|
||||
report_outline = body.report_outline.strip() if body.report_outline else ""
|
||||
instruction = _instruction_with_report_outline(body.instruction, report_outline)
|
||||
suffix = Path(requested_path).suffix.lower()
|
||||
if suffix not in {".md", ".markdown"}:
|
||||
raise HTTPException(status_code=400, detail="AI 全文改写仅支持 Markdown 文件。")
|
||||
@@ -608,7 +645,7 @@ async def rewrite_document(
|
||||
async for delta in _astream_rewrite_requirements(
|
||||
model,
|
||||
file_name=actual_path.name,
|
||||
instruction=body.instruction.strip(),
|
||||
instruction=instruction,
|
||||
style_instruction=style_instruction,
|
||||
original=original,
|
||||
):
|
||||
@@ -628,7 +665,7 @@ async def rewrite_document(
|
||||
if not requirements_plan:
|
||||
requirements_fallback = True
|
||||
requirements_plan = _build_fallback_rewrite_requirements_plan(
|
||||
instruction=body.instruction.strip(),
|
||||
instruction=instruction,
|
||||
style_instruction=style_instruction,
|
||||
)
|
||||
yield _sse(
|
||||
@@ -640,7 +677,7 @@ async def rewrite_document(
|
||||
HumanMessage(
|
||||
content=(
|
||||
f"文件名:{actual_path.name}\n"
|
||||
f"改写要求:{body.instruction.strip()}\n"
|
||||
f"改写要求:{instruction}\n"
|
||||
f"风格要求:{style_instruction}\n\n"
|
||||
"【已确认的改写执行计划开始】\n"
|
||||
f"{requirements_plan}\n"
|
||||
@@ -654,7 +691,7 @@ async def rewrite_document(
|
||||
yield _sse(
|
||||
"requirements_resolved",
|
||||
{
|
||||
"instruction": body.instruction.strip(),
|
||||
"instruction": instruction,
|
||||
"style": body.style or "professional",
|
||||
"modelName": resolved_name or "system_default",
|
||||
"plan": requirements_plan,
|
||||
@@ -712,7 +749,7 @@ async def rewrite_document(
|
||||
"comparison_ready",
|
||||
build_document_rewrite_summary(
|
||||
source_display_name=actual_path.name,
|
||||
instruction=body.instruction.strip(),
|
||||
instruction=instruction,
|
||||
model_name=resolved_name or "system_default",
|
||||
original=original,
|
||||
rewritten=rewritten,
|
||||
@@ -734,6 +771,7 @@ async def rewrite_document(
|
||||
committed_hash = _content_hash(rewritten)
|
||||
await asyncio.to_thread(_atomic_write_text, actual_path, rewritten)
|
||||
version_id: str | None = None
|
||||
version_snapshot_failed = False
|
||||
if version_store is not None:
|
||||
try:
|
||||
version_id = f"drv_{uuid.uuid4().hex}"
|
||||
@@ -746,40 +784,44 @@ async def rewrite_document(
|
||||
original_content=original,
|
||||
original_hash=base_hash,
|
||||
committed_hash=committed_hash,
|
||||
instruction=body.instruction.strip(),
|
||||
instruction=instruction,
|
||||
model_name=resolved_name,
|
||||
)
|
||||
except Exception:
|
||||
# The file is never left changed without its promised undo
|
||||
# snapshot. Roll back only when nobody touched it in the
|
||||
# short persistence window.
|
||||
current_after_write = await asyncio.to_thread(
|
||||
actual_path.read_text,
|
||||
encoding="utf-8",
|
||||
)
|
||||
if _content_hash(current_after_write) == committed_hash:
|
||||
await asyncio.to_thread(_atomic_write_text, actual_path, original)
|
||||
raise
|
||||
try:
|
||||
await version_store.prune_source(
|
||||
user_id=user_id,
|
||||
source_type="artifact",
|
||||
source_id=body.thread_id,
|
||||
source_path=requested_path,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("could not prune artifact rewrite versions for %s", actual_path)
|
||||
# A version snapshot enables undo but is not allowed to
|
||||
# discard a successfully committed document on failure.
|
||||
logger.exception(
|
||||
"could not persist artifact rewrite version for %s; keeping rewritten file",
|
||||
actual_path,
|
||||
)
|
||||
version_id = None
|
||||
version_snapshot_failed = True
|
||||
else:
|
||||
try:
|
||||
await version_store.prune_source(
|
||||
user_id=user_id,
|
||||
source_type="artifact",
|
||||
source_id=body.thread_id,
|
||||
source_path=requested_path,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("could not prune artifact rewrite versions for %s", actual_path)
|
||||
yield _sse(
|
||||
"committed",
|
||||
{
|
||||
"content": rewritten,
|
||||
"committedHash": committed_hash,
|
||||
"versionId": version_id,
|
||||
"versionSnapshotFailed": version_snapshot_failed,
|
||||
},
|
||||
)
|
||||
yield _sse(
|
||||
"done",
|
||||
{"committedHash": committed_hash, "versionId": version_id},
|
||||
{
|
||||
"committedHash": committed_hash,
|
||||
"versionId": version_id,
|
||||
"versionSnapshotFailed": version_snapshot_failed,
|
||||
},
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
|
||||
Reference in new issue
Block a user