Compare commits

..

22 Commits

Author SHA1 Message Date
Jim Liu 宝玉 38cc497748 chore: release v1.117.1 2026-05-16 23:09:11 -05:00
Jim Liu 宝玉 0f95d12a09 Merge pull request #155 from JimLiu/codex/wechat-image-upload-fallback-webp
[codex] Fix WeChat image upload fallback and WebP clipboard
2026-05-16 23:07:09 -05:00
Jim Liu 宝玉 7fd9e51fc2 Fix WeChat image upload fallback and WebP clipboard 2026-05-16 22:33:07 -05:00
Jim Liu 宝玉 a5d227b4e8 Merge pull request #154 from zhangga/codex/fix-wechat-browser-article-publish
Fix WeChat browser article publishing reliability
2026-05-16 22:29:28 -05:00
zeqiang.zhang 81377416b4 Fix WeChat browser article publishing 2026-05-16 22:47:41 +08:00
Jim Liu 宝玉 a44bb08360 chore: release v1.117.0 2026-05-16 00:51:34 -05:00
Jim Liu 宝玉 a07669136c feat(baoyu-xhs-images): sync batch generation policy from baoyu-image-cards 2026-05-16 00:50:36 -05:00
Jim Liu 宝玉 b7298a60c6 feat(baoyu-slide-deck): add batch generation policy with configurable batch size 2026-05-16 00:50:33 -05:00
Jim Liu 宝玉 309f078efb feat(baoyu-image-cards): add batch generation policy with configurable batch size 2026-05-16 00:50:30 -05:00
Jim Liu 宝玉 8958ba5409 feat(baoyu-comic): add batch generation policy with configurable batch size 2026-05-16 00:50:28 -05:00
Jim Liu 宝玉 e6612628dc feat(baoyu-article-illustrator): add batch generation policy with configurable batch size 2026-05-16 00:50:25 -05:00
Jim Liu 宝玉 bd5745f837 chore: release v1.116.5 2026-05-14 01:49:35 -05:00
Jim Liu 宝玉 cb26732559 refactor(baoyu-post-to-wechat): harden Telegram QR notification
- Add 10s timeout to Telegram fetch so unreachable api.telegram.org
  doesn't block waitForLogin indefinitely.
- Move 2s QR-render wait inside sendQrToTelegram, after the env-var
  early return, so the no-op path doesn't pay the delay.
- Use viewport screenshot (captureBeyondViewport: false) as fallback
  to reduce payload size and keep the QR scannable.
