Communitygithub.com

camscanner-ai/camscanner

The CamScanner CLI Skill provides a complete document processing toolkit through the `camscanner-cli` command-line tool and the CamScanner AI Tools API. It supports image enhancement, OCR, format conversion, watermarking, translation, restoration, merging, and related operations. Results can also be saved to the user's CamScanner account.

camscanner 是什么?

camscanner is a Claude Code agent skill that the CamScanner CLI Skill provides a complete document processing toolkit through the `camscanner-cli` command-line tool and the CamScanner AI Tools API. It supports image enhancement, OCR, format conversion, watermarking, translation, restoration, merging, and related operations. Results can also be saved to the user's CamScanner account.

兼容平台Claude Code~Codex CLI~Cursor
npx skills add camscanner-ai/camscanner

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

CamScanner CLI Skill Guide

The CamScanner CLI Skill provides a complete document processing toolkit through the camscanner-cli command-line tool and the CamScanner AI Tools API. It supports image enhancement, OCR, format conversion, watermarking, translation, restoration, merging, receipt recognition, and other image/PDF processing operations, as well as cloud document search.

Environment Setup

Before using this Skill for the first time in a session, the agent must complete the following decision flow. This only needs to run once per session.

The agent must strictly follow this flow — skipping any step is prohibited:

Step 1: camscanner-cli --version
         │
         ├─ Command exists (outputs version) → Step 2
         │
         └─ Command not found → [Windows?] Double-check with Test-Path ↓
                          │
                          ├─ Test-Path "$env:LOCALAPPDATA\camscanner-cli\camscanner-cli.exe" = True
                          │   → Refresh PATH → Step 2 (no install needed)
                          │
                          └─ False / Non-Windows → Run install script → Step 3 (skip upgrade)

Step 2: Run upgrade script
         │
         └─ Done → Step 3

Step 3: camscanner-cli auth status
         │
         ├─ Logged in → ✅ Environment ready, proceed with user task
         │
         └─ Not logged in / expired → Run camscanner-cli auth login → Verify → ✅

Step 1. Check Installation

Run camscanner-cli --version:

  • Command exists (outputs version) → Already installed, continue to Step 2
  • Command not found (command not found / not recognized) → On Windows, you must perform the double-check below first. If confirmed not installed, run the install script. After installation, skip directly to Step 3.

Windows double-check (mandatory):

camscanner-cli --version failing on Windows does not necessarily mean it is not installed — the PATH may not be refreshed or ConPTY may swallow output. Before running the install script, check whether the file exists:

Test-Path "$env:LOCALAPPDATA\camscanner-cli\camscanner-cli.exe"
  • Returns True → CLI is installed, just missing from PATH. Refresh PATH then continue to Step 2:
    $env:PATH = "$env:LOCALAPPDATA\camscanner-cli;$env:PATH"
    
  • Returns False → Confirmed not installed, run the install script → Step 3
PlatformInstall Command
Linux/macOSbash scripts/setup.sh
Windowspowershell -ExecutionPolicy Bypass -File scripts/setup.ps1

Step 2. Version Upgrade Check (installed users only)

Run the upgrade script to check for a new version (the script handles detection internally; exits silently if no update is available; network failures do not block usage):

PlatformUpgrade Command
Linux/macOSbash scripts/upgrade.sh
Windowsnode scripts/upgrade.cjs
Fallback (any platform)node scripts/upgrade.cjs

The upgrade script updates both the CLI binary and Skill files (SKILL.md, references/, scripts/) to keep them in sync. On failure it auto-rolls back; manual rollback: bash scripts/upgrade.sh --rollback or node scripts/upgrade.cjs --rollback.

Step 3. Authentication Check

camscanner-cli auth status
  • Logged in → Environment ready, proceed with user task
  • Not logged in or token expired → Run camscanner-cli auth login, then verify again

Agent login behavior rules (mandatory):

  • Must run camscanner-cli auth login in the foreground (no & backgrounding). The command blocks until the user completes browser OAuth and returns automatically.
  • After login, verify with camscanner-cli auth status; on failure, inform the user to retry.
