Compare commits

...

9 Commits

Author SHA1 Message Date
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
24 changed files with 661 additions and 99 deletions
+1 -1
View File
@@ -6,7 +6,7 @@
},
"metadata": {
"description": "Skills shared by Baoyu for improving daily work efficiency",
"version": "1.116.5"
"version": "1.117.0"
},
"plugins": [
{
+9
View File
@@ -2,6 +2,15 @@
English | [中文](./CHANGELOG.zh.md)
## 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
+9
View File
@@ -2,6 +2,15 @@
[English](./CHANGELOG.md) | 中文
## 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
### 新功能
+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"
@@ -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;
@@ -196,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> {
@@ -294,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,
@@ -303,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))}) {
@@ -438,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)};
@@ -456,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);
@@ -486,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();
@@ -548,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;
@@ -591,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) {
@@ -680,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) {
@@ -705,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;
@@ -749,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.');
@@ -768,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);
}
}
@@ -785,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;
@@ -822,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
+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"