xinghe-muse 2.2.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -89,9 +89,9 @@ ln -s ~/.dsh/bot/workspace/xinghe-muse ~/.dsh/profiles/desktop/node_modules/xing
89
89
 
90
90
  文件名长这样:`花瓶_20261126_231245.webp`、`香薰灯_20261127_003238.mp4`。同一秒跑两次会自动加序号,不会覆盖旧文件。
91
91
 
92
- ## 五、三个工具
92
+ ## 五、四个工具
93
93
 
94
- 装好之后 DSH 里会多出三个工具。
94
+ 装好之后 DSH 里会多出四个工具。
95
95
 
96
96
  ### `muse_web_status`
97
97
 
@@ -106,6 +106,7 @@ ln -s ~/.dsh/bot/workspace/xinghe-muse ~/.dsh/profiles/desktop/node_modules/xing
106
106
  | 参数 | 说明 |
107
107
  |---|---|
108
108
  | `prompt` | 给 Muse 的指令。**原文一个字不改地递交,不 trim、不扩写、不加前后缀**。不填才用内置的产品摄影指令 |
109
+ | `reference` | 参考素材的绝对路径:参考图或参考视频,多个用换行分隔。给到就先挂素材再递提示词 |
109
110
  | `nameHint` | 存盘文件名的基名,不带扩展名。默认用 Muse 给这张图的标题 |
110
111
  | `outDir` | 存到哪个文件夹,默认 `~/Desktop/muse/muse保存图` |
111
112
  | `timeoutSeconds` | 给 Muse 多少秒,夹在 60–600 之间,默认 180。一轮通常 20–90 秒,给足余量更稳 |
@@ -117,6 +118,7 @@ ln -s ~/.dsh/bot/workspace/xinghe-muse ~/.dsh/profiles/desktop/node_modules/xing
117
118
  | 参数 | 说明 |
118
119
  |---|---|
119
120
  | `prompt` | 同上,原文一个字不改地递交,不 trim、不扩写、不加前后缀。不填才用内置的产品视频指令 |
121
+ | `reference` | 同上:**传一条参考视频就能复刻它的镜头、人物、场景、字幕样式** |
120
122
  | `nameHint` | 同上 |
121
123
  | `outDir` | 存到哪个文件夹,默认 `~/Desktop/muse/muse保存视频` |
122
124
  | `timeoutSeconds` | 给 Muse 多少秒,夹在 60–1800 之间,默认 420。视频一轮通常 60–300 秒,给足余量更稳 |
@@ -125,6 +127,24 @@ ln -s ~/.dsh/bot/workspace/xinghe-muse ~/.dsh/profiles/desktop/node_modules/xing
125
127
 
126
128
  两个生成工具都是每跑一次新建一条旁聊,不往旧对话里续。
127
129
 
130
+ ### `muse_stitch_videos`
131
+
132
+ 把分段生成的几段接成一条:视频 0.35 秒叠化 + 音频交叉淡化,接缝看不出硬切、两句人不打架。
133
+
134
+ | 参数 | 说明 |
135
+ |---|---|
136
+ | `parts` | 按顺序排列的分段视频绝对路径,换行分隔,至少两段 |
137
+ | `outFile` | 成品路径,绝对路径,`.mp4`,已存在会被覆盖 |
138
+ | `overlapSeconds` | 叠化时长,默认 0.35。接缝那头是静音时 0.3–0.4 最稳 |
139
+
140
+ macOS 走 AVFoundation(`swiftc` 编一次,缓存在 `~/.cache/xinghe-muse`);其它平台要 `ffmpeg` + `ffprobe` 在 PATH 上。
141
+
142
+ ### 带参考素材复刻一条视频,标准走法
143
+
144
+ 1. 用户丢来一条原片(微信路径、桌面路径都行,中文空格都不影响)。
145
+ 2. 用 `muse_generate_video`,把 `reference` 指到那条片子,`prompt` 写清人物替换、机位、光线、背景、字幕位置、口播全文。
146
+ 3. Muse 单条口型上限 10 秒,25 秒的口播它会自己拆段;两段各拿到一个文件后,用 `muse_stitch_videos` 接成一条。
147
+
128
148
  ## 六、它内部怎么跑
129
149
 
130
150
  ```
@@ -137,17 +157,20 @@ DSH 里的工具调用
137
157
  `run-muse.mjs` 做的顺序:
138
158
 
139
159
  1. 打开 `https://muse.ai/thread/new` 新建旁聊(停在空白页才退回首页点入口)
140
- 2. 往 `textarea[placeholder="消息"]` 里填指令
141
- 3. 点「发送」
142
- 4. 轮询等「停止」按钮消失——它消失就代表这一轮跑完了
143
- 5. 找到最新那条产物,点开它
144
- 6. 从弹层里点「下载」,接住下载事件,把文件存进目标目录
160
+ 2. 有参考素材就先 `setInputFiles` 灌进 `input[type=file]`,等文件名出现在输入区
161
+ 3. 往 `textarea[placeholder="消息"]` 里填指令
162
+ 4. 点「发送」,然后轮询等地址变成 `/thread/<id>`
163
+ 5. 轮询等「停止」按钮消失——它消失就代表这一轮跑完了
164
+ 6. 找到最新那条产物,点开它
165
+ 7. 从弹层里点「下载」,接住下载事件,把文件存进目标目录
145
166
 
146
167
  三个坑值得记下来,改代码前先看:
147
168
 
148
169
  - `ego-browser nodejs` 只接受一个脚本来源,多给参数会直接报 `accepts at most one source argument`;它也不继承 shell 环境变量,`process.env` 是空的。所以参数只能编码成字面量,和脚本正文一起从 stdin 递进去。`drive.mjs` 干的就是这件事。
149
170
  - 图片产物是 `<button aria-label="打开生成的图片…">`,**视频产物是 `<div role="button" aria-label="打开动画视频 ….mp4">`**。只按 `button` 找,视频永远找不到。所以改成按 aria 文案认,再退回结构兜底。
150
171
  - 产物一律先用 `evaluate` 取包围盒、再用 `mouse.click` 按坐标点。`loc=css:[role="button"]` 这类属性选择器 ego 解析不稳,点不动。
172
+ - 参考素材:页面上那个 `input[type=file]` 是可见的,`page.setInputFiles('input[type=file]', [绝对路径])` 直接就能挂上,不弹系统对话框、不点屏幕,窗口不可见也行。挂完要等文件名出现在页面里(大视频上传慢),再填指令发送——先填后挂会把已填的文字冲掉。
173
+ - 发送后地址不会立刻变:实测 2–4 秒才落到 `/thread/<id>`,固定等 3 秒会偶发误判。
151
174
 
152
175
  ## 七、已知限制
153
176
 
package/docs/DETAIL.md CHANGED
@@ -8,6 +8,35 @@
8
8
 
9
9
  ---
10
10
 