ActionCommand
Check statuscamscanner-cli auth status
Browser logincamscanner-cli auth login
Log outcamscanner-cli auth logout

Token safety: Never display token plaintext to the user or write it to an unsafe location.


Operating Limits

  1. Do not leak credentials: Tokens must only be obtained through camscanner-cli auth login and stored in the system keychain.
  2. File size limit: Uploaded files must not exceed 40 MB.
  3. Supported image formats: JPG, JPEG, PNG.
  4. Supported document formats: PDF, TXT, Markdown.

Command Format

camscanner-cli <group> <command> [file...] [flags]

Groups: image (image processing), pdf (PDF processing), txt (text processing), doc (cloud document management), auth (authentication management).

Common flags:

FlagDescription
-o, --output <path>Output file path. If omitted, the CLI derives one automatically.
-s, --saveSave the result to the user's CamScanner account and skip local download.
--save-title <title>Cloud document title. If omitted, the CLI generates one in the form {feature}{time}.
-h, --helpShow help.

Interaction Between -o and -s

ArgumentsBehavior
No -o, no -sSave locally to an automatically derived path.
-o pathSave only to the specified local path.
-sSave only to the cloud and skip local download.
-o path -sSave both locally and to the cloud.

Agent Default Save Policy

Mandatory rule: When the user does not explicitly specify a save method, the agent must save both locally and to the cloud (pass the -s flag). Saving only locally without -s is incorrect behavior. Only omit -s when the user explicitly says "save locally only" / "don't save to cloud".

User IntentAgent Behavior
No explicit save preferenceMust use -s to save both locally and to cloud (i.e., -o <auto-derived path> -s)
Explicitly says "save locally" or specifies a pathOnly -o path, no -s
Explicitly says "save to cloud/account"Only -s, no -o
Feature does not support -s (see commands marked with No in the overview)Save locally only, no -s

--save-title Smart Naming Rules

When saving to cloud with -s, the agent must attempt smart naming via --save-title:

  1. Prefer smart naming: Generate a concise, meaningful title based on the filename, user intent, and document content.
    • Example: User says "convert this invoice to Excel" → --save-title "Invoice to Excel"
    • Example: File is meeting_notes_0810.png, converting to Word → --save-title "Meeting Notes 0810"
    • Example: Merging multiple scans into PDF → --save-title "Scanned Documents Merged"
  2. Fallback when naming fails: If a meaningful title cannot be inferred from context (e.g., filename has no semantics, user did not describe intent), do not pass --save-title — let the CLI use its default rule ({feature}{time}).
  3. Title requirements: Concise (20 chars or fewer), meaningful, no file paths or technical parameters.

Capabilities

Tool Overview

CategoryCommandFunctionOutput TypeSupports -s
Image enhancementimage enhanceRemove shadows, sharpen, convert to black and white, and other 10 modesImageYes
Image enhancementimage hdUpscale images and improve resolutionImageYes
Image enhancementimage restoreRestore old photosImageYes
Format conversionimage convertImage -> Word/Excel/TXT/MarkdownDocumentYes, except TXT
Format conversionimage to-pdfSingle image -> PDFPDFYes
Format conversionpdf convertPDF -> Word/Excel/TXT/MarkdownDocumentYes
Format conversiontxt to-wordTXT -> WordWordYes
Watermarkimage watermarkAdd a text watermark to an imageImageYes
Watermarkpdf watermarkAdd a text watermark to a PDFPDFYes
Watermarkpdf remove-watermarkRemove watermarks from a PDFPDFYes
Translationimage translateTranslate text in an image while preserving layoutImageYes
Formulaimage extract-formulaExtract mathematical formulasImageYes
Mergeimage merge-pdfMerge multiple images into a PDF, up to 100 imagesPDFYes
Mergeimage merge-excelMerge multiple images into Excel, up to 100 imagesExcelYes
Mergeimage merge-wordMerge multiple images into Word, up to 100 imagesWordYes
PDFpdf to-imagesConvert each PDF page to an imageImage directoryYes
PDFpdf to-images-zipConvert PDF pages to an image ZIPZIPNo
Recognitionimage ocrOCR text recognitionstdout textNo
Recognitionimage merge-textOCR multiple images and merge text, up to 100 imagesstdout/fileNo
Detectionimage validateTampering/AI-generated image detectionstdout JSONNo
Editingimage scanAnalyze image layout and obtain character indexes and OSS keysstdout/JSONNo
Editingimage editReplace, delete, or move text based on scan resultsImageYes
Receiptimage receiptInvoice/receipt recognition, returns structured JSONstdout/JSONNo
Cloud docsdoc searchSearch cloud documents (keyword/time/type filter)stdout tableNo

