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

The CLI calls Asklear REST over HTTPS with a Bearer credential (OAuth or 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、sample、search-values、search-products、query、query-details、quote、run-sql、results、export、export-status、exports、pricing、usage 已有命令入口，并复用与 MCP 相同的 REST/MCP 业务服务；商品名称搜索只返回候选身份，用户选定 product_id 后再 query 或 query-details，不会直接返回销售指标。本地浏览器 MCP 的 navigate、observe、click、fill、scroll、extract 也有 asklear browser 等价入口。远程业务命令都支持可选的 --task-query：建议填写一句简洁任务描述；省略时 REST 保持未归因，MCP 使用固定的非用户归因，显式空值仍会被拒绝。复杂请求可用 --input-json、--input-file 或 --input-json - 原样传递完整请求。CLI 支持浏览器 OAuth 和 API Key 两种远程认证，不支持 Device Flow。ranking 不属于 MCP 能力，未提供 CLI 命令。

datasets, describe, sample, search-values, search-products, query, query-details, quote, run-sql, results, export, export-status, exports, pricing and usage are available through the same REST/MCP business services as MCP. Product-name lookup returns identity candidates only; after selecting a product_id, use query or query-details for sales data. The local browser MCP operations navigate, observe, click, fill, scroll and extract also have equivalent asklear browser commands. Remote business commands accept an optional --task-query: provide one concise task description when possible; when omitted, REST stays unattributed and MCP uses a fixed non-user-specific attribution, while explicit empty values are rejected. Use --input-json, --input-file or --input-json - to preserve a complete request. CLI supports browser OAuth and API keys for remote services, but not Device Flow. ranking is not an MCP capability and has no CLI command.

## Installation / 安装与检查

当前 CLI 提供独立的 `asklear-cli` wheel。准备 Python 3.12–3.14 和 uv，然后从 Asklear CN 的受控 HTTPS 入口下载版本 0.1.0。入口每次只返回短期签名跳转，文档不会保存 OSS 地址。安装前先校验下面给出的 SHA-256；摘要不一致时不要安装。不要从 PyPI 安装同名未知包，也不要把服务端供应商凭据配置到客户端。

The CLI is distributed as a standalone `asklear-cli` wheel. Prepare Python 3.12–3.14 and uv, then download version 0.1.0 from Asklear CN's controlled HTTPS endpoint. Each request returns only a short-lived signed redirect; the guide does not contain an OSS URL. Verify the SHA-256 below before installing and do not install a mismatched artifact. Do not install an unknown package with the same name from PyPI or configure upstream credentials on the client.

```sh
CLI_WHEEL=asklear_cli-0.1.0-py3-none-any.whl
CLI_SHA256=20747cdd0cb80092738bc2001b7430116050af5ba1f8ee3154c94a3f4ac49d63
curl -fL --proto '=https' --tlsv1.2 \
  -o "$CLI_WHEEL" \
  https://api.asklear.cn/v1/public/cli/download
printf '%s  %s\n' "$CLI_SHA256" "$CLI_WHEEL" | sha256sum -c -
uv tool install "./$CLI_WHEEL"
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 datasets --task-query '发现可用数据集' --json
asklear collection tasks --task-query '发现采集任务' --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 通过 MCP connection_status 做一次不计费的连接检查验证认证，不输出令牌。logout 只退出当前环境：OAuth 会尝试撤销令牌后删除本地凭据，撤销失败则报错并保留凭据；API Key 只清除本地配置，不撤销服务端 Key。其他环境和 MCP 的登录不受影响。环境变量 Key 需在终端或秘密管理器中自行移除，普通 logout 会提示而不会假称已退出。

auth status uses the MCP connection_status tool for a non-billable connection check 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
TASK_QUERY='执行 Google/Bing 网页搜索'
asklear collection describe web_search_v1 --task-query "$TASK_QUERY" --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" --task-query "$TASK_QUERY" --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
TASK_QUERY='执行 Google/Bing 网页搜索'
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 --task-query "$TASK_QUERY" --json
asklear collection wait JOB_ID --timeout 600 --task-query "$TASK_QUERY" --json
asklear collection get-job JOB_ID --task-query "$TASK_QUERY" --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
TASK_QUERY='采集公开网页'
asklear collection describe raw_html_v1 --task-query "$TASK_QUERY" --json
asklear collection estimate --task-code raw_html_v1 --input-json '{"urls":["https://example.com/"],"output_format":"markdown"}' --task-query "$TASK_QUERY" --json
asklear collection tasks --task-query "$TASK_QUERY" --json
```

## Local browser MCP and CLI / 本地浏览器 MCP 与 CLI

本地浏览器命令与远程 Asklear 数据服务分开，复用本机 Chrome 的登录态和页面，不发送 API Key、OAuth 令牌、Cookie 或页面正文到远程服务。Connector 令牌不是 Asklear API Key；没有本地浏览器 Connector 时可以让 CLI 自动拉起，或用 --no-autostart 明确要求复用已运行的 Connector。

Local browser commands are separate from the remote Asklear data service. They reuse the user's local Chrome session and do not send API keys, OAuth tokens, cookies or page contents to the remote service. A Connector process token is not an Asklear API key. The CLI can start a local Connector when needed, or use --no-autostart to require an existing Connector.

六个命令与本地 MCP 工具一一对应：navigate 打开页面并返回 session_id；observe 返回当前快照；click 和 fill 必须使用最新 snapshot_id 与 element_ref；scroll 使用 pixels；extract 返回有界的可见页面内容。交互后先重新 observe，再继续点击或填写；翻页和加载更多要设置有限次数。

The six commands map one-to-one to the local MCP tools. navigate opens a page and returns a session_id; observe returns the current snapshot; click and fill require the latest snapshot_id and element_ref; scroll takes pixels; extract returns bounded visible-page content. Re-observe after an interaction before clicking or filling again, and use a finite limit for pagination or load-more loops.

```sh
asklear browser navigate --url https://example.com
asklear browser observe --session-id SESSION_ID
asklear browser click --session-id SESSION_ID --snapshot-id SNAPSHOT_ID --element-ref ELEMENT_REF
asklear browser fill --session-id SESSION_ID --snapshot-id SNAPSHOT_ID --element-ref ELEMENT_REF --value '搜索词'
asklear browser scroll --session-id SESSION_ID --pixels 800
asklear browser extract --session-id SESSION_ID
```

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

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

Use datasets for authorized datasets and describe for fields, metrics and available months; discovery commands accept an optional --task-query, which is recommended. 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 --idempotency-key 'query-unique-id' [--task-query '查询销售额'] --json。请替换大写占位符和幂等键，月份使用 YYYY-MM。query 会直接提交查询，可能计费；付费请求必须提供幂等键，同一任务重试时复用原键。需要完整字段时用 --input-json 原样传递，报价和 SQL 分别使用 quote、run-sql，费用和授权以服务端响应为准，不能通过反复重试绕过。

Basic query syntax is asklear query --dataset DATASET --metrics gmv --group-by brand --start START_MONTH --end END_MONTH --idempotency-key 'query-unique-id' [--task-query 'query sales'] --json. Replace placeholders and use a new idempotency key for each new task; reuse the same key when retrying that task. query submits directly and may incur charges. Paid requests require idempotency. Use --input-json to preserve complete fields; use quote and run-sql for pricing and SQL. Pricing and authorization come from the service; do not bypass them with retries.

```sh
asklear datasets --task-query '发现授权数据集' --json
asklear describe jd --task-query '查看 jd 查询契约' --json
asklear describe tmall --task-query '查看 tmall 查询契约' --json
asklear query --help
asklear export --help
asklear pricing --dataset jd --task-query '查看 jd 价格规则' --json
asklear usage --task-query '查看用量' --json
asklear results QUERY_ID --task-query '读取已有查询结果' --json
asklear export-status JOB_ID --task-query '查看导出状态' --json
asklear exports --task-query '查看导出记录' --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.