11
+ ## v.2.3.0(参考素材 + 分段拼接)
12
+
13
+ **这一版解决的是「照着一条片子再出一条」和「长口播被 10 秒上限切成两截」两件事。**
14
+
15
+ ### 一、参考素材:`reference`
16
+
17
+ 两个生成工具都多了一个 `reference` 参数,参考视频、参考图都能传,多个用换行分隔。
18
+
19
+ - 挂载路径:页面里那个可见的 `input[type=file]`,走 `page.setInputFiles` 一次灌进去。不点屏幕、不弹系统对话框,窗口不可见、被最小化都照样能挂。
20
+ - 顺序写死:**先挂素材,再填提示词**。反过来会被当成两次输入,挂上附件时输入框被清过一次,指令就丢了。
21
+ - 挂完等确认:轮询页面文字里是否出现文件名(去扩展名比对)或「参考/附件」字样,最多 120 秒。确认不到也照发,不拿它当失败——大视频上传慢是常态。
22
+ - 路径先做存在性检查,缺文件直接报是哪几个,不带着错路径进去空转。
23
+
24
+ ### 二、分段拼接:`muse_stitch_videos`
25
+
26
+ Muse 网页端单条口型上限约 10 秒,25 秒的口播它自己会拆段,于是必然出现「两段接一刀」。
27
+
28
+ - 引擎:macOS 用 AVFoundation(`lib/stitch.swift`,`swiftc` 编一次缓存到 `~/.cache/xinghe-muse/stitch`,源码改了会自动重编);其它平台用 `ffmpeg` 的 `xfade` + `acrossfade`,需要 `ffprobe` 读时长。
29
+ - 实现:一次只接一刀,多段按顺序两两接下去,中间文件放临时目录。
30
+ - 时间轴三段铺满(这条最要命):`0–s` 只有 A;`s–e` A 与 B 叠化、B 的 opacity 0→1;`e–总长` 只有 B。**指令一重叠就报 `AVFoundationErrorDomain -11841` / `OSStatus -17390`「The video could not be composed」**,报错信息完全不指向真因。
31
+ - 音频同一条叠化区间做交叉淡化。实测:第一段收尾正好是静音(50ms RMS < 400)时,听感是干净的一句接一句,不会两个人同时说。
32
+
33
+ ### 三、顺手修掉的两个脆弱点
34
+
35
+ - 发送后地址不是立刻变的,实测 2–4 秒才落到 `/thread/<id>`;原来固定等 3 秒,偶尔把成功判成失败。改成 20 次 × 1.5 秒轮询。
36
+ - 结果行多带一个 `references` 字段,出了问题时能一眼看出这轮到底挂没挂素材。
37
+
38
+ ---
39
+
11
40
  ## v.2.2.2(版本优化说明)
12
41
 
13
42
  **提示词原样递交,一字不改——写死的不变量。** 用户给的 `prompt` 一律原样递交 Muse:不 trim、不扩写、不改写、不加前后缀、不做任何变换;只有真正没提供时才回退到内置默认指令。三层链路都做了约束:
@@ -22,7 +51,7 @@ DSH 侧另有一条行为规则配合:用户发任何明显要出图/出视频
22
51
 
23
52
  ## 一、能力
24
53
 
25
- DSH 里多三个工具。
54
+ DSH 里多四个工具。
26
55
 
27
56
  ### `muse_web_status`
28
57
 
@@ -154,6 +183,16 @@ STOP button[aria-label="停止"]
154
183
  - Windows 版 ego lite 官方标的是 beta,页面结构变动的风险比 macOS 高。
155
184
  - Linux 不在支持范围内——ego lite 官方还没出。
156
185
 
186
+ ### 产物没出来不许退出(2026-11-28 主管写死)
187
+
188
+ `run-muse.mjs` 里「等这一轮结束」那段没有超时退出分支,`for (;;)` 一直等到 `findMedia` 命中为止:
189
+
190
+ - 只看停止按钮会提前收手——带参考素材时 Muse 先排队十几秒才起跑,停止按钮出现又晚又短。实测症状:thread 有了、Muse 回文有了、`media` 是 null。
191
+ - `timeoutSeconds` 改当上报间隔,每满一格往 stderr 打一次「已等 N 秒 + 生成中 + 最近回文」。
192
+ - 下载入口最多点 8 轮产物重找;仍取不到就 `fetch` 产物 `src` 在页面内取字节,Node 侧写盘。
193
+ - 落地后按文件头纠正扩展名(视频经下载按钮常给成 `.webp`,头是 `ftyp` 才是 `.mp4`)。
194
+ - `catch` 分支先回扫输出目录里本轮前缀的文件,落地了就不报失败。
195
+
157
196
  ## 六、作者
158
197
 
159
198
  星禾。
package/lib/drive.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  * macOS 和 Windows 走同一条路,只差可执行文件的名字。
8
8
  *
9
9
  * 用法:
10
- * node lib/drive.mjs <指令> <保存目录> <超时秒> <文件名提示> [image|video]
10
+ * node lib/drive.mjs <指令> <保存目录> <超时秒> <文件名提示> [image|video] [参考素材JSON]
11
11
  *
12
12
  * 做的事:把参数编码成一段 JS 字面量,接上 run-muse.mjs 的正文,
13
13
  * 一起从 stdin 喂给 ego-browser nodejs。
