---
document_id: agent.cli
schema_version: 2
parent_document_id: agent.guide
section: querying
---

<!-- Generated by scripts.build_agent_guide; do not edit. -->

# CLI integration / CLI 接入指南

## Supported capabilities / 先了解支持范围

CLI 通过 HTTPS REST 和 Bearer API Key 请求 Asklear，不是直接请求数据供应商。数据任务使用通用 collection 命令，包含 Google/Bing 搜索、平台内容任务和 raw_html_v1 网页采集；以当前账号的 tasks 和 describe 返回值为准，不代表所有任务均已逐一通过 CLI 实测。

The CLI calls Asklear REST over HTTPS with a Bearer API key, not upstream providers. Generic collection commands cover search, platform tasks and raw_html_v1. Use tasks and describe to discover account availability; not every task has been individually tested through the CLI.

datasets、describe、query、export、usage 已有命令入口。query 只支持基础聚合参数，不等同于完整 MCP 查询能力；quote、run-sql、ranking 仍为占位命令，不可用于业务。CLI 支持浏览器 OAuth 和 API Key 两种认证，不支持 Device Flow 和本地浏览器交互命令。需登录、点击或滚动的网页请使用浏览器 MCP，而非 raw_html_v1。

datasets, describe, query, export and usage exist. query supports basic aggregation parameters, not full MCP parity. quote, run-sql and ranking are placeholders. CLI supports browser OAuth and API keys, but not Device Flow or local browser interaction commands. Use browser MCP for pages requiring login or interaction.

## Installation / 安装与检查

当前 CLI 随 Asklear 项目源码交付，尚未在这里提供独立公开安装包。你需要获得项目源码访问权限、Python 3.12–3.14 和 uv。在源码根目录运行以下命令；无源码权限时，请先联系 Asklear 获取受支持的交付方式。不要从 PyPI 安装同名未知包，也不要把服务端供应商凭据配置到客户端。

The CLI currently ships with the Asklear source project, not a standalone public package documented here. Obtain authorized source access, Python 3.12–3.14 and uv. Run these commands in the source root. Contact Asklear if you lack access; do not install unknown similarly named packages or configure upstream credentials.

```sh
uv tool install .
uv tool update-shell
asklear --help
asklear collection --help
```

## Authentication and environments / 连接生产或测试环境

以下命令连接 CN 生产环境。login 默认打开浏览器，使用已有 Asklear 账号登录并授权；不需要手动复制 Key。先绑定本机随机回调端口，再使用 PKCE 获取令牌。没有浏览器的 CI/SSH 环境请使用 API Key，本版不提供 Device Flow。首次 login 未指定环境时使用 CN 生产，业务命令未登录且未配置地址时仍默认本机；建议始终显式选择环境。

login opens a browser for Asklear OAuth authorization using PKCE and a random loopback callback port. CI/SSH environments without a browser should use API keys; Device Flow is not implemented. A first login defaults to CN production; unconfigured business commands still default to localhost. Explicitly select the environment.

OAuth 访问令牌和刷新令牌保存在 CLI 专用的权限 0700 目录、0600 文件中，不是系统钥匙串；按服务地址隔离，不复用 MCP 或浏览器连接器的登录状态。访问令牌即将过期时自动刷新，文件锁防止多个 CLI 进程同时轮换。同一环境再次登录前需先 logout，避免留下未撤销的旧授权。不要把凭据写入命令参数、仓库、截图或共享日志。

CLI OAuth tokens live in a dedicated mode-0700 directory with mode-0600 files, not an OS keychain. Storage is isolated by API origin and never shares MCP or browser connector credentials. Tokens refresh before expiry with a cross-process lock. Log out before logging in again to avoid orphaning prior authorization. Keep credentials out of command arguments and shared artifacts.

CN 测试地址为 https://data-test.asklear.cn，Global 生产地址为 https://api.asklearai.com。切换时显式设置对应地址和 Key，不会在环境之间自动回退。下面是 macOS/Linux shell 示例；Windows 请使用对应终端的环境变量语法。