2026-05-14 01:45:58 -05:00
孙斌锋 9baf570caa feat(baoyu-post-to-wechat): send WeChat login QR code to Telegram (#150)
When `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_ID` env vars are set,
the browser login flow automatically sends the WeChat QR code image
to the configured Telegram chat so headless / remote runs don't need
a screen to scan the code.

Strategy (in priority order):
1. Extract QR img.src from known DOM selectors
2. If URL-based src: re-fetch inside Chrome to carry session cookies
3. Fallback: full-page CDP screenshot

Feature is fully opt-in: skipped silently when env vars are absent.

Co-authored-by: Before SUN <beforesun@BeforedeMac-mini.local>
2026-05-14 01:21:45 -05:00
Jim Liu 宝玉 f99815cec9 chore: release v1.116.4 2026-05-14 01:10:54 -05:00
Jim Liu 宝玉 8f0663d515 refactor(baoyu-wechat-summary): streamline roast version prompts 2026-05-14 01:10:51 -05:00
Jim Liu 宝玉 20ebf6126c chore: release v1.116.3 2026-05-13 22:33:29 -05:00
Jim Liu 宝玉 64db328e61 docs: replace Claude Code references with Agent in READMEs 2026-05-13 22:33:16 -05:00
Jim Liu 宝玉 a3819b8e30 chore: release v1.116.2 2026-05-13 22:30:54 -05:00
Jim Liu 宝玉 234c2a832b docs(baoyu-wechat-summary): update example group name in SKILL.md 2026-05-13 22:30:38 -05:00
Jim Liu 宝玉 7943eb7b05 chore: release v1.116.1 2026-05-13 22:28:34 -05:00
Jim Liu 宝玉 4b4a4d3863 feat(baoyu-wechat-summary): add data_root to first-time setup flow 2026-05-13 22:28:13 -05:00
29 changed files with 870 additions and 216 deletions
+1 -1
View File
@@ -6,7 +6,7 @@
},
"metadata": {
"description": "Skills shared by Baoyu for improving daily work efficiency",
"version": "1.116.0"
"version": "1.117.1"
},
"plugins": [
{
+43
View File
@@ -2,6 +2,49 @@
English | [中文](./CHANGELOG.zh.md)
## 1.117.1 - 2026-05-16
### Fixes
- `baoyu-post-to-wechat`: fix WeChat browser article publishing (by @zhangga)
- `baoyu-post-to-wechat`: fix image upload fallback and WebP clipboard copy on macOS
## 1.117.0 - 2026-05-16
### Features
- `baoyu-article-illustrator`: add batch generation policy — backend native batch first, runtime parallel calls second, sequential fallback; configurable `generation_batch_size` and `--batch-size` option
- `baoyu-comic`: add batch generation policy with dependency-aware ordering (character sheet before pages) and configurable `--batch-size`
- `baoyu-image-cards`: add batch generation policy honoring image-1 anchor chain, with configurable `--batch-size`
- `baoyu-slide-deck`: add batch generation policy for slide image rendering with configurable `--batch-size`
- `baoyu-xhs-images`: sync batch generation policy from baoyu-image-cards
## 1.116.5 - 2026-05-14
### Features
- `baoyu-post-to-wechat`: send WeChat login QR code to Telegram when `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_ID` env vars are set, enabling headless / remote login flows (by @beforesun)
### Refactor
- `baoyu-post-to-wechat`: harden Telegram QR notification — add 10s fetch timeout, defer the 2s QR-render wait until env vars are configured, and use viewport screenshot as fallback
## 1.116.4 - 2026-05-14
### Refactor
- `baoyu-wechat-summary`: streamline roast version prompts in output-formats.md (99 → 23 lines), add roast-specific profile usage bullets to SKILL.md Round 2
## 1.116.3 - 2026-05-13
### Documentation
- Replace Claude Code references with generic Agent wording in READMEs to reflect multi-agent support (Claude Code, Codex, etc.)
## 1.116.2 - 2026-05-13
### Documentation
- `baoyu-wechat-summary`: update example group name in SKILL.md
## 1.116.1 - 2026-05-13
### Features
- `baoyu-wechat-summary`: add `data_root` option to first-time setup flow, allowing users to customize the digest output directory during initialization
## 1.116.0 - 2026-05-13
### Features
+43
View File
@@ -2,6 +2,49 @@
[English](./CHANGELOG.md) | 中文
## 1.117.1 - 2026-05-16
### 修复
- `baoyu-post-to-wechat`:修复微信浏览器文章发布问题 (by @zhangga)
- `baoyu-post-to-wechat`:修复图片上传回退逻辑及 macOS WebP 剪贴板复制
## 1.117.0 - 2026-05-16
### 新功能
- `baoyu-article-illustrator`:新增批量生成策略 —— 优先使用后端原生批量接口,其次运行时并行调用,最后顺序生成;支持 `generation_batch_size` 配置和 `--batch-size` 参数
- `baoyu-comic`:新增批量生成策略,支持依赖感知排序(角色图先于页面)和 `--batch-size` 参数
- `baoyu-image-cards`:新增批量生成策略,遵循 image-1 锚定链,支持 `--batch-size` 参数
- `baoyu-slide-deck`:新增幻灯片图片批量生成策略,支持 `--batch-size` 参数
- `baoyu-xhs-images`:同步 baoyu-image-cards 的批量生成策略
## 1.116.5 - 2026-05-14
### 新功能
- `baoyu-post-to-wechat`:当设置 `TELEGRAM_BOT_TOKEN``TELEGRAM_CHAT_ID` 环境变量时,自动将微信登录二维码发送到 Telegram,支持无显示器/远程登录场景 (by @beforesun)
### 重构
- `baoyu-post-to-wechat`:加固 Telegram QR 通知逻辑 —— 增加 10 秒 fetch 超时、未配置环境变量时不再无谓等待 2 秒、回退截图改为视口范围以减小体积
## 1.116.4 - 2026-05-14
### 重构
- `baoyu-wechat-summary`:精简毒舌版提示词(99 → 23 行),在 SKILL.md Round 2 中增加 roast 专用的画像使用指引
## 1.116.3 - 2026-05-13
### 文档
- README 中将 Claude Code 替换为通用的 Agent 表述,体现多 Agent 支持(Claude Code、Codex 等)
## 1.116.2 - 2026-05-13
### 文档
- `baoyu-wechat-summary`:更新 SKILL.md 中的示例群名
## 1.116.1 - 2026-05-13
### 新功能
- `baoyu-wechat-summary`:初始化设置流程中新增 `data_root` 选项,允许用户在首次配置时自定义摘要输出目录
## 1.116.0 - 2026-05-13
### 新功能
+8 -8
View File
@@ -2,7 +2,7 @@
English | [中文](./README.zh.md)
Skills shared by Baoyu for improving daily work efficiency with Claude Code.
Skills shared by Baoyu for improving daily work efficiency with AI Agents (Claude Code, Codex, etc.).
## Prerequisites
@@ -40,7 +40,7 @@ Publishing to ClawHub releases the published skill under `MIT-0`, per ClawHub's
### Register as Plugin Marketplace
Run the following command in Claude Code:
Run the following command in the Agent:
```bash
/plugin marketplace add JimLiu/baoyu-skills
@@ -64,7 +64,7 @@ Run the following command in Claude Code:
**Option 3: Ask the Agent**
Simply tell Claude Code:
Simply tell the Agent:
> Please install Skills from github.com/JimLiu/baoyu-skills
@@ -80,7 +80,7 @@ The marketplace now exposes a single plugin so each skill is registered exactly
To update skills to the latest version:
1. Run `/plugin` in Claude Code
1. Run `/plugin` in the Agent
2. Switch to **Marketplaces** tab (use arrow keys or Tab)
3. Select **baoyu-skills**
4. Choose **Update marketplace**
@@ -579,7 +579,7 @@ Plain text input is treated as a regular post. Markdown files are treated as X A
```bash
# Post with text
/baoyu-post-to-x "Hello from Claude Code!"
/baoyu-post-to-x "Hello from AI Agent!"
# Post with images
/baoyu-post-to-x "Check this out" --image photo.png
@@ -1118,16 +1118,16 @@ Summarize WeChat group chat highlights into a structured digest. Extracts topics
```bash
# Summarize a group's recent messages
/baoyu-wechat-summary 消失的大叔 最近 1
/baoyu-wechat-summary 相亲相爱一家人 最近 1
# Weekly summary
/baoyu-wechat-summary AI 技术群 最近 7
# Incremental (since last digest)
/baoyu-wechat-summary 消失的大叔
/baoyu-wechat-summary 相亲相爱一家人
# Roast version
/baoyu-wechat-summary 消失的大叔 最近 3 天 毒舌版
/baoyu-wechat-summary 相亲相爱一家人 最近 3 天 毒舌版
```
**Requirements**:
+8 -8
View File
@@ -2,7 +2,7 @@
[English](./README.md) | 中文
宝玉分享的 Claude Code 技能集,提升日常工作效率。
宝玉分享的 AI Agent 技能集(适用于 Claude Code、Codex 等),提升日常工作效率。
## 前置要求
@@ -40,7 +40,7 @@ clawhub install baoyu-markdown-to-html
### 注册插件市场
Claude Code 中运行:
Agent 中运行:
```bash
/plugin marketplace add JimLiu/baoyu-skills
@@ -64,7 +64,7 @@ clawhub install baoyu-markdown-to-html
**方式三:告诉 Agent**
直接告诉 Claude Code
直接告诉 Agent
> 请帮我安装 github.com/JimLiu/baoyu-skills 中的 Skills
@@ -80,7 +80,7 @@ clawhub install baoyu-markdown-to-html
更新技能到最新版本:
1. 在 Claude Code 中运行 `/plugin`
1. 在 Agent 中运行 `/plugin`
2. 切换到 **Marketplaces** 标签页(使用方向键或 Tab
3. 选择 **baoyu-skills**
4. 选择 **Update marketplace**
@@ -579,7 +579,7 @@ clawhub install baoyu-markdown-to-html
```bash
# 发布文字
/baoyu-post-to-x "Hello from Claude Code!"
/baoyu-post-to-x "Hello from AI Agent!"
# 发布带图片
/baoyu-post-to-x "看看这个" --image photo.png
@@ -1118,16 +1118,16 @@ AI 驱动的生成后端。
```bash
# 总结群最近消息
/baoyu-wechat-summary 消失的大叔 最近 1 天
/baoyu-wechat-summary 相亲相爱一家人 最近 1 天
# 周报
/baoyu-wechat-summary AI 技术群 最近 7 天
# 增量模式(从上次摘要继续)
/baoyu-wechat-summary 消失的大叔
/baoyu-wechat-summary 相亲相爱一家人
# 毒舌版
/baoyu-wechat-summary 消失的大叔 最近 3 天 毒舌版
/baoyu-wechat-summary 相亲相爱一家人 最近 3 天 毒舌版
```
**前置要求**
+19 -2
View File
@@ -1,7 +1,7 @@
---
name: baoyu-article-illustrator
description: Analyzes article structure, identifies positions requiring visual aids, generates illustrations with Type × Style × Palette three-dimension approach. Use when user asks to "illustrate article", "add images", "generate images for article", or "为文章配图".
version: 1.58.0
version: 1.59.0
metadata:
openclaw:
homepage: https://github.com/JimLiu/baoyu-skills#baoyu-article-illustrator
@@ -42,6 +42,22 @@ Setting `preferred_image_backend: ask` forces the step-3 prompt every run regard
Concrete tool names (`imagegen`, `image_generate`, `baoyu-imagine`) above are examples — substitute the local equivalents under the same rule.
## Batch Generation Policy
After every prompt file for the run has been saved and verified, generate images in batches by default.
Priority order:
1. Use the chosen backend's native batch / multi-task interface if it exists. Each task must keep its own prompt file, output path, aspect ratio, and direct reference images.
2. If no native batch interface exists but the runtime can issue parallel tool calls, dispatch up to `generation_batch_size` images at a time. Default: `4`. An explicit user request in the current message, such as `--batch-size 4` or "并行4张一起生成", overrides EXTEND.md.
3. If neither native batch nor parallel tool calls are available, generate sequentially.
Rules:
- Never start the first batch until all prompt files for that batch exist on disk.
- Retry failed items once without regenerating successful items.
- Do not use subagents merely to parallelize image rendering. Use subagents only for separate prompt iteration or creative exploration.
## Confirmation Policy
Default behavior: **confirm before generation**.
@@ -167,7 +183,7 @@ Full template: [references/workflow.md](references/workflow.md#step-4-generate-o
4. LABELS **MUST** include article-specific data: actual numbers, terms, metrics, quotes
5. **DO NOT** pass ad-hoc inline prompts to `--prompt` without saving prompt files first
6. Select the backend via the `## Image Generation Tools` rule at the top: use whatever is available; if multiple, ask the user once. Do this once per session before any generation.
7. **Execution strategy**: When multiple illustrations have saved prompt files and the task is now plain generation, prefer the chosen backend's batch interface (if it offers one) over spawning subagents. Use subagents only when each image still needs separate prompt iteration or creative exploration. If the backend has no batch interface, generate sequentially.
7. **Execution strategy**: Generate in batches per the `## Batch Generation Policy`: backend native batch first, runtime parallel tool calls second, sequential only as fallback. Default batch size is 4 unless EXTEND.md or the current request overrides it.
8. Process references (`direct`/`style`/`palette`) per prompt frontmatter
9. Apply watermark if EXTEND.md enabled
10. Generate from saved prompt files; retry once on failure
@@ -239,5 +255,6 @@ EXTEND.md lives at the first matching path listed in Step 1.5. Three ways to cha
- `preferred_image_backend: codex-imagegen` — pin to Codex's built-in.
- `preferred_image_backend: baoyu-imagine` — pin to the baoyu-imagine skill.
- `preferred_image_backend: ask` — confirm backend every run.
- `generation_batch_size: 4` — default number of images to render concurrently when the runtime supports parallel generation calls.
- `preferred_type: infographic`, `preferred_style: notion`, `preferred_palette: macaron`, `language: zh`.
- `default_output_dir: imgs-subdir` — where to write generated images relative to the article.
@@ -129,12 +129,15 @@ preferred_style:
default_output_dir: imgs-subdir # same-dir | imgs-subdir | illustrations-subdir | independent
language: null
preferred_image_backend: auto
generation_batch_size: 4
custom_styles: []
---
```
`preferred_image_backend: auto` is the baked-in default — first-time setup does not ask about it. The `## Image Generation Tools` rule in SKILL.md then picks the runtime-native tool (Codex `imagegen`, Hermes `image_generate`, etc.) when available, and falls back to installed backends.
`generation_batch_size: 4` is the baked-in default for batch rendering. The current user request may override it for one run.
## Modifying Preferences Later
See the `## Changing Preferences` section in `SKILL.md` for the canonical list of common edits (pin backend, change defaults, retrigger setup). Full schema: `preferences-schema.md`.
@@ -28,6 +28,8 @@ default_output_dir: null # same-dir|illustrations-subdir|independent
preferred_image_backend: auto # auto|ask|<backend-id>
generation_batch_size: 4 # 1-8, used when backend/runtime supports batch or parallel generation
custom_styles:
- name: my-style
description: "Style description"
@@ -55,6 +57,7 @@ custom_styles:
| `language` | string | null | Output language (null = auto-detect) |
| `default_output_dir` | enum | null | Output directory preference (null = ask each time) |
| `preferred_image_backend` | string | `auto` | Image backend selection. `auto` = prefer runtime-native tool, fall back to the only installed backend, ask if multiple non-native are present. `ask` = always confirm on every run. `<backend-id>` (e.g., `codex-imagegen`, `baoyu-imagine`, `image_generate`) = pin this backend when available; fall back to `auto` when it isn't. Absent = `auto`. Resolution logic is documented in `SKILL.md`'s `## Image Generation Tools` section. |
| `generation_batch_size` | int | 4 | Number of images to dispatch per batch when the backend has native batch support or the runtime can issue parallel generation calls. Clamp invalid values to 1-8. Current user request overrides this value. |
| `custom_styles` | array | [] | User-defined styles |
## Position Options
@@ -118,6 +121,8 @@ language: zh
preferred_image_backend: codex-imagegen
generation_batch_size: 4
custom_styles:
- name: corporate
description: "Professional B2B style"
@@ -18,6 +18,9 @@
# Specify density
/baoyu-article-illustrator path/to/article.md --density rich
# Generate up to 4 images in parallel after prompts are saved
/baoyu-article-illustrator path/to/article.md --batch-size 4
# Direct content input (paste mode)
/baoyu-article-illustrator
[paste content]
@@ -31,6 +34,7 @@
| `--style <name>` | Visual style (see references/styles.md) |
| `--preset <name>` | Shorthand for type + style combo (see [references/style-presets.md](references/style-presets.md)) |
| `--density <level>` | Image count: minimal / balanced / rich |
| `--batch-size <n>` | Temporary generation batch size for this run. Default: `generation_batch_size` from EXTEND.md, otherwise 4. Clamp to 1-8. |
## Input Modes
@@ -335,8 +335,11 @@ Prompt Files:
**DO NOT** pass ad-hoc inline text to `--prompt` without first saving prompt files. The generation command should either use `--promptfiles prompts/NN-{type}-{slug}.md` or read the saved file content for `--prompt`.
**Execution choice**:
- If multiple illustrations already have saved prompt files and the task is now plain generation, prefer the chosen backend's batch interface (if it offers one); otherwise generate sequentially
- Use subagents only when each illustration still needs separate prompt rewriting, style exploration, or other per-image reasoning before generation
- If multiple illustrations already have saved prompt files and the task is now plain generation, use batch generation by default.
- Prefer the chosen backend's native batch / multi-task interface when available.
- If the backend has no native batch interface but the runtime can issue parallel tool calls, dispatch up to `generation_batch_size` tasks at a time. Default: `4`. The current user request overrides EXTEND.md.
- Generate sequentially only when neither backend batch nor runtime parallel calls are available.
- Use subagents only when each illustration still needs separate prompt rewriting, style exploration, or other per-image reasoning before generation. Do not use subagents just to parallelize rendering.
**CRITICAL - References in Frontmatter**:
- Only add `references` field if files ACTUALLY EXIST in `references/` directory
@@ -394,12 +397,18 @@ Add: `Include a subtle watermark "[content]" at [position].`
### 5.5 Generate
1. For each illustration:
- **Backup rule**: If image file exists, rename to `NN-{type}-{slug}-backup-YYYYMMDD-HHMMSS.md`
- If references with `direct` usage: include `--ref` parameter
- Generate image
2. After each: "Generated X/N"
3. On failure: retry once, then log and continue
1. Build a generation task list from saved prompt files:
- `prompt_file`: `{output-dir}/prompts/NN-{type}-{slug}.md`
- `output_file`: `{output-dir}/NN-{type}-{slug}.png`
- `aspect_ratio`: from prompt frontmatter or prompt body
- `refs`: only verified `direct` references from prompt frontmatter
2. **Backup rule**: Before dispatching a task, if its output image already exists, rename it to `NN-{type}-{slug}-backup-YYYYMMDD-HHMMSS.{ext}`.
3. Dispatch tasks in batches:
- Native batch backend: send all eligible tasks, or chunks of `generation_batch_size` if the backend has a practical limit.
- Runtime parallel calls: issue up to `generation_batch_size` image calls concurrently, then continue with the next chunk.
- Sequential fallback: process one task at a time.
4. After each completed task, record: "Generated X/N: filename".
5. On failure: retry the failed task once from the same saved prompt file. Keep successful outputs and continue.
---
+24 -3
View File
@@ -1,7 +1,7 @@
---
name: baoyu-comic
description: Knowledge comic creator supporting multiple art styles and tones. Creates original educational comics with detailed panel layouts and sequential image generation. Use when user asks to create "知识漫画", "教育漫画", "biography comic", "tutorial comic", or "Logicomix-style comic".
version: 1.56.1
description: Knowledge comic creator supporting multiple art styles and tones. Creates original educational comics with detailed panel layouts and batch-capable image generation. Use when user asks to create "知识漫画", "教育漫画", "biography comic", "tutorial comic", or "Logicomix-style comic".
version: 1.57.0
metadata:
openclaw:
homepage: https://github.com/JimLiu/baoyu-skills#baoyu-comic
@@ -46,6 +46,23 @@ Setting `preferred_image_backend: ask` forces the step-3 prompt every run regard
Concrete tool names (`imagegen`, `image_generate`, `baoyu-imagine`) above are examples — substitute the local equivalents under the same rule.
## Batch Generation Policy
After every prompt file for the current generation group has been saved and verified, generate images in batches by default.
Priority order:
1. Use the chosen backend's native batch / multi-task interface if it exists. Each task must keep its own prompt file, output path, aspect ratio, session ID, and direct reference images.
2. If no native batch interface exists but the runtime can issue parallel tool calls, dispatch up to `generation_batch_size` images at a time. Default: `4`. An explicit user request in the current message, such as `--batch-size 4` or "并行4张一起生成", overrides EXTEND.md.
3. If neither native batch nor parallel tool calls are available, generate sequentially.
Rules:
- Honor workflow dependencies first: generate `characters/characters.png` before pages that use it as a reference.
- Never start the first page batch until all selected page prompt files exist on disk.
- Retry failed items once without regenerating successful items.
- Do not use subagents merely to parallelize image rendering. Use subagents only for separate prompt iteration or creative exploration.
## Reference Images
Users may supply reference images to guide art style, palette, scene composition, or subject. This is **separate from** the auto-generated character sheet (Step 7.1) — both can coexist: user refs guide the look, the character sheet anchors recurring character identity.
@@ -90,6 +107,7 @@ references:
| `--aspect` | 3:4 (default, portrait), 4:3 (landscape), 16:9 (widescreen) | Page aspect ratio |
| `--lang` | auto (default), zh, en, ja, etc. | Output language |
| `--ref <files...>` | File paths | Reference images applied to every page for style / palette / scene guidance. See [Reference Images](#reference-images) above. |
| `--batch-size <n>` | 1-8 | Temporary page generation batch size for this run. Default: `generation_batch_size` from EXTEND.md, otherwise 4. |
### Partial Workflow Options
@@ -237,6 +255,8 @@ Analyze → [Check Existing?] → [Confirm: Style + Reviews] → Storyboard →
| Exists | Not supported | Prepend character descriptions to every prompt file |
| Skipped | — | All descriptions inline in prompt |
**Execution strategy**: Generate the character sheet first when needed. Then build the selected page task list from saved prompt files and dispatch pages in batches per the `## Batch Generation Policy`: backend native batch first, runtime parallel tool calls second, sequential only as fallback. `--regenerate N` and `--images-only` apply the same batching rules to the selected existing prompts.
**Backup rule**: existing `prompts/…md` and `…png` files → rename with `-backup-YYYYMMDD-HHMMSS` suffix before regenerating. Aspect ratio from storyboard (default `3:4`; preset may override).
**`--ref` failure recovery**: compress sheet → retry → still fails → drop `--ref` and embed character descriptions in the prompt text.
@@ -257,7 +277,7 @@ If EXTEND.md is not found, first-time setup is **blocking** — complete it befo
| Found | Read, parse, display summary → continue |
| Not found | ⛔ Run first-time setup ([references/config/first-time-setup.md](references/config/first-time-setup.md)) → save EXTEND.md → continue |
**EXTEND.md supports**: watermark, preferred art/tone/layout, custom style definitions, character presets, language preference. Schema: [references/config/preferences-schema.md](references/config/preferences-schema.md).
**EXTEND.md supports**: watermark, preferred art/tone/layout, custom style definitions, character presets, language preference, preferred image backend, generation batch size. Schema: [references/config/preferences-schema.md](references/config/preferences-schema.md).
## References
@@ -316,4 +336,5 @@ EXTEND.md lives at `.baoyu-skills/baoyu-comic/EXTEND.md` (project) or `~/.baoyu-
- `preferred_image_backend: codex-imagegen` — pin to Codex's built-in.
- `preferred_image_backend: baoyu-imagine` — pin to the baoyu-imagine skill.
- `preferred_image_backend: ask` — confirm backend every run.
- `generation_batch_size: 4` — default number of page images to render concurrently when the backend/runtime supports batch or parallel generation.
- `watermark.enabled: true`, `preferred_art`, `preferred_tone`, `preferred_layout`, `language` — shift the auto-selection defaults and cosmetic choices.
@@ -143,12 +143,15 @@ preferred_layout: null
preferred_aspect: null
language: [selected or null]
preferred_image_backend: auto
generation_batch_size: 4
character_presets: []
---
```
`preferred_image_backend: auto` is the baked-in default — first-time setup does not ask about it. The `## Image Generation Tools` rule in SKILL.md then picks the runtime-native tool (Codex `imagegen`, Hermes `image_generate`, etc.) when available, and falls back to installed backends.
`generation_batch_size: 4` is the baked-in default for page batch rendering. The current user request may override it for one run.
## Modifying Preferences Later
See the `## Changing Preferences` section in `SKILL.md` for the canonical list of common edits (pin backend, change defaults, retrigger setup). Full schema: `config/preferences-schema.md`.
@@ -25,6 +25,8 @@ language: null # zh|en|ja|ko|auto
preferred_image_backend: auto # auto|ask|<backend-id>
generation_batch_size: 4 # 1-8, used when backend/runtime supports batch or parallel page generation
character_presets:
- name: my-characters
roles:
@@ -49,6 +51,7 @@ character_presets:
| `preferred_aspect` | string | null | Aspect ratio (3:4, 4:3, 16:9) |
| `language` | string | null | Output language (null = auto-detect) |
| `preferred_image_backend` | string | `auto` | Image backend selection. `auto` = prefer runtime-native tool, fall back to the only installed backend, ask if multiple non-native are present. `ask` = always confirm on every run. `<backend-id>` (e.g., `codex-imagegen`, `baoyu-imagine`, `image_generate`) = pin this backend when available; fall back to `auto` when it isn't. Absent = `auto`. Resolution logic is documented in `SKILL.md`'s `## Image Generation Tools` section. |
| `generation_batch_size` | int | 4 | Number of page images to dispatch per batch when the backend has native batch support or the runtime can issue parallel generation calls. Clamp invalid values to 1-8. Current user request overrides this value. |
| `character_presets` | array | [] | Preset character roles for styles like ohmsha |
## Art Style Options
@@ -127,6 +130,8 @@ language: zh
preferred_image_backend: codex-imagegen
generation_batch_size: 4
character_presets:
- name: tech-tutorial
roles:
+13 -6
View File
@@ -488,12 +488,19 @@ When character sheet was skipped or `--ref` failed:
- No `--ref` parameter needed
- Rely on detailed text descriptions for character consistency
**For each page (cover + pages)**:
1. Read prompt from `prompts/NN-{cover|page}-[slug].md`
2. **Backup rule**: If image file exists, rename to `NN-{cover|page}-[slug]-backup-YYYYMMDD-HHMMSS.png`
3. Generate image using Strategy A, B, or C
4. Save to `NN-{cover|page}-[slug].png`
5. Report progress after each generation: "Generated X/N: [page title]"
**Page batch generation (cover + pages)**:
1. Build a page task list from selected saved prompts:
- `prompt_file`: `prompts/NN-{cover|page}-[slug].md`
- `output_file`: `NN-{cover|page}-[slug].png`
- `aspect_ratio`: from storyboard (default `3:4`; preset may override)
- `refs`: character sheet and verified direct user refs when Strategy A is active
2. **Backup rule**: Before dispatching a task, if its image file exists, rename it to `NN-{cover|page}-[slug]-backup-YYYYMMDD-HHMMSS.png`.
3. Dispatch tasks in batches:
- Native batch backend: send all eligible page tasks, or chunks of `generation_batch_size` if the backend has a practical limit.
- Runtime parallel calls: issue up to `generation_batch_size` image calls concurrently, then continue with the next chunk.
- Sequential fallback: process one page at a time.
4. After each completed task, report: "Generated X/N: [page title]".
5. On failure, retry the failed task once from the same saved prompt file. Keep successful outputs and continue.
**Session Management**:
If image generation skill supports `--sessionId`:
+27 -9
View File
@@ -1,7 +1,7 @@
---
name: baoyu-image-cards
description: Generates infographic image card series with 12 visual styles, 8 layouts, and 3 color palettes. Breaks content into 1-10 cartoon-style image cards optimized for social media engagement. Use when user mentions "小红书图片", "小红书种草", "小绿书", "微信图文", "微信贴图", "image cards", "图片卡片", or wants social media infographic series.
version: 1.56.2
version: 1.57.0
metadata:
openclaw:
homepage: https://github.com/JimLiu/baoyu-skills#baoyu-image-cards
@@ -42,6 +42,23 @@ Setting `preferred_image_backend: ask` forces the step-3 prompt every run regard
Concrete tool names (`imagegen`, `image_generate`, `baoyu-imagine`) above are examples — substitute the local equivalents under the same rule.
## Batch Generation Policy
After every prompt file for the current generation group has been saved and verified, generate images in batches by default.
Priority order:
1. Use the chosen backend's native batch / multi-task interface if it exists. Each task must keep its own prompt file, output path, aspect ratio, session ID, and direct reference images.
2. If no native batch interface exists but the runtime can issue parallel tool calls, dispatch up to `generation_batch_size` images at a time. Default: `4`. An explicit user request in the current message, such as `--batch-size 4` or "并行4张一起生成", overrides EXTEND.md.
3. If neither native batch nor parallel tool calls are available, generate sequentially.
Rules:
- Honor the image-1 anchor chain: generate image 1 first, then batch images 2+ using image 1 as the reference.
- Never start a batch until every selected prompt file for that batch exists on disk.
- Retry failed items once without regenerating successful items.
- Do not use subagents merely to parallelize image rendering. Use subagents only for separate prompt iteration or creative exploration.
## Confirmation Policy
Default behavior: **confirm before generation**.
@@ -64,6 +81,7 @@ Respond in the user's language across questions, progress, errors, and completio
| `--palette <name>` | Color override: macaron / warm / neon |
| `--preset <name>` | Style + layout + optional palette shorthand (see Presets below; per-preset prompt fragments in `references/style-presets.md`) |
| `--ref <files...>` | Reference images applied to image 1 as the series anchor |
| `--batch-size <n>` | Temporary generation batch size for this run. Default: `generation_batch_size` from EXTEND.md, otherwise 4. Clamp to 1-8. |
| `--yes` | Non-interactive: skip all confirmations, use EXTEND.md or built-in defaults, auto-confirm recommended plan (Path A) |
## Dimensions
@@ -299,7 +317,7 @@ Check these paths in order; first hit wins:
- **Not found + interactive** → run first-time setup (see `references/config/first-time-setup.md`) and save before anything else. Do NOT analyze content or ask style questions until preferences exist — this keeps first-run behavior predictable.
- **Not found + `--yes`** → skip setup, use built-in defaults (no watermark, style/layout auto-selected, language from content). Do not prompt, do not create EXTEND.md.
**EXTEND.md keys**: watermark, preferred style/layout, custom style definitions, language preference. Schema: `references/config/preferences-schema.md`.
**EXTEND.md keys**: watermark, preferred style/layout, custom style definitions, language preference, preferred image backend, generation batch size. Schema: `references/config/preferences-schema.md`.
### Step 1: Analyze Content → `analysis.md`
@@ -348,14 +366,13 @@ With confirmed outline + style + layout + palette:
**Visual consistency — image-1 anchor chain**: character / mascot / color rendering drifts between calls unless you anchor them. Generate image 1 (cover) first WITHOUT `--ref`, then pass image 1 as `--ref` to every subsequent image. This is the single most important consistency trick for this skill — don't skip it even if the backend also supports a session ID.
For each image (cover, content, ending):
Generation flow:
1. Write the full prompt to `prompts/NN-{type}-{slug}.md` in the user's preferred language (backup rule applies).
2. Generate:
- **Image 1**: no `--ref` (establishes the anchor).
- **Images 2+**: add `--ref <path-to-image-01.png>`.
- Backup rule applies to the PNG files.
3. Report progress after each image.
1. Write the full prompt for every image to `prompts/NN-{type}-{slug}.md` in the user's preferred language (backup rule applies), then verify all selected prompt files exist.
2. Generate **image 1** first without `--ref`; backup rule applies to the PNG file. This establishes the anchor.
3. Build a task list for **images 2+** using image 1 as `--ref <path-to-image-01.png>`.
4. Dispatch images 2+ in batches per the `## Batch Generation Policy`: backend native batch first, runtime parallel tool calls second, sequential only as fallback.
5. Report progress after each completed image. On failure, retry only the failed item once from the same saved prompt file.
**Watermark** (if enabled in EXTEND.md): append to the generation prompt:
@@ -450,5 +467,6 @@ EXTEND.md lives at the first matching path listed in Step 0. Three ways to chang
- `preferred_image_backend: codex-imagegen` — pin to Codex's built-in.
- `preferred_image_backend: baoyu-imagine` — pin to the baoyu-imagine skill.
- `preferred_image_backend: ask` — confirm backend every run.
- `generation_batch_size: 4` — default number of images to render concurrently when the backend/runtime supports batch or parallel generation.
- `preferred_style: notion`, `preferred_layout: dense`, `preferred_palette: macaron`, `language: zh`.
- `watermark.enabled: true` + `watermark.content: "@handle"` — add a watermark.
@@ -111,12 +111,15 @@ preferred_style:
preferred_layout: null
language: null
preferred_image_backend: auto
generation_batch_size: 4
custom_styles: []
---
```
`preferred_image_backend: auto` is the baked-in default — first-time setup does not ask about it. The `## Image Generation Tools` rule in SKILL.md then picks the runtime-native tool (Codex `imagegen`, Hermes `image_generate`, etc.) when available, and falls back to installed backends.
`generation_batch_size: 4` is the baked-in default for batch rendering. The current user request may override it for one run.
## Modifying Preferences Later
See the `## Changing Preferences` section in `SKILL.md` for the canonical list of common edits (pin backend, change defaults, retrigger setup). Full schema: `preferences-schema.md`.
@@ -26,6 +26,8 @@ language: null # zh|en|ja|ko|auto
preferred_image_backend: auto # auto|ask|<backend-id>
generation_batch_size: 4 # 1-8, used when backend/runtime supports batch or parallel generation
custom_styles:
- name: my-style
description: "Style description"
@@ -52,6 +54,7 @@ custom_styles:
| `preferred_layout` | string | null | Layout preference or null |
| `language` | string | null | Output language (null = auto-detect) |
| `preferred_image_backend` | string | `auto` | Image backend selection. `auto` = prefer runtime-native tool, fall back to the only installed backend, ask if multiple non-native are present. `ask` = always confirm on every run. `<backend-id>` (e.g., `codex-imagegen`, `baoyu-imagine`, `image_generate`) = pin this backend when available; fall back to `auto` when it isn't. Absent = `auto`. Resolution logic is documented in `SKILL.md`'s `## Image Generation Tools` section. |
| `generation_batch_size` | int | 4 | Number of images to dispatch per batch when the backend has native batch support or the runtime can issue parallel generation calls. Clamp invalid values to 1-8. Current user request overrides this value. |
| `custom_styles` | array | [] | User-defined styles |
## Position Options
@@ -109,6 +112,8 @@ language: zh
preferred_image_backend: codex-imagegen
generation_batch_size: 4
custom_styles:
- name: corporate
description: "Professional B2B style"
+1 -1
View File
@@ -245,7 +245,7 @@ Files created:
|-------|-----|
| Missing API credentials | Follow guided setup in Step 2 |
| Access token error | Verify credentials valid and not expired |
| Not logged in (browser) | First run opens browser — scan QR to log in |
| Not logged in (browser) | First run opens browser — scan QR to log in. Set `TELEGRAM_BOT_TOKEN` + `TELEGRAM_CHAT_ID` to receive the QR image via Telegram |
| Chrome not found | Set `WECHAT_BROWSER_CHROME_PATH` |
| Title/summary missing | Use auto-generation or provide manually |
| No cover image | Add frontmatter cover or place `imgs/cover.png` in article directory |
@@ -0,0 +1,20 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const clipboardScript = fs.readFileSync(path.join(__dirname, "copy-to-clipboard.ts"), "utf8");
test("macOS image clipboard copy avoids Swift AppKit JIT", () => {
assert.match(clipboardScript, /copyImageMacWithOsascript/);
assert.doesNotMatch(clipboardScript, /await runCommand\('swift', \[swiftPath, 'image', imagePath\]\)/);
});
test("macOS image clipboard copy converts WebP to PNG before AppleScript", () => {
assert.match(clipboardScript, /convertWebpMacToPng/);
assert.match(clipboardScript, /path\.extname\(imagePath\)\.toLowerCase\(\) === '\.webp'/);
assert.match(clipboardScript, /await copyImageMacWithOsascript\(pngPath\)/);
});
@@ -1,9 +1,12 @@
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import decodeWebp, { init as initWebpDecode } from '@jsquash/webp/decode.js';
import { Jimp, JimpMime } from 'jimp';
const SUPPORTED_IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp']);
@@ -186,12 +189,73 @@ default:
`;
}
async function copyImageMac(imagePath: string): Promise<void> {
await withTempDir('copy-to-clipboard-', async (tempDir) => {
const swiftPath = path.join(tempDir, 'clipboard.swift');
await writeFile(swiftPath, getMacSwiftClipboardSource(), 'utf8');
await runCommand('swift', [swiftPath, 'image', imagePath]);
function escapeAppleScriptString(value: string): string {
return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
function getAppleScriptImageType(imagePath: string): string {
const ext = path.extname(imagePath).toLowerCase();
switch (ext) {
case '.png':
return '«class PNGf»';
case '.jpg':
case '.jpeg':
return 'JPEG picture';
case '.gif':
return 'GIF picture';
default:
throw new Error(`macOS clipboard image copy supports PNG, JPEG, and GIF via AppleScript; convert ${ext || 'this file'} to PNG first.`);
}
}
let webpDecoderReady: Promise<void> | undefined;
async function ensureWebpDecoder(): Promise<void> {
if (!webpDecoderReady) {
webpDecoderReady = (async () => {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const wasmPath = path.resolve(__dirname, 'node_modules/@jsquash/webp/codec/dec/webp_dec.wasm');
const wasmModule = await WebAssembly.compile(await readFile(wasmPath));
await initWebpDecode(wasmModule, {});
})();
}
await webpDecoderReady;
}
async function convertWebpMacToPng(webpPath: string, tempDir: string): Promise<string> {
await ensureWebpDecoder();
const decoded = await decodeWebp(await readFile(webpPath));
const image = new Jimp({
data: Buffer.from(decoded.data.buffer, decoded.data.byteOffset, decoded.data.byteLength),
width: decoded.width,
height: decoded.height,
});
const pngPath = path.join(tempDir, `${path.basename(webpPath, path.extname(webpPath))}.png`);
await writeFile(pngPath, await image.getBuffer(JimpMime.png));
return pngPath;
}
async function copyImageMacWithOsascript(imagePath: string): Promise<void> {
const imageType = getAppleScriptImageType(imagePath);
const escapedPath = escapeAppleScriptString(imagePath);
await runCommand('osascript', [
'-e',
`set the clipboard to (read (POSIX file "${escapedPath}") as ${imageType})`,
]);
}
async function copyImageMac(imagePath: string): Promise<void> {
if (path.extname(imagePath).toLowerCase() === '.webp') {
await withTempDir('copy-to-clipboard-', async (tempDir) => {
const pngPath = await convertWebpMacToPng(imagePath, tempDir);
await copyImageMacWithOsascript(pngPath);
});
return;
}
await copyImageMacWithOsascript(imagePath);
}
async function copyHtmlMac(htmlFilePath: string): Promise<void> {
@@ -377,4 +441,3 @@ await main().catch((err) => {
console.error(`Error: ${message}`);
process.exit(1);
});
@@ -0,0 +1,58 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const articleScript = fs.readFileSync(path.join(__dirname, "wechat-article.ts"), "utf8");
test("browser article paste uses CDP-targeted paste instead of global macOS keystrokes", () => {
assert.equal(
articleScript.includes('tell application "System Events" to keystroke "v" using command down'),
false,
);
});
test("browser article publishing verifies the title before saving drafts", () => {
assert.match(articleScript, /verifyTitleUnchangedBeforeSave/);
assert.match(articleScript, /Title was modified during paste/);
});
test("browser article body insertion does not paste HTML through the active form field", () => {
assert.match(articleScript, /insertHtmlIntoEditorFromFile/);
assert.doesNotMatch(articleScript, /await copyHtmlFromBrowser\(cdp, effectiveHtmlFile, contentImages\)/);
});
test("browser article body operations target the body ProseMirror, not the title ProseMirror", () => {
assert.match(articleScript, /BODY_EDITOR_SELECTOR = '\.rich_media_content \.ProseMirror'/);
assert.doesNotMatch(articleScript, /clickElement\(session, '\\.ProseMirror'\)/);
});
test("browser article reuses the selected account Chrome profile before launching", () => {
assert.match(articleScript, /await findExistingChromeDebugPort\(profileDir\)/);
});
test("browser article inserts inline images through WeChat local upload instead of clipboard paste", () => {
assert.match(articleScript, /uploadImageThroughFileInput/);
assert.match(articleScript, /DOM\.setFileInputFiles/);
assert.doesNotMatch(articleScript, /await copyImageToClipboard\(img\.localPath\)/);
});
test("browser article uploads original images before fallback processing", () => {
const rawUploadIndex = articleScript.indexOf("await uploadImagePathThroughFileInput(session, absolutePath, beforeCount)");
const fallbackIndex = articleScript.indexOf("const fallback = await prepareFallbackWechatBodyImageUpload(absolutePath)");
assert.notEqual(rawUploadIndex, -1);
assert.notEqual(fallbackIndex, -1);
assert.ok(rawUploadIndex < fallbackIndex);
assert.match(articleScript, /prepareWechatBodyImageUpload/);
assert.match(articleScript, /Raw image upload failed, retrying with fallback processing/);
});
test("browser article waits for a saved draft appmsgid before reporting success", () => {
assert.match(articleScript, /waitForDraftSaved/);
assert.match(articleScript, /appmsgid/);
assert.doesNotMatch(articleScript, /Waiting for save confirmation/);
});
@@ -1,12 +1,15 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { launchChrome, tryConnectExisting, findExistingChromeDebugPort, getPageSession, waitForNewTab, clickElement, typeText, evaluate, sleep, getAccountProfileDir, type ChromeSession, type CdpConnection } from './cdp.ts';
import { loadWechatExtendConfig, resolveAccount } from './wechat-extend-config.ts';
import { prepareWechatBodyImageUpload } from './wechat-image-processor.ts';
const WECHAT_URL = 'https://mp.weixin.qq.com/';
const BODY_EDITOR_SELECTOR = '.rich_media_content .ProseMirror';
interface ImageInfo {
placeholder: string;
@@ -31,7 +34,98 @@ interface ArticleOptions {
cdpPort?: number;
}
async function sendQrToTelegram(session: ChromeSession): Promise<void> {
const botToken = process.env.TELEGRAM_BOT_TOKEN;
const chatId = process.env.TELEGRAM_CHAT_ID;
if (!botToken || !chatId) return;
// Wait for QR to render before extracting
await sleep(2000);
try {
// Try to extract QR image from DOM first (avoids full-page screenshot noise)
const domResult = await session.cdp.send<{ result: { value: string } }>('Runtime.evaluate', {
expression: `
(function() {
const selectors = [
'.login__type__container__scan img',
'.login_img img',
'#login_container img',
'.qrcode img',
'img[src*="qrcode"]',
'img[src*="login"]',
];
for (const sel of selectors) {
const el = document.querySelector(sel);
if (el?.src && !el.src.startsWith('data:,')) return el.src.startsWith('data:') ? el.src : 'url:' + el.src;
}
const canvas = document.querySelector('canvas');
if (canvas) try { return canvas.toDataURL('image/png'); } catch {}
return '';
})()
`,
returnByValue: true,
}, { sessionId: session.sessionId });
const raw = (domResult.result.value as string) ?? '';
let imgBuffer: Buffer;
if (raw.startsWith('data:image')) {
imgBuffer = Buffer.from(raw.split(',')[1] ?? '', 'base64');
} else if (raw.startsWith('url:')) {
// Fetch inside Chrome to carry WeChat session cookies
const imgUrl = raw.slice(4);
const inBrowserFetch = await session.cdp.send<{ result: { value: string } }>('Runtime.evaluate', {
expression: `
(async () => {
const resp = await fetch(${JSON.stringify(imgUrl)}, { credentials: 'include' });
const buf = await resp.arrayBuffer();
const bytes = new Uint8Array(buf);
let b = '';
for (let i = 0; i < bytes.length; i++) b += String.fromCharCode(bytes[i]);
return btoa(b);
})()
`,
returnByValue: true,
awaitPromise: true,
}, { sessionId: session.sessionId });
imgBuffer = Buffer.from((inBrowserFetch.result.value as string) ?? '', 'base64');
} else {
// Fallback: viewport screenshot (smaller than full-page; QR is usually in viewport)
const screenshotResp = await session.cdp.send<{ data: string }>(
'Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, { sessionId: session.sessionId }
);
imgBuffer = Buffer.from(screenshotResp.data ?? '', 'base64');
}
const boundary = `tgboundary${Date.now()}`;
const parts: Buffer[] = [
Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="chat_id"\r\n\r\n${chatId}\r\n`),
Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="caption"\r\n\r\nWeChat QR code — please scan to log in\r\n`),
Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="photo"; filename="qr.png"\r\nContent-Type: image/png\r\n\r\n`),
imgBuffer,
Buffer.from(`\r\n--${boundary}--\r\n`),
];
const tgResp = await fetch(`https://api.telegram.org/bot${botToken}/sendPhoto`, {
method: 'POST',
headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },
body: Buffer.concat(parts),
signal: AbortSignal.timeout(10_000),
});
const tgJson = await tgResp.json() as { ok: boolean; description?: string };
if (tgJson.ok) {
console.log('[wechat] QR code sent to Telegram.');
} else {
console.error('[wechat] Telegram send failed:', tgJson.description);
}
} catch (err) {
console.error('[wechat] Failed to send QR to Telegram:', err);
}
}
async function waitForLogin(session: ChromeSession, timeoutMs = 120_000): Promise<boolean> {
// Notify via Telegram if configured (no-op when env vars absent)
await sendQrToTelegram(session);
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const url = await evaluate<string>(session, 'window.location.href');
@@ -105,27 +199,27 @@ async function pasteInEditor(session: ChromeSession): Promise<void> {
}
async function sendCopy(cdp?: CdpConnection, sessionId?: string): Promise<void> {
if (process.platform === 'darwin') {
if (cdp && sessionId) {
const modifiers = process.platform === 'darwin' ? 4 : 2;
await cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'c', code: 'KeyC', modifiers, windowsVirtualKeyCode: 67 }, { sessionId });
await sleep(50);
await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'c', code: 'KeyC', modifiers, windowsVirtualKeyCode: 67 }, { sessionId });
} else if (process.platform === 'darwin') {
spawnSync('osascript', ['-e', 'tell application "System Events" to keystroke "c" using command down']);
} else if (process.platform === 'linux') {
spawnSync('xdotool', ['key', 'ctrl+c']);
} else if (cdp && sessionId) {
await cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'c', code: 'KeyC', modifiers: 2, windowsVirtualKeyCode: 67 }, { sessionId });
await sleep(50);
await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'c', code: 'KeyC', modifiers: 2, windowsVirtualKeyCode: 67 }, { sessionId });
}
}
async function sendPaste(cdp?: CdpConnection, sessionId?: string): Promise<void> {
if (process.platform === 'darwin') {
spawnSync('osascript', ['-e', 'tell application "System Events" to keystroke "v" using command down']);
} else if (process.platform === 'linux') {
spawnSync('xdotool', ['key', 'ctrl+v']);
} else if (cdp && sessionId) {
await cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'v', code: 'KeyV', modifiers: 2, windowsVirtualKeyCode: 86 }, { sessionId });
await sleep(50);
await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'v', code: 'KeyV', modifiers: 2, windowsVirtualKeyCode: 86 }, { sessionId });
if (!cdp || !sessionId) {
throw new Error('Targeted paste requires a Chrome DevTools session');
}
const modifiers = process.platform === 'darwin' ? 4 : 2;
await cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'v', code: 'KeyV', modifiers, windowsVirtualKeyCode: 86 }, { sessionId });
await sleep(50);
await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'v', code: 'KeyV', modifiers, windowsVirtualKeyCode: 86 }, { sessionId });
}
async function copyHtmlFromBrowser(cdp: CdpConnection, htmlFilePath: string, contentImages: ImageInfo[] = []): Promise<void> {
@@ -203,6 +297,82 @@ async function pasteFromClipboardInEditor(session: ChromeSession): Promise<void>
await sleep(1000);
}
async function insertHtmlIntoEditorFromFile(
session: ChromeSession,
htmlFilePath: string,
contentImages: ImageInfo[] = [],
): Promise<void> {
const absolutePath = path.isAbsolute(htmlFilePath) ? htmlFilePath : path.resolve(process.cwd(), htmlFilePath);
const html = fs.readFileSync(absolutePath, 'utf8');
const replacements = contentImages.map(img => ({ placeholder: img.placeholder, localPath: img.localPath }));
const result = await session.cdp.send<{ result: { value: string } }>('Runtime.evaluate', {
expression: `
(function() {
const editor = document.querySelector(${JSON.stringify(BODY_EDITOR_SELECTOR)});
if (!editor) return JSON.stringify({ ok: false, reason: 'editor-missing' });
const template = document.createElement('template');
template.innerHTML = ${JSON.stringify(html)};
const replacements = ${JSON.stringify(replacements)};
for (const img of Array.from(template.content.querySelectorAll('img'))) {
const src = img.getAttribute('src') || '';
const localPath = img.getAttribute('data-local-path') || '';
const replacement = replacements.find((item) => item.placeholder === src || item.localPath === localPath);
if (replacement) {
img.replaceWith(document.createTextNode(replacement.placeholder));
}
}
const output = template.content.querySelector('#output');
const wrapper = document.createElement('div');
if (output) {
wrapper.innerHTML = output.innerHTML;
} else {
wrapper.appendChild(template.content.cloneNode(true));
}
editor.focus();
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(editor);
range.deleteContents();
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
const inserted = document.execCommand('insertHTML', false, wrapper.innerHTML);
editor.dispatchEvent(new InputEvent('input', {
bubbles: true,
inputType: 'insertHTML',
data: wrapper.innerText || ''
}));
return JSON.stringify({
ok: inserted || (editor.innerText || '').trim().length > 0,
textLength: (editor.innerText || '').trim().length
});
})()
`,
returnByValue: true,
}, { sessionId: session.sessionId });
const parsed = JSON.parse(result.result.value || '{}') as { ok?: boolean; reason?: string; textLength?: number };
if (!parsed.ok) {
throw new Error(`Failed to insert HTML into body editor${parsed.reason ? `: ${parsed.reason}` : ''}`);
}
}
async function verifyTitleUnchangedBeforeSave(session: ChromeSession, expectedTitle: string): Promise<void> {
if (!expectedTitle) return;
const actualTitle = await evaluate<string>(session, `document.querySelector('#title')?.value || ''`);
if (actualTitle !== expectedTitle) {
throw new Error(`Title was modified during paste. Expected: "${expectedTitle}", got: "${actualTitle}"`);
}
}
async function prepareEditorPasteTarget(
session: ChromeSession,
context: string,
@@ -212,19 +382,24 @@ async function prepareEditorPasteTarget(
await sleep(100);
if (options.clickEditor) {
await clickElement(session, '.ProseMirror');
await clickElement(session, BODY_EDITOR_SELECTOR);
await sleep(200);
}
const ready = await evaluate<boolean>(session, `
(function() {
const editor = document.querySelector('.ProseMirror');
const editor = document.querySelector(${JSON.stringify(BODY_EDITOR_SELECTOR)});
if (!editor) return false;
const active = document.activeElement;
const selection = window.getSelection();
const selectionInEditor = !!selection && selection.rangeCount > 0 && !!selection.anchorNode && editor.contains(selection.anchorNode);
const focusInEditor = !!active && (active === editor || editor.contains(active));
const activeIsUnsafeInput = !!active && (
active.matches?.('#title, #author, #js_description') ||
((active.tagName === 'INPUT' || active.tagName === 'TEXTAREA') && !editor.contains(active))
);
if (activeIsUnsafeInput) return false;
if (selectionInEditor || focusInEditor) return true;
if (${JSON.stringify(Boolean(options.clickEditor))}) {
@@ -347,7 +522,7 @@ async function selectAndReplacePlaceholder(session: ChromeSession, placeholder:
const result = await session.cdp.send<{ result: { value: boolean } }>('Runtime.evaluate', {
expression: `
(function() {
const editor = document.querySelector('.ProseMirror');
const editor = document.querySelector(${JSON.stringify(BODY_EDITOR_SELECTOR)});
if (!editor) return false;
const placeholder = ${JSON.stringify(placeholder)};
@@ -365,6 +540,7 @@ async function selectAndReplacePlaceholder(session: ChromeSession, placeholder:
// Exact match if next char is not a digit
if (charAfter === undefined || !/\\d/.test(charAfter)) {
node.parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
editor.focus();
const range = document.createRange();
range.setStart(node, idx);
@@ -395,7 +571,7 @@ async function pressDeleteKey(session: ChromeSession): Promise<void> {
async function removeExtraEmptyLineAfterImage(session: ChromeSession): Promise<boolean> {
const removed = await evaluate<boolean>(session, `
(function() {
const editor = document.querySelector('.ProseMirror');
const editor = document.querySelector(${JSON.stringify(BODY_EDITOR_SELECTOR)});
if (!editor) return false;
const sel = window.getSelection();
@@ -457,6 +633,188 @@ async function removeExtraEmptyLineAfterImage(session: ChromeSession): Promise<b
return removed;
}
async function getBodyImageCount(session: ChromeSession): Promise<number> {
return await evaluate<number>(session, `
(function() {
const editor = document.querySelector(${JSON.stringify(BODY_EDITOR_SELECTOR)});
if (!editor) return 0;
return Array.from(editor.querySelectorAll('img')).filter((img) => !img.classList.contains('ProseMirror-separator')).length;
})()
`);
}
async function waitForBodyImageCount(session: ChromeSession, minimumCount: number, timeoutMs = 45_000): Promise<boolean> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const count = await getBodyImageCount(session);
if (count >= minimumCount) return true;
await sleep(500);
}
return false;
}
function inferImageContentType(imagePath: string): string {
const ext = path.extname(imagePath).toLowerCase();
switch (ext) {
case '.jpg':
case '.jpeg':
return 'image/jpeg';
case '.png':
return 'image/png';
case '.gif':
return 'image/gif';
case '.webp':
return 'image/webp';
case '.bmp':
return 'image/bmp';
case '.svg':
return 'image/svg+xml';
default:
return 'application/octet-stream';
}
}
async function uploadImagePathThroughFileInput(
session: ChromeSession,
absolutePath: string,
beforeCount: number,
): Promise<void> {
const documentNode = await session.cdp.send<{ root: { nodeId: number } }>('DOM.getDocument', {
depth: -1,
pierce: true,
}, { sessionId: session.sessionId });
const inputNode = await session.cdp.send<{ nodeId: number }>('DOM.querySelector', {
nodeId: documentNode.root.nodeId,
selector: 'input[type="file"][accept*="image"]',
}, { sessionId: session.sessionId });
if (!inputNode.nodeId) throw new Error('WeChat local image upload input not found');
await session.cdp.send('DOM.setFileInputFiles', {
nodeId: inputNode.nodeId,
files: [absolutePath],
}, { sessionId: session.sessionId });
const inserted = await waitForBodyImageCount(session, beforeCount + 1);
if (!inserted) {
const afterCount = await getBodyImageCount(session);
throw new Error(`Image upload did not insert into editor: ${path.basename(absolutePath)} (${beforeCount} -> ${afterCount})`);
}
}
interface FallbackUploadImage {
uploadPath: string;
wasProcessed: boolean;
processingNotes: string[];
cleanup: () => void;
}
async function prepareFallbackWechatBodyImageUpload(absolutePath: string): Promise<FallbackUploadImage> {
const buffer = fs.readFileSync(absolutePath);
const prepared = await prepareWechatBodyImageUpload({
buffer,
filename: path.basename(absolutePath),
contentType: inferImageContentType(absolutePath),
fileExt: path.extname(absolutePath).toLowerCase(),
fileSize: buffer.length,
});
if (!prepared.wasProcessed) {
return {
uploadPath: absolutePath,
wasProcessed: false,
processingNotes: [],
cleanup: () => {},
};
}
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wechat-body-image-'));
const uploadPath = path.join(tempDir, prepared.filename);
fs.writeFileSync(uploadPath, prepared.buffer);
return {
uploadPath,
wasProcessed: true,
processingNotes: prepared.processingNotes,
cleanup: () => fs.rmSync(tempDir, { recursive: true, force: true }),
};
}
async function uploadImageThroughFileInput(session: ChromeSession, imagePath: string): Promise<void> {
const absolutePath = path.isAbsolute(imagePath) ? imagePath : path.resolve(process.cwd(), imagePath);
if (!fs.existsSync(absolutePath)) throw new Error(`Image file not found: ${absolutePath}`);
const beforeCount = await getBodyImageCount(session);
try {
await uploadImagePathThroughFileInput(session, absolutePath, beforeCount);
return;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (message.includes('local image upload input not found')) throw err;
const currentCount = await getBodyImageCount(session);
if (currentCount > beforeCount) return;
console.warn(`[wechat] Raw image upload failed, retrying with fallback processing: ${message}`);
const fallback = await prepareFallbackWechatBodyImageUpload(absolutePath);
const notes = fallback.processingNotes.length > 0 ? ` (${fallback.processingNotes.join('; ')})` : '';
console.log(`[wechat] Retrying image upload with ${fallback.wasProcessed ? 'processed' : 'original'} file: ${path.basename(fallback.uploadPath)}${notes}`);
try {
await uploadImagePathThroughFileInput(session, fallback.uploadPath, currentCount);
} finally {
fallback.cleanup();
}
}
}
interface DraftSaveStatus {
appmsgid: string;
isLoading: boolean;
submitText: string;
url: string;
messages: string[];
}
async function getDraftSaveStatus(session: ChromeSession): Promise<DraftSaveStatus> {
const raw = await evaluate<string>(session, `
(function() {
const submit = document.querySelector('#js_submit');
const button = submit?.querySelector('button');
const url = location.href;
const appmsgid = new URL(url).searchParams.get('appmsgid') || '';
const messages = Array.from(document.querySelectorAll('.weui-desktop-toast, .weui-desktop-toptips, .js_tips'))
.map((el) => (el.innerText || el.textContent || '').trim())
.filter(Boolean);
return JSON.stringify({
appmsgid,
isLoading: !!submit?.classList.contains('btn_loading') || !!button?.disabled,
submitText: (submit?.innerText || '').trim(),
url,
messages
});
})()
`);
return JSON.parse(raw || '{}') as DraftSaveStatus;
}
async function waitForDraftSaved(session: ChromeSession, timeoutMs = 60_000): Promise<string> {
const start = Date.now();
let lastStatus: DraftSaveStatus | null = null;
while (Date.now() - start < timeoutMs) {
lastStatus = await getDraftSaveStatus(session);
if (lastStatus.appmsgid && !lastStatus.isLoading) return lastStatus.appmsgid;
const relevantFailure = lastStatus.messages.find((message) => /保存.*失败|草稿.*失败|save.*fail/i.test(message));
if (relevantFailure) throw new Error(`Draft save failed: ${relevantFailure}`);
await sleep(1000);
}
throw new Error(`Draft save did not complete${lastStatus ? `: ${JSON.stringify(lastStatus)}` : ''}`);
}
export async function postArticle(options: ArticleOptions): Promise<void> {
const { title, content, htmlFile, markdownFile, theme, color, citeStatus = true, author, summary, images = [], submit = false, profileDir, cdpPort } = options;
let { contentImages = [] } = options;
@@ -500,7 +858,7 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
let chrome: ReturnType<typeof import('node:child_process').spawn> | null = null;
// Try connecting to existing Chrome: explicit port > auto-detect > launch new
const portToTry = cdpPort ?? await findExistingChromeDebugPort();
const portToTry = cdpPort ?? await findExistingChromeDebugPort(profileDir);
if (portToTry) {
const existing = await tryConnectExisting(portToTry);
if (existing) {
@@ -557,7 +915,8 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
const url = await evaluate<string>(session, 'window.location.href');
if (!url.includes('/cgi-bin/')) {
console.log('[wechat] Not logged in. Please scan QR code...');
const hasTelegram = !!(process.env.TELEGRAM_BOT_TOKEN && process.env.TELEGRAM_CHAT_ID);
console.log(`[wechat] Not logged in. Please scan QR code...${hasTelegram ? ' (sending to Telegram)' : ''}`);
const loggedIn = await waitForLogin(session);
if (!loggedIn) throw new Error('Login timeout');
}
@@ -588,7 +947,7 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
console.log('[wechat] Waiting for editor to load...');
const editorLoaded = await waitForElement(session, '#title', 30_000);
if (!editorLoaded) throw new Error('Editor did not load (#title not found)');
await waitForElement(session, '.ProseMirror', 15_000);
await waitForElement(session, BODY_EDITOR_SELECTOR, 15_000);
await sleep(2000);
if (effectiveTitle) {
@@ -613,25 +972,23 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
}
console.log('[wechat] Clicking on editor...');
await clickElement(session, '.ProseMirror');
await clickElement(session, BODY_EDITOR_SELECTOR);
await sleep(1000);
console.log('[wechat] Ensuring editor focus...');
await clickElement(session, '.ProseMirror');
await clickElement(session, BODY_EDITOR_SELECTOR);
await sleep(500);
if (effectiveHtmlFile && fs.existsSync(effectiveHtmlFile)) {
console.log(`[wechat] Copying HTML content from: ${effectiveHtmlFile}`);
await copyHtmlFromBrowser(cdp, effectiveHtmlFile, contentImages);
await sleep(500);
console.log(`[wechat] Inserting HTML content from: ${effectiveHtmlFile}`);
await prepareEditorPasteTarget(session, 'body content paste', { clickEditor: true });
console.log('[wechat] Pasting into editor...');
await pasteFromClipboardInEditor(session);
await insertHtmlIntoEditorFromFile(session, effectiveHtmlFile, contentImages);
await sleep(3000);
await verifyTitleUnchangedBeforeSave(session, effectiveTitle);
const editorHasContent = await evaluate<boolean>(session, `
(function() {
const editor = document.querySelector('.ProseMirror');
const editor = document.querySelector(${JSON.stringify(BODY_EDITOR_SELECTOR)});
if (!editor) return false;
const text = editor.innerText?.trim() || '';
return text.length > 0;
@@ -657,18 +1014,15 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
await sleep(500);
console.log(`[wechat] Copying image: ${path.basename(img.localPath)}`);
await copyImageToClipboard(img.localPath);
await sleep(300);
console.log('[wechat] Deleting placeholder with Backspace...');
await pressDeleteKey(session);
await sleep(200);
console.log('[wechat] Pasting image...');
await prepareEditorPasteTarget(session, 'inline image paste');
await pasteFromClipboardInEditor(session);
await sleep(3000);
console.log(`[wechat] Uploading image: ${path.basename(img.localPath)}`);
await prepareEditorPasteTarget(session, 'inline image upload');
await uploadImageThroughFileInput(session, img.localPath);
await sleep(1000);
await verifyTitleUnchangedBeforeSave(session, effectiveTitle);
await removeExtraEmptyLineAfterImage(session);
}
console.log('[wechat] All images inserted.');
@@ -676,12 +1030,10 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
} else if (content) {
for (const img of images) {
if (fs.existsSync(img)) {
console.log(`[wechat] Pasting image: ${img}`);
await copyImageToClipboard(img);
await sleep(500);
await prepareEditorPasteTarget(session, 'leading image paste');
await pasteInEditor(session);
await sleep(2000);
console.log(`[wechat] Uploading image: ${img}`);
await prepareEditorPasteTarget(session, 'leading image upload');
await uploadImageThroughFileInput(session, img);
await sleep(1000);
await removeExtraEmptyLineAfterImage(session);
}
}
@@ -693,7 +1045,7 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
const editorHasContent = await evaluate<boolean>(session, `
(function() {
const editor = document.querySelector('.ProseMirror');
const editor = document.querySelector(${JSON.stringify(BODY_EDITOR_SELECTOR)});
if (!editor) return false;
const text = editor.innerText?.trim() || '';
return text.length > 0;
@@ -730,17 +1082,12 @@ export async function postArticle(options: ArticleOptions): Promise<void> {
}
}
await verifyTitleUnchangedBeforeSave(session, effectiveTitle);
console.log('[wechat] Saving as draft...');
await evaluate(session, `document.querySelector('#js_submit button').click()`);
await sleep(3000);
const saved = await evaluate<boolean>(session, `!!document.querySelector('.weui-desktop-toast')`);
if (saved) {
console.log('[wechat] Draft saved successfully!');
} else {
console.log('[wechat] Waiting for save confirmation...');
await sleep(5000);
}
const appmsgid = await waitForDraftSaved(session);
console.log(`[wechat] Draft saved successfully! appmsgid: ${appmsgid}`);
console.log('[wechat] Done. Browser window left open.');
} finally {
+23 -3
View File
@@ -1,7 +1,7 @@
---
name: baoyu-slide-deck
description: Generates professional slide deck images from content. Creates outlines with style instructions, then generates individual slide images. Use when user asks to "create slides", "make a presentation", "generate deck", "slide deck", or "PPT".
version: 1.56.2
version: 1.57.0
metadata:
openclaw:
homepage: https://github.com/JimLiu/baoyu-skills#baoyu-slide-deck
@@ -46,6 +46,23 @@ Setting `preferred_image_backend: ask` forces the step-3 prompt every run regard
Concrete tool names (`imagegen`, `image_generate`, `baoyu-imagine`) above are examples — substitute the local equivalents under the same rule.
## Batch Generation Policy
After every prompt file for the current generation group has been saved and verified, generate slide images in batches by default.
Priority order:
1. Use the chosen backend's native batch / multi-task interface if it exists. Each task must keep its own prompt file, output path, aspect ratio, session ID, and direct reference images.
2. If no native batch interface exists but the runtime can issue parallel tool calls, dispatch up to `generation_batch_size` slide images at a time. Default: `4`. An explicit user request in the current message, such as `--batch-size 4` or "并行4张一起生成", overrides EXTEND.md.
3. If neither native batch nor parallel tool calls are available, generate sequentially.
Rules:
- Never start the first batch until all selected slide prompt files exist on disk.
- Retry failed items once without regenerating successful items.
- Do not use subagents merely to parallelize image rendering. Use subagents only for separate prompt iteration or creative exploration.
- Merge PPTX/PDF only after all selected slide images are generated.
## Confirmation Policy
Default behavior: **confirm before generation**.
@@ -77,6 +94,7 @@ Respond in the user's language across questions, progress reports, error message
| `--lang <code>` | Output language (en, zh, ja, ...) |
| `--slides <N>` | Target slide count (8-25 recommended, max 30) |
| `--ref <files...>` | Reference images applied per slide (style / palette / composition / subject) |
| `--batch-size <n>` | Temporary slide image generation batch size for this run. Default: `generation_batch_size` from EXTEND.md, otherwise 4. Clamp to 1-8. |
| `--outline-only` | Stop after outline |
| `--prompts-only` | Stop after prompts (skip image generation) |
| `--images-only` | Skip to Step 7; requires existing `prompts/` |
@@ -223,7 +241,7 @@ Copy this checklist and check off items as you complete them:
| `${XDG_CONFIG_HOME:-$HOME/.config}/baoyu-skills/baoyu-slide-deck/EXTEND.md` | XDG |
| `$HOME/.baoyu-skills/baoyu-slide-deck/EXTEND.md` | User home |
If found, read, parse, and print a summary (style / audience / language / review). If not, proceed with defaults — first-time setup is not blocking for this skill. Schema: `references/config/preferences-schema.md`.
If found, read, parse, and print a summary (style / audience / language / review / generation batch size). If not, proceed with defaults — first-time setup is not blocking for this skill. Schema: `references/config/preferences-schema.md`.
**1.2 Analyze content** — follow `references/analysis-framework.md`: classify content, detect language, note signals for style selection, estimate slide count from length (see the **Slide Count Heuristic** in Style System above), generate topic slug. Save source as `source.md` (honor backup rule if one exists).
@@ -279,7 +297,8 @@ Display the prompts index (`# | Filename | Slide Title`) and ask: proceed / edit
1. Resolve the image backend via the Image Generation Tools rule at the top — ask once if multiple are installed.
2. Confirm every `prompts/NN-slide-{slug}.md` exists (hard requirement; prompt files are the reproducibility record regardless of backend).
3. Session ID: `slides-{topic-slug}-{timestamp}` — pass to the backend only if it supports sessions.
4. For each slide: generate sequentially, reusing the session ID. Backup rule applies to PNG files. Report progress as `Generated X/N`. Auto-retry once on failure before reporting an error.
4. Build a task list for selected slides with each slide's prompt file, output PNG path, aspect ratio, session ID, and verified direct references.
5. Dispatch slide images in batches per the `## Batch Generation Policy`: backend native batch first, runtime parallel tool calls second, sequential only as fallback. Backup rule applies to PNG files before dispatch. Report progress as `Generated X/N`. Retry only failed items once before reporting an error.
`--regenerate N` jumps to this step for the named slides only. `--images-only` starts here with existing prompts.
@@ -352,4 +371,5 @@ EXTEND.md lives at the first matching path listed in Step 1.1. Two ways to chang
- `preferred_image_backend: codex-imagegen` — pin to Codex's built-in.
- `preferred_image_backend: baoyu-imagine` — pin to the baoyu-imagine skill.
- `preferred_image_backend: ask` — confirm backend every run.
- `generation_batch_size: 4` — default number of slide images to render concurrently when the backend/runtime supports batch or parallel generation.
- `preferred_style: blueprint`, `preferred_audience: experts`, `language: zh`.
@@ -13,6 +13,7 @@ audience: general # beginners | intermediate | experts | executives
language: auto # auto | en | zh | ja | etc.
review: true # true = review outline before generation
preferred_image_backend: auto # auto | ask | <backend-id>
generation_batch_size: 4 # 1-8, used when backend/runtime supports batch or parallel slide generation
## Custom Dimensions (only when style: custom)
dimensions:
@@ -42,6 +43,7 @@ custom_styles:
| `language` | string | `auto` | Output language (auto = detect from input) |
| `review` | boolean | `true` | Show outline review before generation |
| `preferred_image_backend` | string | `auto` | Image backend selection. `auto` = prefer runtime-native tool, fall back to the only installed backend, ask if multiple non-native are present. `ask` = always confirm on every run. `<backend-id>` (e.g., `codex-imagegen`, `baoyu-imagine`, `image_generate`) = pin this backend when available; fall back to `auto` when it isn't. Absent = `auto`. Resolution logic is documented in `SKILL.md`'s `## Image Generation Tools` section. |
| `generation_batch_size` | int | 4 | Number of slide images to dispatch per batch when the backend has native batch support or the runtime can issue parallel generation calls. Clamp invalid values to 1-8. Current user request overrides this value. |
### Custom Dimensions
+12 -4
View File
@@ -97,9 +97,10 @@ For option 2, scan the sessions for any private/group thread the user has sent i
- `self_wxid` (e.g., `wxid_abc123`) — fall-back hint: the user can find it with `wx contacts --query "<own nickname>"`, or by inspecting any of their own sent messages in `wx sessions --json`
- `self_display` (e.g., `宝玉`) — how they want their messages attributed
- `default_version` — pick one of `normal` / `roast` / `both`
- `data_root` — where digest folders live. Default: `{project_root}/wechat`. Enter a custom absolute path (e.g. `~/Documents/wechat-digests`) or leave blank for default.
- Save location — pick one of project / XDG / home
Write EXTEND.md to the chosen path, confirm "Preferences saved to [path]. Edit it any time to change defaults.", then continue with the digest workflow.
Write EXTEND.md to the chosen path. If the user provided a non-default `data_root`, include it as an uncommented line; otherwise omit it (the default applies automatically). Confirm "Preferences saved to [path]. Edit it any time to change defaults.", then continue with the digest workflow.
## Workflow
@@ -285,6 +286,13 @@ The `imgs/` directory exists as an **extension point**: a user (or a future wx-c
- Callback past quotes ("继上次'要不要买 moderna'之后,这次又...")
- Don't sacrifice current material to force a callback.
**Roast pass — profile usage extras** (only when generating the roast version):
- 历史槽点可做 callback joke
- Running gag 可以升级和迭代
- 历史毒舌语录可以引用或翻新
- 但当期素材优先,不要为了 callback 硬凑
**Writing order**: write the body categories first, then the opening overview based on the finished body (so the hook is accurate).
Detailed structure, voice, formatting rules, and content guidelines are in [references/output-formats.md](references/output-formats.md). Load that file now if not already loaded.
@@ -324,8 +332,8 @@ Always reflects only the most recent normal digest. Overwrite on each run when `
```json
{
"group_id": "12345678901@chatroom",
"group_name": "消失的大叔",
"folder": "12345678901@chatroom-消失的大叔",
"group_name": "相亲相爱一家人",
"folder": "12345678901@chatroom-相亲相爱一家人",
"last_digest": {
"file": "2026-03-12.md",
"date_range": "2026-03-12",
@@ -392,7 +400,7 @@ Full procedure in [references/profiles.md](references/profiles.md).
```
{data_root}/ # default: {project_root}/wechat/
└── {group_id}-{group_name}/ # e.g. 12345678901@chatroom-消失的大叔/
└── {group_id}-{group_name}/ # e.g. 12345678901@chatroom-相亲相爱一家人/
├── history.json # last digest pointer (fast)
├── history-digests.jsonl # append-only archive
├── 2026-03-12.md # normal digest, single date
@@ -130,103 +130,27 @@ No date, no signature, no version number.
## 2. Roast version (毒舌版)
The roast version mirrors the normal version's structure but inverts the tone. Generate only when `include_roast=true` (configured via EXTEND.md `default_version` or triggered by request keywords like 毒舌/roast/挑衅).
Roast 版基于普通版的话题骨架和素材,用毒舌、尖锐、挑衅的风格重写。整体结构与普通版相同(统计区块、开头概览、群友画像、正文分类、结尾),但风格完全不同。痛点部分省略。仅当 `include_roast=true` 时生成。标题加 "毒舌版" 后缀。
### 2.1 Structural parity
风格要求:
- 你是一位以尖锐和挑衅风格著称的专业评论员
- 对每个群友的行为、言论进行犀利点评,不怕让人尴尬
- 发言排行旁给每个人加一句毒舌备注(括号内)
- 群友画像改为「不留情面版」,放大每个人的槽点和矛盾之处
- 开头概览用更戏谑的口吻,突出荒诞和讽刺
- 正文话题标题可以改得更损
- 引用原话时配上辛辣点评
- 结尾改为:本简报由一个没有感情的 AI 自动生成,如有冒犯,概不负责
```
[Title line — adds "毒舌版" suffix]
[📊 Stats block — each leaderboard row gets a roast comment]
[Opening summary — absurd recap, sarcastic]
[群友画像 — 不留情面版]
[Categorized body — louder, more brutal category titles]
[Fixed footer — roast version]
```
注意:毒舌但不恶毒,调侃但不人身攻击。目标是让群友看了会笑,而不是生气。具体红线:
- 只嘲讽群里的公开行为,不碰外貌、体重、健康、家庭、私人关系
- 不用时间戳推断作息或时区(服务器时间不等于本地时间)
- 不做医学/心理诊断类玩笑(「这位需要看医生」「典型 ADHD」)
- 不揣测对方未主动公开的身份属性(性取向、宗教、政治立场)
- 嘲讽观点本身,不嘲讽发言的权利(「这个观点错得离谱」可以,「连这都不懂还敢发言」不行)
- 如果某人本期没有槽点(3+ 条但都很中性),给一句温和调侃即可,不要硬凑
Pain-point section is **dropped** in the roast version.
### 2.2 Title line
Form: `{群名} 群聊精华 · {日期} · 毒舌版`
Example: `相亲相爱一家人 群聊精华 · 2026-03-12 · 毒舌版`
### 2.3 Statistics block (roast)
- Same `📊 消息统计: 共 N 条消息` opener.
- Leaderboard: each row gets a parenthetical roast comment.
- Form: `{排名}. {昵称}: {消息数} 条 ({一句毒舌评语})`
Example:
```
📊 消息统计: 共 387 条消息
1. 蛙总: 92 条 (一个人撑起了空头的体面)
2. 老王: 58 条 (主要功能是给蛙总当反例)
3. 阿喵: 41 条 (发的链接比发的话还多)
```
### 2.4 Opening summary (roast)
- 1-2 paragraphs, sarcastic recap tone.
- Highlight the day's most ridiculous beat (a failed prediction, a heated argument over something trivial, a wild flex).
- Reference 2-3 of the roast category titles in the prose.
### 2.5 群友画像 (roast — 不留情面版)
- Same per-user entry format as normal, but with the role tag dialed up.
- Amplify quirks, contradictions, fail moments visible in the messages.
- 2-5 bullets with `•`. Each bullet is a roastable observation backed by a direct quote.
- Don't invent — every roast must trace back to something the person actually said in the batch (or in the loaded roast profile from prior batches).
Example:
```
群友画像
蛙总(做空美股钉子户,三周亏损不改其志)
• 今天第 47 次预测 SPY 见顶,给出的理由是"我感觉"
• 被老王翻出上周聊天记录后嘴硬:「上周的不算,那是市场不理性」
• 收盘前突然安静,疑似刚看完账户
```
### 2.6 Categorized body (roast)
- Same 3-6 category structure.
- Titles can be louder, more brutal, mock-headline style.
- Examples of acceptable roast titles:
- `蛙总做空翻车: 一个人对抗整个美股`
- `老王再次试图当人生导师, 群友集体打哈欠`
- `阿喵又分享了一篇没人读完的长文`
- Bodies still preserve real quotes and traceability — sarcasm is in framing, not fabrication.
### 2.7 Footer (roast)
Fixed line, last in file:
```
本简报由一个没有感情的 AI 自动生成,如有冒犯,概不负责
```
### 2.8 Red lines (non-negotiable)
These rules override style; violate them and the roast becomes harmful. Write the spicy version first, then audit against this list and rewrite anything that crosses a line.
- **Mock public group behavior only.** Never appearance, weight, body, health, mental state, family, relationships (unless openly group-discussed at the person's own initiative), finances beyond what they publicly mention.
- **调侃 ≠ 人身攻击。** Readers should laugh at the situation, not feel sorry for the target. If you can't think of a joke that doesn't read as cruel, drop the bullet.
- **No timestamp-based sleep/timezone jokes.** Server time ≠ recipient's local time; also implies surveillance. Forbidden: `凌晨 3 点还在群里发言,怕是没睡好`, `这位是哪个时区的`, etc.
- **No medical/psychological speculation.** Even joking diagnoses (`这位需要看医生`, `典型 ADHD`) are out.
- **No outing.** Don't infer identity attributes the person hasn't volunteered (orientation, religion, politics beyond direct quotes).
- **Roast the take, not the person's right to have a take.** `这个观点错得离谱` is fine. `连这都不懂还敢发言` is not.
If a target hasn't said anything roastable in this batch (3+ messages but all neutral), give them a one-line affectionate ribbing and move on. Don't manufacture conflict.
### 2.9 Writing order
1. Draft the spicy version freely — don't self-censor mid-sentence.
2. After the body is complete, do a separate audit pass against §2.8.
3. Rewrite or delete any line that crosses a red line.
4. Then read the whole thing once more for tone calibration: is it fun, or is it mean?
**写作顺序:** 先放开写最狠的版本,写完再回头检查红线。不要边写边自我审查,那样只会写出温吞水。
---
@@ -345,5 +269,5 @@ Before writing the digest file, mentally walk through:
6. Every quote uses 「」 and is traceable to a real message?
7. Links inline and complete?
8. No markdown bold/heading/link syntax leaked through?
9. (Roast only) Every roast bullet would pass the §2.8 red-line audit?
9. (Roast only) Every roast bullet would pass the §2 红线 audit?
10. Footer line exact match?
+27 -9
View File
@@ -1,7 +1,7 @@
---
name: baoyu-xhs-images
description: "[Deprecated: use baoyu-image-cards] Generates Xiaohongshu (Little Red Book) image card series with 12 visual styles, 8 layouts, and 3 color palettes. Breaks content into 1-10 cartoon-style image cards optimized for XHS engagement. Use when user mentions \"小红书图片\", \"XHS images\", \"RedNote infographics\", \"小红书种草\", \"小绿书\", \"微信图文\", \"微信贴图\", or wants social media infographic series for Chinese platforms."
version: 1.56.2
version: 1.57.0
metadata:
openclaw:
homepage: https://github.com/JimLiu/baoyu-skills#baoyu-xhs-images
@@ -43,6 +43,23 @@ Setting `preferred_image_backend: ask` forces the step-3 prompt every run regard
Concrete tool names (`imagegen`, `image_generate`, `baoyu-imagine`) above are examples — substitute the local equivalents under the same rule.
## Batch Generation Policy
After every prompt file for the current generation group has been saved and verified, generate images in batches by default.
Priority order:
1. Use the chosen backend's native batch / multi-task interface if it exists. Each task must keep its own prompt file, output path, aspect ratio, session ID, and direct reference images.
2. If no native batch interface exists but the runtime can issue parallel tool calls, dispatch up to `generation_batch_size` images at a time. Default: `4`. An explicit user request in the current message, such as `--batch-size 4` or "并行4张一起生成", overrides EXTEND.md.
3. If neither native batch nor parallel tool calls are available, generate sequentially.
Rules:
- Honor the image-1 anchor chain: generate image 1 first, then batch images 2+ using image 1 as the reference.
- Never start a batch until every selected prompt file for that batch exists on disk.
- Retry failed items once without regenerating successful items.
- Do not use subagents merely to parallelize image rendering. Use subagents only for separate prompt iteration or creative exploration.
## Confirmation Policy
Default behavior: **confirm before generation**.
@@ -65,6 +82,7 @@ Respond in the user's language across questions, progress, errors, and completio
| `--palette <name>` | Color override: macaron / warm / neon |
| `--preset <name>` | Style + layout + optional palette shorthand (see Presets below; per-preset prompt fragments in `references/style-presets.md`) |
| `--ref <files...>` | Reference images applied to image 1 as the series anchor |
| `--batch-size <n>` | Temporary generation batch size for this run. Default: `generation_batch_size` from EXTEND.md, otherwise 4. Clamp to 1-8. |
| `--yes` | Non-interactive: skip all confirmations, use EXTEND.md or built-in defaults, auto-confirm recommended plan (Path A) |
## Dimensions
@@ -300,7 +318,7 @@ Check these paths in order; first hit wins:
- **Not found + interactive** → run first-time setup (see `references/config/first-time-setup.md`) and save before anything else. Do NOT analyze content or ask style questions until preferences exist — this keeps first-run behavior predictable.
- **Not found + `--yes`** → skip setup, use built-in defaults (no watermark, style/layout auto-selected, language from content). Do not prompt, do not create EXTEND.md.
**EXTEND.md keys**: watermark, preferred style/layout, custom style definitions, language preference. Schema: `references/config/preferences-schema.md`.
**EXTEND.md keys**: watermark, preferred style/layout, custom style definitions, language preference, preferred image backend, generation batch size. Schema: `references/config/preferences-schema.md`.
### Step 1: Analyze Content → `analysis.md`
@@ -349,14 +367,13 @@ With confirmed outline + style + layout + palette:
**Visual consistency — image-1 anchor chain**: character / mascot / color rendering drifts between calls unless you anchor them. Generate image 1 (cover) first WITHOUT `--ref`, then pass image 1 as `--ref` to every subsequent image. This is the single most important consistency trick for this skill — don't skip it even if the backend also supports a session ID.
For each image (cover, content, ending):
Generation flow:
1. Write the full prompt to `prompts/NN-{type}-{slug}.md` in the user's preferred language (backup rule applies).
2. Generate:
- **Image 1**: no `--ref` (establishes the anchor).
- **Images 2+**: add `--ref <path-to-image-01.png>`.
- Backup rule applies to the PNG files.
3. Report progress after each image.
1. Write the full prompt for every image to `prompts/NN-{type}-{slug}.md` in the user's preferred language (backup rule applies), then verify all selected prompt files exist.
2. Generate **image 1** first without `--ref`; backup rule applies to the PNG file. This establishes the anchor.
3. Build a task list for **images 2+** using image 1 as `--ref <path-to-image-01.png>`.
4. Dispatch images 2+ in batches per the `## Batch Generation Policy`: backend native batch first, runtime parallel tool calls second, sequential only as fallback.
5. Report progress after each completed image. On failure, retry only the failed item once from the same saved prompt file.
**Watermark** (if enabled in EXTEND.md): append to the generation prompt:
@@ -451,5 +468,6 @@ EXTEND.md lives at the first matching path listed in Step 0. Three ways to chang
- `preferred_image_backend: codex-imagegen` — pin to Codex's built-in.
- `preferred_image_backend: baoyu-imagine` — pin to the baoyu-imagine skill.
- `preferred_image_backend: ask` — confirm backend every run.
- `generation_batch_size: 4` — default number of images to render concurrently when the backend/runtime supports batch or parallel generation.
- `preferred_style: notion`, `preferred_layout: dense`, `preferred_palette: macaron`, `language: zh`.
- `watermark.enabled: true` + `watermark.content: "@handle"` — add a watermark.
@@ -111,12 +111,15 @@ preferred_style:
preferred_layout: null
language: null
preferred_image_backend: auto
generation_batch_size: 4
custom_styles: []
---
```
`preferred_image_backend: auto` is the baked-in default — first-time setup does not ask about it. The `## Image Generation Tools` rule in SKILL.md then picks the runtime-native tool (Codex `imagegen`, Hermes `image_generate`, etc.) when available, and falls back to installed backends.
`generation_batch_size: 4` is the baked-in default for batch rendering. The current user request may override it for one run.
## Modifying Preferences Later
See the `## Changing Preferences` section in `SKILL.md` for the canonical list of common edits (pin backend, change defaults, retrigger setup). Full schema: `preferences-schema.md`.
@@ -26,6 +26,8 @@ language: null # zh|en|ja|ko|auto
preferred_image_backend: auto # auto|ask|<backend-id>
generation_batch_size: 4 # 1-8, used when backend/runtime supports batch or parallel generation
custom_styles:
- name: my-style
description: "Style description"
@@ -52,6 +54,7 @@ custom_styles:
| `preferred_layout` | string | null | Layout preference or null |
| `language` | string | null | Output language (null = auto-detect) |
| `preferred_image_backend` | string | `auto` | Image backend selection. `auto` = prefer runtime-native tool, fall back to the only installed backend, ask if multiple non-native are present. `ask` = always confirm on every run. `<backend-id>` (e.g., `codex-imagegen`, `baoyu-imagine`, `image_generate`) = pin this backend when available; fall back to `auto` when it isn't. Absent = `auto`. Resolution logic is documented in `SKILL.md`'s `## Image Generation Tools` section. |
| `generation_batch_size` | int | 4 | Number of images to dispatch per batch when the backend has native batch support or the runtime can issue parallel generation calls. Clamp invalid values to 1-8. Current user request overrides this value. |
| `custom_styles` | array | [] | User-defined styles |
## Position Options
@@ -109,6 +112,8 @@ language: zh
preferred_image_backend: codex-imagegen
generation_batch_size: 4
custom_styles:
- name: corporate
description: "Professional B2B style"