Community生产力与协作github.com

book-to-skill

把书籍和文档(PDF、EPUB、DOCX、HTML、Markdown、TXT、RTF、MOBI/AZW)转换成结构化、可按需加载的 Agent Skill——提取框架、思维模型、原则、方法和反模式,而不是写摘要。当用户上传书籍文件并说「把这本书做成 skill」「蒸馏这本书」「把书转成技能包」,或要求分析书中框架、更新/合并已有的书籍 skill 时使用。

book-to-skill 是什么?

book-to-skill is a Claude Code agent skill that 把书籍和文档(PDF、EPUB、DOCX、HTML、Markdown、TXT、RTF、MOBI/AZW)转换成结构化、可按需加载的 Agent Skill——提取框架、思维模型、原则、方法和反模式,而不是写摘要。当用户上传书籍文件并说「把这本书做成 skill」「蒸馏这本书」「把书转成技能包」,或要求分析书中框架、更新/合并已有的书籍 skill 时使用。.

兼容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/beckshu/book-to-skill/tree/HEAD/skills/book-to-skill

Installed? Explore more 生产力与协作 skills: steipete/gemini, steipete/gh-issues, steipete/skill-creator · View all 6 →

在你喜欢的 AI 中提问

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

文档

Book-to-Skill Converter (Kimi Edition)

Transform the structured knowledge in a book into an actionable Agent Skill. Extract structure, not a summary: A skill is a toolbox containing —

  • Named frameworks (mental models with clear use cases)
  • Actionable principles (rules that guide decisions)
  • Methods & techniques (step-by-step procedures)
  • Anti-patterns (what to avoid and why)
  • Author's tone and way of thinking

Preserve the author's precise wording. "5 Whys" is not the same as "ask why multiple times" — the proper name of a framework must be captured as-is.

Runtime Environment Conventions (Kimi Sandbox)

  • This skill's directory (SKILL_DIR) = the directory containing this SKILL.md. All scripts must be invoked explicitly via the interpreter: python3 SKILL_DIR/scripts/extract.py ..., python3 SKILL_DIR/tools/scan_generated_skill.py ... — do not rely on executable permissions.
  • User-uploaded book files are in /mnt/agents/upload/. First confirm the file exists; if not, ask the user to upload.
  • The generated book skill is written to /mnt/agents/output/<skill_name>/ (the only user-visible persistent directory), and is packed into a .skill file for delivery (see Step 10).
  • If optional dependencies for extraction are missing, the sandbox can directly pip install <package> and retry, or fall back to the fallback extractor as indicated by the script.

Work Modes

  1. Full Conversion (default): User provides a document path with no special instructions → execute Steps 0–10, produce a complete skill.
  2. Analysis Only: User says "analyze only" or "extract first to see" → execute Steps 0–3, produce a structured extraction report and stop, without generating a skill file.
  3. Generate from Existing Analysis: User already has analysis notes → skip Steps 0–3, start from Step 4.
  4. Update / Merge (Update/Fold-in): User asks to merge new content into an existing skill → see the "Update / Merge Workflow" at the end.

Step 0 — Input Confirmation

  • If no input is provided, ask the user: "Which book would you like to make into a skill? Supported formats: PDF, EPUB, DOCX, HTML, Markdown, TXT, RTF, MOBI/AZW. Upload the file or give me the path."
  • If the last argument is not an existing file/directory/wildcard and resembles a lowercase slug with hyphens, treat it as SKILL_NAME; the remaining arguments are INPUT_PATHS.
  • If the input is an existing skill directory (containing SKILL.md and chapters/), or if SKILL_NAME already exists in /mnt/agents/output/, mark this as Update/Merge mode.
  • Re-run Protection: Before a full conversion, if the target skill directory already exists, stop and ask the user to choose: (1) Update/Merge, (2) Confirm the existing skill is complete and stop, or (3) Force regenerate. If a previous run was interrupted and its workdir's metadata.json is intact, the filenames and SHA256 fingerprints of sources match the current input one-to-one, and the extraction mode is the same, you may reuse that workdir; otherwise, re-extract. When in doubt, ask.

Step 1 — Validate Input

Confirm that at least one supported file exists among INPUT_PATHS: .pdf .epub .docx .txt .md .markdown .rst .adoc .html .htm .rtf .mobi .azw .azw3. Expand directories and wildcards first. If no matching files are found, report the error clearly and stop.

Step 1.5 — Confirm Content Type

Ask the user:

What type of material is this? Help me choose the best extraction method:

  1. Technical — Contains code blocks, tables, formulas, diagrams (programming books, papers, architecture guides)
  2. Plain text — Largely prose, few tables/code (management, productivity, nonfiction narrative)
  3. Not sure — Use the fastest method; I'll warn you if quality is limited