CN test uses https://data-test.asklear.cn; Global production uses https://api.asklearai.com. Explicitly select matching credentials and URL; no automatic environment fallback. Examples use macOS/Linux shell syntax.

```sh
export ASKLEAR_BASE_URL=https://api.asklear.cn
asklear login --base-url "$ASKLEAR_BASE_URL"
asklear auth status --json
asklear collection tasks --json
```

## API keys and logout / API Key、登录状态与退出

API Key 用户运行 login --auth api-key，在隐藏提示中输入 Dashboard 创建的 Key；原来的 login --api-key 参数仍兼容，但不建议将秘密写在命令行。自动化环境可由秘密管理器注入 ASKLEAR_API_KEY；它优先于保存的登录状态。使用 OAuth 登录前需取消该变量，避免实际请求仍使用 Key。保存的 Key 不会随 ASKLEAR_BASE_URL 跨环境发送。

Use login --auth api-key for a hidden API key prompt. Legacy --api-key arguments remain compatible but are discouraged. Secret managers may inject ASKLEAR_API_KEY, which overrides saved credentials; unset it before OAuth login. Saved API keys are never forwarded to a different API origin.

auth status 会发送一次不计费的任务发现请求验证认证，不输出令牌。logout 只退出当前环境：OAuth 会尝试撤销令牌后删除本地凭据，撤销失败则报错并保留凭据；API Key 只清除本地配置，不撤销服务端 Key。其他环境和 MCP 的登录不受影响。环境变量 Key 需在终端或秘密管理器中自行移除，普通 logout 会提示而不会假称已退出。

auth status validates authentication with a non-billable discovery request without displaying tokens. logout revokes the current environment OAuth token then removes local credentials; failed revocation retains them. API-key logout clears local configuration only, not the server key. Other environments and MCP credentials remain untouched. Environment-variable keys must be removed in the shell or secret manager.

从 OAuth 切换到 API Key 时，旧 OAuth 授权仍保留，普通 logout 不会撤销它。要切回 OAuth，先执行 asklear logout --auth oauth，成功后再执行 asklear login --auth oauth。显式 OAuth 退出只处理当前服务地址的 CLI OAuth，不修改 API Key 配置或环境变量；撤销失败时保留凭据，修复网络后重试同一命令，不需要手工删除文件。切回 OAuth 登录前须自行取消 ASKLEAR_API_KEY 环境变量。

Switching from OAuth to an API key retains the old OAuth authorization. To switch back, run asklear logout --auth oauth, then asklear login --auth oauth after successful revocation. Explicit OAuth logout affects only CLI OAuth for the selected service address and leaves API-key configuration and environment variables unchanged. Failed revocation retains credentials; retry the same command after restoring connectivity. Unset ASKLEAR_API_KEY before logging in with OAuth.

OAuth 本地凭据采用 POSIX 文件权限，本轮本地验收在 macOS 完成，Linux 需由 CI 继续验收。Windows 环境请先使用 API Key，不把未经验收的平台列为已支持的 OAuth 环境。安装后若找不到 asklear，请按 uv tool update-shell 提示重开终端。

OAuth credentials use POSIX file permissions. Local verification ran on macOS; Linux verification belongs to CI. Use API keys on Windows until OAuth is validated there. If asklear is not on PATH after installation, reopen the shell as directed by uv tool update-shell.

```sh
asklear login --auth api-key --base-url https://api.asklear.cn
asklear auth status --json
asklear logout --json
```

## First search task / 第一个搜索任务：报价 → 确认 → 执行 → 结果

先 describe 查看输入契约，再 estimate 获取报价。下面示例只报价，不执行付费任务。Google 支持显式页码 1–20；Bing 目前仅支持 page=1、range=none。每一页都是独立任务，成功收费 3 Credits，不会自动翻完所有页面。

Inspect describe before estimate. This example only requests a quote. Google supports explicit pages 1–20; Bing only page=1 and range=none. Each page is a separate task costing 3 Credits on success; pagination is not automatic.

