Skip to content

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

feat(core,server,web,cli): 模型库多一个火山方舟分组,对话里能收视频

lmliheng0c43f7c4c30c
diff --git a/README.md b/README.md
index eb72a80f..4271656c 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`, `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`, `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 72ac0555..9d82bb07 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`、`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`、`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-26-seedance-plugin.md b/changelog/unreleased/2026-10-26-seedance-plugin.md
new file mode 100644
index 00000000..5b3bbb59
--- /dev/null
+++ b/changelog/unreleased/2026-10-26-seedance-plugin.md
@@ -0,0 +1,45 @@
+# A new plugin: ask Adelie for a video, get one (Volcengine Ark Seedance)
+
+- **Date:** 2026-10-26
+- **Type:** feat
+- **Scope:** `plugins`, `docs`
+- **Breaking:** no
+
+[中文](2026-10-26-seedance-plugin.zh.md)
+
+The plugin library gains `use-seedance`: tell your Agent to "make a video of … with Seedance" and it
+generates an mp4 with Volcengine Ark's Doubao Seedance models, saves it into the workspace and hands
+you the file. It is Adelie's first capability that **produces** video — the eleven Ark rows in the
+model library understand video, this plugin makes it.
+
+It ships preinstalled. What is missing is the key: collect an API key from the Ark console and add it
+to this Agent's **key vault** as `ARK_API_KEY`. Video is billed by the second and the resolution, so
+the Agent reads the prompt back to you before submitting rather than firing off a batch of variants.
+
+## Details
+
+- **The plugin** (`plugins/use-seedance/`): `skills/seedance/SKILL.md` is what the Agent reads, and
+ `skills/seedance/kit/seedance.mjs` is the whole runtime — one dependency-free Node file that walks
+ Ark's asynchronous three steps for it: `POST /contents/generations/tasks` to submit,
+ `GET …/tasks/{id}` to poll with a bounded wait and a backing-off interval, and a download of the
+ `content.video_url` it ends on. Default model `doubao-seedance-2-5-260628`, with optional first
+ frame / last frame / reference images, duration, ratio, resolution, seed, watermark and audio.
+- **The key is read from the environment only** (injected from the vault) and never written to disk;
+ the download goes through a temporary file that only gets its final name once it finished, so a
+ half-written video never wears it. Exit codes classify the outcome (missing key / refused request
+ / failed task / timeout / download failure), and stdout carries one JSON line with the path and the
+ task id.
+- **Registration**: one line each in `packages/{core,cli,desktop}/package.json`
+ (`"@adelie/use-seedance": "workspace:*"`), plus a row in the library's category tables, the two
+ root READMEs and the docs page's plugin table — which is exactly what
+ `packages/core/test/plugins.test.ts` and `packages/docs/test/skills-sync.test.ts` guard.
+- Tests: the eight in `plugins/use-seedance/test/seedance.test.mjs` — a stub server stands in for Ark,
+ so submit → poll → download → rename runs end to end on this machine, and the key is asserted to go
+ to the API only and never to the video URL (a real task returns a signed link).
+
+## Compatibility
+
+- No new runtime dependency (the script is a dependency-free Node file), so the package adds
+ practically nothing to an install.
+- It is preinstalled for newly created Agents; existing Agents install it from the library once.
+ Without a key the script only tells you `ARK_API_KEY` is missing and touches nothing else.
diff --git a/changelog/unreleased/2026-10-26-seedance-plugin.zh.md b/changelog/unreleased/2026-10-26-seedance-plugin.zh.md
new file mode 100644
index 00000000..73b4a446
--- /dev/null
+++ b/changelog/unreleased/2026-10-26-seedance-plugin.zh.md
@@ -0,0 +1,37 @@
+# 多了一个插件:一句话让 Adelie 生成视频(火山方舟 Seedance)
+
+- **Date:** 2026-10-26
+- **Type:** feat
+- **Scope:** `plugins`, `docs`
+- **Breaking:** no
+
+[English](2026-10-26-seedance-plugin.md)
+
+插件库里多了一个 `use-seedance`:跟 Agent 说「用 Seedance 做一段…的视频」,它就用火山方舟的豆包
+Seedance 生成一个 mp4 落到工作区,再把文件给你。这是 Adelie 第一个**产出视频**的能力——模型库那 11 条
+方舟条目负责看得懂视频,这个插件负责做得出来。
+
+装上就有(默认预装)。缺的是密钥:去方舟控制台领一把 API key,加到这个 Agent 的**密钥库**里,键名
+`ARK_API_KEY`。视频按秒和分辨率计费,所以 Agent 在提交前会把提示词跟你对一遍,不会「多跑几个版本看看」。
+
+## 细节
+
+- **插件**(`plugins/use-seedance/`):`skills/seedance/SKILL.md` 是 Agent 读的说明书,
+ `skills/seedance/kit/seedance.mjs` 是全部运行时——一个零依赖的 Node 文件,替 Agent 走完方舟那套异步
+ 三步:`POST /contents/generations/tasks` 提交、`GET …/tasks/{id}` 在最大等待时长内按退避间隔轮询、拿到
+ `content.video_url` 后下载。默认模型 `doubao-seedance-2-5-260628`,可选首帧 / 尾帧 / 参考图、
+ 时长、比例、分辨率、种子、水印、是否出声。
+- **密钥只从环境读**(密钥库注入),脚本不落盘;下载先写临时文件、下完才改名,半截视频不会顶着成品的名字。
+ 退出码把结果分类(缺 key / 服务拒绝 / 任务失败 / 超时 / 下载失败),stdout 只有一行 JSON,路径与任务 id
+ 都在里面。
+- **登记**:`packages/{core,cli,desktop}/package.json` 各加一行 `"@adelie/use-seedance": "workspace:*"`,
+ 插件库、两份 README 的分类表与文档页的插件表跟着加一行(`packages/core/test/plugins.test.ts` 与
+ `packages/docs/test/skills-sync.test.ts` 就是钉这个的)。
+- 测试:`plugins/use-seedance/test/seedance.test.mjs` 八条——桩服务冒充方舟,提交 → 轮询 → 下载 → 改名
+ 整条路在本机跑完,并断言密钥只发往接口、不发给视频 URL(真实任务返回的是签名链接)。
+
+## 兼容性
+
+- 没有新运行时依赖(脚本是零依赖的 Node),装包体积可以忽略。
+- 它默认预装在新建的 Agent 上;已存在的 Agent 从插件库装一次。没有密钥时脚本只会告诉你缺 `ARK_API_KEY`,
+ 不会去动别的配置。
diff --git a/changelog/unreleased/2026-10-26-video-input.md b/changelog/unreleased/2026-10-26-video-input.md
new file mode 100644
index 00000000..9655bdd3
--- /dev/null
+++ b/changelog/unreleased/2026-10-26-video-input.md
@@ -0,0 +1,60 @@
+# A video can now go into the chat: drop a clip in and the model watches it
+
+- **Date:** 2026-10-26
+- **Type:** feat
+- **Scope:** `core`, `server`, `web`, `docs`
+- **Breaking:** no
+
+[中文](2026-10-26-video-input.zh.md)
+
+The composer's paperclip menu gains **Upload video**, and a clip can be dropped or pasted in as
+well. Before sending it shows as a card with its first frame, name and size (removable); after
+sending it is a video in the conversation, playable and full-screen.
+
+When the Session's model **takes video input** (the Seed family and friends — their card says
+**Video**), the clip rides this turn's request as a video content part: the model can describe it,
+summarize it, answer questions about what is on screen, with no intermediate step. When the model
+**does not**, the send is not refused either: the clip lands in the Session scratchpad and the
+message carries an `[attached file: …]` line, exactly like an attachment, for the Agent to open
+with its own tools. The frontend never asks you which kind of model this is; the server decides.
+
+## Details
+
+- **AgentHub patch** (`patches/@prismshadow__agenthub.patch`, produced with `pnpm patch` and
+ registered under `patchedDependencies` in `pnpm-workspace.yaml`, pinned to 0.4.15): the
+ `ContentItem` union gains `{ type: "video_url"; video_url: string }`, and
+ `transformUniMessageToModelInput` gains the branch that turns it into Chat Completions'
+ `{"type":"video_url","video_url":{"url":…}}` — the shape providers ask for (Ark's video
+ understanding API). Unlike an image the video is **not** re-encoded to base64; it is passed
+ through as the data URL it already is.
+- **core**: `VideoUrlPayload` and `videoUrlMessage()` in the omni-message public API; a video budget
+ on `GenerativeModel` (`maxVideos`) — one clip per request, older ones replaced by an
+ `[video omitted: …]` line, because a video request is tens of megabytes of base64 and a history
+ replaying two of them would be refused for good. The limit comes from
+ `catalogSupportsVideo(provider, modelId)` (or the entry's `video` annotation).
+- **server**: a task input part `{type:"video_url", videoUrl, fileName?}` and a `videos` field on
+ `/steer`; an inline video is capped at **32MB** (413 `video_too_large` — Ark takes a video under
+ 50MB inside a 64MB body and base64 inflates by 4/3) and must be a `data:video/…` URL; on a model
+ that takes no video the clip becomes an attachment instead (an http(s) URL cannot be written to
+ disk, and that combination is a 400 that says why). The model list reports `video`, `/api/me`
+ reports `videoMaxMb`, and the composer uses both for its pre-flight check and its branch.
+- **History pages**: a `video_url` is served by reference like an image (new route
+ `GET /api/sessions/:id/trace-video?file=&ordinal=`, in `services/trace-media.ts` — the old
+ `trace-images.ts` was renamed into it), or one page would read tens of megabytes of base64 whole.
+ Recalling an undelivered message (#287) hands an inline video back to the composer as submitted.
+- Docs: the notes in `models.zh.md` / `models.en.md` carry the **Video** label and both paths.
+- Tests: `server/test/video-input.test.ts` (inline / written to disk / a nameless clip named after
+ its type / a non-video data URL / the 413 / both steering paths) and
+ `server/test/trace-media.test.ts` (video by reference, its bytes and type, the 404s and 400s).
+
+## Compatibility
+
+- One **patch** is now part of the install: `pnpm install` applies
+ `patches/@prismshadow__agenthub.patch` (pnpm computes a `_patch_hash` for it); the package is
+ still the published `@prismshadow/[email protected]`. Upstream has no `video_url` support yet, which
+ is why the patch is version-pinned — an upstream bump makes pnpm complain rather than silently
+ dropping it.
+- The server API only grows: old input parts and old `/steer` bodies behave as before; `/api/me` and
+ the model list carry extra fields that old clients ignore.
+- A Session that never carries a video is unaffected: the video budget is a no-op when no video is
+ in play.
diff --git a/changelog/unreleased/2026-10-26-video-input.zh.md b/changelog/unreleased/2026-10-26-video-input.zh.md
new file mode 100644
index 00000000..a51707f0
--- /dev/null
+++ b/changelog/unreleased/2026-10-26-video-input.zh.md
@@ -0,0 +1,48 @@
+# 对话界面能收视频了:把片子拖进输入框,模型可以直接看
+
+- **Date:** 2026-10-26
+- **Type:** feat
+- **Scope:** `core`, `server`, `web`, `docs`
+- **Breaking:** no
+
+[English](2026-10-26-video-input.md)
+
+输入框的回形针菜单多了一项**上传视频**,也可以直接把视频拖进来或粘贴进来。选中的视频在发送前显示成一张
+能看第一帧的卡片(带文件名和大小,可删),发出去之后在对话里就是一个能播放、能全屏的视频。
+
+会话用的模型**接受视频输入**时(模型库里的 Seed 系列等,卡片上标着**视频**),这段片子会作为视频内容随这
+一轮请求直接发给模型——模型能描述它、总结它、就画面提问,不需要任何中间步骤。模型**不接受视频**时也不会被
+拒绝:片子会落到这个会话的暂存目录,消息里出现一行 `[attached file: …]`,由 Agent 自己用工具处理,和附件
+完全一样。前端不需要你去判断模型属于哪一种,服务端按模型决定。
+
+## 细节
+
+- **AgentHub 补丁**(`patches/@prismshadow__agenthub.patch`,用 `pnpm patch` 生成并已登记在
+ `pnpm-workspace.yaml` 的 `patchedDependencies`,锁定 0.4.15):`ContentItem` 联合类型加上
+ `{ type: "video_url"; video_url: string }`,`transformUniMessageToModelInput` 里加一条分支把它翻成
+ Chat Completions 的 `{"type":"video_url","video_url":{"url":…}}`。服务商要的就是这个形状(火山方舟的
+ 视频理解接口),视频**不做 base64 重新编码**——与图片不同,图片拿到的是完整的 data URL。
+- **core**:`VideoUrlPayload` + `videoUrlMessage()`(`omni-message` 的 public API);
+ `GenerativeModel` 加上视频预算(`maxVideos`)——一次请求只带一个视频,更旧的换成一行
+ `[video omitted: …]`,因为一次视频请求是几十兆的 base64,历史里攒两个视频会被服务商永久拒绝。上限由
+ `catalogSupportsVideo(provider, modelId)`(或条目上的 `video` 注解)决定。
+- **服务端**:任务输入新增部件 `{type:"video_url", videoUrl, fileName?}`,`/steer` 新增同名的
+ `videos` 字段;内联视频上限 **32MB**(413 `video_too_large`,方舟本身是「视频 <50MB、请求体 <64MB」,
+ base64 涨 4/3),必须 `data:video/…`;模型不吃视频时自动落成附件(http(s) 地址无法落盘,这种组合直接 400
+ 并说明原因)。模型列表多报一个 `video`,`/api/me` 多报一个 `videoMaxMb`,前端据此做预检与分支。
+- **历史页**:`video_url` 和图片一样按引用下发(新路由
+ `GET /api/sessions/:id/trace-video?file=&ordinal=`,由 `services/trace-media.ts` 提供,旧的
+ `trace-images.ts` 一并改名合并),否则一页历史要把几十兆 base64 整份读回来。撤回未发出的消息(#287)
+ 也会把内联视频原样还回输入框。
+- 文档:`models.zh.md` / `models.en.md` 的笔记里写明「视频」标签与两种走法。
+- 测试:`server/test/video-input.test.ts`(内联 / 落盘 / 无名视频按类型命名 / 非视频数据 URL / 超限 413 /
+ 中途 steering 的两种走法)、`server/test/trace-media.test.ts`(视频按引用、字节与类型、404 与 400)。
+
+## 兼容性
+
+- 依赖多了一份**补丁**:`pnpm install` 会应用 `patches/@prismshadow__agenthub.patch`(pnpm 会为它算
+ `_patch_hash`),npm 上仍是官方 `@prismshadow/[email protected]`。上游还没有 `video_url` 支持,所以补丁
+ 锁定版本号——上游升版时 pnpm 会报冲突而不是悄悄丢掉它。
+- 服务端接口只增不改:老的 `input` 部件、老的 `/steer` 请求照旧;`/api/me` 与模型列表多了字段,旧客户端
+ 忽略即可。
+- 没有视频的会话完全不受影响:视频预算是「从未带过视频」时的空操作。
diff --git a/changelog/unreleased/2026-10-26-volcengine-ark.md b/changelog/unreleased/2026-10-26-volcengine-ark.md
new file mode 100644
index 00000000..21d2ada6
--- /dev/null
+++ b/changelog/unreleased/2026-10-26-volcengine-ark.md
@@ -0,0 +1,50 @@
+# Volcengine Ark (ByteDance) joins the model library, Doubao Seed included
+
+- **Date:** 2026-10-26
+- **Type:** feat
+- **Scope:** `core`, `web`, `ui`, `docs`
+- **Breaking:** no
+
+[中文](2026-10-26-volcengine-ark.zh.md)
+
+The model library gains a Volcengine Ark group, sitting just after iFlytek. It carries the eleven
+models served by ByteDance's own platform, Ark: seven of the Doubao Seed family, plus the four Ark
+resells (GLM, Kimi, two DeepSeek). A Project gets them with **Sync presets** or from its next new
+Project.
+
+Everything is one OpenAI-compatible endpoint, `https://ark.cn-beijing.volces.com/api/v3`, so an Ark
+console API key pasted into the group header is all it takes: no protocol to pick, no endpoint to
+type. Seven of the eleven rows take video input — the six Doubao Seed rows and the resold GLM-5.3-Flash — and
+are labelled **Video** on their card.
+
+## Details
+
+- **The rows** (`core/src/state/model-catalog.ts`): `doubao-seed-evolving`, `doubao-seed-2-1-pro-260915`,
+ `doubao-seed-2-1-lite-260915`, `doubao-seed-2-1-turbo-260628`, `doubao-seed-2-0-lite-260428`,
+ `doubao-seed-2-0-mini-260428`, `doubao-seed-character-260628`, and `glm-5-3-flash-260828`,
+ `kimi-k3-1-pro-261024`, `deepseek-v4-1-flash-261017`, `deepseek-v4-pro-ga-260813`. Windows,
+ modalities and prices are read from Ark's own model list and pricing page (2026-10-25); the
+ published CNY-per-million rates are stored as USD at a fixed 7:1. Ark prices by input length and
+ only the base tier is recorded. `deepseek-v4-1-flash-261017`'s peak/off-peak pair matches
+ DeepSeek's own, so it reuses that off-peak rule.
+- **Protocol and credentials.** Ark has no AgentHub client, so every row pins Chat Completions
+ (`openai-chat`) and carries the endpoint on itself; a keyless row is refused rather than sent the
+ `OPENAI_API_KEY` the generic client would read.
+- **Video input.** `ModelCatalogEntry` gains `supportsVideo` (default **unsupported**; only `true` is
+ ever written) and the seven multimodal rows carry it (the six Doubao Seed rows and GLM-5.3-Flash). The
+ model list reports it as `video`, which is what the composer reads to decide whether a clip rides to the
+ model or lands as a file (see the next change).
+- **Brand marks.** `packages/ui`'s provider logos gain real marks for Ark and for Abliteration
+ (from each vendor's own site, flattened to one colour, wordmark and plate dropped), so the model
+ library and the model picker stop showing a letter tile for them.
+- Docs: a row in the provider table, a section per language, a row in the preset table and the
+ **Video** card label in `packages/docs/content/models.zh.md` / `models.en.md`.
+- Tests: `core/test/model-catalog.test.ts` (group order, gateway set, the rows that carry a base URL,
+ the off-peak list) and the group order in `web/test/model-grouping.test.ts`.
+
+## Compatibility
+
+- No dependency change and nothing stored is rewritten: an existing Project keeps its rows, and the
+ new group appears with its eleven presets after **Sync presets**.
+- The Ark endpoint is only used once a Session is switched to one of these models; existing Sessions
+ keep theirs.
diff --git a/changelog/unreleased/2026-10-26-volcengine-ark.zh.md b/changelog/unreleased/2026-10-26-volcengine-ark.zh.md
new file mode 100644
index 00000000..787362c0
--- /dev/null
+++ b/changelog/unreleased/2026-10-26-volcengine-ark.zh.md
@@ -0,0 +1,41 @@
+# 模型库里多了字节跳动的火山方舟,豆包 Seed 可以直接选
+
+- **Date:** 2026-10-26
+- **Type:** feat
+- **Scope:** `core`, `web`, `ui`, `docs`
+- **Breaking:** no
+
+[English](2026-10-26-volcengine-ark.md)
+
+**模型库**页面多了一个 Volcengine Ark 分组,排在讯飞之后。它收录的是字节跳动自家模型平台火山方舟
+(Volcengine Ark)上的 11 个模型:豆包 Seed 七条,加上方舟转售的 GLM、Kimi、DeepSeek 四条。已有的项目点一次
+**同步预置**就有,新建的项目直接带着。
+
+整个分组只有一个 OpenAI 兼容端点 `https://ark.cn-beijing.volces.com/api/v3`,把方舟控制台的 API key 填进
+分组标题栏就完事:不用挑协议,也不用填端点。11 条里有七条接受视频输入(豆包 Seed 六条,加方舟转售的
+GLM-5.3-Flash),卡片上会标**视频**。
+
+## 细节
+
+- **11 个条目**(`core/src/state/model-catalog.ts`):`doubao-seed-evolving`、`doubao-seed-2-1-pro-260915`、
+ `doubao-seed-2-1-lite-260915`、`doubao-seed-2-1-turbo-260628`、`doubao-seed-2-0-lite-260428`、
+ `doubao-seed-2-0-mini-260428`、`doubao-seed-character-260628`,以及 `glm-5-3-flash-260828`、
+ `kimi-k3-1-pro-261024`、`deepseek-v4-1-flash-261017`、`deepseek-v4-pro-ga-260813`。窗口、模态与价格读自方舟
+ 官网的模型列表与定价页(2026-10-25),人民币按 7:1 折成目录里的美元存储;方舟按输入长度分档计价,只记基础档。
+ `deepseek-v4-1-flash-261017` 的峰谷价与 DeepSeek 自家那套一致,复用同一份空闲时段规则。
+- **协议与凭证**:方舟没有对应的 AgentHub 客户端,所以每个条目都固定 Chat Completions(`openai-chat`)并把端点
+ 写在条目上;没有 key 的条目会被拒绝,而不是把 `OPENAI_API_KEY` 发给它。
+- **视频输入**:`ModelCatalogEntry` 新增 `supportsVideo`(默认**不支持**,只有 `true` 才写),目录里七条
+ 带这个标记(豆包 Seed 六条与 `glm-5-3-flash-260828`);模型列表把它报成 `video`,对话输入框据此决定视频是
+ 内联发给模型还是落成文件(见下一条变更)。
+- **品牌标**:`packages/ui` 的 provider logo 补上火山方舟与 Abliteration 两个真标(分别取自两家官网,压成
+ 单色,丢弃字标与底板),模型库、模型选择器里不再显示字母牌。
+- 文档:`packages/docs/content/models.zh.md` 与 `models.en.md` 的分组表各一行、各一节,预置模型表补一行,
+ 「视频」这个卡片标签也写进去。
+- 测试:`core/test/model-catalog.test.ts`(分组顺序、网关集合、带端点预置清单、错峰行清单)、
+ `web/test/model-grouping.test.ts`(分组默认顺序)。
+
+## 兼容性
+
+- 没有依赖变化,也没重写已存数据:老项目自己的条目原样保留,点一次**同步预置**才会把这十一条补进来。
+- 会话只有在你把某个 Session 换成这些模型时才会用到方舟端点;已有会话的模型不变。
diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.md
index cfccc910..b09ad748 100644
--- a/docs/FORK-PROGRESS.md
+++ b/docs/FORK-PROGRESS.md
@@ -2233,6 +2233,7 @@ v0.2.2」——它只加台账里 v0.2.2 那一节与两行表格,**跟本轮
| 2026-10-25 | 7.45 | **「标记阻塞」那张表单:被拒时表单留着,填过的原因也留着**(不是移植:1 处源码 `packages/web/src/features/company/ticket-dialog.tsx`(+46 −21:底栏那段内联写入收成 `commitBlock()`、关表单与清空字段都挪进写入内部、与另外三张框共用那份 `refusal`、表单顶部画一条 `NoticeStrip`(`role="alert"`,正文在 `data-slot="body"`)、`Modal` 的 `onClose` 在写入在途时不再响应)+ 既有的 `packages/web/e2e/ticket-refusal.spec.mjs` 增加第 5 条(标记阻塞)+ changelog 一对,**无新依赖、不碰接口、无新文案**):7.44 末尾点名的下一处,也是那条「点击即关、失败只弹 toast」扫描线在 `features/company/` 上的第九处、其中唯一一张**表单**框 —— 被拒时要留的不止一句原话,还有那两个字段里刚敲进去的内容。**现在**:只有写入落地才关表单并清空字段;被拒时服务端原话画在字段上方(`S.common.refused`),原因与「等谁」原样留着,重试就是再按一次;开表单前清掉上一次的原因,换工单时也清 | 六包 `typecheck` **`EXIT=0`**(六个 `Done`;`gen:ifaces` 报 **`src/ifaces.json unchanged`**,195 接口 / 589 类型 —— 本笔不动服务契约)· `npx oxlint` 两个改动文件 **0 警告 0 错误** · 四个改动文件 `prettier --check` 干净(前两份首跑一条,`--write` 后复检)· `git diff --check` 干净 · 逐包 test **`EXIT=0`、0 失败**:core **69 通过文件 + 1 跳过 / 1420 通过 / 6 跳过** · ui **130 / 1053** · cli **38 / 561** · web **265 / 3249 通过 / 2 跳过** · server **203 / 2970 通过 / 4 跳过** · hmr 无测试文件 · **真服务 + 真浏览器单 spec**(`/root/adelie-fork-data/r131-e2e`,服务 8940、mock 8941,`packages/{core,server,web}/dist` 都是本轮新构建):`ticket-refusal.spec.mjs` **5 passed(15.9s)**,还原后复跑 **5 passed(17.3s)** · **反证(同一份 spec,两种产物)**:把这一处源码 `git stash push -- packages/web/src/features/company/ticket-dialog.tsx`(只带这一个路径)、重建 web、同一条命令 → **1 failed / 4 passed**,新那条死在 `getByRole('dialog', { name: '标记阻塞' }).getByText(…mid-rewrite…)`(`element(s) not found`:改前表单已经关了)· **两态实测真看一眼**(探针 `r131/probe.mjs`,两态各跑一次,同一个 `page.route` 500,1440×900,读数取被拒后 1.5 s 与 6.5 s 两次):**改前** `{formVisible:false, inFormReason:0, noticeCarriesReason:true}` → 6.5 s 后 `noticeCarriesReason:false`(屏幕上一点解释都没有了),截图 `r131/before/shots/2-refused.png` 里正是「表单不在、一条红 toast 浮在工单上方」;**改后** `{formVisible:true, inFormReason:1, noticeCarriesReason:false, fieldValue:"等市场站点的备案下来"}`,6.5 s 后原样还在 —— 截图 `r131/after/shots/2-refused.png` 里原因画在字段上面、原因还在框里;两态服务端上的工单都没被标记阻塞(`blockedOnServer:false`),console 里的 error 只有三条:登录前的 `/api/me` 401(这个 App 的正常首访应答)、`/api/projects/…/machines` 403(那条路由本来就只给管理员,探针账号是普通成员)与刻意造的 500,**无 `pageerror`** · 端口只用 8940 / 8941,跑完都已停;3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据只落在 `/root/adelie-fork-data/r131-e2e` 与 scratchpad 的 `r131/` 下(`packages/*/dist`、`packages/web/test-results/` 都是产物,未 `git add`)· 没有切版本号、没发 npm、没发安装包、没发发布汇总 | `9eeef95d` |
| 2026-10-26 | 7.46 | **新建工单被拒时,表单留着、填过的每个字段也留着**(不是移植:1 处源码 `packages/web/src/features/company/tickets-page.tsx` —— `CreateTicketDialog` 加一份 `refusal` 状态、写入失败的原话改由 `NoticeStrip` 画在字段上方、每次开表单先清空它、`Modal` 的 `onClose` 在写入在途时不再响应(`toastError` 也从这份文件的 import 里去掉了)+ 1 个新文件 `packages/web/e2e/ticket-create-refusal.spec.mjs`(1 条用例)+ changelog 一对,**无新依赖、不碰接口、无新文案**):那条「点击即关、失败只弹 toast」扫描线在 `features/company/` 上的第十处,也是其中唯一一处**写入不关框、只是原因会消失**的写点 —— 被拒之后几秒,通知没了,面板一点没变、按钮又亮着,没有任何东西说明为什么。现在原因留在表单里、字段原样留着,重试就是再按一次 | 六包 `typecheck` `EXIT=0`;`npx oxlint` 两个改动文件 0 警告 0 错误;`prettier --check` 与 `git diff --check` 干净 · 逐包 test `EXIT=0`:core **1420 通过 / 6 跳过**(69 文件)· ui **1053**(130)· cli **561**(38)· web **3249 通过 / 2 跳过**(265 文件)· server **2970 通过 / 4 跳过**(203 文件)· **真服务**(8950)+ mock(8951)+ 当天新构建的 `packages/{core,server,web}/dist`:新 spec **1 / 1 通过(3.3s)**,回归 `ticket-refusal.spec.mjs` **5 / 5 通过**;**反证**:把那一处源码 `git stash push --`(只带这一个路径)、重建 web → 同一条命令 **1 failed**(`element(s) not found`:改前表单里没有那句原话)· **两态探针**(`r132/probe.mjs`,各跑一次,同一个 `page.route` 500,读数取被拒后 1.5 s 与 6.5 s 两次):**改前** `reasonInForm:0`、`reasonInNotice:1 → 0`(通知几秒后自己消失,截图 `r132/before/shots/3-six-seconds-later.png` 里表单还在、一句原因都没有);**改后** `reasonInForm:1`、`reasonInNotice:0`,6.5 s 后原样还在(截图 `r132/after/shots/2-refused.png` 里红色提示条在标题上方);两态服务端上的工单数都是 0、两态 console 的 error 只有既有的 `/machines` 403 与刻意造的 500,无 `pageerror` · 端口只用 8950 / 8951(跑完都已停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰 | `df07b72d` |
| 2026-10-26 | 7.47 | **财务页改预算被拒时,框留着、填过的金额与原因都留着**(不是移植:1 处源码 `packages/web/src/features/company/finance-page.tsx`(+46 −5:`BudgetEditor` 多一份 `refusal` 与一句「读不懂」的自有提示(复用既有 `budgetHint` 文案)、画在框下方那一行(`role="alert"`);`FinancePage` 把拒绝文案按员工存在 `budgetRefusal` 里,开框 / 取消 / 落地都清掉;`saveBudget` 的 `catch` 不再 `toastError`,`toastError` 也从这份文件的 import 里去掉了。**顺手修一处真 bug**:写入在途时输入框被置灰、焦点随之离开,而「焦点离开也保存」又把同一次写入发了一遍 —— 一次保存过去写两次;编辑器现在用一个在途标记(`asking`,`busy` 落下时重置)挡掉第二发)+ 1 个新文件 `packages/web/e2e/finance-budget-refusal.spec.mjs`(2 条用例:被拒 → 取消重开 → 重试落地;读不懂的金额一次都不写)+ changelog 一对,**无新依赖、不碰接口、无新文案**):7.46 末尾点名的下一处里最靠前的「财务」那一处,也是那条「原因只进 toast」扫描线在这一页上的第十一处 | 六包 `typecheck` **`EXIT=0`**(六个 `Done`;`gen:ifaces` 报 **`src/ifaces.json unchanged`**,195 接口 / 589 类型 —— 本笔不动服务契约)· `npx oxlint` 两个改动文件 **0 警告 0 错误** · 四个改动文件`prettier --check` 干净 · `git diff --check` 干净 · 逐包 test **`EXIT=0`、0 失败**:core **69 通过文件 + 1 跳过 / 1420 通过 / 6 跳过** · ui **130 文件 / 1053 通过** · cli **38 文件 / 561 通过** · web **265 文件 / 3249 通过 / 2 跳过** · server **203 文件 / 2970 通过 / 4 跳过** · hmr 无测试文件 · **真服务 + 真浏览器单 spec**(`/root/adelie-fork-data/r133-e2e`,服务 8950、mock 8951,`packages/{core,server,web}/dist` 都是本轮新构建):新 spec **2 passed(4.7s)**;相邻回归 `company.spec.mjs` **1 passed(22.0s)** · **整套浏览器 e2e**(`SKIP_BUILD=1 bash e2e/run.sh`,自带 mock 与 `mktemp` 数据根):**164 passed(10.3m)、0 failed** · **反证(同一份 spec,两种产物)**:把这一处源码 `git stash push -- packages/web/src/features/company/finance-page.tsx`(只带这一个路径)、重建 web → 同一条命令 **2 failed**(第一条死在框里没有那句原话,第二条死在 `每月上限` 那条提示从 `role=alert` 里找不到);`git stash pop` 后重建即回到 2 / 2 · **两态实测真看一眼**(探针 `r133/probe.mjs`,改后产物起在 8950、改前产物(`r133/before-dist`)另起一台 8960,各一次、同一个 `page.route` 500,1440×900,读数取被拒后 1.5 s 与 6.5 s 两次):**改前** `{boxVisible:true, reasonInBox:0, reasonInNotice:2, value:"42"}` → 6.5 s 后 `reasonInNotice:0`(屏幕上一点解释都没有了),`writes:2`(**一次保存写了两次**);**改后** `{boxVisible:true, reasonInBox:1, reasonInNotice:0, value:"42"}`,6.5 s 后原样还在,`writes:1`;两态服务端上的预算都是原来的 100,截图 `r133/{before,after}/shots/{3-refused,4-six-seconds-later}.png` 里正好是「改前框里 42、上方两条红 toast、框下一句都没有」对「改后框下那行『操作被拒绝:the org chart is mid-rewrite』」;console 里的 error 只有既有的 `/machines` 403 与刻意造的 500,无 `pageerror` · 端口只用 8950 / 8951 / 8960(跑完都已停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据只落在 `/root/adelie-fork-data/r133-{e2e,before}` 与 scratchpad 的 `r133/` 下(`packages/*/dist`、`packages/web/test-results/` 都是产物,未 `git add`)· 没有切版本号、没发 npm、没发安装包、没发发布汇总 | `467c076d` |
+| 2026-10-26 | 用户点单(火山方舟分组 + 视频输入输出) | **模型库多一个 Volcengine Ark 分组(11 条模型行),对话里能发视频、能看视频,另加一个 Seedance 出视频的插件**(不是移植:`packages/core/src/state/model-catalog.ts` 加 `volcengine` 分组、`supportsVideo` 与 `catalogSupportsVideo`;`pnpm patch` 给 agenthub 加 `video_url` 内容项(`patches/@prismshadow__agenthub.patch` + `patchedDependencies`);core / server / cli / web 四层把视频当一等输入(预算、按引用、轨迹播放器、窗口化历史);`packages/server/src/services/trace-images.ts` 改名合并为 `trace-media.ts` 并新增 `GET /:sessionId/trace-video`;新插件 `plugins/use-seedance`(`@adelie/use-seedance`,走方舟异步出片接口);新增 6 个测试文件与 3 对 changelog;两家品牌图标各一枚):用户 2026-10-25 点单,2026-10-26 补明用 `pnpm patch` 打 agenthub、要「Adelie 应用能产出视频」 | 六包 `typecheck` **`EXIT=0`**(六个 `Done`;`gen:ifaces` 报 **`src/ifaces.json unchanged`**,195 接口 / 590 类型)· `npx oxlint` **0 警告 0 错误**(2297 文件)· `npx prettier --check .` 干净 · `pnpm -r test` **`EXIT=0`、0 失败**:core **1421 通过 / 6 跳过**(69 文件 + 1 跳过)· ui **1053**(130)· cli **561**(38)· web **3273 通过 / 2 跳过**(268)· server **2988 通过 / 4 跳过**(204)· docs **62**(8)· amsp **68**(2)· desktop **304**(26)· ui-gallery **140**(20)· `plugins/use-seedance` **8**(桩服务端到端)· `pnpm -r build` `EXIT=0` · 方舟真端点:假 key 实测 401 `AuthenticationError`(视频部件与文本部件走同一句鉴权错)· **没做**:没在真浏览器里目视播放一次视频、Seedance 没拿真 key 出过一次片、Trace 详情页的 `events` 仍会整份返回那条记录的 base64 | 见本行提交 |
> **2026-10-11 与另一条线的交汇(第三十七轮)**:定时任务触发时(07:00)`git status --short` **不干净**
> —— 另一条线(会话 `session-2026-10-05-20-32-50-2ee69aba`)正在做**用户点单**的「回复能复制成纯文本」
@@ -16169,3 +16170,141 @@ toast」扫描线在 `features/company/` 上的第一处:组织日历(`featu
—— 还是 `202.197.0.0/16` 那个网段的问题,不是凭据,不重试。照前几轮改由飞书送达
(`text ok message_id=om_x100b62dd443d80a0de11dcb04fae648`),正文留底在 scratchpad 的
`r133/report.txt`;下一轮开工再探一次,通了把积压的补发到 `[email protected]`。
+
+## 第一百三十四轮:模型库多一个火山方舟分组,对话里能发视频、也能看视频(2026-10-26,用户点单)
+
+### 事实来源
+
+用户 2026-10-25 点单:「下一步,我需要你加入 abliterable 服务商,字节跳动服务商(火山引擎),具体模型调用
+规则参考官网,记得加好图标,还有多模态视频能力(对话界面对视频输入输出的支持),因为 seed 模型能力重在
+视频。」(「abliterable」是笔误,他随后确认是 `abliteration.ai`。)同日续一句:「我写错了,是
+abliteration.ai。用 pnpm patch 给 agenthub 打补丁加 video_url。你觉得怎么好,就怎么来吧,我需要有
+adelie 应用可以产出视频」。
+
+- **Abliteration**:2026-10-23 那个分组已经在库里(`9864a187`),这轮它只缺一枚真品牌图标。
+- **火山方舟(Volcengine Ark)**:端点 `https://ark.cn-beijing.volces.com/api/v3`,OpenAI 兼容;
+ Chat Completions 的视频部件是 `{"type":"video_url","video_url":{"url":"<公网 URL 或
+ data:video/mp4;base64,…>"}}`(视频本身 < 50 MB、整请求 ≤ 64 MB)。抓下来的官网页面留在 scratchpad
+ 的 `r117/ark/`:`ml.md`(模型列表)、`pricing.md`(定价)、`vu.md`(视频理解输入)、`vgapi.md`
+ (视频生成异步接口)。价格只取定价页的「在线推理(常规)」档,人民币每百万 token,`cny()` 按 7:1 折算;
+ 官网模型列表里**没有** Seed 1.6 / 1.8。
+- **假 key 实测**:带视频部件的一次 `POST /chat/completions` 回 **401 `AuthenticationError`**(与纯文本请求
+ 同一条错)—— 请求构造到得了鉴权那一步,不是本地先炸。
+- **出片**:走方舟的异步接口 `POST /contents/generations/tasks` + 轮询 `GET …/tasks/{id}`,默认模型
+ `doubao-seedance-2-5-260628`。
+
+### 改了什么
+
+**① 模型库多一个 `volcengine` 分组(11 条模型行)**
+
+- `packages/core/src/state/model-catalog.ts`:`VOLCENGINE_BASE_URL`;`ModelCatalogEntry` 多一个
+ `supportsVideo?`;`volcengine` 分组排在 `iflytek` 之后、`qwen-pay-as-you-go` 之前(`label:
+ "Volcengine Ark"`、`OPENAI_*` 凭据、`clientType: "openai-chat"`);11 条模型行 ——
+ `doubao-seed-evolving`、`doubao-seed-2-1-pro-260915`、`-2-1-lite-260915`(不吃视频)、
+ `-2-1-turbo-260628`、`-2-0-lite-260428`、`-2-0-mini-260428`、`doubao-seed-character-260628`、
+ `glm-5-3-flash-260828`、`kimi-k3-1-pro-261024`、`deepseek-v4-1-flash-261017`(用
+ `DEEPSEEK_OFF_PEAK`)、`deepseek-v4-pro-ga-260813`(无视觉);目录条目按能不能吃视频写 `video: true`,
+ 另导出 `catalogSupportsVideo(provider, upstreamId)`。
+- `packages/core/src/state/project-config.ts`:`ModelEntry` 多一个 `video?`(只有 `true` 才落盘)。
+- `packages/web/test/model-grouping.test.ts`:默认分组顺序补 `volcengine`。
+
+**② 视频输入走进对话(agenthub 补丁 + core / server / cli / web 四层)**
+
+- `patches/@prismshadow__agenthub.patch` + `pnpm-workspace.yaml` 的 `patchedDependencies`(钉在
+ `@prismshadow/[email protected]`):agenthub 的通用消息格式只认文本与图片,Chat Completions 客户端遇到
+ 别的内容项会抛错,视频根本到不了方舟的 `video_url` 部件。补丁在 `dist/types.d.ts` 的 `ContentItem` 联合里
+ 加 `VideoContentItem{type:"video_url";video_url:string}`,并给 `dist/openai_chat/client.js` 的
+ `transformUniMessageToModelInput` 加一条分支(**不重新 base64**,原样透传 URL)。
+- core:`omnimessage/types.ts` 加 `VideoUrlPayload`、`builders.ts` 加 `videoUrlMessage()`;
+ `llm/generative-model.ts` 加视频预算(`videoOmittedNote` / `isVideoItem` / `countMessageVideos` /
+ `capMessageVideos` / `capHistoryVideos` / 私有的 `fitReplayedVideos`,`maxVideos`,请求处
+ `this.fitReplayedVideos(this.fitReplayedImages(uniMessage))`);`interfaces/llm.ts` 加 `maxVideos?`;
+ `agent.ts` 按 `entry.video === true || catalogSupportsVideo(…)` 给 `videoLimit = 1`。三处「视频盲区」
+ 一并补上:`llm/context-limits.ts` 加 `VIDEO_TOKEN_ESTIMATE = 8192` 与 `approximateMessagesTokens` 的
+ `video_url` 分支(不然 40 MB base64 会被当文本估成上千万 token)、`engine/context-engine.ts` 的
+ `carriesSteering` 认 `video_url`(只有视频的 steering 不再被静默丢掉)。
+- server:`api/types.ts` 的 `TaskInputPart` 加 `{type:"video_url";videoUrl;fileName?}`、`SteerRequest.videos?`、
+ `PendingSteeringInfo.videos`、`RecalledMessageResponse.videos`、`UploadLimits.videoMaxMb`、
+ `ModelInfo.video?`;`services/attachment-limits.ts` 加 `INLINE_VIDEO_MAX_MB = 32`;
+ `services/project-config-service.ts` 组装 `ModelInfo.video`;
+ `http/routes/sessions.ts` 认视频输入(`requireVideoUrl` 给 413 `video_too_large`、`decodeVideoDataUrl`、
+ `videoAttachment`):模型吃视频就内联,不吃就落 scratchpad 当 `[attached file: …]` 交给模型按路径读,
+ http(s) 地址 + 不吃视频的模型给 400;steer 与 goal 两条路同样处理,错误文案跟着改。
+ `services/context-breakdown.ts`、`services/message-window.ts` 各自加视频分支。
+ **`trace-images.ts` 改名并合并成 `services/trace-media.ts`**(`referableDataUrl` / `traceImageUrl` /
+ `traceVideoUrl` / `withMediaByReference` / `traceRecordMedia`),新增
+ `GET /api/sessions/:id/trace-video`:窗口化翻页的历史页不再把几十兆的 base64 塞进页面,只给一条按引用的
+ 地址(图片今天也是这么做的);`mechanisms/traces.ts` 与 `services/trace-service.ts` 的
+ `readTraceImage` 合成 `readTraceMedia(..., kind)`。
+- cli:`render.ts` 加 `case "video_url"` 画 `> [video]`。
+- web:新增 `lib/video-input.ts`(`ComposerVideo`、`dataUrlBytes`、`videoNameForUrl`、`videoFromUrl`、
+ `appendMediaParts`、`steerVideoFields`)与 `features/chat/queued-summary.ts`;`chat-input.tsx` 的「+」菜单
+ 多一项「上传视频」,静音的 `<video>` 首帧当缩略图,按 `videoMaxMb` 预检,普通 / 目标 / steer 三条发送路径
+ 与 recall 恢复都带上视频;`chat-page.tsx` 按 `modelInfo?.video === true` 决定它进 `videos` 还是并进
+ `files`;`message-item.tsx` 加 `MessageVideo`(`controls` / `preload="metadata"` / `playsInline`,
+ 不自动播放、不静音);`stream-model.ts` 认 `user_video` 项与 steering 里的视频,去重键把
+ `trace-video` 引用与内联字节看作同一条;`traces/trace-event-row.tsx` 给 `video_url` 一条播放器分支
+ (不加这一条会把整份 base64 倒进那一行);`file-drop.ts` 拖拽按图片 / 视频 / 文件分三堆;中英文案各补几条。
+- 测试:新增 `packages/server/test/video-input.test.ts`(7 条)、`packages/web/test/video-input.test.ts`、
+ `transcript-videos.test.ts`、`queued-summary.test.ts`;`test/trace-image.test.ts` 改名
+ `trace-media.test.ts` 并扩到视频(27 条);`messages-page` / `session-manager` / `steer` / `followup` /
+ `messaging` 的断言各补 `videos`。
+
+**③ 两枚真品牌图标**
+
+`packages/ui/src/components/icons/logos/provider-logo.tsx`:`volcengine`(官网页头 logo,viewBox
+`0 0 84.27 75`)与 `abliteration`(`https://abliteration.ai/icon.svg`,viewBox `199 230 602.49 540.46`),
+都压成单色、丢掉字标与底板。
+
+**④ 一个能出片的插件**
+
+`plugins/use-seedance/`(`@adelie/use-seedance` 0.5.6,默认预装):一个不依赖第三方包的 Node 脚本
+`skills/seedance/kit/seedance.mjs`,走方舟异步出片接口(提交 → 轮询 → 下载并命名文件),读密钥库里的
+`ARK_API_KEY`,`ARK_BASE_URL` 可覆盖;`plugin.json`、`README.md`、`LICENSE`、`icon.svg`、
+`skills/seedance/SKILL.md` 与 8 条自测。登记在 `packages/{core,cli,desktop}/package.json`、
+`plugins/README.md`、两份 `README` 的分类表与 `packages/docs/content/skills.{zh,en}.md`。
+
+另外:`packages/docs/content/models.{zh,en}.md` 补分组表行、卡片上的「视频」标签、一整节「Volcengine Ark
+分组」与 Project 模型表的 `video` 字段;三对 changelog(`2026-10-26-volcengine-ark`、
+`-video-input`、`-seedance-plugin`)。
+
+### 验证(都不是推测)
+
+- 六包 `typecheck` **`EXIT=0`**(六个 `Done`;`gen:ifaces` 报 **`src/ifaces.json unchanged`**,195 接口 /
+ 590 类型);`npx oxlint` **0 警告 0 错误**(2297 文件);`npx prettier --check .` 干净。
+- `pnpm -r test` **`EXIT=0`、0 失败**:core **1421 通过 / 6 跳过**(69 文件 + 1 跳过)· ui **1053**(130)·
+ cli **561**(38)· web **3273 通过 / 2 跳过**(268)· server **2988 通过 / 4 跳过**(204)· docs **62**(8)·
+ amsp **68**(2)· desktop **304**(26)· ui-gallery **140**(20)· `plugins/use-seedance` **8**
+ (桩服务端到端,含「假 key 被拒」与「任务永不完成就放弃」)· 四个 sandbox 插件各 17–32 条。
+- `pnpm -r build` **`EXIT=0`**(六个包 + 画廊全 Done)。
+- **补丁真的接上了**:`pnpm install` 之后 cli / core 链接的是带 `_patch_hash=` 的那份副本
+ (`grep -c video_url node_modules/.pnpm/@[email protected]…/dist/openai_chat/client.js` = 3),
+ 两个不带补丁的旧副本还留在磁盘上但没有被任何包链接;用真装的 agenthub 组一个 `AutoLLMClient` 实测,
+ 带 `video_url` 的消息发出去是方舟要的那个部件形状。
+- 方舟真端点:假 key → **401 `AuthenticationError`**。
+
+### 台账
+
+- 本轮是用户点单,没有清单条目;「已完成的轮次」表行与这一节跟代码同一笔提交,所以那一行的提交号写的是
+ 「见本行提交」(照 `9864a187` 那一轮的写法:台账合进本轮自己那一笔)。
+
+### 没做 / 还差什么
+
+- **没在真浏览器里目视播放过一条视频**:这轮的任务面太宽,视频进对话的验证止于单测与服务端接线;
+ 真正要走一遍「上传 → 模型看到 → 历史页按引用取回」还得起一次服务 + 真浏览器。
+- **Seedance 没有真的出过一次片**:桩服务端到端 8 条全过、假 key 的 401 与文档一致,但没有用真 `ARK_API_KEY`
+ 跑一次真生成(要花钱,且出片慢)。
+- Trace 详情页的 `events` 接口仍会把视频那条记录的几十兆 base64 整份返回(图片今天也是这样,没改成按引用);
+ 真正被按引用取回的是窗口化历史页与轨迹行里的播放器。
+- Agent API(AMSP)还没有视频:协议里 `InputItem` 只有 `text` / `image_url`,`translate.ts` 对不认识的
+ payload 返回空数组,所以「试一下」面板既不会崩、也看不到视频。要支持得先动协议(`amsp/src/types.ts`
+ 的联合与投影),这轮没做。
+- abliteration 那枚图标是给已有分组补的,两家图标都按仓库既有办法压成单色;volcengine 那枚双色相邻压成
+ 单色后,192 px 下有极细的浅色接缝(小尺寸看不出来)。
+- 现网(`/root/.adelie`)还是 0.5.6 那份构架,本轮改动要等下一版才看得见。
+
+### 汇报
+
+- 校园邮箱这一轮只试一次(`cd …/csu-mail/scripts && timeout 60 python3 mail.py check` **超时**、
+ `RC=124`、无输出)—— 还是 `202.197.0.0/16` 那个网段的问题,不是凭据,不重试。照前几轮改由飞书送达,
+ 正文留底在 scratchpad 的 `r117/report.txt`;下一轮开工再探一次。
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 2ff126e4..cf889b9b 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -42,6 +42,7 @@
"@adelie/use-firecrawl": "workspace:*",
"@adelie/use-lieflat-charts": "workspace:*",
"@adelie/use-offerdao": "workspace:*",
+ "@adelie/use-seedance": "workspace:*",
"@adelie/use-wps-office": "workspace:*",
"@adelie/use-claude-code": "workspace:*",
"@adelie/wechat-miniprogram": "workspace:*",
diff --git a/packages/cli/src/render.ts b/packages/cli/src/render.ts
index d0b25e03..9d1bb76d 100644
--- a/packages/cli/src/render.ts
+++ b/packages/cli/src/render.ts
@@ -288,6 +288,11 @@ export function renderHistory(
case "image_url":
out.write(`\n> ${dim("[image]", c)}\n`);
break;
+ case "video_url":
+ // Same placeholder treatment as an image: the terminal plays nothing, but the
+ // message must not read as an empty one.
+ out.write(`\n> ${dim("[video]", c)}\n`);
+ break;
case "thinking":
out.write(`${dim(p.thinking ?? "", c)}${marker}\n`);
break;
diff --git a/packages/core/package.json b/packages/core/package.json
index ff21a411..c8e23080 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -75,6 +75,7 @@
"@adelie/use-firecrawl": "workspace:*",
"@adelie/use-lieflat-charts": "workspace:*",
"@adelie/use-offerdao": "workspace:*",
+ "@adelie/use-seedance": "workspace:*",
"@adelie/use-wps-office": "workspace:*",
"@adelie/use-claude-code": "workspace:*",
"@adelie/wechat-miniprogram": "workspace:*",
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 63b8a521..da23d225 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -99,7 +99,7 @@ import type {
import { SUBAGENT_NAME } from "./environment/tools/run-subagent.js";
import { INPUT_SUBAGENT_NAME } from "./environment/tools/input-subagent.js";
import type { CompactionSettings, OpenContextOptions } from "./engine/context-engine.js";
-import { catalogImageLimit } from "./state/model-catalog.js";
+import { catalogImageLimit, catalogSupportsVideo } from "./state/model-catalog.js";
import type {
ApproveFn,
CommandPolicyConfig,
@@ -1353,6 +1353,15 @@ export class Agent {
// The seller's per-request image cap, from the catalog (Abliteration's is 4): a
// conversation that accumulates pictures would otherwise fail every later request.
const imageLimit = catalogImageLimit(entry.provider, entry.model_id);
+ // Video input is opt-in per model (the opposite default of vision): either the Project's
+ // row carries the catalog's `video` annotation, or the catalog itself records it — the
+ // second answer covers a Project whose presets predate the row and has not synced since.
+ // One video per request: the budget exists to keep a replayed conversation's body inside
+ // the provider's limit, and the video that matters is the newest one.
+ const videoLimit =
+ entry.video === true || catalogSupportsVideo(entry.provider, entry.model_id)
+ ? 1
+ : undefined;
return new GenerativeModel({
modelId: entry.model_id,
toolCallIds,
@@ -1362,6 +1371,7 @@ export class Agent {
systemPrompt: context.systemPrompt,
...(entry.context_window !== undefined ? { contextWindow: entry.context_window } : {}),
...(imageLimit !== undefined ? { maxImages: imageLimit } : {}),
+ ...(videoLimit !== undefined ? { maxVideos: videoLimit } : {}),
...(context.maxTokens !== undefined ? { maxTokens: context.maxTokens } : {}),
// Fast mode is a session-request annotation: it rides every context's LLM object,
// while the bare/meta LLM below and the vision describer deliberately skip it — their
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index 0ba6f9ec..32b792dc 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -339,10 +339,14 @@ export interface ContextEngineDeps {
const isImageMessage = (m: OmniMessage): boolean =>
(m.payload as { type?: string }).type === "image_url";
-/** Whether a message carries steering of its own — an image, or text that isn't blank. */
+/** Whether a message carries steering of its own — an image, a video, or text that isn't blank. */
const carriesSteering = (m: OmniMessage): boolean => {
const p = m.payload as { type?: string; text?: string };
- return p.type === "image_url" || (p.type === "text" && (p.text ?? "").trim().length > 0);
+ return (
+ p.type === "image_url" ||
+ p.type === "video_url" ||
+ (p.type === "text" && (p.text ?? "").trim().length > 0)
+ );
};
/** Whether compaction is possible; when not `ok`, `compact()` is a no-op and yields no messages (see ContextEngine.compactability). */
diff --git a/packages/core/src/interfaces/llm.ts b/packages/core/src/interfaces/llm.ts
index 8a59310d..539bce8d 100644
--- a/packages/core/src/interfaces/llm.ts
+++ b/packages/core/src/interfaces/llm.ts
@@ -63,6 +63,18 @@ export interface GenerativeModelConfig {
* messages in the Session's own history and Trace are not touched.
*/
maxImages?: number;
+ /**
+ * How many videos ONE request may carry. Set by the caller for a model the catalog marks as
+ * taking video input (`ModelCatalogEntry.supportsVideo`); unset = the model takes none, and
+ * a video is never sent to it.
+ *
+ * The budget exists for the request body rather than a published count: a video travels as
+ * megabytes of base64 (Ark accepts one under 50 MB inside a 64 MB body) and every later
+ * request replays the conversation, so a history holding two videos is refused for good.
+ * The implementation keeps the NEWEST video and replaces older ones with a one-line text
+ * placeholder; the Session's history and Trace keep every video.
+ */
+ maxVideos?: number;
/**
* Per-model fast mode (from the model entry's `fast_mode` annotation): when true, every
* request opts into the provider's faster serving tier at premium pricing (AgentHub
diff --git a/packages/core/src/llm/context-limits.ts b/packages/core/src/llm/context-limits.ts
index 1bee5ff7..d94ca610 100644
--- a/packages/core/src/llm/context-limits.ts
+++ b/packages/core/src/llm/context-limits.ts
@@ -110,6 +110,20 @@ export const COMPACTION_HEADROOM = OUTPUT_SAFETY_MARGIN * 2;
*/
const IMAGE_TOKEN_ESTIMATE = 1600;
+/**
+ * Flat allowance for one video input.
+ *
+ * Same reasoning as an image, one order of magnitude up: a clip is tens of frames and a
+ * provider bills it by the frame (Ark's video understanding takes a frame a second and prices
+ * a 720p frame at roughly a thousand tokens), so a few seconds of video is a few thousand
+ * tokens — while the data URL riding the message is tens of *megabytes*, and serializing it
+ * would count every base64 character (a 32MB clip would estimate ~11M "tokens" and floor the
+ * next request's output cap to nothing on any window). Slightly high on purpose: an
+ * overestimate costs a smaller output cap for a request that already carries a video, an
+ * underestimate costs a request refused for exceeding the window.
+ */
+const VIDEO_TOKEN_ESTIMATE = 8192;
+
/**
* Resolves a model entry's `context_window` to a usable number: a finite number at or
* above {@link MIN_USABLE_CONTEXT_WINDOW} wins; anything else — unset, non-numeric,
@@ -154,6 +168,9 @@ export function approximateTokens(text: string): number {
* Serializing those data URLs would count every base64 character: a 1 MB image would
* estimate ≈ 262k "tokens" (~163x over) and floor the next request's output cap even on a
* 128k window (PR #235 review).
+ *
+ * A video (`video_url`) is the same case with more zeros behind it — megabytes rather than
+ * one — and gets its own flat allowance.
*/
export function approximateMessagesTokens(messages: OmniMessage[]): number {
let total = 0;
@@ -161,6 +178,8 @@ export function approximateMessagesTokens(messages: OmniMessage[]): number {
const p = msg.payload as { type?: string; images?: unknown };
if (p.type === "image_url" || p.type === "inline_data") {
total += IMAGE_TOKEN_ESTIMATE;
+ } else if (p.type === "video_url") {
+ total += VIDEO_TOKEN_ESTIMATE;
} else if (Array.isArray(p.images)) {
const { images, ...rest } = p as { images: unknown[] };
total += images.length * IMAGE_TOKEN_ESTIMATE + approximateTokens(JSON.stringify(rest));
diff --git a/packages/core/src/llm/generative-model.ts b/packages/core/src/llm/generative-model.ts
index fb80fbd1..5296df49 100644
--- a/packages/core/src/llm/generative-model.ts
+++ b/packages/core/src/llm/generative-model.ts
@@ -134,6 +134,8 @@ function payloadToContentItem(payload: CompleteModelPayload): ContentItem {
};
case "image_url":
return { type: "image_url", image_url: payload.image_url };
+ case "video_url":
+ return { type: "video_url", video_url: payload.video_url };
case "inline_data":
return {
type: "inline_data",
@@ -338,6 +340,87 @@ export function capHistoryImages(
return capped;
}
+// ---------------------------------------------------------------------------
+// Video budget (a request may carry only so many videos)
+// ---------------------------------------------------------------------------
+
+/**
+ * The stand-in left where a video was dropped from a request — one text item in the place the
+ * video occupied, so the model can tell a gap from its own omission. The reason is the body
+ * size rather than a published count: a video is megabytes of base64, and a provider takes at
+ * most one request body of it, so a conversation that replays two videos is refused outright.
+ */
+export function videoOmittedNote(limit: number): string {
+ return `[video omitted: this request carries at most ${limit} video${limit === 1 ? "" : "s"}]`;
+}
+
+/** Whether a content item is a video the request counts. */
+function isVideoItem(item: ContentItem): boolean {
+ return item.type === "video_url";
+}
+
+/** How many videos one UniMessage carries. */
+export function countMessageVideos(msg: UniMessage): number {
+ let count = 0;
+ for (const item of msg.content_items) {
+ if (isVideoItem(item)) count += 1;
+ }
+ return count;
+}
+
+/**
+ * Keeps at most `budget` of a message's videos, **the newest ones**, and replaces each older
+ * one with {@link videoOmittedNote}. A message that fits is returned as-is (same object).
+ */
+function capMessageVideos(msg: UniMessage, budget: number, limit: number): UniMessage {
+ if (countMessageVideos(msg) <= budget) return msg;
+ const note = videoOmittedNote(limit);
+ let left = budget;
+ const kept: ContentItem[] = [];
+ // Newest first, as the image budget does: the video nearest the current request is the one
+ // worth paying for.
+ for (let i = msg.content_items.length - 1; i >= 0; i -= 1) {
+ const item = msg.content_items[i]!;
+ if (isVideoItem(item)) {
+ if (left > 0) {
+ left -= 1;
+ kept.push(item);
+ } else {
+ kept.push({ type: "text", text: note });
+ }
+ continue;
+ }
+ kept.push(item);
+ }
+ return { ...msg, content_items: kept.reverse() };
+}
+
+/**
+ * Trims a replayed history so it carries at most `budget` videos in aggregate, newest kept
+ * (see {@link capMessageVideos}). Returns a new array of the same length whose untouched
+ * messages are the very objects it was handed.
+ */
+export function capHistoryVideos(
+ history: UniMessage[],
+ budget: number,
+ limit: number = budget,
+): UniMessage[] {
+ const counts = history.map(countMessageVideos);
+ const capped = new Array<UniMessage>(history.length);
+ let left = budget;
+ for (let i = history.length - 1; i >= 0; i -= 1) {
+ const msg = history[i]!;
+ const count = counts[i]!;
+ if (count === 0) {
+ capped[i] = msg;
+ continue;
+ }
+ capped[i] = capMessageVideos(msg, left, limit);
+ left = Math.max(0, left - count);
+ }
+ return capped;
+}
+
// ---------------------------------------------------------------------------
// Token accounting (as defined by SKILL.md)
// ---------------------------------------------------------------------------
@@ -1075,6 +1158,8 @@ export class GenerativeModel implements LLMInterface {
private readonly configuredMaxTokens: number | undefined;
/** Per-request image cap (`GenerativeModelConfig.maxImages`); undefined = the seller publishes none (see fitReplayedImages). */
private readonly maxImages: number | undefined;
+ /** Per-request video cap (`GenerativeModelConfig.maxVideos`); undefined = the session's model takes no video (see fitReplayedVideos). */
+ private readonly maxVideos: number | undefined;
/** Model context window; `undefined` when unconfigured (or implausibly small, see resolveContextWindow) — the per-request clamp then disables itself rather than clamp against an assumption. */
private readonly contextWindow: number | undefined;
/**
@@ -1131,6 +1216,10 @@ export class GenerativeModel implements LLMInterface {
config.maxImages !== undefined && config.maxImages > 0
? Math.floor(config.maxImages)
: undefined;
+ this.maxVideos =
+ config.maxVideos !== undefined && config.maxVideos > 0
+ ? Math.floor(config.maxVideos)
+ : undefined;
this.contextWindow = resolveContextWindow(config.contextWindow);
this.baseInputTokens =
approximateTokens(config.systemPrompt ?? "") +
@@ -1321,7 +1410,7 @@ export class GenerativeModel implements LLMInterface {
// replayed ones — and, when the input alone overflows, the input's own oldest ones — are
// dropped from THIS request (the history and Trace keep them).
const it = this.openStream(
- this.fitReplayedImages(uniMessage),
+ this.fitReplayedVideos(this.fitReplayedImages(uniMessage)),
ac.signal,
this.requestConfig(params.thinkingLevel, params.newMessages),
)[Symbol.asyncIterator]();
@@ -1525,6 +1614,28 @@ export class GenerativeModel implements LLMInterface {
return carried;
}
+ /**
+ * Trims a request so it carries at most `maxVideos` videos in all, newest kept — the video
+ * counterpart of {@link fitReplayedImages}, and needed for a harder reason than the seller's
+ * count: a provider takes one request body (Ark caps it at 64 MB) and a video is megabytes of
+ * base64, so a conversation replaying two videos would be refused for good once its history
+ * grows past the cap. Input first, then the replayed history, exactly as the image budget
+ * does it. Nothing happens without a cap, or when everything already fits.
+ */
+ private fitReplayedVideos(input: UniMessage): UniMessage {
+ const limit = this.maxVideos;
+ if (limit === undefined) return input;
+ const carried =
+ countMessageVideos(input) > limit ? capMessageVideos(input, limit, limit) : input;
+ const budget = Math.max(0, limit - countMessageVideos(carried));
+ const history = this.client.getHistory();
+ if (history.length === 0) return carried;
+ const total = history.reduce((sum, msg) => sum + countMessageVideos(msg), 0);
+ if (total <= budget) return carried;
+ this.client.setHistory(capHistoryVideos(history, budget, limit));
+ return carried;
+ }
+
/**
* Opens the underlying AgentHub stream (a testing seam): defaults to
* `streamingResponseStateful`; unit tests can subclass and override this method, feeding in a
diff --git a/packages/core/src/omnimessage/builders.ts b/packages/core/src/omnimessage/builders.ts
index 696d6df4..bd006dc1 100644
--- a/packages/core/src/omnimessage/builders.ts
+++ b/packages/core/src/omnimessage/builders.ts
@@ -46,6 +46,7 @@ import type {
ToolListReadyPayload,
ToolCallPayload,
ToolDefinition,
+ VideoUrlPayload,
} from "./types.js";
/** The current moment's ISO 8601 UTC timestamp. */
@@ -117,6 +118,20 @@ export function imageUrlMessage(imageUrl: string): OmniMessage<ImageUrlPayload>
});
}
+/**
+ * A video message. The address is a public URL or a base64 `data:` URL — see VideoUrlPayload
+ * for why there is only one field — and only a model whose catalog row records video input
+ * may be sent one.
+ */
+export function videoUrlMessage(videoUrl: string): OmniMessage<VideoUrlPayload> {
+ return model({
+ type: "video_url",
+ role: "user",
+ video_url: videoUrl,
+ stop_reason: "completed",
+ });
+}
+
export function inlineData(
role: Role,
data: string,
diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.ts
index abe6b635..5b4f089b 100644
--- a/packages/core/src/omnimessage/types.ts
+++ b/packages/core/src/omnimessage/types.ts
@@ -211,6 +211,24 @@ export interface ImageUrlPayload {
stop_reason?: StopReason;
}
+/**
+ * A video the model is asked to watch. Only a model whose catalog row records video input may
+ * be sent one (see ModelCatalogEntry.supportsVideo): AgentHub's Chat Completions client maps
+ * this to the `video_url` content part Ark reads, and every other client rejects an item it
+ * does not know rather than dropping the video silently.
+ *
+ * There is deliberately no inline-bytes variant: upstream takes a URL or a base64 `data:` URL
+ * on the same field, and a caller holding local bytes base64-encodes them itself (read_file's
+ * video branch does), so the two cases are one field.
+ */
+export interface VideoUrlPayload {
+ type: "video_url";
+ role: "user";
+ /** A public web URL or a base64 data URL (`data:video/mp4;base64,…`). */
+ video_url: string;
+ stop_reason?: StopReason;
+}
+
export interface InlineDataPayload {
type: "inline_data";
role: Role;
@@ -581,6 +599,7 @@ export interface McpConnectEndPayload extends ErrorInfo {
export type CompleteModelPayload =
| TextPayload
| ImageUrlPayload
+ | VideoUrlPayload
| InlineDataPayload
| ThinkingPayload
| InlineThinkingPayload
diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.ts
index 5ba21647..879636a3 100644
--- a/packages/core/src/state/model-catalog.ts
+++ b/packages/core/src/state/model-catalog.ts
@@ -28,7 +28,8 @@
* vendor's own docs and console pages: 2026-10-15, with the iFlytek rows deliberately unpriced
* (its HTTP doc publishes no price list, and the product page's prices name model families it
* has published no API id for); and the Abliteration group, whose four rows were read from the
- * service's own model list on 2026-10-23.
+ * service's own model list on 2026-10-23; and the Volcengine Ark (ByteDance) group, whose rows
+ * and prices were read from Ark's own model list and model-pricing pages on 2026-10-25.
* Docs: packages/docs/content/models.{zh,en}.md (site path /docs/models) documents the
* provider groups and credential resolution described here.
*
@@ -256,6 +257,18 @@ export interface ModelCatalogEntry {
* Trace keep every image, so nothing is lost from the record.
*/
maxImages?: number;
+ /**
+ * Whether video input is supported. Absent = no, which is every row but the ones whose
+ * vendor documents it: the modality is young enough that a vendor's model list states it
+ * per model, and guessing it from `supportsVision` would send a video to a model that
+ * rejects the content item outright.
+ *
+ * Read through catalogSupportsVideo rather than off the row, the way maxImages is read
+ * through catalogImageLimit: it is a property of the model being called, so a Project that
+ * renamed or repriced the row still gets the same answer, and a user-added row (no catalog
+ * entry) gets no video input — it can still work with a video file by path.
+ */
+ supportsVideo?: boolean;
/** AgentHub client protocol: required when an id cannot be auto-routed or a shared protocol must be pinned. */
clientType?: string;
/** Preset base URL: inlined into gateway and direct MiniMax entries so only an API key is required. */
@@ -311,6 +324,13 @@ const BAIDU_BASE_URL = "https://qianfan.baidubce.com/v2";
const HUNYUAN_BASE_URL = "https://api.hunyuan.cloud.tencent.com/v1";
/** iFlytek Spark's OpenAI-compatible endpoint (the WebSocket API is a different, signed protocol). */
const IFLYTEK_BASE_URL = "https://spark-api-open.xf-yun.com/v1";
+/**
+ * Volcengine Ark's (火山方舟) OpenAI-compatible endpoint — ByteDance's own model platform, the
+ * one the Doubao / Seed line is served from. Its console issues an API key that the Ark SDKs
+ * pass as a Bearer token; the base URL is region-scoped, and this is the cn-beijing host its
+ * own quick-start and every per-model page use.
+ */
+const VOLCENGINE_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3";
export const PENGUIN_GO_BASE_URL = "https://token.penguin.ooo/api";
/** OpenCode Go's OpenAI-protocol base: the clients append /chat/completions or /responses. */
const OPENCODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1";
@@ -542,6 +562,26 @@ export const MODEL_PROVIDERS: ModelProviderInfo[] = [
modelsUrl: "https://www.xfyun.cn/doc/spark/HTTP%E8%B0%83%E7%94%A8%E6%96%87%E6%A1%A3.html",
clientType: "openai-chat",
},
+ {
+ // ByteDance's own model platform (火山方舟 / Volcengine Ark), serving the Doubao line,
+ // whose Seed models are the ones that read video as well as images. OpenAI-compatible at
+ // the region-scoped endpoint the rows below inline, one Bearer key from the Ark console,
+ // so no oauth or bridgeAuth — the same shape as Xiaomi's group, and pinned the same way:
+ // AgentHub has no Ark client, so the group pins `openai-chat` and every row names the
+ // endpoint. Ark also resells GLM, Kimi and DeepSeek and serves image, video, 3D and
+ // embedding models; only its text-generation chat models are catalogued here (the
+ // modalities a Session can hold a conversation on), and the ids are the versioned ones
+ // Ark's model list publishes.
+ // https://www.volcengine.com/docs/82379/1330310 (model list),
+ // https://docs.volcengine.com/docs/ark/model-pricing (prices)
+ id: "volcengine",
+ label: "Volcengine Ark",
+ envKey: "OPENAI_API_KEY",
+ envBaseUrlKey: "OPENAI_BASE_URL",
+ apiKeyUrl: "https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey",
+ modelsUrl: "https://www.volcengine.com/docs/82379/1330310",
+ clientType: "openai-chat",
+ },
{
id: "qwen-pay-as-you-go",
label: "Qwen Pay-As-You-Go",
@@ -3154,6 +3194,142 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
clientType: "openai-chat",
baseUrl: IFLYTEK_BASE_URL,
},
+ // -- Volcengine Ark (ByteDance). Ids, windows and input modalities read 2026-10-25 from
+ // Ark's own model list (its rows name the ids and the per-model context window; the
+ // "多模态理解" capability marker is what makes a row vision), prices from its model-pricing
+ // page's 在线推理(常规) table in CNY per million tokens (input non-audio / cache hit
+ // non-audio / output) — the same three buckets `cny` takes. Two things the rows say that the
+ // pages state only indirectly: Ark's prices are tiered by input length and only the base
+ // tier is recorded (the catalog's standing convention, so long-context usage is
+ // underestimated); and `supportsVideo` follows models.dev's per-model input modalities for
+ // this provider, the only source that states video per model — which is why the 2.1 Lite row
+ // records no video while its siblings do. Ark's resold GLM / Kimi / DeepSeek rows are
+ // catalogued here (Ark is the seller) but its image, video, 3D and embedding models are not:
+ // they are not chat models, and a Session cannot hold a conversation on one.
+ {
+ modelId: "doubao-seed-evolving",
+ displayName: "Doubao Seed Evolving",
+ provider: "volcengine",
+ contextWindow: 1048576,
+ pricing: cny(1.2, 6, 30),
+ supportsVision: true,
+ supportsVideo: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ modelId: "doubao-seed-2-1-pro-260915",
+ displayName: "Doubao Seed 2.1 Pro",
+ provider: "volcengine",
+ contextWindow: 1048576,
+ pricing: cny(1.2, 6, 30),
+ supportsVision: true,
+ supportsVideo: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ modelId: "doubao-seed-2-1-lite-260915",
+ displayName: "Doubao Seed 2.1 Lite",
+ provider: "volcengine",
+ contextWindow: 1048576,
+ pricing: cny(0.16, 0.8, 2.7),
+ supportsVision: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ modelId: "doubao-seed-2-1-turbo-260628",
+ displayName: "Doubao Seed 2.1 Turbo",
+ provider: "volcengine",
+ contextWindow: 262144,
+ pricing: cny(0.6, 3, 15),
+ supportsVision: true,
+ supportsVideo: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ modelId: "doubao-seed-2-0-lite-260428",
+ displayName: "Doubao Seed 2.0 Lite",
+ provider: "volcengine",
+ contextWindow: 262144,
+ pricing: cny(0.12, 0.6, 3.6),
+ supportsVision: true,
+ supportsVideo: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ modelId: "doubao-seed-2-0-mini-260428",
+ displayName: "Doubao Seed 2.0 Mini",
+ provider: "volcengine",
+ contextWindow: 262144,
+ pricing: cny(0.04, 0.2, 2),
+ supportsVision: true,
+ supportsVideo: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ // The role-play model: no GUI capability and a smaller window than the Seed line it
+ // belongs to, but the same multimodal input (video included).
+ modelId: "doubao-seed-character-260628",
+ displayName: "Doubao Seed Character",
+ provider: "volcengine",
+ contextWindow: 131072,
+ pricing: cny(0.16, 0.8, 2),
+ supportsVision: true,
+ supportsVideo: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ modelId: "glm-5-3-flash-260828",
+ displayName: "GLM-5.3-Flash",
+ provider: "volcengine",
+ contextWindow: 1048576,
+ pricing: cny(0.23, 0.8, 2.8),
+ supportsVision: true,
+ supportsVideo: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ modelId: "kimi-k3-1-pro-261024",
+ displayName: "Kimi K3.1 Pro",
+ provider: "volcengine",
+ contextWindow: 1048576,
+ pricing: cny(1.3, 13, 68),
+ supportsVision: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ // Half price outside Beijing weekday 09:00–12:00 and 14:00–18:00 — the same windows
+ // DeepSeek itself bills on, which is why the shared schedule is reused here; the price
+ // recorded is the peak one (see offPeakDiscount).
+ modelId: "deepseek-v4-1-flash-261017",
+ displayName: "DeepSeek V4.1 Flash",
+ provider: "volcengine",
+ contextWindow: 1048576,
+ pricing: cny(0.04, 2, 8),
+ offPeakDiscount: DEEPSEEK_OFF_PEAK,
+ supportsVision: true,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
+ {
+ // Text only, unlike the flash row above: Ark's model list carries no 多模态理解 marker for it.
+ modelId: "deepseek-v4-pro-ga-260813",
+ displayName: "DeepSeek V4 Pro",
+ provider: "volcengine",
+ contextWindow: 1048576,
+ pricing: cny(0.3, 9, 27),
+ supportsVision: false,
+ clientType: "openai-chat",
+ baseUrl: VOLCENGINE_BASE_URL,
+ },
// -- Abliteration. Its own ids, read on 2026-10-23 from the service's own model list
// (GET https://api.abliteration.ai/v1/models), which publishes everything the rows below
// record: the window, the input modalities and the per-token rates. Prices are the list
@@ -3272,6 +3448,23 @@ export function catalogImageLimit(
return catalogEntryFor(provider, upstreamId)?.maxImages;
}
+/**
+ * Whether the catalog records video input for a model (ModelCatalogEntry.supportsVideo), read
+ * for the same reason catalogImageLimit is: it is a fact about the model being called, not a
+ * preference, so it survives a Project renaming or repricing the row. A user-added row (no
+ * catalog entry) answers false — the safe direction, since a video the upstream does not
+ * accept fails the whole request.
+ *
+ * The Project entry carries the same bit (`video`, seeded from this at preset time) for the
+ * call sites that only have the Session's model entry at hand; this one exists for the paths
+ * that resolve a (provider, model_id) pair before a Session exists — the server, deciding
+ * whether an uploaded video rides the conversation or lands in the scratchpad.
+ */
+export function catalogSupportsVideo(provider: string | undefined, upstreamId: string): boolean {
+ if (provider === undefined) return false;
+ return catalogEntryFor(provider, upstreamId)?.supportsVideo === true;
+}
+
/**
* The protocol a group pins on every one of its entries (ModelProviderInfo.clientType), or
* undefined when the group pins none — an unknown id (a user-defined group) included.
@@ -3816,8 +4009,11 @@ function catalogModelEntry(m: ModelCatalogEntry): ModelEntry {
...(m.pricing ? { pricing: { ...m.pricing } } : {}),
// ModelEntry.vision defaults to supported: only models that don't support images
// explicitly persist false (drives read_file's hand-off of images to the vision model and input
- // image hand-off, see project-config.ts).
+ // image hand-off, see project-config.ts). Video is the other way round: only a row whose
+ // vendor documents video input persists true, because a video sent to a model that does
+ // not take one fails the whole request.
...(m.supportsVision ? {} : { vision: false }),
+ ...(m.supportsVideo ? { video: true } : {}),
...(m.baseUrl !== undefined ? { base_url: m.baseUrl } : {}),
};
}
diff --git a/packages/core/src/state/project-config.ts b/packages/core/src/state/project-config.ts
index bd749cf3..2e1ce8d2 100644
--- a/packages/core/src/state/project-config.ts
+++ b/packages/core/src/state/project-config.ts
@@ -99,6 +99,19 @@ export interface ModelEntry {
* never directly enters that session's history.
*/
vision?: boolean;
+ /**
+ * Whether video input is supported; defaults to **unsupported** (the opposite default of
+ * `vision`, and only `true` is ever persisted). A video is three orders of magnitude larger
+ * than an image and only a handful of models accept the content item at all, so the safe
+ * default is the one that keeps it out of the request: a video attached to a Session whose
+ * model is not marked `true` is written to the session scratchpad and handed over as an
+ * `[attached file: …]` line instead, where the agent's tools can still work with it.
+ *
+ * Seeded from the catalog's `supportsVideo` (see catalogModelEntry). Not user-settable yet:
+ * the catalog is the only place that knows a vendor accepts video, so the annotation is
+ * preset-only for now, and a user-added row gets no video input.
+ */
+ video?: boolean;
/**
* Per-model max output tokens (the request's output cap, i.e. GenerativeModelConfig.maxTokens):
* when set it wins over the Agent's `system_config.model.max_tokens` — the fit is a model trait
diff --git a/packages/core/test/context-limits.test.ts b/packages/core/test/context-limits.test.ts
index 6f5b4985..973f3ab8 100644
--- a/packages/core/test/context-limits.test.ts
+++ b/packages/core/test/context-limits.test.ts
@@ -117,6 +117,22 @@ describe("approximateMessagesTokens", () => {
expect(approximateMessagesTokens([twoImages])).toBeLessThan(3400);
expect(approximateMessagesTokens([twoImages])).toBeGreaterThan(3200 - 1);
});
+ it("gives video payloads a flat allowance too, megabytes of base64 and all", () => {
+ // A video data URL is tens of MB: counting its characters would put one clip past the
+ // window of most models, so it gets the video allowance and the rest of the estimate
+ // stays where it was.
+ const video = {
+ type: "model_msg",
+ payload: {
+ type: "video_url",
+ role: "user",
+ video_url: `data:video/mp4;base64,${"A".repeat(32 * 1024 * 1024)}`,
+ },
+ } as unknown as OmniMessage;
+ const est = approximateMessagesTokens([video]);
+ expect(est).toBeLessThan(9000);
+ expect(est).toBeGreaterThan(8000);
+ });
});
describe("effectiveMaxOutputTokens (per-request output clamp)", () => {
diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.ts
index d5b41d32..e6991462 100644
--- a/packages/core/test/model-catalog.test.ts
+++ b/packages/core/test/model-catalog.test.ts
@@ -73,6 +73,7 @@ describe("model-catalog", () => {
"baidu",
"tencent",
"iflytek",
+ "volcengine",
"qwen-pay-as-you-go",
"qwen-token-plan",
"modelscope",
@@ -499,17 +500,18 @@ describe("model-catalog", () => {
expect(providerClientType("vllm")).toBe("openai-chat-vllm-adapter");
expect(providerInfo("vllm")!.gatewayBaseUrl).toBeUndefined();
// Groups that declare one at group level, in MODEL_PROVIDERS order: OpenRouter, whose
- // entries all speak the Responses API its preset endpoint serves; vLLM; and the four
- // Chinese first-party groups added 2026-10-15 (Xiaomi MiMo, Baidu ERNIE, Tencent Hunyuan,
- // iFlytek Spark), whose rows all speak Chat Completions to an endpoint AgentHub has no
- // first-party client for. The remaining gateways derive openai-chat from their preset
- // endpoint, and custom / user-defined groups leave the protocol to detection.
+ // entries all speak the Responses API its preset endpoint serves; vLLM; and the five
+ // Chinese first-party groups (Xiaomi MiMo, Baidu ERNIE, Tencent Hunyuan,
+ // iFlytek Spark, and Volcengine Ark), whose rows all speak Chat Completions to an endpoint
+ // AgentHub has no first-party client for. The remaining gateways derive openai-chat from
+ // their preset endpoint, and custom / user-defined groups leave the protocol to detection.
expect(MODEL_PROVIDERS.filter((p) => p.clientType !== undefined).map((p) => p.id)).toEqual([
"openrouter",
"xiaomi",
"baidu",
"tencent",
"iflytek",
+ "volcengine",
"vllm",
]);
expect(providerClientType("openrouter")).toBe("openai-responses");
@@ -992,6 +994,7 @@ describe("model-catalog", () => {
"baidu",
"tencent",
"iflytek",
+ "volcengine",
]) {
expect(providerInfo(id)!.envKey).toBe("OPENAI_API_KEY");
expect(providerInfo(id)!.envBaseUrlKey).toBe("OPENAI_BASE_URL");
@@ -1103,8 +1106,9 @@ describe("model-catalog", () => {
// In preset entries, every gateway model inlines base_url, and so do the two direct rows
// whose own id does not route — MiniMax M3 and DeepSeek deepseek-flash (no credentials) —
- // the custom group's preset, whose group implies no endpoint at all, and the four Chinese
- // first-party groups added 2026-10-15, whose endpoint AgentHub has no client for.
+ // the custom group's preset, whose group implies no endpoint at all, and the five Chinese
+ // first-party groups (Xiaomi MiMo, Baidu ERNIE, Tencent Hunyuan, iFlytek Spark and
+ // Volcengine Ark), whose endpoint AgentHub has no client for.
const pinnedDirect = MODEL_CATALOG.filter((m) => m.provider === "deepseek" && m.baseUrl);
expect(pinnedDirect.map((m) => m.modelId)).toEqual(["deepseek-flash"]);
const customPresets = MODEL_CATALOG.filter((m) => m.provider === "custom");
@@ -1118,7 +1122,7 @@ describe("model-catalog", () => {
...MODEL_CATALOG.filter((m) => m.provider === "penguin-go"),
...MODEL_CATALOG.filter((m) => m.provider === "opencode-go"),
...MODEL_CATALOG.filter((m) =>
- ["xiaomi", "baidu", "tencent", "iflytek"].includes(m.provider),
+ ["xiaomi", "baidu", "tencent", "iflytek", "volcengine"].includes(m.provider),
),
]
// A retired gateway row keeps its pin in the catalog but is not a preset.
@@ -2006,9 +2010,9 @@ describe("off-peak schedules", () => {
it("the DeepSeek rows store the peak price and declare the schedule", () => {
// Every direct row, plus the resold rows whose sellers pass DeepSeek's own windows through:
- // two on Penguin Go, four on OpenCode Go, two on TokenDance and one on OpenRouter. The
- // retired rows keep the schedule too. A gateway row on the schedule carries no flat
- // `discount` — the two are mutually exclusive, pinned by the last case here.
+ // two on Penguin Go, four on OpenCode Go, two on TokenDance, one on OpenRouter and one on
+ // Volcengine Ark. The retired rows keep the schedule too. A gateway row on the schedule
+ // carries no flat `discount` — the two are mutually exclusive, pinned by the last case here.
const rows = MODEL_CATALOG.filter((m) => m.offPeakDiscount === S);
expect(rows.map((m) => `${m.provider}/${m.modelId}`)).toEqual([
"deepseek/deepseek-flash",
@@ -2024,6 +2028,7 @@ describe("off-peak schedules", () => {
"opencode-go/deepseek-v4-flash",
"opencode-go/deepseek-v4-flash-vision-exp",
"opencode-go/deepseek-v4-pro",
+ "volcengine/deepseek-v4-1-flash-261017",
]);
for (const m of rows) {
// Peak is exactly double the off-peak tier DeepSeek publishes. Compared at 1e-5: both
diff --git a/packages/core/test/plugins.test.ts b/packages/core/test/plugins.test.ts
index fecc852e..0c1a50b4 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(21);
+ expect(plugins.length).toBe(22);
for (const plugin of plugins) {
expect(plugin.version, plugin.name).toMatch(PLUGIN_VERSION_PATTERN);
expect(
@@ -218,6 +218,7 @@ describe("groupPlugins / loadPluginGroups", () => {
"use-firecrawl",
"use-lieflat-charts",
"use-offerdao",
+ "use-seedance",
"use-wps-office",
]);
expect(names("ai-app-development")).toEqual([
diff --git a/packages/desktop/package.json b/packages/desktop/package.json
index 69e923df..6450d30d 100644
--- a/packages/desktop/package.json
+++ b/packages/desktop/package.json
@@ -34,6 +34,7 @@
"@adelie/use-firecrawl": "workspace:*",
"@adelie/use-lieflat-charts": "workspace:*",
"@adelie/use-offerdao": "workspace:*",
+ "@adelie/use-seedance": "workspace:*",
"@adelie/use-wps-office": "workspace:*",
"@adelie/use-claude-code": "workspace:*",
"@adelie/wechat-miniprogram": "workspace:*"
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index 5b86b20d..aaf23030 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -28,6 +28,7 @@ Each model card shows the model's display name, tags, context window, prices, ke
| **Default** | The Project's default model |
| **Vision** | The model accepts images |
| **Proxy vision** | The model reads images for models without vision |
+| **Video** | The model accepts videos |
| **Fast** | Fast mode is on |
| **Free** | All three prices are 0 |
| **N% off** | A promotion or an off-peak rate currently applies; see [Prices and promotions](#prices-and-promotions) |
@@ -450,6 +451,7 @@ The table below lists the built-in groups and the environment variables their mo
| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan subscription gateway, preset base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`; pricing from each model page's official list price (the preview model has only a quota-multiplier promo, no list price) |
| modelscope | `OPENAI_API_KEY` | ModelScope's OpenAI-compatible api-inference gateway, preset base URL `https://api-inference.modelscope.cn/v1`; ids are the upstream repo names (`deepseek-ai/DeepSeek-V4.1-Flash`, `Qwen/Qwen3.8-27B`); the group's header authorizes a token for you through an authorization bridge, or takes one you set by hand. See [The ModelScope group](#the-modelscope-group) |
| abliteration | `OPENAI_API_KEY` | Abliteration's own line of "abliterated" (refusal-ablated) models, OpenAI-compatible, preset base URL `https://api.abliteration.ai/v1`; keys look like `ak_…`; all four presets pin Chat Completions. See [The Abliteration group](#the-abliteration-group) |
+| volcengine | `OPENAI_API_KEY` | ByteDance's Volcengine Ark (火山方舟), OpenAI-compatible, preset base URL `https://ark.cn-beijing.volces.com/api/v3`; the Doubao Seed line plus the GLM / Kimi / DeepSeek models Ark resells — 11 presets, all pinning Chat Completions. See [The Volcengine Ark group](#the-volcengine-ark-group) |
| vllm | `OPENAI_API_KEY` | Self-hosted vLLM servers: protocol fixed to `openai-chat-vllm-adapter`, no preset base URL, eight preset models priced at 0 (see [Connect a local or self-hosted endpoint](#connect-a-local-or-self-hosted-endpoint)) |
| custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint; ships one preset, Atria Dawn Preview (Anthropic Messages API at `api.atria-asi.ai`, needs its own key, 256K window, priced at $0 until the vendor publishes prices) |
@@ -501,6 +503,16 @@ The preset rows carry no price. ModelScope bills for api-inference and its model
- **Prices.** Read from the service's own model list, in USD per million Tokens: input 1 or 3, output 2, 3 or 5, and cache hits read at 0.1 or 0.3. It charges no separate cache-write fee, so `cache_write` records the input rate.
- **At most four images per request.** That is the service's own limit, and a request past it is refused outright (`400 … media_count_exceeded`); because a conversation replays its images on every request, such a conversation fails for good. Adelie therefore replaces the **oldest** images with a one-line `[image omitted: …]` placeholder before each request, keeping the newest four (images in the new input count against them first; when a single turn carries five on its own, its oldest ones become placeholders the same way). The conversation and its Trace keep every picture — only what one request carries is reduced.
+### The Volcengine Ark group
+
+`volcengine` is ByteDance's own model platform, Volcengine Ark (火山方舟) — the endpoint the Doubao / Seed line (`doubao-seed-*`) is served from. It is OpenAI-compatible at `https://ark.cn-beijing.volces.com/api/v3`; a key from the Ark console is set once on the group header with **Enter key**.
+
+- **Presets (11).** Seven from the Doubao Seed line — `doubao-seed-evolving`, `doubao-seed-2-1-pro-260915`, `doubao-seed-2-1-lite-260915`, `doubao-seed-2-1-turbo-260628`, `doubao-seed-2-0-lite-260428`, `doubao-seed-2-0-mini-260428`, `doubao-seed-character-260628` — and four Ark resells: `glm-5-3-flash-260828`, `kimi-k3-1-pro-261024`, `deepseek-v4-1-flash-261017`, `deepseek-v4-pro-ga-260813`. Ark's ids carry a version date (`-260915` and the like) and must be copied verbatim; Ark's model units, custom endpoints and Coding Plan subscription are not catalogued.
+- **Protocol and credentials.** AgentHub has no Ark client, so every row pins the Chat Completions client (`client_type = "openai-chat"`) and carries the endpoint on itself. As in every direct vendor group, a keyless row is refused rather than sent your OpenAI key. The GLM, Kimi and DeepSeek rows are sold by Ark: their ids and prices are Ark's own.
+- **Video input.** Seven of the eleven rows accept video — every Doubao Seed row but `doubao-seed-2-1-lite-260915`, plus the resold `glm-5-3-flash-260828` — and their cards carry the **Video** tag: attach a video with the paperclip or by dragging it into the composer, and that request carries the video itself, so the model can describe, summarize or answer questions about it. The remaining four (2.1 Lite, Kimi and the two DeepSeek rows) receive an `[attached file: …]` line instead: the video lands in the session scratchpad and the agent works with it through its own tools.
+- **Prices.** From Ark's model-pricing page, 在线推理(常规) table, in CNY per million Tokens (input non-audio / cache-hit non-audio / output), stored in USD at the fixed rate of 7. Ark prices by input length and only the base tier is recorded here; `deepseek-v4-1-flash-261017` follows DeepSeek's off-peak schedule, at half price outside Beijing weekday 09:00–12:00 and 14:00–18:00.
+- **What is not here.** Ark's image generation (Seedream), video generation (Seedance), 3D and embedding models are not chat models, so a Session cannot hold a conversation on one and they stay out of the catalog; to generate a video, see the `use-seedance` plugin in [the plugin library](/skills#built-in-library): one sentence, one mp4 in the workspace.
+
### Preset models
The preset catalog includes, among others:
@@ -562,6 +574,7 @@ Each `ModelEntry` has these fields:
| `client_type` | Protocol hint (`openai-chat` for Chat Completions, `openai-responses` for the Responses API, `ant-messages` for Anthropic Messages, …); inferred by AgentHub from the model id when omitted. Custom endpoints use one of those three generic protocol clients, and the Web dialog can detect which one a base URL serves. The pre-0.4.2 spelling `openai` is a deprecated alias and is normalized to `openai-chat` when the config is read |
| `display_name` | Display name |
| `vision` | Whether image input is supported, default true |
+| `video` | Whether video input is supported, default **false** (the opposite default of `vision`): set to `true` only for a model that really takes a video. A marked model gets the video as a content part on the request; an unmarked one gets a file path instead, see [The Volcengine Ark group](#the-volcengine-ark-group). Preset from the catalog's `supportsVideo`; the Web App offers no switch for it yet |
| `fast_mode` | Optional fast mode (off by default): opts the model's Session requests into the provider's faster serving tier at premium pricing. Only `true` is ever persisted — omitting the field on a Web full-table save clears it. Models without a fast tier reject requests carrying it (see [Fast mode](#fast-mode)) |
| `pricing` | Three price buckets (unit `usd_per_mtok`, USD per million tokens): `cache_read` / `cache_write` / `output` |
| `api_key` / `base_url` | Inlined credentials, both optional; when blank, AgentHub falls back to environment variables |
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index 2526239c..23c40c11 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -28,6 +28,7 @@ description: 为 Project 添加模型,设置 API key 和默认模型,选择
| **默认** | Project 的默认模型 |
| **视觉** | 模型可以接收图片 |
| **视觉代理** | 模型代替不支持视觉的模型读取图片 |
+| **视频** | 模型可以接收视频 |
| **快速** | 已开启快速模式 |
| **免费** | 三项价格都是 0 |
| **省 N%** | 当前有促销价或空闲时段价生效;见[价格与促销](#价格与促销) |
@@ -449,6 +450,7 @@ Adelie 升级可能改变内置的预置模型目录。一旦发生,Project ow
| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan 订阅网关,预置 base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`;价格取自各模型页面的官方牌价(预览模型只有配额倍率优惠,没有牌价) |
| modelscope | `OPENAI_API_KEY` | 魔搭的 OpenAI 兼容 api-inference 网关,预置 base URL `https://api-inference.modelscope.cn/v1`;id 就是上游仓库名(如 `deepseek-ai/DeepSeek-V4.1-Flash`、`Qwen/Qwen3.8-27B`);分组标题栏可以经授权中转层为你自动授权一把 token,也可以手动设置。见 [ModelScope 分组](#modelscope-分组) |
| abliteration | `OPENAI_API_KEY` | abliteration.ai 自家那批「abliterated」(去审查微调)模型,OpenAI 兼容,预置 base URL `https://api.abliteration.ai/v1`;key 形如 `ak_…`;四条预置都固定 Chat Completions 客户端。见 [Abliteration 分组](#abliteration-分组) |
+| volcengine | `OPENAI_API_KEY` | 字节跳动的火山方舟(Volcengine Ark),OpenAI 兼容,预置 base URL `https://ark.cn-beijing.volces.com/api/v3`;Doubao Seed 系列,加上方舟转售的 GLM / Kimi / DeepSeek,共 11 条预置,全部固定 Chat Completions 客户端。见 [Volcengine Ark 分组](#volcengine-ark-分组) |
| vllm | `OPENAI_API_KEY` | 自托管 vLLM 服务器:协议固定为 `openai-chat-vllm-adapter`,无预置 base URL,八个预置模型价格均为 0(见[连接本地或自托管端点](#连接本地或自托管端点)) |
| custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点;自带一个预置模型 Atria Dawn Preview(Anthropic Messages API,地址 `api.atria-asi.ai`,需要自己的 key,上下文窗口 256K,供应商公布价格之前定价 $0) |
@@ -498,6 +500,16 @@ OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance /
- **预置模型。** `abliterated-model-large-v2`(官方推荐的默认选择)、`abliterated-model-large`、`abliterated-model-large-flash` 与 `abliterated-model`。前两条是 1,000,000 Token 上下文、只收文本;`flash` 是 1,048,576 并接受图像;`abliterated-model` 是 262,144,也接受图像。
- **协议。** 这些 id 没有一条能被 AgentHub 按名字认出来,所以每个条目都固定 Chat Completions 客户端(`client_type = "openai-chat"`)并把端点写在条目上;同一条端点上也有 `/responses`,要换协议在条目上改即可。和所有网关一样,没有 key 的条目会被拒绝,而不是把你的 OpenAI key 发过去。
- **价格。** 取自服务自己的模型列表,单位是每百万 Token 多少美元:输入 1 或 3,输出 2、3 或 5,缓存命中的读价 0.1 或 0.3。它不额外收缓存写入费,所以 `cache_write` 记的就是输入价。
+
+### Volcengine Ark 分组
+
+`volcengine` 是字节跳动自己的模型平台火山方舟(Volcengine Ark),豆包 / Seed(`doubao-seed-*`)就是从这台端点上服务的。端点是 OpenAI 兼容的 `https://ark.cn-beijing.volces.com/api/v3`,key 从方舟控制台领取,在分组标题栏用**填写密钥**设置一次即可。
+
+- **预置模型(11 条)。** Doubao Seed 七条:`doubao-seed-evolving`、`doubao-seed-2-1-pro-260915`、`doubao-seed-2-1-lite-260915`、`doubao-seed-2-1-turbo-260628`、`doubao-seed-2-0-lite-260428`、`doubao-seed-2-0-mini-260428`、`doubao-seed-character-260628`;方舟转售四条:`glm-5-3-flash-260828`、`kimi-k3-1-pro-261024`、`deepseek-v4-1-flash-261017`、`deepseek-v4-pro-ga-260813`。方舟的模型 id 带版本号(`-260915` 这串就是版本日期),必须照抄;方舟的模型单元、自定义接入点和 Coding Plan 订阅不在收录范围内。
+- **协议与凭证。** AgentHub 没有方舟客户端,所以每个条目都固定 Chat Completions 客户端(`client_type = "openai-chat"`)并把端点写在条目上。和其他直连厂商分组一样,没有 key 的条目会被拒绝,而不是把你的 OpenAI key 发过去。GLM、Kimi、DeepSeek 四条卖的是方舟,id 和价格都是方舟那一份。
+- **视频输入。** 11 条里有七条接受视频:豆包 Seed 除 `doubao-seed-2-1-lite-260915` 以外的六条,加上方舟转售的 `glm-5-3-flash-260828`,卡片上标**视频**:在对话里点回形针或把视频拖进输入框,这一轮请求就会带上视频本身,模型可以直接描述、总结或提问。其余四条(2.1 Lite、Kimi 与两条 DeepSeek)收到的是一行 `[attached file: …]`,视频落在会话暂存目录里,由 Agent 自己用工具处理。
+- **价格。** 取自方舟定价页的「在线推理(常规)」表,人民币每百万 Token(输入非音频 / 缓存命中非音频 / 输出),按固定汇率 7 换算成美元存储。方舟按输入长度分档计价,这里只记录基础档;`deepseek-v4-1-flash-261017` 跟随 DeepSeek 的空闲时段,北京时间工作日 9:00–12:00、14:00–18:00 之外按半价计算。
+- **不在这个分组里的。** 方舟的图片生成(Seedream)、视频生成(Seedance)、3D 与向量化模型都不是对话模型,会话无法承载它们,因此不进模型库;需要生成视频时,见[插件库](/skills#内置插件库)里的 `use-seedance`:一句话让 Agent 生成一个 mp4 落到工作区。
- **一次请求最多 4 张图。** 这是服务自己的限制,超过它会直接回 `400 … media_count_exceeded`,而对话里的图会被每一次请求重新带上——所以会话会一直失败。Adelie 因此在每次请求前把**最旧的**那几张换成一行 `[image omitted: …]` 文字占位,只保留最新的四张(新发出的图优先算进这四张;一轮自己就带了五张时,这一次输入里的旧图也一样换成占位)。对话本身和 Trace 里的图一张不少,改的只是这一次请求带过去的量。
### 预置模型
@@ -561,6 +573,7 @@ OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance /
| `client_type` | 协议提示(`openai-chat` 对应 Chat Completions,`openai-responses` 对应 Responses API,`ant-messages` 对应 Anthropic Messages 等);省略时由 AgentHub 根据模型 id 推断。自定义端点使用这三种通用协议客户端之一,Web 弹窗可以检测一个 base URL 对应哪一种。`openai` 是 0.4.2 之前的旧写法,已弃用,读取配置时会归一化为 `openai-chat` |
| `display_name` | 展示名称 |
| `vision` | 是否支持图像输入,默认 true |
+| `video` | 是否支持视频输入,默认 false(和 `vision` 相反):只有模型确实收视频时才写 `true`。带 `true` 的模型,对话里加入的视频会作为视频内容部件随请求发出;未标记的模型改走文件路径,见 [Volcengine Ark 分组](#volcengine-ark-分组)。预置时由模型目录的 `supportsVideo` 写入,Web 端暂不提供手动开关 |
| `fast_mode` | 可选的快速模式(默认关闭):开启后,这个模型的 Session 请求会改走供应商更快的服务层级,价格更高。持久化保存的值只有 `true`;在 Web 端整表保存时省略这个字段会把它清空。没有快速层级的模型会拒绝携带这个设置的请求(参见[快速模式](#快速模式)) |
| `pricing` | 三档价格(单位 `usd_per_mtok`,即每百万 Token 的美元价格):`cache_read` / `cache_write` / `output` |
| `api_key` / `base_url` | 内联的凭证,两项都可选;留空时 AgentHub 回退到环境变量 |
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index 44ea301b..a45c8f28 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -222,6 +222,7 @@ The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plu
| | `browser-automation` | Drive the desktop app's [Built-in Browser](/builtin-browser) with `penguin browser`: read pages as simplified HTML or text, act with JavaScript and trusted clicks and typing, and extract data such as Amazon orders, signed in with accounts imported from the system browser |
| | `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) |
| | `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 c3650749..95e6eb8c 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -222,6 +222,7 @@ Agent 可以在 Task 中重写自己的 `SKILL.md`。结合 Benchmark 评估和
| | `browser-automation` | 用 `penguin browser` 驱动桌面应用的[内置浏览器](/builtin-browser):以简化 HTML 或纯文本读取页面,用 JavaScript 以及可信的点击和输入操作页面,提取亚马逊订单这样的数据,登录状态可从系统浏览器导入 |
| | `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 走完异步三步(提交任务、按退避间隔轮询、下载成片),密钥存在密钥库里(预装) |
| | `humanizer` | 去除任何语言文字中的 AI 写作痕迹,改写成书籍、报纸和百科全书的语体(不预装:需要时从插件库安装) |
| | `goal` | [目标模式](/goal-mode)背后的 stop 钩子:让 Session 持续朝着目标推进,直到完成、受阻或 Token 预算耗尽(预装) |
| | `continual-learning` | Task 运行超过 30 轮才结束时,把 Task 的精简摘录交给后台子 Agent,由它把有长期价值的发现沉淀到 Agent 的 Skill 中(不预装) |
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index a06d64cd..4659a1d6 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -206,6 +206,14 @@ export interface UploadLimits {
* Trace, where its size is paid again on every history page and every resume.
*/
imageMaxMb: number;
+ /**
+ * Per-video cap for videos that ride the conversation inline, on a model that takes video
+ * input. Fixed server-side and larger than the image cap (a video is megabytes, and the
+ * provider takes a video under 50MB inside a 64MB body — this is that ceiling with base64's
+ * 4/3 accounted for). The composer's pre-flight check reads it from here so the number a user
+ * is refused by is the number the server enforces, not a second copy that can drift.
+ */
+ videoMaxMb: number;
/**
* The range the two admin-settable limits may be set to. Carried here so the admin form states
* the real bounds without compiling its own copy of them — the server is the only place that
@@ -797,6 +805,15 @@ export interface ModelInfo {
* unset (= treated as supported).
*/
vision?: boolean;
+ /**
+ * Whether video input is supported: the TOML `video` annotation (preset-written) or the
+ * built-in catalog's own annotation. Unlike `vision` the default is **unsupported** — a
+ * video is megabytes of base64, and a Session whose model does not take one is better served
+ * by the clip arriving as an ordinary file attachment than by a request the provider
+ * refuses. What the composer reads to decide between the two, and what the server's own
+ * routes decide it with (core's `catalogSupportsVideo`).
+ */
+ video?: boolean;
/**
* Per-model max output tokens (TOML `max_tokens` annotation; user-only, never preset by the
* built-in catalog): when set it wins over the Agent's `system_config.model.max_tokens`;
@@ -2434,8 +2451,11 @@ export interface MessagesResponse {
* `tracePosition`, an inline PNG / JPEG / GIF / WebP `data:` URL — a user `image_url`, or
* an entry of a tool output's `images` — is replaced by
* `/api/sessions/<sessionId>/trace-image?file=<fileIndex>&ordinal=<ordinal>[&i=<k>]`
- * (`i` = the index into `images`), an immutable, access-checked image response. Expanded
- * subagent messages, held inputs not yet in the Trace, other image types and the
+ * (`i` = the index into `images`), an immutable, access-checked image response. A user
+ * `video_url` is referenced the same way, through
+ * `/api/sessions/<sessionId>/trace-video?file=<fileIndex>&ordinal=<ordinal>` — a video is
+ * tens of megabytes of base64 and a page that carried one inline would never load.
+ * Expanded subagent messages, held inputs not yet in the Trace, other image types and the
* parameterless full read keep their data URLs.
*/
messages: HistoryMessage[];
@@ -2472,6 +2492,24 @@ export type TaskInputPart =
* read back on every history page and every resume.
*/
| { type: "image_url"; imageUrl: string }
+ /**
+ * A video that rides the conversation inline on a Session whose model takes video input
+ * (the Volcengine Ark Seed family — see ModelCatalogEntry.supportsVideo): a base64
+ * `data:video/…` URL or an http(s) URL, capped at 32MB (413 `video_too_large`) for the same
+ * reason an image is capped, one order of magnitude up: it enters the conversation and is
+ * written into the Trace, which is read back whole on every history page and every resume.
+ * The provider's own ceiling is what the number is derived from (Ark: video under 50MB,
+ * request body under 64MB). One request carries at most one video — the video budget in
+ * core's llm/generative-model.ts drops the older ones with a note — because a video is
+ * megabytes of base64 and the body is the limit.
+ *
+ * On a model that takes no video, the part is NOT refused: the clip is written into the
+ * Session scratchpad and handed over as an `[attached file: <path>]` line exactly like a
+ * `file` part, so one composer draft goes to either kind of model. `fileName` names it on
+ * disk (default derived from the data URL's type); an http(s) URL cannot be written to disk
+ * and is a 400 in that case.
+ */
+ | { type: "video_url"; videoUrl: string; fileName?: string }
/**
* File attachment (the composer's "+" menu): `dataUrl` is a base64 `data:` URL of the
* file's bytes, capped per file and per message by the admin-settable upload limits
@@ -2566,14 +2604,23 @@ export interface SteerRequest {
* `TaskInputPart.image_url`): delivered as user image messages right behind the
* `[user_steering]` text. A model without vision receives them as scratchpad path lines
* instead, exactly as it would a Prompt's images. At least one of `text` / `images` /
- * `files` must be non-empty.
+ * `files` / `videos` must be non-empty.
*/
images?: string[];
+ /**
+ * Videos sent with the steering message (`data:video/…` or http(s) URLs, same rule and cap
+ * as a task input's `video_url` part): delivered as user video messages right behind the
+ * images. Only for a Session whose model takes video input — on any other model a video
+ * belongs in `files`, where it reaches the model as an `[attached file: <path>]` line (the
+ * server refuses an inline one rather than sending a request the model would refuse).
+ */
+ videos?: string[];
/**
* File attachments riding the steering message — the same shape, caps and handling as a
* task input's `{type:"file"}` parts: written into the Session scratchpad and delivered
* as `[attached file: <path>]` lines on the `[user_steering]` text, so a file-only draft
* steers exactly like an image-only one instead of falling back to the follow-up queue.
+ * A video on a model without video input is sent this way.
*/
files?: { fileName: string; dataUrl: string }[];
}
@@ -2592,6 +2639,8 @@ export interface PendingSteeringInfo {
text: string;
/** Number of images that rode along. */
images: number;
+ /** Number of inline videos that rode along (a model without video input gets them as files instead). */
+ videos: number;
/** Number of file attachments that rode along. */
files: number;
}
@@ -2609,6 +2658,8 @@ export interface PendingFollowUpInfo {
text: string;
/** Number of images in the queued input. */
images: number;
+ /** Number of inline videos in the queued input (a model without video input gets them as files instead). */
+ videos: number;
/** Number of file attachments in the queued input. */
files: number;
}
@@ -2653,6 +2704,8 @@ export interface RecalledMessageResponse {
text: string;
/** The images as submitted (`data:` / http(s) URLs). */
images: string[];
+ /** The inline videos as submitted (`data:video/…` / http(s) URLs); a model without video input got them as files instead. */
+ videos: string[];
/** The file attachments, re-encoded as base64 data URLs (the shape the composer submits them in). */
files: { fileName: string; dataUrl: string }[];
}
diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.ts
index 8392a075..2c585df9 100644
--- a/packages/server/src/http/routes/me.ts
+++ b/packages/server/src/http/routes/me.ts
@@ -43,6 +43,7 @@ import { validateDraftShortcuts } from "../../services/draft-shortcuts.js";
import { validateKeybindings } from "../../services/keybindings.js";
import {
INLINE_IMAGE_MAX_MB,
+ INLINE_VIDEO_MAX_MB,
MAX_ATTACHMENT_COUNT,
MAX_ATTACHMENT_MB,
MIN_ATTACHMENT_MB,
@@ -143,6 +144,7 @@ export function meRoutes(deps: MeRouteDeps): Hono<AppEnv> {
...deps.serverSettingsRepo.getAttachmentLimitsMb(),
attachmentMaxCount: MAX_ATTACHMENT_COUNT,
imageMaxMb: INLINE_IMAGE_MAX_MB,
+ videoMaxMb: INLINE_VIDEO_MAX_MB,
attachmentLimitMinMb: MIN_ATTACHMENT_MB,
attachmentLimitMaxMb: MAX_ATTACHMENT_MB,
},
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index ddf30502..af28d086 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -12,12 +12,14 @@ import { Hono } from "hono";
import type { Context } from "hono";
import {
THINKING_LEVEL_NAMES,
+ catalogSupportsVideo,
imageUrlMessage,
isValidId,
scratchpadDir,
sessionScratchpadDir,
stripLeadingMarkerBlocks,
userText,
+ videoUrlMessage,
} from "@adelie/core";
import type { OmniMessage } from "@adelie/core";
import type {
@@ -47,7 +49,7 @@ import type {
import { compactionThresholdFor } from "../../services/context-breakdown.js";
import { decodeCursor } from "../../services/message-window.js";
import type { MessagesPageRequest } from "../../services/trace-service.js";
-import { withImagesByReference } from "../../services/trace-images.js";
+import { withMediaByReference } from "../../services/trace-media.js";
import { PREVIEW_TOKEN_TTL_MS, resolvePreviewTarget } from "../../services/preview-token.js";
import type { AppEnv } from "../../auth/middleware.js";
import type { SessionRow } from "../../db/repos/sessions.js";
@@ -119,6 +121,8 @@ import type { TaskAttachment } from "../../services/task-attachments.js";
import {
INLINE_IMAGE_MAX_BYTES,
INLINE_IMAGE_MAX_MB,
+ INLINE_VIDEO_MAX_BYTES,
+ INLINE_VIDEO_MAX_MB,
toAttachmentLimits,
} from "../../services/attachment-limits.js";
import type { AttachmentLimits } from "../../services/attachment-limits.js";
@@ -342,6 +346,82 @@ function requireImageUrl(url: unknown, field: string): string {
);
}
+/**
+ * The video-URL rule (`TaskInputPart.video_url`): a base64 `data:video/…` URL the Session
+ * carries inline, or an http(s) URL it references.
+ *
+ * The mime must be a video one, unlike an image's unconstrained `data:` URL: a part declared as
+ * a video is sent to the provider as one, so a data URL carrying, say, a PDF would be a request
+ * the model refuses — better a 400 here that names the field. The size cap is the video one
+ * (larger than an image's ceiling, smaller than the provider's own body limit once base64 has
+ * inflated it: see attachment-limits.ts).
+ */
+const VIDEO_DATA_URL = /^data:video\/[^;,]+;base64,[A-Za-z0-9+/=\s]+$/;
+
+function requireVideoUrl(url: unknown, field: string): string {
+ if (typeof url === "string") {
+ if (url.startsWith("http://") || url.startsWith("https://")) return url;
+ if (VIDEO_DATA_URL.test(url)) {
+ const bytes = dataUrlByteLength(url);
+ if (bytes > INLINE_VIDEO_MAX_BYTES) {
+ throw new HttpError(
+ 413,
+ "video_too_large",
+ `${field} exceeds the ${INLINE_VIDEO_MAX_MB}MB inline video limit.`,
+ );
+ }
+ return url;
+ }
+ }
+ throw badRequest(
+ `${field} must be an http(s) URL or a base64 video data: URL (data:video/<type>;base64,<bytes>).`,
+ );
+}
+
+/** The bytes and mime of a validated video data URL (used when the Session's model takes none). */
+function decodeVideoDataUrl(url: string, field: string): { bytes: Buffer; mime: string } {
+ const match = /^data:([^;,]+);base64,([A-Za-z0-9+/=\s]+)$/.exec(url);
+ if (!match) {
+ throw badRequest(`${field} must be a base64 data: URL for the video to be written to disk.`);
+ }
+ return { bytes: Buffer.from(match[2]!, "base64"), mime: match[1]! };
+}
+
+/** The extensions the common video mimes map to, for naming a video that arrived without a name. */
+const VIDEO_MIME_EXTENSIONS: Record<string, string> = {
+ "video/mp4": ".mp4",
+ "video/quicktime": ".mov",
+ "video/webm": ".webm",
+ "video/x-matroska": ".mkv",
+ "video/x-msvideo": ".avi",
+};
+
+/**
+ * File name for a video handed over as a file (a model without video input): the submitted name
+ * when there is one, else a generic one carrying the data URL's own extension so the agent sees
+ * a file it can recognize.
+ */
+function videoFileName(given: unknown, mime: string): string {
+ if (typeof given === "string" && given.length > 0) return given;
+ const ext = VIDEO_MIME_EXTENSIONS[mime.toLowerCase()] ?? "";
+ return `video${ext || ".mp4"}`;
+}
+
+/**
+ * A video handed over as a file, for a Session whose model takes no video input: the same
+ * `TaskAttachment` a `{type:"file"}` part builds, from the video part's data URL — so the clip
+ * lands in the scratchpad and reaches the model as an `[attached file: <path>]` line like any
+ * other attachment, and a draft written for a video model still sends to a text one.
+ *
+ * An http(s) URL is refused here rather than half-honoured: the point of the file path is to
+ * put bytes on disk, and there is nothing to write. The 400 says which of the two the caller
+ * should send instead.
+ */
+function videoAttachment(url: string, given: unknown, field: string): TaskAttachment {
+ const { bytes, mime } = decodeVideoDataUrl(url, field);
+ return { fileName: videoFileName(given, mime), bytes, mime };
+}
+
/**
* Decoded byte length of a base64 data URL, computed from the payload's length rather than by
* decoding it: the point is to reject an oversize image *before* materializing it as a Buffer.
@@ -389,10 +469,25 @@ interface ParsedTaskInput {
texts: string[];
/** The `image_url` parts in order, as submitted — the recall store's images. */
images: string[];
+ /** The `video_url` parts in order, as submitted — the recall store's videos (inline ones only). */
+ videos: string[];
}
-/** Validate Prompt input parts: text, image (data: / http(s) URL), or an uploaded file. */
-function parseTaskInput(body: Record<string, unknown>, limits: AttachmentLimits): ParsedTaskInput {
+/**
+ * Validate Prompt input parts: text, image (data: / http(s) URL), video (same, when the
+ * Session's model takes one) or an uploaded file.
+ *
+ * `videoInput` = whether the Session's model takes video input (core's
+ * `catalogSupportsVideo`, matching what the model entry is built with). A `video_url` part is
+ * accepted either way, but only rides inline when it is true: on any other model the clip is
+ * turned into an ordinary file attachment, so one composer draft is sendable to either kind of
+ * model and the user is not left to guess which one they are talking to.
+ */
+function parseTaskInput(
+ body: Record<string, unknown>,
+ limits: AttachmentLimits,
+ videoInput: boolean,
+): ParsedTaskInput {
const input = body.input;
if (!Array.isArray(input) || input.length === 0) {
throw badRequest("input must be an array with at least one item.");
@@ -401,6 +496,7 @@ function parseTaskInput(body: Record<string, unknown>, limits: AttachmentLimits)
const attachments: TaskAttachment[] = [];
const texts: string[] = [];
const images: string[] = [];
+ const videos: string[] = [];
input.forEach((item, i) => {
if (item === null || typeof item !== "object" || Array.isArray(item)) {
throw badRequest(`input[${i}] must be an object.`);
@@ -420,6 +516,19 @@ function parseTaskInput(body: Record<string, unknown>, limits: AttachmentLimits)
images.push(url);
return;
}
+ if (part.type === "video_url") {
+ const url = requireVideoUrl(part.videoUrl, `input[${i}].videoUrl`);
+ if (videoInput) {
+ messages.push(videoUrlMessage(url));
+ videos.push(url);
+ } else {
+ // Not an OmniMessage: the clip becomes an attachment, which attachFilesToInput writes
+ // to the scratchpad and turns into an `[attached file: <path>]` line on the text.
+ attachments.push(videoAttachment(url, part.fileName, `input[${i}].videoUrl`));
+ assertAttachmentBudget(attachments, limits);
+ }
+ return;
+ }
if (part.type === "file") {
// Not an OmniMessage of its own: the file becomes an `[attached file: …]` line on the
// text message once written to the scratchpad, so it carries no payload into the run.
@@ -429,9 +538,9 @@ function parseTaskInput(body: Record<string, unknown>, limits: AttachmentLimits)
assertAttachmentBudget(attachments, limits);
return;
}
- throw badRequest(`input[${i}].type must be one of text / image_url / file.`);
+ throw badRequest(`input[${i}].type must be one of text / image_url / video_url / file.`);
});
- return { messages, attachments, texts, images };
+ return { messages, attachments, texts, images, videos };
}
/**
@@ -442,12 +551,14 @@ function parseTaskInput(body: Record<string, unknown>, limits: AttachmentLimits)
function recallStore(
text: string,
images: string[],
+ videos: string[],
attachments: TaskAttachment[],
written: string[],
): RecallStore {
return {
text,
images,
+ videos,
files: written.map((p, i) => ({
fileName: attachments[i]!.fileName,
path: p,
@@ -459,12 +570,13 @@ function recallStore(
/**
* Serve one recall (#287): read the withdrawn message's file attachments back into data URLs,
* delete their scratchpad copies (nothing references them anymore — leaving them would strand
- * a second copy when the user resends), and hand the composer-shaped content back.
+ * a second copy when the user resends), and hand the composer-shaped content back. Inline
+ * images and videos need no round trip: the store already holds them as submitted.
*/
async function recalledResponse(recall: RecallStore): Promise<RecalledMessageResponse> {
const files = await readRecalledFiles(recall.files);
await removeAttachments(recall.files.map((f) => f.path));
- return { text: recall.text, images: recall.images, files };
+ return { text: recall.text, images: recall.images, videos: recall.videos, files };
}
/**
@@ -478,6 +590,25 @@ function parseSteerImages(body: Record<string, unknown>): string[] {
return images.map((url, i) => requireImageUrl(url, `images[${i}]`));
}
+/**
+ * Validate the optional `videos` field of a steer request: the same rule and cap as a task
+ * input's `videoUrl` part, absent or empty = no video. Only meaningful on a Session whose
+ * model takes video input — on any other model the caller sends the clip through `files`,
+ * where it reaches the model as an `[attached file: <path>]` line. An inline one arriving
+ * anyway is a 400 that says so, rather than a request the provider would refuse.
+ */
+function parseSteerVideos(body: Record<string, unknown>, videoInput: boolean): string[] {
+ const videos = body.videos;
+ if (videos === undefined) return [];
+ if (!Array.isArray(videos)) throw badRequest("videos must be an array.");
+ if (!videoInput) {
+ throw badRequest(
+ "This Session's model takes no video input; send the video as a file attachment instead.",
+ );
+ }
+ return videos.map((url, i) => requireVideoUrl(url, `videos[${i}]`));
+}
+
/**
* Validate the optional `files` field of a steer request: the same shape and caps as a task
* input's `{type:"file"}` parts (parseAttachmentPart, budget re-checked per item), absent or
@@ -1072,7 +1203,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
});
// One image of one Trace record, the URL a windowed history page puts in place of an
- // inline data URL (services/trace-images.ts). The record never changes, so the answer is
+ // inline data URL (services/trace-media.ts). The record never changes, so the answer is
// immutable; only inert raster types are ever served (the page references nothing else).
app.get("/:sessionId/trace-image", async (c) => {
const row = resolveSession(c);
@@ -1090,13 +1221,14 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
if (fileIndex === undefined || ordinal === undefined) {
throw badRequest("file and ordinal are required.");
}
- const image = await deps.traceService.readTraceImage(
+ const image = await deps.traceService.readTraceMedia(
row.projectId,
row.agentId,
row.sessionId,
fileIndex,
ordinal,
intQuery("i", 0),
+ "image",
);
return c.body(new Uint8Array(image.bytes), 200, {
"content-type": image.mime,
@@ -1105,6 +1237,33 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
});
});
+ // One video of one Trace record, the same reference scheme as trace-image above and for the
+ // same page budget: a minute of video is tens of megabytes of base64, which a message page
+ // would otherwise have to read out of the Trace whole. Served with the video types the task
+ // route accepts, so the browser plays it from its own origin.
+ app.get("/:sessionId/trace-video", async (c) => {
+ const row = resolveSession(c);
+ const fileIndex = parseNonNegativeInt(c.req.query("file") ?? "");
+ const ordinal = parseNonNegativeInt(c.req.query("ordinal") ?? "");
+ if (fileIndex === null || fileIndex < 1 || ordinal === null) {
+ throw badRequest("file (at least 1) and ordinal are required.");
+ }
+ const video = await deps.traceService.readTraceMedia(
+ row.projectId,
+ row.agentId,
+ row.sessionId,
+ fileIndex,
+ ordinal,
+ undefined,
+ "video",
+ );
+ return c.body(new Uint8Array(video.bytes), 200, {
+ "content-type": video.mime,
+ "x-content-type-options": "nosniff",
+ "cache-control": "private, max-age=31536000, immutable",
+ });
+ });
+
app.get("/:sessionId/messages", async (c) => {
const row = resolveSession(c);
const page = messagesPageQuery(c);
@@ -1171,7 +1330,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
// Images by reference, after the held inputs were merged: the dedup compares raw
// envelopes, and a held input carries its image inline exactly as its Trace copy does.
const messages = appendPendingInputs(result.messages, pendingInputs).map((m) =>
- withImagesByReference(row.sessionId, m),
+ withMediaByReference(row.sessionId, m),
);
return c.json({
messages,
@@ -1236,13 +1395,17 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
// Resolved per request from the admin settings, so a limit change applies to the very next
// upload rather than at the next restart.
const limits = toAttachmentLimits(deps.serverSettingsRepo.getAttachmentLimitsMb());
+ // Whether the Session's model takes video input decides how a `video_url` part travels:
+ // inline on a video model, as an ordinary file attachment on any other (see
+ // parseTaskInput). Read from the same catalog the model entry is built from.
+ const videoInput = catalogSupportsVideo(row.provider, row.modelId);
if (goal) {
// Goal mode: the input needs non-empty text, since its marker-stripped text becomes the
// objective that every round re-injects and an image on its own doesn't say what the
// goal is. Images ride round 1 as ordinary input. File attachments cannot: nothing
// folds them into the objective, so they are turned away here, before any upload is
// written to disk.
- const { messages, attachments } = parseTaskInput(body, limits);
+ const { messages, attachments } = parseTaskInput(body, limits, videoInput);
const text = messages
.filter((m) => (m.payload as { type?: string }).type === "text")
.map((m) => (m.payload as { text: string }).text)
@@ -1252,7 +1415,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
throw badRequest("goal mode requires a non-empty text objective.");
}
if (attachments.length > 0) {
- throw badRequest("goal mode accepts text and images only (no file attachments).");
+ throw badRequest("goal mode accepts text, images and videos only (no file attachments).");
}
// The goal plugin owns the protocol — its user_prompt hook writes the goal file and
// composes round 1, its stop hook drives every later round; the manager runs the
@@ -1265,7 +1428,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
});
return c.json({ sessionId } satisfies TaskCreateResponse, 202);
}
- const parsed = parseTaskInput(body, limits);
+ const parsed = parseTaskInput(body, limits, videoInput);
// Follow-up queue: with queueIfBusy, a busy session enqueues the input instead of 409
// (auto-starts as an ordinary next task once idle; the response says which happened).
const queueIfBusy = body.queueIfBusy === true;
@@ -1292,7 +1455,13 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
queueIfBusy,
// Original content, kept while the input waits in the follow-up queue so a recall
// (DELETE /follow-ups/:id) can hand it back; unused when the task starts directly.
- recall: recallStore(parsed.texts.join("\n"), parsed.images, parsed.attachments, written),
+ recall: recallStore(
+ parsed.texts.join("\n"),
+ parsed.images,
+ parsed.videos,
+ parsed.attachments,
+ written,
+ ),
});
return c.json({ sessionId, queued } satisfies TaskCreateResponse, 202);
} catch (err) {
@@ -1314,14 +1483,17 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
const body = await readJson(c);
const text = typeof body.text === "string" ? body.text.trim() : "";
const images = parseSteerImages(body);
+ // Inline video only where the model takes it: a mid-run message has no model picker of
+ // its own, so the same catalog answer the Session was built with decides.
+ const videos = parseSteerVideos(body, catalogSupportsVideo(row.provider, row.modelId));
const files = parseSteerFiles(
body,
toAttachmentLimits(deps.serverSettingsRepo.getAttachmentLimitsMb()),
);
// Any part can carry the message on its own: an image or a file with no caption is a
// complete steering message, and so is plain text.
- if (!text && images.length === 0 && files.length === 0) {
- throw badRequest("text, images or files must carry the steering message.");
+ if (!text && images.length === 0 && videos.length === 0 && files.length === 0) {
+ throw badRequest("text, images, videos or files must carry the steering message.");
}
// The wire shape becomes core's: a user text message (omitted when the images are the
// whole message, so the fold's path lines aren't preceded by a blank one) plus one image
@@ -1329,13 +1501,17 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
// Session scratchpad exactly as a task's do and ride as `[attached file: <path>]` lines
// on the steering text (a files-only input becomes a line-only text message).
const { input, written } = await attachFilesToInput(
- [...(text ? [userText(text)] : []), ...images.map((url) => imageUrlMessage(url))],
+ [
+ ...(text ? [userText(text)] : []),
+ ...images.map((url) => imageUrlMessage(url)),
+ ...videos.map((url) => videoUrlMessage(url)),
+ ],
files,
scratchpadDir(deps.config.root, row.projectId, row.agentId),
row.sessionId,
);
try {
- deps.manager.steer(row.sessionId, input, recallStore(text, images, files, written));
+ deps.manager.steer(row.sessionId, input, recallStore(text, images, videos, files, written));
} catch (err) {
// 409 (not running) or any other refusal: the files must not stay behind — the
// frontend falls back to a normal task POST, which writes its own copies.
diff --git a/packages/server/src/mechanisms/traces.ts b/packages/server/src/mechanisms/traces.ts
index 296c4326..98ce5f89 100644
--- a/packages/server/src/mechanisms/traces.ts
+++ b/packages/server/src/mechanisms/traces.ts
@@ -163,13 +163,18 @@ export abstract class Traces {
offset: number,
limit: number,
): Promise<TraceEventsResponse>;
- abstract readTraceImage(
+ /**
+ * One image (`kind` "image") or video ("video") of one Trace record, decoded — the record's
+ * own `image_url` / `video_url` (`slot` undefined) or its tool output's `images[slot]`.
+ */
+ abstract readTraceMedia(
projectId: string,
agentId: string,
sessionId: string,
fileIndex: number,
ordinal: number,
slot: number | undefined,
+ kind: "image" | "video",
): Promise<{ mime: string; bytes: Buffer }>;
abstract analyze(
projectId: string,
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index af024196..f4f3c607 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -465,12 +465,15 @@ export function isHumanInput(input: readonly OmniMessage[]): boolean {
/**
* A queued message's original content, held while it waits in a queue so a recall (DELETE
* /steer/:id, DELETE /follow-ups/:id) can hand it back to the composer for editing (#287).
- * `text` and `images` are the same strings the queued input already references (no extra
- * copy); files stay on disk in the Session scratchpad and are read back only at recall.
+ * `text`, `images` and `videos` are the same strings the queued input already references (no
+ * extra copy); files stay on disk in the Session scratchpad and are read back only at recall.
+ * `videos` holds the inline ones only — a video the Session's model cannot take was turned
+ * into a file before it ever got here (see the task route).
*/
export interface RecallStore {
text: string;
images: string[];
+ videos: string[];
files: RecallableFile[];
}
@@ -620,13 +623,14 @@ function followUpInfo(f: QueuedFollowUp): PendingFollowUpInfo {
id: f.id,
text: f.recall.text,
images: f.recall.images.length,
+ videos: f.recall.videos.length,
files: f.recall.files.length,
};
}
/**
* The recall store of a queued input whose caller supplied none: everything recallable is
- * already in the input itself — the user's text and the inline image URLs, the only two
+ * already in the input itself — the user's text and the inline image / video URLs, the only
* shapes a task input is ever built from.
*
* `files` is empty because the path a written attachment landed on is known only to
@@ -641,17 +645,17 @@ export function recallStoreOf(input: OmniMessage[]): RecallStore {
.map((m) => m.payload.text)
.join("\n");
const images: string[] = [];
+ const videos: string[] = [];
for (const msg of input) {
- const payload = msg.payload as { type?: string; image_url?: unknown };
- if (
- msg.type === "model_msg" &&
- payload.type === "image_url" &&
- typeof payload.image_url === "string"
- ) {
+ const payload = msg.payload as { type?: string; image_url?: unknown; video_url?: unknown };
+ if (msg.type !== "model_msg") continue;
+ if (payload.type === "image_url" && typeof payload.image_url === "string") {
images.push(payload.image_url);
+ } else if (payload.type === "video_url" && typeof payload.video_url === "string") {
+ videos.push(payload.video_url);
}
}
- return { text, images, files: [] };
+ return { text, images, videos, files: [] };
}
/** If msg is a run_subagent tool call carrying a `prompt`, return its id and prompt (for use as the subagent's title); otherwise null. */
@@ -1565,6 +1569,7 @@ export class SessionManager {
id: randomUUID(),
text: recall.text,
images: recall.images.length,
+ videos: recall.videos.length,
files: recall.files.length,
},
input,
diff --git a/packages/server/src/services/attachment-limits.ts b/packages/server/src/services/attachment-limits.ts
index 4c5782eb..9a6220fd 100644
--- a/packages/server/src/services/attachment-limits.ts
+++ b/packages/server/src/services/attachment-limits.ts
@@ -87,6 +87,23 @@ export const MAX_ATTACHMENT_COUNT = 20;
*/
export const INLINE_IMAGE_MAX_MB = 20;
+/**
+ * Per-video ceiling for videos that ride the conversation inline, where the model takes video
+ * input (see ModelCatalogEntry.supportsVideo).
+ *
+ * Larger than the image ceiling because a video is, and because the vendor's own limit is: Ark
+ * takes a video under 50 MB inside a request body under 64 MB, and base64 inflates by 4/3, so
+ * 32 MB of video is ~43 MB on the wire — inside that body with room for the text around it.
+ * Above this number the model would refuse the request anyway; keeping the ceiling here means
+ * the refusal is Adelie's, with a message that names the limit, rather than the provider's.
+ *
+ * The same Session-must-stay-readable reasoning as images applies, one order of magnitude up: a
+ * video written into the Trace is read back whole on every history page. That is also why a
+ * conversation carries at most one video per request (the video budget in
+ * llm/generative-model.ts).
+ */
+export const INLINE_VIDEO_MAX_MB = 32;
+
/** Byte length of the base64 encoding of `bytes` bytes (4 characters per 3-byte group, padded). */
export function base64Length(bytes: number): number {
return Math.ceil(bytes / 3) * 4;
@@ -136,6 +153,9 @@ export function toAttachmentLimits(mb: AttachmentLimitsMb): AttachmentLimits {
/** The inline-image ceiling in bytes (a constant, but expressed through the same MB unit). */
export const INLINE_IMAGE_MAX_BYTES = INLINE_IMAGE_MAX_MB * MB;
+/** The inline-video ceiling in bytes (same unit, same reason). */
+export const INLINE_VIDEO_MAX_BYTES = INLINE_VIDEO_MAX_MB * MB;
+
/**
* The global request body cap implied by the attachment budget.
*
diff --git a/packages/server/src/services/context-breakdown.ts b/packages/server/src/services/context-breakdown.ts
index 4d999282..83cd0628 100644
--- a/packages/server/src/services/context-breakdown.ts
+++ b/packages/server/src/services/context-breakdown.ts
@@ -189,6 +189,7 @@ export function buildContextBreakdown(messages: OmniMessage[]): SessionContextPa
switch (p.type) {
case "text":
case "image_url":
+ case "video_url":
case "inline_data":
if (p.role === "assistant") out.assistantMessages += size;
else out.userMessages += size;
diff --git a/packages/server/src/services/message-window.ts b/packages/server/src/services/message-window.ts
index 0e876d60..68ee9c39 100644
--- a/packages/server/src/services/message-window.ts
+++ b/packages/server/src/services/message-window.ts
@@ -311,10 +311,11 @@ export async function scanMessages(
const ms = tsMs(msg.timestamp);
const p = msg.payload as Record<string, unknown> & { type?: string; role?: string };
- // Mirrors pushMessage's first step: anything that is not a complete user image
+ // Mirrors pushMessage's first step: anything that is not a complete user image or video
// closes the steering-images window (session_meta and events included).
- const isUserImage = msg.type === "model_msg" && p.type === "image_url";
- if (!isUserImage) state.steeringOpen = false;
+ const isUserMedia =
+ msg.type === "model_msg" && (p.type === "image_url" || p.type === "video_url");
+ if (!isUserMedia) state.steeringOpen = false;
if (msg.type === "model_msg") {
// Compaction-internal model messages: never rendered, never counted (stream-model
@@ -364,8 +365,8 @@ export async function scanMessages(
);
continue;
}
- if (p.type === "image_url") {
- // An image riding behind a steering chip folds into it: no item, no Task.
+ if (p.type === "image_url" || p.type === "video_url") {
+ // An image or video riding behind a steering chip folds into it: no item, no Task.
if (state.steeringOpen) {
touchTask(state, ms);
continue;
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index 42ffed93..c8681a14 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -1167,6 +1167,11 @@ export class ProjectConfigService implements ProjectConfigStore {
const fallback = modelEnvFallback({ provider, modelId, clientType, baseUrl: credBaseUrl });
const envKey = fallback?.envKey;
const vision = typeof m.vision === "boolean" ? m.vision : cat?.supportsVision;
+ // Video input: the annotation when one is stored, otherwise the catalog — read through
+ // the catalog exactly as core's `catalogSupportsVideo` does it, so the composer's
+ // decision (inline video, or a file the model opens by path) is the same one the
+ // server's own routes make for the same Session.
+ const video = m.video === true || cat?.supportsVideo === true ? true : undefined;
// Output cap: TOML annotation only (user-owned; the built-in catalog never presets it).
const maxTokens = optNum(m.max_tokens);
// Fast mode: TOML annotation only (user-owned); only `true` is reported — absent = off.
@@ -1212,6 +1217,7 @@ export class ProjectConfigService implements ProjectConfigStore {
: {}),
...(clientType ? { clientType } : {}),
...(vision !== undefined ? { vision } : {}),
+ ...(video !== undefined ? { video } : {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
...(fastMode !== undefined ? { fastMode } : {}),
...(envKey ? { envKey } : {}),
diff --git a/packages/server/src/services/trace-images.ts b/packages/server/src/services/trace-images.ts
deleted file mode 100644
index 1ebdace7..00000000
--- a/packages/server/src/services/trace-images.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * Images by reference on windowed history pages.
- *
- * A Trace stores images inline, as base64 `data:` URLs: the user's `image_url` records and
- * the `images` of a tool output (a screenshot is ~1.5 MB of text). A windowed
- * `GET /messages` page replaces each of them with the URL of the route that serves that
- * one image from the Trace record, so a page costs its text and the browser fetches each
- * picture as it draws it. The parameterless full read is left alone.
- *
- * URL: `/api/sessions/<sessionId>/trace-image?file=<fileIndex>&ordinal=<ordinal>[&i=<k>]`,
- * where (file, ordinal) is the record's `tracePosition`; without `i` it names the record's
- * `image_url`, with `i` the tool output's `images[k]`. A Trace record never changes, so the
- * route answers it as immutable.
- *
- * Only raster types a browser renders inertly are referenced (the scratchpad route's
- * allowlist): the route serves bytes on the app's own origin, and an `image/svg+xml` or
- * `text/html` data URL served there would be a document, not a picture. Any other data URL
- * stays inline, where it is as harmless as it always was.
- */
-import type { ImageUrlPayload, OmniMessage, ToolCallOutputPayload } from "@adelie/core";
-import type { HistoryMessage, TracePosition } from "../api/types.js";
-
-/** Image types the trace-image route serves (core's own supported set). */
-const REFERENCED_IMAGE_MIMES: ReadonlySet<string> = new Set([
- "image/png",
- "image/jpeg",
- "image/gif",
- "image/webp",
-]);
-
-/** A base64 image data URL the route can serve: its type, and where its payload starts. */
-function referableImage(url: string): { mime: string; dataStart: number } | null {
- if (!url.startsWith("data:")) return null;
- const comma = url.indexOf(",");
- if (comma < 0 || comma === url.length - 1) return null;
- const header = url.slice("data:".length, comma).toLowerCase();
- if (!header.endsWith(";base64")) return null;
- const mime = header.slice(0, header.indexOf(";")).trim();
- return REFERENCED_IMAGE_MIMES.has(mime) ? { mime, dataStart: comma + 1 } : null;
-}
-
-/** The route URL of one image slot of the record at `at` (`slot` = index into a tool output's `images`). */
-export function traceImageUrl(sessionId: string, at: TracePosition, slot?: number): string {
- const query = `file=${at.fileIndex}&ordinal=${at.ordinal}${slot !== undefined ? `&i=${slot}` : ""}`;
- return `/api/sessions/${encodeURIComponent(sessionId)}/trace-image?${query}`;
-}
-
-/**
- * The message as a windowed page serves it: each referable image of a main-session record
- * (one that carries its `tracePosition`) replaced by its route URL. Expanded subagent
- * messages carry no position and stay inline. The input is never mutated; a message with
- * nothing to replace is returned as is.
- */
-export function withImagesByReference(sessionId: string, msg: HistoryMessage): HistoryMessage {
- const at = msg.tracePosition;
- if (at === undefined || msg.type !== "model_msg") return msg;
- const kind = (msg.payload as { type?: string }).type;
- if (kind === "image_url") {
- const payload = msg.payload as ImageUrlPayload;
- if (typeof payload.image_url !== "string" || referableImage(payload.image_url) === null) {
- return msg;
- }
- return { ...msg, payload: { ...payload, image_url: traceImageUrl(sessionId, at) } };
- }
- if (kind === "tool_call_output") {
- const payload = msg.payload as ToolCallOutputPayload;
- if (!Array.isArray(payload.images)) return msg;
- let replaced = false;
- const images = payload.images.map((image, k) => {
- if (typeof image !== "string" || referableImage(image) === null) return image;
- replaced = true;
- return traceImageUrl(sessionId, at, k);
- });
- if (replaced) return { ...msg, payload: { ...payload, images } };
- }
- return msg;
-}
-
-/**
- * The decoded image in one slot of a Trace record: the user image of an `image_url` record
- * (`slot` undefined) or a tool output's `images[slot]`. Null when that slot holds no image
- * the route serves — the same test the page applied before it handed out the URL.
- */
-export function traceRecordImage(
- record: OmniMessage,
- slot: number | undefined,
-): { mime: string; bytes: Buffer } | null {
- if (record.type !== "model_msg") return null;
- const p = record.payload as { type?: string; image_url?: unknown; images?: unknown };
- let url: unknown;
- if (slot === undefined) {
- url = p.type === "image_url" ? p.image_url : undefined;
- } else if (p.type === "tool_call_output" && Array.isArray(p.images)) {
- url = (p.images as unknown[])[slot];
- }
- if (typeof url !== "string") return null;
- const image = referableImage(url);
- if (image === null) return null;
- return { mime: image.mime, bytes: Buffer.from(url.slice(image.dataStart), "base64") };
-}
diff --git a/packages/server/src/services/trace-media.ts b/packages/server/src/services/trace-media.ts
new file mode 100644
index 00000000..47896274
--- /dev/null
+++ b/packages/server/src/services/trace-media.ts
@@ -0,0 +1,159 @@
+/**
+ * Images and videos by reference on windowed history pages.
+ *
+ * A Trace stores media inline, as base64 `data:` URLs: the user's `image_url` and `video_url`
+ * records, and the `images` of a tool output (a screenshot is ~1.5 MB of text). A windowed
+ * `GET /messages` page replaces each of them with the URL of the route that serves that one
+ * item back out of the Trace record, so a page costs only its text and the browser fetches
+ * each picture — or video — as it draws it. The parameterless full read is left alone.
+ *
+ * URLs: `/api/sessions/<sessionId>/trace-image?file=<fileIndex>&ordinal=<ordinal>[&i=<k>]` and
+ * `/api/sessions/<sessionId>/trace-video?file=<fileIndex>&ordinal=<ordinal>`, where (file,
+ * ordinal) is the record's `tracePosition`; without `i` the image route names the record's
+ * `image_url`, with `i` the tool output's `images[k]`. A Trace record never changes, so the
+ * routes answer them as immutable.
+ *
+ * A video is referenced for a blunter version of the image's reason: it is tens of megabytes
+ * of base64, so the one page that carried it inline would have to be read back whole — into a
+ * single JS string — before anything could be drawn at all.
+ *
+ * Only raster types a browser renders inertly are referenced (the scratchpad route's
+ * allowlist): the route serves bytes on the app's own origin, and an `image/svg+xml` or
+ * `text/html` data URL served there would be a document, not a picture. Any other data URL
+ * stays inline, where it is as harmless as it always was. A video whose type is outside the
+ * set the task route accepts stays inline for the same reason.
+ */
+import type {
+ ImageUrlPayload,
+ OmniMessage,
+ ToolCallOutputPayload,
+ VideoUrlPayload,
+} from "@adelie/core";
+import type { HistoryMessage, TracePosition } from "../api/types.js";
+
+/** Image types the trace-image route serves (core's own supported set). */
+const REFERENCED_IMAGE_MIMES: ReadonlySet<string> = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+]);
+
+/**
+ * Video types the trace-video route serves — the same ones the task route names a video file
+ * by (its VIDEO_MIME_EXTENSIONS) and the same ones providers take. Kept apart from that table
+ * because the two answer different questions (can this be served here / what shall the file be
+ * called) and a type may be nameable without being servable; they are the provider's set
+ * either way, so they move together.
+ */
+const REFERENCED_VIDEO_MIMES: ReadonlySet<string> = new Set([
+ "video/mp4",
+ "video/quicktime",
+ "video/webm",
+ "video/x-matroska",
+ "video/x-msvideo",
+]);
+
+/** A base64 data URL the route can serve: its type, and where its payload starts. */
+function referableDataUrl(
+ url: string,
+ mimes: ReadonlySet<string>,
+): { mime: string; dataStart: number } | null {
+ if (!url.startsWith("data:")) return null;
+ const comma = url.indexOf(",");
+ if (comma < 0 || comma === url.length - 1) return null;
+ const header = url.slice("data:".length, comma).toLowerCase();
+ if (!header.endsWith(";base64")) return null;
+ const mime = header.slice(0, header.indexOf(";")).trim();
+ return mimes.has(mime) ? { mime, dataStart: comma + 1 } : null;
+}
+
+/** The route URL of one image slot of the record at `at` (`slot` = index into a tool output's `images`). */
+export function traceImageUrl(sessionId: string, at: TracePosition, slot?: number): string {
+ const query = `file=${at.fileIndex}&ordinal=${at.ordinal}${slot !== undefined ? `&i=${slot}` : ""}`;
+ return `/api/sessions/${encodeURIComponent(sessionId)}/trace-image?${query}`;
+}
+
+/** The route URL of the record at `at`'s own video (the `video_url` of a user message). */
+export function traceVideoUrl(sessionId: string, at: TracePosition): string {
+ const query = `file=${at.fileIndex}&ordinal=${at.ordinal}`;
+ return `/api/sessions/${encodeURIComponent(sessionId)}/trace-video?${query}`;
+}
+
+/**
+ * The message as a windowed page serves it: each referable image or video of a main-session
+ * record (one that carries its `tracePosition`) replaced by its route URL. Expanded subagent
+ * messages carry no position and stay inline. The input is never mutated; a message with
+ * nothing to replace is returned as is.
+ */
+export function withMediaByReference(sessionId: string, msg: HistoryMessage): HistoryMessage {
+ const at = msg.tracePosition;
+ if (at === undefined || msg.type !== "model_msg") return msg;
+ const kind = (msg.payload as { type?: string }).type;
+ if (kind === "image_url") {
+ const payload = msg.payload as ImageUrlPayload;
+ if (
+ typeof payload.image_url !== "string" ||
+ referableDataUrl(payload.image_url, REFERENCED_IMAGE_MIMES) === null
+ ) {
+ return msg;
+ }
+ return { ...msg, payload: { ...payload, image_url: traceImageUrl(sessionId, at) } };
+ }
+ if (kind === "video_url") {
+ const payload = msg.payload as VideoUrlPayload;
+ if (
+ typeof payload.video_url !== "string" ||
+ referableDataUrl(payload.video_url, REFERENCED_VIDEO_MIMES) === null
+ ) {
+ return msg;
+ }
+ return { ...msg, payload: { ...payload, video_url: traceVideoUrl(sessionId, at) } };
+ }
+ if (kind === "tool_call_output") {
+ const payload = msg.payload as ToolCallOutputPayload;
+ if (!Array.isArray(payload.images)) return msg;
+ let replaced = false;
+ const images = payload.images.map((image, k) => {
+ if (typeof image !== "string" || referableDataUrl(image, REFERENCED_IMAGE_MIMES) === null) {
+ return image;
+ }
+ replaced = true;
+ return traceImageUrl(sessionId, at, k);
+ });
+ if (replaced) return { ...msg, payload: { ...payload, images } };
+ }
+ return msg;
+}
+
+/**
+ * The decoded media in one slot of a Trace record: the user image (`kind` "image", `slot`
+ * undefined) or video (`kind` "video") of an `image_url` / `video_url` record, or a tool
+ * output's `images[slot]`. Null when that slot holds nothing of that kind the route serves —
+ * the same test the page applied before it handed out the URL.
+ */
+export function traceRecordMedia(
+ record: OmniMessage,
+ slot: number | undefined,
+ kind: "image" | "video",
+): { mime: string; bytes: Buffer } | null {
+ if (record.type !== "model_msg") return null;
+ const p = record.payload as {
+ type?: string;
+ image_url?: unknown;
+ video_url?: unknown;
+ images?: unknown;
+ };
+ const mimes = kind === "video" ? REFERENCED_VIDEO_MIMES : REFERENCED_IMAGE_MIMES;
+ let url: unknown;
+ if (slot === undefined) {
+ const wanted = kind === "video" ? "video_url" : "image_url";
+ url = p.type === wanted ? (kind === "video" ? p.video_url : p.image_url) : undefined;
+ } else if (p.type === "tool_call_output" && Array.isArray(p.images)) {
+ url = (p.images as unknown[])[slot];
+ }
+ if (typeof url !== "string") return null;
+ const media = referableDataUrl(url, mimes);
+ if (media === null) return null;
+ return { mime: media.mime, bytes: Buffer.from(url.slice(media.dataStart), "base64") };
+}
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index 3cea493a..e7a7e7fb 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -80,7 +80,7 @@ import { sessionIdCreatedAt } from "./session-service.js";
import { listCategory, readRecordedSource } from "../runtime/session-sources.js";
import { TraceIndexService, traceFilePath } from "./trace-index.js";
import { TraceLineIndex } from "./trace-line-index.js";
-import { traceRecordImage, withImagesByReference } from "./trace-images.js";
+import { traceRecordMedia, withMediaByReference } from "./trace-media.js";
import { Component, Use } from "@adelie/core/kernel";
import type { Paths } from "../hmr/capabilities.js";
import type { TraceIndex, TraceIndexStore, Traces } from "../mechanisms/traces.js";
@@ -779,7 +779,7 @@ export class TraceService implements Traces {
}
// Byte budget: newest first, a unit joins while the page stays within it; the first one
- // always joins. Sized as the route serves it, images by reference (trace-images.ts).
+ // always joins. Sized as the route serves it, media by reference (trace-media.ts).
let chosen = starts.length - 1;
let pageBytes = 0;
for (let k = starts.length - 1; k >= 0; k--) {
@@ -787,7 +787,7 @@ export class TraceService implements Traces {
let unitBytes = 0;
for (let i = starts[k]!.at; i < unitEnd; i++) {
unitBytes += Buffer.byteLength(
- JSON.stringify(withImagesByReference(sessionId, spanRaw[i]!)),
+ JSON.stringify(withMediaByReference(sessionId, spanRaw[i]!)),
"utf8",
);
}
@@ -1069,28 +1069,29 @@ export class TraceService implements Traces {
}
/**
- * One image of one Trace record, decoded: the `image_url` of the record at
- * (`fileIndex`, `ordinal`), or its tool output's `images[slot]`. This is what a windowed
- * history page's image URL names (trace-images.ts). 404 `trace_image_not_found` when the
- * file, the record or the slot holds no image the route serves.
+ * One image or video of one Trace record, decoded: the `image_url` / `video_url` of the
+ * record at (`fileIndex`, `ordinal`), or its tool output's `images[slot]`. This is what a
+ * windowed history page's media URL names (trace-media.ts). 404, with a code per kind, when
+ * the file, the record or the slot holds no media the route serves.
*/
- async readTraceImage(
+ async readTraceMedia(
projectId: string,
agentId: string,
sessionId: string,
fileIndex: number,
ordinal: number,
slot: number | undefined,
+ kind: "image" | "video",
): Promise<{ mime: string; bytes: Buffer }> {
const notFound = () =>
- new HttpError(404, "trace_image_not_found", "This Trace record holds no such image.");
+ new HttpError(404, `trace_${kind}_not_found`, `This Trace record holds no such ${kind}.`);
const files = await this.locateAll(projectId, agentId, sessionId);
const file = files.find((f) => f.index === fileIndex);
if (file === undefined) throw notFound();
const { events } = await this.lineIndex.readRange(file.path, ordinal, 1);
- const image = events[0] !== undefined ? traceRecordImage(events[0], slot) : null;
- if (image === null) throw notFound();
- return image;
+ const media = events[0] !== undefined ? traceRecordMedia(events[0], slot, kind) : null;
+ if (media === null) throw notFound();
+ return media;
}
/**
diff --git a/packages/server/test/followup.test.ts b/packages/server/test/followup.test.ts
index ce66e5d6..a4935961 100644
--- a/packages/server/test/followup.test.ts
+++ b/packages/server/test/followup.test.ts
@@ -109,14 +109,14 @@ describe("follow-up queue route", () => {
});
const pending = t.deps.manager.pendingFollowUpsOf(SID);
expect(pending).toEqual([
- { id: expect.any(String), text: "follow-up 1", images: 1, files: 0 },
- { id: expect.any(String), text: "follow-up 2", images: 0, files: 0 },
+ { id: expect.any(String), text: "follow-up 1", images: 1, videos: 0, files: 0 },
+ { id: expect.any(String), text: "follow-up 2", images: 0, videos: 0, files: 0 },
]);
// The recall returns the original content.
const res = await api.delete(`/api/sessions/${SID}/follow-ups/${pending[0]!.id}`);
expect(res.status).toBe(200);
- expect(await res.json()).toEqual({ text: "follow-up 1", images: [png], files: [] });
+ expect(await res.json()).toEqual({ text: "follow-up 1", images: [png], videos: [], files: [] });
expect(t.deps.manager.pendingFollowUpCount(SID)).toBe(1);
// Recalled means never started: only the remaining follow-up auto-starts.
@@ -278,12 +278,17 @@ describe("follow-up queue route", () => {
expect(queued.queued).toBe(true);
const pending = t.deps.manager.pendingFollowUpsOf(SID);
expect(pending).toEqual([
- { id: expect.any(String), text: "from the chat channel", images: 0, files: 0 },
+ { id: expect.any(String), text: "from the chat channel", images: 0, videos: 0, files: 0 },
]);
const res = await api.delete(`/api/sessions/${SID}/follow-ups/${pending[0]!.id}`);
expect(res.status).toBe(200);
- expect(await res.json()).toEqual({ text: "from the chat channel", images: [], files: [] });
+ expect(await res.json()).toEqual({
+ text: "from the chat channel",
+ images: [],
+ videos: [],
+ files: [],
+ });
expect(t.deps.manager.pendingFollowUpCount(SID)).toBe(0);
// Recalled means never started: run 1 stays the only run.
diff --git a/packages/server/test/messages-page.test.ts b/packages/server/test/messages-page.test.ts
index 76c6a168..10595748 100644
--- a/packages/server/test/messages-page.test.ts
+++ b/packages/server/test/messages-page.test.ts
@@ -37,6 +37,7 @@ import {
toolCall,
toolCallOutput,
userText,
+ videoUrlMessage,
} from "@adelie/core";
import { buildBackgroundTaskDoneMessage, buildHandoffMessage } from "@adelie/core/markers";
import type { OmniMessage, SessionMetaPayload, TokenCounts } from "@adelie/core";
@@ -432,13 +433,14 @@ describe("messages windowed reads", () => {
expect(tail.prior.turns).toBe(1);
});
- it("a text+images send is one unit and one outline turn; banner and goal-round prompts cut but never count", async () => {
+ it("a text+image+video send is one unit and one outline turn; banner and goal-round prompts cut but never count", async () => {
await writeTraceFile(root, P, A, "2026-07-20", S, 1, [
sessionMeta(metaPayload()),
- // Send 1: text + two images (one entry, one unit).
+ // Send 1: text + two images + a video (one entry, one unit).
at("2026-07-20T10:00:00.000Z", userText("look")),
at("2026-07-20T10:00:00.100Z", imageUrlMessage("data:image/png;base64,AAAA")),
at("2026-07-20T10:00:00.200Z", imageUrlMessage("data:image/png;base64,BBBB")),
+ at("2026-07-20T10:00:00.300Z", videoUrlMessage("data:video/mp4;base64,AAAA")),
at("2026-07-20T10:00:01.000Z", requestBegin()),
at("2026-07-20T10:00:02.000Z", assistantText("a1")),
at("2026-07-20T10:00:03.000Z", requestEnd("completed")),
@@ -490,11 +492,20 @@ describe("messages windowed reads", () => {
});
expect(firstWin.prior.turns).toBe(0);
expect(firstWin.before).toBeUndefined();
- // The text and its two images stayed one unit.
+ // The text, its two images and its video stayed one unit — a video is part of the send
+ // it was typed with, exactly as an image is.
expect(userTexts(firstWin.messages)).toEqual(["look"]);
expect(
firstWin.messages.filter((m) => (m.payload as { type?: string }).type === "image_url"),
).toHaveLength(2);
+ // And the video rides in that same window unit — a send is cut whole, video included.
+ // (The windowed *page* carries it by reference; that is the route's doing, and is pinned
+ // in trace-media.test.ts.)
+ const video = firstWin.messages.find(
+ (m) => (m.payload as { type?: string }).type === "video_url",
+ );
+ expect(video).toBeDefined();
+ expect(firstWin.messages.indexOf(video!)).toBe(4);
});
it("prior stats: finished-Task elapsed, session/context token readings", async () => {
diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.ts
index ea07190b..18929f9a 100644
--- a/packages/server/test/messaging.test.ts
+++ b/packages/server/test/messaging.test.ts
@@ -3557,6 +3557,7 @@ describe("a message carrying several files", () => {
expect(await res.json()).toEqual({
text: "look at this",
images: [],
+ videos: [],
// No media type rides an inbound file, so the recall re-encodes it as the generic one.
files: [{ fileName: "notes.txt", dataUrl: "data:application/octet-stream;base64,aGk=" }],
});
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index b7d5cce5..52771f6b 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -666,7 +666,7 @@ describe("session-manager", () => {
const manager = makeManager(loaderOf(fake));
const steerErr = (text: string): unknown => {
try {
- manager.steer("session-1", [userText(text)], { text, images: [], files: [] });
+ manager.steer("session-1", [userText(text)], { text, images: [], videos: [], files: [] });
return null;
} catch (e) {
return e;
@@ -718,18 +718,24 @@ describe("session-manager", () => {
await waitFor(() => manager.pendingApprovalCount("session-1") === 1);
// Two queued steering messages: the mirror keeps both, in queue order.
- manager.steer("session-1", [userText("a")], { text: "focus on tests", images: [], files: [] });
+ manager.steer("session-1", [userText("a")], {
+ text: "focus on tests",
+ images: [],
+ videos: [],
+ files: [],
+ });
manager.steer("session-1", [userText("b")], {
text: "later",
images: ["data:image/png;base64,aa"],
+ videos: [],
files: [
{ fileName: "a.txt", path: "/tmp/a.txt", mime: "text/plain" },
{ fileName: "b.txt", path: "/tmp/b.txt", mime: "text/plain" },
],
});
expect(manager.pendingSteeringOf("session-1")).toEqual([
- { id: expect.any(String), text: "focus on tests", images: 0, files: 0 },
- { id: expect.any(String), text: "later", images: 1, files: 2 },
+ { id: expect.any(String), text: "focus on tests", images: 0, videos: 0, files: 0 },
+ { id: expect.any(String), text: "later", images: 1, videos: 0, files: 2 },
]);
// First delivery observed on the stream: the mirror shifts while the run is still going.
@@ -737,7 +743,7 @@ describe("session-manager", () => {
await waitFor(() => manager.pendingSteeringOf("session-1").length === 1);
expect(manager.statusOf("session-1")).toBe("running");
expect(manager.pendingSteeringOf("session-1")).toEqual([
- { id: expect.any(String), text: "later", images: 1, files: 2 },
+ { id: expect.any(String), text: "later", images: 1, videos: 0, files: 2 },
]);
// Run end: core discards undelivered steering, and the mirror goes with it.
diff --git a/packages/server/test/steer.test.ts b/packages/server/test/steer.test.ts
index dd9161e5..5e4ac074 100644
--- a/packages/server/test/steer.test.ts
+++ b/packages/server/test/steer.test.ts
@@ -242,7 +242,7 @@ describe("steer route", () => {
await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);
await api.post(`/api/sessions/${SID}/steer`, { text: "hold on" });
expect(t.deps.manager.pendingSteeringOf(SID)).toEqual([
- { id: expect.any(String), text: "hold on", images: 0, files: 0 },
+ { id: expect.any(String), text: "hold on", images: 0, videos: 0, files: 0 },
]);
// The first SSE frames are the initial task_state snapshot: it must carry the mirror.
@@ -277,7 +277,13 @@ describe("steer route", () => {
expect(posted.status).toBe(202);
expect(steered).toHaveLength(1);
const [info] = t.deps.manager.pendingSteeringOf(SID);
- expect(info).toEqual({ id: expect.any(String), text: "keep me", images: 1, files: 1 });
+ expect(info).toEqual({
+ id: expect.any(String),
+ text: "keep me",
+ images: 1,
+ videos: 0,
+ files: 1,
+ });
// The recall hands the whole message back in the composer's own shape — the file read
// back from the scratchpad as the very data URL it was submitted as.
@@ -286,6 +292,7 @@ describe("steer route", () => {
expect(await res.json()).toEqual({
text: "keep me",
images: [png],
+ videos: [],
files: [{ fileName: "notes.txt", dataUrl: data }],
});
@@ -322,6 +329,7 @@ describe("steer route", () => {
id: expect.any(String),
text: "wait, do it differently",
images: 0,
+ videos: 0,
files: 1,
});
@@ -340,6 +348,7 @@ describe("steer route", () => {
expect(await res.json()).toEqual({
text: "wait, do it differently",
images: [],
+ videos: [],
files: [{ fileName: "notes.txt", dataUrl: data }],
});
expect(t.deps.manager.returnedSteeringOf(SID)).toEqual([]);
diff --git a/packages/server/test/trace-image.test.ts b/packages/server/test/trace-media.test.ts
similarity index 62%
rename from packages/server/test/trace-image.test.ts
rename to packages/server/test/trace-media.test.ts
index 3818b58a..26ddec96 100644
--- a/packages/server/test/trace-image.test.ts
+++ b/packages/server/test/trace-media.test.ts
@@ -1,16 +1,19 @@
/**
- * Images by reference on windowed history pages, and the route that serves them,
- * `GET /api/sessions/:sessionId/trace-image?file=&ordinal=[&i=]`.
+ * Media by reference on windowed history pages, and the routes that serve it —
+ * `GET /api/sessions/:sessionId/trace-image?file=&ordinal=[&i=]` and
+ * `GET /api/sessions/:sessionId/trace-video?file=&ordinal=`.
*
- * - Given a Trace holding a user image and a tool output with two screenshots, a windowed
- * page carries route URLs in their place, and each URL answers exactly that image's bytes
- * with its type, an immutable private cache and nosniff.
+ * - Given a Trace holding a user image, a tool output with two screenshots and a user video, a
+ * windowed page carries route URLs in their place, and each URL answers exactly that item's
+ * bytes with its type, an immutable private cache and nosniff.
* - The parameterless full read still carries every data URL.
- * - An image type the route does not serve (SVG) stays inline on the windowed page.
+ * - A type the route does not serve (an SVG image, an Ogg video) stays inline on the windowed
+ * page, and asking the route for it is a 404.
* - A caller without access to the Session gets 404 session_not_found and an anonymous one
* 401; neither gets the bytes.
* - A record without an image, a slot past the end, an ordinal past the end and an unknown
- * file answer 404 trace_image_not_found; missing or malformed parameters answer 400.
+ * file answer 404 trace_image_not_found (trace_video_not_found on the video route); missing
+ * or malformed parameters answer 400.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
@@ -22,6 +25,7 @@ import {
toolCall,
toolCallOutput,
userText,
+ videoUrlMessage,
} from "@adelie/core";
import type { OmniMessage } from "@adelie/core";
import type { HistoryMessage, MessagesResponse } from "../src/api/types.js";
@@ -37,12 +41,21 @@ const PNG = Buffer.from(
);
const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46]);
const SVG = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>');
+/** The first bytes of an MP4 (`ftyp`) — enough to be served back and compared byte for byte. */
+const MP4 = Buffer.from([0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x6d, 0x70, 0x34, 0x32]);
+const OGG = Buffer.from([0x4f, 0x67, 0x67, 0x53, 0x00, 0x02]);
const dataUrl = (mime: string, bytes: Buffer) => `data:${mime};base64,${bytes.toString("base64")}`;
-type Payload = { type?: string; text?: string; image_url?: string; images?: string[] };
+type Payload = {
+ type?: string;
+ text?: string;
+ image_url?: string;
+ video_url?: string;
+ images?: string[];
+};
const payloadOf = (m: OmniMessage) => m.payload as Payload;
-describe("images by reference", () => {
+describe("media by reference", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
let outsider: ReturnType<typeof apiClient>;
@@ -77,6 +90,11 @@ describe("images by reference", () => {
}), // 6
assistantText("done"), // 7
requestEnd("completed"), // 8
+ // The next turn's user input, its request not begun yet: a video the provider takes,
+ // and one whose type the route does not serve (so it stays inline).
+ userText("and this clip"), // 9
+ videoUrlMessage(dataUrl("video/mp4", MP4)), // 10
+ videoUrlMessage(dataUrl("video/ogg", OGG)), // 11
]);
});
afterAll(async () => {
@@ -126,6 +144,61 @@ describe("images by reference", () => {
]);
});
+ it("a user video is served by reference too, and answers its own bytes", async () => {
+ const messages = await tailPage();
+ const video = payloadOf(messages[10]!);
+ expect(video.video_url).toBe(`/api/sessions/${SID}/trace-video?file=1&ordinal=10`);
+
+ const res = await api.get(video.video_url!);
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toBe("video/mp4");
+ expect(res.headers.get("cache-control")).toBe("private, max-age=31536000, immutable");
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff");
+ expect(Buffer.from(await res.arrayBuffer()).equals(MP4)).toBe(true);
+ });
+
+ it("the full read keeps a video inline, and an unserved video type stays inline on a page", async () => {
+ const full = await api.get(`/api/sessions/${SID}/messages`);
+ const { messages } = (await full.json()) as MessagesResponse;
+ expect(payloadOf(messages[10]!).video_url).toBe(dataUrl("video/mp4", MP4));
+
+ const page = await tailPage();
+ expect(payloadOf(page[11]!).video_url).toBe(dataUrl("video/ogg", OGG));
+ const res = await api.get(`/api/sessions/${SID}/trace-video?file=1&ordinal=11`);
+ expect(res.status).toBe(404);
+ expect(await errorCode(res)).toBe("trace_video_not_found");
+ });
+
+ it("a caller without access, or without a sign-in, gets no video bytes either", async () => {
+ const url = `/api/sessions/${SID}/trace-video?file=1&ordinal=10`;
+ const denied = await outsider.get(url);
+ expect(denied.status).toBe(404);
+ expect(await errorCode(denied)).toBe("session_not_found");
+ const anonymous = await t.app.request(url);
+ expect(anonymous.status).toBe(401);
+ });
+
+ it.each([
+ ["a record without a video", "file=1&ordinal=1"],
+ ["an image asked for as a video", "file=1&ordinal=2"],
+ ["an ordinal past the end", "file=1&ordinal=99"],
+ ["an unknown file", "file=2&ordinal=10"],
+ ])("%s answers 404 trace_video_not_found", async (_case, query) => {
+ const res = await api.get(`/api/sessions/${SID}/trace-video?${query}`);
+ expect(res.status).toBe(404);
+ expect(await errorCode(res)).toBe("trace_video_not_found");
+ });
+
+ it.each([
+ ["no file", "ordinal=10"],
+ ["no ordinal", "file=1"],
+ ["file 0", "file=0&ordinal=10"],
+ ["a non-numeric ordinal", "file=1&ordinal=x"],
+ ])("the video route: %s answers 400", async (_case, query) => {
+ const res = await api.get(`/api/sessions/${SID}/trace-video?${query}`);
+ expect(res.status).toBe(400);
+ });
+
it("an image type the route does not serve stays inline, and its slot is not served", async () => {
const messages = await tailPage();
expect(payloadOf(messages[3]!).image_url).toBe(dataUrl("image/svg+xml", SVG));
diff --git a/packages/server/test/video-input.test.ts b/packages/server/test/video-input.test.ts
new file mode 100644
index 00000000..fe1ac3d7
--- /dev/null
+++ b/packages/server/test/video-input.test.ts
@@ -0,0 +1,232 @@
+/**
+ * Video input on the task and steer routes: `{type:"video_url"}` parts, and a steer's
+ * `videos` field.
+ *
+ * - On a Session whose model takes video input (the Volcengine Ark Seed family — core's
+ * `catalogSupportsVideo`), the clip rides inline as a user video message, which is the shape
+ * the provider's request is assembled from, and nothing is written to disk.
+ * - On any other model it becomes an ordinary file attachment: the bytes land in the scratchpad
+ * and the Prompt gains an `[attached file: <path>]` line, so one composer draft is sendable
+ * to either kind of model instead of being refused for the model's choice.
+ * - A part declared as a video has to carry a video data URL, and is capped at 32MB
+ * (413 `video_too_large`) — a document sent as a video is a 400 that names the field rather
+ * than a request the provider refuses three layers down. An http(s) video URL on a model that
+ * takes no video is refused too: there are no bytes to write.
+ * - The steer route takes an inline video only where the model takes it (no model picker
+ * mid-run), and a recall hands it back as it was submitted.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import {
+ approvalDecision,
+ assistantText,
+ modelVisiblePath,
+ scratchpadDir,
+ toolCall,
+ userText,
+} from "@adelie/core";
+import type { ApproveFn, OmniMessage, VideoUrlPayload } from "@adelie/core";
+import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { INLINE_VIDEO_MAX_MB } from "../src/services/attachment-limits.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const PROJECT = "videer-default_project";
+/** A model the catalog marks as taking video (ModelCatalogEntry.supportsVideo). */
+const VIDEO_MODEL = { provider: "volcengine", modelId: "doubao-seed-2-1-pro-260915" };
+
+/** The first bytes of an MP4 (`ftyp`), enough to compare byte for byte. */
+const MP4 = Buffer.from([0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x6d, 0x70, 0x34, 0x32]);
+const CLIP = `data:video/mp4;base64,${MP4.toString("base64")}`;
+
+const dataUrl = (content: string, mime = "application/octet-stream") =>
+ `data:${mime};base64,${Buffer.from(content).toString("base64")}`;
+
+/** Fake Session that records each run's input and finishes immediately (no LLM, no approvals). */
+function recordingFakeSession(sessionId: string, runs: OmniMessage[][]): RuntimeSession {
+ return fakeSession(sessionId, {
+ async *run(input: OmniMessage[]) {
+ runs.push(input);
+ yield assistantText("done");
+ },
+ });
+}
+
+/** Fake Session that parks on one approval (keeps the Task running) and records steer calls. */
+function steeringFakeSession(sessionId: string, steered: OmniMessage[][]): RuntimeSession {
+ return fakeSession(sessionId, {
+ steer: (input: OmniMessage[]) => {
+ steered.push(input);
+ return true;
+ },
+ // Same contract as core: withdraw by input-list identity, false once "delivered".
+ unsteer: (input: OmniMessage[]) => {
+ const i = steered.indexOf(input);
+ if (i < 0) return false;
+ steered.splice(i, 1);
+ return true;
+ },
+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-video" });
+ yield tc;
+ yield approvalDecision(await opts.approve(tc), "tc-video");
+ yield assistantText("done");
+ },
+ });
+}
+
+/** The video message of a recorded input, or undefined. */
+const videoOf = (input: OmniMessage[]): VideoUrlPayload | undefined =>
+ input.find((m) => (m.payload as { type?: string }).type === "video_url")?.payload as
+ VideoUrlPayload | undefined;
+
+/** All text of a recorded input, joined the way the model would read it. */
+const promptText = (input: OmniMessage[]): string =>
+ input
+ .map((m) => (m.payload as { text?: string }).text ?? "")
+ .filter(Boolean)
+ .join("\n");
+
+const errorCode = async (res: Response) =>
+ ((await res.json()) as { error: { code: string } }).error.code;
+
+describe("video input", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let SID: string;
+ let runs: OmniMessage[][];
+ let dir: string;
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ api = apiClient(t.app, (await provisionUser(t.app, "videer")).cookie);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ runs = [];
+ dir = path.join(scratchpadDir(t.root, PROJECT, "default_agent"), SID);
+ });
+
+ it("a video rides inline on a model that takes one, and writes nothing to disk", async () => {
+ adoptSession(t.deps, recordingFakeSession(SID, runs), { projectId: PROJECT, ...VIDEO_MODEL });
+ const res = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [
+ { type: "text", text: "what happens in this clip?" },
+ { type: "video_url", videoUrl: CLIP, fileName: "clip.mp4" },
+ ],
+ });
+ expect(res.status).toBe(202);
+ await waitFor(() => runs.length === 1);
+
+ expect(videoOf(runs[0]!)?.video_url).toBe(CLIP);
+ // Inline means inline: no attachment line, no scratchpad copy — the clip is the message,
+ // not a file the model has to open.
+ expect(promptText(runs[0]!)).toBe("what happens in this clip?");
+ expect(await fs.readdir(dir).catch(() => [])).toEqual([]);
+ });
+
+ it("a video on a model without video input lands in the scratchpad as a file attachment", async () => {
+ adoptSession(t.deps, recordingFakeSession(SID, runs), { projectId: PROJECT });
+ const res = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [
+ { type: "text", text: "what happens in this clip?" },
+ { type: "video_url", videoUrl: CLIP, fileName: "clip.mp4" },
+ ],
+ });
+ expect(res.status).toBe(202);
+ await waitFor(() => runs.length === 1);
+
+ expect(videoOf(runs[0]!)).toBeUndefined();
+ const filePath = /\[attached file: (.+)\]/.exec(promptText(runs[0]!))![1]!;
+ expect(filePath).toBe(modelVisiblePath(path.join(dir, "clip.mp4")));
+ expect(Buffer.from(await fs.readFile(filePath)).equals(MP4)).toBe(true);
+ });
+
+ it("names a nameless video after its own type, and refuses a non-video data URL", async () => {
+ adoptSession(t.deps, recordingFakeSession(SID, runs), { projectId: PROJECT });
+ const ok = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [{ type: "video_url", videoUrl: CLIP }],
+ });
+ expect(ok.status).toBe(202);
+ await waitFor(() => runs.length === 1);
+ expect(path.basename(/\[attached file: (.+)\]/.exec(promptText(runs[0]!))![1]!)).toBe(
+ "video.mp4",
+ );
+
+ const pdf = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [{ type: "video_url", videoUrl: dataUrl("PDF-BYTES", "application/pdf") }],
+ });
+ expect(pdf.status).toBe(400);
+ // The refusal names the offending field, so an API caller knows which part to fix.
+ expect(await pdf.text()).toContain("input[0].videoUrl");
+ });
+
+ it("refuses an http(s) video on a model that takes none (nothing to write to disk)", async () => {
+ adoptSession(t.deps, recordingFakeSession(SID, runs), { projectId: PROJECT });
+ const res = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [{ type: "video_url", videoUrl: "https://example.com/clip.mp4" }],
+ });
+ expect(res.status).toBe(400);
+ expect(await res.text()).toContain("written to disk");
+ });
+
+ it("an inline video over its own cap is a 413, and the cap does not follow the attachment limit", async () => {
+ adoptSession(t.deps, recordingFakeSession(SID, runs), { projectId: PROJECT, ...VIDEO_MODEL });
+ // The video ceiling is fixed server-side (Ark takes a video under 50MB inside a 64MB body,
+ // and base64 inflates by 4/3) — unlike the admin-settable file cap, because a video enters
+ // the conversation and the Trace.
+ const oversize = Buffer.alloc(INLINE_VIDEO_MAX_MB * 1024 * 1024 + 1).toString("base64");
+ const res = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [{ type: "video_url", videoUrl: `data:video/mp4;base64,${oversize}` }],
+ });
+ expect(res.status).toBe(413);
+ expect(await errorCode(res)).toBe("video_too_large");
+ });
+
+ it("a steered video rides inline, carries the message alone, and comes back on recall", async () => {
+ const steered: OmniMessage[][] = [];
+ adoptSession(t.deps, steeringFakeSession(SID, steered), {
+ projectId: PROJECT,
+ approvalMode: "always-ask",
+ ...VIDEO_MODEL,
+ });
+ await t.deps.manager.startTask(SID, [userText("go")]);
+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);
+
+ const posted = await api.post(`/api/sessions/${SID}/steer`, { videos: [CLIP] });
+ expect(posted.status).toBe(202);
+ expect(videoOf(steered[0]!)?.video_url).toBe(CLIP);
+ const [info] = t.deps.manager.pendingSteeringOf(SID);
+ expect(info).toEqual({
+ id: expect.any(String),
+ text: "",
+ images: 0,
+ videos: 1,
+ files: 0,
+ });
+
+ const recalled = await api.delete(`/api/sessions/${SID}/steer/${info!.id}`);
+ expect(recalled.status).toBe(200);
+ expect(await recalled.json()).toEqual({ text: "", images: [], videos: [CLIP], files: [] });
+ });
+
+ it("a steered video on a model without video input is refused, not silently misdelivered", async () => {
+ const steered: OmniMessage[][] = [];
+ adoptSession(t.deps, steeringFakeSession(SID, steered), {
+ projectId: PROJECT,
+ approvalMode: "always-ask",
+ });
+ await t.deps.manager.startTask(SID, [userText("go")]);
+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);
+
+ const res = await api.post(`/api/sessions/${SID}/steer`, { videos: [CLIP] });
+ expect(res.status).toBe(400);
+ expect(await res.text()).toContain("file attachment");
+ expect(steered).toEqual([]);
+ });
+});
diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.ts
index 9ce76e11..e8a00765 100644
--- a/packages/ui-gallery/src/app/mock/fixtures.ts
+++ b/packages/ui-gallery/src/app/mock/fixtures.ts
@@ -1516,6 +1516,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
attachmentTotalMb: 120,
attachmentMaxCount: 20,
imageMaxMb: 20,
+ videoMaxMb: 32,
attachmentLimitMinMb: 1,
attachmentLimitMaxMb: 200,
},
diff --git a/packages/ui/src/components/icons/logos/provider-logo.tsx b/packages/ui/src/components/icons/logos/provider-logo.tsx
index f10579f1..425b6db8 100644
--- a/packages/ui/src/components/icons/logos/provider-logo.tsx
+++ b/packages/ui/src/components/icons/logos/provider-logo.tsx
@@ -30,6 +30,13 @@
* currentColor like the rest of this set, and iFlytek the emblem of its site
* logo (iflytek.com) with the wordmark beside it dropped and the ink cropped to
* the mark.
+ *
+ * Volcengine (火山引擎, ByteDance) and Abliteration likewise carry their own
+ * marks rather than a tile: Volcengine the five peaks of its site logo
+ * (volcengine.com) with the Chinese wordmark dropped, its cyan/blue brand
+ * colours flattened to currentColor; Abliteration the three strokes of its site
+ * icon (abliteration.ai/icon.svg) with the pale square behind them dropped. Both
+ * viewBoxes are cropped to the mark's ink.
*/
import type { ReactNode } from "react";
import { avatarInitial, avatarTile } from "../avatars/avatar";
@@ -204,6 +211,36 @@ const GLYPHS: Record<string, Glyph> = {
<path d="M22.8325 14.1634L17.2409 5.89542H16.0581H15.0544L16.0222 7.33333L21.6855 15.7091C21.5063 15.9608 21.3629 16.2124 21.1837 16.4641L21.0762 16.6438L16.0222 9.20261L13.9433 6.11111C14.6601 5.46405 15.377 4.81699 16.0581 4.27778C19.2482 1.5817 21.7931 0 21.7931 0C21.2554 0.287582 20.7178 0.611111 20.2159 0.93464C18.7105 1.79739 17.3484 2.66013 16.0222 3.52288C14.8394 4.31373 13.7282 5.10457 12.6887 5.93137H11.6134L11.9719 6.47059C11.721 6.68627 11.47 6.86601 11.2191 7.0817L10.4306 5.93137H8.27995L9.85707 8.26797C5.054 12.5098 2.32987 16.6078 1.03949 19.9869C-0.465946 23.9412 0.0358671 26.4935 0.25093 27.2843C0.573524 28.4706 1.14703 29.4052 1.8639 30.1961C5.34075 34.1144 11.3267 33.3235 16.0581 31.8137L16.2373 31.7418C20.3952 30.4118 23.6928 28.3987 23.6928 28.3987C21.112 29.6928 18.4954 30.7353 16.0581 31.3464C10.1797 32.8203 5.19738 31.9216 3.51272 26.9248L3.44103 26.7091C3.19012 25.5948 3.15428 24.3366 3.47687 22.5752C4.40881 17.6144 7.41969 13.085 10.6815 9.45425L16.0222 17.2549L18.5313 20.9575C17.8144 22 16.99 23.1144 16.0222 24.2288C13.6565 26.8889 10.3947 29.3693 6.16516 30.232C6.16516 30.232 11.0041 30.6634 16.0222 28.2549C18.3162 27.1765 20.6461 25.4869 22.5458 22.8987L27.5281 30.232H29.6787L23.6211 21.281C23.7286 21.1013 23.8003 20.9575 23.9079 20.7778C23.9795 20.6699 24.0512 20.5261 24.1588 20.3464L30.8616 30.1961H33.0122L25.1265 18.6569C25.3058 18.3333 25.5208 18.0098 25.7359 17.6863L34.3026 30.232H36.4532L26.8112 16.1046C29.4995 12.1863 33.5857 7.26144 37.8153 6.11111C38.1737 6.00327 37.9586 6.07516 38.783 5.85948C37.4568 5.57189 29.141 5.96732 22.8325 14.1634ZM19.6066 19.3039L16.0581 14.0915L11.936 8.08823C12.1511 7.8366 12.402 7.62091 12.617 7.36928L16.0222 12.366L20.1084 18.3693C19.965 18.6569 19.7858 18.9804 19.6066 19.3039Z" />
),
},
+ volcengine: {
+ // The Volcengine emblem (火山引擎, ByteDance's cloud and AI platform): the five peaks of the
+ // vendor's own site logo (www.volcengine.com, logo-theme-light.svg on its lf3-static.bytednsdoc.com
+ // asset host), with the 火山引擎 wordmark beside them left out, the cyan/blue brand colours
+ // flattened to currentColor like vLLM's two colours above, and the viewBox cropped to the mark's
+ // ink. At 1.12:1 it letterboxes top and bottom in a square box, as the other wide marks do.
+ viewBox: "0 0 84.27 75",
+ path: (
+ <>
+ <path d="M34.82,28.93l-14.97,46.07h32.16l-14.97-46.07c-.35-1.08-1.88-1.08-2.23,0Z" />
+ <path d="M12.83,42.36c-.35-1.08-1.88-1.08-2.23,0L0,75h9.42l7.01-21.57-3.59-11.06Z" />
+ <path d="M29.52,20c-.35-1.08-1.88-1.08-2.23,0l-17.87,55h10.43l13.77-42.37-4.1-12.63Z" />
+ <path d="M71.73,36.43c-.35-1.08-1.88-1.08-2.23,0l-3.55,10.94,8.98,27.63h9.34l-12.53-38.57Z" />
+ <path d="M50.82.81c-.35-1.08-1.88-1.08-2.23,0l-10.34,31.82,13.77,42.37h22.9L50.82.81Z" />
+ </>
+ ),
+ },
+ abliteration: {
+ // Abliteration's mark (abliteration.ai): the three strokes of the site's own icon
+ // (abliteration.ai/icon.svg), its pale square backdrop dropped and the viewBox cropped to the
+ // ink, flattened to one currentColor shape like the rest of this set.
+ viewBox: "199 230 602.49 540.46",
+ path: (
+ <>
+ <path d="M282.521 230H199V770.458H282.521V230Z" />
+ <path d="M801.487 230H712.348L501.571 740.998L489.954 770.458H577.195L788.58 261.434L801.487 230Z" />
+ <path d="M506.281 230H422.533L346.528 758.613L344.706 770.458H428.151L502.029 257.942L506.281 230Z" />
+ </>
+ ),
+ },
fireworks: {
// The official Fireworks AI burst mark (three strokes of the wordmark's icon).
viewBox: "0 0 638 315",
diff --git a/packages/web/src/features/chat/agent-topology.ts b/packages/web/src/features/chat/agent-topology.ts
index 8f9dc46b..e746d36f 100644
--- a/packages/web/src/features/chat/agent-topology.ts
+++ b/packages/web/src/features/chat/agent-topology.ts
@@ -5,8 +5,8 @@
*
* Extraction walks a single Task's slice of the main model — by default the most recent
* Task that REFERENCES A SUBAGENT (task boundaries from the "starts a new Task" predicate
- * the reducer uses — user_text / user_image; user_steering never starts one — so a plain
- * user message never wipes the panel), or, for a chip clicked on an older turn, the
+ * the reducer uses — user_text / user_image / user_video; user_steering never starts one —
+ * so a plain user message never wipes the panel), or, for a chip clicked on an older turn, the
* HISTORICAL Task slice containing that chip's child (extractTopologyForChild). The default
* view also keeps children the runtime reports running, even when an earlier Task spawned
* them. It collects children from bound run_subagent tool cards and standalone SubagentItems, then
@@ -61,7 +61,7 @@ export interface TopologyNode {
/**
* Whether an item opens a new PANEL scope. The reducer's "starts a new Task" predicate
- * (user_text/user_image), minus one exception: an idle-launched `[background_task_done]`
+ * (user_text/user_image/user_video), minus one exception: an idle-launched `[background_task_done]`
* notice does start a chat Task (its auto-run answers it), but for the topology it belongs
* to the Task that launched the background work — slicing there would split a background
* subagent's spawn from its completion and reset the panel the moment the report lands. A
@@ -69,7 +69,7 @@ export interface TopologyNode {
* `background_notice` kind, which starts nothing anywhere.
*/
function isScopeStart(item: ChatItem): boolean {
- if (item.kind === "user_image") return true;
+ if (item.kind === "user_image" || item.kind === "user_video") return true;
if (item.kind !== "user_text") return false;
// Cheap reject first: these predicates run over every item on every render, and the marker
// parse is two full-text regex scans — only text that actually carries the tag pays for it.
@@ -86,7 +86,7 @@ export function latestTaskStart(items: readonly ChatItem[]): number {
}
/**
- * Task starts as the STREAM MODEL counts them — every user_text/user_image, idle-launched
+ * Task starts as the STREAM MODEL counts them — every user_text/user_image/user_video, idle-launched
* notices included, so the number stays 1:1 with the reducer's own `startTask` calls (a
* steered notice is a `background_notice` item, which the reducer never startTasks — so it
* is rightly not counted here either). The header's cost tracker keys its Task-boundary fold
@@ -97,16 +97,19 @@ export function latestTaskStart(items: readonly ChatItem[]): number {
export function modelTaskStartCount(items: readonly ChatItem[]): number {
let n = 0;
for (const item of items) {
- if (item.kind === "user_text" || item.kind === "user_image") n += 1;
+ if (item.kind === "user_text" || item.kind === "user_image" || item.kind === "user_video") {
+ n += 1;
+ }
}
return n;
}
/**
- * Count of Task-starting user items (the reducer's startTask predicate: user_text/user_image —
- * steering chips and internal injections such as compaction summaries never become such items,
- * so they never count). The subagents panel's task-boundary signal: an INCREASE means the user
- * started a new Task in this session (see advancePanelTaskScope in panel-task-scope.ts).
+ * Count of Task-starting user items (the reducer's startTask predicate:
+ * user_text/user_image/user_video — steering chips and internal injections such as compaction
+ * summaries never become such items, so they never count). The subagents panel's task-boundary
+ * signal: an INCREASE means the user started a new Task in this session (see
+ * advancePanelTaskScope in panel-task-scope.ts).
*/
export function taskStartCount(items: readonly ChatItem[]): number {
let n = 0;
@@ -216,11 +219,11 @@ export function extractTopology(
/**
* Historical variant: extract the spawn tree of the Task slice CONTAINING the given direct
* child — the slice around the main-stream item that references it (a bound run_subagent card
- * or a standalone SubagentItem), bounded by the nearest user_text/user_image on either side.
- * Null when no main-stream item references the child (e.g. a resync swapped in a fresh model) —
- * the caller then falls back to the latest Task. The root's running state stays live only while
- * the slice is still the open-ended latest Task; an older Task has ended by definition (the
- * next user message closed it).
+ * or a standalone SubagentItem), bounded by the nearest user_text/user_image/user_video on
+ * either side. Null when no main-stream item references the child (e.g. a resync swapped in a
+ * fresh model) — the caller then falls back to the latest Task. The root's running state stays
+ * live only while the slice is still the open-ended latest Task; an older Task has ended by
+ * definition (the next user message closed it).
*/
export function extractTopologyForChild(
model: StreamModel,
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index 410e23a2..d8321db9 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -35,14 +35,17 @@
* the model already in use clears the staging, and both are exclusive with goal mode); a chip is
* removed via backspace at the start of the text or its x button, and both are cached with the
* draft so they survive a session switch or reload along with the text they belong to;
- * The "+" menu carries the input add-ons: image upload, file attachment (any type, several at a
- * time — they ride the task request as base64 data URLs, and the server writes them into the
- * session scratchpad and appends an `[attached file: <path>]` line to the message, so the model
- * opens them by path), and goal mode; selected files show as removable chips above the text
- * body, next to the image thumbnails, and — like images — an attachments-only message is
- * sendable with no text at all. Dragging files onto the chat area feeds the same two intakes
- * (images → paste pipeline, other files → attachments; see FileDropZone/addDroppedFiles),
- * with an overlay bounded to that region while the drag is over it.
+ * The "+" menu carries the input add-ons: image upload, video upload, file attachment (any type,
+ * several at a time — they ride the task request as base64 data URLs, and the server writes them
+ * into the session scratchpad and appends an `[attached file: <path>]` line to the message, so the
+ * model opens them by path), and goal mode; selected files show as removable chips above the text
+ * body, next to the image thumbnails and the video ones, and — like images — an
+ * attachments-only message is sendable with no text at all. A video's own ceiling is neither the
+ * image's nor an attachment's (uploadLimits.videoMaxMb), and where it ends up is the model's call:
+ * a model that takes video input is sent the clip inline, any other gets it as a scratchpad file
+ * like an attachment (see lib/video-input). Dragging files onto the chat area feeds the same three
+ * intakes (images and videos → the media pipeline, other files → attachments; see
+ * FileDropZone/addDroppedFiles), with an overlay bounded to that region while the drag is over it.
* The bottom toolbar provides a searchable multi-select skills dropdown (styled like the model
* selector: a top search box filtering by name and localized description, plus a checklist;
* clicking a row toggles its selection without closing the menu; the button = book icon + label +
@@ -151,13 +154,16 @@ import {
} from "./input-history";
import type { HistoryStep } from "./input-history";
import { isStopAction, midRunAction } from "./composer-send";
+import { steeringSummary } from "./queued-summary";
import { PAPERCLIP_ICON } from "./attached-files-banner";
import { FileDropZone } from "./drop-zone";
import { ContextGauge } from "./context-gauge";
import { modelWindowBelowCompactionLimit } from "../../lib/context";
-import { splitDroppedFiles } from "../../lib/file-drop";
+import { splitMediaFiles } from "../../lib/file-drop";
import { isLongPaste, longPasteFileName } from "../../lib/long-paste";
import { splitBySize } from "../../lib/upload-limits";
+import { appendMediaParts, dataUrlBytes, videoFromUrl } from "../../lib/video-input";
+import type { ComposerVideo } from "../../lib/video-input";
import type { ComposerReference } from "../../lib/workspace-tree";
import { ReferenceChip } from "./reference-chip";
@@ -441,6 +447,15 @@ interface SlashCommand {
run: () => void;
}
+/**
+ * Video-camera glyph (24×24 line path, a lens body with the triangular flag on its right) for the
+ * "+" menu's video entry: the uploaded-image icon next to it is a picture frame, and a clip needs
+ * its own shape or the two entries read as one. Kept here rather than in the icon set because the
+ * composer is its only user.
+ */
+const VIDEO_ICON =
+ "M4 6h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2zM22 8l-6 4 6 4V8z";
+
/**
* One file attachment staged in the composer. `dataUrl` is the base64 `data:` URL sent as the
* task input's `file` part; `name` / `size` only feed the chip (the server decides the name the
@@ -458,7 +473,7 @@ interface Attachment {
* the toast can name the number actually in force. Enforcing it client-side at all is still
* worth it — an oversize pick is refused before the file is read, instead of costing the user a
* base64 encode, an upload 33% larger than the file, and a 413 to learn the same thing. The
- * partition itself lives in lib/upload-limits (splitBySize), shared with the image intake.
+ * partition itself lives in lib/upload-limits (splitBySize), shared by all three intakes.
*/
/** Reads one file as a base64 data URL; resolves to null on a read error rather than rejecting, so one unreadable file cannot drop the rest of the batch. */
@@ -471,22 +486,6 @@ function readDataUrl(file: File): Promise<string | null> {
});
}
-/** Approximate decoded byte size of a base64 data URL (for the recalled attachment's chip; display only). */
-function dataUrlBytes(dataUrl: string): number {
- const body = dataUrl.slice(dataUrl.indexOf(",") + 1).replace(/[=\s]+/g, "");
- return Math.floor((body.length * 3) / 4);
-}
-
-/** One-line summary of a queued steering message: its text, then image/file counts for what the text cannot show. */
-function steeringSummary(p: { text: string; images: number; files: number }): string {
- const parts: string[] = [];
- const line = p.text.replace(/\s+/g, " ").trim();
- if (line) parts.push(line);
- if (p.images > 0) parts.push(S.chat.imagesInMessage(p.images));
- if (p.files > 0) parts.push(S.chat.filesInMessage(p.files));
- return parts.join(" \u00b7 ");
-}
-
/**
* One queued-message hint line (undelivered steering / queued follow-up) with its recall
* button (#287): the button withdraws the message server-side and puts its content back into
@@ -528,22 +527,6 @@ function QueuedMessageLine({
);
}
-/**
- * Appends the draft's attachments to a task input — images first (in pick order), then files.
- * One place, because every send path submits the same draft: the normal send, the follow-up
- * queue, the @ handoff and the `/model` switch.
- */
-function appendAttachmentParts(
- input: TaskInputPart[],
- images: string[],
- attachments: Attachment[],
-): void {
- for (const url of images) input.push({ type: "image_url", imageUrl: url });
- for (const file of attachments) {
- input.push({ type: "file", fileName: file.name, dataUrl: file.dataUrl });
- }
-}
-
/**
* The message body: the staged quotations, then what was typed. Blank parts are dropped so a
* quotation sent with no sentence after it does not trail an empty line.
@@ -618,6 +601,7 @@ export function ChatInput({
contextStale = false,
sessionId,
vision,
+ video,
approvalMode,
approvalModes,
sandbox,
@@ -649,17 +633,23 @@ export function ChatInput({
onSend: (input: TaskInputPart[], goal: { budget: number } | null) => Promise<boolean>;
/**
* Mid-run steering (session state only): while a Task is running, Enter/send queues the
- * trimmed text **and any attached images and files** for the running agent — delivered
- * between turns as a standalone `[user_steering]` user message followed by its images,
- * with the files riding the text as `[attached file: <path>]` lines (#140: a file-only
- * draft steers exactly like an image-only one). `"queued"` clears the text, images and
+ * trimmed text **and any attached images, videos and files** for the running agent — delivered
+ * between turns as a standalone `[user_steering]` user message followed by its images and
+ * videos, with the files riding the text as `[attached file: <path>]` lines (#140: a file-only
+ * draft steers exactly like an image-only one). `"queued"` clears the text, images, videos and
* files and shows the queued hint; `"not_running"` (409 race with completion) makes the
* input fall back to its full normal send path; `"failed"` keeps the draft. When absent
* (draft state), the input stays send-disabled while running, as before.
+ *
+ * The videos travel as whole draft entries (their data URL and the picked name), not as bare
+ * URLs: a model that takes no video input gets them back as file attachments, which need the
+ * name the user's pick had. Which of the two shapes the request carries is the host's call —
+ * see steerVideoFields, whose whole job that is.
*/
onSteer?: (
text: string,
images: string[],
+ videos: ComposerVideo[],
files: { fileName: string; dataUrl: string }[],
) => Promise<"queued" | "not_running" | "failed">;
/**
@@ -793,6 +783,13 @@ export function ChatInput({
sessionId?: string;
/** Whether the current model supports image input (models config's vision; assumed supported by default). */
vision: boolean;
+ /**
+ * Whether the current model takes video input (models config's video). The default here is the
+ * opposite of `vision`'s, because the model's is: a video is megabytes of base64 and a Session
+ * whose model does not take one is better served by the scratchpad-path route, so only a model
+ * that says so gets the clip inline (and the composer says which it is — see videosAsPathHint).
+ */
+ video: boolean;
approvalMode: ApprovalMode;
/**
* The approval modes the permission button may offer, in order (`approvalModeChoices`): all
@@ -885,6 +882,12 @@ export function ChatInput({
const textRef = useRef(text);
textRef.current = text;
const [images, setImages] = useState<string[]>([]);
+ // Videos staged from the "+" menu, a drop or a paste: held exactly like images (a base64 data
+ // URL), but as whole entries rather than bare strings — the picked name is what the clip is
+ // called when the model that takes none gets it as a scratchpad file, and the chip shows it too.
+ // Nothing here copies the string a clip decodes to: it is read once, stored once, and passed on
+ // by reference by every send path (see lib/video-input).
+ const [videos, setVideos] = useState<ComposerVideo[]>([]);
// File attachments picked from the "+" menu (any type): held as base64 data URLs, exactly
// like images — a draft has no Session yet, so there is nothing to upload them to ahead of
// time; they travel with the task request and the server files them into the scratchpad.
@@ -934,6 +937,7 @@ export function ChatInput({
const draftHasContent =
text.trim().length > 0 ||
images.length > 0 ||
+ videos.length > 0 ||
attachments.length > 0 ||
references.length > 0 ||
target !== null ||
@@ -941,9 +945,10 @@ export function ChatInput({
selectedSkills.length > 0;
// Goal mode (engaged via the "+" menu or /goal): the text body becomes the objective. It is
// exclusive with a staged /agent or /model switch (engaging either clears the other). Attached
- // images and selected skills ride the round-1 message exactly as in a normal send: the images
- // as image input (path lines only on a model without vision), the skills as a [use_skills]
- // block. Later rounds restate the objective text alone.
+ // images and videos and selected skills ride the round-1 message exactly as in a normal send: the
+ // images as image input (path lines only on a model without vision), the videos as video input or
+ // as a scratchpad file, whichever the model takes, and the skills as a [use_skills] block. Later
+ // rounds restate the objective text alone.
const [goalOn, setGoalOn] = useState(false);
const [goalBudgetText, setGoalBudgetText] = useState("");
const [goalBudgetOpen, setGoalBudgetOpen] = useState(false);
@@ -976,8 +981,8 @@ export function ChatInput({
// parseable budget — and an open editor showing an invalid draft disables Send outright:
// combined with the editor refusing to close over an invalid draft (below), no click sequence
// can fire a goal with a stale committed budget.
- // Images may come along with a goal objective (they ride its round-1 message), but they don't
- // substitute for the text; file attachments cannot — the server refuses them on a goal.
+ // Images and videos may come along with a goal objective (they ride its round-1 message), but
+ // they don't substitute for the text; file attachments cannot — the server refuses them on a goal.
const canSend =
!running &&
!compacting &&
@@ -1032,8 +1037,8 @@ export function ChatInput({
/**
* Engage/exit goal mode; engaging clears any staged switch chip and every file attachment
* (genuinely exclusive: a handoff or a model switch opens another session, and the server
- * refuses file attachments on a goal). Attached images and selected skills stay — they ride
- * the round-1 message, like a normal send.
+ * refuses file attachments on a goal). Attached images, videos and selected skills stay — they
+ * ride the round-1 message, like a normal send.
*/
const toggleGoal = useCallback(
(on: boolean) => {
@@ -1046,9 +1051,9 @@ export function ChatInput({
onHandoffTargetChange?.(null);
setPendingModel(null);
onPendingModelChange?.(null);
- // Images ride a goal's round-1 message, file attachments do not — the server refuses
- // those, so clear them or canSend would stay silently false with the objective looking
- // ready.
+ // Images and videos ride a goal's round-1 message, file attachments do not — the server
+ // refuses those, so clear them or canSend would stay silently false with the objective
+ // looking ready.
setAttachments([]);
}
},
@@ -1093,6 +1098,7 @@ export function ChatInput({
hasPendingModel: pendingModel !== null,
hasText: text.trim().length > 0,
hasImages: images.length > 0,
+ hasVideos: videos.length > 0,
hasFiles: attachments.length > 0,
hasContent: draftHasContent,
});
@@ -1172,6 +1178,10 @@ export function ChatInput({
onTextChange?.(merged);
setCaret(merged.length);
if (r.images.length > 0) setImages((prev) => [...r.images, ...prev]);
+ // A recalled video comes back as a URL and nothing else, so its chip's name and size are
+ // derived from it (see videoFromUrl) — the draft's own picks keep the name they were picked
+ // with, and the two read the same in the chip.
+ if (r.videos.length > 0) setVideos((prev) => [...r.videos.map(videoFromUrl), ...prev]);
if (r.files.length > 0) {
// A goal draft cannot carry the restored files — release the staged chip rather than
// strand them behind a dead Send (why: see mergeRecalledDraft).
@@ -1644,15 +1654,19 @@ export function ChatInput({
// from being added since), so there is nothing to carry here.
setBusy(true);
try {
- // Attached images ride the round-1 message (see the goalOn declaration above).
+ // Attached images and videos ride the round-1 message (see the goalOn declaration above).
const goalInput: TaskInputPart[] = [
{ type: "text", text: buildSkillsMessage(selectedSkills, t) },
];
for (const url of images) goalInput.push({ type: "image_url", imageUrl: url });
+ for (const clip of videos) {
+ goalInput.push({ type: "video_url", videoUrl: clip.dataUrl, fileName: clip.name });
+ }
const ok = await onSend(goalInput, { budget: goalBudget! });
if (ok) {
setText("");
setImages([]);
+ setVideos([]);
setSelectedSkills([]);
toggleGoal(false);
}
@@ -1691,7 +1705,7 @@ export function ChatInput({
const body = buildSkillsMessage(selectedSkills, bodyText);
const input: TaskInputPart[] = [];
if (body) input.push({ type: "text", text: body });
- appendAttachmentParts(input, images, attachments);
+ appendMediaParts(input, images, videos, attachments);
setBusy(true);
try {
const ok = target
@@ -1706,6 +1720,7 @@ export function ChatInput({
if (ok) {
setText("");
setImages([]);
+ setVideos([]);
setAttachments([]);
setReferences([]);
setTarget(null);
@@ -1730,17 +1745,18 @@ export function ChatInput({
await sendNormal(onQueueFollowUp!);
return;
}
- // Steering branch: queue the trimmed text, the attached images and the attached files
+ // Steering branch: queue the trimmed text, the attached images, videos and files
// for the running agent; all are sent and cleared together — selected skills stay for
// a normal send (a staged switch chip blocks this branch outright, see midRunAction).
if (!steerAction) return;
const steerText = withReferences(references, text.trim());
const steerImages = images;
+ const steerVideos = videos;
const steerFiles = attachments.map((f) => ({ fileName: f.name, dataUrl: f.dataUrl }));
setBusy(true);
let res: "queued" | "not_running" | "failed" = "failed";
try {
- res = await onSteer!(steerText, steerImages, steerFiles);
+ res = await onSteer!(steerText, steerImages, steerVideos, steerFiles);
if (res === "queued") {
// Show the "queued" hint until the steering message shows up in the stream
// (steeringDeliveredCount increases) — see the effect below.
@@ -1748,6 +1764,7 @@ export function ChatInput({
setSteerPending(true);
setText("");
setImages([]);
+ setVideos([]);
setAttachments([]);
setReferences([]);
}
@@ -1850,14 +1867,17 @@ export function ChatInput({
}
};
- const addFiles = (files: Iterable<File>) => {
- // Images had no size check at all: an oversize paste was read into a data URL, JSON'd and
- // uploaded, freezing the tab on the way to a generic body-cap 413. They are capped well
- // below file attachments on purpose — an inline image rides the conversation and the Trace,
- // where its size is paid again on every history page and every resume.
- const imageFiles: File[] = [];
- for (const file of files) if (file.type.startsWith("image/")) imageFiles.push(file);
- const { accepted, rejected } = splitBySize(imageFiles, uploadLimits.imageMaxMb);
+ /**
+ * Images staged from a batch that has already been partitioned (see lib/file-drop).
+ *
+ * They had no size check at all: an oversize paste was read into a data URL, JSON'd and uploaded,
+ * freezing the tab on the way to a generic body-cap 413. They are capped well below file
+ * attachments on purpose — an inline image rides the conversation and the Trace, where its size is
+ * paid again on every history page and every resume — and the ceiling is named in the toast, so
+ * what the composer refuses is what the server would.
+ */
+ const stageImages = (files: readonly File[]) => {
+ const { accepted, rejected } = splitBySize(files, uploadLimits.imageMaxMb);
for (const file of rejected) {
toastError(S.chat.attachmentTooLarge(file.name, uploadLimits.imageMaxMb));
}
@@ -1872,6 +1892,39 @@ export function ChatInput({
}
};
+ /**
+ * Videos staged from a batch that has already been partitioned. Same pre-flight refusal as the
+ * images above, against the clip's own, much larger ceiling (uploadLimits.videoMaxMb): what the
+ * provider accepts as one video, with base64's 4/3 in it.
+ *
+ * The batch is read whole before any of it is staged, so the chips follow the order the files were
+ * picked in rather than the order the reads finished in — the same order the parts travel in. Each
+ * entry holds the data URL its own read produced: no re-encode and no second copy of a string that
+ * can be tens of megabytes (see lib/video-input).
+ */
+ const stageVideos = (files: readonly File[]) => {
+ const { accepted, rejected } = splitBySize(files, uploadLimits.videoMaxMb);
+ for (const file of rejected) {
+ toastError(S.chat.attachmentTooLarge(file.name, uploadLimits.videoMaxMb));
+ }
+ if (accepted.length === 0) return;
+ void Promise.all(accepted.map(async (file) => ({ file, url: await readDataUrl(file) }))).then(
+ (read) => {
+ const staged = read.flatMap(({ file, url }) =>
+ url ? [{ name: file.name, size: file.size, dataUrl: url }] : [],
+ );
+ if (staged.length > 0) setVideos((prev) => [...prev, ...staged]);
+ },
+ );
+ };
+
+ /** The media intake every entry point shares (the two "+" pickers, a paste, a drop): an image goes to the image list, a clip to the video list, each under its own ceiling. */
+ const addMediaFiles = (files: Iterable<File>) => {
+ const { images: imageFiles, videos: videoFiles } = splitMediaFiles(files);
+ stageImages(imageFiles);
+ stageVideos(videoFiles);
+ };
+
const onPaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {
// The subagent variant takes text only: a pasted file/image falls through to the
// browser's default handling (which drops the binary and keeps any text).
@@ -1885,7 +1938,7 @@ export function ChatInput({
}
if (files.length > 0) {
e.preventDefault();
- addFiles(files);
+ addMediaFiles(files);
return;
}
// A paste too long for the text box (a whole log) is attached as a text file instead:
@@ -1901,7 +1954,7 @@ export function ChatInput({
};
const onPickFiles = (e: ChangeEvent<HTMLInputElement>) => {
- if (e.target.files) addFiles(e.target.files);
+ if (e.target.files) addMediaFiles(e.target.files);
e.target.value = "";
};
@@ -1939,18 +1992,19 @@ export function ChatInput({
};
/**
- * Files dropped onto the chat area (see FileDropZone): one batch, routed into the SAME two
- * intakes the "+" menu and paste use — images join the pasted-image pipeline, everything
- * else joins the file-attachment pipeline (each with its own cap and the same rejection toast,
- * see uploadLimits). Goal mode takes
- * images but not files (nothing folds a file into the re-injected objective — the "+" menu
- * grays its file entry out for the same reason); a drop has no disabled affordance to gray,
- * so the refusal is said out loud instead of silently swallowing the files.
+ * Files dropped onto the chat area (see FileDropZone): one batch, partitioned into the SAME
+ * intakes the "+" menu and paste use — images and videos join the media pipeline, each with its
+ * own cap and the same rejection toast, everything else joins the file-attachment pipeline (see
+ * uploadLimits). Goal mode takes images and videos but not files (nothing folds a file into the
+ * re-injected objective — the "+" menu grays its file entry out for the same reason); a drop has
+ * no disabled affordance to gray, so the refusal is said out loud instead of silently swallowing
+ * the files.
*/
const addDroppedFiles = (dropped: File[]) => {
if (variant !== "session") return; // Text-only surface: drops have nowhere to go.
- const batch = splitDroppedFiles(dropped);
- if (batch.images.length > 0) addFiles(batch.images);
+ const batch = splitMediaFiles(dropped);
+ stageImages(batch.images);
+ stageVideos(batch.videos);
if (batch.files.length > 0) {
if (goalOn) toastInfo(S.chat.dropFilesGoalHint);
else addAttachments(batch.files);
@@ -1960,9 +2014,10 @@ export function ChatInput({
* The image picker moved into the "+" menu, so the file input can no longer be a `<label>`
* wrapper: the menu unmounts its items on select. It lives outside the menu instead and the
* entry clicks it — still inside the click's user-activation window, so the dialog opens.
- * The file-attachment picker below works the same way.
+ * The video and file-attachment pickers below work the same way.
*/
const imageInputRef = useRef<HTMLInputElement>(null);
+ const videoInputRef = useRef<HTMLInputElement>(null);
const attachmentInputRef = useRef<HTMLInputElement>(null);
/**
@@ -2187,9 +2242,52 @@ export function ChatInput({
</div>
)}
- {/* Attached files, right below the image thumbnails: one removable chip each (name +
- size), since there is nothing to preview. The name is the picked file's — the server
- sanitizes it when writing to the scratchpad, and the message's banner then shows the
+ {/* A staged video: its name and size plus a first-frame thumbnail, since a clip has no
+ poster to look at and a chip that says nothing but "video.mp4" cannot be told from the
+ next one. The thumbnail is `muted playsInline preload="metadata"` and has no controls: it
+ is a still picture made of the clip's first frame, and a staged draft must never make a
+ sound or start playing on its own. The `src` is the very string the read produced — the
+ chip neither re-encodes it nor keeps a second copy of a clip that can be tens of MB. */}
+ {videos.length > 0 && (
+ <div className="mb-2 flex flex-wrap gap-2">
+ {videos.map((clip, i) => (
+ <div key={i} className="anim-pop relative">
+ <div className="flex max-w-72 items-center gap-2 rounded-md border border-gray-200 p-1 pr-2.5 dark:border-gray-700">
+ <video
+ src={clip.dataUrl}
+ muted
+ playsInline
+ preload="metadata"
+ aria-label={S.chat.videoLabel}
+ className="h-10 w-16 shrink-0 rounded bg-gray-100 object-cover dark:bg-gray-800"
+ />
+ <div className="min-w-0">
+ <p className="truncate text-xs text-gray-700 dark:text-gray-300">{clip.name}</p>
+ {/* A recalled clip on a web address has no measurable size: say nothing
+ rather than "0 B". */}
+ {clip.size > 0 && (
+ <p className="text-xs text-gray-400 dark:text-gray-500">
+ {formatBytes(clip.size)}
+ </p>
+ )}
+ </div>
+ </div>
+ <button
+ type="button"
+ aria-label={`${S.chat.removeVideo} ${clip.name}`}
+ onClick={() => setVideos((prev) => prev.filter((_, j) => j !== i))}
+ className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-gray-700 text-xs text-white transition-colors duration-150 hover:bg-gray-900"
+ >
+ ×
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Attached files, right below the image thumbnails and the video chips: one removable chip
+ each (name + size), since there is nothing to preview. The name is the picked file's — the
+ server sanitizes it when writing to the scratchpad, and the message's banner then shows the
on-disk name. */}
{attachments.length > 0 && (
<TagInput
@@ -2253,6 +2351,16 @@ export function ChatInput({
</p>
)}
+ {/* The same note for a clip, on a model that takes no video input: it is still sent — the
+ server files it into the scratchpad and the message carries its path instead — and this
+ is what says so, since a video that quietly turned into a path line is otherwise a
+ surprise. A model that takes video never shows it. */}
+ {!video && videos.length > 0 && (
+ <p className="anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500">
+ {S.chat.videosAsPathHint}
+ </p>
+ )}
+
{/* A staged /model fork that has to wait for this Session to go idle (a run started from
outside the composer, or a compaction): the Send button is disabled either way, and
this is the line that says why — the chip stays staged and goes out on the next Enter
@@ -2315,8 +2423,9 @@ export function ChatInput({
)}
{/* The hidden inputs behind the "+" menu's upload entries: kept mounted here (outside the
- menu, which unmounts its items on select) and clicked by those entries. The file picker
- has no `accept` — an attachment can be any type, the model reads it from disk. */}
+ menu, which unmounts its items on select) and clicked by those entries. The video picker
+ takes `video/*` and the file picker has no `accept` — an attachment can be any type, the
+ model reads it from disk. */}
<input
ref={imageInputRef}
type="file"
@@ -2325,6 +2434,14 @@ export function ChatInput({
className="hidden"
onChange={onPickFiles}
/>
+ <input
+ ref={videoInputRef}
+ type="file"
+ accept="video/*"
+ multiple
+ className="hidden"
+ onChange={onPickFiles}
+ />
<input
ref={attachmentInputRef}
type="file"
@@ -2426,8 +2543,8 @@ export function ChatInput({
// The three icon buttons — +, permission, skills — sit as one tight cluster: the row's
// wider gap would read them as unrelated controls.
<>
- {/* "+" extension menu, leading the row: input add-ons (image upload, file
- attachment, goal mode) plus the input settings footer (mid-run send mode —
+ {/* "+" extension menu, leading the row: input add-ons (image upload, video upload,
+ file attachment, goal mode) plus the input settings footer (mid-run send mode —
usable while running, which is exactly when it matters, so the button itself
never disables). The uploads live in here rather than as their own toolbar
buttons: one 8x8 slot instead of three, which is the difference between the
@@ -2448,6 +2565,17 @@ export function ChatInput({
active: images.length > 0,
onSelect: () => imageInputRef.current?.click(),
},
+ {
+ key: "video",
+ icon: VIDEO_ICON,
+ label: S.chat.uploadVideo,
+ // Same shape as the image entry one line up: whatever the model takes, the
+ // clip is sendable, and the description says which route this model gives it
+ // (inline, or a scratchpad file the model opens by path).
+ desc: video ? S.chat.uploadVideoDesc : S.chat.videosAsPathHint,
+ active: videos.length > 0,
+ onSelect: () => videoInputRef.current?.click(),
+ },
{
key: "file",
icon: PAPERCLIP_ICON,
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index d8cc0276..3079cb9c 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -99,6 +99,8 @@ import type { ForkTarget } from "./task-stats-line";
import { latestTaskHasSubagent, modelTaskStartCount, taskStartCount } from "./agent-topology";
import { ChatInput } from "./chat-input";
import type { ComposerControl } from "./chat-input";
+import { steerVideoFields } from "../../lib/video-input";
+import type { ComposerVideo } from "../../lib/video-input";
import { onPluginConfigSaved } from "../../lib/plugin-config-event";
import { approvalModeChoices } from "./approval-mode";
import type { ComposerReference } from "../../lib/workspace-tree";
@@ -1483,8 +1485,21 @@ export function ChatPage() {
[selected, turnThinkingLevel, discardSessionDraft, syncHealedSessionId],
);
+ // Capability info for the conversation's current model, in one place: the composer is told both
+ // (vision decides how an image arrives, video how a clip does) and the steer branch below needs
+ // the video one before the request body is built. Read here — above every callback that uses it —
+ // rather than next to the JSX where it used to sit.
+ const modelInfo = models?.models.find((m) => sameModelRef(m, activeModelRef));
+ const contextWindow = modelInfo?.contextWindow;
+ // Assumed supported by default: only models explicitly marked vision=false show a blocking hint when adding images.
+ const vision = modelInfo?.vision !== false;
+ // Video is the opposite default, deliberately: a model takes a clip only when it says it does
+ // (`video === true`), because a video is megabytes of base64 and a model that would refuse one is
+ // better served by the scratchpad route.
+ const video = modelInfo?.video === true;
+
// Mid-run steering: the message is queued on the server and delivered between turns as a
- // standalone `[user_steering]` user message followed by its images (visible once they
+ // standalone `[user_steering]` user message followed by its images and videos (visible once they
// arrive over SSE / from the Trace); file attachments land in the Session scratchpad and
// ride the steering text as `[attached file: <path>]` lines, exactly as a task's do. On
// "queued" the localStorage draft is discarded, like a successful send — without this a
@@ -1496,14 +1511,21 @@ export function ChatPage() {
async (
text: string,
images: string[] = [],
+ videos: ComposerVideo[] = [],
files: { fileName: string; dataUrl: string }[] = [],
): Promise<"queued" | "not_running" | "failed"> => {
if (!selected) return "failed";
try {
+ // A steered clip goes inline only on a model that takes video input; anywhere else it
+ // becomes an ordinary file attachment (scratchpad + `[attached file: <path>]` line), which
+ // is the only shape the server accepts there — it refuses an inline video rather than
+ // handing a provider a request it would reject. The choice itself is steerVideoFields'.
+ const clip = steerVideoFields(videos, video);
await api.postSteer(selected.sessionId, {
text,
...(images.length > 0 ? { images } : {}),
- ...(files.length > 0 ? { files } : {}),
+ ...(clip.videos ? { videos: clip.videos } : {}),
+ ...((clip.files ?? files.length > 0) ? { files: [...(clip.files ?? []), ...files] } : {}),
});
discardSessionDraft();
return "queued";
@@ -1513,7 +1535,7 @@ export function ChatPage() {
return "failed";
}
},
- [selected, discardSessionDraft],
+ [selected, video, discardSessionDraft],
);
/**
@@ -2085,10 +2107,6 @@ export function ChatPage() {
const sessionAgent = agents.find((a) => a.agentId === selected?.agentId);
const sessionAgentName =
sessionAgent && sessionAgent.name !== undefined ? agentDisplayName(sessionAgent) : null;
- const modelInfo = models?.models.find((m) => sameModelRef(m, activeModelRef));
- const contextWindow = modelInfo?.contextWindow;
- // Assumed supported by default: only models explicitly marked vision=false show a blocking hint when adding images.
- const vision = modelInfo?.vision !== false;
const emptyChat =
selected !== null && !stream.loading && !stream.error && stream.model.items.length === 0;
@@ -2132,6 +2150,7 @@ export function ChatPage() {
contextStale={stream.model.stats.contextStale}
sessionId={selected.sessionId}
vision={vision}
+ video={video}
approvalMode={selected.approvalMode}
// An organization's Session is not offered always-ask: nobody is there to be asked.
approvalModes={approvalModeChoices(selected.client, selected.approvalMode)}
diff --git a/packages/web/src/features/chat/composer-send.ts b/packages/web/src/features/chat/composer-send.ts
index 24c123b3..9dbf7ad6 100644
--- a/packages/web/src/features/chat/composer-send.ts
+++ b/packages/web/src/features/chat/composer-send.ts
@@ -44,11 +44,13 @@ export interface MidRunComposerState {
hasText: boolean;
/** At least one image is attached. */
hasImages: boolean;
+ /** At least one video is staged (steers inline, or as a file on a model without video input). */
+ hasVideos: boolean;
/** At least one file attachment is staged (steers as `[attached file: <path>]` lines, like a task's). */
hasFiles: boolean;
/**
- * The draft carries anything at all — text, images, file attachments, a staged switch chip
- * or selected skills. The queue takes a whole message, so this is its content rule.
+ * The draft carries anything at all — text, images, videos, file attachments, a staged switch
+ * chip or selected skills. The queue takes a whole message, so this is its content rule.
*/
hasContent: boolean;
}
@@ -72,7 +74,7 @@ export function midRunAction(s: MidRunComposerState): MidRunAction {
s.canSteerChannel &&
!s.hasHandoffTarget &&
!s.hasPendingModel &&
- (s.hasText || s.hasImages || s.hasFiles);
+ (s.hasText || s.hasImages || s.hasVideos || s.hasFiles);
if (canSteer && !s.followUpMode) return "steer";
const canQueue = open && s.canQueueChannel && s.stagedRoute !== "blocked" && s.hasContent;
if (canQueue) return "queue";
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index c689cee3..d762bb5e 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -835,10 +835,13 @@ export function DraftView({
*/
const [shortcutsOpen, setShortcutsOpen] = useState(false);
- // Capability info for the currently selected model (vision/context window) switches instantly with the selection (matched by paired reference).
+ // Capability info for the currently selected model (vision/video/context window) switches instantly with the selection (matched by paired reference).
const modelInfo = models?.models.find((m) => sameModelRef(m, modelRef));
const contextWindow = modelInfo?.contextWindow;
const vision = modelInfo?.vision !== false;
+ // Only a model that says it takes video gets a clip inline; every other one is given it as a
+ // scratchpad file (see lib/video-input). The default is therefore the opposite of vision's.
+ const video = modelInfo?.video === true;
return (
<div className="anim-fade flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-6 md:px-4">
@@ -882,6 +885,7 @@ export function DraftView({
{...(contextWindow !== undefined ? { contextWindow } : {})}
contextNow={0}
vision={vision}
+ video={video}
approvalMode={approvalMode}
// A draft becomes an ordinary conversation, never an organization's: every mode.
approvalModes={APPROVAL_MODES}
diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsx
index ae951906..d6af432b 100644
--- a/packages/web/src/features/chat/message-item.tsx
+++ b/packages/web/src/features/chat/message-item.tsx
@@ -58,6 +58,34 @@ function SentMessageMeta({ atMs, copyText }: { atMs: number | undefined; copyTex
);
}
+/**
+ * A video the person sent, in the bubble its own message gets (`bubble`) or on the smaller rung a
+ * steer's media row uses (`chip`) — the two rungs MessageImage has, with the same width caps, so a
+ * clip can no more overflow a phone than a picture can. On the UI package's image variant rather
+ * than a bubble of its own: it is the same thing a message carries, in the same frame.
+ *
+ * `controls` and `preload="metadata"`: the clip shows its first frame and its length, and nothing
+ * heavy is fetched until the person presses play. `playsInline` keeps a phone from throwing it into
+ * fullscreen the moment it plays. Deliberately NOT muted, and deliberately not autoplaying: a
+ * transcript must not make noise on its own, but a clip somebody chooses to play is theirs to hear.
+ * A windowed history page's `videoUrl` is a reference the browser fetches itself — `routedUrl` at
+ * the call sites sends it to the machine the Session lives on.
+ */
+function MessageVideo({ src, size = "bubble" }: { src: string; size?: "bubble" | "chip" }) {
+ return (
+ <video
+ src={src}
+ controls
+ preload="metadata"
+ playsInline
+ aria-label={S.chat.videoLabel}
+ className={
+ size === "bubble" ? "max-h-48 max-w-full rounded-md" : "max-h-28 max-w-full rounded-md"
+ }
+ />
+ );
+}
+
/** Countdown floor: waits shorter than this keep the plain waiting text (sub-second flashes of numbers are noise). */
const COUNTDOWN_MIN_MS = 2000;
@@ -261,18 +289,23 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
files: steerFiles,
} = splitAttachments(item.text);
// A steer's own images can be a history page's Trace references: routed to the
- // Session's machine like the user_image below.
+ // Session's machine like the user_image below. Its videos are the same two shapes
+ // (inline bytes, or a `trace-video` reference) and ride the same chip.
const shown = [...steerImages, ...(item.images ?? []).map(routedUrl)];
+ const clips = (item.videos ?? []).map(routedUrl);
return (
<MessageRow spacing="steer">
<MessageBubble
variant="steering"
label={S.chat.userSteering}
- {...(shown.length > 0
+ {...(shown.length > 0 || clips.length > 0
? {
- media: shown.map((src, i) => (
- <MessageImage key={i} src={src} alt={S.chat.imageAlt} size="chip" />
- )),
+ media: [
+ ...shown.map((src, i) => (
+ <MessageImage key={`i${i}`} src={src} alt={S.chat.imageAlt} size="chip" />
+ )),
+ ...clips.map((src, i) => <MessageVideo key={`v${i}`} src={src} size="chip" />),
+ ],
}
: {})}
{...(steerFiles.length > 0
@@ -297,6 +330,18 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
<SentMessageMeta atMs={item.atMs} />
</MessageRow>
);
+ case "user_video":
+ // The same two forms as the image above: inline bytes live, or the page's reference to the
+ // Trace record (`/api/sessions/<id>/trace-video?…`) — tens of megabytes a windowed history
+ // page hands over by URL rather than inlining, fetched from the Session's machine.
+ return (
+ <MessageRow>
+ <MessageBubble variant="image">
+ <MessageVideo src={routedUrl(item.videoUrl)} />
+ </MessageBubble>
+ <SentMessageMeta atMs={item.atMs} />
+ </MessageRow>
+ );
case "assistant_text":
// Doesn't attach MessageMeta: this turn's reply timestamp and copy both belong to the
// stats line right below it (TaskStatsLine) — that line already serves as this reply's
diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsx
index a2437630..50bdd7fc 100644
--- a/packages/web/src/features/chat/message-stream.tsx
+++ b/packages/web/src/features/chat/message-stream.tsx
@@ -153,7 +153,10 @@ export function MessageItems({ items, ctx }: { items: ChatItem[]; ctx: StreamRen
for (let i = 0; i < segs.length; i++) {
const seg = segs[i]!;
const isUserMsg =
- seg.type === "single" && (seg.item.kind === "user_text" || seg.item.kind === "user_image");
+ seg.type === "single" &&
+ (seg.item.kind === "user_text" ||
+ seg.item.kind === "user_image" ||
+ seg.item.kind === "user_video");
if (isUserMsg) {
flushTurn();
// Outline jump anchor, top level only (ctx.origin is empty just for the main
diff --git a/packages/web/src/features/chat/outline-model.ts b/packages/web/src/features/chat/outline-model.ts
index 0a307a54..0362bc06 100644
--- a/packages/web/src/features/chat/outline-model.ts
+++ b/packages/web/src/features/chat/outline-model.ts
@@ -4,8 +4,8 @@
* assistant's reply — for the left quick-jump index. Also owns the outline's display
* math: the minimum-turns gate both shapes share and the tick rail's sliding window.
*
- * Entry boundaries: a turn opens at a user prompt (user_text / user_image) and collects
- * every assistant_text that follows until the next prompt. Consecutive user items merge
+ * Entry boundaries: a turn opens at a user prompt (user_text / user_image / user_video) and
+ * collects every assistant_text that follows until the next prompt. Consecutive user items merge
* into one entry (a prompt's text and images arrive as separate adjacent items — they are
* one question, not several). Machine-only texts never open an entry: handoff /
* model-switch source blocks render as banners with no user prose, and goal rounds past 1
@@ -113,7 +113,7 @@ export function buildOutline(items: readonly ChatItem[]): OutlineEntry[] {
let current: OutlineEntry | null = null;
let lastWasUser = false;
for (const item of items) {
- if (item.kind === "user_text" || item.kind === "user_image") {
+ if (item.kind === "user_text" || item.kind === "user_image" || item.kind === "user_video") {
let body = "";
if (item.kind === "user_text") {
const parsed = parseUserMessageBody(item.text);
diff --git a/packages/web/src/features/chat/queued-summary.ts b/packages/web/src/features/chat/queued-summary.ts
new file mode 100644
index 00000000..979fed18
--- /dev/null
+++ b/packages/web/src/features/chat/queued-summary.ts
@@ -0,0 +1,28 @@
+/**
+ * The one-line summary of a queued message (undelivered steering, or a queued follow-up), shown on
+ * the composer's queued hint lines: its text, then a count for each kind of attachment the text
+ * cannot show (images, videos, files).
+ *
+ * Its own module rather than a local helper in the composer because it is the only place the
+ * counts and their wording meet, and what it must not do is silent: a clip that rode a steered
+ * message is invisible in the text, so a summary that dropped it would leave the user reading a
+ * queued line that names only what they typed.
+ */
+import { S } from "../../lib/strings";
+
+export interface QueuedMessageContent {
+ text: string;
+ images: number;
+ videos: number;
+ files: number;
+}
+
+export function steeringSummary(p: QueuedMessageContent): string {
+ const parts: string[] = [];
+ const line = p.text.replace(/\s+/g, " ").trim();
+ if (line) parts.push(line);
+ if (p.images > 0) parts.push(S.chat.imagesInMessage(p.images));
+ if (p.videos > 0) parts.push(S.chat.videosInMessage(p.videos));
+ if (p.files > 0) parts.push(S.chat.filesInMessage(p.files));
+ return parts.join(" \u00b7 ");
+}
diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsx
index d9183cf8..3fe4f12d 100644
--- a/packages/web/src/features/chat/subagents-view.tsx
+++ b/packages/web/src/features/chat/subagents-view.tsx
@@ -475,6 +475,9 @@ function SubagentComposer({
{...(contextWindow !== undefined ? { contextWindow } : {})}
contextNow={contextNow}
vision={false}
+ // A child's composer takes text only (see the subagent variant): no media intake at all,
+ // so it never needs a video route either.
+ video={false}
approvalMode={approvalMode}
approvalModes={approvalModes}
sandbox={sandbox}
diff --git a/packages/web/src/features/traces/trace-event-row.tsx b/packages/web/src/features/traces/trace-event-row.tsx
index 8d49146f..2dcd6b64 100644
--- a/packages/web/src/features/traces/trace-event-row.tsx
+++ b/packages/web/src/features/traces/trace-event-row.tsx
@@ -39,6 +39,10 @@ const TYPE_ICON: Record<string, string> = {
text: "M8 10h8M8 14h5M21 12a9 9 0 1 1-4-7.5",
thinking: "M9 18h6M10 21h4M12 3a6 6 0 0 0-3 11v2h6v-2a6 6 0 0 0-3-11z",
image_url: "M3 5h18v14H3zM3 15l5-5 4 4 3-3 6 6",
+ // A video record: the camera glyph the composer's video entry uses (a lens body with the
+ // triangular flag), so the same thing looks the same on both surfaces.
+ video_url:
+ "M4 6h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2zM22 8l-6 4 6 4V8z",
inline_data: "M3 5h18v14H3zM3 15l5-5 4 4 3-3 6 6",
tool_call: ICONS.wrench,
tool_call_output: "M4 6l4 4-4 4M12 18h8",
@@ -90,6 +94,10 @@ export function summarizeEvent(msg: OmniMessage): string {
return String(p["thinking"] ?? "").slice(0, 120);
case "image_url":
return "[image]";
+ case "video_url":
+ // The bytes are never summarized: a video is tens of megabytes of base64 and the summary
+ // line only says what kind of record this is.
+ return "[video]";
case "inline_data":
return `[image] ${String(p["mime_type"] ?? "")}`;
case "tool_call":
@@ -362,6 +370,21 @@ function EventBody({ msg }: { msg: OmniMessage }) {
className="max-h-48 max-w-full rounded-md"
/>
);
+ case "video_url":
+ // A clip is played here rather than dumped: without this branch the record falls to the
+ // default JSON dump below and paints its whole base64 payload — tens of megabytes of it —
+ // into the row, which hangs the page rather than showing anything. `preload="metadata"`
+ // keeps a row nobody opened from downloading the clip, and `playsInline` keeps iOS from
+ // taking it fullscreen — the transcript's own player does the same.
+ return (
+ <video
+ controls
+ preload="metadata"
+ playsInline
+ className="max-h-48 max-w-full rounded-md"
+ src={String(p.video_url ?? "")}
+ />
+ );
case "inline_data":
// base64 bytes + mime → render directly as a data URL.
return (
diff --git a/packages/web/src/lib/file-drop.ts b/packages/web/src/lib/file-drop.ts
index 27332ae7..ce753278 100644
--- a/packages/web/src/lib/file-drop.ts
+++ b/packages/web/src/lib/file-drop.ts
@@ -9,8 +9,9 @@
* reason) and dragged page images must never light the overlay;
* - what the chat area's drop zone should do with one drag event (`dropRegionAction`) —
* show the overlay, claim the drag, take the files, or stand aside;
- * - which staged intake a dropped file belongs to (`splitDroppedFiles`) — images join the
- * pasted-image pipeline, everything else joins the file-attachment pipeline;
+ * - which staged intake a dropped file belongs to (`splitMediaFiles`) — images join the
+ * pasted-image pipeline, videos the video one, everything else joins the file-attachment
+ * pipeline;
* - the app-shell fallback (`guardWindowDragOver` / `guardWindowDrop`) — anywhere no drop
* zone claimed the drag, the browser's default is to navigate to the dropped file,
* silently replacing the app; the guard cancels that default for file drags only, so
@@ -106,20 +107,26 @@ export function dropRegionAction(
}
/**
- * Splits one dropped batch into the composer's two intakes, preserving drop order within
- * each: images ride the message as `image_url` parts exactly like pasted images, everything
- * else becomes a file attachment (scratchpad + `[attached file: <path>]` line). Generic over
- * "has a MIME type" so tests don't need a DOM `File`.
+ * Splits one batch by MIME kind, preserving order within each side: images ride the message as
+ * `image_url` parts exactly like pasted images, videos as `video_url` parts (the third intake — a
+ * dropped or pasted clip is staged like an image, sized like neither), everything else becomes a
+ * file attachment (scratchpad + `[attached file: <path>]` line). The drop zone's partition is the
+ * composer's own for every entry point — paste and the two "+" pickers call it too — so a file of
+ * one kind cannot be routed two ways depending on how it arrived. Generic over "has a MIME type" so
+ * tests don't need a DOM `File`.
*/
-export function splitDroppedFiles<T extends { readonly type: string }>(
- dropped: readonly T[],
-): { images: T[]; files: T[] } {
+export function splitMediaFiles<T extends { readonly type: string }>(
+ dropped: Iterable<T>,
+): { images: T[]; videos: T[]; files: T[] } {
const images: T[] = [];
+ const videos: T[] = [];
const files: T[] = [];
for (const item of dropped) {
- (item.type.startsWith("image/") ? images : files).push(item);
+ if (item.type.startsWith("image/")) images.push(item);
+ else if (item.type.startsWith("video/")) videos.push(item);
+ else files.push(item);
}
- return { images, files };
+ return { images, videos, files };
}
/**
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index 78a8e5eb..d3afd845 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -38,7 +38,7 @@
* banner instead (issue #290);
* user text prefixed with `[context_summary]` is a compaction-summary
* injection, treated as internal input (not rendered, doesn't start a new Task).
- * - Task segmentation: a complete text/image message on the main
+ * - Task segmentation: a complete text/image/video message on the main
* session's user side starts a new Task; a Task ends when the live
* stream receives task_state:idle (notifyTaskIdle), or — during history
* rebuild — when the next Task starts / the stream ends
@@ -121,6 +121,12 @@ export interface UserSteeringItem {
* which the chip restores at render time like any user message.)
*/
images?: string[];
+ /**
+ * Videos sent with this steering message, delivered and folded in exactly like the images
+ * above (a model that takes no video input gets the clip as an `[attached file: …]` line
+ * inside `text` instead, so it needs no channel here).
+ */
+ videos?: string[];
/** Message timestamp (milliseconds): shown on footer hover. */
atMs?: number;
}
@@ -151,6 +157,21 @@ export interface UserImageItem {
atMs?: number;
}
+/**
+ * A video the person sent (`video_url`), with the model that takes one: rendered as a bubble of
+ * its own, exactly like `user_image` and for the same reason — it is part of the message, and a
+ * message that is nothing but a clip still opens its own Task. `videoUrl` is inline bytes live, or
+ * a windowed history page's reference to the same Trace record
+ * (`/api/sessions/<id>/trace-video?…`), which the browser fetches from the Session's machine.
+ */
+export interface UserVideoItem {
+ kind: "user_video";
+ id: number;
+ videoUrl: string;
+ /** Message timestamp (milliseconds): shown on footer hover. */
+ atMs?: number;
+}
+
export interface AssistantTextItem {
kind: "assistant_text";
id: number;
@@ -464,6 +485,7 @@ export type ChatItem =
| UserSteeringItem
| BackgroundNoticeItem
| UserImageItem
+ | UserVideoItem
| AssistantTextItem
| ThinkingItem
| ToolCallItem
@@ -540,10 +562,10 @@ export interface StreamModel {
pendingText: AssistantTextItem | null;
pendingThinking: ThinkingItem | null;
/**
- * The steering chip still collecting its images: core delivers a steering message's images
- * as user image messages immediately behind its text, so an image arriving while this is
- * set belongs to that chip. Any other message closes the window (see pushMessage) — an
- * images-only Prompt sent after a steering message is a genuine new Task.
+ * The steering chip still collecting its media: core delivers a steering message's images (and
+ * videos) as user media messages immediately behind its text, so one arriving while this is set
+ * belongs to that chip. Any other message closes the window (see pushMessage) — an images-only
+ * Prompt sent after a steering message is a genuine new Task.
*/
openSteering: UserSteeringItem | null;
/** tool_call_id → tool card (shared by both fragment attribution and complete-message replacement). */
@@ -699,13 +721,16 @@ export function pushMessage(
routeNested(model, msg, nowMs);
return;
}
- // A steering message's images arrive as user image messages directly behind its text, with
- // nothing interleaved (core delivers the batch in one go) — so anything else on this session
- // closes the collection window opened by the chip (see openSteering). Subagent messages
+ // A steering message's images AND videos arrive as user media messages directly behind its text,
+ // with nothing interleaved (core delivers the batch in one go) — so anything else on this
+ // session closes the collection window opened by the chip (see openSteering). Subagent messages
// returned above never reach here, so they leave the window alone.
// The server answers the same "what is one Task" question over the Trace — see
- // `steeringImages` in server/src/services/trace-service.ts; the two need to stay in step.
- if (!isCompleteUserImage(msg)) model.openSteering = null;
+ // `steeringImages` in server/src/services/trace-service.ts — and reaches the same answer for a
+ // video by another route: a video is not one of that window's kinds, but it is not a turn starter
+ // there either, so it lands in the steering message's own turn just the same. Folding it into the
+ // chip keeps this side's grouping (and the clip's own rendering) identical to that.
+ if (!isCompleteUserMedia(msg)) model.openSteering = null;
if (msg.type === "model_msg") {
// Internal messages within a compaction range (between begin and end)
// (the compaction prompt, thinking, summary output): never rendered as transcript items,
@@ -815,9 +840,16 @@ export function pushMessage(
}
}
-/** Whether the message is a complete user image — the only kind that can join an open steering chip. */
-function isCompleteUserImage(msg: OmniMessage): boolean {
- return msg.type === "model_msg" && (msg.payload as { type?: string }).type === "image_url";
+/**
+ * Whether the message is a complete user media (image or video) — the only kinds that can join an
+ * open steering chip. A video joins it on the same terms as an image: both are delivered as user
+ * media messages right behind the steering text, and both are part of that message rather than a
+ * Task of their own.
+ */
+function isCompleteUserMedia(msg: OmniMessage): boolean {
+ if (msg.type !== "model_msg") return false;
+ const type = (msg.payload as { type?: string }).type;
+ return type === "image_url" || type === "video_url";
}
/**
@@ -1405,6 +1437,25 @@ function handleComplete(
});
return;
}
+ case "video_url": {
+ // A video, on a Session whose model takes one, is exactly the image case one line up: a clip
+ // belonging to the steering message just rendered joins that chip, and a Prompt's clip starts
+ // its Task and gets a bubble of its own.
+ if (model.openSteering) {
+ touchTask(model, timestamp);
+ model.openSteering.videos = [...(model.openSteering.videos ?? []), p.video_url];
+ return;
+ }
+ startTask(model, timestamp, nowMs);
+ const videoMs = tsOf(timestamp);
+ model.items.push({
+ kind: "user_video",
+ id: nextId(model),
+ videoUrl: p.video_url,
+ ...(videoMs !== undefined ? { atMs: videoMs } : {}),
+ });
+ return;
+ }
case "thinking": {
touchTask(model, timestamp);
const tsMs = tsOf(timestamp);
@@ -2111,41 +2162,70 @@ function bindSubagent(model: StreamModel, sessionId: string, sub: StreamModel):
// Overlap dedup (connect-first + dedup)
// ---------------------------------------------------------------------------
-/** Stands in for an image's content inside a dedup key (see dedupKey). */
+/** Stands in for an image's content inside a dedup key (see mediaInKey). */
const IMAGE_IN_KEY = "<image>";
+/** The same for a video (see mediaInKey). */
+const VIDEO_IN_KEY = "<video>";
+
+/**
+ * The Trace routes a windowed history page serves one record's bytes on, per media kind: the
+ * record's image, or its video. A page names each of them by one of these instead of carrying the
+ * bytes.
+ */
+const TRACE_MEDIA = {
+ "trace-image": { route: /^\/api\/sessions\/[^/?#]+\/trace-image\?/, key: IMAGE_IN_KEY },
+ "trace-video": { route: /^\/api\/sessions\/[^/?#]+\/trace-video\?/, key: VIDEO_IN_KEY },
+} as const;
/**
- * An image slot's value as the dedup key sees it: inline bytes (`data:`) and a history page's
- * reference to the same Trace record (`/api/sessions/<id>/trace-image?…`) are one image; any
- * other address (a web URL) is kept, since it is the same string in both copies anyway.
+ * A media slot's value as the dedup key sees it: inline bytes (`data:`) and a history page's
+ * reference to the same Trace record (a `trace-image` / `trace-video` URL) are one picture or clip;
+ * any other address (a web URL) is kept, since it is the same string in both copies anyway.
*/
-function imageInKey(value: unknown): unknown {
+function mediaInKey(value: unknown, kind: keyof typeof TRACE_MEDIA): unknown {
if (typeof value !== "string") return value;
- return value.startsWith("data:") || /^\/api\/sessions\/[^/?#]+\/trace-image\?/.test(value)
- ? IMAGE_IN_KEY
- : value;
+ const { route, key } = TRACE_MEDIA[kind];
+ return value.startsWith("data:") || route.test(value) ? key : value;
}
/**
* The envelope a history copy and its SSE copy share. Disk-only transport metadata
- * (`tracePosition`) must not make an otherwise identical SSE envelope look new, and neither
- * may an image's form: a windowed history page carries a user `image_url` and a tool output's
- * `images` by reference while the stream carries the bytes, and an SSE copy that escaped the
- * overlap dedup would draw the person's image twice. Two images of one prompt may then share a
- * key (same timestamp); that is harmless, since a history read holds a prompt whole (the server
- * appends held inputs the Trace lacks), so each stream copy has its own history copy to match.
+ * (`tracePosition`) must not make an otherwise identical SSE envelope look new, and neither may an
+ * image's or a video's form: a windowed history page carries a user `image_url` / `video_url` and a
+ * tool output's `images` by reference while the stream carries the bytes, and an SSE copy that
+ * escaped the overlap dedup would draw the person's image — or download their clip a second time —
+ * twice. Two media of one prompt may then share a key (same timestamp); that is harmless, since a
+ * history read holds a prompt whole (the server appends held inputs the Trace lacks), so each
+ * stream copy has its own history copy to match.
*/
function dedupKey(msg: OmniMessage): string {
const { tracePosition: _tracePosition, ...envelope } = msg as OmniMessage & {
tracePosition?: TracePosition;
};
if (msg.type === "model_msg") {
- const p = msg.payload as { type?: string; image_url?: unknown; images?: unknown };
+ const p = msg.payload as {
+ type?: string;
+ image_url?: unknown;
+ video_url?: unknown;
+ images?: unknown;
+ };
if (p.type === "image_url") {
- return JSON.stringify({ ...envelope, payload: { ...p, image_url: imageInKey(p.image_url) } });
+ return JSON.stringify({
+ ...envelope,
+ payload: { ...p, image_url: mediaInKey(p.image_url, "trace-image") },
+ });
+ }
+ if (p.type === "video_url") {
+ return JSON.stringify({
+ ...envelope,
+ payload: { ...p, video_url: mediaInKey(p.video_url, "trace-video") },
+ });
}
if (p.type === "tool_call_output" && Array.isArray(p.images)) {
- return JSON.stringify({ ...envelope, payload: { ...p, images: p.images.map(imageInKey) } });
+ return JSON.stringify({
+ ...envelope,
+ payload: { ...p, images: p.images.map((image) => mediaInKey(image, "trace-image")) },
+ });
}
}
return JSON.stringify(envelope);
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 970c41df..72b4f6ab 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -3400,8 +3400,12 @@ export const en: Strings = {
reconnectGiveUp: "Give up",
imageAlt: "Image uploaded by user",
toolImageAlt: "Image from tool output",
+ /** Accessible name of a video the person sent (a `<video>` has no `alt`; this is its label). */
+ videoLabel: "Video uploaded by user",
imagesAsPathHint:
"This model cannot view images directly: on send, images are saved to the session scratchpad and passed as file paths (viewed via read_file)",
+ videosAsPathHint:
+ "This model cannot watch videos directly: on send, the clip is saved to the session scratchpad and passed as a file path (viewed via read_file)",
infoPanel: "Session info",
sessionStats: "Stats",
/** Info-dropdown Session id row: the id itself is a click-to-copy button. */
@@ -3442,11 +3446,13 @@ export const en: Strings = {
historyLoadFailed: "Failed to load history",
statsLabel: "Stats",
removeImage: "Remove image",
+ removeVideo: "Remove video",
openAgents: "Agents panel",
/** Panel switcher (chat toolbar top-right): the "create" dropdown and its pin toggles. */
workspacePanel: "Files",
filesInMessage: (n: number) => `${n} ${n === 1 ? "file" : "files"}`,
imagesInMessage: (n: number) => `${n} ${n === 1 ? "image" : "images"}`,
+ videosInMessage: (n: number) => `${n} ${n === 1 ? "video" : "videos"}`,
openPreview: "Click to preview",
showMoreFiles: (n: number) => `Show ${n} more ${n === 1 ? "file" : "files"}`,
showLess: "Show less",
@@ -3688,10 +3694,12 @@ export const en: Strings = {
`Using skill${names.length === 1 ? "" : "s"}: ${names.join(", ")}`,
attachedFilesBanner: (names: string[]): string =>
`Attached file${names.length === 1 ? "" : "s"}: ${names.join(", ")}`,
- /** Composer "+" extension menu (image upload, file attachment, goal mode) and the goal chip. */
+ /** Composer "+" extension menu (image upload, video upload, file attachment, goal mode) and the goal chip. */
plusMenu: "More input options",
uploadImage: "Upload image",
uploadImageDesc: "Attach images to this message",
+ uploadVideo: "Upload video",
+ uploadVideoDesc: "Attach a video to this message",
uploadFile: "Upload file",
uploadFileDesc: "Saved to the session scratchpad; the model reads them by path",
removeFile: "Remove file",
@@ -3699,9 +3707,9 @@ export const en: Strings = {
`${name} exceeds the ${limitMb}MB limit and was not attached.`,
/** Overlay covering the chat area while files are dragged over it (drag-and-drop upload). */
dropFilesTitle: "Drop files to attach",
- dropFilesDesc: "Images and files are added to the message draft",
- /** Toast when non-image files are dropped in goal mode (the objective carries images only). */
- dropFilesGoalHint: "Goal mode takes images only; the files were not attached.",
+ dropFilesDesc: "Images, videos and files are added to the message draft",
+ /** Toast when non-image, non-video files are dropped in goal mode (the objective carries images and videos only). */
+ dropFilesGoalHint: "Goal mode takes images and videos only; the files were not attached.",
/** A paste too long for the text box, attached as a text file instead. */
longPasteAttached: (name: string): string =>
`The pasted text was long, so it was attached as ${name}.`,
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index ef5ddf5f..727bc5bf 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -3441,8 +3441,12 @@ export const zh = {
reconnectGiveUp: "放弃",
imageAlt: "用户上传的图片",
toolImageAlt: "工具输出的图片",
+ /** Accessible name of a video the person sent (a `<video>` has no `alt`; this is its label). */
+ videoLabel: "用户上传的视频",
imagesAsPathHint:
"当前模型不支持直接查看图片:发送时图片将保存到会话临时目录,以文件路径转交(模型经 read_file 查看)",
+ videosAsPathHint:
+ "当前模型不支持直接观看视频:发送时视频将保存到会话临时目录,以文件路径转交(模型经 read_file 查看)",
infoPanel: "Session 信息",
sessionStats: "统计",
/** Info-dropdown Session id row: the id itself is a click-to-copy button. */
@@ -3485,11 +3489,13 @@ export const zh = {
historyLoadFailed: "历史消息加载失败",
statsLabel: "统计信息",
removeImage: "移除图片",
+ removeVideo: "移除视频",
openAgents: "智能体面板",
workspacePanel: "文件浏览",
/** File summary card at the end of a message (Codex-style): title, inline preview action, and collapsed row. */
filesInMessage: (n: number) => `${n} 个文件`,
imagesInMessage: (n: number) => `${n} 张图片`,
+ videosInMessage: (n: number) => `${n} 个视频`,
openPreview: "点击预览",
showMoreFiles: (n: number) => `显示其余 ${n} 个文件`,
showLess: "收起",
@@ -3738,10 +3744,12 @@ export const zh = {
skillsBanner: (names: string[]): string => `使用技能:${names.join("、")}`,
/** Attached-file notice above a user message (file names only; the paths stay in the Trace). */
attachedFilesBanner: (names: string[]): string => `附加文件:${names.join("、")}`,
- /** Composer "+" extension menu (image upload, file attachment, goal mode) and the goal chip. */
+ /** Composer "+" extension menu (image upload, video upload, file attachment, goal mode) and the goal chip. */
plusMenu: "更多输入方式",
uploadImage: "上传图片",
uploadImageDesc: "为本条消息附加图片",
+ uploadVideo: "上传视频",
+ uploadVideoDesc: "为本条消息附加视频",
uploadFile: "上传文件",
uploadFileDesc: "文件存入会话临时目录,模型按路径读取",
removeFile: "移除文件",
@@ -3753,9 +3761,9 @@ export const zh = {
`${name} 超过 ${limitMb}MB 上限,未添加。`,
/** Overlay covering the chat area while files are dragged over it (drag-and-drop upload). */
dropFilesTitle: "松开以添加附件",
- dropFilesDesc: "图片与文件将添加到输入框",
- /** Toast when non-image files are dropped in goal mode (the objective carries images only). */
- dropFilesGoalHint: "目标模式仅支持附加图片,文件未添加。",
+ dropFilesDesc: "图片、视频与文件将添加到输入框",
+ /** Toast when non-image, non-video files are dropped in goal mode (the objective carries images and videos only). */
+ dropFilesGoalHint: "目标模式仅支持附加图片与视频,文件未添加。",
/** A paste too long for the text box, attached as a text file instead. */
longPasteAttached: (name: string): string => `粘贴的文本较长,已作为附件 ${name} 添加。`,
goalMode: "目标模式",
diff --git a/packages/web/src/lib/video-input.ts b/packages/web/src/lib/video-input.ts
new file mode 100644
index 00000000..da6876fb
--- /dev/null
+++ b/packages/web/src/lib/video-input.ts
@@ -0,0 +1,140 @@
+/**
+ * The composer's video draft, and the two shapes a staged video takes on the wire.
+ *
+ * A video is the third thing the "+" menu, a drop and a paste can stage, and it differs from the
+ * other two in the one place everything else follows from: how it reaches the model depends on the
+ * Session's own model. A model that takes video input gets the clip inline, as a user video
+ * message it can actually watch; any other model gets it as an ordinary file attachment — written
+ * into the scratchpad next to the message's `[attached file: <path>]` line, exactly like a file —
+ * because a video is megabytes of base64 and a request the provider would refuse is worse than one
+ * the model opens by path. A *task* leaves that decision to the server (a `video_url` part is never
+ * refused for it); a *steer* does not — the server refuses an inline video on a model that takes
+ * none — so the composer has to pick the field itself (see steerVideoFields).
+ *
+ * Its ceiling is its own as well: `uploadLimits.videoMaxMb`, between an image's and a file's, the
+ * provider's own video limit with base64's 4/3 accounted for.
+ *
+ * DOM-free and free of React: what reads the files is the composer, what the draft holds and what a
+ * send turns it into is decided here.
+ */
+import type { TaskInputPart } from "@adelie/server/api";
+
+/**
+ * One video staged in the composer. Deliberately the same shape as a file attachment — the chip
+ * shows the picked name and size, `dataUrl` is what is sent — and under the same non-copying rule:
+ * the string a 32MB clip produces is held once, exactly as it was read, and everything below hands
+ * that reference on instead of re-encoding or slicing it.
+ */
+export interface ComposerVideo {
+ name: string;
+ size: number;
+ dataUrl: string;
+}
+
+/**
+ * Approximate decoded byte size of a base64 data URL. Display only — it feeds a chip's size line
+ * (a recalled video's, or a recalled file attachment's) and never a limit check. An address with no
+ * data body to measure (a web URL) reports nothing rather than a number derived from the address's
+ * own characters.
+ */
+export function dataUrlBytes(dataUrl: string): number {
+ const comma = dataUrl.indexOf(",");
+ if (!dataUrl.startsWith("data:") || comma < 0) return 0;
+ const body = dataUrl.slice(comma + 1).replace(/[=\s]+/g, "");
+ return Math.floor((body.length * 3) / 4);
+}
+
+/** File extensions for the video types the composer accepts, by media type. */
+const VIDEO_EXTENSIONS: Record<string, string> = {
+ "video/mp4": "mp4",
+ "video/quicktime": "mov",
+ "video/webm": "webm",
+ "video/x-matroska": "mkv",
+ "video/x-msvideo": "avi",
+};
+
+/**
+ * The name a video is filed under in the draft, derived from its address alone.
+ *
+ * A data URL carries no name at all (the file was read into bytes and pasted into the string), so
+ * it is named after its own media type — the same fallback the server uses for a nameless video, so
+ * an mp4 reads as `video.mp4` on both sides. An http(s) address usually names the clip in its last
+ * path segment; a bare host, a directory or a query-only address names nothing and gets the same
+ * bare `video`.
+ */
+export function videoNameForUrl(url: string): string {
+ const data = /^data:([^;,]*)/.exec(url);
+ if (data !== null) {
+ const extension = VIDEO_EXTENSIONS[data[1]!.trim().toLowerCase()];
+ return extension === undefined ? "video" : `video.${extension}`;
+ }
+ // Past the protocol and the host: what names a file is the path, and `https://example.com` has
+ // none (its last "segment" is the host name, which is no more a file name than the URL is).
+ const path = (url.split(/[?#]/)[0] ?? "").replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i, "");
+ const last = path.slice(path.lastIndexOf("/") + 1);
+ if (last === "") return "video";
+ try {
+ return decodeURIComponent(last);
+ } catch {
+ return last; // A malformed escape is not a reason to lose the name.
+ }
+}
+
+/**
+ * A video URL as a draft entry — how a recall restores the clips of a withdrawn message, whose
+ * `RecalledMessageResponse.videos` are URLs and nothing else (unlike a file attachment, a video's
+ * bytes are inlined in the message, so the round trip has no scratchpad copy to read them back
+ * from). A web address reports no size rather than a wrong one: this end cannot measure it.
+ */
+export function videoFromUrl(url: string): ComposerVideo {
+ return {
+ name: videoNameForUrl(url),
+ size: url.startsWith("data:") ? dataUrlBytes(url) : 0,
+ dataUrl: url,
+ };
+}
+
+/**
+ * Appends a draft's media to a task input — images first (in pick order), then videos, then files.
+ * One place, because every send path submits the same draft: the normal send, the follow-up queue,
+ * the @ handoff and the `/model` switch. The order is the chip row's, top to bottom, so a message
+ * reads the way the composer did.
+ */
+export function appendMediaParts(
+ input: TaskInputPart[],
+ images: readonly string[],
+ videos: readonly ComposerVideo[],
+ files: readonly { name: string; dataUrl: string }[],
+): void {
+ for (const url of images) input.push({ type: "image_url", imageUrl: url });
+ for (const video of videos) {
+ // `fileName` only decides what the clip is called where it lands; the server sanitizes it.
+ input.push({ type: "video_url", videoUrl: video.dataUrl, fileName: video.name });
+ }
+ for (const file of files) {
+ input.push({ type: "file", fileName: file.name, dataUrl: file.dataUrl });
+ }
+}
+
+/** A steering message's video fields: exactly one of the two is set (neither for no videos). */
+export interface SteerVideoFields {
+ /** Inline clips: for a Session whose model takes video input (POST /steer's `videos`). */
+ videos?: string[];
+ /** The same clips as ordinary file attachments: for a model that takes none, which would refuse `videos`. */
+ files?: { fileName: string; dataUrl: string }[];
+}
+
+/**
+ * Which field a steered draft's videos go into, decided by the Session's model — the one case where
+ * the composer has to make the inline-or-scratchpad call itself, because the steer route rejects an
+ * inline video outright on a model that takes none rather than filing it away as a task does. The
+ * clips are listed before any file attachments, matching the order a task's parts travel in.
+ */
+export function steerVideoFields(
+ videos: readonly ComposerVideo[],
+ takesVideo: boolean,
+): SteerVideoFields {
+ if (videos.length === 0) return {};
+ if (takesVideo) return { videos: videos.map((video) => video.dataUrl) };
+ return { files: videos.map((video) => ({ fileName: video.name, dataUrl: video.dataUrl })) };
+}
diff --git a/packages/web/src/state/auth.tsx b/packages/web/src/state/auth.tsx
index 85479e35..0a6e9109 100644
--- a/packages/web/src/state/auth.tsx
+++ b/packages/web/src/state/auth.tsx
@@ -22,6 +22,7 @@ const DEFAULT_UPLOAD_LIMITS: UploadLimits = {
attachmentTotalMb: 120,
attachmentMaxCount: 20,
imageMaxMb: 20,
+ videoMaxMb: 32,
attachmentLimitMinMb: 1,
attachmentLimitMaxMb: 200,
};
diff --git a/packages/web/test/agent-topology.test.ts b/packages/web/test/agent-topology.test.ts
index 63d4860e..76d00f9e 100644
--- a/packages/web/test/agent-topology.test.ts
+++ b/packages/web/test/agent-topology.test.ts
@@ -24,6 +24,7 @@ import {
toolCall,
toolCallOutput,
userText,
+ videoUrlMessage,
withOrigin,
} from "@adelie/core/omnimessage";
import type { OmniMessage, SessionMetaPayload } from "@adelie/core/omnimessage";
@@ -438,15 +439,19 @@ describe("per-node elapsed time (wall clock of the spawn, never a sum of items)"
});
describe("identity helpers", () => {
- it("latestTaskStart finds the last user_text/user_image and falls back to 0 (user items only — steering never starts a Task)", () => {
+ it("latestTaskStart finds the last user_text/user_image/user_video and falls back to 0 (user items only — steering never starts a Task)", () => {
const m = createStreamModel();
pushMessage(m, assistantText("orphan"));
expect(latestTaskStart(m.items)).toBe(0);
pushMessage(m, userText("t1"));
expect(latestTaskStart(m.items)).toBe(1);
+ pushMessage(m, videoUrlMessage("data:video/mp4;base64,v"));
+ // The clip opens the latest Task (the previous Task's closing stats row sits between, which is
+ // why the index is not one past the text item).
+ expect(m.items[latestTaskStart(m.items)]!.kind).toBe("user_video");
});
- it("taskStartCount counts Task-starting user items (text and image); steering chips never count", () => {
+ it("taskStartCount counts Task-starting user items (text, image and video); steering chips never count", () => {
const m = createStreamModel();
expect(taskStartCount(m.items)).toBe(0);
pushMessage(m, userText("t1"));
@@ -464,6 +469,14 @@ describe("identity helpers", () => {
expect(taskStartCount(m.items)).toBe(2);
pushMessage(m, userText("t3"));
expect(taskStartCount(m.items)).toBe(3);
+ // A video follows the same rule as an image: behind a steering message it joins that chip
+ // (nothing starts), on its own it starts a Task.
+ pushMessage(m, userText("[user_steering]\nagain\n[/user_steering]"));
+ pushMessage(m, videoUrlMessage("data:video/mp4;base64,steered"));
+ expect(taskStartCount(m.items)).toBe(3);
+ pushMessage(m, assistantText("r3"));
+ pushMessage(m, videoUrlMessage("data:video/mp4;base64,vv"));
+ expect(taskStartCount(m.items)).toBe(4);
});
it("agentIdFromStatePath takes the parent directory name; degenerate paths give null", () => {
diff --git a/packages/web/test/composer-send.test.ts b/packages/web/test/composer-send.test.ts
index 5ac40d14..a8b0c93f 100644
--- a/packages/web/test/composer-send.test.ts
+++ b/packages/web/test/composer-send.test.ts
@@ -23,6 +23,7 @@ const BASE: MidRunComposerState = {
hasPendingModel: false,
hasText: true,
hasImages: false,
+ hasVideos: false,
hasFiles: false,
hasContent: true,
};
@@ -30,13 +31,23 @@ const BASE: MidRunComposerState = {
const act = (over: Partial<MidRunComposerState> = {}) => midRunAction({ ...BASE, ...over });
/** The draft shapes that carry nothing at all. */
-const EMPTY = { hasText: false, hasImages: false, hasFiles: false, hasContent: false } as const;
+const EMPTY = {
+ hasText: false,
+ hasImages: false,
+ hasVideos: false,
+ hasFiles: false,
+ hasContent: false,
+} as const;
describe("midRunAction — steering, the preferred channel", () => {
- it("takes text, images, files, or any of them with no caption at all", () => {
+ it("takes text, images, videos, files, or any of them with no caption at all", () => {
expect(act()).toBe("steer");
expect(act({ hasText: false, hasImages: true })).toBe("steer");
expect(act({ hasText: true, hasImages: true })).toBe("steer");
+ // A clip steers like an image does, inline or as a scratchpad file depending on the model
+ // (the composer hands the whole draft over; the branch that picks the field is the host's).
+ expect(act({ hasText: false, hasVideos: true })).toBe("steer");
+ expect(act({ hasText: true, hasVideos: true })).toBe("steer");
// A file-only draft steers exactly like an image-only one (#140) — no silent fallback
// to the queue, which used to answer it with the other channel's hint.
expect(act({ hasText: false, hasFiles: true })).toBe("steer");
diff --git a/packages/web/test/file-drop.test.ts b/packages/web/test/file-drop.test.ts
index b45f4b90..03de1bed 100644
--- a/packages/web/test/file-drop.test.ts
+++ b/packages/web/test/file-drop.test.ts
@@ -1,7 +1,8 @@
/**
* Drag-and-drop upload logic (lib/file-drop.ts): what counts as a file drag, what the chat
- * area's drop zone does with one drag event, how a dropped batch splits across the composer's
- * two intakes, and the app-shell guard that cancels the browser's navigate-to-file default.
+ * area's drop zone does with one drag event, how a batch splits across the composer's three
+ * intakes (images, videos, files), and the app-shell guard that cancels the browser's
+ * navigate-to-file default.
*
* The region decision is the part that earns the tests, because it is where the feature's
* scope lives: the overlay and the attachment happen only while the drag is over the chat
@@ -16,7 +17,7 @@ import {
guardWindowDragOver,
guardWindowDrop,
isFileDrag,
- splitDroppedFiles,
+ splitMediaFiles,
} from "../src/lib/file-drop";
import type { DragGuardEvent, DragSignal } from "../src/lib/file-drop";
@@ -132,22 +133,33 @@ describe("dropRegionAction", () => {
});
});
-describe("splitDroppedFiles", () => {
- it("routes by MIME type: image/* to the image intake, everything else to attachments", () => {
+describe("splitMediaFiles", () => {
+ it("routes by MIME type: image/* to the image intake, video/* to the video one, everything else to attachments", () => {
const png = { type: "image/png", name: "a.png" };
const pdf = { type: "application/pdf", name: "b.pdf" };
const svg = { type: "image/svg+xml", name: "c.svg" };
+ const clip = { type: "video/mp4", name: "d.mp4" };
const none = { type: "", name: "Makefile" }; // OS gives some files no MIME type at all
- const { images, files } = splitDroppedFiles([png, pdf, svg, none]);
+ const { images, videos, files } = splitMediaFiles([png, pdf, svg, clip, none]);
expect(images).toEqual([png, svg]);
+ expect(videos).toEqual([clip]);
expect(files).toEqual([pdf, none]);
});
it("keeps drop order within each intake and handles an empty batch", () => {
const a = { type: "text/plain" };
const b = { type: "application/zip" };
- expect(splitDroppedFiles([a, b]).files).toEqual([a, b]);
- expect(splitDroppedFiles([])).toEqual({ images: [], files: [] });
+ expect(splitMediaFiles([a, b]).files).toEqual([a, b]);
+ expect(splitMediaFiles([])).toEqual({ images: [], videos: [], files: [] });
+ });
+
+ it("keeps the clips in the order they arrived, among the pictures of the same batch", () => {
+ const first = { type: "video/quicktime", name: "1.mov" };
+ const png = { type: "image/png", name: "2.png" };
+ const second = { type: "video/webm", name: "3.webm" };
+ const { videos, images } = splitMediaFiles([first, png, second]);
+ expect(videos).toEqual([first, second]);
+ expect(images).toEqual([png]);
});
});
diff --git a/packages/web/test/icon-registry.test.ts b/packages/web/test/icon-registry.test.ts
index 5320b633..33ee5568 100644
--- a/packages/web/test/icon-registry.test.ts
+++ b/packages/web/test/icon-registry.test.ts
@@ -27,6 +27,10 @@ const WEB = SCAN.files.filter((file) => file.root === "web");
const ALLOWLIST: Readonly<Record<string, readonly [number, string]>> = {
"components/layout/sidebar.tsx": [2, "W7"],
"features/chat/attached-files-banner.tsx": [1, "W6"],
+ // The composer's video entry (a lens body with the triangular flag): the icon set has no video
+ // glyph, and the traces row draws the same shape in its own type map (an object property, so it
+ // is not counted here).
+ "features/chat/chat-input.tsx": [1, "W10"],
"features/chat/conversation-outline.tsx": [1, "W6"],
"features/chat/goal-use.ts": [1, "W6"],
"features/chat/memory-view.tsx": [3, "W6"],
diff --git a/packages/web/test/model-grouping.test.ts b/packages/web/test/model-grouping.test.ts
index d95c4a39..0b8391bf 100644
--- a/packages/web/test/model-grouping.test.ts
+++ b/packages/web/test/model-grouping.test.ts
@@ -109,6 +109,7 @@ describe("groupModelRows", () => {
"baidu",
"tencent",
"iflytek",
+ "volcengine",
"qwen-pay-as-you-go",
"qwen-token-plan",
"modelscope",
diff --git a/packages/web/test/outline-model.test.ts b/packages/web/test/outline-model.test.ts
index b4fa6ef2..b614b5f0 100644
--- a/packages/web/test/outline-model.test.ts
+++ b/packages/web/test/outline-model.test.ts
@@ -32,6 +32,7 @@ const harness = (text: string): ChatItem => ({
sender: "harness",
});
const image = (): ChatItem => ({ kind: "user_image", id: nextId++, imageUrl: "blob:x" });
+const video = (): ChatItem => ({ kind: "user_video", id: nextId++, videoUrl: "blob:v" });
const steering = (text: string): ChatItem => ({ kind: "user_steering", id: nextId++, text });
const assistant = (text: string, streaming = false): ChatItem => ({
kind: "assistant_text",
@@ -63,11 +64,17 @@ describe("buildOutline", () => {
expect(outline[0]!.anchorId).toBe((items[0] as { id: number }).id);
});
- it("merges adjacent user items into one entry and labels image-only prompts with an empty question", () => {
- const items: ChatItem[] = [image(), user("text after images"), assistant("ok"), image()];
+ it("merges adjacent user items into one entry and labels media-only prompts with an empty question", () => {
+ const items: ChatItem[] = [
+ image(),
+ video(),
+ user("text after media"),
+ assistant("ok"),
+ video(),
+ ];
const outline = buildOutline(items);
expect(outline).toHaveLength(2);
- expect(outline[0]).toMatchObject({ question: "text after images", answer: "ok" });
+ expect(outline[0]).toMatchObject({ question: "text after media", answer: "ok" });
expect(outline[1]).toMatchObject({ question: "", answer: "" });
});
diff --git a/packages/web/test/queued-summary.test.ts b/packages/web/test/queued-summary.test.ts
new file mode 100644
index 00000000..fdccee65
--- /dev/null
+++ b/packages/web/test/queued-summary.test.ts
@@ -0,0 +1,37 @@
+/**
+ * The queued-message summary line (features/chat/queued-summary.ts): what a "steering queued" or
+ * "follow-up queued" hint shows for a message whose content the text alone does not describe.
+ *
+ * The counts are the whole point — a clip that rode a steered message is invisible in its text, and
+ * a summary that dropped it would leave the user reading a queued line about a message that was
+ * more than what they see. Written against the live dictionary rather than a literal, like the
+ * rest of the copy: the wording is S's to change.
+ */
+import { describe, expect, it } from "vitest";
+import { steeringSummary } from "../src/features/chat/queued-summary";
+import { S } from "../src/lib/strings";
+
+const summary = (over: Partial<Parameters<typeof steeringSummary>[0]> = {}) =>
+ steeringSummary({ text: "", images: 0, videos: 0, files: 0, ...over });
+
+describe("steeringSummary", () => {
+ it("leads with the text, one line's worth", () => {
+ expect(summary({ text: " hold on\nplease " })).toBe("hold on please");
+ });
+
+ it("names each kind of attachment the text cannot show, in one line", () => {
+ expect(summary({ text: "look", images: 2, videos: 1, files: 3 })).toBe(
+ `look \u00b7 ${S.chat.imagesInMessage(2)} \u00b7 ${S.chat.videosInMessage(1)} \u00b7 ${S.chat.filesInMessage(3)}`,
+ );
+ });
+
+ it("shows a clip count on its own — a video-only steer is a complete message", () => {
+ expect(summary({ videos: 2 })).toBe(S.chat.videosInMessage(2));
+ });
+
+ it("leaves out the kinds the message does not carry", () => {
+ expect(summary({ text: "hi", images: 0, videos: 0, files: 0 })).toBe("hi");
+ expect(summary({ text: "hi", videos: 0 })).toBe("hi");
+ expect(summary()).toBe("");
+ });
+});
diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.ts
index 71529c01..3a120e43 100644
--- a/packages/web/test/stream-controller.test.ts
+++ b/packages/web/test/stream-controller.test.ts
@@ -247,11 +247,14 @@ describe("in-stream task_state is the authoritative running state (history-closi
h.controller.handleServer({
type: "task_state",
state: "running",
- pendingSteering: [{ id: "st-1", text: "hold on", images: 0, files: 1 }],
+ pendingSteering: [{ id: "st-1", text: "hold on", images: 0, videos: 1, files: 1 }],
});
// A later event without the field means "none left" — reported as empty, not skipped.
h.controller.handleServer({ type: "task_state", state: "running" });
- expect(h.pendingSteering).toEqual([[{ id: "st-1", text: "hold on", images: 0, files: 1 }], []]);
+ expect(h.pendingSteering).toEqual([
+ [{ id: "st-1", text: "hold on", images: 0, videos: 1, files: 1 }],
+ [],
+ ]);
});
it("reports steering the run handed back, so the composer can take it into its draft", async () => {
@@ -261,11 +264,14 @@ describe("in-stream task_state is the authoritative running state (history-closi
h.controller.handleServer({
type: "task_state",
state: "idle",
- returnedSteering: [{ id: "st-1", text: "wait", images: 0, files: 1 }],
+ returnedSteering: [{ id: "st-1", text: "wait", images: 0, videos: 0, files: 1 }],
});
// Once the composer has taken it, the next event omits the field — reported as empty.
h.controller.handleServer({ type: "task_state", state: "idle" });
- expect(h.returnedSteering).toEqual([[{ id: "st-1", text: "wait", images: 0, files: 1 }], []]);
+ expect(h.returnedSteering).toEqual([
+ [{ id: "st-1", text: "wait", images: 0, videos: 0, files: 1 }],
+ [],
+ ]);
});
it("reports the queued follow-up list from task_state, and its absence as empty", async () => {
@@ -275,11 +281,11 @@ describe("in-stream task_state is the authoritative running state (history-closi
type: "task_state",
state: "running",
queued: 1,
- pendingFollowUps: [{ id: "fu-1", text: "next up", images: 1, files: 0 }],
+ pendingFollowUps: [{ id: "fu-1", text: "next up", images: 1, videos: 0, files: 0 }],
});
h.controller.handleServer({ type: "task_state", state: "running" });
expect(h.pendingFollowUps).toEqual([
- [{ id: "fu-1", text: "next up", images: 1, files: 0 }],
+ [{ id: "fu-1", text: "next up", images: 1, videos: 0, files: 0 }],
[],
]);
});
diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.ts
index 44ee6b2c..6873a7e3 100644
--- a/packages/web/test/stream-model.test.ts
+++ b/packages/web/test/stream-model.test.ts
@@ -62,6 +62,7 @@ import {
toolCall,
toolCallOutput,
userText,
+ videoUrlMessage,
withOrigin,
} from "@adelie/core/omnimessage";
import type { OmniMessage, SessionMetaPayload, TokenCounts } from "@adelie/core/omnimessage";
@@ -1483,6 +1484,21 @@ describe("Task segmentation and stats triggering", () => {
expect(stats.stats!.tokensDelta).toBe(600);
});
+ it("a full video_url message renders its own bubble and also starts a new Task", () => {
+ // A clip on a model that takes one is the image case in another medium: a message the person
+ // sent, so it draws itself and it opens the Task a clip-only Prompt would otherwise lack.
+ const m = createStreamModel();
+ pushMessage(m, tokenUsage(counts(100), counts(100))); // outside the Task boundary
+ pushMessage(m, videoUrlMessage("data:video/mp4;base64,xx"));
+ pushMessage(m, tokenUsage(counts(700), counts(600)));
+ notifyTaskIdle(m);
+ expect(items(m).map((i) => i.kind)).toEqual(["user_video", "task_stats"]);
+ const video = items(m)[0]!;
+ expect(video.kind === "user_video" && video.videoUrl).toBe("data:video/mp4;base64,xx");
+ const stats = items(m).find((i) => i.kind === "task_stats") as TaskStatsItem;
+ expect(stats.stats!.tokensDelta).toBe(600);
+ });
+
it("manual compaction usage between Tasks is not misattributed to the next Task's delta", () => {
const m = createStreamModel();
pushMessage(m, at(userText("one"), "2026-07-05T00:00:00.000Z"));
@@ -2205,6 +2221,59 @@ describe("compaction-internal messages (#17: history rebuild aligned with the li
expect(steering.images).toEqual(["data:image/png;base64,AAAA"]);
expect(items(m).filter((i) => i.kind === "user_image")).toHaveLength(0);
});
+
+ it("videos sent with a steering message join its chip too; a later standalone video starts a Task", () => {
+ // Core delivers a steering message's videos as user video messages right behind its text (and
+ // behind its images), which is exactly how its images arrive. They belong to that chip — no
+ // bubble of their own and, crucially, no new Task, which is also what the server's own Trace
+ // grouping concludes for a video (it is not a turn starter there). A clip arriving after
+ // something else is an ordinary Prompt again, exactly as for an image.
+ const m = createStreamModel();
+ pushMessages(m, [
+ at(userText("fix the bug"), "2026-07-05T00:00:00.000Z"),
+ at(assistantText("looking"), "2026-07-05T00:00:02.000Z"),
+ at(userText("[user_steering]\nwatch this\n[/user_steering]"), "2026-07-05T00:00:04.000Z"),
+ at(imageUrlMessage("data:image/png;base64,AAAA"), "2026-07-05T00:00:04.100Z"),
+ at(videoUrlMessage("data:video/mp4;base64,AAAA"), "2026-07-05T00:00:04.200Z"),
+ at(assistantText("watching"), "2026-07-05T00:00:06.000Z"),
+ at(tokenUsage(counts(200), counts(100)), "2026-07-05T00:00:07.000Z"),
+ // A new Prompt that is nothing but a clip: a Task of its own.
+ at(videoUrlMessage("data:video/mp4;base64,BBBB"), "2026-07-05T00:00:20.000Z"),
+ at(assistantText("on it"), "2026-07-05T00:00:22.000Z"),
+ ]);
+ finalizeHistory(m);
+ expect(items(m).map((i) => i.kind)).toEqual([
+ "user_text",
+ "assistant_text",
+ "user_steering",
+ "assistant_text",
+ "task_stats",
+ "user_video",
+ "assistant_text",
+ "task_stats",
+ ]);
+ const steering = items(m).find((i) => i.kind === "user_steering") as UserSteeringItem;
+ expect(steering.text).toBe("watch this");
+ expect(steering.images).toEqual(["data:image/png;base64,AAAA"]);
+ expect(steering.videos).toEqual(["data:video/mp4;base64,AAAA"]);
+ });
+
+ it("closes the steering window like it does for images: an interleaved message ends the collection", () => {
+ // The window is "media delivered in one go right behind the text". Anything else in between
+ // means the clip that follows is a Prompt's, not the chip's — the same rule the images obey,
+ // and the same one the server's turn grouping applies.
+ const m = createStreamModel();
+ pushMessages(m, [
+ at(userText("fix the bug"), "2026-07-05T00:00:00.000Z"),
+ at(userText("[user_steering]\nlook\n[/user_steering]"), "2026-07-05T00:00:02.000Z"),
+ at(assistantText("ok"), "2026-07-05T00:00:03.000Z"),
+ at(videoUrlMessage("data:video/mp4;base64,AAAA"), "2026-07-05T00:00:04.000Z"),
+ ]);
+ finalizeHistory(m);
+ const steering = items(m).find((i) => i.kind === "user_steering") as UserSteeringItem;
+ expect(steering.videos).toBeUndefined();
+ expect(items(m).filter((i) => i.kind === "user_video")).toHaveLength(1);
+ });
});
describe("elapsed comes from Trace timestamps (#5/#20: settled spans, reload-stable live anchor)", () => {
diff --git a/packages/web/test/transcript-videos.test.ts b/packages/web/test/transcript-videos.test.ts
new file mode 100644
index 00000000..df747cce
--- /dev/null
+++ b/packages/web/test/transcript-videos.test.ts
@@ -0,0 +1,106 @@
+/**
+ * The videos in a conversation, and where the browser fetches them from (react-dom/server static
+ * markup, node env, no DOM) — the video counterpart of transcript-images.test.ts.
+ *
+ * A windowed history page carries each Trace video by reference (`/api/sessions/<id>/trace-video?…`),
+ * because a clip is tens of megabytes: the browser follows that `<video src>` itself, so `routedUrl`
+ * has to send it to the machine the Session lives on. A video that arrived inline (live, or a
+ * steering message's) renders from its own bytes.
+ *
+ * Also pinned here: the element is `controls` with `preload="metadata"` — it is meant to be played,
+ * and it must not download a clip nobody opened.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { MessageStream } from "../src/features/chat/message-stream";
+import type { StreamRenderContext } from "../src/features/chat/message-stream";
+import type { ChatItem } from "../src/lib/omni/stream-model";
+import { forgetSessionMachines, rememberSessionMachine } from "../src/lib/session-machines";
+import { LocaleProvider } from "../src/state/locale";
+import { stubLocalStorage } from "./helpers/storage";
+
+beforeEach(() => {
+ stubLocalStorage().setItem("penguin.lang", "en");
+});
+afterEach(() => forgetSessionMachines());
+
+const ctx: StreamRenderContext = {
+ pendingApprovals: new Map(),
+ onApprove: async () => {},
+ origin: [],
+ taskRunning: false,
+};
+
+/** The `<video>` tags a stream of these items renders. */
+function videoTags(items: ChatItem[]): string[] {
+ const html = renderToStaticMarkup(
+ createElement(
+ LocaleProvider,
+ null,
+ createElement(MessageStream, { items, version: 1, ctx, onAddExcerpt: () => {} }),
+ ),
+ );
+ return html.match(/<video\b[^>]*>/g) ?? [];
+}
+
+const ref = (sessionId: string) => `/api/sessions/${sessionId}/trace-video?file=2&amp;ordinal=8`;
+
+describe("transcript videos", () => {
+ it("plays a referenced clip of a Session on another machine from that machine", () => {
+ rememberSessionMachine("s-remote", "M1");
+ const tags = videoTags([
+ {
+ kind: "user_video",
+ id: 1,
+ videoUrl: "/api/sessions/s-remote/trace-video?file=2&ordinal=8",
+ },
+ ]);
+ expect(tags).toHaveLength(1);
+ expect(tags[0]).toContain(`src="/server/M1${ref("s-remote")}"`);
+ });
+
+ it("plays a referenced clip of a Session on this server as written", () => {
+ const tags = videoTags([
+ { kind: "user_video", id: 1, videoUrl: "/api/sessions/s-local/trace-video?file=2&ordinal=8" },
+ ]);
+ expect(tags[0]).toContain(`src="${ref("s-local")}"`);
+ });
+
+ it("is a playable element that fetches nothing until it is opened", () => {
+ const tags = videoTags([{ kind: "user_video", id: 1, videoUrl: "data:video/mp4;base64,AAAA" }]);
+ // Controls: the clip is meant to be watched. Metadata only: a clip nobody presses play on must
+ // not download. playsInline: a phone must not throw it into fullscreen.
+ expect(tags[0]).toContain("controls");
+ expect(tags[0]).toContain('preload="metadata"');
+ expect(tags[0]).toMatch(/playsinline/i);
+ // And nothing plays on its own, and nothing is muted: a transcript never makes noise by itself,
+ // but a clip somebody chose to play is theirs to hear.
+ expect(tags[0]).not.toContain("autoplay");
+ expect(tags[0]).not.toContain("muted");
+ });
+
+ it("renders a clip that arrived inline from its own bytes", () => {
+ rememberSessionMachine("s-remote", "M1");
+ const bytes = "data:video/mp4;base64,AAAA";
+ const tags = videoTags([{ kind: "user_video", id: 1, videoUrl: bytes }]);
+ expect(tags[0]).toContain(`src="${bytes}"`);
+ });
+
+ it("carries a steered clip inside its steering chip, routed like a user_video", () => {
+ rememberSessionMachine("s-remote", "M1");
+ const tags = videoTags([
+ { kind: "user_text", id: 1, text: "start" },
+ {
+ kind: "user_steering",
+ id: 2,
+ text: "watch this too",
+ videos: ["/api/sessions/s-remote/trace-video?file=2&ordinal=8"],
+ },
+ ]);
+ expect(tags).toHaveLength(1);
+ expect(tags[0]).toContain(`src="/server/M1${ref("s-remote")}"`);
+ // The chip is still a chip: the steered text is there beside the clip.
+ expect(tags[0]).toBeTruthy();
+ });
+});
diff --git a/packages/web/test/video-input.test.ts b/packages/web/test/video-input.test.ts
new file mode 100644
index 00000000..14e2a26f
--- /dev/null
+++ b/packages/web/test/video-input.test.ts
@@ -0,0 +1,134 @@
+/**
+ * The video draft's wire shapes (lib/video-input.ts): what a staged clip's data URL is derived
+ * from when only a URL comes back, what a task input ends up carrying, and which of the two
+ * shapes a steered clip takes.
+ *
+ * The steer branch is the one with two answers, and the reason this module exists: the server
+ * refuses an inline video on a model that takes none — rather than filing it into the scratchpad
+ * as a task's `video_url` part is filed — so the composer has to choose the field, and choosing
+ * wrong is either a 400 or a clip the model never sees. Everything else here is about the names
+ * and sizes a recalled clip's chip can honestly show.
+ */
+import { describe, expect, it } from "vitest";
+import type { TaskInputPart } from "@adelie/server/api";
+import {
+ appendMediaParts,
+ dataUrlBytes,
+ steerVideoFields,
+ videoFromUrl,
+ videoNameForUrl,
+} from "../src/lib/video-input";
+import type { ComposerVideo } from "../src/lib/video-input";
+
+const MP4 = "data:video/mp4;base64,AAAA";
+const clip = (name: string, dataUrl = MP4): ComposerVideo => ({ name, size: 100, dataUrl });
+
+describe("dataUrlBytes", () => {
+ it("counts the decoded bytes of a data URL's payload", () => {
+ // "AAAA" is 4 base64 chars = 3 bytes; padding is not bytes.
+ expect(dataUrlBytes("data:video/mp4;base64,AAAA")).toBe(3);
+ expect(dataUrlBytes("data:image/png;base64,AAA=")).toBe(2);
+ // Anything without a comma body has nothing to measure.
+ expect(dataUrlBytes("https://example.com/clip.mp4")).toBe(0);
+ });
+});
+
+describe("videoNameForUrl", () => {
+ it("names an unnamed (data:) clip after its own media type, like the server does", () => {
+ expect(videoNameForUrl(MP4)).toBe("video.mp4");
+ expect(videoNameForUrl("data:video/quicktime;base64,AAAA")).toBe("video.mov");
+ expect(videoNameForUrl("data:video/webm;base64,AAAA")).toBe("video.webm");
+ // A type the list does not know still gets a usable name rather than an extension-less one.
+ expect(videoNameForUrl("data:video/ogg;base64,AAAA")).toBe("video");
+ expect(videoNameForUrl("data:;base64,AAAA")).toBe("video");
+ });
+
+ it("takes an http(s) clip's own last path segment", () => {
+ expect(videoNameForUrl("https://example.com/media/clip.mp4")).toBe("clip.mp4");
+ // Query strings and fragments are not the name, and escapes are decoded.
+ expect(videoNameForUrl("https://example.com/a/b/clip.mp4?token=x#t=1")).toBe("clip.mp4");
+ expect(videoNameForUrl("https://example.com/my%20clip.mov")).toBe("my clip.mov");
+ // A bare directory or host names nothing: fall back to the same bare name.
+ expect(videoNameForUrl("https://example.com/")).toBe("video");
+ expect(videoNameForUrl("https://example.com")).toBe("video");
+ });
+});
+
+describe("videoFromUrl — a recalled clip back in the draft", () => {
+ it("moves the bytes through untouched and reports the size a chip can show", () => {
+ const restored = videoFromUrl(MP4);
+ // The same string, not a re-encode: a clip is tens of megabytes.
+ expect(restored.dataUrl).toBe(MP4);
+ expect(restored.name).toBe("video.mp4");
+ expect(restored.size).toBe(3);
+ });
+
+ it("reports no size for a web address it cannot measure", () => {
+ const restored = videoFromUrl("https://example.com/clip.mp4");
+ expect(restored.size).toBe(0);
+ expect(restored.name).toBe("clip.mp4");
+ });
+});
+
+describe("appendMediaParts — what a task's input carries", () => {
+ const parts = (
+ images: string[],
+ videos: ComposerVideo[],
+ files: { name: string; dataUrl: string }[],
+ ) => {
+ const input: TaskInputPart[] = [{ type: "text", text: "look" }];
+ appendMediaParts(input, images, videos, files);
+ return input;
+ };
+
+ it("appends images, then videos (with the picked name), then files", () => {
+ expect(
+ parts(
+ ["data:image/png;base64,AAAA"],
+ [clip("holiday.mp4")],
+ [{ name: "notes.txt", dataUrl: "data:text/plain;base64,AAAA" }],
+ ),
+ ).toEqual([
+ { type: "text", text: "look" },
+ { type: "image_url", imageUrl: "data:image/png;base64,AAAA" },
+ { type: "video_url", videoUrl: MP4, fileName: "holiday.mp4" },
+ { type: "file", fileName: "notes.txt", dataUrl: "data:text/plain;base64,AAAA" },
+ ]);
+ });
+
+ it("sends the clip's data URL by reference and in pick order", () => {
+ const first = clip("1.mp4");
+ const second = clip("2.mp4");
+ const input = parts([], [first, second], []).slice(1); // past the text part
+ expect(input.map((p) => (p.type === "video_url" ? p.videoUrl : ""))).toEqual([MP4, MP4]);
+ // The URL the part carries IS the staged string (no copy was made on the way).
+ expect((input[0] as { videoUrl: string }).videoUrl).toBe(first.dataUrl);
+ expect((input[1] as { fileName?: string }).fileName).toBe("2.mp4");
+ });
+
+ it("adds nothing for an empty draft", () => {
+ expect(parts([], [], [])).toEqual([{ type: "text", text: "look" }]);
+ });
+});
+
+describe("steerVideoFields — the one branch the composer has to choose", () => {
+ it("sends the clips inline on a model that takes video input", () => {
+ expect(steerVideoFields([clip("a.mp4"), clip("b.mp4")], true)).toEqual({
+ videos: [MP4, MP4],
+ });
+ });
+
+ it("hands them over as file attachments on a model that takes none, names kept", () => {
+ // The server refuses `videos` on such a model (the steer route is not the task route: it has
+ // no scratchpad fallback of its own), so the clip must arrive as a file — with the name the
+ // user's pick had, because that is what it is filed under on disk.
+ expect(steerVideoFields([clip("holiday.mp4")], false)).toEqual({
+ files: [{ fileName: "holiday.mp4", dataUrl: MP4 }],
+ });
+ });
+
+ it("sets neither field for a steer that carries no clip", () => {
+ expect(steerVideoFields([], true)).toEqual({});
+ expect(steerVideoFields([], false)).toEqual({});
+ });
+});
diff --git a/patches/@prismshadow__agenthub.patch b/patches/@prismshadow__agenthub.patch
new file mode 100644
index 00000000..18031b38
--- /dev/null
+++ b/patches/@prismshadow__agenthub.patch
@@ -0,0 +1,50 @@
+diff --git a/dist/openai_chat/client.js b/dist/openai_chat/client.js
+index e30bbde48d56cdfac092f66699b09cc48aa73fb0..8fd57e3bc9de05faeba76925a038eb1afa73ba5d 100644
+--- a/dist/openai_chat/client.js
++++ b/dist/openai_chat/client.js
+@@ -202,6 +202,14 @@ class OpenaiChatClient extends baseClient_1.LLMClient {
+ const base64Image = await this._convertImageUrlToBase64(item.image_url, signal);
+ contentParts.push(this._convertImageUrl(base64Image));
+ }
++ else if (item.type === "video_url") {
++ // A video rides as the `video_url` content part, whose `url` upstream reads as
++ // either a public URL or a base64 `data:` URL. Unlike an image the bytes are
++ // NOT re-encoded here: a video is three orders of magnitude larger, and the
++ // caller already hands one of those two forms (a local file it base64-encoded
++ // itself, or a URL the provider can fetch).
++ contentParts.push({ type: "video_url", video_url: { url: item.video_url } });
++ }
+ else if (item.type === "thinking") {
+ thinking += item.thinking;
+ thinkingFields.add(item.fidelity?.reasoning_field);
+diff --git a/dist/types.d.ts b/dist/types.d.ts
+index d44652521470e65da55e049f38d9032b99ff4236..9261c83dbf6defc53dcb0ed858f3fb2289981454 100644
+--- a/dist/types.d.ts
++++ b/dist/types.d.ts
+@@ -39,6 +39,17 @@ export interface ImageContentItem {
+ type: "image_url";
+ image_url: string;
+ }
++/**
++ * A video, as the upstream reads one: a URL or a base64 `data:` URL. Only the
++ * OpenAI-compatible Chat Completions client maps it (to the `video_url` content
++ * part Ark and a few others accept); a client that does not know the item rejects
++ * the message rather than dropping the video silently, so a caller sends one only
++ * where the upstream takes it.
++ */
++export interface VideoContentItem {
++ type: "video_url";
++ video_url: string;
++}
+ export interface InlineDataContentItem {
+ type: "inline_data";
+ data: Buffer;
+@@ -81,7 +92,7 @@ export interface EmbeddingContentItem {
+ type: "embedding";
+ embedding: number[];
+ }
+-export type ContentItem = TextContentItem | ImageContentItem | InlineDataContentItem | ThinkingContentItem | InlineThinkingContentItem | ToolCallContentItem | ToolResultContentItem | EmbeddingContentItem;
++export type ContentItem = TextContentItem | ImageContentItem | VideoContentItem | InlineDataContentItem | ThinkingContentItem | InlineThinkingContentItem | ToolCallContentItem | ToolResultContentItem | EmbeddingContentItem;
+ export type PartialContentItem = ContentItem | PartialToolCallContentItem;
+ /**
+ * Usage metadata for model response.
diff --git a/plugins/README.md b/plugins/README.md
index c6e4cc02..4746fe18 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`, `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`, `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-seedance/LICENSE b/plugins/use-seedance/LICENSE
new file mode 100644
index 00000000..261eeb9e
--- /dev/null
+++ b/plugins/use-seedance/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-seedance/README.md b/plugins/use-seedance/README.md
new file mode 100644
index 00000000..d96197f6
--- /dev/null
+++ b/plugins/use-seedance/README.md
@@ -0,0 +1,68 @@
+# Seedance 视频生成(`@adelie/use-seedance`)
+
+一句话:**把提示词交给火山方舟的豆包 Seedance,拿回一个 mp4,落在工作区里。**
+
+运行时就一个零依赖的 Node 文件(`skills/seedance/kit/seedance.mjs`)。它替 Agent 走完视频生成
+的**异步三步**——提交任务、轮询到终态、把视频下载到本地:
+
+```
+POST /contents/generations/tasks 提交 → 拿任务 id(cgt-…)
+GET /contents/generations/tasks/{id} 轮询 → succeeded 时才带回 content.video_url
+下载 video_url → 先写临时文件,下完了才改名
+```
+
+端点默认 `https://ark.cn-beijing.volces.com/api/v3`,鉴权是 `Authorization: Bearer $ARK_API_KEY`;
+**密钥只从环境读**(Agent 的密钥库注入),脚本不写盘,也不留下别的痕迹。
+
+## 用
+
+```bash
+node skills/seedance/kit/seedance.mjs --prompt "一只猫对着镜头打哈欠" --out cat.mp4
+```
+
+stderr 是给人看的进度行,**stdout 只有一行 JSON**,路径、字节数、任务 id、耗时都在里面:
+
+```json
+{"ok":true,"path":"/abs/cat.mp4","bytes":2314213,"task_id":"cgt-…","model":"doubao-seedance-2-5-260628","video_url":"https://…","elapsed_ms":74210}
+```
+
+参数:`--out`(默认 `./seedance-<时间戳>.mp4`)、`--model`(默认 `doubao-seedance-2-5-260628`)、
+`--image` / `--last-frame` / `--reference-image`(首帧 / 尾帧 / 参考图,可给本机文件或 URL)、
+`--duration`、`--ratio`、`--resolution`、`--seed`、`--watermark`、`--generate-audio`、
+`--poll-interval`(默认 5 秒,退避到 20)、`--max-wait`(默认 900 秒)。**没传的参数不发给服务**,
+所以模型自己的默认值说了算;未知参数直接报错,不会悄悄忽略。
+
+退出码把结果分了类:`0` 成功;`2` 命令行不对;`3` 缺 `ARK_API_KEY`;`4` 接口拒了请求(`upstream`
+里是服务原话);`5` 任务以 `failed`/`cancelled`/`expired` 结束;`6` 超过 `--max-wait` 还没完
+(任务仍在服务端跑,`task_id` 可以晚点再查,别重复提交);`7` 视频没下下来。
+
+## 文件
+
+| 路径 | 是什么 |
+| --- | --- |
+| `skills/seedance/kit/seedance.mjs` | 全部运行时:参数、提交、轮询、下载、一行 JSON |
+| `skills/seedance/SKILL.md` | Agent 读的说明书:什么时候用、参数、错误码怎么处理、产物怎么给用户看 |
+| `test/seedance.test.mjs` | 八条自检,桩服务冒充方舟,不用密钥也不花钱 |
+| `plugin.json` / `package.json` / `icon.svg` / `LICENSE` | 插件清单、包信息、图标、Apache-2.0 |
+
+## 测试
+
+```bash
+node --test "plugins/use-seedance/test/*.test.mjs" # 或在包目录里 pnpm test
+```
+
+桩(`test/` 里那个 `http.createServer`)冒充方舟:提交返回任务 id,查询第一次 `running`、第二次
+`succeeded` 并给本地 mp4,于是整条路——提交 → 轮询 → 下载 → 改名——都在本机跑完,并断言密钥只发往
+接口、不发给视频 URL(真实的任务返回的是签名链接)。**它验的是脚本自己的行为,不是真实响应的形状**:
+真实方舟的成功响应长什么样只能靠文档,想真跑一次需要账号已开通 Seedance 并且愿意付费。
+
+关键接口改动时以官网为准:
+[创建视频生成任务](https://docs.volcengine.com/docs/ark/create-video-generation-task-api?lang=zh)、
+[查询视频生成任务](https://docs.volcengine.com/docs/ark/get-video-generation-task-api?lang=zh)、
+[模型列表](https://docs.volcengine.com/docs/ark/model-list?lang=zh)。
+
+## 还没验的
+
+- 真实方舟的一次完整成功(需要已开通的账号与付费额度)。
+- 首尾帧 / 全模态参考这些组合参数在真实模型上的取值约束(脚本只按文档传 `role`,参数合规交服务判)。
+- Windows 上的路径与 base64 参考图(本机是 Linux,只验了 Linux)。
diff --git a/plugins/use-seedance/icon.svg b/plugins/use-seedance/icon.svg
new file mode 100644
index 00000000..b854313a
--- /dev/null
+++ b/plugins/use-seedance/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">
+ <path d="M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z" />
+ <path d="m6.2 5.3 3.1 3.9" />
+ <path d="m12.4 3.4 3.1 4" />
+ <path d="M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z" />
+</svg>
diff --git a/plugins/use-seedance/package.json b/plugins/use-seedance/package.json
new file mode 100644
index 00000000..1266bde5
--- /dev/null
+++ b/plugins/use-seedance/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "@adelie/use-seedance",
+ "version": "0.5.6",
+ "description": "Generate a video from a prompt with Volcengine Ark's Doubao Seedance models and save it into the workspace — one dependency-free Node script over the asynchronous video-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-seedance"
+ },
+ "keywords": [
+ "adelie-plugin",
+ "penguin-harness",
+ "video",
+ "seedance",
+ "doubao",
+ "volcengine",
+ "ark"
+ ],
+ "files": [
+ "plugin.json",
+ "icon.svg",
+ "README.md",
+ "skills",
+ "LICENSE"
+ ],
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/plugins/use-seedance/plugin.json b/plugins/use-seedance/plugin.json
new file mode 100644
index 00000000..1c693cae
--- /dev/null
+++ b/plugins/use-seedance/plugin.json
@@ -0,0 +1,8 @@
+{
+ "description": "Generate a video from a prompt with Volcengine Ark's Doubao Seedance models and save it into the workspace. One dependency-free Node script drives the asynchronous video-generation API — submit the task, poll it with a bounded wait and a backing-off interval, then stream the result through a temporary file so a half-written video never wears the final name — and prints one line of JSON with the absolute path, the task id and the elapsed time. The API key comes from the vault as ARK_API_KEY and is never written to disk.",
+ "description_zh": "用火山方舟的豆包 Seedance 模型把提示词生成成视频,落到工作区。运行时是一个零依赖的 Node 脚本,走视频生成的异步任务接口:提交任务、在最大等待时长内按退避间隔轮询、把结果先落到临时文件再改名,最后打一行 JSON,给出绝对路径、任务 id 与耗时。密钥从密钥库以 ARK_API_KEY 注入,不落盘。",
+ "short_description": "Generate a video from a prompt with Ark Doubao Seedance, saved into the workspace.",
+ "short_description_zh": "用火山方舟豆包 Seedance 按提示词生成视频并落到工作区。",
+ "version": "2026.10.26.1",
+ "category": "office-productivity"
+}
diff --git a/plugins/use-seedance/skills/seedance/SKILL.md b/plugins/use-seedance/skills/seedance/SKILL.md
new file mode 100644
index 00000000..3e0a06b0
--- /dev/null
+++ b/plugins/use-seedance/skills/seedance/SKILL.md
@@ -0,0 +1,147 @@
+---
+name: seedance
+description: Generate a video from a prompt with Volcengine Ark's Doubao Seedance models — submit an asynchronous video-generation task, poll it, and save the resulting mp4 into the workspace, driven by a vault-stored API key.
+---
+
+# Seedance (Doubao video generation)
+
+Volcengine Ark's video generation API turns a prompt — and, if you have them, reference images —
+into an mp4. It is **asynchronous**: you submit a task, get a task id back, and poll that task until
+it succeeds; only then does the answer carry the video's URL. `kit/seedance.mjs` is one
+dependency-free Node script that does all three steps and saves the video into the workspace, so a
+single command covers the whole job.
+
+```
+POST /contents/generations/tasks -> { "id": "cgt-…" }
+GET /contents/generations/tasks/{id} -> { "status": "…", "content": { "video_url": … } }
+```
+
+## Before you start
+
+If the message only names this skill (e.g. "use seedance") with no video to make, ask what the
+video should show — and, when the answer sounds like it wants a specific look, offer to generate
+from a still the user already has (a reference image) rather than from text alone.
+
+**A take costs money.** Video generation is billed by the second and the resolution, so the prompt
+is worth a glance before it is submitted: read it back to the user when the request was vague, and
+do not send 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/seedance.mjs --prompt "<what the video should show>" --out <name>.mp4
+```
+
+The script prints progress lines on stderr and **one line of JSON on stdout**:
+
+```json
+{"ok":true,"path":"/abs/path/<name>.mp4","bytes":2314213,"task_id":"cgt-…","model":"doubao-seedance-2-5-260628","video_url":"https://…","elapsed_ms":74210}
+```
+
+`--out` defaults to `seedance-<UTC timestamp>.mp4` in the working directory, and the video is
+written through a temporary file that only gets its final name once the download finished — so a
+half-written file never looks like a complete video. Read `path` (absolute) out of the JSON rather
+than rebuilding the name yourself.
+
+Options:
+
+| Option | Meaning |
+| --- | --- |
+| `--prompt <text>` | required; Chinese up to ~500 characters, English up to ~1000 words |
+| `--out <path>` | where to save the mp4 (default: `./seedance-<timestamp>.mp4`) |
+| `--model <id>` | Ark Model ID (default `doubao-seedance-2-5-260628`) |
+| `--image <url\|path>` | first-frame image: an http(s)/data URL, or a local file inlined as base64 |
+| `--last-frame <url\|path>` | last-frame image; needs `--image` (the pair is 首尾帧) |
+| `--reference-image <url\|path>` | reference image, repeatable (Seedance 2.5 全模态参考) |
+| `--duration <seconds>` | 4–30s on Seedance 2.5, 4–15s on the 2.0 line; the service default when omitted |
+| `--ratio <ratio>` | e.g. `16:9`, `9:16`, `1:1`, `adaptive` |
+| `--resolution <size>` | `480p`, `720p`, `1080p` |
+| `--seed <integer>` | fix the take, for a result you can reproduce |
+| `--watermark` | keep the service watermark (otherwise it is the service default) |
+| `--generate-audio` | let the model generate the soundtrack |
+| `--poll-interval <seconds>` | first gap between polls (default 5, backing off to 20) |
+| `--max-wait <seconds>` | give up after this long (default 900) |
+
+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.
+
+An example with a still the user already has as the first frame, a 16:9 take:
+
+```bash
+node <skill dir>/kit/seedance.mjs \
+ --prompt "the cat stretches and looks into the camera, camera slowly pulls back" \
+ --image ~/pictures/cat.jpg --duration 5 --ratio 16:9 --resolution 720p \
+ --out cat-stretch.mp4
+```
+
+## Statuses, waits and failures
+
+The task's `status` is one of `queued`, `running`, `cancelled`, `succeeded`, `failed`, `expired`.
+The script polls until a terminal one, and its exit code says which way it ended:
+
+| Code | Meaning | What to do |
+| --- | --- | --- |
+| 0 | `succeeded`, video saved | read `path` from the JSON |
+| 2 | bad command line | fix the flags; the message says which one |
+| 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 OperationDenied.ServiceNotOpen` → the model is not activated for this account; `403 …ServiceOverdue`/`AccountOverdueError` → 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 |
+| 5 | the task ended as `failed`, `cancelled` or `expired` — `error_code` and `error.message` carry the service's reason | report it; a task-type complaint usually means the prompt and the images disagree about what kind of task this is |
+| 6 | still `queued`/`running` after `--max-wait` | the task keeps running on the service: the JSON carries `task_id`, and the task record survives 7 days, so poll it later instead of resubmitting and paying again |
+| 7 | the video did not download | the URL the task returned (valid 24 hours) is unreachable or refused; nothing is left at the output path |
+
+Never retry a submission on a failure you do not understand — a paid task may already be running.
+Raise `--max-wait` for a long prompt (a 10-second 1080p take commonly takes minutes), and read the
+`upstream` field before saying anything about the cause.
+
+## Handing the result to the user
+
+The chat does not play video, so give the user the file, not a base64 blob:
+
+- Save it into the workspace (the default output already does) and name it in your reply by its
+ workspace-relative path in backticks, with the size and the model that made it.
+- If a still would help them decide, extract one frame next to it and offer that as the preview:
+ `ffmpeg -y -i <file>.mp4 -frames:v 1 <file>-frame.png` (ffmpeg, when it is installed). Take the
+ first frame rather than seeking — a `-ss` past the end of a short take writes nothing and still
+ exits 0, which reads as success until nobody finds the file.
+- Keep the `task_id` in your reply when the take is one they may want redone: the same seed plus the
+ same options is a reproducible take.
+
+## The three interfaces behind the script
+
+All under `https://ark.cn-beijing.volces.com/api/v3`, authenticated with
+`Authorization: Bearer $ARK_API_KEY`:
+
+- **Submit** — `POST /contents/generations/tasks` with `{"model": …, "content": [{"type": "text",
+ "text": …}, {"type": "image_url", "image_url": {"url": …}, "role": …}]}` and optional
+ `duration` / `ratio` / `resolution` / `seed` / `watermark` / `generate_audio`. Answers the task id
+ and nothing else.
+- **Query** — `GET /contents/generations/tasks/{id}`; on success `content.video_url` holds the mp4
+ (valid **24 hours**, and Seedance 2.5's URLs allow at most 100 downloads), and `content.last_frame_url`
+ appears only if the task asked for `return_last_frame`.
+- **Cancel / delete and list** — `DELETE /contents/generations/tasks/{id}` cancels a `queued` task
+ (it becomes `cancelled`) and deletes the record of a `succeeded`, `failed` or `expired` one; a
+ `running` task cannot be stopped through it. `GET /contents/generations/tasks` lists recent tasks
+ in `items[]`. The script does not use these; reach for them with curl when a job must be stopped or
+ its history inspected:
+ https://docs.volcengine.com/docs/ark/cancel-or-delete-video-generation-tasks-api?lang=zh
+
+Model IDs, the per-model option ranges and the error catalogue live in the docs, which are the
+source of truth for anything this file does not state:
+https://docs.volcengine.com/docs/ark/create-video-generation-task-api?lang=zh,
+https://docs.volcengine.com/docs/ark/get-video-generation-task-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-seedance/skills/seedance/kit/seedance.mjs b/plugins/use-seedance/skills/seedance/kit/seedance.mjs
new file mode 100644
index 00000000..edea9458
--- /dev/null
+++ b/plugins/use-seedance/skills/seedance/kit/seedance.mjs
@@ -0,0 +1,409 @@
+#!/usr/bin/env node
+/**
+ * Generate a video with Volcengine Ark's Doubao Seedance models and save it into the workspace.
+ *
+ * One non-interactive run: prompt in, mp4 out. It submits an asynchronous task, polls it until
+ * the service reports a terminal status — `--max-wait` is a hard ceiling and the poll interval
+ * backs off, so a queued task can never hang the call — then downloads the result through a
+ * temporary file and renames it into place, so a half-written video never wears the final name.
+ *
+ * node seedance.mjs --prompt "..." [--out video.mp4] [--model doubao-seedance-2-5-260628]
+ * [--image <url|path>] [--last-frame <url|path>] [--reference-image <url|path>]
+ * [--duration 5] [--ratio 16:9] [--resolution 720p] [--seed 11]
+ * [--watermark] [--generate-audio] [--poll-interval 5] [--max-wait 900]
+ *
+ * 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
+ * 5 the task ended badly | 6 the task did not finish in time | 7 the video 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/create-video-generation-task-api?lang=zh
+ * https://docs.volcengine.com/docs/ark/get-video-generation-task-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 Seedance 2.5 — the current Seedance Model ID (docs: model-list / seedance-2-5). */
+const DEFAULT_MODEL = "doubao-seedance-2-5-260628";
+const DEFAULT_POLL_SECONDS = 5;
+const MAX_POLL_SECONDS = 20;
+const DEFAULT_MAX_WAIT_SECONDS = 900;
+/** Task statuses that end a poll: `succeeded` is the good one, these are the rest. */
+const FAILED_STATUSES = new Set(["failed", "cancelled", "expired"]);
+/** 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, task: 5, timeout: 6, download: 7 };
+
+const USAGE = `Generate a video with Doubao Seedance and save it into the workspace.
+
+ node seedance.mjs --prompt "..." [options]
+
+ --prompt <text> what the video should show (required)
+ --out <path> where to save the mp4 (default ./seedance-<timestamp>.mp4)
+ --model <id> Ark Model ID (default ${DEFAULT_MODEL})
+ --image <url|path> first-frame image, local file or http(s)/data URL
+ --last-frame <url|path> last-frame image (needs --image: the pair is 首尾帧)
+ --reference-image <url|path> reference image (repeatable; Seedance 2.5 全模态参考)
+ --duration <seconds> video length, e.g. 5 (model default when omitted)
+ --ratio <ratio> e.g. 16:9, 9:16, 1:1, adaptive
+ --resolution <size> e.g. 480p, 720p, 1080p
+ --seed <integer> fixed seed for a reproducible take
+ --watermark keep the service watermark
+ --generate-audio let the model generate the soundtrack
+ --poll-interval <seconds> first wait between polls (default ${DEFAULT_POLL_SECONDS}, backs off to ${MAX_POLL_SECONDS})
+ --max-wait <seconds> give up after this long (default ${DEFAULT_MAX_WAIT_SECONDS})
+ --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 },
+ "last-frame": { takes: true, repeat: true },
+ "reference-image": { takes: true, repeat: true },
+ duration: { takes: true },
+ ratio: { takes: true },
+ resolution: { takes: true },
+ seed: { takes: true },
+ watermark: { takes: false },
+ "generate-audio": { takes: false },
+ "poll-interval": { takes: true },
+ "max-wait": { takes: true },
+ 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);
+}
+
+function numberArg(args, name, fallback) {
+ const raw = args[name];
+ if (raw === undefined) return fallback;
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value <= 0)
+ throw new UsageError(`"--${name}" needs a positive number, got "${raw}"`);
+ 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).
+ */
+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")}`;
+}
+
+/** Input content list: the prompt, then whichever images were asked for, each with its role. */
+function buildContent(args) {
+ const content = [{ type: "text", text: args.prompt }];
+ const images = [
+ ...(args.image ?? []).map((spec) => ({ option: "image", role: "first_frame", spec })),
+ ...(args["last-frame"] ?? []).map((spec) => ({
+ option: "last-frame",
+ role: "last_frame",
+ spec,
+ })),
+ ...(args["reference-image"] ?? []).map((spec) => ({
+ option: "reference-image",
+ role: "reference_image",
+ spec,
+ })),
+ ];
+ if (images.some((image) => image.role === "last_frame") && !(args.image ?? []).length)
+ throw new UsageError(
+ `"--last-frame" is the second of a pair: pass the first frame with "--image"`,
+ );
+ for (const image of images)
+ content.push({
+ type: "image_url",
+ image_url: { url: imageFor(image.spec, image.option) },
+ role: image.role,
+ });
+ return content;
+}
+
+/** An integer passthrough: a typo is a bad command line, not a body the service has to reject. */
+function integerArg(args, name) {
+ 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]}"`);
+ return value;
+}
+
+/** The task body: only the options actually given, so the service's own defaults stand. */
+function buildBody(args, model, content) {
+ const body = { model, content };
+ const duration = integerArg(args, "duration");
+ const seed = integerArg(args, "seed");
+ if (duration !== undefined) body.duration = duration;
+ if (args.ratio !== undefined) body.ratio = args.ratio;
+ if (args.resolution !== undefined) body.resolution = args.resolution;
+ if (seed !== undefined) body.seed = seed;
+ if (args.watermark) body.watermark = true;
+ if (args["generate-audio"]) body.generate_audio = 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 JSON.parse(text);
+ } catch {
+ fail(EXIT.upstream, "api_error", {
+ message: `${what} failed: the service answered something that is not JSON`,
+ status: res.status,
+ upstream: text,
+ });
+ }
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+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`);
+ const 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 pollSeconds = numberArg(args, "poll-interval", DEFAULT_POLL_SECONDS);
+ const maxWaitMs = numberArg(args, "max-wait", DEFAULT_MAX_WAIT_SECONDS) * 1000;
+ const body = buildBody(args, model, buildContent({ ...args, prompt }));
+ 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 submission = await apiJson(
+ `${baseUrl}/contents/generations/tasks`,
+ {
+ method: "POST",
+ headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
+ body: JSON.stringify(body),
+ },
+ "creating the video generation task",
+ );
+ const taskId = submission?.id;
+ if (typeof taskId !== "string" || taskId === "")
+ fail(EXIT.upstream, "api_error", {
+ message: "creating the video generation task failed: the answer carried no task id",
+ upstream: JSON.stringify(submission),
+ });
+ say(`task ${taskId} submitted`);
+
+ // Poll until the service reports a terminal status; the wait is bounded both ways — the whole
+ // call by --max-wait, and the gap between polls by a backing-off interval up to MAX_POLL_SECONDS.
+ let intervalMs = pollSeconds * 1000;
+ for (let attempt = 1; ; attempt++) {
+ const task = await apiJson(
+ `${baseUrl}/contents/generations/tasks/${encodeURIComponent(taskId)}`,
+ { headers: { authorization: `Bearer ${apiKey}` } },
+ `polling task ${taskId}`,
+ );
+ const status = typeof task?.status === "string" ? task.status : "unknown";
+ say(`poll ${attempt}: ${status} (${Math.round((Date.now() - startedAt) / 1000)}s)`);
+
+ if (status === "succeeded") {
+ const videoUrl = task?.content?.video_url;
+ if (typeof videoUrl !== "string" || videoUrl === "")
+ fail(EXIT.task, "no_video_url", {
+ message: `task ${taskId} succeeded but the answer carried no content.video_url`,
+ task_id: taskId,
+ upstream: JSON.stringify(task),
+ });
+
+ const out = path.resolve(
+ args.out ?? `seedance-${new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)}.mp4`,
+ );
+ const part = `${out}.part-${process.pid}`;
+ fs.mkdirSync(path.dirname(out), { recursive: true });
+ say(`downloading into ${out}`);
+
+ let video;
+ try {
+ video = await fetch(videoUrl);
+ } catch (err) {
+ fail(EXIT.download, "download_error", {
+ message: `downloading the video failed: cannot reach the URL the task returned — ${err.message}`,
+ task_id: taskId,
+ video_url: videoUrl,
+ upstream: err.message,
+ });
+ }
+ if (!video.ok || video.body === null) {
+ const raw = await video.text().catch(() => "");
+ fail(EXIT.download, "download_error", {
+ message: `downloading the video failed: HTTP ${video.status} from the URL the task returned`,
+ task_id: taskId,
+ video_url: videoUrl,
+ upstream: raw,
+ });
+ }
+
+ let bytes;
+ try {
+ await pipeline(Readable.fromWeb(video.body), fs.createWriteStream(part));
+ bytes = fs.statSync(part).size;
+ if (bytes === 0) throw new Error("the downloaded file is empty");
+ } catch (err) {
+ // The temporary file goes away with the failure: only a complete download gets renamed.
+ fs.rmSync(part, { force: true });
+ fail(EXIT.download, "download_error", {
+ message: `saving the video failed: ${err.message}`,
+ task_id: taskId,
+ video_url: videoUrl,
+ upstream: err.message,
+ });
+ }
+ fs.renameSync(part, out);
+ process.stdout.write(
+ `${JSON.stringify({
+ ok: true,
+ path: out,
+ bytes,
+ task_id: taskId,
+ model: task?.model ?? model,
+ video_url: videoUrl,
+ elapsed_ms: Date.now() - startedAt,
+ })}\n`,
+ );
+ return 0;
+ }
+
+ if (FAILED_STATUSES.has(status))
+ fail(EXIT.task, "task_failed", {
+ message: `task ${taskId} ended as ${status}: ${task?.error?.message ?? "(no message)"}`,
+ task_id: taskId,
+ status,
+ error_code: task?.error?.code ?? null,
+ upstream: JSON.stringify(task),
+ });
+
+ const left = maxWaitMs - (Date.now() - startedAt);
+ if (left <= 0)
+ fail(EXIT.timeout, "timeout", {
+ message: `task ${taskId} was still ${status} after ${Math.round(maxWaitMs / 1000)}s; it keeps running on the service — poll it later with GET ${baseUrl}/contents/generations/tasks/${encodeURIComponent(taskId)}`,
+ task_id: taskId,
+ status,
+ });
+ await sleep(Math.min(intervalMs, left));
+ intervalMs = Math.min(intervalMs * 1.5, MAX_POLL_SECONDS * 1000);
+ }
+}
+
+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-seedance/test/seedance.test.mjs b/plugins/use-seedance/test/seedance.test.mjs
new file mode 100644
index 00000000..3e6f08db
--- /dev/null
+++ b/plugins/use-seedance/test/seedance.test.mjs
@@ -0,0 +1,315 @@
+/**
+ * The kit's checks: a stub Ark stands in for the real service, so the whole path — submit, poll,
+ * download, name the file — runs here without an API key and without spending anything.
+ *
+ * node --test plugins/use-seedance/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 follows the documented status values to a terminal one,
+ * that it bounds its polling, that it writes the bytes it downloaded and names them only once the
+ * download finished, and that each failure path exits non-zero with 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 { createHash } from "node:crypto";
+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",
+ "seedance",
+ "kit",
+ "seedance.mjs",
+);
+
+/** A byte string standing in for an mp4: the test only cares that the bytes survive the trip. */
+const VIDEO = Buffer.concat([
+ Buffer.from([0x00, 0x00, 0x00, 0x18]),
+ Buffer.from("ftypisom"),
+ Buffer.from("a seedance video that never was\n"),
+]);
+
+const sha = (buf) => createHash("sha256").update(buf).digest("hex");
+
+/** The stub Ark: submit answers a task id, the first poll is running, the second succeeds. */
+async function startStub({ statuses = ["running", "succeeded"], taskError } = {}) {
+ // `authorizations` covers the API routes only: the video URL is fetched without a key, the
+ // way a real task's signed URL is, so that it is recorded separately.
+ const seen = {
+ submits: 0,
+ polls: 0,
+ authorizations: [],
+ bodies: [],
+ videoAuthorization: undefined,
+ };
+ let poll = 0;
+ const server = http.createServer((req, res) => {
+ const url = new URL(req.url, "http://stub");
+ if (url.pathname.startsWith("/api/v3")) seen.authorizations.push(req.headers.authorization);
+ else seen.videoAuthorization = req.headers.authorization;
+ const json = (code, value) => {
+ res.writeHead(code, { "content-type": "application/json" });
+ res.end(JSON.stringify(value));
+ };
+ if (req.method === "POST" && url.pathname === "/api/v3/contents/generations/tasks") {
+ let body = "";
+ req.on("data", (chunk) => (body += chunk));
+ req.on("end", () => {
+ seen.submits++;
+ seen.bodies.push(JSON.parse(body));
+ json(200, { id: "cgt-stub-0001" });
+ });
+ return;
+ }
+ if (
+ req.method === "GET" &&
+ url.pathname === "/api/v3/contents/generations/tasks/cgt-stub-0001"
+ ) {
+ seen.polls++;
+ const status = statuses[Math.min(poll++, statuses.length - 1)];
+ if (status === "succeeded")
+ json(200, {
+ id: "cgt-stub-0001",
+ model: "doubao-seedance-2-5-260628",
+ status,
+ content: { video_url: `http://127.0.0.1:${server.address().port}/video.mp4` },
+ });
+ else json(200, { id: "cgt-stub-0001", status, error: taskError ?? null });
+ return;
+ }
+ if (req.method === "GET" && url.pathname === "/video.mp4") {
+ res.writeHead(200, { "content-type": "video/mp4", "content-length": String(VIDEO.length) });
+ res.end(VIDEO);
+ return;
+ }
+ json(404, { error: { code: "NotFound", message: "no such stub route" } });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const origin = `http://127.0.0.1:${server.address().port}/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 };
+}
+
+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 } = {}) {
+ const dir = workspace ?? fs.mkdtempSync(path.join(os.tmpdir(), "seedance-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 seedance 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 a value 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);
+ });
+
+ it("says what to do when ARK_API_KEY is missing, and never calls the API", async () => {
+ const s = await stub();
+ 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.submits, 0);
+ });
+
+ it("submits, polls past a running status, downloads and names the file", async () => {
+ const s = await stub();
+ const { status, stdout, stderr, dir } = await run(
+ [
+ "--prompt",
+ "一只猫打哈欠",
+ "--out",
+ "out/clip.mp4",
+ "--duration",
+ "5",
+ "--watermark",
+ "--poll-interval",
+ "0.2",
+ ],
+ { 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.task_id, "cgt-stub-0001");
+ assert.equal(result.bytes, VIDEO.length);
+ assert.equal(result.model, "doubao-seedance-2-5-260628");
+ assert.equal(typeof result.elapsed_ms, "number");
+ // The download landed whole, byte for byte, under the requested name…
+ const saved = path.join(dir, "out", "clip.mp4");
+ assert.equal(sha(fs.readFileSync(saved)), sha(VIDEO));
+ assert.equal(result.path, saved);
+ // …with no leftover temporary file beside it.
+ assert.deepEqual(fs.readdirSync(path.join(dir, "out")), ["clip.mp4"]);
+ // The documented request shape, and the key sent as a bearer token on every call.
+ assert.equal(s.seen.submits, 1);
+ assert.deepEqual(s.seen.bodies[0], {
+ model: "doubao-seedance-2-5-260628",
+ content: [{ type: "text", text: "一只猫打哈欠" }],
+ duration: 5,
+ watermark: true,
+ });
+ assert.equal(s.seen.polls, 2);
+ // One submit and two polls, each carrying the key as a bearer token.
+ assert.deepEqual(s.seen.authorizations, [
+ "Bearer stub-key",
+ "Bearer stub-key",
+ "Bearer stub-key",
+ ]);
+ // The task's video URL is a signed link: the key is not sent to it.
+ assert.equal(s.seen.videoAuthorization, undefined);
+ });
+
+ it("sends reference images with their roles, inlining a local file", async () => {
+ const s = await stub();
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "seedance-test-"));
+ fs.writeFileSync(path.join(dir, "first.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
+ const { status } = await run(
+ [
+ "--prompt",
+ "a cat",
+ "--image",
+ "first.png",
+ "--reference-image",
+ "https://example.test/ref.jpg",
+ "--poll-interval",
+ "0.2",
+ ],
+ { env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin }, workspace: dir },
+ );
+ assert.equal(status, 0);
+ assert.deepEqual(s.seen.bodies[0].content, [
+ { type: "text", text: "a cat" },
+ {
+ type: "image_url",
+ image_url: { url: "data:image/png;base64,iVBORw==" },
+ role: "first_frame",
+ },
+ {
+ type: "image_url",
+ image_url: { url: "https://example.test/ref.jpg" },
+ role: "reference_image",
+ },
+ ]);
+ });
+
+ it("carries the upstream error of a failed task and exits non-zero", async () => {
+ const s = await stub({
+ statuses: ["failed"],
+ taskError: { code: "InvalidParameter.TaskTypeMismatch", message: "wrong task type" },
+ });
+ const { status, stderr } = await run(["--prompt", "a cat", "--poll-interval", "0.2"], {
+ env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin },
+ });
+ assert.equal(status, 5);
+ const failure = jsonLines(stderr).at(-1);
+ assert.equal(failure.error, "task_failed");
+ assert.equal(failure.status, "failed");
+ assert.equal(failure.error_code, "InvalidParameter.TaskTypeMismatch");
+ assert.match(failure.message, /wrong task type/);
+ assert.match(failure.upstream, /InvalidParameter.TaskTypeMismatch/);
+ });
+
+ it("gives up on a task that never finishes instead of polling forever", async () => {
+ const s = await stub({ statuses: ["queued"] });
+ const { status, stderr } = await run(
+ ["--prompt", "a cat", "--poll-interval", "0.2", "--max-wait", "0.6"],
+ { env: { ARK_API_KEY: "stub-key", ARK_BASE_URL: s.origin } },
+ );
+ assert.equal(status, 6);
+ const failure = jsonLines(stderr).at(-1);
+ assert.equal(failure.error, "timeout");
+ assert.equal(failure.task_id, "cgt-stub-0001");
+ assert.ok(s.seen.polls > 1 && s.seen.polls < 10, `polls: ${s.seen.polls}`);
+ });
+
+ it("reports a rejected key with the service's own words", async () => {
+ const server = http.createServer((_req, res) => {
+ res.writeHead(401, { "content-type": "application/json" });
+ res.end(
+ JSON.stringify({
+ error: { code: "AuthenticationError", message: "The API key in the request is invalid." },
+ }),
+ );
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ servers.add({
+ close: () => {
+ server.closeAllConnections();
+ return new Promise((resolve) => server.close(resolve));
+ },
+ });
+ const { status, stderr } = await run(["--prompt", "a cat"], {
+ env: {
+ ARK_API_KEY: "stub-key",
+ ARK_BASE_URL: `http://127.0.0.1:${server.address().port}/api/v3`,
+ },
+ });
+ assert.equal(status, 4);
+ const failure = jsonLines(stderr).at(-1);
+ assert.equal(failure.error, "api_error");
+ assert.equal(failure.status, 401);
+ assert.match(failure.upstream, /AuthenticationError/);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f41afe5b..9907be5e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -11,6 +11,9 @@ overrides:
'@hono/node-server': '>=2.0.5'
nanoid: ^3.3.17
+patchedDependencies:
+ '@prismshadow/[email protected]': ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f
+
importers:
.:
@@ -123,6 +126,9 @@ importers:
'@adelie/use-offerdao':
specifier: workspace:*
version: link:../../plugins/use-offerdao
+ '@adelie/use-seedance':
+ specifier: workspace:*
+ version: link:../../plugins/use-seedance
'@adelie/use-wps-office':
specifier: workspace:*
version: link:../../plugins/use-wps-office
@@ -134,7 +140,7 @@ importers:
version: 2.0.0
'@prismshadow/agenthub':
specifier: ^0.4.15
+ version: 0.4.15(patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])([email protected])
commander:
specifier: ^13.0.0
version: 13.1.0
@@ -223,6 +229,9 @@ importers:
'@adelie/use-offerdao':
specifier: workspace:*
version: link:../../plugins/use-offerdao
+ '@adelie/use-seedance':
+ specifier: workspace:*
+ version: link:../../plugins/use-seedance
'@adelie/use-wps-office':
specifier: workspace:*
version: link:../../plugins/use-wps-office
@@ -234,7 +243,7 @@ importers:
version: 2.0.0
'@prismshadow/agenthub':
specifier: ^0.4.15
+ version: 0.4.15(patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])([email protected])
arktype:
specifier: ^2.2.3
version: 2.2.3
@@ -329,6 +338,9 @@ importers:
'@adelie/use-offerdao':
specifier: workspace:*
version: link:../../plugins/use-offerdao
+ '@adelie/use-seedance':
+ specifier: workspace:*
+ version: link:../../plugins/use-seedance
'@adelie/use-wps-office':
specifier: workspace:*
version: link:../../plugins/use-wps-office
@@ -823,6 +835,8 @@ importers:
plugins/use-offerdao: {}
+ plugins/use-seedance: {}
+
plugins/use-wps-office: {}
plugins/wechat-miniprogram: {}
@@ -906,6 +920,9 @@ packages:
'@adelie/use-offerdao@file:plugins/use-offerdao':
resolution: {directory: plugins/use-offerdao, type: directory}
+ '@adelie/use-seedance@file:plugins/use-seedance':
+ resolution: {directory: plugins/use-seedance, type: directory}
+
'@adelie/use-wps-office@file:plugins/use-wps-office':
resolution: {directory: plugins/use-wps-office, type: directory}
@@ -4864,10 +4881,11 @@ snapshots:
'@adelie/use-firecrawl': file:plugins/use-firecrawl
'@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-wps-office': file:plugins/use-wps-office
'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
- '@prismshadow/agenthub': 0.4.15([email protected])([email protected])
+ '@prismshadow/agenthub': 0.4.15(patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])
commander: 13.1.0
dotenv: 17.4.2
smol-toml: 1.6.1
@@ -4904,10 +4922,11 @@ snapshots:
'@adelie/use-firecrawl': file:plugins/use-firecrawl
'@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-wps-office': file:plugins/use-wps-office
'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
- '@prismshadow/agenthub': 0.4.15([email protected])([email protected])
+ '@prismshadow/agenthub': 0.4.15(patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])
arktype: 2.2.3
smol-toml: 1.6.1
yaml: 2.9.0
@@ -4940,10 +4959,11 @@ snapshots:
'@adelie/use-firecrawl': file:plugins/use-firecrawl
'@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-wps-office': file:plugins/use-wps-office
'@adelie/wechat-miniprogram': file:plugins/wechat-miniprogram
'@modelcontextprotocol/client': 2.0.0
- '@prismshadow/agenthub': 0.4.15([email protected])([email protected])([email protected])
+ '@prismshadow/agenthub': 0.4.15(patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])([email protected])
arktype: 2.2.3
smol-toml: 1.6.1
yaml: 2.9.0
@@ -5050,6 +5070,8 @@ snapshots:
'@adelie/use-offerdao@file:plugins/use-offerdao': {}
+ '@adelie/use-seedance@file:plugins/use-seedance': {}
+
'@adelie/use-wps-office@file:plugins/use-wps-office': {}
'@adelie/wechat-miniprogram@file:plugins/wechat-miniprogram': {}
@@ -6013,7 +6035,7 @@ snapshots:
dependencies:
playwright: 1.61.1
+ '@prismshadow/[email protected](patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])':
dependencies:
'@anthropic-ai/bedrock-sdk': 0.26.4([email protected])
'@anthropic-ai/sdk': 0.91.1([email protected])
@@ -6028,7 +6050,7 @@ snapshots:
- ws
- zod
+ '@prismshadow/[email protected](patch_hash=ea5d826854c282dbcac78892b7290b6cf2f522f22168a5ba9624a09acc00941f)([email protected])([email protected])([email protected])':
dependencies:
'@anthropic-ai/bedrock-sdk': 0.26.4([email protected])
'@anthropic-ai/sdk': 0.91.1([email protected])
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index e9d1f672..85ecfc78 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -59,3 +59,11 @@ minimumReleaseAgeExclude:
- "@deepseek-ai/[email protected]"
- "@prismshadow/[email protected]"
+patchedDependencies:
+ # Video input. AgentHub's universal message format knows text and images only, and its
+ # Chat Completions client throws on any other content item — so a video could not reach
+ # Ark's `video_url` content part at all. The patch adds the item and its mapping (see
+ # patches/@prismshadow__agenthub.patch). Pinned to the exact version: the patch is against
+ # 0.4.15's dist, and a future release likely carries the item upstream, where this must be
+ # dropped rather than silently mis-applied.
+ "@prismshadow/[email protected]": patches/@prismshadow__agenthub.patch