@@ -37,7 +37,16 @@ function fail(detail) {
37
37
 
38
38
  async function main() {
39
39
  // 写死:prompt 从 argv 拿到后原样内嵌,不 trim、不改写;JSON.stringify 只做转义,不改内容。
40
- const [prompt = '', outDir = '', timeoutSec = '180', nameHint = '', kind = 'image'] = process.argv.slice(2)
40
+ const [prompt = '', outDir = '', timeoutSec = '180', nameHint = '', kind = 'image', refsRaw = '[]'] = process.argv.slice(2)
41
+
42
+ // 参考素材只做「转成数组再编码」这一件事:路径本身一个字都不动。
43
+ let refs = []
44
+ try {
45
+ const parsed = JSON.parse(refsRaw)
46
+ if (Array.isArray(parsed)) refs = parsed.filter((p) => typeof p === 'string' && p.trim() !== '')
47
+ } catch {
48
+ refs = []
49
+ }
41
50
 
42
51
  let body
43
52
  try {
@@ -66,6 +75,7 @@ async function main() {
66
75
  nameHint,
67
76
  spaceName,
68
77
  kind,
78
+ JSON.stringify(refs),
69
79
  ])};\n`
70
80
 
71
81
  const child = spawn(egoBrowser, ['nodejs'], {
package/lib/index.js CHANGED
@@ -9,6 +9,12 @@
9
9
  *
10
10
  * 前提:ego lite 已安装,并在其中登录过 muse.ai。它不必先启动,窗口也不必可见。
11
11
  *
12
+ * ── 参考素材(v2.3.0)──────────────────────────────────────────────────
13
+ * 用户给的参考视频、参考图,原样挂到 muse.ai 的输入框上,和提示词一起递交。
14
+ * 用法:muse_generate_video({ reference: '/abs/a.mp4', prompt: '...' }),
15
+ * 多个素材用换行分隔。挂载走页面里的 input[type=file],不点屏幕。
16
+ * ──────────────────────────────────────────────────────────────────────
17
+ *
12
18
  * ── 写死的不变量(不可改):提示词原样递交 ──────────────────────────────
13
19
  * 用户给的 prompt 一律原样递交 Muse:不 trim、不扩写、不改写、不加前后缀、不做任何变换。
14
20
  * 只有真正没提供 prompt 时才回退到内置默认指令。
@@ -17,8 +23,11 @@
17
23
  */
18
24
 
19
25
  import { spawn } from 'node:child_process'
26
+ import { homedir } from 'node:os'
27
+ import { tmpdir } from 'node:os'
20
28
  import { access, constants } from 'node:fs/promises'
21
- import { dirname, join } from 'node:path'
29
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
30
+ import { mkdir, stat } from 'node:fs/promises'
22
31
  import { fileURLToPath } from 'node:url'
23
32
 
24
33
  import { defineTool } from '@deepseek-ai/dsh-tools'
@@ -118,6 +127,21 @@ function parseResult(stdout) {
118
127
  return undefined
119
128
  }
120
129
 
130
+ /**
131
+ * 把 reference 参数拆成绝对路径数组。
132
+ *
133
+ * 一个字段里允许塞多个:换行、分号、竖线都当分隔符,路径中间的空格不拆(微信那种带空格的名字很常见)。
134
+ * 相对路径按当前工作目录补全,其余一个字不动。
135
+ */
136
+ function parseRefs(value) {
137
+ if (typeof value !== 'string' || value.trim() === '') return []
138
+ return value
139
+ .split(/[\r\n;|]+/)
140
+ .map((one) => one.trim())
141
+ .filter((one) => one !== '')
142
+ .map((one) => (isAbsolute(one) ? one : resolve(one)))
143
+ }
144
+
121
145
  async function driverReady() {
122
146
  try {
123
147
  await access(DRIVER, constants.R_OK)
@@ -200,6 +224,13 @@ export function apply(ctx) {
200
224
  '给 Muse 的指令。原文一个字不改地递交,不 trim、不扩写、不加前后缀。'
201
225
  + '不填才用内置的产品摄影指令。',
202
226
  },
227
+ reference: {
228
+ type: 'string',
229
+ description:
230
+ '参考素材的绝对路径:参考视频(.mp4/.mov/.webm)或参考图(.png/.jpg/.webp)都行,'
231
+ + '多个用换行分隔。给到就先把素材挂到输入框上,再递提示词;'
232
+ + '要复刻某条视频的镜头、人物、场景时,把那条视频传给它。',
233
+ },
203
234
  nameHint: {
204
235
  type: 'string',
205
236
  description: '存盘文件名的基名,不带扩展名。默认用 Muse 给这张图的标题,取不到就退回通用名。',
@@ -227,6 +258,7 @@ export function apply(ctx) {
227
258
  caption: { type: 'string' },
228
259
  reply: { type: 'string', required: true },
229
260
  threadUrl: { type: 'string', required: true },
261
+ references: { type: 'array', items: { type: 'string' } },
230
262
  detail: { type: 'string', required: true },
231
263
  },
232
264
  },
@@ -241,6 +273,7 @@ export function apply(ctx) {
241
273
  async execute(args) {
242
274
  // 写死:给到就原样用(含首尾空白),一个字都不动;只有没给才回退默认。
243
275
  const prompt = typeof args.prompt === 'string' ? args.prompt : DEFAULT_PROMPT
276
+ const refs = parseRefs(args.reference)
244
277
  const outDir = args.outDir ?? OUT_DIR
245
278
  const nameHint = args.nameHint ?? ''
246
279
  const waitSeconds = Math.min(Math.max(args.timeoutSeconds ?? 180, MIN_WAIT), MAX_WAIT)
@@ -264,7 +297,7 @@ export function apply(ctx) {
264
297
  // 驱动自身的上限是等待时间加上固定开销(开页、下载、收尾),
265
298
  // 这里再宽一点,只有浏览器彻底卡死才会触发。
266
299
  const result = await drive(
267
- [prompt, outDir, String(waitSeconds), nameHint, 'image'],
300
+ [prompt, outDir, String(waitSeconds), nameHint, 'image', JSON.stringify(refs)],
268
301
  (waitSeconds + 300) * 1000,
269
302
  )
270
303
 
@@ -285,6 +318,7 @@ export function apply(ctx) {
285
318
  : {},
286
319
  reply: parsed.reply ?? '',
287
320
  threadUrl: parsed.threadUrl ?? '',
321
+ references: refs,
288
322
  detail: parsed.detail || (parsed.ok === true
289
323
  ? `已保存到 ${parsed.media ?? parsed.image}。`
290
324
  : '这一轮结束了但没有存下文件。'),
@@ -306,6 +340,13 @@ export function apply(ctx) {
306
340
  '给 Muse 的视频指令。原文一个字不改地递交,不 trim、不扩写、不加前后缀。'
307
341
  + '不填才用内置的产品视频指令。',
308
342
  },
343
+ reference: {
344
+ type: 'string',
345
+ description:
346
+ '参考素材的绝对路径:参考视频(.mp4/.mov/.webm)或参考图(.png/.jpg/.webp)都行,'
347
+ + '多个用换行分隔。给到就先把素材挂到输入框上,再递提示词;'
348
+ + '要复刻某条视频的镜头、人物、场景时,把那条视频传给它。',
349
+ },
309
350
  nameHint: {
310
351
  type: 'string',
311
352
  description: '存盘文件名的基名,不带扩展名。默认用 Muse 给这段视频的标题,取不到就退回通用名。',
@@ -333,6 +374,7 @@ export function apply(ctx) {
333
374
  caption: { type: 'string' },
334
375
  reply: { type: 'string', required: true },
335
376
  threadUrl: { type: 'string', required: true },
377
+ references: { type: 'array', items: { type: 'string' } },
336
378
  detail: { type: 'string', required: true },
337
379
  },
338
380
  },
@@ -347,6 +389,7 @@ export function apply(ctx) {
347
389
  async execute(args) {
348
390
  // 写死:给到就原样用(含首尾空白),一个字都不动;只有没给才回退默认。
349
391
  const prompt = typeof args.prompt === 'string' ? args.prompt : DEFAULT_VIDEO_PROMPT
392
+ const refs = parseRefs(args.reference)
350
393
  const outDir = args.outDir ?? OUT_DIR_VIDEO
351
394
  const nameHint = args.nameHint ?? ''
352
395
  const waitSeconds = Math.min(
@@ -372,7 +415,7 @@ export function apply(ctx) {
372
415
 
373
416
  // 视频的下载本身也可能慢(文件大),固定开销给宽一些。
374
417
  const result = await drive(
375
- [prompt, outDir, String(waitSeconds), nameHint, 'video'],
418
+ [prompt, outDir, String(waitSeconds), nameHint, 'video', JSON.stringify(refs)],
376
419
  (waitSeconds + 420) * 1000,
377
420
  )
378
421
 
@@ -394,10 +437,188 @@ export function apply(ctx) {
394
437
  : {},
395
438
  reply: parsed.reply ?? '',
396
439
  threadUrl: parsed.threadUrl ?? '',
440
+ references: refs,
397
441
  detail: parsed.detail || (parsed.ok === true
398
442
  ? `已保存到 ${media}。`
399
443
  : '这一轮结束了但没有存下文件。'),
400
444
  }
445
+
446
+ /** 叠化拼接用的编译缓存目录:编译一次,之后直接跑。 */
447
+ const STITCH_CACHE = join(homedir(), '.cache', 'xinghe-muse')
448
+ /** ~/.cache 不可写(沙箱、只读家目录)时退到系统临时目录,别让拼接为了个缓存目录就废掉。 */
449
+ const STITCH_CACHE_FALLBACK = join(tmpdir(), 'xinghe-muse')
450
+ const STITCH_SWIFT = join(pkgRoot, 'lib', 'stitch.swift')
451
+
452
+ /** 跑一个子进程,收退出码和输出。 */
453
+ function run(cmd, args, env) {
454
+ return new Promise((done) => {
455
+ const child = spawn(cmd, args, {
456
+ stdio: ['ignore', 'pipe', 'pipe'],
457
+ windowsHide: true,
458
+ env: { ...process.env, ...(env ?? {}) },
459
+ })
460
+ let out = ''
461
+ let err = ''
462
+ child.stdout.on('data', (c) => { out += c.toString('utf8') })
463
+ child.stderr.on('data', (c) => { err += c.toString('utf8') })
464
+ child.on('error', (e) => done({ code: -1, out, err: err + e.message }))
465
+ child.on('close', (code) => done({ code: code ?? -1, out, err }))
466
+ })
467
+ }
468
+
469
+ /**
470
+ * 拿到可用的拼接器。
471
+ *
472
+ * macOS 走 AVFoundation(swiftc 编一次,缓存在 ~/.cache/xinghe-muse);
473
+ * 其它平台走 ffmpeg + ffprobe,两个都得在 PATH 上。
474
+ */
475
+ async function stitcher() {
476
+ if (process.platform === 'darwin') {
477
+ let lastError = ''
478
+ for (const cache of [STITCH_CACHE, STITCH_CACHE_FALLBACK]) {
479
+ const bin = join(cache, 'stitch')
480
+ let fresh = false
481
+ try {
482
+ const [b, sw] = await Promise.all([stat(bin), stat(STITCH_SWIFT)])
483
+ fresh = b.mtimeMs >= sw.mtimeMs
484
+ } catch {
485
+ fresh = false
486
+ }
487
+ if (!fresh) {
488
+ try {
489
+ await mkdir(cache, { recursive: true })
490
+ } catch (error) {
491
+ lastError = `缓存目录建不了:${cache}(${error.message})`
492
+ continue
493
+ }
494
+ const built = await run('swiftc', ['-O', STITCH_SWIFT, '-o', bin], {
495
+ CLANG_MODULE_CACHE_PATH: cache,
496
+ SWIFT_MODULECACHE_PATH: cache,
497
+ TMPDIR: cache,
498
+ })
499
+ if (built.code !== 0) {
500
+ lastError = `swiftc 编译拼接器失败:${built.err.slice(-400)}`
501
+ continue
502
+ }
503
+ }
504
+ return { kind: 'swift', bin }
505
+ }
506
+ return { error: lastError || '拼接器编译不出来,装 Xcode 命令行工具后再试。' }
507
+ }
508
+ return { kind: 'ffmpeg', bin: 'ffmpeg' }
509
+ }
510
+
511
+ /** 两段叠化:一次只接一刀,多段按顺序两两接下去。 */
512
+ async function stitchOnce(kind, bin, a, b, out, overlap) {
513
+ if (kind === 'swift') {
514
+ const r = await run(bin, [out, a, b, String(overlap)])
515
+ return r.code === 0 ? undefined : `拼接失败:${(r.err || r.out).slice(-400)}`
516
+ }
517
+
518
+ const probe = await run('ffprobe', [
519
+ '-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', a,
520
+ ])
521
+ const durA = Number(probe.out.trim())
522
+ if (!Number.isFinite(durA) || durA <= 0) {
523
+ return '读不到第一段的时长,ffprobe 没给出数字;装好 ffmpeg 全套再试。'
524
+ }
525
+ const offset = Math.max(durA - overlap, 0)
526
+ const filter = `[0:v][1:v]xfade=transition=fade:duration=${overlap}:offset=${offset}[v];`
527
+ + `[0:a][1:a]acrossfade=d=${overlap}[a]`
528
+ const r = await run(bin, [
529
+ '-y', '-i', a, '-i', b,
530
+ '-filter_complex', filter,
531
+ '-map', '[v]', '-map', '[a]',
532
+ '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18',
533
+ '-c:a', 'aac', '-b:a', '192k',
534
+ out,
535
+ ])
536
+ return r.code === 0 ? undefined : `ffmpeg 拼接失败:${r.err.slice(-400)}`
537
+ }
538
+ },
539
+ }))
540
+
541
+ ctx.tools.register(defineTool({
542
+ name: 'muse_stitch_videos',
543
+ description:
544
+ '把 muse 分段生成的几段视频接成一条:默认 0.35 秒叠化(视频 xfade + 音频交叉淡化),'
545
+ + '接缝看不出硬切、声音不打架。Muse 单条口型上限 10 秒,长口播就是分段生成再在这里接。'
546
+ + 'macOS 用 AVFoundation(swiftc 编一次),其它平台要 ffmpeg + ffprobe。',
547
+ parameters: {
548
+ parts: {
549
+ type: 'string',
550
+ description: '按顺序排列的分段视频绝对路径,多个用换行分隔,至少两段。',
551
+ },
552
+ outFile: {
553
+ type: 'string',
554
+ description: '成品输出路径,给绝对路径,扩展名 .mp4。已存在会被覆盖。',
555
+ },
556
+ overlapSeconds: {
557
+ type: 'number',
558
+ description: '叠化时长,默认 0.35 秒。接缝那头是静音时 0.3–0.4 最稳,太短能看出跳。',
559
+ },
560
+ },
561
+ output: {
562
+ schema: {
563
+ type: 'object',
564
+ additionalProperties: false,
565
+ properties: {
566
+ ok: { type: 'boolean', required: true },
567
+ output: { type: 'string' },
568
+ bytes: { type: 'number' },
569
+ parts: { type: 'array', items: { type: 'string' } },
570
+ detail: { type: 'string', required: true },
571
+ },
572
+ },
573
+ render: (_args, v) => [{
574
+ type: 'text',
575
+ text: v.ok
576
+ ? `已接成 ${v.output}(${v.bytes ?? 0} 字节,${(v.parts ?? []).length} 段)`
577
+ : `没接成:${v.detail}`,
578
+ }],
579
+ },
580
+ async execute(args) {
581
+ const parts = parseRefs(args.parts)
582
+ const overlap = Math.min(Math.max(args.overlapSeconds ?? 0.35, 0.05), 1.5)
583
+ const outFile = args.outFile ? (isAbsolute(args.outFile) ? args.outFile : resolve(args.outFile)) : ''
584
+
585
+ if (parts.length < 2) {
586
+ return { ok: false, detail: '至少要两段才谈得上接。', parts }
587
+ }
588
+ if (!outFile) {
589
+ return { ok: false, detail: '给一个成品输出路径(绝对路径,.mp4)。', parts }
590
+ }
591
+ for (const one of parts) {
592
+ try {
593
+ await stat(one)
594
+ } catch {
595
+ return { ok: false, detail: `这段找不到:${one}`, parts }
596
+ }
597
+ }
598
+
599
+ const engine = await stitcher()
600
+ if (engine.error) return { ok: false, detail: engine.error, parts }
601
+
602
+ // 多段:每次把「已接好的」和下一段接一刀,中间文件放临时目录。
603
+ const work = join(tmpdir(), `xinghe-muse-stitch-${Date.now()}`)
604
+ await mkdir(work, { recursive: true })
605
+ let current = parts[0]
606
+ for (let i = 1; i < parts.length; i += 1) {
607
+ const last = i === parts.length - 1
608
+ const target = last ? outFile : join(work, `step-${i}.mp4`)
609
+ const bad = await stitchOnce(engine.kind, engine.bin, current, parts[i], target, overlap)
610
+ if (bad) return { ok: false, detail: bad, parts }
611
+ current = target
612
+ }
613
+
614
+ const info = await stat(outFile).catch(() => undefined)
615
+ return {
616
+ ok: true,
617
+ output: outFile,
618
+ bytes: info?.size ?? 0,
619
+ parts,
620
+ detail: `叠化 ${overlap}s,${parts.length} 段接成一条。`,
621
+ }
401
622
  },
402
623
  }))
403
624
  }
package/lib/run-muse.mjs CHANGED
@@ -6,7 +6,11 @@
6
6
  * 由 lib/drive.mjs 从 stdin 喂给 `ego-browser nodejs` 执行,因此这里拿不到 argv,
7
7
  * 也读不到 shell 环境变量:所有输入都在 globalThis.__museArgv 里。
8
8
  *
9
- * argv: <指令> <保存目录> <超时秒> <文件名提示> <任务空间名> <类型 image|video>
9
+ * argv: <指令> <保存目录> <超时秒> <文件名提示> <任务空间名> <类型 image|video> <参考素材JSON>
10
+ *
11
+ * 参考素材(v2.3.0 起):第 7 项是 JSON 数组的绝对路径,图片和视频都能挂,
12
+ * 可以挂多个。挂载走页面上那个可见的 input[type=file],走 setInputFiles,
13
+ * 不点屏幕、不弹系统对话框,所以窗口不可见也照样能挂上去。
10
14
  *
11
15
  * stdout 只打一行 JSON 作为结果,诊断信息一律走 stderr,调用方靠这个分界。
12
16
  *
@@ -19,10 +23,27 @@
19
23
  * 先进首页、点「新旁聊」,拿不到再退回直接开。
20
24
  */
21
25
 
22
- const [prompt, outDir, timeoutSec, nameHint, spaceName, kindRaw] = globalThis.__museArgv ?? []
26
+ const [prompt, outDir, timeoutSec, nameHint, spaceName, kindRaw, refsRaw] = globalThis.__museArgv ?? []
23
27
  const KIND = kindRaw === 'video' ? 'video' : 'image'
24
28
  const IS_VIDEO = KIND === 'video'
25
29
 
30
+ /**
31
+ * 参考素材:图、视频都收,绝对路径数组。
32
+ *
33
+ * 传进来是 JSON 字符串而不是数组对象——drive.mjs 那边只做一次 JSON.stringify,
34
+ * 这里解析失败就当没给,不让它炸掉整轮。
35
+ */
36
+ const REFS = (() => {
37
+ try {
38
+ const value = JSON.parse(refsRaw ?? '[]')
39
+ return Array.isArray(value)
40
+ ? value.filter((p) => typeof p === 'string' && p.trim() !== '')
41
+ : []
42
+ } catch {
43
+ return []
44
+ }
45
+ })()
46
+
26
47
  /** 视频比图片慢得多,同一套轮询逻辑给更宽的上限。 */
27
48
  const GEN_TIMEOUT = (IS_VIDEO
28
49
  ? Math.max(60, Math.min(Number(timeoutSec) || 420, 1800))
@@ -51,21 +72,29 @@ const findMedia = `(kind) => {
51
72
  const isVideo = (a) => /(动画视频|视频|影片|video)/i.test(a) || /\\.(mp4|webm|mov)\\b/i.test(a);
52
73
  const isImage = (a) => /(图片|图像|照片|image)/i.test(a) || /\\.(png|jpe?g|webp|gif)\\b/i.test(a);
53
74
  const wanted = kind === 'video' ? isVideo : isImage;
75
+ // 挂了参考素材的轮次,用户消息里也有一份视频/图预览,不排掉就会把**输入**当产物下载。
76
+ const isRef = (a) => /参考|附件|reference|attach/i.test(a);
54
77
 
55
78
  const boxOf = (el) => {
56
79
  const r = el.getBoundingClientRect();
57
80
  return { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) };
58
81
  };
59
82
 
60
- // 一:按文案,从后往前(最新的在后面)
61
- for (let i = nodes.length - 1; i >= 0; i -= 1) {
62
- const el = nodes[i];
63
- const aria = (el.getAttribute('aria-label') || '') + ' ' + (el.getAttribute('title') || '');
64
- if (!aria.trim()) continue;
65
- if (!wanted(aria)) continue;
66
- const b = boxOf(el);
67
- if (b.w < 80 || b.h < 80) continue;
68
- return { aria: el.getAttribute('aria-label') || '', ...b, how: 'aria' };
83
+ // 一:按文案,从后往前(最新的在后面)。先只认「打开…产物」这一路文案,
84
+ // 认不到再放宽——产物和参考素材的文案差别就在这里。
85
+ const passes = [/打开/, null];
86
+ for (const gate of passes) {
87
+ for (let i = nodes.length - 1; i >= 0; i -= 1) {
88
+ const el = nodes[i];
89
+ const aria = (el.getAttribute('aria-label') || '') + ' ' + (el.getAttribute('title') || '');
90
+ if (!aria.trim()) continue;
91
+ if (isRef(aria)) continue;
92
+ if (!wanted(aria)) continue;
93
+ if (gate && !gate.test(aria)) continue;
94
+ const b = boxOf(el);
95
+ if (b.w < 80 || b.h < 80) continue;
96
+ return { aria: el.getAttribute('aria-label') || '', ...b, how: gate ? 'aria' : 'aria-loose' };
97
+ }
69
98
  }
70
99
 
71
100
  // 二:按结构兜底
@@ -73,6 +102,7 @@ const findMedia = `(kind) => {
73
102
  for (let i = media.length - 1; i >= 0; i -= 1) {
74
103
  const host = media[i].closest('[role="button"], button, a');
75
104
  if (!host) continue;
105
+ if (isRef(host.getAttribute('aria-label') || '')) continue;
76
106
  const b = boxOf(host);
77
107
  if (b.w < 80 || b.h < 80) continue;
78
108
  return { aria: host.getAttribute('aria-label') || '', ...b, how: 'dom' };
@@ -138,8 +168,53 @@ const EXT_RE = IS_VIDEO
138
168
  : /\.(png|jpe?g|webp|gif)$/i
139
169
  const DEFAULT_EXT = IS_VIDEO ? '.mp4' : '.webp'
140
170
 
171
+ /** 产物 aria 里写的扩展名,任何一套都认——用来纠正下载按钮给错的名字。 */
172
+ const ANY_EXT = /\.(mp4|webm|mov|m4v|png|jpe?g|webp|gif)\b/i
173
+
174
+ /**
175
+ * 按文件头推真实扩展名。
176
+ *
177
+ * 实测:视频产物经下载按钮落地,建议名是 .webp,字节里却是 mp4——
178
+ * 名字错了外面双击打不开,所以落地后一律按头改一次。
179
+ */
180
+ async function matchExt(file) {
181
+ const probe = await (await import('node:fs/promises')).open(file, 'r')
182
+ try {
183
+ const head = Buffer.alloc(16)
184
+ await probe.read(head, 0, 16, 0)
185
+ const ascii = head.toString('latin1')
186
+ if (ascii.startsWith('\x89PNG')) return '.png'
187
+ if (ascii.startsWith('\xFF\xD8\xFF')) return '.jpg'
188
+ if (ascii.startsWith('GIF8')) return '.gif'
189
+ if (ascii.startsWith('RIFF') && ascii.slice(8, 12) === 'WEBP') return '.webp'
190
+ if (ascii.slice(4, 8) === 'ftyp') return '.mp4'
191
+ if (head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) return '.webm'
192
+ return ''
193
+ } finally {
194
+ await probe.close()
195
+ }
196
+ }
197
+
198
+ /** 这一轮可能落地的产物:按「目录 + 文件名前缀」扫最近的几个,异常时用它兜底。 */
199
+ let OUT_DIR_NOW = ''
200
+ let BASE_NOW = ''
201
+ async function landedFile() {
202
+ if (!OUT_DIR_NOW || !BASE_NOW) return ''
203
+ const fs = await import('node:fs/promises')
204
+ const { join } = await import('node:path')
205
+ const names = await fs.readdir(OUT_DIR_NOW).catch(() => [])
206
+ const hits = names
207
+ .filter((n) => n.startsWith(`${BASE_NOW}_`))
208
+ .map((n) => join(OUT_DIR_NOW, n))
209
+ if (!hits.length) return ''
210
+ const stats = await Promise.all(hits.map(async (p) => ({ p, m: (await fs.stat(p)).mtimeMs })))
211
+ stats.sort((a, b) => b.m - a.m)
212
+ return stats[0].p
213
+ }
214
+
141
215
  const empty = {
142
216
  ok: false, threadUrl: '', media: null, kind: KIND, reply: '', caption: '', detail: '',
217
+ references: REFS,
143
218
  }
144
219
 
145
220
  function emit(value) {
@@ -220,99 +295,238 @@ async function main() {
220
295
 
221
296
  await openNewThread(page)
222
297
  await page.waitForSelector(COMPOSER, { state: 'visible', timeout: 30_000 })
298
+ await page.waitForTimeout(800)
299
+
300
+ // 参考素材先挂,再填指令:顺序反了会被当成两次输入,附件挂上来时输入框被清空过。
301
+ if (REFS.length > 0) {
302
+ const missing = []
303
+ for (const file of REFS) {
304
+ try {
305
+ await fs.access(file)
306
+ } catch {
307
+ missing.push(file)
308
+ }
309
+ }
310
+ if (missing.length > 0) {
311
+ emit({
312
+ threadUrl: await page.url(),
313
+ detail: `参考素材打不开:${missing.join(';')}。给绝对路径,图片或视频都行。`,
314
+ })
315
+ return
316
+ }
317
+
318
+ // 页面上那个 input[type=file] 直接灌文件,不点屏幕、不弹系统对话框。
319
+ await page.setInputFiles('input[type=file]', REFS)
320
+ say(`已在灌 ${REFS.length} 个参考素材`)
321
+
322
+ // 等它真挂上。判据按可靠度排:blob 预览 > 移除按钮 > 文件名/参考字样。
323
+ // 本地文件上传后预览是 blob: URL,这个信号最不会误判——中文长文件名经常被页面截断或改写。
324
+ const attachState = `() => {
325
+ const thumbs = [...document.querySelectorAll('img, video')]
326
+ .filter((m) => ((m.currentSrc || m.src || '').startsWith('blob:'))).length;
327
+ const removable = [...document.querySelectorAll('button, [role="button"]')]
328
+ .some((b) => /移除|删除|remove|clear|撤销/i.test(b.getAttribute('aria-label') || ''));
329
+ return { thumbs, removable, text: document.body.innerText.slice(0, 6000) };
330
+ }`
331
+ const stems = REFS.map((p) => p.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, '') ?? '')
332
+ let attached = false
333
+ for (let i = 0; i < 120; i += 1) {
334
+ await page.waitForTimeout(1000)
335
+ const state = await page.evaluate(new Function(`return (${attachState})()`))
336
+ const byName = stems.some((s) => s && state.text.includes(s))
337
+ const byBlob = state.thumbs > 0 || state.removable
338
+ if (byBlob || byName) {
339
+ attached = true
340
+ say(`参考素材已挂上(${byBlob ? '预览/移除按钮' : '文件名'}信号)`)
341
+ break
342
+ }
343
+ }
344
+ if (!attached) say('没确认到附件挂载信号,继续发送(照发,不拿它当失败)')
345
+
346
+ // 预览是 blob: 的本地对象地址,一选完就在,**不代表传完**。
347
+ // 传完的判据:发送按钮可用 + 页面上没有「上传中/百分比」。
348
+ // 上传没完就点发送,那一下是空点,地址永远停在 /thread/new——实测踩过。
349
+ const uploadState = `() => {
350
+ const send = document.querySelector('button[aria-label="发送"]');
351
+ const disabled = !send || send.disabled === true
352
+ || send.getAttribute('aria-disabled') === 'true';
353
+ const text = document.body.innerText;
354
+ const busy = /上传中|正在上传|uploading|处理中/i.test(text);
355
+ return { disabled, busy };
356
+ }`
357
+ let settled = false
358
+ for (let i = 0; i < 120; i += 1) {
359
+ const state = await page.evaluate(new Function(`return (${uploadState})()`))
360
+ if (!state.busy && !state.disabled) {
361
+ settled = true
362
+ break
363
+ }
364
+ await page.waitForTimeout(1000)
365
+ }
366
+ say(settled ? '上传收尾,可以发了' : '等不到上传结束的信号,仍然照发一次')
367
+ await page.waitForTimeout(800)
368
+ }
223
369
 
224
370
  // 写死:prompt 原样递交 Muse,不 trim、不扩写、不改一个字(上面的 trim 只用来判空)。
225
371
  await page.fill(COMPOSER, prompt)
226
372
  await page.waitForTimeout(500)
227
373
  await page.click(SEND, { label: IS_VIDEO ? '发送视频指令' : '发送生成指令' })
228
- await page.waitForTimeout(3000)
229
-
230
- const threadUrl = await page.url()
231
374
 
232
- // 没登录会被打回落地页,那里没有 thread id。在这里就判掉,不等满超时。
233
- if (!isThread(threadUrl)) {
234
- say('当前页面不是一条旁聊,多半是登录态过期')
235
- emit({
236
- threadUrl,
237
- detail: '先在 ego lite 里登录 muse.ai,再调一次就好。',
375
+ // 发送后地址不是立刻变的。实测:纯文字 2–4 秒;**带参考视频要 15–20 秒**
376
+ // (Muse 先把它排进队列才换页)。所以窗口给到 60 秒,中间只看两件事:
377
+ // 地址变了没有;输入框里那串字还在不在(还在就说明没发出去,可以补点一下)。
378
+ let threadUrl = ''
379
+ let clicks = 0
380
+ const sendDeadline = Date.now() + 60_000
381
+ while (Date.now() < sendDeadline) {
382
+ await page.waitForTimeout(1500)
383
+ threadUrl = await page.url()
384
+ if (isThread(threadUrl)) break
385
+ if (clicks >= 2) continue
386
+ const pending = await page.evaluate(() => {
387
+ const ta = document.querySelector('textarea[placeholder="消息"]')
388
+ return {
389
+ hasSend: !!document.querySelector('button[aria-label="发送"]'),
390
+ draft: ta ? (ta.value || '').length : -1,
391
+ }
238
392
  })
239
- return
393
+ // 输入框空了 = 已经发出去了,只是还没换页,别重复点。
394
+ if (pending.hasSend && pending.draft > 0) {
395
+ clicks += 1
396
+ say(`指令还压着没发出去,补点第 ${clicks} 次`)
397
+ try {
398
+ await page.click(SEND, { label: IS_VIDEO ? '发送视频指令' : '发送生成指令' })
399
+ } catch (error) {
400
+ say(`补点没点上:${String(error?.message ?? error).split('\n')[0]}`)
401
+ }
402
+ }
240
403
  }
241
404
 
242
- // 等这一轮结束:停止按钮出现又消失,或者干脆没出现过
243
- const deadline = Date.now() + GEN_TIMEOUT
244
- let generating = true
245
- let sawStop = false
246
- while (Date.now() < deadline) {
247
- await page.waitForTimeout(IS_VIDEO ? 4000 : 2500)
248
- generating = await page.evaluate(new Function(`return (${stillGenerating})()`))
249
- if (generating) sawStop = true
250
- else if (sawStop || Date.now() > deadline - GEN_TIMEOUT + 15_000) break
251
- }
252
- if (generating) {
253
- say(`${GEN_TIMEOUT / 1000}s 后还在生成`)
405
+ // 没登录会被打回落地页,那里没有 thread id。在这里就判掉,不等满超时。
406
+ if (!isThread(threadUrl)) {
407
+ say('当前页面不是一条旁聊')
254
408
  emit({
255
409
  threadUrl,
256
- detail: `这一轮还在进行中,已经等了 ${Math.round(GEN_TIMEOUT / 1000)} 秒。`
257
- + '旁聊原样留着,可以调大 timeoutSeconds 再调一次,也能自己打开那条旁聊看。',
410
+ detail: REFS.length > 0
411
+ ? '素材挂上了但指令没发出去(发送按钮还没解禁时点的那一下是空点)。'
412
+ + '重调一次;仍然发不出去就打开 ego lite 看那一页卡在哪。'
413
+ : '多半是登录态过期:先在 ego lite 里登录 muse.ai,再调一次就好。',
258
414
  })
259
415
  return
260
416
  }
261
- // 收尾动画还在跑,给它一点时间把产物挂上 DOM
262
- await page.waitForTimeout(IS_VIDEO ? 5000 : 3000)
263
417
 
264
- const found = await page.evaluate(new Function(`return (${findMedia})(${JSON.stringify(KIND)})`))
265
- if (!found) {
266
- const text = await page.evaluate(new Function(`return (${replies})()`))
267
- const said = (text || []).slice(-2).join(' | ') || '(没有可读文字)'
268
- emit({
269
- threadUrl,
270
- reply: said,
271
- detail: `这一轮 Muse 回的是:${said} 旁聊留着,可以直接打开看,也可以再调一次。`,
272
- })
273
- return
418
+ // 等这一轮结束。**不能只看停止按钮**:带参考素材时 Muse 要先排队十几秒才起跑,
419
+ // 停止按钮又出现得晚、点得短,只看它会提前收手,产物还没挂上 DOM 就判结束了——
420
+ // 实测踩过:thread 有了、回复有了、media 却是 null。
421
+ // 所以判据改成「产物挂上了,并且停止按钮不在」,两条都满足才算这一轮真完。
422
+ // 写死(用户 2026-11-28 明确要求):
423
+ // 产物没生成出来、没下载落地,这一轮不许退出。
424
+ // 所以这里**没有**「等超时就算了」的分支。timeoutSec 只当上报间隔用,不当退出判据。
425
+ // 只要还在生成就一直等;停止按钮消失后再给收尾动画留时间;等不到就继续等,
426
+ // 每满一个上报间隔往 stderr 打一次现场,好让外面看得见它还活着。
427
+ const peek = () => page.evaluate(new Function(`return (${findMedia})(${JSON.stringify(KIND)})`))
428
+ const TICK = IS_VIDEO ? 4000 : 2500
429
+ let found = null
430
+ let waited = 0
431
+ let lastReport = 0
432
+ for (;;) {
433
+ found = await peek()
434
+ if (found) break
435
+ const generating = await page.evaluate(new Function(`return (${stillGenerating})()`))
436
+ waited += TICK
437
+ if (waited - lastReport >= GEN_TIMEOUT) {
438
+ lastReport = waited
439
+ const text = await page.evaluate(new Function(`return (${replies})()`))
440
+ say(`还在等产物:已等 ${Math.round(waited / 1000)}s,生成中=${generating},`
441
+ + `最近回复:${(text || []).slice(-1)[0] || '(无)'}`)
442
+ }
443
+ await page.waitForTimeout(TICK)
274
444
  }
445
+ say(`产物已挂上,等了 ${Math.round(waited / 1000)}s:${found.how}`)
275
446
  say(`命中产物(${found.how}):${found.aria} @ ${found.x},${found.y} ${found.w}x${found.h}`)
276
447
 
277
448
  // 走坐标点,不用 CSS 选择器:role=button 的选择器 ego 解析不了
278
449
  await page.mouse.click(found.x + Math.round(found.w / 2), found.y + Math.round(found.h / 2))
279
450
  await page.waitForTimeout(IS_VIDEO ? 4000 : 2500)
280
451
 
281
- // 弹层里找下载入口:图片是「下载」,视频预览也是「下载」
282
- const dialog = await page.evaluate(new Function(`return (${dialogItems})()`))
283
- const dl = dialog.items.find((it) => /下载|保存|download/i.test(it.label + it.text))
284
- if (!dl) {
285
- const list = dialog.items.map((it) => it.label || it.text).filter(Boolean).slice(0, 12)
286
- emit({
287
- threadUrl,
288
- caption: niceName(found.aria),
289
- detail: '弹层里可点的项变了,取下载入口的规则要跟着调。'
290
- + `当前弹层标题:${dialog.dlgText || '(空)'};可点项:${list.join('、') || '(无)'}`,
291
- })
292
- return
452
+ // 弹层里找下载入口:图片是「下载」,视频预览也是「下载」。
453
+ // 弹层偶尔要一两秒才渲染完,取不到就再点一次产物,最多 8 轮——期间照样不退出。
454
+ let dl = null
455
+ for (let i = 0; i < 8; i += 1) {
456
+ const dialog = await page.evaluate(new Function(`return (${dialogItems})()`))
457
+ dl = dialog.items.find((it) => /下载|保存|download/i.test(it.label + it.text))
458
+ if (dl) break
459
+ const list = dialog.items.map((it) => it.label || it.text).filter(Boolean).slice(0, 8)
460
+ say(`弹层还没出下载入口(第 ${i + 1} 轮):${list.join('、') || '(无)'},再点一次产物`)
461
+ await page.mouse.click(found.x + Math.round(found.w / 2), found.y + Math.round(found.h / 2))
462
+ await page.waitForTimeout(IS_VIDEO ? 4000 : 2500)
293
463
  }
294
- say(`下载入口:${dl.label || dl.text} @ ${dl.x},${dl.y}`)
295
464
 
296
- const download = page.waitForEvent('download', { timeout: IS_VIDEO ? 240_000 : 120_000 })
297
- await page.mouse.click(dl.x, dl.y)
298
- const file = await download
465
+ // 产物落地这一关也不许退:下载按钮点不出来,就退回「在页面里把字节抓回来」。
466
+ let saved = null
467
+ if (dl) {
468
+ say(`下载入口:${dl.label || dl.text} @ ${dl.x},${dl.y}`)
469
+ const download = page.waitForEvent('download', { timeout: IS_VIDEO ? 240_000 : 120_000 })
470
+ await page.mouse.click(dl.x, dl.y)
471
+ saved = await download
472
+ } else {
473
+ say('没有下载入口,改成直接从页面抓产物字节')
474
+ }
299
475
 
300
- const suggested = file.suggestedFilename() || ''
301
- const ext = EXT_RE.exec(suggested)?.[0] ?? DEFAULT_EXT
302
476
  const caption = niceName(found.aria)
303
477
  const base = slug(nameHint || caption || (IS_VIDEO ? 'muse生成视频' : 'muse生成图片'))
304
- let target = join(outDir, `${base}_${stampOf(new Date())}${ext}`)
305
- // 不覆盖已有文件:同一秒跑两次就加序号。
306
- for (let i = 2; ; i += 1) {
307
- try {
308
- await fs.access(target)
309
- target = join(outDir, `${base}_${stampOf(new Date())}_${i}${ext}`)
310
- } catch {
311
- break
478
+ const stamp = stampOf(new Date())
479
+ OUT_DIR_NOW = outDir
480
+ BASE_NOW = base
481
+ const pick = async (ext) => {
482
+ let p = join(outDir, `${base}_${stamp}${ext}`)
483
+ for (let i = 2; ; i += 1) {
484
+ try {
485
+ // 不覆盖已有文件:同一秒跑两次就加序号。
486
+ await fs.access(p)
487
+ p = join(outDir, `${base}_${stamp}_${i}${ext}`)
488
+ } catch {
489
+ return p
490
+ }
312
491
  }
313
492
  }
314
- await file.saveAs(target)
493
+
494
+ let target
495
+ if (dl) {
496
+ const suggested = saved.suggestedFilename() || ''
497
+ // 建议名里的扩展名常常是 webp(产物其实是 mp4),所以先存下来,落地后再按文件头改。
498
+ const ext = EXT_RE.exec(suggested)?.[0] ?? ANY_EXT.exec(found.aria)?.[0] ?? DEFAULT_EXT
499
+ target = await pick(ext)
500
+ await saved.saveAs(target)
501
+ } else {
502
+ const grabbed = await page.evaluate(`async () => {
503
+ const nodes = [...document.querySelectorAll('video, img')];
504
+ const last = nodes[nodes.length - 1];
505
+ const src = (last && (last.currentSrc || last.src)) || '';
506
+ if (!src) return { ok: false, why: '没找到带 src 的产物' };
507
+ const res = await fetch(src);
508
+ const buf = new Uint8Array(await res.arrayBuffer());
509
+ let s = '';
510
+ const CH = 0x8000;
511
+ for (let i = 0; i < buf.length; i += CH) s += String.fromCharCode(...buf.subarray(i, i + CH));
512
+ return { ok: true, b64: btoa(s), bytes: buf.length, type: res.headers.get('content-type') || '' };
513
+ }`)
514
+ if (!grabbed?.ok) throw new Error(`抓产物字节失败:${grabbed?.why ?? '未知原因'}`)
515
+ target = await pick(ANY_EXT.exec(found.aria)?.[0] ?? DEFAULT_EXT)
516
+ await fs.writeFile(target, Buffer.from(grabbed.b64, 'base64'))
517
+ say(`已从页面抓回 ${grabbed.bytes} 字节(${grabbed.type || '无 content-type'})`)
518
+ }
519
+
520
+ // 按文件头纠正扩展名:下载按钮给的名字与实际编码经常不一致,名字错了外面播不了。
521
+ const fixed = await matchExt(target)
522
+ if (fixed && fixed !== target) {
523
+ const renamed = target.replace(/\.[^.]+$/, fixed)
524
+ await fs.rename(target, renamed)
525
+ target = renamed
526
+ }
527
+
315
528
  const stat = await fs.stat(target)
529
+ if (!stat.size) throw new Error('产物落地了但大小是 0,等同没生成')
316
530
  const text = await page.evaluate(new Function(`return (${replies})()`))
317
531
 
318
532
  emit({
@@ -325,7 +539,23 @@ async function main() {
325
539
  detail: '',
326
540
  })
327
541
  } catch (error) {
328
- emit({ detail: `驱动这一步没走完:${String(error?.message ?? error).split('\n')[0]}。再调一次通常就过去了。` })
542
+ const why = String(error?.message ?? error).split('\n')[0]
543
+ // 主管写死的规矩:产物已经落地就不许报失败。走到异常也要先回看一遍磁盘。
544
+ const landed = await landedFile().catch(() => '')
545
+ if (landed) {
546
+ const size = await fs.stat(landed).then((s) => s.size).catch(() => 0)
547
+ if (size > 0) {
548
+ emit({
549
+ ok: true,
550
+ threadUrl,
551
+ media: landed,
552
+ bytes: size,
553
+ detail: `这一步报了「${why}」,但产物已经落地,按成功算。`,
554
+ })
555
+ return
556
+ }
557
+ }
558
+ emit({ detail: `驱动这一步没走完:${why}。产物还没落地,按规矩继续跑,不当作完成。` })
329
559
  } finally {
330
560
  // 失败的轮次什么都不留;成功的已经把文件拷出来了。
331
561
  await task.finish({ keep: [] }).catch(() => {})
@@ -0,0 +1,89 @@
1
+ /**
2
+ * 两段视频叠化拼接:把 b 叠在 a 的尾巴上,做 xfade + 音频交叉淡化,导出一条。
3
+ *
4
+ * 作者:星禾
5
+ *
6
+ * 用法:stitch <输出.mp4> <A.mp4> <B.mp4> [叠化秒=0.35]
7
+ *
8
+ * 两条实测教训:
9
+ * 1. 三段指令必须严格铺满时间轴、不许重叠(0–s 只有 A;s–e A 与 B 叠化;
10
+ * e–总长 只有 B)。指令一重叠就报 AVFoundationErrorDomain -11841 / OSStatus -17390
11
+ * "The video could not be composed",而且报得很含糊。
12
+ * 2. 视频叠化、音频也走交叉淡化;接缝那头正好是静音时,听感是干净的一句接一句。
13
+ */
14
+ import Foundation
15
+ import AVFoundation
16
+ import CoreImage
17
+
18
+ let a = CommandLine.arguments
19
+ let outURL = URL(fileURLWithPath: a[1])
20
+ let ua = URL(fileURLWithPath: a[2])
21
+ let ub = URL(fileURLWithPath: a[3])
22
+ let overlap = a.count > 4 ? (Double(a[4]) ?? 0.35) : 0.35
23
+ try? FileManager.default.removeItem(at: outURL)
24
+
25
+ let A = AVURLAsset(url: ua), B = AVURLAsset(url: ub)
26
+ let da = CMTimeGetSeconds(A.duration), db = CMTimeGetSeconds(B.duration)
27
+ let comp = AVMutableComposition()
28
+ let vA = comp.addMutableTrack(withMediaType: .video, preferredTrackID: 1)!
29
+ let vB = comp.addMutableTrack(withMediaType: .video, preferredTrackID: 2)!
30
+ let aA = comp.addMutableTrack(withMediaType: .audio, preferredTrackID: 3)!
31
+ let aB = comp.addMutableTrack(withMediaType: .audio, preferredTrackID: 4)!
32
+ let tA = A.tracks(withMediaType: .video)[0]
33
+ let tB = B.tracks(withMediaType: .video)[0]
34
+ try vA.insertTimeRange(CMTimeRange(start: .zero, duration: A.duration), of: tA, at: .zero)
35
+ try vB.insertTimeRange(CMTimeRange(start: .zero, duration: B.duration), of: tB, at: CMTime(seconds: da - overlap, preferredTimescale: 600))
36
+ vA.preferredTransform = tA.preferredTransform
37
+ vB.preferredTransform = tB.preferredTransform
38
+ if let sA = A.tracks(withMediaType: .audio).first { try aA.insertTimeRange(CMTimeRange(start: .zero, duration: A.duration), of: sA, at: .zero) }
39
+ if let sB = B.tracks(withMediaType: .audio).first { try aB.insertTimeRange(CMTimeRange(start: .zero, duration: B.duration), of: sB, at: CMTime(seconds: da - overlap, preferredTimescale: 600)) }
40
+
41
+ let total = da + db - overlap
42
+ let renderSize = tA.naturalSize.applying(tA.preferredTransform)
43
+ let size = CGSize(width: abs(renderSize.width), height: abs(renderSize.height))
44
+
45
+ let vc = AVMutableVideoComposition()
46
+ vc.renderSize = size
47
+ vc.frameDuration = CMTime(value: 1, timescale: 30)
48
+
49
+ let lA = AVMutableVideoCompositionLayerInstruction(assetTrack: vA)
50
+ let lB = AVMutableVideoCompositionLayerInstruction(assetTrack: vB)
51
+ let s = CMTime(seconds: da - overlap, preferredTimescale: 600)
52
+ let e = CMTime(seconds: da, preferredTimescale: 600)
53
+ let totalT = CMTime(seconds: total, preferredTimescale: 600)
54
+ lB.setOpacityRamp(fromStartOpacity: 0, toEndOpacity: 1, timeRange: CMTimeRange(start: s, duration: CMTimeSubtract(e, s)))
55
+
56
+ let i1 = AVMutableVideoCompositionInstruction()
57
+ i1.timeRange = CMTimeRange(start: .zero, duration: s)
58
+ i1.layerInstructions = [lA]
59
+
60
+ let i2 = AVMutableVideoCompositionInstruction()
61
+ i2.timeRange = CMTimeRange(start: s, duration: CMTimeSubtract(e, s))
62
+ i2.layerInstructions = [lA, lB]
63
+
64
+ let i3 = AVMutableVideoCompositionInstruction()
65
+ i3.timeRange = CMTimeRange(start: e, duration: CMTimeSubtract(totalT, e))
66
+ i3.layerInstructions = [lB]
67
+
68
+ vc.instructions = [i1, i2, i3]
69
+
70
+ let mix = AVMutableAudioMix()
71
+ let pA = AVMutableAudioMixInputParameters(track: aA)
72
+ pA.setVolumeRamp(fromStartVolume: 1, toEndVolume: 0, timeRange: CMTimeRange(start: s, duration: CMTimeSubtract(e, s)))
73
+ let pB = AVMutableAudioMixInputParameters(track: aB)
74
+ pB.setVolumeRamp(fromStartVolume: 0, toEndVolume: 1, timeRange: CMTimeRange(start: s, duration: CMTimeSubtract(e, s)))
75
+ mix.inputParameters = [pA, pB]
76
+
77
+ let export = AVAssetExportSession(asset: comp, presetName: AVAssetExportPresetHighestQuality)!
78
+ export.outputURL = outURL
79
+ export.outputFileType = .mp4
80
+ export.videoComposition = vc
81
+ export.audioMix = mix
82
+ let sem = DispatchSemaphore(value: 0)
83
+ export.exportAsynchronously { sem.signal() }
84
+ sem.wait()
85
+ print(export.status == .completed ? "ok \(outURL.path) total=\(total)" : "fail \(String(describing: export.error))")
86
+
87
+ extension CMTime {
88
+ func subtractingCM(_ o: CMTime) -> CMTime { CMTimeSubtract(self, o) }
89
+ }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "xinghe-muse 出图-出视频",
4
- "description": "在 ego lite 浏览器里驱动 muse.ai 出图、出视频:新建旁聊、发出指令、等这一轮跑完、把原始文件下载下来存进文件夹。全程不点屏幕,窗口被盖住、最小化、别的程序抢焦点都不影响。macOS 与 Windows 都能用。 作者:星禾。",
4
+ "description": "在 ego lite 浏览器里驱动 muse.ai 出图、出视频:可以带自己的参考视频/参考图(原样挂到输入框),新建旁聊、发出指令、等这一轮跑完、把原始文件下载下来存进文件夹。分段生成的几段还能用 muse_stitch_videos 叠化接成一条。全程不点屏幕,窗口被盖住、最小化、别的程序抢焦点都不影响。macOS 与 Windows 都能用。 作者:星禾。",
5
5
  "detail": "docs/DETAIL.md",
6
6
  "author": "星禾"
7
7
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "xinghe-muse",
3
- "version": "2.2.2",
3
+ "version": "2.3.0",
4
4
  "displayName": "xinghe-muse 出图-出视频",
5
- "description": "Generate images and video through muse.ai in the ego lite browser, saving the downloaded file to a folder. Works on macOS and Windows.",
5
+ "description": "Generate images and video through muse.ai in the ego lite browser — optionally with your own reference video/image attached — saving the result to a folder. Works on macOS and Windows.",
6
6
  "author": "星禾",
7
7
  "license": "MIT",
8
8
  "type": "module",
@@ -42,4 +42,4 @@
42
42
  "publishConfig": {
43
43
  "access": "public"
44
44
  }
45
- }
45
+ }