```sh
asklear collection describe web_search_v1 --json
SEARCH_INPUT='{"engine":"google_advanced","query":"robot vacuum","locale":"zh-CN","range":"none","page":1}'
asklear collection estimate --task-code web_search_v1 --input-json "$SEARCH_INPUT" --json
```

## Start within an approved budget / 确认预算后启动并等待

核对报价 upper_bound_credits 和 expires_at，确认愿意支付后，将下面 QUOTE_TOKEN 替换为刚才报价返回的 quote_token。输入必须与报价一致。max-credits 是预算上限，不是改价参数。idempotency-key 每个新任务使用新值；网络中断重试同一任务时必须保留原值，不能重新生成。不要把报价令牌分享到日志。

Review upper_bound_credits and expires_at, then replace QUOTE_TOKEN with the returned quote_token only after approving the cost. Keep input unchanged. max-credits caps the budget, not the price. Use a new idempotency key per new task but retain it when retrying the same task after network failure. Do not share quote tokens in logs.

用 start 返回的 job_id 替换 JOB_ID。wait 只轮询已有任务，不再次启动或扣取任务费用；超时或中断后用同一 job_id 继续查询。JSON 输出包含完整结果；get-job/wait 的表格模式只展示状态。

Replace JOB_ID with the start response job_id. wait only polls an existing job; it never starts or bills another task. Resume using the same job_id after timeout or interruption. JSON includes full results; table mode only displays job status.

```sh
REQUEST_ID=$(uuidgen)
asklear collection start --task-code web_search_v1 --input-json "$SEARCH_INPUT" --quote-token 'QUOTE_TOKEN' --idempotency-key "$REQUEST_ID" --max-credits 3 --json
asklear collection wait JOB_ID --timeout 600 --json
asklear collection get-job JOB_ID --json
```

## Web and platform collection / 网页采集和其他平台任务

raw_html_v1 使用同样的报价、启动、等待流程，只需替换 task-code 和输入；它采集公开 URL，不复用本地登录态。下方示例仅报价，费用以该任务报价为准，不套用搜索的固定 3 Credits。平台任务先在 tasks 中选 code，再从 describe 获取真实示例和限制，不透传供应商字段。

raw_html_v1 uses the same lifecycle with different task-code and input. It fetches public URLs without local browser login state. The example only quotes; use its returned price, not the search task price. For platform tasks, select a code from tasks and inspect describe for supported inputs.

输入支持 --input-json、--input-file 和 --input-json -（从标准输入读取），三者互斥。输入文件必须是 UTF-8 JSON 对象。start 的输入应与同一任务 estimate 完全一致。

Inputs accept mutually exclusive --input-json, --input-file, or --input-json - for stdin. Files must contain UTF-8 JSON objects. Keep start input identical to the corresponding estimate.

```sh
asklear collection describe raw_html_v1 --json
asklear collection estimate --task-code raw_html_v1 --input-json '{"urls":["https://example.com/"],"output_format":"markdown"}' --json
asklear collection tasks --json
```

## Dataset queries and limitations / 数据查询与当前限制

先 datasets 查看授权数据集，再 describe 查看字段、指标和真实可用月份。京东、天猫分别使用 dataset=jd、dataset=tmall；不要默认二者拥有相同月份。下面先执行只读发现，不会发起聚合查询。

Use datasets for authorized datasets and describe for fields, metrics and available months. JD uses jd and Tmall uses tmall. Never assume they share a month range. These discovery commands do not execute aggregation queries.

基础查询格式为 asklear query --dataset DATASET --metrics gmv --group-by brand --start START_MONTH --end END_MONTH --json。请替换大写占位符，月份使用 YYYY-MM。query 会直接提交查询，可能计费；目前不能携带服务端要求的 max_credits/approved_plan_digest，遇到预算确认错误时请改用 MCP 或 Playground 完成报价确认，不能通过反复重试绕过。export 也不是完整 MCP 导出替代品，使用前检查 --help 和服务端响应。

