> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zeus.agentspro.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 存储后端

> Zeus CloudDriveBackend 存储方案

> DeepAgents Backend 用于管理 Agent 的文件系统操作，包括产物存储、用户云盘和长期记忆。

***

## 1. 概述

### 1.1 当前问题

| 问题          | 说明                                     |
| ----------- | -------------------------------------- |
| **虚拟内存丢失**  | StateBackend 使用 InMemoryStore，服务重启数据全丢 |
| **前端拿不到数据** | 虚拟文件系统的文件无法被前端访问                       |
| **沙盒销毁**    | E2B 沙盒超时后产物丢失                          |
| **多环境混乱**   | Desktop、Sandbox、虚拟内存三种环境数据不统一          |

### 1.2 目标

* 所有产物自动持久化到云存储
* 用户拥有"云盘"体验，随时访问自己的文件
* 统一存储架构，减少复杂度

***

## 2. DeepAgents Backend 类型

DeepAgents 提供以下 Backend 类型：

| Backend               | 持久性      | 存储位置                 | 适用场景       |
| --------------------- | -------- | -------------------- | ---------- |
| **StateBackend**      | ❌ 临时     | LangGraph State (内存) | 单次会话临时文件   |
| **StoreBackend**      | ✅ 持久     | LangGraph Store      | 长期记忆       |
| **FilesystemBackend** | ✅ 持久     | 本地文件系统               | Desktop 模式 |
| **BaseSandbox**       | ⚠️ 沙盒存活期 | 远程沙盒 (E2B)           | 代码执行       |
| **CompositeBackend**  | 组合       | 路由到不同 Backend        | 混合架构       |

***

## 3. 推荐方案：CloudDriveBackend

### 3.1 架构设计

```mermaid theme={null}
flowchart TB
    subgraph Tools["DeepAgent 工具调用"]
        direction LR
        FileRead["file_read<br/>file_ls"]
        FileWrite["file_write<br/>file_grep"]
        FileEdit["file_edit<br/>file_glob"]
    end

    subgraph CloudDrive["CloudDriveBackend"]
        subgraph Cache["Redis (缓存层)"]
            CacheInfo["热文件缓存 TTL: 5min<br/>减少 Supabase API 调用<br/>无需持久化，纯缓存"]
        end
        
        subgraph Storage["Supabase Storage (持久层)"]
            subgraph Bucket["workspace bucket"]
                subgraph UserDir["users/{user_id}/"]
                    Workspace["workspace/<br/>├── projects/<br/>├── sandbox-output/<br/>└── uploads/"]
                    Memory["memory/<br/>├── user_profile.json<br/>└── facts/"]
                end
            end
        end
        
        Cache --> Storage
    end

    FileRead --> CloudDrive
    FileWrite --> CloudDrive
    FileEdit --> CloudDrive
```

### 3.2 存储结构

```mermaid theme={null}
graph LR
    subgraph SupabaseStorage["Supabase Storage: workspace bucket"]
        subgraph Users["users/"]
            subgraph UserID["{user_id}/"]
                subgraph Workspace["workspace/ - 工作区"]
                    Projects["projects/<br/>└── my-app/<br/>    ├── src/main.py<br/>    └── README.md"]
                    SandboxOutput["sandbox-output/<br/>└── 2024-01-31/<br/>    └── result.csv"]
                    Uploads["uploads/<br/>└── data.xlsx"]
                end
                
                subgraph Memory["memory/ - 长期记忆"]
                    UserProfile["user_profile.json"]
                    Facts["facts/<br/>├── coding_style.json<br/>└── preferences.json"]
                    Conversations["conversations/<br/>└── 2024-01/<br/>    └── summary.json"]
                end
            end
        end
    end
```

***

## 4. CloudDriveBackend 概述

CloudDriveBackend 是基于 Supabase Storage 的持久化文件后端，具有以下特点：

* 每个用户隔离的存储空间
* 所有文件自动持久化
* Redis 缓存加速
* 支持大文件（图片、文档等）

存储结构：

* `/workspace/` - 工作区文件（Agent 产物）
* `/memory/` - 长期记忆（用户知识）

路径映射规则：

* 虚拟路径 `/code/main.py` 映射到 `users/{user_id}/workspace/code/main.py`
* 虚拟路径 `/memory/facts.json` 映射到 `users/{user_id}/memory/facts.json`

CloudDriveBackend 实现了完整的 BackendProtocol 接口，包括文件列表、读取、写入、编辑、搜索、glob 匹配、上传和下载等操作。

### 4.1 集成方式

BaseService 通过 Redis 缓存和用户级 Backend 缓存管理 CloudDriveBackend 实例。每个用户拥有独立的 Backend 实例，通过 `get_backend(user_id)` 获取。

***

## 5. Desktop 模式支持

当用户使用 Desktop 应用时，系统会根据设备类型自动选择合适的 Backend：

* **Desktop 模式**：使用 FilesystemBackend（本地文件系统）
* **Cloud 模式**：使用 CloudDriveBackend（Supabase Storage）

***

## 6. 前端云盘 API

前端通过以下 API 接口与云盘交互：

* `GET /api/storage/list?path=...` - 列出文件
* `POST /api/storage/upload` - 上传文件
* `GET /api/storage/download?path=...` - 下载文件
* `DELETE /api/storage/delete?path=...` - 删除文件
* `GET /api/storage/url?path=...` - 获取预览 URL

***

## 7. 沙盒产物同步

当 E2B 沙盒生成文件后，系统会自动将产物同步到用户云盘，存储在 `/workspace/sandbox-output/{date}/` 路径下。

***

## 8. 性能优化

### 8.1 Redis 缓存效果

| 操作     | 无缓存       | 有缓存 (命中) | 提升       |
| ------ | --------- | -------- | -------- |
| 读取文件   | 200-500ms | 1-5ms    | **100x** |
| 列出目录   | 100-300ms | 5-10ms   | **30x**  |
| 检查文件存在 | 100-200ms | 1ms      | **100x** |

### 8.2 缓存策略

* 工作区文件 TTL: 5 分钟
* 记忆文件 TTL: 10 分钟
* 写入/编辑后立即更新缓存

***

## 9. 迁移步骤

1. **创建 Supabase Storage Bucket** - 在 Supabase Dashboard 中创建 `workspace` bucket
2. **配置 RLS 策略** - 确保用户只能访问自己的文件
3. **配置环境变量** - 设置 `SUPABASE_URL`、`SUPABASE_SERVICE_KEY`、`REDIS_URL`（可选）
4. **创建 CloudDriveBackend** - 实现 Backend 核心逻辑
5. **修改 BaseService** - 集成 CloudDriveBackend
6. **删除旧代码** - 移除 StateBackend 和 InMemoryStore 相关使用

***

## 10. 总结

| 项目      | 当前状态              | 目标状态                         |
| ------- | ----------------- | ---------------------------- |
| Backend | StateBackend (内存) | CloudDriveBackend (Supabase) |
| 持久化     | ❌ 服务重启丢失          | ✅ 永久保存                       |
| 用户可见    | ❌ 前端拿不到           | ✅ 云盘体验                       |
| 缓存      | ❌ 无               | ✅ Redis 加速                   |
| Memory  | InMemoryStore     | Supabase Storage (自己实现)      |
