Update local frontend and backend changes

This commit is contained in:
吉鑫升 committed 2026-05-13 17:17:42 +08:00
1 parent faca2c9a2d
commit a27206c543
35 files changed
+1756 -334

No files matched your search

@@ -384,7 +384,7 @@ task(description="Oracle Cloud analysis", prompt="...", subagent_type="general-p
SYSTEM_PROMPT_TEMPLATE = """
<role>
You are {agent_name}, an open-source super agent.
You are {agent_name}, an internal super agent.
</role>
{soul}
@@ -438,21 +438,19 @@ You are {agent_name}, an open-source super agent.
- ❌ DO NOT skip clarification for "efficiency" - accuracy matters more than speed
- ❌ DO NOT make assumptions when information is missing - ALWAYS ask
- ❌ DO NOT proceed with guesses - STOP and call ask_clarification first
- ✅ Analyze the request in thinking → Identify unclear aspects → Ask BEFORE any action
- ✅ If you identify the need for clarification in your thinking, you MUST call the tool IMMEDIATELY
- ✅ After calling ask_clarification, execution will be interrupted automatically
- ✅ Wait for user response - do NOT continue with assumptions
- ✅ When practical, provide 3-4 clear, mutually distinct options so the user can choose quickly
- ✅ Keep options concise and actionable; the user can still provide a custom answer if none fit
- ✅ Analyze the request in thinking → Identify unclear aspects → Ask BEFORE any action
- ✅ If you identify the need for clarification in your thinking, you MUST call the tool IMMEDIATELY
- ✅ After calling ask_clarification, execution will be interrupted automatically
- ✅ Wait for user response - do NOT continue with assumptions
**How to Use:**
```python
ask_clarification(
question="Your specific question here?",
clarification_type="missing_info", # or other type
context="Why you need this information", # optional but recommended
options=["option1", "option2", "option3"] # use 3-4 options when practical
)
ask_clarification(
question="Your specific question here?",
clarification_type="missing_info", # or other type
context="Why you need this information", # optional but recommended
options=["option1", "option2"] # optional, for choices
)
```
**Example:**
@@ -519,10 +517,10 @@ Recent breakthroughs in language models have also accelerated progress
```markdown
## Executive Summary
DeerFlow is an open-source AI agent framework that gained significant traction in early 2026
[citation:GitHub Repository](https://github.com/bytedance/deer-flow). The project focuses on
providing a production-ready agent system with sandbox execution and memory management
[citation:DeerFlow Documentation](https://deer-flow.dev/docs).
LangGraph is an open-source workflow orchestration framework for LLM applications
[citation:LangGraph Repository](https://github.com/langchain-ai/langgraph). The project
focuses on providing stateful multi-agent graphs with built-in checkpointing and streaming
[citation:LangGraph Documentation](https://langchain-ai.github.io/langgraph/).
## Key Analysis
@@ -534,8 +532,8 @@ combined with a FastAPI gateway for REST API access [citation:FastAPI](https://f
## Sources
### Primary Sources
- [GitHub Repository](https://github.com/bytedance/deer-flow) - Official source code and documentation
- [DeerFlow Documentation](https://deer-flow.dev/docs) - Technical specifications
- [LangGraph Repository](https://github.com/langchain-ai/langgraph) - Official source code and documentation
- [LangGraph Documentation](https://langchain-ai.github.io/langgraph/) - Technical specifications
### Media Coverage
- [AI Trends 2026](https://techcrunch.com/ai-trends) - Industry analysis
@@ -547,7 +545,7 @@ combined with a FastAPI gateway for REST API access [citation:FastAPI](https://f
- The `[citation:Title](URL)` format is ONLY for inline citations within the report body
- ❌ WRONG: `GitHub 仓库 - 官方源代码和文档` (no URL!)
- ❌ WRONG in Sources: `[citation:GitHub Repository](url)` (citation prefix is for inline only!)
- ✅ RIGHT in Sources: `[GitHub Repository](https://github.com/bytedance/deer-flow) - 官方源代码和文档`
- ✅ RIGHT in Sources: `[LangGraph Repository](https://github.com/langchain-ai/langgraph) - 官方源代码和文档`
**WORKFLOW for Research Tasks:**
1. Use web_search to find sources → Extract {{title, url, snippet}} from results
@@ -839,7 +837,7 @@ def apply_prompt_template(
# Format the prompt with dynamic skills and memory
prompt = SYSTEM_PROMPT_TEMPLATE.format(
agent_name=agent_name or storage_agent_id or "DeerFlow 2.0",
agent_name=agent_name or storage_agent_id or "CM 助手",
soul=get_agent_soul(storage_agent_id),
skills_section=skills_section,
deferred_tools_section=deferred_tools_section,
@@ -252,6 +252,7 @@ class ScheduledTaskService:
async def get_run(self, user_id: str, run_id: str) -> dict[str, Any] | None:
run = await self.store.get_run(run_id, user_id)
if run is not None:
run["can_edit"] = True
return run
# Subscriber visibility: look up the run unfiltered, then verify the
# caller has a subscription on the parent task.
@@ -260,8 +261,78 @@ class ScheduledTaskService:
return None
if await self.store.get_subscription(candidate["task_id"], user_id) is None:
return None
candidate["can_edit"] = False
return candidate
async def update_run_file(
self,
user_id: str,
run_id: str,
file_index: int,
new_content: str,
) -> dict[str, Any]:
"""Overwrite an archived run file in place. Owner-only.
Returns updated file metadata. Raises:
- PermissionError if the caller is not the run owner (subscribers blocked)
- FileNotFoundError if the run or file index does not exist
- ValueError if the file is not editable (binary / not previewable)
"""
run = await self.store.get_run(run_id, user_id)
if run is None:
# Either the run doesn't exist, or the caller is a subscriber, not owner.
candidate = await self.store.get_run_any(run_id)
if candidate is None:
raise FileNotFoundError(f"Run {run_id} not found")
raise PermissionError("Only the run owner may edit result files")
result = run.get("result") or {}
files = result.get("files") if isinstance(result, dict) else None
if not isinstance(files, list) or file_index < 0 or file_index >= len(files):
raise FileNotFoundError(f"File index {file_index} not found in run {run_id}")
item = files[file_index]
if not isinstance(item, dict) or not isinstance(item.get("path"), str):
raise FileNotFoundError(f"File index {file_index} has no archive path")
archive_path = Path(item["path"])
if not archive_path.exists() or not archive_path.is_file():
raise FileNotFoundError(f"Archived file {archive_path} is no longer available")
# Constrain edits to text-previewable files. We mirror the same rule the
# router uses for previews so binary files cannot be silently corrupted.
suffix = archive_path.suffix.lower()
mime_type = item.get("mime_type")
is_text = (
(isinstance(mime_type, str) and (mime_type.startswith("text/") or mime_type in {"application/json", "application/xml"}))
or suffix in {".md", ".markdown", ".txt", ".json", ".csv", ".xml", ".yaml", ".yml", ".log"}
)
if not is_text:
raise ValueError("Only text-previewable files (markdown, txt, json, etc.) can be edited")
# Make sure we stay inside the per-run archive root before touching disk.
archive_root = (get_paths().base_dir / "scheduled-task-runs" / run_id).resolve()
try:
archive_path.resolve().relative_to(archive_root)
except ValueError as exc:
raise PermissionError("Refusing to edit file outside the run archive") from exc
archive_path.write_text(new_content, encoding="utf-8")
new_size = archive_path.stat().st_size
# Reflect the new size in the run row so subsequent list/preview calls
# report the latest figure. Other fields stay untouched.
files[file_index] = {**item, "size": new_size}
new_result = {**result, "files": files}
await self.store.update_run(run_id, {"result": new_result})
return {
"index": file_index,
"name": item.get("name") or archive_path.name,
"size": new_size,
"mime_type": mime_type,
"kind": item.get("kind"),
}
async def delete_run(self, user_id: str, run_id: str) -> bool:
deleted = await self.store.delete_run(run_id, user_id)
if deleted:
@@ -91,41 +91,48 @@ class LocalSkillStorage(SkillStorage):
tmp_path = Path(tmp_file.name)
tmp_path.replace(target)
async def ainstall_skill_from_archive(self, archive_path: str | Path) -> dict:
def _open_skill_archive(self, archive_path: str | Path, *, require_skill_suffix: bool):
import zipfile
from deerflow.skills.installer import (
SkillAlreadyExistsError,
_move_staged_skill_into_reserved_target,
_scan_skill_archive_contents_or_raise,
resolve_skill_dir_from_archive,
safe_extract_skill_archive,
)
from deerflow.skills.validation import _validate_skill_frontmatter
logger.info("Installing skill from %s", archive_path)
path = Path(archive_path)
if not path.is_file():
if not path.exists():
raise FileNotFoundError(f"Skill file not found: {archive_path}")
raise ValueError(f"Path is not a file: {archive_path}")
if path.suffix != ".skill":
if require_skill_suffix and path.suffix != ".skill":
raise ValueError("File must have .skill extension")
custom_dir = self._host_root / "custom"
custom_dir.mkdir(parents=True, exist_ok=True)
try:
zf = zipfile.ZipFile(path, "r")
except FileNotFoundError:
raise FileNotFoundError(f"Skill file not found: {archive_path}") from None
except (zipfile.BadZipFile, IsADirectoryError):
raise ValueError("File is not a valid ZIP archive") from None
return zf
def validate_skill_archive(self, archive_path: str | Path, *, require_skill_suffix: bool = False) -> dict:
"""Inspect a skill archive WITHOUT installing it.
Returns a dict with ``skill_name``, ``description``, ``license``,
``allowed_tools``, ``conflict`` (bool), ``warnings`` (list[str]).
Raises ``ValueError`` for fatal validation problems (bad zip, bad
frontmatter). The expensive LLM security scan is **not** invoked here.
"""
import re
import yaml
from deerflow.skills.installer import (
resolve_skill_dir_from_archive,
safe_extract_skill_archive,
)
from deerflow.skills.types import SKILL_MD_FILE
from deerflow.skills.validation import _validate_skill_frontmatter
with tempfile.TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
try:
zf = zipfile.ZipFile(path, "r")
except FileNotFoundError:
raise FileNotFoundError(f"Skill file not found: {archive_path}") from None
except (zipfile.BadZipFile, IsADirectoryError):
raise ValueError("File is not a valid ZIP archive") from None
with zf:
with self._open_skill_archive(archive_path, require_skill_suffix=require_skill_suffix) as zf:
safe_extract_skill_archive(zf, tmp_path)
skill_dir = resolve_skill_dir_from_archive(tmp_path)
@@ -136,9 +143,91 @@ class LocalSkillStorage(SkillStorage):
if not skill_name or "/" in skill_name or "\\" in skill_name or ".." in skill_name:
raise ValueError(f"Invalid skill name: {skill_name}")
skill_md_text = (skill_dir / SKILL_MD_FILE).read_text(encoding="utf-8")
frontmatter: dict = {}
match = re.match(r"^---\n(.*?)\n---", skill_md_text, re.DOTALL)
if match:
try:
parsed = yaml.safe_load(match.group(1)) or {}
if isinstance(parsed, dict):
frontmatter = parsed
except yaml.YAMLError:
frontmatter = {}
allowed_tools = frontmatter.get("allowed-tools") or []
if not isinstance(allowed_tools, list):
allowed_tools = [str(allowed_tools)]
else:
allowed_tools = [str(item) for item in allowed_tools]
warnings: list[str] = []
script_files = [
path for path in skill_dir.rglob("*")
if path.is_file() and path.relative_to(skill_dir).parts and path.relative_to(skill_dir).parts[0] == "scripts"
]
if script_files:
warnings.append(f"Archive contains {len(script_files)} script file(s); they will be security-scanned at install time.")
conflict_custom = (self._host_root / SkillCategory.CUSTOM.value / skill_name / SKILL_MD_FILE).exists()
conflict_public = self.public_skill_exists(skill_name)
conflict = conflict_custom or conflict_public
return {
"ok": True,
"skill_name": skill_name,
"description": str(frontmatter.get("description", "")).strip(),
"license": (str(frontmatter["license"]).strip() if frontmatter.get("license") else None),
"allowed_tools": allowed_tools,
"conflict": conflict,
"conflict_kind": ("public" if conflict_public else ("custom" if conflict_custom else None)),
"warnings": warnings,
}
async def ainstall_skill_from_archive(
self,
archive_path: str | Path,
*,
overwrite: bool = False,
require_skill_suffix: bool = True,
) -> dict:
from deerflow.skills.installer import (
SkillAlreadyExistsError,
_move_staged_skill_into_reserved_target,
_scan_skill_archive_contents_or_raise,
resolve_skill_dir_from_archive,
safe_extract_skill_archive,
)
from deerflow.skills.validation import _validate_skill_frontmatter
logger.info("Installing skill from %s (overwrite=%s)", archive_path, overwrite)
custom_dir = self._host_root / "custom"
custom_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
with self._open_skill_archive(archive_path, require_skill_suffix=require_skill_suffix) as zf:
safe_extract_skill_archive(zf, tmp_path)
skill_dir = resolve_skill_dir_from_archive(tmp_path)
is_valid, message, skill_name = _validate_skill_frontmatter(skill_dir)
if not is_valid:
raise ValueError(f"Invalid skill: {message}")
if not skill_name or "/" in skill_name or "\\" in skill_name or ".." in skill_name:
raise ValueError(f"Invalid skill name: {skill_name}")
if self.public_skill_exists(skill_name):
raise SkillAlreadyExistsError(f"Skill '{skill_name}' conflicts with a built-in public skill and cannot be overwritten")
target = custom_dir / skill_name
replaced = False
if target.exists():
raise SkillAlreadyExistsError(f"Skill '{skill_name}' already exists")
if not overwrite:
raise SkillAlreadyExistsError(f"Skill '{skill_name}' already exists")
shutil.rmtree(target)
replaced = True
await _scan_skill_archive_contents_or_raise(skill_dir, skill_name)
@@ -152,6 +241,7 @@ class LocalSkillStorage(SkillStorage):
"success": True,
"skill_name": skill_name,
"message": f"Skill '{skill_name}' installed successfully",
"overwritten": replaced,
}
def delete_custom_skill(self, name: str, *, history_meta: dict | None = None) -> None: