---
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 / 先了解支持范围

未连接前可匿名读取本区 GET /v1/public/capabilities?view=reference，查看已公开能力、入口状态和详细 Docs 链接；目录不授予执行权限。连接后的 docs 按同一 catalog_version 返回当前能力参考，逐入口 page 提供完整契约；通用教程仍保留。当前账号授权与实际可执行状态继续以原 discover 和业务鉴权为准。

Before connecting, anonymously read regional GET /v1/public/capabilities?view=reference for published capabilities, entrypoint status and detailed Docs links. Listing grants no execution access. Connected docs uses the same catalog_version for current capability references, with full contracts on entrypoint pages; tutorials remain available. Existing discover and business authentication still decide account access and execution.

CLI 通过 HTTPS REST 和 Bearer 凭据（OAuth 或 API Key）请求 Asklear。新 Agent 任务使用 discover/run/task 和 Task HTTP；旧 collection 命令经 Collection HTTP 保留兼容，覆盖 Google/Bing 搜索及 raw_html_v1 等旧任务。当前账号和区域是否开放新能力以服务端 discover 为准；代码或本文出现命令不等于已在 CN 或 Global 上线。

The CLI calls Asklear REST over HTTPS with a Bearer credential (OAuth or API key). New Agent tasks use discover/run/task over Task HTTP; legacy collection commands use Collection HTTP for existing tasks such as Google/Bing search and raw_html_v1. Check server-side discover for availability in the current account and region. A command in the code or this guide does not imply a CN or Global rollout.

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 / 安装与检查

以下是现有 CN 受控下载入口的 0.1.0 wheel 安装示例，不表示该发布物已经包含本文所述的新 Agent 命令，也不适用于 Global。准备 Python 3.12–3.14 和 uv；入口只返回短期签名跳转，不保存 OSS 地址。安装前校验下列 SHA-256，安装后用 --help 核对实际命令。不要从 PyPI 安装同名未知包，也不要把服务端凭据配置到客户端。

The following installs the existing 0.1.0 wheel from CN's controlled download endpoint. It does not establish that this artifact contains the new Agent commands, and it is not a Global installer. Prepare Python 3.12–3.14 and uv. The endpoint returns a short-lived signed redirect, not a permanent OSS URL. Verify the SHA-256 and check installed commands with --help. Do not install an unknown namesake package from PyPI or configure service 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
```

## Service versions and Global compatibility / 服务版本与 Global 兼容

新 Agent CLI 候选源码要求本区服务启用 Task HTTP 和必要辅助 HTTP；这只是交付候选，尚未生产发布或完成区域验收。旧 Global 服务仍配此前已验收的旧版 CLI。当前没有可核验的 Global CLI 安装链接或已验收的新版本号，不要把 CN 下载地址、wheel 校验值或候选新命令当作 Global 安装指引。Global 补齐接口并单独验收后才能更新推荐版本。

The new Agent CLI candidate source requires regional Task HTTP and supporting HTTP routes; this delivery candidate is not yet released to production or regionally validated. Use the previously validated CLI with the old Global service. There is no verified Global CLI download link or validated new version number; do not reuse the CN installer, wheel checksum or candidate commands as Global installation instructions. Update the recommendation only after Global routes and the client are validated there.

候选源码对必要辅助 HTTP 或 Task 路由返回的无结构 404 报 server_version_unsupported，并附实际服务地址和本区版本指引；带业务错误体的结构化 404 保留原错误。不会自动切区或回退 MCP。认证、授权及网络错误保留各自分类，不能误判为服务版本不支持；请求失败后不要换区域或用新幂等键重复收费提交。此版本错误行为仍须随候选完成验收，不能视作旧 Global 已支持新路由。

For an unstructured 404 on a required supporting HTTP or Task route, the candidate source reports server_version_unsupported with the actual service URL and regional version guidance. A structured 404 with a business error keeps that error. It does not switch regions or fall back to MCP. Keep authentication, authorization and network errors in their own categories; do not switch regions or repeat a potentially billable submission with a new idempotency key. This candidate behavior still requires validation and does not mean old Global supports the new routes.

## 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.kleardata.ai。切换时显式设置对应地址和 Key，不会在环境之间自动回退。下面是 macOS/Linux shell 示例；Windows 请使用对应终端的环境变量语法。

CN test uses https://data-test.asklear.cn; Global production uses https://api.kleardata.ai. 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
```