Unsupported Operations

  • Online collaborative editing.
  • File version management.
  • Video/audio processing.
  • Batch folder management.
  • Cloud document content editing (search only).

Reference Routing

Before executing an operation, the agent must read the corresponding reference file for full parameters and usage.

Command References (Required)

TriggerReference FileContents
Processing image filesreferences/image-processing.mdFull parameters, mode values, and examples for all image commands
Processing PDF filesreferences/pdf-processing.mdFull parameters, limits, and examples for all pdf commands
Searching cloud documentsThe "Cloud Document Management" section in this fileFull parameters and usage for doc search
Invoice/receipt recognitionThe "Invoice/Receipt Recognition" section in this fileFull parameters and usage for image receipt
User request requires multiple stepsreferences/tool-combos.mdScenario-to-command combination mapping

Workflow References (Required for Multi-Step Tasks)

TriggerWorkflow FileContents
Multiple images need merging or batch conversionreferences/batch-convert.mdMerge strategy selection and batching logic
Image enhancement, upscaling, or restorationreferences/image-enhance.mdMode selection decision tree
OCR or text extractionreferences/ocr-extract.mdPlain text vs Markdown vs Word comparison
Image translationreferences/translate.mdLanguage codes and multilingual version workflow
Watermark add/removereferences/watermark-protection.mdRecommended parameters and scenario mapping

Intent Routing Rules

Route intents in the priority order below. Do not jump directly to a command based only on keywords.

Top-Level Split: Document Search vs File Processing

User IntentRoute DirectionNotes
Search/find/look up cloud documentsdoc search flowDoes not involve image/PDF processing
Process images/PDFs (enhance, convert, OCR, recognize, etc.)→ File processing routes below (starting at Level 1)Existing flow

Key judgment: Is the user's need "searching cloud documents" or "processing local files"? The former uses the doc search command; the latter uses image/pdf/txt commands. These are independent flows and must not be mixed.

Level 1: Determine Input File Type

Input File TypeAvailable Command Group
Image (jpg/jpeg/png)image *
PDFpdf *
TXT/Markdowntxt to-word
Mixed types (image + PDF)Process each type separately. Cross-type merging into a single artifact is not supported.

Level 2: Determine Operation Intent

Use the user's verbs, keywords, and context to determine the operation type.

Operation TypeTrigger EvidenceCommand Direction
Format conversion"convert to Word", "convert to Excel", "convert to PDF", "convert to Markdown"convert / to-pdf / merge-*
OCR recognition"recognize", "OCR", "extract text"ocr / merge-text / pdf convert --format txt/md
Image enhancement"enhance", "remove shadows", "sharpen", "remove moire"image enhance
Image upscaling"HD", "clearer", "increase resolution", "blurry"image hd
Photo restoration"restore", "old photo", "scratch", "faded"image restore
Watermark processing"add watermark", "remove watermark"watermark / remove-watermark / enhance --mode 10
Translation"translate"image translate
Detection"detect", "Photoshop", "tampered", "AI-generated"image validate
Editing"edit image text", "replace text", "modify text", "change X to Y"image scan -> image edit (automatically locate character indexes)
Formula extraction"formula", "LaTeX"image extract-formula
Receipt recognition"invoice", "receipt", "expense report", "bill", "ticket"image receipt

Level 3: Determine Quantity and Artifact

