Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: add remote usage and API key guidance

jinzhenj0d35ccc36791
diff --git a/README.md b/README.md
index 5fca55ee..104d9cff 100644
--- a/README.md
+++ b/README.md
@@ -703,6 +703,15 @@ Rules:
- `--remote` or a remote-enabled parsing rule is still required.
- Avoid printing secrets from config.
+## Remote API Usage
+
+Query usage and limits for the configured Remote API:
+
+```bash
+mineru usage
+mineru usage --json
+```
+
## JSON Output
Use `--json` when an agent needs stable machine-readable fields.
diff --git a/docs/next/cli/README.md b/docs/next/cli/README.md
index 535b8a62..ff77fb54 100644
--- a/docs/next/cli/README.md
+++ b/docs/next/cli/README.md
@@ -39,11 +39,12 @@ MinerU 仓库提供两款命令行工具:
3. [mineru read](mineru-read.md): 理解 locator-first 读取、page/block 定位、image 输出和 continuation。
4. [mineru server](mineru-server.md): 理解 doclib 生命周期和 parse-server 协作。
5. [mineru library](mineru-library.md): 理解 search、find、list、show、config、watch、scan、invalidate、forget 和 cleanup。
-6. [mineru-kit](mineru-kit.md): 理解无状态工具定位。
-7. [mineru-kit models](mineru-kit-models.md): 理解模型下载、当前模型配置查看和轻量校验。
-8. [mineru-kit parse](mineru-kit-parse.md): 理解批处理解析、目录输入、local/remote 规则和输出命名。
-9. [mineru-kit api-server](mineru-kit-api-server.md): 理解本地/自部署 parse-server。
-10. [mineru-kit vlm-server](mineru-kit-vlm-server.md): 理解本地 VLM 服务与 api-server backend 的边界。
+6. [mineru usage](mineru-usage.md): 理解 Remote API usage、limits 和 API Key 引导。
+7. [mineru-kit](mineru-kit.md): 理解无状态工具定位。
+8. [mineru-kit models](mineru-kit-models.md): 理解模型下载、当前模型配置查看和轻量校验。
+9. [mineru-kit parse](mineru-kit-parse.md): 理解批处理解析、目录输入、local/remote 规则和输出命名。
+10. [mineru-kit api-server](mineru-kit-api-server.md): 理解本地/自部署 parse-server。
+11. [mineru-kit vlm-server](mineru-kit-vlm-server.md): 理解本地 VLM 服务与 api-server backend 的边界。
## 4. 共享约束
diff --git a/docs/next/cli/mineru-e2e-test-cases.md b/docs/next/cli/mineru-e2e-test-cases.md
index 6e9cd636..0e12f681 100644
--- a/docs/next/cli/mineru-e2e-test-cases.md
+++ b/docs/next/cli/mineru-e2e-test-cases.md
@@ -190,7 +190,7 @@ mineru --help
预期:
- exit code = 0
-- 输出包含 `parse`、`read`、`scan`、`watch`、`search`、`find`、`list`、`show`、`server`、`config`、`invalidate`、`forget`、`cleanup`
+- 输出包含 `parse`、`read`、`scan`、`watch`、`search`、`find`、`usage`、`list`、`show`、`server`、`config`、`invalidate`、`forget`、`cleanup`
- 输出包含 `telemetry`
- 输出不包含 `mineru-kit`
@@ -205,6 +205,7 @@ mineru scan --help
mineru watch --help
mineru search --help
mineru find --help
+mineru usage --help
mineru list --help
mineru show --help
mineru telemetry --help
@@ -984,6 +985,96 @@ mineru config get not.a.real.key --json
- `--json` 失败时 stdout 必须为可直接解析的 JSON error,且包含 `error.code` 和 `error.message`
- 不包含 Python traceback
+## 5A. Remote API Usage
+
+### USAGE-001 查询 Remote API usage
+
+命令:
+
+```bash
+mineru config set parse_server.remote.url https://mineru.net/api
+mineru usage
+mineru usage --json
+```
+
+预期:
+
+- 三条命令均 exit code = 0
+- 普通输出标题为 `Remote API Usage`
+- 普通输出包含 Remote URL、access level、billing period、current 和 limits
+- JSON stdout 可直接解析,且包含 `object=usage`、`access_level`、`billing_period`、`current` 和 `limits`
+- JSON 数值来自 Remote API,不依赖本用例硬编码固定配额
+- 不包含 Local Parse Server usage
+
+### USAGE-002 anonymous guidance
+
+前置:
+
+- doclib server 进程未设置 `MINERU_API_KEY`
+- 当前 Remote URL 为 `https://mineru.net/api`
+
+命令:
+
+```bash
+mineru config unset parse_server.remote.api_key
+mineru usage --json
+```
+
+预期:
+
+- exit code = 0
+- `access_level = anonymous`
+- 顶层包含 `guidance`
+- `guidance.type = configure_official_api_key`
+- `guidance.required = false`
+- `guidance.url = https://mineru.net/apiManage/token`
+- `guidance.command` 使用 `parse_server.remote.api_key`,且不包含真实 API Key
+- `error` 字段不存在
+
+### USAGE-003 invalid API Key guidance
+
+命令:
+
+```bash
+mineru config set parse_server.remote.api_key invalid-e2e-api-key
+mineru usage --json
+mineru config unset parse_server.remote.api_key
+```
+
+预期:
+
+- set 和 unset 均 exit code = 0,且不回显完整 API Key
+- usage exit code != 0
+- usage stdout 为可直接解析的 JSON
+- `error.code = invalid_api_key`
+- `error.param = parse_server.remote.api_key`
+- 顶层 `guidance.type = configure_official_api_key`
+- `guidance.required = true`
+- guidance 不修改 `error.message` 或其它 error 字段
+
+### USAGE-004 环境变量 fallback
+
+前置:
+
+- doclib server 使用有效 `MINERU_API_KEY` 启动
+- SQLite 中没有 `parse_server.remote.api_key` override
+
+命令:
+
+```bash
+mineru config unset parse_server.remote.api_key
+mineru config get parse_server.remote.api_key --json
+mineru usage --json
+```
+
+预期:
+
+- 三条命令均 exit code = 0
+- config JSON 的 source 为 `environment`
+- config JSON 只包含脱敏值,不包含完整环境变量 API Key
+- usage 的 `access_level = registered`
+- usage JSON 不包含 anonymous API Key guidance
+
## 6. Watch 命令
### WATCH-001 添加 watch
diff --git a/docs/next/cli/mineru-usage.md b/docs/next/cli/mineru-usage.md
new file mode 100644
index 00000000..0cd100a0
--- /dev/null
+++ b/docs/next/cli/mineru-usage.md
@@ -0,0 +1,37 @@
+# `mineru usage`
+
+状态: Accepted
+范围: 查询当前配置的 Remote API 用量和限制
+
+## 命令
+
+```bash
+mineru usage
+mineru usage --json
+```
+
+该命令通过本地 doclib 调用当前配置 Remote API 的 `GET /v1/usage`,不统计 Local Parse Server 活动。
+
+普通输出展示 Remote URL、access level、billing period、全部 current 字段和全部 limits 字段。JSON 使用 CLI 自己的响应结构,
+包含 `remote_url`、嵌套的 `usage` 和可空的 `guidance`。
+
+## API Key
+
+Remote API Key 的解析优先级为:
+
+```text
+parse_server.remote.api_key > MINERU_API_KEY > anonymous
+```
+
+Anonymous 是合法 access level。只有当前 Remote URL 是 `https://mineru.net/api` 时,以下场景才展示 Official API Key 引导:
+
+- anonymous usage,可选引导;
+- `invalid_api_key`,必须修复;
+- `feature_requires_api_key`,必须配置;
+- anonymous `rate_limit_exceeded`,可选引导;
+- anonymous `quota_exceeded`,可选引导。
+
+JSON 错误中的 `guidance` 是 `error` 的 sibling;成功 usage 响应中的 `guidance` 与 `usage` 同级,没有适用引导时为 `null`。
+自定义 Remote Server 不展示 Official API 注册链接或配置文案。
+
+完整设计见 [ADR-0026](../decisions/0026-remote-usage-api-key-guidance.md)。
diff --git a/docs/next/config.md b/docs/next/config.md
index f131aac7..234761b0 100644
--- a/docs/next/config.md
+++ b/docs/next/config.md
@@ -156,8 +156,10 @@ parse-server 是 `medium` / `high` / `xhigh` 等质量 tier 的解析能力来
API Key 读取优先级:
-1. SQLite config 中的 `parse_server.remote.api_key` 或 `parse_server.local.self_hosted_api_key`。
-2. 环境变量 `MINERU_API_KEY`,仅在对应 config API Key 未配置时作为默认值。
+1. Remote API 使用 SQLite config 中的 `parse_server.remote.api_key`。
+2. 未配置 Remote API Key 时,回退到环境变量 `MINERU_API_KEY`。
+
+`parse_server.local.self_hosted_api_key` 只读取自身的 SQLite config,不回退到 Remote API 的环境变量。
环境变量适合无 tty 场景和 CI 的默认凭证,但运行中的 doclib server 会优先使用 `mineru config set`
写入的运行时配置。环境变量不应改变是否允许 remote 上传的判断。
diff --git a/docs/next/decisions/0026-remote-usage-api-key-guidance.md b/docs/next/decisions/0026-remote-usage-api-key-guidance.md
new file mode 100644
index 00000000..cc69f54f
--- /dev/null
+++ b/docs/next/decisions/0026-remote-usage-api-key-guidance.md
@@ -0,0 +1,355 @@
+# ADR-0026: Remote API Usage 与 API Key 引导
+
+状态: Accepted
+日期: 2026-07-14
+相关文档: ../api/usage-limits.md, ../cli/mineru-parse.md, 0005-doclib-interface-client-server-contract.md, 0015-cli-output-json-composition.md, 0023-cli-runtime-contract.md
+
+## 背景
+
+MinerU Unified API 提供 `GET /v1/usage`,用于查询 Remote API 当前身份的计费周期、累计用量和限制。Official API 支持 anonymous 和 registered 两种 access level;Local Parse Server 通常没有账号配额或计费限制,因此本地进程统计不应与 Remote API usage 混在同一个用户命令中。
+
+当前 `mineru` 没有查询 Remote API usage 的命令。Remote API Key 可以通过 doclib runtime config 的 `parse_server.remote.api_key` 配置,但 CLI 也没有在合适的错误场景中提供注册、创建 API Key 和设置 API Key 的可操作引导。
+
+匿名 Remote API 是合法能力。引导出现得过于频繁,会让用户误以为注册和 API Key 是使用 MinerU 或 Remote API 的前置条件。因此引导必须由明确的 access level 或错误码驱动,并且只针对 Official API 展示 Official API 平台链接。
+
+本文中的用户可见术语统一使用 **API Key**。`https://mineru.net/apiManage/token` 是既有兼容 URL,只有 URL path 保留 `token`,其他命令、字段说明和文案不使用 Token 指代 API Key。
+
+## 决策
+
+### 1. 增加 `mineru usage`
+
+新增顶层命令:
+
+```bash
+mineru usage
+mineru usage --json
+```
+
+命令只表示当前配置的 Remote API usage,不查询或合并 Local Parse Server usage。顶层 help 使用明确说明:
+
+```text
+usage Show Remote API usage and limits.
+```
+
+普通文本输出标题使用 `Remote API Usage`,避免把 `usage` 误解为 CLI 使用手册。CLI 使用手册继续通过 `mineru --help` 和 `mineru <command> --help` 获取。
+
+### 2. 通过 doclib 查询 Remote API
+
+`mineru usage` 不直接读取 SQLite 配置,也不在 CLI 中自行实现 Remote HTTP client。调用链统一为:
+
+```text
+mineru usage
+ -> DoclibClient.get_remote_usage()
+ -> GET /api/v1/remote-usage
+ -> DoclibServer.get_remote_usage()
+ -> configured Remote GET /v1/usage
+```
+
+doclib public method 命名为 `get_remote_usage()`,本地 doclib HTTP route 为 `GET /api/v1/remote-usage`,返回模型为
+`RemoteUsageResponse`。本地 route 使用 `remote-usage` 明确该资源来自 Remote API,并避免与未来可能增加的本地运行统计混淆。
+
+doclib 负责:
+
+- 读取 `parse_server.remote.url`。
+- 解析 Remote API Key。
+- 构造 Bearer authentication header;未配置 API Key 时不发送该 header。
+- 请求 Remote `/v1/usage`。
+- 保留 Remote API 的结构化错误语义。
+
+这与现有 Remote parse 路径的配置所有权和进程边界一致,不为 CLI 建立第二套配置、认证或错误处理逻辑。
+
+Remote API Key 由 doclib 中的统一 resolver 按以下优先级解析:
+
+```text
+parse_server.remote.api_key
+ > MINERU_API_KEY
+ > anonymous
+```
+
+- SQLite runtime config 中的空字符串视为未配置。
+- `MINERU_API_KEY` 是进程环境变量 fallback,不加入 `config.py` 的 startup config model,也不持久化。
+- Remote parse、Remote health probe 和 Remote usage 必须使用同一个 resolver,不能分别实现凭据回退。
+- `rate_limit_exceeded` 和 `quota_exceeded` 是否属于 anonymous 请求,根据 resolver 返回的有效 API Key 是否为空判断。
+- guidance 中的配置命令写入 `parse_server.remote.api_key`,因此会覆盖环境变量 fallback。
+
+### 3. Usage JSON 契约
+
+`mineru usage --json` 使用 CLI 自己的响应结构,并将 Remote `/v1/usage` 响应放在 `usage` 字段中:
+
+```json
+{
+ "remote_url": "https://mineru.net/api",
+ "usage": {
+ "object": "usage",
+ "access_level": "anonymous",
+ "billing_period": {
+ "start": "2026-07-14T00:00:00Z",
+ "end": "2026-07-15T00:00:00Z"
+ },
+ "current": {
+ "pages_processed": 26,
+ "files_processed": 0,
+ "jobs_created": 8
+ },
+ "limits": {
+ "max_pages_per_file": 200,
+ "max_file_size_bytes": 209715200,
+ "max_files_per_job": 200,
+ "max_concurrent_jobs": 500,
+ "max_file_retention_days": 30
+ }
+ },
+ "guidance": null
+}
+```
+
+服务端返回的限制值是运行时能力,CLI 不硬编码文档示例中的数值。
+
+doclib server 返回纯 `RemoteUsageResponse`,不生成 CLI guidance。CLI 使用一个输出模型同时服务 JSON 和文本模式;该模型添加
+`remote_url` 和可空的 `guidance`,不要求 CLI JSON 与 doclib server 响应结构一致。通用 CLI runtime 不增加专用 JSON renderer。
+
+### 4. API Key 引导只在五种时机出现
+
+只有满足本节条件时,CLI 才主动展示 API Key 引导。除此之外不主动提示注册或配置 API Key。
+
+| 时机 | 附加条件 | 是否必须配置 API Key |
+|------|----------|----------------------|
+| `mineru usage` 返回 `access_level=anonymous` | Official API | 否 |
+| `invalid_api_key` | Official API | 是,必须替换无效 API Key |
+| `feature_requires_api_key` | Official API | 是,必须配置 API Key 才能使用该能力 |
+| `rate_limit_exceeded` | Official API 且当前未配置 API Key,即 anonymous 请求 | 否;首先遵循 `Retry-After`,API Key 是提高 access level 的可选方案 |
+| `quota_exceeded` | Official API 且当前未配置 API Key,即 anonymous 请求 | 否;API Key 是切换 registered access level 的可选方案 |
+
+以下场景明确不展示 API Key 引导:
+
+- 普通 anonymous Remote parse 成功。
+- 每次 `mineru parse --remote` 开始前。
+- Local Parse Server 启动、状态或错误。
+- 与认证、特性、限流和配额无关的解析错误。
+- CLI help。
+- 自定义或 self-hosted Remote URL 返回同名错误。
+
+### 5. 只为 Official API 展示平台注册链接
+
+Official API 的 canonical base URL 是:
+
+```text
+https://mineru.net/api
+```
+
+Official API Key 管理 URL 是:
+
+```text
+https://mineru.net/apiManage/token
+```
+
+只有当前配置的 Remote URL 被严格识别为 Official API 时,才可以展示该管理 URL 和 Official API 注册文案。判断应规范化无意义的尾部 `/`,但不能把任意自定义域名、代理、self-hosted server 或仅仅返回相同错误码的服务当成 Official API。
+
+非官方 Remote Server 的注册和 API Key 签发机制未知。CLI 保留其原始成功或错误响应,但不提供 Official API 平台引导。
+
+### 6. 普通文本输出
+
+`mineru usage` 的普通文本输出完整展示:
+
+- 当前配置的 Remote URL。
+- `access_level`。
+- UTC billing period。
+- `current` 中的全部用量字段。
+- `limits` 中的全部限制字段。
+
+文件大小和保留期分别使用适合人类阅读的 MiB 和 day 单位;JSON 输出仍保留服务端原始单位和值。示例:
+
+```text
+Remote API Usage
+
+Remote URL: https://mineru.net/api
+Access level: anonymous
+Billing period: 2026-07-14 00:00 UTC - 2026-07-15 00:00 UTC
+
+Current
+ Pages processed: 26
+ Files processed: 0
+ Jobs created: 8
+
+Limits
+ Max pages per file: 200
+ Max file size: 200 MiB
+ Max files per job: 200
+ Max concurrent jobs: 500
+ File retention: 30 days
+```
+
+普通文本模式在原有成功或错误信息之后展示可操作信息,但不回显当前 API Key:
+
+```text
+Manage or create an API Key:
+https://mineru.net/apiManage/token
+
+Set the API Key:
+mineru config set parse_server.remote.api_key '<API_KEY>'
+```
+
+可选引导必须使用不会暗示注册为必需条件的文案。`invalid_api_key` 和 `feature_requires_api_key` 可以明确说明,继续当前受限操作需要有效 API Key。
+
+### 7. JSON guidance 契约
+
+错误驱动的 JSON 输出不得覆盖或向 `error.message` 拼接教程。引导使用顶层 `guidance` sibling field:
+
+```json
+{
+ "error": {
+ "type": "authentication_error",
+ "code": "invalid_api_key",
+ "message": "Remote authentication failed: user authenticate failed",
+ "param": "parse_server.remote.api_key"
+ },
+ "guidance": {
+ "type": "configure_official_api_key",
+ "required": true,
+ "message": "Configure a valid Official API Key to continue.",
+ "url": "https://mineru.net/apiManage/token",
+ "command": "mineru config set parse_server.remote.api_key '<API_KEY>'"
+ }
+}
+```
+
+Anonymous usage 的成功 JSON 在 `usage` 字段之外使用相同 guidance 结构:
+
+```json
+{
+ "remote_url": "https://mineru.net/api",
+ "usage": {
+ "object": "usage",
+ "access_level": "anonymous",
+ "billing_period": {},
+ "current": {},
+ "limits": {}
+ },
+ "guidance": {
+ "type": "configure_official_api_key",
+ "required": false,
+ "message": "An Official API Key is optional and enables registered access.",
+ "url": "https://mineru.net/apiManage/token",
+ "command": "mineru config set parse_server.remote.api_key '<API_KEY>'"
+ }
+}
+```
+
+规则:
+
+- 成功的 usage JSON 使用固定结构,没有适用引导时返回 `"guidance": null`;错误 JSON 只在存在引导时增加该字段。
+- `guidance.type` 是稳定的机器判断字段,调用方不依赖 `message` 分支。
+- `required` 明确区分必须修复和可选增强,防止 Agent 把匿名访问误判为错误。
+- `url` 和 `command` 分开,便于人类界面和 Agent 分别使用。
+- `guidance` 是 CLI JSON composition 字段,不修改 Unified API 的 `error` envelope。
+- 不复用 `ParseResponse.tip`、`ForgetPathResponse.warnings` 或 `DocContentResponse.next_request`。这些字段分别表示 parse 补充文本、操作风险和渐进读取续请求,语义更窄。
+
+### 8. Remote 错误信号与客户端归一化
+
+截至 2026-07-14,Official Remote API 的实测和现有记录如下:
+
+| 信号 | Remote 行为 | 客户端状态 |
+|------|-------------|------------|
+| `access_level=anonymous` | `GET /v1/usage` 返回标准字段 | 可直接判断 |
+| `invalid_api_key` | HTTP 401,body 仍可能使用 legacy `msgCode=A0202` / `msg=user authenticate failed` | API client 和 health probe 已归一化为 `invalid_api_key` |
+| `feature_requires_api_key` | HTTP 403,标准 `error` envelope | API client 保留 `error.code` |
+| `rate_limit_exceeded` | 已有真实 Remote parse 记录,包含标准 code 和 retry message | API client 和 doclib parse row 保留 code |
+| `quota_exceeded` | 本 ADR 按 Remote API 返回标准 `error` envelope 处理 | API client 保留 `error.code` |
+
+结构化错误必须沿以下路径保留:
+
+```text
+Remote HTTP response
+ -> MinerU API client error
+ -> doclib operation / parse row
+ -> mineru CLI error JSON
+```
+
+HTTP 401 和 legacy Official API authentication body 继续归一化为:
+
+```json
+{
+ "type": "authentication_error",
+ "code": "invalid_api_key",
+ "message": "Remote authentication failed: user authenticate failed",
+ "param": "parse_server.remote.api_key"
+}
+```
+
+`feature_requires_api_key`、`rate_limit_exceeded` 和 `quota_exceeded` 使用服务端标准 `error.code`,不通过英文 message 猜测错误类型。
+
+## 替代方案
+
+### 方案 A: CLI 直接请求 Remote `/v1/usage`
+
+未采用。
+
+这会让 CLI 直接读取 doclib runtime config 或复制配置解析逻辑,并形成第二套 HTTP、authentication 和错误归一化路径。
+
+### 方案 B: 把 Local 和 Remote usage 合并到 `mineru usage`
+
+未采用。
+
+Local Parse Server 的启动期计数不是账号配额或计费数据。混合展示会让用户误以为本地解析也受 Remote 限制。
+
+### 方案 C: 每次 anonymous Remote parse 都提示注册
+
+未采用。
+
+Anonymous 是合法使用方式。高频提示会制造注册为必要条件的错误印象,并污染 Agent 和脚本输出。
+
+### 方案 D: 把配置教程拼入 `error.message`
+
+未采用。
+
+`error` 是稳定的机器可读错误 envelope。教程、URL 和命令需要独立演进,不应改变服务端错误语义或迫使 Agent 解析自由文本。
+
+### 方案 E: 复用 `tip`、`warnings` 或 `next_request`
+
+未采用。
+
+- `tip` 是 parse response 中的自由文本字符串。
+- `warnings` 表示操作风险。
+- `next_request` 表示内容分页或续读请求。
+
+API Key 引导跨 usage success 和 error response,需要独立、结构化且可表达 required/optional 的字段。
+
+## 影响
+
+### 对 doclib
+
+- 增加查询 configured Remote `/v1/usage` 的 interface/client/server 能力。
+- Remote URL 和 API Key 继续由 doclib config service 管理。
+- Remote 标准错误码必须完整保留到调用方。
+
+### 对 CLI
+
+- 增加顶层 `mineru usage [--json]`。
+- 普通输出使用 `Remote API Usage` 标题。
+- 五种明确时机可以附加 Official API Key 引导;其他场景不主动提示。
+- JSON error envelope 保持不变,`guidance` 作为 sibling field。
+
+### 对安全和隐私
+
+- 不回显已配置 API Key。
+- `config show/get/set/unset` 继续使用现有敏感配置脱敏逻辑。
+- 不把 API Key 放入 telemetry。
+- 不向自定义 Remote Server 用户展示 Official API 注册机制。
+- 引导命令只包含 `<API_KEY>` placeholder,不包含实际凭据。
+- 不为 API Key 增加专用隐藏输入流程;现有 `config set <key> <value>` 契约保持不变。用户执行含真实 API Key 的命令时,
+ shell 是否记录命令由其 shell 配置决定,这是保持通用配置接口简单性的已知取舍。
+
+### 对兼容性
+
+- Unified API `/v1/usage` 和 error envelope 不改变。
+- `guidance` 是 MinerU CLI JSON composition 的新增可选字段。
+- JSON 调用方应继续忽略未知 sibling fields。
+
+## 后续动作
+
+1. 实现统一的 doclib Remote API Key resolver,并迁移 parse 和 health probe。
+2. 实现 doclib Remote usage contract 和 Remote HTTP 调用。
+3. 实现 `mineru usage` 普通文本与 JSON 输出。
+4. 实现 Official URL 判定和五种 API Key guidance 触发规则。
+5. 增加 Remote error normalization、doclib contract、CLI JSON 和普通文本测试。
+6. 更新 CLI、API、README、SKILL 和 E2E 文档。
diff --git a/docs/next/decisions/README.md b/docs/next/decisions/README.md
index 7db5018b..f6244ca1 100644
--- a/docs/next/decisions/README.md
+++ b/docs/next/decisions/README.md
@@ -53,6 +53,7 @@
| [ADR-0023](0023-cli-runtime-contract.md) | Accepted | CLI Runtime 输出、错误与退出码集中契约 |
| [ADR-0024](0024-file-type-tier-normalization.md) | Accepted | 文件类型与 Tier 归一化语义 |
| [ADR-0025](0025-model-download-local-dir.md) | Accepted | 模型下载与本地模型目录 |
+| [ADR-0026](0026-remote-usage-api-key-guidance.md) | Accepted | Remote API Usage 与 API Key 引导 |
## 模板
diff --git a/docs/next/sdk/doclib-client.md b/docs/next/sdk/doclib-client.md
index 97adecf3..08566a02 100644
--- a/docs/next/sdk/doclib-client.md
+++ b/docs/next/sdk/doclib-client.md
@@ -150,6 +150,15 @@ def info(self, file_path: str) -> dict: ...
`search()` 的 `files` 返回与文档 SHA 关联的全部 file aliases,按 file id 降序排列;每项包含 path、filename、ext 和 status。已索引的 orphan 文档使用空列表。active 优先只属于非 JSON CLI 展示策略,不改变 SDK 响应。搜索结果可信度只通过 `tier` 表达。
+## Remote API 方法
+
+| 方法 | 响应 |
+|------|------|
+| `get_remote_usage()` | `RemoteUsageResponse`,返回当前配置 Remote API 的 access level、billing period、current usage 和 limits。 |
+
+该方法通过 doclib 读取 Remote URL 和有效 API Key,并调用本地 doclib route `GET /api/v1/remote-usage`。它不返回 Local Parse
+Server 运行统计。
+
## Config 方法
Doclib client 暴露运行时配置能力:
diff --git a/mineru/cli/commands/__init__.py b/mineru/cli/commands/__init__.py
index 6b528a81..e466e4ab 100644
--- a/mineru/cli/commands/__init__.py
+++ b/mineru/cli/commands/__init__.py
@@ -13,6 +13,7 @@ from . import (
server,
show,
telemetry,
+ usage,
watch,
)
@@ -29,5 +30,6 @@ __all__ = [
"server",
"show",
"telemetry",
+ "usage",
"watch",
]
diff --git a/mineru/cli/commands/parse.py b/mineru/cli/commands/parse.py
index 5dea1dcb..7cff264b 100644
--- a/mineru/cli/commands/parse.py
+++ b/mineru/cli/commands/parse.py
@@ -23,6 +23,7 @@ from ...doclib.types import (
from ...errors import MineruError, error_response
from ...types import Tier
from ..contracts import CliContext, CliResult
+from ..guidance import api_key_guidance_for_error
from ..path_utils import normalize_cli_path
from ..runtime import cli_ok, emit_result, run_cli
@@ -123,6 +124,7 @@ def parse_cmd(
explicit_limit=limit is not None,
explicit_remote=remote,
),
+ error_guidance=api_key_guidance_for_error if remote else None,
)
diff --git a/mineru/cli/commands/usage.py b/mineru/cli/commands/usage.py
new file mode 100644
index 00000000..d1fc8ddb
--- /dev/null
+++ b/mineru/cli/commands/usage.py
@@ -0,0 +1,104 @@
+"""mineru usage - Remote API usage and limits."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+import typer
+from pydantic import BaseModel, Field
+
+from ...doclib.client import DoclibClient
+from ...doclib.types import RemoteUsageResponse
+from ..contracts import CliContext, RenderableOutput
+from ..guidance import (
+ REMOTE_API_URL_CONFIG,
+ api_key_guidance_for_anonymous_usage,
+ api_key_guidance_for_error,
+)
+from ..runtime import run_cli
+
+
+class RemoteUsageOutput(BaseModel):
+ remote_url: str
+ usage: RemoteUsageResponse
+ guidance: dict[str, object] | None = None
+ guidance_text: str | None = Field(default=None, exclude=True, repr=False)
+
+
+def usage_cmd(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:
+ """Show Remote API usage and limits."""
+ run_cli(
+ CliContext(json_mode=json_mode),
+ _get_remote_usage,
+ render=_render_remote_usage,
+ error_guidance=api_key_guidance_for_error,
+ )
+
+
+def _get_remote_usage() -> RemoteUsageOutput:
+ client = DoclibClient(timeout=30)
+ remote_url = client.get_config_key(REMOTE_API_URL_CONFIG).value
+ usage = client.get_remote_usage()
+ guidance = api_key_guidance_for_anonymous_usage(remote_url) if usage.access_level == "anonymous" else None
+ return RemoteUsageOutput(
+ remote_url=remote_url,
+ usage=usage,
+ guidance=guidance.data if guidance is not None else None,
+ guidance_text=guidance.text if guidance is not None else None,
+ )
+
+
+def _render_remote_usage(view: RemoteUsageOutput) -> RenderableOutput:
+ usage = view.usage
+ lines = [
+ "Remote API Usage",
+ "",
+ f"Remote URL: {view.remote_url}",
+ f"Access level: {usage.access_level}",
+ f"Billing period: {_format_billing_period(usage.billing_period.start, usage.billing_period.end)}",
+ "",
+ "Current",
+ f" Pages processed: {usage.current.pages_processed}",
+ f" Files processed: {usage.current.files_processed}",
+ f" Jobs created: {usage.current.jobs_created}",
+ "",
+ "Limits",
+ f" Max pages per file: {usage.limits.max_pages_per_file}",
+ f" Max file size: {_format_bytes(usage.limits.max_file_size_bytes)}",
+ f" Max files per job: {usage.limits.max_files_per_job}",
+ f" Max concurrent jobs: {usage.limits.max_concurrent_jobs}",
+ f" File retention: {_format_retention(usage.limits.max_file_retention_days)}",
+ ]
+ output: list[str] = ["\n".join(lines)]
+ if view.guidance_text is not None:
+ output.append(view.guidance_text)
+ return output
+
+
+def _format_billing_period(start: str, end: str | None) -> str:
+ formatted_start = _format_utc_timestamp(start)
+ if end is None:
+ return f"{formatted_start} - ongoing"
+ return f"{formatted_start} - {_format_utc_timestamp(end)}"
+
+
+def _format_utc_timestamp(value: str) -> str:
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
+ except ValueError:
+ return value
+ return parsed.strftime("%Y-%m-%d %H:%M UTC")
+
+
+def _format_bytes(value: int) -> str:
+ mib = value / (1024 * 1024)
+ return f"{mib:g} MiB"
+
+
+def _format_retention(days: int | None) -> str:
+ if days is None:
+ return "not specified"
+ return f"{days} day" if days == 1 else f"{days} days"
+
+
+__all__ = ["usage_cmd"]
diff --git a/mineru/cli/contracts.py b/mineru/cli/contracts.py
index e202fb01..496f8ec3 100644
--- a/mineru/cli/contracts.py
+++ b/mineru/cli/contracts.py
@@ -16,6 +16,12 @@ RenderableOutput: TypeAlias = RenderableObject | Iterable[RenderableObject]
CliRenderer = Callable[[T], RenderableOutput | None]
+@dataclass(frozen=True)
+class CliGuidance:
+ data: dict[str, object]
+ text: str
+
+
@dataclass(frozen=True)
class CliContext:
json_mode: bool
diff --git a/mineru/cli/guidance.py b/mineru/cli/guidance.py
new file mode 100644
index 00000000..7b82f766
--- /dev/null
+++ b/mineru/cli/guidance.py
@@ -0,0 +1,112 @@
+"""Structured CLI guidance for Official Remote API access."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from urllib.parse import urlsplit
+
+from ..doclib.client import DoclibClient
+from ..errors import MineruError
+from .contracts import CliGuidance
+
+OFFICIAL_REMOTE_API_URL = "https://mineru.net/api"
+OFFICIAL_API_KEY_URL = "https://mineru.net/apiManage/token"
+REMOTE_API_KEY_CONFIG = "parse_server.remote.api_key"
+REMOTE_API_URL_CONFIG = "parse_server.remote.url"
+SET_API_KEY_COMMAND = "mineru config set parse_server.remote.api_key '<API_KEY>'"
+
+
+@dataclass(frozen=True)
+class RemoteApiContext:
+ remote_url: str
+ api_key_configured: bool
+
+
+def is_official_remote_url(url: str) -> bool:
+ """Return whether ``url`` is the canonical Official API base URL."""
+ try:
+ parsed = urlsplit(url)
+ port = parsed.port
+ except ValueError:
+ return False
+ return (
+ parsed.scheme.lower() == "https"
+ and parsed.hostname == "mineru.net"
+ and port in (None, 443)
+ and parsed.path.rstrip("/") == "/api"
+ and not parsed.username
+ and not parsed.password
+ and not parsed.query
+ and not parsed.fragment
+ )
+
+
+def load_remote_api_context() -> RemoteApiContext:
+ """Read effective Remote API configuration through doclib."""
+ config = DoclibClient(timeout=3).get_config()
+ return RemoteApiContext(
+ remote_url=config.config.get(REMOTE_API_URL_CONFIG, ""),
+ api_key_configured=bool(config.config.get(REMOTE_API_KEY_CONFIG, "")),
+ )
+
+
+def api_key_guidance_for_error(error: MineruError) -> CliGuidance | None:
+ """Return Official API Key guidance for one eligible Remote error."""
+ if error.code not in {"invalid_api_key", "feature_requires_api_key", "rate_limit_exceeded", "quota_exceeded"}:
+ return None
+
+ context = load_remote_api_context()
+ if not is_official_remote_url(context.remote_url):
+ return None
+
+ if error.code == "invalid_api_key":
+ return _api_key_guidance(required=True, message="Configure a valid Official API Key to continue.")
+ if error.code == "feature_requires_api_key":
+ return _api_key_guidance(required=True, message="This Remote API feature requires an Official API Key.")
+ if context.api_key_configured:
+ return None
+ if error.code == "rate_limit_exceeded":
+ return _api_key_guidance(
+ required=False,
+ message="An Official API Key is optional and may provide registered rate limits.",
+ )
+ return _api_key_guidance(
+ required=False,
+ message="An Official API Key is optional and enables registered access.",
+ )
+
+
+def api_key_guidance_for_anonymous_usage(remote_url: str) -> CliGuidance | None:
+ if not is_official_remote_url(remote_url):
+ return None
+ return _api_key_guidance(
+ required=False,
+ message="An Official API Key is optional and enables registered access.",
+ )
+
+
+def _api_key_guidance(*, required: bool, message: str) -> CliGuidance:
+ return CliGuidance(
+ data={
+ "type": "configure_official_api_key",
+ "required": required,
+ "message": message,
+ "url": OFFICIAL_API_KEY_URL,
+ "command": SET_API_KEY_COMMAND,
+ },
+ text=(f"{message}\n\nManage or create an API Key:\n{OFFICIAL_API_KEY_URL}\n\nSet the API Key:\n{SET_API_KEY_COMMAND}"),
+ )
+
+
+__all__ = [
+ "OFFICIAL_API_KEY_URL",
+ "OFFICIAL_REMOTE_API_URL",
+ "REMOTE_API_KEY_CONFIG",
+ "REMOTE_API_URL_CONFIG",
+ "RemoteApiContext",
+ "SET_API_KEY_COMMAND",
+ "api_key_guidance_for_anonymous_usage",
+ "api_key_guidance_for_error",
+ "is_official_remote_url",
+ "load_remote_api_context",
+]
diff --git a/mineru/cli/main.py b/mineru/cli/main.py
index c29d4fdd..fd0d8983 100644
--- a/mineru/cli/main.py
+++ b/mineru/cli/main.py
@@ -9,7 +9,7 @@ import typer
from click.core import Context
from typer.core import TyperGroup
-from .commands import cleanup, config, list_resources, server, show, telemetry, watch
+from .commands import cleanup, config, list_resources, server, show, telemetry, usage, watch
from .commands.forget import forget_cmd
from .commands.invalidate import invalidate_cmd
from .commands.parse import parse_cmd
@@ -26,6 +26,7 @@ class VersionInfo:
mineru_version: str
python_version: str
+
# Typer stores commands and command groups separately before building the Click
# command tree, so source registration order alone does not preserve the mixed
# top-level help order.
@@ -36,6 +37,7 @@ TOP_LEVEL_COMMAND_ORDER = [
"watch",
"search",
"find",
+ "usage",
"list",
"show",
"telemetry",
@@ -78,6 +80,7 @@ app.command("scan")(scan_cmd)
app.add_typer(watch.app, name="watch")
app.command("search")(search_cmd)
app.command("find")(find_cmd)
+app.command("usage")(usage.usage_cmd)
app.add_typer(list_resources.app, name="list")
app.add_typer(show.app, name="show")
app.add_typer(telemetry.app, name="telemetry")
diff --git a/mineru/cli/runtime.py b/mineru/cli/runtime.py
index 191e4273..1ab1e9e6 100644
--- a/mineru/cli/runtime.py
+++ b/mineru/cli/runtime.py
@@ -11,7 +11,15 @@ import typer
from ..errors import MineruError, ServerNotRunningError, error_response
from . import output
-from .contracts import CliContext, CliRenderer, CliResult, CliTaskResult, RenderableOutput, RichObject
+from .contracts import (
+ CliContext,
+ CliGuidance,
+ CliRenderer,
+ CliResult,
+ CliTaskResult,
+ RenderableOutput,
+ RichObject,
+)
T = TypeVar("T")
@@ -59,6 +67,7 @@ def run_cli(
action: Callable[[], T | CliResult[T]],
*,
render: CliRenderer[T] | None = None,
+ error_guidance: Callable[[MineruError], CliGuidance | None] | None = None,
warnings: Callable[[T], list[str]] | None = None,
notices: Callable[[T], list[str]] | None = None,
exit_code: int | Callable[[T], int] = 0,
@@ -68,8 +77,15 @@ def run_cli(
except typer.Exit:
raise
except Exception as exc:
- emit_error(ctx, exc)
- result = _coerce_result(value, render=render, warnings=warnings, notices=notices, exit_code=exit_code)
+ guidance = _resolve_error_guidance(exc, error_guidance)
+ emit_error(ctx, exc, guidance=guidance)
+ result = _coerce_result(
+ value,
+ render=render,
+ warnings=warnings,
+ notices=notices,
+ exit_code=exit_code,
+ )
emit_result(ctx, result)
@@ -97,12 +113,17 @@ def emit_result(ctx: CliContext, result: CliResult[T]) -> None:
raise typer.Exit(exit_code)
-def emit_error(ctx: CliContext, exc: Exception) -> NoReturn:
+def emit_error(ctx: CliContext, exc: Exception, *, guidance: CliGuidance | None = None) -> NoReturn:
mineru_error = to_mineru_error(exc)
if ctx.json_mode:
- output.print_json(error_response(mineru_error))
+ payload = error_response(mineru_error)
+ if guidance is not None:
+ payload["guidance"] = guidance.data
+ output.print_json(payload)
else:
output.print_error(mineru_error.message or str(exc))
+ if guidance is not None:
+ output.print_notice(guidance.text)
raise typer.Exit(1) from None
@@ -165,6 +186,18 @@ def _coerce_result(
)
+def _resolve_error_guidance(
+ exc: Exception,
+ resolver: Callable[[MineruError], CliGuidance | None] | None,
+) -> CliGuidance | None:
+ if resolver is None:
+ return None
+ try:
+ return resolver(to_mineru_error(exc))
+ except Exception:
+ return None
+
+
def _parse_error_tuple(raw: str) -> tuple[str, str, str | None] | None:
try:
value = ast.literal_eval(raw)
diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.py
index ac0d8f6d..69cdc155 100644
--- a/mineru/doclib/background/parse_server_health.py
+++ b/mineru/doclib/background/parse_server_health.py
@@ -20,6 +20,7 @@ from ...config import LogConfig, ManagedParseServerConfig, config
from ...parser.api_client import should_trust_env_for_url
from ...types import TIERS, Tier, validate_tier
from ..config_defaults import CONFIG_DEFAULTS
+from ..remote_api import resolve_remote_api_key
logger = logging.getLogger("mineru.health_check")
@@ -299,7 +300,7 @@ class ParseServerHealthCheck:
# probe remote
remote_url = cast(str, await self.config_svc.get("parse_server.remote.url"))
- remote_api_key = (await self.config_svc.get("parse_server.remote.api_key")) or None
+ remote_api_key = (await resolve_remote_api_key(self.config_svc)).value
probe = await self._probe(remote_url, api_key=remote_api_key)
now_ms = int(time.time() * 1000)
health.remote.url = remote_url
@@ -323,9 +324,7 @@ class ParseServerHealthCheck:
await asyncio.sleep(self.interval_sec)
- async def _try_restart_managed_for_tier_change(
- self, health: ParseServerHealth, desired_managed_tier: Tier
- ) -> bool:
+ async def _try_restart_managed_for_tier_change(self, health: ParseServerHealth, desired_managed_tier: Tier) -> bool:
running_managed_tier = health.running_managed_tier
if running_managed_tier is None or running_managed_tier == desired_managed_tier:
return False
@@ -352,9 +351,7 @@ class ParseServerHealthCheck:
count_restart: bool = True,
) -> None:
if count_restart and health.restart_count >= MAX_RESTART_ATTEMPTS:
- logger.error(
- "Managed parse-server failed %d restarts, disabling", MAX_RESTART_ATTEMPTS
- )
+ logger.error("Managed parse-server failed %d restarts, disabling", MAX_RESTART_ATTEMPTS)
health.local_mode = "disabled"
return
diff --git a/mineru/doclib/base.py b/mineru/doclib/base.py
index d00ff83d..a5be8c74 100644
--- a/mineru/doclib/base.py
+++ b/mineru/doclib/base.py
@@ -46,6 +46,7 @@ from .types import (
RemoveExcludeRuleResponse,
RemoveParsingRuleResponse,
RemoveWatchResponse,
+ RemoteUsageResponse,
ScanInfo,
ScanKind,
ScanListResponse,
@@ -353,6 +354,15 @@ class DoclibInterface(ABC):
"""
raise NotImplementedError()
+ @abstractmethod
+ def get_remote_usage(self) -> RemoteUsageResponse:
+ """Return usage and limits from the configured Remote API.
+
+ Raises:
+ MineruError: for Remote API authentication, permission, rate limit, transport, or response failures.
+ """
+ raise NotImplementedError()
+
@abstractmethod
def get_config(self) -> ConfigResponse:
"""Return runtime doclib key-value config.
@@ -704,6 +714,11 @@ class AsyncDoclibInterface(ABC):
"""Async version of ``DoclibInterface.get_file_by_path``."""
raise NotImplementedError()
+ @abstractmethod
+ async def get_remote_usage(self) -> RemoteUsageResponse:
+ """Async version of ``DoclibInterface.get_remote_usage``."""
+ raise NotImplementedError()
+
@abstractmethod
async def get_config(self) -> ConfigResponse:
"""Async version of ``DoclibInterface.get_config``."""
diff --git a/mineru/doclib/client.py b/mineru/doclib/client.py
index fdf8f946..fb7a006e 100644
--- a/mineru/doclib/client.py
+++ b/mineru/doclib/client.py
@@ -61,6 +61,7 @@ from .types import (
RemoveExcludeRuleResponse,
RemoveParsingRuleResponse,
RemoveWatchResponse,
+ RemoteUsageResponse,
ScanInfo,
ScanKind,
ScanListResponse,
@@ -306,6 +307,10 @@ class DoclibClient(DoclibInterface):
def get_file_by_path(self, path: str) -> FileInfoResponse:
return self._request_model(FileInfoResponse, params={"path": path})
+ @route("GET", "/remote-usage", tags=("remote",))
+ def get_remote_usage(self) -> RemoteUsageResponse:
+ return self._request_model(RemoteUsageResponse)
+
@route("GET", "/configs", tags=("config",))
def get_config(self) -> ConfigResponse:
return self._request_model(ConfigResponse)
diff --git a/mineru/doclib/remote_api.py b/mineru/doclib/remote_api.py
new file mode 100644
index 00000000..4fafe742
--- /dev/null
+++ b/mineru/doclib/remote_api.py
@@ -0,0 +1,43 @@
+"""Remote API runtime configuration helpers."""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Literal
+
+if TYPE_CHECKING:
+ from .services.config_svc import ConfigService
+
+REMOTE_API_KEY_CONFIG = "parse_server.remote.api_key"
+REMOTE_API_KEY_ENV = "MINERU_API_KEY"
+
+RemoteApiKeySource = Literal["override", "environment", "anonymous"]
+
+
+@dataclass(frozen=True)
+class ResolvedRemoteApiKey:
+ value: str | None
+ source: RemoteApiKeySource
+
+
+async def resolve_remote_api_key(config_svc: ConfigService) -> ResolvedRemoteApiKey:
+ """Resolve one effective Remote API Key for all doclib Remote callers."""
+ configured = (await config_svc.get(REMOTE_API_KEY_CONFIG)) or ""
+ if configured:
+ return ResolvedRemoteApiKey(value=configured, source="override")
+
+ environment = os.environ.get(REMOTE_API_KEY_ENV, "")
+ if environment:
+ return ResolvedRemoteApiKey(value=environment, source="environment")
+
+ return ResolvedRemoteApiKey(value=None, source="anonymous")
+
+
+__all__ = [
+ "REMOTE_API_KEY_CONFIG",
+ "REMOTE_API_KEY_ENV",
+ "RemoteApiKeySource",
+ "ResolvedRemoteApiKey",
+ "resolve_remote_api_key",
+]
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index a5a2da25..8cd2eec7 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -17,6 +17,7 @@ from urllib.parse import urlparse
from fastapi import APIRouter, FastAPI, Request
from fastapi.responses import JSONResponse
from PIL import Image
+from pydantic import ValidationError
from ..config import config
from ..errors import InvalidRequestError, MineruError, NotFoundError, error_response, http_status_for
@@ -34,6 +35,7 @@ from .base import AsyncDoclibInterface
from .config_schema import validate_config_value
from .core.db import DatabaseManager
from .locators import ContentCursor, block_char_ref, block_ref, page_ref, parse_content_cursor
+from .remote_api import REMOTE_API_KEY_CONFIG, resolve_remote_api_key
from .rows import (
ContentSearchResultRow,
DocRow,
@@ -81,6 +83,7 @@ from .types import (
ConfigResponse,
ConfigSetRequest,
ConfigSetResponse,
+ ConfigSource,
ConfigUnsetResponse,
ConfigValueResponse,
ContentAsset,
@@ -124,6 +127,7 @@ from .types import (
RemoveExcludeRuleResponse,
RemoveParsingRuleResponse,
RemoveWatchResponse,
+ RemoteUsageResponse,
ScanInfo,
ScanKind,
ScanListResponse,
@@ -824,25 +828,56 @@ class DoclibServer(AsyncDoclibInterface):
active_parses=active_parses,
)
+ @route("GET", "/remote-usage", tags=("remote",))
+ async def get_remote_usage(self) -> RemoteUsageResponse:
+ from ..parser.api_client import MinerUApiParser, _APITransportError, _V1APIError
+
+ remote_url = cast(str, await self.state.config_svc.get("parse_server.remote.url"))
+ resolved_api_key = await resolve_remote_api_key(self.state.config_svc)
+ client = MinerUApiParser(api_url=remote_url, api_key=resolved_api_key.value)
+ try:
+ payload = await client.get_usage_async()
+ except _APITransportError as exc:
+ code = "remote_timeout" if exc.timed_out else "remote_unreachable"
+ raise MineruError(
+ code,
+ f"Remote API transport failed during {exc.stage} after {exc.attempts} attempt(s) ({type(exc.cause).__name__}).",
+ ) from exc
+ except _V1APIError as exc:
+ raise MineruError(exc.code, exc.message, exc.param) from exc
+ try:
+ return RemoteUsageResponse.model_validate(payload)
+ except ValidationError as exc:
+ raise MineruError("api_error", "Remote API returned an invalid usage response.") from exc
+
@route("GET", "/configs", tags=("config",))
async def get_config(self) -> ConfigResponse:
config, sources = await self.state.config_svc.get_all_with_sources()
+ resolved_api_key = await resolve_remote_api_key(self.state.config_svc)
+ if resolved_api_key.value is not None:
+ config[REMOTE_API_KEY_CONFIG] = resolved_api_key.value
+ sources[REMOTE_API_KEY_CONFIG] = resolved_api_key.source
return ConfigResponse(config=_mask_config(config), sources=sources)
@route("GET", "/configs/{key}", tags=("config",))
async def get_config_key(self, key: str) -> ConfigValueResponse:
- value = await self.state.config_svc.get(key)
- source = await self.state.config_svc.get_source(key)
+ value, source = await self._effective_config_value(key)
return ConfigValueResponse(key=key, value=_mask_config_value(key, value or ""), source=source)
@route("PUT", "/configs/{key}", tags=("config",))
async def set_config(self, key: str, request: ConfigSetRequest) -> ConfigSetResponse:
await self._validate_config_set(key, request.value)
await self.state.config_svc.set(key, request.value)
- value = await self.state.config_svc.get(key)
- source = await self.state.config_svc.get_source(key)
+ value, source = await self._effective_config_value(key)
return ConfigSetResponse(key=key, value=_mask_config_value(key, value or ""), source=source)
+ async def _effective_config_value(self, key: str) -> tuple[str | None, ConfigSource]:
+ if key == REMOTE_API_KEY_CONFIG:
+ resolved = await resolve_remote_api_key(self.state.config_svc)
+ source = "default" if resolved.source == "anonymous" else resolved.source
+ return resolved.value, source
+ return await self.state.config_svc.get(key), await self.state.config_svc.get_source(key)
+
async def _validate_config_set(self, key: str, value: str) -> None:
validate_config_value(key, value)
if key == "parse_server.local.mode":
@@ -858,8 +893,7 @@ class DoclibServer(AsyncDoclibInterface):
@route("DELETE", "/configs/{key}", tags=("config",))
async def unset_config(self, key: str) -> ConfigUnsetResponse:
removed = await self.state.config_svc.unset(key)
- value = await self.state.config_svc.get(key)
- source = await self.state.config_svc.get_source(key)
+ value, source = await self._effective_config_value(key)
return ConfigUnsetResponse(key=key, value=_mask_config_value(key, value or ""), source=source, removed=removed)
@route("POST", "/watches", tags=("watches",))
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index f94b1334..851fc097 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -30,6 +30,7 @@ from ...types import QUALITY_TIERS, TIER_ORDER, PageInfo, Tier, select_default_q
from ..core.db import DatabaseManager
from ..core.file_io import FileStat, MetadataExtractionError, compute_sha256, extract_metadata, get_file_stat
from ..core.fts import FTSManager
+from ..remote_api import resolve_remote_api_key
from ..rows import DocRow, FileRow, ParseBatchRow, ParseRow, Sha256Row, ShortIdRow, WatchTargetRow
from ..types import (
FILE_STATUS_ACTIVE,
@@ -1130,7 +1131,7 @@ class ParseService:
if privacy == "remote":
url = cast(str, await self.config_svc.get("parse_server.remote.url"))
- api_key = (await self.config_svc.get("parse_server.remote.api_key")) or None
+ api_key = (await resolve_remote_api_key(self.config_svc)).value
if not health.remote.probe.healthy:
if health.remote.probe.error_code == "invalid_api_key":
raise ParseFailure(
diff --git a/mineru/doclib/types.py b/mineru/doclib/types.py
index 7120d0bc..395837ff 100644
--- a/mineru/doclib/types.py
+++ b/mineru/doclib/types.py
@@ -20,7 +20,8 @@ TelemetryConsentState = Literal["unset", "enabled", "disabled"]
TelemetryAction = Literal["enable", "disable", "flush"]
InvalidateTarget = Literal["parses"]
ForgetMatchedAs = Literal["file", "directory", "none"]
-ConfigSource = Literal["default", "override"]
+ConfigSource = Literal["default", "override", "environment"]
+RemoteAccessLevel = Literal["anonymous", "registered"]
ContentFormat = Literal["markdown", "image"]
ImageFormat = Literal["jpeg", "png", "webp"]
@@ -398,6 +399,33 @@ class ConfigUnsetResponse(ConfigValueResponse):
removed: bool = True
+class RemoteUsageBillingPeriod(DoclibModel):
+ start: str
+ end: str | None = None
+
+
+class RemoteUsageCurrent(DoclibModel):
+ pages_processed: int = 0
+ files_processed: int = 0
+ jobs_created: int = 0
+
+
+class RemoteUsageLimits(DoclibModel):
+ max_pages_per_file: int
+ max_file_size_bytes: int
+ max_files_per_job: int
+ max_concurrent_jobs: int
+ max_file_retention_days: int | None = None
+
+
+class RemoteUsageResponse(DoclibModel):
+ object: Literal["usage"] = "usage"
+ access_level: RemoteAccessLevel
+ billing_period: RemoteUsageBillingPeriod
+ current: RemoteUsageCurrent
+ limits: RemoteUsageLimits
+
+
class WatchRequest(DoclibModel):
path: str
removable: bool = False
diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.py
index c09f8ff1..cab747a9 100644
--- a/mineru/parser/api_client.py
+++ b/mineru/parser/api_client.py
@@ -115,6 +115,30 @@ class MinerUApiParser(DocumentParser):
job = await self._async_do_parse(payload)
return await self._async_build_result(job, file_path.name)
+ def get_usage(self) -> dict[str, Any]:
+ """Return usage and limits for the configured API identity."""
+ with httpx.Client(timeout=httpx.Timeout(30, connect=10), trust_env=self._trust_env) as cli:
+ response = _request_with_retry(
+ cli,
+ "GET",
+ f"{self._base_url}/v1/usage",
+ stage="usage query",
+ headers=self._headers(),
+ )
+ return self._check(response)
+
+ async def get_usage_async(self) -> dict[str, Any]:
+ """Asynchronous version of :meth:`get_usage`."""
+ async with httpx.AsyncClient(timeout=httpx.Timeout(30, connect=10), trust_env=self._trust_env) as cli:
+ response = await _async_request_with_retry(
+ cli,
+ "GET",
+ f"{self._base_url}/v1/usage",
+ stage="usage query",
+ headers=self._headers(),
+ )
+ return self._check(response)
+
# ── payload construction ─────────────────────────────────────────
def _build_source(self, file_path: Path) -> dict[str, Any]:
diff --git a/skills/mineru/SKILL.md b/skills/mineru/SKILL.md
index 77b55a64..1f7bfb24 100644
--- a/skills/mineru/SKILL.md
+++ b/skills/mineru/SKILL.md
@@ -75,6 +75,7 @@ Use this decision tree before running commands:
8. User asks to add or refresh a watched folder: use `mineru watch` or `mineru scan`.
9. User asks MinerU to forget a file or folder without deleting it: use `mineru forget`.
10. User asks to force a reparse: use `mineru parse --force` or `mineru invalidate`.
+11. User asks for Remote API usage or limits: use `mineru usage --json`.
## Common Workflows
@@ -695,6 +696,14 @@ Rules:
- `--remote` or a remote-enabled parsing rule is still required.
- Avoid printing secrets from config.
+## Remote API Usage
+
+Use `usage` only for the configured Remote API; Local Parse Servers do not have account usage limits:
+
+```bash
+mineru usage --json
+```
+
## JSON Output
Use `--json` when an agent needs stable machine-readable fields.
diff --git a/tests/unittest/test_cli_command_contract.py b/tests/unittest/test_cli_command_contract.py
index ffd34479..4d1ef4c2 100644
--- a/tests/unittest/test_cli_command_contract.py
+++ b/tests/unittest/test_cli_command_contract.py
@@ -34,6 +34,7 @@ MIGRATED_QUERY_COMMANDS = {
"commands/server.py",
"commands/show.py",
"commands/telemetry.py",
+ "commands/usage.py",
"commands/watch.py",
}
diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.py
index 8061afd1..b53213b7 100644
--- a/tests/unittest/test_cli_next_command_design.py
+++ b/tests/unittest/test_cli_next_command_design.py
@@ -134,6 +134,7 @@ def test_root_commands_keep_product_order() -> None:
"watch",
"search",
"find",
+ "usage",
"list",
"show",
"telemetry",
@@ -771,7 +772,21 @@ def test_parse_wait_json_maps_invalid_api_key_param(monkeypatch: Any, tmp_path:
def list_parses(self, **kwargs: Any) -> ListParsesResponse:
return ListParsesResponse(parses=[failed], total=1, limit=50, offset=0)
+ class _GuidanceClient:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 3
+
+ def get_config(self) -> ConfigResponse:
+ return ConfigResponse(
+ config={
+ "parse_server.remote.url": "https://mineru.net/api",
+ "parse_server.remote.api_key": "******",
+ },
+ sources={},
+ )
+
monkeypatch.setattr(parse, "DoclibClient", _Client)
+ monkeypatch.setattr("mineru.cli.guidance.DoclibClient", _GuidanceClient)
monkeypatch.setattr(parse.time, "sleep", lambda seconds: None)
result = runner.invoke(app, ["parse", str(source), "--remote", "--wait", "1", "--json"])
@@ -781,6 +796,8 @@ def test_parse_wait_json_maps_invalid_api_key_param(monkeypatch: Any, tmp_path:
assert payload["error"]["type"] == "authentication_error"
assert payload["error"]["code"] == "invalid_api_key"
assert payload["error"]["param"] == "parse_server.remote.api_key"
+ assert payload["guidance"]["type"] == "configure_official_api_key"
+ assert payload["guidance"]["required"] is True
def test_parse_wait_json_handles_failed_row_without_error_details(monkeypatch: Any, tmp_path: Path) -> None:
diff --git a/tests/unittest/test_cli_runtime_contract.py b/tests/unittest/test_cli_runtime_contract.py
index 7befc7f4..e5e6c702 100644
--- a/tests/unittest/test_cli_runtime_contract.py
+++ b/tests/unittest/test_cli_runtime_contract.py
@@ -9,7 +9,7 @@ import typer
from mineru.cli import output
from mineru.cli import contracts
-from mineru.cli.contracts import CliContext
+from mineru.cli.contracts import CliContext, CliGuidance
from mineru.cli.runtime import cli_ok, cli_task, emit_error, emit_result, run_cli
from mineru.errors import MineruError
@@ -131,6 +131,48 @@ def test_emit_error_non_json_writes_human_error_to_stderr(capsys: pytest.Capture
assert captured.err == "Error: File missing.\n"
+def test_emit_error_json_adds_guidance_without_changing_error(capsys: pytest.CaptureFixture[str]) -> None:
+ guidance = CliGuidance(
+ data={"type": "configure_official_api_key", "required": True},
+ text="Configure an API Key.",
+ )
+
+ with pytest.raises(typer.Exit) as exc_info:
+ emit_error(
+ CliContext(json_mode=True),
+ MineruError("invalid_api_key", "Invalid API Key.", "parse_server.remote.api_key"),
+ guidance=guidance,
+ )
+
+ captured = capsys.readouterr()
+ assert exc_info.value.exit_code == 1
+ assert json.loads(captured.out) == {
+ "error": {
+ "type": "authentication_error",
+ "code": "invalid_api_key",
+ "message": "Invalid API Key.",
+ "param": "parse_server.remote.api_key",
+ },
+ "guidance": {"type": "configure_official_api_key", "required": True},
+ }
+
+
+def test_run_cli_error_guidance_failure_does_not_hide_original_error(capsys: pytest.CaptureFixture[str]) -> None:
+ def fail_guidance(_error: MineruError) -> CliGuidance | None:
+ raise RuntimeError("guidance unavailable")
+
+ with pytest.raises(typer.Exit) as exc_info:
+ run_cli(
+ CliContext(json_mode=True),
+ lambda: (_ for _ in ()).throw(MineruError("invalid_api_key", "Invalid API Key.")),
+ error_guidance=fail_guidance,
+ )
+
+ captured = capsys.readouterr()
+ assert exc_info.value.exit_code == 1
+ assert json.loads(captured.out)["error"]["code"] == "invalid_api_key"
+
+
def test_emit_result_writes_notices_and_warnings_to_stderr(capsys: pytest.CaptureFixture[str]) -> None:
result = cli_ok(
{"status": "done"},
diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.py
index 32c03546..ad4ccf85 100644
--- a/tests/unittest/test_doclib_interface_contract.py
+++ b/tests/unittest/test_doclib_interface_contract.py
@@ -87,6 +87,7 @@ def test_doclib_interface_declares_expected_methods() -> None:
"search",
"find",
"get_file_by_path",
+ "get_remote_usage",
"get_config",
"get_config_key",
"set_config",
@@ -207,6 +208,7 @@ def test_interface_app_uses_doclib_server_routes(tmp_path) -> None:
assert "/api/v1/docs" in route_paths
assert "/api/v1/docs/{doc_ref}" in route_paths
assert "/api/v1/content" in route_paths
+ assert "/api/v1/remote-usage" in route_paths
assert "/api/v1/docs/{doc_ref}/exports" in route_paths
assert "/api/docs" in route_paths
assert "/docs" not in route_paths
diff --git a/tests/unittest/test_remote_usage.py b/tests/unittest/test_remote_usage.py
new file mode 100644
index 00000000..5d167518
--- /dev/null
+++ b/tests/unittest/test_remote_usage.py
@@ -0,0 +1,362 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from typer.testing import CliRunner
+
+from mineru.cli import guidance
+from mineru.cli.commands import usage
+from mineru.cli.main import app
+from mineru.doclib.remote_api import ResolvedRemoteApiKey, resolve_remote_api_key
+from mineru.doclib.server import DoclibServer
+from mineru.doclib.types import ConfigResponse, ConfigValueResponse, RemoteUsageResponse
+from mineru.errors import MineruError
+from mineru.parser.api_client import MinerUApiParser
+
+runner = CliRunner()
+
+
+def _usage_response(access_level: str = "anonymous") -> RemoteUsageResponse:
+ return RemoteUsageResponse.model_validate(
+ {
+ "object": "usage",
+ "access_level": access_level,
+ "billing_period": {"start": "2026-07-14T00:00:00Z", "end": "2026-07-15T00:00:00Z"},
+ "current": {"pages_processed": 26, "files_processed": 2, "jobs_created": 8},
+ "limits": {
+ "max_pages_per_file": 200,
+ "max_file_size_bytes": 209715200,
+ "max_files_per_job": 200,
+ "max_concurrent_jobs": 500,
+ "max_file_retention_days": 30,
+ },
+ }
+ )
+
+
+class _UsageClient:
+ remote_url = guidance.OFFICIAL_REMOTE_API_URL
+ response = _usage_response()
+
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def get_config_key(self, key: str) -> ConfigValueResponse:
+ assert key == guidance.REMOTE_API_URL_CONFIG
+ return ConfigValueResponse(key=key, value=self.remote_url, source="default")
+
+ def get_remote_usage(self) -> RemoteUsageResponse:
+ return self.response
+
+
+class _GuidanceConfigClient:
+ remote_url = guidance.OFFICIAL_REMOTE_API_URL
+ api_key = ""
+
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 3
+
+ def get_config(self) -> ConfigResponse:
+ return ConfigResponse(
+ config={
+ guidance.REMOTE_API_URL_CONFIG: self.remote_url,
+ guidance.REMOTE_API_KEY_CONFIG: self.api_key,
+ },
+ sources={},
+ )
+
+
+def test_remote_api_key_resolver_prefers_override(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _ConfigService:
+ async def get(self, key: str) -> str:
+ assert key == "parse_server.remote.api_key"
+ return "config-key"
+
+ monkeypatch.setenv("MINERU_API_KEY", "env-key")
+
+ result = asyncio.run(resolve_remote_api_key(_ConfigService())) # type: ignore[arg-type]
+
+ assert result == ResolvedRemoteApiKey(value="config-key", source="override")
+
+
+def test_remote_api_key_resolver_falls_back_to_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _ConfigService:
+ async def get(self, key: str) -> str:
+ assert key == "parse_server.remote.api_key"
+ return ""
+
+ monkeypatch.setenv("MINERU_API_KEY", "env-key")
+
+ result = asyncio.run(resolve_remote_api_key(_ConfigService())) # type: ignore[arg-type]
+
+ assert result == ResolvedRemoteApiKey(value="env-key", source="environment")
+
+
+def test_remote_api_key_resolver_returns_anonymous(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _ConfigService:
+ async def get(self, key: str) -> str:
+ assert key == "parse_server.remote.api_key"
+ return ""
+
+ monkeypatch.delenv("MINERU_API_KEY", raising=False)
+
+ result = asyncio.run(resolve_remote_api_key(_ConfigService())) # type: ignore[arg-type]
+
+ assert result == ResolvedRemoteApiKey(value=None, source="anonymous")
+
+
+ ("url", "expected"),
+ [
+ ("https://mineru.net/api", True),
+ ("https://mineru.net/api/", True),
+ ("https://mineru.net:443/api", True),
+ ("http://mineru.net/api", False),
+ ("https://staging.mineru.net/api", False),
+ ("https://mineru.net/api/proxy", False),
+ ("https://mineru.net/api?target=custom", False),
+ ],
+)
+def test_official_remote_url_detection_is_strict(url: str, expected: bool) -> None:
+ assert guidance.is_official_remote_url(url) is expected
+
+
+def test_api_client_get_usage_async_uses_usage_endpoint_and_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[tuple[str, dict[str, str]]] = []
+
+ class _Response:
+ status_code = 200
+ text = ""
+
+ def json(self) -> dict[str, Any]:
+ return _usage_response().model_dump()
+
+ class _AsyncClient:
+ def __init__(self, **kwargs: Any) -> None:
+ assert kwargs["trust_env"] is True
+
+ async def __aenter__(self) -> "_AsyncClient":
+ return self
+
+ async def __aexit__(self, *args: object) -> None:
+ return None
+
+ async def get(self, url: str, *, headers: dict[str, str]) -> _Response:
+ calls.append((url, headers))
+ return _Response()
+
+ monkeypatch.setattr("mineru.parser.api_client.httpx.AsyncClient", _AsyncClient)
+ parser = MinerUApiParser(api_url=guidance.OFFICIAL_REMOTE_API_URL, api_key="api-key")
+
+ result = asyncio.run(parser.get_usage_async())
+
+ assert result["object"] == "usage"
+ assert calls == [("https://mineru.net/api/v1/usage", {"Authorization": "Bearer api-key"})]
+
+
+def test_doclib_remote_usage_maps_remote_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _ConfigService:
+ async def get(self, key: str) -> str:
+ return {
+ "parse_server.remote.url": guidance.OFFICIAL_REMOTE_API_URL,
+ "parse_server.remote.api_key": "bad-key",
+ }[key]
+
+ async def fail_usage(_self: MinerUApiParser) -> dict[str, Any]:
+ from mineru.parser.api_client import _V1APIError
+
+ raise _V1APIError("invalid_api_key", "Invalid API Key.", "parse_server.remote.api_key")
+
+ monkeypatch.setattr(MinerUApiParser, "get_usage_async", fail_usage)
+ server = DoclibServer(SimpleNamespace(config_svc=_ConfigService()))
+
+ with pytest.raises(MineruError) as exc_info:
+ asyncio.run(server.get_remote_usage())
+
+ assert exc_info.value.code == "invalid_api_key"
+ assert exc_info.value.param == "parse_server.remote.api_key"
+
+
+def test_doclib_remote_usage_uses_resolved_environment_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
+ seen_api_keys: list[str | None] = []
+
+ class _ConfigService:
+ async def get(self, key: str) -> str:
+ return {
+ "parse_server.remote.url": guidance.OFFICIAL_REMOTE_API_URL,
+ "parse_server.remote.api_key": "",
+ }[key]
+
+ async def get_usage(parser: MinerUApiParser) -> dict[str, Any]:
+ seen_api_keys.append(parser._api_key)
+ return _usage_response("registered").model_dump()
+
+ monkeypatch.setenv("MINERU_API_KEY", "environment-key")
+ monkeypatch.setattr(MinerUApiParser, "get_usage_async", get_usage)
+ server = DoclibServer(SimpleNamespace(config_svc=_ConfigService()))
+
+ response = asyncio.run(server.get_remote_usage())
+
+ assert response.access_level == "registered"
+ assert seen_api_keys == ["environment-key"]
+
+
+def test_doclib_config_key_reports_environment_api_key_without_exposing_it(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _ConfigService:
+ async def get(self, key: str) -> str:
+ assert key == "parse_server.remote.api_key"
+ return ""
+
+ async def get_source(self, key: str) -> str:
+ assert key == "parse_server.remote.api_key"
+ return "default"
+
+ monkeypatch.setenv("MINERU_API_KEY", "environment-secret")
+ server = DoclibServer(SimpleNamespace(config_svc=_ConfigService()))
+
+ response = asyncio.run(server.get_config_key("parse_server.remote.api_key"))
+
+ assert response.source == "environment"
+ assert response.value != "environment-secret"
+ assert "******" in response.value
+
+
+def test_usage_json_wraps_remote_fields_and_adds_optional_guidance(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(usage, "DoclibClient", _UsageClient)
+
+ result = runner.invoke(app, ["usage", "--json"])
+
+ assert result.exit_code == 0
+ payload = json.loads(result.output)
+ assert payload["remote_url"] == "https://mineru.net/api"
+ assert payload["usage"]["object"] == "usage"
+ assert payload["usage"]["access_level"] == "anonymous"
+ assert payload["usage"]["current"]["pages_processed"] == 26
+ assert payload["guidance"]["type"] == "configure_official_api_key"
+ assert payload["guidance"]["required"] is False
+ assert "guidance_text" not in payload
+
+
+def test_usage_json_returns_null_guidance_for_registered_access(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _RegisteredClient(_UsageClient):
+ response = _usage_response("registered")
+
+ monkeypatch.setattr(usage, "DoclibClient", _RegisteredClient)
+
+ result = runner.invoke(app, ["usage", "--json"])
+
+ assert result.exit_code == 0
+ assert json.loads(result.output)["guidance"] is None
+
+
+def test_usage_json_returns_null_official_guidance_for_custom_remote(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _CustomClient(_UsageClient):
+ remote_url = "https://example.com/api"
+
+ monkeypatch.setattr(usage, "DoclibClient", _CustomClient)
+
+ result = runner.invoke(app, ["usage", "--json"])
+
+ assert result.exit_code == 0
+ assert json.loads(result.output)["guidance"] is None
+
+
+def test_usage_human_output_shows_complete_remote_usage(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(usage, "DoclibClient", _UsageClient)
+
+ result = runner.invoke(app, ["usage"])
+
+ assert result.exit_code == 0
+ assert "Remote API Usage" in result.stdout
+ assert "Remote URL: https://mineru.net/api" in result.stdout
+ assert "Billing period: 2026-07-14 00:00 UTC - 2026-07-15 00:00 UTC" in result.stdout
+ assert "Max file size: 200 MiB" in result.stdout
+ assert "File retention: 30 days" in result.stdout
+ assert guidance.OFFICIAL_API_KEY_URL in result.stdout
+
+
+def test_usage_invalid_api_key_keeps_error_and_adds_required_guidance(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _InvalidClient(_UsageClient):
+ def get_remote_usage(self) -> RemoteUsageResponse:
+ raise MineruError("invalid_api_key", "Invalid API Key.", "parse_server.remote.api_key")
+
+ monkeypatch.setattr(usage, "DoclibClient", _InvalidClient)
+ monkeypatch.setattr(guidance, "DoclibClient", _GuidanceConfigClient)
+
+ result = runner.invoke(app, ["usage", "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["error"] == {
+ "type": "authentication_error",
+ "code": "invalid_api_key",
+ "message": "Invalid API Key.",
+ "param": "parse_server.remote.api_key",
+ }
+ assert payload["guidance"]["required"] is True
+
+
+def test_usage_invalid_api_key_human_output_separates_error_and_guidance(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _InvalidClient(_UsageClient):
+ def get_remote_usage(self) -> RemoteUsageResponse:
+ raise MineruError("invalid_api_key", "Invalid API Key.", "parse_server.remote.api_key")
+
+ monkeypatch.setattr(usage, "DoclibClient", _InvalidClient)
+ monkeypatch.setattr(guidance, "DoclibClient", _GuidanceConfigClient)
+
+ result = runner.invoke(app, ["usage"])
+
+ assert result.exit_code == 1
+ assert result.stdout == ""
+ assert "Error: Invalid API Key." in result.stderr
+ assert "Manage or create an API Key:" in result.stderr
+ assert guidance.OFFICIAL_API_KEY_URL in result.stderr
+ assert guidance.SET_API_KEY_COMMAND in result.stderr
+
+
[email protected]("error_code", ["invalid_api_key", "feature_requires_api_key"])
+def test_auth_and_feature_errors_require_api_key_guidance(
+ monkeypatch: pytest.MonkeyPatch,
+ error_code: str,
+) -> None:
+ monkeypatch.setattr(guidance, "DoclibClient", _GuidanceConfigClient)
+
+ result = guidance.api_key_guidance_for_error(MineruError(error_code, "API Key required."))
+
+ assert result is not None
+ assert result.data["required"] is True
+
+
[email protected]("error_code", ["rate_limit_exceeded", "quota_exceeded"])
+def test_anonymous_limit_errors_offer_optional_api_key_guidance(
+ monkeypatch: pytest.MonkeyPatch,
+ error_code: str,
+) -> None:
+ monkeypatch.setattr(guidance, "DoclibClient", _GuidanceConfigClient)
+
+ result = guidance.api_key_guidance_for_error(MineruError(error_code, "Limit reached."))
+
+ assert result is not None
+ assert result.data["required"] is False
+
+
+def test_registered_rate_limit_does_not_offer_api_key_guidance(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _RegisteredConfigClient(_GuidanceConfigClient):
+ api_key = "******"
+
+ monkeypatch.setattr(guidance, "DoclibClient", _RegisteredConfigClient)
+
+ assert guidance.api_key_guidance_for_error(MineruError("rate_limit_exceeded", "Retry later.")) is None
+
+
+def test_custom_remote_error_does_not_offer_official_guidance(monkeypatch: pytest.MonkeyPatch) -> None:
+ class _CustomConfigClient(_GuidanceConfigClient):
+ remote_url = "https://example.com/api"
+
+ monkeypatch.setattr(guidance, "DoclibClient", _CustomConfigClient)
+
+ assert guidance.api_key_guidance_for_error(MineruError("invalid_api_key", "Invalid API Key.")) is None