Skill: laiye-adp/laiye-ocr (version 1.10.3)

--- name: agentic-doc-parse-and-extract description: Enables AI-powered parsing and key information extraction from high-frequency documents including invoices, orders, receipts, long texts, and common Chinese identity & credential documents. Supports reusable custom templates for non-standard business files. Features batch concurrent processing to automate document workflows for finance, administration, HR data entry and other departments. --- # agentic-doc-parse-and-extract Skill agentic-doc-parse-and-extract is an official command-line tool released by Laiye Technology's ADP (Agentic Document Processing) product, enabling both humans and AI agents to invoke ADP capabilities in the terminal for document parsing and extraction. ## Quick Start Guide for AI Agents ### Core Workflow 1. **Install dependencies**: On first execution, install the ADP CLI tool and dependencies by following the instructions in [references/examples.md](references/examples.md). 2. **Discover commands**: Run `adp schema` to get the machine-readable JSON spec of all commands, parameters, types, and defaults. 3. **Authentication**: On first execution, run `adp config get` to verify credentials. If no valid configuration exists, prompt the user to provide an API Key. 4. **Check Application**: On first execution, retrieve the application list via `adp app-id list`. For subsequent executions, prioritize `adp app-id cache` (cached in context). If the cache is unavailable, refresh it by calling `adp app-id list` again. 5. **Execute**: Run `adp extract url <URL> --app-id <ID>` or `adp parse url <URL> --app-id <ID>`. 6. **Query**: Check results asynchronously with `adp extract query <task_id>` or `adp parse query <task_id>`. 7. **Error handling**: When a command fails, parse the stderr JSON to determine error type and recovery action. See [references/error-handling.md](references/error-handling.md). ### Common Scenarios → Command Mapping | User Intent | Recommended Command | Handling Rules | | :---------- | :------------------ | :------------- | | - Read full document content<br>- Parse layout & structure<br>- Convert document to text<br>- Process / analyze full document | `adp parse` | - Sync processing for small files<br>- Async processing (`--async` parameter) for files >20MB or >200 pages | | - Extract key fields (amount, date, name, ID, etc.)<br>- Output structured results (JSON/table) | `adp extract` | - Use Extract directly, **no need to parse first**<br>- Use matched existing app<br>- Create a custom extraction app if the document type is not in the known app list | | Batch processing of local files | `adp extract local <folder path>` <br> `adp parse local <folder path> ` | Batch processing can accept files from the local folder. | | Batch processing of URL files | `adp extract url <URL list file path>` <br> `adp parse url <URL list file path> ` | If you need to process multiple URLs in a batch, you can first save the list of URLs in a text file, and then input the corresponding URL of this text file to achieve batch processing at once. | Note: - The `adp extract` command has built-in document parsing capabilities. After ADP automatically parses the document, it performs structured extraction. Therefore, when users need to extract the structured content of the document, there is no need to use apd for parsing. - URL list file format: A plain text file where each line is a URL pointing to a document to be processed. ### Quick Reference for Common Commands ```bash # Command Discovery (for Agent introspection) adp schema # Configuration Check adp config get # Query Applications (First Use) adp app-id list # Document Extraction (Invoice/Receipt) adp extract url <file URL> --app-id <app_id> # Document Parsing (Long Document) adp parse url <file URL> --app-id <app_id> # Base64 Input adp extract base64 <base64_string> --app-id <app_id> --file-name invoice.pdf adp parse base64 <base64_string> --app-id <app_id> --file-name document.pdf # Asynchronous Query adp extract query <task_id> adp parse query <task_id> adp parse query <task_id1> <task_id2> --watch # batch query with auto-poll # Batch Processing adp extract local <folder path> --app-id <app_id> --export <folder path> --concurrency 2 adp parse local <folder path> --app-id <app_id> --export <folder path> --concurrency 2 ``` ## Performance Optimization Suggestions - **Reuse APP_ID**: Cache it in the context after one query to avoid calling `app-id list` every time. - **Sync First**: For small files (<20MB), prioritize using synchronous calls to avoid asynchronous polling. - **Batch Processing**: Processes multiple documents via `url <URL list file path>` or `local <folder path>` in a single run, without looped invocations. Default `--concurrency 2`. - **Local Cache**: Store commonly used APP_IDs in environment variables or configuration files. - **Priority Extraction**: If only key information needs to be extracted, use `extract` instead of `parse` (faster). - **Use --retry for batch**: Set `--retry 2` for batch processing to auto-recover from transient failures. - **Use --timeout for large files**: Increase `--timeout` for files >20MB. Default is 900s. --- ## Detailed Product Introduction ### Core Function Definition - **parse**: Parses the entire document to retrieve full text, layout, structure, and content. - **extract**: Extracts specific structured fields from the document, such as amount, date, company name, and order number. ### Application Scenarios - **Long Document Parsing**: Efficiently process long documents with fast parsing speed, accurately extract multiple elements such as text, tables and images, replace manual extraction, and improve efficiency. - **Structured Extraction for Scanned/Photographed Documents**: For scanned documents and photos, complete structured extraction in reading order, generate clear and editable electronic documents, and eliminate manual entry errors. - **Intelligent Invoice Extraction**: After uploading invoice images/documents, AI automatically invokes preset applications to accurately extract 10+ key fields such as invoice number and amount, suitable for financial filing scenarios. - **Intelligent Order Extraction**: Support batch upload of orders from multiple distributors, AI extracts 10+ key fields such as order number and buyer-seller information, automatically identifies currencies, and reduces manual verification costs. - **Domestic ID Document Extraction**: Process in seconds, supporting the identification and extraction of more than 10 common types of documents in China; for example, core information such as name and ID number can be quickly extracted from ID card scans. - **Automatic Splitting and Extraction of Mixed Documents**: Batch upload mixed documents such as contracts and invoices, AI automatically classifies, splits and completes structured extraction to improve processing efficiency. - **Batch Document Processing**: Support batch upload of various business documents, extract information and output standardized structured data, reducing repetitive manual operations. ## Detailed Usage Steps ### Step 1: Obtain the Installation Package For details, see [references/examples.md](references/examples.md) ### Step 2: Obtain and Configure API Key #### 1. Access the ADP Portal to Obtain Credentials We provide independent Public Cloud access addresses for domestic and international users, which need to be configured separately by region. Accessing nearby can better ensure high-speed and stable calls across the network. | Region | Login Address | API Base URL | |-----|----------|--------------| | Chinese Mainland | [https://adp.laiye.com/](https://adp.laiye.com/?utm_source=clawhub) | `https://adp.laiye.com/` | | Overseas Region | [https://adp-global.laiye.com/](https://adp-global.laiye.com/?utm_source=clawhub) | `https://adp-global.laiye.com/` | #### 2. Get API Key after registration/login New users need to register an ADP account first, and after registration, they can get 100 free credits/month - After logging in, click on the personal avatar, and you can directly access the `API_Key` entry. #### 3. Complete the authentication configuration For details, see [references/examples.md](references/examples.md) #### 4. Verify the configuration For details, see [references/examples.md](references/examples.md) **Notes**: 1. If API Key and API Base URL have been configured, the configuration information needs to be stored in environment variables to avoid uploading configuration items every time they are used. 2. If API Key and API Base URL have not been configured yet, they need to be configured according to the above steps. ### Step 3: Upload Documents After completing the authentication of the API Key, guide the user to upload local files or specify the file URL. After the user uploads the document, they can query the supported application scope of ADP and select the appropriate application for document parsing and extraction. If no suitable application is found, they can choose to create a custom extraction application, configure exclusive fields and parsing modes to meet the personalized document processing requirements. ### Step 4: Query Available Applications This function is used to query the built-in applications under the user's account (such as invoices/receipts, orders, common cards and certificates in China region, etc. which are standardized documents). Based on the `app-label`, you can assist in filtering the suitable application IDs. If no suitable application is found, you can choose to create a custom extraction application, configure specific fields and parsing modes to meet the personalized document processing requirements. **Notes**: 1. For the first execution, use `adp app-id list`. For subsequent executions, prefer to use `adp app-id cache` (cache the application ID in the context). If the cache becomes invalid or there are no suitable applications in the cache, call `adp app-id list` again to update the cache. For detailed examples of commands and responses, see [references/examples.md](references/examples.md). ### Step 5: Add custom extraction application Support creating custom extraction applications, and independently add business-specific extraction fields as needed, and improve the detailed description of each field; the system will accurately identify the document content based on the configured fields and definitions, and complete customized information extraction for personalized documents and non-standard forms. For example commands, responses, and detailed parameter descriptions, please refer to [references/examples.md](references/examples.md) ### Step 6: Execute Document Processing ### Single Document Parsing Perform document parsing based on the selected application ID, which will return a formatted JSON result containing information such as document content, element position coordinates, OCR Confidence Level, etc. For examples of commands and responses, please refer to [references/examples.md](references/examples.md) ### Single Document Extraction Perform document extraction based on the selected application ID, which will return a formatted JSON result containing information such as extraction fields, extraction results, and Confidence Level. For examples of commands and responses, please refer to [references/examples.md](references/examples.md) ### Batch Document Processing ADP supports batch processing capabilities. Users can upload multiple file URLs or local folder paths at once, and the system will automatically identify each document type and match the most suitable application for processing, greatly improving the efficiency of batch document processing. For detailed command examples, see [references/examples.md](references/examples.md) **Note**: The number of concurrent requests is limited to 1 for free users, while enterprise users can adjust it according to their needs, with a maximum support of 2. ### Asynchronous Processing (Suitable for Large Documents) ADP provides asynchronous processing capabilities, allowing users to choose asynchronous mode to perform document parsing and extraction. The system will return a task ID, and users can periodically query the task status and results through the query interface, which is suitable for processing complex documents or batch documents with long processing times. If the document uploaded by the user is larger than 20MB or contains more than 200 pages, it is recommended to use the asynchronous processing mode. For examples of commands and responses, see [references/examples.md](references/examples.md) --- ## Complete Command List For a complete list of all available commands with full parameter specs, see [references/commands.md](references/commands.md) ## Response Schema Reference For the output structure of each command (including batch processing output mechanism), see [references/response-schema.md](references/response-schema.md) ## Error Handling Guide For error codes, types, and Agent auto-recovery strategies, see [references/error-handling.md](references/error-handling.md) --- ## Precautions When using ADP output, always present the returned data as-is. Do not modify, add, or remove any fields during extraction or parsing to ensure data integrity. 1. **API Key Security**: Please keep your API Key secure and avoid disclosing it to unauthorized third parties. 2. **API Base URL Configuration**: Select the corresponding address based on the region. For Chinese Mainland, use `https://adp.laiye.com/`, and for overseas regions, use `https://adp-global.laiye.com/` 3. **File Size Limit**: The maximum size of a single file is 50MB 4. **Supported Formats**: .jpg, .jpeg, .png, .bmp, .tiff, .tif, .pdf, .doc, .docx, .xls, .xlsx 5. **Free Quota**: New users receive 100 free credits per month, which are reset at the beginning of each month. Credits can be used for document parsing and extraction processing. 6. **Check Balance**: Run `adp credit` to check the current account's credit balance. 7. **Billing Rules**: - Document parsing: 0.5 credits per page - Invoice/receipt extraction: 1.5 credits per page - Order extraction: 1.5 credits per page - Custom extraction: 1 credit per page 8. **App ID Reuse**: The app ID used by the user can be remembered for direct use next time, eliminating the need to enter the app_id after each query. The app ID under each user is unique and fixed; unless the user deletes the app, the app_id will not change, and the previously queried app_id can be directly used for document processing calls. --- ## Related Resources - **CLI Documentation**: [ADP CLI User Guide](https://laiye-tech.feishu.cn/wiki/YIaawiK2DimisZk5KfDc8a8cnLh) - **API Documentation**: [OpenAPI User Guide](https://laiye-tech.feishu.cn/wiki/S1t2wYR04ivndKkMDxxcp2SFnKd) - **User Guide**: [Public Cloud Operation Manual](https://laiye-tech.feishu.cn/wiki/OfexwgVUQiOpEek4kO7c7NEJnAe) - **Problem Feedback**: [GitHub Issues](https://github.com/laiye-ai/adp-cli/issues) | [REDACTED_SECRET] - **Official Website**: [Laiye Technology](https://laiye.com) --- Copyright © 2026 [Laiye Technology (Beijing) Co., Ltd.] All rights reserved.