Basic query syntax is asklear query --dataset DATASET --metrics gmv --group-by brand --start START_MONTH --end END_MONTH --json. Replace placeholders with authorized dataset and YYYY-MM months. query submits directly and may incur charges. It cannot pass max_credits/approved_plan_digest required by some server policies; use MCP or Playground for budget approval instead of retrying. export is not a full MCP replacement; check --help and service responses.

```sh
asklear datasets --json
asklear describe jd --json
asklear describe tmall --json
asklear query --help
asklear export --help
asklear usage --json
```

## Billing and concurrency / 计费、限流和并发

CLI、MCP 和 Playground 的数据任务复用服务端计费。报价不执行任务；启动时预留 Credits，成功结算，失败释放预留。Google/Bing 每个成功搜索任务 3 Credits；其他任务按 describe/estimate 契约计价，可能按 URL 数或结果量计算，不能一律按 3 Credits。

CLI, MCP and Playground share server-side collection billing. Quoting does not execute a task. Starting reserves Credits, success settles and failure releases the reservation. Search costs 3 Credits per successful task; other tasks follow their own describe/estimate contract.

服务端限制每分钟请求额度（RPM），不是严格的每秒 QPS。API Key 模式下，发现、报价、任务状态使用独立 discovery 桶，额度为该 Key 基础 RPM 的 5 倍；启动任务使用普通桶。OAuth 使用当前 Agent 连接的限额，不套用 API Key 的 5 倍规则。两种方式都有租户请求并发和活跃任务限制。超限返回 429，不要通过增加 CLI 进程数量绕过。

Server limits use RPM rather than strict per-second QPS. With API keys, discovery, estimates and status use a separate bucket with five times that key's base RPM; starts use the regular bucket. OAuth uses Agent-connection limits, not the API-key five-times rule. Tenant concurrency and active-task caps also apply. Do not try to bypass 429 limits with additional CLI processes.

活跃采集任务上限代码默认每租户 10 个（排队与运行合计），部署可调整；实际以服务端为准。请求并发和来源调用限制目前是进程级，不能理解为整个集群统一上限。CLI 没有批量并发调度器。wait 遵循 Retry-After 或 poll_after_seconds，默认间隔 1 秒；单次 HTTP 请求超时 120 秒，因此 wait --timeout 不是严格的整体墙钟时间上限。

The default active-task cap is 10 per tenant including queued and running jobs; deployments may override it. Request and source-call concurrency limits are process-local, not cluster-wide. CLI has no batch scheduler. wait follows Retry-After or poll_after_seconds, defaulting to one second. HTTP timeout is 120 seconds; wait --timeout is not a strict overall wall-clock deadline.

## Output and recovery / 脚本输出与错误恢复

建议脚本使用 --json。除 export 外，带输出选项的业务命令也支持 --output json；export 的 --output PATH 是下载文件路径，--format json 是导出文件格式，--json 才是命令响应格式，三者不能混用。成功结果写 stdout，结构化服务错误写 stderr。退出码：0 成功，1 服务或任务错误，2 输入错误，3 Credits 或确认要求，4 认证或权限。命令解析器的部分参数错误仍是文本，不要假设所有 stderr 都能解析为 JSON。

Prefer --json. Business commands with output options also accept --output json except export, where --output PATH selects the downloaded file path, --format json selects the export format, and --json selects the command response format. Successful output goes to stdout and structured service errors to stderr. Exit codes are 0 success, 1 service/task failure, 2 input, 3 Credits/approval, 4 authentication/permissions. Some command-parser errors remain text.

401/403：核对当前环境、Key 和授权。429 concurrency_limited / collection_queue_full：降低并发、等待后再查；CLI 收到错误响应不会自动重试。400 collection_input_invalid：按 describe 修正输入再报价。报价过期：重新 estimate；幂等冲突：确认是否把同一 key 用于不同请求。任务已创建但终端中断：先 get-job，不要立即重新 start。

For 401/403 verify environment, key and permissions. For 429 concurrency_limited/collection_queue_full reduce concurrency and wait; error responses are not automatically retried. For 400 collection_input_invalid correct inputs before quoting. Refresh expired quotes, investigate idempotency conflicts, and retrieve an existing job before starting another after interruption.