ConditionRoute
Single image -> format conversionimage convert --format xx or image to-pdf
Multiple images -> one documentimage merge-pdf/word/excel, up to 100 images
Multiple images -> process separatelyExecute one by one
Single PDF -> format conversionpdf convert --format xx
Multiple PDFsExecute one by one. There is no PDF merge command.

Level 4: Target Format and Required Parameters

Input -> TargetCorrect CommandCommon Pitfall
Image -> Wordimage convert --format word
Image -> Excelimage convert --format excel
Image -> Markdownimage convert --format md
Image -> TXTimage convert --format txtDoes not support -s
Image -> PDFimage to-pdf for one image, or image merge-pdf for multiple imagesNot image convert --format pdf
PDF -> Wordpdf convert --format word
PDF -> Excelpdf convert --format excel
PDF -> Markdownpdf convert --format md
PDF -> imagespdf to-images or pdf to-images-zip
TXT -> Wordtxt to-word

Intent Disambiguation Rules

When a user request matches multiple operations, disambiguate as follows.

ConflictDisambiguation Rule
"make it sharper and clearer": enhance --mode 2 vs hdIf the original image is blurry or low-resolution, use hd; if it is already clear but needs sharper details, use enhance --mode 2; ask if uncertain.
"scan": image scan vs to-pdfIf the user intends to edit content, use scan + edit; otherwise default to "generate a PDF" and use to-pdf.
"OCR": plain text vs Markdown vs WordAsk which format the user wants; default recommendation is convert --format md to preserve structure.
"restore": restore vs enhanceIf the user mentions old photos, scratches, or fading, use restore; otherwise choose an enhance mode based on the specific issue.
"detect": tampering vs AI-generatedIf the user mentions Photoshop, tampering, or modification, use mode 1; if the user mentions AI, generated, or fake, use mode 2; ask if uncertain.
"remove watermark": PDF vs imageChoose automatically by input type: PDF -> pdf remove-watermark, image -> enhance --mode 10.

Principle: if an ambiguity changes the command choice, ask the user instead of guessing.

Common Routing Mistakes the Agent Must Avoid

User RequestWrong RouteCorrect RouteReason
"merge two PDFs"image merge-pdfNot currently supported; tell the userimage merge-pdf only accepts image inputs
"recognize text in this PDF"image ocrpdf convert --format txt/mdimage ocr only accepts images
"scan these photos into a PDF"image scanimage to-pdf or image merge-pdfimage scan is layout analysis
"remove the watermark from this image"pdf remove-watermarkimage enhance --mode 10pdf remove-watermark only processes PDFs
"image to PDF"image convert --format pdfimage to-pdf / image merge-pdfconvert_image does not support PDF output
"combine a.jpg and b.pdf into one Word file"silently process separatelyExplain that cross-type merging is not supportedDifferent input types cannot be merged into one artifact
"recognize this invoice"image convert --format excelimage receipt invoice.jpgreceipt extracts structured fields; convert converts image content to a table format
"find my contract document"image ocrdoc search "contract"Searching cloud documents, not processing images

Cloud Document Management

doc search — Search Cloud Documents

Search the user's CamScanner cloud documents. Supports keyword search, time range filtering, and document type filtering, which can be combined.

camscanner-cli doc search [keyword] [flags]
Parameter/FlagDescription
keyword (positional)Search keywords (multiple words separated by spaces; any match counts — OR semantics)
-f, --filterDocument type filter: pdf/word/excel/ppt/image/markdown/html
-n, --limitMaximum number of results (default 5, max 50)
-a, --afterStart time (supports 2006-01-02, 2006-01-02 15:04:05, or unix timestamp)
-b, --beforeEnd time (same formats as above)
-s, --scopeSearch scope: title (default — title + page title + notes) or full (includes OCR full text)

Usage examples:

# Search for documents containing "contract"
camscanner-cli doc search "contract"

# Search recent PDF documents
camscanner-cli doc search -f pdf -n 10

# Search documents within a time range
camscanner-cli doc search --after 2026-08-01 --before 2026-08-31

# Keyword + type + time combined search
camscanner-cli doc search "report" -f word --after 2026-08-01