path: license.md
content: Commercial License Agreement

Effective Date: [March 30, 2026]
Copyright © 2026 [Laiye Technology (Beijing) Co., Ltd.] All rights reserved.

This “Skill” (referring to the entirety including models, software, code, weights, documentation, data, and related derivative works, “the Product”) is developed and wholly owned by Laiye Technology (Beijing) Co., Ltd. (“Licensor”). The mentioned derivative works refer to new works created by modifying, integrating, fine-tuning, or further developing the Product. Subject to your (“Licensee” or “you”) compliance with the terms of this Agreement, the Licensor grants you a worldwide, royalty-free, non-exclusive license.

1. Licensing

1.1 Free Use and Distribution: The Licensor grants the Licensee a non-transferable, non-exclusive right to freely use, copy, publish, and distribute copies of the Product for non-commercial purposes. The aforementioned "non-commercial purposes" include, but are not limited to:
Personal learning, research, teaching, and evaluation.
Technical exchanges within academic institutions or open-source communities, non-profit projects.
Integration or demonstration in non-commercial products or services.
1.2 Commercial License:	Any activity intended to directly or indirectly obtain commercial benefits, revenue, or consideration (“Commercial Exploitation”) requires the explicit written authorization (i.e., a "Commercial License") from the Licensor. Commercial Exploitation includes, but is not limited to:
Distributing the Product or derivative works thereof in forms such as sales, resale, licensing fees, subscription fees, or other charges.
Providing the Product or derivative works thereof as a SaaS (Software as a Service) to third parties.
Integrating the Product or derivative works thereof, as a core function, into software, hardware, or services intended for sale or lease.
Any for-profit activity that utilizes the functionality or content of the Product to provide services to third parties.

2. Reserved Rights and Ownership

2.1	Ownership, intellectual property rights (including but not limited to copyright, patents, trademarks, trade secrets), and other related rights and interests in the Product (including all copies thereof) belong to the Licensor or its affiliates. This Agreement does not constitute any form of transfer of rights or sale of the Licensor's intellectual property.
2.2	The Licensee may non-commercially distribute unmodified copies of the Product through channels such as open-source platforms, or engage in non-commercial further development, and distribution, provided that this Agreement, the copyright notice, and the original identification are fully retained.
3. Distribution Conditions

When the Licensee distributes or provides the Product, all of the following conditions must be met:
Retention of Notices:	Prominently retain all copyright notices of the Product, the text of this License Agreement, and the disclaimer on distributed copies.
No Misrepresentation:	Should not imply that the Licensor endorses your distribution version.

4. Disclaimer of Warranties

THE PRODUCT IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO: THE LICENSOR DOES NOT WARRANT THAT THE PRODUCT IS FREE FROM ERRORS, BUGS, WILL OPERATE PROPERLY, OR IS SUITABLE FOR A PARTICULAR PURPOSE; THE LICENSOR DOES NOT WARRANT THAT USE OF THE PRODUCT WILL NOT INFRINGE UPON THIRD-PARTY RIGHTS; THE LICENSOR SHALL NOT BE LIABLE TO THE LICENSEE OR ANY THIRD PARTY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, OR PUNITIVE DAMAGES ARISING FROM THE USE OF THE PRODUCT.

5. Termination

5.1	This Agreement becomes effective from the Licensee's first use of the Product and continues until terminated.
5.2	If the Licensee violates the restrictions in Article 1 "License Grant" of this Agreement (e.g., unauthorized Commercial Exploitation), this Agreement will terminate automatically without prior notice.
5.3	Upon termination, the Licensee must immediately cease using the Product and destroy all copies of the Product in its possession.

6. Miscellaneous

6.1	The formation, execution, interpretation, and dispute resolution of this Agreement shall be governed by the laws of the People's Republic of China.
6.2	The Licensee shall not assign or transfer any of its rights or obligations under this Agreement without the Licensor's prior written consent.
6.3	This Agreement constitutes the entire agreement between the parties concerning this license matter and supersedes any prior oral or written communications and agreements between the parties regarding this matter.
6.4	Any dispute related to this Agreement shall be settled through friendly negotiation between the parties. If negotiation fails, either party has the right to submit the dispute to the competent court in the place where the Licensor is registered.

For obtaining a Commercial License or if you have any questions, please contact:
[[REDACTED_SECRET]]


The Product is licensed under the Commercial License Agreement.  For commercial use, please contact us to obtain authorization.

path: README-CN.md
content: <div align="center">
<a id="agentic_doc_parse_and_extract"></a>

# 📄 来也智能体文档处理官方CLI (agentic_doc_parse_and_extract)

agentic_doc_parse_and_extract 是来也科技ADP（Agentic Document Processing）产品发布的官方命令行工具，让人类和 AI Agent 都能在终端中调用ADP能力进行文档解析与抽取

[English](README.md) | [简体中文](README-CN.md)

</div>

## 🚀 关于来也ADP

ADP是来也科技公司**智能体文档处理产品 (Agentic Document Processing，简称 ADP)**， 基于大模型的通用理解能力，不依赖规则与标注，具备对多语言、多模态、多场景的通用理解能力；智能体的自主规划与执行，能够理解任务目标、自主规划步骤、调用工具、完成复杂任务；端到端的业务自动化，从文档输入到业务决策再到人机协同，形成完整闭环。

**agentic-doc-parse-and-extract** 是 ADP 官方开源 CLI 工具，同时支持人工终端调用 + AI Skill 自动调用。一条命令即可完成：文档结构化解析 + 关键字段智能抽取，覆盖发票、订单、证件、票据、通用文档全场景，输出标准 JSON，无缝对接自动化与 AI 流程。

---

### 💡 核心功能

agentic-doc-parse-and-extract 聚焦文档全流程智能处理，兼顾人工终端调用与 AI Agent 自动调用，核心功能覆盖解析、抽取、批量处理全场景，无需复杂配置，一条命令即可完成操作：

| 功能名称 | 功能描述 | 最佳场景 |
|---------|------------------|----------|
| **文档解析** | 自动识别 PDF、图片等多格式文档，将杂乱的非结构化内容（如扫描件、手写体、复杂排版文档）转化为标准化结构化数据，保留原始文档层级与关键关联关系 | 将非结构化文档转换为结构化数据，供 LLM 阅读和后续抽取使用 |
| **开箱即用文档抽取** | 基于 ADP 大模型原生 AI 能力，内置发票、收据、订单、中国地区常用证件等标准化抽取模型，无需配置规则、无需人工标注，一键提取各类通用单据关键字段，输出标准 JSON | 应付账款自动化、费用管理、采购自动化、卡证信息快速录入系统 |
| **自定义文档抽取** | 支持自主创建、编辑与管理个性化抽取应用，可针对企业专属单据、行业定制表单配置专属抽取字段与识别逻辑 | 企业专属单据、行业定制表单、非标准化文档的私有化抽取需求 |
| **任务查询** | 支持异步任务提交与状态查询，可快速查看任务执行进度、成功/失败状态，以及任务最终处理结果 | 批量任务处理、异步文档处理、问题排查与处理记录追溯 |
| **应用管理** | 提供完整的应用管理能力，可查看所有可用的抽取应用（系统内置 + 自定义）、查询应用详情、应用标签 | 多场景业务切换、应用全生命周期管控、自定义应用管理 |

