# 與 Turso Cloud 同步

> 將 agent 檔案系統與遠端 Turso 資料庫同步
> Canonical HTML: https://tursodb.cn/zh-tw/docs/agentfs/guides/sync/
> Upstream Source (MIT): https://docs.turso.tech/agentfs/guides/sync
> Language: zh-TW

---
AgentFS 可以與 [Turso Cloud](https://turso.tech) 同步，藉此實現備份、協作以及分散式 agent 部署。

## 設定同步

### 1. 建立 Turso 資料庫

如果你還沒有 Turso 帳號，請先[註冊](https://turso.tech)。

為你的 agent 建立一個資料庫：

```bash
turso db create my-agent-db
```

取得資料庫 URL：

```bash
turso db show my-agent-db --url
# Output: libsql://my-agent-db-username.turso.io
```

### 2. 以同步功能初始化

建立一個已啟用同步的新 agent 檔案系統：

```bash
agentfs init my-agent --sync-remote-url libsql://my-agent-db-username.turso.io
```

或是為既有的 agent 加入同步：

```bash
# Edit the database to add sync configuration
# (Feature coming soon)
```

## 同步指令

### 拉取遠端變更

從 Turso Cloud 下載變更：

```bash
agentfs sync my-agent pull
```

### 推送本機變更

將本機變更上傳至 Turso Cloud：

```bash
agentfs sync my-agent push
```

### 檢視同步狀態

查看同步統計資料：

```bash
agentfs sync my-agent stats
```

### 建立檢查點

強制建立同步檢查點：

```bash
agentfs sync my-agent checkpoint
```

## 使用情境

### 備份與還原

自動備份 agent 狀態：

```bash
# After important work
agentfs sync my-agent push

# On a new machine
agentfs init my-agent --sync-remote-url libsql://...
agentfs sync my-agent pull
```

### 多機器 Agent

在多台機器上執行 agent 並共用狀態：

```bash
# Machine A
agentfs run --session shared-agent python3 agent.py
agentfs sync shared-agent push

# Machine B
agentfs sync shared-agent pull
agentfs run --session shared-agent python3 agent.py
```

## 部分同步

對於大型檔案系統，可使用部分同步只取得需要的內容：

```bash
agentfs init my-agent \
  --sync-remote-url libsql://... \
  --sync-partial-prefetch \
  --sync-partial-segment-size 1000
```

### 部分同步選項

| 選項 | 說明 |
| - | - |
| `--sync-partial-prefetch` | 啟用預先擷取 |
| `--sync-partial-segment-size` | 部分同步的區段大小 |
| `--sync-partial-bootstrap-query` | 自訂 bootstrap 查詢 |
| `--sync-partial-bootstrap-length` | Bootstrap 前綴長度 |

## 驗證

同步需要 Turso 驗證權杖。請透過環境變數設定：

```bash
export TURSO_AUTH_TOKEN=$(turso db tokens create my-agent-db)
```

或建立長效權杖：

```bash
turso db tokens create my-agent-db --expiration none
```

## 衝突解決

AgentFS 對於衝突採用「後寫入者勝出」（last-write-wins）策略。若同一個檔案在多台機器上被修改：

1. 從機器 A 推送成功
2. 從機器 B 推送失敗（衝突）
3. 機器 B 必須先拉取，然後再推送

## 後續步驟

<div class="doc-cards">
<a class="doc-card" href="https://turso.tech" target="_blank" rel="noopener noreferrer"><div class="doc-card-title"><span>Turso Cloud</span><span class="doc-card-arrow" aria-hidden="true">↗</span></div><p class="doc-card-desc">進一步瞭解 Turso Cloud</p></a>
<a class="doc-card" href="/zh-tw/docs/agentfs/guides/nfs/"><div class="doc-card-title"><span>NFS 伺服器</span><span class="doc-card-arrow" aria-hidden="true">→</span></div><p class="doc-card-desc">透過 NFS 進行遠端存取</p></a>
</div>