## 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.

当前 CLI 的 auth status 通过 /v1/agent/connection 做不计费的连接检查，不请求 MCP，也不输出令牌；旧 Global 若缺此辅助 HTTP，需按本区已验收的 CLI 版本配对。logout 只退出当前环境：OAuth 会尝试撤销令牌后删除本地凭据，撤销失败则报错并保留凭据；API Key 只清除本地配置，不撤销服务端 Key。其他环境和 MCP 的登录不受影响。环境变量 Key 需在终端或秘密管理器中自行移除，普通 logout 会提示而不会假称已退出。

Current CLI auth status checks /v1/agent/connection without billing, calling MCP or displaying tokens. Pair an old Global service missing this supporting HTTP route with its previously validated CLI. 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
```

## Agent Task API: discover, run and read / Agent Task API：发现、提交和读回

新命令的路由为 discover → GET /v1/capabilities（详情为 /v1/capabilities/{operation_id}）、run → POST /v1/agent/run、task list/get → GET /v1/data-tasks 与 /v1/data-tasks/{task_ref}。它们直接使用本区 Task HTTP，不经过旧 /v1/collections/* 或 MCP。以下仅为源码中的命令格式；须先确认安装的 CLI 含有命令、服务端已启用任务功能，再以当前账号 discover 的 operation_id 和 Schema 填入真实输入。不要把示意占位符当作可运行能力或上线声明。

Task routing is discover -> GET /v1/capabilities (detail at /v1/capabilities/{operation_id}), run -> POST /v1/agent/run, and task list/get -> GET /v1/data-tasks and /v1/data-tasks/{task_ref}. These call regional Task HTTP directly, not legacy /v1/collections/* or MCP. Commands below show source-level syntax only. Confirm the installed CLI has them and the regional service has enabled data tasks, then use an operation_id and input Schema returned by discover for this account. Placeholders do not establish availability or rollout.

run 默认使用 --wait-seconds 10（可设 0–30），--no-wait 立即返回；窗口到期返回 queued/running 和 task_ref 只表示已受理，可用 task get 读取状态或已保存结果。收费能力由 run 生成计划，未获服务端授权时可能返回 awaiting_approval；v1 没有独立的 Task estimate。重试同一提交保留原幂等键；已保存结果读回不重新采集。

run defaults to --wait-seconds 10 (range 0-30); --no-wait returns immediately. A queued/running response with task_ref after that window means accepted, not completed; use task get for status or saved results. run creates a plan for billable operations and may return awaiting_approval until server-side approval; v1 has no separate Task estimate. Retain the original idempotency key when retrying the same submission. Reading saved results does not start a new collection.

Provider Task 用顶层 --pages 指定任意正整数或 max（默认 1），服务端自动翻页，不传 cursor/offset/page。能补详情的列表可加 --include-details，--max-detail-items 默认 20、范围 1–128；例如列表取 5 页但只补 20 条详情，达到详情上限仍继续列表。时间和排序按 discover 中各能力的输入格式填写。返回保留完整正文、作者、时间、互动数及必要业务标识，不返回整份供应商 JSON；读取结果仍使用 task get。具体能力和页数上限以当前账号 discover 和报价为准，源码支持不等于已上线。

Provider Tasks accept top-level --pages as any supported positive integer or max (default 1). The server manages pagination; omit cursor/offset/page. Supported lists accept --include-details and --max-detail-items (default 20, range 1-128). For example, fetch five list pages but enrich at most 20 unique details; the detail cap does not stop list pagination. Use each capability's discovered time and sort formats. Results keep complete prose, authors, time, engagement and essential business identifiers instead of the supplier JSON. Read them with task get. Account discovery and the quote determine availability and page limits; source support does not establish rollout.

若 discover 提供 search_social_content，可在 input 中指定 platform、query、pages 和平台专属 filters，统一搜索默认 3 页。例如 Reddit 用 {"platform":"reddit","query":"coffee","pages":2,"filters":{"sort":"NEW","time_range":"week"},"include_details":true}；自动翻页后最多补 20 条详情。YouTube 的筛选名则是 sort_by/upload_date，按 discover 的条件 Schema 填写，不跨平台照搬。没有详情 API 的平台不要传 include_details=true。每次只搜索显式选择的平台，国内／海外分组不表示自动搜索全部平台；MCP 同样使用 discover/run/task/cancel。

If discover lists search_social_content, supply platform, query, pages and platform-specific filters in input; this workflow defaults to three pages. For example, Reddit accepts {"platform":"reddit","query":"coffee","pages":2,"filters":{"sort":"NEW","time_range":"week"},"include_details":true} and enriches up to 20 details after automatic pagination. YouTube uses sort_by/upload_date instead; follow the discovered conditional Schema. Omit include_details=true where no detail API exists. Each task searches only its explicitly selected platform; domestic/overseas groupings do not trigger fan-out. MCP uses the same discover/run/task/cancel flow.

A11/V2 候选源码已实现显式 run --wait --timeout：--wait 必须配有限正数 --timeout，不能与 --no-wait 同用。它在提交前设定严格总墙钟期限，提交时将服务端等待设为 0，之后只轮询同一 task_ref；首次 HTTP 请求前开始计时，每次请求超时和轮询等待均受剩余时间约束。期限在提交前耗尽则不提交并保留 idempotency_key；提交后到期输出已知状态和 task_ref、退出码 1，不取消服务端任务；请求超时或网络中断时错误保留原键及已知引用。旧 collection wait --timeout 不保证严格总期限，不能与新 Task run 混用。此项仅为候选源码能力，尚未生产发布；上方安装包不保证包含这些参数。

The A11/V2 candidate source implements explicit run --wait --timeout. --wait requires a finite positive --timeout, and --wait cannot be combined with --no-wait. It sets a strict wall-clock deadline before submission, sends wait_seconds=0, then polls only the same task_ref. Timing starts before the first HTTP request; each request timeout and polling sleep is bounded by the remaining time. If the deadline expires before submission, it submits no task and retains idempotency_key. After submission, expiry outputs known state and task_ref with exit code 1 without cancelling the server task. Request timeout or network failure preserves the key and any known reference in the error. Legacy collection wait --timeout has no equivalent guarantee. This is candidate source behavior, not yet released to production; the installer above is not verified to include these flags.

若 discover 提供 web.raw_html.capture，可用 run 提交 1–10 条 urls 和 output_format（markdown 或 json）。这是一次批量抓取，pages 只能为 1 或 max；结果保留完整正文或结构化元素及逐 URL 状态。预留全部 URL 的费用，只按成功 URL 收费；用 task get 读取已保存结果不重新抓取。是否开放及实际报价以本区服务端返回为准。

If discover lists web.raw_html.capture, submit one to ten urls and output_format (markdown or json) with run. This is one batch capture, with pages limited to 1 or max. Results retain complete text or structured elements and each URL's status. The quote reserves all URLs and settlement charges only successful URLs; task get reads saved results without fetching again. Regional discovery and the returned quote determine availability and price.

```sh
asklear discover --json
asklear discover OPERATION_ID --json
asklear run --operation OPERATION_ID --input-json '{}' --idempotency-key REQUEST_ID --no-wait --json
asklear task get TASK_REF --view status --json
asklear task get TASK_REF --view results --json
asklear task list --json
```

## Legacy Collection search and quote / 旧 Collection 搜索：报价与兼容流程

以下旧 collection 命令调用 /v1/collections/*，只用于兼容现有 Collection API 工作流，不是新 Agent Task API 的默认入口。先 describe 查看输入契约，再 estimate 获取报价；示例只报价。Google 支持显式页码 1–20，Bing 目前仅支持 page=1、range=none；每页是独立旧任务，成功收费 3 Credits，不自动翻页。

These legacy collection commands call /v1/collections/* for existing Collection API workflows, not the default Agent Task API route. Inspect describe before estimate; this example only quotes. Google supports explicit pages 1-20, Bing page=1 and range=none. Each page is a separate legacy job 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
```