# Full-text search (including OCR content)
camscanner-cli doc search "invoice number" -s full -n 20

Output format: The CLI displays search results in a table.

Agent display rules (mandatory): When presenting search results to the user, the agent must include at least the following four columns:

ColumnSourceDescription
TitleCLI output "标题" columnDocument title
TypeInferred from link URL pathe.g., /pdfDetail → PDF, /markdownDetail → Markdown, /detail → Scan/Image
FolderCLI output "所在目录" columnFolder containing the document
LinkCLI output "链接" columnClickable web page URL

Type inference rule: /pdfDetail = PDF, /markdownDetail = Markdown, /detail = Scan (image). Map other types from the URL path name accordingly. The agent must not omit the Type column or show only title and link.

Agent behavior rules:

  • When the user says "find/search/look up my documents", use doc searchdo not enter the image/pdf processing flow.
  • Multiple keywords are separated by spaces and use OR semantics (any match counts).
  • When no keyword is provided, returns the most recent document list.
  • Default returns 5 results; increase -n when the user needs more.

Keyword tokenization strategy:

The agent should reasonably tokenize the user's search description, separating words with spaces to improve hit probability (under OR semantics, more tokens means broader matching). However, tokenization must be careful:

  • Should tokenize: user says "thesis formula HD" → split to "thesis formula HD"; user says "meeting notes August" → split to "meeting notes August"
  • Should not tokenize: proper nouns, brand names, personal names, and fixed phrases must not be forcibly split. E.g., "CamScanner" stays as one token; "Zhang San's report" keeps "Zhang San" together.
  • When uncertain, do not tokenize: if unsure whether splitting improves results, pass the user's original text as a single keyword.

Semantic intent recognition:

The agent must parse the user's query semantically, extracting time, type, and other structured intents into the corresponding parameters — not as search keywords:

  • Time intent → --after / --before parameters: when the user mentions a time range, parse it as a time filter, not as a keyword.
    • "papers from last August" → doc search "papers" --after 2025-08-01 --before 2025-08-31
    • "meeting notes from last week" → doc search "meeting notes" --after 2026-08-17 --before 2026-08-23
    • "contracts from this year" → doc search "contracts" --after 2026-01-01
  • Type intent → -f parameter: when the user mentions a document type, map it to the type filter.
    • "find my PDF invoices" → doc search "invoices" -f pdf
  • Quantity intent → -n parameter: when the user says "recent ones", "find more", etc., adjust the return count.

Core principle: The tokenization strategy applies only to actual search keywords. Time, type, quantity, and other structured semantics must be extracted into the corresponding command parameters and must never be mixed into keywords. Wrong example: doc search "last August papers" — this would match "last August" as literal text in document content instead of filtering by time.

Search scope decision (-s parameter):

User IntentParameter
Explicitly says "in the title", "in notes", "page title"-s title
Explicitly says "in the content", "in the body", "full text search"-s full
No explicit intent (default)First search with -s title; if no results, automatically retry with -s full

Two-step search strategy: When the user does not specify a search scope, first search by title (faster), then search full text if no results (covers OCR content). If both return nothing, confirm the document does not exist.


Invoice/Receipt Recognition

image receipt — Invoice Recognition

Recognize invoice/receipt images and return structured JSON data (invoice type, amount, date, invoice number, etc.).

camscanner-cli image receipt <file> [-o output.json]
Parameter/FlagDescription
file (positional)Invoice/receipt image path (required)
-o, --outputOutput JSON file path (if omitted, prints to terminal)

Usage examples:

# Recognize an invoice and output to terminal
camscanner-cli image receipt invoice.jpg

# Recognize and save result to a file
camscanner-cli image receipt invoice.jpg -o invoice_result.json

Return data: JSON format containing a bills_list array (one element per invoice), each element including invoice type, amount, tax, date, invoice number, and other structured fields. If invoice_type is "ot", it means no valid invoice information was recognized.

