mirror of
https://github.com/langgenius/dify.git
synced 2026-10-04 13:47:55 +08:00
refactor(dify-agent): download Binding files through Agent Stub (#40143)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
c094117ca2
commit
916d7e1c96
71 files changed
+4692
-2484
No files matched your search
@@ -31,9 +31,9 @@ from dify_agent.server.observability import configure_server_observability
|
||||
from dify_agent.server.routes.runs import create_runs_router
|
||||
from dify_agent.server.routes.execution_bindings import create_execution_bindings_router
|
||||
from dify_agent.server.routes.home_snapshots import create_home_snapshots_router
|
||||
from dify_agent.server.routes.workspace_files import create_workspace_files_router
|
||||
from dify_agent.server.routes.binding_files import create_binding_files_router
|
||||
from dify_agent.server.execution_bindings import ExecutionBindingService
|
||||
from dify_agent.server.workspace_files import AgentStubWorkspaceFileUploader, WorkspaceFileService
|
||||
from dify_agent.server.binding_files import BindingFileService
|
||||
from dify_agent.server.home_snapshots import HomeSnapshotService
|
||||
from dify_agent.server.settings import ServerSettings
|
||||
from dify_agent.storage.redis_run_store import RedisRunStore
|
||||
@@ -72,15 +72,11 @@ def create_app(settings: ServerSettings | None = None) -> FastAPI:
|
||||
agent_stub_api_base_url=resolved_settings.agent_stub_api_base_url,
|
||||
agent_stub_token_factory=agent_stub_token_factory,
|
||||
)
|
||||
workspace_file_service = (
|
||||
WorkspaceFileService(
|
||||
binding_file_service = (
|
||||
BindingFileService(
|
||||
execution_bindings=runtime_backend_profile.execution_bindings,
|
||||
upload_max_bytes=resolved_settings.sandbox_file_upload_max_bytes,
|
||||
file_uploader=(
|
||||
AgentStubWorkspaceFileUploader(file_request_handler=agent_stub_file_request_handler)
|
||||
if agent_stub_file_request_handler is not None
|
||||
else None
|
||||
),
|
||||
agent_stub_api_base_url=resolved_settings.agent_stub_api_base_url,
|
||||
agent_stub_token_factory=agent_stub_token_factory,
|
||||
)
|
||||
if runtime_backend_profile is not None
|
||||
else None
|
||||
@@ -145,7 +141,7 @@ def create_app(settings: ServerSettings | None = None) -> FastAPI:
|
||||
)
|
||||
app.include_router(create_execution_bindings_router(lambda: execution_binding_service))
|
||||
app.include_router(create_home_snapshots_router(lambda: home_snapshot_service))
|
||||
app.include_router(create_workspace_files_router(lambda: workspace_file_service))
|
||||
app.include_router(create_binding_files_router(lambda: binding_file_service))
|
||||
app.include_router(
|
||||
create_agent_stub_router(
|
||||
token_codec=agent_stub_token_codec,
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
"""Binding filesystem operations through an operation-scoped RuntimeLease."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import posixpath
|
||||
import re
|
||||
import shlex
|
||||
from dataclasses import dataclass
|
||||
from typing import ClassVar, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, ValidationError
|
||||
|
||||
from dify_agent.adapters.shell.protocols import CompleteShellCommandResult, ShellProviderError
|
||||
from dify_agent.agent_stub.protocol import is_canonical_dify_file_reference
|
||||
from dify_agent.agent_stub.shell_env import ShellAgentStubTokenFactory, build_shell_agent_stub_env
|
||||
from dify_agent.protocol import (
|
||||
BindingFileDownloadRequest,
|
||||
BindingFileDownloadResponse,
|
||||
BindingFileListRequest,
|
||||
BindingFileListResponse,
|
||||
BindingFileReadRequest,
|
||||
BindingFileReadResponse,
|
||||
)
|
||||
from dify_agent.runtime.command_runner import execute_complete_with_commands
|
||||
from dify_agent.runtime_backend import (
|
||||
BindingAcquireError,
|
||||
BindingLostError,
|
||||
ExecutionBindingBackend,
|
||||
RuntimeLayout,
|
||||
WorkspaceUnavailableError,
|
||||
)
|
||||
from dify_agent.runtime_backend.leases import open_runtime_lease
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_LIST_MAX_ENTRIES = 1000
|
||||
_BROWSE_TIMEOUT_SECONDS = 60.0
|
||||
_BROWSE_OUTPUT_MAX_BYTES = 1024 * 1024
|
||||
_DOWNLOAD_TIMEOUT_SECONDS = 60.0
|
||||
_DOWNLOAD_OUTPUT_MAX_BYTES = 32 * 1024
|
||||
_PAYLOAD_BEGIN = "<<<DIFY_BINDING_FILE_BEGIN>>>"
|
||||
_PAYLOAD_END = "<<<DIFY_BINDING_FILE_END>>>"
|
||||
|
||||
_LIST_BINDING_FILES_SCRIPT = r"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
path = sys.argv[1]
|
||||
response_path = sys.argv[2]
|
||||
limit = int(sys.argv[3])
|
||||
directory_fd = None
|
||||
try:
|
||||
directory_fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
names = sorted(os.listdir(directory_fd))
|
||||
entries = []
|
||||
for name in names[:limit]:
|
||||
child_stat = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
|
||||
mode = child_stat.st_mode
|
||||
entry_type = (
|
||||
"symlink" if stat.S_ISLNK(mode) else
|
||||
"dir" if stat.S_ISDIR(mode) else
|
||||
"file" if stat.S_ISREG(mode) else
|
||||
"other"
|
||||
)
|
||||
entries.append({
|
||||
"name": name,
|
||||
"type": entry_type,
|
||||
"size": int(child_stat.st_size),
|
||||
"mtime": int(child_stat.st_mtime),
|
||||
})
|
||||
finally:
|
||||
if directory_fd is not None:
|
||||
os.close(directory_fd)
|
||||
|
||||
payload = {"path": response_path, "entries": entries, "truncated": len(names) > limit}
|
||||
blob = base64.b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode()
|
||||
print("<<<DIFY_BINDING_FILE_BEGIN>>>" + blob + "<<<DIFY_BINDING_FILE_END>>>")
|
||||
"""
|
||||
|
||||
_READ_BINDING_FILE_SCRIPT = r"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
path = sys.argv[1]
|
||||
response_path = sys.argv[2]
|
||||
max_bytes = int(sys.argv[3])
|
||||
file_fd = None
|
||||
try:
|
||||
file_fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
file_stat = os.fstat(file_fd)
|
||||
if not stat.S_ISREG(file_stat.st_mode):
|
||||
raise FileNotFoundError(path)
|
||||
size = int(file_stat.st_size)
|
||||
data = os.read(file_fd, max_bytes + 1)
|
||||
finally:
|
||||
if file_fd is not None:
|
||||
os.close(file_fd)
|
||||
|
||||
truncated = len(data) > max_bytes
|
||||
data = data[:max_bytes]
|
||||
try:
|
||||
text = data.decode("utf-8")
|
||||
binary = False
|
||||
except UnicodeDecodeError:
|
||||
text = None
|
||||
binary = True
|
||||
payload = {
|
||||
"path": response_path,
|
||||
"size": size,
|
||||
"truncated": truncated,
|
||||
"binary": binary,
|
||||
"text": text,
|
||||
}
|
||||
blob = base64.b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode()
|
||||
print("<<<DIFY_BINDING_FILE_BEGIN>>>" + blob + "<<<DIFY_BINDING_FILE_END>>>")
|
||||
"""
|
||||
|
||||
|
||||
class BindingFileError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
status_code: int
|
||||
|
||||
def __init__(self, code: str, message: str, *, status_code: int = 400) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class _CliUploadResult(BaseModel):
|
||||
transfer_method: Literal["tool_file"]
|
||||
reference: str
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore")
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class BindingFileService:
|
||||
execution_bindings: ExecutionBindingBackend
|
||||
agent_stub_api_base_url: str | None
|
||||
agent_stub_token_factory: ShellAgentStubTokenFactory | None
|
||||
|
||||
async def list_files(self, request: BindingFileListRequest) -> BindingFileListResponse:
|
||||
try:
|
||||
async with open_runtime_lease(self.execution_bindings, request.backend_binding_ref) as lease:
|
||||
resolved_path = resolve_binding_path(request.path, lease.layout)
|
||||
result = await execute_complete_with_commands(
|
||||
lease.commands,
|
||||
_python_command(
|
||||
_LIST_BINDING_FILES_SCRIPT,
|
||||
resolved_path,
|
||||
request.path,
|
||||
str(_LIST_MAX_ENTRIES),
|
||||
),
|
||||
cwd=lease.layout.workspace_dir,
|
||||
env={"HOME": lease.layout.home_dir},
|
||||
timeout=_BROWSE_TIMEOUT_SECONDS,
|
||||
max_output_bytes=_BROWSE_OUTPUT_MAX_BYTES,
|
||||
)
|
||||
payload = _require_browse_payload(result, operation="list")
|
||||
try:
|
||||
return BindingFileListResponse.model_validate(payload)
|
||||
except ValidationError as exc:
|
||||
raise WorkspaceUnavailableError("Binding file list returned an invalid response") from exc
|
||||
except BindingFileError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise _normalize_binding_file_error(exc) from exc
|
||||
|
||||
async def read_file(self, request: BindingFileReadRequest) -> BindingFileReadResponse:
|
||||
try:
|
||||
async with open_runtime_lease(self.execution_bindings, request.backend_binding_ref) as lease:
|
||||
resolved_path = resolve_binding_path(request.path, lease.layout)
|
||||
result = await execute_complete_with_commands(
|
||||
lease.commands,
|
||||
_python_command(
|
||||
_READ_BINDING_FILE_SCRIPT,
|
||||
resolved_path,
|
||||
request.path,
|
||||
str(request.max_bytes),
|
||||
),
|
||||
cwd=lease.layout.workspace_dir,
|
||||
env={"HOME": lease.layout.home_dir},
|
||||
timeout=_BROWSE_TIMEOUT_SECONDS,
|
||||
max_output_bytes=_BROWSE_OUTPUT_MAX_BYTES,
|
||||
)
|
||||
payload = _require_browse_payload(result, operation="read")
|
||||
try:
|
||||
return BindingFileReadResponse.model_validate(payload)
|
||||
except ValidationError as exc:
|
||||
raise WorkspaceUnavailableError("Binding file read returned an invalid response") from exc
|
||||
except BindingFileError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise _normalize_binding_file_error(exc) from exc
|
||||
|
||||
async def download_file(self, request: BindingFileDownloadRequest) -> BindingFileDownloadResponse:
|
||||
context = request.execution_context
|
||||
if not context.user_id or not context.user_from:
|
||||
raise BindingFileError(
|
||||
"invalid_execution_context",
|
||||
"Binding file download requires user_id and user_from",
|
||||
status_code=400,
|
||||
)
|
||||
if self.agent_stub_api_base_url is None or self.agent_stub_token_factory is None:
|
||||
raise BindingFileError(
|
||||
"agent_stub_upload_unavailable",
|
||||
"Agent Stub file upload is not configured",
|
||||
status_code=503,
|
||||
)
|
||||
|
||||
try:
|
||||
agent_stub_env = build_shell_agent_stub_env(
|
||||
agent_stub_api_base_url=self.agent_stub_api_base_url,
|
||||
execution_context=context,
|
||||
token_factory=self.agent_stub_token_factory,
|
||||
session_id=None,
|
||||
)
|
||||
if agent_stub_env is None:
|
||||
raise BindingFileError(
|
||||
"agent_stub_upload_unavailable",
|
||||
"Agent Stub file upload is not configured",
|
||||
status_code=503,
|
||||
)
|
||||
async with open_runtime_lease(self.execution_bindings, request.backend_binding_ref) as lease:
|
||||
resolved_path = resolve_binding_path(request.path, lease.layout)
|
||||
env = {"HOME": lease.layout.home_dir, **agent_stub_env}
|
||||
try:
|
||||
result = await execute_complete_with_commands(
|
||||
lease.commands,
|
||||
f"dify-agent file upload --no-download-link {shlex.quote(resolved_path)}",
|
||||
cwd=lease.layout.workspace_dir,
|
||||
env=env,
|
||||
timeout=_DOWNLOAD_TIMEOUT_SECONDS,
|
||||
max_output_bytes=_DOWNLOAD_OUTPUT_MAX_BYTES,
|
||||
)
|
||||
except ShellProviderError as exc:
|
||||
if exc.code == "timeout":
|
||||
raise _download_failed() from exc
|
||||
raise
|
||||
if result.exit_code != 0 or not result.output_complete:
|
||||
_log_download_failure(result.output, agent_stub_env)
|
||||
raise _download_failed()
|
||||
try:
|
||||
payload = json.loads(result.output)
|
||||
uploaded = _CliUploadResult.model_validate(payload)
|
||||
except (json.JSONDecodeError, ValidationError, TypeError) as exc:
|
||||
raise _download_failed() from exc
|
||||
if not is_canonical_dify_file_reference(uploaded.reference):
|
||||
raise _download_failed()
|
||||
return BindingFileDownloadResponse(reference=uploaded.reference)
|
||||
except BindingFileError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
normalized = _normalize_binding_file_error(exc)
|
||||
if normalized.code in {"binding_not_found", "binding_unavailable"}:
|
||||
raise normalized from exc
|
||||
raise _download_failed() from exc
|
||||
|
||||
|
||||
def resolve_binding_path(path: str, layout: RuntimeLayout) -> str:
|
||||
"""Resolve convenient Binding paths without adding a containment policy."""
|
||||
|
||||
if path == "~":
|
||||
candidate = layout.home_dir
|
||||
elif path.startswith("~/"):
|
||||
candidate = posixpath.join(layout.home_dir, path[2:])
|
||||
elif posixpath.isabs(path):
|
||||
candidate = path
|
||||
else:
|
||||
candidate = posixpath.join(layout.workspace_dir, path or ".")
|
||||
return posixpath.normpath(candidate)
|
||||
|
||||
|
||||
def _python_command(source: str, *args: str) -> str:
|
||||
return " ".join(["python3", "-c", shlex.quote(source), *(shlex.quote(arg) for arg in args)])
|
||||
|
||||
|
||||
def _require_browse_payload(result: CompleteShellCommandResult, *, operation: str) -> dict[str, object]:
|
||||
exit_code = result.exit_code
|
||||
output_complete = result.output_complete
|
||||
output = result.output
|
||||
if exit_code != 0:
|
||||
if any(
|
||||
name in output
|
||||
for name in ("FileNotFoundError", "NotADirectoryError", "IsADirectoryError", "PermissionError")
|
||||
):
|
||||
raise BindingFileError(
|
||||
"invalid_binding_path",
|
||||
f"Binding file {operation} path is unavailable",
|
||||
status_code=400,
|
||||
)
|
||||
raise WorkspaceUnavailableError(f"Binding file {operation} command failed")
|
||||
if not output_complete:
|
||||
raise WorkspaceUnavailableError(f"Binding file {operation} output was incomplete")
|
||||
match = re.search(re.escape(_PAYLOAD_BEGIN) + r"(.*?)" + re.escape(_PAYLOAD_END), output, flags=re.DOTALL)
|
||||
if match is None:
|
||||
raise WorkspaceUnavailableError(f"Binding file {operation} returned no framed payload")
|
||||
try:
|
||||
decoded = base64.b64decode("".join(match.group(1).split()), validate=True)
|
||||
payload = json.loads(decoded)
|
||||
except (ValueError, json.JSONDecodeError) as exc:
|
||||
raise WorkspaceUnavailableError(f"Binding file {operation} returned an invalid payload") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise WorkspaceUnavailableError(f"Binding file {operation} returned a non-object payload")
|
||||
return payload
|
||||
|
||||
|
||||
def _normalize_binding_file_error(exc: Exception) -> BindingFileError:
|
||||
if isinstance(exc, BindingFileError):
|
||||
return exc
|
||||
if isinstance(exc, ValueError):
|
||||
return BindingFileError("invalid_binding_path", "Binding file path or payload is invalid", status_code=400)
|
||||
if isinstance(exc, BindingLostError):
|
||||
return BindingFileError("binding_not_found", "Execution Binding was not found", status_code=404)
|
||||
if isinstance(exc, BindingAcquireError | WorkspaceUnavailableError):
|
||||
return BindingFileError("binding_unavailable", "Execution Binding is unavailable", status_code=502)
|
||||
return BindingFileError("binding_unavailable", "Execution Binding file operation failed", status_code=502)
|
||||
|
||||
|
||||
def _download_failed() -> BindingFileError:
|
||||
return BindingFileError(
|
||||
"binding_file_download_failed",
|
||||
"Binding file could not be converted to a ToolFile",
|
||||
status_code=502,
|
||||
)
|
||||
|
||||
|
||||
def _log_download_failure(output: str, env: dict[str, str]) -> None:
|
||||
redacted = output
|
||||
for secret in env.values():
|
||||
if len(secret) > 8:
|
||||
redacted = redacted.replace(secret, "***")
|
||||
logger.warning("Binding file upload command failed: %s", redacted[-1024:])
|
||||
|
||||
|
||||
__all__ = ["BindingFileError", "BindingFileService", "resolve_binding_path"]
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Private Binding file routes used by Dify API."""
|
||||
|
||||
from collections.abc import Callable, Coroutine
|
||||
from typing import Annotated, Any, override
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.routing import APIRoute
|
||||
from starlette.responses import Response
|
||||
|
||||
from dify_agent.protocol import (
|
||||
BindingFileDownloadRequest,
|
||||
BindingFileDownloadResponse,
|
||||
BindingFileListRequest,
|
||||
BindingFileListResponse,
|
||||
BindingFileReadRequest,
|
||||
BindingFileReadResponse,
|
||||
)
|
||||
from dify_agent.server.binding_files import BindingFileError, BindingFileService
|
||||
|
||||
_INVALID_BINDING_PATH_MESSAGE = "Binding file path or payload is invalid"
|
||||
_BROWSE_PATHS = frozenset(
|
||||
{
|
||||
"/execution-bindings/files/list",
|
||||
"/execution-bindings/files/read",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class _BindingFileValidationRoute(APIRoute):
|
||||
@override
|
||||
def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
|
||||
route_handler = super().get_route_handler()
|
||||
|
||||
async def handle(request: Request) -> Response:
|
||||
try:
|
||||
return await route_handler(request)
|
||||
except RequestValidationError:
|
||||
if self.path not in _BROWSE_PATHS:
|
||||
raise
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={
|
||||
"detail": {
|
||||
"code": "invalid_binding_path",
|
||||
"message": _INVALID_BINDING_PATH_MESSAGE,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
return handle
|
||||
|
||||
|
||||
def create_binding_files_router(get_service: Callable[[], BindingFileService | None]) -> APIRouter:
|
||||
router = APIRouter(
|
||||
prefix="/execution-bindings/files",
|
||||
tags=["execution-bindings"],
|
||||
route_class=_BindingFileValidationRoute,
|
||||
)
|
||||
|
||||
def service_dep() -> BindingFileService:
|
||||
service = get_service()
|
||||
if service is None:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail={"code": "runtime_backend_unavailable", "message": "Binding file service is not configured"},
|
||||
)
|
||||
return service
|
||||
|
||||
def raise_http(exc: BindingFileError) -> HTTPException:
|
||||
return HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message})
|
||||
|
||||
@router.post("/list", response_model=BindingFileListResponse)
|
||||
async def list_files(
|
||||
request: BindingFileListRequest,
|
||||
service: Annotated[BindingFileService, Depends(service_dep)],
|
||||
) -> BindingFileListResponse:
|
||||
try:
|
||||
return await service.list_files(request)
|
||||
except BindingFileError as exc:
|
||||
raise raise_http(exc) from exc
|
||||
|
||||
@router.post("/read", response_model=BindingFileReadResponse)
|
||||
async def read_file(
|
||||
request: BindingFileReadRequest,
|
||||
service: Annotated[BindingFileService, Depends(service_dep)],
|
||||
) -> BindingFileReadResponse:
|
||||
try:
|
||||
return await service.read_file(request)
|
||||
except BindingFileError as exc:
|
||||
raise raise_http(exc) from exc
|
||||
|
||||
@router.post("/download", response_model=BindingFileDownloadResponse)
|
||||
async def download_file(
|
||||
request: BindingFileDownloadRequest,
|
||||
service: Annotated[BindingFileService, Depends(service_dep)],
|
||||
) -> BindingFileDownloadResponse:
|
||||
try:
|
||||
return await service.download_file(request)
|
||||
except BindingFileError as exc:
|
||||
raise raise_http(exc) from exc
|
||||
|
||||
return router
|
||||
|
||||
|
||||
__all__ = ["create_binding_files_router"]
|
||||
@@ -1,67 +0,0 @@
|
||||
"""Private Workspace file routes used by Dify API."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from dify_agent.protocol import (
|
||||
WorkspaceListRequest,
|
||||
WorkspaceListResponse,
|
||||
WorkspaceReadRequest,
|
||||
WorkspaceReadResponse,
|
||||
WorkspaceUploadRequest,
|
||||
WorkspaceUploadResponse,
|
||||
)
|
||||
from dify_agent.server.workspace_files import WorkspaceFileError, WorkspaceFileService
|
||||
|
||||
|
||||
def create_workspace_files_router(get_service: Callable[[], WorkspaceFileService | None]) -> APIRouter:
|
||||
router = APIRouter(prefix="/workspace", tags=["workspace"])
|
||||
|
||||
def service_dep() -> WorkspaceFileService:
|
||||
service = get_service()
|
||||
if service is None:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail={"code": "runtime_backend_unavailable", "message": "Workspace service is not configured"},
|
||||
)
|
||||
return service
|
||||
|
||||
def raise_http(exc: WorkspaceFileError) -> HTTPException:
|
||||
return HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message})
|
||||
|
||||
@router.post("/files/list", response_model=WorkspaceListResponse)
|
||||
async def list_files(
|
||||
request: WorkspaceListRequest,
|
||||
service: Annotated[WorkspaceFileService, Depends(service_dep)],
|
||||
) -> WorkspaceListResponse:
|
||||
try:
|
||||
return await service.list_files(request)
|
||||
except WorkspaceFileError as exc:
|
||||
raise raise_http(exc) from exc
|
||||
|
||||
@router.post("/files/read", response_model=WorkspaceReadResponse)
|
||||
async def read_file(
|
||||
request: WorkspaceReadRequest,
|
||||
service: Annotated[WorkspaceFileService, Depends(service_dep)],
|
||||
) -> WorkspaceReadResponse:
|
||||
try:
|
||||
return await service.read_file(request)
|
||||
except WorkspaceFileError as exc:
|
||||
raise raise_http(exc) from exc
|
||||
|
||||
@router.post("/files/upload", response_model=WorkspaceUploadResponse)
|
||||
async def upload_file(
|
||||
request: WorkspaceUploadRequest,
|
||||
service: Annotated[WorkspaceFileService, Depends(service_dep)],
|
||||
) -> WorkspaceUploadResponse:
|
||||
try:
|
||||
return await service.upload_file(request)
|
||||
except WorkspaceFileError as exc:
|
||||
raise raise_http(exc) from exc
|
||||
|
||||
return router
|
||||
|
||||
|
||||
__all__ = ["create_workspace_files_router"]
|
||||
@@ -71,7 +71,6 @@ class ServerSettings(BaseSettings):
|
||||
)
|
||||
e2b_shellctl_auth_token: str = ""
|
||||
e2b_shellctl_port: int = Field(default=5004, ge=1, le=65535)
|
||||
sandbox_file_upload_max_bytes: int = Field(default=50 * 1024 * 1024, ge=1)
|
||||
agent_stub_api_base_url: str | None = Field(default=None, validation_alias="DIFY_AGENT_STUB_API_BASE_URL")
|
||||
sandbox_files_base_url: str | None = Field(
|
||||
default=None,
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
"""Workspace file access through an operation-scoped RuntimeLease.
|
||||
|
||||
Paths are passed directly to the backend FileSystem. Dify Agent does not rebase
|
||||
them to ``layout.workspace_dir`` or impose another containment boundary.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
import mimetypes
|
||||
from pathlib import PurePosixPath
|
||||
from typing import ClassVar, Protocol
|
||||
|
||||
import httpx
|
||||
from pydantic import BaseModel, ConfigDict, ValidationError
|
||||
|
||||
from dify_agent.agent_stub.protocol import (
|
||||
AgentStubFileDownloadRequest,
|
||||
AgentStubFileMapping,
|
||||
AgentStubFileUploadRequest,
|
||||
)
|
||||
from dify_agent.agent_stub.server.agent_stub_files import AgentStubFileRequestError, AgentStubFileRequestHandler
|
||||
from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubPrincipal
|
||||
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
|
||||
from dify_agent.protocol import (
|
||||
WorkspaceListRequest,
|
||||
WorkspaceListResponse,
|
||||
WorkspaceReadRequest,
|
||||
WorkspaceReadResponse,
|
||||
WorkspaceUploadRequest,
|
||||
WorkspaceUploadResponse,
|
||||
WorkspaceUploadedFile,
|
||||
)
|
||||
from dify_agent.runtime_backend import (
|
||||
BindingAcquireError,
|
||||
BindingLostError,
|
||||
ExecutionBindingBackend,
|
||||
WorkspaceFileTooLargeError,
|
||||
WorkspacePathError,
|
||||
WorkspaceUnavailableError,
|
||||
)
|
||||
from dify_agent.runtime_backend.leases import open_runtime_lease
|
||||
|
||||
_LIST_MAX_ENTRIES = 1000
|
||||
_UPLOAD_TIMEOUT_SECONDS = 30.0
|
||||
|
||||
|
||||
class _SignedUploadResponse(BaseModel):
|
||||
reference: str
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class WorkspaceFileError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
status_code: int
|
||||
|
||||
def __init__(self, code: str, message: str, *, status_code: int = 400) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class WorkspaceFileUploader(Protocol):
|
||||
async def upload(
|
||||
self,
|
||||
*,
|
||||
execution_context: DifyExecutionContextLayerConfig,
|
||||
filename: str,
|
||||
mimetype: str,
|
||||
content: bytes,
|
||||
) -> WorkspaceUploadedFile: ...
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AgentStubWorkspaceFileUploader:
|
||||
file_request_handler: AgentStubFileRequestHandler
|
||||
timeout: httpx.Timeout | float = _UPLOAD_TIMEOUT_SECONDS
|
||||
transport: httpx.AsyncBaseTransport | None = None
|
||||
|
||||
async def upload(
|
||||
self,
|
||||
*,
|
||||
execution_context: DifyExecutionContextLayerConfig,
|
||||
filename: str,
|
||||
mimetype: str,
|
||||
content: bytes,
|
||||
) -> WorkspaceUploadedFile:
|
||||
principal = AgentStubPrincipal(
|
||||
execution_context=execution_context,
|
||||
session_id=None,
|
||||
scope=[],
|
||||
token_id="workspace-file-upload",
|
||||
)
|
||||
try:
|
||||
upload_request = await self.file_request_handler.create_upload_request(
|
||||
principal=principal,
|
||||
request=AgentStubFileUploadRequest(filename=filename, mimetype=mimetype),
|
||||
)
|
||||
async with httpx.AsyncClient(
|
||||
timeout=self.timeout,
|
||||
follow_redirects=True,
|
||||
trust_env=False,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
upload_request.upload_url,
|
||||
files={"file": (filename, content, mimetype)},
|
||||
)
|
||||
_ = response.raise_for_status()
|
||||
payload = _SignedUploadResponse.model_validate(response.json())
|
||||
mapping = AgentStubFileMapping(transfer_method="tool_file", reference=payload.reference)
|
||||
download_request = await self.file_request_handler.create_download_request(
|
||||
principal=principal,
|
||||
request=AgentStubFileDownloadRequest(file=mapping, for_frontend=False),
|
||||
)
|
||||
return WorkspaceUploadedFile(
|
||||
reference=payload.reference,
|
||||
download_url=download_request.download_url,
|
||||
)
|
||||
except AgentStubFileRequestError as exc:
|
||||
raise WorkspaceFileError("agent_stub_upload_failed", str(exc.detail), status_code=exc.status_code) from exc
|
||||
except httpx.TimeoutException as exc:
|
||||
raise WorkspaceFileError(
|
||||
"agent_stub_upload_failed", "signed file upload timed out", status_code=504
|
||||
) from exc
|
||||
except httpx.HTTPStatusError as exc:
|
||||
raise WorkspaceFileError(
|
||||
"agent_stub_upload_failed",
|
||||
f"signed file upload failed with status {exc.response.status_code}",
|
||||
status_code=exc.response.status_code,
|
||||
) from exc
|
||||
except httpx.RequestError as exc:
|
||||
raise WorkspaceFileError(
|
||||
"agent_stub_upload_failed", f"signed file upload failed: {exc}", status_code=502
|
||||
) from exc
|
||||
except (ValidationError, ValueError) as exc:
|
||||
raise WorkspaceFileError(
|
||||
"agent_stub_upload_failed", "signed file upload returned invalid data", status_code=502
|
||||
) from exc
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class WorkspaceFileService:
|
||||
execution_bindings: ExecutionBindingBackend
|
||||
upload_max_bytes: int
|
||||
file_uploader: WorkspaceFileUploader | None = None
|
||||
|
||||
async def list_files(self, request: WorkspaceListRequest) -> WorkspaceListResponse:
|
||||
try:
|
||||
async with open_runtime_lease(self.execution_bindings, request.backend_binding_ref) as lease:
|
||||
result = await lease.files.list_directory(path=request.path, limit=_LIST_MAX_ENTRIES)
|
||||
return WorkspaceListResponse.model_validate(
|
||||
{
|
||||
"path": result.path,
|
||||
"entries": [asdict(entry) for entry in result.entries],
|
||||
"truncated": result.truncated,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
raise _normalize_file_error(exc) from exc
|
||||
|
||||
async def read_file(self, request: WorkspaceReadRequest) -> WorkspaceReadResponse:
|
||||
try:
|
||||
async with open_runtime_lease(self.execution_bindings, request.backend_binding_ref) as lease:
|
||||
result = await lease.files.read_file(path=request.path, max_bytes=request.max_bytes)
|
||||
return WorkspaceReadResponse(
|
||||
path=result.path,
|
||||
size=result.size,
|
||||
truncated=result.truncated,
|
||||
binary=result.binary,
|
||||
text=result.text,
|
||||
)
|
||||
except Exception as exc:
|
||||
raise _normalize_file_error(exc) from exc
|
||||
|
||||
async def upload_file(self, request: WorkspaceUploadRequest) -> WorkspaceUploadResponse:
|
||||
uploader = self.file_uploader
|
||||
if uploader is None:
|
||||
raise WorkspaceFileError(
|
||||
"agent_stub_upload_unavailable", "Agent Stub file upload is not configured", status_code=503
|
||||
)
|
||||
try:
|
||||
async with open_runtime_lease(self.execution_bindings, request.backend_binding_ref) as lease:
|
||||
result = await lease.files.read_bytes(path=request.path, max_bytes=self.upload_max_bytes)
|
||||
filename = PurePosixPath(result.path).name or "file"
|
||||
mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
||||
uploaded_file = await uploader.upload(
|
||||
execution_context=request.execution_context,
|
||||
filename=filename,
|
||||
mimetype=mimetype,
|
||||
content=result.content,
|
||||
)
|
||||
return WorkspaceUploadResponse(path=result.path, file=uploaded_file)
|
||||
except WorkspaceFileError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise _normalize_file_error(exc) from exc
|
||||
|
||||
|
||||
def _normalize_file_error(exc: Exception) -> WorkspaceFileError:
|
||||
if isinstance(exc, WorkspaceFileError):
|
||||
return exc
|
||||
if isinstance(exc, WorkspacePathError):
|
||||
return WorkspaceFileError("invalid_workspace_path", str(exc), status_code=400)
|
||||
if isinstance(exc, WorkspaceFileTooLargeError):
|
||||
return WorkspaceFileError("file_too_large", str(exc), status_code=413)
|
||||
if isinstance(exc, BindingLostError):
|
||||
return WorkspaceFileError("binding_not_found", str(exc), status_code=404)
|
||||
if isinstance(exc, (WorkspaceUnavailableError, BindingAcquireError)):
|
||||
return WorkspaceFileError("workspace_unavailable", str(exc), status_code=502)
|
||||
return WorkspaceFileError("workspace_file_failed", str(exc), status_code=502)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AgentStubWorkspaceFileUploader",
|
||||
"WorkspaceFileError",
|
||||
"WorkspaceFileService",
|
||||
"WorkspaceFileUploader",
|
||||
]
|
||||
Reference in new issue
Block a user