Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(plugins): Agent 现在能生成图片了,一句话一张图落在工作区

lmlihengde544bb47b0d
diff --git a/README.md b/README.md
index 4271656c..61e14533 100644
--- a/README.md
+++ b/README.md
@@ -96,7 +96,7 @@ optimise its own Skills:
| Category | Plugins |
| --- | --- |
-| Office Productivity | `data-analysis`, `use-firecrawl`, `use-offerdao`, `browser-automation`, `use-bento-slides`, `use-lieflat-charts`, `use-wps-office`, `use-seedance`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` |
+| Office Productivity | `data-analysis`, `use-firecrawl`, `use-offerdao`, `browser-automation`, `use-bento-slides`, `use-lieflat-charts`, `use-wps-office`, `use-seedance`, `use-seedream`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` |
| Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram` |
| AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` |
| Agent Company | `agent-company` |
diff --git a/README.zh.md b/README.zh.md
index 9d82bb07..72864f93 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -82,7 +82,7 @@ Adelie 运行在你的电脑或服务器上,自动串联 Agent 应用的创建
| 分类 | 插件 |
| ----------- | ------------------------------------------------------------------------------- |
-| 办公效率 | `data-analysis`、`use-firecrawl`、`use-offerdao`、`browser-automation`、`use-bento-slides`、`use-lieflat-charts`、`use-wps-office`、`use-seedance`、`humanizer`、`goal`、`continual-learning`、`csu-mail`、`lesson-video`、`requirements-box` |
+| 办公效率 | `data-analysis`、`use-firecrawl`、`use-offerdao`、`browser-automation`、`use-bento-slides`、`use-lieflat-charts`、`use-wps-office`、`use-seedance`、`use-seedream`、`humanizer`、`goal`、`continual-learning`、`csu-mail`、`lesson-video`、`requirements-box` |
| 软件开发 | `software-development`、`use-claude-code`、`wechat-miniprogram` |
| AI 应用开发 | `agent-development`、`model-development`、`skill-porting`、`agent-tuning` |
| Agent 公司 | `agent-company` |
diff --git a/changelog/unreleased/2026-10-28-use-seedream.md b/changelog/unreleased/2026-10-28-use-seedream.md
new file mode 100644
index 00000000..33cba367
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-use-seedream.md
@@ -0,0 +1,52 @@
+# Agents can generate images: one command, a picture in the workspace
+
+- **Date:** 2026-10-28
+- **Type:** feat
+- **Scope:** `plugins`, `core`, `docs`
+- **Breaking:** no
+
+[中文](2026-10-28-use-seedream.zh.md)
+
+Adelie could make a video but not a picture: Ark's image generation (Seedream) was left out of the model
+catalog because a Session cannot hold a conversation on it, and no plugin covered the gap. The new
+`use-seedream` plugin fills it — one dependency-free Node script that turns a prompt into images and
+saves them into the workspace, next to the `use-seedance` the video side already had.
+
+The same command also covers what makes the Seedream family interesting: up to 14 reference images (a
+local file is inlined, so nothing has to be uploaded first), a group of up to 15 images in one request,
+a **layer split** — one backdrop plus up to 16 individually editable transparent PNG layers, with each
+layer's `z_index`, name and bounding box reported back — and transparent backgrounds.
+
+## Details
+
+- `plugins/use-seedream/skills/seedream/kit/seedream.mjs` (new): the runner. One synchronous
+ `POST {base}/images/generations`, options sent only when given (`size`, `sequential_image_generation`,
+ `layer_decomposition`, `background`, `output_format`, `seed`, `watermark`), images downloaded from the
+ answer's URL or decoded from `b64_json`, every file written through `<name>.part-<pid>` and renamed only
+ once complete. A `WxH` size is checked locally against the service's pixel window (1280×720 …
+ 4096×4096) so a bad one is a usage error, not a 400 from the API. Exit codes match the video plugin:
+ `0` saved, `2` bad command line, `3` no `ARK_API_KEY`, `4` the API refused (its own text in `upstream`,
+ `ModelNotOpen` included), `7` an image did not download.
+- A multi-image answer makes `--out` a directory and names files `<NNN>-z<z_index>-<name>.<ext>` — a
+ running number for order, the stacking index when the service gives one, the cleaned-up name it
+ reported (`base` / `layer` when it reported none). Layers are always PNG.
+- `plugins/use-seedream/skills/seedream/SKILL.md` (new): when to use it, the cost warning (a group or a
+ layer split is several billed images), the credential check, and the note that Markdown image syntax
+ does not resolve in the chat — results are handed over as workspace paths.
+- `plugins/use-seedream/{plugin.json,README.md,icon.svg,LICENSE,package.json}` (new): packaged and
+ described like `use-seedance`, `category: office-productivity`.
+- `packages/{core,cli,desktop}/package.json` + `pnpm-lock.yaml`: `@adelie/use-seedream: workspace:*`, so
+ the plugin is preinstalled like the video one.
+- `packages/core/test/plugins.test.ts`: the plugin list gains `use-seedream` (and the count moves to 23);
+ `plugins/README.md`, `README.md`, `README.zh.md` and `packages/docs/content/skills.{zh,en}.md` carry its
+ one-line entry, which the repository's own tables are checked against.
+- `plugins/use-seedream/test/seedream.test.mjs` (new): 10 cases against a local stub — the missing key,
+ a single download, a group request's body, a layer split's naming and `layers[]`, a local reference
+ image inlined as a data URL, a `b64_json` answer, bad flags, and the service's own words on a refusal.
+
+## Compatibility
+
+- Nothing existing changed shape: a new plugin, one more name in the plugin lists.
+- The default model is `doubao-seedream-5-0-pro-260628`; another Seedream id goes in with `--model`.
+- The live API has not been called yet: the Ark account in this vault has that model **not activated**
+ (`ModelNotOpen`), so everything above is verified against the stub, not against the service.
diff --git a/changelog/unreleased/2026-10-28-use-seedream.zh.md b/changelog/unreleased/2026-10-28-use-seedream.zh.md
new file mode 100644
index 00000000..112ea05e
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-use-seedream.zh.md
@@ -0,0 +1,47 @@
+# Agent 能生成图片了:一句话,一张图落在工作区里
+
+- **Date:** 2026-10-28
+- **Type:** feat
+- **Scope:** `plugins`, `core`, `docs`
+- **Breaking:** no
+
+[English](2026-10-28-use-seedream.md)
+
+之前 Adelie 能出视频,却出不了图:方舟的图像生成(Seedream)不是对话模型、进不了模型库,插件里也没有
+对应的一条。新插件 `use-seedream` 把这个缺口补上了 —— 一个零依赖的 Node 脚本,把提示词变成图片并落到
+工作区,和视频那边的 `use-seedance` 并排。
+
+同一个命令还覆盖了 Seedream 这家真正有意思的部分:最多 14 张参考图(本机文件直接内联,不用先传上去)、
+一次最多 15 张的组图、**图层拆分**(1 张底图 + 最多 16 个可单独编辑的透明 PNG 图层,每层的 `z_index`、
+名称和边界框都会回报),以及透明背景。
+
+## 细节
+
+- `plugins/use-seedream/skills/seedream/kit/seedream.mjs`(新增):一次同步的
+ `POST {base}/images/generations`,只发用到的参数(`size`、`sequential_image_generation`、
+ `layer_decomposition`、`background`、`output_format`、`seed`、`watermark`),按回答里的 URL 下载
+ 或用 `b64_json` 解码,每个文件先写 `<name>.part-<pid>` 再改名 —— 半截的图不会顶替最终文件名。
+ `WxH` 尺寸在本地按服务的像素区间(1280×720 … 4096×4096)先校一遍,写错算命令行错,而不是让服务回
+ 一个 400。退出码沿用视频插件:`0` 成功、`2` 命令行不对、`3` 缺 `ARK_API_KEY`、`4` 接口拒绝(服务原话
+ 在 `upstream` 里,含 `ModelNotOpen`)、`7` 图没下下来。
+- 多图时 `--out` 当目录,文件名是 `<NNN>-z<z_index>-<名称>.<扩展名>`:序号管顺序,有层序就带上,名称用
+ 服务给的那个(没有就用 `base` / `layer`)。图层恒为 PNG。
+- `plugins/use-seedream/skills/seedream/SKILL.md`(新增):什么时候用、先说清计费(组图或图层拆分就是
+ 好几张在计费)、先确认凭据,以及一条要紧的:聊天里的 Markdown 图片语法解析不到工作区文件 —— 结果按
+ 路径交给用户,别写 `![]()`。
+- `plugins/use-seedream/{plugin.json,README.md,icon.svg,LICENSE,package.json}`(新增):打包与描述方式
+ 照 `use-seedance`,`category: office-productivity`。
+- `packages/{core,cli,desktop}/package.json` 与 `pnpm-lock.yaml`:加 `@adelie/use-seedream: workspace:*`,
+ 所以它和视频插件一样是预装的。
+- `packages/core/test/plugins.test.ts`:插件名单加 `use-seedream`(计数跟着到 23);`plugins/README.md`、
+ `README.md`、`README.zh.md`、`packages/docs/content/skills.{zh,en}.md` 各补一条 —— 仓库自带守卫就是
+ 拿这些表和插件库逐条对。
+- `plugins/use-seedream/test/seedream.test.mjs`(新增):10 条对本地桩服务的用例 —— 缺密钥、单图下载、
+ 组图请求体、图层拆分的命名与 `layers[]`、本机参考图内联、`b64_json` 落盘、坏参数、以及被拒不吞错误。
+
+## 兼容
+
+- 原有接口一个都没动:多了一个插件、插件清单里多一个名字。
+- 默认模型是 `doubao-seedream-5-0-pro-260628`,换别的 Seedream 用 `--model`。
+- **真实接口还没跑过**:密钥库里这把方舟 key 对应账号没有开通该模型(`ModelNotOpen`),所以以上全部是
+ 对桩服务验的,不是对服务验的。
diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.md
index 399de88c..d6ea672f 100644
--- a/docs/FORK-PROGRESS.md
+++ b/docs/FORK-PROGRESS.md
@@ -18198,3 +18198,56 @@ key)、**4.1–4.3**(明令不动)、**5.6** / **5.10**(拍板 / 新依
### 提交
- 代码 + 用例 + changelog 中英一对 + 本轮台账同在这一笔(按约定不再另开「补记」提交)。
+
+## 第一百五十二轮:考察豆包的图片工具栏,并把图像生成插件装进 Adelie(2026-10-28,用户点单)
+
+### 起点:用户把方舟的密钥交了过来
+
+- 上一轮考察完豆包那排按钮、结论是「先有引擎才有按钮」,用户问「方舟是火山引擎吗」,随后直接把
+ `ARK_API_KEY` 给了(已写进本 Agent 的密钥库,值不落任何文件)。开工 `HEAD` = `46357436`。
+- 先跑最小真调用:`doubao-seedream-5-0-pro-260628` 回 **404 `ModelNotOpen`**(账号 2102830717 没开通该
+ 模型);`doubao-seedream-5-0-260128`、`4-0-250828`、`3-0-t2i`、`seededit-3-0-i2i` 全是
+ `InvalidEndpointOrModel.NotFound`。**密钥本身是好的**(鉴权通过、拿到账号 id 与 request id),缺的是在方舟
+ 控制台「开通模型」这一步。
+- 所以真实接口一张图都没出过 —— 这一轮所有结论都是对本地桩服务验的,这点在 changelog 里也写明了。
+
+### 干了什么:新增 `plugins/use-seedream`
+
+- 运行时 `skills/seedream/kit/seedream.mjs`:一次性同步 `POST {base}/images/generations`,参数按需发
+ (`size` / `sequential_image_generation` + `max_images` / `layer_decomposition` / `background` /
+ `output_format` / `seed` / `watermark`),参考图最多 14 张、本机文件内联成 data URL,结果按 URL 下载或
+ `b64_json` 解码,一律先写 `.part-<pid>` 再改名。`WxH` 尺寸本地按 1280×720–4096×4096 校验(服务文档的
+ 像素区间),写错算命令行错。退出码与 seedance 对齐:0 成功 / 2 命令行 / 3 缺密钥 / 4 被拒 / 7 下载失败。
+- 多图(组图或图层拆分)时 `--out` 当目录,文件名 `<NNN>-z<z_index>-<名称>.<ext>`,图层恒 PNG;stdout 仍是
+ 一行 JSON(`paths`、`layers[]` 带 `z_index` / `name` / `bounding_box`、`request_id`、`usage`)。
+- 包结构照 seedance:`plugin.json`(`2026.10.28.1`,office-productivity)、中文 `README.md`、只有 name +
+ description 的 `SKILL.md`、`icon.svg`、`LICENSE`。
+- 注册四处:`packages/{core,cli,desktop}/package.json` 各加 `@adelie/use-seedream: workspace:*`,
+ `packages/core/test/plugins.test.ts` 的名单加一条(计数 22 → 23);`pnpm install --lockfile-only` 把
+ `pnpm-lock.yaml` 补上(不动 node_modules,避免踩「注入式布局把 @adelie/ui 链接换掉」那个老坑)。
+- 另外三处是仓库自带守卫逼出来的:`plugins/README.md`、`README.md`、`README.zh.md` 的表格,以及
+ `packages/docs/content/skills.{zh,en}.md` 各一条 —— 不加,`plugins.test.ts` 与 `skills-sync.test.ts` 直接红。
+- 顺手改掉 SKILL 里一句不实的话:原先写「聊天能显示图片」,实际 `Prose` 只覆盖 `pre` 与 `a`,Markdown
+ 图片语法在聊天里解析到的是 Web 自己的源,工作区文件打不开,改成「按路径交给用户」。
+
+### 验证
+
+- `node --test plugins/use-seedream/test/*.test.mjs`:**10/10 通过**(缺密钥、单图下载、组图请求体、图层
+ 拆分命名与 `layers[]`、本机参考图内联、`b64_json`、坏参数、被拒带原话)。
+- `packages/core` 全量:**69 文件 / 1438 通过 / 6 跳过**(`EXIT=0`),含插件名单与计数。
+- `packages/docs/test/skills-sync.test.ts`:3/3 通过。
+- 全仓 `prettier --check .` 干净、`oxlint .` 0 警告 0 错误。
+- 没做的:真实接口冒烟(模型未开通,等用户点「开通」);`--count 1` 会发 `max_images: 1`,真实服务是否接受
+ 没验过。
+
+### 没做 / 还差什么
+
+- **豆包那排按钮还一个没画**:本轮只把引擎装上。界面(`Lightbox` 里的胶囊条、缩略图、像素角标)与框选 /
+ 涂抹这些交互,按上一轮的报告分二、三期做。
+- 考察报告在 `/root/Adelie_develop/doubao-image-canvas-research.md`(不在这个仓库里),官方文档原文落在
+ `doubao-research/evidence/`。
+- 现网(7777)仍是 v0.5.9 的安装,要看见这个插件得发版,需用户点头。
+
+### 提交
+
+- 插件 + 注册 + 文档 + changelog 中英一对 + 本轮台账,一笔提交。
diff --git a/packages/cli/package.json b/packages/cli/package.json
index a55fd6bc..aa9b1ba9 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -43,6 +43,7 @@
"@adelie/use-lieflat-charts": "workspace:*",
"@adelie/use-offerdao": "workspace:*",
"@adelie/use-seedance": "workspace:*",
+ "@adelie/use-seedream": "workspace:*",
"@adelie/use-wps-office": "workspace:*",
"@adelie/use-claude-code": "workspace:*",
"@adelie/wechat-miniprogram": "workspace:*",
diff --git a/packages/core/package.json b/packages/core/package.json
index 1cc5942d..1fa83317 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -76,6 +76,7 @@
"@adelie/use-lieflat-charts": "workspace:*",
"@adelie/use-offerdao": "workspace:*",
"@adelie/use-seedance": "workspace:*",
+ "@adelie/use-seedream": "workspace:*",
"@adelie/use-wps-office": "workspace:*",
"@adelie/use-claude-code": "workspace:*",
"@adelie/wechat-miniprogram": "workspace:*",
diff --git a/packages/core/test/plugins.test.ts b/packages/core/test/plugins.test.ts
index 0c1a50b4..c1120f23 100644
--- a/packages/core/test/plugins.test.ts
+++ b/packages/core/test/plugins.test.ts
@@ -65,7 +65,7 @@ describe("loadLibraryPlugins", () => {
it("loads every plugin directory sorted by name, each with a date-sequence version and a category", () => {
const plugins = loadLibraryPlugins();
expect(plugins.map((p) => p.name)).toEqual([...plugins.map((p) => p.name)].sort());
- expect(plugins.length).toBe(22);
+ expect(plugins.length).toBe(23);
for (const plugin of plugins) {
expect(plugin.version, plugin.name).toMatch(PLUGIN_VERSION_PATTERN);
expect(
@@ -219,6 +219,7 @@ describe("groupPlugins / loadPluginGroups", () => {
"use-lieflat-charts",
"use-offerdao",
"use-seedance",
+ "use-seedream",
"use-wps-office",
]);
expect(names("ai-app-development")).toEqual([
diff --git a/packages/desktop/package.json b/packages/desktop/package.json
index f5b5a443..ac6272d5 100644
--- a/packages/desktop/package.json
+++ b/packages/desktop/package.json
@@ -35,6 +35,7 @@
"@adelie/use-lieflat-charts": "workspace:*",
"@adelie/use-offerdao": "workspace:*",
"@adelie/use-seedance": "workspace:*",
+ "@adelie/use-seedream": "workspace:*",
"@adelie/use-wps-office": "workspace:*",
"@adelie/use-claude-code": "workspace:*",
"@adelie/wechat-miniprogram": "workspace:*"
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index a45c8f28..119e0675 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -223,6 +223,7 @@ The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plu
| | `use-bento-slides` | Author and edit Bento presentations: single-file `.bento.html` decks whose document is JSON, mapping material to charts, morph transitions and state slides |
| | `use-lieflat-charts` | Turn data into polished, interactive HTML charts — sixty-odd templates across Lupi editorial, Basics, Glance, Maps and the interactive big graphs — and, only when the user asks for it, into a paged HTML/PDF deck or a full-page report; one colour system per deliverable (Mono by default, plus three built-in presets or a custom palette). Ported from the upstream `lieflat-charts` skill (PolyForm Noncommercial 1.0.0 — see the plugin's `LICENSE` and `NOTICE.md`); about 2.5 MB of templates, not preinstalled: install it from the library onto the Agents that draw |
| | `use-seedance` | Turn a prompt into a video with Volcengine Ark's Doubao Seedance models and save it into the workspace — one dependency-free Node script over Ark's asynchronous video-generation API (submit, poll, download), with the key kept in the vault (preinstalled) |
+| | `use-seedream` | Turn a prompt — plus up to 14 reference images — into pictures with Volcengine Ark's Doubao Seedream models and save them into the workspace: a group of up to 15 images per call, a layer split (one backdrop plus up to 16 individually editable transparent PNG layers) and transparent backgrounds, with the key kept in the vault (preinstalled) |
| | `humanizer` | Strip AI-writing tells from prose in any language and rewrite it into the register of books, newspapers and encyclopedias (not preinstalled: install from the library when needed) |
| | `goal` | The stop hook behind [goal mode](/goal-mode): keeps the Session working toward an objective until it is complete, blocked, or out of Token budget (preinstalled) |
| | `continual-learning` | When a Task ends after more than 30 turns, hands its condensed excerpt to a background subagent that folds the durable findings into the agent's Skills (not preinstalled) |
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index 95e6eb8c..0d1d68ca 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -223,6 +223,7 @@ Agent 可以在 Task 中重写自己的 `SKILL.md`。结合 Benchmark 评估和
| | `use-bento-slides` | 创建和编辑 Bento 演示文稿:单文件 `.bento.html` 幻灯片,文件内容为 JSON,支持素材到图表的映射、morph 过渡和状态幻灯片 |
| | `use-lieflat-charts` | 把数据做成精致、可交互的 HTML 图表(Lupi 编辑型、Basics 基础型、Glance 快读型、地图与交互大图六十几套模板),用户明确要求时才做可翻页的 HTML/PDF 演示或整页报告;同一份交付只锁一种色系(默认 Mono,另有青瓷蓝 / 椰林绿 / 编辑部红与自定义色板)。移植自上游 `lieflat-charts` skill(许可是 PolyForm 非商业 1.0.0,见插件内 `LICENSE` 与 `NOTICE.md`);约 2.5 MB 模板,不预装:需要画图的 Agent 从插件库安装 |
| | `use-seedance` | 用火山方舟的豆包 Seedance 模型按提示词生成视频、落到工作区:零依赖的 Node 脚本替 Agent 走完异步三步(提交任务、按退避间隔轮询、下载成片),密钥存在密钥库里(预装) |
+| | `use-seedream` | 用火山方舟的豆包 Seedream 模型按提示词生成图片、落到工作区:支持参考图(最多 14 张)、组图(一次最多 15 张)、图层拆分(1 张底图 + 最多 16 个可单独编辑的透明 PNG 图层)与透明底,密钥存在密钥库里(预装) |
| | `humanizer` | 去除任何语言文字中的 AI 写作痕迹,改写成书籍、报纸和百科全书的语体(不预装:需要时从插件库安装) |
| | `goal` | [目标模式](/goal-mode)背后的 stop 钩子:让 Session 持续朝着目标推进,直到完成、受阻或 Token 预算耗尽(预装) |
| | `continual-learning` | Task 运行超过 30 轮才结束时,把 Task 的精简摘录交给后台子 Agent,由它把有长期价值的发现沉淀到 Agent 的 Skill 中(不预装) |
diff --git a/plugins/README.md b/plugins/README.md
index 4746fe18..53998597 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -8,7 +8,7 @@ Included plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plugins
| Category | Plugins |
| --- | --- |
-| Office Productivity | `data-analysis`, `use-firecrawl`, `use-offerdao`, `browser-automation`, `use-bento-slides`, `use-lieflat-charts`, `use-wps-office`, `use-seedance`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` |
+| Office Productivity | `data-analysis`, `use-firecrawl`, `use-offerdao`, `browser-automation`, `use-bento-slides`, `use-lieflat-charts`, `use-wps-office`, `use-seedance`, `use-seedream`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` |
| Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram` |
| AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` |
| Agent Company | `agent-company` |
diff --git a/plugins/use-seedream/LICENSE b/plugins/use-seedream/LICENSE
new file mode 100644
index 00000000..261eeb9e
--- /dev/null
+++ b/plugins/use-seedream/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/plugins/use-seedream/README.md b/plugins/use-seedream/README.md
new file mode 100644
index 00000000..52984127
--- /dev/null
+++ b/plugins/use-seedream/README.md
@@ -0,0 +1,73 @@
+# Seedream 图像生成(`@adelie/use-seedream`)
+
+一句话:**把提示词交给火山方舟的豆包 Seedream,拿回图片,落在工作区里。**
+
+运行时就一个零依赖的 Node 文件(`skills/seedream/kit/seedream.mjs`)。它替 Agent 走完图片生成
+的**同步一步**——一次请求,答案里直接带回图片:
+
+```
+POST /images/generations 一次请求 → data[] 里是图片:url(默认)或 b64_json
+下载 url 或解码 b64_json → 先写临时文件,写完了才改名
+```
+
+端点默认 `https://ark.cn-beijing.volces.com/api/v3`,鉴权是 `Authorization: Bearer $ARK_API_KEY`;
+**密钥只从环境读**(Agent 的密钥库注入),脚本不写盘,也不留下别的痕迹。
+
+## 用
+
+```bash
+node skills/seedream/kit/seedream.mjs --prompt "一只猫在窗台上晒太阳" --out cat.png
+```
+
+stderr 是给人看的进度行,**stdout 只有一行 JSON**,路径、耗时、用量都在里面:
+
+```json
+{"ok":true,"model":"doubao-seedream-5-0-pro-260628","size":"2K","request_id":"0217…","elapsed_ms":18342,"paths":["/abs/cat.png"],"usage":{"generated_images":1}}
+```
+
+参数:`--out`(单图是文件路径,出多图时是目录;默认单图 `./seedream-<时间戳>.<格式>`、
+多图 `./seedream-<时间戳>/`)、
+`--model`(默认 `doubao-seedream-5-0-pro-260628`)、`--image`(参考图,可重复,最多 14 张,
+本机文件会内联成 `data:<mime>;base64,…`)、`--size`(`1K`/`2K`/`4K` 或 `2048x2048`,
+总像素须在 1280×720 与 4096×4096 之间)、`--count`(一次出组图,1–15 张)、`--layers`(图层拆分)、
+`--transparent`、`--format`(`png`/`jpeg`)、`--seed`、`--watermark`。**没传的参数不发给服务**,
+所以模型自己的默认值说了算;未知参数直接报错,不会悄悄忽略。
+
+出多图(`--count` 或 `--layers`)时 `--out` 当目录用,文件名是三位序号加内容:
+`001-base.png`、`002-z0-cat-outline.png`……序号后面带 `-z<z_index>`(有的话)和清洗过的层名
+(中文层名清洗后为空,就用 `base` / `layer`)。图层一律是 PNG。
+
+退出码把结果分了类:`0` 成功;`2` 命令行不对;`3` 缺 `ARK_API_KEY`;`4` 接口拒了请求(`upstream`
+里是服务原话);`7` 图片没下下来(临时文件已删,最终路径上不会留半张图)。
+
+## 文件
+
+| 路径 | 是什么 |
+| --- | --- |
+| `skills/seedream/kit/seedream.mjs` | 全部运行时:参数、请求、下载/解码、一行 JSON |
+| `skills/seedream/SKILL.md` | Agent 读的说明书:什么时候用、参数、错误码怎么处理、产物怎么给用户看 |
+| `test/seedream.test.mjs` | 自检,桩服务冒充方舟,不用密钥也不花钱 |
+| `plugin.json` / `package.json` / `icon.svg` / `LICENSE` | 插件清单、包信息、图标、Apache-2.0 |
+
+## 测试
+
+```bash
+node --test "plugins/use-seedream/test/*.test.mjs" # 或在包目录里 pnpm test
+```
+
+桩(`test/` 里那个 `http.createServer`)冒充方舟:生成接口按用例返回 URL 或 base64,
+图片地址由同一个桩提供,于是整条路——请求 → 下载 → 改名——都在本机跑完,并断言密钥只发往接口、
+不发给图片 URL(真实的返回是签名链接)。**它验的是脚本自己的行为,不是真实响应的形状**:
+真实方舟的成功响应长什么样只能靠文档,想真跑一次需要账号已开通 Seedream 并且愿意付费。
+
+关键接口改动时以官网为准:
+[图片生成](https://docs.volcengine.com/docs/ark/image-generation-api?lang=zh)、
+[模型列表](https://docs.volcengine.com/docs/ark/model-list?lang=zh)。
+
+## 还没验的
+
+- 真实方舟的一次完整成功(需要已开通的账号与付费额度)。
+- 图层拆分的真实响应:文档说 `data` 里是 1 张底图加最多 16 个图层、每项带
+ `name`/`z_index`/`description`/`bounding_box`,脚本按这个形状解析,但没对着真响应跑过。
+- `sequential_image_generation` 与 `layer_decomposition` 在真实模型上的组合约束(脚本只按文档传参)。
+- Windows 上的路径与 base64 参考图(本机是 Linux,只验了 Linux)。
diff --git a/plugins/use-seedream/icon.svg b/plugins/use-seedream/icon.svg
new file mode 100644
index 00000000..7191709e
--- /dev/null
+++ b/plugins/use-seedream/icon.svg
@@ -0,0 +1,6 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <rect x="3" y="4" width="18" height="16" rx="2" />
+ <circle cx="8" cy="9" r="1.6" />
+ <path d="m21 16.5-4.5-4.5L7 20.5" />
+ <path d="M14 5.5 14.6 7l1.5.6-1.5.6L14 9.7l-.6-1.5L11.9 7.6l1.5-.6Z" />
+</svg>
diff --git a/plugins/use-seedream/package.json b/plugins/use-seedream/package.json
new file mode 100644
index 00000000..57dc347a
--- /dev/null
+++ b/plugins/use-seedream/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "@adelie/use-seedream",
+ "version": "0.5.9",
+ "description": "Generate images from a prompt with Volcengine Ark's Doubao Seedream models and save them into the workspace — one dependency-free Node script over the synchronous image-generation API, driven by a vault-stored API key.",
+ "license": "Apache-2.0",
+ "scripts": {
+ "test": "node --test \"test/*.test.mjs\""
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/lmliheng/Adelie.git",
+ "directory": "plugins/use-seedream"
+ },
+ "keywords": [
+ "adelie-plugin",
+ "penguin-harness",
+ "image",
+ "seedream",
+ "doubao",
+ "volcengine",
+ "ark"
+ ],
+ "files": [
+ "plugin.json",
+ "icon.svg",
+ "README.md",
+ "skills",
+ "LICENSE"
+ ],
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/plugins/use-seedream/plugin.json b/plugins/use-seedream/plugin.json
new file mode 100644
index 00000000..97746f6e
--- /dev/null
+++ b/plugins/use-seedream/plugin.json
@@ -0,0 +1,8 @@
+{
+ "description": "Generate images from a prompt with Volcengine Ark's Doubao Seedream models and save them into the workspace. One dependency-free Node script drives the synchronous image-generation API — reference images inlined as base64, groups of images in one request, and layer decomposition into a base image plus transparent PNG layers — with every file written through a temporary path and renamed only when complete, then prints one line of JSON with the absolute paths, the z-ordered layers and the elapsed time. The API key comes from the vault as ARK_API_KEY and is never written to disk.",
+ "description_zh": "用火山方舟的豆包 Seedream 模型把提示词生成成图片,落到工作区。运行时是一个零依赖的 Node 脚本,走同步的图片生成接口:参考图内联成 base64、一次请求出组图、按图层拆分出一张底图加若干透明 PNG 图层;每个文件先落临时路径、写完才改名,最后打一行 JSON,给出绝对路径、按 z 排序的图层与耗时。密钥从密钥库以 ARK_API_KEY 注入,不落盘。",
+ "short_description": "Generate images from a prompt with Ark Doubao Seedream, saved into the workspace.",
+ "short_description_zh": "用火山方舟豆包 Seedream 按提示词生成图片并落到工作区。",
+ "version": "2026.10.28.1",
+ "category": "office-productivity"
+}
diff --git a/plugins/use-seedream/skills/seedream/SKILL.md b/plugins/use-seedream/skills/seedream/SKILL.md
new file mode 100644
index 00000000..4c10db09
--- /dev/null
+++ b/plugins/use-seedream/skills/seedream/SKILL.md
@@ -0,0 +1,151 @@
+---
+name: seedream
+description: Generate images from a prompt with Volcengine Ark's Doubao Seedream models — one synchronous request that answers with image URLs or inline base64, saved into the workspace through temporary files, with optional reference images, groups and layer decomposition, driven by a vault-stored API key.
+---
+
+# Seedream (Doubao image generation)
+
+Volcengine Ark's image generation API turns a prompt — and, if you have them, reference images —
+into pictures. It is **synchronous**: one POST answers with the images themselves, as URLs to
+download or as inline base64. `kit/seedream.mjs` is one dependency-free Node script that builds
+the request, fetches or decodes every image and saves them into the workspace, so a single command
+covers the whole job.
+
+```
+POST /images/generations -> { "data": [ { "url": …, "size": …, "output_format": … } ],
+ "usage": { … } }
+```
+
+## Before you start
+
+If the message only names this skill (e.g. "use seedream") with no picture to make, ask what the
+image should show — and, when the answer sounds like it wants a specific subject or look, offer to
+generate from a reference image the user already has rather than from text alone.
+
+**Every image costs money.** Generation is billed per image, so a group of three (`--count 3`) or a
+layer split is three or more billed images, not one. Read a vague prompt back to the user before
+submitting, and do not fire a batch of variants "to see which one looks better" unless they asked
+for one.
+
+Then check the credential:
+
+```bash
+[ -n "$ARK_API_KEY" ] && echo ok || echo missing
+```
+
+If it is missing (also visible in your Vault Keys section), ask the user to add `ARK_API_KEY` to
+this agent's **key vault** — gear icon on the agent card → settings → key vault tab. The key comes
+from the Ark console (https://ark.volcengine.com/region:cn-beijing/apikey); vault values reach your
+shell environment on the next task. Nothing else is needed: the script reads the key from the
+environment and never writes it to disk.
+
+## Generate
+
+```bash
+node <skill dir>/kit/seedream.mjs --prompt "<what the image should show>" --out <name>.png
+```
+
+The script prints progress lines on stderr and **one line of JSON on stdout**:
+
+```json
+{"ok":true,"model":"doubao-seedream-5-0-pro-260628","size":"2K","request_id":"0217…","elapsed_ms":18342,"paths":["/abs/path/<name>.png"],"usage":{"generated_images":1}}
+```
+
+`--out` defaults to `seedream-<UTC timestamp>.<ext>` for one image and `seedream-<UTC timestamp>/`
+for several, in the working directory. Every file is written
+through a temporary file that only gets its final name once the write finished — so a half-written
+image never looks like a complete one. Read `paths` (absolute) out of the JSON rather than
+rebuilding the names yourself.
+
+When the answer carries several images — `--count`, `--layers`, or simply more images than one —
+`--out` is a **directory**, and the files are named `<NNN>-z<z_index>-<name>.<ext>`: a running
+number, the layer's stacking index when it has one, and the cleaned-up name the service gave
+(non-ASCII names clean to nothing, so `base` / `layer` stands in). Layers are always PNG.
+
+Options:
+
+| Option | Meaning |
+| --- | --- |
+| `--prompt <text>` | required; what the picture should show |
+| `--out <path>` | file for one image, directory for several (default `./seedream-<timestamp>`) |
+| `--model <id>` | Ark Model ID (default `doubao-seedream-5-0-pro-260628`) |
+| `--image <url\|path>` | reference image, repeatable up to **14**; a local file is inlined as base64 |
+| `--size <1K\|2K\|4K\|WxH>` | output size, e.g. `2K` or `2048x2048` |
+| `--count <n>` | a group of n images (1–15) in one request |
+| `--layers` | split the result into a base image plus up to **16** transparent PNG layers |
+| `--transparent` | transparent background instead of opaque |
+| `--format <png\|jpeg>` | output file format |
+| `--seed <integer>` | fix the take, for a result you can reproduce |
+| `--watermark` | keep the service watermark (otherwise it is the service default) |
+
+Only the options you pass are sent, so every default stays the service's own. An unknown option, a
+missing value or a bad number is an error — never a silently ignored argument. A `WxH` size is
+checked locally against the service's pixel window (**at least 1280×720, at most 4096×4096 total
+pixels**) and a too-small or too-large one is rejected with the bound it broke.
+
+An example with a reference image, a 2K take:
+
+```bash
+node <skill dir>/kit/seedream.mjs \
+ --prompt "the same cat, now sitting in a sunbeam, soft morning light" \
+ --image ~/pictures/cat.jpg --size 2K --out cat-sunbeam.png
+```
+
+## Layers and groups
+
+- **Layers** (`--layers`) come back as one base image plus at most **16** layers, each with
+ `name`, `z_index`, `description` and a `bounding_box` (absolute and normalized). The base image
+ is saved first, then the layers in ascending `z_index`; the JSON's `layers[]` repeats each
+ layer's `path`, `z_index`, `name`, `size` and `bounding_box` so a caller can reassemble them.
+ Layers are always **transparent PNG**, whatever `--format` says. If the service fails to
+ produce any one layer, the whole request fails — nothing is delivered.
+- **Groups** (`--count n`) ask for n images in one request (`sequential_image_generation: auto`
+ with `max_images`). The service may return fewer than asked for; `paths` always lists what
+ actually landed.
+
+## Failures
+
+| Code | Meaning | What to do |
+| --- | --- | --- |
+| 0 | images saved | read `paths` from the JSON |
+| 2 | bad command line | fix the flags; the message says which one (including more than 14 `--image` or a size outside the pixel window) |
+| 3 | `ARK_API_KEY` missing | ask the user for the key (see above) |
+| 4 | the API refused the request — HTTP status and the service's own text are in `upstream` | `401` → wrong or missing key; `403 …ServiceNotOpen` → the model is not activated for this account; `403 …ServiceOverdue` → the account is out of credit; `429` → rate or concurrency limit, wait rather than retry-looping; `400 InvalidParameter*` → an option the model does not accept |
+| 7 | an image did not download or decode | the URL was unreachable or answered empty; nothing is left at that path (the temporary file is removed), and `paths` lists the images that did land |
+
+Never retry a submission on a failure you do not understand — a request that reached the service
+may already have been billed. Read the `upstream` field before saying anything about the cause.
+
+## Handing the result to the user
+
+Give the user the files, not a base64 blob — and give them as paths, not as Markdown images:
+
+- Save them into the workspace (the default output already does) and name each one in your reply
+ by its workspace-relative path in backticks, with the model that made it. Markdown image syntax
+ (`![](relative.png)`) does **not** resolve in the chat — it points at the web app's own origin,
+ not at the workspace — so the user opens the file from the Files panel instead.
+- For a layer split, show the base image as the preview and mention that the transparent layers
+ sit beside it — a PNG viewer that stacks by filename order will not reassemble them, so say the
+ layers are separate files.
+- Keep `request_id` in your reply when the user may ask about the request later; the same seed
+ plus the same options is a reproducible take.
+
+## The interface behind the script
+
+Under `https://ark.cn-beijing.volces.com/api/v3`, authenticated with
+`Authorization: Bearer $ARK_API_KEY`:
+
+- `POST /images/generations` with `{"model": …, "prompt": …, "image": … , "size": …, …}` and
+ `response_format: "url"`. `image` is a string for one reference image and an array for several
+ (a local file goes in as a `data:<mime>;base64,…` URL); the synchronous answer carries
+ `data[]` — `url` and `output_format` when `response_format` is `url`, `b64_json` when it is
+ `b64_json` — plus `usage`. The script sends `url` and downloads, but decodes `b64_json` if that
+ is what comes back.
+
+Model IDs and the per-model option ranges live in the docs, which are the source of truth for
+anything this file does not state:
+https://docs.volcengine.com/docs/ark/image-generation-api?lang=zh,
+https://docs.volcengine.com/docs/ark/model-list?lang=zh
+
+`ARK_BASE_URL` overrides the endpoint. It exists so the script can be pointed at a local stub when
+it is being tested — leave it unset for real work.
diff --git a/plugins/use-seedream/skills/seedream/kit/seedream.mjs b/plugins/use-seedream/skills/seedream/kit/seedream.mjs
new file mode 100644
index 00000000..dd1c7ff9
--- /dev/null
+++ b/plugins/use-seedream/skills/seedream/kit/seedream.mjs
@@ -0,0 +1,456 @@
+#!/usr/bin/env node
+/**
+ * Generate images with Volcengine Ark's Doubao Seedream models and save them into the workspace.
+ *
+ * One non-interactive run: prompt in, images out. The endpoint is synchronous — a single POST
+ * answers with the images themselves (either a URL to download or inline base64) — so unlike the
+ * video API there is nothing to poll. Every file is written through a temporary path and renamed
+ * only once it is complete, so a half-written image never wears the final name.
+ *
+ * node seedream.mjs --prompt "..." [--out image.png] [--model doubao-seedream-5-0-pro-260628]
+ * [--image <url|path>] [--size 2K] [--count 3] [--layers]
+ * [--transparent] [--format png] [--seed 11] [--watermark]
+ *
+ * Progress goes to stderr as plain lines; the outcome goes to stdout as ONE line of JSON, so a
+ * caller can pipe stdout straight into a JSON reader. Every failure leaves a non-zero exit code
+ * and carries the upstream error text in the JSON on stderr:
+ *
+ * 1 unexpected | 2 bad usage | 3 no API key | 4 the API refused the request | 7 an image did not download
+ *
+ * Credentials: `ARK_API_KEY` (a vault key — this script never writes a key to disk). The endpoint
+ * comes from `ARK_BASE_URL` and defaults to the official one; the override exists so the script
+ * can be pointed at a local stub, which is how its end-to-end path is tested without spending
+ * anything.
+ *
+ * API reference: https://docs.volcengine.com/docs/ark/image-generation-api?lang=zh
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { Readable } from "node:stream";
+import { pipeline } from "node:stream/promises";
+
+/** The official Ark endpoint; `ARK_BASE_URL` overrides it (see the header). */
+const DEFAULT_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3";
+/** Doubao Seedream 5.0 Pro — the current Seedream Model ID (docs: model-list / seedream-5-0). */
+const DEFAULT_MODEL = "doubao-seedream-5-0-pro-260628";
+/** Reference images per request, and layers per decomposition, as the service defines them. */
+const MAX_IMAGES = 14;
+const MAX_COUNT = 15;
+/** Size bounds in total pixels: 1280x720 below, 4096x4096 above. */
+const MIN_PIXELS = 1280 * 720;
+const MAX_PIXELS = 4096 * 4096;
+/** Mime types for `--image` files handed to the API as a base64 data URL. */
+const IMAGE_MIME = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".webp": "image/webp",
+ ".gif": "image/gif",
+ ".bmp": "image/bmp",
+};
+
+const EXIT = { unexpected: 1, usage: 2, key: 3, upstream: 4, download: 7 };
+
+const USAGE = `Generate an image with Doubao Seedream and save it into the workspace.
+
+ node seedream.mjs --prompt "..." [options]
+
+ --prompt <text> what the image should show (required)
+ --out <path> file to save to, or a directory when several images come back
+ (default ./seedream-<timestamp>)
+ --model <id> Ark Model ID (default ${DEFAULT_MODEL})
+ --image <url|path> reference image, repeatable up to ${MAX_IMAGES}; local file or http(s)/data URL
+ --size <1K|2K|4K|WxH> output size, e.g. 2K or 2048x2048
+ --count <n> a group of n images (1-${MAX_COUNT}) in one request
+ --layers split the result into layers (one base image + up to 16 layers)
+ --transparent transparent background instead of an opaque one
+ --format <png|jpeg> output file format
+ --seed <integer> fixed seed for a reproducible take
+ --watermark keep the service watermark
+ --help print this text
+
+Environment: ARK_API_KEY (required), ARK_BASE_URL (defaults to the official endpoint).`;
+
+/** A bad command line: reported with the usage text, never guessed at. */
+class UsageError extends Error {}
+
+/** One option table, so an unknown or valueless option is an error rather than a silent no-op. */
+const SPECS = {
+ prompt: { takes: true },
+ out: { takes: true },
+ model: { takes: true },
+ image: { takes: true, repeat: true },
+ size: { takes: true },
+ count: { takes: true },
+ layers: { takes: false },
+ transparent: { takes: false },
+ format: { takes: true },
+ seed: { takes: true },
+ watermark: { takes: false },
+ help: { takes: false },
+};
+
+function parseArgs(argv) {
+ const values = {};
+ for (let i = 0; i < argv.length; i++) {
+ const raw = argv[i];
+ if (!raw.startsWith("--")) throw new UsageError(`unexpected argument "${raw}"`);
+ const eq = raw.indexOf("=");
+ const name = eq === -1 ? raw.slice(2) : raw.slice(2, eq);
+ const spec = SPECS[name];
+ if (!spec) throw new UsageError(`unknown option "--${name}"`);
+ if (!spec.takes) {
+ if (eq !== -1) throw new UsageError(`"--${name}" takes no value`);
+ values[name] = true;
+ continue;
+ }
+ const inline = eq === -1 ? undefined : raw.slice(eq + 1);
+ const value = inline ?? argv[i + 1];
+ if (value === undefined || (inline === undefined && value.startsWith("--")))
+ throw new UsageError(`"--${name}" needs a value`);
+ if (inline === undefined) i++;
+ if (spec.repeat) (values[name] ??= []).push(value);
+ else values[name] = value;
+ }
+ return values;
+}
+
+/** Progress and diagnostics for a human; stdout stays reserved for the one JSON line. */
+function say(text) {
+ process.stderr.write(`${text}\n`);
+}
+
+function fail(code, error, extra = {}) {
+ process.stderr.write(`${JSON.stringify({ ok: false, error, ...extra })}\n`);
+ process.exit(code);
+}
+
+/** An integer passthrough: a typo is a bad command line, not a body the service has to reject. */
+function integerArg(args, name, { min, max } = {}) {
+ if (args[name] === undefined) return undefined;
+ const value = Number(args[name]);
+ if (!Number.isInteger(value))
+ throw new UsageError(`"--${name}" needs an integer, got "${args[name]}"`);
+ if (min !== undefined && value < min)
+ throw new UsageError(`"--${name}" needs at least ${min}, got "${args[name]}"`);
+ if (max !== undefined && value > max)
+ throw new UsageError(`"--${name}" accepts at most ${max}, got "${args[name]}"`);
+ return value;
+}
+
+/**
+ * An image option as the API wants it: an http(s)/data URL is passed through, a local path is
+ * read and inlined as a base64 data URL (the docs' base64 form for reference images).
+ */
+function imageFor(spec, option) {
+ if (/^(?:https?|data):/i.test(spec)) return spec;
+ const file = path.resolve(spec);
+ let bytes;
+ try {
+ bytes = fs.readFileSync(file);
+ } catch (err) {
+ throw new UsageError(`"--${option}" cannot read ${file}: ${err.message}`);
+ }
+ const mime = IMAGE_MIME[path.extname(file).toLowerCase()] ?? "image/jpeg";
+ return `data:${mime};base64,${bytes.toString("base64")}`;
+}
+
+/**
+ * A size the service will take: a named step is passed on as written, an explicit `WxH` is
+ * checked against the pixel window here — a bad one is a command-line mistake, and the error says
+ * which bound it broke instead of letting the service answer with a generic 400.
+ */
+function sizeArg(raw) {
+ if (raw === undefined) return undefined;
+ const named = /^(1k|2k|4k)$/i.exec(raw.trim());
+ if (named) return named[1].toUpperCase();
+ const dims = /^(\d+)x(\d+)$/i.exec(raw.trim());
+ if (!dims) throw new UsageError(`"--size" needs 1K, 2K, 4K or <width>x<height>, got "${raw}"`);
+ const width = Number(dims[1]);
+ const height = Number(dims[2]);
+ const pixels = width * height;
+ if (pixels < MIN_PIXELS || pixels > MAX_PIXELS)
+ throw new UsageError(
+ `"--size" ${width}x${height} is ${pixels} pixels; the service accepts between ${MIN_PIXELS} (1280x720) and ${MAX_PIXELS} (4096x4096)`,
+ );
+ return `${width}x${height}`;
+}
+
+function formatArg(raw) {
+ if (raw === undefined) return undefined;
+ const value = raw.trim().toLowerCase();
+ if (value !== "png" && value !== "jpeg")
+ throw new UsageError(`"--format" needs png or jpeg, got "${raw}"`);
+ return value;
+}
+
+/** The request body: only the options actually given, so the service's own defaults stand. */
+function buildBody(args, model) {
+ const images = (args.image ?? []).map((spec) => imageFor(spec, "image"));
+ if (images.length > MAX_IMAGES)
+ throw new UsageError(
+ `"--image" accepts at most ${MAX_IMAGES} reference images, got ${images.length}`,
+ );
+ // The API takes a bare string for one reference image and an array for several.
+ const body = {
+ model,
+ prompt: args.prompt,
+ response_format: "url",
+ };
+ if (images.length === 1) body.image = images[0];
+ else if (images.length > 1) body.image = images;
+ const size = sizeArg(args.size);
+ if (size !== undefined) body.size = size;
+ const count = integerArg(args, "count", { min: 1, max: MAX_COUNT });
+ if (count !== undefined) {
+ // A group is the service's sequential generation filled to the requested number of images.
+ body.sequential_image_generation = "auto";
+ body.sequential_image_generation_options = { max_images: count };
+ }
+ if (args.layers) body.layer_decomposition = true;
+ if (args.transparent) body.background = "transparent";
+ const format = formatArg(args.format);
+ if (format !== undefined) body.output_format = format;
+ const seed = integerArg(args, "seed");
+ if (seed !== undefined) body.seed = seed;
+ if (args.watermark) body.watermark = true;
+ return body;
+}
+
+/**
+ * One JSON request, with the upstream body kept verbatim on failure: the API's own message is
+ * what tells a caller whether this is a key, a quota or a parameter problem.
+ */
+async function apiJson(url, init, what) {
+ let res;
+ try {
+ res = await fetch(url, init);
+ } catch (err) {
+ fail(EXIT.upstream, "unreachable", {
+ message: `${what} failed: cannot reach ${url} — ${err.message}`,
+ upstream: err.message,
+ });
+ }
+ const text = await res.text();
+ if (!res.ok)
+ fail(EXIT.upstream, "api_error", {
+ message: `${what} failed: HTTP ${res.status} from ${url}`,
+ status: res.status,
+ upstream: text,
+ });
+ try {
+ return { answer: JSON.parse(text), headers: res.headers };
+ } catch {
+ fail(EXIT.upstream, "api_error", {
+ message: `${what} failed: the service answered something that is not JSON`,
+ status: res.status,
+ upstream: text,
+ });
+ }
+}
+
+/** `[A-Za-z0-9._-]` survives, everything else becomes a dash; empty names fall back. */
+function cleanName(raw, fallback) {
+ const cleaned = String(raw ?? "")
+ .replace(/[^A-Za-z0-9._-]/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 40)
+ .replace(/-+$/g, "");
+ return cleaned || fallback;
+}
+
+function zIndexOf(item) {
+ return Number.isInteger(item?.z_index) ? item.z_index : undefined;
+}
+
+/**
+ * File stems for a multi-image answer: a running number, the layer's z index when it has one,
+ * and its name. The number keeps the order visible; the z index keeps the stacking readable.
+ */
+function planStems(items) {
+ const used = new Map();
+ return items.map((item, index) => {
+ const z = zIndexOf(item);
+ const stem = [
+ String(index + 1).padStart(3, "0"),
+ z === undefined ? undefined : `z${z}`,
+ cleanName(item?.name, z === undefined ? "base" : "layer"),
+ ]
+ .filter(Boolean)
+ .join("-");
+ const seen = used.get(stem) ?? 0;
+ used.set(stem, seen + 1);
+ return seen === 0 ? stem : `${stem}-${seen + 1}`;
+ });
+}
+
+/** Layers are always PNG; anything else follows the answer's format, then the request's. */
+function extensionFor(item, format, isLayer) {
+ if (isLayer) return "png";
+ const value = String(item?.output_format ?? format ?? "png").toLowerCase();
+ return value === "jpeg" || value === "jpg" ? "jpg" : "png";
+}
+
+/**
+ * One image on disk, through a temporary file: an answer may carry a URL to fetch or the bytes
+ * inline, and either way a partial write must not end up wearing the final name.
+ */
+async function saveItem(item, out) {
+ const part = `${out}.part-${process.pid}`;
+ fs.mkdirSync(path.dirname(out), { recursive: true });
+ try {
+ if (typeof item?.b64_json === "string" && item.b64_json !== "") {
+ fs.writeFileSync(part, Buffer.from(item.b64_json, "base64"));
+ } else if (typeof item?.url === "string" && item.url !== "") {
+ const res = await fetch(item.url);
+ if (!res.ok || res.body === null)
+ throw new Error(`HTTP ${res.status} from the URL the service returned`);
+ await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(part));
+ } else {
+ throw new Error("the answer carried neither url nor b64_json");
+ }
+ if (fs.statSync(part).size === 0) throw new Error("the saved image is empty");
+ } catch (err) {
+ // The temporary file goes away with the failure: only a complete image gets renamed.
+ fs.rmSync(part, { force: true });
+ throw err;
+ }
+ fs.renameSync(part, out);
+}
+
+/** Answers often omit fields; keep only the ones that are actually there. */
+function compact(value) {
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.help) {
+ process.stdout.write(`${USAGE}\n`);
+ return 0;
+ }
+ if (!args.prompt?.trim()) throw new UsageError(`"--prompt" is required`);
+ args.prompt = args.prompt.trim();
+
+ // The command line is fully understood (and any bad value rejected) before anything is sent or
+ // asked for: a typo should not look like a credential problem.
+ const model = args.model ?? DEFAULT_MODEL;
+ const count = integerArg(args, "count", { min: 1, max: MAX_COUNT });
+ const format = formatArg(args.format);
+ const body = buildBody(args, model);
+ const baseUrl = (process.env.ARK_BASE_URL?.trim() || DEFAULT_BASE_URL).replace(/\/+$/, "");
+ if (!/^https?:\/\//i.test(baseUrl))
+ throw new UsageError(`ARK_BASE_URL must be an http(s) URL, got "${baseUrl}"`);
+
+ const apiKey = process.env.ARK_API_KEY?.trim();
+ if (!apiKey)
+ fail(EXIT.key, "missing_key", {
+ message:
+ "ARK_API_KEY is not set. Add it to this agent's key vault (the agent card's settings → key vault) — the key comes from the Ark console at https://ark.volcengine.com/region:cn-beijing/apikey — then run the task again.",
+ });
+
+ const startedAt = Date.now();
+ say(`model ${model}, endpoint ${baseUrl}`);
+
+ const { answer, headers } = await apiJson(
+ `${baseUrl}/images/generations`,
+ {
+ method: "POST",
+ headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
+ body: JSON.stringify(body),
+ },
+ "generating the image",
+ );
+ const items = Array.isArray(answer?.data) ? answer.data : [];
+ if (items.length === 0)
+ fail(EXIT.upstream, "api_error", {
+ message: "generating the image failed: the answer carried no data",
+ upstream: JSON.stringify(answer),
+ });
+ const requestId =
+ (typeof answer?.request_id === "string" && answer.request_id) ||
+ (typeof answer?.id === "string" && answer.id) ||
+ headers.get("x-request-id") ||
+ undefined;
+
+ // A group request or a layer split answers several images, so `--out` names a directory then;
+ // an answer that arrives with more images than asked for still gets its own files.
+ const multi = Boolean(args.layers) || (count ?? 1) > 1 || items.length > 1;
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
+ // A single image needs an extension to be openable, and that comes from the answer's format.
+ const fallback = multi
+ ? `seedream-${stamp}`
+ : `seedream-${stamp}.${extensionFor(items[0], format, false)}`;
+ const target = path.resolve(args.out ?? fallback);
+ // Base image first, then the layers in stacking order: the numbering follows that order.
+ const ordered = [...items].sort((a, b) => (zIndexOf(a) ?? -1) - (zIndexOf(b) ?? -1));
+ const stems = multi ? planStems(ordered) : [];
+ const paths = [];
+
+ for (const [index, item] of ordered.entries()) {
+ if (typeof item?.url !== "string" && typeof item?.b64_json !== "string")
+ fail(EXIT.upstream, "api_error", {
+ message: `generating the image failed: image ${index + 1} carried neither url nor b64_json`,
+ upstream: JSON.stringify(item),
+ });
+ const isLayer = zIndexOf(item) !== undefined;
+ const ext = extensionFor(item, format, isLayer);
+ const out = multi ? path.join(target, `${stems[index]}.${ext}`) : target;
+ say(`saving image ${index + 1}/${ordered.length} into ${out}`);
+ try {
+ await saveItem(item, out);
+ } catch (err) {
+ fail(EXIT.download, "download_error", {
+ message: `saving image ${index + 1} failed: ${err.message}`,
+ paths,
+ upstream: err.message,
+ });
+ }
+ paths.push(out);
+ }
+
+ const layers = multi
+ ? ordered
+ .map((item, index) => {
+ const z = zIndexOf(item);
+ if (z === undefined) return undefined;
+ return compact({
+ path: paths[index],
+ z_index: z,
+ name: item.name,
+ size: item.size,
+ bounding_box: item.bounding_box,
+ });
+ })
+ .filter(Boolean)
+ : [];
+
+ const result = compact({
+ ok: true,
+ model: answer?.model ?? model,
+ size: body.size ?? items[0]?.size,
+ request_id: requestId,
+ elapsed_ms: Date.now() - startedAt,
+ paths,
+ layers: layers.length ? layers : undefined,
+ usage: answer?.usage,
+ });
+ process.stdout.write(`${JSON.stringify(result)}\n`);
+ return 0;
+}
+
+try {
+ process.exitCode = await main();
+} catch (err) {
+ if (err instanceof UsageError) {
+ process.stderr.write(`${err.message}\n\n${USAGE}\n`);
+ process.stderr.write(
+ `${JSON.stringify({ ok: false, error: "usage", message: err.message })}\n`,
+ );
+ process.exit(EXIT.usage);
+ }
+ fail(EXIT.unexpected, "unexpected", {
+ message: err instanceof Error ? err.message : String(err),
+ upstream: err instanceof Error ? (err.stack ?? err.message) : String(err),
+ });
+}
diff --git a/plugins/use-seedream/test/seedream.test.mjs b/plugins/use-seedream/test/seedream.test.mjs
new file mode 100644
index 00000000..521f30a8
--- /dev/null
+++ b/plugins/use-seedream/test/seedream.test.mjs
@@ -0,0 +1,361 @@
+/**
+ * The kit's checks: a stub Ark stands in for the real service, so the whole path — request,
+ * download or base64 decode, name the files — runs here without an API key and without spending
+ * anything.
+ *
+ * node --test plugins/use-seedream/test/
+ *
+ * What the stub proves is the script's own behaviour: that it reads the key from the environment
+ * and sends it as a Bearer token, that it builds the documented request body (reference images,
+ * groups, layer decomposition), that it follows the documented answer shape for both `url` and
+ * `b64_json`, that it writes bytes whole and names them only once the write finished, and that
+ * each failure path exits with the code it promises and the upstream text attached.
+ * What it cannot prove is the shape of a REAL success response — that comes from the docs.
+ */
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { promisify } from "node:util";
+import { after, describe, it } from "node:test";
+
+const SCRIPT = path.join(
+ path.dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "skills",
+ "seedream",
+ "kit",
+ "seedream.mjs",
+);
+
+const MODEL = "doubao-seedream-5-0-pro-260628";
+
+/** Distinct bytes per stub image, so the tests can tell which file holds which answer. */
+const bytesFor = (name) => Buffer.from(`a stub image named ${name} that never was\n`);
+
+/**
+ * The stub Ark: one POST answers with whatever the test asked for, and every `/img/<name>` path
+ * serves the bytes `bytesFor(name)` so a download can be traced back to its item.
+ */
+async function startStub({ status = 200, answer } = {}) {
+ // `imageAuthorization` covers the download requests only: a real answer's URL is a signed link,
+ // so the API key must not travel to it, and that is what this records.
+ const seen = { posts: 0, bodies: [], authorizations: [], imageAuthorization: undefined };
+ let root = "";
+ const server = http.createServer((req, res) => {
+ const url = new URL(req.url, "http://stub");
+ const json = (code, value) => {
+ res.writeHead(code, { "content-type": "application/json" });
+ res.end(JSON.stringify(value));
+ };
+ if (req.method === "POST" && url.pathname === "/api/v3/images/generations") {
+ seen.authorizations.push(req.headers.authorization);
+ let body = "";
+ req.on("data", (chunk) => (body += chunk));
+ req.on("end", () => {
+ seen.posts++;
+ seen.bodies.push(JSON.parse(body));
+ json(status, answer(seen, root));
+ });
+ return;
+ }
+ if (req.method === "GET" && url.pathname.startsWith("/img/")) {
+ seen.imageAuthorization = req.headers.authorization;
+ const bytes = bytesFor(url.pathname.slice("/img/".length));
+ res.writeHead(200, { "content-type": "image/png", "content-length": String(bytes.length) });
+ res.end(bytes);
+ return;
+ }
+ json(404, { error: { code: "NotFound", message: "no such stub route" } });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ root = `http://127.0.0.1:${server.address().port}`;
+ const origin = `${root}/api/v3`;
+ // The kit's fetch keeps its connection alive, so closing the listener alone would wait for it:
+ // drop the sockets too, or the run has to sit out undici's keep-alive timeout.
+ const close = () => {
+ server.closeAllConnections();
+ return new Promise((resolve) => server.close(resolve));
+ };
+ return { server, origin, seen, close };
+}
+
+/** One answer image per stub file name, as the `url` form of the documented response. */
+const urlItems = (root, names) => ({
+ model: MODEL,
+ data: names.map((name) => ({
+ url: `${root}/img/${name}.png`,
+ size: "2048x2048",
+ output_format: "png",
+ })),
+ usage: { generated_images: names.length },
+});
+
+const execFileAsync = promisify(execFile);
+
+/**
+ * Runs the kit once, from a throwaway workspace so a default output path lands somewhere safe.
+ * The child runs asynchronously on purpose: the stub lives in this process, and a blocking run
+ * would leave it unable to answer, which is a hang rather than a failing test.
+ */
+async function run(args, { env = {}, workspace } = {}) {
+ // The child resolves a relative `--out` against its own cwd, and the OS reports that as the real
+ // path — on macOS a tmpdir of /var/… comes back as /private/var/… — so hand the real one back and
+ // let the callers compare against the same thing.
+ const dir = fs.realpathSync(
+ workspace ?? fs.mkdtempSync(path.join(os.tmpdir(), "seedream-test-")),
+ );
+ try {
+ const { stdout, stderr } = await execFileAsync(process.execPath, [SCRIPT, ...args], {
+ cwd: dir,
+ encoding: "utf8",
+ env: { PATH: process.env.PATH, ...env },
+ });
+ return { status: 0, stdout, stderr, dir };
+ } catch (err) {
+ return { status: err.code ?? -1, stdout: err.stdout ?? "", stderr: err.stderr ?? "", dir };
+ }
+}
+
+/** The JSON lines of a stream: progress and usage text are plain lines and are skipped here. */
+const jsonLines = (text) =>
+ text
+ .split("\n")
+ .filter((line) => line.startsWith("{") && line.endsWith("}"))
+ .map((line) => JSON.parse(line));
+
+describe("the seedream kit", () => {
+ const servers = new Set();
+ const stub = async (options) => {
+ const s = await startStub(options);
+ servers.add(s);
+ return s;
+ };
+ after(async () => {
+ for (const s of servers) await s.close();
+ });
+
+ it("reports a bad command line instead of guessing at it", async () => {
+ const { status, stderr, stdout } = await run(["--prompt", "a cat", "--bogus", "1"]);
+ assert.equal(status, 2);
+ assert.equal(stdout, "");
+ assert.match(stderr, /unknown option "--bogus"/);
+ assert.deepEqual(jsonLines(stderr).at(-1), {
+ ok: false,
+ error: "usage",
+ message: 'unknown option "--bogus"',
+ });
+ });
+
+ it("demands a prompt, and refuses values the service could only reject", async () => {
+ assert.equal((await run([])).status, 2);
+ const seeded = await run(["--prompt", "a cat", "--seed", "later"]);
+ assert.equal(seeded.status, 2);
+ assert.match(seeded.stderr, /"--seed" needs an integer, got "later"/);
+ assert.equal((await run(["--prompt", "a cat", "--image"])).status, 2);
+ // 1280x720 is the lower bound on total pixels, 4096x4096 the upper one.
+ const tiny = await run(["--prompt", "a cat", "--size", "640x480"]);
+ assert.equal(tiny.status, 2);
+ assert.match(tiny.stderr, /"--size" 640x480 is 307200 pixels/);
+ const huge = await run(["--prompt", "a cat", "--size", "5000x5000"]);
+ assert.equal(huge.status, 2);
+ assert.match(huge.stderr, /accepts between 921600 \(1280x720\) and 16777216/);
+ assert.equal((await run(["--prompt", "a cat", "--format", "webp"])).status, 2);
+ assert.equal((await run(["--prompt", "a cat", "--count", "16"])).status, 2);
+ });
+
+ it("refuses a fifteenth reference image before anything is sent", async () => {
+ const images = Array.from({ length: 15 }, (_, i) => [
+ "--image",
+ `https://example.test/${i}.png`,
+ ]);
+ const { status, stderr } = await run(["--prompt", "a cat", ...images.flat()]);
+ assert.equal(status, 2);
+ assert.match(stderr, /"--image" accepts at most 14 reference images, got 15/);
+ });
+
+ it("says what to do when ARK_API_KEY is missing, and never calls the API", async () => {
+ const s = await stub({ answer: (_seen, root) => urlItems(root, ["one"]) });
+ const { status, stderr } = await run(["--prompt", "a cat"], {
+ env: { ARK_BASE_URL: s.origin },
+ });
+ assert.equal(status, 3);
+ assert.match(stderr, /ARK_API_KEY is not set/);
+ assert.match(stderr, /key vault/);
+ assert.equal(s.seen.posts, 0);
+ });
+
+ it("generates one image, downloads it, and prints one line of JSON", async () => {
+ const s = await stub({ answer: (_seen, root) => urlItems(root, ["one"]) });
+ const { status, stdout, stderr, dir } = await run(
+ ["--prompt", "一只猫晒太阳", "--out", "out/cat.png", "--size", "2K", "--watermark"],
+ { env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin } },
+ );
+ assert.equal(status, 0, stderr);
+ const result = jsonLines(stdout).at(-1);
+ assert.equal(result.ok, true);
+ assert.equal(result.model, MODEL);
+ assert.equal(result.size, "2K");
+ assert.deepEqual(result.usage, { generated_images: 1 });
+ assert.equal(typeof result.elapsed_ms, "number");
+ // The download landed whole, under the requested name…
+ const saved = path.join(dir, "out", "cat.png");
+ assert.deepEqual(result.paths, [saved]);
+ assert.deepEqual(fs.readFileSync(saved), bytesFor("one.png"));
+ // …with no leftover temporary file beside it.
+ assert.deepEqual(fs.readdirSync(path.join(dir, "out")), ["cat.png"]);
+ // The documented request shape, and the key sent as a bearer token.
+ assert.equal(s.seen.posts, 1);
+ assert.deepEqual(s.seen.bodies[0], {
+ model: MODEL,
+ prompt: "一只猫晒太阳",
+ size: "2K",
+ watermark: true,
+ response_format: "url",
+ });
+ assert.deepEqual(s.seen.authorizations, ["Bearer stub-key"]);
+ // An answer URL is a signed link: the key is not sent to it.
+ assert.equal(s.seen.imageAuthorization, undefined);
+ });
+
+ it("writes an inline base64 answer to disk too", async () => {
+ const bytes = bytesFor("inline.png");
+ const s = await stub({
+ answer: () => ({
+ model: MODEL,
+ data: [{ b64_json: bytes.toString("base64"), output_format: "png" }],
+ }),
+ });
+ const { status, stdout, dir } = await run(["--prompt", "a cat", "--out", "inline.png"], {
+ env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin },
+ });
+ assert.equal(status, 0);
+ const result = jsonLines(stdout).at(-1);
+ assert.deepEqual(fs.readFileSync(path.join(dir, "inline.png")), bytes);
+ assert.deepEqual(result.paths, [path.join(dir, "inline.png")]);
+ });
+
+ it("asks for a group of three with sequential generation, and names them in a directory", async () => {
+ const s = await stub({ answer: (_seen, root) => urlItems(root, ["g1", "g2", "g3"]) });
+ const { status, stdout, dir } = await run(
+ ["--prompt", "a cat", "--count", "3", "--out", "group"],
+ { env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin } },
+ );
+ assert.equal(status, 0);
+ const body = s.seen.bodies[0];
+ assert.equal(body.sequential_image_generation, "auto");
+ assert.deepEqual(body.sequential_image_generation_options, { max_images: 3 });
+ assert.equal(body.layer_decomposition, undefined);
+ const result = jsonLines(stdout).at(-1);
+ assert.deepEqual(
+ result.paths.map((p) => path.relative(dir, p)),
+ ["group/001-base.png", "group/002-base.png", "group/003-base.png"],
+ );
+ assert.deepEqual(fs.readdirSync(path.join(dir, "group")).sort(), [
+ "001-base.png",
+ "002-base.png",
+ "003-base.png",
+ ]);
+ assert.deepEqual(fs.readFileSync(path.join(dir, "group", "002-base.png")), bytesFor("g2.png"));
+ assert.equal(result.layers, undefined);
+ });
+
+ it("splits into layers, naming each by its z index with the base image first", async () => {
+ const s = await stub({
+ answer: (_seen, root) => ({
+ model: MODEL,
+ data: [
+ { url: `${root}/img/base.png`, size: "2048x2048", output_format: "png" },
+ {
+ url: `${root}/img/back.png`,
+ z_index: 1,
+ name: "背景",
+ description: "the whole background",
+ output_format: "png",
+ bounding_box: {
+ absolute: { x: 0, y: 0, width: 2048, height: 2048 },
+ normalized: { x: 0, y: 0, width: 1, height: 1 },
+ },
+ },
+ {
+ url: `${root}/img/cat.png`,
+ z_index: 0,
+ name: "cat outline",
+ description: "the cat",
+ output_format: "png",
+ bounding_box: {
+ absolute: { x: 100, y: 200, width: 300, height: 400 },
+ normalized: { x: 0.05, y: 0.1, width: 0.15, height: 0.2 },
+ },
+ },
+ ],
+ }),
+ });
+ const { status, stdout, dir } = await run(
+ ["--prompt", "a cat", "--layers", "--out", "layers"],
+ { env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin } },
+ );
+ assert.equal(status, 0);
+ assert.equal(s.seen.bodies[0].layer_decomposition, true);
+ const result = jsonLines(stdout).at(-1);
+ // Base first, then z0, then z1 — the running number follows the stacking order…
+ assert.deepEqual(
+ result.paths.map((p) => path.relative(dir, p)),
+ ["layers/001-base.png", "layers/002-z0-cat-outline.png", "layers/003-z1-layer.png"],
+ );
+ // …and the Chinese layer name cleans to nothing, so the fallback stands in for it.
+ assert.deepEqual(fs.readdirSync(path.join(dir, "layers")).sort(), [
+ "001-base.png",
+ "002-z0-cat-outline.png",
+ "003-z1-layer.png",
+ ]);
+ assert.deepEqual(
+ fs.readFileSync(path.join(dir, "layers", "002-z0-cat-outline.png")),
+ bytesFor("cat.png"),
+ );
+ // The JSON repeats the layers in z order, with their names and boxes.
+ assert.deepEqual(
+ result.layers.map((layer) => [layer.z_index, layer.name]),
+ [
+ [0, "cat outline"],
+ [1, "背景"],
+ ],
+ );
+ assert.deepEqual(result.layers[0].bounding_box, {
+ absolute: { x: 100, y: 200, width: 300, height: 400 },
+ normalized: { x: 0.05, y: 0.1, width: 0.15, height: 0.2 },
+ });
+ assert.equal(result.layers[0].path, path.join(dir, "layers", "002-z0-cat-outline.png"));
+ });
+
+ it("inlines a local reference image as a data URL", async () => {
+ const s = await stub({ answer: (_seen, root) => urlItems(root, ["one"]) });
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "seedream-test-"));
+ fs.writeFileSync(path.join(dir, "first.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
+ const { status } = await run(["--prompt", "a cat", "--image", "first.png"], {
+ env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin },
+ workspace: dir,
+ });
+ assert.equal(status, 0);
+ assert.equal(s.seen.bodies[0].image, "data:image/png;base64,iVBORw==");
+ });
+
+ it("carries the service's own words when the request is refused", async () => {
+ const s = await stub({
+ status: 404,
+ answer: () => ({ error: { code: "NotFound", message: "the model does not exist" } }),
+ });
+ const { status, stdout, stderr } = await run(["--prompt", "a cat"], {
+ env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin },
+ });
+ assert.equal(status, 4);
+ assert.equal(stdout, "");
+ const failure = jsonLines(stderr).at(-1);
+ assert.equal(failure.error, "api_error");
+ assert.equal(failure.status, 404);
+ assert.match(failure.upstream, /the model does not exist/);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fd6145af..0f3cfea6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -129,6 +129,9 @@ importers:
'@adelie/use-seedance':
specifier: workspace:*
version: link:../../plugins/use-seedance
+ '@adelie/use-seedream':
+ specifier: workspace:*
+ version: link:../../plugins/use-seedream
'@adelie/use-wps-office':
specifier: workspace:*
version: link:../../plugins/use-wps-office
@@ -232,6 +235,9 @@ importers:
'@adelie/use-seedance':
specifier: workspace:*
version: link:../../plugins/use-seedance
+ '@adelie/use-seedream':
+ specifier: workspace:*
+ version: link:../../plugins/use-seedream
'@adelie/use-wps-office':
specifier: workspace:*
version: link:../../plugins/use-wps-office
@@ -341,6 +347,9 @@ importers:
'@adelie/use-seedance':
specifier: workspace:*
version: link:../../plugins/use-seedance
+ '@adelie/use-seedream':
+ specifier: workspace:*
+ version: link:../../plugins/use-seedream
'@adelie/use-wps-office':
specifier: workspace:*
version: link:../../plugins/use-wps-office
@@ -840,6 +849,8 @@ importers:
plugins/use-seedance: {}
+ plugins/use-seedream: {}
+
plugins/use-wps-office: {}
plugins/wechat-miniprogram: {}
@@ -926,6 +937,9 @@ packages:
'@adelie/use-seedance@file:plugins/use-seedance':
resolution: {directory: plugins/use-seedance, type: directory}
+ '@adelie/use-seedream@file:plugins/use-seedream':
+ resolution: {directory: plugins/use-seedream, type: directory}
+
'@adelie/use-wps-office@file:plugins/use-wps-office':
resolution: {directory: plugins/use-wps-office, type: directory}
@@ -4964,6 +4978,7 @@ snapshots:
'@adelie/use-lieflat-charts': file:plugins/use-lieflat-charts
'@adelie/use-offerdao': file:plugins/use-offerdao
'@adelie/use-seedance': file:plugins/use-seedance
+ '@adelie/use-seedream': file:plugins/use-seedream
'@adelie/use-wps-office': file:plugins/use-wps-office
'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
@@ -5005,6 +5020,7 @@ snapshots:
'@adelie/use-lieflat-charts': file:plugins/use-lieflat-charts
'@adelie/use-offerdao': file:plugins/use-offerdao
'@adelie/use-seedance': file:plugins/use-seedance
+ '@adelie/use-seedream': file:plugins/use-seedream
'@adelie/use-wps-office': file:plugins/use-wps-office
'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
@@ -5042,6 +5058,7 @@ snapshots:
'@adelie/use-lieflat-charts': file:plugins/use-lieflat-charts
'@adelie/use-offerdao': file:plugins/use-offerdao
'@adelie/use-seedance': file:plugins/use-seedance
+ '@adelie/use-seedream': file:plugins/use-seedream
'@adelie/use-wps-office': file:plugins/use-wps-office
'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
@@ -5154,6 +5171,8 @@ snapshots:
'@adelie/use-seedance@file:plugins/use-seedance': {}
+ '@adelie/use-seedream@file:plugins/use-seedream': {}
+
'@adelie/use-wps-office@file:plugins/use-wps-office': {}
'@adelie/wechat-miniprogram@file:plugins/wechat-miniprogram': {}