Agent behavior rules:

  • When the user mentions "recognize invoice", "expense report", "receipt", or "extract invoice info", use image receipt.
  • Do not confuse invoice recognition with image convert --format excel: the former extracts structured fields (amount, tax ID, etc.), the latter converts image content to a table format.
  • The recognition result is structured JSON data. The agent should parse it and present it to the user in a human-readable way (e.g., listing key fields like amount, date).
  • image receipt does not support the -s flag (the result is JSON data, not a document).

Error SignatureCauseHandling
Authentication failed, run camscanner-cli auth loginToken expired or user is not logged inRun camscanner-cli auth login
file does not existInput path is wrongCheck the file path
file size exceeds the maximum limitFile exceeds 40 MBCompress the file and retry
rate limit exceeded (429)Calls are too frequentWait 10 seconds and retry
txt format cannot be saved as a cloud documentTXT is not supported as a cloud document typeUse --format md instead
HTTP 504Backend service timeoutWait 5 seconds and retry once
HTTP 500Internal server errorWait 5 seconds and retry once

Retry Strategy

Operation TypeIdempotentSafe to Retry
All conversion/enhancement commandsYesSafe to retry
Saving cloud documents with -sNoRetry may create duplicate documents, which is acceptable
image editYesSafe to retry

Retry Limits and Circuit Breaker (Mandatory)

The agent must follow these retry limits and must not retry indefinitely.

Retry limit: for the same command on the same file, retry at most 3 times (4 total attempts including the first run). After the limit is reached, the agent must stop retrying, report the error details to the user, and suggest troubleshooting steps.

Circuit breaker: when the same operation type, such as convert, enhance, or ocr, fails 3 times in one session, even across different files, the agent must:

  1. Stop all further attempts for that operation type.
  2. Summarize the errors already observed and analyze likely root causes, such as unsupported format, corrupted file, or mismatched parameters.
  3. Report the failure status and recommended fixes to the user.
  4. Resume only if the user explicitly asks to keep trying.

Retry intervals:

Error TypeIntervalNotes
HTTP 42910 secondsRate limited; wait before retrying
HTTP 500/5045 secondsTemporary server-side failure
HTTP 400No waitClient-side issue; inspect parameters and files before retrying

HTTP 400 retry handling: HTTP 400 usually means the request parameters or file are invalid. Before retrying, the agent should check:

  • Whether the file format is supported.
  • Whether the file is corrupted or empty.
  • Whether parameter spelling and values are correct.
  • For multi-file operations such as merge-* or merge-text, whether there are too many input files. Large file counts may exceed request-size or processing limits, so try fewer files per batch.
  • If the problem remains after inspection, retries are still allowed, but the 3-retry limit must be respected.

Safety Constraints

  • Tokens are managed by the system keychain. The skill does not store or log tokens.

  • Data flow:

    • Input files are uploaded to CamScanner servers for processing and are temporarily stored there during processing.
    • Converted artifacts generate temporary file_id values, which are used to download results.
    • With -s, processing results are persistently saved to the user's CamScanner account.
    • With -o, results are downloaded locally; server-side temporary files are cleaned up according to the server retention policy.
    • The skill itself does not additionally cache or persist document content.
  • Output path conflict protection: The CLI silently overwrites existing files when -o is used. Before write operations, the agent must check whether the output path already exists. If it does:

    1. Prefer appending a numeric suffix, such as output_1.jpg or output_2.jpg.
    2. Or ask the user to confirm overwrite.
    3. Never overwrite an existing user file without confirmation.
  • Multiple file argument rules: Do not pass multiple files with glob wildcards such as *.jpg. The agent must:

    1. List files in the directory first and determine page order using natural sorting, where page2 comes before page10.
    2. Pass each file as a full quoted path so spaces or special characters in filenames are safe.
    3. Confirm the file list and order with the user before execution.
    # Correct: explicitly listed, quoted, and ordered.
    camscanner-cli image merge-pdf "scan_01.jpg" "scan_02.jpg" "scan_03.jpg" -s
    
    # Wrong: glob order is uncertain and paths are unsafe.
    camscanner-cli image merge-pdf *.jpg -s
    

相关技能