## Legacy Collection start and wait / 旧 Collection：确认预算后启动并等待

核对报价 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
```

## Legacy web and platform collection / 旧 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 / 计费、限流和并发

以下旧 Collection 计费规则属于原有 Collection API，不代表新 Task API 的价格。旧 CLI、MCP 和 Playground 的采集任务复用服务端计费；estimate 不执行任务，start 预留 Credits，成功结算，失败释放预留。Google/Bing 每个成功搜索任务 3 Credits；其他旧任务按 describe/estimate 契约计价，不能一律按 3 Credits。

The following legacy Collection billing rules describe the existing Collection API, not Task API prices. Legacy CLI, MCP and Playground collection jobs share server billing. estimate does not execute a job; start reserves Credits, success settles and failure releases the reservation. Google/Bing costs 3 Credits per successful search; other legacy jobs follow their own describe/estimate contract.

旧 Collection 的基础请求限制按每分钟额度（RPM），管理员还可配置 RPS、每日次数、账期次数和并发；Key 与租户限额同时生效。API Key 模式下，旧任务发现、报价和状态使用独立 discovery 桶，额度为该 Key 基础 RPM 的 5 倍；start 使用普通桶，每日和账期次数仍共享。OAuth 使用当前 Agent 连接限额，不套用 API Key 的 5 倍规则。两种方式都有租户请求并发和活跃任务限制。超限返回 429，不要通过增加 CLI 进程数量绕过；新 Task 的容量与额度以本区服务端策略为准。

Base legacy Collection request limits use RPM; administrators can also configure RPS, daily requests, billing-period requests and concurrency. Key and tenant limits both apply. With API keys, legacy Collection discovery, estimates and status use a separate bucket with five times that key's base RPM; start uses the regular bucket, while daily and billing-period counts remain shared. OAuth uses Agent-connection limits, not the API-key five-times rule. Tenant concurrency and active-job caps also apply. Do not try to bypass 429 limits with additional CLI processes. New Task capacity and quotas follow the regional server policy.

旧 Collection 活跃任务上限代码默认每租户 10 个（排队与运行合计），部署可调整；实际以服务端为准。生产客户 RPS 与请求并发通过共享存储跨 API 实例生效，依赖不可用时返回 503；本地 demo 和单元测试可使用内存实现，来源调用限制独立。CLI 没有批量并发调度器。旧 collection wait 遵循 Retry-After 或 poll_after_seconds，默认间隔 1 秒；单次 HTTP 请求超时 120 秒，因此 collection wait --timeout 不是严格的整体墙钟时间上限，也不能推导新 Task run 的等待保证。

The legacy Collection active-job cap defaults to 10 per tenant including queued and running jobs; deployments may override it. Production customer RPS and request concurrency are shared across API instances; unavailable limit storage returns 503. Local demos and unit tests may use memory storage. Source-call limits are separate. CLI has no batch scheduler. Legacy collection wait follows Retry-After or poll_after_seconds, defaulting to one second. An HTTP request may take 120 seconds, so collection wait --timeout is not a strict overall wall-clock deadline and says nothing about Task run waiting guarantees.

## 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 action required (Credits, approval, or paused recovery), 4 authentication/permissions. Some command-parser errors remain text.

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

For 401/403 verify environment, key and permissions. For legacy Collection 429 concurrency_limited/collection_queue_full, reduce concurrency and check later; error responses are not automatically retried. For 400 collection_input_invalid correct inputs before quoting. Refresh expired quotes and investigate idempotency conflicts. After interruption, use collection get-job for a legacy job; for a new Task, use task get and the original idempotency key instead of immediately submitting with a new key.