---

### 🎯 适用人群

- **AI Agent 开发者：** 通过标准 Skill 快速集成文档解析抽取能力，赋能智能体自动化办公流程
- **企业研发与架构团队：** 统一接入 CLI 工具，低成本落地全品类单据结构化自动化处理
- **财务 & 行政运营团队：** 批量解析发票、收据、报销单，减少人工录入与核对成本
- **业务系统集成方：** 依赖标准化 JSON 输出，无缝对接 ERP、RPA、业务中台等上下游系统
- **内部平台建设者：** 支持本地部署与环境适配，满足企业内网安全与权限管控要求


## 📁 项目文件结构与文件说明

```
agentic-doc-parse-and-extract/
├── skill.md                  # Skill配置与调用说明
├── README.md                 # 来也ADP产品介绍与CLI下载与调用说明
├── references/               # 参数枚举、错误码、JSON返回说明
    ├── examples.md           # 调用与返回示例代码 参数说明
    ├── commands.md           # 所有命令列表
    ├── response-schema.md    # 返回参数说明
    ├── error-handling.md     # 错误与应对措施
├──  License                  # 授权许可
```


## 📋 API Key
### 获取API Key
1. 访问 [ADP 中国地区网址](https://adp.laiye.com/?utm_source=clawhub)、 [ADP 全球地区网址](https://adp-global.laiye.com/?utm_source=clawhub)
2. 注册新账户（新用户每月 100 免费积分）


## 💻 环境与安装
### 支持平台与版本
| 平台 | 最低要求 |
|---------|------------------|
| **Windows** | Windows 10 或更高版本 |
| **Linux** | Ubuntu 18.04+, CentOS 7+, 或主流Linux发行版 |
| **macOS** | macOS 10.14 (Mojave) 或更高版本 |
---

### 安装

  ```bash
  # 方法 1: npm（推荐，全平台通用，国内可通过 npmmirror 镜像加速）
  npm install -g @laiye-adp/agentic-doc-parse-and-extract-cli --registry=https://registry.npmmirror.com/ || npm install -g @laiye-adp/agentic-doc-parse-and-extract-cli

  # 方法 2: Shell 脚本（Linux / macOS，无 npm 环境时使用）
  curl -fsSL https://raw.githubusercontent.com/laiye-ai/adp-cli/main/scripts/adp-init.sh | bash

  # 方法 3: PowerShell 脚本（Windows，无 npm 环境时使用）
  Invoke-WebRequest -Uri "https://raw.githubusercontent.com/laiye-ai/adp-cli/main/scripts/adp-init.ps1" -OutFile "$env:TEMP\adp-init.ps1"; & "$env:TEMP\adp-init.ps1"
  ```

---

## ✨ 核心特性

### 📦 开箱即用产品

| 产品 | 提取内容 | 最佳场景 |
|---------|------------------|----------|
| **文档解析** | 提取文档内的文本、表格、图片、印章等元素 | 将文档转换成结构化数据供LLM阅读 |
| **发票/收据抽取** | 发票号码、日期、供应商、明细项目、总额、税费 | 应付账款自动化、费用管理 |
| **订单抽取** | 采购单号、商品、数量、价格、交付信息 | 采购自动化、电商集成 |
| **卡证抽取** | 身份证、银行卡、驾驶证、营业执照等11种常用卡证 | 卡证信息快速录入系统 |

### 🛠️ 技术能力

- **10+ 种文件格式** ： 覆盖主流图片与办公文档格式（.jpg, .jpeg, .png, .bmp, .tiff, .tif, .pdf, .doc, .docx, .xls, .xlsx）
- **VLM + LLM 双引擎** ： 视觉理解 + 语义提取，实现最大准确率
- **同步与异步模式** ： 所有功能均对外开放同步、异步 API
- **文件限制：** 最大文件大小：50MB
- **批量处理：** 支持文件夹递归处理

### 🌟 产品优势
- 依托来也科技 ADP 大模型核心能力，结合 CLI 工具轻量化特性，打造高效、灵活、易集成的文档处理解决方案，核心优势突出：
- 零门槛上手：无需专业技术背景，无需规则配置与数据标注，内置标准化抽取模型，开箱即用，一条命令完成文档解析与抽取。
- 全场景适配：覆盖发票、收据、订单、证件等通用场景，同时支持自定义扩展，适配企业专属单据、行业定制表单，兼顾通用性与个性化需求。
- 高效集成适配：支持 AI Agent Skill 原生调用、终端手动调用，输出标准 JSON 格式，无缝对接 RPA、ERP、业务中台等上下游系统，降低集成成本。
- 多终端兼容：Windows、macOS、Linux 全平台支持，无需额外安装依赖，配置环境变量后全局可调用，适配本地部署与多场景办公需求。
- 高精度高稳定：基于 ADP 大模型优化，非结构化文档（扫描件、手写体、复杂排版）识别准确率高，支持异步任务管理，保障业务流程稳定运行。

<a id="credit"></a>
### 💰 计费

- **新用户福利：** 每月获得 100 免费积分，不限制使用应用
- **资产消耗规则：**
    | 处理阶段 | 费用 |
    |-----------------|------|
    | 文档解析 | 0.5 积分/页 |
    | 采购订单抽取 | 1.5 积分/页 |
    | 发票/收据抽取 | 1.5 积分/页 |
    | 自定义抽取 | 1 积分/页 |

- **资产充值：** 可直接登录ADP门户网站进行资产充值，我们为国内外用户提供了独立公有云接入地址，需要按区域分开配置，就近访问可更大程度保障全网高速稳定调用。
  - 中国大陆地区[登录](https://adp.laiye.com/?utm_source=clawhub)
  - 非中国大陆地区用户[登录](https://adp-global.laiye.com/?utm_source=clawhub)

  如支付遇到问题，请联系支持邮箱：📧 [REDACTED_SECRET]

## 📜 授权许可

我们采用 开源工具 + 付费服务 的组合模式：CLI 工具完全免费开源，方便大家快速接入；而核心的 ADP 智能解析能力为公有云商业服务，按实际使用量计费，旨在为用户提供高精准、高稳定的文档处理体验。

- **CLI 工具**：MIT License 开源许可，可自由使用、修改和分发
- **ADP 服务**：基于公有云的 AI 文档处理服务，按使用量计费，[计费规则](#credit)

### 💰 免费额度
新用户注册后每月可获得 **100 免费积分**，可体验完整功能


## 📞 支持与联系
- **CLI 使用指南：** [ADP CLI 使用指南](https://laiye-tech.feishu.cn/wiki/Hz3Vw1IQki3YQtk33gLcSdwSndc)
- **API 接口文档：** [Open API 使用指南](https://laiye-tech.feishu.cn/wiki/PO9Jw4cH3iV2ThkMPW2c539pnkc)
- **ADP 产品操作手册：** [公有云操作手册](https://laiye-tech.feishu.cn/wiki/UDYIwG42pisBbFkJI39ctpeKnWh)

- **问题反馈：** [GitHub Issues](https://github.com/laiye-ai-repos/adp-skill/issues)
- **邮箱：** [REDACTED_SECRET]
- **官网：** [来也科技](https://laiye.com)

---

<div align="center">
[⬆ 返回顶部](#agentic_doc_parse_and_extract)

**用 ❤️ 构建智能体 AI 的未来**
版权所有 © 2026 [来也科技（北京）有限公司] 保留所有权利。

</div>


path: README.md
content: <div align="center">
<a id="agentic_doc_parse_and_extract"></a>

# 📄 Laiye Agentic Document Processing CLI (agentic_doc_parse_and_extract)

agentic_doc_parse_and_extract is the official command-line tool released by Laiye Technology's ADP (Agentic Document Processing) product, enabling both humans and AI Agents to invoke ADP capabilities in the terminal for document parsing and extraction.

[English](README.md) | [Simplified Chinese](README-CN.md)

</div>

## 🚀 About Laiye ADP

ADP is Laiye's **intelligent agent document processing product (Agentic Document Processing, referred to as ADP)** , based on the general understanding ability of large models, without relying on rules and annotations, with the general understanding ability of multi-language, MultiModal Machine Learning, and multi-scene; autonomous planning and execution of intelligent agents, able to understand task goals, autonomous planning steps, invoke tools, and complete complex tasks; end-to-end business automation, from document input to business decision-making to human-machine collaboration, forming a complete closed loop.

**agentic-doc-parse-and-extract** is the official open-source CLI tool of ADP, supporting both manual terminal invocation and automatic invocation via AI Skill. With a single command, it can accomplish: structured document parsing + intelligent extraction of key fields, covering all scenarios including invoices, orders, certificates, bills, and general documents, outputting standard JSON, and seamlessly integrating with automation and AI workflows.

---

### 💡 Core Features

agentic-doc-parse-and-extract focuses on intelligent processing of the entire document workflow, taking into account both manual terminal calls and automatic calls by AI Agents. Its core functions cover all scenarios of parsing, extraction, and batch processing, requiring no complex configuration, and operations can be completed with a single command:

| Function Name | Function Description | Optimal Scenario |
|---------|------------------|----------|
| **Document Parsing** | Automatically recognize multi-format documents such as PDFs and images, convert messy unstructured content (e.g., scanned documents, handwritten text, complex layout documents) into standardized Structured Data, while preserving the original document hierarchy and key relationships | Convert unstructured documents into Structured Data for LLM reading and subsequent extraction |
| **Out Of The Box Document Extraction** | Based on the native AI capabilities of the ADP large model, it comes with built-in standardized extraction models for invoices, receipts, orders, commonly used certificates in China, etc. No need to configure rules or manual annotation, one-click extraction of key fields from various types of general documentation, outputting standard JSON | Account Payable automation, expense management, procurement automation, quick entry of card and certificate information into the system |
| **Custom Document Extraction** | Supports independent creation, editing, and management of personalized extraction applications, allowing configuration of exclusive extraction fields and recognition logic for enterprise-specific documentation and industry-customized forms | Private extraction requirements for enterprise-specific documentation, industry-customized forms, and non-standardized documents |
| **Task Query** | Supports asynchronous task submission and status query, enabling quick viewing of task execution progress, success/failure status, and final task processing results | Batch task processing, asynchronous document processing, problem troubleshooting, and processing record tracing |
| **Application Management** | Provides comprehensive application management capabilities, allowing users to view all available extraction applications (system-built + custom), query application details, and manage application tags | Multi-scenario business switching, full lifecycle management of applications, and custom application management |

---

### 🎯 Target Audience

- **AI Agent Developers:** Quickly integrate document parsing and extraction capabilities through standard Skills to empower intelligent agents in automated work processes
- **Enterprise R&D and Architecture Team:** Unified access to CLI tools, enabling low-cost implementation of structured and automated processing for all types of documentation
- **Finance & Administrative Operations Team:** Batch parsing of invoices, receipts, and reimbursement forms, reducing manual entry and verification costs
- **Business System Integrator:** Relying on standardized JSON output, seamlessly connecting with upstream and downstream systems such as ERP, RPA, and Central Product Platform
- **Internal Platform Builder:** Supporting local deployment and environment adaptation to meet the requirements of enterprise intranet security and permission management

## 📁 Project File Structure and File Description

```
agentic-doc-parse-and-extract/
├── skill.md                  # Skill configuration and invocation instructions
├── README.md                 # Introduction to Laiye ADP product and instructions for CLI download and invocation
├── references/               # Parameter enumeration, error codes, and JSON return instructions
    ├── examples.md           # Sample code for invocation and return with parameter explanations
    ├── commands.md           # List of all commands
    ├── response-schema.md    # Return parameter description
    ├── error-handling.md     # Mistakes and what to do about them
├── License                   # License authorization
```

## 📋 API Key
### Get API Key
1. Visit [ADP China Region URL](https://adp.laiye.com/?utm_source=clawhub), [ADP Global Region URL](https://adp-global.laiye.com/?utm_source=clawhub)
2. Register a new account (new users get 100 free credits per month)

## 💻 Environment and Installation
### Supported Platforms and Versions
| Platform | Minimum Requirements |
|---------|------------------|
| **Windows** | Windows 10 or later |
| **Linux** | Ubuntu 18.04+, CentOS 7+, or mainstream Linux distributions |
| **macOS** | macOS 10.14 (Mojave) or later |
---

### Install

 ```bash
  # Method 1: npm (recommended, works on all platforms, China-friendly with npmmirror)
  npm install -g @laiye-adp/agentic-doc-parse-and-extract-cli --registry=https://registry.npmmirror.com/ || npm install -g @laiye-adp/agentic-doc-parse-and-extract-cli
  export PATH="$(npm prefix -g)/bin:$PATH"

  # Method 2: Shell script (Linux / macOS, if npm is not available)
  curl -fsSL https://raw.githubusercontent.com/laiye-ai/adp-cli/main/scripts/adp-init.sh | bash

  # Method 3: PowerShell script (Windows, if npm is not available)
  Invoke-WebRequest -Uri "https://raw.githubusercontent.com/laiye-ai/adp-cli/main/scripts/adp-init.ps1" -OutFile "$env:TEMP\adp-init.ps1"; & "$env:TEMP\adp-init.ps1"
  ```

---

## ✨ Product & Technical Highlights

### 📦 Out Of The Box Product

| Product | Extracted Content | Optimal Scenario |
|---------|------------------|----------|
| **Document Parsing** | Extract elements such as text, tables, images, seals, etc. from the document | Convert the document into structured data for LLM to read |
| **Invoice/Receipt Extraction** | Invoice number, date, supplier, item details, total amount, taxes | Accounts payable automation, expense management |
| **Order Extraction** | Purchase Order Number, Commodity, Quantity, Price, Delivery Information | Procurement Automation, E-commerce Integration |
| **Card Extraction** | 11 types of commonly used cards and certificates such as ID card, bank card, driver's license, business license, etc. | Quick entry of card and certificate information into the system |

### 🛠️ Technical Capabilities

- **10+ File Formats**: Covers mainstream image and work document formats (.jpg,.jpeg,.png,.bmp,.tiff,.tif,.pdf,.doc,.docx,.xls,.xlsx)
- **VLM + LLM Dual Engines**: Visual understanding + semantic extraction to achieve maximum accuracy
- **Synchronous and Asynchronous Modes**: All functions are open to external synchronous and asynchronous APIs
- **File Restrictions:** Maximum file size: 50MB
- **Batch Processing:** Supports folder recursion processing
### 🌟 Product Advantages
- Relying on the core capabilities of Laiye Technology's ADP large model and combining the lightweight features of CLI tools, we have created an efficient, flexible, and easily integrated document processing solution with prominent core advantages:
- Zero-threshold entry: No professional technical background is required, no rule configuration or data annotation is needed, with a built-in standardized extraction model that is out of the box, and a single command can complete document parsing and extraction.
- Full-scenario adaptation: Covers common scenarios such as invoices, receipts, orders, certificates, etc., while supporting custom extensions to adapt to enterprise-specific documentation and industry-specific forms, taking into account both general and personalized needs.
- Efficient integration and adaptation: Supports native calls of AI Agent Skill and manual calls from terminals, outputs in standard JSON format, seamlessly connects with upstream and downstream systems such as RPA, ERP, and Central Product Platform, reducing integration costs.
- Multi-terminal compatibility: Supports all platforms including Windows, macOS, and Linux, requires no additional installation of dependencies, can be globally called after configuring environment variables, and adapts to local deployment and multi-scenario work requirements.
- High Precision and Stability: Optimized based on the ADP large model, it has high recognition accuracy for unstructured documents (scanned documents, handwritten text, complex layouts), supports asynchronous task management, and ensures the stable operation of business processes.

<a id="credit"></a>
### 💰 Billing

- **New User Benefits:** Receive 100 free credits per month, with no restrictions on application usage
- **Asset Consumption Rules:**
    | Processing Stage | Cost |
    |-----------------|------|
    | Document Parsing | 0.5 points/page |
    | Purchase Order Extraction | 1.5 points/page |
    | Invoice/Receipt Extraction | 1.5 points/page |
    | Custom Extraction | 1 point/page |

- **Asset Recharge:**  You can directly log in to the ADP Portal to recharge assets. We provide independent Public Cloud access addresses for domestic and international users, which need to be configured separately by region. Accessing from a nearby location can better ensure high-speed and stable invocation across the network.
  - Users in Chinese Mainland [Log in](https://adp.laiye.com/?utm_source=clawhub)
  - Users outside Chinese Mainland [Log in](https://adp-global.laiye.com/?utm_source=clawhub)

 If you encounter any issues with payment, please contact the support email: 📧 [REDACTED_SECRET]

## 📜 License

We adopt a combined model of open-source tools + paid services: the CLI tool is completely free and open-source, making it easy for everyone to quickly integrate; while the core ADP intelligent parsing capability is a Public Cloud commercial service, billed based on actual usage, aiming to provide users with a highly accurate and stable document processing experience.

- **CLI Tool**: Open source under the MIT License, freely available for use, modification, and distribution
- **ADP Service**: AI document processing service based on Public Cloud, billed by usage, [Billing Rules](#credit)

### 💰 Free Quota
New users can receive **100 free credits** per month after registration, allowing them to experience full functionality

## 📞 Support and Contact
- **CLI Documentation**: [ADP CLI User Guide](https://laiye-tech.feishu.cn/wiki/YIaawiK2DimisZk5KfDc8a8cnLh)
- **API Documentation**: [OpenAPI User Guide](https://laiye-tech.feishu.cn/wiki/S1t2wYR04ivndKkMDxxcp2SFnKd?from=from_copylink)
- **User Guide**: [Public Cloud Operation Manual](https://laiye-tech.feishu.cn/wiki/OfexwgVUQiOpEek4kO7c7NEJnAe)
- **Problem Feedback**: [GitHub Issues](https://github.com/laiye-ai/adp-cli/issues) | [REDACTED_SECRET]
- **Official Website**: [Laiye Technology](https://laiye.com/en/)

---

<div align="center">
[⬆ Back to Top](#agentic_doc_parse_and_extract)

**Build the Future of Agentic AI with ❤️**
Copyright © 2026 [Laiye Technology (Beijing) Co., Ltd.] All rights reserved.

</div>

path: references/commands.md
content: # ADP CLI Complete Command Reference

> This document is strictly aligned with the CLI's built-in `adp schema` output. Agent can also run `adp schema` to get the machine-readable JSON version of this spec.

## Global Options

| Option | Type | Description |
|--------|------|-------------|
| `--lang` | string | Set language (`en` or `zh`) |
| `--json` | boolean | Output in JSON format (recommended for Agent) |
| `--quiet` | boolean | Suppress all output except errors |

---

## config — Configuration Management

### `adp config set`

Set API Key or Base URL.

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `--api-key` | string | No | API Key for authentication |
| `--api-base-url` | string | No | API Base URL |

### `adp config get`

View current configuration (no options).

### `adp config clear`

Clear all configuration.

| Option | Type | Description |
|--------|------|-------------|
| `--force`, `-y` | boolean | Skip confirmation prompt |

---

## app-id — Application Management

### `adp app-id list`

Query available applications.

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--app-label` | string | No | — | Filter by application label |
| `--app-type` | integer | No | — | Filter by application type: `0`=system preset, `1`=custom; omit to list all |
| `--limit` | integer | No | 120 | Maximum number of results |

### `adp app-id cache`

View cached application list (no options). Cache is permanent and does not expire.

---

## credit — Credit Balance

### `adp credit`

Check current account credit balance.

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `--api-key` | string | No | Override configured API Key |

---

## parse — Document Parsing

Parses the entire document to retrieve full text, layout, structure, and content.

### `adp parse local <file-path>`

Parse local file or folder (batch mode when path is a folder).

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--app-id` | string | **Yes** | — | Application ID |
| `--async` | boolean | No | false | Enable asynchronous processing |
| `--no-wait` | boolean | No | false | Submit async task and return immediately (use with `--async`) |
| `--export` | string | No | — | Export results to specified path |
| `--timeout` | integer | No | 900 | Timeout in seconds |
| `--concurrency` | integer | No | 1 | Concurrent processing count (max 1 free, max 2 paid) |
| `--retry` | integer | No | 0 | Number of retries on failure (exponential backoff) |

### `adp parse url <url>`

Parse document from URL. When the URL points to a text file containing a list of URLs (one per line), batch mode is activated.

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--app-id` | string | **Yes** | — | Application ID |
| `--async` | boolean | No | false | Enable asynchronous processing |
| `--no-wait` | boolean | No | false | Submit async task and return immediately (use with `--async`) |
| `--export` | string | No | — | Export results to specified path |
| `--timeout` | integer | No | 900 | Timeout in seconds |
| `--concurrency` | integer | No | 1 | Concurrent processing count |
| `--retry` | integer | No | 0 | Number of retries on failure |

### `adp parse base64 <base64-strings>`

Parse base64-encoded document content.

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--app-id` | string | **Yes** | — | Application ID |
| `--async` | boolean | No | false | Enable asynchronous processing |
| `--no-wait` | boolean | No | false | Submit async task and return immediately |
| `--export` | string | No | — | Export results to specified path |
| `--timeout` | integer | No | 900 | Timeout in seconds |
| `--file-name` | string | No | "document" | Display name with extension for the base64 content (used to detect file type; does not read from disk) |
| `--concurrency` | integer | No | 1 | Concurrent processing count |
| `--retry` | integer | No | 0 | Number of retries on failure |

### `adp parse query <task-ids...>`

Query async parse task status and results. Supports multiple task IDs as arguments.

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--watch` | boolean | No | false | Continuously poll until task completes |
| `--file` | string | No | — | Read task IDs from a JSON file (produced by `--no-wait`) |
| `--export` | string | No | — | Export results to specified path |
| `--timeout` | integer | No | 900 | Watch mode timeout in seconds |
| `--concurrency` | integer | No | 1 | Concurrent query count |

---

## extract — Document Extraction

Extracts specific structured fields from documents (amount, date, company name, etc.).

### `adp extract local <file-path>`

Extract from local file or folder (batch mode when path is a folder).

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--app-id` | string | **Yes** | — | Application ID |
| `--async` | boolean | No | false | Enable asynchronous processing |
| `--no-wait` | boolean | No | false | Submit async task and return immediately |
| `--export` | string | No | — | Export results to specified path |
| `--timeout` | integer | No | 900 | Timeout in seconds |
| `--concurrency` | integer | No | 1 | Concurrent processing count |
| `--retry` | integer | No | 0 | Number of retries on failure |

### `adp extract url <url>`

Extract from URL document. Supports URL list file for batch mode.

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--app-id` | string | **Yes** | — | Application ID |
| `--async` | boolean | No | false | Enable asynchronous processing |
| `--no-wait` | boolean | No | false | Submit async task and return immediately |
| `--export` | string | No | — | Export results to specified path |
| `--timeout` | integer | No | 900 | Timeout in seconds |
| `--concurrency` | integer | No | 1 | Concurrent processing count |
| `--retry` | integer | No | 0 | Number of retries on failure |

### `adp extract base64 <base64-strings>`

Extract from base64-encoded document content.

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--app-id` | string | **Yes** | — | Application ID |
| `--async` | boolean | No | false | Enable asynchronous processing |
| `--no-wait` | boolean | No | false | Submit async task and return immediately |
| `--export` | string | No | — | Export results to specified path |
| `--timeout` | integer | No | 900 | Timeout in seconds |
| `--file-name` | string | No | "document" | Display name with extension for the base64 content (used to detect file type; does not read from disk) |
| `--concurrency` | integer | No | 1 | Concurrent processing count |
| `--retry` | integer | No | 0 | Number of retries on failure |

### `adp extract query <task-ids...>`

Query async extract task status and results. Supports multiple task IDs.

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `--watch` | boolean | No | false | Continuously poll until task completes |
| `--file` | string | No | — | Read task IDs from a JSON file (produced by `--no-wait`) |
| `--export` | string | No | — | Export results to specified path |
| `--timeout` | integer | No | 900 | Watch mode timeout in seconds |
| `--concurrency` | integer | No | 1 | Concurrent query count |

---

## custom-app — Custom Extraction Application Management

### `adp custom-app create`

Create a custom extraction application.

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `--api-key` | string | No | Override configured API Key |
| `--app-name` | string | **Yes** | Application name |
| `--app-label` | string | No | Application labels (up to 5) |
| `--extract-fields` | string (JSON) | **Yes** | Field definitions in JSON format |
| `--parse-mode` | string | **Yes** | Parsing mode: `advance`, `standard`, or `agentic` |
| `--enable-long-doc` | string | **Yes** | Enable long document processing (`true`/`false`) |
| `--long-doc-config` | string (JSON) | No | Long document type configuration (only applied when `--enable-long-doc true`) |

### `adp custom-app update`

Update an existing custom extraction application.

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `--api-key` | string | No | Override configured API Key |
| `--app-id` | string | **Yes** | Application ID to update |
| `--app-name` | string | No | New application name |
| `--app-label` | string | No | New application labels |
| `--extract-fields` | string (JSON) | **Yes** | Updated field definitions |
| `--parse-mode` | string | **Yes** | Parsing mode: `advance`, `standard`, or `agentic` |
| `--enable-long-doc` | string | No | Enable long document processing (`true`/`false`); if omitted, server default behavior is preserved |
| `--long-doc-config` | string (JSON) | No | Long document type configuration (only applied when `--enable-long-doc true`) |

### `adp custom-app get-config`

View custom application configuration.

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `--api-key` | string | No | Override configured API Key |
| `--app-id` | string | **Yes** | Application ID |
| `--config-version` | string | No | Configuration version (e.g., `v1`) |

### `adp custom-app delete`

Delete a custom application.

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `--api-key` | string | No | Override configured API Key |
| `--app-id` | string | **Yes** | Application ID to delete |

### `adp custom-app delete-version`

Delete a specific version of a custom application.

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `--api-key` | string | No | Override configured API Key |
| `--app-id` | string | **Yes** | Application ID |
| `--config-version` | string | **Yes** | Version to delete (e.g., `v2`) |

### `adp custom-app ai-generate`

AI-powered field recommendation based on a sample document.

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `--api-key` | string | No | Override configured API Key |
| `--app-id` | string | **Yes** | Application ID |
| `--file-url` | string | No | Sample document URL |
| `--file-local` | string | No | Sample document local path |
| `--base64` | string | No | Sample document base64 content |

> Note: Provide exactly one of `--file-url`, `--file-local`, or `--base64`.

---

## schema — Machine-Readable Command Spec

### `adp schema`

Output the complete command schema in JSON format. Designed for Agent introspection — Agent can call this command at startup to dynamically discover all available commands, parameters, types, and defaults.

---

## help — Help

### `adp --help`

View the complete list of commands and usage instructions.

---

## ADP Error Codes

See [error-handling.md](error-handling.md) for the complete error code reference and Agent recovery strategies.


path: references/error-handling.md
content: # ADP CLI Error Handling Guide for Agent

> This document defines all error types, exit codes, and recommended Agent recovery strategies.

## Error Output Format

Errors are output to **stderr**. In JSON mode (`--json` or non-TTY), the format is:

```json
{
  "type": "ERROR_TYPE",
  "message": "Human-readable error description",
  "fix": "Suggested fix action",
  "retryable": true,
  "details": {"context": "command_name"}
}
```

Key field for Agent: **`retryable`** — if `true`, the Agent should retry with exponential backoff.

---

## Error Types and Agent Recovery Strategies

### AUTH_ERROR (Exit Code: 4)

**Triggers:** Invalid API Key, expired API Key, authentication failed, 401/403 HTTP status.

**Agent strategy:**
1. Run `adp config get` to check if API Key is configured
2. If not configured → prompt user to provide API Key
3. If configured but invalid → prompt user to verify/update API Key
4. Do NOT retry automatically — authentication errors are not transient

### PARAM_ERROR (Exit Code: 2)

**Triggers:** Invalid JSON format, unsupported file type, invalid parameter value, missing required parameter.

**Agent strategy:**
1. Read the `message` field to identify which parameter is wrong
2. Fix the parameter and retry
3. Common fixes:
   - JSON parse error → validate JSON syntax in `--extract-fields` or `--long-doc-config`
   - Unsupported file type → check file extension is one of: .jpg, .jpeg, .png, .bmp, .tiff, .tif, .pdf, .doc, .docx, .xls, .xlsx
   - Invalid enum value → check `--parse-mode` is one of: `advance`, `standard`, `agentic`

### RESOURCE_ERROR (Exit Code: 3)

**Triggers:** app-id not found, file not found, task not found, version not found, 404 HTTP status.

**Agent strategy:**
1. If app-id not found → run `adp app-id list` to refresh, then retry with correct app-id
2. If local file not found → verify file path exists
3. If task not found → the task_id may be incorrect or expired
4. Do NOT retry with same parameters

### NETWORK_ERROR (Exit Code: 1)

**Triggers:** Connection refused, DNS lookup failure, timeout, TLS handshake error.

**Agent strategy:**
1. This is retryable — retry with exponential backoff (2s, 4s, 8s)
2. Max 3 retries
3. If still failing → check network connectivity, verify `--api-base-url` is correct
4. Consider using `--timeout` with a larger value for slow networks

### API_ERROR (Exit Code: 1)

**Triggers:** Rate limiting (429), server error (5xx), generic API failures.

**Agent strategy:**
1. If 429 (rate limited) → wait 30 seconds, then retry
2. If 5xx → retry with exponential backoff, max 3 attempts
3. If persistent → suggest user contact support ([REDACTED_SECRET])

### CONFLICT_ERROR (Exit Code: 5)

**Triggers:** Resource already exists, duplicate app name.

**Agent strategy:**
1. If creating custom-app with duplicate name → use a different `--app-name`
2. If updating → check current state with `custom-app get-config` first
3. Do NOT retry with same parameters

### SYSTEM_ERROR (Exit Code: 1)

**Triggers:** Unexpected internal errors.

**Agent strategy:**
1. Log the error message for diagnostics
2. Do NOT retry — these are typically programming errors or unexpected states
3. Suggest user report the issue

---

## Exit Codes Quick Reference

| Code | Name | Retryable | Agent Action |
|------|------|-----------|--------------|
| 0 | Success | — | Proceed normally |
| 1 | General Error | Depends on type | Check `retryable` field in error JSON |
| 2 | Parameter Error | No | Fix parameter and retry |
| 3 | Resource Not Found | No | Verify resource ID/path |
| 4 | Permission Denied | No | Prompt user for credentials |
| 5 | Conflict | No | Change conflicting parameter |
| 6 | Partial Failure | — | Check batch summary for per-file status |

---

## Batch Processing Error Handling

Exit code `6` (Partial Failure) means some files succeeded and some failed in a batch.

**Agent strategy:**
1. Parse the stdout summary JSON
2. For files with `"status": "failed"`, read the `error` field
3. Decide per-file: retry failed files individually, or report to user
4. Use `--retry N` flag to enable automatic retry with exponential backoff at CLI level

---

## Credit-Related Errors

When credit balance is insufficient, the API returns a specific error. Agent should:
1. Run `adp credit` to check remaining balance
2. Report the balance to user
3. Provide billing reference:
   - Document parsing: 0.5 credits/page
   - Invoice/receipt extraction: 1.5 credits/page
   - Order extraction: 1.5 credits/page
   - Custom extraction: 1 credit/page

---

## Timeout Handling

Default timeout is 900 seconds (15 minutes). For large documents or slow networks:

**Agent strategy:**
1. If timeout occurs on sync processing → retry with `--async` mode
2. For files >20MB or >200 pages → always use `--async`
3. Increase timeout with `--timeout 1800` if needed


path: references/examples.md
content: # ADP CLI Sample code and response

## 1. Install ADP CLI

First check if ADP CLI is already installed by running `adp version`. If it succeeds, skip to step 2.

If not installed, choose the appropriate method:

```bash
# Method 1: npm (recommended, works on all platforms, China-friendly with npmmirror)
npm install -g @laiye-adp/agentic-doc-parse-and-extract-cli --registry=https://registry.npmmirror.com/ || npm install -g @laiye-adp/agentic-doc-parse-and-extract-cli

# Method 2: Shell script (Linux / macOS, if npm is not available)
curl -fsSL https://raw.githubusercontent.com/laiye-ai/adp-cli/main/scripts/adp-init.sh | bash

# Method 3: PowerShell script (Windows, if npm is not available)
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/laiye-ai/adp-cli/main/scripts/adp-init.ps1" -OutFile "$env:TEMP\adp-init.ps1"; & "$env:TEMP\adp-init.ps1"
```

### Resolving `adp` when it's not on PATH (important for Agents)

After `npm install -g`, the npm global bin directory is often **not** on the current shell's `PATH`, so a bare `adp` call will fail with "command not found". Agents must resolve the absolute path to the `adp` binary instead of relying on `PATH`.

**Resolution rule:**
- **Windows**: `npm prefix -g` returns the directory that already contains `adp.cmd` / `adp.exe`. Use `<prefix>\adp.cmd`.
- **Linux / macOS**: `npm prefix -g` returns the prefix; the binary lives at `<prefix>/bin/adp`.

**Cross-platform one-liner to locate the binary:**

```bash
# Linux / macOS (bash/zsh)
ADP_BIN="$(npm prefix -g)/bin/adp"
"$ADP_BIN" version
```

```powershell
# Windows (PowerShell)
$ADP_BIN = Join-Path (npm prefix -g) "adp.cmd"
& $ADP_BIN version
```

```bash
# Windows (Git Bash / MSYS in Claude Code)
ADP_BIN="$(npm prefix -g)/adp.cmd"
"$ADP_BIN" version
```

**Optional**: prepend the directory to PATH for the current shell session only (does not persist):
```bash
# bash/zsh
export PATH="$(dirname "$ADP_BIN"):$PATH"
```
```powershell
# PowerShell
$env:PATH = "$(Split-Path $ADP_BIN);$env:PATH"
```

### Agent installation logic

1. Run `adp version` — if it succeeds, CLI is already installed and on PATH, skip installation and use bare `adp` for all subsequent commands.
2. If not installed, check if `npm` is available → use Method 1. Else detect OS: Linux / macOS → Method 2; Windows → Method 3.
3. **After install, do NOT assume `adp` is on PATH.** Resolve `ADP_BIN`:
   - **Method 1 (npm)**: use the platform rule above (`npm prefix -g` ± `/bin`).
   - **Method 2 / 3 (shell scripts)**: parse the last line of script output — it prints `ADP_INSTALL_PATH=<absolute path>` for this exact purpose.
4. Verify with `"$ADP_BIN" version` (or `& $ADP_BIN version` in PowerShell). If it succeeds, install is good.
5. For all subsequent `adp ...` examples in this document, substitute the bare `adp` with `"$ADP_BIN"` (or your resolved absolute path) until the user opens a new terminal where PATH is refreshed.

## 2. Configure API Key and Base URL

### Verify configuration

```bash
adp config get
```

**Response example**：
```json
{
  "configured": true,
  "api_key_masked": "9ce0...ab4f",
  "api_base_url": "https://adp.laiye.com/"
}
```
### configuration
```bash
# Configure API Key
adp config set --api-key YOUR_API_KEY

# Configure Base URL
adp config set --api-base-url https://your-api-url.com
```


## 3. Query the list of available applications

```bash
# List available applications
adp app-id list 

# Show cached applications（The application ID cache is permanent and will not expire）
adp app-id cache 
```


**Response example**：
```json
  [
    {
      "app_id": "2f74******58400",
      "app_label": null,
      "app_name": "Custom Application Name",
      "app_type": 1
    },
   {
      "app_id": "ootb_******c8d1",
      "app_label": [
        "invoice",
        "Receipt",
        "Bill",
        "Financial document",
        "Information extraction"
      ],
      "app_name": "Invoice",
      "app_type": 0
    },
   {
      "app_id": "ootb_******a2b5",
      "app_label": [
        "Order",
        "E-commerce logistics",
        "Inventory management",
        "Information extraction"
      ],
      "app_name": "Purchase Order",
      "app_type": 0
    },
    {
      "app_id": "ootb_******y2b4",
      "app_label": [
        "Document parsing",
        "Image extraction",
        "OCR",
        "Structural analysis",
        "Batch Parsing"
      ],
      "app_name": "Document parsing",
      "app_type": 0
    },
  ]
```

## 4. Create a custom extraction application

```bash
# First, use AI to generate field recommendations
adp custom-app ai-generate --app-id YOUR_APP_ID --file-url https://example.com/sample-invoice.pdf

# Second, Create a custom application
adp custom-app create \
  --api-key "9ce0********4b4f" \
  --app-name "Financial document extraction" \
  --extract-fields '[
    {"field_name":"Invoice number","field_type":"string","field_prompt":"Extract the serial number at the top left corner of the invoice"},
    {"field_name":"Invoice date","field_type":"date","field_prompt":"Extract the invoice issuance date"},
    {"field_name":"Product details","field_type":"table","field_prompt": null,"sub_fields": 
    [
      {"field_name":"Contract Number","field_type":"string","field_prompt":"Extract the contract number"},
      {"field_name":"Signing Date","field_type": "date","field_prompt":"Extract the signing date"}
    ]
    }
  ]' \
  --parse-mode "standard" \
  --enable-long-doc true \
  --long-doc-config '[
    {"doc_type":"Contract","doc_desc":"Multi-page contract"},
    {"doc_type":"Tender document","doc_desc":"Engineering tender documents"}
  ]'
```

**Response example**：
```json
{
  "code": "success",
  "message": "",
  "tips": null,
  "data": {
    "app_id": "ed5195882cd311f19359627c0509427d",
    "app_name": "Custom Application Name",
    "app_label": ["Custom Label 1", "Custom Label 2"] , "config_version": "v1"
  }
}
```

## 5. Document Parsing

```bash
adp parse url <File URL> --app-id YOUR_APP_ID
```

**Response example**：
```json
{
  "data": {
    "task_id": "",
    "file_url": "",
    "status": 4,
    "message": "",
    "doc_recognize_result": [
      {
        "page_num": 1,
        "document_content": "Electronic invoice\n\nTax Bureau\n\nInvoice code: 144032009110\n\nInvoice number: 23700770\n\ndate: 2020-12-13",
        "document_details": [
          {
            "type": "Text",
            "text": "Incoice",
            "position": [
              {
                "points": [
                  {"x": 311, "y": 50},
                  {"x": 369, "y": 50},
                  {"x": 369, "y": 59},
                  {"x": 311, "y": 59}
                ]
              }
            ],
            "ocr_confidence": {
              "ocr_mean_confidence": 0.9989976211580984,
              "ocr_min_confidence": 0.9989976211580984,
              "is_overall_confidence": 1
            }
          },
          {
            "type": "Text",
            "text": "invoice number: 23700770",
            "position": [
              {
                "points": [
                  {"x": 493, "y": 32},
                  {"x": 573, "y": 32},
                  {"x": 573, "y": 42},
                  {"x": 493, "y": 42}
                ]
              }
            ],
            "ocr_confidence": {
              "ocr_mean_confidence": 0.9999735751246535,
              "ocr_min_confidence": 0.9997363785557283,
              "is_overall_confidence": 1
            }
          },
          {
            "type": "Text",
            "text": "Date: 2020-12-13",
            "position": [
              {
                "points": [
                  {"x": 493, "y": 50},
                  {"x": 623, "y": 50},
                  {"x": 623, "y": 60},
                  {"x": 493, "y": 60}
                ]
              }
            ],
            "ocr_confidence": {
              "ocr_mean_confidence": 0.9999853806227165,
              "ocr_min_confidence": 0.9998685294404747,
              "is_overall_confidence": 1
            }
          },
          {
            "type": "Picture",
            "text": "https://adp.laiye.com/web/agentic_doc_processor/laiye/file/e4b140162cd511f19d1c627c0509427d",
            "position": [
              {
                "points": [
                  {"x": 541, "y": 329},
                  {"x": 666, "y": 329},
                  {"x": 666, "y": 428},
                  {"x": 541, "y": 428}
                ]
              }
            ],
            "ocr_confidence": {
              "ocr_mean_confidence": 0.9506070037576528,
              "ocr_min_confidence": 0.07206936378157035,
              "is_overall_confidence": 0
            }
          }
        ]
      }
    ]
  },
  "code": "success",
  "message": "",
  "tips": null
}
```

## 6. Document extraction

```bash
adp extract url <file URL> --app-id YOUR_APP_ID
```

**Response example**：
```json
[
  {
    "field_key": "invoice_number",
    "field_name": "invoice number",
    "field_values": [
      {
        "field_value": "24VLT0591617",
        "field_confidence": 1.0,
        "references": []
      }
    ]
  },
  {
    "field_key": "invoice_date",
    "field_name": "date",
    "field_values": [
      {
        "field_value": "2024-11-01",
        "field_confidence": 1.0,
        "references": []
      }
    ]
  },
  {
    "field_key": "currency",
    "field_name": "Currency type",
    "field_values": [
      {
        "field_value": "EUR",
        "field_confidence": 0.0,
        "references": []
      }
    ]
  },
  {
    "field_key": "total_without_tax",
    "field_name": "Total amount (excluding tax)",
    "field_values": [
      {
        "field_value": "€ 1.223,43",
        "field_confidence": 1.0,
        "references": []
      }
    ]
  },
  {
    "field_key": "line_items",
    "field_name": "Product Details Table",
    "references": [],
    "field_confidence": 1.0,
    "table_values": [
      [
        {
          "field_name": "Project code",
          "field_values": [
            {
              "field_value": "241021 SI0421.00",
              "field_confidence": 1.0,
              "references": "Project code: 241021 SI0421.00"
            }
          ],
          "field_key": "line_items_item_code"
        },
        {
          "field_name": "Description",
          "field_values": [
            {
              "field_value": "TESLA MODEL 3 BEV LONG-RANGE DUAL MOTOR AWD",
              "field_confidence": 1.0,
              "references": "Description: TESLA MODEL 3 BEV LONG-RANGE DUAL MOTOR AWD"
            }
          ],
          "field_key": "line_items_description"
        },
        {
          "field_name": "number",
          "field_values": [
            {
              "field_value": "1",
              "field_confidence": 1.0,
              "references": "number: 1"
            }
          ],
          "field_key": "line_items_quantity"
        },
        {
          "field_name": "Unit price",
          "field_values": [
            {
              "field_value": "€ 1.223,43",
              "field_confidence": 1.0,
              "references": "Unit price: € 1.223,43"
            }
          ],
          "field_key": "line_items_unit_price"
        },
        {
          "field_name": "Total amount",
          "field_values": [
            {
              "field_value": "€ 1.223,43",
              "field_confidence": 1.0,
              "references": "Total amount: € 1.223,43"
            }
          ],
          "field_key": "line_items_total_amount"
        }
      ]
    ]
  }
]
```

## 7. Batch Processing 
```bash
# Batch processing of documents in the local folder
adp parse local <folder path> --app-id <app_ID> --export <folder path> --concurrency 2
adp extract local <folder path> --app-id <app_ID> --export <folder path> --concurrency 2 

# Batch processing of documents within the URL list file
adp parse url <URL list file path> --app-id <app_ID> --export <folder path> --concurrency 2
adp extract url <URL list file path> --app-id <app_ID> --export <folder path> --concurrency 2
```

**Note**: Batch processing requires processing all the files in the folder sequentially, and the output result supports being specified to be saved in the user-defined folder path.

## 8. Asynchronous Processing 
```bash
# Batch processing of documents in the local folder
adp parse local <file path> --app-id <app_ID> --export <folder path> --concurrency 2 --async
adp extract local <file path> --app-id <app_ID> --export <folder path> --concurrency 2 --async 

# Batch processing of documents within the URL list file
adp parse url <file URL> --app-id <app_ID> --export <folder path> --concurrency 2 --async
adp extract url <file URL> --app-id <app_ID> --export <folder path> --concurrency 2 --async 

# Query the status and results of asynchronous parsing processing tasks 
adp parse query <task_id>

# Query the status and results of asynchronous extraction processing tasks 
adp extract query <task_id>
```


**Query Response example**：
```json
{
  "Task_ID": "dffe****427d",
  "Status": "SUCCESS"
}
```

## 9. Batch Processing Output

When processing multiple files, the CLI creates an output directory and writes individual result files.

### Sync batch output

```bash
adp extract local ./invoices/ --app-id YOUR_APP_ID --export ./results --concurrency 2
```

**stdout output (summary JSON):**
```json
{
  "total": 3,
  "success": 2,
  "failed": 1,
  "output_dir": "/home/user/results",
  "files": [
    {"input": "invoice1.pdf", "output": "invoice1.pdf.json", "status": "success"},
    {"input": "invoice2.pdf", "output": "invoice2.pdf.json", "status": "success"},
    {"input": "corrupted.pdf", "output": "corrupted.pdf.error.json", "status": "failed", "error": "Bad request: unsupported file format"}
  ]
}
```

**Output directory structure:**
```
results/
  ├── invoice1.pdf.json          # Full extract result (same format as single-file response)
  ├── invoice2.pdf.json
  ├── corrupted.pdf.error.json   # {"input": "corrupted.pdf", "status": "failed", "error": "..."}
  └── _summary.json              # Same content as stdout summary
```

**Agent must:** Read `output_dir` from summary, then read each `{output_dir}/{filename}.json` to get individual results.

### Async batch with --no-wait

```bash
adp extract local ./invoices/ --app-id YOUR_APP_ID --async --no-wait --export tasks.json
```

**Output (tasks.json):**
```json
[
  {"path": "invoice1.pdf", "task_id": "abc123def456"},
  {"path": "invoice2.pdf", "task_id": "ghi789jkl012"}
]
```

**Later, query all tasks:**
```bash
adp extract query --file tasks.json --watch --export ./results
```

---

## 10. Error Scenario Examples

### Authentication error (API Key not configured)

```bash
adp extract url https://example.com/invoice.pdf --app-id YOUR_APP_ID --json
```

**stderr output:**
```json
{
  "type": "AUTH_ERROR",
  "message": "Authentication error: unauthorized",
  "fix": "Check your API key is correct and has not expired.",
  "retryable": false,
  "details": {"context": "extract"}
}
```
**Exit code:** 4

**Agent recovery:** Run `adp config get` to check, then prompt user for API Key.

### Credit balance insufficient

```bash
adp credit --json
```

```json
{
  "credit_balance": 0.0
}
```

**Agent recovery:** Report balance to user. Billing: parse 0.5/page, extract 1-1.5/page.

### Invalid app-id

```bash
adp extract url https://example.com/invoice.pdf --app-id invalid_id --json
```

**stderr output:**
```json
{
  "type": "RESOURCE_ERROR",
  "message": "Resource not found: app not found",
  "fix": "Check the resource ID or path is correct.",
  "retryable": false,
  "details": {"context": "extract"}
}
```
**Exit code:** 3

**Agent recovery:** Run `adp app-id list` to get valid app IDs.

### Unsupported file format

```bash
adp parse local ./readme.txt --app-id YOUR_APP_ID --json
```

**stderr output:**
```json
{
  "type": "PARAM_ERROR",
  "message": "Parameter error: unsupported file type",
  "fix": "Check the input parameters are correct.",
  "retryable": false,
  "details": {"context": "parse"}
}
```
**Exit code:** 2

**Agent recovery:** Check file extension. Supported: .jpg, .jpeg, .png, .bmp, .tiff, .tif, .pdf, .doc, .docx, .xls, .xlsx

### Network timeout

```bash
adp parse url https://example.com/large-doc.pdf --app-id YOUR_APP_ID --json
```

**stderr output:**
```json
{
  "type": "NETWORK_ERROR",
  "message": "Network error: i/o timeout",
  "fix": "Check your network connection and try again.",
  "retryable": true,
  "details": {"context": "parse"}
}
```
**Exit code:** 1

**Agent recovery:** Retry with `--timeout 1800`, or switch to `--async` mode for large files.

### Async task not yet complete

```bash
adp parse query abc123def456 --json
```

```json
{
  "task_id": "abc123def456",
  "status": "PROCESSING"
}
```

**Agent recovery:** Wait and query again. Use `--watch` flag to auto-poll until completion.

### Batch partial failure

```bash
adp extract local ./mixed_docs/ --app-id YOUR_APP_ID --export ./results --json
```

**Exit code:** 6 (partial failure)

**Agent recovery:** Parse the summary JSON, handle successful files normally, report or retry failed files individually.

---

## Description of Response Fields 

### Document Extraction Response Key Fields
- `field_name`: The name of the extracted field. If it contains "table_values", it indicates that this is a table field and the `field_name` is usually the name of the table; if it does not contain "table_values", it indicates an ordinary field and the `field_name` is usually the description of the field
- `field_value`: The specific value of the extraction result
- `field_confidence`: The confidence score of the extraction result, ranging from 0 to 1. The higher the value, the more reliable the extraction result
- `table_values`: The extraction result of the table type, presented in a two-dimensional array format, including the extraction result of each cell and the corresponding field name, confidence level, etc. The array under it usually contains the contents of `field_name`, `field_value`, `field_confidence`, etc. 

## Custom Application Parameter Description 

### parse_mode (Parsing Mode)
There are 3 modes available for selection:
1. `advance`: Enhanced parsing, suitable for documents with complex formats such as seals, signatures, and multi-tables
2. `standard`: Standard parsing, suitable for standard and clear electronic documents
3. `agentic`: Intelligent parsing, intelligently combining multiple models for parsing, significantly improving the stability of parsing for complex documents 

### Other Parameters
- `app_label`: Up to 5 can be added
- `enable-long-doc`: Default is off (false). It can be enabled (true) when dealing with long documents. It precisely extracts fields within the specified document type and uses independent billing (0.5 credit per page). It is usually enabled when the document has more than 20 pages and has multiple types. When enabled, it needs to be used in conjunction with `doc_type` and `doc_desc`.


path: references/response-schema.md
content: # ADP CLI Response Schema Reference

> This document defines the output structure of each command so that Agent can reliably parse results.

## Output Modes

The CLI has two output modes controlled by `--json` flag:
- **Human-readable** (default in TTY): colored text with formatting
- **JSON mode** (`--json` or non-TTY/pipe): structured JSON to stdout, errors to stderr

**Agent should always use `--json` flag** or pipe output to ensure machine-readable JSON.

---

## config get

```json
{
  "configured": true,
  "api_key_masked": "9ce0...ab4f",
  "api_base_url": "https://adp.laiye.com/"
}
```

| Field | Type | Description |
|-------|------|-------------|
| `configured` | boolean | Whether API Key is configured |
| `api_key_masked` | string | Masked API Key (first 4 + last 4 chars) |
| `api_base_url` | string | Current API Base URL |

---

## app-id list

```json
[
  {
    "app_id": "61ac******bd21",
    "app_name": "Overseas Invoices/Receipts",
    "app_label": ["Invoice", "Receipt", "Bill"],
    "app_type": 1
  }
]
```

| Field | Type | Description |
|-------|------|-------------|
| `app_id` | string | Application ID (use this for `--app-id`) |
| `app_name` | string | Application display name |
| `app_label` | string[] | Labels for matching user intent |
| `app_type` | int | 0:Out-of-the-box application(Pre-set);1:Custom application|

---

## credit

```json
{
  "credit_balance": 95.5
}
```

---

## parse (single file, sync)

Top-level response:

```json
{
  "code": "success",
  "message": "",
  "tips": null,
  "data": {
    "task_id": "",
    "file_url": "",
    "status": 4,
    "message": "",
    "doc_recognize_result": [...]
  }
}
```

### doc_recognize_result item

```json
{
  "page_num": 1,
  "document_content": "Full text content of this page...",
  "document_details": [
    {
      "type": "Text | Picture | Table",
      "text": "content or image URL",
      "position": [{"points": [{"x": 311, "y": 50}, ...]}],
      "ocr_confidence": {
        "ocr_mean_confidence": 0.999,
        "ocr_min_confidence": 0.998,
        "is_overall_confidence": 1
      }
    }
  ]
}
```

| Field | Type | Description |
|-------|------|-------------|
| `page_num` | integer | Page number (1-indexed) |
| `document_content` | string | Full text of the page in reading order |
| `document_details` | array | Element-level details with position and confidence |
| `document_details[].type` | string | Element type: `Text`, `Picture`, or `Table` |
| `document_details[].text` | string | Text content, or image URL for Picture type |
| `document_details[].position` | array | Bounding box coordinates (4 corner points) |
| `document_details[].ocr_confidence.ocr_mean_confidence` | float | Average OCR confidence (0-1) |
| `document_details[].ocr_confidence.ocr_min_confidence` | float | Minimum OCR confidence (0-1) |

---

## extract (single file, sync)

Returns an array of extracted fields:

```json
[
  {
    "field_key": "invoice_number",
    "field_name": "Invoice Number",
    "field_values": [
      {
        "field_value": "24VLT0591617",
        "field_confidence": 1.0,
        "references": []
      }
    ]
  },
  {
    "field_key": "line_items",
    "field_name": "Product Details Table",
    "references": [],
    "field_confidence": 1.0,
    "table_values": [
      [
        {
          "field_name": "Description",
          "field_key": "line_items_description",
          "field_values": [
            {
              "field_value": "TESLA MODEL 3",
              "field_confidence": 1.0,
              "references": "Description: TESLA MODEL 3"
            }
          ]
        }
      ]
    ]
  }
]
```

### Field types

**Regular field** (no `table_values`):

| Field | Type | Description |
|-------|------|-------------|
| `field_key` | string | Machine-readable field identifier |
| `field_name` | string | Human-readable field name |
| `field_values` | array | Extracted values |
| `field_values[].field_value` | string | The extracted value |
| `field_values[].field_confidence` | float | Confidence score (0-1) |

**Table field** (has `table_values`):

| Field | Type | Description |
|-------|------|-------------|
| `field_key` | string | Table identifier (e.g., `line_items`) |
| `field_name` | string | Table name |
| `table_values` | array[array] | 2D array: rows of cells, each cell has `field_name`, `field_key`, `field_values` |

### How to distinguish field types

- If the field object contains `table_values` → it is a table field, read from `table_values`
- If the field object contains `field_values` without `table_values` → it is a regular field

---

## Async task submission (--async)

When using `--async` without `--no-wait`, the CLI polls until completion and returns the same response as sync mode.

When using `--async --no-wait`, the CLI returns immediately:

```json
{
  "task_id": "dffe****427d",
  "status": "PROCESSING"
}
```

---

## Async query (parse query / extract query)

```json
{
  "task_id": "dffe****427d",
  "status": "SUCCESS"
}
```

| Status | Meaning |
|--------|---------|
| `SUCCESS` | Task completed, result data included |
| `PROCESSING` | Still processing, query again later |
| `FAILED` | Task failed |

When status is `SUCCESS`, the full parse/extract result is included in the response.

---

## Batch Processing Output

### Sync batch (multiple files)

**stdout** outputs a summary JSON:

```json
{
  "total": 5,
  "success": 4,
  "failed": 1,
  "output_dir": "/absolute/path/to/adp_results_20260417_143025",
  "files": [
    {"input": "invoice1.pdf", "output": "invoice1.pdf.json", "status": "success"},
    {"input": "invoice2.pdf", "output": "invoice2.pdf.json", "status": "success"},
    {"input": "bad.pdf", "output": "bad.pdf.error.json", "status": "failed", "error": "..."}
  ]
}
```

| Field | Type | Description |
|-------|------|-------------|
| `total` | integer | Total number of files processed |
| `success` | integer | Number of successful files |
| `failed` | integer | Number of failed files |
| `output_dir` | string | **Absolute path** to the output directory — Agent must read files from here |
| `files` | array | Per-file status and output filename |
| `files[].input` | string | Original input filename |
| `files[].output` | string | Output filename in `output_dir` |
| `files[].status` | string | `success` or `failed` |
| `files[].error` | string | Error message (only when failed) |

### Output directory structure

```
adp_results_20260417_143025/     (or --export specified path)
  ├── invoice1.pdf.json          # Successful result (same schema as single-file response)
  ├── invoice2.pdf.json
  ├── bad.pdf.error.json         # Failed result: {"input": "...", "status": "failed", "error": "..."}
  └── _summary.json              # Same content as stdout summary
```

**Agent workflow for batch results:**
1. Parse the stdout summary JSON
2. Read `output_dir` path from summary
3. For each file in `files` array where `status` is `success`:
   - Read `{output_dir}/{files[].output}` to get the individual result
   - The JSON structure inside each file is identical to the single-file parse/extract response
4. For failed files, the error reason is in both the summary and the `.error.json` file

### Default output directory

- If `--export` is specified: uses that path
- If `--export` is not specified: auto-creates `adp_results_{YYYYMMDD_HHMMSS}/` in current directory

### Async batch (--async --no-wait)

Returns a JSON array of task IDs:

```json
[
  {"path": "invoice1.pdf", "task_id": "abc123"},
  {"path": "invoice2.pdf", "task_id": "def456"},
  {"path": "bad.pdf", "error": "file too large"}
]
```

**Agent workflow for async batch:**
1. Save the output to a file (using `--export tasks.json`)
2. Later, query all tasks: `adp parse query --file tasks.json --watch`
3. The `--file` flag reads the JSON array and queries all task IDs

---

## custom-app create

```json
{
  "code": "success",
  "message": "",
  "tips": null,
  "data": {
    "app_id": "ed5195882cd311f19359627c0509427d",
    "app_name": "Custom Application Name",
    "app_label": ["Custom Label 1"],
    "config_version": "v1"
  }
}
```

---

## custom-app ai-generate

Returns AI-recommended extraction fields based on the sample document. The Agent can use these recommendations to populate `--extract-fields` when calling `custom-app create`.

---

## Error Response Format

When `--json` flag is used, errors are output to **stderr** as:

```json
{
  "type": "AUTH_ERROR",
  "message": "Authentication error: invalid API key",
  "fix": "Check your API key is correct and has not expired.",
  "retryable": false,
  "details": {"context": "extract"}
}
```

See [error-handling.md](error-handling.md) for the complete error type reference.

---

## Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General error |
| 2 | Parameter error |
| 3 | Resource not found |
| 4 | Permission denied |
| 5 | Conflict |
| 6 | Partial failure (batch: some succeeded, some failed) |


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)