Option 1 → BOOK_TYPE=technical; Option 2/3 → BOOK_TYPE=text. Technical mode informs the user: PDFs will attempt Docling layout-aware extraction; EPUB and other formats use their respective text extractors. Code, tables, and formulas may lose structure. The actual extraction_method and fallback_reason for each file can be found in metadata.json.

Step 2 — Extract Text

python3 SKILL_DIR/scripts/extract.py $INPUT_PATHS --mode <BOOK_TYPE> --install-missing ask

The script checks for optional dependencies and suggests fallbacks. In non-interactive scenarios, it uses the fallback by default. Environment pre-check: python3 SKILL_DIR/scripts/extract.py --check.

Each run creates an independent workdir (default <tempdir>/book_skill_work-<pid>/, or specify via BOOK_SKILL_WORKDIR), containing:

  • full_text.txt — Full text merged from all sources, with clear separation boundaries.
  • metadata.json — Overall word/page/token estimates, count of dropped images, workdir path, and per-source details.

At the end, the script prints three paths: Workdir ->, Text ->, Meta ->. Use the actual output, do not assume fixed paths.

Before generation, confirm that the extracted text is from the user's requested document: Verify the filename/source_file in metadata.json, or the first SOURCE: header in full_text.txt.

Step 2.5 — Pre-generation Cost Estimate

Read metadata.json and present the following to the user:

📖 Sources detected: N (list each file name and format; alert if >5 images dropped)
📄 Total pages/sections: ~N | Words: ~N | Total tokens: ~NK
💰 Estimated token consumption: Input ~NK (reading + prompts), Output ~NK (generated skill files)
⏱  Estimated time: ~N minutes
📁 Will generate: SKILL.md + chapters/ + glossary.md + patterns.md + cheatsheet.md
➡ Continue with full conversion? (Reply "analyze only" to see the extraction report first)

Estimation method: Input ≈ metadata's estimated_tokens × 1.3; Output ≈ number of chapters × per-chapter budget (text≈1,000, technical≈1,800 token) + 4,000 (SKILL.md) + 4,500 (three supporting files). Wait for user confirmation before continuing.

Step 2.6 — Programmatic Exploration of Large Books (> 50k tokens)

Treat full_text.txt as a queryable corpus. Do not read the entire book into context:

wc -w "$FULL_TEXT_PATH"                                   # Check size first
grep -n -E "^\s*(Chapter|CHAPTER|第[0-9一二三四五六七八九十]+章)" "$FULL_TEXT_PATH" | head -40   # Find chapter line numbers
sed -n '<start>,<end>p' "$FULL_TEXT_PATH"                # Extract only the needed section
grep -c -i "<framework keyword>" "$FULL_TEXT_PATH"        # Verify existence before asserting

A 200-page book is approximately 75k tokens. Rereading the entire book for each chapter would cost millions of input tokens. Use grep + sed to extract only the slices you need, keeping costs proportional to output.

Small books (≤ 50k tokens) can be read directly.

Step 3 — Analyze Book Structure

Read the first 8,000 characters of full_text.txt to identify: title, author, chapter structure ("Chapter N", "PART I", "第 N 章", table of contents), core themes, and approximate chapter count. If a table of contents is found, map out all chapters accordingly.

In Analysis Only mode, produce a report and stop:

## Extraction Report — <Book Title>
### Author's Core Frameworks
- **<Framework Name>**: <What it is, when to use it>
### Key Principles
- <Principle>: <Actionable rule>
### Methods & Techniques
- <Technique>: <Steps or practice>
### Anti-patterns
- <What to avoid>: <Why>
### Suggested Skill Name
`{Author's last name}-{Core concept}`, e.g., `cialdini-influence`
### Chapters Detected
| # | Title | Major Frameworks |

Step 4 — Confirm Usage (Full Conversion Only)

What will this skill primarily help you do? (Select all that apply)

  1. Apply the author's frameworks in my work
  2. Use the author's mental models to think through problems
  3. Look up specific chapters and concepts
  4. All of the above

Based on this, derive DEPTH (no separate prompt needed): Only 3 is selected → reference (concise quick-reference); includes 1/2/4 → study (deeper derivation, examples). For modes 2/3, skip this step and default to study.

Step 5 — Determine Skill Name & Output Location

