# REST API

所有接口在 `https://agentdocs.page` 下。错误统一返回 `{ "error": { "code": "FILE_TOO_LARGE", "message": "...", "requestId": "..." } }`。

## 上传

上传需要在 `Authorization` 头里带上传密钥。支持两种形式：

```bash
# 1) multipart
curl -H "Authorization: Bearer $AGENTDOCS_KEY" -F file=@report.md https://agentdocs.page/api/files

# 2) 原始 body（必须带 ?filename=）
curl -H "Authorization: Bearer $AGENTDOCS_KEY" -H "Content-Type: text/markdown" \
  --data-binary @report.md "https://agentdocs.page/api/files?filename=report.md"
```

成功返回 `201`：

```json
{
  "id": "…",
  "filename": "report.md",
  "format": "md",
  "size": 1234,
  "createdAt": "…",
  "viewerUrl": "https://agentdocs.page/f/…",
  "downloadUrl": "https://agentdocs.page/api/files/…/download",
  "rawUrl": "https://agentdocs.page/f/…?raw"
}
```

把 `viewerUrl` 发给人阅读；Agent 用 `rawUrl` 取回原文。

R2 用量超过免费额度的 80% 时，上传返回 `503`。`error.code` 仍是 `STORAGE_UNAVAILABLE`，`message` 会说明上传已暂停。这不是限速，不会返回 `429`。

## 读取与下载

| 方法与路径 | 说明 | 鉴权 |
| --- | --- | --- |
| `GET /f/:id` | 阅读页（人用）。带 `Accept: text/markdown` 或以 `text/plain` 开头时返回原文 | 无 |
| `GET /f/:id.md`、`GET /f/:id?raw` | 原文，`text/plain; charset=utf-8` | 无 |
| `GET /api/files/:id` | JSON：`id`、`filename`、`format`、`size`、`createdAt`、`experimental`、`source` | 无 |
| `GET /api/files/:id/download` | 原始字节，`Content-Disposition: attachment` | 无 |
| `DELETE /api/files/:id` | 删除，成功返回 `204` | 管理密钥 |
| `GET /api/health` | `{ ok, version }` | 无 |

## 错误码

| 错误码 | 状态 | 含义 |
| --- | --- | --- |
| `BAD_REQUEST` | 400 | 请求格式错误（缺少文件、缺少文件名等） |
| `UNAUTHORIZED` | 401 | 密钥缺失、无效或权限不足 |
| `FORBIDDEN` | 403 | 跨域预检一律拒绝 |
| `NOT_FOUND` | 404 | 文件不存在、已删除，或 ID 格式不合法 |
| `REVISION_CONFLICT` | 409 | 文档的 `base_revision` 不是当前修订（文档 API，尚未开放） |
| `FILE_TOO_LARGE` | 413 | 超过 1 MiB |
| `UNSUPPORTED_FORMAT` | 415 | 扩展名不在白名单 |
| `INVALID_TEXT` | 422 | 不是合法 UTF-8、含 NUL 字节或为空文件 |
| `EDIT_FAILED` | 422 | 文档编辑的 `old_str` 无匹配或匹配多处（文档 API，尚未开放） |
| `RATE_LIMITED` | 429 | 触发限速 |
| `INTERNAL_ERROR` | 500 | 服务端异常 |
| `STORAGE_UNAVAILABLE` | 503 | 存储暂时不可用，可重试；用量熔断暂停上传时也用这个码，消息会说明原因 |

格式与大小见[格式说明](/docs/formats)和[限制与隐私](/docs/limits)。

## 个人 API Key

登录后在「设置 → API Key」创建。Key 以 `adk_` 开头，只显示一次；吊销后立即失效。Agent 或脚本用它访问 `/api/docs`：

```bash
curl -H "Authorization: Bearer $AGENTDOCS_API_KEY" -H "Content-Type: application/json" \
  -d '{"filename":"report.md","content":"# 报告"}' https://agentdocs.page/api/docs
```

权限（scope）：`docs:read` 读取、`docs:write` 创建与编辑、`docs:share` 改可见性、`docs:delete` 删除。缺少权限返回 `403`。
