mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-09-20 11:36:17 +00:00
* feat(projects): Projects MVP Phase 2 — instructions, document shelf, promotion, trash Implements docs/superpowers/specs/2026-09-12-projects-mvp-phase2-design.md (issue #5160, tracker #5129) in the slice order of the spec's §16. Slices: - A: ProjectsConfig + write-time 422 UTF-8 byte cap; PROJECT_CONTEXT_KEY admission pinning (both server-owned sets + worker hoist); latest-only request-scoped <project> block via DynamicContextMiddleware wrap_model_call/awrap_model_call (idempotent reassembly, reserved ID prefix + marker + provenance, never persisted); journal audit fingerprints; Instructions tab. - B: ProjectDocumentRow + migration 0023; ProjectDocumentRepository with locked check-and-set; hash-qualified immutable shelf storage with Paths helpers; upload/list/content/delete-to-trash routes; project delete trashes the shelf in-transaction; request-scoped bounded <documents> index with honest count/shown + actionable overflow note; list_project_documents/read_project_document tools registered only on pinned runs; PAT allowlist + drift guards; blocking-IO anchors. - C: shared thread-upload ingestion service (uploads router refactored to parity); POST from-thread with provenance; attach-to-thread with lock-staged copy (archived source allowed); read-only thread-files view with per-group truncation reporting. - D: restore (restored/merged/not_found/no_target/content_missing; no file moves), purge (continuous row lock across unlink/delete/commit, retryable on FS errors), retention sweep (lazy + startup, 24h orphan guard, row-side reconciliation never deletes). - E: Documents tab (shelf + conversation-files browser, provenance, archived banner, content-missing rows), /workspace/trash route, sidebar entry, composer attach handoff, i18n (en-US/zh-CN), e2e mocks + specs. Review hardening folded in (10 rounds, all with tests): - force active shelf content (HTML/XML family) to download; nosniff on artifact + content responses; unified unsandboxed-iframe PDF preview (fixes the pre-existing Chromium sandbox blank in the artifact viewer) - scope document trash to the URL project under the document lock - atomic no-overwrite filename reservation for ALL ingestion (seeded claims + os.link commit with suffix retry; same-name re-upload now unique-names instead of replacing); hidden staging only, no visible placeholders; lease cleanup on setup failure - serialize conversion under the document lock with post-lock active revalidation; drain locked filesystem work on cancellation; preserve bytes when an insert's commit state is uncertain (including trashed rows) - original-integrity checks before serving text or cached conversions; content_missing surfaced in list responses (UI reads the flag, no 409-probe); downloads always serve original bytes - bounded streaming document reads with cached char counts; shelf limits declared in middleware release identity - thread-root confinement for from-thread sources; config fallback rejects fractional/infinite values; composer counts staged attachments; pending attachments persist until submission or removal; in-flight instruction/rename edits survive save refetches; shelf and trash pagination; conversation-file and thread-files pages stay subscribed to refetches Docs: README/README_zh, backend API.md/ARCHITECTURE.md, AGENTS.md contracts, config.example.yaml projects block. Review follow-ups (head b4807477 → this revision): - The trash retention sweep is split so repeated lazy triggers stay bounded: the indexed expiry purge still runs on every trigger (GET /api/trash/documents, POST /api/trash/purge) while the O(all rows + all files) reconciliation is throttled to one run per user per 15 minutes (process-local, per-user window). The startup sweep now runs as a background task instead of blocking gateway readiness, and shutdown awaits it (bounded). - The export scrub (stripInternalMarkers) is fence- and indentation-aware like the render path, so a pasted, fenced <project>/<documents> snippet survives markdown export while real injected blocks (never fenced) are still removed. Fence regexes moved to a dependency-free leaf module to avoid the messages↔streamdown import cycle. - The artifact viewer's PDF iframe no longer carries an added title attribute (the upstream e2e contract locates it via :not([title])), and the upstream artifact-preview spec now pins the new contract: PDFs render unsandboxed, images keep sandbox="". * fix(projects): round-2 review — cancel an overrun trash sweep, restore the PDF frame title - Shutdown cancelled only the shield around the background startup sweep, so an all-users reconciliation that outlived the 5s budget kept walking rows and files while the document repo and DB engine were disposed underneath it. The wait now lives in `_shutdown_startup_trash_sweep`, which cancels the task and drains it before worker exit: the shield keeps the wait bounded, the cancel makes it final (CancelledError lands at the sweep's next await, and `_run_startup_trash_sweep` only catches `Exception`, so nothing swallows it). - The browser-preview iframe lost `title={getFileName(filepath)}` in the previous fix round, leaving the PDF frame without an accessible name while its siblings keep theirs. Restore it (WCAG frame titles), assert it in the DOM test, and anchor the e2e on `iframe[title="report.pdf"]` instead of `iframe:not([title])`. * fix(projects): round-3 review — report the sweep's late finish, not a phantom cancel `Task.cancel()` returns False when the sweep already finished inside the window between the deadline firing and the cancel, so the shutdown log claimed a cancellation that never happened. Branch on that outcome: the warning stays for a real cancel, a late finish is logged at info, and both paths still reap the task before worker exit. * fix(projects): round-4 review — make Empty trash delete what it confirms `POST /api/trash/purge` only ran the retention sweep, and the sweep's candidate selection is age-gated, so a freshly trashed document survived "Empty trash" even though the confirmation promises that every listed document is permanently deleted. With one trashed row the route answered `{"purged": 0}` and left it in place; `GET /api/trash/documents` sweeps expired rows before listing, so the visible rows were normally ineligible for the action by construction. Empty trash now drives `purge_all_trashed`: the caller's trashed rows (`list_all_trashed`, no age filter) each go through the same guarded, row-locked `purge` as the single-document delete — bytes first, then the row, in one transaction — so a row restored mid-flight is skipped instead of force-deleted, and an unlink failure rolls that row back and answers 500 with a retryable message. Retention expiry stays where it was: the sweep's `purge_candidates` is now the only age-gated selection, and the lazy retention sweep still runs on the listing and at startup. Tests: the router suite replaces the retention-gated expectation with the reviewer's repro (fresh row purged, bytes unlinked, shelf and other users' trash untouched, a failing unlink stays retryable and 500); a blocking-I/O anchor drives the new entry point through the offload; the mocked e2e covers the action end to end; a new real-backend spec performs it against the real gateway and re-reads `GET /api/trash/documents`. README, API, ARCHITECTURE and the phase-2 design docs (en+zh) state the age-independent contract.
550 lines
24 KiB
Python
550 lines
24 KiB
Python
import hashlib
|
|
import logging
|
|
import os
|
|
import re
|
|
import shutil
|
|
from pathlib import Path, PureWindowsPath
|
|
|
|
from deerflow.config.runtime_paths import runtime_home
|
|
from deerflow.utils.thread_id import validate_thread_id
|
|
|
|
# Virtual path prefix seen by agents inside the sandbox
|
|
VIRTUAL_PATH_PREFIX = "/mnt/user-data"
|
|
|
|
_SAFE_USER_ID_RE = re.compile(r"^[A-Za-z0-9_\-]+$")
|
|
_SAFE_INTEGRATION_ID_RE = re.compile(r"^[A-Za-z0-9_.\-]+$")
|
|
_UNSAFE_USER_ID_CHAR_RE = re.compile(r"[^A-Za-z0-9_\-]")
|
|
_SAFE_USER_ID_DIGEST_HEX_LEN = 16
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def _default_local_base_dir() -> Path:
|
|
"""Return the caller project's writable DeerFlow state directory."""
|
|
return runtime_home()
|
|
|
|
|
|
def _validate_thread_id(thread_id: str) -> str:
|
|
"""Validate a thread ID before using it in filesystem paths."""
|
|
return validate_thread_id(thread_id)
|
|
|
|
|
|
def _validate_user_id(user_id: str) -> str:
|
|
"""Validate a user ID before using it in filesystem paths."""
|
|
if not _SAFE_USER_ID_RE.match(user_id):
|
|
raise ValueError(f"Invalid user_id {user_id!r}: only alphanumeric characters, hyphens, and underscores are allowed.")
|
|
return user_id
|
|
|
|
|
|
def _validate_integration_id(integration_id: str) -> str:
|
|
"""Validate an integration ID before using it in filesystem paths."""
|
|
if not _SAFE_INTEGRATION_ID_RE.match(integration_id):
|
|
raise ValueError(f"Invalid integration_id {integration_id!r}: only alphanumeric characters, dots, hyphens, and underscores are allowed.")
|
|
# The charset allows dots for names like ``some.integration``; reject the
|
|
# bare ``.``/``..`` path components so a future caller cannot escape the
|
|
# per-integration namespace via ``_join_host_path(..., integration_id, ...)``.
|
|
if integration_id in {".", ".."}:
|
|
raise ValueError(f"Invalid integration_id {integration_id!r}: '.' and '..' are not allowed.")
|
|
return integration_id
|
|
|
|
|
|
def _validate_project_id(project_id: str) -> str:
|
|
"""Validate a project ID before using it in filesystem paths."""
|
|
if not _SAFE_USER_ID_RE.match(project_id):
|
|
raise ValueError(f"Invalid project_id {project_id!r}: only alphanumeric characters, hyphens, and underscores are allowed.")
|
|
return project_id
|
|
|
|
|
|
def make_safe_user_id(raw: str) -> str:
|
|
"""Normalize an external identity into the user-id charset (``[A-Za-z0-9_-]``).
|
|
|
|
IM channel ids (Feishu/Slack/Telegram) may contain characters that
|
|
:func:`_validate_user_id` rejects. Already-safe ids pass through unchanged;
|
|
lossy ones get a short digest suffix so two distinct inputs never share a
|
|
storage bucket.
|
|
"""
|
|
if not raw:
|
|
raise ValueError("user_id must be a non-empty string.")
|
|
sanitized = _UNSAFE_USER_ID_CHAR_RE.sub("-", raw)
|
|
if sanitized == raw:
|
|
return raw
|
|
digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:_SAFE_USER_ID_DIGEST_HEX_LEN]
|
|
return f"{sanitized}-{digest}"
|
|
|
|
|
|
def _legacy_safe_user_id(raw: str, sanitized: str) -> str:
|
|
"""Bucket name produced by the previous (SHA-1) digest revision for ``raw``."""
|
|
digest = hashlib.sha1(raw.encode("utf-8"), usedforsecurity=False).hexdigest()[:_SAFE_USER_ID_DIGEST_HEX_LEN]
|
|
return f"{sanitized}-{digest}"
|
|
|
|
|
|
def _join_host_path(base: str, *parts: str) -> str:
|
|
"""Join host filesystem path segments while preserving native style.
|
|
|
|
Docker Desktop on Windows expects bind mount sources to stay in Windows
|
|
path form (for example ``C:\\repo\\backend\\.deer-flow``). Using
|
|
``Path(base) / ...`` on a POSIX host can accidentally rewrite those paths
|
|
with mixed separators, so this helper preserves the original style.
|
|
"""
|
|
if not parts:
|
|
return base
|
|
|
|
if re.match(r"^[A-Za-z]:[\\/]", base) or base.startswith("\\\\") or "\\" in base:
|
|
result = PureWindowsPath(base)
|
|
for part in parts:
|
|
result /= part
|
|
return str(result)
|
|
|
|
result = Path(base)
|
|
for part in parts:
|
|
result /= part
|
|
return str(result)
|
|
|
|
|
|
def join_host_path(base: str, *parts: str) -> str:
|
|
"""Join host filesystem path segments while preserving native style."""
|
|
return _join_host_path(base, *parts)
|
|
|
|
|
|
class Paths:
|
|
"""
|
|
Centralized path configuration for DeerFlow application data.
|
|
|
|
Directory layout (host side):
|
|
{base_dir}/
|
|
├── memory.json
|
|
├── USER.md <-- global user profile (injected into all agents)
|
|
├── agents/
|
|
│ └── {agent_name}/
|
|
│ ├── config.yaml
|
|
│ ├── SOUL.md <-- agent personality/identity (injected alongside lead prompt)
|
|
│ └── memory.json
|
|
└── threads/
|
|
└── {thread_id}/
|
|
└── user-data/ <-- mounted as /mnt/user-data/ inside sandbox
|
|
├── workspace/ <-- /mnt/user-data/workspace/
|
|
├── uploads/ <-- /mnt/user-data/uploads/
|
|
└── outputs/ <-- /mnt/user-data/outputs/
|
|
|
|
BaseDir resolution (in priority order):
|
|
1. Constructor argument `base_dir`
|
|
2. DEER_FLOW_HOME environment variable
|
|
3. Caller project fallback: `{project_root}/.deer-flow`
|
|
"""
|
|
|
|
def __init__(self, base_dir: str | Path | None = None) -> None:
|
|
self._base_dir = Path(base_dir).resolve() if base_dir is not None else None
|
|
|
|
@property
|
|
def host_base_dir(self) -> Path:
|
|
"""Host-visible base dir for Docker volume mount sources.
|
|
|
|
When running inside Docker with a mounted Docker socket (DooD), the Docker
|
|
daemon runs on the host and resolves mount paths against the host filesystem.
|
|
Set DEER_FLOW_HOST_BASE_DIR to the host-side path that corresponds to this
|
|
container's base_dir so that sandbox container volume mounts work correctly.
|
|
|
|
Falls back to base_dir when the env var is not set (native/local execution).
|
|
"""
|
|
if env := os.getenv("DEER_FLOW_HOST_BASE_DIR"):
|
|
return Path(env)
|
|
return self.base_dir
|
|
|
|
def _host_base_dir_str(self) -> str:
|
|
"""Return the host base dir as a raw string for bind mounts."""
|
|
if env := os.getenv("DEER_FLOW_HOST_BASE_DIR"):
|
|
return env
|
|
return str(self.base_dir)
|
|
|
|
@property
|
|
def base_dir(self) -> Path:
|
|
"""Root directory for all application data."""
|
|
if self._base_dir is not None:
|
|
return self._base_dir
|
|
|
|
if env_home := os.getenv("DEER_FLOW_HOME"):
|
|
return Path(env_home).resolve()
|
|
|
|
return _default_local_base_dir()
|
|
|
|
@property
|
|
def memory_file(self) -> Path:
|
|
"""Path to the persisted memory file: `{base_dir}/memory.json`."""
|
|
return self.base_dir / "memory.json"
|
|
|
|
@property
|
|
def user_md_file(self) -> Path:
|
|
"""Path to the global user profile file: `{base_dir}/USER.md`."""
|
|
return self.base_dir / "USER.md"
|
|
|
|
@property
|
|
def agents_dir(self) -> Path:
|
|
"""Legacy root for shared (pre user-isolation) custom agents: `{base_dir}/agents/`.
|
|
|
|
New code should use :meth:`user_agents_dir` instead. This property remains
|
|
only as a read-side fallback for installations that have not yet run the
|
|
``migrate_user_isolation.py`` script.
|
|
"""
|
|
return self.base_dir / "agents"
|
|
|
|
@property
|
|
def managed_subagents_dir(self) -> Path:
|
|
"""Deployment-level managed subagent definitions.
|
|
|
|
Each definition is stored as its own JSON file so an atomic replace
|
|
never targets a mounted directory or a single shared manifest file.
|
|
"""
|
|
return self.base_dir / "managed-subagents"
|
|
|
|
def managed_subagent_file(self, name: str) -> Path:
|
|
"""Path to one managed subagent definition."""
|
|
return self.managed_subagents_dir / f"{name.lower()}.json"
|
|
|
|
def agent_dir(self, name: str) -> Path:
|
|
"""Legacy per-agent directory (no user isolation): `{base_dir}/agents/{name}/`."""
|
|
return self.agents_dir / name.lower()
|
|
|
|
def agent_memory_file(self, name: str) -> Path:
|
|
"""Legacy per-agent memory file: `{base_dir}/agents/{name}/memory.json`."""
|
|
return self.agent_dir(name) / "memory.json"
|
|
|
|
def user_dir(self, user_id: str) -> Path:
|
|
"""Directory for a specific user: `{base_dir}/users/{user_id}/`."""
|
|
return self.base_dir / "users" / _validate_user_id(user_id)
|
|
|
|
def prepare_user_dir_for_raw_id(self, raw_user_id: str) -> str:
|
|
"""Return the safe user ID and migrate this ID's legacy unsafe-id bucket.
|
|
|
|
A previous branch revision used SHA-1 for unsafe external user IDs.
|
|
New IDs use SHA-256; the legacy bucket name is recomputed from the same
|
|
raw ID, so only this user's own old bucket can ever be moved — a
|
|
different raw ID sharing the sanitized prefix produces a different
|
|
legacy digest and is never touched.
|
|
"""
|
|
safe_user_id = make_safe_user_id(raw_user_id)
|
|
sanitized = _UNSAFE_USER_ID_CHAR_RE.sub("-", raw_user_id)
|
|
if safe_user_id == raw_user_id:
|
|
return safe_user_id
|
|
|
|
users_dir = self.base_dir / "users"
|
|
target_dir = users_dir / safe_user_id
|
|
legacy_dir = users_dir / _legacy_safe_user_id(raw_user_id, sanitized)
|
|
try:
|
|
if target_dir.exists() or not legacy_dir.is_dir():
|
|
return safe_user_id
|
|
legacy_dir.rename(target_dir)
|
|
logger.info("Migrated legacy unsafe-id user directory to the current digest format")
|
|
except OSError:
|
|
logger.exception("Failed to migrate legacy unsafe-id user directory")
|
|
return safe_user_id
|
|
|
|
def user_memory_file(self, user_id: str) -> Path:
|
|
"""Per-user memory file: `{base_dir}/users/{user_id}/memory.json`."""
|
|
return self.user_dir(user_id) / "memory.json"
|
|
|
|
def user_agents_dir(self, user_id: str) -> Path:
|
|
"""Per-user root for that user's custom agents: `{base_dir}/users/{user_id}/agents/`."""
|
|
return self.user_dir(user_id) / "agents"
|
|
|
|
def user_agent_dir(self, user_id: str, agent_name: str) -> Path:
|
|
"""Per-user per-agent directory: `{base_dir}/users/{user_id}/agents/{name}/`."""
|
|
return self.user_agents_dir(user_id) / agent_name.lower()
|
|
|
|
def user_agent_memory_file(self, user_id: str, agent_name: str) -> Path:
|
|
"""Per-user per-agent memory: `{base_dir}/users/{user_id}/agents/{name}/memory.json`."""
|
|
return self.user_agent_dir(user_id, agent_name) / "memory.json"
|
|
|
|
def user_skills_dir(self, user_id: str) -> Path:
|
|
"""Per-user root for that user's custom skills: `{base_dir}/users/{user_id}/skills/`."""
|
|
return self.user_dir(user_id) / "skills"
|
|
|
|
def user_custom_skills_dir(self, user_id: str) -> Path:
|
|
"""Per-user custom skills directory: `{base_dir}/users/{user_id}/skills/custom/`.
|
|
|
|
This is the user-scoped replacement for the global ``{base_dir}/skills/custom/``
|
|
directory. Custom skills are written here; public skills remain under the
|
|
global ``{base_dir}/skills/public/`` (read-only).
|
|
"""
|
|
return self.user_skills_dir(user_id) / "custom"
|
|
|
|
def integration_skills_dir(self) -> Path:
|
|
"""Globally installed managed integration skills.
|
|
|
|
Layout: ``{base_dir}/integrations/skills/{provider}/{skill}/``. The
|
|
package contents are shared and read-only; credentials and enabled
|
|
state remain user-scoped elsewhere under ``users/{user_id}``.
|
|
"""
|
|
return self.base_dir / "integrations" / "skills"
|
|
|
|
@property
|
|
def skills_view_dir(self) -> Path:
|
|
"""Global sandbox-visible skills projection: ``{base_dir}/skills_view/``."""
|
|
return self.base_dir / "skills_view"
|
|
|
|
@property
|
|
def public_skills_view_dir(self) -> Path:
|
|
"""Enabled public skills exposed to sandboxes."""
|
|
return self.skills_view_dir / "public"
|
|
|
|
def user_skills_view_dir(self, user_id: str) -> Path:
|
|
"""Per-user sandbox-visible skills projection root."""
|
|
return self.user_dir(user_id) / "skills_view"
|
|
|
|
def user_custom_skills_view_dir(self, user_id: str) -> Path:
|
|
"""Enabled custom skills exposed to one user's sandboxes."""
|
|
return self.user_skills_view_dir(user_id) / "custom"
|
|
|
|
def user_legacy_skills_view_dir(self, user_id: str) -> Path:
|
|
"""Enabled legacy skills exposed to one user's sandboxes."""
|
|
return self.user_skills_view_dir(user_id) / "legacy"
|
|
|
|
def user_integration_skills_view_dir(self, user_id: str) -> Path:
|
|
"""Enabled managed integration skills exposed to one user's sandboxes."""
|
|
return self.user_skills_view_dir(user_id) / "integrations"
|
|
|
|
def thread_skills_view_dir(self, thread_id: str, *, user_id: str) -> Path:
|
|
"""Sandbox-visible skill projection scoped to one user/thread.
|
|
|
|
The directory lives below the thread root so ordinary thread deletion
|
|
also removes its policy projection.
|
|
"""
|
|
return self.thread_dir(thread_id, user_id=user_id) / "skills_view"
|
|
|
|
def host_thread_skills_view_dir(self, thread_id: str, *, user_id: str) -> str:
|
|
"""Host path for a thread-scoped skill projection."""
|
|
return _join_host_path(self.host_thread_dir(thread_id, user_id=user_id), "skills_view")
|
|
|
|
def thread_dir(self, thread_id: str, *, user_id: str | None = None) -> Path:
|
|
"""
|
|
Host path for a thread's data.
|
|
|
|
When *user_id* is provided:
|
|
`{base_dir}/users/{user_id}/threads/{thread_id}/`
|
|
Otherwise (legacy layout):
|
|
`{base_dir}/threads/{thread_id}/`
|
|
|
|
This directory contains a `user-data/` subdirectory that is mounted
|
|
as `/mnt/user-data/` inside the sandbox.
|
|
|
|
Raises:
|
|
ValueError: If `thread_id` or `user_id` contains unsafe characters (path
|
|
separators or `..`) that could cause directory traversal.
|
|
"""
|
|
if user_id is not None:
|
|
return self.user_dir(user_id) / "threads" / _validate_thread_id(thread_id)
|
|
return self.base_dir / "threads" / _validate_thread_id(thread_id)
|
|
|
|
def sandbox_work_dir(self, thread_id: str, *, user_id: str | None = None) -> Path:
|
|
"""
|
|
Host path for the agent's workspace directory.
|
|
Host: `{base_dir}/threads/{thread_id}/user-data/workspace/`
|
|
Sandbox: `/mnt/user-data/workspace/`
|
|
"""
|
|
return self.thread_dir(thread_id, user_id=user_id) / "user-data" / "workspace"
|
|
|
|
def sandbox_uploads_dir(self, thread_id: str, *, user_id: str | None = None) -> Path:
|
|
"""
|
|
Host path for user-uploaded files.
|
|
Host: `{base_dir}/threads/{thread_id}/user-data/uploads/`
|
|
Sandbox: `/mnt/user-data/uploads/`
|
|
"""
|
|
return self.thread_dir(thread_id, user_id=user_id) / "user-data" / "uploads"
|
|
|
|
def sandbox_outputs_dir(self, thread_id: str, *, user_id: str | None = None) -> Path:
|
|
"""
|
|
Host path for agent-generated artifacts.
|
|
Host: `{base_dir}/threads/{thread_id}/user-data/outputs/`
|
|
Sandbox: `/mnt/user-data/outputs/`
|
|
"""
|
|
return self.thread_dir(thread_id, user_id=user_id) / "user-data" / "outputs"
|
|
|
|
def user_projects_dir(self, user_id: str) -> Path:
|
|
"""Host path root for one user's project shelves: ``users/{user_id}/projects/``."""
|
|
return self.user_dir(user_id) / "projects"
|
|
|
|
def user_project_dir(self, user_id: str, project_id: str) -> Path:
|
|
"""Host path for one project: ``users/{user_id}/projects/{project_id}/``."""
|
|
return self.user_projects_dir(user_id) / _validate_project_id(project_id)
|
|
|
|
def project_documents_dir(self, user_id: str, project_id: str) -> Path:
|
|
"""Host path for a project's document shelf.
|
|
|
|
Layout (Phase-2 spec §6.2): ``.staging/{uuid}`` for in-flight bytes,
|
|
then one exclusive namespace per row at
|
|
``{sha256[:2]}/{sha256}/{document_id}/original/{name}`` with an
|
|
optional ``derived/converted.md`` companion.
|
|
"""
|
|
return self.user_project_dir(user_id, project_id) / "documents"
|
|
|
|
def project_document_path(self, user_id: str, relpath: str) -> Path:
|
|
"""Resolve a shelf ``stored_relpath`` to its absolute host path.
|
|
|
|
``stored_relpath`` is stored relative to ``users/{user_id}/projects/``
|
|
(it begins with ``{project_id}/documents/``) so a restore can re-point
|
|
a row without moving bytes. Resolution mirrors
|
|
:meth:`resolve_virtual_path`: join under the user projects root,
|
|
resolve, then re-check confinement — a relpath that escapes the root
|
|
is rejected. Relpaths only ever come from server-generated content
|
|
addresses, never from request text (§12).
|
|
"""
|
|
base = self.user_projects_dir(user_id).resolve()
|
|
actual = (base / relpath).resolve()
|
|
try:
|
|
actual.relative_to(base)
|
|
except ValueError:
|
|
raise ValueError("Access denied: path traversal detected") from None
|
|
return actual
|
|
|
|
def acp_workspace_dir(self, thread_id: str, *, user_id: str | None = None) -> Path:
|
|
"""
|
|
Host path for the ACP workspace of a specific thread.
|
|
Host: `{base_dir}/threads/{thread_id}/acp-workspace/`
|
|
Sandbox: `/mnt/acp-workspace/`
|
|
|
|
Each thread gets its own isolated ACP workspace so that concurrent
|
|
sessions cannot read each other's ACP agent outputs.
|
|
"""
|
|
return self.thread_dir(thread_id, user_id=user_id) / "acp-workspace"
|
|
|
|
def sandbox_user_data_dir(self, thread_id: str, *, user_id: str | None = None) -> Path:
|
|
"""
|
|
Host path for the user-data root.
|
|
Host: `{base_dir}/threads/{thread_id}/user-data/`
|
|
Sandbox: `/mnt/user-data/`
|
|
"""
|
|
return self.thread_dir(thread_id, user_id=user_id) / "user-data"
|
|
|
|
def host_thread_dir(self, thread_id: str, *, user_id: str | None = None) -> str:
|
|
"""Host path for a thread directory, preserving Windows path syntax."""
|
|
if user_id is not None:
|
|
return _join_host_path(self._host_base_dir_str(), "users", _validate_user_id(user_id), "threads", _validate_thread_id(thread_id))
|
|
return _join_host_path(self._host_base_dir_str(), "threads", _validate_thread_id(thread_id))
|
|
|
|
def host_sandbox_user_data_dir(self, thread_id: str, *, user_id: str | None = None) -> str:
|
|
"""Host path for a thread's user-data root."""
|
|
return _join_host_path(self.host_thread_dir(thread_id, user_id=user_id), "user-data")
|
|
|
|
def host_sandbox_work_dir(self, thread_id: str, *, user_id: str | None = None) -> str:
|
|
"""Host path for the workspace mount source."""
|
|
return _join_host_path(self.host_sandbox_user_data_dir(thread_id, user_id=user_id), "workspace")
|
|
|
|
def host_sandbox_uploads_dir(self, thread_id: str, *, user_id: str | None = None) -> str:
|
|
"""Host path for the uploads mount source."""
|
|
return _join_host_path(self.host_sandbox_user_data_dir(thread_id, user_id=user_id), "uploads")
|
|
|
|
def host_sandbox_outputs_dir(self, thread_id: str, *, user_id: str | None = None) -> str:
|
|
"""Host path for the outputs mount source."""
|
|
return _join_host_path(self.host_sandbox_user_data_dir(thread_id, user_id=user_id), "outputs")
|
|
|
|
def host_acp_workspace_dir(self, thread_id: str, *, user_id: str | None = None) -> str:
|
|
"""Host path for the ACP workspace mount source."""
|
|
return _join_host_path(self.host_thread_dir(thread_id, user_id=user_id), "acp-workspace")
|
|
|
|
def host_user_custom_skills_dir(self, user_id: str) -> str:
|
|
"""Host path for a user's custom skills directory, preserving Windows path syntax."""
|
|
return _join_host_path(self._host_base_dir_str(), "users", _validate_user_id(user_id), "skills", "custom")
|
|
|
|
def host_integration_skills_dir(self) -> str:
|
|
"""Host path for globally installed managed integration skills."""
|
|
return _join_host_path(self._host_base_dir_str(), "integrations", "skills")
|
|
|
|
def host_user_integration_config_dir(self, user_id: str, integration_id: str) -> str:
|
|
"""Host path for a user's managed integration runtime config directory."""
|
|
return _join_host_path(self._host_base_dir_str(), "users", _validate_user_id(user_id), "integrations", _validate_integration_id(integration_id), "config")
|
|
|
|
def host_user_integration_data_dir(self, user_id: str, integration_id: str) -> str:
|
|
"""Host path for a user's managed integration runtime data directory."""
|
|
return _join_host_path(self._host_base_dir_str(), "users", _validate_user_id(user_id), "integrations", _validate_integration_id(integration_id), "data")
|
|
|
|
def ensure_thread_dirs(self, thread_id: str, *, user_id: str | None = None) -> None:
|
|
"""Create all standard sandbox directories for a thread.
|
|
|
|
Directories are created with mode 0o777 so that sandbox containers
|
|
(which may run as a different UID than the host backend process) can
|
|
write to the volume-mounted paths without "Permission denied" errors.
|
|
The explicit chmod() call is necessary because Path.mkdir(mode=...) is
|
|
subject to the process umask and may not yield the intended permissions.
|
|
|
|
Includes the ACP workspace directory so it can be volume-mounted into
|
|
the sandbox container at ``/mnt/acp-workspace`` even before the first
|
|
ACP agent invocation.
|
|
"""
|
|
for d in [
|
|
self.sandbox_work_dir(thread_id, user_id=user_id),
|
|
self.sandbox_uploads_dir(thread_id, user_id=user_id),
|
|
self.sandbox_outputs_dir(thread_id, user_id=user_id),
|
|
self.acp_workspace_dir(thread_id, user_id=user_id),
|
|
]:
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
d.chmod(0o777)
|
|
|
|
def delete_thread_dir(self, thread_id: str, *, user_id: str | None = None) -> None:
|
|
"""Delete all persisted data for a thread.
|
|
|
|
The operation is idempotent: missing thread directories are ignored.
|
|
"""
|
|
thread_dir = self.thread_dir(thread_id, user_id=user_id)
|
|
if thread_dir.exists():
|
|
shutil.rmtree(thread_dir)
|
|
|
|
def resolve_virtual_path(self, thread_id: str, virtual_path: str, *, user_id: str | None = None) -> Path:
|
|
"""Resolve a sandbox virtual path to the actual host filesystem path.
|
|
|
|
Args:
|
|
thread_id: The thread ID.
|
|
virtual_path: Virtual path as seen inside the sandbox, e.g.
|
|
``/mnt/user-data/outputs/report.pdf``.
|
|
Leading slashes are stripped before matching.
|
|
user_id: Optional user ID for user-scoped path resolution.
|
|
|
|
Returns:
|
|
The resolved absolute host filesystem path.
|
|
|
|
Raises:
|
|
ValueError: If the path does not start with the expected virtual
|
|
prefix or a path-traversal attempt is detected.
|
|
"""
|
|
stripped = virtual_path.lstrip("/")
|
|
prefix = VIRTUAL_PATH_PREFIX.lstrip("/")
|
|
|
|
# Require an exact segment-boundary match to avoid prefix confusion
|
|
# (e.g. reject paths like "mnt/user-dataX/...").
|
|
if stripped != prefix and not stripped.startswith(prefix + "/"):
|
|
raise ValueError(f"Path must start with /{prefix}")
|
|
|
|
relative = stripped[len(prefix) :].lstrip("/")
|
|
base = self.sandbox_user_data_dir(thread_id, user_id=user_id).resolve()
|
|
actual = (base / relative).resolve()
|
|
|
|
try:
|
|
actual.relative_to(base)
|
|
except ValueError:
|
|
raise ValueError("Access denied: path traversal detected")
|
|
|
|
return actual
|
|
|
|
|
|
# ── Singleton ────────────────────────────────────────────────────────────
|
|
|
|
_paths: Paths | None = None
|
|
|
|
|
|
def get_paths() -> Paths:
|
|
"""Return the global Paths singleton (lazy-initialized)."""
|
|
global _paths
|
|
if _paths is None:
|
|
_paths = Paths()
|
|
return _paths
|
|
|
|
|
|
def resolve_path(path: str) -> Path:
|
|
"""Resolve *path* to an absolute ``Path``.
|
|
|
|
Relative paths are resolved relative to the application base directory.
|
|
Absolute paths are returned as-is (after normalisation).
|
|
"""
|
|
p = Path(path)
|
|
if not p.is_absolute():
|
|
p = get_paths().base_dir / path
|
|
return p.resolve()
|