If SKILL_NAME is provided, use it. Otherwise, give two candidates for the user to choose from: Author-Concept style ({Author's last name}-{Core concept}, e.g., meadows-systems) or Book Title style (title in lowercase with hyphens). Default to Author-Concept style for books with strong methodological content.

Target directory: /mnt/agents/output/<skill_name>/. If it already exists, ask the user: (1) Update/Merge, (2) Overwrite and rebuild, (3) Use a different name (append -2 or a custom slug).

Step 6 — Create Directory

mkdir -p "/mnt/agents/output/<skill_name>/chapters"

Step 7 — Generate Chapter Files

Per-chapter token budget (adaptive):

DEPTH=referenceDEPTH=study
BOOK_TYPE=text800–1,2001,000–1,800
BOOK_TYPE=technical1,200–1,8002,000–3,000
  • The budget is a target, not a hard limit. Prioritize density over length; never pad for word count.
  • study depth must be earned through content: Under ## Example Reconstruction, reproduce a complete example from the book (sample dialogue, conversation, filled template, a full decision trace by the author) — this is the part learners most often revisit. Expand the "how to" of top frameworks into explicit steps or criteria. Add a sentence on "why it works / when it fails" for the most important 1–2 frameworks. If no example can be reconstructed, let it fall below the budget lower bound and note in the Core Idea that this chapter is thinner.

Process chapters one by one: Prefer using the start_line/end_line from the top-level chapter_ranges in metadata.json (1-based, inclusive, can be directly used with sed -n); if not available, use grep to find chapter titles. Output to /mnt/agents/output/<skill_name>/chapters/ch<NN>-<slug>.md, using this template:

# Chapter N: <Full Title>

## Core Idea
<1–2 sentences: the single most important thing in this chapter>

## Frameworks in This Chapter
- **<Framework Name>**: <Original author wording — preserve the proper name>
  - When to use: <Specific scenario>
  - How to do it: <Steps or criteria>

## Key Concepts
- **<Term>**: <One-sentence precise definition>
(5–10 most important terms from this chapter)

## Mental Models
<2–4, written as "Use X when Y" or "Think of X as Y">

## Anti-patterns
- **<What to avoid>**: <Why it fails>

## Code Example (Technical books only; omit when BOOK_TYPE=text)
```<language>
<The most instructive code snippet from this chapter, preserving indentation>
  • What it demonstrates:

Quick Reference Table (Technical books only; omit rule same as above)

<Reproduce the chapter's comparison matrix, parameter table, or decision table as a markdown table>

Example Reconstruction (Only for DEPTH=study; omit for reference)

<Compactly reproduce a concrete example the author fully walked through; stay faithful to the original, never copy long passages verbatim>

Key Takeaways

(3–7 points a practitioner must remember)

Related Chapters

  • Chapter N:
  • :

For technical books, prioritize "Code Example" and "Quick Reference Table"; for plain text books, prioritize "Frameworks in This Chapter" and "Mental Models." Omit empty technical subsections directly.

## Step 8 — Generate Supporting Files

### glossary.md (≤1,500 token)
All important terms from the book, sorted alphabetically. Format: `**Term** — Definition (Chapter N)`.

### patterns.md (≤2,000 token)
All specific techniques, design patterns, and algorithms from the book. Format:

Pattern Name

When to use: … How to do it: … Trade-offs: …


### cheatsheet.md (≤1,200 token)
**This is the most differentiating layer of the skill — it is a reasoning aid, not a keyword list.** It captures the author's judgment: what decisions they make and why. Include, in priority order:

1. **Decision Rules** — "When X happens, do Y, because Z."
2. **Decision Trees** (nested lists or small tables) — Multi-branch choices.
3. **Trade-off Matrices** — Score options on dimensions the author cares about.
4. **Thresholds & Defaults** — Specific numbers, ratios, rules of thumb the author explicitly gives.
5. **Signals & Smells** — Heuristics to quickly diagnose a situation ("If you see X, you're probably already in Y").

Avoid: Bare "term → definition" lines (that's the glossary), or long paragraphs of prose (that's the chapter files). Every line should help the reader make a decision.

## Step 9 — Generate Main SKILL.md (body ≤4,000 token, important content first)

```markdown
---
name: <skill_name>
description: A knowledge base from "<Book Title>" (<Author>). Use this when you need to apply <Author>'s frameworks on <3–6 key topics>, study the book in depth, or look up its concepts.
---

# "<Book Title>"
**Author**: <Author> | **Pages**: ~<N> | **Chapters**: <N> | **Generated**: <YYYY-MM-DD>

## How to Use This Skill
- Ask without a specific question — I'll present the core frameworks
- Ask with a topic — e.g., "pricing", "copy" — I'll locate and read the relevant chapter before answering
- Ask with a chapter number — e.g., "ch05" — I'll load that chapter directly
- Ask "What chapters are there?" — I'll give you the full index

## Core Frameworks & Mental Models
<Approximately 2,000 token: The author's most important named frameworks and principles. Preserve proper names.
 Write as "Use X when Y" or "Prefer X over Y because Z." This is a toolbox, not a summary.>

## Chapter Index
| # | Title | Key Frameworks |
|---|------|-----------------|
| [ch01](chapters/ch01-<slug>.md) | <Title> | <Framework1>, <Framework2> |
...

## Topic Index
<Sorted alphabetically: Important terms/frameworks → chapters that cover them>
- **<Term>** → ch<N>[, ch<N>]

## Supporting Files
- [glossary.md](glossary.md) — All key terms
- [patterns.md](patterns.md) — All techniques and patterns
- [cheatsheet.md](cheatsheet.md) — Quick reference and decision guide

## Scope
This skill only covers the content of this book. For topics outside this scope, consult other skills or ask me directly.
<If >5 images were dropped, note: N images from the original book were not extracted>

Step 9.5 — Safety Scan

Must run before delivery or packaging:

python3 SKILL_DIR/tools/scan_generated_skill.py "/mnt/agents/output/<skill_name>"

If the exit code is non-zero, stop and present the scan report (file/line numbers) to the user for review; do not rewrite generated files or package for delivery until the issues are resolved or the user explicitly accepts them.

Step 10 — Package and Deliver (Kimi)

cd /mnt/agents/output && rm -f <skill_name>.skill && \
  cd <skill_name> && zip -qr ../<skill_name>.skill . && cd ..

Then clean up the workdir actually used by this run (the path shown as Workdir -> in extraction output, i.e., the workdir field in metadata.json) — only delete directories created by this run:

rm -rf "$WORKDIR"

Finally, report to the user:

✅ Skill generated and packaged: <skill_name>.skill

📚 Book: "<Book Title>" — <Author>
📄 Pages: ~<N> | Chapters: <N>

Generated files:
  SKILL.md      — Core frameworks + index (~X token)
  chapters/     — N chapter files (each ~X token)
  glossary.md   — Glossary (~X token)
  patterns.md   — Techniques & patterns (~X token)
  cheatsheet.md — Quick reference & decision guide (~X token)

Usage:
  Ask <skill_name> directly           → Load core frameworks
  Ask <skill_name> about <topic>       → Locate and explain the topic
  Ask <skill_name> to expand ch<N>     → Dive into a specific chapter

Attach the .skill file as a deliverable, and remind the user: The .skill file can be directly installed as a Kimi skill, or unzipped and copied for use with other agents.


Update / Merge Workflow (Mode 4)

  1. Read existing structure: Read the existing SKILL.md's chapter index, topic index, metadata, and core frameworks; list chapters/ to find the highest chapter number (e.g., ch12); read glossary/patterns/cheatsheet to see what's already included.
  2. Match content: For content in the current full_text.txt that directly extends existing chapter topics → read the old chapter file, merge and rewrite; for entirely new chapters/sections → create new files starting from the next chapter number (ch13-, ch14-, …).
  3. Generate/update chapter files: Follow the template and budget in Step 7.
  4. Merge supporting files: Re-sort glossary after adding new terms, append chapter references to existing terms ("(Chapter 4, Chapter 13)"); append new patterns to patterns.md (total ≤2,500 token); incorporate new decision rules and comparison tables into cheatsheet.md.
  5. Regenerate main SKILL.md: Update chapter count, page count, and generation date; fold new content into core frameworks (still ≤4,000 token); append new chapters to the chapter index; merge topic index, adding the new chapter link to existing topics ("→ ch05, ch13").
  6. Scan, clean, report: Execute Step 9.5, then re-package the .skill file per Step 10, reporting the new chapters and merged entries.

Quality Red Lines

  1. Extract structure, not a summary — Capture named frameworks, original wording, and anti-patterns, not chapter summaries.
  2. Preserve the author's precision — Proper names are not to be replaced.
  3. Density over completeness — 1,000 token of refined insight beats 10,000 token of excerpt.
  4. Practitioner tone — Write "Use X when Y," not "This book explains X."
  5. Front-load important content — When compressing, keep only the beginning; put the most important content first in SKILL.md.
  6. Chapter files loaded on demand — They do not occupy context unless read.
  7. Never copy the original verbatim — Always synthesize, refine, and extract signals. Skill content generated from third-party copyrighted books is intended for personal learning use only; do not distribute publicly.
  8. Topic index is critical — It is the roadmap for the agent to navigate to the correct chapter file.

相关技能